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

PairingGrantStore.ts

583 lines18.9 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 credential: row.credential,
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 credential: row.credential,
353 scopes: row.scopes,
354 subject: row.subject,
355 createdAt: row.createdAt,
356 expiresAt: row.expiresAt,
357 } satisfies AuthPairingLink),
358 );
359 },
360 Effect.mapError((cause) => new ActivePairingLinksLoadError({ cause })),
361 );
362​
363 const revoke: PairingGrantStore["Service"]["revoke"] = Effect.fn("PairingGrantStore.revoke")(
364 function* (id) {
365 const revokedAt = yield* DateTime.now;
366 const revoked = yield* pairingLinks
367 .revoke({
368 id,
369 revokedAt,
370 })
371 .pipe(Effect.mapError((cause) => new PairingLinkRevokeError({ pairingLinkId: id, cause })));
372 if (revoked) {
373 yield* emitRemoved(id);
374 }
375 return revoked;
376 },
377 );
378​
379 const issueOneTimeToken: PairingGrantStore["Service"]["issueOneTimeToken"] = Effect.fn(
380 "PairingGrantStore.issueOneTimeToken",
381 )(function* (input) {
382 const id = yield* crypto.randomUUIDv4.pipe(
383 Effect.mapError(
384 (cause) => new PairingCredentialRandomGenerationError({ operation: "generate-id", cause }),
385 ),
386 );
387 const credential = yield* generatePairingToken;
388 const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
389 const ttl =
390 input?.ttl ??
391 (isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
392 const now = yield* DateTime.now;
393 const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
394 const issued: IssuedBootstrapCredential = {
395 id,
396 credential,
397 ...(input?.label ? { label: input.label } : {}),
398 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
399 expiresAt,
400 };
401 const subject = input?.subject ?? "one-time-token";
402 yield* pairingLinks
403 .create({
404 id,
405 credential,
406 method: "one-time-token",
407 scopes: input?.scopes ?? AuthStandardClientScopes,
408 subject,
409 label: input?.label ?? null,
410 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
411 createdAt: now,
412 expiresAt: expiresAt,
413 })
414 .pipe(
415 Effect.mapError(
416 (cause) =>
417 new PairingCredentialIssueError({
418 pairingLinkId: id,
419 subject,
420 ...(input?.label ? { label: input.label } : {}),
421 cause,
422 }),
423 ),
424 );
425 yield* emitUpsert({
426 id,
427 credential,
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 const seededResult: ConsumeResult = yield* Ref.modify(
441 seededGrantsRef,
442 (current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
443 const grant = current.get(credential);
444 if (!grant) {
445 return [
446 {
447 _tag: "error",
448 reason: "not-found",
449 error: new UnknownBootstrapCredentialError({}),
450 },
451 current,
452 ];
453 }
454​
455 const next = new Map(current);
456 if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
457 next.delete(credential);
458 return [
459 {
460 _tag: "error",
461 reason: "expired",
462 error: new ExpiredBootstrapCredentialError({}),
463 },
464 next,
465 ];
466 }
467​
468 if (grant.proofKeyThumbprint && grant.proofKeyThumbprint !== input?.proofKeyThumbprint) {
469 return [
470 {
471 _tag: "error",
472 reason: "not-found",
473 error: new BootstrapCredentialProofKeyMismatchError({}),
474 },
475 next,
476 ];
477 }
478​
479 const remainingUses = grant.remainingUses;
480 if (typeof remainingUses === "number") {
481 if (remainingUses <= 1) {
482 next.delete(credential);
483 } else {
484 next.set(credential, {
485 ...grant,
486 remainingUses: remainingUses - 1,
487 });
488 }
489 }
490​
491 return [
492 {
493 _tag: "success",
494 grant: {
495 method: grant.method,
496 scopes: grant.scopes,
497 subject: grant.subject,
498 ...(grant.label ? { label: grant.label } : {}),
499 ...(grant.proofKeyThumbprint
500 ? { proofKeyThumbprint: grant.proofKeyThumbprint }
501 : {}),
502 expiresAt: grant.expiresAt,
503 } satisfies BootstrapGrant,
504 },
505 next,
506 ];
507 },
508 );
509​
510 if (seededResult._tag === "success") {
511 return seededResult.grant;
512 }
513 if (seededResult.reason !== "not-found") {
514 return yield* seededResult.error;
515 }
516​
517 const consumed = yield* pairingLinks
518 .consumeAvailable({
519 credential,
520 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
521 consumedAt: now,
522 now,
523 })
524 .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));
525​
526 if (Option.isSome(consumed)) {
527 yield* emitRemoved(consumed.value.id);
528 return {
529 method: consumed.value.method,
530 scopes: consumed.value.scopes,
531 subject: consumed.value.subject,
532 ...(consumed.value.label ? { label: consumed.value.label } : {}),
533 ...(consumed.value.proofKeyThumbprint
534 ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }
535 : {}),
536 expiresAt: consumed.value.expiresAt,
537 } satisfies BootstrapGrant;
538 }
539​
540 const matching = yield* pairingLinks
541 .getByCredential({ credential })
542 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
543 if (Option.isNone(matching)) {
544 return yield* new UnknownBootstrapCredentialError({});
545 }
546​
547 if (matching.value.revokedAt !== null) {
548 return yield* new UnavailableBootstrapCredentialError({});
549 }
550​
551 if (matching.value.consumedAt !== null) {
552 return yield* new UnknownBootstrapCredentialError({});
553 }
554​
555 if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
556 return yield* new ExpiredBootstrapCredentialError({});
557 }
558​
559 if (
560 matching.value.proofKeyThumbprint !== null &&
561 matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint
562 ) {
563 return yield* new BootstrapCredentialProofKeyMismatchError({});
564 }
565​
566 return yield* new UnavailableBootstrapCredentialError({});
567 },
568 );
569​
570 return PairingGrantStore.of({
571 issueOneTimeToken,
572 listActive,
573 get streamChanges() {
574 return Stream.fromPubSub(changesPubSub);
575 },
576 revoke,
577 consume,
578 });
579});
580​
581export const layer = Layer.effect(PairingGrantStore, make).pipe(
582 Layer.provideMerge(AuthPairingLinks.layer),
583);