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