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

PairingGrantStore.ts

612 lines19.3 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​
257const 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 // Accept tokens derived from the rotating desktop secret; older desktops send only a token.
307 const desktopBootstrapSecret = config.desktopBootstrapSecret;
308 const consumeRotatingDesktopToken = (credential: string, nowMs: number) =>
309 desktopBootstrapSecret !== undefined &&
310 isValidDesktopBootstrapToken(desktopBootstrapSecret, credential, nowMs);
311​
312 if (config.desktopBootstrapToken && desktopBootstrapSecret === undefined) {
313 const now = yield* DateTime.now;
314 yield* seedGrant(config.desktopBootstrapToken, {
315 method: "desktop-bootstrap",
316 scopes: AuthStandardClientScopes,
317 subject: "desktop-bootstrap",
318 expiresAt: DateTime.add(now, {
319 milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS),
320 }),
321 // Reloads and expired bearer sessions must be able to re-exchange the desktop seed.
322 remainingUses: "unbounded",
323 });
324 }
325​
326 const listActive: PairingGrantStore["Service"]["listActive"] = Effect.fn(
327 "PairingGrantStore.listActive",
328 )(
329 function* () {
330 const now = yield* DateTime.now;
331 const rows = yield* pairingLinks.listActive({ now });
332​
333 return rows.map((row) =>
334 row.label
335 ? ({
336 id: row.id,
337 scopes: row.scopes,
338 subject: row.subject,
339 label: row.label,
340 createdAt: row.createdAt,
341 expiresAt: row.expiresAt,
342 } satisfies AuthPairingLink)
343 : ({
344 id: row.id,
345 scopes: row.scopes,
346 subject: row.subject,
347 createdAt: row.createdAt,
348 expiresAt: row.expiresAt,
349 } satisfies AuthPairingLink),
350 );
351 },
352 Effect.mapError((cause) => new ActivePairingLinksLoadError({ cause })),
353 );
354​
355 const revoke: PairingGrantStore["Service"]["revoke"] = Effect.fn("PairingGrantStore.revoke")(
356 function* (id) {
357 const revokedAt = yield* DateTime.now;
358 const revoked = yield* pairingLinks
359 .revoke({
360 id,
361 revokedAt,
362 })
363 .pipe(Effect.mapError((cause) => new PairingLinkRevokeError({ pairingLinkId: id, cause })));
364 if (revoked) {
365 yield* emitRemoved(id);
366 }
367 return revoked;
368 },
369 );
370​
371 const issueOneTimeToken: PairingGrantStore["Service"]["issueOneTimeToken"] = Effect.fn(
372 "PairingGrantStore.issueOneTimeToken",
373 )(function* (input) {
374 const id = yield* crypto
375 .randomUUIDv4()
376 .pipe(
377 Effect.mapError(
378 (cause) =>
379 new PairingCredentialRandomGenerationError({ operation: "generate-id", cause }),
380 ),
381 );
382 const credential = yield* generatePairingToken;
383 const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
384 const ttl =
385 input?.ttl ??
386 (isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
387 const now = yield* DateTime.now;
388 const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
389 const issued: IssuedBootstrapCredential = {
390 id,
391 credential,
392 ...(input?.label ? { label: input.label } : {}),
393 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
394 expiresAt,
395 };
396 const subject = input?.subject ?? "one-time-token";
397 yield* pairingLinks
398 .create({
399 id,
400 credential,
401 method: "one-time-token",
402 scopes: input?.scopes ?? AuthStandardClientScopes,
403 subject,
404 label: input?.label ?? null,
405 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
406 createdAt: now,
407 expiresAt: expiresAt,
408 })
409 .pipe(
410 Effect.mapError(
411 (cause) =>
412 new PairingCredentialIssueError({
413 pairingLinkId: id,
414 subject,
415 ...(input?.label ? { label: input.label } : {}),
416 cause,
417 }),
418 ),
419 );
420 yield* emitUpsert({
421 id,
422 scopes: input?.scopes ?? AuthStandardClientScopes,
423 subject: input?.subject ?? "one-time-token",
424 ...(input?.label ? { label: input.label } : {}),
425 createdAt: now,
426 expiresAt,
427 });
428 return issued;
429 });
430​
431 const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")(
432 function* (credential, input) {
433 const now = yield* DateTime.now;
434 if (consumeRotatingDesktopToken(credential, now.epochMilliseconds)) {
435 return {
436 method: "desktop-bootstrap",
437 scopes: AuthStandardClientScopes,
438 subject: "desktop-bootstrap",
439 expiresAt: DateTime.add(now, {
440 milliseconds: DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,
441 }),
442 } satisfies BootstrapGrant;
443 }
444 const seededResult: ConsumeResult = yield* Ref.modify(
445 seededGrantsRef,
446 (current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
447 const grant = current.get(credential);
448 if (!grant) {
449 return [
450 {
451 _tag: "error",
452 reason: "not-found",
453 error: new UnknownBootstrapCredentialError({}),
454 },
455 current,
456 ];
457 }
458​
459 const next = new Map(current);
460 if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
461 next.delete(credential);
462 return [
463 {
464 _tag: "error",
465 reason: "expired",
466 error: new ExpiredBootstrapCredentialError({}),
467 },
468 next,
469 ];
470 }
471​
472 if (grant.proofKeyThumbprint && grant.proofKeyThumbprint !== input?.proofKeyThumbprint) {
473 return [
474 {
475 _tag: "error",
476 reason: "not-found",
477 error: new BootstrapCredentialProofKeyMismatchError({}),
478 },
479 next,
480 ];
481 }
482​
483 if (
484 input?.requestedScopes !== undefined &&
485 !input.requestedScopes.some((scope) => grant.scopes.includes(scope))
486 ) {
487 return [
488 {
489 _tag: "error",
490 reason: "scope-not-granted",
491 error: new BootstrapCredentialScopeNotGrantedError({}),
492 },
493 current,
494 ];
495 }
496​
497 const remainingUses = grant.remainingUses;
498 if (typeof remainingUses === "number") {
499 if (remainingUses <= 1) {
500 next.delete(credential);
501 } else {
502 next.set(credential, {
503 ...grant,
504 remainingUses: remainingUses - 1,
505 });
506 }
507 }
508​
509 return [
510 {
511 _tag: "success",
512 grant: {
513 method: grant.method,
514 scopes: grant.scopes,
515 subject: grant.subject,
516 ...(grant.label ? { label: grant.label } : {}),
517 ...(grant.proofKeyThumbprint
518 ? { proofKeyThumbprint: grant.proofKeyThumbprint }
519 : {}),
520 expiresAt: grant.expiresAt,
521 } satisfies BootstrapGrant,
522 },
523 next,
524 ];
525 },
526 );
527​
528 if (seededResult._tag === "success") {
529 return seededResult.grant;
530 }
531 if (seededResult.reason !== "not-found") {
532 return yield* seededResult.error;
533 }
534​
535 // Check scopes in the UPDATE so rejected requests cannot spend one-time links.
536 const consumed = yield* pairingLinks
537 .consumeAvailable({
538 credential,
539 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
540 ...(input?.requestedScopes !== undefined
541 ? { requestedScopes: input.requestedScopes }
542 : {}),
543 consumedAt: now,
544 now,
545 })
546 .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));
547​
548 if (Option.isSome(consumed)) {
549 yield* emitRemoved(consumed.value.id);
550 return {
551 method: consumed.value.method,
552 scopes: consumed.value.scopes,
553 subject: consumed.value.subject,
554 ...(consumed.value.label ? { label: consumed.value.label } : {}),
555 ...(consumed.value.proofKeyThumbprint
556 ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }
557 : {}),
558 expiresAt: consumed.value.expiresAt,
559 } satisfies BootstrapGrant;
560 }
561​
562 const matching = yield* pairingLinks
563 .getByCredential({ credential })
564 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
565 if (Option.isNone(matching)) {
566 return yield* new UnknownBootstrapCredentialError({});
567 }
568​
569 if (matching.value.revokedAt !== null) {
570 return yield* new UnavailableBootstrapCredentialError({});
571 }
572​
573 if (matching.value.consumedAt !== null) {
574 return yield* new UnknownBootstrapCredentialError({});
575 }
576​
577 if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
578 return yield* new ExpiredBootstrapCredentialError({});
579 }
580​
581 if (
582 matching.value.proofKeyThumbprint !== null &&
583 matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint
584 ) {
585 return yield* new BootstrapCredentialProofKeyMismatchError({});
586 }
587​
588 if (
589 input?.requestedScopes !== undefined &&
590 !input.requestedScopes.some((scope) => matching.value.scopes.includes(scope))
591 ) {
592 return yield* new BootstrapCredentialScopeNotGrantedError({});
593 }
594​
595 return yield* new UnavailableBootstrapCredentialError({});
596 },
597 );
598​
599 return PairingGrantStore.of({
600 issueOneTimeToken,
601 listActive,
602 get streamChanges() {
603 return Stream.fromPubSub(changesPubSub);
604 },
605 revoke,
606 consume,
607 });
608});
609​
610export const layer = Layer.effect(PairingGrantStore, make).pipe(
611 Layer.provideMerge(AuthPairingLinks.layer),
612);