Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PairingGrantStore.ts

600 lines19.6 KB

1import {
2 AuthAdministrativeScopes,
3 AuthStandardClientScopes,
4 type AuthEnvironmentScope,
5 type AuthPairingLink,
6 type ServerAuthBootstrapMethod,
7} from "@t3tools/contracts";
8import {
9 DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,
10 isValidDesktopBootstrapToken,
11} from "@t3tools/shared/desktopBootstrapToken";
12import * as Context from "effect/Context";
13import * as Crypto from "effect/Crypto";
14import * as DateTime from "effect/DateTime";
15import * as Duration from "effect/Duration";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as PubSub from "effect/PubSub";
20import * as Ref from "effect/Ref";
21import * as Schema from "effect/Schema";
22import * as Stream from "effect/Stream";
23​
24import * as ServerConfig from "../config.ts";
25import * as AuthPairingLinks from "../persistence/AuthPairingLinks.ts";
26​
27export interface BootstrapGrant {
28 readonly method: ServerAuthBootstrapMethod;
29 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
30 readonly subject: string;
31 readonly label?: string;
32 readonly proofKeyThumbprint?: string;
33 readonly expiresAt: DateTime.DateTime;
35​
36export class UnknownBootstrapCredentialError extends Schema.TaggedError<UnknownBootstrapCredentialError>()(
37 "UnknownBootstrapCredentialError",
38 {},
39) {
40 override get message(): string {
41 return "Unknown bootstrap credential.";
42 }
44​
45export class ExpiredBootstrapCredentialError extends Schema.TaggedError<ExpiredBootstrapCredentialError>()(
46 "ExpiredBootstrapCredentialError",
47 {},
48) {
49 override get message(): string {
50 return "Bootstrap credential expired.";
51 }
53​
54export class BootstrapCredentialProofKeyMismatchError extends Schema.TaggedError<BootstrapCredentialProofKeyMismatchError>()(
55 "BootstrapCredentialProofKeyMismatchError",
56 {},
57) {
58 override get message(): string {
59 return "Bootstrap credential proof key mismatch.";
60 }
62​
63export class UnavailableBootstrapCredentialError extends Schema.TaggedError<UnavailableBootstrapCredentialError>()(
64 "UnavailableBootstrapCredentialError",
65 {},
66) {
67 override get message(): string {
68 return "Bootstrap credential is no longer available.";
69 }
71​
72export const BootstrapCredentialInvalidError = Schema.Union([
73 UnknownBootstrapCredentialError,
74 ExpiredBootstrapCredentialError,
75 BootstrapCredentialProofKeyMismatchError,
76 UnavailableBootstrapCredentialError,
77]);
78export type BootstrapCredentialInvalidError = typeof BootstrapCredentialInvalidError.Type;
79​
80export class ActivePairingLinksLoadError extends Schema.TaggedError<ActivePairingLinksLoadError>()(
81 "ActivePairingLinksLoadError",
82 {
83 cause: Schema.Defect(),
84 },
85) {
86 override get message(): string {
87 return "Failed to load active pairing links.";
88 }
90​
91export class PairingLinkRevokeError extends Schema.TaggedError<PairingLinkRevokeError>()(
92 "PairingLinkRevokeError",
93 {
94 pairingLinkId: Schema.String,
95 cause: Schema.Defect(),
96 },
97) {
98 override get message(): string {
99 return `Failed to revoke pairing link '${this.pairingLinkId}'.`;
100 }
102​
103export class PairingCredentialIssueError extends Schema.TaggedError<PairingCredentialIssueError>()(
104 "PairingCredentialIssueError",
105 {
106 pairingLinkId: Schema.String,
107 subject: Schema.String,
108 label: Schema.optional(Schema.String),
109 cause: Schema.Defect(),
110 },
111) {
112 override get message(): string {
113 return `Failed to issue pairing credential '${this.pairingLinkId}' for '${this.subject}'.`;
114 }
116​
117export class PairingCredentialRandomGenerationError extends Schema.TaggedError<PairingCredentialRandomGenerationError>()(
118 "PairingCredentialRandomGenerationError",
119 {
120 operation: Schema.Literals(["generate-id", "generate-token"]),
121 cause: Schema.Defect(),
122 },
123) {
124 override get message(): string {
125 return `Failed to generate pairing credential data during '${this.operation}'.`;
126 }
128​
129export class BootstrapCredentialConsumeError extends Schema.TaggedError<BootstrapCredentialConsumeError>()(
130 "BootstrapCredentialConsumeError",
131 {
132 cause: Schema.Defect(),
133 },
134) {
135 override get message(): string {
136 return "Failed to consume bootstrap credential.";
137 }
139​
140export class BootstrapCredentialConsumeAvailableError extends Schema.TaggedError<BootstrapCredentialConsumeAvailableError>()(
141 "BootstrapCredentialConsumeAvailableError",
142 {
143 cause: Schema.Defect(),
144 },
145) {
146 override get message(): string {
147 return "Failed to atomically consume an available bootstrap credential.";
148 }
150​
151export class BootstrapCredentialLookupError extends Schema.TaggedError<BootstrapCredentialLookupError>()(
152 "BootstrapCredentialLookupError",
153 {
154 cause: Schema.Defect(),
155 },
156) {
157 override get message(): string {
158 return "Failed to look up bootstrap credential state.";
159 }
161​
162export const BootstrapCredentialInternalError = Schema.Union([
163 ActivePairingLinksLoadError,
164 PairingLinkRevokeError,
165 PairingCredentialIssueError,
166 PairingCredentialRandomGenerationError,
167 BootstrapCredentialConsumeError,
168 BootstrapCredentialConsumeAvailableError,
169 BootstrapCredentialLookupError,
170]);
171export type BootstrapCredentialInternalError = typeof BootstrapCredentialInternalError.Type;
172export const isBootstrapCredentialInternalError = Schema.is(BootstrapCredentialInternalError);
173​
174export const BootstrapCredentialError = Schema.Union([
175 BootstrapCredentialInvalidError,
176 BootstrapCredentialInternalError,
177]);
178export type BootstrapCredentialError = typeof BootstrapCredentialError.Type;
179​
180export interface IssuedBootstrapCredential {
181 readonly id: string;
182 readonly credential: string;
183 readonly label?: string;
184 readonly proofKeyThumbprint?: string;
185 readonly expiresAt: DateTime.Utc;
187​
188export type BootstrapCredentialChange =
189 | {
190 readonly type: "pairingLinkUpserted";
191 readonly pairingLink: AuthPairingLink;
192 }
193 | {
194 readonly type: "pairingLinkRemoved";
195 readonly id: string;
196 };
197​
198export class PairingGrantStore extends Context.Service<
199 PairingGrantStore,
200 {
201 readonly issueOneTimeToken: (input?: {
202 readonly ttl?: Duration.Duration;
203 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
204 readonly subject?: string;
205 readonly label?: string;
206 readonly proofKeyThumbprint?: string;
207 /**
208 * "startup" marks the credential the server mints for itself at boot,
209 * which gets the long dev TTL when a dev URL is configured.
210 */
211 readonly purpose?: "startup";
212 }) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
213 readonly listActive: () => Effect.Effect<
214 ReadonlyArray<AuthPairingLink>,
215 BootstrapCredentialInternalError
216 >;
217 readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
218 readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
219 readonly consume: (
220 credential: string,
221 input?: {
222 readonly proofKeyThumbprint?: string;
223 },
224 ) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
225 }
226>()("t3/auth/PairingGrantStore") {}
227​
228interface StoredBootstrapGrant extends BootstrapGrant {
229 readonly remainingUses: number | "unbounded";
231​
232type ConsumeResult =
233 | {
234 readonly _tag: "error";
235 readonly reason: "not-found" | "expired";
236 readonly error: BootstrapCredentialError;
237 }
238 | {
239 readonly _tag: "success";
240 readonly grant: BootstrapGrant;
241 };
242​
243const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
244// The desktop-bootstrap grant rides on a trusted IPC channel (fd3 or
245// stdin) at backend launch, so it doesn't have to be short-lived the
246// way a user-facing pairing link does. Letting it live for the
247// lifetime of the backend process (24h is more than long enough for
248// practical desktop use, and well under "forever" in case the seed
249// gets logged anywhere by accident) means a page reload past the 5-min
250// window can still recover by re-bootstrapping rather than locking
251// the user out of the backend.
252const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
253// A dev server's startup token is read off a log by whoever (or whatever) is
254// driving the session, often minutes later — after a `node --watch` restart, a
255// detour into another task, or a hand-off to the person actually doing the
256// testing. Five minutes turns that into a restart-the-server loop for no
257// security benefit: the token only unlocks a local dev backend, and its holder
258// could read the log anyway. Same reasoning (and duration) as the desktop
259// bootstrap grant above. Only applies when a dev URL is configured; user-issued
260// pairing links and real servers keep the 5-minute default.
261const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
262const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
263const PAIRING_TOKEN_LENGTH = 12;
264const PAIRING_TOKEN_REJECTION_LIMIT =
265 Math.floor(256 / PAIRING_TOKEN_ALPHABET.length) * PAIRING_TOKEN_ALPHABET.length;
266​
267export const make = Effect.gen(function* () {
268 const crypto = yield* Crypto.Crypto;
269 const config = yield* ServerConfig.ServerConfig;
270 const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository;
271 const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
272 const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
273 const generatePairingToken = Effect.gen(function* () {
274 let credential = "";
275 while (credential.length < PAIRING_TOKEN_LENGTH) {
276 const bytes = yield* crypto
277 .randomBytes(PAIRING_TOKEN_LENGTH)
278 .pipe(
279 Effect.mapError(
280 (cause) =>
281 new PairingCredentialRandomGenerationError({ operation: "generate-token", cause }),
282 ),
283 );
284 for (const byte of bytes) {
285 if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) {
286 continue;
287 }
288 credential += PAIRING_TOKEN_ALPHABET[byte % PAIRING_TOKEN_ALPHABET.length]!;
289 if (credential.length === PAIRING_TOKEN_LENGTH) {
290 return credential;
291 }
292 }
293 }
294 return credential;
295 });
296​
297 const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>
298 Ref.update(seededGrantsRef, (current) => {
299 const next = new Map(current);
300 next.set(credential, grant);
301 return next;
302 });
303​
304 const emitUpsert = (pairingLink: AuthPairingLink) =>
305 PubSub.publish(changesPubSub, {
306 type: "pairingLinkUpserted",
307 pairingLink,
308 }).pipe(Effect.asVoid);
309​
310 const emitRemoved = (id: string) =>
311 PubSub.publish(changesPubSub, {
312 type: "pairingLinkRemoved",
313 id,
314 }).pipe(Effect.asVoid);
315​
316 // A desktop that sends its secret rotates the renderer's token, so accept
317 // whichever token the secret derives for the current window instead of
318 // seeding one fixed token. Older desktops only send the token.
319 const desktopBootstrapSecret = config.desktopBootstrapSecret;
320 const consumeRotatingDesktopToken = (credential: string, nowMs: number) =>
321 desktopBootstrapSecret !== undefined &&
322 isValidDesktopBootstrapToken(desktopBootstrapSecret, credential, nowMs);
323​
324 if (config.desktopBootstrapToken && desktopBootstrapSecret === undefined) {
325 const now = yield* DateTime.now;
326 yield* seedGrant(config.desktopBootstrapToken, {
327 method: "desktop-bootstrap",
328 scopes: AuthAdministrativeScopes,
329 subject: "desktop-bootstrap",
330 expiresAt: DateTime.add(now, {
331 milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS),
332 }),
333 // Unbounded uses so the renderer can re-exchange the seed for a
334 // fresh bearer session after a page reload (or after the prior
335 // bearer expires). The seed itself stays inside the desktop
336 // process and the rendered page, both of which the user already
337 // implicitly trusts.
338 remainingUses: "unbounded",
339 });
340 }
341​
342 const listActive: PairingGrantStore["Service"]["listActive"] = Effect.fn(
343 "PairingGrantStore.listActive",
344 )(
345 function* () {
346 const now = yield* DateTime.now;
347 const rows = yield* pairingLinks.listActive({ now });
348​
349 return rows.map((row) =>
350 row.label
351 ? ({
352 id: row.id,
353 scopes: row.scopes,
354 subject: row.subject,
355 label: row.label,
356 createdAt: row.createdAt,
357 expiresAt: row.expiresAt,
358 } satisfies AuthPairingLink)
359 : ({
360 id: row.id,
361 scopes: row.scopes,
362 subject: row.subject,
363 createdAt: row.createdAt,
364 expiresAt: row.expiresAt,
365 } satisfies AuthPairingLink),
366 );
367 },
368 Effect.mapError((cause) => new ActivePairingLinksLoadError({ cause })),
369 );
370​
371 const revoke: PairingGrantStore["Service"]["revoke"] = Effect.fn("PairingGrantStore.revoke")(
372 function* (id) {
373 const revokedAt = yield* DateTime.now;
374 const revoked = yield* pairingLinks
375 .revoke({
376 id,
377 revokedAt,
378 })
379 .pipe(Effect.mapError((cause) => new PairingLinkRevokeError({ pairingLinkId: id, cause })));
380 if (revoked) {
381 yield* emitRemoved(id);
382 }
383 return revoked;
384 },
385 );
386​
387 const issueOneTimeToken: PairingGrantStore["Service"]["issueOneTimeToken"] = Effect.fn(
388 "PairingGrantStore.issueOneTimeToken",
389 )(function* (input) {
390 const id = yield* crypto.randomUUIDv4.pipe(
391 Effect.mapError(
392 (cause) => new PairingCredentialRandomGenerationError({ operation: "generate-id", cause }),
393 ),
394 );
395 const credential = yield* generatePairingToken;
396 const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
397 const ttl =
398 input?.ttl ??
399 (isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
400 const now = yield* DateTime.now;
401 const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
402 const issued: IssuedBootstrapCredential = {
403 id,
404 credential,
405 ...(input?.label ? { label: input.label } : {}),
406 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
407 expiresAt,
408 };
409 const subject = input?.subject ?? "one-time-token";
410 yield* pairingLinks
411 .create({
412 id,
413 credential,
414 method: "one-time-token",
415 scopes: input?.scopes ?? AuthStandardClientScopes,
416 subject,
417 label: input?.label ?? null,
418 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
419 createdAt: now,
420 expiresAt: expiresAt,
421 })
422 .pipe(
423 Effect.mapError(
424 (cause) =>
425 new PairingCredentialIssueError({
426 pairingLinkId: id,
427 subject,
428 ...(input?.label ? { label: input.label } : {}),
429 cause,
430 }),
431 ),
432 );
433 yield* emitUpsert({
434 id,
435 scopes: input?.scopes ?? AuthStandardClientScopes,
436 subject: input?.subject ?? "one-time-token",
437 ...(input?.label ? { label: input.label } : {}),
438 createdAt: now,
439 expiresAt,
440 });
441 return issued;
442 });
443​
444 const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")(
445 function* (credential, input) {
446 const now = yield* DateTime.now;
447 if (consumeRotatingDesktopToken(credential, now.epochMilliseconds)) {
448 return {
449 method: "desktop-bootstrap",
450 scopes: AuthAdministrativeScopes,
451 subject: "desktop-bootstrap",
452 expiresAt: DateTime.add(now, {
453 milliseconds: DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,
454 }),
455 } satisfies BootstrapGrant;
456 }
457 const seededResult: ConsumeResult = yield* Ref.modify(
458 seededGrantsRef,
459 (current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
460 const grant = current.get(credential);
461 if (!grant) {
462 return [
463 {
464 _tag: "error",
465 reason: "not-found",
466 error: new UnknownBootstrapCredentialError({}),
467 },
468 current,
469 ];
470 }
471​
472 const next = new Map(current);
473 if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
474 next.delete(credential);
475 return [
476 {
477 _tag: "error",
478 reason: "expired",
479 error: new ExpiredBootstrapCredentialError({}),
480 },
481 next,
482 ];
483 }
484​
485 if (grant.proofKeyThumbprint && grant.proofKeyThumbprint !== input?.proofKeyThumbprint) {
486 return [
487 {
488 _tag: "error",
489 reason: "not-found",
490 error: new BootstrapCredentialProofKeyMismatchError({}),
491 },
492 next,
493 ];
494 }
495​
496 const remainingUses = grant.remainingUses;
497 if (typeof remainingUses === "number") {
498 if (remainingUses <= 1) {
499 next.delete(credential);
500 } else {
501 next.set(credential, {
502 ...grant,
503 remainingUses: remainingUses - 1,
504 });
505 }
506 }
507​
508 return [
509 {
510 _tag: "success",
511 grant: {
512 method: grant.method,
513 scopes: grant.scopes,
514 subject: grant.subject,
515 ...(grant.label ? { label: grant.label } : {}),
516 ...(grant.proofKeyThumbprint
517 ? { proofKeyThumbprint: grant.proofKeyThumbprint }
518 : {}),
519 expiresAt: grant.expiresAt,
520 } satisfies BootstrapGrant,
521 },
522 next,
523 ];
524 },
525 );
526​
527 if (seededResult._tag === "success") {
528 return seededResult.grant;
529 }
530 if (seededResult.reason !== "not-found") {
531 return yield* seededResult.error;
532 }
533​
534 const consumed = yield* pairingLinks
535 .consumeAvailable({
536 credential,
537 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
538 consumedAt: now,
539 now,
540 })
541 .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));
542​
543 if (Option.isSome(consumed)) {
544 yield* emitRemoved(consumed.value.id);
545 return {
546 method: consumed.value.method,
547 scopes: consumed.value.scopes,
548 subject: consumed.value.subject,
549 ...(consumed.value.label ? { label: consumed.value.label } : {}),
550 ...(consumed.value.proofKeyThumbprint
551 ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }
552 : {}),
553 expiresAt: consumed.value.expiresAt,
554 } satisfies BootstrapGrant;
555 }
556​
557 const matching = yield* pairingLinks
558 .getByCredential({ credential })
559 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
560 if (Option.isNone(matching)) {
561 return yield* new UnknownBootstrapCredentialError({});
562 }
563​
564 if (matching.value.revokedAt !== null) {
565 return yield* new UnavailableBootstrapCredentialError({});
566 }
567​
568 if (matching.value.consumedAt !== null) {
569 return yield* new UnknownBootstrapCredentialError({});
570 }
571​
572 if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
573 return yield* new ExpiredBootstrapCredentialError({});
574 }
575​
576 if (
577 matching.value.proofKeyThumbprint !== null &&
578 matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint
579 ) {
580 return yield* new BootstrapCredentialProofKeyMismatchError({});
581 }
582​
583 return yield* new UnavailableBootstrapCredentialError({});
584 },
585 );
586​
587 return PairingGrantStore.of({
588 issueOneTimeToken,
589 listActive,
590 get streamChanges() {
591 return Stream.fromPubSub(changesPubSub);
592 },
593 revoke,
594 consume,
595 });
596});
597​
598export const layer = Layer.effect(PairingGrantStore, make).pipe(
599 Layer.provideMerge(AuthPairingLinks.layer),
600);