@agentproto/auth

中文文档
1.4.0发布于 2026/10/27Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 1.2万

@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.

原始使用文档
文档目录15 节
  1. Install
  2. Two authoring paths, one validated shape
  3. TS literal
  4. .md manifest
  5. Running a flow
  6. pat flow
  7. service-auth flow
  8. Discovery
  9. Token storage
  10. Credential store
  11. Credential broker — resolveHeaders
  12. Feeding an MCP transport
  13. Sub-accounts
  14. API surface
  15. License

@agentproto/auth

AIP-50 AUTH.md reference implementation. An auth-provider doctype: a markdown + frontmatter (or TS-literal) manifest that declares, for one API server, how a CLI tool or agent authenticates and where to call the AIP-19 provision endpoints. It holds configuration, never credentials — the flow engine reads or prompts credentials at runtime.

Aligned to the WorkOS auth.md open standard: two-hop .well-known discovery, the agent_auth metadata block, and the service-auth claim ceremony (urn:workos:agent-auth:grant-type:claim).

Status: 0.2.0-alpha. Two flows specified in v1 (pat, service-auth); id-jag (agentproto-as-IdP) is reserved.

Spec: https://agentproto.sh/docs/aip-50 · Standard: https://github.com/workos/auth.md

Install

pnpm add @agentproto/auth

Two authoring paths, one validated shape

A single Zod schema (./schema.ts) backs both paths, so a malformed literal and a malformed .md fail with the same diagnostic.

TS literal

import { defineAuthProvider } from "@agentproto/auth"

export const guilde = defineAuthProvider({
  id: "guilde",
  description: "Guilde AI company platform — browser-approve, no key to paste.",
  apiBase: "https://api.guilde.work",
  auth: {
    flow: "service-auth",
    clientId: "agentproto-cli",
    tokenStore: { keychain: "bureau-guilde", account: "{server}" },
  },
  install: {
    sealKey: "/guilde/api/v1/connectors/seal-key",
    secretBacked: "/guilde/api/v1/guilds/{guildId}/connectors/secret-backed",
  },
})

.md manifest

A host reads its own vendor-shipped *.auth.md and registers it without editing this package — the manifest parser is the extension seam.

---
id: acme
description: ACME API — paste a personal access token.
apiBase: https://api.acme.example
auth:
  flow: pat
  tokenStore:
    keychain: acme-cli
    account: "{server}"
---

# ACME

Human/LLM-facing prose about how to obtain a token lives in the body.
import { parseAuthProviderManifest, registerAuthProvider } from "@agentproto/auth"

const acme = parseAuthProviderManifest(await readFile("acme.auth.md", "utf8"))
registerAuthProvider(acme)

Running a flow

runAuthFlow resolves the provider, attempts discovery, and dispatches to the engine selected by provider.auth.flow — no if/switch chains at call sites.

import { getAuthProvider, runAuthFlow } from "@agentproto/auth"

const provider = getAuthProvider("guilde")!
const result = await runAuthFlow(provider, { server: "https://api.guilde.work" })
// → { accessToken: "oat_…", tokenKind: "oat" }

pat flow

Read an existing token from the platform Keychain, or prompt for one interactively. No browser, no ceremony — the legacy-compatible path for servers that issue personal access keys.

service-auth flow

The auth.md claim ceremony:

  1. POST {identity_endpoint} with { type: "service_auth", client_id } → claim_token + claim.{ user_code, verification_uri, expires_in }.
  2. Open the browser at verification_uri; the user approves.
  3. Poll POST {token_endpoint} with grant_type=urn:workos:agent-auth:grant-type:claim and claim_token until access_token is returned (authorization_pending / slow_down / expired_token / access_denied are handled per RFC 8628).
  4. On success, store the identity_assertion JWT in the Keychain — per AIP-50, the assertion is the durable credential; the access_token is ephemeral and is never persisted, and the claim_token stays in memory only.

On a subsequent run the ceremony is skipped when possible: the stored assertion is exchanged at the token endpoint via urn:ietf:params:oauth:grant-type:jwt-bearer for a fresh access_token ("this IS the refresh path" — no refresh token). Only when the assertion is expired or rejected (invalid_grant) does a new browser ceremony start.

Discovery

discoverEndpoints(apiBase) performs the two-hop chain and throws DiscoveryError when a server predates auth.md. Callers catch it and fall back to the static manifest config — discovery failure must never block a static flow.

GET {apiBase}/.well-known/oauth-protected-resource     → authorization_servers[0]
GET {authServerBase}/.well-known/oauth-authorization-server
                                  → token_endpoint + agent_auth.identity_endpoint

Every request (discovery, ceremony, refresh) is bounded by a per-request timeout (DEFAULT_HTTP_TIMEOUT_MS, override via discoverEndpoints(base, { timeoutMs })) and honours a caller AbortSignal ({ signal } / FlowRunOptions.signal), so a hung server can never stall the CLI. Responses are Zod-validated at the boundary rather than trusted.

Token storage

token-store.ts is the platform switch and guards the platform — readKeychainToken / writeKeychainToken throw a clear error where no backend exists rather than silently returning undefined (which would re-prompt every run). macOS wraps the security CLI; Windows (recap D7) seals one DPAPI-protected file per slot under ~/.agentproto/keychain-dpapi/ via .NET ProtectedData at CurrentUser scope through PowerShell — per-user encryption, zero npm dependencies, and nothing beyond stock Windows (Get-StoredCredential is NOT required). Linux is still unimplemented; libsecret would be the equivalent there. resolveAccount(account, server) expands the {server} template in a tokenStore.account spec.

Credential store

Flow engines never touch a concrete backend — they depend on the CredentialStore interface, so the same pat / service-auth flow runs against the macOS Keychain in a CLI, an in-memory map in a test, or an encrypted file on a headless host.

interface CredentialStore {
  read(ref: StoreRef): Promise<StoredCredential | undefined>
  write(ref: StoreRef, cred: StoredCredential): Promise<void>
  delete?(ref: StoreRef): Promise<void>   // optional — backend permitting
}

interface StoreRef { path: string; account?: string }      // where it lives
interface StoredCredential {                               // what's stored
  value: string
  kind: "pat" | "assertion" | "oat"
  expiresAt?: string
  metadata?: Record<string, unknown>
}

resolveStoreRef(tokenStore, server) maps a provider's tokenStore spec (expanding the {server} template) to a StoreRef — so a token written under a ref resolves under the same ref on read.

BackendUse
KeychainStoremacOS security CLI — the interactive-CLI default
MemoryStoreephemeral, for tests
FileStoreAES-256-GCM at rest; key from AGENTPROTO_STORE_KEY, no plaintext fallback — for headless hosts with no Keychain

A host can implement the interface over its own vault (Guilde backs it with an AAD-bound, per-user secrets service). The flow engine is none the wiser.

Credential broker — resolveHeaders

The broker is the "Agent.pw parity" surface: give it a path, get back ready-to-use HTTP auth headers, with a fresh token resolved at call-time. It turns a stored credential (or a full flow run) into { Authorization: "Bearer …" } without the caller knowing which.

import { CredentialBroker } from "@agentproto/auth"

const broker = new CredentialBroker({ store, getProvider: getAuthProvider })

const headers = await broker.resolveHeaders({
  path: "guilde",              // "<providerId>" or "<providerId>/<account>"
  server: "https://api.guilde.work", // optional; defaults to provider.apiBase
  signal,                      // optional AbortSignal
})
// → { Authorization: "Bearer oat_…" }

resolveHeaders:

  1. parses path → providerId (+ optional account) and resolves the provider via getProvider; throws on an unknown provider;
  2. reads the store at the resolved ref — if a stored bearer credential is still fresh (past a 60s skew), returns it directly;
  3. otherwise runs the provider's flow (runAuthFlow, threading the same store + signal) — for service-auth, that's the assertion → jwt-bearer exchange — and returns the minted token;
  4. throws if the flow yields no usable access token.

Fresh-per-call, no long-lived header cache. This is the headless/cron payoff: a scheduled agent re-resolves a valid Authorization at connect-time with no human re-auth, as long as a durable credential (a PAT, or a service-auth assertion) sits in the store.

Runnable example: src/__tests__/broker.example.test.ts is a zero-mock, copy-pasteable wire-up (provider → store → broker → resolveHeaders) you can lift verbatim.

Feeding an MCP transport

@agentproto/secrets/exposure declares a structural McpHeaderResolver (resolveHeaders({ path, server?, signal? })) that CredentialBroker satisfies with no adapter — so a connector can declare an mcp-header exposure and have resolveMcpHeaderExposure(exposure, broker) lay brokered headers onto the transport. secrets keeps zero dependency on auth through that structural seam. See @agentproto/secrets' README.

Sub-accounts

An account (a login or billing identity) can have sub-accounts — orgs, workspaces, projects — each with its own quota. A profile pins one with the optional subaccount field, so every pin is a distinct, truthful wallet:

{ "id": "acme-ws01", "endpoint": "<endpoint>", "method": "api-key",
  "source": "<account-source>", "subaccount": { "kind": "org", "id": "org_01ABC", "name": "Ws01" } }

kind is [a-z][a-z0-9-]*; id is opaque; name is a display label used in usage-limit tags. The field is optional and the on-disk store format is unchanged. CLI: agentproto auth profile create <id> --subaccount <kind>:<id> and agentproto auth subaccounts list <profile|account> [--create [--prefix]].

How a pin is applied belongs to a provider, never to this package or the runtime. A provider implements SubaccountProvider and is added with registerSubaccountProvider:

MemberPurpose
id, source?, endpoints?, kindsidentity, and which accounts it owns (by source name, else by endpoint)
list(account)discovery: { account, subaccounts: [{kind, id, name}] }
resolve(profile, { credential? })spawn time: { credential?, credentialEnvOverride?, env?, isolateDataHome? }
migrateLegacySource?(source)read-time migration of a pre-pin provider-encoded source into the pin

A provider throws SubaccountError when a pin cannot be listed or resolved; the runtime fails the spawn loudly rather than falling back to the account's default scope. Providers ship with their adapter and the host registers them (the CLI does so for the built-ins).

The registry is process-global and starts EMPTY: a host that uses @agentproto/auth outside the CLI must call registerSubaccountProvider for each provider it needs BEFORE creating, reading or spawning pinned profiles. Until then, creating a profile with a legacy opencode-console:<orgId> source is rejected, and a spawn on a pinned profile whose provider is not registered fails with auth_source_unresolved (it never runs on the account's default scope). A pin on a credential-backed profile is accepted at create time even when no provider owns its endpoint yet; the clear error comes at spawn time.

API surface

ExportPurpose
defineAuthProvider(def)TS-literal authoring → frozen handle
parseAuthProviderManifest(src).md authoring → frozen handle
registerAuthProvider / getAuthProvider / listAuthProviders / listAuthProviderIdsmodule-level registry (pre-seeded with builtins)
discoverEndpoints / DiscoveryErrortwo-hop .well-known discovery
runAuthFlowresolve → discover → dispatch
FLOW_ENGINESregistered flow engines (pat, service-auth)
CredentialBroker / CredentialBrokerOptionspath → fresh resolveHeaders
eligibleProfiles(adapter × route) → vendor + profile eligibility predicate
CredentialStore / StoreRef / StoredCredentialpluggable-store interface + shapes
KeychainStore / MemoryStore / FileStore / resolveStoreRefbuilt-in backends + ref resolver
readKeychainToken / writeKeychainToken / resolveAccountKeychain helpers
guildeAuthProvider / BUILTIN_AUTH_PROVIDERSshipped builtins
registerSubaccountProvider / findSubaccountProvider / listSubaccountProviderssub-account provider registry
SubaccountProvider / SubaccountPin / SubaccountError / parseSubaccountPinsub-account contract

License

MIT — see LICENSE.

版本与发布记录

@agentproto/auth 共发布 15 个版本,首次发布于 2026/06/21;过去 12 个月发布了 15 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.4.0latest2026/10/279 天前
1.3.12026/10/1918 天前
1.3.02026/10/1621 天前
1.2.02026/10/1026 天前
1.1.22026/09/301 个月前
1.1.12026/09/301 个月前

关于 @agentproto/auth 的常见问题

@agentproto/auth 是什么?

@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.

如何安装 @agentproto/auth?

在项目目录运行 npm install @agentproto/auth,或使用 pnpm add / yarn add / bun add。

@agentproto/auth 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@agentproto/auth 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@agentproto/auth 可以商用吗?

@agentproto/auth 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@agentproto/auth 的下载量有多少?

根据 npm 官方下载统计,@agentproto/auth 在 2026/10/05 – 2026/11/03 这 30 天内被下载 11,624 次,日均约 387 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@agentproto/auth 还在维护吗?

最新版本 1.4.0 发布于 2026/10/27(9 天前);至今共发布 15 个版本,其中过去 12 个月发布了 15 个;首次发布于 2026/06/21。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。