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

PairingGrantStore.ts

634 lines20.4 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 SecureRandom from "effect/crypto/SecureRandom";
13import * as DateTime from "effect/DateTime";
14import * as Duration from "effect/Duration";
15import * as Mac from "effect/crypto/Mac";
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 /** All scopes must be granted; requestedScopes only requires an overlap for OAuth. */
231 readonly requiredScopes?: ReadonlyArray<AuthEnvironmentScope>;
232 },
233 ) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
234 }
235>()("t3/auth/PairingGrantStore") {}
236​
237interface StoredBootstrapGrant extends BootstrapGrant {
238 readonly remainingUses: number | "unbounded";
240​
241type ConsumeResult =
242 | {
243 readonly _tag: "error";
244 readonly reason: "not-found" | "expired" | "scope-not-granted";
245 readonly error: BootstrapCredentialError;
246 }
247 | {
248 readonly _tag: "success";
249 readonly grant: BootstrapGrant;
250 };
251​
252const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
253const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
254const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
255const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
256const PAIRING_TOKEN_LENGTH = 12;
257const PAIRING_TOKEN_REJECTION_LIMIT =
258 Math.floor(256 / PAIRING_TOKEN_ALPHABET.length) * PAIRING_TOKEN_ALPHABET.length;
259​
260const PAIRING_TOKEN_PATTERN = new RegExp(
261 `^[${PAIRING_TOKEN_ALPHABET}]{${PAIRING_TOKEN_LENGTH}}$`,
262 "i",
263);
264​
265const make = Effect.gen(function* () {
266 const random = yield* SecureRandom.SecureRandom;
267 const config = yield* ServerConfig.ServerConfig;
268 const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository;
269 const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
270 const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
271 const generatePairingToken = Effect.gen(function* () {
272 let credential = "";
273 while (credential.length < PAIRING_TOKEN_LENGTH) {
274 const bytes = yield* random
275 .randomBytes(PAIRING_TOKEN_LENGTH)
276 .pipe(
277 Effect.mapError(
278 (cause) =>
279 new PairingCredentialRandomGenerationError({ operation: "generate-token", cause }),
280 ),
281 );
282 for (const byte of bytes) {
283 if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) {
284 continue;
285 }
286 credential += PAIRING_TOKEN_ALPHABET[byte % PAIRING_TOKEN_ALPHABET.length]!;
287 if (credential.length === PAIRING_TOKEN_LENGTH) {
288 return credential;
289 }
290 }
291 }
292 return credential;
293 });
294​
295 const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>
296 Ref.update(seededGrantsRef, (current) => {
297 const next = new Map(current);
298 next.set(credential, grant);
299 return next;
300 });
301​
302 const emitUpsert = (pairingLink: AuthPairingLink) =>
303 PubSub.publish(changesPubSub, {
304 type: "pairingLinkUpserted",
305 pairingLink,
306 }).pipe(Effect.asVoid);
307​
308 const emitRemoved = (id: string) =>
309 PubSub.publish(changesPubSub, {
310 type: "pairingLinkRemoved",
311 id,
312 }).pipe(Effect.asVoid);
313​
314 // Accept tokens derived from the rotating desktop secret; older desktops send only a token.
315 const desktopBootstrapSecret = config.desktopBootstrapSecret;
316 const mac = yield* Mac.Mac;
317 const consumeRotatingDesktopToken = (credential: string, nowMs: number) =>
318 desktopBootstrapSecret === undefined
319 ? Effect.succeed(false)
320 : isValidDesktopBootstrapToken(desktopBootstrapSecret, credential, nowMs).pipe(
321 Effect.provideService(Mac.Mac, mac),
322 );
323​
324 if (config.desktopBootstrapToken && desktopBootstrapSecret === undefined) {
325 const now = yield* DateTime.now;
326 yield* seedGrant(config.desktopBootstrapToken, {
327 method: "desktop-bootstrap",
328 scopes: AuthStandardClientScopes,
329 subject: "desktop-bootstrap",
330 expiresAt: DateTime.add(now, {
331 milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS),
332 }),
333 // Reloads and expired bearer sessions must be able to re-exchange the desktop seed.
334 remainingUses: "unbounded",
335 });
336 }
337​
338 const listActive: PairingGrantStore["Service"]["listActive"] = Effect.fn(
339 "PairingGrantStore.listActive",
340 )(
341 function* () {
342 const now = yield* DateTime.now;
343 const rows = yield* pairingLinks.listActive({ now });
344​
345 return rows.map((row) =>
346 row.label
347 ? ({
348 id: row.id,
349 scopes: row.scopes,
350 subject: row.subject,
351 label: row.label,
352 createdAt: row.createdAt,
353 expiresAt: row.expiresAt,
354 } satisfies AuthPairingLink)
355 : ({
356 id: row.id,
357 scopes: row.scopes,
358 subject: row.subject,
359 createdAt: row.createdAt,
360 expiresAt: row.expiresAt,
361 } satisfies AuthPairingLink),
362 );
363 },
364 Effect.mapError((cause) => new ActivePairingLinksLoadError({ cause })),
365 );
366​
367 const revoke: PairingGrantStore["Service"]["revoke"] = Effect.fn("PairingGrantStore.revoke")(
368 function* (id) {
369 const revokedAt = yield* DateTime.now;
370 const revoked = yield* pairingLinks
371 .revoke({
372 id,
373 revokedAt,
374 })
375 .pipe(Effect.mapError((cause) => new PairingLinkRevokeError({ pairingLinkId: id, cause })));
376 if (revoked) {
377 yield* emitRemoved(id);
378 }
379 return revoked;
380 },
381 );
382​
383 const issueOneTimeToken: PairingGrantStore["Service"]["issueOneTimeToken"] = Effect.fn(
384 "PairingGrantStore.issueOneTimeToken",
385 )(function* (input) {
386 const id = yield* random
387 .uuidV4()
388 .pipe(
389 Effect.mapError(
390 (cause) =>
391 new PairingCredentialRandomGenerationError({ operation: "generate-id", cause }),
392 ),
393 );
394 const credential = yield* generatePairingToken;
395 const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
396 const ttl =
397 input?.ttl ??
398 (isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
399 const now = yield* DateTime.now;
400 const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
401 const issued: IssuedBootstrapCredential = {
402 id,
403 credential,
404 ...(input?.label ? { label: input.label } : {}),
405 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
406 expiresAt,
407 };
408 const subject = input?.subject ?? "one-time-token";
409 yield* pairingLinks
410 .create({
411 id,
412 credential,
413 method: "one-time-token",
414 scopes: input?.scopes ?? AuthStandardClientScopes,
415 subject,
416 label: input?.label ?? null,
417 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
418 createdAt: now,
419 expiresAt: expiresAt,
420 })
421 .pipe(
422 Effect.mapError(
423 (cause) =>
424 new PairingCredentialIssueError({
425 pairingLinkId: id,
426 subject,
427 ...(input?.label ? { label: input.label } : {}),
428 cause,
429 }),
430 ),
431 );
432 yield* emitUpsert({
433 id,
434 scopes: input?.scopes ?? AuthStandardClientScopes,
435 subject: input?.subject ?? "one-time-token",
436 ...(input?.label ? { label: input.label } : {}),
437 createdAt: now,
438 expiresAt,
439 });
440 return issued;
441 });
442​
443 const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")(
444 function* (credential, input) {
445 const now = yield* DateTime.now;
446 if (yield* consumeRotatingDesktopToken(credential, now.epochMilliseconds)) {
447 return {
448 method: "desktop-bootstrap",
449 scopes: AuthStandardClientScopes,
450 subject: "desktop-bootstrap",
451 expiresAt: DateTime.add(now, {
452 milliseconds: DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,
453 }),
454 } satisfies BootstrapGrant;
455 }
456 const seededResult: ConsumeResult = yield* Ref.modify(
457 seededGrantsRef,
458 (current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
459 const grant = current.get(credential);
460 if (!grant) {
461 return [
462 {
463 _tag: "error",
464 reason: "not-found",
465 error: new UnknownBootstrapCredentialError({}),
466 },
467 current,
468 ];
469 }
470​
471 const next = new Map(current);
472 if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
473 next.delete(credential);
474 return [
475 {
476 _tag: "error",
477 reason: "expired",
478 error: new ExpiredBootstrapCredentialError({}),
479 },
480 next,
481 ];
482 }
483​
484 if (grant.proofKeyThumbprint && grant.proofKeyThumbprint !== input?.proofKeyThumbprint) {
485 return [
486 {
487 _tag: "error",
488 reason: "not-found",
489 error: new BootstrapCredentialProofKeyMismatchError({}),
490 },
491 next,
492 ];
493 }
494​
495 if (
496 (input?.requestedScopes !== undefined &&
497 !input.requestedScopes.some((scope) => grant.scopes.includes(scope))) ||
498 (input?.requiredScopes !== undefined &&
499 !input.requiredScopes.every((scope) => grant.scopes.includes(scope)))
500 ) {
501 return [
502 {
503 _tag: "error",
504 reason: "scope-not-granted",
505 error: new BootstrapCredentialScopeNotGrantedError({}),
506 },
507 current,
508 ];
509 }
510​
511 const remainingUses = grant.remainingUses;
512 if (typeof remainingUses === "number") {
513 if (remainingUses <= 1) {
514 next.delete(credential);
515 } else {
516 next.set(credential, {
517 ...grant,
518 remainingUses: remainingUses - 1,
519 });
520 }
521 }
522​
523 return [
524 {
525 _tag: "success",
526 grant: {
527 method: grant.method,
528 scopes: grant.scopes,
529 subject: grant.subject,
530 ...(grant.label ? { label: grant.label } : {}),
531 ...(grant.proofKeyThumbprint
532 ? { proofKeyThumbprint: grant.proofKeyThumbprint }
533 : {}),
534 expiresAt: grant.expiresAt,
535 } satisfies BootstrapGrant,
536 },
537 next,
538 ];
539 },
540 );
541​
542 if (seededResult._tag === "success") {
543 return seededResult.grant;
544 }
545 if (seededResult.reason !== "not-found") {
546 return yield* seededResult.error;
547 }
548​
549 // Only credentials in the issued pairing-code format are case-insensitive.
550 const pairingCredential = PAIRING_TOKEN_PATTERN.test(credential)
551 ? credential.toUpperCase()
552 : credential;
553​
554 // Check scopes in the UPDATE so rejected requests cannot spend one-time links.
555 const consumed = yield* pairingLinks
556 .consumeAvailable({
557 credential: pairingCredential,
558 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
559 ...(input?.requestedScopes !== undefined
560 ? { requestedScopes: input.requestedScopes }
561 : {}),
562 ...(input?.requiredScopes !== undefined ? { requiredScopes: input.requiredScopes } : {}),
563 consumedAt: now,
564 now,
565 })
566 .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));
567​
568 if (Option.isSome(consumed)) {
569 yield* emitRemoved(consumed.value.id);
570 return {
571 method: consumed.value.method,
572 scopes: consumed.value.scopes,
573 subject: consumed.value.subject,
574 ...(consumed.value.label ? { label: consumed.value.label } : {}),
575 ...(consumed.value.proofKeyThumbprint
576 ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }
577 : {}),
578 expiresAt: consumed.value.expiresAt,
579 } satisfies BootstrapGrant;
580 }
581​
582 const matching = yield* pairingLinks
583 .getByCredential({ credential: pairingCredential })
584 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
585 if (Option.isNone(matching)) {
586 return yield* new UnknownBootstrapCredentialError({});
587 }
588​
589 if (matching.value.revokedAt !== null) {
590 return yield* new UnavailableBootstrapCredentialError({});
591 }
592​
593 if (matching.value.consumedAt !== null) {
594 return yield* new UnknownBootstrapCredentialError({});
595 }
596​
597 if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
598 return yield* new ExpiredBootstrapCredentialError({});
599 }
600​
601 if (
602 matching.value.proofKeyThumbprint !== null &&
603 matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint
604 ) {
605 return yield* new BootstrapCredentialProofKeyMismatchError({});
606 }
607​
608 if (
609 (input?.requestedScopes !== undefined &&
610 !input.requestedScopes.some((scope) => matching.value.scopes.includes(scope))) ||
611 (input?.requiredScopes !== undefined &&
612 !input.requiredScopes.every((scope) => matching.value.scopes.includes(scope)))
613 ) {
614 return yield* new BootstrapCredentialScopeNotGrantedError({});
615 }
616​
617 return yield* new UnavailableBootstrapCredentialError({});
618 },
619 );
620​
621 return PairingGrantStore.of({
622 issueOneTimeToken,
623 listActive,
624 get streamChanges() {
625 return Stream.fromPubSub(changesPubSub);
626 },
627 revoke,
628 consume,
629 });
630});
631​
632export const layer = Layer.effect(PairingGrantStore, make).pipe(
633 Layer.provideMerge(AuthPairingLinks.layer),
634);