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

PairingGrantStore.ts

580 lines18.8 KB

1import {
2 AuthAdministrativeScopes,
3 AuthStandardClientScopes,
4 type AuthEnvironmentScope,
5 type AuthPairingLink,
6 type ServerAuthBootstrapMethod,
7} from "@t3tools/contracts";
8import * as Context from "effect/Context";
9import * as Crypto from "effect/Crypto";
10import * as DateTime from "effect/DateTime";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as PubSub from "effect/PubSub";
16import * as Ref from "effect/Ref";
17import * as Schema from "effect/Schema";
18import * as Stream from "effect/Stream";
19​
20import * as ServerConfig from "../config.ts";
21import * as AuthPairingLinks from "../persistence/AuthPairingLinks.ts";
22​
23export interface BootstrapGrant {
24 readonly method: ServerAuthBootstrapMethod;
25 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
26 readonly subject: string;
27 readonly label?: string;
28 readonly proofKeyThumbprint?: string;
29 readonly expiresAt: DateTime.DateTime;
31​
32export class UnknownBootstrapCredentialError extends Schema.TaggedErrorClass<UnknownBootstrapCredentialError>()(
33 "UnknownBootstrapCredentialError",
34 {},
35) {
36 override get message(): string {
37 return "Unknown bootstrap credential.";
38 }
40​
41export class ExpiredBootstrapCredentialError extends Schema.TaggedErrorClass<ExpiredBootstrapCredentialError>()(
42 "ExpiredBootstrapCredentialError",
43 {},
44) {
45 override get message(): string {
46 return "Bootstrap credential expired.";
47 }
49​
50export class BootstrapCredentialProofKeyMismatchError extends Schema.TaggedErrorClass<BootstrapCredentialProofKeyMismatchError>()(
51 "BootstrapCredentialProofKeyMismatchError",
52 {},
53) {
54 override get message(): string {
55 return "Bootstrap credential proof key mismatch.";
56 }
58​
59export class UnavailableBootstrapCredentialError extends Schema.TaggedErrorClass<UnavailableBootstrapCredentialError>()(
60 "UnavailableBootstrapCredentialError",
61 {},
62) {
63 override get message(): string {
64 return "Bootstrap credential is no longer available.";
65 }
67​
68export const BootstrapCredentialInvalidError = Schema.Union([
69 UnknownBootstrapCredentialError,
70 ExpiredBootstrapCredentialError,
71 BootstrapCredentialProofKeyMismatchError,
72 UnavailableBootstrapCredentialError,
73]);
74export type BootstrapCredentialInvalidError = typeof BootstrapCredentialInvalidError.Type;
75export const isBootstrapCredentialInvalidError = Schema.is(BootstrapCredentialInvalidError);
76​
77export class ActivePairingLinksLoadError extends Schema.TaggedErrorClass<ActivePairingLinksLoadError>()(
78 "ActivePairingLinksLoadError",
79 {
80 cause: Schema.Defect(),
81 },
82) {
83 override get message(): string {
84 return "Failed to load active pairing links.";
85 }
87​
88export class PairingLinkRevokeError extends Schema.TaggedErrorClass<PairingLinkRevokeError>()(
89 "PairingLinkRevokeError",
90 {
91 pairingLinkId: Schema.String,
92 cause: Schema.Defect(),
93 },
94) {
95 override get message(): string {
96 return `Failed to revoke pairing link '${this.pairingLinkId}'.`;
97 }
99​
100export class PairingCredentialIssueError extends Schema.TaggedErrorClass<PairingCredentialIssueError>()(
101 "PairingCredentialIssueError",
102 {
103 pairingLinkId: Schema.String,
104 subject: Schema.String,
105 label: Schema.optional(Schema.String),
106 cause: Schema.Defect(),
107 },
108) {
109 override get message(): string {
110 return `Failed to issue pairing credential '${this.pairingLinkId}' for '${this.subject}'.`;
111 }
113​
114export class PairingCredentialRandomGenerationError extends Schema.TaggedErrorClass<PairingCredentialRandomGenerationError>()(
115 "PairingCredentialRandomGenerationError",
116 {
117 operation: Schema.Literals(["generate-id", "generate-token"]),
118 cause: Schema.Defect(),
119 },
120) {
121 override get message(): string {
122 return `Failed to generate pairing credential data during '${this.operation}'.`;
123 }
125​
126export class BootstrapCredentialConsumeError extends Schema.TaggedErrorClass<BootstrapCredentialConsumeError>()(
127 "BootstrapCredentialConsumeError",
128 {
129 cause: Schema.Defect(),
130 },
131) {
132 override get message(): string {
133 return "Failed to consume bootstrap credential.";
134 }
136​
137export class BootstrapCredentialConsumeAvailableError extends Schema.TaggedErrorClass<BootstrapCredentialConsumeAvailableError>()(
138 "BootstrapCredentialConsumeAvailableError",
139 {
140 cause: Schema.Defect(),
141 },
142) {
143 override get message(): string {
144 return "Failed to atomically consume an available bootstrap credential.";
145 }
147​
148export class BootstrapCredentialLookupError extends Schema.TaggedErrorClass<BootstrapCredentialLookupError>()(
149 "BootstrapCredentialLookupError",
150 {
151 cause: Schema.Defect(),
152 },
153) {
154 override get message(): string {
155 return "Failed to look up bootstrap credential state.";
156 }
158​
159export const BootstrapCredentialInternalError = Schema.Union([
160 ActivePairingLinksLoadError,
161 PairingLinkRevokeError,
162 PairingCredentialIssueError,
163 PairingCredentialRandomGenerationError,
164 BootstrapCredentialConsumeError,
165 BootstrapCredentialConsumeAvailableError,
166 BootstrapCredentialLookupError,
167]);
168export type BootstrapCredentialInternalError = typeof BootstrapCredentialInternalError.Type;
169export const isBootstrapCredentialInternalError = Schema.is(BootstrapCredentialInternalError);
170​
171export const BootstrapCredentialError = Schema.Union([
172 BootstrapCredentialInvalidError,
173 BootstrapCredentialInternalError,
174]);
175export type BootstrapCredentialError = typeof BootstrapCredentialError.Type;
176export const isBootstrapCredentialError = Schema.is(BootstrapCredentialError);
177​
178export interface IssuedBootstrapCredential {
179 readonly id: string;
180 readonly credential: string;
181 readonly label?: string;
182 readonly proofKeyThumbprint?: string;
183 readonly expiresAt: DateTime.Utc;
185​
186export type BootstrapCredentialChange =
187 | {
188 readonly type: "pairingLinkUpserted";
189 readonly pairingLink: AuthPairingLink;
190 }
191 | {
192 readonly type: "pairingLinkRemoved";
193 readonly id: string;
194 };
195​
196export class PairingGrantStore extends Context.Service<
197 PairingGrantStore,
198 {
199 readonly issueOneTimeToken: (input?: {
200 readonly ttl?: Duration.Duration;
201 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
202 readonly subject?: string;
203 readonly label?: string;
204 readonly proofKeyThumbprint?: string;
205 /**
206 * "startup" marks the credential the server mints for itself at boot,
207 * which gets the long dev TTL when a dev URL is configured.
208 */
209 readonly purpose?: "startup";
210 }) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
211 readonly listActive: () => Effect.Effect<
212 ReadonlyArray<AuthPairingLink>,
213 BootstrapCredentialInternalError
214 >;
215 readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
216 readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
217 readonly consume: (
218 credential: string,
219 input?: {
220 readonly proofKeyThumbprint?: string;
221 },
222 ) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
223 }
224>()("t3/auth/PairingGrantStore") {}
225​
226interface StoredBootstrapGrant extends BootstrapGrant {
227 readonly remainingUses: number | "unbounded";
229​
230type ConsumeResult =
231 | {
232 readonly _tag: "error";
233 readonly reason: "not-found" | "expired";
234 readonly error: BootstrapCredentialError;
235 }
236 | {
237 readonly _tag: "success";
238 readonly grant: BootstrapGrant;
239 };
240​
241const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
242// The desktop-bootstrap grant rides on a trusted IPC channel (fd3 or
243// stdin) at backend launch, so it doesn't have to be short-lived the
244// way a user-facing pairing link does. Letting it live for the
245// lifetime of the backend process (24h is more than long enough for
246// practical desktop use, and well under "forever" in case the seed
247// gets logged anywhere by accident) means a page reload past the 5-min
248// window can still recover by re-bootstrapping rather than locking
249// the user out of the backend.
250const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
251// A dev server's startup token is read off a log by whoever (or whatever) is
252// driving the session, often minutes later — after a `node --watch` restart, a
253// detour into another task, or a hand-off to the person actually doing the
254// testing. Five minutes turns that into a restart-the-server loop for no
255// security benefit: the token only unlocks a local dev backend, and its holder
256// could read the log anyway. Same reasoning (and duration) as the desktop
257// bootstrap grant above. Only applies when a dev URL is configured; user-issued
258// pairing links and real servers keep the 5-minute default.
259const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
260const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
261const PAIRING_TOKEN_LENGTH = 12;
262const PAIRING_TOKEN_REJECTION_LIMIT =
263 Math.floor(256 / PAIRING_TOKEN_ALPHABET.length) * PAIRING_TOKEN_ALPHABET.length;
264​
265export const make = Effect.gen(function* () {
266 const crypto = yield* Crypto.Crypto;
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* crypto
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 if (config.desktopBootstrapToken) {
315 const now = yield* DateTime.now;
316 yield* seedGrant(config.desktopBootstrapToken, {
317 method: "desktop-bootstrap",
318 scopes: AuthAdministrativeScopes,
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.randomUUIDv4.pipe(
381 Effect.mapError(
382 (cause) => new PairingCredentialRandomGenerationError({ operation: "generate-id", cause }),
383 ),
384 );
385 const credential = yield* generatePairingToken;
386 const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
387 const ttl =
388 input?.ttl ??
389 (isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
390 const now = yield* DateTime.now;
391 const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
392 const issued: IssuedBootstrapCredential = {
393 id,
394 credential,
395 ...(input?.label ? { label: input.label } : {}),
396 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
397 expiresAt,
398 };
399 const subject = input?.subject ?? "one-time-token";
400 yield* pairingLinks
401 .create({
402 id,
403 credential,
404 method: "one-time-token",
405 scopes: input?.scopes ?? AuthStandardClientScopes,
406 subject,
407 label: input?.label ?? null,
408 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
409 createdAt: now,
410 expiresAt: expiresAt,
411 })
412 .pipe(
413 Effect.mapError(
414 (cause) =>
415 new PairingCredentialIssueError({
416 pairingLinkId: id,
417 subject,
418 ...(input?.label ? { label: input.label } : {}),
419 cause,
420 }),
421 ),
422 );
423 yield* emitUpsert({
424 id,
425 scopes: input?.scopes ?? AuthStandardClientScopes,
426 subject: input?.subject ?? "one-time-token",
427 ...(input?.label ? { label: input.label } : {}),
428 createdAt: now,
429 expiresAt,
430 });
431 return issued;
432 });
433​
434 const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")(
435 function* (credential, input) {
436 const now = yield* DateTime.now;
437 const seededResult: ConsumeResult = yield* Ref.modify(
438 seededGrantsRef,
439 (current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
440 const grant = current.get(credential);
441 if (!grant) {
442 return [
443 {
444 _tag: "error",
445 reason: "not-found",
446 error: new UnknownBootstrapCredentialError({}),
447 },
448 current,
449 ];
450 }
451​
452 const next = new Map(current);
453 if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
454 next.delete(credential);
455 return [
456 {
457 _tag: "error",
458 reason: "expired",
459 error: new ExpiredBootstrapCredentialError({}),
460 },
461 next,
462 ];
463 }
464​
465 if (grant.proofKeyThumbprint && grant.proofKeyThumbprint !== input?.proofKeyThumbprint) {
466 return [
467 {
468 _tag: "error",
469 reason: "not-found",
470 error: new BootstrapCredentialProofKeyMismatchError({}),
471 },
472 next,
473 ];
474 }
475​
476 const remainingUses = grant.remainingUses;
477 if (typeof remainingUses === "number") {
478 if (remainingUses <= 1) {
479 next.delete(credential);
480 } else {
481 next.set(credential, {
482 ...grant,
483 remainingUses: remainingUses - 1,
484 });
485 }
486 }
487​
488 return [
489 {
490 _tag: "success",
491 grant: {
492 method: grant.method,
493 scopes: grant.scopes,
494 subject: grant.subject,
495 ...(grant.label ? { label: grant.label } : {}),
496 ...(grant.proofKeyThumbprint
497 ? { proofKeyThumbprint: grant.proofKeyThumbprint }
498 : {}),
499 expiresAt: grant.expiresAt,
500 } satisfies BootstrapGrant,
501 },
502 next,
503 ];
504 },
505 );
506​
507 if (seededResult._tag === "success") {
508 return seededResult.grant;
509 }
510 if (seededResult.reason !== "not-found") {
511 return yield* seededResult.error;
512 }
513​
514 const consumed = yield* pairingLinks
515 .consumeAvailable({
516 credential,
517 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
518 consumedAt: now,
519 now,
520 })
521 .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));
522​
523 if (Option.isSome(consumed)) {
524 yield* emitRemoved(consumed.value.id);
525 return {
526 method: consumed.value.method,
527 scopes: consumed.value.scopes,
528 subject: consumed.value.subject,
529 ...(consumed.value.label ? { label: consumed.value.label } : {}),
530 ...(consumed.value.proofKeyThumbprint
531 ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }
532 : {}),
533 expiresAt: consumed.value.expiresAt,
534 } satisfies BootstrapGrant;
535 }
536​
537 const matching = yield* pairingLinks
538 .getByCredential({ credential })
539 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
540 if (Option.isNone(matching)) {
541 return yield* new UnknownBootstrapCredentialError({});
542 }
543​
544 if (matching.value.revokedAt !== null) {
545 return yield* new UnavailableBootstrapCredentialError({});
546 }
547​
548 if (matching.value.consumedAt !== null) {
549 return yield* new UnknownBootstrapCredentialError({});
550 }
551​
552 if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
553 return yield* new ExpiredBootstrapCredentialError({});
554 }
555​
556 if (
557 matching.value.proofKeyThumbprint !== null &&
558 matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint
559 ) {
560 return yield* new BootstrapCredentialProofKeyMismatchError({});
561 }
562​
563 return yield* new UnavailableBootstrapCredentialError({});
564 },
565 );
566​
567 return PairingGrantStore.of({
568 issueOneTimeToken,
569 listActive,
570 get streamChanges() {
571 return Stream.fromPubSub(changesPubSub);
572 },
573 revoke,
574 consume,
575 });
576});
577​
578export const layer = Layer.effect(PairingGrantStore, make).pipe(
579 Layer.provideMerge(AuthPairingLinks.layer),
580);