/** * ArkType schemas for the auth-broker wire protocol. * * Shared between the server (validates inbound request bodies) and the client * (validates responses from the broker). Schemas mirror the TypeScript types * in `./types.ts` 1:1; the types remain the source of truth for static typing, * and `Type` is asserted-compatible with them where possible. * * Response schemas accept keys they do not declare, and usage enums read a * value they do not know as `"unknown"`, so a client keeps working against a * newer broker. Request bodies the broker acts on use `"+": "reject"`: a broker * must not apply a write whose fields it cannot read. The observed-usage report * is the exception, since its unknown fields cannot change what gets recorded. * The OAuth credential schema keeps extra keys on writes too: it preserves * provider-specific extension fields so they round-trip through the broker * instead of being dropped (see below). */ import { type FluentType, type Type, type } from "@oh-my-pi/omptype"; import { type ApiKeyCredential, type AuthCredential, type AuthCredentialSnapshotEntry, type DisabledCredentialSummary, type OAuthCredential, REMOTE_REFRESH_SENTINEL, type RemoteOAuthCredential, type SnapshotCredential, } from "../auth-storage"; import { usageStatusSchema, usageUnitSchema } from "../usage"; import type { ClientUsageReportRequest, ClientUsageReportResponse, ClientUsageSummaryResponse, CredentialBlockDeleteRequest, CredentialBlockRequest, CredentialBlockResponse, CredentialBlockSnapshot, CredentialBlocksDeleteResponse, CredentialDisableResponse, CredentialRefreshResponse, CredentialUploadRequest, CredentialUploadResponse, DisabledCredentialsResponse, HealthzResponse, RefresherSchedule, SnapshotEntry, SnapshotResponse, SnapshotStreamEntryEvent, SnapshotStreamEvent, SnapshotStreamRemovedEvent, SnapshotStreamSnapshotEvent, UsageHistoryResponse, UsageResponse, UsageStaleResponse, } from "./types"; // ─── Credential payloads ───────────────────────────────────────────────────── /** Real OAuth credential (broker-side) — refresh token is the actual upstream value. */ export const oauthCredentialSchema: FluentType = type({ "apiEndpoint?": "string", type: "'oauth'", refresh: type("string").narrow( (value, ctx) => value !== REMOTE_REFRESH_SENTINEL || ctx.mustBe(`not equal to the remote sentinel (${REMOTE_REFRESH_SENTINEL})`), ), access: type("string").atLeastLength(1), expires: "number", "enterpriseUrl?": "string", "projectId?": "string", "email?": "string", "accountId?": "string", "orgId?": "string", "orgName?": "string", "region?": "string", "inferenceRegion?": "'global' | 'eu' | 'us'", "activeOrganizationId?": "string", "authorizedAt?": "number", "kiroClientId?": "string", "kiroClientSecret?": "string", "kiroOidcRegion?": "string", "kiroProfileArn?": "string", }); /** OAuth credential as it appears in broker snapshots — refresh replaced with sentinel. */ export const remoteOauthCredentialSchema: FluentType = type({ "apiEndpoint?": "string", type: "'oauth'", refresh: type.enumerated(REMOTE_REFRESH_SENTINEL), access: type("string").atLeastLength(1), expires: "number", "enterpriseUrl?": "string", "projectId?": "string", "email?": "string", "accountId?": "string", "orgId?": "string", "orgName?": "string", "region?": "string", "inferenceRegion?": "'global' | 'eu' | 'us'", "activeOrganizationId?": "string", "authorizedAt?": "number", "kiroClientId?": "string", // Redacted by `redactCredentialForWire`; a snapshot carrying it is rejected. "kiroClientSecret?": "undefined", "kiroOidcRegion?": "string", "kiroProfileArn?": "string", }); export const apiKeyCredentialSchema: FluentType = type({ "+": "reject", type: "'api_key'", key: type("string").atLeastLength(1), "source?": "'login'", }); /** Discriminated union accepted on POST /v1/credential (writes). */ export const writableAuthCredentialSchema: FluentType = oauthCredentialSchema.or(apiKeyCredentialSchema); /** Discriminated union returned in snapshots (refresh is sentinel for OAuth). */ export const snapshotCredentialSchema: FluentType = remoteOauthCredentialSchema.or( apiKeyCredentialSchema.onUndeclaredKey("ignore"), ); /** * Reads an enum a newer broker may extend: a value this client does not know * becomes `"unknown"` instead of failing the whole response. */ function readEnumOrUnknown(known: Type): FluentType { return type("string").pipe(value => (known.allows(value) ? value : "unknown")); } // ─── Snapshot ──────────────────────────────────────────────────────────────── export const credentialSnapshotEntrySchema: FluentType = type({ id: "number.integer", provider: type("string").atLeastLength(1), credential: snapshotCredentialSchema, identityKey: "string | null", }); export const credentialBlockSnapshotSchema: FluentType = type({ providerKey: type("string").atLeastLength(1), blockScope: "string", blockedUntilMs: "number", "updatedAtMs?": "number", }); export const snapshotEntrySchema: FluentType = type({ id: "number.integer", provider: type("string").atLeastLength(1), credential: snapshotCredentialSchema, identityKey: "string | null", rotatesInMs: "number | null", "blocks?": credentialBlockSnapshotSchema.array(), }); export const refresherScheduleSchema: FluentType = type({ enabled: "boolean", intervalMs: "number", skewMs: "number", nextSweepInMs: "number", }); export const snapshotResponseSchema: FluentType = type({ generation: "number.integer", generatedAt: "number", serverNowMs: "number", refresher: refresherScheduleSchema, credentials: snapshotEntrySchema.array(), }); // ─── Snapshot stream (SSE) ─────────────────────────────────────────────────── /** First frame on connect — full snapshot embedded inline with a `kind` tag. */ export const snapshotStreamSnapshotEventSchema: FluentType = type({ generation: "number.integer", generatedAt: "number", serverNowMs: "number", refresher: refresherScheduleSchema, credentials: snapshotEntrySchema.array(), kind: "'snapshot'", }); /** Per-credential upsert/refresh delta. */ export const snapshotStreamEntryEventSchema: FluentType = type({ kind: "'entry'", generation: "number.integer", serverNowMs: "number", refresher: refresherScheduleSchema, entry: snapshotEntrySchema, }); /** Per-credential delete delta. */ export const snapshotStreamRemovedEventSchema: FluentType = type({ kind: "'removed'", generation: "number.integer", serverNowMs: "number", refresher: refresherScheduleSchema, id: "number.integer", }); /** Discriminated union over every event frame the snapshot stream emits. */ export const snapshotStreamEventSchema: FluentType = snapshotStreamSnapshotEventSchema .or(snapshotStreamEntryEventSchema) .or(snapshotStreamRemovedEventSchema); // ─── Healthz ───────────────────────────────────────────────────────────────── export const healthzResponseSchema: FluentType = type({ ok: "boolean", "version?": "string", }); // ─── Usage ─────────────────────────────────────────────────────────────────── const usageWindowSchema = type({ id: "string", label: "string", "durationMs?": "number", "resetsAt?": "number", }); const usageAmountSchema = type({ "used?": "number", "limit?": "number", "remaining?": "number", "usedFraction?": "number", "remainingFraction?": "number", unit: readEnumOrUnknown(usageUnitSchema), }); const usageScopeSchema = type({ provider: "string", "accountId?": "string", "projectId?": "string", "orgId?": "string", "modelId?": "string", "tier?": "string", "windowId?": "string", "shared?": "boolean", "sharedGroup?": "string", }); const usageLimitSchema = type({ id: "string", label: "string", scope: usageScopeSchema, "window?": usageWindowSchema, amount: usageAmountSchema, "status?": readEnumOrUnknown(usageStatusSchema), "notes?": "string[]", }); const usageResetCreditsSchema = type({ availableCount: "number", "redeemableCount?": "number", "nextCreditId?": "string", "eligible?": "boolean", "reason?": "string", "cooldownUntil?": "string", "credits?": type({ "id?": "string", "title?": "string", "program?": "string", "remainingCount?": "number", "usable?": "boolean", "requiresLimit?": "boolean", "clears?": "string[]", "blocking?": "string[]", "usedFractions?": { "[string]": "number" }, "grantedAt?": "string", "expiresAt?": "string", "status?": "string", }).array(), }); const arkUsageReportSchema = type({ provider: "string", fetchedAt: "number", limits: usageLimitSchema.array(), "resetCredits?": usageResetCreditsSchema, "notes?": "string[]", "metadata?": { "[string]": "unknown" }, "raw?": "unknown", }); /** * Broker `/v1/usage` response. Reports are full {@link UsageReport}s minus the * heavy provider-specific `raw` field (the server strips it before send) — we * keep `raw` optional in the underlying schema so a misconfigured broker that * forgot to strip still validates. */ export const usageResponseSchema: Type = type({ generatedAt: "number", reports: arkUsageReportSchema.array(), }); const usageHistoryEntrySchema = type({ recordedAt: "number", provider: "string", accountKey: "string", "email?": "string", "accountId?": "string", limitId: "string", label: "string", "windowLabel?": "string", "usedFraction?": "number", "status?": readEnumOrUnknown(usageStatusSchema), "resetsAt?": "number", }); /** Broker `/v1/usage/history` response — recorded usage-limit snapshots, oldest first. */ export const usageHistoryResponseSchema: Type = type({ generatedAt: "number", entries: usageHistoryEntrySchema.array(), }); const observedUsageEntrySchema = type({ at: "number", provider: "string", model: "string", requests: "number", inputTokens: "number", outputTokens: "number", cacheReadTokens: "number", cacheWriteTokens: "number", costUsd: "number", }); /** Broker `POST /v1/usage/observed` request — one client's batched observed usage. */ export const clientUsageReportRequestSchema: FluentType = type({ installId: "string", "hostname?": "string", "app?": "string", entries: observedUsageEntrySchema.array(), }); export const clientUsageReportResponseSchema: FluentType = type({ ok: "boolean", }); const clientUsageClientSummarySchema = type({ installId: "string", "hostname?": "string", firstSeen: "number", lastSeen: "number", providers: type({ "app?": "string", provider: "string", requests: "number", inputTokens: "number", outputTokens: "number", cacheReadTokens: "number", cacheWriteTokens: "number", costUsd: "number", }).array(), }); /** Broker `GET /v1/usage/clients` response — per-client token burn aggregates. */ export const clientUsageSummaryResponseSchema: FluentType = type({ generatedAt: "number", clients: clientUsageClientSummarySchema.array(), }); // ─── Refresh ───────────────────────────────────────────────────────────────── export const credentialRefreshResponseSchema: FluentType = type({ entry: credentialSnapshotEntrySchema, }); // ─── Disable ───────────────────────────────────────────────────────────────── export const credentialDisableRequestSchema: FluentType<{ cause?: string }> = type({ "+": "reject", "cause?": "string", }); export const credentialDisableResponseSchema: FluentType = type({ ok: "boolean", }); /** One disabled-credential tombstone — identity + cause, never token material. */ export const disabledCredentialSummarySchema: FluentType = type({ id: "number.integer", provider: type("string").atLeastLength(1), type: "'oauth' | 'api_key'", "email?": "string", "accountId?": "string", "orgId?": "string", "orgName?": "string", cause: "string", "disabledAtMs?": "number", }); /** Broker `GET /v1/credentials/disabled` response. */ export const disabledCredentialsResponseSchema: FluentType = type({ generatedAt: "number", disabled: disabledCredentialSummarySchema.array(), }); // ─── Credential blocks ─────────────────────────────────────────────────────── export const credentialBlockRequestSchema: FluentType = credentialBlockSnapshotSchema.onUndeclaredKey("reject"); export const credentialBlockDeleteRequestSchema: FluentType = type({ "+": "reject", providerKey: type("string").atLeastLength(1), blockScope: "string", }); export const credentialBlockResponseSchema: FluentType = type({ ok: "boolean", }); export const credentialBlocksDeleteResponseSchema: FluentType = type({ ok: "boolean", }); export const usageStaleResponseSchema: FluentType = type({ ok: "boolean", }); // ─── Upload ────────────────────────────────────────────────────────────────── export const credentialUploadRequestSchema: FluentType = type({ "+": "reject", provider: type("string").atLeastLength(1), credential: writableAuthCredentialSchema, }); export const credentialUploadResponseSchema: FluentType = type({ entries: credentialSnapshotEntrySchema.array(), });