sailfork / t3code-github / apps/ server/ src/ auth/ PairingGrantStore.ts

import {
  AuthStandardClientScopes,
  type AuthEnvironmentScope,
  type AuthPairingLink,
  type ServerAuthBootstrapMethod,
} from "@t3tools/contracts";
import {
  DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,
  isValidDesktopBootstrapToken,
} from "@t3tools/shared/desktopBootstrapToken";
import * as Context from "effect/Context";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Mac from "effect/crypto/Mac";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";

import * as ServerConfig from "../config.ts";
import * as AuthPairingLinks from "../persistence/AuthPairingLinks.ts";

export interface BootstrapGrant {
  readonly method: ServerAuthBootstrapMethod;
  readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
  readonly subject: string;
  readonly label?: string;
  readonly proofKeyThumbprint?: string;
  readonly expiresAt: DateTime.DateTime;
}

export class UnknownBootstrapCredentialError extends Schema.TaggedError<UnknownBootstrapCredentialError>()(
  "UnknownBootstrapCredentialError",
  {},
) {
  override get message(): string {
    return "Unknown bootstrap credential.";
  }
}

export class ExpiredBootstrapCredentialError extends Schema.TaggedError<ExpiredBootstrapCredentialError>()(
  "ExpiredBootstrapCredentialError",
  {},
) {
  override get message(): string {
    return "Bootstrap credential expired.";
  }
}

export class BootstrapCredentialProofKeyMismatchError extends Schema.TaggedError<BootstrapCredentialProofKeyMismatchError>()(
  "BootstrapCredentialProofKeyMismatchError",
  {},
) {
  override get message(): string {
    return "Bootstrap credential proof key mismatch.";
  }
}

export class UnavailableBootstrapCredentialError extends Schema.TaggedError<UnavailableBootstrapCredentialError>()(
  "UnavailableBootstrapCredentialError",
  {},
) {
  override get message(): string {
    return "Bootstrap credential is no longer available.";
  }
}

export class BootstrapCredentialScopeNotGrantedError extends Schema.TaggedError<BootstrapCredentialScopeNotGrantedError>()(
  "BootstrapCredentialScopeNotGrantedError",
  {},
) {
  override get message(): string {
    return "The requested authentication scope was not granted.";
  }
}

export const BootstrapCredentialInvalidError = Schema.Union([
  UnknownBootstrapCredentialError,
  ExpiredBootstrapCredentialError,
  BootstrapCredentialProofKeyMismatchError,
  UnavailableBootstrapCredentialError,
]);
export type BootstrapCredentialInvalidError = typeof BootstrapCredentialInvalidError.Type;

export class ActivePairingLinksLoadError extends Schema.TaggedError<ActivePairingLinksLoadError>()(
  "ActivePairingLinksLoadError",
  {
    cause: Schema.Defect(),
  },
) {
  override get message(): string {
    return "Failed to load active pairing links.";
  }
}

export class PairingLinkRevokeError extends Schema.TaggedError<PairingLinkRevokeError>()(
  "PairingLinkRevokeError",
  {
    pairingLinkId: Schema.String,
    cause: Schema.Defect(),
  },
) {
  override get message(): string {
    return `Failed to revoke pairing link '${this.pairingLinkId}'.`;
  }
}

export class PairingCredentialIssueError extends Schema.TaggedError<PairingCredentialIssueError>()(
  "PairingCredentialIssueError",
  {
    pairingLinkId: Schema.String,
    subject: Schema.String,
    label: Schema.optional(Schema.String),
    cause: Schema.Defect(),
  },
) {
  override get message(): string {
    return `Failed to issue pairing credential '${this.pairingLinkId}' for '${this.subject}'.`;
  }
}

export class PairingCredentialRandomGenerationError extends Schema.TaggedError<PairingCredentialRandomGenerationError>()(
  "PairingCredentialRandomGenerationError",
  {
    operation: Schema.Literals(["generate-id", "generate-token"]),
    cause: Schema.Defect(),
  },
) {
  override get message(): string {
    return `Failed to generate pairing credential data during '${this.operation}'.`;
  }
}

export class BootstrapCredentialConsumeError extends Schema.TaggedError<BootstrapCredentialConsumeError>()(
  "BootstrapCredentialConsumeError",
  {
    cause: Schema.Defect(),
  },
) {
  override get message(): string {
    return "Failed to consume bootstrap credential.";
  }
}

export class BootstrapCredentialConsumeAvailableError extends Schema.TaggedError<BootstrapCredentialConsumeAvailableError>()(
  "BootstrapCredentialConsumeAvailableError",
  {
    cause: Schema.Defect(),
  },
) {
  override get message(): string {
    return "Failed to atomically consume an available bootstrap credential.";
  }
}

export class BootstrapCredentialLookupError extends Schema.TaggedError<BootstrapCredentialLookupError>()(
  "BootstrapCredentialLookupError",
  {
    cause: Schema.Defect(),
  },
) {
  override get message(): string {
    return "Failed to look up bootstrap credential state.";
  }
}

export const BootstrapCredentialInternalError = Schema.Union([
  ActivePairingLinksLoadError,
  PairingLinkRevokeError,
  PairingCredentialIssueError,
  PairingCredentialRandomGenerationError,
  BootstrapCredentialConsumeError,
  BootstrapCredentialConsumeAvailableError,
  BootstrapCredentialLookupError,
]);
export type BootstrapCredentialInternalError = typeof BootstrapCredentialInternalError.Type;
export const isBootstrapCredentialInternalError = Schema.is(BootstrapCredentialInternalError);

export const BootstrapCredentialError = Schema.Union([
  BootstrapCredentialInvalidError,
  BootstrapCredentialInternalError,
  BootstrapCredentialScopeNotGrantedError,
]);
export type BootstrapCredentialError = typeof BootstrapCredentialError.Type;

export interface IssuedBootstrapCredential {
  readonly id: string;
  readonly credential: string;
  readonly label?: string;
  readonly proofKeyThumbprint?: string;
  readonly expiresAt: DateTime.Utc;
}

export type BootstrapCredentialChange =
  | {
      readonly type: "pairingLinkUpserted";
      readonly pairingLink: AuthPairingLink;
    }
  | {
      readonly type: "pairingLinkRemoved";
      readonly id: string;
    };

export class PairingGrantStore extends Context.Service<
  PairingGrantStore,
  {
    readonly issueOneTimeToken: (input?: {
      readonly ttl?: Duration.Duration;
      readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
      readonly subject?: string;
      readonly label?: string;
      readonly proofKeyThumbprint?: string;
      readonly purpose?: "startup";
    }) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
    readonly listActive: () => Effect.Effect<
      ReadonlyArray<AuthPairingLink>,
      BootstrapCredentialInternalError
    >;
    readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
    readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
    readonly consume: (
      credential: string,
      input?: {
        readonly proofKeyThumbprint?: string;
        readonly requestedScopes?: ReadonlyArray<AuthEnvironmentScope>;
        /** All scopes must be granted; requestedScopes only requires an overlap for OAuth. */
        readonly requiredScopes?: ReadonlyArray<AuthEnvironmentScope>;
      },
    ) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
  }
>()("t3/auth/PairingGrantStore") {}

interface StoredBootstrapGrant extends BootstrapGrant {
  readonly remainingUses: number | "unbounded";
}

type ConsumeResult =
  | {
      readonly _tag: "error";
      readonly reason: "not-found" | "expired" | "scope-not-granted";
      readonly error: BootstrapCredentialError;
    }
  | {
      readonly _tag: "success";
      readonly grant: BootstrapGrant;
    };

const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
const PAIRING_TOKEN_LENGTH = 12;
const PAIRING_TOKEN_REJECTION_LIMIT =
  Math.floor(256 / PAIRING_TOKEN_ALPHABET.length) * PAIRING_TOKEN_ALPHABET.length;

const PAIRING_TOKEN_PATTERN = new RegExp(
  `^[${PAIRING_TOKEN_ALPHABET}]{${PAIRING_TOKEN_LENGTH}}

	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	apps/server/src/auth/PairingGrantStore.ts at main · sailfork/t3code-github · Sailfork
	
		
, "i", ); const make = Effect.gen(function* () { const random = yield* SecureRandom.SecureRandom; const config = yield* ServerConfig.ServerConfig; const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository; const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>()); const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>(); const generatePairingToken = Effect.gen(function* () { let credential = ""; while (credential.length < PAIRING_TOKEN_LENGTH) { const bytes = yield* random .randomBytes(PAIRING_TOKEN_LENGTH) .pipe( Effect.mapError( (cause) => new PairingCredentialRandomGenerationError({ operation: "generate-token", cause }), ), ); for (const byte of bytes) { if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) { continue; } credential += PAIRING_TOKEN_ALPHABET[byte % PAIRING_TOKEN_ALPHABET.length]!; if (credential.length === PAIRING_TOKEN_LENGTH) { return credential; } } } return credential; }); const seedGrant = (credential: string, grant: StoredBootstrapGrant) => Ref.update(seededGrantsRef, (current) => { const next = new Map(current); next.set(credential, grant); return next; }); const emitUpsert = (pairingLink: AuthPairingLink) => PubSub.publish(changesPubSub, { type: "pairingLinkUpserted", pairingLink, }).pipe(Effect.asVoid); const emitRemoved = (id: string) => PubSub.publish(changesPubSub, { type: "pairingLinkRemoved", id, }).pipe(Effect.asVoid); // Accept tokens derived from the rotating desktop secret; older desktops send only a token. const desktopBootstrapSecret = config.desktopBootstrapSecret; const mac = yield* Mac.Mac; const consumeRotatingDesktopToken = (credential: string, nowMs: number) => desktopBootstrapSecret === undefined ? Effect.succeed(false) : isValidDesktopBootstrapToken(desktopBootstrapSecret, credential, nowMs).pipe( Effect.provideService(Mac.Mac, mac), ); if (config.desktopBootstrapToken && desktopBootstrapSecret === undefined) { const now = yield* DateTime.now; yield* seedGrant(config.desktopBootstrapToken, { method: "desktop-bootstrap", scopes: AuthStandardClientScopes, subject: "desktop-bootstrap", expiresAt: DateTime.add(now, { milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS), }), // Reloads and expired bearer sessions must be able to re-exchange the desktop seed. remainingUses: "unbounded", }); } const listActive: PairingGrantStore["Service"]["listActive"] = Effect.fn( "PairingGrantStore.listActive", )( function* () { const now = yield* DateTime.now; const rows = yield* pairingLinks.listActive({ now }); return rows.map((row) => row.label ? ({ id: row.id, scopes: row.scopes, subject: row.subject, label: row.label, createdAt: row.createdAt, expiresAt: row.expiresAt, } satisfies AuthPairingLink) : ({ id: row.id, scopes: row.scopes, subject: row.subject, createdAt: row.createdAt, expiresAt: row.expiresAt, } satisfies AuthPairingLink), ); }, Effect.mapError((cause) => new ActivePairingLinksLoadError({ cause })), ); const revoke: PairingGrantStore["Service"]["revoke"] = Effect.fn("PairingGrantStore.revoke")( function* (id) { const revokedAt = yield* DateTime.now; const revoked = yield* pairingLinks .revoke({ id, revokedAt, }) .pipe(Effect.mapError((cause) => new PairingLinkRevokeError({ pairingLinkId: id, cause }))); if (revoked) { yield* emitRemoved(id); } return revoked; }, ); const issueOneTimeToken: PairingGrantStore["Service"]["issueOneTimeToken"] = Effect.fn( "PairingGrantStore.issueOneTimeToken", )(function* (input) { const id = yield* random .uuidV4() .pipe( Effect.mapError( (cause) => new PairingCredentialRandomGenerationError({ operation: "generate-id", cause }), ), ); const credential = yield* generatePairingToken; const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup"; const ttl = input?.ttl ?? (isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES); const now = yield* DateTime.now; const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) }); const issued: IssuedBootstrapCredential = { id, credential, ...(input?.label ? { label: input.label } : {}), ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}), expiresAt, }; const subject = input?.subject ?? "one-time-token"; yield* pairingLinks .create({ id, credential, method: "one-time-token", scopes: input?.scopes ?? AuthStandardClientScopes, subject, label: input?.label ?? null, proofKeyThumbprint: input?.proofKeyThumbprint ?? null, createdAt: now, expiresAt: expiresAt, }) .pipe( Effect.mapError( (cause) => new PairingCredentialIssueError({ pairingLinkId: id, subject, ...(input?.label ? { label: input.label } : {}), cause, }), ), ); yield* emitUpsert({ id, scopes: input?.scopes ?? AuthStandardClientScopes, subject: input?.subject ?? "one-time-token", ...(input?.label ? { label: input.label } : {}), createdAt: now, expiresAt, }); return issued; }); const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")( function* (credential, input) { const now = yield* DateTime.now; if (yield* consumeRotatingDesktopToken(credential, now.epochMilliseconds)) { return { method: "desktop-bootstrap", scopes: AuthStandardClientScopes, subject: "desktop-bootstrap", expiresAt: DateTime.add(now, { milliseconds: DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS, }), } satisfies BootstrapGrant; } const seededResult: ConsumeResult = yield* Ref.modify( seededGrantsRef, (current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => { const grant = current.get(credential); if (!grant) { return [ { _tag: "error", reason: "not-found", error: new UnknownBootstrapCredentialError({}), }, current, ]; } const next = new Map(current); if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) { next.delete(credential); return [ { _tag: "error", reason: "expired", error: new ExpiredBootstrapCredentialError({}), }, next, ]; } if (grant.proofKeyThumbprint && grant.proofKeyThumbprint !== input?.proofKeyThumbprint) { return [ { _tag: "error", reason: "not-found", error: new BootstrapCredentialProofKeyMismatchError({}), }, next, ]; } if ( (input?.requestedScopes !== undefined && !input.requestedScopes.some((scope) => grant.scopes.includes(scope))) || (input?.requiredScopes !== undefined && !input.requiredScopes.every((scope) => grant.scopes.includes(scope))) ) { return [ { _tag: "error", reason: "scope-not-granted", error: new BootstrapCredentialScopeNotGrantedError({}), }, current, ]; } const remainingUses = grant.remainingUses; if (typeof remainingUses === "number") { if (remainingUses <= 1) { next.delete(credential); } else { next.set(credential, { ...grant, remainingUses: remainingUses - 1, }); } } return [ { _tag: "success", grant: { method: grant.method, scopes: grant.scopes, subject: grant.subject, ...(grant.label ? { label: grant.label } : {}), ...(grant.proofKeyThumbprint ? { proofKeyThumbprint: grant.proofKeyThumbprint } : {}), expiresAt: grant.expiresAt, } satisfies BootstrapGrant, }, next, ]; }, ); if (seededResult._tag === "success") { return seededResult.grant; } if (seededResult.reason !== "not-found") { return yield* seededResult.error; } // Only credentials in the issued pairing-code format are case-insensitive. const pairingCredential = PAIRING_TOKEN_PATTERN.test(credential) ? credential.toUpperCase() : credential; // Check scopes in the UPDATE so rejected requests cannot spend one-time links. const consumed = yield* pairingLinks .consumeAvailable({ credential: pairingCredential, proofKeyThumbprint: input?.proofKeyThumbprint ?? null, ...(input?.requestedScopes !== undefined ? { requestedScopes: input.requestedScopes } : {}), ...(input?.requiredScopes !== undefined ? { requiredScopes: input.requiredScopes } : {}), consumedAt: now, now, }) .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause }))); if (Option.isSome(consumed)) { yield* emitRemoved(consumed.value.id); return { method: consumed.value.method, scopes: consumed.value.scopes, subject: consumed.value.subject, ...(consumed.value.label ? { label: consumed.value.label } : {}), ...(consumed.value.proofKeyThumbprint ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint } : {}), expiresAt: consumed.value.expiresAt, } satisfies BootstrapGrant; } const matching = yield* pairingLinks .getByCredential({ credential: pairingCredential }) .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause }))); if (Option.isNone(matching)) { return yield* new UnknownBootstrapCredentialError({}); } if (matching.value.revokedAt !== null) { return yield* new UnavailableBootstrapCredentialError({}); } if (matching.value.consumedAt !== null) { return yield* new UnknownBootstrapCredentialError({}); } if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) { return yield* new ExpiredBootstrapCredentialError({}); } if ( matching.value.proofKeyThumbprint !== null && matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint ) { return yield* new BootstrapCredentialProofKeyMismatchError({}); } if ( (input?.requestedScopes !== undefined && !input.requestedScopes.some((scope) => matching.value.scopes.includes(scope))) || (input?.requiredScopes !== undefined && !input.requiredScopes.every((scope) => matching.value.scopes.includes(scope))) ) { return yield* new BootstrapCredentialScopeNotGrantedError({}); } return yield* new UnavailableBootstrapCredentialError({}); }, ); return PairingGrantStore.of({ issueOneTimeToken, listActive, get streamChanges() { return Stream.fromPubSub(changesPubSub); }, revoke, consume, }); }); export const layer = Layer.effect(PairingGrantStore, make).pipe( Layer.provideMerge(AuthPairingLinks.layer), );
apps/server/src/auth/PairingGrantStore.ts at main · sailfork/t3code-github · Sailfork
,\n \"i\",\n);\n\nconst make = Effect.gen(function* () {\n const random = yield* SecureRandom.SecureRandom;\n const config = yield* ServerConfig.ServerConfig;\n const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository;\n const seededGrantsRef = yield* Ref.make(new Map\u003cstring, StoredBootstrapGrant>());\n const changesPubSub = yield* PubSub.unbounded\u003cBootstrapCredentialChange>();\n const generatePairingToken = Effect.gen(function* () {\n let credential = \"\";\n while (credential.length \u003c PAIRING_TOKEN_LENGTH) {\n const bytes = yield* random\n .randomBytes(PAIRING_TOKEN_LENGTH)\n .pipe(\n Effect.mapError(\n (cause) =>\n new PairingCredentialRandomGenerationError({ operation: \"generate-token\", cause }),\n ),\n );\n for (const byte of bytes) {\n if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) {\n continue;\n }\n credential += PAIRING_TOKEN_ALPHABET[byte % PAIRING_TOKEN_ALPHABET.length]!;\n if (credential.length === PAIRING_TOKEN_LENGTH) {\n return credential;\n }\n }\n }\n return credential;\n });\n\n const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>\n Ref.update(seededGrantsRef, (current) => {\n const next = new Map(current);\n next.set(credential, grant);\n return next;\n });\n\n const emitUpsert = (pairingLink: AuthPairingLink) =>\n PubSub.publish(changesPubSub, {\n type: \"pairingLinkUpserted\",\n pairingLink,\n }).pipe(Effect.asVoid);\n\n const emitRemoved = (id: string) =>\n PubSub.publish(changesPubSub, {\n type: \"pairingLinkRemoved\",\n id,\n }).pipe(Effect.asVoid);\n\n // Accept tokens derived from the rotating desktop secret; older desktops send only a token.\n const desktopBootstrapSecret = config.desktopBootstrapSecret;\n const mac = yield* Mac.Mac;\n const consumeRotatingDesktopToken = (credential: string, nowMs: number) =>\n desktopBootstrapSecret === undefined\n ? Effect.succeed(false)\n : isValidDesktopBootstrapToken(desktopBootstrapSecret, credential, nowMs).pipe(\n Effect.provideService(Mac.Mac, mac),\n );\n\n if (config.desktopBootstrapToken && desktopBootstrapSecret === undefined) {\n const now = yield* DateTime.now;\n yield* seedGrant(config.desktopBootstrapToken, {\n method: \"desktop-bootstrap\",\n scopes: AuthStandardClientScopes,\n subject: \"desktop-bootstrap\",\n expiresAt: DateTime.add(now, {\n milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS),\n }),\n // Reloads and expired bearer sessions must be able to re-exchange the desktop seed.\n remainingUses: \"unbounded\",\n });\n }\n\n const listActive: PairingGrantStore[\"Service\"][\"listActive\"] = Effect.fn(\n \"PairingGrantStore.listActive\",\n )(\n function* () {\n const now = yield* DateTime.now;\n const rows = yield* pairingLinks.listActive({ now });\n\n return rows.map((row) =>\n row.label\n ? ({\n id: row.id,\n scopes: row.scopes,\n subject: row.subject,\n label: row.label,\n createdAt: row.createdAt,\n expiresAt: row.expiresAt,\n } satisfies AuthPairingLink)\n : ({\n id: row.id,\n scopes: row.scopes,\n subject: row.subject,\n createdAt: row.createdAt,\n expiresAt: row.expiresAt,\n } satisfies AuthPairingLink),\n );\n },\n Effect.mapError((cause) => new ActivePairingLinksLoadError({ cause })),\n );\n\n const revoke: PairingGrantStore[\"Service\"][\"revoke\"] = Effect.fn(\"PairingGrantStore.revoke\")(\n function* (id) {\n const revokedAt = yield* DateTime.now;\n const revoked = yield* pairingLinks\n .revoke({\n id,\n revokedAt,\n })\n .pipe(Effect.mapError((cause) => new PairingLinkRevokeError({ pairingLinkId: id, cause })));\n if (revoked) {\n yield* emitRemoved(id);\n }\n return revoked;\n },\n );\n\n const issueOneTimeToken: PairingGrantStore[\"Service\"][\"issueOneTimeToken\"] = Effect.fn(\n \"PairingGrantStore.issueOneTimeToken\",\n )(function* (input) {\n const id = yield* random\n .uuidV4()\n .pipe(\n Effect.mapError(\n (cause) =>\n new PairingCredentialRandomGenerationError({ operation: \"generate-id\", cause }),\n ),\n );\n const credential = yield* generatePairingToken;\n const isDevStartupToken = config.devUrl !== undefined && input?.purpose === \"startup\";\n const ttl =\n input?.ttl ??\n (isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);\n const now = yield* DateTime.now;\n const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });\n const issued: IssuedBootstrapCredential = {\n id,\n credential,\n ...(input?.label ? { label: input.label } : {}),\n ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),\n expiresAt,\n };\n const subject = input?.subject ?? \"one-time-token\";\n yield* pairingLinks\n .create({\n id,\n credential,\n method: \"one-time-token\",\n scopes: input?.scopes ?? AuthStandardClientScopes,\n subject,\n label: input?.label ?? null,\n proofKeyThumbprint: input?.proofKeyThumbprint ?? null,\n createdAt: now,\n expiresAt: expiresAt,\n })\n .pipe(\n Effect.mapError(\n (cause) =>\n new PairingCredentialIssueError({\n pairingLinkId: id,\n subject,\n ...(input?.label ? { label: input.label } : {}),\n cause,\n }),\n ),\n );\n yield* emitUpsert({\n id,\n scopes: input?.scopes ?? AuthStandardClientScopes,\n subject: input?.subject ?? \"one-time-token\",\n ...(input?.label ? { label: input.label } : {}),\n createdAt: now,\n expiresAt,\n });\n return issued;\n });\n\n const consume: PairingGrantStore[\"Service\"][\"consume\"] = Effect.fn(\"PairingGrantStore.consume\")(\n function* (credential, input) {\n const now = yield* DateTime.now;\n if (yield* consumeRotatingDesktopToken(credential, now.epochMilliseconds)) {\n return {\n method: \"desktop-bootstrap\",\n scopes: AuthStandardClientScopes,\n subject: \"desktop-bootstrap\",\n expiresAt: DateTime.add(now, {\n milliseconds: DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,\n }),\n } satisfies BootstrapGrant;\n }\n const seededResult: ConsumeResult = yield* Ref.modify(\n seededGrantsRef,\n (current): readonly [ConsumeResult, Map\u003cstring, StoredBootstrapGrant>] => {\n const grant = current.get(credential);\n if (!grant) {\n return [\n {\n _tag: \"error\",\n reason: \"not-found\",\n error: new UnknownBootstrapCredentialError({}),\n },\n current,\n ];\n }\n\n const next = new Map(current);\n if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {\n next.delete(credential);\n return [\n {\n _tag: \"error\",\n reason: \"expired\",\n error: new ExpiredBootstrapCredentialError({}),\n },\n next,\n ];\n }\n\n if (grant.proofKeyThumbprint && grant.proofKeyThumbprint !== input?.proofKeyThumbprint) {\n return [\n {\n _tag: \"error\",\n reason: \"not-found\",\n error: new BootstrapCredentialProofKeyMismatchError({}),\n },\n next,\n ];\n }\n\n if (\n (input?.requestedScopes !== undefined &&\n !input.requestedScopes.some((scope) => grant.scopes.includes(scope))) ||\n (input?.requiredScopes !== undefined &&\n !input.requiredScopes.every((scope) => grant.scopes.includes(scope)))\n ) {\n return [\n {\n _tag: \"error\",\n reason: \"scope-not-granted\",\n error: new BootstrapCredentialScopeNotGrantedError({}),\n },\n current,\n ];\n }\n\n const remainingUses = grant.remainingUses;\n if (typeof remainingUses === \"number\") {\n if (remainingUses \u003c= 1) {\n next.delete(credential);\n } else {\n next.set(credential, {\n ...grant,\n remainingUses: remainingUses - 1,\n });\n }\n }\n\n return [\n {\n _tag: \"success\",\n grant: {\n method: grant.method,\n scopes: grant.scopes,\n subject: grant.subject,\n ...(grant.label ? { label: grant.label } : {}),\n ...(grant.proofKeyThumbprint\n ? { proofKeyThumbprint: grant.proofKeyThumbprint }\n : {}),\n expiresAt: grant.expiresAt,\n } satisfies BootstrapGrant,\n },\n next,\n ];\n },\n );\n\n if (seededResult._tag === \"success\") {\n return seededResult.grant;\n }\n if (seededResult.reason !== \"not-found\") {\n return yield* seededResult.error;\n }\n\n // Only credentials in the issued pairing-code format are case-insensitive.\n const pairingCredential = PAIRING_TOKEN_PATTERN.test(credential)\n ? credential.toUpperCase()\n : credential;\n\n // Check scopes in the UPDATE so rejected requests cannot spend one-time links.\n const consumed = yield* pairingLinks\n .consumeAvailable({\n credential: pairingCredential,\n proofKeyThumbprint: input?.proofKeyThumbprint ?? null,\n ...(input?.requestedScopes !== undefined\n ? { requestedScopes: input.requestedScopes }\n : {}),\n ...(input?.requiredScopes !== undefined ? { requiredScopes: input.requiredScopes } : {}),\n consumedAt: now,\n now,\n })\n .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));\n\n if (Option.isSome(consumed)) {\n yield* emitRemoved(consumed.value.id);\n return {\n method: consumed.value.method,\n scopes: consumed.value.scopes,\n subject: consumed.value.subject,\n ...(consumed.value.label ? { label: consumed.value.label } : {}),\n ...(consumed.value.proofKeyThumbprint\n ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }\n : {}),\n expiresAt: consumed.value.expiresAt,\n } satisfies BootstrapGrant;\n }\n\n const matching = yield* pairingLinks\n .getByCredential({ credential: pairingCredential })\n .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));\n if (Option.isNone(matching)) {\n return yield* new UnknownBootstrapCredentialError({});\n }\n\n if (matching.value.revokedAt !== null) {\n return yield* new UnavailableBootstrapCredentialError({});\n }\n\n if (matching.value.consumedAt !== null) {\n return yield* new UnknownBootstrapCredentialError({});\n }\n\n if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {\n return yield* new ExpiredBootstrapCredentialError({});\n }\n\n if (\n matching.value.proofKeyThumbprint !== null &&\n matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint\n ) {\n return yield* new BootstrapCredentialProofKeyMismatchError({});\n }\n\n if (\n (input?.requestedScopes !== undefined &&\n !input.requestedScopes.some((scope) => matching.value.scopes.includes(scope))) ||\n (input?.requiredScopes !== undefined &&\n !input.requiredScopes.every((scope) => matching.value.scopes.includes(scope)))\n ) {\n return yield* new BootstrapCredentialScopeNotGrantedError({});\n }\n\n return yield* new UnavailableBootstrapCredentialError({});\n },\n );\n\n return PairingGrantStore.of({\n issueOneTimeToken,\n listActive,\n get streamChanges() {\n return Stream.fromPubSub(changesPubSub);\n },\n revoke,\n consume,\n });\n});\n\nexport const layer = Layer.effect(PairingGrantStore, make).pipe(\n Layer.provideMerge(AuthPairingLinks.layer),\n);\n","preview":null,"history":null,"version":"add1c7990f13c7d123ed0975004a8f24dfaac596"},"/_session?shell=1":null}