@agentproto/auth 1.0.3 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +26 -1
- package/dist/index.mjs +56 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -914,6 +914,31 @@ declare function setAuthProfileEnabled(id: string, enabled: boolean, deps: Profi
|
|
|
914
914
|
* Returns the updated (non-secret) profile.
|
|
915
915
|
*/
|
|
916
916
|
declare function setAuthProfileModels(id: string, curation: ModelCuration, deps: ProfileProvisionDeps): Promise<AuthProfile>;
|
|
917
|
+
/** Patch input for {@link updateAuthProfile}. Each field is tri-state:
|
|
918
|
+
* ABSENT leaves the current value untouched, `null` clears it, and a
|
|
919
|
+
* concrete value replaces it. At least one of `label` / `costBudget` must
|
|
920
|
+
* be present (absent from both is a no-op input, rejected rather than
|
|
921
|
+
* silently doing nothing). */
|
|
922
|
+
interface UpdateAuthProfileInput {
|
|
923
|
+
/** New display label, or `null` to clear it. */
|
|
924
|
+
label?: string | null;
|
|
925
|
+
/** New windowed spend cap, or `null` to clear it. */
|
|
926
|
+
costBudget?: CostBudget | null;
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* Update a profile's `label` and/or `costBudget` (WS-G5) — the two fields
|
|
930
|
+
* `profile-store.ts`'s schema already carries but never had a setter for.
|
|
931
|
+
* Metadata-only, mirroring {@link setAuthProfileEnabled} / {@link
|
|
932
|
+
* setAuthProfileModels}: NEVER touches `credentialRef`, `source`, or the
|
|
933
|
+
* credential store. `null` clears a field entirely (byte-identical to a
|
|
934
|
+
* profile that never had it); ABSENT leaves the current value untouched. A
|
|
935
|
+
* given `label` is trimmed and rejected if it becomes empty or exceeds
|
|
936
|
+
* {@link MAX_LABEL_LENGTH}; a given `costBudget` is validated against the
|
|
937
|
+
* same `costBudgetSchema` the on-disk file itself is parsed with. Throws
|
|
938
|
+
* {@link AuthProfileValidationError} for an unknown id, an empty patch, or a
|
|
939
|
+
* field that fails validation. Returns the updated (non-secret) profile.
|
|
940
|
+
*/
|
|
941
|
+
declare function updateAuthProfile(id: string, patch: UpdateAuthProfileInput, deps: ProfileProvisionDeps): Promise<AuthProfile>;
|
|
917
942
|
/** The result of {@link refreshAuthProfileModels} — the updated profile plus
|
|
918
943
|
* the diff against the previous allowlist, so a caller (CLI, MCP tool) can
|
|
919
944
|
* report exactly what changed without re-diffing itself. */
|
|
@@ -1067,4 +1092,4 @@ declare const BUILTIN_AUTH_PROVIDERS: readonly AuthProviderHandle[];
|
|
|
1067
1092
|
declare const SPEC_NAME = "agentauth";
|
|
1068
1093
|
declare const SPEC_VERSION = "v1";
|
|
1069
1094
|
|
|
1070
|
-
export { type AdapterAuthManifest, type AuthConfig, type AuthMethod, type AuthProfile, AuthProfileValidationError, type AuthProfilesFile, type AuthProviderDefinition, type AuthProviderFrontmatter, type AuthProviderHandle, type AuthProviderManifest, BUILTIN_AUTH_PROVIDERS, CeremonyRequiredError, type CostBudget, type CostBudgetScope, type CreateAuthProfileInput, type CreatedAuthProfile, CredentialBroker, type CredentialBrokerOptions, type CredentialIdentity, type CredentialStore, type DeletedAuthProfile, type DeviceCodeAuthConfig, type DiscoveredEndpoints, DiscoveryError, FLOW_ENGINES, FileStore, type FlowEngine, type FlowId, type FlowResult, type FlowRunOptions, type InstallConfig, KeychainStore, MemoryStore, type ModelCuration, type PATAuthConfig, type ProfileProvisionDeps, type RefreshAuthProfileModelsResult, type RunFlowOptions, SPEC_NAME, SPEC_VERSION, type ServiceAuthConfig, type StoreRef, type StoredCredential, type TokenStoreSpec, type ValidatedCreateInput, addAuthProfile, authConfigSchema, authProfilesPath, authProviderFrontmatterSchema, createAuthProfile, credentialIdentity, defineAuthProvider, deleteAuthProfile, deleteKeychainToken, deriveCredentialRef, discoverEndpoints, eligibleProfiles, fingerprintCredential, getAuthProfile, getAuthProvider, guildeAuthProvider, installConfigSchema, listAuthProfiles, listAuthProviderIds, listAuthProviders, loadAuthProfiles, methodsPresentable, parseAuthProviderManifest, parseAuthProviderManifestRaw, readKeychainToken, refreshAuthProfileModels, registerAuthProvider, removeAuthProfile, resolveAccount, resolveEndpoint, resolveStoreRef, runAuthFlow, setAuthProfileEnabled, setAuthProfileModels, tokenStoreSpecSchema, validateCreateInput, writeKeychainToken };
|
|
1095
|
+
export { type AdapterAuthManifest, type AuthConfig, type AuthMethod, type AuthProfile, AuthProfileValidationError, type AuthProfilesFile, type AuthProviderDefinition, type AuthProviderFrontmatter, type AuthProviderHandle, type AuthProviderManifest, BUILTIN_AUTH_PROVIDERS, CeremonyRequiredError, type CostBudget, type CostBudgetScope, type CreateAuthProfileInput, type CreatedAuthProfile, CredentialBroker, type CredentialBrokerOptions, type CredentialIdentity, type CredentialStore, type DeletedAuthProfile, type DeviceCodeAuthConfig, type DiscoveredEndpoints, DiscoveryError, FLOW_ENGINES, FileStore, type FlowEngine, type FlowId, type FlowResult, type FlowRunOptions, type InstallConfig, KeychainStore, MemoryStore, type ModelCuration, type PATAuthConfig, type ProfileProvisionDeps, type RefreshAuthProfileModelsResult, type RunFlowOptions, SPEC_NAME, SPEC_VERSION, type ServiceAuthConfig, type StoreRef, type StoredCredential, type TokenStoreSpec, type UpdateAuthProfileInput, type ValidatedCreateInput, addAuthProfile, authConfigSchema, authProfilesPath, authProviderFrontmatterSchema, createAuthProfile, credentialIdentity, defineAuthProvider, deleteAuthProfile, deleteKeychainToken, deriveCredentialRef, discoverEndpoints, eligibleProfiles, fingerprintCredential, getAuthProfile, getAuthProvider, guildeAuthProvider, installConfigSchema, listAuthProfiles, listAuthProviderIds, listAuthProviders, loadAuthProfiles, methodsPresentable, parseAuthProviderManifest, parseAuthProviderManifestRaw, readKeychainToken, refreshAuthProfileModels, registerAuthProvider, removeAuthProfile, resolveAccount, resolveEndpoint, resolveStoreRef, runAuthFlow, setAuthProfileEnabled, setAuthProfileModels, tokenStoreSpecSchema, updateAuthProfile, validateCreateInput, writeKeychainToken };
|
package/dist/index.mjs
CHANGED
|
@@ -1458,6 +1458,61 @@ async function setAuthProfileModels(id, curation, deps) {
|
|
|
1458
1458
|
await deps.addProfile(updated);
|
|
1459
1459
|
return updated;
|
|
1460
1460
|
}
|
|
1461
|
+
var MAX_LABEL_LENGTH = 200;
|
|
1462
|
+
async function updateAuthProfile(id, patch, deps) {
|
|
1463
|
+
const trimmed = (id ?? "").trim();
|
|
1464
|
+
if (!trimmed) throw new AuthProfileValidationError("id is required");
|
|
1465
|
+
const hasLabel = Object.prototype.hasOwnProperty.call(patch, "label");
|
|
1466
|
+
const hasCostBudget = Object.prototype.hasOwnProperty.call(patch, "costBudget");
|
|
1467
|
+
if (!hasLabel && !hasCostBudget) {
|
|
1468
|
+
throw new AuthProfileValidationError(
|
|
1469
|
+
"at least one of label or costBudget is required"
|
|
1470
|
+
);
|
|
1471
|
+
}
|
|
1472
|
+
let nextLabel;
|
|
1473
|
+
if (hasLabel && patch.label !== null) {
|
|
1474
|
+
if (typeof patch.label !== "string") {
|
|
1475
|
+
throw new AuthProfileValidationError("label must be a string or null");
|
|
1476
|
+
}
|
|
1477
|
+
nextLabel = patch.label.trim();
|
|
1478
|
+
if (!nextLabel) {
|
|
1479
|
+
throw new AuthProfileValidationError("label must not be blank; pass null to clear it");
|
|
1480
|
+
}
|
|
1481
|
+
if (nextLabel.length > MAX_LABEL_LENGTH) {
|
|
1482
|
+
throw new AuthProfileValidationError(
|
|
1483
|
+
`label must be at most ${MAX_LABEL_LENGTH} characters`
|
|
1484
|
+
);
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
let nextCostBudget;
|
|
1488
|
+
if (hasCostBudget && patch.costBudget !== null) {
|
|
1489
|
+
const parsed = costBudgetSchema.safeParse(patch.costBudget);
|
|
1490
|
+
if (!parsed.success) {
|
|
1491
|
+
throw new AuthProfileValidationError(
|
|
1492
|
+
`costBudget is invalid: ${parsed.error.issues.map((i) => i.message).join(", ")}`
|
|
1493
|
+
);
|
|
1494
|
+
}
|
|
1495
|
+
nextCostBudget = parsed.data;
|
|
1496
|
+
}
|
|
1497
|
+
const profile = await deps.getProfile(trimmed);
|
|
1498
|
+
if (!profile) {
|
|
1499
|
+
throw new AuthProfileValidationError(`no profile with id "${trimmed}"`);
|
|
1500
|
+
}
|
|
1501
|
+
const { label: _dropLabel, costBudget: _dropCostBudget, ...rest } = profile;
|
|
1502
|
+
const updated = { ...rest };
|
|
1503
|
+
if (hasLabel) {
|
|
1504
|
+
if (nextLabel !== void 0) updated.label = nextLabel;
|
|
1505
|
+
} else if (profile.label !== void 0) {
|
|
1506
|
+
updated.label = profile.label;
|
|
1507
|
+
}
|
|
1508
|
+
if (hasCostBudget) {
|
|
1509
|
+
if (nextCostBudget !== void 0) updated.costBudget = nextCostBudget;
|
|
1510
|
+
} else if (profile.costBudget !== void 0) {
|
|
1511
|
+
updated.costBudget = profile.costBudget;
|
|
1512
|
+
}
|
|
1513
|
+
await deps.addProfile(updated);
|
|
1514
|
+
return updated;
|
|
1515
|
+
}
|
|
1461
1516
|
async function refreshAuthProfileModels(id, currentIds, deps) {
|
|
1462
1517
|
const trimmed = (id ?? "").trim();
|
|
1463
1518
|
if (!trimmed) throw new AuthProfileValidationError("id is required");
|
|
@@ -1506,6 +1561,6 @@ function eligibleProfiles(profiles, manifest, route) {
|
|
|
1506
1561
|
var SPEC_NAME = "agentauth";
|
|
1507
1562
|
var SPEC_VERSION = "v1";
|
|
1508
1563
|
|
|
1509
|
-
export { AuthProfileValidationError, BUILTIN_AUTH_PROVIDERS, CeremonyRequiredError, CredentialBroker, DiscoveryError, FLOW_ENGINES, FileStore, KeychainStore, MemoryStore, SPEC_NAME, SPEC_VERSION, addAuthProfile, authConfigSchema, authProfilesPath, authProviderFrontmatterSchema, createAuthProfile, credentialIdentity, defineAuthProvider, deleteAuthProfile, deleteKeychainToken, deriveCredentialRef, discoverEndpoints, eligibleProfiles, fingerprintCredential, getAuthProfile, getAuthProvider, guildeAuthProvider, installConfigSchema, listAuthProfiles, listAuthProviderIds, listAuthProviders, loadAuthProfiles, methodsPresentable, parseAuthProviderManifest, parseAuthProviderManifestRaw, readKeychainToken, refreshAuthProfileModels, registerAuthProvider, removeAuthProfile, resolveAccount, resolveEndpoint, resolveStoreRef, runAuthFlow, setAuthProfileEnabled, setAuthProfileModels, tokenStoreSpecSchema, validateCreateInput, writeKeychainToken };
|
|
1564
|
+
export { AuthProfileValidationError, BUILTIN_AUTH_PROVIDERS, CeremonyRequiredError, CredentialBroker, DiscoveryError, FLOW_ENGINES, FileStore, KeychainStore, MemoryStore, SPEC_NAME, SPEC_VERSION, addAuthProfile, authConfigSchema, authProfilesPath, authProviderFrontmatterSchema, createAuthProfile, credentialIdentity, defineAuthProvider, deleteAuthProfile, deleteKeychainToken, deriveCredentialRef, discoverEndpoints, eligibleProfiles, fingerprintCredential, getAuthProfile, getAuthProvider, guildeAuthProvider, installConfigSchema, listAuthProfiles, listAuthProviderIds, listAuthProviders, loadAuthProfiles, methodsPresentable, parseAuthProviderManifest, parseAuthProviderManifestRaw, readKeychainToken, refreshAuthProfileModels, registerAuthProvider, removeAuthProfile, resolveAccount, resolveEndpoint, resolveStoreRef, runAuthFlow, setAuthProfileEnabled, setAuthProfileModels, tokenStoreSpecSchema, updateAuthProfile, validateCreateInput, writeKeychainToken };
|
|
1510
1565
|
//# sourceMappingURL=index.mjs.map
|
|
1511
1566
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schema.ts","../src/define-auth-provider.ts","../src/manifest.ts","../src/builtins.ts","../src/registry.ts","../src/http.ts","../src/discover.ts","../src/token-store.ts","../src/store/keychain-store.ts","../src/store/resolve-ref.ts","../src/flow-engines/pat.ts","../src/flow-engines/device-grant.ts","../src/flow-engines/service-auth.ts","../src/flow-engines/device-code.ts","../src/flow-engines/index.ts","../src/run-flow.ts","../src/store/memory-store.ts","../src/store/file-store.ts","../src/broker.ts","../src/profile-store.ts","../src/profile-provision.ts","../src/eligibility.ts","../src/index.ts"],"names":["z","resolve","promisify","execFile","DEFAULT_POLL_INTERVAL_S","keyOf","headers","readFile","mkdir","writeFile","profile","updated"],"mappings":";;;;;;;;;;;;;;;;AAUO,IAAM,oBAAA,GAAuB,EACjC,MAAA,CAAO;AAAA,EACN,QAAA,EAAU,CAAA,CAAE,MAAA,EAAO,CAAE,IAAI,CAAC,CAAA;AAAA,EAC1B,MAAM,CAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAC,EAAE,QAAA,EAAS;AAAA,EACjC,SAAS,CAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAC,EAAE,QAAA;AAC7B,CAAC,EACA,MAAA;AAEI,IAAM,mBAAA,GAAsB,EAChC,MAAA,CAAO;AAAA,EACN,IAAA,EAAM,CAAA,CAAE,OAAA,CAAQ,KAAK,CAAA;AAAA,EACrB,UAAA,EAAY;AACd,CAAC,EACA,MAAA,EAAO;AAEH,IAAM,uBAAA,GAA0B,EACpC,MAAA,CAAO;AAAA,EACN,IAAA,EAAM,CAAA,CAAE,OAAA,CAAQ,cAAc,CAAA;AAAA,EAC9B,UAAU,CAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAC,EAAE,QAAA,EAAS;AAAA,EACrC,WAAW,CAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAC,EAAE,QAAA,EAAS;AAAA,EACtC,UAAA,EAAY;AACd,CAAC,EACA,MAAA,EAAO;AAEH,IAAM,0BAAA,GAA6B,EACvC,MAAA,CAAO;AAAA,EACN,IAAA,EAAM,CAAA,CAAE,OAAA,CAAQ,aAAa,CAAA;AAAA,EAC7B,UAAU,CAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAC,EAAE,QAAA,EAAS;AAAA,EACrC,OAAO,CAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAC,EAAE,QAAA,EAAS;AAAA,EAClC,aAAa,CAAA,CAAE,MAAA,GAAS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,KAAK,CAAA;AAClD,EAAA,OAAO,QAAA,CAAS,MAAA;AAAA,IACd,CAAA,CAAA,KAAK,CAAC,CAAA,CAAE,QAAA,IAAY,CAAA,CAAE,aAAa,QAAA,IAAY,OAAA,CAAQ,QAAA,CAAS,CAAA,CAAE,MAAM;AAAA,GAC1E;AACF;;;ACuCO,IAAM,SAAA,GAAY;AAClB,IAAM,YAAA,GAAe","file":"index.mjs","sourcesContent":["/**\n * AIP-50 auth-provider frontmatter / literal Zod schema.\n *\n * Single source of truth for both authoring paths: `defineAuthProvider`\n * (TS literal) and `parseAuthProviderManifest` (.md) run this same schema,\n * so a malformed literal and a malformed manifest fail identically.\n */\n\nimport { z } from \"zod\"\n\nexport const tokenStoreSpecSchema = z\n .object({\n keychain: z.string().min(1),\n path: z.string().min(1).optional(),\n account: z.string().min(1).optional(),\n })\n .strict()\n\nexport const patAuthConfigSchema = z\n .object({\n flow: z.literal(\"pat\"),\n tokenStore: tokenStoreSpecSchema,\n })\n .strict()\n\nexport const serviceAuthConfigSchema = z\n .object({\n flow: z.literal(\"service-auth\"),\n clientId: z.string().min(1).optional(),\n loginHint: z.string().min(1).optional(),\n tokenStore: tokenStoreSpecSchema,\n })\n .strict()\n\nexport const deviceCodeAuthConfigSchema = z\n .object({\n flow: z.literal(\"device-code\"),\n clientId: z.string().min(1).optional(),\n scope: z.string().min(1).optional(),\n deviceLabel: z.string().min(1).optional(),\n tokenStore: tokenStoreSpecSchema,\n })\n .strict()\n\nexport const authConfigSchema = z.discriminatedUnion(\"flow\", [\n patAuthConfigSchema,\n serviceAuthConfigSchema,\n deviceCodeAuthConfigSchema,\n])\n\nexport const installConfigSchema = z\n .object({\n sealKey: z.string().min(1),\n secretBacked: z.string().min(1),\n })\n .strict()\n\nexport const authProviderFrontmatterSchema = z\n .object({\n id: z.string().min(2).max(80),\n description: z.string().min(1).max(2000),\n apiBase: z.string().url(),\n auth: authConfigSchema,\n install: installConfigSchema.optional(),\n // Recommended values \"tunnel\" | \"api\" | \"mcp\" — free-form allowed, not an enum.\n audience: z.string().min(1).optional(),\n })\n .strict()\n .describe(\n \"AIP-50 auth-provider manifest: how a CLI tool authenticates to an API server and (optionally) where to call the AIP-19 provision endpoints.\",\n )\n\nexport type AuthProviderFrontmatter = z.infer<typeof authProviderFrontmatterSchema>\n","/**\n * `defineAuthProvider` — TS-literal authoring path for an auth-provider.\n *\n * Built on `createDoctype` so it gets the cross-AIP invariants: id-pattern,\n * ≤2000-char description, frozen handle, canonical error prefix. Field-level\n * validation uses the shared Zod from `./schema.ts`, so a malformed literal\n * fails with the same diagnostic as a malformed `.md`.\n */\n\nimport { createDoctype } from \"@agentproto/define-doctype\"\nimport { authProviderFrontmatterSchema } from \"./schema.js\"\nimport type { AuthProviderDefinition, AuthProviderHandle } from \"./types.js\"\n\nexport const defineAuthProvider = createDoctype<\n AuthProviderDefinition,\n AuthProviderHandle\n>({\n aip: 50,\n name: \"authProvider\",\n validate(def) {\n const result = authProviderFrontmatterSchema.safeParse(def)\n if (!result.success) {\n throw new Error(\n `defineAuthProvider (AIP-50): ${result.error.issues\n .map((i) => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \")}`,\n )\n }\n },\n build(def) {\n return {\n ...def,\n auth: Object.freeze({ ...def.auth }),\n install: def.install ? Object.freeze({ ...def.install }) : undefined,\n }\n },\n})\n","/**\n * `.md` authoring path for an auth-provider — parse a frontmatter manifest\n * into a frozen handle. Mirrors `parseRecipeManifest` from AIP-19: gray-matter\n * splits the frontmatter, the shared Zod validates it, `defineAuthProvider`\n * builds the handle so both authoring paths converge on one validated shape.\n *\n * This parser is the extension seam: a host reads its own external `.md`\n * manifests (e.g. vendor-shipped `guilde.auth.md`) and registers them without\n * editing this package.\n */\n\nimport matter from \"gray-matter\"\nimport {\n authProviderFrontmatterSchema,\n type AuthProviderFrontmatter,\n} from \"./schema.js\"\nimport { defineAuthProvider } from \"./define-auth-provider.js\"\nimport type { AuthProviderHandle } from \"./types.js\"\n\nexport interface AuthProviderManifest {\n frontmatter: AuthProviderFrontmatter\n body: string\n}\n\nexport function parseAuthProviderManifestRaw(\n source: string,\n): AuthProviderManifest {\n const parsed = matter(source)\n if (Object.keys(parsed.data).length === 0) {\n throw new Error(\"parseAuthProviderManifest: missing or empty frontmatter\")\n }\n const result = authProviderFrontmatterSchema.safeParse(parsed.data)\n if (!result.success) {\n throw new Error(\n `parseAuthProviderManifest: invalid frontmatter — ${result.error.issues\n .map((i) => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \")}`,\n )\n }\n return { frontmatter: result.data, body: parsed.content }\n}\n\n/** Parse an auth-provider `.md` straight to a frozen handle. */\nexport function parseAuthProviderManifest(source: string): AuthProviderHandle {\n const { frontmatter } = parseAuthProviderManifestRaw(source)\n return defineAuthProvider(frontmatter)\n}\n","/**\n * Builtin auth-provider manifests — shipped as TS literals so they bundle\n * into the tsup output with zero filesystem reads at runtime. A host adds more\n * by parsing its own `.md` with `parseAuthProviderManifest` and registering\n * the result via `registerAuthProvider`.\n */\n\nimport { defineAuthProvider } from \"./define-auth-provider.js\"\nimport type { AuthProviderHandle } from \"./types.js\"\n\n/** Guilde AI company platform.\n *\n * Authenticates via the AIP-50 service-auth claim ceremony: browser opens,\n * user clicks Approve, bureau stores the oat_* access token.\n * Discovery from /.well-known/oauth-protected-resource supplies live endpoints;\n * the static fields below are the offline fallback. */\nexport const guildeAuthProvider = defineAuthProvider({\n id: \"guilde\",\n description:\n \"Guilde AI company platform. Authenticate via a browser-approve flow — no key to paste.\",\n apiBase: \"https://api.guilde.work\",\n audience: \"api\",\n auth: {\n flow: \"service-auth\",\n clientId: \"agentproto-cli\",\n tokenStore: {\n keychain: \"bureau-guilde\",\n account: \"{server}\",\n },\n },\n install: {\n sealKey: \"/guilde/api/v1/connectors/seal-key\",\n secretBacked: \"/guilde/api/v1/guilds/{guildId}/connectors/secret-backed\",\n },\n})\n\nexport const BUILTIN_AUTH_PROVIDERS: readonly AuthProviderHandle[] = [\n guildeAuthProvider,\n]\n","/**\n * Auth-provider registry — id → handle lookup, pre-seeded with builtins.\n *\n * Mirrors the provision-recipe registry shape (AIP-19). Re-registering an id\n * overrides it (last write wins), so a host can shadow a builtin.\n */\n\nimport { BUILTIN_AUTH_PROVIDERS } from \"./builtins.js\"\nimport type { AuthProviderHandle } from \"./types.js\"\n\nconst _registry = new Map<string, AuthProviderHandle>()\nfor (const p of BUILTIN_AUTH_PROVIDERS) _registry.set(p.id, p)\n\nexport function registerAuthProvider(provider: AuthProviderHandle): void {\n _registry.set(provider.id, provider)\n}\n\nexport function getAuthProvider(id: string): AuthProviderHandle | undefined {\n return _registry.get(id)\n}\n\nexport function listAuthProviders(): AuthProviderHandle[] {\n return [..._registry.values()]\n}\n\nexport function listAuthProviderIds(): string[] {\n return [..._registry.keys()]\n}\n","/**\n * Internal HTTP helpers — not part of the public API.\n *\n * Every network call in this package (discovery, the claim ceremony, token\n * refresh) must be bounded: a hung or slow server MUST NOT stall the CLI\n * indefinitely. `deadlineSignal` combines an optional caller `AbortSignal`\n * with a timeout into one signal to hand to `fetch`.\n *\n * Implemented with a plain `AbortController` + `setTimeout` rather than\n * `AbortSignal.any`/`AbortSignal.timeout` so it works on every runtime that\n * ships `fetch`, without assuming a specific Node minor.\n */\n\n/** Default per-request timeout. Discovery and token calls are small JSON\n * round-trips; 10s is generous without hanging an interactive CLI. */\nexport const DEFAULT_HTTP_TIMEOUT_MS = 10_000\n\n/**\n * AIP-50 §Security: discovery and auth requests MUST use HTTPS, to defeat\n * MITM/TOCTOU on the `.well-known` and token endpoints. Loopback http is\n * allowed — it isn't network-exposed — so local development against a dev\n * server keeps working. Throws on any other insecure URL.\n */\nexport function assertSecureUrl(url: string): void {\n let u: URL\n try {\n u = new URL(url)\n } catch {\n throw new Error(`invalid URL: ${url}`)\n }\n if (u.protocol === \"https:\") return\n const host = u.hostname\n const isLoopback =\n host === \"localhost\" ||\n host === \"127.0.0.1\" ||\n host === \"::1\" ||\n host === \"[::1]\" ||\n host.endsWith(\".localhost\")\n if (u.protocol === \"http:\" && isLoopback) return\n throw new Error(\n `insecure URL '${url}' — AIP-50 requires HTTPS for discovery/auth ` +\n `(loopback http is allowed for local development).`,\n )\n}\n\nexport interface DeadlineHandle {\n /** Signal to pass to `fetch(url, { signal })`. */\n signal: AbortSignal\n /** Cancel the timer + detach the outer listener once the request settles.\n * ALWAYS call this in a `finally` to avoid a dangling timer/listener. */\n clear: () => void\n}\n\n/**\n * Build an `AbortSignal` that fires when EITHER the timeout elapses or the\n * caller's `outer` signal aborts.\n */\nexport function deadlineSignal(\n timeoutMs: number,\n outer?: AbortSignal,\n): DeadlineHandle {\n const ctrl = new AbortController()\n const onAbort = () => ctrl.abort(outer?.reason)\n\n if (outer) {\n if (outer.aborted) ctrl.abort(outer.reason)\n else outer.addEventListener(\"abort\", onAbort, { once: true })\n }\n\n const timer = setTimeout(\n () => ctrl.abort(new Error(`request timed out after ${timeoutMs}ms`)),\n timeoutMs,\n )\n // Don't let a pending timeout keep the process alive on its own.\n if (typeof timer !== \"number\") timer.unref()\n\n return {\n signal: ctrl.signal,\n clear: () => {\n clearTimeout(timer)\n outer?.removeEventListener(\"abort\", onAbort)\n },\n }\n}\n\n/** `fetch` bounded by `deadlineSignal`. Merges any caller-supplied\n * `init.signal` with the timeout. */\nexport async function fetchWithDeadline(\n url: string,\n init: RequestInit = {},\n timeoutMs: number = DEFAULT_HTTP_TIMEOUT_MS,\n): Promise<Response> {\n const { signal, clear } = deadlineSignal(timeoutMs, init.signal ?? undefined)\n try {\n return await fetch(url, { ...init, signal })\n } finally {\n clear()\n }\n}\n","/**\n * Two-hop discovery per the auth.md standard (AIP-50 §Discovery algorithm),\n * with a second strategy for hosts that don't speak auth.md.\n *\n * Strategy 1 (OAuth PRM chain):\n * Hop 1: GET {apiBase}/.well-known/oauth-protected-resource (PRM, RFC 8414)\n * → extract authorization_servers[0] as authServerBase\n * Hop 2: GET {authServerBase}/.well-known/oauth-authorization-server (AS metadata)\n * → extract token_endpoint + agent_auth block\n *\n * Strategy 2 (agentproto-host.json), tried when strategy 1 fails:\n * GET {apiBase}/.well-known/agentproto-host.json\n * → extract device_authorization_endpoint + token_endpoint\n *\n * Callers MUST catch DiscoveryError and fall back to static manifest config —\n * discovery failures are common (server predates auth.md) and MUST NOT prevent\n * the PAT or other static flows from working.\n */\n\nimport { z } from \"zod\"\nimport type { DiscoveredEndpoints } from \"./types.js\"\nimport { fetchWithDeadline, assertSecureUrl } from \"./http.js\"\n\nexport class DiscoveryError extends Error {\n readonly serverUrl: string\n constructor(message: string, serverUrl: string) {\n super(`DiscoveryError (${serverUrl}): ${message}`)\n this.name = \"DiscoveryError\"\n this.serverUrl = serverUrl\n }\n}\n\n// Discovery JSON is server-controlled, so it's validated rather than asserted.\n// Everything is optional + `.loose()`: the document evolves, and the required\n// fields are enforced explicitly below with precise DiscoveryError messages.\nconst prmSchema = z\n .object({\n resource: z.string().optional(),\n resource_name: z.string().optional(),\n authorization_servers: z.array(z.string()).optional(),\n scopes_supported: z.array(z.string()).optional(),\n bearer_methods_supported: z.array(z.string()).optional(),\n })\n .loose()\n\nconst asMetaSchema = z\n .object({\n issuer: z.string().optional(),\n token_endpoint: z.string().optional(),\n revocation_endpoint: z.string().optional(),\n device_authorization_endpoint: z.string().optional(),\n grant_types_supported: z.array(z.string()).optional(),\n agent_auth: z\n .object({\n skill: z.string().optional(),\n identity_endpoint: z.string().optional(),\n claim_endpoint: z.string().optional(),\n events_endpoint: z.string().optional(),\n identity_types_supported: z.array(z.string()).optional(),\n identity_assertion: z\n .object({ assertion_types_supported: z.array(z.string()).optional() })\n .loose()\n .optional(),\n })\n .loose()\n .optional(),\n })\n .loose()\n\nconst hostJsonSchema = z\n .object({\n device_authorization_endpoint: z.string().optional(),\n token_endpoint: z.string().optional(),\n revocation_endpoint: z.string().optional(),\n })\n .loose()\n\ntype PRMShape = z.infer<typeof prmSchema>\ntype ASMetaShape = z.infer<typeof asMetaSchema>\ntype HostJsonShape = z.infer<typeof hostJsonSchema>\n\nexport interface DiscoverOptions {\n /** Abort the discovery fetches (e.g. on user Ctrl-C). */\n signal?: AbortSignal\n /** Per-hop timeout. Defaults to DEFAULT_HTTP_TIMEOUT_MS. */\n timeoutMs?: number\n}\n\nasync function discoverViaPRM(\n base: string,\n fetchOpts: RequestInit,\n opts: DiscoverOptions,\n): Promise<DiscoveredEndpoints> {\n // Hop 1 — PRM\n const prmUrl = `${base}/.well-known/oauth-protected-resource`\n let prm: PRMShape\n try {\n assertSecureUrl(prmUrl)\n const res = await fetchWithDeadline(prmUrl, fetchOpts, opts.timeoutMs)\n if (!res.ok) {\n throw new DiscoveryError(\n `PRM returned ${res.status} ${res.statusText}`,\n base,\n )\n }\n prm = prmSchema.parse(await res.json())\n } catch (err) {\n if (err instanceof DiscoveryError) throw err\n throw new DiscoveryError(`PRM fetch failed: ${err}`, base)\n }\n\n const authServerBase = prm.authorization_servers?.[0]?.replace(/\\/$/, \"\")\n if (!authServerBase) {\n throw new DiscoveryError(\n \"PRM missing authorization_servers[0]\",\n base,\n )\n }\n\n // Hop 2 — AS metadata\n const asUrl = `${authServerBase}/.well-known/oauth-authorization-server`\n let as: ASMetaShape\n try {\n assertSecureUrl(asUrl)\n const res = await fetchWithDeadline(asUrl, fetchOpts, opts.timeoutMs)\n if (!res.ok) {\n throw new DiscoveryError(\n `AS metadata returned ${res.status} ${res.statusText}`,\n base,\n )\n }\n as = asMetaSchema.parse(await res.json())\n } catch (err) {\n if (err instanceof DiscoveryError) throw err\n throw new DiscoveryError(`AS metadata fetch failed: ${err}`, base)\n }\n\n const tokenEndpoint = as.token_endpoint\n const identityEndpoint = as.agent_auth?.identity_endpoint\n if (!tokenEndpoint) {\n throw new DiscoveryError(\"AS metadata missing token_endpoint\", base)\n }\n if (!identityEndpoint) {\n throw new DiscoveryError(\n \"AS metadata missing agent_auth.identity_endpoint\",\n base,\n )\n }\n\n return {\n resource: prm.resource ?? base,\n resourceName: prm.resource_name,\n authServerBase,\n tokenEndpoint,\n revocationEndpoint: as.revocation_endpoint,\n identityEndpoint,\n claimEndpoint: as.agent_auth?.claim_endpoint,\n deviceAuthorizationEndpoint: as.device_authorization_endpoint,\n identityTypesSupported: as.agent_auth?.identity_types_supported ?? [],\n grantTypesSupported: as.grant_types_supported ?? [],\n }\n}\n\nasync function discoverViaHostJson(\n base: string,\n fetchOpts: RequestInit,\n opts: DiscoverOptions,\n): Promise<DiscoveredEndpoints> {\n const url = `${base}/.well-known/agentproto-host.json`\n let doc: HostJsonShape\n try {\n assertSecureUrl(url)\n const res = await fetchWithDeadline(url, fetchOpts, opts.timeoutMs)\n if (!res.ok) {\n throw new DiscoveryError(\n `agentproto-host.json returned ${res.status} ${res.statusText}`,\n base,\n )\n }\n doc = hostJsonSchema.parse(await res.json())\n } catch (err) {\n if (err instanceof DiscoveryError) throw err\n throw new DiscoveryError(`agentproto-host.json fetch failed: ${err}`, base)\n }\n\n if (!doc.token_endpoint) {\n throw new DiscoveryError(\n \"agentproto-host.json missing token_endpoint\",\n base,\n )\n }\n if (!doc.device_authorization_endpoint) {\n throw new DiscoveryError(\n \"agentproto-host.json missing device_authorization_endpoint\",\n base,\n )\n }\n\n return {\n resource: base,\n authServerBase: base,\n tokenEndpoint: doc.token_endpoint,\n revocationEndpoint: doc.revocation_endpoint,\n deviceAuthorizationEndpoint: doc.device_authorization_endpoint,\n identityTypesSupported: [],\n grantTypesSupported: [],\n }\n}\n\nexport async function discoverEndpoints(\n apiBase: string,\n opts: DiscoverOptions = {},\n): Promise<DiscoveredEndpoints> {\n const base = apiBase.replace(/\\/$/, \"\")\n // AIP-50 §Security: HTTPS only (loopback exempt for dev), and never follow\n // redirects on discovery — a 3xx is treated as a failure, not chased to a\n // potentially-rogue endpoint.\n const fetchOpts: RequestInit = {\n signal: opts.signal,\n redirect: \"manual\",\n }\n\n try {\n return await discoverViaPRM(base, fetchOpts, opts)\n } catch (prmErr) {\n // A caller-initiated abort is terminal — don't fire a second round of\n // requests on a signal that has already aborted (its \"abort\" event has\n // already fired once and a fresh listener on it will never see it again,\n // hanging the fallback forever).\n if (opts.signal?.aborted) throw prmErr\n // Second strategy: a host that doesn't speak the auth.md PRM chain may\n // still expose device-code endpoints via agentproto-host.json. If that\n // also fails, surface the ORIGINAL PRM error — it's almost always the\n // more informative one (host.json 404s are the common case).\n try {\n return await discoverViaHostJson(base, fetchOpts, opts)\n } catch {\n throw prmErr\n }\n }\n}\n","/**\n * Keychain helpers — read/write a token in the platform Keychain.\n *\n * Uses the macOS `security` CLI. On non-macOS hosts, callers should swap this\n * module for a platform-appropriate equivalent (libsecret on Linux, Credential\n * Manager on Windows).\n */\n\nimport { execFile } from \"node:child_process\"\nimport { promisify } from \"node:util\"\n\nconst exec = promisify(execFile)\n\n/**\n * Guard the macOS-only backend. Without this, `readKeychainToken` would swallow\n * the missing-`security` error and return undefined on Linux/Windows — making a\n * stored credential look absent and re-prompting on every run — while\n * `writeKeychainToken` would throw an opaque ENOENT. Fail loudly and clearly\n * instead, until a libsecret / Credential Manager backend exists.\n */\nfunction assertKeychainSupported(): void {\n if (process.platform !== \"darwin\") {\n throw new Error(\n `@agentproto/auth token-store: the Keychain backend only supports macOS ` +\n `(got platform \"${process.platform}\"). Provide a libsecret (Linux) or ` +\n `Credential Manager (Windows) implementation to run here.`,\n )\n }\n}\n\n/** Substitute `{server}` template in a tokenStore account spec. */\nexport function resolveAccount(\n account: string | undefined,\n server: string,\n): string {\n if (!account) return server\n return account.replace(\"{server}\", server)\n}\n\n/** Read a token from the Keychain. Returns undefined if not found. */\nexport async function readKeychainToken(\n service: string,\n account: string,\n): Promise<string | undefined> {\n assertKeychainSupported()\n try {\n const { stdout } = await exec(\"security\", [\n \"find-generic-password\",\n \"-s\",\n service,\n \"-a\",\n account,\n \"-w\",\n ])\n const t = stdout.replace(/\\n$/, \"\")\n return t || undefined\n } catch {\n return undefined\n }\n}\n\n/** Write a token to the Keychain (-U updates in place). */\nexport async function writeKeychainToken(\n service: string,\n account: string,\n token: string,\n): Promise<void> {\n assertKeychainSupported()\n await exec(\"security\", [\n \"add-generic-password\",\n \"-U\",\n \"-s\",\n service,\n \"-a\",\n account,\n \"-w\",\n token,\n \"-D\",\n \"agentproto auth token\",\n ])\n}\n\n/** Remove a token from the Keychain. Returns true if an entry was deleted,\n * false when none existed (a delete of an absent entry is not an error —\n * the desired end state, \"no credential at this slot\", already holds). */\nexport async function deleteKeychainToken(\n service: string,\n account: string,\n): Promise<boolean> {\n assertKeychainSupported()\n try {\n await exec(\"security\", [\n \"delete-generic-password\",\n \"-s\",\n service,\n \"-a\",\n account,\n ])\n return true\n } catch {\n // `security` exits non-zero when the item isn't found — treat as a no-op.\n return false\n }\n}\n","/**\n * KeychainStore — `CredentialStore` backed by the platform Keychain.\n *\n * Wraps the low-level `token-store.ts` helpers (macOS `security` CLI today).\n * The Keychain only holds one opaque string per entry, so `kind`/`expiresAt`/\n * `metadata` are packed into a small JSON envelope that IS that string.\n *\n * Back-compat: an entry written before this store existed (or by any other\n * tool) is a bare token string, not an envelope. `read` falls back to\n * treating the whole string as the value with kind `\"pat\"` — the only flow\n * that pre-dates this store — rather than failing on non-JSON content.\n */\n\nimport { z } from \"zod\"\nimport {\n deleteKeychainToken,\n readKeychainToken,\n writeKeychainToken,\n} from \"../token-store.js\"\nimport type { CredentialStore, StoreRef, StoredCredential } from \"./types.js\"\n\nconst envelopeSchema = z.object({\n v: z.string(),\n k: z.enum([\"pat\", \"assertion\", \"oat\", \"daemon\"]),\n e: z.string().optional(),\n m: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport class KeychainStore implements CredentialStore {\n async read(ref: StoreRef): Promise<StoredCredential | undefined> {\n const account = ref.account ?? ref.path\n const raw = await readKeychainToken(ref.path, account)\n if (raw === undefined) return undefined\n\n try {\n const envelope = envelopeSchema.parse(JSON.parse(raw))\n return {\n value: envelope.v,\n kind: envelope.k,\n ...(envelope.e !== undefined ? { expiresAt: envelope.e } : {}),\n ...(envelope.m !== undefined ? { metadata: envelope.m } : {}),\n }\n } catch {\n return { value: raw, kind: \"pat\" }\n }\n }\n\n async write(ref: StoreRef, cred: StoredCredential): Promise<void> {\n const account = ref.account ?? ref.path\n const envelope: z.infer<typeof envelopeSchema> = {\n v: cred.value,\n k: cred.kind,\n ...(cred.expiresAt !== undefined ? { e: cred.expiresAt } : {}),\n ...(cred.metadata !== undefined ? { m: cred.metadata } : {}),\n }\n await writeKeychainToken(ref.path, account, JSON.stringify(envelope))\n }\n\n async delete(ref: StoreRef): Promise<void> {\n const account = ref.account ?? ref.path\n await deleteKeychainToken(ref.path, account)\n }\n}\n","/**\n * Map a provider's `TokenStoreSpec` to a backend-agnostic `StoreRef`.\n *\n * Shared by every flow engine so the `path`/`keychain` back-compat alias and\n * the `{server}` account template are resolved identically everywhere.\n */\n\nimport { resolveAccount } from \"../token-store.js\"\nimport type { TokenStoreSpec } from \"../types.js\"\nimport type { CredentialStore, StoreRef, StoredCredential } from \"./types.js\"\n\n/** When `audience` is declared, it's folded into the physical store key —\n * `${audience}:${path}` — so credentials scoped to different audiences\n * (e.g. \"tunnel\" vs \"api\") never collide under the same slot. Absent\n * `audience` = today's unprefixed path, unchanged. */\nexport function resolveStoreRef(\n spec: TokenStoreSpec,\n server: string,\n audience?: string,\n): StoreRef {\n const path = spec.path ?? spec.keychain\n return {\n path: audience ? `${audience}:${path}` : path,\n account: resolveAccount(spec.account, server),\n }\n}\n\n/** Derive both the audience-prefixed `ref` and the unprefixed `legacyRef` in\n * one call — the pair every flow engine and the broker need for the\n * audience back-compat read (`readStoreRefWithFallback`). When no audience\n * is declared, `legacyRef === ref` (same object), matching `resolveStoreRef`\n * called with `audience` undefined. */\nexport function resolveStoreRefs(\n spec: TokenStoreSpec,\n server: string,\n audience?: string,\n): { ref: StoreRef; legacyRef: StoreRef } {\n const ref = resolveStoreRef(spec, server, audience)\n const legacyRef = audience ? resolveStoreRef(spec, server) : ref\n return { ref, legacyRef }\n}\n\n/**\n * Read through `ref`, falling back once to `legacyRef` on a miss.\n *\n * This is the read half of the audience back-compat rule: a write always\n * targets the audience-prefixed ref, but a credential written before the\n * provider adopted an audience still lives at the unprefixed (legacy) path.\n * Rather than duplicate that fallback at every flow-engine/broker read site,\n * it lives here, next to `resolveStoreRef` — the one place that already\n * knows how prefixed vs. legacy refs are derived. Callers that don't declare\n * an audience pass `ref === legacyRef` (or just call `store.read` directly);\n * this only does extra work when the two refs actually differ.\n */\nexport async function readStoreRefWithFallback(\n store: CredentialStore,\n ref: StoreRef,\n legacyRef: StoreRef,\n): Promise<StoredCredential | undefined> {\n const stored = await store.read(ref)\n if (stored) return stored\n if (ref.path === legacyRef.path && ref.account === legacyRef.account) {\n return undefined\n }\n return store.read(legacyRef)\n}\n","/**\n * PAT flow engine — reads an existing token from the Keychain or prompts for one.\n *\n * This is the \"legacy-compatible\" flow: the user has a personal API key\n * (`gld_*`, `sk-*`, …) and the CLI needs to store/retrieve it. No browser\n * open, no ceremony. Use `service-auth` for the seamless browser-approve path.\n */\n\nimport { createInterface } from \"node:readline\"\nimport type {\n FlowEngine,\n FlowRunOptions,\n FlowResult,\n AuthProviderHandle,\n DiscoveredEndpoints,\n} from \"../types.js\"\nimport { KeychainStore } from \"../store/keychain-store.js\"\nimport { resolveStoreRefs, readStoreRefWithFallback } from \"../store/resolve-ref.js\"\n\n/**\n * Read a secret from the terminal WITHOUT echoing it — the typed key must not\n * land on screen or in scrollback. On a TTY we drop to raw mode and render a `*`\n * mask per character. When stdin isn't a TTY (piped input, CI, tests) there's no\n * echo to suppress and no raw mode to enter, so we read a line normally.\n */\nasync function promptToken(label: string): Promise<string> {\n const input = process.stdin\n const out = process.stderr\n\n if (!input.isTTY) {\n return new Promise((resolve) => {\n const rl = createInterface({ input, output: out })\n out.write(`${label}: `)\n rl.question(\"\", (answer) => {\n rl.close()\n resolve(answer.trim())\n })\n })\n }\n\n return new Promise((resolve, reject) => {\n out.write(`${label}: `)\n const chars: string[] = []\n input.setRawMode(true)\n input.resume()\n input.setEncoding(\"utf8\")\n\n const cleanup = () => {\n input.setRawMode(false)\n input.pause()\n input.removeListener(\"data\", onData)\n }\n\n const onData = (chunk: string) => {\n for (const ch of chunk) {\n switch (ch) {\n case \"\\r\":\n case \"\\n\":\n out.write(\"\\n\")\n cleanup()\n resolve(chars.join(\"\").trim())\n return\n case \"\\u0003\": // Ctrl-C\n out.write(\"\\n\")\n cleanup()\n reject(new Error(\"auth cancelled\"))\n return\n case \"\\u0004\": // Ctrl-D — treat as end-of-input\n out.write(\"\\n\")\n cleanup()\n resolve(chars.join(\"\").trim())\n return\n case \"\\u007f\": // Backspace / Delete\n case \"\\b\":\n if (chars.length > 0) {\n chars.pop()\n out.write(\"\\b \\b\")\n }\n break\n default:\n // Mask printable input; ignore stray control characters.\n if (ch >= \" \") {\n chars.push(ch)\n out.write(\"*\")\n }\n }\n }\n }\n\n input.on(\"data\", onData)\n })\n}\n\nexport const patFlowEngine: FlowEngine = {\n id: \"pat\",\n\n async run(\n provider: AuthProviderHandle,\n _discovered: DiscoveredEndpoints | null,\n opts: FlowRunOptions,\n ): Promise<FlowResult> {\n const { auth } = provider\n if (auth.flow !== \"pat\") {\n throw new Error(`patFlowEngine: invoked with flow=\"${auth.flow}\"`)\n }\n\n const store = opts.store ?? new KeychainStore()\n const { ref, legacyRef } = resolveStoreRefs(\n auth.tokenStore,\n opts.server,\n provider.audience,\n )\n\n if (!opts.force) {\n const existing = await readStoreRefWithFallback(store, ref, legacyRef)\n if (existing) {\n return { accessToken: existing.value, tokenKind: \"pat\" }\n }\n }\n\n const token = await promptToken(`${provider.id} personal access token`)\n if (!token) throw new Error(\"no token provided\")\n\n await store.write(ref, { value: token, kind: \"pat\" })\n\n return { accessToken: token, tokenKind: \"pat\" }\n },\n}\n","/**\n * Shared RFC 8628 device-grant polling primitive (internal, not exported from\n * the package root).\n *\n * Both the auth.md claim ceremony (`service-auth.ts`) and the device-code flow\n * poll an OAuth token endpoint with a grant-specific URN until the AS reports\n * success or a terminal error. This module holds that shared poll loop plus\n * the small HTTP/browser helpers both flows need — lifted verbatim from\n * `service-auth.ts` so new flow engines have somewhere to reuse them from.\n */\n\nimport { execFile } from \"node:child_process\"\nimport { promisify } from \"node:util\"\nimport { z } from \"zod\"\nimport { fetchWithDeadline } from \"../http.js\"\n\nconst execAsync = promisify(execFile)\n\n// ── response schemas ──────────────────────────────────────────────────────────\n//\n// JSON crosses a trust boundary here (the AS controls the bytes), so every\n// response is validated with Zod rather than asserted. `.loose()` keeps unknown\n// fields the spec may add. The inferred types feed the rest of the engine.\n\n/** Successful token/refresh/exchange response — the AS minted a credential. */\nexport const tokenSuccessSchema = z\n .object({\n access_token: z.string(),\n token_type: z.string().optional(),\n refresh_token: z.string().optional(),\n identity_assertion: z.string().optional(),\n assertion_expires_in: z.number().optional(),\n assertion_expires: z.string().optional(),\n // device-code flow fields (ignored by service-auth today; see WP-2).\n expires_in: z.number().optional(),\n scope: z.string().optional(),\n subject: z.string().optional(),\n revocation_id: z.string().optional(),\n })\n .loose()\n\n/** OAuth error response (`authorization_pending`, `slow_down`, `access_denied`…). */\nexport const tokenErrorSchema = z\n .object({\n error: z.string(),\n error_description: z.string().optional(),\n })\n .loose()\n\n/** A token endpoint reply is either a minted credential or an OAuth error.\n * Success is tried first so a body carrying an access_token never matches the\n * error arm. */\nexport const tokenResponseSchema = z.union([tokenSuccessSchema, tokenErrorSchema])\n\nexport type TokenSuccess = z.infer<typeof tokenSuccessSchema>\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nexport async function openBrowser(url: string): Promise<void> {\n const [cmd, args]: [string, string[]] =\n process.platform === \"darwin\"\n ? [\"open\", [url]]\n : process.platform === \"win32\"\n ? [\"cmd\", [\"/c\", \"start\", url]]\n : [\"xdg-open\", [url]]\n try {\n await execAsync(cmd, args)\n } catch {\n // best-effort — URL already printed to stderr\n }\n}\n\n// NOTE: deliberately does NOT check res.ok — the OAuth device/claim flow returns\n// HTTP 400 with a JSON `{ error }` body for authorization_pending / slow_down,\n// which the poll loop reads as data. Throwing on non-2xx would break polling.\nexport async function postFormOAuth<T>(\n url: string,\n params: Record<string, string>,\n schema: z.ZodType<T>,\n signal?: AbortSignal,\n): Promise<T> {\n const res = await fetchWithDeadline(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams(params).toString(),\n signal,\n })\n return schema.parse(await res.json())\n}\n\nexport interface DeviceGrantPollOptions {\n /** Token endpoint URL to poll. */\n tokenEndpoint: string\n /** Grant-type URN sent on every poll (e.g. the claim or device_code grant). */\n grantType: string\n /** Token-carrying form params — e.g. `claim_token`/`device_code` plus\n * `client_id`. `grant_type` is added automatically; do not include it here. */\n params: Record<string, string>\n /** Poll interval in seconds; grows by 5s on each `slow_down`. */\n intervalS: number\n /** Approval window in seconds, measured from when polling starts. */\n expiresIn: number\n signal?: AbortSignal\n}\n\n/** RFC 8628 poll loop shared by every grant that polls a token endpoint for\n * user approval (auth.md claim ceremony, device-code). */\nexport async function pollDeviceGrant(\n o: DeviceGrantPollOptions,\n): Promise<TokenSuccess> {\n const deadline = Date.now() + o.expiresIn * 1_000\n let pollMs = o.intervalS * 1_000\n\n while (Date.now() < deadline) {\n if (o.signal?.aborted) throw new Error(\"auth cancelled\")\n await new Promise<void>((r) => setTimeout(r, pollMs))\n\n const data = await postFormOAuth(\n o.tokenEndpoint,\n { grant_type: o.grantType, ...o.params },\n tokenResponseSchema,\n o.signal,\n )\n\n if (!(\"error\" in data)) return data\n\n const pollErr = data.error\n if (pollErr === \"authorization_pending\") continue\n if (pollErr === \"slow_down\") {\n pollMs += 5_000\n continue\n }\n if (pollErr === \"expired_token\") {\n throw new Error(\"auth timeout — claim expired before user approved\")\n }\n if (pollErr === \"access_denied\") {\n throw new Error(\"access denied — user rejected the authorisation request\")\n }\n\n const desc = data.error_description\n throw new Error(`token endpoint error: ${pollErr}${desc ? ` — ${desc}` : \"\"}`)\n }\n\n throw new Error(\"auth timeout — approval window closed\")\n}\n","/**\n * service-auth flow engine — auth.md claim ceremony.\n *\n * Protocol:\n * POST /agent/identity { type:\"service_auth\" }\n * → registration_id + claim_token + user_code + verification_uri\n * User approves at verification_uri in browser.\n * Poll POST {token_endpoint} with grant_type=urn:workos:agent-auth:grant-type:claim\n * until approved / denied / expired.\n * On success: store the identity_assertion JWT (AIP-50 §Token storage —\n * the assertion is the durable credential; the access_token MUST NOT be\n * persisted, and the claim_token stays in memory only).\n *\n * Subsequent runs skip the ceremony: the stored assertion is exchanged via the\n * jwt-bearer grant for a fresh access_token (\"this IS the refresh path\" — no\n * refresh_token). Only when the assertion is expired/rejected does a new\n * ceremony start.\n *\n * See: https://github.com/workos/auth.md / AIP-50\n */\n\nimport { z } from \"zod\"\nimport type {\n FlowEngine,\n FlowRunOptions,\n FlowResult,\n AuthProviderHandle,\n DiscoveredEndpoints,\n} from \"../types.js\"\nimport { KeychainStore } from \"../store/keychain-store.js\"\nimport { resolveStoreRefs, readStoreRefWithFallback } from \"../store/resolve-ref.js\"\nimport { fetchWithDeadline, assertSecureUrl } from \"../http.js\"\nimport {\n openBrowser,\n postFormOAuth,\n pollDeviceGrant,\n tokenResponseSchema,\n type TokenSuccess,\n} from \"./device-grant.js\"\n\nconst CLAIM_GRANT_TYPE = \"urn:workos:agent-auth:grant-type:claim\"\nconst JWT_BEARER_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:jwt-bearer\"\nconst DEFAULT_POLL_INTERVAL_S = 5\n\n// ── response schemas ──────────────────────────────────────────────────────────\n//\n// JSON crosses a trust boundary here (the AS controls the bytes), so every\n// response is validated with Zod rather than asserted. `.loose()` keeps unknown\n// fields the spec may add. The inferred types feed the rest of the engine.\n// (Token success/error schemas live in device-grant.ts, shared with every flow\n// that polls a token endpoint.)\n\nconst identityResponseSchema = z\n .object({\n registration_id: z.string(),\n claim_token: z.string(),\n claim: z\n .object({\n user_code: z.string(),\n verification_uri: z.string(),\n expires_in: z.number(),\n interval: z.number().optional(),\n })\n .loose(),\n })\n .loose()\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nasync function postJson<T>(\n url: string,\n body: unknown,\n schema: z.ZodType<T>,\n signal?: AbortSignal,\n): Promise<T> {\n const res = await fetchWithDeadline(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n signal,\n })\n if (!res.ok) {\n const text = await res.text()\n throw new Error(`POST ${url} → ${res.status}: ${text}`)\n }\n return schema.parse(await res.json())\n}\n\n// ── Identity-assertion exchange (jwt-bearer, RFC 7523) ────────────────────────\n//\n// The stored credential IS the identity_assertion JWT. Exchange it at the token\n// endpoint for a fresh, short-lived access token — the AIP-50 refresh path, with\n// no refresh_token involved. Returns null on any error (expired / invalid_grant\n// / server doesn't support the grant) so the caller falls back to a ceremony.\nasync function exchangeAssertion(\n tokenEndpoint: string,\n assertion: string,\n clientId: string,\n signal?: AbortSignal,\n): Promise<TokenSuccess | null> {\n try {\n const data = await postFormOAuth(\n tokenEndpoint,\n {\n grant_type: JWT_BEARER_GRANT_TYPE,\n assertion,\n client_id: clientId,\n },\n tokenResponseSchema,\n signal,\n )\n if (\"error\" in data) return null\n return data\n } catch {\n return null\n }\n}\n\n// ── engine ───────────────────────────────────────────────────────────────────\n\nexport const serviceAuthFlowEngine: FlowEngine = {\n id: \"service-auth\",\n\n async run(\n provider: AuthProviderHandle,\n discovered: DiscoveredEndpoints | null,\n opts: FlowRunOptions,\n ): Promise<FlowResult> {\n const { auth } = provider\n if (auth.flow !== \"service-auth\") {\n throw new Error(`serviceAuthFlowEngine: invoked with flow=\"${auth.flow}\"`)\n }\n // `auth.flow === \"service-auth\"` is guaranteed by the guard above, so the\n // discriminated union has already narrowed `auth` to ServiceAuthConfig.\n const config = auth\n const clientId = config.clientId ?? \"agentproto-cli\"\n const server = opts.server.replace(/\\/$/, \"\")\n\n // Endpoint resolution — prefer live discovery, fall back to conventions\n const identityEndpoint =\n discovered?.identityEndpoint ?? `${server}/agent/identity`\n const tokenEndpoint =\n discovered?.tokenEndpoint ?? `${server}/oauth/token`\n\n // AIP-50 §Security: auth requests MUST use HTTPS (loopback exempt for dev).\n assertSecureUrl(identityEndpoint)\n assertSecureUrl(tokenEndpoint)\n\n const store = opts.store ?? new KeychainStore()\n const { ref, legacyRef } = resolveStoreRefs(\n config.tokenStore,\n server,\n provider.audience,\n )\n\n // Cached path — the stored credential IS the identity_assertion JWT (AIP-50:\n // never the access token, never a refresh token). Exchange it via jwt-bearer\n // for a fresh access token; on failure (expired / invalid_grant) fall through\n // to a full browser ceremony.\n if (!opts.force) {\n const stored = await readStoreRefWithFallback(store, ref, legacyRef)\n if (stored) {\n const exchanged = await exchangeAssertion(\n tokenEndpoint,\n stored.value,\n clientId,\n opts.signal,\n )\n if (exchanged) {\n // If the server rotated the assertion, persist the new one; otherwise\n // the existing assertion stays valid for the next exchange.\n if (exchanged.identity_assertion) {\n await store.write(ref, {\n value: exchanged.identity_assertion,\n kind: \"assertion\",\n })\n }\n return {\n accessToken: exchanged.access_token,\n ...(exchanged.identity_assertion\n ? { identityAssertion: exchanged.identity_assertion }\n : {}),\n tokenKind: \"oat\",\n }\n }\n }\n }\n\n // 1 — POST /agent/identity to start the claim ceremony\n const identity = await postJson(\n identityEndpoint,\n {\n type: \"service_auth\",\n client_id: clientId,\n ...(config.loginHint ? { login_hint: config.loginHint } : {}),\n },\n identityResponseSchema,\n opts.signal,\n )\n\n const { claim_token, claim } = identity\n const intervalS = claim.interval ?? DEFAULT_POLL_INTERVAL_S\n const windowMin = Math.round(claim.expires_in / 60)\n\n // 2 — Print code + open browser\n process.stderr.write(`\\n`)\n process.stderr.write(` Approve ${provider.id} access in your browser\\n\\n`)\n process.stderr.write(` Code: ${claim.user_code}\\n`)\n process.stderr.write(` URL: ${claim.verification_uri}\\n\\n`)\n if (opts.openBrowser !== false) {\n await openBrowser(claim.verification_uri)\n }\n process.stderr.write(` Waiting for approval (${windowMin} min)…\\n\\n`)\n\n // 3 — Poll until approved / denied / expired\n const tokenResult = await pollDeviceGrant({\n tokenEndpoint,\n grantType: CLAIM_GRANT_TYPE,\n params: { claim_token, client_id: clientId },\n intervalS,\n expiresIn: claim.expires_in,\n signal: opts.signal,\n })\n\n // 4 — Store the identity_assertion as the durable credential (AIP-50: the\n // access_token is ephemeral and MUST NOT be persisted; the claim_token\n // was held in memory only). The assertion is re-exchanged via jwt-bearer\n // on the next run.\n const accessToken = tokenResult.access_token\n const assertion = tokenResult.identity_assertion\n\n // Resolve assertion expiry as ISO 8601\n let assertionExpires: string | undefined\n if (tokenResult.assertion_expires) {\n assertionExpires = tokenResult.assertion_expires\n } else if (tokenResult.assertion_expires_in) {\n assertionExpires = new Date(\n Date.now() + tokenResult.assertion_expires_in * 1_000,\n ).toISOString()\n }\n\n if (assertion) {\n await store.write(ref, {\n value: assertion,\n kind: \"assertion\",\n ...(assertionExpires ? { expiresAt: assertionExpires } : {}),\n })\n }\n\n return {\n accessToken,\n identityAssertion: assertion,\n assertionExpires,\n tokenKind: \"oat\",\n }\n },\n}\n","/**\n * device-code flow engine — plain RFC 8628 device-authorization ceremony.\n *\n * Protocol:\n * POST {device_authorization_endpoint} { client_id, scope?, device_label? }\n * → device_code + user_code + verification_uri(_complete) + expires_in\n * User approves at verification_uri in browser.\n * Poll POST {token_endpoint} with grant_type=urn:ietf:params:oauth:grant-type:device_code\n * until approved / denied / expired.\n * On success: store the access_token as the durable credential (kind:\"daemon\")\n * — unlike service-auth, the access token IS the thing that's persisted;\n * refresh_token/scope/subject/revocation_id ride in `metadata`.\n *\n * Subsequent runs: a fresh stored credential (or one with no expiry) short-\n * circuits the ceremony. An expired credential with a stored refresh_token is\n * exchanged via `grant_type=refresh_token`; on failure (or when no\n * refresh_token was stored) a new ceremony starts.\n */\n\nimport { z } from \"zod\"\nimport type {\n FlowEngine,\n FlowRunOptions,\n FlowResult,\n AuthProviderHandle,\n DiscoveredEndpoints,\n} from \"../types.js\"\nimport { KeychainStore } from \"../store/keychain-store.js\"\nimport { resolveStoreRefs, readStoreRefWithFallback } from \"../store/resolve-ref.js\"\nimport type { CredentialStore, StoreRef, StoredCredential } from \"../store/types.js\"\nimport { fetchWithDeadline, assertSecureUrl } from \"../http.js\"\nimport {\n openBrowser,\n postFormOAuth,\n pollDeviceGrant,\n tokenResponseSchema,\n type TokenSuccess,\n} from \"./device-grant.js\"\n\nconst DEVICE_CODE_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:device_code\"\nconst REFRESH_GRANT_TYPE = \"refresh_token\"\nconst DEFAULT_POLL_INTERVAL_S = 5\n\n/** Thrown by the device-code engine when `opts.refreshOnly` is set and no\n * fresh or refreshable credential is available — the only remaining path\n * would be an interactive ceremony, which `refreshOnly` callers explicitly\n * opt out of. Callers (e.g. `serve` boot on a headless host) catch this to\n * fall back to their own non-interactive behavior instead of hanging. */\nexport class CeremonyRequiredError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"CeremonyRequiredError\"\n }\n}\n\n// ── response schema ───────────────────────────────────────────────────────────\n//\n// JSON crosses a trust boundary here (the AS controls the bytes), so the\n// response is validated with Zod rather than asserted. `.loose()` keeps\n// unknown fields the spec may add.\n\nconst deviceAuthorizationResponseSchema = z\n .object({\n device_code: z.string(),\n user_code: z.string(),\n verification_uri: z.string(),\n verification_uri_complete: z.string().optional(),\n expires_in: z.number(),\n interval: z.number().optional(),\n })\n .loose()\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nasync function postDeviceAuthorization(\n url: string,\n params: Record<string, string>,\n signal?: AbortSignal,\n) {\n const res = await fetchWithDeadline(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams(params).toString(),\n signal,\n })\n if (!res.ok) {\n const text = await res.text()\n throw new Error(`POST ${url} → ${res.status}: ${text}`)\n }\n return deviceAuthorizationResponseSchema.parse(await res.json())\n}\n\n/** Read a string metadata field without an `as` cast — `metadata` is\n * `Record<string, unknown>`, so every read is a runtime type check. */\nfunction metaString(\n metadata: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n const v = metadata?.[key]\n return typeof v === \"string\" ? v : undefined\n}\n\nfunction isExpired(cred: StoredCredential): boolean {\n if (!cred.expiresAt) return false\n const t = Date.parse(cred.expiresAt)\n if (Number.isNaN(t)) return true\n return t <= Date.now()\n}\n\nfunction resultFromStored(cred: StoredCredential): FlowResult {\n const refreshToken = metaString(cred.metadata, \"refreshToken\")\n const scope = metaString(cred.metadata, \"scope\")\n const subject = metaString(cred.metadata, \"subject\")\n const revocationId = metaString(cred.metadata, \"revocationId\")\n return {\n accessToken: cred.value,\n tokenKind: \"daemon\",\n ...(refreshToken ? { refreshToken } : {}),\n ...(scope ? { scope } : {}),\n ...(subject ? { subject } : {}),\n ...(revocationId ? { revocationId } : {}),\n }\n}\n\n/** Refresh via `grant_type=refresh_token`. Returns null on any error\n * (expired / invalid_grant / server doesn't support the grant) so the\n * caller falls back to a full ceremony. */\nasync function refreshAccessToken(\n tokenEndpoint: string,\n refreshToken: string,\n clientId: string,\n signal?: AbortSignal,\n): Promise<TokenSuccess | null> {\n try {\n const data = await postFormOAuth(\n tokenEndpoint,\n {\n grant_type: REFRESH_GRANT_TYPE,\n refresh_token: refreshToken,\n client_id: clientId,\n },\n tokenResponseSchema,\n signal,\n )\n if (\"error\" in data) return null\n return data\n } catch {\n return null\n }\n}\n\nasync function persistAndResult(\n store: CredentialStore,\n ref: StoreRef,\n o: {\n accessToken: string\n expiresIn?: number\n refreshToken?: string\n scope?: string\n subject?: string\n deviceLabel?: string\n revocationId?: string\n },\n): Promise<FlowResult> {\n const expiresAt = o.expiresIn\n ? new Date(Date.now() + o.expiresIn * 1_000).toISOString()\n : undefined\n\n const metadata: Record<string, unknown> = {\n obtainedAt: new Date().toISOString(),\n ...(o.refreshToken ? { refreshToken: o.refreshToken } : {}),\n ...(o.scope ? { scope: o.scope } : {}),\n ...(o.subject ? { subject: o.subject } : {}),\n ...(o.deviceLabel ? { deviceLabel: o.deviceLabel } : {}),\n ...(o.revocationId ? { revocationId: o.revocationId } : {}),\n }\n\n await store.write(ref, {\n value: o.accessToken,\n kind: \"daemon\",\n ...(expiresAt ? { expiresAt } : {}),\n metadata,\n })\n\n return {\n accessToken: o.accessToken,\n tokenKind: \"daemon\",\n ...(o.refreshToken ? { refreshToken: o.refreshToken } : {}),\n ...(o.scope ? { scope: o.scope } : {}),\n ...(o.subject ? { subject: o.subject } : {}),\n ...(o.revocationId ? { revocationId: o.revocationId } : {}),\n }\n}\n\n// ── engine ───────────────────────────────────────────────────────────────────\n\nexport const deviceCodeFlowEngine: FlowEngine = {\n id: \"device-code\",\n\n async run(\n provider: AuthProviderHandle,\n discovered: DiscoveredEndpoints | null,\n opts: FlowRunOptions,\n ): Promise<FlowResult> {\n const { auth } = provider\n if (auth.flow !== \"device-code\") {\n throw new Error(`deviceCodeFlowEngine: invoked with flow=\"${auth.flow}\"`)\n }\n // `auth.flow === \"device-code\"` is guaranteed by the guard above, so the\n // discriminated union has already narrowed `auth` to DeviceCodeAuthConfig.\n const config = auth\n const clientId = config.clientId ?? \"agentproto-cli\"\n const server = opts.server.replace(/\\/$/, \"\")\n\n // Endpoint resolution — prefer live discovery, fall back to conventions.\n const deviceAuthorizationEndpoint =\n discovered?.deviceAuthorizationEndpoint ?? `${server}/oauth/device`\n const tokenEndpoint = discovered?.tokenEndpoint ?? `${server}/oauth/token`\n\n // AIP-50 §Security: auth requests MUST use HTTPS (loopback exempt for dev).\n assertSecureUrl(deviceAuthorizationEndpoint)\n assertSecureUrl(tokenEndpoint)\n\n const store = opts.store ?? new KeychainStore()\n const { ref, legacyRef } = resolveStoreRefs(\n config.tokenStore,\n server,\n provider.audience,\n )\n\n // Shared by both the ordinary cached path and `refreshOnly`: exchange a\n // stored refresh_token for a fresh access token, persisting the result.\n // Returns null (never throws) on a missing refresh_token or any grant\n // failure, so both callers can decide what to do next.\n async function tryRefresh(stored: StoredCredential): Promise<FlowResult | null> {\n const refreshToken = metaString(stored.metadata, \"refreshToken\")\n if (!refreshToken) return null\n const refreshed = await refreshAccessToken(\n tokenEndpoint,\n refreshToken,\n clientId,\n opts.signal,\n )\n if (!refreshed) return null\n return persistAndResult(store, ref, {\n accessToken: refreshed.access_token,\n expiresIn: refreshed.expires_in,\n refreshToken: refreshed.refresh_token ?? refreshToken,\n scope: refreshed.scope ?? metaString(stored.metadata, \"scope\"),\n subject: refreshed.subject ?? metaString(stored.metadata, \"subject\"),\n deviceLabel:\n config.deviceLabel ?? metaString(stored.metadata, \"deviceLabel\"),\n revocationId:\n refreshed.revocation_id ?? metaString(stored.metadata, \"revocationId\"),\n })\n }\n\n // `refreshOnly` — attempt only the cached/refresh path, never the\n // interactive ceremony. Distinct from the ordinary cached path below so\n // a refresh failure here throws instead of falling through.\n if (opts.refreshOnly) {\n const stored = await readStoreRefWithFallback(store, ref, legacyRef)\n if (stored) {\n if (!isExpired(stored)) {\n return resultFromStored(stored)\n }\n const refreshed = await tryRefresh(stored)\n if (refreshed) return refreshed\n }\n throw new CeremonyRequiredError(\n `${provider.id}: no fresh or refreshable device-code credential — an interactive ceremony would be required, but refreshOnly was set`,\n )\n }\n\n // Cached path — the stored credential IS the access token (pat-class\n // persistence). A fresh (or expiry-less) credential short-circuits the\n // ceremony entirely; an expired one with a refresh_token is renewed via\n // grant_type=refresh_token before falling back to a ceremony.\n if (!opts.force) {\n const stored = await readStoreRefWithFallback(store, ref, legacyRef)\n if (stored) {\n if (!isExpired(stored)) {\n return resultFromStored(stored)\n }\n const refreshed = await tryRefresh(stored)\n if (refreshed) return refreshed\n // refresh failed (expired / invalid_grant) — fall through to a ceremony\n }\n }\n\n // 1 — POST the device-authorization endpoint to start the ceremony\n const params: Record<string, string> = { client_id: clientId }\n if (config.scope) params.scope = config.scope\n if (config.deviceLabel) params.device_label = config.deviceLabel\n\n const authz = await postDeviceAuthorization(\n deviceAuthorizationEndpoint,\n params,\n opts.signal,\n )\n\n const intervalS = authz.interval ?? DEFAULT_POLL_INTERVAL_S\n const windowMin = Math.round(authz.expires_in / 60)\n\n // 2 — Print code + open browser\n process.stderr.write(`\\n`)\n process.stderr.write(` Approve ${provider.id} access in your browser\\n\\n`)\n process.stderr.write(` Code: ${authz.user_code}\\n`)\n process.stderr.write(` URL: ${authz.verification_uri}\\n\\n`)\n if (opts.openBrowser !== false) {\n await openBrowser(authz.verification_uri_complete ?? authz.verification_uri)\n }\n process.stderr.write(` Waiting for approval (${windowMin} min)…\\n\\n`)\n\n // 3 — Poll until approved / denied / expired\n const tokenResult = await pollDeviceGrant({\n tokenEndpoint,\n grantType: DEVICE_CODE_GRANT_TYPE,\n params: { device_code: authz.device_code, client_id: clientId },\n intervalS,\n expiresIn: authz.expires_in,\n signal: opts.signal,\n })\n\n // 4 — Persist the access token as the durable credential (pat-class).\n return persistAndResult(store, ref, {\n accessToken: tokenResult.access_token,\n expiresIn: tokenResult.expires_in,\n refreshToken: tokenResult.refresh_token,\n scope: tokenResult.scope,\n subject: tokenResult.subject,\n deviceLabel: config.deviceLabel,\n revocationId: tokenResult.revocation_id,\n })\n },\n}\n","/**\n * Flow engine registry — dispatch by `provider.auth.flow`.\n *\n * Add a new engine:\n * 1. Implement `FlowEngine` in a sibling file\n * 2. Add it here — no if/switch chains at call sites\n */\n\nimport type { FlowEngine } from \"../types.js\"\nimport { patFlowEngine } from \"./pat.js\"\nimport { serviceAuthFlowEngine } from \"./service-auth.js\"\nimport { deviceCodeFlowEngine } from \"./device-code.js\"\n\nexport const FLOW_ENGINES: Readonly<Record<string, FlowEngine>> = {\n [patFlowEngine.id]: patFlowEngine,\n [serviceAuthFlowEngine.id]: serviceAuthFlowEngine,\n [deviceCodeFlowEngine.id]: deviceCodeFlowEngine,\n}\n","/**\n * `runAuthFlow` — resolve provider → discover endpoints → dispatch to engine.\n *\n * Discovery is attempted silently; callers receive the result without knowing\n * whether live or static endpoint config was used. The flow engine receives\n * `null` for `discovered` if discovery failed or was not attempted.\n */\n\nimport { FLOW_ENGINES } from \"./flow-engines/index.js\"\nimport { discoverEndpoints, DiscoveryError } from \"./discover.js\"\nimport type {\n AuthProviderHandle,\n DiscoveredEndpoints,\n FlowResult,\n FlowRunOptions,\n} from \"./types.js\"\n\nexport interface RunFlowOptions extends FlowRunOptions {\n /** Pre-resolved endpoints (skip discovery). Pass null to force re-discovery. */\n discovered?: DiscoveredEndpoints | null\n /** Suppress debug output. Default: false. */\n quiet?: boolean\n}\n\nexport async function runAuthFlow(\n provider: AuthProviderHandle,\n opts: RunFlowOptions,\n): Promise<FlowResult> {\n const flowId = provider.auth.flow\n const engine = FLOW_ENGINES[flowId]\n if (!engine) {\n throw new Error(\n `runAuthFlow: unknown flow \"${flowId}\" — registered: ${Object.keys(FLOW_ENGINES).join(\", \")}`,\n )\n }\n\n // Discovery: try unless caller already provided endpoints\n let discovered: DiscoveredEndpoints | null =\n opts.discovered !== undefined ? opts.discovered : null\n\n if (\n discovered === null &&\n (flowId === \"service-auth\" || flowId === \"device-code\")\n ) {\n try {\n discovered = await discoverEndpoints(opts.server, { signal: opts.signal })\n } catch (err) {\n if (!opts.quiet) {\n const msg =\n err instanceof DiscoveryError\n ? err.message\n : `discovery failed: ${err}`\n process.stderr.write(`[auth] ${msg} — using static config\\n`)\n }\n }\n }\n\n return engine.run(provider, discovered, opts)\n}\n","/**\n * MemoryStore — in-process `CredentialStore` backed by a `Map`.\n *\n * Ephemeral: gone when the process exits. Used for tests and short-lived\n * tooling that shouldn't touch a real backend.\n */\n\nimport type { CredentialStore, StoreRef, StoredCredential } from \"./types.js\"\n\nfunction keyOf(ref: StoreRef): string {\n return `${ref.path}\u0000${ref.account ?? ref.path}`\n}\n\nexport class MemoryStore implements CredentialStore {\n private readonly entries = new Map<string, StoredCredential>()\n\n async read(ref: StoreRef): Promise<StoredCredential | undefined> {\n const entry = this.entries.get(keyOf(ref))\n return entry ? { ...entry } : undefined\n }\n\n async write(ref: StoreRef, cred: StoredCredential): Promise<void> {\n this.entries.set(keyOf(ref), { ...cred })\n }\n\n async delete(ref: StoreRef): Promise<void> {\n this.entries.delete(keyOf(ref))\n }\n}\n","/**\n * FileStore — encrypted-JSON-file `CredentialStore`.\n *\n * Every entry is sealed independently with AES-256-GCM under a key read from\n * `AGENTPROTO_STORE_KEY` (hex or base64, 32 raw bytes). There is no plaintext\n * fallback: a missing or malformed key throws rather than writing credentials\n * to disk in the clear.\n */\n\nimport {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n} from \"node:crypto\"\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\"\nimport { dirname } from \"node:path\"\nimport { z } from \"zod\"\nimport type { CredentialStore, StoreRef, StoredCredential } from \"./types.js\"\n\nconst ALGORITHM = \"aes-256-gcm\"\nconst KEY_ENV_VAR = \"AGENTPROTO_STORE_KEY\"\nconst IV_BYTES = 12\n\nconst sealedEntrySchema = z.object({\n iv: z.string(),\n tag: z.string(),\n ciphertext: z.string(),\n})\ntype SealedEntry = z.infer<typeof sealedEntrySchema>\n\nconst sealedFileSchema = z.record(z.string(), sealedEntrySchema)\n\nconst storedCredentialSchema = z.object({\n value: z.string(),\n kind: z.enum([\"pat\", \"assertion\", \"oat\", \"daemon\"]),\n expiresAt: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\n\nfunction keyOf(ref: StoreRef): string {\n return `${ref.path} ${ref.account ?? ref.path}`\n}\n\nfunction isEnoent(err: unknown): boolean {\n return (\n typeof err === \"object\" &&\n err !== null &&\n \"code\" in err &&\n err.code === \"ENOENT\"\n )\n}\n\n/** Decode `AGENTPROTO_STORE_KEY` (hex or base64) into exactly 32 raw bytes. */\nfunction loadKey(): Buffer {\n const raw = process.env[KEY_ENV_VAR]\n if (!raw) {\n throw new Error(\n `FileStore: missing ${KEY_ENV_VAR} — set a 32-byte key (64 hex chars, ` +\n `or base64) to use the encrypted file store. Refusing to store ` +\n `credentials in plaintext.`,\n )\n }\n const key = /^[0-9a-fA-F]{64}$/.test(raw)\n ? Buffer.from(raw, \"hex\")\n : Buffer.from(raw, \"base64\")\n if (key.length !== 32) {\n throw new Error(\n `FileStore: ${KEY_ENV_VAR} must decode to exactly 32 bytes (got ` +\n `${key.length}). Provide a 64-char hex string or base64 encoding 32 bytes.`,\n )\n }\n return key\n}\n\nfunction seal(key: Buffer, plaintext: string): SealedEntry {\n const iv = randomBytes(IV_BYTES)\n const cipher = createCipheriv(ALGORITHM, key, iv)\n const ciphertext = Buffer.concat([\n cipher.update(plaintext, \"utf8\"),\n cipher.final(),\n ])\n return {\n iv: iv.toString(\"base64\"),\n tag: cipher.getAuthTag().toString(\"base64\"),\n ciphertext: ciphertext.toString(\"base64\"),\n }\n}\n\nfunction unseal(key: Buffer, entry: SealedEntry): string {\n const decipher = createDecipheriv(\n ALGORITHM,\n key,\n Buffer.from(entry.iv, \"base64\"),\n )\n decipher.setAuthTag(Buffer.from(entry.tag, \"base64\"))\n const plaintext = Buffer.concat([\n decipher.update(Buffer.from(entry.ciphertext, \"base64\")),\n decipher.final(),\n ])\n return plaintext.toString(\"utf8\")\n}\n\nexport class FileStore implements CredentialStore {\n constructor(private readonly filePath: string) {}\n\n async read(ref: StoreRef): Promise<StoredCredential | undefined> {\n const key = loadKey()\n const file = await this.readFile()\n const sealed = file[keyOf(ref)]\n if (!sealed) return undefined\n return storedCredentialSchema.parse(JSON.parse(unseal(key, sealed)))\n }\n\n async write(ref: StoreRef, cred: StoredCredential): Promise<void> {\n const key = loadKey()\n const file = await this.readFile()\n file[keyOf(ref)] = seal(key, JSON.stringify(cred))\n await this.writeFile(file)\n }\n\n async delete(ref: StoreRef): Promise<void> {\n const file = await this.readFile()\n delete file[keyOf(ref)]\n await this.writeFile(file)\n }\n\n private async readFile(): Promise<Record<string, SealedEntry>> {\n try {\n const raw = await readFile(this.filePath, \"utf8\")\n return sealedFileSchema.parse(JSON.parse(raw))\n } catch (err) {\n if (isEnoent(err)) return {}\n throw err\n }\n }\n\n private async writeFile(file: Record<string, SealedEntry>): Promise<void> {\n await mkdir(dirname(this.filePath), { recursive: true })\n await writeFile(this.filePath, JSON.stringify(file, null, 2), \"utf8\")\n }\n}\n","/**\n * CredentialBroker — resolve ready-to-use auth headers for a `<providerId>`\n * or `<providerId>/<account>` path, auto-refreshing via the flow engine when\n * the stored credential is missing, expired, or not directly usable.\n *\n * Agent.pw-parity API: callers ask for headers by path and never touch\n * tokens, flows, or the underlying store directly.\n */\n\nimport { runAuthFlow } from \"./run-flow.js\"\nimport { resolveStoreRefs, readStoreRefWithFallback } from \"./store/resolve-ref.js\"\nimport type { CredentialStore, StoredCredential } from \"./store/types.js\"\nimport type { AuthProviderHandle } from \"./types.js\"\n\n/** Refresh this long before the actual expiry, so a credential that's about\n * to expire mid-request gets renewed proactively instead of failing. */\nconst EXPIRY_SKEW_MS = 60_000\n\nexport interface CredentialBrokerOptions {\n /** Backend to read cached credentials from and persist refreshed ones to. */\n store: CredentialStore\n /** Provider lookup — pass `getAuthProvider` from the registry, or a custom\n * resolver (e.g. scoped to a single host's providers). */\n getProvider: (id: string) => AuthProviderHandle | undefined\n}\n\ninterface ParsedPath {\n providerId: string\n account?: string\n}\n\n/** Split `\"<providerId>\"` or `\"<providerId>/<account>\"` on the first `/`. */\nfunction parsePath(path: string): ParsedPath {\n const slash = path.indexOf(\"/\")\n if (slash === -1) return { providerId: path }\n return { providerId: path.slice(0, slash), account: path.slice(slash + 1) }\n}\n\n/** `expiresAt` in the future (past the refresh skew), or absent entirely. A\n * malformed `expiresAt` is treated as expired — refresh rather than risk\n * serving a header that a downstream API will reject. */\nfunction isFresh(cred: StoredCredential): boolean {\n if (!cred.expiresAt) return true\n const expiresAtMs = Date.parse(cred.expiresAt)\n if (Number.isNaN(expiresAtMs)) return false\n return expiresAtMs - EXPIRY_SKEW_MS > Date.now()\n}\n\n/** Header map for a credential usable as a bearer token directly, or\n * `undefined` when it isn't. `assertion` is never bearer-usable — it must be\n * exchanged by a flow engine first — so it always falls through to\n * `runAuthFlow`. */\nfunction bearerHeaders(\n value: string,\n kind: StoredCredential[\"kind\"],\n): Record<string, string> | undefined {\n if (kind === \"pat\" || kind === \"oat\" || kind === \"daemon\") {\n return { Authorization: `Bearer ${value}` }\n }\n return undefined\n}\n\nexport class CredentialBroker {\n private readonly store: CredentialStore\n private readonly getProvider: (id: string) => AuthProviderHandle | undefined\n\n constructor(opts: CredentialBrokerOptions) {\n this.store = opts.store\n this.getProvider = opts.getProvider\n }\n\n async resolveHeaders(o: {\n path: string\n server?: string\n signal?: AbortSignal\n /** Audience the caller expects this credential to be scoped to. Checked\n * only when the resolved provider also declares one — see the mismatch\n * error below. Does not itself change which store key is read; the\n * provider's own `audience` (not the caller's) determines that. */\n audience?: string\n }): Promise<Record<string, string>> {\n const { providerId, account } = parsePath(o.path)\n const provider = this.getProvider(providerId)\n if (!provider) {\n throw new Error(`CredentialBroker: unknown auth provider \"${providerId}\"`)\n }\n\n if (\n o.audience !== undefined &&\n provider.audience !== undefined &&\n o.audience !== provider.audience\n ) {\n throw new Error(\n `CredentialBroker: provider \"${providerId}\" is scoped to audience \"${provider.audience}\", requested \"${o.audience}\"`,\n )\n }\n\n const server = o.server ?? provider.apiBase\n const { ref, legacyRef } = resolveStoreRefs(\n provider.auth.tokenStore,\n server,\n provider.audience,\n )\n if (account !== undefined) {\n ref.account = account\n legacyRef.account = account\n }\n\n const stored = await readStoreRefWithFallback(this.store, ref, legacyRef)\n if (stored && isFresh(stored)) {\n const headers = bearerHeaders(stored.value, stored.kind)\n if (headers) return headers\n }\n\n const result = await runAuthFlow(provider, {\n server,\n store: this.store,\n signal: o.signal,\n })\n const headers =\n result.accessToken !== undefined\n ? bearerHeaders(result.accessToken, result.tokenKind)\n : undefined\n if (!headers) {\n throw new Error(\n `CredentialBroker: auth flow for \"${providerId}\" produced no usable access token`,\n )\n }\n return headers\n }\n}\n","/**\n * Named auth-profile store — CRUD over `~/.agentproto/auth-profiles.json`\n * (mode 0600), generalizing `providers-store`'s single-key-per-provider file\n * (`packages/providers-store/src/index.ts:68-90`, `ProviderEntry`/\n * `ProvidersFile`) to N named `AuthProfile`s per billing endpoint, keyed by `id`.\n *\n * This is the profile-metadata store, not the credential store: entries hold\n * `credentialRef` (a pointer), never a secret, so — unlike `FileStore`\n * (`store/file-store.ts`) — this file needs no encryption. Reuses the exact\n * persistence primitives `providers-store` already established (a versioned\n * JSON file under `~/.agentproto/`, `node:fs/promises`, mode 0600) rather\n * than inventing a new format, just relocated to `@agentproto/auth` — the\n * correct home for named profiles per SPEC §1c (`providers.json` is the\n * degenerate one-key-per-provider case this generalizes).\n */\n\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\"\nimport { homedir } from \"node:os\"\nimport { join, resolve } from \"node:path\"\nimport { z } from \"zod\"\nimport type { AuthMethod, AuthProfile } from \"./profile-types.js\"\n\nconst authMethodSchema = z.enum([\"oauth-bearer\", \"api-key\"]) satisfies z.ZodType<AuthMethod>\n\n/** Version-1 on-disk shape. Keep `vendor` here permanently for compatibility:\n * callers only ever see the unambiguous in-memory `endpoint` field. */\nconst modelCurationSchema = z.object({\n mode: z.enum([\"all\", \"allow\"]),\n ids: z.array(z.string()),\n})\n\nconst costBudgetSchema = z.object({\n maxCostUsd: z.number(),\n window: z.string(),\n scope: z.enum([\"session\", \"profile\"]),\n})\n\nconst authProfileSchema = z.object({\n id: z.string(),\n vendor: z.string(),\n method: authMethodSchema,\n credentialRef: z.string().optional(),\n source: z.string().optional(),\n label: z.string().optional(),\n // Additive, back-compat fields — an entry that predates them parses\n // unchanged (both optional), and `endpoint` still shadows the on-disk\n // `vendor` alias below.\n disabled: z.boolean().optional(),\n models: modelCurationSchema.optional(),\n costBudget: costBudgetSchema.optional(),\n origin: z.string().optional(),\n}).transform(({ vendor, ...profile }): AuthProfile => ({ ...profile, endpoint: vendor }))\n\nconst authProfilesFileSchema = z.object({\n version: z.literal(1),\n profiles: z.record(z.string(), authProfileSchema),\n})\n\nexport type AuthProfilesFile = z.infer<typeof authProfilesFileSchema>\n\n/** Fresh empty file each call — never share the `profiles` object, or a\n * later mutation leaks into every other load in-process (same defense\n * `providers-store`'s `emptyFile()` establishes). */\nfunction emptyFile(): AuthProfilesFile {\n return { version: 1, profiles: {} }\n}\n\nexport function authProfilesPath(): string {\n return resolve(homedir(), \".agentproto\", \"auth-profiles.json\")\n}\n\nexport async function loadAuthProfiles(): Promise<AuthProfilesFile> {\n try {\n const raw = await readFile(authProfilesPath(), \"utf8\")\n return authProfilesFileSchema.parse(JSON.parse(raw))\n } catch {\n return emptyFile() // ENOENT / malformed → empty\n }\n}\n\nasync function writeAuthProfiles(file: AuthProfilesFile): Promise<void> {\n const dir = join(homedir(), \".agentproto\")\n await mkdir(dir, { recursive: true })\n // mode 0600 so other local users can't read the profile metadata.\n const diskFile = {\n version: file.version,\n profiles: Object.fromEntries(\n Object.entries(file.profiles).map(([id, { endpoint, ...profile }]) => [\n id,\n { ...profile, vendor: endpoint },\n ]),\n ),\n }\n await writeFile(authProfilesPath(), JSON.stringify(diskFile, null, 2) + \"\\n\", {\n encoding: \"utf8\",\n mode: 0o600,\n })\n}\n\n/** List all profiles, optionally filtered to one billing endpoint. */\nexport async function listAuthProfiles(endpoint?: string): Promise<AuthProfile[]> {\n const file = await loadAuthProfiles()\n const all = Object.values(file.profiles)\n return endpoint === undefined ? all : all.filter(p => p.endpoint === endpoint)\n}\n\n/** Look up a single profile by id, or undefined if none exists. */\nexport async function getAuthProfile(id: string): Promise<AuthProfile | undefined> {\n const file = await loadAuthProfiles()\n return file.profiles[id]\n}\n\n/** Add (or replace) a profile, keyed by its `id`. */\nexport async function addAuthProfile(profile: AuthProfile): Promise<void> {\n const file = await loadAuthProfiles()\n file.profiles[profile.id] = profile\n await writeAuthProfiles(file)\n}\n\n/** Remove a profile by id. Returns true if it existed. */\nexport async function removeAuthProfile(id: string): Promise<boolean> {\n const file = await loadAuthProfiles()\n if (!(id in file.profiles)) return false\n delete file.profiles[id]\n await writeAuthProfiles(file)\n return true\n}\n","/**\n * Auth-profile provisioning — the create/delete flow the store CRUD\n * (`profile-store.ts`) deliberately leaves out.\n *\n * `profile-store.ts` writes only profile *metadata* (`credentialRef`, a\n * pointer). Provisioning is the two-sided operation nobody else owned: write\n * the *secret* to the credential store at a derived slot, THEN record the\n * metadata pointing at it — and, on delete, tear both down together. This is\n * the single place that knows the `agentproto.auth.<vendor>[.<qualifier>]`\n * keychain-slot convention (matching the entries seeded by hand in\n * `~/.agentproto/auth-profiles.json`).\n *\n * The secret is INPUT-only. It is written to the `CredentialStore` and never\n * echoed back: `createAuthProfile` returns non-secret metadata plus a\n * one-way `fingerprint` (same \"fingerprint, don't echo\" discipline as\n * `broker.ts` / `KeychainStore`), so a caller can confirm *which* credential\n * landed without ever seeing it.\n *\n * Dependency-injected (`ProfileProvisionDeps`) so it's unit-testable against\n * a `MemoryStore` + an in-memory profile map, with no keychain or filesystem.\n */\n\nimport { createHash } from \"node:crypto\"\nimport type { AuthMethod, AuthProfile, ModelCuration } from \"./profile-types.js\"\nimport type { CredentialStore } from \"./store/types.js\"\n\n/** Input to {@link createAuthProfile}. `credential` is the raw secret — it is\n * written to the store and NEVER returned. Exactly one of `credential` /\n * `source` must be given for an `oauth-bearer` profile; `api-key` always\n * requires `credential` (a source-backed profile only makes sense for a\n * self-refreshing subscription bearer). */\nexport interface CreateAuthProfileInput {\n /** Stable id, unique across all profiles. */\n id: string\n /** Billing endpoint / vendor this credential authenticates against\n * (`anthropic`, `openrouter`, `moonshot`, …). */\n endpoint: string\n /** How this profile authenticates. */\n method: AuthMethod\n /** The raw secret (a subscription OAuth bearer, an API key). INPUT-ONLY.\n * Mutually exclusive with `source`. */\n credential?: string\n /** Self-refreshing credential source (`oauth-bearer` only, e.g.\n * `\"claude-code-oauth\"`) — the profile stores no secret; the credential is\n * resolved fresh at spawn time instead. Mutually exclusive with\n * `credential`. */\n source?: string\n /** Optional human-readable name. */\n label?: string\n /** Optional explicit credential-store slot. Omitted ⇒ derived from\n * `endpoint` + `method` (see {@link deriveCredentialRef}). Ignored for a\n * source-backed profile (nothing is written to the credential store). */\n credentialRef?: string\n /** Optional provenance — where the credential was imported from (a WS6\n * discovery origin). Stamped verbatim on the created profile; purely\n * informational. */\n origin?: string\n}\n\n/** The non-secret result of a create — safe to log, return over the wire, or\n * render in a UI. Carries a fingerprint, never the credential. */\nexport interface CreatedAuthProfile {\n id: string\n endpoint: string\n method: AuthMethod\n /** Set for a credential-backed profile; absent for a source-backed one. */\n credentialRef?: string\n /** Set for a source-backed profile; absent for a credential-backed one. */\n source?: string\n label?: string\n /** Provenance stamped at import time, when given. */\n origin?: string\n /** One-way fingerprint of the stored credential (sha256, truncated) — lets\n * a caller confirm *which* secret was stored without exposing it. Absent\n * for a source-backed profile — there is no stored secret to fingerprint. */\n fingerprint?: string\n}\n\n/** The result of a delete. `deleted` is false when no profile had that id\n * (idempotent — the desired end state already held). */\nexport interface DeletedAuthProfile {\n deleted: boolean\n id: string\n /** The slot the credential lived at, when a profile was actually removed. */\n credentialRef?: string\n}\n\n/** Injectable persistence surface — production wires these to\n * `profile-store.ts` + a `KeychainStore`; tests pass in-memory doubles. */\nexport interface ProfileProvisionDeps {\n /** Where secrets live (a `KeychainStore` in production). */\n store: CredentialStore\n getProfile: (id: string) => Promise<AuthProfile | undefined>\n listProfiles: () => Promise<AuthProfile[]>\n addProfile: (profile: AuthProfile) => Promise<void>\n removeProfile: (id: string) => Promise<boolean>\n}\n\n/** Raised when create/delete input fails validation. Distinct type so a host\n * (HTTP route, MCP tool) can map it to a 400 rather than a 500. */\nexport class AuthProfileValidationError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"AuthProfileValidationError\"\n }\n}\n\nconst AUTH_METHODS: readonly AuthMethod[] = [\"oauth-bearer\", \"api-key\"]\n\n/** ids and endpoints become keychain-slot / filename fragments, so keep them\n * to a conservative, injection-safe charset. */\nconst SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/\n\n/** Normalized, validated create input — every field trimmed and checked.\n * Exactly one of `credential` / `source` is present. */\nexport interface ValidatedCreateInput {\n id: string\n endpoint: string\n method: AuthMethod\n credential?: string\n source?: string\n label?: string\n credentialRef?: string\n origin?: string\n}\n\n/**\n * Validate + normalize raw create input. Pure — no I/O. Throws\n * {@link AuthProfileValidationError} with a specific message on the first\n * problem it finds, so the surface layer can surface a clear 400.\n */\nexport function validateCreateInput(input: CreateAuthProfileInput): ValidatedCreateInput {\n const id = (input.id ?? \"\").trim()\n if (!id) throw new AuthProfileValidationError(\"id is required\")\n if (!SLUG_RE.test(id)) {\n throw new AuthProfileValidationError(\n `id \"${id}\" is invalid — use letters, digits, \".\", \"_\" or \"-\", ` +\n `starting with a letter or digit`,\n )\n }\n\n const endpoint = (input.endpoint ?? \"\").trim()\n if (!endpoint) throw new AuthProfileValidationError(\"endpoint is required\")\n if (!SLUG_RE.test(endpoint)) {\n throw new AuthProfileValidationError(\n `endpoint \"${endpoint}\" is invalid — use letters, digits, \".\", \"_\" or \"-\"`,\n )\n }\n\n const method = input.method\n if (!AUTH_METHODS.includes(method)) {\n throw new AuthProfileValidationError(\n `method must be one of ${AUTH_METHODS.join(\" | \")} (got \"${String(method)}\")`,\n )\n }\n\n // Trim surrounding whitespace only — a pasted token can carry a stray\n // trailing newline, but must not be blank once trimmed.\n const credential = input.credential !== undefined ? input.credential.trim() : undefined\n const source = input.source?.trim()\n\n if (method === \"api-key\") {\n if (source) {\n throw new AuthProfileValidationError(\n \"source is only supported for oauth-bearer profiles — api-key profiles require a credential\",\n )\n }\n if (!credential) throw new AuthProfileValidationError(\"credential is required\")\n } else {\n if (credential && source) {\n throw new AuthProfileValidationError(\n \"give either credential or source, not both — a source-backed profile stores no secret\",\n )\n }\n if (!credential && !source) {\n throw new AuthProfileValidationError(\"credential or source is required\")\n }\n }\n\n const label = input.label?.trim()\n const credentialRef = input.credentialRef?.trim()\n if (credentialRef !== undefined && credentialRef !== \"\" && !SLUG_RE.test(credentialRef)) {\n throw new AuthProfileValidationError(\n `credentialRef \"${credentialRef}\" is invalid — use letters, digits, \".\", \"_\" or \"-\"`,\n )\n }\n\n const origin = input.origin?.trim()\n\n return {\n id,\n endpoint,\n method,\n ...(credential ? { credential } : {}),\n ...(source ? { source } : {}),\n ...(label ? { label } : {}),\n ...(credentialRef ? { credentialRef } : {}),\n ...(origin ? { origin } : {}),\n }\n}\n\n/**\n * Derive the credential-store slot for a profile. Matches the convention of\n * the hand-seeded entries: `agentproto.auth.<endpoint>` for an api-key,\n * `agentproto.auth.<endpoint>.sub` for a subscription (oauth-bearer), plus an\n * optional `<qualifier>` to disambiguate a second profile on the same\n * endpoint+method. Pure.\n */\nexport function deriveCredentialRef(input: {\n endpoint: string\n method: AuthMethod\n qualifier?: string\n}): string {\n const parts = [\"agentproto\", \"auth\", input.endpoint]\n if (input.method === \"oauth-bearer\") parts.push(\"sub\")\n if (input.qualifier) parts.push(input.qualifier)\n return parts.join(\".\")\n}\n\n/** One-way fingerprint of a secret — sha256, first 12 hex chars. Enough to\n * distinguish credentials by eye; not reversible. */\nexport function fingerprintCredential(secret: string): string {\n return createHash(\"sha256\").update(secret, \"utf8\").digest(\"hex\").slice(0, 12)\n}\n\n/** Below this length, `slice(-4)` would expose too large a fraction of the\n * secret to be a safe \"last 4\" — so `last4` is withheld (never the secret).\n * Real API keys / bearer tokens are far longer; this only guards a degenerate\n * short value. */\nconst MIN_LEN_FOR_LAST4 = 8\n\n/** Non-secret identity of a STORED credential — a one-way {@link\n * fingerprintCredential} plus the trailing 4 characters (the standard\n * \"which key is this\" affordance, like a card's last four). Neither is\n * reversible to the secret. `last4` is omitted for a secret too short to\n * reveal a tail safely (see {@link MIN_LEN_FOR_LAST4}) — fail closed rather\n * than expose. */\nexport interface CredentialIdentity {\n fingerprint: string\n last4?: string\n}\n\n/** Compute the non-secret {@link CredentialIdentity} of a stored secret.\n * Money-safety: returns ONLY the one-way fingerprint + a trailing tail —\n * never the secret, and never the tail when the secret is too short to\n * reveal one safely. */\nexport function credentialIdentity(secret: string): CredentialIdentity {\n return {\n fingerprint: fingerprintCredential(secret),\n ...(secret.length >= MIN_LEN_FOR_LAST4 ? { last4: secret.slice(-4) } : {}),\n }\n}\n\n/** The `StoredCredential.kind` a method maps to (mirrors `profile-types.ts`:\n * `pat` → `api-key`, `oat` → `oauth-bearer`). */\nfunction credentialKind(method: AuthMethod): \"pat\" | \"oat\" {\n return method === \"oauth-bearer\" ? \"oat\" : \"pat\"\n}\n\n/**\n * Create a profile end-to-end: validate, derive the credential slot (avoiding\n * collision with an existing profile's slot), write the secret to the store,\n * then record the metadata. Rejects a duplicate id rather than silently\n * overwriting. Returns non-secret metadata + a fingerprint; the credential is\n * never echoed back.\n */\nexport async function createAuthProfile(\n input: CreateAuthProfileInput,\n deps: ProfileProvisionDeps,\n): Promise<CreatedAuthProfile> {\n const v = validateCreateInput(input)\n\n if (await deps.getProfile(v.id)) {\n throw new AuthProfileValidationError(\n `a profile with id \"${v.id}\" already exists — delete it first or pick another id`,\n )\n }\n\n // Source-backed: no secret, nothing written to the credential store.\n if (v.source !== undefined) {\n const profile: AuthProfile = {\n id: v.id,\n endpoint: v.endpoint,\n method: v.method,\n source: v.source,\n ...(v.label ? { label: v.label } : {}),\n ...(v.origin ? { origin: v.origin } : {}),\n }\n await deps.addProfile(profile)\n return {\n id: profile.id,\n endpoint: profile.endpoint,\n method: profile.method,\n source: v.source,\n ...(profile.label ? { label: profile.label } : {}),\n ...(profile.origin ? { origin: profile.origin } : {}),\n }\n }\n\n const credential = v.credential!\n\n const existing = await deps.listProfiles()\n const takenRefs = new Set(existing.map(p => p.credentialRef))\n\n let credentialRef = v.credentialRef ?? deriveCredentialRef(v)\n // If the derived slot already holds another profile's secret, qualify it\n // with the id so two profiles on the same endpoint+method don't clobber\n // each other's keychain entry.\n if (!v.credentialRef && takenRefs.has(credentialRef)) {\n credentialRef = deriveCredentialRef({ ...v, qualifier: v.id })\n }\n\n await deps.store.write(\n { path: credentialRef },\n { value: credential, kind: credentialKind(v.method) },\n )\n\n const profile: AuthProfile = {\n id: v.id,\n endpoint: v.endpoint,\n method: v.method,\n credentialRef,\n ...(v.label ? { label: v.label } : {}),\n ...(v.origin ? { origin: v.origin } : {}),\n }\n await deps.addProfile(profile)\n\n return {\n id: profile.id,\n endpoint: profile.endpoint,\n method: profile.method,\n credentialRef,\n ...(profile.label ? { label: profile.label } : {}),\n ...(profile.origin ? { origin: profile.origin } : {}),\n fingerprint: fingerprintCredential(credential),\n }\n}\n\n/**\n * Delete a profile and its credential. Idempotent: a missing id returns\n * `{ deleted: false }` rather than throwing. The keychain entry is removed\n * only when no OTHER profile still references the same slot — two profiles\n * can legitimately share a `credentialRef`, and dropping one must not strand\n * the other.\n */\nexport async function deleteAuthProfile(\n id: string,\n deps: ProfileProvisionDeps,\n): Promise<DeletedAuthProfile> {\n const trimmed = (id ?? \"\").trim()\n if (!trimmed) throw new AuthProfileValidationError(\"id is required\")\n\n const profile = await deps.getProfile(trimmed)\n if (!profile) return { deleted: false, id: trimmed }\n\n await deps.removeProfile(trimmed)\n\n // Source-backed profiles store no secret — nothing to tear down.\n if (profile.credentialRef === undefined) {\n return { deleted: true, id: trimmed }\n }\n\n const stillReferenced = (await deps.listProfiles()).some(\n p => p.credentialRef === profile.credentialRef,\n )\n if (!stillReferenced && deps.store.delete) {\n await deps.store.delete({ path: profile.credentialRef })\n }\n\n return { deleted: true, id: trimmed, credentialRef: profile.credentialRef }\n}\n\n/**\n * Enable or disable a whole profile (WS2). Metadata-only — never touches the\n * credential store. Enabling CLEARS the `disabled` field entirely rather than\n * writing `disabled: false`, so a re-enabled profile is byte-identical on\n * disk to one that was never disabled (the ABSENT-means-enabled invariant).\n * Throws {@link AuthProfileValidationError} for an unknown id so a host can map\n * it to a 404/400. Returns the updated (non-secret) profile.\n */\nexport async function setAuthProfileEnabled(\n id: string,\n enabled: boolean,\n deps: ProfileProvisionDeps,\n): Promise<AuthProfile> {\n const trimmed = (id ?? \"\").trim()\n if (!trimmed) throw new AuthProfileValidationError(\"id is required\")\n\n const profile = await deps.getProfile(trimmed)\n if (!profile) {\n throw new AuthProfileValidationError(`no profile with id \"${trimmed}\"`)\n }\n\n // Rebuild WITHOUT `disabled`, then re-add it only when disabling — keeps the\n // enabled state absent-by-default.\n const { disabled: _drop, ...rest } = profile\n const updated: AuthProfile = enabled ? { ...rest } : { ...rest, disabled: true }\n await deps.addProfile(updated)\n return updated\n}\n\n/**\n * Set a profile's per-model curation allowlist (WS3). Metadata-only. `mode:\n * \"all\"` CLEARS the `models` field entirely (curation off ⇒ absent, the\n * byte-identical \"services everything\" default), so only a genuine `mode:\n * \"allow\"` persists a `models` object. `ids` are trimmed, de-duped, and\n * blanks dropped. Throws {@link AuthProfileValidationError} for an unknown id.\n * Returns the updated (non-secret) profile.\n */\nexport async function setAuthProfileModels(\n id: string,\n curation: ModelCuration,\n deps: ProfileProvisionDeps,\n): Promise<AuthProfile> {\n const trimmed = (id ?? \"\").trim()\n if (!trimmed) throw new AuthProfileValidationError(\"id is required\")\n if (curation.mode !== \"all\" && curation.mode !== \"allow\") {\n throw new AuthProfileValidationError(\n `models.mode must be \"all\" or \"allow\" (got \"${String(curation.mode)}\")`,\n )\n }\n\n const profile = await deps.getProfile(trimmed)\n if (!profile) {\n throw new AuthProfileValidationError(`no profile with id \"${trimmed}\"`)\n }\n\n const { models: _drop, ...rest } = profile\n if (curation.mode === \"all\") {\n // \"all\" == absent — drop the field so the on-disk shape stays byte-\n // identical to a never-curated profile.\n const updated: AuthProfile = { ...rest }\n await deps.addProfile(updated)\n return updated\n }\n\n const ids = [...new Set((curation.ids ?? []).map(s => s.trim()).filter(Boolean))]\n const updated: AuthProfile = { ...rest, models: { mode: \"allow\", ids } }\n await deps.addProfile(updated)\n return updated\n}\n\n/** The result of {@link refreshAuthProfileModels} — the updated profile plus\n * the diff against the previous allowlist, so a caller (CLI, MCP tool) can\n * report exactly what changed without re-diffing itself. */\nexport interface RefreshAuthProfileModelsResult {\n profile: AuthProfile\n /** Ids newly present in the refreshed allowlist that weren't in the old one. */\n added: string[]\n /** Ids that were in the old allowlist but have dropped out of the current\n * catalog snapshot (e.g. a retired model). */\n removed: string[]\n}\n\n/**\n * Re-sync a `mode: \"allow\"` profile's `ids` against a CURRENT catalog\n * snapshot for its endpoint (WS3 follow-up — fixes curation drift). A\n * profile's allowlist is otherwise a frozen snapshot taken once at\n * create/import time: the catalog moves (new models ship, old ones retire)\n * but `ids` never does, so a profile silently stops seeing new models and\n * keeps offering retired ones. This re-runs the SAME enumeration a caller\n * would have used to build the list in the first place — \"every model\n * currently known for this profile's endpoint\" — against `currentIds`, so\n * `ids` tracks the live catalog instead of the day it was written.\n *\n * `currentIds` is caller-supplied (typically every id `getModelsByProvider`\n * /`buildCatalogProviderModels` reports for `profile.endpoint`) rather than\n * looked up here, keeping this package decoupled from `@agentproto/model-catalog`\n * (see {@link AuthProfile.endpoint}'s doc) and the diffing logic unit-testable\n * against a fake snapshot with no catalog wiring at all.\n *\n * Deliberately EXPLICIT and OPT-IN — a caller (CLI verb, MCP tool) invokes\n * this on one named profile; nothing calls it automatically. A profile a\n * human deliberately narrowed is therefore never touched unless that human\n * (or an operator with the same intent) explicitly asks this profile to be\n * refreshed.\n *\n * Throws {@link AuthProfileValidationError} for an unknown id, and — by\n * design — for a profile with no `mode: \"allow\"` curation to refresh: an\n * absent `models` field (or `mode: \"all\"`) already tracks the live catalog\n * on every read (see `profileAllowsModel` in `catalog-models.ts`), so\n * \"refreshing\" it would be a silent no-op that could mask the caller asking\n * for the wrong profile. Rejecting loudly instead surfaces that mismatch.\n */\nexport async function refreshAuthProfileModels(\n id: string,\n currentIds: readonly string[],\n deps: ProfileProvisionDeps,\n): Promise<RefreshAuthProfileModelsResult> {\n const trimmed = (id ?? \"\").trim()\n if (!trimmed) throw new AuthProfileValidationError(\"id is required\")\n\n const profile = await deps.getProfile(trimmed)\n if (!profile) {\n throw new AuthProfileValidationError(`no profile with id \"${trimmed}\"`)\n }\n if (!profile.models || profile.models.mode !== \"allow\") {\n throw new AuthProfileValidationError(\n `profile \"${trimmed}\" has no mode:\"allow\" curation to refresh — ` +\n `mode:\"all\" (or absent models) already tracks the live catalog on every read`,\n )\n }\n\n const nextIds = [...new Set(currentIds.map(s => s.trim()).filter(Boolean))]\n const prevIds = profile.models.ids\n const prevSet = new Set(prevIds)\n const nextSet = new Set(nextIds)\n const added = nextIds.filter(i => !prevSet.has(i))\n const removed = prevIds.filter(i => !nextSet.has(i))\n\n const updated: AuthProfile = { ...profile, models: { mode: \"allow\", ids: nextIds } }\n await deps.addProfile(updated)\n return { profile: updated, added, removed }\n}\n","/**\n * (adapter × route) → billing-endpoint resolution + the profile eligibility predicate\n * (SPEC §1c, `agentproto-session-config-axes/SPEC.md:102-125`).\n *\n * profile eligible for (adapter, route) iff\n * profile.endpoint == resolveEndpoint(adapter, route).endpoint\n * AND profile.method ∈ methodsPresentable(adapter, route)\n *\n * `route` is the endpoint selector (SPEC axis #4 — direct vs a gateway mode\n * like `moonshot`/`openrouter`), so access is deliberately downstream of it:\n * which endpoint (and thus which profiles) are eligible changes when route\n * changes. `AdapterAuthManifest` is a narrow, package-local projection of\n * exactly what this predicate needs from an adapter's real AIP-45 manifest\n * (`packages/driver/agent-cli/src/types.ts`'s `AgentCliDefinition`) — this\n * package intentionally does not depend on `@agentproto/driver-agent-cli`\n * (wrong dependency direction; drivers consume auth, not vice versa), so the\n * runtime is the one that will later project a real manifest into this\n * shape (out of scope here — foundation only, no live spawn-path wiring).\n *\n * `methodsByRoute` is the static per-endpoint method table ADR'd in SPEC §3.4:\n * \"which auth methods this adapter can present for a resolved route.\" It is\n * the derivable replacement for two hand-maintained artifacts SPEC §1c calls\n * out for eventual removal — the per-adapter `authSubscription` boolean\n * (`adapters/claude-code/src/index.ts:90-95`) and curatorial vendor deny\n * lists (`adapters/hermes/HERMES.md:40-42`) — neither of which this PR\n * touches; `authSubscription` stays exactly as-is (see the comment on it in\n * `spawn-defaults.ts:345` — this module is additive, not a replacement).\n *\n * ACP `authenticate` is NOT a live discovery source for this table (the\n * server handler is a stub, `packages/acp/src/server/index.ts:69`) — method\n * discovery is this static table, not runtime negotiation (SPEC §3.7).\n */\n\nimport type { AuthMethod, AuthProfile } from \"./profile-types.js\"\n\n/** A narrow, package-local projection of an adapter's declared auth\n * capability — enough to resolve (adapter, route) → endpoint and the auth\n * methods presentable on that route. Not the real AIP-45 manifest type. */\nexport interface AdapterAuthManifest {\n /** Adapter id (e.g. \"claude-code\", \"hermes\"), for error messages only. */\n id: string\n /** route id (e.g. \"direct\", or a gateway mode id like \"moonshot\") →\n * the billing endpoint used when spawned on that route. */\n endpointByRoute: Readonly<Record<string, string>>\n /** route id → the auth methods this adapter can present when spawned on\n * that route — the method-side of the eligibility predicate. */\n methodsByRoute: Readonly<Record<string, readonly AuthMethod[]>>\n}\n\n/** Resolve which billing endpoint a given (adapter, route) pair uses. Throws\n * when the manifest declares no endpoint for `route` — an unresolvable route\n * is a caller bug (a bad/unknown route id), not a \"no profiles eligible\"\n * case, so this fails loud rather than returning an empty endpoint. */\nexport function resolveEndpoint(\n manifest: AdapterAuthManifest,\n route: string,\n): { endpoint: string } {\n const endpoint = manifest.endpointByRoute[route]\n if (endpoint === undefined) {\n throw new Error(\n `resolveEndpoint: adapter \"${manifest.id}\" declares no endpoint for route \"${route}\"`,\n )\n }\n return { endpoint }\n}\n\n/** Which auth methods `manifest`'s adapter can present on `route`. Empty\n * (never throws) when the route is declared for vendor resolution but has\n * no methods table entry — that's \"no eligible profiles\", a legitimate\n * eligibility outcome, not an error. */\nexport function methodsPresentable(\n manifest: AdapterAuthManifest,\n route: string,\n): AuthMethod[] {\n return [...(manifest.methodsByRoute[route] ?? [])]\n}\n\n/** The eligibility predicate: profiles whose endpoint matches the route's\n * resolved endpoint AND whose method the adapter can present on that route.\n * A whole-profile-disabled profile (`disabled: true`) is skipped outright —\n * every model it would otherwise service drops to non-runnable (WS2). This is\n * the profile-level gate; per-model curation (`models`) is intersected\n * downstream in the catalog join, not here (SPEC §1c / catalog-models.ts). */\nexport function eligibleProfiles(\n profiles: readonly AuthProfile[],\n manifest: AdapterAuthManifest,\n route: string,\n): AuthProfile[] {\n const { endpoint } = resolveEndpoint(manifest, route)\n const methods = methodsPresentable(manifest, route)\n return profiles.filter(\n p => !p.disabled && p.endpoint === endpoint && methods.includes(p.method),\n )\n}\n","/**\n * @agentproto/auth — AIP-50 AUTH.md reference implementation.\n *\n * Public API:\n * defineAuthProvider(def) — TS-literal authoring (frozen handle)\n * parseAuthProviderManifest(source) — .md authoring (gray-matter + Zod)\n * registerAuthProvider(handle) — extend the module-level registry\n * getAuthProvider(id) — lookup by vendor id\n * listAuthProviderIds() — enumerate known providers\n * discoverEndpoints(apiBase) — two-hop PRM → AS metadata discovery\n * runAuthFlow(provider, opts) — resolve + discover + dispatch to engine\n * FLOW_ENGINES — registered flow engines (pat, …)\n * CeremonyRequiredError — thrown by device-code's refreshOnly\n * mode when only an interactive\n * ceremony would satisfy the request\n * writeKeychainToken(svc, acct, t) — persist a credential to Keychain\n * readKeychainToken(svc, acct) — read a credential from Keychain\n * resolveAccount(acct, server) — expand {server} template\n * KeychainStore / MemoryStore / FileStore — built-in CredentialStore backends\n * resolveStoreRef(spec, server) — map a TokenStoreSpec to a StoreRef\n * CredentialBroker — path → ready-to-use auth headers\n * AuthProfile / AuthMethod — named, endpoint-scoped credential ref\n * listAuthProfiles/getAuthProfile/\n * addAuthProfile/removeAuthProfile — named-profile store CRUD\n * resolveEndpoint/methodsPresentable/\n * eligibleProfiles — (adapter × route) → endpoint + the\n * profile eligibility predicate\n * refreshAuthProfileModels(id, ids) — re-sync a mode:\"allow\" profile's\n * `ids` against a current catalog\n * snapshot (fixes curation drift)\n */\n\nexport { defineAuthProvider } from \"./define-auth-provider.js\"\nexport {\n parseAuthProviderManifest,\n parseAuthProviderManifestRaw,\n type AuthProviderManifest,\n} from \"./manifest.js\"\nexport {\n registerAuthProvider,\n getAuthProvider,\n listAuthProviders,\n listAuthProviderIds,\n} from \"./registry.js\"\nexport {\n discoverEndpoints,\n DiscoveryError,\n} from \"./discover.js\"\nexport { runAuthFlow, type RunFlowOptions } from \"./run-flow.js\"\nexport { FLOW_ENGINES } from \"./flow-engines/index.js\"\nexport { CeremonyRequiredError } from \"./flow-engines/device-code.js\"\nexport {\n readKeychainToken,\n writeKeychainToken,\n deleteKeychainToken,\n resolveAccount,\n} from \"./token-store.js\"\nexport { KeychainStore } from \"./store/keychain-store.js\"\nexport { MemoryStore } from \"./store/memory-store.js\"\nexport { FileStore } from \"./store/file-store.js\"\nexport { resolveStoreRef } from \"./store/resolve-ref.js\"\nexport type {\n CredentialStore,\n StoreRef,\n StoredCredential,\n} from \"./store/types.js\"\nexport { CredentialBroker, type CredentialBrokerOptions } from \"./broker.js\"\nexport type {\n AuthMethod,\n AuthProfile,\n ModelCuration,\n CostBudget,\n CostBudgetScope,\n} from \"./profile-types.js\"\nexport {\n authProfilesPath,\n loadAuthProfiles,\n listAuthProfiles,\n getAuthProfile,\n addAuthProfile,\n removeAuthProfile,\n type AuthProfilesFile,\n} from \"./profile-store.js\"\nexport {\n createAuthProfile,\n deleteAuthProfile,\n setAuthProfileEnabled,\n setAuthProfileModels,\n refreshAuthProfileModels,\n validateCreateInput,\n deriveCredentialRef,\n fingerprintCredential,\n credentialIdentity,\n AuthProfileValidationError,\n type CreateAuthProfileInput,\n type CreatedAuthProfile,\n type DeletedAuthProfile,\n type CredentialIdentity,\n type ProfileProvisionDeps,\n type ValidatedCreateInput,\n type RefreshAuthProfileModelsResult,\n} from \"./profile-provision.js\"\nexport {\n resolveEndpoint,\n methodsPresentable,\n eligibleProfiles,\n type AdapterAuthManifest,\n} from \"./eligibility.js\"\nexport { guildeAuthProvider, BUILTIN_AUTH_PROVIDERS } from \"./builtins.js\"\nexport {\n authProviderFrontmatterSchema,\n authConfigSchema,\n tokenStoreSpecSchema,\n installConfigSchema,\n type AuthProviderFrontmatter,\n} from \"./schema.js\"\nexport type {\n AuthProviderDefinition,\n AuthProviderHandle,\n AuthConfig,\n PATAuthConfig,\n ServiceAuthConfig,\n DeviceCodeAuthConfig,\n InstallConfig,\n TokenStoreSpec,\n FlowEngine,\n FlowId,\n FlowResult,\n FlowRunOptions,\n DiscoveredEndpoints,\n} from \"./types.js\"\n\nexport const SPEC_NAME = \"agentauth\"\nexport const SPEC_VERSION = \"v1\"\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/schema.ts","../src/define-auth-provider.ts","../src/manifest.ts","../src/builtins.ts","../src/registry.ts","../src/http.ts","../src/discover.ts","../src/token-store.ts","../src/store/keychain-store.ts","../src/store/resolve-ref.ts","../src/flow-engines/pat.ts","../src/flow-engines/device-grant.ts","../src/flow-engines/service-auth.ts","../src/flow-engines/device-code.ts","../src/flow-engines/index.ts","../src/run-flow.ts","../src/store/memory-store.ts","../src/store/file-store.ts","../src/broker.ts","../src/profile-store.ts","../src/profile-provision.ts","../src/eligibility.ts","../src/index.ts"],"names":["z","resolve","promisify","execFile","DEFAULT_POLL_INTERVAL_S","keyOf","headers","readFile","mkdir","writeFile","profile","updated"],"mappings":";;;;;;;;;;;;;;;;AAUO,IAAM,oBAAA,GAAuB,EACjC,MAAA,CAAO;AAAA,EACN,QAAA,EAAU,CAAA,CAAE,MAAA,EAAO,CAAE,IAAI,CAAC,CAAA;AAAA,EAC1B,MAAM,CAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAC,EAAE,QAAA,EAAS;AAAA,EACjC,SAAS,CAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAC,EAAE,QAAA;AAC7B,CAAC,EACA,MAAA;AAEI,IAAM,mBAAA,GAAsB,EAChC,MAAA,CAAO;AAAA,EACN,IAAA,EAAM,CAAA,CAAE,OAAA,CAAQ,KAAK,CAAA;AAAA,EACrB,UAAA,EAAY;AACd,CAAC,EACA,MAAA,EAAO;AAEH,IAAM,uBAAA,GAA0B,EACpC,MAAA,CAAO;AAAA,EACN,IAAA,EAAM,CAAA,CAAE,OAAA,CAAQ,cAAc,CAAA;AAAA,EAC9B,UAAU,CAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAC,EAAE,QAAA,EAAS;AAAA,EACrC,WAAW,CAAA,CAAE,MAAA,GAAS,GAAA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AAA;AAAA,KACpF;AAAA,EACF;AACA,EAAA,OAAO,EAAE,QAAA,EAAS;AACpB;AAMO,SAAS,kBAAA,CACd,UACA,KAAA,EACc;AACd,EAAA,OAAO,CAAC,GAAI,QAAA,CAAS,eAAe,KAAK,CAAA,IAAK,EAAG,CAAA;AACnD;AAQO,SAAS,gBAAA,CACd,QAAA,EACA,QAAA,EACA,KAAA,EACe;AACf,EAAA,MAAM,EAAE,QAAA,EAAS,GAAI,eAAA,CAAgB,UAAU,KAAK,CAAA;AACpD,EAAA,MAAM,OAAA,GAAU,kBAAA,CAAmB,QAAA,EAAU,KAAK,CAAA;AAClD,EAAA,OAAO,QAAA,CAAS,MAAA;AAAA,IACd,CAAA,CAAA,KAAK,CAAC,CAAA,CAAE,QAAA,IAAY,CAAA,CAAE,aAAa,QAAA,IAAY,OAAA,CAAQ,QAAA,CAAS,CAAA,CAAE,MAAM;AAAA,GAC1E;AACF;;;ACyCO,IAAM,SAAA,GAAY;AAClB,IAAM,YAAA,GAAe","file":"index.mjs","sourcesContent":["/**\n * AIP-50 auth-provider frontmatter / literal Zod schema.\n *\n * Single source of truth for both authoring paths: `defineAuthProvider`\n * (TS literal) and `parseAuthProviderManifest` (.md) run this same schema,\n * so a malformed literal and a malformed manifest fail identically.\n */\n\nimport { z } from \"zod\"\n\nexport const tokenStoreSpecSchema = z\n .object({\n keychain: z.string().min(1),\n path: z.string().min(1).optional(),\n account: z.string().min(1).optional(),\n })\n .strict()\n\nexport const patAuthConfigSchema = z\n .object({\n flow: z.literal(\"pat\"),\n tokenStore: tokenStoreSpecSchema,\n })\n .strict()\n\nexport const serviceAuthConfigSchema = z\n .object({\n flow: z.literal(\"service-auth\"),\n clientId: z.string().min(1).optional(),\n loginHint: z.string().min(1).optional(),\n tokenStore: tokenStoreSpecSchema,\n })\n .strict()\n\nexport const deviceCodeAuthConfigSchema = z\n .object({\n flow: z.literal(\"device-code\"),\n clientId: z.string().min(1).optional(),\n scope: z.string().min(1).optional(),\n deviceLabel: z.string().min(1).optional(),\n tokenStore: tokenStoreSpecSchema,\n })\n .strict()\n\nexport const authConfigSchema = z.discriminatedUnion(\"flow\", [\n patAuthConfigSchema,\n serviceAuthConfigSchema,\n deviceCodeAuthConfigSchema,\n])\n\nexport const installConfigSchema = z\n .object({\n sealKey: z.string().min(1),\n secretBacked: z.string().min(1),\n })\n .strict()\n\nexport const authProviderFrontmatterSchema = z\n .object({\n id: z.string().min(2).max(80),\n description: z.string().min(1).max(2000),\n apiBase: z.string().url(),\n auth: authConfigSchema,\n install: installConfigSchema.optional(),\n // Recommended values \"tunnel\" | \"api\" | \"mcp\" — free-form allowed, not an enum.\n audience: z.string().min(1).optional(),\n })\n .strict()\n .describe(\n \"AIP-50 auth-provider manifest: how a CLI tool authenticates to an API server and (optionally) where to call the AIP-19 provision endpoints.\",\n )\n\nexport type AuthProviderFrontmatter = z.infer<typeof authProviderFrontmatterSchema>\n","/**\n * `defineAuthProvider` — TS-literal authoring path for an auth-provider.\n *\n * Built on `createDoctype` so it gets the cross-AIP invariants: id-pattern,\n * ≤2000-char description, frozen handle, canonical error prefix. Field-level\n * validation uses the shared Zod from `./schema.ts`, so a malformed literal\n * fails with the same diagnostic as a malformed `.md`.\n */\n\nimport { createDoctype } from \"@agentproto/define-doctype\"\nimport { authProviderFrontmatterSchema } from \"./schema.js\"\nimport type { AuthProviderDefinition, AuthProviderHandle } from \"./types.js\"\n\nexport const defineAuthProvider = createDoctype<\n AuthProviderDefinition,\n AuthProviderHandle\n>({\n aip: 50,\n name: \"authProvider\",\n validate(def) {\n const result = authProviderFrontmatterSchema.safeParse(def)\n if (!result.success) {\n throw new Error(\n `defineAuthProvider (AIP-50): ${result.error.issues\n .map((i) => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \")}`,\n )\n }\n },\n build(def) {\n return {\n ...def,\n auth: Object.freeze({ ...def.auth }),\n install: def.install ? Object.freeze({ ...def.install }) : undefined,\n }\n },\n})\n","/**\n * `.md` authoring path for an auth-provider — parse a frontmatter manifest\n * into a frozen handle. Mirrors `parseRecipeManifest` from AIP-19: gray-matter\n * splits the frontmatter, the shared Zod validates it, `defineAuthProvider`\n * builds the handle so both authoring paths converge on one validated shape.\n *\n * This parser is the extension seam: a host reads its own external `.md`\n * manifests (e.g. vendor-shipped `guilde.auth.md`) and registers them without\n * editing this package.\n */\n\nimport matter from \"gray-matter\"\nimport {\n authProviderFrontmatterSchema,\n type AuthProviderFrontmatter,\n} from \"./schema.js\"\nimport { defineAuthProvider } from \"./define-auth-provider.js\"\nimport type { AuthProviderHandle } from \"./types.js\"\n\nexport interface AuthProviderManifest {\n frontmatter: AuthProviderFrontmatter\n body: string\n}\n\nexport function parseAuthProviderManifestRaw(\n source: string,\n): AuthProviderManifest {\n const parsed = matter(source)\n if (Object.keys(parsed.data).length === 0) {\n throw new Error(\"parseAuthProviderManifest: missing or empty frontmatter\")\n }\n const result = authProviderFrontmatterSchema.safeParse(parsed.data)\n if (!result.success) {\n throw new Error(\n `parseAuthProviderManifest: invalid frontmatter — ${result.error.issues\n .map((i) => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \")}`,\n )\n }\n return { frontmatter: result.data, body: parsed.content }\n}\n\n/** Parse an auth-provider `.md` straight to a frozen handle. */\nexport function parseAuthProviderManifest(source: string): AuthProviderHandle {\n const { frontmatter } = parseAuthProviderManifestRaw(source)\n return defineAuthProvider(frontmatter)\n}\n","/**\n * Builtin auth-provider manifests — shipped as TS literals so they bundle\n * into the tsup output with zero filesystem reads at runtime. A host adds more\n * by parsing its own `.md` with `parseAuthProviderManifest` and registering\n * the result via `registerAuthProvider`.\n */\n\nimport { defineAuthProvider } from \"./define-auth-provider.js\"\nimport type { AuthProviderHandle } from \"./types.js\"\n\n/** Guilde AI company platform.\n *\n * Authenticates via the AIP-50 service-auth claim ceremony: browser opens,\n * user clicks Approve, bureau stores the oat_* access token.\n * Discovery from /.well-known/oauth-protected-resource supplies live endpoints;\n * the static fields below are the offline fallback. */\nexport const guildeAuthProvider = defineAuthProvider({\n id: \"guilde\",\n description:\n \"Guilde AI company platform. Authenticate via a browser-approve flow — no key to paste.\",\n apiBase: \"https://api.guilde.work\",\n audience: \"api\",\n auth: {\n flow: \"service-auth\",\n clientId: \"agentproto-cli\",\n tokenStore: {\n keychain: \"bureau-guilde\",\n account: \"{server}\",\n },\n },\n install: {\n sealKey: \"/guilde/api/v1/connectors/seal-key\",\n secretBacked: \"/guilde/api/v1/guilds/{guildId}/connectors/secret-backed\",\n },\n})\n\nexport const BUILTIN_AUTH_PROVIDERS: readonly AuthProviderHandle[] = [\n guildeAuthProvider,\n]\n","/**\n * Auth-provider registry — id → handle lookup, pre-seeded with builtins.\n *\n * Mirrors the provision-recipe registry shape (AIP-19). Re-registering an id\n * overrides it (last write wins), so a host can shadow a builtin.\n */\n\nimport { BUILTIN_AUTH_PROVIDERS } from \"./builtins.js\"\nimport type { AuthProviderHandle } from \"./types.js\"\n\nconst _registry = new Map<string, AuthProviderHandle>()\nfor (const p of BUILTIN_AUTH_PROVIDERS) _registry.set(p.id, p)\n\nexport function registerAuthProvider(provider: AuthProviderHandle): void {\n _registry.set(provider.id, provider)\n}\n\nexport function getAuthProvider(id: string): AuthProviderHandle | undefined {\n return _registry.get(id)\n}\n\nexport function listAuthProviders(): AuthProviderHandle[] {\n return [..._registry.values()]\n}\n\nexport function listAuthProviderIds(): string[] {\n return [..._registry.keys()]\n}\n","/**\n * Internal HTTP helpers — not part of the public API.\n *\n * Every network call in this package (discovery, the claim ceremony, token\n * refresh) must be bounded: a hung or slow server MUST NOT stall the CLI\n * indefinitely. `deadlineSignal` combines an optional caller `AbortSignal`\n * with a timeout into one signal to hand to `fetch`.\n *\n * Implemented with a plain `AbortController` + `setTimeout` rather than\n * `AbortSignal.any`/`AbortSignal.timeout` so it works on every runtime that\n * ships `fetch`, without assuming a specific Node minor.\n */\n\n/** Default per-request timeout. Discovery and token calls are small JSON\n * round-trips; 10s is generous without hanging an interactive CLI. */\nexport const DEFAULT_HTTP_TIMEOUT_MS = 10_000\n\n/**\n * AIP-50 §Security: discovery and auth requests MUST use HTTPS, to defeat\n * MITM/TOCTOU on the `.well-known` and token endpoints. Loopback http is\n * allowed — it isn't network-exposed — so local development against a dev\n * server keeps working. Throws on any other insecure URL.\n */\nexport function assertSecureUrl(url: string): void {\n let u: URL\n try {\n u = new URL(url)\n } catch {\n throw new Error(`invalid URL: ${url}`)\n }\n if (u.protocol === \"https:\") return\n const host = u.hostname\n const isLoopback =\n host === \"localhost\" ||\n host === \"127.0.0.1\" ||\n host === \"::1\" ||\n host === \"[::1]\" ||\n host.endsWith(\".localhost\")\n if (u.protocol === \"http:\" && isLoopback) return\n throw new Error(\n `insecure URL '${url}' — AIP-50 requires HTTPS for discovery/auth ` +\n `(loopback http is allowed for local development).`,\n )\n}\n\nexport interface DeadlineHandle {\n /** Signal to pass to `fetch(url, { signal })`. */\n signal: AbortSignal\n /** Cancel the timer + detach the outer listener once the request settles.\n * ALWAYS call this in a `finally` to avoid a dangling timer/listener. */\n clear: () => void\n}\n\n/**\n * Build an `AbortSignal` that fires when EITHER the timeout elapses or the\n * caller's `outer` signal aborts.\n */\nexport function deadlineSignal(\n timeoutMs: number,\n outer?: AbortSignal,\n): DeadlineHandle {\n const ctrl = new AbortController()\n const onAbort = () => ctrl.abort(outer?.reason)\n\n if (outer) {\n if (outer.aborted) ctrl.abort(outer.reason)\n else outer.addEventListener(\"abort\", onAbort, { once: true })\n }\n\n const timer = setTimeout(\n () => ctrl.abort(new Error(`request timed out after ${timeoutMs}ms`)),\n timeoutMs,\n )\n // Don't let a pending timeout keep the process alive on its own.\n if (typeof timer !== \"number\") timer.unref()\n\n return {\n signal: ctrl.signal,\n clear: () => {\n clearTimeout(timer)\n outer?.removeEventListener(\"abort\", onAbort)\n },\n }\n}\n\n/** `fetch` bounded by `deadlineSignal`. Merges any caller-supplied\n * `init.signal` with the timeout. */\nexport async function fetchWithDeadline(\n url: string,\n init: RequestInit = {},\n timeoutMs: number = DEFAULT_HTTP_TIMEOUT_MS,\n): Promise<Response> {\n const { signal, clear } = deadlineSignal(timeoutMs, init.signal ?? undefined)\n try {\n return await fetch(url, { ...init, signal })\n } finally {\n clear()\n }\n}\n","/**\n * Two-hop discovery per the auth.md standard (AIP-50 §Discovery algorithm),\n * with a second strategy for hosts that don't speak auth.md.\n *\n * Strategy 1 (OAuth PRM chain):\n * Hop 1: GET {apiBase}/.well-known/oauth-protected-resource (PRM, RFC 8414)\n * → extract authorization_servers[0] as authServerBase\n * Hop 2: GET {authServerBase}/.well-known/oauth-authorization-server (AS metadata)\n * → extract token_endpoint + agent_auth block\n *\n * Strategy 2 (agentproto-host.json), tried when strategy 1 fails:\n * GET {apiBase}/.well-known/agentproto-host.json\n * → extract device_authorization_endpoint + token_endpoint\n *\n * Callers MUST catch DiscoveryError and fall back to static manifest config —\n * discovery failures are common (server predates auth.md) and MUST NOT prevent\n * the PAT or other static flows from working.\n */\n\nimport { z } from \"zod\"\nimport type { DiscoveredEndpoints } from \"./types.js\"\nimport { fetchWithDeadline, assertSecureUrl } from \"./http.js\"\n\nexport class DiscoveryError extends Error {\n readonly serverUrl: string\n constructor(message: string, serverUrl: string) {\n super(`DiscoveryError (${serverUrl}): ${message}`)\n this.name = \"DiscoveryError\"\n this.serverUrl = serverUrl\n }\n}\n\n// Discovery JSON is server-controlled, so it's validated rather than asserted.\n// Everything is optional + `.loose()`: the document evolves, and the required\n// fields are enforced explicitly below with precise DiscoveryError messages.\nconst prmSchema = z\n .object({\n resource: z.string().optional(),\n resource_name: z.string().optional(),\n authorization_servers: z.array(z.string()).optional(),\n scopes_supported: z.array(z.string()).optional(),\n bearer_methods_supported: z.array(z.string()).optional(),\n })\n .loose()\n\nconst asMetaSchema = z\n .object({\n issuer: z.string().optional(),\n token_endpoint: z.string().optional(),\n revocation_endpoint: z.string().optional(),\n device_authorization_endpoint: z.string().optional(),\n grant_types_supported: z.array(z.string()).optional(),\n agent_auth: z\n .object({\n skill: z.string().optional(),\n identity_endpoint: z.string().optional(),\n claim_endpoint: z.string().optional(),\n events_endpoint: z.string().optional(),\n identity_types_supported: z.array(z.string()).optional(),\n identity_assertion: z\n .object({ assertion_types_supported: z.array(z.string()).optional() })\n .loose()\n .optional(),\n })\n .loose()\n .optional(),\n })\n .loose()\n\nconst hostJsonSchema = z\n .object({\n device_authorization_endpoint: z.string().optional(),\n token_endpoint: z.string().optional(),\n revocation_endpoint: z.string().optional(),\n })\n .loose()\n\ntype PRMShape = z.infer<typeof prmSchema>\ntype ASMetaShape = z.infer<typeof asMetaSchema>\ntype HostJsonShape = z.infer<typeof hostJsonSchema>\n\nexport interface DiscoverOptions {\n /** Abort the discovery fetches (e.g. on user Ctrl-C). */\n signal?: AbortSignal\n /** Per-hop timeout. Defaults to DEFAULT_HTTP_TIMEOUT_MS. */\n timeoutMs?: number\n}\n\nasync function discoverViaPRM(\n base: string,\n fetchOpts: RequestInit,\n opts: DiscoverOptions,\n): Promise<DiscoveredEndpoints> {\n // Hop 1 — PRM\n const prmUrl = `${base}/.well-known/oauth-protected-resource`\n let prm: PRMShape\n try {\n assertSecureUrl(prmUrl)\n const res = await fetchWithDeadline(prmUrl, fetchOpts, opts.timeoutMs)\n if (!res.ok) {\n throw new DiscoveryError(\n `PRM returned ${res.status} ${res.statusText}`,\n base,\n )\n }\n prm = prmSchema.parse(await res.json())\n } catch (err) {\n if (err instanceof DiscoveryError) throw err\n throw new DiscoveryError(`PRM fetch failed: ${err}`, base)\n }\n\n const authServerBase = prm.authorization_servers?.[0]?.replace(/\\/$/, \"\")\n if (!authServerBase) {\n throw new DiscoveryError(\n \"PRM missing authorization_servers[0]\",\n base,\n )\n }\n\n // Hop 2 — AS metadata\n const asUrl = `${authServerBase}/.well-known/oauth-authorization-server`\n let as: ASMetaShape\n try {\n assertSecureUrl(asUrl)\n const res = await fetchWithDeadline(asUrl, fetchOpts, opts.timeoutMs)\n if (!res.ok) {\n throw new DiscoveryError(\n `AS metadata returned ${res.status} ${res.statusText}`,\n base,\n )\n }\n as = asMetaSchema.parse(await res.json())\n } catch (err) {\n if (err instanceof DiscoveryError) throw err\n throw new DiscoveryError(`AS metadata fetch failed: ${err}`, base)\n }\n\n const tokenEndpoint = as.token_endpoint\n const identityEndpoint = as.agent_auth?.identity_endpoint\n if (!tokenEndpoint) {\n throw new DiscoveryError(\"AS metadata missing token_endpoint\", base)\n }\n if (!identityEndpoint) {\n throw new DiscoveryError(\n \"AS metadata missing agent_auth.identity_endpoint\",\n base,\n )\n }\n\n return {\n resource: prm.resource ?? base,\n resourceName: prm.resource_name,\n authServerBase,\n tokenEndpoint,\n revocationEndpoint: as.revocation_endpoint,\n identityEndpoint,\n claimEndpoint: as.agent_auth?.claim_endpoint,\n deviceAuthorizationEndpoint: as.device_authorization_endpoint,\n identityTypesSupported: as.agent_auth?.identity_types_supported ?? [],\n grantTypesSupported: as.grant_types_supported ?? [],\n }\n}\n\nasync function discoverViaHostJson(\n base: string,\n fetchOpts: RequestInit,\n opts: DiscoverOptions,\n): Promise<DiscoveredEndpoints> {\n const url = `${base}/.well-known/agentproto-host.json`\n let doc: HostJsonShape\n try {\n assertSecureUrl(url)\n const res = await fetchWithDeadline(url, fetchOpts, opts.timeoutMs)\n if (!res.ok) {\n throw new DiscoveryError(\n `agentproto-host.json returned ${res.status} ${res.statusText}`,\n base,\n )\n }\n doc = hostJsonSchema.parse(await res.json())\n } catch (err) {\n if (err instanceof DiscoveryError) throw err\n throw new DiscoveryError(`agentproto-host.json fetch failed: ${err}`, base)\n }\n\n if (!doc.token_endpoint) {\n throw new DiscoveryError(\n \"agentproto-host.json missing token_endpoint\",\n base,\n )\n }\n if (!doc.device_authorization_endpoint) {\n throw new DiscoveryError(\n \"agentproto-host.json missing device_authorization_endpoint\",\n base,\n )\n }\n\n return {\n resource: base,\n authServerBase: base,\n tokenEndpoint: doc.token_endpoint,\n revocationEndpoint: doc.revocation_endpoint,\n deviceAuthorizationEndpoint: doc.device_authorization_endpoint,\n identityTypesSupported: [],\n grantTypesSupported: [],\n }\n}\n\nexport async function discoverEndpoints(\n apiBase: string,\n opts: DiscoverOptions = {},\n): Promise<DiscoveredEndpoints> {\n const base = apiBase.replace(/\\/$/, \"\")\n // AIP-50 §Security: HTTPS only (loopback exempt for dev), and never follow\n // redirects on discovery — a 3xx is treated as a failure, not chased to a\n // potentially-rogue endpoint.\n const fetchOpts: RequestInit = {\n signal: opts.signal,\n redirect: \"manual\",\n }\n\n try {\n return await discoverViaPRM(base, fetchOpts, opts)\n } catch (prmErr) {\n // A caller-initiated abort is terminal — don't fire a second round of\n // requests on a signal that has already aborted (its \"abort\" event has\n // already fired once and a fresh listener on it will never see it again,\n // hanging the fallback forever).\n if (opts.signal?.aborted) throw prmErr\n // Second strategy: a host that doesn't speak the auth.md PRM chain may\n // still expose device-code endpoints via agentproto-host.json. If that\n // also fails, surface the ORIGINAL PRM error — it's almost always the\n // more informative one (host.json 404s are the common case).\n try {\n return await discoverViaHostJson(base, fetchOpts, opts)\n } catch {\n throw prmErr\n }\n }\n}\n","/**\n * Keychain helpers — read/write a token in the platform Keychain.\n *\n * Uses the macOS `security` CLI. On non-macOS hosts, callers should swap this\n * module for a platform-appropriate equivalent (libsecret on Linux, Credential\n * Manager on Windows).\n */\n\nimport { execFile } from \"node:child_process\"\nimport { promisify } from \"node:util\"\n\nconst exec = promisify(execFile)\n\n/**\n * Guard the macOS-only backend. Without this, `readKeychainToken` would swallow\n * the missing-`security` error and return undefined on Linux/Windows — making a\n * stored credential look absent and re-prompting on every run — while\n * `writeKeychainToken` would throw an opaque ENOENT. Fail loudly and clearly\n * instead, until a libsecret / Credential Manager backend exists.\n */\nfunction assertKeychainSupported(): void {\n if (process.platform !== \"darwin\") {\n throw new Error(\n `@agentproto/auth token-store: the Keychain backend only supports macOS ` +\n `(got platform \"${process.platform}\"). Provide a libsecret (Linux) or ` +\n `Credential Manager (Windows) implementation to run here.`,\n )\n }\n}\n\n/** Substitute `{server}` template in a tokenStore account spec. */\nexport function resolveAccount(\n account: string | undefined,\n server: string,\n): string {\n if (!account) return server\n return account.replace(\"{server}\", server)\n}\n\n/** Read a token from the Keychain. Returns undefined if not found. */\nexport async function readKeychainToken(\n service: string,\n account: string,\n): Promise<string | undefined> {\n assertKeychainSupported()\n try {\n const { stdout } = await exec(\"security\", [\n \"find-generic-password\",\n \"-s\",\n service,\n \"-a\",\n account,\n \"-w\",\n ])\n const t = stdout.replace(/\\n$/, \"\")\n return t || undefined\n } catch {\n return undefined\n }\n}\n\n/** Write a token to the Keychain (-U updates in place). */\nexport async function writeKeychainToken(\n service: string,\n account: string,\n token: string,\n): Promise<void> {\n assertKeychainSupported()\n await exec(\"security\", [\n \"add-generic-password\",\n \"-U\",\n \"-s\",\n service,\n \"-a\",\n account,\n \"-w\",\n token,\n \"-D\",\n \"agentproto auth token\",\n ])\n}\n\n/** Remove a token from the Keychain. Returns true if an entry was deleted,\n * false when none existed (a delete of an absent entry is not an error —\n * the desired end state, \"no credential at this slot\", already holds). */\nexport async function deleteKeychainToken(\n service: string,\n account: string,\n): Promise<boolean> {\n assertKeychainSupported()\n try {\n await exec(\"security\", [\n \"delete-generic-password\",\n \"-s\",\n service,\n \"-a\",\n account,\n ])\n return true\n } catch {\n // `security` exits non-zero when the item isn't found — treat as a no-op.\n return false\n }\n}\n","/**\n * KeychainStore — `CredentialStore` backed by the platform Keychain.\n *\n * Wraps the low-level `token-store.ts` helpers (macOS `security` CLI today).\n * The Keychain only holds one opaque string per entry, so `kind`/`expiresAt`/\n * `metadata` are packed into a small JSON envelope that IS that string.\n *\n * Back-compat: an entry written before this store existed (or by any other\n * tool) is a bare token string, not an envelope. `read` falls back to\n * treating the whole string as the value with kind `\"pat\"` — the only flow\n * that pre-dates this store — rather than failing on non-JSON content.\n */\n\nimport { z } from \"zod\"\nimport {\n deleteKeychainToken,\n readKeychainToken,\n writeKeychainToken,\n} from \"../token-store.js\"\nimport type { CredentialStore, StoreRef, StoredCredential } from \"./types.js\"\n\nconst envelopeSchema = z.object({\n v: z.string(),\n k: z.enum([\"pat\", \"assertion\", \"oat\", \"daemon\"]),\n e: z.string().optional(),\n m: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport class KeychainStore implements CredentialStore {\n async read(ref: StoreRef): Promise<StoredCredential | undefined> {\n const account = ref.account ?? ref.path\n const raw = await readKeychainToken(ref.path, account)\n if (raw === undefined) return undefined\n\n try {\n const envelope = envelopeSchema.parse(JSON.parse(raw))\n return {\n value: envelope.v,\n kind: envelope.k,\n ...(envelope.e !== undefined ? { expiresAt: envelope.e } : {}),\n ...(envelope.m !== undefined ? { metadata: envelope.m } : {}),\n }\n } catch {\n return { value: raw, kind: \"pat\" }\n }\n }\n\n async write(ref: StoreRef, cred: StoredCredential): Promise<void> {\n const account = ref.account ?? ref.path\n const envelope: z.infer<typeof envelopeSchema> = {\n v: cred.value,\n k: cred.kind,\n ...(cred.expiresAt !== undefined ? { e: cred.expiresAt } : {}),\n ...(cred.metadata !== undefined ? { m: cred.metadata } : {}),\n }\n await writeKeychainToken(ref.path, account, JSON.stringify(envelope))\n }\n\n async delete(ref: StoreRef): Promise<void> {\n const account = ref.account ?? ref.path\n await deleteKeychainToken(ref.path, account)\n }\n}\n","/**\n * Map a provider's `TokenStoreSpec` to a backend-agnostic `StoreRef`.\n *\n * Shared by every flow engine so the `path`/`keychain` back-compat alias and\n * the `{server}` account template are resolved identically everywhere.\n */\n\nimport { resolveAccount } from \"../token-store.js\"\nimport type { TokenStoreSpec } from \"../types.js\"\nimport type { CredentialStore, StoreRef, StoredCredential } from \"./types.js\"\n\n/** When `audience` is declared, it's folded into the physical store key —\n * `${audience}:${path}` — so credentials scoped to different audiences\n * (e.g. \"tunnel\" vs \"api\") never collide under the same slot. Absent\n * `audience` = today's unprefixed path, unchanged. */\nexport function resolveStoreRef(\n spec: TokenStoreSpec,\n server: string,\n audience?: string,\n): StoreRef {\n const path = spec.path ?? spec.keychain\n return {\n path: audience ? `${audience}:${path}` : path,\n account: resolveAccount(spec.account, server),\n }\n}\n\n/** Derive both the audience-prefixed `ref` and the unprefixed `legacyRef` in\n * one call — the pair every flow engine and the broker need for the\n * audience back-compat read (`readStoreRefWithFallback`). When no audience\n * is declared, `legacyRef === ref` (same object), matching `resolveStoreRef`\n * called with `audience` undefined. */\nexport function resolveStoreRefs(\n spec: TokenStoreSpec,\n server: string,\n audience?: string,\n): { ref: StoreRef; legacyRef: StoreRef } {\n const ref = resolveStoreRef(spec, server, audience)\n const legacyRef = audience ? resolveStoreRef(spec, server) : ref\n return { ref, legacyRef }\n}\n\n/**\n * Read through `ref`, falling back once to `legacyRef` on a miss.\n *\n * This is the read half of the audience back-compat rule: a write always\n * targets the audience-prefixed ref, but a credential written before the\n * provider adopted an audience still lives at the unprefixed (legacy) path.\n * Rather than duplicate that fallback at every flow-engine/broker read site,\n * it lives here, next to `resolveStoreRef` — the one place that already\n * knows how prefixed vs. legacy refs are derived. Callers that don't declare\n * an audience pass `ref === legacyRef` (or just call `store.read` directly);\n * this only does extra work when the two refs actually differ.\n */\nexport async function readStoreRefWithFallback(\n store: CredentialStore,\n ref: StoreRef,\n legacyRef: StoreRef,\n): Promise<StoredCredential | undefined> {\n const stored = await store.read(ref)\n if (stored) return stored\n if (ref.path === legacyRef.path && ref.account === legacyRef.account) {\n return undefined\n }\n return store.read(legacyRef)\n}\n","/**\n * PAT flow engine — reads an existing token from the Keychain or prompts for one.\n *\n * This is the \"legacy-compatible\" flow: the user has a personal API key\n * (`gld_*`, `sk-*`, …) and the CLI needs to store/retrieve it. No browser\n * open, no ceremony. Use `service-auth` for the seamless browser-approve path.\n */\n\nimport { createInterface } from \"node:readline\"\nimport type {\n FlowEngine,\n FlowRunOptions,\n FlowResult,\n AuthProviderHandle,\n DiscoveredEndpoints,\n} from \"../types.js\"\nimport { KeychainStore } from \"../store/keychain-store.js\"\nimport { resolveStoreRefs, readStoreRefWithFallback } from \"../store/resolve-ref.js\"\n\n/**\n * Read a secret from the terminal WITHOUT echoing it — the typed key must not\n * land on screen or in scrollback. On a TTY we drop to raw mode and render a `*`\n * mask per character. When stdin isn't a TTY (piped input, CI, tests) there's no\n * echo to suppress and no raw mode to enter, so we read a line normally.\n */\nasync function promptToken(label: string): Promise<string> {\n const input = process.stdin\n const out = process.stderr\n\n if (!input.isTTY) {\n return new Promise((resolve) => {\n const rl = createInterface({ input, output: out })\n out.write(`${label}: `)\n rl.question(\"\", (answer) => {\n rl.close()\n resolve(answer.trim())\n })\n })\n }\n\n return new Promise((resolve, reject) => {\n out.write(`${label}: `)\n const chars: string[] = []\n input.setRawMode(true)\n input.resume()\n input.setEncoding(\"utf8\")\n\n const cleanup = () => {\n input.setRawMode(false)\n input.pause()\n input.removeListener(\"data\", onData)\n }\n\n const onData = (chunk: string) => {\n for (const ch of chunk) {\n switch (ch) {\n case \"\\r\":\n case \"\\n\":\n out.write(\"\\n\")\n cleanup()\n resolve(chars.join(\"\").trim())\n return\n case \"\\u0003\": // Ctrl-C\n out.write(\"\\n\")\n cleanup()\n reject(new Error(\"auth cancelled\"))\n return\n case \"\\u0004\": // Ctrl-D — treat as end-of-input\n out.write(\"\\n\")\n cleanup()\n resolve(chars.join(\"\").trim())\n return\n case \"\\u007f\": // Backspace / Delete\n case \"\\b\":\n if (chars.length > 0) {\n chars.pop()\n out.write(\"\\b \\b\")\n }\n break\n default:\n // Mask printable input; ignore stray control characters.\n if (ch >= \" \") {\n chars.push(ch)\n out.write(\"*\")\n }\n }\n }\n }\n\n input.on(\"data\", onData)\n })\n}\n\nexport const patFlowEngine: FlowEngine = {\n id: \"pat\",\n\n async run(\n provider: AuthProviderHandle,\n _discovered: DiscoveredEndpoints | null,\n opts: FlowRunOptions,\n ): Promise<FlowResult> {\n const { auth } = provider\n if (auth.flow !== \"pat\") {\n throw new Error(`patFlowEngine: invoked with flow=\"${auth.flow}\"`)\n }\n\n const store = opts.store ?? new KeychainStore()\n const { ref, legacyRef } = resolveStoreRefs(\n auth.tokenStore,\n opts.server,\n provider.audience,\n )\n\n if (!opts.force) {\n const existing = await readStoreRefWithFallback(store, ref, legacyRef)\n if (existing) {\n return { accessToken: existing.value, tokenKind: \"pat\" }\n }\n }\n\n const token = await promptToken(`${provider.id} personal access token`)\n if (!token) throw new Error(\"no token provided\")\n\n await store.write(ref, { value: token, kind: \"pat\" })\n\n return { accessToken: token, tokenKind: \"pat\" }\n },\n}\n","/**\n * Shared RFC 8628 device-grant polling primitive (internal, not exported from\n * the package root).\n *\n * Both the auth.md claim ceremony (`service-auth.ts`) and the device-code flow\n * poll an OAuth token endpoint with a grant-specific URN until the AS reports\n * success or a terminal error. This module holds that shared poll loop plus\n * the small HTTP/browser helpers both flows need — lifted verbatim from\n * `service-auth.ts` so new flow engines have somewhere to reuse them from.\n */\n\nimport { execFile } from \"node:child_process\"\nimport { promisify } from \"node:util\"\nimport { z } from \"zod\"\nimport { fetchWithDeadline } from \"../http.js\"\n\nconst execAsync = promisify(execFile)\n\n// ── response schemas ──────────────────────────────────────────────────────────\n//\n// JSON crosses a trust boundary here (the AS controls the bytes), so every\n// response is validated with Zod rather than asserted. `.loose()` keeps unknown\n// fields the spec may add. The inferred types feed the rest of the engine.\n\n/** Successful token/refresh/exchange response — the AS minted a credential. */\nexport const tokenSuccessSchema = z\n .object({\n access_token: z.string(),\n token_type: z.string().optional(),\n refresh_token: z.string().optional(),\n identity_assertion: z.string().optional(),\n assertion_expires_in: z.number().optional(),\n assertion_expires: z.string().optional(),\n // device-code flow fields (ignored by service-auth today; see WP-2).\n expires_in: z.number().optional(),\n scope: z.string().optional(),\n subject: z.string().optional(),\n revocation_id: z.string().optional(),\n })\n .loose()\n\n/** OAuth error response (`authorization_pending`, `slow_down`, `access_denied`…). */\nexport const tokenErrorSchema = z\n .object({\n error: z.string(),\n error_description: z.string().optional(),\n })\n .loose()\n\n/** A token endpoint reply is either a minted credential or an OAuth error.\n * Success is tried first so a body carrying an access_token never matches the\n * error arm. */\nexport const tokenResponseSchema = z.union([tokenSuccessSchema, tokenErrorSchema])\n\nexport type TokenSuccess = z.infer<typeof tokenSuccessSchema>\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nexport async function openBrowser(url: string): Promise<void> {\n const [cmd, args]: [string, string[]] =\n process.platform === \"darwin\"\n ? [\"open\", [url]]\n : process.platform === \"win32\"\n ? [\"cmd\", [\"/c\", \"start\", url]]\n : [\"xdg-open\", [url]]\n try {\n await execAsync(cmd, args)\n } catch {\n // best-effort — URL already printed to stderr\n }\n}\n\n// NOTE: deliberately does NOT check res.ok — the OAuth device/claim flow returns\n// HTTP 400 with a JSON `{ error }` body for authorization_pending / slow_down,\n// which the poll loop reads as data. Throwing on non-2xx would break polling.\nexport async function postFormOAuth<T>(\n url: string,\n params: Record<string, string>,\n schema: z.ZodType<T>,\n signal?: AbortSignal,\n): Promise<T> {\n const res = await fetchWithDeadline(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams(params).toString(),\n signal,\n })\n return schema.parse(await res.json())\n}\n\nexport interface DeviceGrantPollOptions {\n /** Token endpoint URL to poll. */\n tokenEndpoint: string\n /** Grant-type URN sent on every poll (e.g. the claim or device_code grant). */\n grantType: string\n /** Token-carrying form params — e.g. `claim_token`/`device_code` plus\n * `client_id`. `grant_type` is added automatically; do not include it here. */\n params: Record<string, string>\n /** Poll interval in seconds; grows by 5s on each `slow_down`. */\n intervalS: number\n /** Approval window in seconds, measured from when polling starts. */\n expiresIn: number\n signal?: AbortSignal\n}\n\n/** RFC 8628 poll loop shared by every grant that polls a token endpoint for\n * user approval (auth.md claim ceremony, device-code). */\nexport async function pollDeviceGrant(\n o: DeviceGrantPollOptions,\n): Promise<TokenSuccess> {\n const deadline = Date.now() + o.expiresIn * 1_000\n let pollMs = o.intervalS * 1_000\n\n while (Date.now() < deadline) {\n if (o.signal?.aborted) throw new Error(\"auth cancelled\")\n await new Promise<void>((r) => setTimeout(r, pollMs))\n\n const data = await postFormOAuth(\n o.tokenEndpoint,\n { grant_type: o.grantType, ...o.params },\n tokenResponseSchema,\n o.signal,\n )\n\n if (!(\"error\" in data)) return data\n\n const pollErr = data.error\n if (pollErr === \"authorization_pending\") continue\n if (pollErr === \"slow_down\") {\n pollMs += 5_000\n continue\n }\n if (pollErr === \"expired_token\") {\n throw new Error(\"auth timeout — claim expired before user approved\")\n }\n if (pollErr === \"access_denied\") {\n throw new Error(\"access denied — user rejected the authorisation request\")\n }\n\n const desc = data.error_description\n throw new Error(`token endpoint error: ${pollErr}${desc ? ` — ${desc}` : \"\"}`)\n }\n\n throw new Error(\"auth timeout — approval window closed\")\n}\n","/**\n * service-auth flow engine — auth.md claim ceremony.\n *\n * Protocol:\n * POST /agent/identity { type:\"service_auth\" }\n * → registration_id + claim_token + user_code + verification_uri\n * User approves at verification_uri in browser.\n * Poll POST {token_endpoint} with grant_type=urn:workos:agent-auth:grant-type:claim\n * until approved / denied / expired.\n * On success: store the identity_assertion JWT (AIP-50 §Token storage —\n * the assertion is the durable credential; the access_token MUST NOT be\n * persisted, and the claim_token stays in memory only).\n *\n * Subsequent runs skip the ceremony: the stored assertion is exchanged via the\n * jwt-bearer grant for a fresh access_token (\"this IS the refresh path\" — no\n * refresh_token). Only when the assertion is expired/rejected does a new\n * ceremony start.\n *\n * See: https://github.com/workos/auth.md / AIP-50\n */\n\nimport { z } from \"zod\"\nimport type {\n FlowEngine,\n FlowRunOptions,\n FlowResult,\n AuthProviderHandle,\n DiscoveredEndpoints,\n} from \"../types.js\"\nimport { KeychainStore } from \"../store/keychain-store.js\"\nimport { resolveStoreRefs, readStoreRefWithFallback } from \"../store/resolve-ref.js\"\nimport { fetchWithDeadline, assertSecureUrl } from \"../http.js\"\nimport {\n openBrowser,\n postFormOAuth,\n pollDeviceGrant,\n tokenResponseSchema,\n type TokenSuccess,\n} from \"./device-grant.js\"\n\nconst CLAIM_GRANT_TYPE = \"urn:workos:agent-auth:grant-type:claim\"\nconst JWT_BEARER_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:jwt-bearer\"\nconst DEFAULT_POLL_INTERVAL_S = 5\n\n// ── response schemas ──────────────────────────────────────────────────────────\n//\n// JSON crosses a trust boundary here (the AS controls the bytes), so every\n// response is validated with Zod rather than asserted. `.loose()` keeps unknown\n// fields the spec may add. The inferred types feed the rest of the engine.\n// (Token success/error schemas live in device-grant.ts, shared with every flow\n// that polls a token endpoint.)\n\nconst identityResponseSchema = z\n .object({\n registration_id: z.string(),\n claim_token: z.string(),\n claim: z\n .object({\n user_code: z.string(),\n verification_uri: z.string(),\n expires_in: z.number(),\n interval: z.number().optional(),\n })\n .loose(),\n })\n .loose()\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nasync function postJson<T>(\n url: string,\n body: unknown,\n schema: z.ZodType<T>,\n signal?: AbortSignal,\n): Promise<T> {\n const res = await fetchWithDeadline(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n signal,\n })\n if (!res.ok) {\n const text = await res.text()\n throw new Error(`POST ${url} → ${res.status}: ${text}`)\n }\n return schema.parse(await res.json())\n}\n\n// ── Identity-assertion exchange (jwt-bearer, RFC 7523) ────────────────────────\n//\n// The stored credential IS the identity_assertion JWT. Exchange it at the token\n// endpoint for a fresh, short-lived access token — the AIP-50 refresh path, with\n// no refresh_token involved. Returns null on any error (expired / invalid_grant\n// / server doesn't support the grant) so the caller falls back to a ceremony.\nasync function exchangeAssertion(\n tokenEndpoint: string,\n assertion: string,\n clientId: string,\n signal?: AbortSignal,\n): Promise<TokenSuccess | null> {\n try {\n const data = await postFormOAuth(\n tokenEndpoint,\n {\n grant_type: JWT_BEARER_GRANT_TYPE,\n assertion,\n client_id: clientId,\n },\n tokenResponseSchema,\n signal,\n )\n if (\"error\" in data) return null\n return data\n } catch {\n return null\n }\n}\n\n// ── engine ───────────────────────────────────────────────────────────────────\n\nexport const serviceAuthFlowEngine: FlowEngine = {\n id: \"service-auth\",\n\n async run(\n provider: AuthProviderHandle,\n discovered: DiscoveredEndpoints | null,\n opts: FlowRunOptions,\n ): Promise<FlowResult> {\n const { auth } = provider\n if (auth.flow !== \"service-auth\") {\n throw new Error(`serviceAuthFlowEngine: invoked with flow=\"${auth.flow}\"`)\n }\n // `auth.flow === \"service-auth\"` is guaranteed by the guard above, so the\n // discriminated union has already narrowed `auth` to ServiceAuthConfig.\n const config = auth\n const clientId = config.clientId ?? \"agentproto-cli\"\n const server = opts.server.replace(/\\/$/, \"\")\n\n // Endpoint resolution — prefer live discovery, fall back to conventions\n const identityEndpoint =\n discovered?.identityEndpoint ?? `${server}/agent/identity`\n const tokenEndpoint =\n discovered?.tokenEndpoint ?? `${server}/oauth/token`\n\n // AIP-50 §Security: auth requests MUST use HTTPS (loopback exempt for dev).\n assertSecureUrl(identityEndpoint)\n assertSecureUrl(tokenEndpoint)\n\n const store = opts.store ?? new KeychainStore()\n const { ref, legacyRef } = resolveStoreRefs(\n config.tokenStore,\n server,\n provider.audience,\n )\n\n // Cached path — the stored credential IS the identity_assertion JWT (AIP-50:\n // never the access token, never a refresh token). Exchange it via jwt-bearer\n // for a fresh access token; on failure (expired / invalid_grant) fall through\n // to a full browser ceremony.\n if (!opts.force) {\n const stored = await readStoreRefWithFallback(store, ref, legacyRef)\n if (stored) {\n const exchanged = await exchangeAssertion(\n tokenEndpoint,\n stored.value,\n clientId,\n opts.signal,\n )\n if (exchanged) {\n // If the server rotated the assertion, persist the new one; otherwise\n // the existing assertion stays valid for the next exchange.\n if (exchanged.identity_assertion) {\n await store.write(ref, {\n value: exchanged.identity_assertion,\n kind: \"assertion\",\n })\n }\n return {\n accessToken: exchanged.access_token,\n ...(exchanged.identity_assertion\n ? { identityAssertion: exchanged.identity_assertion }\n : {}),\n tokenKind: \"oat\",\n }\n }\n }\n }\n\n // 1 — POST /agent/identity to start the claim ceremony\n const identity = await postJson(\n identityEndpoint,\n {\n type: \"service_auth\",\n client_id: clientId,\n ...(config.loginHint ? { login_hint: config.loginHint } : {}),\n },\n identityResponseSchema,\n opts.signal,\n )\n\n const { claim_token, claim } = identity\n const intervalS = claim.interval ?? DEFAULT_POLL_INTERVAL_S\n const windowMin = Math.round(claim.expires_in / 60)\n\n // 2 — Print code + open browser\n process.stderr.write(`\\n`)\n process.stderr.write(` Approve ${provider.id} access in your browser\\n\\n`)\n process.stderr.write(` Code: ${claim.user_code}\\n`)\n process.stderr.write(` URL: ${claim.verification_uri}\\n\\n`)\n if (opts.openBrowser !== false) {\n await openBrowser(claim.verification_uri)\n }\n process.stderr.write(` Waiting for approval (${windowMin} min)…\\n\\n`)\n\n // 3 — Poll until approved / denied / expired\n const tokenResult = await pollDeviceGrant({\n tokenEndpoint,\n grantType: CLAIM_GRANT_TYPE,\n params: { claim_token, client_id: clientId },\n intervalS,\n expiresIn: claim.expires_in,\n signal: opts.signal,\n })\n\n // 4 — Store the identity_assertion as the durable credential (AIP-50: the\n // access_token is ephemeral and MUST NOT be persisted; the claim_token\n // was held in memory only). The assertion is re-exchanged via jwt-bearer\n // on the next run.\n const accessToken = tokenResult.access_token\n const assertion = tokenResult.identity_assertion\n\n // Resolve assertion expiry as ISO 8601\n let assertionExpires: string | undefined\n if (tokenResult.assertion_expires) {\n assertionExpires = tokenResult.assertion_expires\n } else if (tokenResult.assertion_expires_in) {\n assertionExpires = new Date(\n Date.now() + tokenResult.assertion_expires_in * 1_000,\n ).toISOString()\n }\n\n if (assertion) {\n await store.write(ref, {\n value: assertion,\n kind: \"assertion\",\n ...(assertionExpires ? { expiresAt: assertionExpires } : {}),\n })\n }\n\n return {\n accessToken,\n identityAssertion: assertion,\n assertionExpires,\n tokenKind: \"oat\",\n }\n },\n}\n","/**\n * device-code flow engine — plain RFC 8628 device-authorization ceremony.\n *\n * Protocol:\n * POST {device_authorization_endpoint} { client_id, scope?, device_label? }\n * → device_code + user_code + verification_uri(_complete) + expires_in\n * User approves at verification_uri in browser.\n * Poll POST {token_endpoint} with grant_type=urn:ietf:params:oauth:grant-type:device_code\n * until approved / denied / expired.\n * On success: store the access_token as the durable credential (kind:\"daemon\")\n * — unlike service-auth, the access token IS the thing that's persisted;\n * refresh_token/scope/subject/revocation_id ride in `metadata`.\n *\n * Subsequent runs: a fresh stored credential (or one with no expiry) short-\n * circuits the ceremony. An expired credential with a stored refresh_token is\n * exchanged via `grant_type=refresh_token`; on failure (or when no\n * refresh_token was stored) a new ceremony starts.\n */\n\nimport { z } from \"zod\"\nimport type {\n FlowEngine,\n FlowRunOptions,\n FlowResult,\n AuthProviderHandle,\n DiscoveredEndpoints,\n} from \"../types.js\"\nimport { KeychainStore } from \"../store/keychain-store.js\"\nimport { resolveStoreRefs, readStoreRefWithFallback } from \"../store/resolve-ref.js\"\nimport type { CredentialStore, StoreRef, StoredCredential } from \"../store/types.js\"\nimport { fetchWithDeadline, assertSecureUrl } from \"../http.js\"\nimport {\n openBrowser,\n postFormOAuth,\n pollDeviceGrant,\n tokenResponseSchema,\n type TokenSuccess,\n} from \"./device-grant.js\"\n\nconst DEVICE_CODE_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:device_code\"\nconst REFRESH_GRANT_TYPE = \"refresh_token\"\nconst DEFAULT_POLL_INTERVAL_S = 5\n\n/** Thrown by the device-code engine when `opts.refreshOnly` is set and no\n * fresh or refreshable credential is available — the only remaining path\n * would be an interactive ceremony, which `refreshOnly` callers explicitly\n * opt out of. Callers (e.g. `serve` boot on a headless host) catch this to\n * fall back to their own non-interactive behavior instead of hanging. */\nexport class CeremonyRequiredError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"CeremonyRequiredError\"\n }\n}\n\n// ── response schema ───────────────────────────────────────────────────────────\n//\n// JSON crosses a trust boundary here (the AS controls the bytes), so the\n// response is validated with Zod rather than asserted. `.loose()` keeps\n// unknown fields the spec may add.\n\nconst deviceAuthorizationResponseSchema = z\n .object({\n device_code: z.string(),\n user_code: z.string(),\n verification_uri: z.string(),\n verification_uri_complete: z.string().optional(),\n expires_in: z.number(),\n interval: z.number().optional(),\n })\n .loose()\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nasync function postDeviceAuthorization(\n url: string,\n params: Record<string, string>,\n signal?: AbortSignal,\n) {\n const res = await fetchWithDeadline(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams(params).toString(),\n signal,\n })\n if (!res.ok) {\n const text = await res.text()\n throw new Error(`POST ${url} → ${res.status}: ${text}`)\n }\n return deviceAuthorizationResponseSchema.parse(await res.json())\n}\n\n/** Read a string metadata field without an `as` cast — `metadata` is\n * `Record<string, unknown>`, so every read is a runtime type check. */\nfunction metaString(\n metadata: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n const v = metadata?.[key]\n return typeof v === \"string\" ? v : undefined\n}\n\nfunction isExpired(cred: StoredCredential): boolean {\n if (!cred.expiresAt) return false\n const t = Date.parse(cred.expiresAt)\n if (Number.isNaN(t)) return true\n return t <= Date.now()\n}\n\nfunction resultFromStored(cred: StoredCredential): FlowResult {\n const refreshToken = metaString(cred.metadata, \"refreshToken\")\n const scope = metaString(cred.metadata, \"scope\")\n const subject = metaString(cred.metadata, \"subject\")\n const revocationId = metaString(cred.metadata, \"revocationId\")\n return {\n accessToken: cred.value,\n tokenKind: \"daemon\",\n ...(refreshToken ? { refreshToken } : {}),\n ...(scope ? { scope } : {}),\n ...(subject ? { subject } : {}),\n ...(revocationId ? { revocationId } : {}),\n }\n}\n\n/** Refresh via `grant_type=refresh_token`. Returns null on any error\n * (expired / invalid_grant / server doesn't support the grant) so the\n * caller falls back to a full ceremony. */\nasync function refreshAccessToken(\n tokenEndpoint: string,\n refreshToken: string,\n clientId: string,\n signal?: AbortSignal,\n): Promise<TokenSuccess | null> {\n try {\n const data = await postFormOAuth(\n tokenEndpoint,\n {\n grant_type: REFRESH_GRANT_TYPE,\n refresh_token: refreshToken,\n client_id: clientId,\n },\n tokenResponseSchema,\n signal,\n )\n if (\"error\" in data) return null\n return data\n } catch {\n return null\n }\n}\n\nasync function persistAndResult(\n store: CredentialStore,\n ref: StoreRef,\n o: {\n accessToken: string\n expiresIn?: number\n refreshToken?: string\n scope?: string\n subject?: string\n deviceLabel?: string\n revocationId?: string\n },\n): Promise<FlowResult> {\n const expiresAt = o.expiresIn\n ? new Date(Date.now() + o.expiresIn * 1_000).toISOString()\n : undefined\n\n const metadata: Record<string, unknown> = {\n obtainedAt: new Date().toISOString(),\n ...(o.refreshToken ? { refreshToken: o.refreshToken } : {}),\n ...(o.scope ? { scope: o.scope } : {}),\n ...(o.subject ? { subject: o.subject } : {}),\n ...(o.deviceLabel ? { deviceLabel: o.deviceLabel } : {}),\n ...(o.revocationId ? { revocationId: o.revocationId } : {}),\n }\n\n await store.write(ref, {\n value: o.accessToken,\n kind: \"daemon\",\n ...(expiresAt ? { expiresAt } : {}),\n metadata,\n })\n\n return {\n accessToken: o.accessToken,\n tokenKind: \"daemon\",\n ...(o.refreshToken ? { refreshToken: o.refreshToken } : {}),\n ...(o.scope ? { scope: o.scope } : {}),\n ...(o.subject ? { subject: o.subject } : {}),\n ...(o.revocationId ? { revocationId: o.revocationId } : {}),\n }\n}\n\n// ── engine ───────────────────────────────────────────────────────────────────\n\nexport const deviceCodeFlowEngine: FlowEngine = {\n id: \"device-code\",\n\n async run(\n provider: AuthProviderHandle,\n discovered: DiscoveredEndpoints | null,\n opts: FlowRunOptions,\n ): Promise<FlowResult> {\n const { auth } = provider\n if (auth.flow !== \"device-code\") {\n throw new Error(`deviceCodeFlowEngine: invoked with flow=\"${auth.flow}\"`)\n }\n // `auth.flow === \"device-code\"` is guaranteed by the guard above, so the\n // discriminated union has already narrowed `auth` to DeviceCodeAuthConfig.\n const config = auth\n const clientId = config.clientId ?? \"agentproto-cli\"\n const server = opts.server.replace(/\\/$/, \"\")\n\n // Endpoint resolution — prefer live discovery, fall back to conventions.\n const deviceAuthorizationEndpoint =\n discovered?.deviceAuthorizationEndpoint ?? `${server}/oauth/device`\n const tokenEndpoint = discovered?.tokenEndpoint ?? `${server}/oauth/token`\n\n // AIP-50 §Security: auth requests MUST use HTTPS (loopback exempt for dev).\n assertSecureUrl(deviceAuthorizationEndpoint)\n assertSecureUrl(tokenEndpoint)\n\n const store = opts.store ?? new KeychainStore()\n const { ref, legacyRef } = resolveStoreRefs(\n config.tokenStore,\n server,\n provider.audience,\n )\n\n // Shared by both the ordinary cached path and `refreshOnly`: exchange a\n // stored refresh_token for a fresh access token, persisting the result.\n // Returns null (never throws) on a missing refresh_token or any grant\n // failure, so both callers can decide what to do next.\n async function tryRefresh(stored: StoredCredential): Promise<FlowResult | null> {\n const refreshToken = metaString(stored.metadata, \"refreshToken\")\n if (!refreshToken) return null\n const refreshed = await refreshAccessToken(\n tokenEndpoint,\n refreshToken,\n clientId,\n opts.signal,\n )\n if (!refreshed) return null\n return persistAndResult(store, ref, {\n accessToken: refreshed.access_token,\n expiresIn: refreshed.expires_in,\n refreshToken: refreshed.refresh_token ?? refreshToken,\n scope: refreshed.scope ?? metaString(stored.metadata, \"scope\"),\n subject: refreshed.subject ?? metaString(stored.metadata, \"subject\"),\n deviceLabel:\n config.deviceLabel ?? metaString(stored.metadata, \"deviceLabel\"),\n revocationId:\n refreshed.revocation_id ?? metaString(stored.metadata, \"revocationId\"),\n })\n }\n\n // `refreshOnly` — attempt only the cached/refresh path, never the\n // interactive ceremony. Distinct from the ordinary cached path below so\n // a refresh failure here throws instead of falling through.\n if (opts.refreshOnly) {\n const stored = await readStoreRefWithFallback(store, ref, legacyRef)\n if (stored) {\n if (!isExpired(stored)) {\n return resultFromStored(stored)\n }\n const refreshed = await tryRefresh(stored)\n if (refreshed) return refreshed\n }\n throw new CeremonyRequiredError(\n `${provider.id}: no fresh or refreshable device-code credential — an interactive ceremony would be required, but refreshOnly was set`,\n )\n }\n\n // Cached path — the stored credential IS the access token (pat-class\n // persistence). A fresh (or expiry-less) credential short-circuits the\n // ceremony entirely; an expired one with a refresh_token is renewed via\n // grant_type=refresh_token before falling back to a ceremony.\n if (!opts.force) {\n const stored = await readStoreRefWithFallback(store, ref, legacyRef)\n if (stored) {\n if (!isExpired(stored)) {\n return resultFromStored(stored)\n }\n const refreshed = await tryRefresh(stored)\n if (refreshed) return refreshed\n // refresh failed (expired / invalid_grant) — fall through to a ceremony\n }\n }\n\n // 1 — POST the device-authorization endpoint to start the ceremony\n const params: Record<string, string> = { client_id: clientId }\n if (config.scope) params.scope = config.scope\n if (config.deviceLabel) params.device_label = config.deviceLabel\n\n const authz = await postDeviceAuthorization(\n deviceAuthorizationEndpoint,\n params,\n opts.signal,\n )\n\n const intervalS = authz.interval ?? DEFAULT_POLL_INTERVAL_S\n const windowMin = Math.round(authz.expires_in / 60)\n\n // 2 — Print code + open browser\n process.stderr.write(`\\n`)\n process.stderr.write(` Approve ${provider.id} access in your browser\\n\\n`)\n process.stderr.write(` Code: ${authz.user_code}\\n`)\n process.stderr.write(` URL: ${authz.verification_uri}\\n\\n`)\n if (opts.openBrowser !== false) {\n await openBrowser(authz.verification_uri_complete ?? authz.verification_uri)\n }\n process.stderr.write(` Waiting for approval (${windowMin} min)…\\n\\n`)\n\n // 3 — Poll until approved / denied / expired\n const tokenResult = await pollDeviceGrant({\n tokenEndpoint,\n grantType: DEVICE_CODE_GRANT_TYPE,\n params: { device_code: authz.device_code, client_id: clientId },\n intervalS,\n expiresIn: authz.expires_in,\n signal: opts.signal,\n })\n\n // 4 — Persist the access token as the durable credential (pat-class).\n return persistAndResult(store, ref, {\n accessToken: tokenResult.access_token,\n expiresIn: tokenResult.expires_in,\n refreshToken: tokenResult.refresh_token,\n scope: tokenResult.scope,\n subject: tokenResult.subject,\n deviceLabel: config.deviceLabel,\n revocationId: tokenResult.revocation_id,\n })\n },\n}\n","/**\n * Flow engine registry — dispatch by `provider.auth.flow`.\n *\n * Add a new engine:\n * 1. Implement `FlowEngine` in a sibling file\n * 2. Add it here — no if/switch chains at call sites\n */\n\nimport type { FlowEngine } from \"../types.js\"\nimport { patFlowEngine } from \"./pat.js\"\nimport { serviceAuthFlowEngine } from \"./service-auth.js\"\nimport { deviceCodeFlowEngine } from \"./device-code.js\"\n\nexport const FLOW_ENGINES: Readonly<Record<string, FlowEngine>> = {\n [patFlowEngine.id]: patFlowEngine,\n [serviceAuthFlowEngine.id]: serviceAuthFlowEngine,\n [deviceCodeFlowEngine.id]: deviceCodeFlowEngine,\n}\n","/**\n * `runAuthFlow` — resolve provider → discover endpoints → dispatch to engine.\n *\n * Discovery is attempted silently; callers receive the result without knowing\n * whether live or static endpoint config was used. The flow engine receives\n * `null` for `discovered` if discovery failed or was not attempted.\n */\n\nimport { FLOW_ENGINES } from \"./flow-engines/index.js\"\nimport { discoverEndpoints, DiscoveryError } from \"./discover.js\"\nimport type {\n AuthProviderHandle,\n DiscoveredEndpoints,\n FlowResult,\n FlowRunOptions,\n} from \"./types.js\"\n\nexport interface RunFlowOptions extends FlowRunOptions {\n /** Pre-resolved endpoints (skip discovery). Pass null to force re-discovery. */\n discovered?: DiscoveredEndpoints | null\n /** Suppress debug output. Default: false. */\n quiet?: boolean\n}\n\nexport async function runAuthFlow(\n provider: AuthProviderHandle,\n opts: RunFlowOptions,\n): Promise<FlowResult> {\n const flowId = provider.auth.flow\n const engine = FLOW_ENGINES[flowId]\n if (!engine) {\n throw new Error(\n `runAuthFlow: unknown flow \"${flowId}\" — registered: ${Object.keys(FLOW_ENGINES).join(\", \")}`,\n )\n }\n\n // Discovery: try unless caller already provided endpoints\n let discovered: DiscoveredEndpoints | null =\n opts.discovered !== undefined ? opts.discovered : null\n\n if (\n discovered === null &&\n (flowId === \"service-auth\" || flowId === \"device-code\")\n ) {\n try {\n discovered = await discoverEndpoints(opts.server, { signal: opts.signal })\n } catch (err) {\n if (!opts.quiet) {\n const msg =\n err instanceof DiscoveryError\n ? err.message\n : `discovery failed: ${err}`\n process.stderr.write(`[auth] ${msg} — using static config\\n`)\n }\n }\n }\n\n return engine.run(provider, discovered, opts)\n}\n","/**\n * MemoryStore — in-process `CredentialStore` backed by a `Map`.\n *\n * Ephemeral: gone when the process exits. Used for tests and short-lived\n * tooling that shouldn't touch a real backend.\n */\n\nimport type { CredentialStore, StoreRef, StoredCredential } from \"./types.js\"\n\nfunction keyOf(ref: StoreRef): string {\n return `${ref.path}\u0000${ref.account ?? ref.path}`\n}\n\nexport class MemoryStore implements CredentialStore {\n private readonly entries = new Map<string, StoredCredential>()\n\n async read(ref: StoreRef): Promise<StoredCredential | undefined> {\n const entry = this.entries.get(keyOf(ref))\n return entry ? { ...entry } : undefined\n }\n\n async write(ref: StoreRef, cred: StoredCredential): Promise<void> {\n this.entries.set(keyOf(ref), { ...cred })\n }\n\n async delete(ref: StoreRef): Promise<void> {\n this.entries.delete(keyOf(ref))\n }\n}\n","/**\n * FileStore — encrypted-JSON-file `CredentialStore`.\n *\n * Every entry is sealed independently with AES-256-GCM under a key read from\n * `AGENTPROTO_STORE_KEY` (hex or base64, 32 raw bytes). There is no plaintext\n * fallback: a missing or malformed key throws rather than writing credentials\n * to disk in the clear.\n */\n\nimport {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n} from \"node:crypto\"\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\"\nimport { dirname } from \"node:path\"\nimport { z } from \"zod\"\nimport type { CredentialStore, StoreRef, StoredCredential } from \"./types.js\"\n\nconst ALGORITHM = \"aes-256-gcm\"\nconst KEY_ENV_VAR = \"AGENTPROTO_STORE_KEY\"\nconst IV_BYTES = 12\n\nconst sealedEntrySchema = z.object({\n iv: z.string(),\n tag: z.string(),\n ciphertext: z.string(),\n})\ntype SealedEntry = z.infer<typeof sealedEntrySchema>\n\nconst sealedFileSchema = z.record(z.string(), sealedEntrySchema)\n\nconst storedCredentialSchema = z.object({\n value: z.string(),\n kind: z.enum([\"pat\", \"assertion\", \"oat\", \"daemon\"]),\n expiresAt: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\n\nfunction keyOf(ref: StoreRef): string {\n return `${ref.path} ${ref.account ?? ref.path}`\n}\n\nfunction isEnoent(err: unknown): boolean {\n return (\n typeof err === \"object\" &&\n err !== null &&\n \"code\" in err &&\n err.code === \"ENOENT\"\n )\n}\n\n/** Decode `AGENTPROTO_STORE_KEY` (hex or base64) into exactly 32 raw bytes. */\nfunction loadKey(): Buffer {\n const raw = process.env[KEY_ENV_VAR]\n if (!raw) {\n throw new Error(\n `FileStore: missing ${KEY_ENV_VAR} — set a 32-byte key (64 hex chars, ` +\n `or base64) to use the encrypted file store. Refusing to store ` +\n `credentials in plaintext.`,\n )\n }\n const key = /^[0-9a-fA-F]{64}$/.test(raw)\n ? Buffer.from(raw, \"hex\")\n : Buffer.from(raw, \"base64\")\n if (key.length !== 32) {\n throw new Error(\n `FileStore: ${KEY_ENV_VAR} must decode to exactly 32 bytes (got ` +\n `${key.length}). Provide a 64-char hex string or base64 encoding 32 bytes.`,\n )\n }\n return key\n}\n\nfunction seal(key: Buffer, plaintext: string): SealedEntry {\n const iv = randomBytes(IV_BYTES)\n const cipher = createCipheriv(ALGORITHM, key, iv)\n const ciphertext = Buffer.concat([\n cipher.update(plaintext, \"utf8\"),\n cipher.final(),\n ])\n return {\n iv: iv.toString(\"base64\"),\n tag: cipher.getAuthTag().toString(\"base64\"),\n ciphertext: ciphertext.toString(\"base64\"),\n }\n}\n\nfunction unseal(key: Buffer, entry: SealedEntry): string {\n const decipher = createDecipheriv(\n ALGORITHM,\n key,\n Buffer.from(entry.iv, \"base64\"),\n )\n decipher.setAuthTag(Buffer.from(entry.tag, \"base64\"))\n const plaintext = Buffer.concat([\n decipher.update(Buffer.from(entry.ciphertext, \"base64\")),\n decipher.final(),\n ])\n return plaintext.toString(\"utf8\")\n}\n\nexport class FileStore implements CredentialStore {\n constructor(private readonly filePath: string) {}\n\n async read(ref: StoreRef): Promise<StoredCredential | undefined> {\n const key = loadKey()\n const file = await this.readFile()\n const sealed = file[keyOf(ref)]\n if (!sealed) return undefined\n return storedCredentialSchema.parse(JSON.parse(unseal(key, sealed)))\n }\n\n async write(ref: StoreRef, cred: StoredCredential): Promise<void> {\n const key = loadKey()\n const file = await this.readFile()\n file[keyOf(ref)] = seal(key, JSON.stringify(cred))\n await this.writeFile(file)\n }\n\n async delete(ref: StoreRef): Promise<void> {\n const file = await this.readFile()\n delete file[keyOf(ref)]\n await this.writeFile(file)\n }\n\n private async readFile(): Promise<Record<string, SealedEntry>> {\n try {\n const raw = await readFile(this.filePath, \"utf8\")\n return sealedFileSchema.parse(JSON.parse(raw))\n } catch (err) {\n if (isEnoent(err)) return {}\n throw err\n }\n }\n\n private async writeFile(file: Record<string, SealedEntry>): Promise<void> {\n await mkdir(dirname(this.filePath), { recursive: true })\n await writeFile(this.filePath, JSON.stringify(file, null, 2), \"utf8\")\n }\n}\n","/**\n * CredentialBroker — resolve ready-to-use auth headers for a `<providerId>`\n * or `<providerId>/<account>` path, auto-refreshing via the flow engine when\n * the stored credential is missing, expired, or not directly usable.\n *\n * Agent.pw-parity API: callers ask for headers by path and never touch\n * tokens, flows, or the underlying store directly.\n */\n\nimport { runAuthFlow } from \"./run-flow.js\"\nimport { resolveStoreRefs, readStoreRefWithFallback } from \"./store/resolve-ref.js\"\nimport type { CredentialStore, StoredCredential } from \"./store/types.js\"\nimport type { AuthProviderHandle } from \"./types.js\"\n\n/** Refresh this long before the actual expiry, so a credential that's about\n * to expire mid-request gets renewed proactively instead of failing. */\nconst EXPIRY_SKEW_MS = 60_000\n\nexport interface CredentialBrokerOptions {\n /** Backend to read cached credentials from and persist refreshed ones to. */\n store: CredentialStore\n /** Provider lookup — pass `getAuthProvider` from the registry, or a custom\n * resolver (e.g. scoped to a single host's providers). */\n getProvider: (id: string) => AuthProviderHandle | undefined\n}\n\ninterface ParsedPath {\n providerId: string\n account?: string\n}\n\n/** Split `\"<providerId>\"` or `\"<providerId>/<account>\"` on the first `/`. */\nfunction parsePath(path: string): ParsedPath {\n const slash = path.indexOf(\"/\")\n if (slash === -1) return { providerId: path }\n return { providerId: path.slice(0, slash), account: path.slice(slash + 1) }\n}\n\n/** `expiresAt` in the future (past the refresh skew), or absent entirely. A\n * malformed `expiresAt` is treated as expired — refresh rather than risk\n * serving a header that a downstream API will reject. */\nfunction isFresh(cred: StoredCredential): boolean {\n if (!cred.expiresAt) return true\n const expiresAtMs = Date.parse(cred.expiresAt)\n if (Number.isNaN(expiresAtMs)) return false\n return expiresAtMs - EXPIRY_SKEW_MS > Date.now()\n}\n\n/** Header map for a credential usable as a bearer token directly, or\n * `undefined` when it isn't. `assertion` is never bearer-usable — it must be\n * exchanged by a flow engine first — so it always falls through to\n * `runAuthFlow`. */\nfunction bearerHeaders(\n value: string,\n kind: StoredCredential[\"kind\"],\n): Record<string, string> | undefined {\n if (kind === \"pat\" || kind === \"oat\" || kind === \"daemon\") {\n return { Authorization: `Bearer ${value}` }\n }\n return undefined\n}\n\nexport class CredentialBroker {\n private readonly store: CredentialStore\n private readonly getProvider: (id: string) => AuthProviderHandle | undefined\n\n constructor(opts: CredentialBrokerOptions) {\n this.store = opts.store\n this.getProvider = opts.getProvider\n }\n\n async resolveHeaders(o: {\n path: string\n server?: string\n signal?: AbortSignal\n /** Audience the caller expects this credential to be scoped to. Checked\n * only when the resolved provider also declares one — see the mismatch\n * error below. Does not itself change which store key is read; the\n * provider's own `audience` (not the caller's) determines that. */\n audience?: string\n }): Promise<Record<string, string>> {\n const { providerId, account } = parsePath(o.path)\n const provider = this.getProvider(providerId)\n if (!provider) {\n throw new Error(`CredentialBroker: unknown auth provider \"${providerId}\"`)\n }\n\n if (\n o.audience !== undefined &&\n provider.audience !== undefined &&\n o.audience !== provider.audience\n ) {\n throw new Error(\n `CredentialBroker: provider \"${providerId}\" is scoped to audience \"${provider.audience}\", requested \"${o.audience}\"`,\n )\n }\n\n const server = o.server ?? provider.apiBase\n const { ref, legacyRef } = resolveStoreRefs(\n provider.auth.tokenStore,\n server,\n provider.audience,\n )\n if (account !== undefined) {\n ref.account = account\n legacyRef.account = account\n }\n\n const stored = await readStoreRefWithFallback(this.store, ref, legacyRef)\n if (stored && isFresh(stored)) {\n const headers = bearerHeaders(stored.value, stored.kind)\n if (headers) return headers\n }\n\n const result = await runAuthFlow(provider, {\n server,\n store: this.store,\n signal: o.signal,\n })\n const headers =\n result.accessToken !== undefined\n ? bearerHeaders(result.accessToken, result.tokenKind)\n : undefined\n if (!headers) {\n throw new Error(\n `CredentialBroker: auth flow for \"${providerId}\" produced no usable access token`,\n )\n }\n return headers\n }\n}\n","/**\n * Named auth-profile store — CRUD over `~/.agentproto/auth-profiles.json`\n * (mode 0600), generalizing `providers-store`'s single-key-per-provider file\n * (`packages/providers-store/src/index.ts:68-90`, `ProviderEntry`/\n * `ProvidersFile`) to N named `AuthProfile`s per billing endpoint, keyed by `id`.\n *\n * This is the profile-metadata store, not the credential store: entries hold\n * `credentialRef` (a pointer), never a secret, so — unlike `FileStore`\n * (`store/file-store.ts`) — this file needs no encryption. Reuses the exact\n * persistence primitives `providers-store` already established (a versioned\n * JSON file under `~/.agentproto/`, `node:fs/promises`, mode 0600) rather\n * than inventing a new format, just relocated to `@agentproto/auth` — the\n * correct home for named profiles per SPEC §1c (`providers.json` is the\n * degenerate one-key-per-provider case this generalizes).\n */\n\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\"\nimport { homedir } from \"node:os\"\nimport { join, resolve } from \"node:path\"\nimport { z } from \"zod\"\nimport type { AuthMethod, AuthProfile } from \"./profile-types.js\"\n\nconst authMethodSchema = z.enum([\"oauth-bearer\", \"api-key\"]) satisfies z.ZodType<AuthMethod>\n\n/** Version-1 on-disk shape. Keep `vendor` here permanently for compatibility:\n * callers only ever see the unambiguous in-memory `endpoint` field. */\nconst modelCurationSchema = z.object({\n mode: z.enum([\"all\", \"allow\"]),\n ids: z.array(z.string()),\n})\n\nexport const costBudgetSchema = z.object({\n maxCostUsd: z.number(),\n window: z.string(),\n scope: z.enum([\"session\", \"profile\"]),\n})\n\nconst authProfileSchema = z.object({\n id: z.string(),\n vendor: z.string(),\n method: authMethodSchema,\n credentialRef: z.string().optional(),\n source: z.string().optional(),\n label: z.string().optional(),\n // Additive, back-compat fields — an entry that predates them parses\n // unchanged (both optional), and `endpoint` still shadows the on-disk\n // `vendor` alias below.\n disabled: z.boolean().optional(),\n models: modelCurationSchema.optional(),\n costBudget: costBudgetSchema.optional(),\n origin: z.string().optional(),\n}).transform(({ vendor, ...profile }): AuthProfile => ({ ...profile, endpoint: vendor }))\n\nconst authProfilesFileSchema = z.object({\n version: z.literal(1),\n profiles: z.record(z.string(), authProfileSchema),\n})\n\nexport type AuthProfilesFile = z.infer<typeof authProfilesFileSchema>\n\n/** Fresh empty file each call — never share the `profiles` object, or a\n * later mutation leaks into every other load in-process (same defense\n * `providers-store`'s `emptyFile()` establishes). */\nfunction emptyFile(): AuthProfilesFile {\n return { version: 1, profiles: {} }\n}\n\nexport function authProfilesPath(): string {\n return resolve(homedir(), \".agentproto\", \"auth-profiles.json\")\n}\n\nexport async function loadAuthProfiles(): Promise<AuthProfilesFile> {\n try {\n const raw = await readFile(authProfilesPath(), \"utf8\")\n return authProfilesFileSchema.parse(JSON.parse(raw))\n } catch {\n return emptyFile() // ENOENT / malformed → empty\n }\n}\n\nasync function writeAuthProfiles(file: AuthProfilesFile): Promise<void> {\n const dir = join(homedir(), \".agentproto\")\n await mkdir(dir, { recursive: true })\n // mode 0600 so other local users can't read the profile metadata.\n const diskFile = {\n version: file.version,\n profiles: Object.fromEntries(\n Object.entries(file.profiles).map(([id, { endpoint, ...profile }]) => [\n id,\n { ...profile, vendor: endpoint },\n ]),\n ),\n }\n await writeFile(authProfilesPath(), JSON.stringify(diskFile, null, 2) + \"\\n\", {\n encoding: \"utf8\",\n mode: 0o600,\n })\n}\n\n/** List all profiles, optionally filtered to one billing endpoint. */\nexport async function listAuthProfiles(endpoint?: string): Promise<AuthProfile[]> {\n const file = await loadAuthProfiles()\n const all = Object.values(file.profiles)\n return endpoint === undefined ? all : all.filter(p => p.endpoint === endpoint)\n}\n\n/** Look up a single profile by id, or undefined if none exists. */\nexport async function getAuthProfile(id: string): Promise<AuthProfile | undefined> {\n const file = await loadAuthProfiles()\n return file.profiles[id]\n}\n\n/** Add (or replace) a profile, keyed by its `id`. */\nexport async function addAuthProfile(profile: AuthProfile): Promise<void> {\n const file = await loadAuthProfiles()\n file.profiles[profile.id] = profile\n await writeAuthProfiles(file)\n}\n\n/** Remove a profile by id. Returns true if it existed. */\nexport async function removeAuthProfile(id: string): Promise<boolean> {\n const file = await loadAuthProfiles()\n if (!(id in file.profiles)) return false\n delete file.profiles[id]\n await writeAuthProfiles(file)\n return true\n}\n","/**\n * Auth-profile provisioning — the create/delete flow the store CRUD\n * (`profile-store.ts`) deliberately leaves out.\n *\n * `profile-store.ts` writes only profile *metadata* (`credentialRef`, a\n * pointer). Provisioning is the two-sided operation nobody else owned: write\n * the *secret* to the credential store at a derived slot, THEN record the\n * metadata pointing at it — and, on delete, tear both down together. This is\n * the single place that knows the `agentproto.auth.<vendor>[.<qualifier>]`\n * keychain-slot convention (matching the entries seeded by hand in\n * `~/.agentproto/auth-profiles.json`).\n *\n * The secret is INPUT-only. It is written to the `CredentialStore` and never\n * echoed back: `createAuthProfile` returns non-secret metadata plus a\n * one-way `fingerprint` (same \"fingerprint, don't echo\" discipline as\n * `broker.ts` / `KeychainStore`), so a caller can confirm *which* credential\n * landed without ever seeing it.\n *\n * Dependency-injected (`ProfileProvisionDeps`) so it's unit-testable against\n * a `MemoryStore` + an in-memory profile map, with no keychain or filesystem.\n */\n\nimport { createHash } from \"node:crypto\"\nimport type { AuthMethod, AuthProfile, CostBudget, ModelCuration } from \"./profile-types.js\"\nimport { costBudgetSchema } from \"./profile-store.js\"\nimport type { CredentialStore } from \"./store/types.js\"\n\n/** Input to {@link createAuthProfile}. `credential` is the raw secret — it is\n * written to the store and NEVER returned. Exactly one of `credential` /\n * `source` must be given for an `oauth-bearer` profile; `api-key` always\n * requires `credential` (a source-backed profile only makes sense for a\n * self-refreshing subscription bearer). */\nexport interface CreateAuthProfileInput {\n /** Stable id, unique across all profiles. */\n id: string\n /** Billing endpoint / vendor this credential authenticates against\n * (`anthropic`, `openrouter`, `moonshot`, …). */\n endpoint: string\n /** How this profile authenticates. */\n method: AuthMethod\n /** The raw secret (a subscription OAuth bearer, an API key). INPUT-ONLY.\n * Mutually exclusive with `source`. */\n credential?: string\n /** Self-refreshing credential source (`oauth-bearer` only, e.g.\n * `\"claude-code-oauth\"`) — the profile stores no secret; the credential is\n * resolved fresh at spawn time instead. Mutually exclusive with\n * `credential`. */\n source?: string\n /** Optional human-readable name. */\n label?: string\n /** Optional explicit credential-store slot. Omitted ⇒ derived from\n * `endpoint` + `method` (see {@link deriveCredentialRef}). Ignored for a\n * source-backed profile (nothing is written to the credential store). */\n credentialRef?: string\n /** Optional provenance — where the credential was imported from (a WS6\n * discovery origin). Stamped verbatim on the created profile; purely\n * informational. */\n origin?: string\n}\n\n/** The non-secret result of a create — safe to log, return over the wire, or\n * render in a UI. Carries a fingerprint, never the credential. */\nexport interface CreatedAuthProfile {\n id: string\n endpoint: string\n method: AuthMethod\n /** Set for a credential-backed profile; absent for a source-backed one. */\n credentialRef?: string\n /** Set for a source-backed profile; absent for a credential-backed one. */\n source?: string\n label?: string\n /** Provenance stamped at import time, when given. */\n origin?: string\n /** One-way fingerprint of the stored credential (sha256, truncated) — lets\n * a caller confirm *which* secret was stored without exposing it. Absent\n * for a source-backed profile — there is no stored secret to fingerprint. */\n fingerprint?: string\n}\n\n/** The result of a delete. `deleted` is false when no profile had that id\n * (idempotent — the desired end state already held). */\nexport interface DeletedAuthProfile {\n deleted: boolean\n id: string\n /** The slot the credential lived at, when a profile was actually removed. */\n credentialRef?: string\n}\n\n/** Injectable persistence surface — production wires these to\n * `profile-store.ts` + a `KeychainStore`; tests pass in-memory doubles. */\nexport interface ProfileProvisionDeps {\n /** Where secrets live (a `KeychainStore` in production). */\n store: CredentialStore\n getProfile: (id: string) => Promise<AuthProfile | undefined>\n listProfiles: () => Promise<AuthProfile[]>\n addProfile: (profile: AuthProfile) => Promise<void>\n removeProfile: (id: string) => Promise<boolean>\n}\n\n/** Raised when create/delete input fails validation. Distinct type so a host\n * (HTTP route, MCP tool) can map it to a 400 rather than a 500. */\nexport class AuthProfileValidationError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"AuthProfileValidationError\"\n }\n}\n\nconst AUTH_METHODS: readonly AuthMethod[] = [\"oauth-bearer\", \"api-key\"]\n\n/** ids and endpoints become keychain-slot / filename fragments, so keep them\n * to a conservative, injection-safe charset. */\nconst SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/\n\n/** Normalized, validated create input — every field trimmed and checked.\n * Exactly one of `credential` / `source` is present. */\nexport interface ValidatedCreateInput {\n id: string\n endpoint: string\n method: AuthMethod\n credential?: string\n source?: string\n label?: string\n credentialRef?: string\n origin?: string\n}\n\n/**\n * Validate + normalize raw create input. Pure — no I/O. Throws\n * {@link AuthProfileValidationError} with a specific message on the first\n * problem it finds, so the surface layer can surface a clear 400.\n */\nexport function validateCreateInput(input: CreateAuthProfileInput): ValidatedCreateInput {\n const id = (input.id ?? \"\").trim()\n if (!id) throw new AuthProfileValidationError(\"id is required\")\n if (!SLUG_RE.test(id)) {\n throw new AuthProfileValidationError(\n `id \"${id}\" is invalid — use letters, digits, \".\", \"_\" or \"-\", ` +\n `starting with a letter or digit`,\n )\n }\n\n const endpoint = (input.endpoint ?? \"\").trim()\n if (!endpoint) throw new AuthProfileValidationError(\"endpoint is required\")\n if (!SLUG_RE.test(endpoint)) {\n throw new AuthProfileValidationError(\n `endpoint \"${endpoint}\" is invalid — use letters, digits, \".\", \"_\" or \"-\"`,\n )\n }\n\n const method = input.method\n if (!AUTH_METHODS.includes(method)) {\n throw new AuthProfileValidationError(\n `method must be one of ${AUTH_METHODS.join(\" | \")} (got \"${String(method)}\")`,\n )\n }\n\n // Trim surrounding whitespace only — a pasted token can carry a stray\n // trailing newline, but must not be blank once trimmed.\n const credential = input.credential !== undefined ? input.credential.trim() : undefined\n const source = input.source?.trim()\n\n if (method === \"api-key\") {\n if (source) {\n throw new AuthProfileValidationError(\n \"source is only supported for oauth-bearer profiles — api-key profiles require a credential\",\n )\n }\n if (!credential) throw new AuthProfileValidationError(\"credential is required\")\n } else {\n if (credential && source) {\n throw new AuthProfileValidationError(\n \"give either credential or source, not both — a source-backed profile stores no secret\",\n )\n }\n if (!credential && !source) {\n throw new AuthProfileValidationError(\"credential or source is required\")\n }\n }\n\n const label = input.label?.trim()\n const credentialRef = input.credentialRef?.trim()\n if (credentialRef !== undefined && credentialRef !== \"\" && !SLUG_RE.test(credentialRef)) {\n throw new AuthProfileValidationError(\n `credentialRef \"${credentialRef}\" is invalid — use letters, digits, \".\", \"_\" or \"-\"`,\n )\n }\n\n const origin = input.origin?.trim()\n\n return {\n id,\n endpoint,\n method,\n ...(credential ? { credential } : {}),\n ...(source ? { source } : {}),\n ...(label ? { label } : {}),\n ...(credentialRef ? { credentialRef } : {}),\n ...(origin ? { origin } : {}),\n }\n}\n\n/**\n * Derive the credential-store slot for a profile. Matches the convention of\n * the hand-seeded entries: `agentproto.auth.<endpoint>` for an api-key,\n * `agentproto.auth.<endpoint>.sub` for a subscription (oauth-bearer), plus an\n * optional `<qualifier>` to disambiguate a second profile on the same\n * endpoint+method. Pure.\n */\nexport function deriveCredentialRef(input: {\n endpoint: string\n method: AuthMethod\n qualifier?: string\n}): string {\n const parts = [\"agentproto\", \"auth\", input.endpoint]\n if (input.method === \"oauth-bearer\") parts.push(\"sub\")\n if (input.qualifier) parts.push(input.qualifier)\n return parts.join(\".\")\n}\n\n/** One-way fingerprint of a secret — sha256, first 12 hex chars. Enough to\n * distinguish credentials by eye; not reversible. */\nexport function fingerprintCredential(secret: string): string {\n return createHash(\"sha256\").update(secret, \"utf8\").digest(\"hex\").slice(0, 12)\n}\n\n/** Below this length, `slice(-4)` would expose too large a fraction of the\n * secret to be a safe \"last 4\" — so `last4` is withheld (never the secret).\n * Real API keys / bearer tokens are far longer; this only guards a degenerate\n * short value. */\nconst MIN_LEN_FOR_LAST4 = 8\n\n/** Non-secret identity of a STORED credential — a one-way {@link\n * fingerprintCredential} plus the trailing 4 characters (the standard\n * \"which key is this\" affordance, like a card's last four). Neither is\n * reversible to the secret. `last4` is omitted for a secret too short to\n * reveal a tail safely (see {@link MIN_LEN_FOR_LAST4}) — fail closed rather\n * than expose. */\nexport interface CredentialIdentity {\n fingerprint: string\n last4?: string\n}\n\n/** Compute the non-secret {@link CredentialIdentity} of a stored secret.\n * Money-safety: returns ONLY the one-way fingerprint + a trailing tail —\n * never the secret, and never the tail when the secret is too short to\n * reveal one safely. */\nexport function credentialIdentity(secret: string): CredentialIdentity {\n return {\n fingerprint: fingerprintCredential(secret),\n ...(secret.length >= MIN_LEN_FOR_LAST4 ? { last4: secret.slice(-4) } : {}),\n }\n}\n\n/** The `StoredCredential.kind` a method maps to (mirrors `profile-types.ts`:\n * `pat` → `api-key`, `oat` → `oauth-bearer`). */\nfunction credentialKind(method: AuthMethod): \"pat\" | \"oat\" {\n return method === \"oauth-bearer\" ? \"oat\" : \"pat\"\n}\n\n/**\n * Create a profile end-to-end: validate, derive the credential slot (avoiding\n * collision with an existing profile's slot), write the secret to the store,\n * then record the metadata. Rejects a duplicate id rather than silently\n * overwriting. Returns non-secret metadata + a fingerprint; the credential is\n * never echoed back.\n */\nexport async function createAuthProfile(\n input: CreateAuthProfileInput,\n deps: ProfileProvisionDeps,\n): Promise<CreatedAuthProfile> {\n const v = validateCreateInput(input)\n\n if (await deps.getProfile(v.id)) {\n throw new AuthProfileValidationError(\n `a profile with id \"${v.id}\" already exists — delete it first or pick another id`,\n )\n }\n\n // Source-backed: no secret, nothing written to the credential store.\n if (v.source !== undefined) {\n const profile: AuthProfile = {\n id: v.id,\n endpoint: v.endpoint,\n method: v.method,\n source: v.source,\n ...(v.label ? { label: v.label } : {}),\n ...(v.origin ? { origin: v.origin } : {}),\n }\n await deps.addProfile(profile)\n return {\n id: profile.id,\n endpoint: profile.endpoint,\n method: profile.method,\n source: v.source,\n ...(profile.label ? { label: profile.label } : {}),\n ...(profile.origin ? { origin: profile.origin } : {}),\n }\n }\n\n const credential = v.credential!\n\n const existing = await deps.listProfiles()\n const takenRefs = new Set(existing.map(p => p.credentialRef))\n\n let credentialRef = v.credentialRef ?? deriveCredentialRef(v)\n // If the derived slot already holds another profile's secret, qualify it\n // with the id so two profiles on the same endpoint+method don't clobber\n // each other's keychain entry.\n if (!v.credentialRef && takenRefs.has(credentialRef)) {\n credentialRef = deriveCredentialRef({ ...v, qualifier: v.id })\n }\n\n await deps.store.write(\n { path: credentialRef },\n { value: credential, kind: credentialKind(v.method) },\n )\n\n const profile: AuthProfile = {\n id: v.id,\n endpoint: v.endpoint,\n method: v.method,\n credentialRef,\n ...(v.label ? { label: v.label } : {}),\n ...(v.origin ? { origin: v.origin } : {}),\n }\n await deps.addProfile(profile)\n\n return {\n id: profile.id,\n endpoint: profile.endpoint,\n method: profile.method,\n credentialRef,\n ...(profile.label ? { label: profile.label } : {}),\n ...(profile.origin ? { origin: profile.origin } : {}),\n fingerprint: fingerprintCredential(credential),\n }\n}\n\n/**\n * Delete a profile and its credential. Idempotent: a missing id returns\n * `{ deleted: false }` rather than throwing. The keychain entry is removed\n * only when no OTHER profile still references the same slot — two profiles\n * can legitimately share a `credentialRef`, and dropping one must not strand\n * the other.\n */\nexport async function deleteAuthProfile(\n id: string,\n deps: ProfileProvisionDeps,\n): Promise<DeletedAuthProfile> {\n const trimmed = (id ?? \"\").trim()\n if (!trimmed) throw new AuthProfileValidationError(\"id is required\")\n\n const profile = await deps.getProfile(trimmed)\n if (!profile) return { deleted: false, id: trimmed }\n\n await deps.removeProfile(trimmed)\n\n // Source-backed profiles store no secret — nothing to tear down.\n if (profile.credentialRef === undefined) {\n return { deleted: true, id: trimmed }\n }\n\n const stillReferenced = (await deps.listProfiles()).some(\n p => p.credentialRef === profile.credentialRef,\n )\n if (!stillReferenced && deps.store.delete) {\n await deps.store.delete({ path: profile.credentialRef })\n }\n\n return { deleted: true, id: trimmed, credentialRef: profile.credentialRef }\n}\n\n/**\n * Enable or disable a whole profile (WS2). Metadata-only — never touches the\n * credential store. Enabling CLEARS the `disabled` field entirely rather than\n * writing `disabled: false`, so a re-enabled profile is byte-identical on\n * disk to one that was never disabled (the ABSENT-means-enabled invariant).\n * Throws {@link AuthProfileValidationError} for an unknown id so a host can map\n * it to a 404/400. Returns the updated (non-secret) profile.\n */\nexport async function setAuthProfileEnabled(\n id: string,\n enabled: boolean,\n deps: ProfileProvisionDeps,\n): Promise<AuthProfile> {\n const trimmed = (id ?? \"\").trim()\n if (!trimmed) throw new AuthProfileValidationError(\"id is required\")\n\n const profile = await deps.getProfile(trimmed)\n if (!profile) {\n throw new AuthProfileValidationError(`no profile with id \"${trimmed}\"`)\n }\n\n // Rebuild WITHOUT `disabled`, then re-add it only when disabling — keeps the\n // enabled state absent-by-default.\n const { disabled: _drop, ...rest } = profile\n const updated: AuthProfile = enabled ? { ...rest } : { ...rest, disabled: true }\n await deps.addProfile(updated)\n return updated\n}\n\n/**\n * Set a profile's per-model curation allowlist (WS3). Metadata-only. `mode:\n * \"all\"` CLEARS the `models` field entirely (curation off ⇒ absent, the\n * byte-identical \"services everything\" default), so only a genuine `mode:\n * \"allow\"` persists a `models` object. `ids` are trimmed, de-duped, and\n * blanks dropped. Throws {@link AuthProfileValidationError} for an unknown id.\n * Returns the updated (non-secret) profile.\n */\nexport async function setAuthProfileModels(\n id: string,\n curation: ModelCuration,\n deps: ProfileProvisionDeps,\n): Promise<AuthProfile> {\n const trimmed = (id ?? \"\").trim()\n if (!trimmed) throw new AuthProfileValidationError(\"id is required\")\n if (curation.mode !== \"all\" && curation.mode !== \"allow\") {\n throw new AuthProfileValidationError(\n `models.mode must be \"all\" or \"allow\" (got \"${String(curation.mode)}\")`,\n )\n }\n\n const profile = await deps.getProfile(trimmed)\n if (!profile) {\n throw new AuthProfileValidationError(`no profile with id \"${trimmed}\"`)\n }\n\n const { models: _drop, ...rest } = profile\n if (curation.mode === \"all\") {\n // \"all\" == absent — drop the field so the on-disk shape stays byte-\n // identical to a never-curated profile.\n const updated: AuthProfile = { ...rest }\n await deps.addProfile(updated)\n return updated\n }\n\n const ids = [...new Set((curation.ids ?? []).map(s => s.trim()).filter(Boolean))]\n const updated: AuthProfile = { ...rest, models: { mode: \"allow\", ids } }\n await deps.addProfile(updated)\n return updated\n}\n\n/** Above this length a label is almost certainly a paste gone wrong rather\n * than a deliberate name — reject rather than silently truncate. */\nconst MAX_LABEL_LENGTH = 200\n\n/** Patch input for {@link updateAuthProfile}. Each field is tri-state:\n * ABSENT leaves the current value untouched, `null` clears it, and a\n * concrete value replaces it. At least one of `label` / `costBudget` must\n * be present (absent from both is a no-op input, rejected rather than\n * silently doing nothing). */\nexport interface UpdateAuthProfileInput {\n /** New display label, or `null` to clear it. */\n label?: string | null\n /** New windowed spend cap, or `null` to clear it. */\n costBudget?: CostBudget | null\n}\n\n/**\n * Update a profile's `label` and/or `costBudget` (WS-G5) — the two fields\n * `profile-store.ts`'s schema already carries but never had a setter for.\n * Metadata-only, mirroring {@link setAuthProfileEnabled} / {@link\n * setAuthProfileModels}: NEVER touches `credentialRef`, `source`, or the\n * credential store. `null` clears a field entirely (byte-identical to a\n * profile that never had it); ABSENT leaves the current value untouched. A\n * given `label` is trimmed and rejected if it becomes empty or exceeds\n * {@link MAX_LABEL_LENGTH}; a given `costBudget` is validated against the\n * same `costBudgetSchema` the on-disk file itself is parsed with. Throws\n * {@link AuthProfileValidationError} for an unknown id, an empty patch, or a\n * field that fails validation. Returns the updated (non-secret) profile.\n */\nexport async function updateAuthProfile(\n id: string,\n patch: UpdateAuthProfileInput,\n deps: ProfileProvisionDeps,\n): Promise<AuthProfile> {\n const trimmed = (id ?? \"\").trim()\n if (!trimmed) throw new AuthProfileValidationError(\"id is required\")\n\n const hasLabel = Object.prototype.hasOwnProperty.call(patch, \"label\")\n const hasCostBudget = Object.prototype.hasOwnProperty.call(patch, \"costBudget\")\n if (!hasLabel && !hasCostBudget) {\n throw new AuthProfileValidationError(\n \"at least one of label or costBudget is required\",\n )\n }\n\n let nextLabel: string | undefined\n if (hasLabel && patch.label !== null) {\n // patch is caller-declared as UpdateAuthProfileInput, but an HTTP body\n // reaches here with no such guarantee — validate the runtime type\n // before .trim() rather than let a non-string throw a raw TypeError.\n if (typeof patch.label !== \"string\") {\n throw new AuthProfileValidationError(\"label must be a string or null\")\n }\n nextLabel = patch.label.trim()\n if (!nextLabel) {\n throw new AuthProfileValidationError(\"label must not be blank; pass null to clear it\")\n }\n if (nextLabel.length > MAX_LABEL_LENGTH) {\n throw new AuthProfileValidationError(\n `label must be at most ${MAX_LABEL_LENGTH} characters`,\n )\n }\n }\n\n let nextCostBudget: CostBudget | undefined\n if (hasCostBudget && patch.costBudget !== null) {\n const parsed = costBudgetSchema.safeParse(patch.costBudget)\n if (!parsed.success) {\n throw new AuthProfileValidationError(\n `costBudget is invalid: ${parsed.error.issues.map(i => i.message).join(\", \")}`,\n )\n }\n nextCostBudget = parsed.data\n }\n\n const profile = await deps.getProfile(trimmed)\n if (!profile) {\n throw new AuthProfileValidationError(`no profile with id \"${trimmed}\"`)\n }\n\n const { label: _dropLabel, costBudget: _dropCostBudget, ...rest } = profile\n const updated: AuthProfile = { ...rest }\n if (hasLabel) {\n if (nextLabel !== undefined) updated.label = nextLabel\n } else if (profile.label !== undefined) {\n updated.label = profile.label\n }\n if (hasCostBudget) {\n if (nextCostBudget !== undefined) updated.costBudget = nextCostBudget\n } else if (profile.costBudget !== undefined) {\n updated.costBudget = profile.costBudget\n }\n\n await deps.addProfile(updated)\n return updated\n}\n\n/** The result of {@link refreshAuthProfileModels} — the updated profile plus\n * the diff against the previous allowlist, so a caller (CLI, MCP tool) can\n * report exactly what changed without re-diffing itself. */\nexport interface RefreshAuthProfileModelsResult {\n profile: AuthProfile\n /** Ids newly present in the refreshed allowlist that weren't in the old one. */\n added: string[]\n /** Ids that were in the old allowlist but have dropped out of the current\n * catalog snapshot (e.g. a retired model). */\n removed: string[]\n}\n\n/**\n * Re-sync a `mode: \"allow\"` profile's `ids` against a CURRENT catalog\n * snapshot for its endpoint (WS3 follow-up — fixes curation drift). A\n * profile's allowlist is otherwise a frozen snapshot taken once at\n * create/import time: the catalog moves (new models ship, old ones retire)\n * but `ids` never does, so a profile silently stops seeing new models and\n * keeps offering retired ones. This re-runs the SAME enumeration a caller\n * would have used to build the list in the first place — \"every model\n * currently known for this profile's endpoint\" — against `currentIds`, so\n * `ids` tracks the live catalog instead of the day it was written.\n *\n * `currentIds` is caller-supplied (typically every id `getModelsByProvider`\n * /`buildCatalogProviderModels` reports for `profile.endpoint`) rather than\n * looked up here, keeping this package decoupled from `@agentproto/model-catalog`\n * (see {@link AuthProfile.endpoint}'s doc) and the diffing logic unit-testable\n * against a fake snapshot with no catalog wiring at all.\n *\n * Deliberately EXPLICIT and OPT-IN — a caller (CLI verb, MCP tool) invokes\n * this on one named profile; nothing calls it automatically. A profile a\n * human deliberately narrowed is therefore never touched unless that human\n * (or an operator with the same intent) explicitly asks this profile to be\n * refreshed.\n *\n * Throws {@link AuthProfileValidationError} for an unknown id, and — by\n * design — for a profile with no `mode: \"allow\"` curation to refresh: an\n * absent `models` field (or `mode: \"all\"`) already tracks the live catalog\n * on every read (see `profileAllowsModel` in `catalog-models.ts`), so\n * \"refreshing\" it would be a silent no-op that could mask the caller asking\n * for the wrong profile. Rejecting loudly instead surfaces that mismatch.\n */\nexport async function refreshAuthProfileModels(\n id: string,\n currentIds: readonly string[],\n deps: ProfileProvisionDeps,\n): Promise<RefreshAuthProfileModelsResult> {\n const trimmed = (id ?? \"\").trim()\n if (!trimmed) throw new AuthProfileValidationError(\"id is required\")\n\n const profile = await deps.getProfile(trimmed)\n if (!profile) {\n throw new AuthProfileValidationError(`no profile with id \"${trimmed}\"`)\n }\n if (!profile.models || profile.models.mode !== \"allow\") {\n throw new AuthProfileValidationError(\n `profile \"${trimmed}\" has no mode:\"allow\" curation to refresh — ` +\n `mode:\"all\" (or absent models) already tracks the live catalog on every read`,\n )\n }\n\n const nextIds = [...new Set(currentIds.map(s => s.trim()).filter(Boolean))]\n const prevIds = profile.models.ids\n const prevSet = new Set(prevIds)\n const nextSet = new Set(nextIds)\n const added = nextIds.filter(i => !prevSet.has(i))\n const removed = prevIds.filter(i => !nextSet.has(i))\n\n const updated: AuthProfile = { ...profile, models: { mode: \"allow\", ids: nextIds } }\n await deps.addProfile(updated)\n return { profile: updated, added, removed }\n}\n","/**\n * (adapter × route) → billing-endpoint resolution + the profile eligibility predicate\n * (SPEC §1c, `agentproto-session-config-axes/SPEC.md:102-125`).\n *\n * profile eligible for (adapter, route) iff\n * profile.endpoint == resolveEndpoint(adapter, route).endpoint\n * AND profile.method ∈ methodsPresentable(adapter, route)\n *\n * `route` is the endpoint selector (SPEC axis #4 — direct vs a gateway mode\n * like `moonshot`/`openrouter`), so access is deliberately downstream of it:\n * which endpoint (and thus which profiles) are eligible changes when route\n * changes. `AdapterAuthManifest` is a narrow, package-local projection of\n * exactly what this predicate needs from an adapter's real AIP-45 manifest\n * (`packages/driver/agent-cli/src/types.ts`'s `AgentCliDefinition`) — this\n * package intentionally does not depend on `@agentproto/driver-agent-cli`\n * (wrong dependency direction; drivers consume auth, not vice versa), so the\n * runtime is the one that will later project a real manifest into this\n * shape (out of scope here — foundation only, no live spawn-path wiring).\n *\n * `methodsByRoute` is the static per-endpoint method table ADR'd in SPEC §3.4:\n * \"which auth methods this adapter can present for a resolved route.\" It is\n * the derivable replacement for two hand-maintained artifacts SPEC §1c calls\n * out for eventual removal — the per-adapter `authSubscription` boolean\n * (`adapters/claude-code/src/index.ts:90-95`) and curatorial vendor deny\n * lists (`adapters/hermes/HERMES.md:40-42`) — neither of which this PR\n * touches; `authSubscription` stays exactly as-is (see the comment on it in\n * `spawn-defaults.ts:345` — this module is additive, not a replacement).\n *\n * ACP `authenticate` is NOT a live discovery source for this table (the\n * server handler is a stub, `packages/acp/src/server/index.ts:69`) — method\n * discovery is this static table, not runtime negotiation (SPEC §3.7).\n */\n\nimport type { AuthMethod, AuthProfile } from \"./profile-types.js\"\n\n/** A narrow, package-local projection of an adapter's declared auth\n * capability — enough to resolve (adapter, route) → endpoint and the auth\n * methods presentable on that route. Not the real AIP-45 manifest type. */\nexport interface AdapterAuthManifest {\n /** Adapter id (e.g. \"claude-code\", \"hermes\"), for error messages only. */\n id: string\n /** route id (e.g. \"direct\", or a gateway mode id like \"moonshot\") →\n * the billing endpoint used when spawned on that route. */\n endpointByRoute: Readonly<Record<string, string>>\n /** route id → the auth methods this adapter can present when spawned on\n * that route — the method-side of the eligibility predicate. */\n methodsByRoute: Readonly<Record<string, readonly AuthMethod[]>>\n}\n\n/** Resolve which billing endpoint a given (adapter, route) pair uses. Throws\n * when the manifest declares no endpoint for `route` — an unresolvable route\n * is a caller bug (a bad/unknown route id), not a \"no profiles eligible\"\n * case, so this fails loud rather than returning an empty endpoint. */\nexport function resolveEndpoint(\n manifest: AdapterAuthManifest,\n route: string,\n): { endpoint: string } {\n const endpoint = manifest.endpointByRoute[route]\n if (endpoint === undefined) {\n throw new Error(\n `resolveEndpoint: adapter \"${manifest.id}\" declares no endpoint for route \"${route}\"`,\n )\n }\n return { endpoint }\n}\n\n/** Which auth methods `manifest`'s adapter can present on `route`. Empty\n * (never throws) when the route is declared for vendor resolution but has\n * no methods table entry — that's \"no eligible profiles\", a legitimate\n * eligibility outcome, not an error. */\nexport function methodsPresentable(\n manifest: AdapterAuthManifest,\n route: string,\n): AuthMethod[] {\n return [...(manifest.methodsByRoute[route] ?? [])]\n}\n\n/** The eligibility predicate: profiles whose endpoint matches the route's\n * resolved endpoint AND whose method the adapter can present on that route.\n * A whole-profile-disabled profile (`disabled: true`) is skipped outright —\n * every model it would otherwise service drops to non-runnable (WS2). This is\n * the profile-level gate; per-model curation (`models`) is intersected\n * downstream in the catalog join, not here (SPEC §1c / catalog-models.ts). */\nexport function eligibleProfiles(\n profiles: readonly AuthProfile[],\n manifest: AdapterAuthManifest,\n route: string,\n): AuthProfile[] {\n const { endpoint } = resolveEndpoint(manifest, route)\n const methods = methodsPresentable(manifest, route)\n return profiles.filter(\n p => !p.disabled && p.endpoint === endpoint && methods.includes(p.method),\n )\n}\n","/**\n * @agentproto/auth — AIP-50 AUTH.md reference implementation.\n *\n * Public API:\n * defineAuthProvider(def) — TS-literal authoring (frozen handle)\n * parseAuthProviderManifest(source) — .md authoring (gray-matter + Zod)\n * registerAuthProvider(handle) — extend the module-level registry\n * getAuthProvider(id) — lookup by vendor id\n * listAuthProviderIds() — enumerate known providers\n * discoverEndpoints(apiBase) — two-hop PRM → AS metadata discovery\n * runAuthFlow(provider, opts) — resolve + discover + dispatch to engine\n * FLOW_ENGINES — registered flow engines (pat, …)\n * CeremonyRequiredError — thrown by device-code's refreshOnly\n * mode when only an interactive\n * ceremony would satisfy the request\n * writeKeychainToken(svc, acct, t) — persist a credential to Keychain\n * readKeychainToken(svc, acct) — read a credential from Keychain\n * resolveAccount(acct, server) — expand {server} template\n * KeychainStore / MemoryStore / FileStore — built-in CredentialStore backends\n * resolveStoreRef(spec, server) — map a TokenStoreSpec to a StoreRef\n * CredentialBroker — path → ready-to-use auth headers\n * AuthProfile / AuthMethod — named, endpoint-scoped credential ref\n * listAuthProfiles/getAuthProfile/\n * addAuthProfile/removeAuthProfile — named-profile store CRUD\n * resolveEndpoint/methodsPresentable/\n * eligibleProfiles — (adapter × route) → endpoint + the\n * profile eligibility predicate\n * refreshAuthProfileModels(id, ids) — re-sync a mode:\"allow\" profile's\n * `ids` against a current catalog\n * snapshot (fixes curation drift)\n */\n\nexport { defineAuthProvider } from \"./define-auth-provider.js\"\nexport {\n parseAuthProviderManifest,\n parseAuthProviderManifestRaw,\n type AuthProviderManifest,\n} from \"./manifest.js\"\nexport {\n registerAuthProvider,\n getAuthProvider,\n listAuthProviders,\n listAuthProviderIds,\n} from \"./registry.js\"\nexport {\n discoverEndpoints,\n DiscoveryError,\n} from \"./discover.js\"\nexport { runAuthFlow, type RunFlowOptions } from \"./run-flow.js\"\nexport { FLOW_ENGINES } from \"./flow-engines/index.js\"\nexport { CeremonyRequiredError } from \"./flow-engines/device-code.js\"\nexport {\n readKeychainToken,\n writeKeychainToken,\n deleteKeychainToken,\n resolveAccount,\n} from \"./token-store.js\"\nexport { KeychainStore } from \"./store/keychain-store.js\"\nexport { MemoryStore } from \"./store/memory-store.js\"\nexport { FileStore } from \"./store/file-store.js\"\nexport { resolveStoreRef } from \"./store/resolve-ref.js\"\nexport type {\n CredentialStore,\n StoreRef,\n StoredCredential,\n} from \"./store/types.js\"\nexport { CredentialBroker, type CredentialBrokerOptions } from \"./broker.js\"\nexport type {\n AuthMethod,\n AuthProfile,\n ModelCuration,\n CostBudget,\n CostBudgetScope,\n} from \"./profile-types.js\"\nexport {\n authProfilesPath,\n loadAuthProfiles,\n listAuthProfiles,\n getAuthProfile,\n addAuthProfile,\n removeAuthProfile,\n type AuthProfilesFile,\n} from \"./profile-store.js\"\nexport {\n createAuthProfile,\n deleteAuthProfile,\n setAuthProfileEnabled,\n setAuthProfileModels,\n updateAuthProfile,\n refreshAuthProfileModels,\n validateCreateInput,\n deriveCredentialRef,\n fingerprintCredential,\n credentialIdentity,\n AuthProfileValidationError,\n type CreateAuthProfileInput,\n type CreatedAuthProfile,\n type DeletedAuthProfile,\n type CredentialIdentity,\n type ProfileProvisionDeps,\n type ValidatedCreateInput,\n type UpdateAuthProfileInput,\n type RefreshAuthProfileModelsResult,\n} from \"./profile-provision.js\"\nexport {\n resolveEndpoint,\n methodsPresentable,\n eligibleProfiles,\n type AdapterAuthManifest,\n} from \"./eligibility.js\"\nexport { guildeAuthProvider, BUILTIN_AUTH_PROVIDERS } from \"./builtins.js\"\nexport {\n authProviderFrontmatterSchema,\n authConfigSchema,\n tokenStoreSpecSchema,\n installConfigSchema,\n type AuthProviderFrontmatter,\n} from \"./schema.js\"\nexport type {\n AuthProviderDefinition,\n AuthProviderHandle,\n AuthConfig,\n PATAuthConfig,\n ServiceAuthConfig,\n DeviceCodeAuthConfig,\n InstallConfig,\n TokenStoreSpec,\n FlowEngine,\n FlowId,\n FlowResult,\n FlowRunOptions,\n DiscoveredEndpoints,\n} from \"./types.js\"\n\nexport const SPEC_NAME = \"agentauth\"\nexport const SPEC_VERSION = \"v1\"\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentproto/auth",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "@agentproto/auth — AIP-50 AUTH.md reference implementation. Auth-provider doctype: how CLI tools and agents authenticate to API servers via a standardized discovery chain and pluggable flow engines, aligned to the WorkOS auth.md open standard.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agentproto",
|