Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Stream from "effect/Stream";
7import * as Queue from "effect/Queue";
8import * as TestClock from "effect/testing/TestClock";
9import {
10 DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,
11 currentDesktopBootstrapToken,
12} from "@t3tools/shared/desktopBootstrapToken";
13
14import * as ServerConfig from "../config.ts";
15import * as AuthPairingLinks from "../persistence/AuthPairingLinks.ts";
16import { PersistenceSqlError } from "../persistence/Errors.ts";
17import * as SqlitePersistence from "../persistence/Sqlite.ts";
18import * as PairingGrantStore from "./PairingGrantStore.ts";
19
20const layerServerConfig = (
21 overrides?: Partial<
22 Pick<ServerConfig.ServerConfig["Service"], "desktopBootstrapToken" | "desktopBootstrapSecret">
23 >,
24) =>
25 Layer.effect(
26 ServerConfig.ServerConfig,
27 Effect.gen(function* () {
28 const config = yield* ServerConfig.ServerConfig;
29 return {
30 ...config,
31 ...overrides,
32 } satisfies ServerConfig.ServerConfig["Service"];
33 }),
34 ).pipe(
35 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-bootstrap-test-" })),
36 );
37
38const layerPairingGrantStore = (
39 overrides?: Partial<
40 Pick<ServerConfig.ServerConfig["Service"], "desktopBootstrapToken" | "desktopBootstrapSecret">
41 >,
42) =>
43 PairingGrantStore.layer.pipe(
44 Layer.provide(SqlitePersistence.layerMemory),
45 Layer.provide(layerServerConfig(overrides)),
46 );
47
48const layerPairingGrantStoreTest = (
49 overrides: Partial<AuthPairingLinks.AuthPairingLinkRepository["Service"]>,
50) =>
51 Layer.effect(PairingGrantStore.PairingGrantStore, PairingGrantStore.make).pipe(
52 Layer.provide(
53 Layer.succeed(
54 AuthPairingLinks.AuthPairingLinkRepository,
55 AuthPairingLinks.AuthPairingLinkRepository.of({
56 create: () => Effect.void,
57 consumeAvailable: () => Effect.succeedNone,
58 listActive: () => Effect.succeed([]),
59 revoke: () => Effect.succeed(false),
60 getByCredential: () => Effect.succeedNone,
61 ...overrides,
62 }),
63 ),
64 ),
65 Layer.provide(layerServerConfig()),
66 );
67
68it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
69 it.effect("issues pairing tokens in a short manual-entry format", () =>
70 Effect.gen(function* () {
71 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
72 const issued = yield* bootstrapCredentials.issueOneTimeToken();
73
74 expect(issued.credential).toMatch(/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{12}$/);
75 }).pipe(Effect.provide(layerPairingGrantStore())),
76 );
77
78 it.effect("issues one-time bootstrap tokens that can only be consumed once", () =>
79 Effect.gen(function* () {
80 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
81 const issued = yield* bootstrapCredentials.issueOneTimeToken({ label: "Julius iPhone" });
82 const first = yield* bootstrapCredentials.consume(issued.credential);
83 const second = yield* Effect.flip(bootstrapCredentials.consume(issued.credential));
84
85 expect(first.method).toBe("one-time-token");
86 expect(first.scopes).toEqual([
87 "orchestration:read",
88 "orchestration:operate",
89 "terminal:operate",
90 "review:write",
91 "relay:read",
92 ]);
93 expect(first.subject).toBe("one-time-token");
94 expect(first.label).toBe("Julius iPhone");
95 expect(issued.label).toBe("Julius iPhone");
96 expect(second._tag).toBe("UnknownBootstrapCredentialError");
97 expect(second.message).toContain("Unknown bootstrap credential");
98 }).pipe(Effect.provide(layerPairingGrantStore())),
99 );
100
101 it.effect("atomically consumes a one-time token when multiple requests race", () =>
102 Effect.gen(function* () {
103 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
104 const token = yield* bootstrapCredentials.issueOneTimeToken();
105 const results = yield* Effect.all(
106 Array.from({ length: 8 }, () =>
107 Effect.result(bootstrapCredentials.consume(token.credential)),
108 ),
109 {
110 concurrency: "unbounded",
111 },
112 );
113
114 const successes = results.filter((result) => result._tag === "Success");
115 const failures = results.filter((result) => result._tag === "Failure");
116
117 expect(successes).toHaveLength(1);
118 expect(failures).toHaveLength(7);
119 for (const failure of failures) {
120 expect(failure.failure._tag).toBe("UnknownBootstrapCredentialError");
121 expect(failure.failure.message).toContain("Unknown bootstrap credential");
122 }
123 }).pipe(Effect.provide(layerPairingGrantStore())),
124 );
125
126 it.effect("requires the bound proof key thumbprint when present", () =>
127 Effect.gen(function* () {
128 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
129 const token = yield* bootstrapCredentials.issueOneTimeToken({
130 proofKeyThumbprint: "client-proof-key-thumbprint",
131 });
132
133 const missing = yield* Effect.flip(bootstrapCredentials.consume(token.credential));
134 const wrong = yield* Effect.flip(
135 bootstrapCredentials.consume(token.credential, {
136 proofKeyThumbprint: "other-proof-key-thumbprint",
137 }),
138 );
139 const consumed = yield* bootstrapCredentials.consume(token.credential, {
140 proofKeyThumbprint: "client-proof-key-thumbprint",
141 });
142
143 expect(missing.message).toContain("proof key mismatch");
144 expect(wrong.message).toContain("proof key mismatch");
145 expect(consumed.proofKeyThumbprint).toBe("client-proof-key-thumbprint");
146 }).pipe(Effect.provide(layerPairingGrantStore())),
147 );
148
149 it.effect("seeds the desktop bootstrap credential as a reusable grant", () =>
150 Effect.gen(function* () {
151 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
152 const first = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
153 const second = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
154 const third = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
155
156 expect(first.method).toBe("desktop-bootstrap");
157 expect(first.scopes).toEqual([
158 "orchestration:read",
159 "orchestration:operate",
160 "terminal:operate",
161 "review:write",
162 "relay:read",
163 "access:read",
164 "access:write",
165 "relay:write",
166 ]);
167 expect(first.subject).toBe("desktop-bootstrap");
168 expect(second.method).toBe("desktop-bootstrap");
169 expect(third.method).toBe("desktop-bootstrap");
170 }).pipe(
171 Effect.provide(
172 layerPairingGrantStore({
173 desktopBootstrapToken: "desktop-bootstrap-token",
174 }),
175 ),
176 ),
177 );
178
179 it.effect("reports seeded desktop bootstrap credentials as expired after their ttl", () =>
180 Effect.gen(function* () {
181 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
182
183 // The desktop-bootstrap grant lives for 24h. Within that window
184 // it stays reusable.
185 yield* TestClock.adjust(Duration.hours(12));
186 const stillValid = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
187 expect(stillValid.method).toBe("desktop-bootstrap");
188
189 yield* TestClock.adjust(Duration.hours(13));
190 const expired = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
191
192 expect(expired._tag).toBe("ExpiredBootstrapCredentialError");
193 expect(expired.message).toContain("Bootstrap credential expired");
194 }).pipe(
195 Effect.provide(
196 Layer.merge(
197 layerPairingGrantStore({
198 desktopBootstrapToken: "desktop-bootstrap-token",
199 }),
200 TestClock.layer(),
201 ),
202 ),
203 ),
204 );
205
206 it.effect("accepts rotating desktop bootstrap tokens derived from the desktop secret", () =>
207 Effect.gen(function* () {
208 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
209 const window = DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS;
210
211 // A desktop open for days hands the renderer a fresh token each window.
212 yield* TestClock.adjust(Duration.days(5));
213 const now = 5 * 24 * 60 * 60 * 1000;
214 const current = yield* bootstrapCredentials.consume(
215 currentDesktopBootstrapToken("desktop-secret", now),
216 );
217 expect(current.method).toBe("desktop-bootstrap");
218
219 const stale = yield* Effect.flip(
220 bootstrapCredentials.consume(
221 currentDesktopBootstrapToken("desktop-secret", now - 2 * window),
222 ),
223 );
224 expect(stale._tag).toBe("UnknownBootstrapCredentialError");
225
226 // The launch token is not accepted on its own once a secret is present.
227 const launch = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
228 expect(launch._tag).toBe("UnknownBootstrapCredentialError");
229 }).pipe(
230 Effect.provide(
231 Layer.merge(
232 layerPairingGrantStore({
233 desktopBootstrapToken: "desktop-bootstrap-token",
234 desktopBootstrapSecret: "desktop-secret",
235 }),
236 TestClock.layer(),
237 ),
238 ),
239 ),
240 );
241
242 it.effect("keeps credentials out of pairing lists and change events", () =>
243 Effect.gen(function* () {
244 const grants = yield* PairingGrantStore.PairingGrantStore;
245 const changes = yield* Queue.unbounded<PairingGrantStore.BootstrapCredentialChange>();
246 yield* grants.streamChanges.pipe(
247 Stream.runForEach((change) => Queue.offer(changes, change)),
248 Effect.forkScoped({ startImmediately: true }),
249 );
250 for (const input of [{}, { label: "Synthetic phone" }]) {
251 const issued = yield* grants.issueOneTimeToken(input);
252 const change = yield* Queue.take(changes);
253 expect(change?.type).toBe("pairingLinkUpserted");
254 if (change?.type !== "pairingLinkUpserted")
255 throw new Error("Expected a pairing link update");
256 expect(change.pairingLink.id).toBe(issued.id);
257 expect(change.pairingLink).not.toHaveProperty("credential");
258 const listed = (yield* grants.listActive()).find((link) => link.id === issued.id);
259 expect(listed).toEqual(change.pairingLink);
260 const consumed = yield* grants.consume(issued.credential);
261 expect(consumed.scopes).toEqual(change.pairingLink.scopes);
262 expect(yield* Queue.take(changes)).toEqual({ type: "pairingLinkRemoved", id: issued.id });
263 }
264 }).pipe(Effect.scoped, Effect.provide(layerPairingGrantStore())),
265 );
266
267 it.effect("lists and revokes active pairing links", () =>
268 Effect.gen(function* () {
269 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
270 const first = yield* bootstrapCredentials.issueOneTimeToken();
271 const second = yield* bootstrapCredentials.issueOneTimeToken({
272 scopes: ["orchestration:read", "access:write"],
273 });
274
275 const activeBeforeRevoke = yield* bootstrapCredentials.listActive();
276 expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(first.id);
277 expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(second.id);
278 for (const entry of activeBeforeRevoke) {
279 expect(entry).not.toHaveProperty("credential");
280 }
281
282 const revoked = yield* bootstrapCredentials.revoke(first.id);
283 const activeAfterRevoke = yield* bootstrapCredentials.listActive();
284 const revokedConsume = yield* Effect.flip(bootstrapCredentials.consume(first.credential));
285
286 expect(revoked).toBe(true);
287 expect(activeAfterRevoke.map((entry) => entry.id)).not.toContain(first.id);
288 expect(activeAfterRevoke.map((entry) => entry.id)).toContain(second.id);
289 expect(revokedConsume.message).toContain("no longer available");
290 expect(revokedConsume._tag).toBe("UnavailableBootstrapCredentialError");
291 }).pipe(Effect.provide(layerPairingGrantStore())),
292 );
293
294 it.effect("identifies consume-available failures and preserves their cause", () => {
295 const repositoryFailure = new PersistenceSqlError({
296 operation: "consume-pairing-link",
297 detail: "Database unavailable",
298 cause: new Error("database unavailable"),
299 });
300
301 return Effect.gen(function* () {
302 const pairingGrants = yield* PairingGrantStore.PairingGrantStore;
303 const error = yield* Effect.flip(pairingGrants.consume("credential"));
304
305 if (error._tag !== "BootstrapCredentialConsumeAvailableError") {
306 return yield* Effect.die(error);
307 }
308 expect(error.cause).toBe(repositoryFailure);
309 }).pipe(
310 Effect.provide(
311 layerPairingGrantStoreTest({
312 consumeAvailable: () => Effect.fail(repositoryFailure),
313 }),
314 ),
315 );
316 });
317});