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

PairingGrantStore.ts

629 lines20.2 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 /** All scopes must be granted; requestedScopes only requires an overlap for OAuth. */
230 readonly requiredScopes?: ReadonlyArray<AuthEnvironmentScope>;
231 },
232 ) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
233 }
234>()("t3/auth/PairingGrantStore") {}
235​
236interface StoredBootstrapGrant extends BootstrapGrant {
237 readonly remainingUses: number | "unbounded";
239​
240type ConsumeResult =
241 | {
242 readonly _tag: "error";
243 readonly reason: "not-found" | "expired" | "scope-not-granted";
244 readonly error: BootstrapCredentialError;
245 }
246 | {
247 readonly _tag: "success";
248 readonly grant: BootstrapGrant;
249 };
250​
251const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
252const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
253const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
254const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
255const PAIRING_TOKEN_LENGTH = 12;
256const PAIRING_TOKEN_REJECTION_LIMIT =
257 Math.floor(256 / PAIRING_TOKEN_ALPHABET.length) * PAIRING_TOKEN_ALPHABET.length;
258​
259const PAIRING_TOKEN_PATTERN = new RegExp(
260 `^[${PAIRING_TOKEN_ALPHABET}]{${PAIRING_TOKEN_LENGTH}}$`,
261 "i",
262);
263​
264const make = Effect.gen(function* () {
265 const crypto = yield* Crypto.Crypto;
266 const config = yield* ServerConfig.ServerConfig;
267 const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository;
268 const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
269 const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
270 const generatePairingToken = Effect.gen(function* () {
271 let credential = "";
272 while (credential.length < PAIRING_TOKEN_LENGTH) {
273 const bytes = yield* crypto
274 .randomBytes(PAIRING_TOKEN_LENGTH)
275 .pipe(
276 Effect.mapError(
277 (cause) =>
278 new PairingCredentialRandomGenerationError({ operation: "generate-token", cause }),
279 ),
280 );
281 for (const byte of bytes) {
282 if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) {
283 continue;
284 }
285 credential += PAIRING_TOKEN_ALPHABET[byte % PAIRING_TOKEN_ALPHABET.length]!;
286 if (credential.length === PAIRING_TOKEN_LENGTH) {
287 return credential;
288 }
289 }
290 }
291 return credential;
292 });
293​
294 const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>
295 Ref.update(seededGrantsRef, (current) => {
296 const next = new Map(current);
297 next.set(credential, grant);
298 return next;
299 });
300​
301 const emitUpsert = (pairingLink: AuthPairingLink) =>
302 PubSub.publish(changesPubSub, {
303 type: "pairingLinkUpserted",
304 pairingLink,
305 }).pipe(Effect.asVoid);
306​
307 const emitRemoved = (id: string) =>
308 PubSub.publish(changesPubSub, {
309 type: "pairingLinkRemoved",
310 id,
311 }).pipe(Effect.asVoid);
312​
313 // Accept tokens derived from the rotating desktop secret; older desktops send only a token.
314 const desktopBootstrapSecret = config.desktopBootstrapSecret;
315 const consumeRotatingDesktopToken = (credential: string, nowMs: number) =>
316 desktopBootstrapSecret !== undefined &&
317 isValidDesktopBootstrapToken(desktopBootstrapSecret, credential, nowMs);
318​
319 if (config.desktopBootstrapToken && desktopBootstrapSecret === undefined) {
320 const now = yield* DateTime.now;
321 yield* seedGrant(config.desktopBootstrapToken, {
322 method: "desktop-bootstrap",
323 scopes: AuthStandardClientScopes,
324 subject: "desktop-bootstrap",
325 expiresAt: DateTime.add(now, {
326 milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS),
327 }),
328 // Reloads and expired bearer sessions must be able to re-exchange the desktop seed.
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: AuthStandardClientScopes,
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 (input?.requiredScopes !== undefined &&
494 !input.requiredScopes.every((scope) => grant.scopes.includes(scope)))
495 ) {
496 return [
497 {
498 _tag: "error",
499 reason: "scope-not-granted",
500 error: new BootstrapCredentialScopeNotGrantedError({}),
501 },
502 current,
503 ];
504 }
505​
506 const remainingUses = grant.remainingUses;
507 if (typeof remainingUses === "number") {
508 if (remainingUses <= 1) {
509 next.delete(credential);
510 } else {
511 next.set(credential, {
512 ...grant,
513 remainingUses: remainingUses - 1,
514 });
515 }
516 }
517​
518 return [
519 {
520 _tag: "success",
521 grant: {
522 method: grant.method,
523 scopes: grant.scopes,
524 subject: grant.subject,
525 ...(grant.label ? { label: grant.label } : {}),
526 ...(grant.proofKeyThumbprint
527 ? { proofKeyThumbprint: grant.proofKeyThumbprint }
528 : {}),
529 expiresAt: grant.expiresAt,
530 } satisfies BootstrapGrant,
531 },
532 next,
533 ];
534 },
535 );
536​
537 if (seededResult._tag === "success") {
538 return seededResult.grant;
539 }
540 if (seededResult.reason !== "not-found") {
541 return yield* seededResult.error;
542 }
543​
544 // Only credentials in the issued pairing-code format are case-insensitive.
545 const pairingCredential = PAIRING_TOKEN_PATTERN.test(credential)
546 ? credential.toUpperCase()
547 : credential;
548​
549 // Check scopes in the UPDATE so rejected requests cannot spend one-time links.
550 const consumed = yield* pairingLinks
551 .consumeAvailable({
552 credential: pairingCredential,
553 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
554 ...(input?.requestedScopes !== undefined
555 ? { requestedScopes: input.requestedScopes }
556 : {}),
557 ...(input?.requiredScopes !== undefined ? { requiredScopes: input.requiredScopes } : {}),
558 consumedAt: now,
559 now,
560 })
561 .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));
562​
563 if (Option.isSome(consumed)) {
564 yield* emitRemoved(consumed.value.id);
565 return {
566 method: consumed.value.method,
567 scopes: consumed.value.scopes,
568 subject: consumed.value.subject,
569 ...(consumed.value.label ? { label: consumed.value.label } : {}),
570 ...(consumed.value.proofKeyThumbprint
571 ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }
572 : {}),
573 expiresAt: consumed.value.expiresAt,
574 } satisfies BootstrapGrant;
575 }
576​
577 const matching = yield* pairingLinks
578 .getByCredential({ credential: pairingCredential })
579 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
580 if (Option.isNone(matching)) {
581 return yield* new UnknownBootstrapCredentialError({});
582 }
583​
584 if (matching.value.revokedAt !== null) {
585 return yield* new UnavailableBootstrapCredentialError({});
586 }
587​
588 if (matching.value.consumedAt !== null) {
589 return yield* new UnknownBootstrapCredentialError({});
590 }
591​
592 if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
593 return yield* new ExpiredBootstrapCredentialError({});
594 }
595​
596 if (
597 matching.value.proofKeyThumbprint !== null &&
598 matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint
599 ) {
600 return yield* new BootstrapCredentialProofKeyMismatchError({});
601 }
602​
603 if (
604 (input?.requestedScopes !== undefined &&
605 !input.requestedScopes.some((scope) => matching.value.scopes.includes(scope))) ||
606 (input?.requiredScopes !== undefined &&
607 !input.requiredScopes.every((scope) => matching.value.scopes.includes(scope)))
608 ) {
609 return yield* new BootstrapCredentialScopeNotGrantedError({});
610 }
611​
612 return yield* new UnavailableBootstrapCredentialError({});
613 },
614 );
615​
616 return PairingGrantStore.of({
617 issueOneTimeToken,
618 listActive,
619 get streamChanges() {
620 return Stream.fromPubSub(changesPubSub);
621 },
622 revoke,
623 consume,
624 });
625});
626​
627export const layer = Layer.effect(PairingGrantStore, make).pipe(
628 Layer.provideMerge(AuthPairingLinks.layer),
629);