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

PairingGrantStore.ts

620 lines19.7 KB

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