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

PairingGrantStore.ts

578 lines18.6 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.TaggedError<UnknownBootstrapCredentialError>()(
33 "UnknownBootstrapCredentialError",
34 {},
35) {
36 override get message(): string {
37 return "Unknown bootstrap credential.";
38 }
40​
41export class ExpiredBootstrapCredentialError extends Schema.TaggedError<ExpiredBootstrapCredentialError>()(
42 "ExpiredBootstrapCredentialError",
43 {},
44) {
45 override get message(): string {
46 return "Bootstrap credential expired.";
47 }
49​
50export class BootstrapCredentialProofKeyMismatchError extends Schema.TaggedError<BootstrapCredentialProofKeyMismatchError>()(
51 "BootstrapCredentialProofKeyMismatchError",
52 {},
53) {
54 override get message(): string {
55 return "Bootstrap credential proof key mismatch.";
56 }
58​
59export class UnavailableBootstrapCredentialError extends Schema.TaggedError<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;
75​
76export class ActivePairingLinksLoadError extends Schema.TaggedError<ActivePairingLinksLoadError>()(
77 "ActivePairingLinksLoadError",
78 {
79 cause: Schema.Defect(),
80 },
81) {
82 override get message(): string {
83 return "Failed to load active pairing links.";
84 }
86​
87export class PairingLinkRevokeError extends Schema.TaggedError<PairingLinkRevokeError>()(
88 "PairingLinkRevokeError",
89 {
90 pairingLinkId: Schema.String,
91 cause: Schema.Defect(),
92 },
93) {
94 override get message(): string {
95 return `Failed to revoke pairing link '${this.pairingLinkId}'.`;
96 }
98​
99export class PairingCredentialIssueError extends Schema.TaggedError<PairingCredentialIssueError>()(
100 "PairingCredentialIssueError",
101 {
102 pairingLinkId: Schema.String,
103 subject: Schema.String,
104 label: Schema.optional(Schema.String),
105 cause: Schema.Defect(),
106 },
107) {
108 override get message(): string {
109 return `Failed to issue pairing credential '${this.pairingLinkId}' for '${this.subject}'.`;
110 }
112​
113export class PairingCredentialRandomGenerationError extends Schema.TaggedError<PairingCredentialRandomGenerationError>()(
114 "PairingCredentialRandomGenerationError",
115 {
116 operation: Schema.Literals(["generate-id", "generate-token"]),
117 cause: Schema.Defect(),
118 },
119) {
120 override get message(): string {
121 return `Failed to generate pairing credential data during '${this.operation}'.`;
122 }
124​
125export class BootstrapCredentialConsumeError extends Schema.TaggedError<BootstrapCredentialConsumeError>()(
126 "BootstrapCredentialConsumeError",
127 {
128 cause: Schema.Defect(),
129 },
130) {
131 override get message(): string {
132 return "Failed to consume bootstrap credential.";
133 }
135​
136export class BootstrapCredentialConsumeAvailableError extends Schema.TaggedError<BootstrapCredentialConsumeAvailableError>()(
137 "BootstrapCredentialConsumeAvailableError",
138 {
139 cause: Schema.Defect(),
140 },
141) {
142 override get message(): string {
143 return "Failed to atomically consume an available bootstrap credential.";
144 }
146​
147export class BootstrapCredentialLookupError extends Schema.TaggedError<BootstrapCredentialLookupError>()(
148 "BootstrapCredentialLookupError",
149 {
150 cause: Schema.Defect(),
151 },
152) {
153 override get message(): string {
154 return "Failed to look up bootstrap credential state.";
155 }
157​
158export const BootstrapCredentialInternalError = Schema.Union([
159 ActivePairingLinksLoadError,
160 PairingLinkRevokeError,
161 PairingCredentialIssueError,
162 PairingCredentialRandomGenerationError,
163 BootstrapCredentialConsumeError,
164 BootstrapCredentialConsumeAvailableError,
165 BootstrapCredentialLookupError,
166]);
167export type BootstrapCredentialInternalError = typeof BootstrapCredentialInternalError.Type;
168export const isBootstrapCredentialInternalError = Schema.is(BootstrapCredentialInternalError);
169​
170export const BootstrapCredentialError = Schema.Union([
171 BootstrapCredentialInvalidError,
172 BootstrapCredentialInternalError,
173]);
174export type BootstrapCredentialError = typeof BootstrapCredentialError.Type;
175​
176export interface IssuedBootstrapCredential {
177 readonly id: string;
178 readonly credential: string;
179 readonly label?: string;
180 readonly proofKeyThumbprint?: string;
181 readonly expiresAt: DateTime.Utc;
183​
184export type BootstrapCredentialChange =
185 | {
186 readonly type: "pairingLinkUpserted";
187 readonly pairingLink: AuthPairingLink;
188 }
189 | {
190 readonly type: "pairingLinkRemoved";
191 readonly id: string;
192 };
193​
194export class PairingGrantStore extends Context.Service<
195 PairingGrantStore,
196 {
197 readonly issueOneTimeToken: (input?: {
198 readonly ttl?: Duration.Duration;
199 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
200 readonly subject?: string;
201 readonly label?: string;
202 readonly proofKeyThumbprint?: string;
203 /**
204 * "startup" marks the credential the server mints for itself at boot,
205 * which gets the long dev TTL when a dev URL is configured.
206 */
207 readonly purpose?: "startup";
208 }) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
209 readonly listActive: () => Effect.Effect<
210 ReadonlyArray<AuthPairingLink>,
211 BootstrapCredentialInternalError
212 >;
213 readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
214 readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
215 readonly consume: (
216 credential: string,
217 input?: {
218 readonly proofKeyThumbprint?: string;
219 },
220 ) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
221 }
222>()("t3/auth/PairingGrantStore") {}
223​
224interface StoredBootstrapGrant extends BootstrapGrant {
225 readonly remainingUses: number | "unbounded";
227​
228type ConsumeResult =
229 | {
230 readonly _tag: "error";
231 readonly reason: "not-found" | "expired";
232 readonly error: BootstrapCredentialError;
233 }
234 | {
235 readonly _tag: "success";
236 readonly grant: BootstrapGrant;
237 };
238​
239const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
240// The desktop-bootstrap grant rides on a trusted IPC channel (fd3 or
241// stdin) at backend launch, so it doesn't have to be short-lived the
242// way a user-facing pairing link does. Letting it live for the
243// lifetime of the backend process (24h is more than long enough for
244// practical desktop use, and well under "forever" in case the seed
245// gets logged anywhere by accident) means a page reload past the 5-min
246// window can still recover by re-bootstrapping rather than locking
247// the user out of the backend.
248const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
249// A dev server's startup token is read off a log by whoever (or whatever) is
250// driving the session, often minutes later — after a `node --watch` restart, a
251// detour into another task, or a hand-off to the person actually doing the
252// testing. Five minutes turns that into a restart-the-server loop for no
253// security benefit: the token only unlocks a local dev backend, and its holder
254// could read the log anyway. Same reasoning (and duration) as the desktop
255// bootstrap grant above. Only applies when a dev URL is configured; user-issued
256// pairing links and real servers keep the 5-minute default.
257const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
258const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
259const PAIRING_TOKEN_LENGTH = 12;
260const PAIRING_TOKEN_REJECTION_LIMIT =
261 Math.floor(256 / PAIRING_TOKEN_ALPHABET.length) * PAIRING_TOKEN_ALPHABET.length;
262​
263export const make = Effect.gen(function* () {
264 const crypto = yield* Crypto.Crypto;
265 const config = yield* ServerConfig.ServerConfig;
266 const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository;
267 const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
268 const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
269 const generatePairingToken = Effect.gen(function* () {
270 let credential = "";
271 while (credential.length < PAIRING_TOKEN_LENGTH) {
272 const bytes = yield* crypto
273 .randomBytes(PAIRING_TOKEN_LENGTH)
274 .pipe(
275 Effect.mapError(
276 (cause) =>
277 new PairingCredentialRandomGenerationError({ operation: "generate-token", cause }),
278 ),
279 );
280 for (const byte of bytes) {
281 if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) {
282 continue;
283 }
284 credential += PAIRING_TOKEN_ALPHABET[byte % PAIRING_TOKEN_ALPHABET.length]!;
285 if (credential.length === PAIRING_TOKEN_LENGTH) {
286 return credential;
287 }
288 }
289 }
290 return credential;
291 });
292​
293 const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>
294 Ref.update(seededGrantsRef, (current) => {
295 const next = new Map(current);
296 next.set(credential, grant);
297 return next;
298 });
299​
300 const emitUpsert = (pairingLink: AuthPairingLink) =>
301 PubSub.publish(changesPubSub, {
302 type: "pairingLinkUpserted",
303 pairingLink,
304 }).pipe(Effect.asVoid);
305​
306 const emitRemoved = (id: string) =>
307 PubSub.publish(changesPubSub, {
308 type: "pairingLinkRemoved",
309 id,
310 }).pipe(Effect.asVoid);
311​
312 if (config.desktopBootstrapToken) {
313 const now = yield* DateTime.now;
314 yield* seedGrant(config.desktopBootstrapToken, {
315 method: "desktop-bootstrap",
316 scopes: AuthAdministrativeScopes,
317 subject: "desktop-bootstrap",
318 expiresAt: DateTime.add(now, {
319 milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS),
320 }),
321 // Unbounded uses so the renderer can re-exchange the seed for a
322 // fresh bearer session after a page reload (or after the prior
323 // bearer expires). The seed itself stays inside the desktop
324 // process and the rendered page, both of which the user already
325 // implicitly trusts.
326 remainingUses: "unbounded",
327 });
328 }
329​
330 const listActive: PairingGrantStore["Service"]["listActive"] = Effect.fn(
331 "PairingGrantStore.listActive",
332 )(
333 function* () {
334 const now = yield* DateTime.now;
335 const rows = yield* pairingLinks.listActive({ now });
336​
337 return rows.map((row) =>
338 row.label
339 ? ({
340 id: row.id,
341 scopes: row.scopes,
342 subject: row.subject,
343 label: row.label,
344 createdAt: row.createdAt,
345 expiresAt: row.expiresAt,
346 } satisfies AuthPairingLink)
347 : ({
348 id: row.id,
349 scopes: row.scopes,
350 subject: row.subject,
351 createdAt: row.createdAt,
352 expiresAt: row.expiresAt,
353 } satisfies AuthPairingLink),
354 );
355 },
356 Effect.mapError((cause) => new ActivePairingLinksLoadError({ cause })),
357 );
358​
359 const revoke: PairingGrantStore["Service"]["revoke"] = Effect.fn("PairingGrantStore.revoke")(
360 function* (id) {
361 const revokedAt = yield* DateTime.now;
362 const revoked = yield* pairingLinks
363 .revoke({
364 id,
365 revokedAt,
366 })
367 .pipe(Effect.mapError((cause) => new PairingLinkRevokeError({ pairingLinkId: id, cause })));
368 if (revoked) {
369 yield* emitRemoved(id);
370 }
371 return revoked;
372 },
373 );
374​
375 const issueOneTimeToken: PairingGrantStore["Service"]["issueOneTimeToken"] = Effect.fn(
376 "PairingGrantStore.issueOneTimeToken",
377 )(function* (input) {
378 const id = yield* crypto.randomUUIDv4.pipe(
379 Effect.mapError(
380 (cause) => new PairingCredentialRandomGenerationError({ operation: "generate-id", cause }),
381 ),
382 );
383 const credential = yield* generatePairingToken;
384 const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
385 const ttl =
386 input?.ttl ??
387 (isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
388 const now = yield* DateTime.now;
389 const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
390 const issued: IssuedBootstrapCredential = {
391 id,
392 credential,
393 ...(input?.label ? { label: input.label } : {}),
394 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
395 expiresAt,
396 };
397 const subject = input?.subject ?? "one-time-token";
398 yield* pairingLinks
399 .create({
400 id,
401 credential,
402 method: "one-time-token",
403 scopes: input?.scopes ?? AuthStandardClientScopes,
404 subject,
405 label: input?.label ?? null,
406 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
407 createdAt: now,
408 expiresAt: expiresAt,
409 })
410 .pipe(
411 Effect.mapError(
412 (cause) =>
413 new PairingCredentialIssueError({
414 pairingLinkId: id,
415 subject,
416 ...(input?.label ? { label: input.label } : {}),
417 cause,
418 }),
419 ),
420 );
421 yield* emitUpsert({
422 id,
423 scopes: input?.scopes ?? AuthStandardClientScopes,
424 subject: input?.subject ?? "one-time-token",
425 ...(input?.label ? { label: input.label } : {}),
426 createdAt: now,
427 expiresAt,
428 });
429 return issued;
430 });
431​
432 const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")(
433 function* (credential, input) {
434 const now = yield* DateTime.now;
435 const seededResult: ConsumeResult = yield* Ref.modify(
436 seededGrantsRef,
437 (current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
438 const grant = current.get(credential);
439 if (!grant) {
440 return [
441 {
442 _tag: "error",
443 reason: "not-found",
444 error: new UnknownBootstrapCredentialError({}),
445 },
446 current,
447 ];
448 }
449​
450 const next = new Map(current);
451 if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
452 next.delete(credential);
453 return [
454 {
455 _tag: "error",
456 reason: "expired",
457 error: new ExpiredBootstrapCredentialError({}),
458 },
459 next,
460 ];
461 }
462​
463 if (grant.proofKeyThumbprint && grant.proofKeyThumbprint !== input?.proofKeyThumbprint) {
464 return [
465 {
466 _tag: "error",
467 reason: "not-found",
468 error: new BootstrapCredentialProofKeyMismatchError({}),
469 },
470 next,
471 ];
472 }
473​
474 const remainingUses = grant.remainingUses;
475 if (typeof remainingUses === "number") {
476 if (remainingUses <= 1) {
477 next.delete(credential);
478 } else {
479 next.set(credential, {
480 ...grant,
481 remainingUses: remainingUses - 1,
482 });
483 }
484 }
485​
486 return [
487 {
488 _tag: "success",
489 grant: {
490 method: grant.method,
491 scopes: grant.scopes,
492 subject: grant.subject,
493 ...(grant.label ? { label: grant.label } : {}),
494 ...(grant.proofKeyThumbprint
495 ? { proofKeyThumbprint: grant.proofKeyThumbprint }
496 : {}),
497 expiresAt: grant.expiresAt,
498 } satisfies BootstrapGrant,
499 },
500 next,
501 ];
502 },
503 );
504​
505 if (seededResult._tag === "success") {
506 return seededResult.grant;
507 }
508 if (seededResult.reason !== "not-found") {
509 return yield* seededResult.error;
510 }
511​
512 const consumed = yield* pairingLinks
513 .consumeAvailable({
514 credential,
515 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
516 consumedAt: now,
517 now,
518 })
519 .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));
520​
521 if (Option.isSome(consumed)) {
522 yield* emitRemoved(consumed.value.id);
523 return {
524 method: consumed.value.method,
525 scopes: consumed.value.scopes,
526 subject: consumed.value.subject,
527 ...(consumed.value.label ? { label: consumed.value.label } : {}),
528 ...(consumed.value.proofKeyThumbprint
529 ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }
530 : {}),
531 expiresAt: consumed.value.expiresAt,
532 } satisfies BootstrapGrant;
533 }
534​
535 const matching = yield* pairingLinks
536 .getByCredential({ credential })
537 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
538 if (Option.isNone(matching)) {
539 return yield* new UnknownBootstrapCredentialError({});
540 }
541​
542 if (matching.value.revokedAt !== null) {
543 return yield* new UnavailableBootstrapCredentialError({});
544 }
545​
546 if (matching.value.consumedAt !== null) {
547 return yield* new UnknownBootstrapCredentialError({});
548 }
549​
550 if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
551 return yield* new ExpiredBootstrapCredentialError({});
552 }
553​
554 if (
555 matching.value.proofKeyThumbprint !== null &&
556 matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint
557 ) {
558 return yield* new BootstrapCredentialProofKeyMismatchError({});
559 }
560​
561 return yield* new UnavailableBootstrapCredentialError({});
562 },
563 );
564​
565 return PairingGrantStore.of({
566 issueOneTimeToken,
567 listActive,
568 get streamChanges() {
569 return Stream.fromPubSub(changesPubSub);
570 },
571 revoke,
572 consume,
573 });
574});
575​
576export const layer = Layer.effect(PairingGrantStore, make).pipe(
577 Layer.provideMerge(AuthPairingLinks.layer),
578);