Persist saved environments inline with records
- Store bearer tokens on saved environment records in web and desktop - Preserve secrets when rewriting registry entries - Add coverage for the new persistence flow
This commit is contained in:
1 parent
e56b58c60e
commit
110fc3eca1
9 files changed
+252
-155
No files matched your search
@@ -87,6 +87,8 @@ describe("clientPersistence", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
const secretStorage = makeSecretStorage(true);
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
expect(
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
@@ -103,12 +105,23 @@ describe("clientPersistence", () => {
|
||||
secretStorage,
|
||||
}),
|
||||
).toBe("bearer-token");
|
||||
|
||||
expect(JSON.parse(fs.readFileSync(registryPath, "utf8"))).toEqual({
|
||||
records: [
|
||||
{
|
||||
...savedRegistryRecord,
|
||||
encryptedBearerToken: Buffer.from("enc:bearer-token", "utf8").toString("base64"),
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves existing secrets when encryption is unavailable", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
const availableSecretStorage = makeSecretStorage(true);
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
@@ -138,6 +151,8 @@ describe("clientPersistence", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
const secretStorage = makeSecretStorage(true);
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
@@ -179,10 +194,25 @@ describe("clientPersistence", () => {
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("returns false when writing a secret without metadata", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
|
||||
expect(
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
secretStorage: makeSecretStorage(true),
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves encrypted secrets when metadata is rewritten", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
const secretStorage = makeSecretStorage(true);
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
|
||||
@@ -14,7 +14,6 @@ interface PersistedSavedEnvironmentStorageRecord extends PersistedSavedEnvironme
|
||||
|
||||
interface SavedEnvironmentRegistryDocument {
|
||||
readonly records: readonly PersistedSavedEnvironmentStorageRecord[];
|
||||
readonly encryptedBearerTokenById: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
export interface DesktopSecretStorage {
|
||||
@@ -60,23 +59,13 @@ function isPersistedSavedEnvironmentStorageRecord(
|
||||
function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmentRegistryDocument {
|
||||
const parsed = readJsonFile<SavedEnvironmentRegistryDocument>(filePath);
|
||||
if (!Predicate.isObject(parsed)) {
|
||||
return { records: [], encryptedBearerTokenById: {} };
|
||||
return { records: [] };
|
||||
}
|
||||
|
||||
const records = Array.isArray(parsed.records)
|
||||
? parsed.records.filter(isPersistedSavedEnvironmentStorageRecord)
|
||||
: [];
|
||||
const encryptedBearerTokenById = Predicate.isObject(parsed.encryptedBearerTokenById)
|
||||
? Object.fromEntries(
|
||||
Object.entries(parsed.encryptedBearerTokenById).filter(
|
||||
(entry): entry is [string, string] => typeof entry[1] === "string",
|
||||
),
|
||||
)
|
||||
: {};
|
||||
|
||||
return {
|
||||
records,
|
||||
encryptedBearerTokenById,
|
||||
records: Array.isArray(parsed.records)
|
||||
? parsed.records.filter(isPersistedSavedEnvironmentStorageRecord)
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -114,10 +103,28 @@ export function writeSavedEnvironmentRegistry(
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
): void {
|
||||
const currentDocument = readSavedEnvironmentRegistryDocument(registryPath);
|
||||
const encryptedBearerTokenById = currentDocument.encryptedBearerTokenById;
|
||||
const encryptedBearerTokenById = new Map(
|
||||
currentDocument.records.flatMap((record) =>
|
||||
record.encryptedBearerToken
|
||||
? [[record.environmentId, record.encryptedBearerToken] as const]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
writeJsonFile(registryPath, {
|
||||
records,
|
||||
encryptedBearerTokenById,
|
||||
records: records.map((record) => {
|
||||
const encryptedBearerToken = encryptedBearerTokenById.get(record.environmentId);
|
||||
return encryptedBearerToken
|
||||
? {
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
encryptedBearerToken,
|
||||
}
|
||||
: record;
|
||||
}),
|
||||
} satisfies SavedEnvironmentRegistryDocument);
|
||||
}
|
||||
|
||||
@@ -127,7 +134,9 @@ export function readSavedEnvironmentSecret(input: {
|
||||
readonly secretStorage: DesktopSecretStorage;
|
||||
}): string | null {
|
||||
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
|
||||
const encoded = document.encryptedBearerTokenById[input.environmentId];
|
||||
const encoded = document.records.find(
|
||||
(record) => record.environmentId === input.environmentId,
|
||||
)?.encryptedBearerToken;
|
||||
if (!encoded) {
|
||||
return null;
|
||||
}
|
||||
@@ -155,14 +164,30 @@ export function writeSavedEnvironmentSecret(input: {
|
||||
return false;
|
||||
}
|
||||
|
||||
let found = false;
|
||||
|
||||
writeJsonFile(input.registryPath, {
|
||||
records: document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
|
||||
encryptedBearerTokenById: {
|
||||
...document.encryptedBearerTokenById,
|
||||
[input.environmentId]: input.secretStorage.encryptString(input.secret).toString("base64"),
|
||||
},
|
||||
records: document.records.map((record) => {
|
||||
if (record.environmentId !== input.environmentId) {
|
||||
return record;
|
||||
}
|
||||
|
||||
found = true;
|
||||
const encryptedBearerToken = input.secretStorage
|
||||
.encryptString(input.secret)
|
||||
.toString("base64");
|
||||
return {
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
encryptedBearerToken,
|
||||
} satisfies PersistedSavedEnvironmentStorageRecord;
|
||||
}),
|
||||
} satisfies SavedEnvironmentRegistryDocument);
|
||||
return true;
|
||||
return found;
|
||||
}
|
||||
|
||||
export function removeSavedEnvironmentSecret(input: {
|
||||
@@ -170,13 +195,22 @@ export function removeSavedEnvironmentSecret(input: {
|
||||
readonly environmentId: string;
|
||||
}): void {
|
||||
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
|
||||
if (!(input.environmentId in document.encryptedBearerTokenById)) {
|
||||
if (
|
||||
!document.records.some(
|
||||
(record) =>
|
||||
record.environmentId === input.environmentId && record.encryptedBearerToken !== undefined,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { [input.environmentId]: _removed, ...remaining } = document.encryptedBearerTokenById;
|
||||
writeJsonFile(input.registryPath, {
|
||||
records: document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
|
||||
encryptedBearerTokenById: remaining,
|
||||
records: document.records.map((record) => {
|
||||
if (record.environmentId !== input.environmentId) {
|
||||
return record;
|
||||
}
|
||||
|
||||
return toPersistedSavedEnvironmentRecord(record);
|
||||
}),
|
||||
} satisfies SavedEnvironmentRegistryDocument);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const testEnvironmentId = EnvironmentId.makeUnsafe("environment-1");
|
||||
|
||||
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
|
||||
environmentId: testEnvironmentId,
|
||||
label: "Remote environment",
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
wsBaseUrl: "wss://remote.example.com/",
|
||||
createdAt: "2026-04-09T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
};
|
||||
|
||||
function createLocalStorageStub(): Storage {
|
||||
const store = new Map<string, string>();
|
||||
return {
|
||||
getItem: (key) => store.get(key) ?? null,
|
||||
setItem: (key, value) => {
|
||||
store.set(key, value);
|
||||
},
|
||||
removeItem: (key) => {
|
||||
store.delete(key);
|
||||
},
|
||||
clear: () => {
|
||||
store.clear();
|
||||
},
|
||||
key: (index) => [...store.keys()][index] ?? null,
|
||||
get length() {
|
||||
return store.size;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function getTestWindow(): Window & typeof globalThis {
|
||||
const localStorage = createLocalStorageStub();
|
||||
const testWindow = {
|
||||
localStorage,
|
||||
} as Window & typeof globalThis;
|
||||
vi.stubGlobal("window", testWindow);
|
||||
vi.stubGlobal("localStorage", localStorage);
|
||||
return testWindow;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.resetModules();
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("clientPersistenceStorage", () => {
|
||||
it("stores browser secrets inline with the saved environment record", async () => {
|
||||
const testWindow = getTestWindow();
|
||||
const {
|
||||
SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
|
||||
readBrowserSavedEnvironmentRegistry,
|
||||
readBrowserSavedEnvironmentSecret,
|
||||
writeBrowserSavedEnvironmentRegistry,
|
||||
writeBrowserSavedEnvironmentSecret,
|
||||
} = await import("./clientPersistenceStorage");
|
||||
|
||||
writeBrowserSavedEnvironmentRegistry([savedRegistryRecord]);
|
||||
expect(writeBrowserSavedEnvironmentSecret(testEnvironmentId, "bearer-token")).toBe(true);
|
||||
writeBrowserSavedEnvironmentRegistry([savedRegistryRecord]);
|
||||
|
||||
expect(readBrowserSavedEnvironmentRegistry()).toEqual([savedRegistryRecord]);
|
||||
expect(readBrowserSavedEnvironmentSecret(testEnvironmentId)).toBe("bearer-token");
|
||||
expect(
|
||||
JSON.parse(testWindow.localStorage.getItem(SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY)!),
|
||||
).toEqual({
|
||||
version: 1,
|
||||
records: [
|
||||
{
|
||||
...savedRegistryRecord,
|
||||
bearerToken: "bearer-token",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import {
|
||||
ClientSettingsSchema,
|
||||
type ClientSettings,
|
||||
EnvironmentId,
|
||||
type ClientSettings,
|
||||
type EnvironmentId as EnvironmentIdValue,
|
||||
type PersistedSavedEnvironmentRecord,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -12,20 +12,6 @@ import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorag
|
||||
export const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
|
||||
export const SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY = "t3code:saved-environment-registry:v1";
|
||||
|
||||
interface BrowserSavedEnvironmentRecord extends PersistedSavedEnvironmentRecord {
|
||||
readonly bearerToken?: string;
|
||||
}
|
||||
|
||||
interface BrowserSavedEnvironmentRegistryState {
|
||||
readonly byId?: Record<string, unknown>;
|
||||
readonly secretsById?: Record<string, string>;
|
||||
}
|
||||
|
||||
interface BrowserSavedEnvironmentRegistryDocument {
|
||||
readonly state?: BrowserSavedEnvironmentRegistryState;
|
||||
readonly version?: number;
|
||||
}
|
||||
|
||||
const BrowserSavedEnvironmentRecordSchema = Schema.Struct({
|
||||
environmentId: EnvironmentId,
|
||||
label: Schema.String,
|
||||
@@ -35,35 +21,19 @@ const BrowserSavedEnvironmentRecordSchema = Schema.Struct({
|
||||
lastConnectedAt: Schema.NullOr(Schema.String),
|
||||
bearerToken: Schema.optionalKey(Schema.String),
|
||||
});
|
||||
type BrowserSavedEnvironmentRecord = typeof BrowserSavedEnvironmentRecordSchema.Type;
|
||||
|
||||
const BrowserSavedEnvironmentRegistryDocumentSchema = Schema.Struct({
|
||||
version: Schema.optionalKey(Schema.Number),
|
||||
state: Schema.optionalKey(
|
||||
Schema.Struct({
|
||||
byId: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),
|
||||
secretsById: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
|
||||
}),
|
||||
),
|
||||
records: Schema.optionalKey(Schema.Array(BrowserSavedEnvironmentRecordSchema)),
|
||||
});
|
||||
|
||||
const decodeBrowserSavedEnvironmentRecord = Schema.decodeUnknownSync(
|
||||
BrowserSavedEnvironmentRecordSchema,
|
||||
);
|
||||
type BrowserSavedEnvironmentRegistryDocument =
|
||||
typeof BrowserSavedEnvironmentRegistryDocumentSchema.Type;
|
||||
|
||||
function hasWindow(): boolean {
|
||||
return typeof window !== "undefined";
|
||||
}
|
||||
|
||||
function normalizeBrowserSavedEnvironmentRecord(
|
||||
value: unknown,
|
||||
): BrowserSavedEnvironmentRecord | null {
|
||||
try {
|
||||
return decodeBrowserSavedEnvironmentRecord(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function toPersistedSavedEnvironmentRecord(
|
||||
record: PersistedSavedEnvironmentRecord,
|
||||
): PersistedSavedEnvironmentRecord {
|
||||
@@ -103,12 +73,11 @@ function readBrowserSavedEnvironmentRegistryDocument(): BrowserSavedEnvironmentR
|
||||
}
|
||||
|
||||
try {
|
||||
return (
|
||||
getLocalStorageItem(
|
||||
SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
|
||||
BrowserSavedEnvironmentRegistryDocumentSchema,
|
||||
) ?? {}
|
||||
const parsed = getLocalStorageItem(
|
||||
SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
|
||||
BrowserSavedEnvironmentRegistryDocumentSchema,
|
||||
);
|
||||
return parsed ?? {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
@@ -129,31 +98,7 @@ function writeBrowserSavedEnvironmentRegistryDocument(
|
||||
}
|
||||
|
||||
function readBrowserSavedEnvironmentRecordsWithSecrets(): ReadonlyArray<BrowserSavedEnvironmentRecord> {
|
||||
const state = readBrowserSavedEnvironmentRegistryDocument().state;
|
||||
const byId = state?.byId ?? {};
|
||||
const secretsById = state?.secretsById ?? {};
|
||||
return Object.values(byId).flatMap((record) => {
|
||||
const normalizedRecord = normalizeBrowserSavedEnvironmentRecord(record);
|
||||
if (!normalizedRecord) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const bearerToken =
|
||||
typeof secretsById[normalizedRecord.environmentId] === "string" &&
|
||||
secretsById[normalizedRecord.environmentId]
|
||||
? secretsById[normalizedRecord.environmentId]
|
||||
: typeof normalizedRecord.bearerToken === "string" &&
|
||||
normalizedRecord.bearerToken.length > 0
|
||||
? normalizedRecord.bearerToken
|
||||
: null;
|
||||
|
||||
return [
|
||||
{
|
||||
...normalizedRecord,
|
||||
...(bearerToken ? { bearerToken } : {}),
|
||||
} satisfies BrowserSavedEnvironmentRecord,
|
||||
];
|
||||
});
|
||||
return readBrowserSavedEnvironmentRegistryDocument().records ?? [];
|
||||
}
|
||||
|
||||
function writeBrowserSavedEnvironmentRecords(
|
||||
@@ -161,14 +106,7 @@ function writeBrowserSavedEnvironmentRecords(
|
||||
): void {
|
||||
writeBrowserSavedEnvironmentRegistryDocument({
|
||||
version: 1,
|
||||
state: {
|
||||
byId: Object.fromEntries(records.map((record) => [record.environmentId, record])),
|
||||
secretsById: Object.fromEntries(
|
||||
records.flatMap((record) =>
|
||||
record.bearerToken ? [[record.environmentId, record.bearerToken] as const] : [],
|
||||
),
|
||||
),
|
||||
},
|
||||
records,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -181,37 +119,32 @@ export function readBrowserSavedEnvironmentRegistry(): ReadonlyArray<PersistedSa
|
||||
export function writeBrowserSavedEnvironmentRegistry(
|
||||
records: ReadonlyArray<PersistedSavedEnvironmentRecord>,
|
||||
): void {
|
||||
const document = readBrowserSavedEnvironmentRegistryDocument();
|
||||
const directSecretsById = document.state?.secretsById ?? {};
|
||||
const existing = new Map(
|
||||
readBrowserSavedEnvironmentRecordsWithSecrets().map(
|
||||
(record) => [record.environmentId, record] as const,
|
||||
),
|
||||
);
|
||||
writeBrowserSavedEnvironmentRecords(
|
||||
records.map((record) => ({
|
||||
...record,
|
||||
...((existing.get(record.environmentId)?.bearerToken ??
|
||||
directSecretsById[record.environmentId])
|
||||
records.map((record) => {
|
||||
const bearerToken = existing.get(record.environmentId)?.bearerToken;
|
||||
return bearerToken
|
||||
? {
|
||||
bearerToken:
|
||||
existing.get(record.environmentId)?.bearerToken ??
|
||||
directSecretsById[record.environmentId],
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
bearerToken,
|
||||
}
|
||||
: {}),
|
||||
})),
|
||||
: toPersistedSavedEnvironmentRecord(record);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function readBrowserSavedEnvironmentSecret(
|
||||
environmentId: EnvironmentIdValue,
|
||||
): string | null {
|
||||
const state = readBrowserSavedEnvironmentRegistryDocument().state;
|
||||
const directSecret = state?.secretsById?.[environmentId];
|
||||
if (typeof directSecret === "string" && directSecret.length > 0) {
|
||||
return directSecret;
|
||||
}
|
||||
|
||||
return (
|
||||
readBrowserSavedEnvironmentRecordsWithSecrets().find(
|
||||
(record) => record.environmentId === environmentId,
|
||||
@@ -224,48 +157,38 @@ export function writeBrowserSavedEnvironmentSecret(
|
||||
secret: string,
|
||||
): boolean {
|
||||
const document = readBrowserSavedEnvironmentRegistryDocument();
|
||||
const state = document.state ?? {};
|
||||
const byId = state.byId ?? {};
|
||||
const existingRecord = normalizeBrowserSavedEnvironmentRecord(byId[environmentId]);
|
||||
const records = document.records ?? [];
|
||||
let found = false;
|
||||
writeBrowserSavedEnvironmentRegistryDocument({
|
||||
version: document.version ?? 1,
|
||||
state: {
|
||||
byId: existingRecord
|
||||
? {
|
||||
...byId,
|
||||
[environmentId]: {
|
||||
...existingRecord,
|
||||
bearerToken: secret,
|
||||
},
|
||||
}
|
||||
: byId,
|
||||
secretsById: {
|
||||
...state.secretsById,
|
||||
[environmentId]: secret,
|
||||
},
|
||||
},
|
||||
records: records.map((record) => {
|
||||
if (record.environmentId !== environmentId) {
|
||||
return record;
|
||||
}
|
||||
found = true;
|
||||
return {
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
bearerToken: secret,
|
||||
} satisfies BrowserSavedEnvironmentRecord;
|
||||
}),
|
||||
});
|
||||
return true;
|
||||
return found;
|
||||
}
|
||||
|
||||
export function removeBrowserSavedEnvironmentSecret(environmentId: EnvironmentIdValue): void {
|
||||
const document = readBrowserSavedEnvironmentRegistryDocument();
|
||||
const state = document.state ?? {};
|
||||
const byId = { ...state.byId };
|
||||
const existingRecord = normalizeBrowserSavedEnvironmentRecord(byId[environmentId]);
|
||||
const nextById = existingRecord
|
||||
? {
|
||||
...byId,
|
||||
[environmentId]: toPersistedSavedEnvironmentRecord(existingRecord),
|
||||
}
|
||||
: byId;
|
||||
const { [environmentId]: _removed, ...remainingSecrets } = state.secretsById ?? {};
|
||||
|
||||
writeBrowserSavedEnvironmentRegistryDocument({
|
||||
version: document.version ?? 1,
|
||||
state: {
|
||||
byId: nextById,
|
||||
secretsById: remainingSecrets,
|
||||
},
|
||||
records: (document.records ?? []).map((record) => {
|
||||
if (record.environmentId !== environmentId) {
|
||||
return record;
|
||||
}
|
||||
return toPersistedSavedEnvironmentRecord(record);
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -17,6 +17,9 @@ vi.mock("../editorPreferences", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("../localApi", () => ({
|
||||
ensureLocalApi: vi.fn(() => {
|
||||
throw new Error("ensureLocalApi not implemented in browser test");
|
||||
}),
|
||||
readLocalApi: readLocalApiMock,
|
||||
}));
|
||||
|
||||
|
||||
@@ -126,6 +126,9 @@ vi.mock("~/lib/gitStatusState", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("~/localApi", () => ({
|
||||
ensureLocalApi: vi.fn(() => {
|
||||
throw new Error("ensureLocalApi not implemented in browser test");
|
||||
}),
|
||||
readLocalApi: vi.fn(() => null),
|
||||
}));
|
||||
|
||||
|
||||
@@ -113,6 +113,9 @@ vi.mock("~/environmentApi", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("~/localApi", () => ({
|
||||
ensureLocalApi: vi.fn(() => {
|
||||
throw new Error("ensureLocalApi not implemented in browser test");
|
||||
}),
|
||||
readLocalApi: readLocalApiMock,
|
||||
}));
|
||||
|
||||
|
||||
@@ -47,12 +47,20 @@ function toPersistedSavedEnvironmentRecord(
|
||||
};
|
||||
}
|
||||
|
||||
function valuesOfSavedEnvironmentRegistry(
|
||||
byId: Record<EnvironmentId, SavedEnvironmentRecord>,
|
||||
): ReadonlyArray<SavedEnvironmentRecord> {
|
||||
return Object.values(byId) as ReadonlyArray<SavedEnvironmentRecord>;
|
||||
}
|
||||
|
||||
function persistSavedEnvironmentRegistryState(
|
||||
byId: Record<EnvironmentId, SavedEnvironmentRecord>,
|
||||
): void {
|
||||
void ensureLocalApi()
|
||||
.persistence.setSavedEnvironmentRegistry(
|
||||
Object.values(byId).map((record) => toPersistedSavedEnvironmentRecord(record)),
|
||||
valuesOfSavedEnvironmentRegistry(byId).map((record) =>
|
||||
toPersistedSavedEnvironmentRecord(record),
|
||||
),
|
||||
)
|
||||
.catch((error) => {
|
||||
console.error("[SAVED_ENVIRONMENTS] persist failed", error);
|
||||
@@ -193,7 +201,18 @@ export function resolveEnvironmentHttpUrl(input: {
|
||||
export function resetSavedEnvironmentRegistryStoreForTests() {
|
||||
savedEnvironmentRegistryHydrated = false;
|
||||
savedEnvironmentRegistryHydrationPromise = null;
|
||||
useSavedEnvironmentRegistryStore.getState().reset();
|
||||
useSavedEnvironmentRegistryStore.setState({ byId: {} });
|
||||
}
|
||||
|
||||
export async function persistSavedEnvironmentRecord(record: SavedEnvironmentRecord): Promise<void> {
|
||||
const byId = {
|
||||
...useSavedEnvironmentRegistryStore.getState().byId,
|
||||
[record.environmentId]: record,
|
||||
};
|
||||
|
||||
await ensureLocalApi().persistence.setSavedEnvironmentRegistry(
|
||||
valuesOfSavedEnvironmentRegistry(byId).map((entry) => toPersistedSavedEnvironmentRecord(entry)),
|
||||
);
|
||||
}
|
||||
|
||||
export async function readSavedEnvironmentBearerToken(
|
||||
|
||||
@@ -39,6 +39,7 @@ import {
|
||||
getSavedEnvironmentRecord,
|
||||
hasSavedEnvironmentRegistryHydrated,
|
||||
listSavedEnvironmentRecords,
|
||||
persistSavedEnvironmentRecord,
|
||||
readSavedEnvironmentBearerToken,
|
||||
removeSavedEnvironmentBearerToken,
|
||||
type SavedEnvironmentRecord,
|
||||
@@ -612,6 +613,7 @@ export async function addSavedEnvironment(input: {
|
||||
lastConnectedAt: isoNow(),
|
||||
};
|
||||
|
||||
await persistSavedEnvironmentRecord(record);
|
||||
await writeSavedEnvironmentBearerToken(environmentId, bearerSession.sessionToken);
|
||||
await ensureSavedEnvironmentConnection(record, {
|
||||
bearerToken: bearerSession.sessionToken,
|
||||
|
||||
Reference in new issue
Block a user