Open History to see the last commit
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;
30}
31
32export class UnknownBootstrapCredentialError extends Schema.TaggedErrorClass<UnknownBootstrapCredentialError>()(
33 "UnknownBootstrapCredentialError",
34 {},
35) {
36 override get message(): string {
37 return "Unknown bootstrap credential.";
38 }
39}
40
41export class ExpiredBootstrapCredentialError extends Schema.TaggedErrorClass<ExpiredBootstrapCredentialError>()(
42 "ExpiredBootstrapCredentialError",
43 {},
44) {
45 override get message(): string {
46 return "Bootstrap credential expired.";
47 }
48}
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 }
57}
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 }
66}
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 }
86}
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 }
98}
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 }
112}
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 }
124}
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 }
135}
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 }
146}
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 }
157}
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;
184}
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 }) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
206 readonly listActive: () => Effect.Effect<
207 ReadonlyArray<AuthPairingLink>,
208 BootstrapCredentialInternalError
209 >;
210 readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
211 readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
212 readonly consume: (
213 credential: string,
214 input?: {
215 readonly proofKeyThumbprint?: string;
216 },
217 ) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
218 }
219>()("t3/auth/PairingGrantStore") {}
220
221interface StoredBootstrapGrant extends BootstrapGrant {
222 readonly remainingUses: number | "unbounded";
223}
224
225type ConsumeResult =
226 | {
227 readonly _tag: "error";
228 readonly reason: "not-found" | "expired";
229 readonly error: BootstrapCredentialError;
230 }
231 | {
232 readonly _tag: "success";
233 readonly grant: BootstrapGrant;
234 };
235
236const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
237// The desktop-bootstrap grant rides on a trusted IPC channel (fd3 or
238// stdin) at backend launch, so it doesn't have to be short-lived the
239// way a user-facing pairing link does. Letting it live for the
240// lifetime of the backend process (24h is more than long enough for
241// practical desktop use, and well under "forever" in case the seed
242// gets logged anywhere by accident) means a page reload past the 5-min
243// window can still recover by re-bootstrapping rather than locking
244// the user out of the backend.
245const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
246const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
247const PAIRING_TOKEN_LENGTH = 12;
248const PAIRING_TOKEN_REJECTION_LIMIT =
249 Math.floor(256 / PAIRING_TOKEN_ALPHABET.length) * PAIRING_TOKEN_ALPHABET.length;
250
251export const make = Effect.gen(function* () {
252 const crypto = yield* Crypto.Crypto;
253 const config = yield* ServerConfig.ServerConfig;
254 const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository;
255 const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
256 const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
257 const generatePairingToken = Effect.gen(function* () {
258 let credential = "";
259 while (credential.length < PAIRING_TOKEN_LENGTH) {
260 const bytes = yield* crypto
261 .randomBytes(PAIRING_TOKEN_LENGTH)
262 .pipe(
263 Effect.mapError(
264 (cause) =>
265 new PairingCredentialRandomGenerationError({ operation: "generate-token", cause }),
266 ),
267 );
268 for (const byte of bytes) {
269 if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) {
270 continue;
271 }
272 credential += PAIRING_TOKEN_ALPHABET[byte % PAIRING_TOKEN_ALPHABET.length]!;
273 if (credential.length === PAIRING_TOKEN_LENGTH) {
274 return credential;
275 }
276 }
277 }
278 return credential;
279 });
280
281 const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>
282 Ref.update(seededGrantsRef, (current) => {
283 const next = new Map(current);
284 next.set(credential, grant);
285 return next;
286 });
287
288 const emitUpsert = (pairingLink: AuthPairingLink) =>
289 PubSub.publish(changesPubSub, {
290 type: "pairingLinkUpserted",
291 pairingLink,
292 }).pipe(Effect.asVoid);
293
294 const emitRemoved = (id: string) =>
295 PubSub.publish(changesPubSub, {
296 type: "pairingLinkRemoved",
297 id,
298 }).pipe(Effect.asVoid);
299
300 if (config.desktopBootstrapToken) {
301 const now = yield* DateTime.now;
302 yield* seedGrant(config.desktopBootstrapToken, {
303 method: "desktop-bootstrap",
304 scopes: AuthAdministrativeScopes,
305 subject: "desktop-bootstrap",
306 expiresAt: DateTime.add(now, {
307 milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS),
308 }),
309 // Unbounded uses so the renderer can re-exchange the seed for a
310 // fresh bearer session after a page reload (or after the prior
311 // bearer expires). The seed itself stays inside the desktop
312 // process and the rendered page, both of which the user already
313 // implicitly trusts.
314 remainingUses: "unbounded",
315 });
316 }
317
318 const listActive: PairingGrantStore["Service"]["listActive"] = Effect.fn(
319 "PairingGrantStore.listActive",
320 )(
321 function* () {
322 const now = yield* DateTime.now;
323 const rows = yield* pairingLinks.listActive({ now });
324
325 return rows.map((row) =>
326 row.label
327 ? ({
328 id: row.id,
329 credential: row.credential,
330 scopes: row.scopes,
331 subject: row.subject,
332 label: row.label,
333 createdAt: row.createdAt,
334 expiresAt: row.expiresAt,
335 } satisfies AuthPairingLink)
336 : ({
337 id: row.id,
338 credential: row.credential,
339 scopes: row.scopes,
340 subject: row.subject,
341 createdAt: row.createdAt,
342 expiresAt: row.expiresAt,
343 } satisfies AuthPairingLink),
344 );
345 },
346 Effect.mapError((cause) => new ActivePairingLinksLoadError({ cause })),
347 );
348
349 const revoke: PairingGrantStore["Service"]["revoke"] = Effect.fn("PairingGrantStore.revoke")(
350 function* (id) {
351 const revokedAt = yield* DateTime.now;
352 const revoked = yield* pairingLinks
353 .revoke({
354 id,
355 revokedAt,
356 })
357 .pipe(Effect.mapError((cause) => new PairingLinkRevokeError({ pairingLinkId: id, cause })));
358 if (revoked) {
359 yield* emitRemoved(id);
360 }
361 return revoked;
362 },
363 );
364
365 const issueOneTimeToken: PairingGrantStore["Service"]["issueOneTimeToken"] = Effect.fn(
366 "PairingGrantStore.issueOneTimeToken",
367 )(function* (input) {
368 const id = yield* crypto.randomUUIDv4.pipe(
369 Effect.mapError(
370 (cause) => new PairingCredentialRandomGenerationError({ operation: "generate-id", cause }),
371 ),
372 );
373 const credential = yield* generatePairingToken;
374 const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
375 const now = yield* DateTime.now;
376 const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
377 const issued: IssuedBootstrapCredential = {
378 id,
379 credential,
380 ...(input?.label ? { label: input.label } : {}),
381 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
382 expiresAt,
383 };
384 const subject = input?.subject ?? "one-time-token";
385 yield* pairingLinks
386 .create({
387 id,
388 credential,
389 method: "one-time-token",
390 scopes: input?.scopes ?? AuthStandardClientScopes,
391 subject,
392 label: input?.label ?? null,
393 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
394 createdAt: now,
395 expiresAt: expiresAt,
396 })
397 .pipe(
398 Effect.mapError(
399 (cause) =>
400 new PairingCredentialIssueError({
401 pairingLinkId: id,
402 subject,
403 ...(input?.label ? { label: input.label } : {}),
404 cause,
405 }),
406 ),
407 );
408 yield* emitUpsert({
409 id,
410 credential,
411 scopes: input?.scopes ?? AuthStandardClientScopes,
412 subject: input?.subject ?? "one-time-token",
413 ...(input?.label ? { label: input.label } : {}),
414 createdAt: now,
415 expiresAt,
416 });
417 return issued;
418 });
419
420 const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")(
421 function* (credential, input) {
422 const now = yield* DateTime.now;
423 const seededResult: ConsumeResult = yield* Ref.modify(
424 seededGrantsRef,
425 (current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
426 const grant = current.get(credential);
427 if (!grant) {
428 return [
429 {
430 _tag: "error",
431 reason: "not-found",
432 error: new UnknownBootstrapCredentialError({}),
433 },
434 current,
435 ];
436 }
437
438 const next = new Map(current);
439 if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
440 next.delete(credential);
441 return [
442 {
443 _tag: "error",
444 reason: "expired",
445 error: new ExpiredBootstrapCredentialError({}),
446 },
447 next,
448 ];
449 }
450
451 if (grant.proofKeyThumbprint && grant.proofKeyThumbprint !== input?.proofKeyThumbprint) {
452 return [
453 {
454 _tag: "error",
455 reason: "not-found",
456 error: new BootstrapCredentialProofKeyMismatchError({}),
457 },
458 next,
459 ];
460 }
461
462 const remainingUses = grant.remainingUses;
463 if (typeof remainingUses === "number") {
464 if (remainingUses <= 1) {
465 next.delete(credential);
466 } else {
467 next.set(credential, {
468 ...grant,
469 remainingUses: remainingUses - 1,
470 });
471 }
472 }
473
474 return [
475 {
476 _tag: "success",
477 grant: {
478 method: grant.method,
479 scopes: grant.scopes,
480 subject: grant.subject,
481 ...(grant.label ? { label: grant.label } : {}),
482 ...(grant.proofKeyThumbprint
483 ? { proofKeyThumbprint: grant.proofKeyThumbprint }
484 : {}),
485 expiresAt: grant.expiresAt,
486 } satisfies BootstrapGrant,
487 },
488 next,
489 ];
490 },
491 );
492
493 if (seededResult._tag === "success") {
494 return seededResult.grant;
495 }
496 if (seededResult.reason !== "not-found") {
497 return yield* seededResult.error;
498 }
499
500 const consumed = yield* pairingLinks
501 .consumeAvailable({
502 credential,
503 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
504 consumedAt: now,
505 now,
506 })
507 .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));
508
509 if (Option.isSome(consumed)) {
510 yield* emitRemoved(consumed.value.id);
511 return {
512 method: consumed.value.method,
513 scopes: consumed.value.scopes,
514 subject: consumed.value.subject,
515 ...(consumed.value.label ? { label: consumed.value.label } : {}),
516 ...(consumed.value.proofKeyThumbprint
517 ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }
518 : {}),
519 expiresAt: consumed.value.expiresAt,
520 } satisfies BootstrapGrant;
521 }
522
523 const matching = yield* pairingLinks
524 .getByCredential({ credential })
525 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
526 if (Option.isNone(matching)) {
527 return yield* new UnknownBootstrapCredentialError({});
528 }
529
530 if (matching.value.revokedAt !== null) {
531 return yield* new UnavailableBootstrapCredentialError({});
532 }
533
534 if (matching.value.consumedAt !== null) {
535 return yield* new UnknownBootstrapCredentialError({});
536 }
537
538 if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
539 return yield* new ExpiredBootstrapCredentialError({});
540 }
541
542 if (
543 matching.value.proofKeyThumbprint !== null &&
544 matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint
545 ) {
546 return yield* new BootstrapCredentialProofKeyMismatchError({});
547 }
548
549 return yield* new UnavailableBootstrapCredentialError({});
550 },
551 );
552
553 return PairingGrantStore.of({
554 issueOneTimeToken,
555 listActive,
556 get streamChanges() {
557 return Stream.fromPubSub(changesPubSub);
558 },
559 revoke,
560 consume,
561 });
562});
563
564export const layer = Layer.effect(PairingGrantStore, make).pipe(
565 Layer.provideMerge(AuthPairingLinks.layer),
566);