Open History to see the last commit
1import {
2 ConnectionTransientError,
3 PrimaryConnectionTarget,
4} from "@t3tools/client-runtime/connection";
5import { EnvironmentId } from "@t3tools/contracts";
6import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform";
7import { describe, expect, it } from "@effect/vitest";
8import * as Effect from "effect/Effect";
9import * as Deferred from "effect/Deferred";
10import * as Option from "effect/Option";
11import * as Schema from "effect/Schema";
12import * as Stream from "effect/Stream";
13import { afterEach, vi } from "vite-plus/test";
14
15import {
16 makeBrowserGitHubRoutingPermissions,
17 makeCatalogBackend,
18 makeCatalogStore,
19} from "./storage";
20
21const emptyCatalog = {
22 schemaVersion: 1,
23 targets: [],
24 profiles: [],
25 credentials: [],
26 remoteDpopTokens: [],
27 disabledEnvironmentIds: [],
28} as const;
29const decodeCatalog = Schema.decodeUnknownSync(Schema.fromJsonString(ConnectionCatalogDocument));
30const encodeCatalog = Schema.encodeSync(Schema.fromJsonString(ConnectionCatalogDocument));
31
32afterEach(() => {
33 vi.unstubAllGlobals();
34 vi.restoreAllMocks();
35});
36
37describe("makeCatalogStore", () => {
38 it.effect("quarantines malformed catalogs and starts from an empty document", () =>
39 Effect.gen(function* () {
40 const writes: string[] = [];
41 const quarantined: string[] = [];
42 const store = yield* makeCatalogStore({
43 read: Effect.succeed("{not-json"),
44 write: (raw) => Effect.sync(() => writes.push(raw)),
45 quarantine: (raw) => Effect.sync(() => quarantined.push(raw)),
46 });
47
48 expect(yield* store.read).toEqual(emptyCatalog);
49 expect(quarantined).toEqual(["{not-json"]);
50 expect(writes).toHaveLength(1);
51 expect(decodeCatalog(writes[0]!)).toEqual(emptyCatalog);
52 }),
53 );
54
55 it.effect("does not hide catalog read failures", () =>
56 Effect.gen(function* () {
57 const failure = new ConnectionTransientError({
58 reason: "remote-unavailable",
59 detail: "permission denied",
60 });
61 const store = yield* makeCatalogStore({
62 read: Effect.fail(failure),
63 write: () => Effect.void,
64 });
65
66 expect(yield* Effect.flip(store.read)).toBe(failure);
67 }),
68 );
69});
70
71describe("makeCatalogBackend", () => {
72 it.effect("fails writes when desktop secure storage declines the catalog", () =>
73 Effect.gen(function* () {
74 const setConnectionCatalog = vi.fn().mockResolvedValue(false);
75 vi.stubGlobal("window", {
76 desktopBridge: {
77 getConnectionCatalog: vi.fn().mockResolvedValue(null),
78 setConnectionCatalog,
79 },
80 });
81 const backend = makeCatalogBackend({} as IDBDatabase);
82
83 const error = yield* backend.write("{}").pipe(Effect.flip);
84
85 expect(error).toBeInstanceOf(ConnectionTransientError);
86 expect(error.message).toContain("Desktop secure storage is unavailable");
87 expect(setConnectionCatalog).toHaveBeenCalledWith("{}");
88 }),
89 );
90});
91
92describe("browser GitHub routing permissions", () => {
93 it.effect("revokes across runtimes before storage events and resists stale catalog writes", () =>
94 Effect.gen(function* () {
95 const values = new Map<string, string>();
96 const localStorage: Storage = {
97 get length() {
98 return values.size;
99 },
100 key: (index) => [...values.keys()][index] ?? null,
101 getItem: (key) => values.get(key) ?? null,
102 setItem: (key, value) => {
103 values.set(key, value);
104 },
105 removeItem: (key) => {
106 values.delete(key);
107 },
108 clear: () => {
109 values.clear();
110 },
111 };
112 const firstBrowser = Object.assign(new EventTarget(), { localStorage });
113 const secondBrowser = Object.assign(new EventTarget(), { localStorage });
114 const first = makeBrowserGitHubRoutingPermissions(firstBrowser);
115 const second = makeBrowserGitHubRoutingPermissions(secondBrowser);
116 const entry = {
117 target: new PrimaryConnectionTarget({
118 environmentId: EnvironmentId.make("first"),
119 label: "First",
120 httpBaseUrl: "http://localhost:3000",
121 wsBaseUrl: "ws://localhost:3000",
122 }),
123 profile: Option.none(),
124 enabled: true,
125 };
126 const other = {
127 ...entry,
128 target: new PrimaryConnectionTarget({
129 ...entry.target,
130 environmentId: EnvironmentId.make("second"),
131 }),
132 };
133 expect(yield* first.get(entry)).toBe("off");
134 yield* first.set(entry, "read-write");
135 expect(yield* second.get(entry)).toBe("read-write");
136 const oldPermissions = Option.getOrThrow(yield* Stream.runHead(first.changes));
137 const staleCatalog = yield* makeCatalogStore({
138 read: Effect.succeed(
139 encodeCatalog({ ...emptyCatalog, githubRoutingPermissions: oldPermissions }),
140 ),
141 write: () => Effect.void,
142 });
143 yield* staleCatalog.read;
144 const listening = yield* Deferred.make<void>();
145 const revoked = yield* Deferred.make<void>();
146 yield* second.changes.pipe(
147 Stream.runForEach((permissions) =>
148 Deferred.succeed(permissions.length > 0 ? listening : revoked, undefined),
149 ),
150 Effect.forkChild,
151 );
152 yield* Deferred.await(listening);
153
154 yield* first.set(entry, "off");
155 expect(yield* second.get(entry)).toBe("off");
156 secondBrowser.dispatchEvent(Object.assign(new Event("storage"), { key: null }));
157 yield* Deferred.await(revoked);
158 yield* second.set(other, "read");
159 yield* staleCatalog.update((document) => ({ ...document, accountId: "updated" }));
160 expect(yield* second.get(entry)).toBe("off");
161 expect(yield* first.get(other)).toBe("read");
162 expect(yield* makeBrowserGitHubRoutingPermissions(firstBrowser).get(entry)).toBe("off");
163
164 yield* first.set(entry, "read-write");
165 yield* second.forget(entry.target.environmentId);
166 expect(yield* first.get(entry)).toBe("off");
167 expect(yield* first.get(other)).toBe("read");
168 vi.spyOn(localStorage, "setItem").mockImplementation(() => {
169 throw new Error("Storage unavailable");
170 });
171 expect(yield* first.set(entry, "read-write").pipe(Effect.flip)).toBeInstanceOf(
172 ConnectionTransientError,
173 );
174 expect(yield* second.get(entry)).toBe("off");
175 }).pipe(Effect.scoped),
176 );
177});