wb-auth 0.2.0 → 0.4.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.cjs +786 -224
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +165 -69
- package/dist/index.d.ts +165 -69
- package/dist/index.js +786 -230
- package/dist/index.js.map +1 -1
- package/package.json +73 -76
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/signer.ts","../src/adapters/_utils.ts","../src/adapters/fetch.ts","../src/adapters/playwright.ts","../src/identity.ts","../src/index.ts"],"sourcesContent":["/**\n * Pure-function signer for Web Bot Auth (RFC 9421).\n *\n * Mirrors python/src/wbauth/signer.py — same defaults (Ed25519, tag=\n * \"web-bot-auth\", expires=created+60s, covered components [\"@authority\",\n * \"signature-agent\"] + \"content-digest\" for bodies).\n *\n * The function delegates all RFC 9421 mechanics (signing-base canonicalization,\n * structured-field encoding, Ed25519 signing) to `web-bot-auth` 0.1.3's\n * `signatureHeaders`. We only own the Web Bot Auth profile glue: pre-setting\n * Signature-Agent (Pitfall 6), picking covered components, defaulting expires.\n */\nimport { type SignatureParams, signatureHeaders } from \"web-bot-auth\";\nimport type { Identity } from \"./identity.js\";\nimport type { NormalizedRequest } from \"./normalized-request.js\";\n\n// ---------- Module constants (HARD-CODED — typos = silent verifier reject) ----------\n\n/** IETF Web Bot Auth profile mandate. NEVER change. Pitfall 6. */\nconst WEB_BOT_AUTH_TAG = \"web-bot-auth\";\n/** Canonical Signature label. Most verifier examples assume \"sig1\". */\nconst DEFAULT_LABEL = \"sig1\";\n/** Default expires window. 60s leaves NTP-skew + network-latency headroom. */\nconst DEFAULT_EXPIRES_SECONDS = 60;\n/** Methods that may carry a body and therefore want content-digest covered. */\nconst DIGEST_METHODS = new Set([\"POST\", \"PUT\", \"PATCH\"]);\n// WEB_BOT_AUTH_TAG is enforced internally by web-bot-auth's signatureHeaders;\n// we keep the constant for greppability of the profile invariant.\nvoid WEB_BOT_AUTH_TAG;\n\n// ---------- Public types ----------\n\nexport interface SignatureHeaders {\n\tsignature: string;\n\tsignatureInput: string;\n\tsignatureAgent: string;\n}\n\nexport interface SignOptions {\n\t/** Signing timestamp. Defaults to `new Date()`. Override for vector reproducibility. */\n\tcreated?: Date;\n\t/** Validity window in seconds. Defaults to 60. */\n\texpiresAfterSeconds?: number;\n\t/** Anti-replay nonce. Defaults to web-bot-auth's `generateNonce()` (64-byte b64). */\n\tnonce?: string;\n\t/** Signature label (the `sig1=` prefix). Defaults to \"sig1\". */\n\tlabel?: string;\n}\n\n// ---------- Components selector (mirror Python `_components_for`) ----------\n\nfunction componentsFor(method: string, hasBody: boolean): string[] {\n\tconst base = [\"@authority\", \"signature-agent\"];\n\tif (hasBody && DIGEST_METHODS.has(method.toUpperCase())) {\n\t\tbase.push(\"content-digest\");\n\t}\n\treturn base;\n}\n\n/** Headers regenerated on every sign() call. */\nconst RESIGN_HEADERS = [\"signature\", \"signature-input\", \"signature-agent\"];\n\nfunction hasHeader(headers: Record<string, string>, name: string): boolean {\n\tconst n = name.toLowerCase();\n\treturn Object.keys(headers).some((k) => k.toLowerCase() === n);\n}\n\nfunction removeHeaders(headers: Record<string, string>, names: string[]): void {\n\tfor (const k of Object.keys(headers)) {\n\t\tif (names.includes(k.toLowerCase())) delete headers[k];\n\t}\n}\n\n// ---------- Public API ----------\n\n/**\n * Sign a NormalizedRequest with the Web Bot Auth profile.\n *\n * Mutates `request.headers` in place: writes Signature-Agent BEFORE building\n * the signing base (Pitfall 6 — without pre-set, web-bot-auth defaults to\n * `[\"@authority\"]` only and silently breaks byte-equality with the Python\n * signer). After signatureHeaders returns, also writes Signature and\n * Signature-Input back into `request.headers`.\n *\n * @returns the same three values as a typed dataclass for callers that prefer\n * a return value over header inspection.\n */\nexport async function sign(\n\trequest: NormalizedRequest,\n\tidentity: Identity,\n\topts: SignOptions = {},\n): Promise<SignatureHeaders> {\n\t// 1. Defensive https:// check — Identity ctor enforces it too, but a future\n\t// bypassed ctor would otherwise leak http://. Pitfall 1.\n\tif (!identity.signatureAgentUrl.startsWith(\"https://\")) {\n\t\tthrow new Error(\n\t\t\t`signatureAgentUrl must be https://, got: ${identity.signatureAgentUrl}`,\n\t\t);\n\t}\n\n\t// 2. Validate options up-front (parity with Python signer).\n\tconst expiresAfterSeconds =\n\t\topts.expiresAfterSeconds ?? DEFAULT_EXPIRES_SECONDS;\n\tif (!Number.isFinite(expiresAfterSeconds) || expiresAfterSeconds <= 0) {\n\t\tthrow new RangeError(\n\t\t\t`expiresAfterSeconds must be a positive number, got: ${expiresAfterSeconds}`,\n\t\t);\n\t}\n\n\t// 3. Drop stale signature headers in ANY casing. A retried / redirected\n\t// request still carries the previous hop's values; leaving them in place\n\t// produces merged `sig1=..., sig1=...` headers that every verifier rejects.\n\tremoveHeaders(request.headers, RESIGN_HEADERS);\n\n\t// 4. Set Signature-Agent header (RFC 8941 string in double quotes).\n\t// CRITICAL: must be set BEFORE signatureHeaders inspects the message,\n\t// otherwise web-bot-auth picks REQUEST_COMPONENTS_WITHOUT_SIGNATURE_AGENT.\n\tconst signatureAgentHeader = `\"${identity.signatureAgentUrl}\"`;\n\trequest.headers[\"Signature-Agent\"] = signatureAgentHeader;\n\n\t// 5. Defaults.\n\tconst created = opts.created ?? new Date();\n\tconst expires = new Date(created.getTime() + expiresAfterSeconds * 1000);\n\tconst label = opts.label ?? DEFAULT_LABEL;\n\n\t// 6. Components based on body presence.\n\tconst hasBody =\n\t\trequest.body !== null &&\n\t\trequest.body !== undefined &&\n\t\trequest.body.byteLength > 0;\n\tconst components = componentsFor(request.method, hasBody);\n\tif (\n\t\tcomponents.includes(\"content-digest\") &&\n\t\t!hasHeader(request.headers, \"content-digest\")\n\t) {\n\t\t// Python raises here too. Signing a missing header would yield a\n\t\t// signature that no verifier can ever validate.\n\t\tthrow new Error(\n\t\t\t'Covered header field \"content-digest\" not found in the message. ' +\n\t\t\t\t\"Call ensureContentDigest() or use createSignedFetch()/applyTo(), which add it automatically.\",\n\t\t);\n\t}\n\n\t// 7. Build a Web `Request` for web-bot-auth's `signatureHeaders`.\n\tconst headers = new Headers();\n\tfor (const [k, v] of Object.entries(request.headers)) headers.set(k, v);\n\tconst init: RequestInit = { method: request.method, headers };\n\t// Cast: Uint8Array is a valid BodyInit at runtime (web fetch spec) but DOM\n\t// typing wants ArrayBufferView/string/Blob etc. The cast is safe.\n\tif (hasBody) init.body = request.body as unknown as BodyInit;\n\tconst req = new Request(request.url, init);\n\n\t// 8. Delegate to web-bot-auth. The signer is the active key's pre-resolved\n\t// Signer (cached in Identity at construction time).\n\tconst params: SignatureParams = {\n\t\tcreated,\n\t\texpires,\n\t\tkey: label,\n\t\tcomponents,\n\t\t...(opts.nonce !== undefined ? { nonce: opts.nonce } : {}),\n\t};\n\tconst result = await signatureHeaders(req, identity._signer(), params);\n\n\t// 9. Mutate request.headers (mirror Python signer behavior).\n\trequest.headers.Signature = result.Signature;\n\trequest.headers[\"Signature-Input\"] = result[\"Signature-Input\"];\n\n\treturn {\n\t\tsignature: result.Signature,\n\t\tsignatureInput: result[\"Signature-Input\"],\n\t\tsignatureAgent: signatureAgentHeader,\n\t};\n}\n","/**\n * Shared adapter helpers (internal — not part of the public surface).\n *\n * Mirror python/src/wbauth/adapters/_utils.py. The signer auto-includes\n * `content-digest` in covered components for POST/PUT/PATCH with a body;\n * adapters call ensureContentDigest() before sign() so that precondition\n * is met. RFC 9530 sha-256 in structured-fields form (`sha-256=:<b64>:`).\n */\nimport { createHash } from \"node:crypto\";\n\nconst DIGEST_METHODS = new Set([\"POST\", \"PUT\", \"PATCH\"]);\n\n/** Default UAs injected by HTTP stacks; an Identity UA should replace them. */\nconst LIBRARY_DEFAULT_UA = /^(node|undici|node-fetch)(\\/|$)/i;\n\nfunction findHeader(\n\theaders: Record<string, string>,\n\tname: string,\n): string | undefined {\n\tconst n = name.toLowerCase();\n\treturn Object.keys(headers).find((k) => k.toLowerCase() === n);\n}\n\n/**\n * Mutate `headers` in place to add Content-Digest when warranted. No-op if:\n * - body is null/empty,\n * - method is not POST/PUT/PATCH,\n * - the request already carries a Content-Digest header (case-insensitive).\n */\nexport function ensureContentDigest(\n\tmethod: string,\n\theaders: Record<string, string>,\n\tbody: Uint8Array | null,\n): void {\n\tif (!body || body.byteLength === 0) return;\n\tif (!DIGEST_METHODS.has(method.toUpperCase())) return;\n\tif (findHeader(headers, \"content-digest\")) return;\n\tconst b64 = createHash(\"sha256\").update(body).digest(\"base64\");\n\theaders[\"Content-Digest\"] = `sha-256=:${b64}:`;\n}\n\n/**\n * Apply the Identity's User-Agent unless the caller explicitly set a\n * non-library UA. Library defaults (node, undici) are replaced.\n */\nexport function applyUserAgent(\n\theaders: Record<string, string>,\n\tuserAgent: string | undefined,\n): void {\n\tif (!userAgent) return;\n\tconst key = findHeader(headers, \"user-agent\");\n\tif (key === undefined) {\n\t\theaders[\"User-Agent\"] = userAgent;\n\t\treturn;\n\t}\n\tif (LIBRARY_DEFAULT_UA.test(headers[key] ?? \"\")) {\n\t\tdelete headers[key];\n\t\theaders[\"User-Agent\"] = userAgent;\n\t}\n}\n\n/**\n * Host allow-list matcher. Entries are exact hostnames (`api.example.com`)\n * or wildcard subdomains (`*.example.com`, which also matches `example.com`).\n */\nexport function hostMatches(\n\thostname: string,\n\tallow: readonly string[],\n): boolean {\n\tconst h = hostname.toLowerCase().replace(/\\.$/, \"\");\n\treturn allow.some((raw) => {\n\t\tconst a = raw.toLowerCase().replace(/\\.$/, \"\");\n\t\tif (a.startsWith(\"*.\")) {\n\t\t\tconst base = a.slice(2);\n\t\t\treturn h === base || h.endsWith(`.${base}`);\n\t\t}\n\t\treturn h === a;\n\t});\n}\n","/**\n * createSignedFetch — drop-in `fetch` wrapper that signs every outgoing request.\n *\n * Mirrors python/src/wbauth/adapters/httpx_auth.py. Stateless: closure over\n * `identity` only. Returns a function whose signature matches `typeof fetch`,\n * so user code can swap `fetch` for `signedFetch` without other changes.\n *\n * - Request-object inputs keep their `signal`, `redirect`, `credentials`,\n * `cache`, `keepalive`, `integrity` and `referrerPolicy`.\n * - Re-sending an already signed request (retry wrappers) produces exactly one\n * fresh signature — stale Signature* headers are replaced, never merged.\n *\n * v1 limitation: streaming bodies are buffered (`req.clone().arrayBuffer()`)\n * so Content-Digest can be computed.\n */\n\nimport type { Identity } from \"../identity.js\";\nimport { sign } from \"../signer.js\";\nimport { applyUserAgent, ensureContentDigest } from \"./_utils.js\";\n\nexport interface SignedFetchOptions {\n\t/** Underlying fetch implementation. Defaults to `globalThis.fetch` at call time. */\n\tfetch?: typeof fetch;\n}\n\nexport function createSignedFetch(\n\tidentity: Identity,\n\toptions: SignedFetchOptions = {},\n): typeof fetch {\n\treturn async function signedFetch(\n\t\tinput: RequestInfo | URL,\n\t\tinit: RequestInit = {},\n\t): Promise<Response> {\n\t\tconst req = new Request(input, init);\n\t\tconst method = req.method;\n\t\tconst url = req.url;\n\n\t\t// Read body once — Request consumes its body stream; clone first.\n\t\tlet body: Uint8Array | null = null;\n\t\tif (req.body) {\n\t\t\tconst buf = await req.clone().arrayBuffer();\n\t\t\tbody = buf.byteLength > 0 ? new Uint8Array(buf) : null;\n\t\t}\n\n\t\t// Mutable header dict (Headers already lower-cases + de-duplicates).\n\t\tconst headers: Record<string, string> = {};\n\t\treq.headers.forEach((value, key) => {\n\t\t\theaders[key] = value;\n\t\t});\n\n\t\t// Auto-Content-Digest BEFORE sign() (signer precondition for POST/PUT/PATCH + body).\n\t\tensureContentDigest(method, headers, body);\n\n\t\t// Sign — replaces stale Signature* headers, then writes fresh ones.\n\t\tawait sign({ method, url, headers, body }, identity);\n\t\tapplyUserAgent(headers, identity.userAgent);\n\n\t\tconst outInit: RequestInit = {\n\t\t\t...init,\n\t\t\tmethod,\n\t\t\theaders,\n\t\t\t// Uint8Array is a valid BodyInit at runtime; DOM typings disagree.\n\t\t\tbody: (body ?? undefined) as BodyInit | undefined,\n\t\t\tsignal: init.signal ?? req.signal,\n\t\t\tredirect: init.redirect ?? req.redirect,\n\t\t\tcredentials: init.credentials ?? req.credentials,\n\t\t\tcache: init.cache ?? req.cache,\n\t\t\tkeepalive: init.keepalive ?? req.keepalive,\n\t\t};\n\t\tconst integrity = init.integrity ?? req.integrity;\n\t\tif (integrity) outInit.integrity = integrity;\n\t\tconst referrerPolicy = init.referrerPolicy ?? req.referrerPolicy;\n\t\tif (referrerPolicy) outInit.referrerPolicy = referrerPolicy;\n\n\t\tconst doFetch = options.fetch ?? globalThis.fetch;\n\t\treturn doFetch(url, outInit);\n\t};\n}\n","/**\n * applyTo — sign every matching request a Playwright page sends.\n *\n * Mirrors python/src/wbauth/adapters/playwright.py.\n *\n * Privacy: by default every http(s) request is signed, including third-party\n * analytics/CDN hosts, which reveals your agent identity to them. Pass\n * `hosts` to restrict signing to the sites you actually target:\n *\n * await applyTo(page, identity, { hosts: [\"example.com\", \"*.example.org\"] });\n *\n * Non-http(s) requests (data:, blob:, chrome-extension:) are never signed.\n * Note: Playwright disables the HTTP cache while a route is active.\n */\nimport type { Page, Request as PWRequest, Route } from \"playwright\";\nimport type { Identity } from \"../identity.js\";\nimport { sign } from \"../signer.js\";\nimport { applyUserAgent, ensureContentDigest, hostMatches } from \"./_utils.js\";\n\nexport interface ApplyToOptions {\n\t/** Only sign requests to these hosts (`example.com`, `*.example.com`). */\n\thosts?: readonly string[];\n\t/** Custom predicate; takes precedence over `hosts`. */\n\tshouldSign?: (url: URL) => boolean;\n\t/** Route pattern passed to `page.route`. Default `\"**\\/*\"`. */\n\tpattern?: string;\n}\n\nexport async function applyTo(\n\tpage: Page,\n\tidentity: Identity,\n\toptions: ApplyToOptions = {},\n): Promise<void> {\n\tconst pattern = options.pattern ?? \"**/*\";\n\tconst decide = (raw: string): boolean => {\n\t\tlet u: URL;\n\t\ttry {\n\t\t\tu = new URL(raw);\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t\tif (u.protocol !== \"https:\" && u.protocol !== \"http:\") return false;\n\t\tif (options.shouldSign) return options.shouldSign(u);\n\t\tif (options.hosts) return hostMatches(u.hostname, options.hosts);\n\t\treturn true;\n\t};\n\n\tawait page.route(pattern, async (route: Route, request: PWRequest) => {\n\t\tconst url = request.url();\n\t\tif (!decide(url)) {\n\t\t\tconst r = route as Route & { fallback?: () => Promise<void> };\n\t\t\tawait (r.fallback ? r.fallback() : route.continue());\n\t\t\treturn;\n\t\t}\n\t\tconst headers = await request.allHeaders();\n\t\tconst postData = request.postDataBuffer();\n\t\tconst body = postData ? new Uint8Array(postData) : null;\n\t\tensureContentDigest(request.method(), headers, body);\n\t\tawait sign({ method: request.method(), url, headers, body }, identity);\n\t\tapplyUserAgent(headers, identity.userAgent);\n\t\tawait route.continue({ headers });\n\t});\n}\n","/**\n * Identity, KeyPair, and key-file helpers for the wbauth TypeScript SDK.\n *\n * Mirrors python/src/wbauth/identity.py — same on-disk format (PKCS8\n * NoEncryption PEM at 0o600), same kid (RFC 7638 JWK thumbprint), same\n * multi-key rotation semantics (active + retiring), same REDACTED repr\n * (IDENT-08).\n *\n * Cross-language guarantee (D-60): the PEM file Python writes via\n * `Ed25519PrivateKey.private_bytes(PEM, PKCS8, NoEncryption)` is byte-equal\n * to what Node's `crypto.generateKeyPairSync('ed25519').privateKey.export({\n * format: 'pem', type: 'pkcs8' })` writes. Both runtimes can load each\n * other's keyfile and produce the same kid + signatures.\n *\n * Key implementation choice (Pitfall 1): PEM→JWK is done via Node 20+\n * stdlib `node:crypto.createPrivateKey(pem).export({format:'jwk'})`. We do\n * NOT use `jose` or any third-party JOSE library — the stdlib output is\n * verified byte-identical to what Python's cryptography library produces\n * for the same PKCS8 PEM (RESEARCH §2.2 live verification 2026-05-10).\n */\n\nimport { createPrivateKey, generateKeyPairSync } from \"node:crypto\";\nimport {\n\tcloseSync,\n\texistsSync,\n\tmkdirSync,\n\topenSync,\n\treadFileSync,\n\tstatSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, resolve } from \"node:path\";\nimport type { Signer } from \"http-message-sig\";\nimport { signerFromJWK } from \"web-bot-auth/crypto\";\n\n// ---------- Module constants ----------\n\n/** Default path for the active signing key. Matches Python DEFAULT_KEY_PATH. */\nexport const DEFAULT_KEY_PATH = resolve(\n\thomedir(),\n\t\".config\",\n\t\"wbauth\",\n\t\"key.pem\",\n);\n\n/**\n * RFC 9421 Appendix B.1.4 publicly-known test key — NEVER use in production.\n * The private \"d\" component is published in the RFC and known to everyone.\n * `Identity.fromTestKey()` returns an Identity using these bytes.\n */\nconst TEST_KEY_JWK: JsonWebKey = {\n\tkty: \"OKP\",\n\tcrv: \"Ed25519\",\n\td: \"n4Ni-HpISpVObnQMW0wOhCKROaIKqKtW_2ZYb2p9KcU\",\n\tx: \"JrQLj5P_89iXES9-vFgrIy29clF9CC_oPPsw3c5D0bs\",\n};\n\n// ---------- Public types ----------\n\nexport interface IdentityOptions {\n\t/** Stable HTTPS URL where this agent's JWKS is published. Must start with `https://`. */\n\tsignatureAgentUrl: string;\n\t/** Optional User-Agent string adapters inject when caller did not supply one. */\n\tuserAgent?: string;\n}\n\nexport interface KeyPair {\n\t/** Private JWK (includes \"d\") — used to mint the signer. Never logged. */\n\tprivateJwk: JsonWebKey;\n\t/** Public JWK ({kty, crv, x, kid}) — what exportJwks returns per key. */\n\tpublicJwk: JsonWebKey & { kid: string };\n\t/** RFC 7638 base64url-no-pad thumbprint of the public key. */\n\tkid: string;\n\t/** Pre-resolved web-bot-auth Signer (caches the imported CryptoKey). */\n\tsigner: Signer;\n}\n\n// ---------- Identity class ----------\n\nexport class Identity {\n\tprivate _active: KeyPair;\n\tprivate _retiring: KeyPair | null;\n\treadonly signatureAgentUrl: string;\n\treadonly userAgent: string | undefined;\n\n\tprivate constructor(\n\t\tactive: KeyPair,\n\t\topts: IdentityOptions,\n\t\tretiring: KeyPair | null = null,\n\t) {\n\t\tif (!opts.signatureAgentUrl.startsWith(\"https://\")) {\n\t\t\tthrow new Error(\n\t\t\t\t`signatureAgentUrl must be https://, got: ${opts.signatureAgentUrl}`,\n\t\t\t);\n\t\t}\n\t\tthis._active = active;\n\t\tthis._retiring = retiring;\n\t\tthis.signatureAgentUrl = opts.signatureAgentUrl;\n\t\tthis.userAgent = opts.userAgent;\n\t}\n\n\t// ---------- Public read-only API ----------\n\n\t/** The active key's kid (used as `keyid=` param in Signature-Input). */\n\tget kid(): string {\n\t\treturn this._active.kid;\n\t}\n\n\t/** Module-internal: returns the resolved Signer for sign() to use. */\n\t_signer(): Signer {\n\t\treturn this._active.signer;\n\t}\n\n\t/**\n\t * Export the public JWKS document.\n\t *\n\t * Returns `{keys: [active_jwk]}` if no retiring key is held, or\n\t * `{keys: [active_jwk, retiring_jwk]}` after a rotation. Active is always\n\t * first. Verifiers select by `kid`. Mirror of Python `export_jwks`.\n\t */\n\texportJwks(): { keys: Array<JsonWebKey & { kid: string }> } {\n\t\tconst keys: Array<JsonWebKey & { kid: string }> = [this._active.publicJwk];\n\t\tif (this._retiring) keys.push(this._retiring.publicJwk);\n\t\treturn { keys };\n\t}\n\n\t/**\n\t * IDENT-07: generate a new active key, demote current to retiring.\n\t *\n\t * Returns a NEW Identity (immutable update — the old Identity is unchanged).\n\t * Any previously-retiring key is dropped (only one overlap window).\n\t */\n\tasync rotate(newPath: string = DEFAULT_KEY_PATH): Promise<Identity> {\n\t\tconst newPair = await generateKeypairTo(expandUser(newPath));\n\t\treturn new Identity(\n\t\t\tnewPair,\n\t\t\t{ signatureAgentUrl: this.signatureAgentUrl, userAgent: this.userAgent },\n\t\t\tthis._active,\n\t\t);\n\t}\n\n\t// ---------- Constructors ----------\n\n\t/**\n\t * Primary entry point. Loads `path` if it exists, generates a fresh key\n\t * there otherwise. The on-disk file is PKCS8 NoEncryption PEM at 0o600,\n\t * byte-equal to what Python's `Identity.load_or_generate` writes (D-60).\n\t */\n\tstatic async loadOrGenerate(\n\t\tpath: string = DEFAULT_KEY_PATH,\n\t\topts: IdentityOptions,\n\t): Promise<Identity> {\n\t\tconst resolved = expandUser(path);\n\t\tconst pair = existsSync(resolved)\n\t\t\t? await loadKeypair(resolved)\n\t\t\t: await generateKeypairTo(resolved);\n\t\treturn new Identity(pair, opts);\n\t}\n\n\t/**\n\t * Construct from the RFC 9421 Appendix B.1.4 publicly-known test key.\n\t * For tests + Cloudflare debug smoke checks. NEVER use in production.\n\t * Does NOT write any file to disk.\n\t */\n\tstatic async fromTestKey(\n\t\tsignatureAgentUrl: string,\n\t\topts: Omit<IdentityOptions, \"signatureAgentUrl\"> = {},\n\t): Promise<Identity> {\n\t\tconst pair = await keyPairFromJwk(TEST_KEY_JWK);\n\t\treturn new Identity(pair, { ...opts, signatureAgentUrl });\n\t}\n\n\t// ---------- Redaction guarantees (IDENT-08) ----------\n\n\ttoString(): string {\n\t\treturn `<Identity REDACTED kid='${this.kid}' sig_agent='${this.signatureAgentUrl}'>`;\n\t}\n\n\t/** util.inspect / console.log render the same REDACTED form (IDENT-08). */\n\t[Symbol.for(\"nodejs.util.inspect.custom\")](): string {\n\t\treturn this.toString();\n\t}\n}\n\n// ---------- Helpers (module-private) ----------\n\nfunction expandUser(path: string): string {\n\treturn resolve(path.startsWith(\"~\") ? path.replace(/^~/, homedir()) : path);\n}\n\nasync function keyPairFromJwk(privateJwk: JsonWebKey): Promise<KeyPair> {\n\tconst signer = await signerFromJWK(privateJwk);\n\t// signerFromJWK pre-computes the kid (RFC 7638 thumbprint) into signer.keyid.\n\t// Reuse it instead of calling jwkToKeyID separately (avoids the 3-arg helper).\n\tconst kid = signer.keyid;\n\tconst publicJwk: JsonWebKey & { kid: string } = {\n\t\tkty: privateJwk.kty,\n\t\tcrv: privateJwk.crv,\n\t\tx: privateJwk.x,\n\t\tkid,\n\t};\n\treturn { privateJwk, publicJwk, kid, signer };\n}\n\nasync function loadKeypair(path: string): Promise<KeyPair> {\n\t// POSIX permission check (mirror Python — refuse wider-than-0o600).\n\t// Pitfall 8: Windows lacks POSIX mode bits → emit warning, do not enforce.\n\tif (process.platform !== \"win32\") {\n\t\tconst mode = statSync(path).mode & 0o777;\n\t\tif ((mode & 0o077) !== 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Key file ${path} has mode 0o${mode.toString(8)}; expected 0o600. Fix: chmod 600 ${path}`,\n\t\t\t);\n\t\t}\n\t} else {\n\t\tprocess.emitWarning(\n\t\t\t`Windows detected — file permissions on ${path} cannot be enforced via POSIX mode. Use NTFS ACLs or store the key in a per-user secrets vault.`,\n\t\t);\n\t}\n\tconst pem = readFileSync(path, \"utf8\");\n\tconst jwk = createPrivateKey(pem).export({ format: \"jwk\" }) as JsonWebKey;\n\tif (jwk.kty !== \"OKP\" || jwk.crv !== \"Ed25519\") {\n\t\tthrow new TypeError(`Expected Ed25519, got kty=${jwk.kty}, crv=${jwk.crv}`);\n\t}\n\treturn keyPairFromJwk(jwk);\n}\n\nasync function generateKeypairTo(path: string): Promise<KeyPair> {\n\tconst dir = dirname(path);\n\tmkdirSync(dir, { recursive: true });\n\tif (existsSync(path)) {\n\t\t// Belt + suspenders: O_EXCL would catch this too, but raising here gives\n\t\t// a cleaner error than the low-level EEXIST.\n\t\tthrow new Error(`Key already exists at ${path}; refuse overwrite`);\n\t}\n\tconst { privateKey } = generateKeyPairSync(\"ed25519\");\n\tconst pem = privateKey.export({ format: \"pem\", type: \"pkcs8\" }) as string;\n\t// Race-free 0o600 creation: openSync with \"wx\" = O_WRONLY|O_CREAT|O_EXCL.\n\t// Mirrors Python `os.open(path, O_WRONLY|O_CREAT|O_EXCL, 0o600)`.\n\tconst fd = openSync(path, \"wx\", 0o600);\n\ttry {\n\t\twriteFileSync(fd, pem);\n\t} finally {\n\t\tcloseSync(fd);\n\t}\n\tconst jwk = privateKey.export({ format: \"jwk\" }) as JsonWebKey;\n\treturn keyPairFromJwk(jwk);\n}\n","/**\n * wbauth: Web Bot Auth (RFC 9421) TypeScript SDK — Phase 4 public surface.\n *\n * Per CONTEXT D-74: flat root exports. Subpath exports (`wb-auth/adapters`)\n * are a v1.x optimization, not required for Phase 4.\n *\n * Quickstart:\n * import { Identity, createSignedFetch } from \"wb-auth\";\n * const id = await Identity.loadOrGenerate(\"./key.pem\", {\n * signatureAgentUrl: \"https://example.com/.well-known/.../<kid>\",\n * });\n * const sf = createSignedFetch(id);\n * const res = await sf(\"https://api.example.com/data\");\n */\n\nexport type { SignedFetchOptions } from \"./adapters/fetch.js\";\nexport { createSignedFetch } from \"./adapters/fetch.js\";\nexport type { ApplyToOptions } from \"./adapters/playwright.js\";\nexport { applyTo } from \"./adapters/playwright.js\";\nexport type { IdentityOptions, KeyPair } from \"./identity.js\";\nexport { DEFAULT_KEY_PATH, Identity } from \"./identity.js\";\nexport type { NormalizedRequest } from \"./normalized-request.js\";\nexport type { SignatureHeaders, SignOptions } from \"./signer.js\";\nexport { sign } from \"./signer.js\";\n\nexport const VERSION = \"0.2.0\";\n"],"mappings":";AAYA,SAA+B,wBAAwB;AASvD,IAAM,gBAAgB;AAEtB,IAAM,0BAA0B;AAEhC,IAAM,iBAAiB,oBAAI,IAAI,CAAC,QAAQ,OAAO,OAAO,CAAC;AA0BvD,SAAS,cAAc,QAAgB,SAA4B;AAClE,QAAM,OAAO,CAAC,cAAc,iBAAiB;AAC7C,MAAI,WAAW,eAAe,IAAI,OAAO,YAAY,CAAC,GAAG;AACxD,SAAK,KAAK,gBAAgB;AAAA,EAC3B;AACA,SAAO;AACR;AAGA,IAAM,iBAAiB,CAAC,aAAa,mBAAmB,iBAAiB;AAEzE,SAAS,UAAU,SAAiC,MAAuB;AAC1E,QAAM,IAAI,KAAK,YAAY;AAC3B,SAAO,OAAO,KAAK,OAAO,EAAE,KAAK,CAAC,MAAM,EAAE,YAAY,MAAM,CAAC;AAC9D;AAEA,SAAS,cAAc,SAAiC,OAAuB;AAC9E,aAAW,KAAK,OAAO,KAAK,OAAO,GAAG;AACrC,QAAI,MAAM,SAAS,EAAE,YAAY,CAAC,EAAG,QAAO,QAAQ,CAAC;AAAA,EACtD;AACD;AAgBA,eAAsB,KACrB,SAC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AO,EAAE,QAAQ,MAAM,CAAC;AAC1D,MAAI,IAAI,QAAQ,SAAS,IAAI,QAAQ,WAAW;AAC/C,UAAM,IAAI,UAAU,6BAA6B,IAAI,GAAG,SAAS,IAAI,GAAG,EAAE;AAAA,EAC3E;AACA,SAAO,eAAe,GAAG;AAC1B;AAEA,eAAe,kBAAkB,MAAgC;AAChE,QAAM,MAAM,QAAQ,IAAI;AACxB,YAAU,KAAK,EAAE,WAAW,KAAK,CAAC;AAClC,MAAI,WAAW,IAAI,GAAG;AAGrB,UAAM,IAAI,MAAM,yBAAyB,IAAI,oBAAoB;AAAA,EAClE;AACA,QAAM,EAAE,WAAW,IAAI,oBAAoB,SAAS;AACpD,QAAM,MAAM,WAAW,OAAO,EAAE,QAAQ,OAAO,MAAM,QAAQ,CAAC;AAG9D,QAAM,KAAK,SAAS,MAAM,MAAM,GAAK;AACrC,MAAI;AACH,kBAAc,IAAI,GAAG;AAAA,EACtB,UAAE;AACD,cAAU,EAAE;AAAA,EACb;AACA,QAAM,MAAM,WAAW,OAAO,EAAE,QAAQ,MAAM,CAAC;AAC/C,SAAO,eAAe,GAAG;AAC1B;;;AC/NO,IAAM,UAAU;","names":["DIGEST_METHODS"]}
|
|
1
|
+
{"version":3,"sources":["../src/signer.ts","../src/identity.ts","../src/adapters/_utils.ts","../src/adapters/fetch.ts","../src/adapters/playwright.ts","../src/verifier.ts","../src/index.ts"],"sourcesContent":["/**\n * Pure-function signer for Web Bot Auth (RFC 9421).\n *\n * Mirrors python/src/wbauth/signer.py byte-for-byte — same defaults\n * (Ed25519, tag=\"web-bot-auth\", expires=created+60s, covered components\n * [\"@authority\", \"signature-agent\"] + \"content-digest\" for bodies, 64-byte\n * base64 nonce).\n *\n * The profile is fixed, so the RFC 9421 signature base is built directly\n * (no WHATWG `Request` construction, no body copy, no generic\n * structured-field serializer). Cross-language vectors in spec/test-vectors\n * pin the exact bytes.\n */\nimport { randomBytes } from \"node:crypto\";\nimport type { Identity } from \"./identity.js\";\nimport { validateSignatureAgentUrl } from \"./identity.js\";\nimport type { NormalizedRequest } from \"./normalized-request.js\";\n\n// ---------- Module constants (HARD-CODED — typos = silent verifier reject) ----------\n\n/** IETF Web Bot Auth profile mandate. NEVER change. */\nexport const WEB_BOT_AUTH_TAG = \"web-bot-auth\";\n/** Canonical Signature label. */\nconst DEFAULT_LABEL = \"sig1\";\n/** Default expires window. 60s leaves NTP-skew + network-latency headroom. */\nconst DEFAULT_EXPIRES_SECONDS = 60;\n/** Hard upper bound on the validity window (parity with Python). */\nexport const MAX_EXPIRES_SECONDS = 3600;\n/** Random bytes in the default nonce (base64) — web-bot-auth's NONCE_LENGTH_IN_BYTES. */\nexport const NONCE_BYTES = 64;\n\nconst SF_KEY_RE = /^[a-z*][a-z0-9_\\-.*]*$/;\nconst DEFAULT_PORTS: Record<string, string> = {\n\t\"https:\": \"443\",\n\t\"http:\": \"80\",\n};\n\n// ---------- Public types ----------\n\nexport interface SignatureHeaders {\n\tsignature: string;\n\tsignatureInput: string;\n\tsignatureAgent: string;\n}\n\nexport interface SignOptions {\n\t/** Signing timestamp. Defaults to `new Date()`. Override for vector reproducibility. */\n\tcreated?: Date;\n\t/** Validity window in seconds. Defaults to 60. */\n\texpiresAfterSeconds?: number;\n\t/** Anti-replay nonce. Defaults to 64 random bytes, base64. */\n\tnonce?: string;\n\t/** Signature label (the `sig1=` prefix). Defaults to \"sig1\". */\n\tlabel?: string;\n}\n\n// ---------- Helpers ----------\n\n/** RFC 8941 sf-string (printable ASCII only). */\nexport function sfString(value: string): string {\n\tfor (const ch of value) {\n\t\tconst c = ch.charCodeAt(0);\n\t\tif (c < 0x20 || c > 0x7e) {\n\t\t\tthrow new Error(\n\t\t\t\t`value is not a valid structured-field string: ${JSON.stringify(value)}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn `\"${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n}\n\n/** RFC 9421 §2.2.3 `@authority`: lower-case host, no userinfo, no default port. */\nexport function normalizeAuthority(url: string): string {\n\tconst u = new URL(url);\n\tif (!u.hostname) throw new Error(`URL has no host: ${url}`);\n\tconst host = u.hostname.toLowerCase();\n\tconst port =\n\t\tu.port && u.port !== DEFAULT_PORTS[u.protocol] ? `:${u.port}` : \"\";\n\treturn `${host}${port}`;\n}\n\nfunction componentsFor(hasBody: boolean): string[] {\n\treturn hasBody\n\t\t? [\"@authority\", \"signature-agent\", \"content-digest\"]\n\t\t: [\"@authority\", \"signature-agent\"];\n}\n\n/** Headers regenerated on every sign() call. */\nconst RESIGN_HEADERS = [\"signature\", \"signature-input\", \"signature-agent\"];\n\nfunction getHeader(\n\theaders: Record<string, string>,\n\tname: string,\n): string | undefined {\n\tconst n = name.toLowerCase();\n\tconst k = Object.keys(headers).find((key) => key.toLowerCase() === n);\n\treturn k === undefined ? undefined : headers[k];\n}\n\nfunction removeHeaders(headers: Record<string, string>, names: string[]): void {\n\tfor (const k of Object.keys(headers)) {\n\t\tif (names.includes(k.toLowerCase())) delete headers[k];\n\t}\n}\n\n// ---------- Public API ----------\n\n/**\n * Sign a NormalizedRequest with the Web Bot Auth profile.\n *\n * Mutates `request.headers` in place (Signature-Agent, Signature-Input,\n * Signature) and returns the same three values.\n */\nexport async function sign(\n\trequest: NormalizedRequest,\n\tidentity: Identity,\n\topts: SignOptions = {},\n): Promise<SignatureHeaders> {\n\tvalidateSignatureAgentUrl(identity.signatureAgentUrl);\n\n\tconst expiresAfterSeconds =\n\t\topts.expiresAfterSeconds ?? DEFAULT_EXPIRES_SECONDS;\n\tif (\n\t\ttypeof expiresAfterSeconds !== \"number\" ||\n\t\t!Number.isFinite(expiresAfterSeconds) ||\n\t\texpiresAfterSeconds <= 0 ||\n\t\texpiresAfterSeconds > MAX_EXPIRES_SECONDS\n\t) {\n\t\tthrow new RangeError(\n\t\t\t`expiresAfterSeconds must be a number in (0, ${MAX_EXPIRES_SECONDS}], got: ${expiresAfterSeconds}`,\n\t\t);\n\t}\n\tconst label = opts.label ?? DEFAULT_LABEL;\n\tif (!SF_KEY_RE.test(label)) {\n\t\tthrow new Error(\n\t\t\t`label must be an RFC 8941 key, got: ${JSON.stringify(label)}`,\n\t\t);\n\t}\n\n\t// Drop stale signature headers in ANY casing (retries / redirects).\n\tremoveHeaders(request.headers, RESIGN_HEADERS);\n\tconst signatureAgentHeader = sfString(identity.signatureAgentUrl);\n\trequest.headers[\"Signature-Agent\"] = signatureAgentHeader;\n\n\tconst created = Math.floor((opts.created ?? new Date()).getTime() / 1000);\n\tconst expires = created + Math.floor(expiresAfterSeconds);\n\tconst nonce = opts.nonce ?? randomBytes(NONCE_BYTES).toString(\"base64\");\n\n\tconst hasBody = request.body != null && request.body.byteLength > 0;\n\tconst components = componentsFor(hasBody);\n\tconst values: Record<string, string> = {\n\t\t\"@authority\": normalizeAuthority(request.url),\n\t\t\"signature-agent\": signatureAgentHeader,\n\t};\n\tif (hasBody) {\n\t\tconst cd = getHeader(request.headers, \"content-digest\");\n\t\tif (cd === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t'Covered header field \"content-digest\" not found in the message. ' +\n\t\t\t\t\t\"Call ensureContentDigest() or use createSignedFetch()/applyTo(), which add it automatically.\",\n\t\t\t);\n\t\t}\n\t\tvalues[\"content-digest\"] = cd.trim();\n\t}\n\n\tconst signer = identity._signer();\n\tconst params =\n\t\t`(${components.map((c) => `\"${c}\"`).join(\" \")})` +\n\t\t`;created=${created}` +\n\t\t`;keyid=${sfString(signer.keyid)}` +\n\t\t`;alg=\"ed25519\"` +\n\t\t`;expires=${expires}` +\n\t\t`;nonce=${sfString(nonce)}` +\n\t\t`;tag=${sfString(WEB_BOT_AUTH_TAG)}`;\n\tconst base = `${components.map((c) => `\"${c}\": ${values[c]}`).join(\"\\n\")}\\n\"@signature-params\": ${params}`;\n\tconst raw = await signer.sign(base);\n\n\tconst signatureInput = `${label}=${params}`;\n\tconst signature = `${label}=:${Buffer.from(raw).toString(\"base64\")}:`;\n\trequest.headers[\"Signature-Input\"] = signatureInput;\n\trequest.headers.Signature = signature;\n\treturn { signature, signatureInput, signatureAgent: signatureAgentHeader };\n}\n","/**\n * Identity, KeyPair, and key-file helpers for the wbauth TypeScript SDK.\n *\n * Mirrors python/src/wbauth/identity.py — same on-disk format (PKCS8 PEM at\n * 0o600, optionally passphrase-encrypted), same kid (RFC 7638 JWK\n * thumbprint), same multi-key rotation semantics (active + retiring, in\n * memory via `rotate()` or persisted via `rotateKeyring()`), same REDACTED\n * repr (IDENT-08).\n *\n * Key material is held in ECMAScript `#private` fields and only as a\n * non-extractable `KeyObject`/`Signer`, so `JSON.stringify(identity)`,\n * `structuredClone`, spreading or `Object.entries` never expose `d`.\n */\n\nimport {\n\tcreateHash,\n\tcreatePrivateKey,\n\tcreatePublicKey,\n\tsign as cryptoSign,\n\tgenerateKeyPairSync,\n\ttype KeyObject,\n} from \"node:crypto\";\nimport { mkdir, open, readFile, rename, stat } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\n\n// ---------- Module constants ----------\n\n/** Default path for the active signing key. Matches Python DEFAULT_KEY_PATH. */\nexport const DEFAULT_KEY_PATH = resolve(\n\thomedir(),\n\t\".config\",\n\t\"wbauth\",\n\t\"key.pem\",\n);\n\n/** Environment variable holding the passphrase for encrypted PEM key files. */\nexport const KEY_PASSWORD_ENV = \"WBAUTH_KEY_PASSWORD\";\nexport const KEYRING_ACTIVE = \"active.pem\";\nexport const KEYRING_RETIRING = \"retiring.pem\";\n\n/**\n * RFC 9421 Appendix B.1.4 publicly-known test key — NEVER use in production.\n */\nconst TEST_KEY_JWK: import(\"node:crypto\").JsonWebKey = {\n\tkty: \"OKP\",\n\tcrv: \"Ed25519\",\n\td: \"n4Ni-HpISpVObnQMW0wOhCKROaIKqKtW_2ZYb2p9KcU\",\n\tx: \"JrQLj5P_89iXES9-vFgrIy29clF9CC_oPPsw3c5D0bs\",\n};\n\nlet warnedWindows = false;\n\n// ---------- Public types ----------\n\nexport interface IdentityOptions {\n\t/** Stable HTTPS URL where this agent's JWKS is published. Must start with `https://`. */\n\tsignatureAgentUrl: string;\n\t/** Optional User-Agent string adapters inject when caller did not supply one. */\n\tuserAgent?: string;\n}\n\nexport interface KeyOptions {\n\t/** Passphrase for an encrypted PEM. Defaults to `$WBAUTH_KEY_PASSWORD`. */\n\tpassword?: string;\n}\n\n/** Public JWK of one key ({kty, crv, x, kid}). */\nexport type PublicJwk = JsonWebKey & { kid: string };\n\n/**\n * Pluggable Ed25519 signing backend (local key, KMS, HSM, keychain).\n * `sign` receives the RFC 9421 signature base as UTF-8 bytes and must return\n * the raw 64-byte Ed25519 signature.\n */\nexport interface Ed25519SignerBackend {\n\t/** Public key as a JWK ({kty:\"OKP\", crv:\"Ed25519\", x}). */\n\tpublicJwk: JsonWebKey;\n\tsign(data: Uint8Array): Uint8Array | Promise<Uint8Array>;\n}\n\n/** Signer handed to `sign()` (structurally compatible with web-bot-auth's). */\nexport interface Signer {\n\talg: \"ed25519\";\n\tkeyid: string;\n\tsign(data: string): Promise<Uint8Array>;\n}\n\n/** Public view of a key pair. Private material is never exposed. */\nexport interface KeyPair {\n\tpublicJwk: PublicJwk;\n\tkid: string;\n\tsigner: Signer;\n}\n\n// ---------- Validation ----------\n\n/**\n * Validate a Signature-Agent URL: absolute https:// with a host, printable\n * ASCII only, no spaces/quotes/backslashes (it is emitted as an RFC 8941\n * sf-string and must not break the header or the signature base).\n */\nexport function validateSignatureAgentUrl(url: string): string {\n\tif (typeof url !== \"string\" || !url.startsWith(\"https://\")) {\n\t\tthrow new Error(`signatureAgentUrl must be https://, got: ${String(url)}`);\n\t}\n\tfor (const ch of url) {\n\t\tconst c = ch.charCodeAt(0);\n\t\tif (c < 0x21 || c > 0x7e || ch === '\"' || ch === \"\\\\\") {\n\t\t\tthrow new Error(\n\t\t\t\t`signatureAgentUrl must be printable ASCII without spaces, quotes or backslashes, got: ${JSON.stringify(url)}`,\n\t\t\t);\n\t\t}\n\t}\n\tlet host = \"\";\n\ttry {\n\t\thost = new URL(url).hostname;\n\t} catch {\n\t\t/* handled below */\n\t}\n\tif (!host) throw new Error(`signatureAgentUrl has no host: ${url}`);\n\treturn url;\n}\n\nfunction validateUserAgent(ua: string | undefined): string | undefined {\n\tif (\n\t\tua !== undefined &&\n\t\t[...ua].some((c) => c.charCodeAt(0) < 0x20 || c.charCodeAt(0) === 0x7f)\n\t) {\n\t\tthrow new Error(\n\t\t\t`userAgent must not contain control characters: ${JSON.stringify(ua)}`,\n\t\t);\n\t}\n\treturn ua;\n}\n\n// ---------- Identity class ----------\n\nexport class Identity {\n\t#active: KeyPair;\n\t#retiring: KeyPair | null;\n\treadonly #signatureAgentUrl: string;\n\treadonly #userAgent: string | undefined;\n\n\tprivate constructor(\n\t\tactive: KeyPair,\n\t\topts: IdentityOptions,\n\t\tretiring: KeyPair | null = null,\n\t) {\n\t\tthis.#signatureAgentUrl = validateSignatureAgentUrl(opts.signatureAgentUrl);\n\t\tthis.#userAgent = validateUserAgent(opts.userAgent);\n\t\tthis.#active = active;\n\t\tthis.#retiring = retiring;\n\t}\n\n\t// ---------- Public read-only API ----------\n\n\tget signatureAgentUrl(): string {\n\t\treturn this.#signatureAgentUrl;\n\t}\n\n\tget userAgent(): string | undefined {\n\t\treturn this.#userAgent;\n\t}\n\n\t/** The active key's kid (used as `keyid=` param in Signature-Input). */\n\tget kid(): string {\n\t\treturn this.#active.kid;\n\t}\n\n\t/** The active key's public JWK (copy; never contains private material). */\n\tget publicJwk(): PublicJwk {\n\t\treturn { ...this.#active.publicJwk };\n\t}\n\n\t/** Module-internal: returns the active Signer for sign() to use. */\n\t_signer(): Signer {\n\t\treturn this.#active.signer;\n\t}\n\n\t/** Public JWKS: active first, then the retiring key (if any). */\n\texportJwks(): { keys: PublicJwk[] } {\n\t\tconst keys: PublicJwk[] = [{ ...this.#active.publicJwk }];\n\t\tif (this.#retiring) keys.push({ ...this.#retiring.publicJwk });\n\t\treturn { keys };\n\t}\n\n\t/**\n\t * IDENT-07: generate a new active key, demote current to retiring.\n\t * In-memory only — use `rotateKeyring()` to persist. The default path is\n\t * a fresh timestamped file next to DEFAULT_KEY_PATH (never collides).\n\t */\n\tasync rotate(newPath?: string, keyOpts: KeyOptions = {}): Promise<Identity> {\n\t\tconst path = newPath\n\t\t\t? expandUser(newPath)\n\t\t\t: join(\n\t\t\t\t\tdirname(DEFAULT_KEY_PATH),\n\t\t\t\t\t`key-${Math.floor(Date.now() / 1000)}.pem`,\n\t\t\t\t);\n\t\tconst newPair = await generateKeypairTo(path, keyOpts);\n\t\treturn new Identity(newPair, this.#opts(), this.#active);\n\t}\n\n\t/**\n\t * Persisted rotation: `<dir>/active.pem` → `retiring.pem` (replacing the\n\t * previous retiring key), then a fresh `active.pem` is generated.\n\t */\n\tasync rotateKeyring(\n\t\tdir: string,\n\t\tkeyOpts: KeyOptions = {},\n\t): Promise<Identity> {\n\t\tconst d = expandUser(dir);\n\t\tconst active = join(d, KEYRING_ACTIVE);\n\t\tconst retiring = join(d, KEYRING_RETIRING);\n\t\tawait stat(active);\n\t\tawait rename(active, retiring);\n\t\tlet pair: KeyPair;\n\t\ttry {\n\t\t\tpair = await generateKeypairTo(active, keyOpts);\n\t\t} catch (e) {\n\t\t\tawait rename(retiring, active);\n\t\t\tthrow e;\n\t\t}\n\t\treturn new Identity(\n\t\t\tpair,\n\t\t\tthis.#opts(),\n\t\t\tawait loadKeypair(retiring, keyOpts),\n\t\t);\n\t}\n\n\t#opts(): IdentityOptions {\n\t\treturn {\n\t\t\tsignatureAgentUrl: this.#signatureAgentUrl,\n\t\t\tuserAgent: this.#userAgent,\n\t\t};\n\t}\n\n\t// ---------- Constructors ----------\n\n\t/**\n\t * Loads `path` if it exists, generates a fresh key there otherwise.\n\t * Concurrent first starts are safe: the loser of the O_EXCL race loads the\n\t * winner's key. `retiringPath` optionally loads the previous key.\n\t */\n\tstatic async loadOrGenerate(\n\t\tpath: string = DEFAULT_KEY_PATH,\n\t\topts: IdentityOptions & KeyOptions & { retiringPath?: string },\n\t): Promise<Identity> {\n\t\tvalidateSignatureAgentUrl(opts.signatureAgentUrl);\n\t\tconst resolved = expandUser(path);\n\t\tlet pair: KeyPair | null = null;\n\t\tif (!(await exists(resolved))) {\n\t\t\ttry {\n\t\t\t\tpair = await generateKeypairTo(resolved, opts);\n\t\t\t} catch (e) {\n\t\t\t\tif (\n\t\t\t\t\t(e as NodeJS.ErrnoException).code !== \"EEXIST\" &&\n\t\t\t\t\t!(await exists(resolved))\n\t\t\t\t)\n\t\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\tpair ??= await loadKeypair(resolved, opts);\n\t\tlet retiring: KeyPair | null = null;\n\t\tif (opts.retiringPath && (await exists(expandUser(opts.retiringPath)))) {\n\t\t\tretiring = await loadKeypair(expandUser(opts.retiringPath), opts);\n\t\t}\n\t\treturn new Identity(pair, opts, retiring);\n\t}\n\n\t/** Load an existing key; never creates one. */\n\tstatic async load(\n\t\tpath: string,\n\t\topts: IdentityOptions & KeyOptions,\n\t): Promise<Identity> {\n\t\treturn new Identity(await loadKeypair(expandUser(path), opts), opts);\n\t}\n\n\t/** Generate a new key at `path`; never overwrites. */\n\tstatic async generate(\n\t\tpath: string,\n\t\topts: IdentityOptions & KeyOptions,\n\t): Promise<Identity> {\n\t\tvalidateSignatureAgentUrl(opts.signatureAgentUrl);\n\t\treturn new Identity(await generateKeypairTo(expandUser(path), opts), opts);\n\t}\n\n\t/** `<dir>/active.pem` (+ `retiring.pem`), generating active on first use. */\n\tstatic async loadKeyring(\n\t\tdir: string,\n\t\topts: IdentityOptions & KeyOptions,\n\t): Promise<Identity> {\n\t\tconst d = expandUser(dir);\n\t\treturn Identity.loadOrGenerate(join(d, KEYRING_ACTIVE), {\n\t\t\t...opts,\n\t\t\tretiringPath: join(d, KEYRING_RETIRING),\n\t\t});\n\t}\n\n\t/** Wrap an external signer (KMS, HSM, keychain). */\n\tstatic async fromSigner(\n\t\tbackend: Ed25519SignerBackend,\n\t\topts: IdentityOptions,\n\t): Promise<Identity> {\n\t\tconst jwk = backend.publicJwk;\n\t\tif (jwk.kty !== \"OKP\" || jwk.crv !== \"Ed25519\" || !jwk.x) {\n\t\t\tthrow new TypeError(\"fromSigner: publicJwk must be an Ed25519 OKP JWK\");\n\t\t}\n\t\tconst kid = thumbprint(jwk);\n\t\tconst enc = new TextEncoder();\n\t\treturn new Identity(\n\t\t\t{\n\t\t\t\tkid,\n\t\t\t\tpublicJwk: { kty: \"OKP\", crv: \"Ed25519\", x: jwk.x, kid },\n\t\t\t\tsigner: {\n\t\t\t\t\talg: \"ed25519\",\n\t\t\t\t\tkeyid: kid,\n\t\t\t\t\tsign: async (data: string) => backend.sign(enc.encode(data)),\n\t\t\t\t},\n\t\t\t},\n\t\t\topts,\n\t\t);\n\t}\n\n\t/** RFC 9421 Appendix B.1.4 test key. NEVER use in production. */\n\tstatic async fromTestKey(\n\t\tsignatureAgentUrl: string,\n\t\topts: Omit<IdentityOptions, \"signatureAgentUrl\"> = {},\n\t): Promise<Identity> {\n\t\tconst key = createPrivateKey({ key: TEST_KEY_JWK, format: \"jwk\" });\n\t\treturn new Identity(keyPairFromKeyObject(key), {\n\t\t\t...opts,\n\t\t\tsignatureAgentUrl,\n\t\t});\n\t}\n\n\t// ---------- Redaction guarantees (IDENT-08) ----------\n\n\ttoString(): string {\n\t\treturn `<Identity REDACTED kid='${this.kid}' sig_agent='${this.#signatureAgentUrl}'>`;\n\t}\n\n\t/** JSON.stringify(identity) → public data only. */\n\ttoJSON(): {\n\t\tkid: string;\n\t\tsignatureAgentUrl: string;\n\t\tuserAgent?: string;\n\t\tjwks: { keys: PublicJwk[] };\n\t} {\n\t\treturn {\n\t\t\tkid: this.kid,\n\t\t\tsignatureAgentUrl: this.#signatureAgentUrl,\n\t\t\t...(this.#userAgent !== undefined ? { userAgent: this.#userAgent } : {}),\n\t\t\tjwks: this.exportJwks(),\n\t\t};\n\t}\n\n\t/** util.inspect / console.log render the same REDACTED form (IDENT-08). */\n\t[Symbol.for(\"nodejs.util.inspect.custom\")](): string {\n\t\treturn this.toString();\n\t}\n}\n\n// ---------- Helpers (module-private) ----------\n\nfunction expandUser(path: string): string {\n\t// Only \"~\" and \"~/…\" mean the current user's home; \"~other\" is left alone.\n\tif (path === \"~\") return homedir();\n\tif (path.startsWith(\"~/\") || path.startsWith(\"~\\\\\")) {\n\t\treturn resolve(homedir(), path.slice(2));\n\t}\n\treturn resolve(path);\n}\n\nasync function exists(path: string): Promise<boolean> {\n\ttry {\n\t\tawait stat(path);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction b64url(buf: Buffer): string {\n\treturn buf\n\t\t.toString(\"base64\")\n\t\t.replace(/\\+/g, \"-\")\n\t\t.replace(/\\//g, \"_\")\n\t\t.replace(/=+$/, \"\");\n}\n\n/** RFC 7638 thumbprint of an Ed25519 OKP JWK. */\nexport function thumbprint(jwk: JsonWebKey): string {\n\tconst canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x });\n\treturn b64url(createHash(\"sha256\").update(canonical).digest());\n}\n\nfunction keyPairFromKeyObject(privateKey: KeyObject): KeyPair {\n\tconst pub = createPublicKey(privateKey).export({\n\t\tformat: \"jwk\",\n\t}) as JsonWebKey;\n\tif (pub.kty !== \"OKP\" || pub.crv !== \"Ed25519\") {\n\t\tthrow new TypeError(`Expected Ed25519, got kty=${pub.kty}, crv=${pub.crv}`);\n\t}\n\tconst kid = thumbprint(pub);\n\treturn {\n\t\tkid,\n\t\tpublicJwk: { kty: \"OKP\", crv: \"Ed25519\", x: pub.x as string, kid },\n\t\tsigner: {\n\t\t\talg: \"ed25519\",\n\t\t\tkeyid: kid,\n\t\t\t// Sync node:crypto Ed25519 — no WebCrypto import / promise hop.\n\t\t\tsign: async (data: string) =>\n\t\t\t\tnew Uint8Array(cryptoSign(null, Buffer.from(data, \"utf8\"), privateKey)),\n\t\t},\n\t};\n}\n\nfunction passwordFor(opts: KeyOptions): string | undefined {\n\treturn opts.password ?? (process.env[KEY_PASSWORD_ENV] || undefined);\n}\n\nasync function loadKeypair(\n\tpath: string,\n\topts: KeyOptions = {},\n): Promise<KeyPair> {\n\tif (process.platform !== \"win32\") {\n\t\tconst mode = (await stat(path)).mode & 0o777;\n\t\tif ((mode & 0o077) !== 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Key file ${path} has mode 0o${mode.toString(8)}; expected 0o600. Fix: chmod 600 ${path}`,\n\t\t\t);\n\t\t}\n\t} else if (!warnedWindows) {\n\t\twarnedWindows = true;\n\t\tprocess.emitWarning(\n\t\t\t`Windows detected — file permissions on ${path} cannot be enforced via POSIX mode. Use NTFS ACLs or store the key in a per-user secrets vault.`,\n\t\t);\n\t}\n\tconst pem = await readFile(path, \"utf8\");\n\tconst encrypted = pem.includes(\"ENCRYPTED\");\n\tconst passphrase = passwordFor(opts);\n\tif (encrypted && !passphrase) {\n\t\tthrow new TypeError(\n\t\t\t`Key file ${path} is encrypted; pass { password } or set $${KEY_PASSWORD_ENV}`,\n\t\t);\n\t}\n\tconst key = createPrivateKey(\n\t\tencrypted ? { key: pem, format: \"pem\", passphrase } : pem,\n\t);\n\treturn keyPairFromKeyObject(key);\n}\n\nasync function generateKeypairTo(\n\tpath: string,\n\topts: KeyOptions = {},\n): Promise<KeyPair> {\n\tawait mkdir(dirname(path), { recursive: true });\n\tif (await exists(path)) {\n\t\tconst err = new Error(\n\t\t\t`Key already exists at ${path}; refuse overwrite`,\n\t\t) as NodeJS.ErrnoException;\n\t\terr.code = \"EEXIST\";\n\t\tthrow err;\n\t}\n\tconst { privateKey } = generateKeyPairSync(\"ed25519\");\n\tconst passphrase = passwordFor(opts);\n\tconst pem = privateKey.export(\n\t\tpassphrase\n\t\t\t? { format: \"pem\", type: \"pkcs8\", cipher: \"aes-256-cbc\", passphrase }\n\t\t\t: { format: \"pem\", type: \"pkcs8\" },\n\t) as string;\n\t// Race-free 0o600 creation: \"wx\" = O_WRONLY|O_CREAT|O_EXCL.\n\tconst fh = await open(path, \"wx\", 0o600);\n\ttry {\n\t\tawait fh.writeFile(pem);\n\t\tawait fh.sync();\n\t} finally {\n\t\tawait fh.close();\n\t}\n\treturn keyPairFromKeyObject(privateKey);\n}\n","/**\n * Shared adapter helpers (internal — not part of the public surface).\n *\n * Mirror python/src/wbauth/adapters/_utils.py. The signer auto-includes\n * `content-digest` in covered components for any request with a body;\n * adapters call ensureContentDigest() before sign() so that precondition\n * is met. RFC 9530 sha-256 in structured-fields form (`sha-256=:<b64>:`).\n */\nimport { createHash } from \"node:crypto\";\n\n/** Default UAs injected by HTTP stacks; an Identity UA should replace them. */\nconst LIBRARY_DEFAULT_UA = /^(node|undici|node-fetch)(\\/|$)/i;\n\nfunction findHeader(\n\theaders: Record<string, string>,\n\tname: string,\n): string | undefined {\n\tconst n = name.toLowerCase();\n\treturn Object.keys(headers).find((k) => k.toLowerCase() === n);\n}\n\n/**\n * Mutate `headers` in place to add Content-Digest when warranted. No-op if:\n * - body is null/empty,\n * - the request already carries a Content-Digest header (case-insensitive).\n */\nexport function ensureContentDigest(\n\tmethod: string,\n\theaders: Record<string, string>,\n\tbody: Uint8Array | null,\n): void {\n\tif (!body || body.byteLength === 0) return;\n\tvoid method; // any method with a body is covered (DELETE, QUERY, …)\n\tconst b64 = createHash(\"sha256\").update(body).digest(\"base64\");\n\tconst key = findHeader(headers, \"content-digest\");\n\tif (key !== undefined) {\n\t\tconst m = /(?:^|,)\\s*sha-256=:([A-Za-z0-9+/=]+):/.exec(headers[key] ?? \"\");\n\t\t// Caller's own digest (other algorithm) or still correct → keep.\n\t\tif (m === null || m[1] === b64) return;\n\t\tdelete headers[key]; // stale digest (e.g. previous redirect hop)\n\t}\n\theaders[\"Content-Digest\"] = `sha-256=:${b64}:`;\n}\n\nconst SIGNATURE_HEADERS = new Set([\n\t\"signature\",\n\t\"signature-input\",\n\t\"signature-agent\",\n]);\n\n/** Remove Signature / Signature-Input / Signature-Agent in any casing. */\nexport function stripSignatureHeaders(headers: Record<string, string>): void {\n\tfor (const k of Object.keys(headers)) {\n\t\tif (SIGNATURE_HEADERS.has(k.toLowerCase())) delete headers[k];\n\t}\n}\n\nexport interface SignScopeOptions {\n\t/** Only sign requests to these hosts (`example.com`, `*.example.com`). */\n\thosts?: readonly string[];\n\t/** Custom predicate; takes precedence over `hosts`. */\n\tshouldSign?: (url: URL) => boolean;\n\t/** Also sign plain `http://` requests (off by default: replayable in clear text). */\n\tallowInsecure?: boolean;\n}\n\n/** The shared \"sign this URL?\" predicate used by every adapter. */\nexport function makeSignDecider(\n\topts: SignScopeOptions = {},\n): (raw: string) => boolean {\n\treturn (raw: string) => {\n\t\tlet u: URL;\n\t\ttry {\n\t\t\tu = new URL(raw);\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t\tif (u.protocol !== \"https:\" && u.protocol !== \"http:\") return false;\n\t\tif (!u.hostname) return false;\n\t\tif (u.protocol === \"http:\" && !opts.allowInsecure) return false;\n\t\tif (opts.shouldSign) return opts.shouldSign(u);\n\t\tif (opts.hosts) return hostMatches(u.hostname, opts.hosts);\n\t\treturn true;\n\t};\n}\n\n/**\n * Apply the Identity's User-Agent unless the caller explicitly set a\n * non-library UA. Library defaults (node, undici) are replaced.\n */\nexport function applyUserAgent(\n\theaders: Record<string, string>,\n\tuserAgent: string | undefined,\n): void {\n\tif (!userAgent) return;\n\tconst key = findHeader(headers, \"user-agent\");\n\tif (key === undefined) {\n\t\theaders[\"User-Agent\"] = userAgent;\n\t\treturn;\n\t}\n\tif (LIBRARY_DEFAULT_UA.test(headers[key] ?? \"\")) {\n\t\tdelete headers[key];\n\t\theaders[\"User-Agent\"] = userAgent;\n\t}\n}\n\n/**\n * Host allow-list matcher. Entries are exact hostnames (`api.example.com`)\n * or wildcard subdomains (`*.example.com`, which also matches `example.com`).\n */\nexport function hostMatches(\n\thostname: string,\n\tallow: readonly string[],\n): boolean {\n\tconst h = hostname.toLowerCase().replace(/\\.$/, \"\");\n\treturn allow.some((raw) => {\n\t\tconst a = raw.toLowerCase().replace(/\\.$/, \"\");\n\t\tif (a.startsWith(\"*.\")) {\n\t\t\tconst base = a.slice(2);\n\t\t\treturn h === base || h.endsWith(`.${base}`);\n\t\t}\n\t\treturn h === a;\n\t});\n}\n","/**\n * createSignedFetch — drop-in `fetch` wrapper that signs every outgoing request.\n *\n * Mirrors python/src/wbauth/adapters/httpx_auth.py. Stateless: closure over\n * `identity` only. Returns a function whose signature matches `typeof fetch`,\n * so user code can swap `fetch` for `signedFetch` without other changes.\n *\n * - Request-object inputs keep their `signal`, `redirect`, `credentials`,\n * `cache`, `keepalive`, `integrity` and `referrerPolicy`.\n * - Re-sending an already signed request (retry wrappers) produces exactly one\n * fresh signature — stale Signature* headers are replaced, never merged.\n * - **Redirects** (`redirect: \"follow\"`, the default) are followed here, not\n * by the underlying fetch, so each hop is re-signed for its own\n * `@authority`. Native fetch would otherwise replay hop 1's signature to the\n * redirect target. Method/body rewriting and cross-origin credential\n * stripping follow the WHATWG fetch spec.\n *\n * - `hosts` / `shouldSign` restrict which hosts receive your identity\n * (redirects to other hosts go out unsigned); plain-http requests are\n * unsigned unless `allowInsecure: true`.\n *\n * v1 limitation: streaming bodies are buffered (`req.clone().arrayBuffer()`)\n * so Content-Digest can be computed.\n */\n\nimport type { Identity } from \"../identity.js\";\nimport { sign } from \"../signer.js\";\nimport {\n\tapplyUserAgent,\n\tensureContentDigest,\n\tmakeSignDecider,\n\ttype SignScopeOptions,\n\tstripSignatureHeaders,\n} from \"./_utils.js\";\n\nexport interface SignedFetchOptions extends SignScopeOptions {\n\t/** Underlying fetch implementation. Defaults to `globalThis.fetch` at call time. */\n\tfetch?: typeof fetch;\n\t/** Maximum redirects followed (and re-signed). Default 20, like fetch. */\n\tmaxRedirects?: number;\n}\n\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n/** Request headers dropped when a redirect crosses origins (fetch spec §4.4). */\nconst CROSS_ORIGIN_STRIP = new Set([\n\t\"authorization\",\n\t\"cookie\",\n\t\"proxy-authorization\",\n]);\n/** Request-body headers dropped when a redirect turns the request into GET. */\nconst BODY_HEADERS = new Set([\n\t\"content-type\",\n\t\"content-length\",\n\t\"content-encoding\",\n\t\"content-language\",\n\t\"content-location\",\n\t\"content-digest\",\n]);\n\nfunction dropHeaders(headers: Record<string, string>, names: Set<string>) {\n\tfor (const k of Object.keys(headers)) {\n\t\tif (names.has(k.toLowerCase())) delete headers[k];\n\t}\n}\n\nexport function createSignedFetch(\n\tidentity: Identity,\n\toptions: SignedFetchOptions = {},\n): typeof fetch {\n\tconst decide = makeSignDecider(options);\n\treturn async function signedFetch(\n\t\tinput: RequestInfo | URL,\n\t\tinit: RequestInit = {},\n\t): Promise<Response> {\n\t\tconst req = new Request(input, init);\n\t\tlet method = req.method;\n\t\tlet url = req.url;\n\n\t\tlet body: Uint8Array | null = null;\n\t\tif (req.body) {\n\t\t\tconst buf = await req.clone().arrayBuffer();\n\t\t\tbody = buf.byteLength > 0 ? new Uint8Array(buf) : null;\n\t\t}\n\n\t\tconst baseHeaders: Record<string, string> = {};\n\t\treq.headers.forEach((value, key) => {\n\t\t\tbaseHeaders[key] = value;\n\t\t});\n\n\t\tconst redirectMode = init.redirect ?? req.redirect;\n\t\tconst followHere = redirectMode === \"follow\";\n\t\tconst maxRedirects = options.maxRedirects ?? 20;\n\t\tconst doFetch = options.fetch ?? globalThis.fetch;\n\n\t\tfor (let hop = 0; ; hop++) {\n\t\t\tconst headers: Record<string, string> = { ...baseHeaders };\n\t\t\tif (decide(url)) {\n\t\t\t\tensureContentDigest(method, headers, body);\n\t\t\t\tawait sign({ method, url, headers, body }, identity);\n\t\t\t} else {\n\t\t\t\t// Out of scope (other host / plain http): never forward a signature.\n\t\t\t\tstripSignatureHeaders(headers);\n\t\t\t}\n\t\t\tapplyUserAgent(headers, identity.userAgent);\n\n\t\t\tconst outInit: RequestInit = {\n\t\t\t\t...init,\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\tbody: (body ?? undefined) as BodyInit | undefined,\n\t\t\t\tsignal: init.signal ?? req.signal,\n\t\t\t\tredirect: followHere ? \"manual\" : redirectMode,\n\t\t\t\tcredentials: init.credentials ?? req.credentials,\n\t\t\t\tcache: init.cache ?? req.cache,\n\t\t\t\tkeepalive: init.keepalive ?? req.keepalive,\n\t\t\t};\n\t\t\tconst integrity = init.integrity ?? req.integrity;\n\t\t\tif (integrity) outInit.integrity = integrity;\n\t\t\tconst referrerPolicy = init.referrerPolicy ?? req.referrerPolicy;\n\t\t\tif (referrerPolicy) outInit.referrerPolicy = referrerPolicy;\n\n\t\t\tconst res = await doFetch(url, outInit);\n\t\t\tif (!followHere || !REDIRECT_STATUSES.has(res.status)) return res;\n\t\t\tconst location = res.headers.get(\"location\");\n\t\t\tif (location === null) return res;\n\t\t\tif (hop >= maxRedirects) {\n\t\t\t\tthrow new TypeError(`redirect count exceeded (${maxRedirects})`);\n\t\t\t}\n\t\t\tconst next = new URL(location, url);\n\t\t\tif (next.protocol !== \"http:\" && next.protocol !== \"https:\") {\n\t\t\t\tthrow new TypeError(`unsupported redirect scheme: ${next.protocol}`);\n\t\t\t}\n\t\t\tconst upper = method.toUpperCase();\n\t\t\tif (\n\t\t\t\t(res.status === 303 && upper !== \"GET\" && upper !== \"HEAD\") ||\n\t\t\t\t((res.status === 301 || res.status === 302) && upper === \"POST\")\n\t\t\t) {\n\t\t\t\tmethod = \"GET\";\n\t\t\t\tbody = null;\n\t\t\t\tdropHeaders(baseHeaders, BODY_HEADERS);\n\t\t\t}\n\t\t\tif (new URL(url).origin !== next.origin) {\n\t\t\t\tdropHeaders(baseHeaders, CROSS_ORIGIN_STRIP);\n\t\t\t}\n\t\t\tawait res.body?.cancel().catch(() => {});\n\t\t\turl = next.href;\n\t\t}\n\t};\n}\n","/**\n * applyTo — sign every matching request a Playwright page sends.\n *\n * Mirrors python/src/wbauth/adapters/playwright.py.\n *\n * Privacy: by default every http(s) request is signed, including third-party\n * analytics/CDN hosts, which reveals your agent identity to them. Pass\n * `hosts` to restrict signing to the sites you actually target:\n *\n * await applyTo(page, identity, { hosts: [\"example.com\", \"*.example.org\"] });\n *\n * Non-http(s) requests (data:, blob:, chrome-extension:) are never signed.\n * Note: Playwright disables the HTTP cache while a route is active.\n */\nimport type { Page, Request as PWRequest, Route } from \"playwright\";\nimport type { Identity } from \"../identity.js\";\nimport { sign } from \"../signer.js\";\nimport {\n\tapplyUserAgent,\n\tensureContentDigest,\n\tmakeSignDecider,\n\ttype SignScopeOptions,\n} from \"./_utils.js\";\n\nexport interface ApplyToOptions extends SignScopeOptions {\n\t/** Route pattern passed to `page.route`. Default `\"**\\/*\"`. */\n\tpattern?: string;\n}\n\nexport async function applyTo(\n\tpage: Page,\n\tidentity: Identity,\n\toptions: ApplyToOptions = {},\n): Promise<() => Promise<void>> {\n\tconst pattern = options.pattern ?? \"**/*\";\n\tconst decide = makeSignDecider(options);\n\n\tconst handler = async (route: Route, request: PWRequest) => {\n\t\tconst url = request.url();\n\t\tif (!decide(url)) {\n\t\t\tconst r = route as Route & { fallback?: () => Promise<void> };\n\t\t\tawait (r.fallback ? r.fallback() : route.continue());\n\t\t\treturn;\n\t\t}\n\t\tconst headers = await request.allHeaders();\n\t\tconst postData = request.postDataBuffer();\n\t\tconst body = postData ? new Uint8Array(postData) : null;\n\t\tensureContentDigest(request.method(), headers, body);\n\t\tawait sign({ method: request.method(), url, headers, body }, identity);\n\t\tapplyUserAgent(headers, identity.userAgent);\n\t\tawait route.continue({ headers });\n\t};\n\tawait page.route(pattern, handler);\n\t/** Detach: remove the signing route handler. */\n\treturn async () => {\n\t\tawait page.unroute(pattern, handler);\n\t};\n}\n","/**\n * Origin-side verification of Web Bot Auth signatures — mirror of\n * python/src/wbauth/verifier.py.\n *\n * const verifier = new Verifier();\n * const agent = await verifier.verify(request); // WHATWG Request\n *\n * Checks: tag=\"web-bot-auth\", alg=ed25519, created/expires window (with skew,\n * ≤ 3600 s), @authority covered, signature-agent covered when sent,\n * content-digest covered AND matching the body, nonce not replayed, key\n * resolved from the Signature-Agent directory (thumbprint must equal keyid).\n */\nimport {\n\tcreateHash,\n\tcreatePublicKey,\n\tverify as cryptoVerify,\n} from \"node:crypto\";\nimport { thumbprint } from \"./identity.js\";\nimport {\n\tMAX_EXPIRES_SECONDS,\n\tnormalizeAuthority,\n\tWEB_BOT_AUTH_TAG,\n} from \"./signer.js\";\n\nexport const DIRECTORY_PATH = \"/.well-known/http-message-signatures-directory\";\nconst DIRECTORY_MAX_BYTES = 64 * 1024;\n\nexport class VerificationError extends Error {\n\toverride name = \"VerificationError\";\n}\n\nexport interface VerifiedAgent {\n\tkid: string;\n\tsignatureAgentUrl: string | null;\n\tlabel: string;\n\tcreated: number;\n\texpires: number;\n\tnonce: string | null;\n\tcovered: string[];\n\tjwk: JsonWebKey;\n}\n\nexport type KeyResolver = (\n\tkid: string,\n\tsignatureAgent: string | null,\n) => Promise<JsonWebKey | null | undefined>;\n\nexport interface VerifierOptions {\n\tkeyResolver?: KeyResolver;\n\t/** fetch used for directory lookups (default globalThis.fetch). */\n\tfetch?: typeof fetch;\n\t/** Directory cache TTL in seconds (default 300). */\n\tjwksTtlSeconds?: number;\n\t/** Clock skew tolerance in seconds (default 5). */\n\tmaxSkew?: number;\n\trequireNonce?: boolean;\n\tnonceStore?: NonceStore;\n}\n\n/** In-memory TTL set of seen nonces. Replace with a shared store in clusters. */\nexport class NonceStore {\n\t#seen = new Map<string, number>();\n\tconstructor(private readonly maxSize = 100_000) {}\n\tseen(nonce: string, expiresAt: number): boolean {\n\t\tconst now = Date.now() / 1000;\n\t\tif (this.#seen.size >= this.maxSize) {\n\t\t\tfor (const [n, e] of this.#seen) if (e <= now) this.#seen.delete(n);\n\t\t\tfor (const n of [...this.#seen.keys()].slice(\n\t\t\t\t0,\n\t\t\t\tMath.ceil(this.maxSize / 10),\n\t\t\t)) {\n\t\t\t\tif (this.#seen.size < this.maxSize) break;\n\t\t\t\tthis.#seen.delete(n);\n\t\t\t}\n\t\t}\n\t\tconst prev = this.#seen.get(nonce);\n\t\tif (prev !== undefined && prev > now) return true;\n\t\tthis.#seen.set(nonce, expiresAt);\n\t\treturn false;\n\t}\n}\n\n// ---------- Structured-field parsing (profile subset) ----------\n\nconst SF_STRING = String.raw`\"(?:[^\"\\\\]|\\\\.)*\"`;\nconst PARAM = String.raw`;\\s*([a-z*][a-z0-9_.*-]*)(?:=(${SF_STRING}|-?\\d+(?:\\.\\d+)?|\\?[01]|[A-Za-z*][^;,\\s]*))?`;\nconst SIG_INPUT_RE = new RegExp(\n\tString.raw`\\s*([a-z*][a-z0-9_.*-]*)=(\\((?:\\s*${SF_STRING}(?:;[^\\s)\"]+)*)*\\s*\\))((?:${PARAM})*)`,\n\t\"y\",\n);\n\nconst unquote = (v: string) =>\n\tv.startsWith('\"') ? v.slice(1, -1).replace(/\\\\(.)/g, \"$1\") : v;\n\ninterface ParsedInput {\n\tlabel: string;\n\trawParams: string;\n\tcomponents: string[];\n\tparams: Record<string, string | number | boolean>;\n}\n\nexport function parseSignatureInput(value: string): ParsedInput[] {\n\tconst out: ParsedInput[] = [];\n\tlet pos = 0;\n\twhile (pos < value.length) {\n\t\tSIG_INPUT_RE.lastIndex = pos;\n\t\tconst m = SIG_INPUT_RE.exec(value);\n\t\tif (!m) throw new VerificationError(\"malformed Signature-Input\");\n\t\tconst [, label = \"\", inner = \"\", rest = \"\"] = m;\n\t\tif (/\"\\s*;/.test(inner))\n\t\t\tthrow new VerificationError(\"component parameters are not supported\");\n\t\tconst params: Record<string, string | number | boolean> = {};\n\t\tfor (const p of rest.matchAll(new RegExp(PARAM, \"g\"))) {\n\t\t\tconst k = p[1] as string;\n\t\t\tconst v = p[2];\n\t\t\tparams[k] =\n\t\t\t\tv === undefined\n\t\t\t\t\t? true\n\t\t\t\t\t: v.startsWith('\"')\n\t\t\t\t\t\t? unquote(v)\n\t\t\t\t\t\t: /^-?\\d+$/.test(v)\n\t\t\t\t\t\t\t? Number(v)\n\t\t\t\t\t\t\t: v;\n\t\t}\n\t\tout.push({\n\t\t\tlabel,\n\t\t\trawParams: inner + rest,\n\t\t\tcomponents: [...inner.matchAll(new RegExp(SF_STRING, \"g\"))].map((x) =>\n\t\t\t\tunquote(x[0]),\n\t\t\t),\n\t\t\tparams,\n\t\t});\n\t\tpos = SIG_INPUT_RE.lastIndex;\n\t\twhile (pos < value.length && (value[pos] === \" \" || value[pos] === \",\"))\n\t\t\tpos++;\n\t}\n\treturn out;\n}\n\nfunction parseSignature(value: string): Map<string, Buffer> {\n\tconst out = new Map<string, Buffer>();\n\tfor (const m of value.matchAll(\n\t\t/\\s*([a-z*][a-z0-9_.*-]*)=:([A-Za-z0-9+/=]*):/g,\n\t)) {\n\t\tout.set(m[1] as string, Buffer.from(m[2] as string, \"base64\"));\n\t}\n\treturn out;\n}\n\nfunction componentValue(\n\tname: string,\n\treq: { method: string; url: string },\n\theaders: Headers,\n\tauthority?: string,\n): string {\n\tconst u = new URL(req.url);\n\tswitch (name) {\n\t\tcase \"@authority\":\n\t\t\treturn authority ?? normalizeAuthority(req.url);\n\t\tcase \"@method\":\n\t\t\treturn req.method.toUpperCase();\n\t\tcase \"@scheme\":\n\t\t\treturn u.protocol.slice(0, -1);\n\t\tcase \"@target-uri\":\n\t\t\treturn u.href;\n\t\tcase \"@path\":\n\t\t\treturn u.pathname || \"/\";\n\t\tcase \"@query\":\n\t\t\treturn u.search || \"?\";\n\t}\n\tif (name.startsWith(\"@\"))\n\t\tthrow new VerificationError(`unsupported derived component ${name}`);\n\tconst v = headers.get(name);\n\tif (v === null) throw new VerificationError(`covered header ${name} missing`);\n\treturn v.trim();\n}\n\nfunction directoryUrl(signatureAgent: string): string {\n\tconst u = new URL(signatureAgent);\n\tif (u.protocol !== \"https:\")\n\t\tthrow new VerificationError(\"Signature-Agent must be https://\");\n\tif (u.pathname === \"/\" || u.pathname === \"\") {\n\t\tu.pathname = DIRECTORY_PATH;\n\t\tu.search = \"\";\n\t}\n\tu.hash = \"\";\n\treturn u.href;\n}\n\nexport class Verifier {\n\t#opts: VerifierOptions;\n\t#nonces: NonceStore;\n\t#jwks = new Map<string, { until: number; keys: JsonWebKey[] }>();\n\n\tconstructor(opts: VerifierOptions = {}) {\n\t\tthis.#opts = opts;\n\t\tthis.#nonces = opts.nonceStore ?? new NonceStore();\n\t}\n\n\tasync #directoryKeys(url: string): Promise<JsonWebKey[]> {\n\t\tconst hit = this.#jwks.get(url);\n\t\tif (hit && hit.until > Date.now()) return hit.keys;\n\t\tconst f = this.#opts.fetch ?? globalThis.fetch;\n\t\tlet res: Response;\n\t\ttry {\n\t\t\tres = await f(url, {\n\t\t\t\theaders: {\n\t\t\t\t\taccept:\n\t\t\t\t\t\t\"application/http-message-signatures-directory+json, application/json\",\n\t\t\t\t},\n\t\t\t\tredirect: \"error\",\n\t\t\t\tsignal: AbortSignal.timeout(3000),\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tthrow new VerificationError(`directory unreachable: ${String(e)}`);\n\t\t}\n\t\tif (res.status !== 200)\n\t\t\tthrow new VerificationError(`directory ${url} answered ${res.status}`);\n\t\tconst buf = await res.arrayBuffer();\n\t\tif (buf.byteLength > DIRECTORY_MAX_BYTES)\n\t\t\tthrow new VerificationError(\"directory too large\");\n\t\tlet keys: unknown;\n\t\ttry {\n\t\t\tkeys = (JSON.parse(new TextDecoder().decode(buf)) as { keys?: unknown })\n\t\t\t\t.keys;\n\t\t} catch {\n\t\t\tthrow new VerificationError(\"directory is not a JWKS\");\n\t\t}\n\t\tif (!Array.isArray(keys))\n\t\t\tthrow new VerificationError(\"directory is not a JWKS\");\n\t\tthis.#jwks.set(url, {\n\t\t\tuntil: Date.now() + (this.#opts.jwksTtlSeconds ?? 300) * 1000,\n\t\t\tkeys,\n\t\t});\n\t\treturn keys as JsonWebKey[];\n\t}\n\n\tasync #resolve(\n\t\tkid: string,\n\t\tsignatureAgent: string | null,\n\t): Promise<JsonWebKey> {\n\t\tif (this.#opts.keyResolver) {\n\t\t\tconst jwk = await this.#opts.keyResolver(kid, signatureAgent);\n\t\t\tif (!jwk) throw new VerificationError(`unknown keyid ${kid}`);\n\t\t\treturn jwk;\n\t\t}\n\t\tif (!signatureAgent)\n\t\t\tthrow new VerificationError(\n\t\t\t\t\"no Signature-Agent and no keyResolver configured\",\n\t\t\t);\n\t\tfor (const k of await this.#directoryKeys(directoryUrl(signatureAgent))) {\n\t\t\tif (\n\t\t\t\tk &&\n\t\t\t\tk.kty === \"OKP\" &&\n\t\t\t\tk.crv === \"Ed25519\" &&\n\t\t\t\tk.x &&\n\t\t\t\tthumbprint(k) === kid\n\t\t\t)\n\t\t\t\treturn k;\n\t\t}\n\t\tthrow new VerificationError(\n\t\t\t`keyid ${kid} not published by ${signatureAgent}`,\n\t\t);\n\t}\n\n\t/**\n\t * Verify a WHATWG Request (body is read from a clone). `authority`\n\t * overrides the value derived from the URL (e.g. behind a proxy).\n\t */\n\tasync verify(\n\t\trequest: Request,\n\t\topts: { authority?: string; now?: number } = {},\n\t): Promise<VerifiedAgent> {\n\t\tconst h = request.headers;\n\t\tconst sigInput = h.get(\"signature-input\");\n\t\tconst sigHeader = h.get(\"signature\");\n\t\tif (!sigInput || !sigHeader)\n\t\t\tthrow new VerificationError(\"request is not signed\");\n\t\tconst sigs = parseSignature(sigHeader);\n\t\tconst cand = parseSignatureInput(sigInput).find(\n\t\t\t(c) => c.params.tag === WEB_BOT_AUTH_TAG,\n\t\t);\n\t\tif (!cand)\n\t\t\tthrow new VerificationError('no signature with tag=\"web-bot-auth\"');\n\t\tconst { label, rawParams, components, params } = cand;\n\t\tconst raw = sigs.get(label);\n\t\tif (!raw) throw new VerificationError(`Signature has no ${label} member`);\n\t\tif ((params.alg ?? \"ed25519\") !== \"ed25519\")\n\t\t\tthrow new VerificationError(\"only alg=ed25519 is supported\");\n\t\tconst { created, expires, keyid } = params;\n\t\tif (\n\t\t\ttypeof created !== \"number\" ||\n\t\t\ttypeof expires !== \"number\" ||\n\t\t\ttypeof keyid !== \"string\"\n\t\t) {\n\t\t\tthrow new VerificationError(\"created, expires and keyid are required\");\n\t\t}\n\t\tconst skew = this.#opts.maxSkew ?? 5;\n\t\tconst now = opts.now ?? Date.now() / 1000;\n\t\tif (created > now + skew)\n\t\t\tthrow new VerificationError(\"signature created in the future\");\n\t\tif (expires < now - skew) throw new VerificationError(\"signature expired\");\n\t\tif (expires <= created || expires - created > MAX_EXPIRES_SECONDS) {\n\t\t\tthrow new VerificationError(\"invalid validity window\");\n\t\t}\n\t\tif (!components.includes(\"@authority\"))\n\t\t\tthrow new VerificationError(\"@authority must be covered\");\n\t\tlet signatureAgent: string | null = null;\n\t\tconst sa = h.get(\"signature-agent\");\n\t\tif (sa !== null) {\n\t\t\tif (!components.includes(\"signature-agent\")) {\n\t\t\t\tthrow new VerificationError(\"Signature-Agent sent but not covered\");\n\t\t\t}\n\t\t\tsignatureAgent = unquote(sa.trim());\n\t\t}\n\t\tconst body = request.body\n\t\t\t? new Uint8Array(await request.clone().arrayBuffer())\n\t\t\t: new Uint8Array();\n\t\tif (body.byteLength > 0) {\n\t\t\tif (!components.includes(\"content-digest\")) {\n\t\t\t\tthrow new VerificationError(\n\t\t\t\t\t\"request has a body but content-digest is not covered\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst m = /(?:^|,)\\s*sha-256=:([A-Za-z0-9+/=]+):/.exec(\n\t\t\t\th.get(\"content-digest\") ?? \"\",\n\t\t\t);\n\t\t\tconst actual = createHash(\"sha256\").update(body).digest(\"base64\");\n\t\t\tif (!m || m[1] !== actual)\n\t\t\t\tthrow new VerificationError(\"Content-Digest does not match the body\");\n\t\t}\n\t\tconst nonce = typeof params.nonce === \"string\" ? params.nonce : null;\n\t\tif (this.#opts.requireNonce && !nonce)\n\t\t\tthrow new VerificationError(\"nonce required\");\n\n\t\tconst base = [\n\t\t\t...components.map(\n\t\t\t\t(c) => `\"${c}\": ${componentValue(c, request, h, opts.authority)}`,\n\t\t\t),\n\t\t\t`\"@signature-params\": ${rawParams}`,\n\t\t].join(\"\\n\");\n\t\tconst jwk = await this.#resolve(keyid, signatureAgent);\n\t\tlet ok = false;\n\t\ttry {\n\t\t\tconst key = createPublicKey({\n\t\t\t\tkey: { kty: \"OKP\", crv: \"Ed25519\", x: jwk.x as string },\n\t\t\t\tformat: \"jwk\",\n\t\t\t});\n\t\t\tok = cryptoVerify(null, Buffer.from(base, \"utf8\"), key, raw);\n\t\t} catch {\n\t\t\tok = false;\n\t\t}\n\t\tif (!ok) throw new VerificationError(\"signature does not verify\");\n\t\tif (nonce && this.#nonces.seen(nonce, expires + skew))\n\t\t\tthrow new VerificationError(\"nonce replayed\");\n\t\treturn {\n\t\t\tkid: keyid,\n\t\t\tsignatureAgentUrl: signatureAgent,\n\t\t\tlabel,\n\t\t\tcreated,\n\t\t\texpires,\n\t\t\tnonce,\n\t\t\tcovered: components,\n\t\t\tjwk,\n\t\t};\n\t}\n}\n\n/**\n * Fetch-style middleware helper (Hono, itty-router, Workers, Bun, Deno…):\n * returns the verified agent, `null` for unsigned requests, or a 401\n * `Response` when `required` and verification fails.\n */\nexport function createVerifierMiddleware(\n\topts: VerifierOptions & { required?: boolean } = {},\n) {\n\tconst verifier = new Verifier(opts);\n\treturn async (request: Request): Promise<VerifiedAgent | null | Response> => {\n\t\tconst signed = request.headers.has(\"signature-input\");\n\t\tif (!signed && !opts.required) return null;\n\t\ttry {\n\t\t\tif (!signed) throw new VerificationError(\"request is not signed\");\n\t\t\treturn await verifier.verify(request);\n\t\t} catch (e) {\n\t\t\tif (!opts.required) return null;\n\t\t\treturn new Response(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\terror: \"web_bot_auth\",\n\t\t\t\t\treason: String((e as Error).message),\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tstatus: 401,\n\t\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t};\n}\n","/**\n * wbauth: Web Bot Auth (RFC 9421) TypeScript SDK — Phase 4 public surface.\n *\n * Per CONTEXT D-74: flat root exports. Subpath exports (`wb-auth/adapters`)\n * are a v1.x optimization, not required for Phase 4.\n *\n * Quickstart:\n * import { Identity, createSignedFetch } from \"wb-auth\";\n * const id = await Identity.loadOrGenerate(\"./key.pem\", {\n * signatureAgentUrl: \"https://example.com/.well-known/.../<kid>\",\n * });\n * const sf = createSignedFetch(id);\n * const res = await sf(\"https://api.example.com/data\");\n */\n\nexport type { SignScopeOptions } from \"./adapters/_utils.js\";\nexport type { SignedFetchOptions } from \"./adapters/fetch.js\";\nexport { createSignedFetch } from \"./adapters/fetch.js\";\nexport type { ApplyToOptions } from \"./adapters/playwright.js\";\nexport { applyTo } from \"./adapters/playwright.js\";\nexport type {\n\tEd25519SignerBackend,\n\tIdentityOptions,\n\tKeyOptions,\n\tKeyPair,\n\tPublicJwk,\n\tSigner,\n} from \"./identity.js\";\nexport {\n\tDEFAULT_KEY_PATH,\n\tIdentity,\n\tKEY_PASSWORD_ENV,\n\tthumbprint,\n\tvalidateSignatureAgentUrl,\n} from \"./identity.js\";\nexport type { NormalizedRequest } from \"./normalized-request.js\";\nexport type { SignatureHeaders, SignOptions } from \"./signer.js\";\nexport { normalizeAuthority, sign } from \"./signer.js\";\nexport type {\n\tKeyResolver,\n\tVerifiedAgent,\n\tVerifierOptions,\n} from \"./verifier.js\";\nexport {\n\tcreateVerifierMiddleware,\n\tNonceStore,\n\tVerificationError,\n\tVerifier,\n} from \"./verifier.js\";\n\nexport const VERSION = \"0.4.0\";\n"],"mappings":";AAaA,SAAS,mBAAmB;;;ACC5B;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA,QAAQ;AAAA,EACR;AAAA,OAEM;AACP,SAAS,OAAO,MAAM,UAAU,QAAQ,YAAY;AACpD,SAAS,eAAe;AACxB,SAAS,SAAS,MAAM,eAAe;AAKhC,IAAM,mBAAmB;AAAA,EAC/B,QAAQ;AAAA,EACR;AAAA,EACA;AAAA,EACA;AACD;AAGO,IAAM,mBAAmB;AACzB,IAAM,iBAA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MACnB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,SAAS;AAAA,MACT;AAAA,IACD;AAAA,EACD;AACD;AAOO,SAAS,yBACf,OAAiD,CAAC,GACjD;AACD,QAAM,WAAW,IAAI,SAAS,IAAI;AAClC,SAAO,OAAO,YAA+D;AAC5E,UAAM,SAAS,QAAQ,QAAQ,IAAI,iBAAiB;AACpD,QAAI,CAAC,UAAU,CAAC,KAAK,SAAU,QAAO;AACtC,QAAI;AACH,UAAI,CAAC,OAAQ,OAAM,IAAI,kBAAkB,uBAAuB;AAChE,aAAO,MAAM,SAAS,OAAO,OAAO;AAAA,IACrC,SAAS,GAAG;AACX,UAAI,CAAC,KAAK,SAAU,QAAO;AAC3B,aAAO,IAAI;AAAA,QACV,KAAK,UAAU;AAAA,UACd,OAAO;AAAA,UACP,QAAQ,OAAQ,EAAY,OAAO;AAAA,QACpC,CAAC;AAAA,QACD;AAAA,UACC,QAAQ;AAAA,UACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,QAC/C;AAAA,MACD;AAAA,IACD;AAAA,EACD;AACD;;;AC3VO,IAAM,UAAU;","names":["createHash","createHash","createPublicKey","createHash","createPublicKey"]}
|
package/package.json
CHANGED
|
@@ -1,77 +1,74 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
}
|
|
2
|
+
"name": "wb-auth",
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Web Bot Auth (RFC 9421) TypeScript SDK — signed identity for AI agents and crawlers",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.cjs",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"import": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"require": {
|
|
16
|
+
"types": "./dist/index.d.cts",
|
|
17
|
+
"default": "./dist/index.cjs"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"./package.json": "./package.json"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist"
|
|
24
|
+
],
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"license": "Apache-2.0",
|
|
27
|
+
"repository": {
|
|
28
|
+
"type": "git",
|
|
29
|
+
"url": "git+https://github.com/MrKoriy/wbauth.git",
|
|
30
|
+
"directory": "typescript"
|
|
31
|
+
},
|
|
32
|
+
"homepage": "https://github.com/MrKoriy/wbauth#readme",
|
|
33
|
+
"bugs": "https://github.com/MrKoriy/wbauth/issues",
|
|
34
|
+
"keywords": [
|
|
35
|
+
"web-bot-auth",
|
|
36
|
+
"rfc9421",
|
|
37
|
+
"http-message-signatures",
|
|
38
|
+
"ed25519",
|
|
39
|
+
"ai-agents",
|
|
40
|
+
"crawler",
|
|
41
|
+
"playwright"
|
|
42
|
+
],
|
|
43
|
+
"engines": {
|
|
44
|
+
"node": ">=20"
|
|
45
|
+
},
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public",
|
|
48
|
+
"provenance": true
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@biomejs/biome": "^2",
|
|
52
|
+
"@types/node": "^20",
|
|
53
|
+
"playwright": "^1.59",
|
|
54
|
+
"tsup": "^8",
|
|
55
|
+
"tsx": "^4.23.15",
|
|
56
|
+
"typescript": "^6",
|
|
57
|
+
"vitest": "^4",
|
|
58
|
+
"web-bot-auth": "^0.1.3"
|
|
59
|
+
},
|
|
60
|
+
"peerDependencies": {
|
|
61
|
+
"playwright": "^1"
|
|
62
|
+
},
|
|
63
|
+
"peerDependenciesMeta": {
|
|
64
|
+
"playwright": {
|
|
65
|
+
"optional": true
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
"scripts": {
|
|
69
|
+
"build": "tsup",
|
|
70
|
+
"test": "vitest run",
|
|
71
|
+
"lint": "biome check .",
|
|
72
|
+
"typecheck": "tsc --noEmit -p ."
|
|
73
|
+
}
|
|
74
|
+
}
|