Open History to see the last commit
1import { AuthStandardClientScopes } from "@t3tools/contracts";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { expect, it } from "@effect/vitest";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Stream from "effect/Stream";
8import * as Queue from "effect/Queue";
9import * as TestClock from "effect/testing/TestClock";
10import {
11 DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,
12 currentDesktopBootstrapToken,
13} from "@t3tools/shared/desktopBootstrapToken";
14
15import * as ServerConfig from "../config.ts";
16import * as SqlitePersistence from "../persistence/Sqlite.ts";
17import * as PairingGrantStore from "./PairingGrantStore.ts";
18
19const layerServerConfig = (
20 overrides?: Partial<
21 Pick<ServerConfig.ServerConfig["Service"], "desktopBootstrapToken" | "desktopBootstrapSecret">
22 >,
23) =>
24 Layer.effect(
25 ServerConfig.ServerConfig,
26 Effect.gen(function* () {
27 const config = yield* ServerConfig.ServerConfig;
28 return {
29 ...config,
30 ...overrides,
31 } satisfies ServerConfig.ServerConfig["Service"];
32 }),
33 ).pipe(
34 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-bootstrap-test-" })),
35 );
36
37const layerPairingGrantStore = (
38 overrides?: Partial<
39 Pick<ServerConfig.ServerConfig["Service"], "desktopBootstrapToken" | "desktopBootstrapSecret">
40 >,
41) =>
42 PairingGrantStore.layer.pipe(
43 Layer.provide(SqlitePersistence.layerMemory),
44 Layer.provide(layerServerConfig(overrides)),
45 );
46
47it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
48 it.effect("issues one-time bootstrap tokens that can only be consumed once", () =>
49 Effect.gen(function* () {
50 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
51 const issued = yield* bootstrapCredentials.issueOneTimeToken({ label: "Julius iPhone" });
52 const first = yield* bootstrapCredentials.consume(issued.credential);
53 const second = yield* Effect.flip(bootstrapCredentials.consume(issued.credential));
54
55 expect(first.method).toBe("one-time-token");
56 expect(first.scopes).toEqual(AuthStandardClientScopes);
57 expect(first.subject).toBe("one-time-token");
58 expect(first.label).toBe("Julius iPhone");
59 expect(issued.label).toBe("Julius iPhone");
60 expect(second._tag).toBe("UnknownBootstrapCredentialError");
61 expect(second.message).toContain("Unknown bootstrap credential");
62 }).pipe(Effect.provide(layerPairingGrantStore())),
63 );
64
65 it.effect("atomically consumes a one-time token when multiple requests race", () =>
66 Effect.gen(function* () {
67 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
68 const token = yield* bootstrapCredentials.issueOneTimeToken();
69 const results = yield* Effect.all(
70 Array.from({ length: 8 }, () =>
71 Effect.result(
72 bootstrapCredentials.consume(token.credential, {
73 requestedScopes: ["orchestration:read"],
74 }),
75 ),
76 ),
77 {
78 concurrency: "unbounded",
79 },
80 );
81
82 const successes = results.filter((result) => result._tag === "Success");
83 const failures = results.filter((result) => result._tag === "Failure");
84
85 expect(successes).toHaveLength(1);
86 expect(failures).toHaveLength(7);
87 for (const failure of failures) {
88 expect(failure.failure._tag).toBe("UnknownBootstrapCredentialError");
89 expect(failure.failure.message).toContain("Unknown bootstrap credential");
90 }
91 }).pipe(Effect.provide(layerPairingGrantStore())),
92 );
93
94 it.effect("requires the bound proof key thumbprint when present", () =>
95 Effect.gen(function* () {
96 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
97 const token = yield* bootstrapCredentials.issueOneTimeToken({
98 proofKeyThumbprint: "client-proof-key-thumbprint",
99 scopes: ["orchestration:read"],
100 });
101
102 const missing = yield* Effect.flip(bootstrapCredentials.consume(token.credential));
103 const wrong = yield* Effect.flip(
104 bootstrapCredentials.consume(token.credential, {
105 proofKeyThumbprint: "other-proof-key-thumbprint",
106 requestedScopes: ["access:write"],
107 }),
108 );
109 const forbiddenScope = yield* Effect.flip(
110 bootstrapCredentials.consume(token.credential, {
111 proofKeyThumbprint: "client-proof-key-thumbprint",
112 requestedScopes: ["access:write"],
113 }),
114 );
115 const consumed = yield* bootstrapCredentials.consume(token.credential, {
116 proofKeyThumbprint: "client-proof-key-thumbprint",
117 requestedScopes: ["orchestration:read"],
118 });
119
120 expect(missing.message).toContain("proof key mismatch");
121 expect(wrong.message).toContain("proof key mismatch");
122 expect(forbiddenScope._tag).toBe("BootstrapCredentialScopeNotGrantedError");
123 expect(consumed.proofKeyThumbprint).toBe("client-proof-key-thumbprint");
124 }).pipe(Effect.provide(layerPairingGrantStore())),
125 );
126
127 it.effect("reports seeded desktop bootstrap credentials as expired after their ttl", () =>
128 Effect.gen(function* () {
129 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
130
131 yield* TestClock.adjust(Duration.hours(12));
132 const stillValid = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
133 expect(stillValid.method).toBe("desktop-bootstrap");
134
135 yield* TestClock.adjust(Duration.hours(13));
136 const expired = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
137
138 expect(expired._tag).toBe("ExpiredBootstrapCredentialError");
139 expect(expired.message).toContain("Bootstrap credential expired");
140 }).pipe(
141 Effect.provide(
142 Layer.merge(
143 layerPairingGrantStore({
144 desktopBootstrapToken: "desktop-bootstrap-token",
145 }),
146 TestClock.layer(),
147 ),
148 ),
149 ),
150 );
151
152 it.effect("accepts rotating desktop bootstrap tokens derived from the desktop secret", () =>
153 Effect.gen(function* () {
154 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
155 const window = DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS;
156
157 yield* TestClock.adjust(Duration.days(5));
158 const now = 5 * 24 * 60 * 60 * 1000;
159 const current = yield* bootstrapCredentials.consume(
160 currentDesktopBootstrapToken("desktop-secret", now),
161 );
162 expect(current.method).toBe("desktop-bootstrap");
163
164 const stale = yield* Effect.flip(
165 bootstrapCredentials.consume(
166 currentDesktopBootstrapToken("desktop-secret", now - 2 * window),
167 ),
168 );
169 expect(stale._tag).toBe("UnknownBootstrapCredentialError");
170
171 const launch = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
172 expect(launch._tag).toBe("UnknownBootstrapCredentialError");
173 }).pipe(
174 Effect.provide(
175 Layer.merge(
176 layerPairingGrantStore({
177 desktopBootstrapToken: "desktop-bootstrap-token",
178 desktopBootstrapSecret: "desktop-secret",
179 }),
180 TestClock.layer(),
181 ),
182 ),
183 ),
184 );
185
186 it.effect("keeps credentials out of pairing lists and change events", () =>
187 Effect.gen(function* () {
188 const grants = yield* PairingGrantStore.PairingGrantStore;
189 const changes = yield* Queue.unbounded<PairingGrantStore.BootstrapCredentialChange>();
190 yield* grants.streamChanges.pipe(
191 Stream.runForEach((change) => Queue.offer(changes, change)),
192 Effect.forkScoped({ startImmediately: true }),
193 );
194 for (const input of [{}, { label: "Synthetic phone" }]) {
195 const issued = yield* grants.issueOneTimeToken(input);
196 const change = yield* Queue.take(changes);
197 expect(change?.type).toBe("pairingLinkUpserted");
198 if (change?.type !== "pairingLinkUpserted")
199 throw new Error("Expected a pairing link update");
200 expect(change.pairingLink.id).toBe(issued.id);
201 expect(change.pairingLink).not.toHaveProperty("credential");
202 const listed = (yield* grants.listActive()).find((link) => link.id === issued.id);
203 expect(listed).toEqual(change.pairingLink);
204 const consumed = yield* grants.consume(issued.credential);
205 expect(consumed.scopes).toEqual(change.pairingLink.scopes);
206 expect(yield* Queue.take(changes)).toEqual({ type: "pairingLinkRemoved", id: issued.id });
207 }
208 }).pipe(Effect.scoped, Effect.provide(layerPairingGrantStore())),
209 );
210});