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