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

PairingGrantStore.ts

621 lines19.7 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 class BootstrapCredentialScopeNotGrantedError extends Schema.TaggedError<BootstrapCredentialScopeNotGrantedError>()(
73 "BootstrapCredentialScopeNotGrantedError",
74 {},
75) {
76 override get message(): string {
77 return "The requested authentication scope was not granted.";
78 }
80​
81export const BootstrapCredentialInvalidError = Schema.Union([
82 UnknownBootstrapCredentialError,
83 ExpiredBootstrapCredentialError,
84 BootstrapCredentialProofKeyMismatchError,
85 UnavailableBootstrapCredentialError,
86]);
87export type BootstrapCredentialInvalidError = typeof BootstrapCredentialInvalidError.Type;
88​
89export class ActivePairingLinksLoadError extends Schema.TaggedError<ActivePairingLinksLoadError>()(
90 "ActivePairingLinksLoadError",
91 {
92 cause: Schema.Defect(),
93 },
94) {
95 override get message(): string {
96 return "Failed to load active pairing links.";
97 }
99​
100export class PairingLinkRevokeError extends Schema.TaggedError<PairingLinkRevokeError>()(
101 "PairingLinkRevokeError",
102 {
103 pairingLinkId: Schema.String,
104 cause: Schema.Defect(),
105 },
106) {
107 override get message(): string {
108 return `Failed to revoke pairing link '${this.pairingLinkId}'.`;
109 }
111​
112export class PairingCredentialIssueError extends Schema.TaggedError<PairingCredentialIssueError>()(
113 "PairingCredentialIssueError",
114 {
115 pairingLinkId: Schema.String,
116 subject: Schema.String,
117 label: Schema.optional(Schema.String),
118 cause: Schema.Defect(),
119 },
120) {
121 override get message(): string {
122 return `Failed to issue pairing credential '${this.pairingLinkId}' for '${this.subject}'.`;
123 }
125​
126export class PairingCredentialRandomGenerationError extends Schema.TaggedError<PairingCredentialRandomGenerationError>()(
127 "PairingCredentialRandomGenerationError",
128 {
129 operation: Schema.Literals(["generate-id", "generate-token"]),
130 cause: Schema.Defect(),
131 },
132) {
133 override get message(): string {
134 return `Failed to generate pairing credential data during '${this.operation}'.`;
135 }
137​
138export class BootstrapCredentialConsumeError extends Schema.TaggedError<BootstrapCredentialConsumeError>()(
139 "BootstrapCredentialConsumeError",
140 {
141 cause: Schema.Defect(),
142 },
143) {
144 override get message(): string {
145 return "Failed to consume bootstrap credential.";
146 }
148​
149export class BootstrapCredentialConsumeAvailableError extends Schema.TaggedError<BootstrapCredentialConsumeAvailableError>()(
150 "BootstrapCredentialConsumeAvailableError",
151 {
152 cause: Schema.Defect(),
153 },
154) {
155 override get message(): string {
156 return "Failed to atomically consume an available bootstrap credential.";
157 }
159​
160export class BootstrapCredentialLookupError extends Schema.TaggedError<BootstrapCredentialLookupError>()(
161 "BootstrapCredentialLookupError",
162 {
163 cause: Schema.Defect(),
164 },
165) {
166 override get message(): string {
167 return "Failed to look up bootstrap credential state.";
168 }
170​
171export const BootstrapCredentialInternalError = Schema.Union([
172 ActivePairingLinksLoadError,
173 PairingLinkRevokeError,
174 PairingCredentialIssueError,
175 PairingCredentialRandomGenerationError,
176 BootstrapCredentialConsumeError,
177 BootstrapCredentialConsumeAvailableError,
178 BootstrapCredentialLookupError,
179]);
180export type BootstrapCredentialInternalError = typeof BootstrapCredentialInternalError.Type;
181export const isBootstrapCredentialInternalError = Schema.is(BootstrapCredentialInternalError);
182​
183export const BootstrapCredentialError = Schema.Union([
184 BootstrapCredentialInvalidError,
185 BootstrapCredentialInternalError,
186 BootstrapCredentialScopeNotGrantedError,
187]);
188export type BootstrapCredentialError = typeof BootstrapCredentialError.Type;
189​
190export interface IssuedBootstrapCredential {
191 readonly id: string;
192 readonly credential: string;
193 readonly label?: string;
194 readonly proofKeyThumbprint?: string;
195 readonly expiresAt: DateTime.Utc;
197​
198export type BootstrapCredentialChange =
199 | {
200 readonly type: "pairingLinkUpserted";
201 readonly pairingLink: AuthPairingLink;
202 }
203 | {
204 readonly type: "pairingLinkRemoved";
205 readonly id: string;
206 };
207​
208export class PairingGrantStore extends Context.Service<
209 PairingGrantStore,
210 {
211 readonly issueOneTimeToken: (input?: {
212 readonly ttl?: Duration.Duration;
213 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
214 readonly subject?: string;
215 readonly label?: string;
216 readonly proofKeyThumbprint?: string;
217 readonly purpose?: "startup";
218 }) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
219 readonly listActive: () => Effect.Effect<
220 ReadonlyArray<AuthPairingLink>,
221 BootstrapCredentialInternalError
222 >;
223 readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
224 readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
225 readonly consume: (
226 credential: string,
227 input?: {
228 readonly proofKeyThumbprint?: string;
229 readonly requestedScopes?: ReadonlyArray<AuthEnvironmentScope>;
230 },
231 ) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
232 }
233>()("t3/auth/PairingGrantStore") {}
234​
235interface StoredBootstrapGrant extends BootstrapGrant {
236 readonly remainingUses: number | "unbounded";
238​
239type ConsumeResult =
240 | {
241 readonly _tag: "error";
242 readonly reason: "not-found" | "expired" | "scope-not-granted";
243 readonly error: BootstrapCredentialError;
244 }
245 | {
246 readonly _tag: "success";
247 readonly grant: BootstrapGrant;
248 };
249​
250const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
251const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
252const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
253const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
254const PAIRING_TOKEN_LENGTH = 12;
255const PAIRING_TOKEN_REJECTION_LIMIT =
256 Math.floor(256 / PAIRING_TOKEN_ALPHABET.length) * PAIRING_TOKEN_ALPHABET.length;
257​
258export const make = Effect.gen(function* () {
259 const crypto = yield* Crypto.Crypto;
260 const config = yield* ServerConfig.ServerConfig;
261 const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository;
262 const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
263 const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
264 const generatePairingToken = Effect.gen(function* () {
265 let credential = "";
266 while (credential.length < PAIRING_TOKEN_LENGTH) {
267 const bytes = yield* crypto
268 .randomBytes(PAIRING_TOKEN_LENGTH)
269 .pipe(
270 Effect.mapError(
271 (cause) =>
272 new PairingCredentialRandomGenerationError({ operation: "generate-token", cause }),
273 ),
274 );
275 for (const byte of bytes) {
276 if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) {
277 continue;
278 }
279 credential += PAIRING_TOKEN_ALPHABET[byte % PAIRING_TOKEN_ALPHABET.length]!;
280 if (credential.length === PAIRING_TOKEN_LENGTH) {
281 return credential;
282 }
283 }
284 }
285 return credential;
286 });
287​
288 const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>
289 Ref.update(seededGrantsRef, (current) => {
290 const next = new Map(current);
291 next.set(credential, grant);
292 return next;
293 });
294​
295 const emitUpsert = (pairingLink: AuthPairingLink) =>
296 PubSub.publish(changesPubSub, {
297 type: "pairingLinkUpserted",
298 pairingLink,
299 }).pipe(Effect.asVoid);
300​
301 const emitRemoved = (id: string) =>
302 PubSub.publish(changesPubSub, {
303 type: "pairingLinkRemoved",
304 id,
305 }).pipe(Effect.asVoid);
306​
307 // A desktop that sends its secret rotates the renderer's token, so accept
308 // whichever token the secret derives for the current window instead of
309 // seeding one fixed token. Older desktops only send the token.
310 const desktopBootstrapSecret = config.desktopBootstrapSecret;
311 const consumeRotatingDesktopToken = (credential: string, nowMs: number) =>
312 desktopBootstrapSecret !== undefined &&
313 isValidDesktopBootstrapToken(desktopBootstrapSecret, credential, nowMs);
314​
315 if (config.desktopBootstrapToken && desktopBootstrapSecret === undefined) {
316 const now = yield* DateTime.now;
317 yield* seedGrant(config.desktopBootstrapToken, {
318 method: "desktop-bootstrap",
319 scopes: AuthAdministrativeScopes,
320 subject: "desktop-bootstrap",
321 expiresAt: DateTime.add(now, {
322 milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS),
323 }),
324 // Unbounded uses so the renderer can re-exchange the seed for a
325 // fresh bearer session after a page reload (or after the prior
326 // bearer expires). The seed itself stays inside the desktop
327 // process and the rendered page, both of which the user already
328 // implicitly trusts.
329 remainingUses: "unbounded",
330 });
331 }
332​
333 const listActive: PairingGrantStore["Service"]["listActive"] = Effect.fn(
334 "PairingGrantStore.listActive",
335 )(
336 function* () {
337 const now = yield* DateTime.now;
338 const rows = yield* pairingLinks.listActive({ now });
339​
340 return rows.map((row) =>
341 row.label
342 ? ({
343 id: row.id,
344 scopes: row.scopes,
345 subject: row.subject,
346 label: row.label,
347 createdAt: row.createdAt,
348 expiresAt: row.expiresAt,
349 } satisfies AuthPairingLink)
350 : ({
351 id: row.id,
352 scopes: row.scopes,
353 subject: row.subject,
354 createdAt: row.createdAt,
355 expiresAt: row.expiresAt,
356 } satisfies AuthPairingLink),
357 );
358 },
359 Effect.mapError((cause) => new ActivePairingLinksLoadError({ cause })),
360 );
361​
362 const revoke: PairingGrantStore["Service"]["revoke"] = Effect.fn("PairingGrantStore.revoke")(
363 function* (id) {
364 const revokedAt = yield* DateTime.now;
365 const revoked = yield* pairingLinks
366 .revoke({
367 id,
368 revokedAt,
369 })
370 .pipe(Effect.mapError((cause) => new PairingLinkRevokeError({ pairingLinkId: id, cause })));
371 if (revoked) {
372 yield* emitRemoved(id);
373 }
374 return revoked;
375 },
376 );
377​
378 const issueOneTimeToken: PairingGrantStore["Service"]["issueOneTimeToken"] = Effect.fn(
379 "PairingGrantStore.issueOneTimeToken",
380 )(function* (input) {
381 const id = yield* crypto
382 .randomUUIDv4()
383 .pipe(
384 Effect.mapError(
385 (cause) =>
386 new PairingCredentialRandomGenerationError({ operation: "generate-id", cause }),
387 ),
388 );
389 const credential = yield* generatePairingToken;
390 const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
391 const ttl =
392 input?.ttl ??
393 (isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
394 const now = yield* DateTime.now;
395 const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
396 const issued: IssuedBootstrapCredential = {
397 id,
398 credential,
399 ...(input?.label ? { label: input.label } : {}),
400 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
401 expiresAt,
402 };
403 const subject = input?.subject ?? "one-time-token";
404 yield* pairingLinks
405 .create({
406 id,
407 credential,
408 method: "one-time-token",
409 scopes: input?.scopes ?? AuthStandardClientScopes,
410 subject,
411 label: input?.label ?? null,
412 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
413 createdAt: now,
414 expiresAt: expiresAt,
415 })
416 .pipe(
417 Effect.mapError(
418 (cause) =>
419 new PairingCredentialIssueError({
420 pairingLinkId: id,
421 subject,
422 ...(input?.label ? { label: input.label } : {}),
423 cause,
424 }),
425 ),
426 );
427 yield* emitUpsert({
428 id,
429 scopes: input?.scopes ?? AuthStandardClientScopes,
430 subject: input?.subject ?? "one-time-token",
431 ...(input?.label ? { label: input.label } : {}),
432 createdAt: now,
433 expiresAt,
434 });
435 return issued;
436 });
437​
438 const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")(
439 function* (credential, input) {
440 const now = yield* DateTime.now;
441 if (consumeRotatingDesktopToken(credential, now.epochMilliseconds)) {
442 return {
443 method: "desktop-bootstrap",
444 scopes: AuthAdministrativeScopes,
445 subject: "desktop-bootstrap",
446 expiresAt: DateTime.add(now, {
447 milliseconds: DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,
448 }),
449 } satisfies BootstrapGrant;
450 }
451 const seededResult: ConsumeResult = yield* Ref.modify(
452 seededGrantsRef,
453 (current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
454 const grant = current.get(credential);
455 if (!grant) {
456 return [
457 {
458 _tag: "error",
459 reason: "not-found",
460 error: new UnknownBootstrapCredentialError({}),
461 },
462 current,
463 ];
464 }
465​
466 const next = new Map(current);
467 if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
468 next.delete(credential);
469 return [
470 {
471 _tag: "error",
472 reason: "expired",
473 error: new ExpiredBootstrapCredentialError({}),
474 },
475 next,
476 ];
477 }
478​
479 if (grant.proofKeyThumbprint && grant.proofKeyThumbprint !== input?.proofKeyThumbprint) {
480 return [
481 {
482 _tag: "error",
483 reason: "not-found",
484 error: new BootstrapCredentialProofKeyMismatchError({}),
485 },
486 next,
487 ];
488 }
489​
490 if (
491 input?.requestedScopes !== undefined &&
492 !input.requestedScopes.some((scope) => grant.scopes.includes(scope))
493 ) {
494 return [
495 {
496 _tag: "error",
497 reason: "scope-not-granted",
498 error: new BootstrapCredentialScopeNotGrantedError({}),
499 },
500 current,
501 ];
502 }
503​
504 const remainingUses = grant.remainingUses;
505 if (typeof remainingUses === "number") {
506 if (remainingUses <= 1) {
507 next.delete(credential);
508 } else {
509 next.set(credential, {
510 ...grant,
511 remainingUses: remainingUses - 1,
512 });
513 }
514 }
515​
516 return [
517 {
518 _tag: "success",
519 grant: {
520 method: grant.method,
521 scopes: grant.scopes,
522 subject: grant.subject,
523 ...(grant.label ? { label: grant.label } : {}),
524 ...(grant.proofKeyThumbprint
525 ? { proofKeyThumbprint: grant.proofKeyThumbprint }
526 : {}),
527 expiresAt: grant.expiresAt,
528 } satisfies BootstrapGrant,
529 },
530 next,
531 ];
532 },
533 );
534​
535 if (seededResult._tag === "success") {
536 return seededResult.grant;
537 }
538 if (seededResult.reason !== "not-found") {
539 return yield* seededResult.error;
540 }
541​
542 // The scope check is part of the UPDATE's WHERE clause so a rejected
543 // request cannot consume a one-time link. The re-check below only
544 // explains why nothing matched.
545 const consumed = yield* pairingLinks
546 .consumeAvailable({
547 credential,
548 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
549 ...(input?.requestedScopes !== undefined
550 ? { requestedScopes: input.requestedScopes }
551 : {}),
552 consumedAt: now,
553 now,
554 })
555 .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));
556​
557 if (Option.isSome(consumed)) {
558 yield* emitRemoved(consumed.value.id);
559 return {
560 method: consumed.value.method,
561 scopes: consumed.value.scopes,
562 subject: consumed.value.subject,
563 ...(consumed.value.label ? { label: consumed.value.label } : {}),
564 ...(consumed.value.proofKeyThumbprint
565 ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }
566 : {}),
567 expiresAt: consumed.value.expiresAt,
568 } satisfies BootstrapGrant;
569 }
570​
571 const matching = yield* pairingLinks
572 .getByCredential({ credential })
573 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
574 if (Option.isNone(matching)) {
575 return yield* new UnknownBootstrapCredentialError({});
576 }
577​
578 if (matching.value.revokedAt !== null) {
579 return yield* new UnavailableBootstrapCredentialError({});
580 }
581​
582 if (matching.value.consumedAt !== null) {
583 return yield* new UnknownBootstrapCredentialError({});
584 }
585​
586 if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
587 return yield* new ExpiredBootstrapCredentialError({});
588 }
589​
590 if (
591 matching.value.proofKeyThumbprint !== null &&
592 matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint
593 ) {
594 return yield* new BootstrapCredentialProofKeyMismatchError({});
595 }
596​
597 if (
598 input?.requestedScopes !== undefined &&
599 !input.requestedScopes.some((scope) => matching.value.scopes.includes(scope))
600 ) {
601 return yield* new BootstrapCredentialScopeNotGrantedError({});
602 }
603​
604 return yield* new UnavailableBootstrapCredentialError({});
605 },
606 );
607​
608 return PairingGrantStore.of({
609 issueOneTimeToken,
610 listActive,
611 get streamChanges() {
612 return Stream.fromPubSub(changesPubSub);
613 },
614 revoke,
615 consume,
616 });
617});
618​
619export const layer = Layer.effect(PairingGrantStore, make).pipe(
620 Layer.provideMerge(AuthPairingLinks.layer),
621);