uvd-describe-sdk 0.2.0 → 0.3.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.
@@ -1,5 +1,5 @@
1
- import { w as PartnerSigner } from '../client-RAhXcpdY.mjs';
2
- export { P as PARTNER_CHAIN_ID, d as PARTNER_KEY_ENV } from '../config-uvI_GS-x.mjs';
1
+ import { y as PartnerSigner } from '../client-BMfgl1zP.mjs';
2
+ export { P as PARTNER_CHAIN_ID, d as PARTNER_KEY_ENV } from '../config-DzzhWFYr.mjs';
3
3
 
4
4
  /**
5
5
  * The partner rail — how a product of the house reads describe.net for free.
@@ -1,5 +1,5 @@
1
- import { w as PartnerSigner } from '../client-RAhXcpdY.js';
2
- export { P as PARTNER_CHAIN_ID, d as PARTNER_KEY_ENV } from '../config-uvI_GS-x.js';
1
+ import { y as PartnerSigner } from '../client-BMfgl1zP.js';
2
+ export { P as PARTNER_CHAIN_ID, d as PARTNER_KEY_ENV } from '../config-DzzhWFYr.js';
3
3
 
4
4
  /**
5
5
  * The partner rail — how a product of the house reads describe.net for free.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config.ts","../../src/partner/index.ts"],"names":["signRequestWithSigner","signRequest","CONFORMANCE_VECTORS_F3_1"],"mappings":";;;;;;;AAyHO,IAAM,gBAAA,GAAmB;AAUzB,IAAM,eAAA,GAAkB;;;ACnC/B,SAAS,aAAa,OAAA,EAAyC;AAC7D,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,OAAO,CAAA,EAAG;AACnD,IAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,GAAA,CAAI,IAAI,CAAA,GAAI,KAAA;AAAA,EAC7C;AACA,EAAA,OAAO,GAAA;AACT;AAGA,SAAS,SAAA,GAAoB;AAC3B,EAAA,MAAM,KAAA,GAAQ,IAAI,UAAA,CAAW,EAAE,CAAA;AAG/B,EAAA,UAAA,CAAW,MAAA,CAAO,gBAAgB,KAAK,CAAA;AACvC,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,KAAA,EAAO,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,SAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA;AAC1E;AAuCO,SAAS,kBACd,MAAA,EAMe;AACf,EAAA,MAAM,EAAE,OAAA,EAAS,WAAA,EAAa,OAAA,GAAU,kBAAiB,GAAI,MAAA;AAC7D,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,MAAM,IAAA,CAAK,EAAE,MAAA,EAAQ,KAAI,EAAG;AAC1B,MAAA,OAAO,YAAA;AAAA,QACL,MAAMA,6BAAA,CAAsB;AAAA,UAC1B,MAAA;AAAA,UACA,GAAA;AAAA,UACA,OAAA;AAAA,UACA,OAAA;AAAA,UACA,OAAO,SAAA,EAAU;AAAA,UACjB;AAAA,SACD;AAAA,OACH;AAAA,IACF;AAAA,GACF;AACF;AAsDO,SAAS,cAAA,CACd,OAAA,GAKI,EAAC,EACU;AACf,EAAA,MAAM,EAAE,OAAA,GAAU,gBAAA,EAAkB,MAAA,GAAS,iBAAgB,GAAI,OAAA;AACjE,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,IAAQ,UAAA,CAA0E,OAAA,EAAS,GAAA;AAE/G,EAAA,MAAM,GAAA,GAAM,MAAM,MAAM,CAAA;AACxB,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,CAAI,IAAA,OAAW,EAAA,EAAI;AAChD,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,mBAAmB,MAAM,CAAA,2OAAA;AAAA,KAI3B;AAAA,EACF;AAIA,EAAA,MAAM,GAAA,GAAM,IAAI,IAAA,EAAK;AACrB,EAAA,IAAI,CAAC,wBAAA,CAAyB,IAAA,CAAK,GAAG,CAAA,EAAG;AAGvC,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,gBAAA,EAAmB,MAAM,CAAA,uCAAA,EACf,GAAA,CAAI,MAAM,CAAA,wGAAA;AAAA,KAEtB;AAAA,EACF;AAMA,EAAA,OAAO;AAAA,IACL,MAAM,IAAA,CAAK,EAAE,MAAA,EAAQ,KAAI,EAAG;AAC1B,MAAA,OAAO,YAAA;AAAA,QACL,MAAMC,mBAAA,CAAY,EAAE,MAAA,EAAQ,GAAA,EAAK,OAAA,EAAS,KAAA,EAAO,SAAA,EAAU,EAAG,UAAA,EAAY,GAAA,EAAK;AAAA,OACjF;AAAA,IACF;AAAA,GACF;AACF;AAcO,SAAS,gBAAA,GAA2B;AACzC,EAAA,MAAM,GAAA,GAAMC,iCAAyB,MAAA,CAAO,WAAA;AAC5C,EAAA,IAAI,CAAC,GAAA,EAAK,MAAM,IAAI,MAAM,wDAAwD,CAAA;AAClF,EAAA,OAAO,GAAA;AACT","file":"index.js","sourcesContent":["/**\n * The only place this package defines a calibrable value.\n *\n * House rule (decisión de Saul, 2026-08-26, born from a measured case in\n * describe.net: one threshold written with TWO DIFFERENT VALUES across four\n * surfaces, and the one charged was not the one the site promised). Nothing\n * else in this package re-types these numbers — modules import them.\n *\n * What does NOT live here, by the same rule: anything that moves a score or a\n * price. This SDK computes neither, so the list is short: `POLICY_VERSION` and\n * the prices are the server's and travel in its responses. We never type a\n * price. See `errors.ts` for what we do with a 402 challenge instead.\n */\n\n/** Where the index answers. Overridable per client for a staging deploy. */\nexport const DEFAULT_BASE_URL = 'https://api.describe.net';\n\n/** Where a human reads the same wallet. Never fetched — only linked. */\nexport const DEFAULT_SITE_URL = 'https://describe.net';\n\n/**\n * 30 s, and the number is not taste — it is the one number of the three live\n * consumers that came with its measurement written down (EM `client.py:19-23`,\n * INC-2026-08-19):\n *\n * * the provider's Lambda cold start was measured at **15,2 s**, so anything\n * under it turns a cold index into a fake outage. An 8 s timeout already\n * broke a real integration once.\n * * its API Gateway integration ceiling is **29 s**, so waiting past 30 buys\n * nothing the gateway will ever deliver.\n * * it is deliberately DISTINCT from the Facilitator's 45 s so two clocks can\n * never expire in the same second and produce an error nobody can attribute.\n *\n * Measured across the ecosystem on 2026-08-30: EM 30 s, MeshRelay 30 000 ms,\n * KarmaKadabra 25 s. Two of three already sit here.\n */\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\n/**\n * 400 ms, **on by default**, and the default is the decision — so here is the\n * argument, because it is the one thing about this package that spends the\n * caller's latency without being asked.\n *\n * The number is not ours: it is what **KarmaKadabra** sleeps before every read\n * (`random.uniform(0, 0.4)`), contributed on 2026-08-30 with the measurement\n * that produced it — *\"27 agentes despiertan al MISMO tiempo por EventBridge y\n * pegan simultáneo contra su límite de rps COMPARTIDO con los otros\n * consumidores. Sin jitter, un enjambre es un DDoS educado.\"* They run the\n * largest fleet against this index, so their calibration beats our taste.\n *\n * ## Why ON, when a library that sleeps unasked is a surprise\n *\n * The surprise is real and it is the honest objection. Three things outweigh it:\n *\n * 1. **The cost of the mistake does not land on whoever makes it.** The rate\n * limit is shared with no per-partner bucket (see `userAgent` below), so an\n * unjittered swarm is paid for by the OTHER consumer, who gets the 429 and\n * has no lever to fix it. When the cost of a default falls on someone who\n * cannot change it, the default has to be the safe one.\n * 2. **Opt-out is discoverable; opt-in is not.** `jitterMs: 0` is one field\n * away and typed. The other direction cannot be found by reading your own\n * code: you learn you needed jitter from someone else's incident, and by\n * then you have already spent their budget. KarmaKadabra's own framing —\n * whoever writes a single script never finds out the problem exists until\n * they have a fleet.\n * 3. **It is bounded and small against this package's own numbers.** At most\n * 400 ms, 200 ms on average, against a 30 000 ms timeout and a provider\n * cold start measured at 15,2 s. And it is the same shape of default this\n * client already ships: `failOpen: true` also changes behaviour without\n * being asked, for the same reason — the safe thing, loudly documented,\n * with one field to turn it off.\n *\n * ## What is NOT written here, on purpose\n *\n * The rate limit itself. KarmaKadabra's own note cited 20 rps, which was the\n * documentation's figure and is now stale (it is 50 sustained / burst 40 since\n * 2026-08-28). A number that has already gone stale once in one hop between two\n * teams does not belong in a constant: **the `RateLimit-Policy` response header\n * is the authority**, and this value is calibrated against a fleet size, not\n * against a ceiling. See the correction in `userAgent`.\n */\nexport const DEFAULT_JITTER_MS = 400;\n\n/**\n * The treasury this SDK will pay, and NOTHING else.\n *\n * Read live from the 402 challenge of `GET /reputation/wallet/{w}` on\n * 2026-08-30 (`recipient`, and `payTo` on all six `accepts[]` entries — base,\n * avalanche, arbitrum, optimism, polygon, celo — identical on every one).\n *\n * Pinning it is the point: an x402 challenge is fetched over the network and\n * names its own recipient, so a client that pays whatever `payTo` arrives will\n * happily pay an attacker who can answer as the API. A challenge whose `payTo`\n * is not this address is `DO_NOT_PAY` — never a retry, never a warning that a\n * caller can ignore.\n *\n * 🔴 THE FAILURE MODE OF PINNING, written down because it will happen: if\n * describe.net rotates its treasury, every published version of this SDK stops\n * paying until it is republished. That is the SAFE direction of the failure\n * (refusing to pay a stranger beats paying one), and the escape hatch is\n * `expectedPayTo` in the client config — a caller who has verified the new\n * address out of band can move without waiting for us.\n */\nexport const TREASURY_EVM = '0xe4dc963c56979E0260fc146b87eE24F18220e545';\n\n/**\n * The chain id that goes in the ERC-8128 keyid of a partner signature.\n *\n * 8453 (Base). Not a preference — it is what the gate accepts:\n * `describe-net/describenet/partner.py:90` sets `CHAIN_ID = 8453` and passes it\n * as the ONLY member of `allowed_chain_ids`, with its own comment explaining\n * that `None` (accept any chain) would be \"innecesariamente laxo para una\n * allowlist de tres servicios propios\". Read 2026-08-30.\n *\n * The payment SDK's own default happens to be 8453 too, and this constant\n * deliberately does not lean on that: this value belongs to describe.net's\n * policy, not to the signer's convenience, and the day one moves the other must\n * not follow by accident. Measured failure mode of getting it wrong: the gate\n * answers `chain_not_allowed` and the route charges — loud, since partner mode\n * throws `DescribePartnerRejected` instead of paying.\n */\nexport const PARTNER_CHAIN_ID = 8453;\n\n/**\n * The environment variable `partnerFromEnv()` reads the signing key from.\n *\n * A variable name is not a secret; the value it holds is. Naming it here means\n * a consumer can grep for it, a deploy manifest can set it, and nobody has to\n * guess — while `partnerFromEnv()` staying the ONLY reader means the key has\n * exactly one path into this package.\n */\nexport const PARTNER_KEY_ENV = 'DESCRIBE_PARTNER_PRIVATE_KEY';\n\n/**\n * The package version, for the `User-Agent`.\n *\n * MeshRelay reads its version from `package.json` at runtime because \"a\n * User-Agent that lies about the version is worse than none\"\n * (`describenet.js:39`). It can afford the `readFileSync`: it is a server, not\n * a bundled library. We cannot — a library that reads its own manifest at\n * runtime either bundles `package.json` into the artifact or breaks in a\n * browser, and this package has to run in a browser.\n *\n * So the constant is typed here and `config.test.ts` asserts it equals\n * `package.json`'s `version`. Same guarantee (the UA cannot lie), paid at test\n * time instead of at runtime. Bumping the version without the constant is a\n * red test, not a silent lie in someone's access log.\n */\nexport const SDK_VERSION = '0.2.0';\n\n/** `uvd-describe-sdk-ts/0.1.0`, plus `(+<product>)` when the caller names itself. */\nexport const SDK_NAME = 'uvd-describe-sdk-ts';\n\n/**\n * Build the `User-Agent`.\n *\n * The provider's rate limit is **shared by every consumer with no per-partner\n * bucket**, so identifying ourselves is the only thing that makes our share of\n * it attributable at all. That is why the UA is on by default and `product` is\n * the one field a caller should bother to fill.\n *\n * ⚠️ CORRECTION 2026-08-30, left written rather than swapped: this comment\n * first said \"20 rps\", copied from `meshrelay/describenet.js:19-20`. The live\n * OpenAPI says **50 requests/second sustained, bursts up to 40**, at the API\n * Gateway edge, and it also says where the truth lives: *\"Every response\n * carries the policy as a header, `RateLimit-Policy: 50;w=1;burst=40` … and\n * **that header is the authority**\"*. So neither number belongs in this file —\n * read the header. Cached free routes (`/health`, `/pricing`, `/leaderboard`,\n * `/stats/*`) are served by CloudFront and do not consume the budget on a hit.\n * The 20 was probably right when MeshRelay wrote it; a dated figure does not\n * stop being stale, it only stops being a lie.\n *\n * ⚠️ It is attribution, not authentication. describe.net has no accounts and\n * no API keys — \"el pago es la autenticación\" — so anyone can send any UA.\n * Never treat this string as identity, on either side.\n */\nexport function userAgent(product?: string): string {\n const base = `${SDK_NAME}/${SDK_VERSION}`;\n const trimmed = (product ?? '').trim();\n return trimmed ? `${base} (+${trimmed})` : base;\n}\n","/**\n * The partner rail — how a product of the house reads describe.net for free.\n *\n * ## What this is, in one paragraph\n *\n * describe.net has no accounts and no API keys, on purpose: *\"el pago es la\n * autenticación\"*. So when Execution Market, MeshRelay and KarmaKadabra\n * deprecated their local reputation maths and became read-dependencies of the\n * index (2026-08-28), the question \"does a service of the house pay like a\n * stranger?\" could not be answered with a token. It was answered with an\n * ALLOWLIST OF PUBLIC ADDRESSES plus a per-request ERC-8128 signature\n * (`describe-net/describenet/partner.py`). The partner holds a dedicated wallet\n * with no funds whose only job is to sign; describe.net holds a list of\n * addresses. **The service custodies no secret of ours** — a breach there leaks\n * a list of things that were already public — and that property, not\n * convenience, is why this is a signature and not the `X-API-Key` everyone\n * reaches for first.\n *\n * This module is the client half. It is the only file in this package with a\n * RUNTIME import of `uvd-x402-sdk`, which is why it lives behind the\n * `uvd-describe-sdk/partner` subpath: the main entry and the `x402` entry keep\n * their zero-runtime-imports property, and a consumer who never signs installs\n * nothing.\n *\n * ## Upstream-first: the primitive already existed, MEASURED before writing\n *\n * `uvd-x402-sdk` 2.75.0 (installed, checked 2026-08-30) exports the whole\n * ERC-8128 signer from `uvd-x402-sdk/erc8128` — `signRequest`,\n * `signRequestWithSigner`, `signRequestWithWallet`, plus the pure base builder\n * and the verifier. So NOTHING is signed in this repo: this file picks a chain\n * id and a nonce and forwards. Not one byte of RFC 9421 canonicalisation is\n * reimplemented here, and if any of it ever needs to change, it changes THERE.\n *\n * Verified end to end, offline, on 2026-08-30: headers produced by\n * `signRequestWithSigner` at chain 8453 verify under the EXACT policy\n * `partner.py` builds (authority `api.describe.net`, `allowed_chain_ids=[8453]`,\n * `max_validity_sec=300`, `clock_skew_future_sec=30`), recovering the signer's\n * address. `partner.test.ts` is that probe, kept as a test.\n *\n * ## The nonce: minted here, and here is the argument\n *\n * The payment SDK requires a nonce and refuses to invent one — *\"a local nonce\n * authenticates against a first-use-wins store and is rejected by an\n * issuer-bound one, which turns a server blip into an auth mystery\"*\n * (`erc8128/signer.ts:15-17`). That reasoning is about servers that HAVE a nonce\n * store. describe.net has none: `PartnerGate` builds its `VerifyPolicy` with no\n * `nonce` field at all (`partner.py:216-223`), and the verifier skips every\n * nonce rule when `policy.nonce is None` — no presence check\n * (`verifier.py:458-462`), no consumption (`verifier.py:304`). Read in the\n * installed PyPI `uvd-x402-sdk` 0.70.0 on 2026-08-30.\n *\n * So there is no store to be unknown to, and a locally minted random nonce is\n * strictly better than the alternative the policy would also accept (none at\n * all): it makes each signature unique, so two identical GETs in the same second\n * do not produce byte-identical headers. This is the caller owning the\n * consequence, which is exactly what `onNonceUnavailable` exists to express in\n * the payment SDK — stated here rather than hidden.\n *\n * 🔴 If describe.net ever adds a nonce store, this line becomes wrong and the\n * failure is loud, not silent: every partner request starts answering 402 with\n * `nonce_unknown` and `DescribePartnerRejected` says so. That is the direction\n * this failure should point.\n *\n * ## What is signed, and the consequence of a custom `baseUrl`\n *\n * The signature covers `@method`, `@authority` and `@path` (plus `@query` when\n * there is one), and `@authority` comes from the URL being requested. The gate\n * pins `api.describe.net` and NEVER derives it from a header (`partner.py:73-84`\n * — deriving an authority from client-controlled input is how a verifier was\n * once made to rebuild a base over an attacker's domain). So a client pointed at\n * any other origin — a staging host, a proxy, the raw execute-api host behind\n * CloudFront — signs an authority the gate does not accept and is charged. That\n * is deliberate on both sides, and it fails LOUDLY here as\n * `DescribePartnerRejected` rather than quietly as a bill.\n */\n\nimport {\n CONFORMANCE_VECTORS_F3_1,\n signRequest,\n signRequestWithSigner,\n} from 'uvd-x402-sdk/erc8128';\n\nimport type { PartnerSigner } from '../client';\nimport { PARTNER_CHAIN_ID, PARTNER_KEY_ENV } from '../config';\n\n/**\n * The signer's typed header object as a plain `Record<string, string>`.\n *\n * Not cosmetic: `Erc8128Headers` declares `'Content-Digest'?: string`, and an\n * interface with an optional member is not assignable to `Record<string,\n * string>` — the dts build says so, loudly (TS2322 at the return, TS2345 at the\n * parameter, which is why the parameter is `object` and not a `Record` of its\n * own). Dropping the undefined entries here is the honest conversion, and it\n * means the client never merges a header whose value is `undefined` into a\n * `fetch` call, which is how a literal `\"undefined\"` ends up on a wire.\n */\nfunction plainHeaders(headers: object): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) {\n if (typeof value === 'string') out[name] = value;\n }\n return out;\n}\n\n/** A 128-bit hex nonce. See the module header for why this is minted locally. */\nfunction mintNonce(): string {\n const bytes = new Uint8Array(16);\n // `globalThis.crypto` is standard in Node >= 18 and in every browser, which\n // is the same floor as this package's `engines`. No import, no polyfill.\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/** What every factory here accepts. Both fields have defaults that are right. */\nexport interface PartnerOptions {\n /**\n * The keyid's chain id. Defaults to `PARTNER_CHAIN_ID` (8453, Base), which is\n * what the gate pins. Override only if describe.net's `CHAIN_ID` moves.\n */\n chainId?: number;\n}\n\n/**\n * The rail, from a signer you already have. **This is the preferred form.**\n *\n * It takes an OBJECT THAT SIGNS, never a key: a browser wallet, an ethers\n * `Wallet` built somewhere else, an OWS vault, a KMS client, a queue that asks a\n * human. The key material never enters this package, never enters\n * `uvd-x402-sdk`'s signer, and cannot end up in a stack trace it produces.\n *\n * ```ts\n * import { DescribeClient } from 'uvd-describe-sdk';\n * import { partnerFromSigner } from 'uvd-describe-sdk/partner';\n *\n * // `wallet` is yours — this package never learns how it holds its key.\n * const describe = new DescribeClient({\n * product: 'meshrelay',\n * partner: partnerFromSigner({\n * address: await wallet.getAddress(),\n * signMessage: (base) => wallet.signMessage(base),\n * }),\n * });\n *\n * // Metered route, no payer, no USDC: the free rail carries it.\n * const detail = await describe.walletBreakdown('0x97cd…0996');\n * ```\n *\n * `signMessage` is an EIP-191 `personal_sign` over the string it is handed and\n * must return `0x` + 130 hex. It is the ONE thing this rail cannot do for you.\n */\nexport function partnerFromSigner(\n signer: {\n /** The signing wallet's address. Public by design — the allowlist is public. */\n address: string;\n /** EIP-191 personal_sign over the signature base. */\n signMessage(message: string): string | Promise<string>;\n } & PartnerOptions,\n): PartnerSigner {\n const { address, signMessage, chainId = PARTNER_CHAIN_ID } = signer;\n return {\n address,\n async sign({ method, url }) {\n return plainHeaders(\n await signRequestWithSigner({\n method,\n url,\n address,\n chainId,\n nonce: mintNonce(),\n signMessage,\n }),\n );\n },\n };\n}\n\n/**\n * The rail, from a private key **the environment holds**.\n *\n * ## Why this reads the variable itself instead of taking a string\n *\n * Because a function that takes a key as an argument is a function somebody\n * calls with a literal. Two DAO wallets were drained in minutes by bots\n * scanning public repositories for `0x` + 64 hex (INC-2026-03-30), and \"it was\n * only for a test\" is how both got there. This signature makes the safe path\n * the only path: the key can come from `process.env` and from nowhere else, so\n * there is no argument to paste one into. If your key lives somewhere better —\n * Secrets Manager, a vault, a hardware signer — fetch it there and use\n * {@link partnerFromSigner}, which never sees a key at all.\n *\n * ```ts\n * // DESCRIBE_PARTNER_PRIVATE_KEY is set in the environment. Never in code.\n * const describe = new DescribeClient({\n * product: 'karmakadabra',\n * partner: partnerFromEnv(),\n * });\n * ```\n *\n * Throws immediately — at wiring time, not at the first request — when the\n * variable is unset or malformed. A partner rail that is going to fail should\n * fail before the process claims to be up.\n *\n * ## 🔴 The shape check, and the measurement that put it here\n *\n * The key is trimmed and checked against `^(0x)?[0-9a-fA-F]{64}$` before it\n * reaches the payment SDK, and that is a SECURITY guard, not politeness.\n * Measured 2026-08-30 with `ethers` 6.17.0, the version `uvd-x402-sdk` 2.75.0\n * pulls in:\n *\n * * `new ethers.Wallet('0x'+64hex)` with a **trailing newline** — the single\n * most common way an env var gets malformed, e.g. `KEY=$(cat file)` —\n * throws `invalid BytesLike value (argument=\"value\", value=\"0xabab…ab\\n\")`.\n * **The entire private key is inside the message, verbatim.**\n * * only a well-formed-but-invalid key reaches the redacted path,\n * `invalid private key (argument=\"privateKey\", value=\"[REDACTED]\")`.\n *\n * So the redaction everyone assumes is there covers the second case and not the\n * first, and the first is the likely one. Trimming closes the newline path; the\n * shape check guarantees that whatever reaches `ethers` is exactly 64 hex\n * characters and can therefore only fail into the REDACTED branch. The error\n * this function throws names the variable and the length and never the value.\n *\n * ⚠️ Reported upstream, not patched there by this session: `signRequest` in\n * `uvd-x402-sdk/erc8128` hands its `privateKey` straight to `new\n * ethers.Wallet()` (`signer.ts:255-258`) and has the same exposure for anyone\n * calling it directly. The house rule is that the fix goes upstream; this guard\n * protects THIS path in the meantime and is not a reimplementation of anything.\n */\nexport function partnerFromEnv(\n options: PartnerOptions & {\n /** Which variable holds the key. Defaults to `DESCRIBE_PARTNER_PRIVATE_KEY`. */\n envVar?: string;\n /** Injectable for tests. Defaults to `process.env`. */\n env?: Record<string, string | undefined>;\n } = {},\n): PartnerSigner {\n const { chainId = PARTNER_CHAIN_ID, envVar = PARTNER_KEY_ENV } = options;\n const env = options.env ?? (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;\n\n const raw = env?.[envVar];\n if (typeof raw !== 'string' || raw.trim() === '') {\n throw new Error(\n `partnerFromEnv: ${envVar} is not set. The partner rail signs every ` +\n 'request with a dedicated wallet; without its key this client is an ' +\n 'anonymous client, and an anonymous client pays. Set the variable, or ' +\n 'use partnerFromSigner() with a signer you build yourself.',\n );\n }\n\n // Trimmed on purpose: a private key has no meaningful surrounding\n // whitespace, and the alternative to trimming is the ethers leak above.\n const key = raw.trim();\n if (!/^(0x)?[0-9a-fA-F]{64}$/.test(key)) {\n // Length and nothing else. Never the value, never a prefix of it, never a\n // \"did you mean\" that echoes it back.\n throw new Error(\n `partnerFromEnv: ${envVar} is not a 32-byte hex private key ` +\n `(got ${key.length} characters after trimming; expected 64, or 66 with ` +\n 'the 0x prefix). The value is deliberately not shown.',\n );\n }\n\n // The address is derived by the payment SDK from the key, so we do not know\n // it here without building a wallet ourselves — which would mean importing\n // `ethers` into this package. It stays undefined; error messages lose one\n // detail and this package keeps its dependency list empty.\n return {\n async sign({ method, url }) {\n return plainHeaders(\n await signRequest({ method, url, chainId, nonce: mintNonce(), privateKey: key }),\n );\n },\n };\n}\n\n/**\n * The synthetic key the payment SDK ships in its ERC-8128 conformance vectors,\n * documented there as a key that never held funds.\n *\n * Exported for one reason: so that a consumer's own tests can exercise the\n * partner rail without anybody typing 64 hex characters into a repository. It\n * is read out of the installed package at call time and is not stored anywhere\n * in this one.\n *\n * 🔴 It is PUBLIC and it is in everybody's `node_modules`. Never fund it, never\n * allowlist it, never use it outside a test.\n */\nexport function syntheticTestKey(): string {\n const key = CONFORMANCE_VECTORS_F3_1.frozen.private_key;\n if (!key) throw new Error('the installed uvd-x402-sdk ships no synthetic test key');\n return key;\n}\n\nexport type { PartnerSigner } from '../client';\nexport { PARTNER_CHAIN_ID, PARTNER_KEY_ENV } from '../config';\n"]}
1
+ {"version":3,"sources":["../../src/config.ts","../../src/partner/index.ts"],"names":["signRequestWithSigner","signRequest","CONFORMANCE_VECTORS_F3_1"],"mappings":";;;;;;;AAyHO,IAAM,gBAAA,GAAmB;AAUzB,IAAM,eAAA,GAAkB;;;ACnC/B,SAAS,aAAa,OAAA,EAAyC;AAC7D,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,OAAO,CAAA,EAAG;AACnD,IAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,GAAA,CAAI,IAAI,CAAA,GAAI,KAAA;AAAA,EAC7C;AACA,EAAA,OAAO,GAAA;AACT;AAGA,SAAS,SAAA,GAAoB;AAC3B,EAAA,MAAM,KAAA,GAAQ,IAAI,UAAA,CAAW,EAAE,CAAA;AAG/B,EAAA,UAAA,CAAW,MAAA,CAAO,gBAAgB,KAAK,CAAA;AACvC,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,KAAA,EAAO,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,SAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA;AAC1E;AAuCO,SAAS,kBACd,MAAA,EAMe;AACf,EAAA,MAAM,EAAE,OAAA,EAAS,WAAA,EAAa,OAAA,GAAU,kBAAiB,GAAI,MAAA;AAC7D,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,MAAM,IAAA,CAAK,EAAE,MAAA,EAAQ,KAAI,EAAG;AAC1B,MAAA,OAAO,YAAA;AAAA,QACL,MAAMA,6BAAA,CAAsB;AAAA,UAC1B,MAAA;AAAA,UACA,GAAA;AAAA,UACA,OAAA;AAAA,UACA,OAAA;AAAA,UACA,OAAO,SAAA,EAAU;AAAA,UACjB;AAAA,SACD;AAAA,OACH;AAAA,IACF;AAAA,GACF;AACF;AAsDO,SAAS,cAAA,CACd,OAAA,GAKI,EAAC,EACU;AACf,EAAA,MAAM,EAAE,OAAA,GAAU,gBAAA,EAAkB,MAAA,GAAS,iBAAgB,GAAI,OAAA;AACjE,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,IAAQ,UAAA,CAA0E,OAAA,EAAS,GAAA;AAE/G,EAAA,MAAM,GAAA,GAAM,MAAM,MAAM,CAAA;AACxB,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,CAAI,IAAA,OAAW,EAAA,EAAI;AAChD,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,mBAAmB,MAAM,CAAA,2OAAA;AAAA,KAI3B;AAAA,EACF;AAIA,EAAA,MAAM,GAAA,GAAM,IAAI,IAAA,EAAK;AACrB,EAAA,IAAI,CAAC,wBAAA,CAAyB,IAAA,CAAK,GAAG,CAAA,EAAG;AAGvC,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,gBAAA,EAAmB,MAAM,CAAA,uCAAA,EACf,GAAA,CAAI,MAAM,CAAA,wGAAA;AAAA,KAEtB;AAAA,EACF;AAMA,EAAA,OAAO;AAAA,IACL,MAAM,IAAA,CAAK,EAAE,MAAA,EAAQ,KAAI,EAAG;AAC1B,MAAA,OAAO,YAAA;AAAA,QACL,MAAMC,mBAAA,CAAY,EAAE,MAAA,EAAQ,GAAA,EAAK,OAAA,EAAS,KAAA,EAAO,SAAA,EAAU,EAAG,UAAA,EAAY,GAAA,EAAK;AAAA,OACjF;AAAA,IACF;AAAA,GACF;AACF;AAcO,SAAS,gBAAA,GAA2B;AACzC,EAAA,MAAM,GAAA,GAAMC,iCAAyB,MAAA,CAAO,WAAA;AAC5C,EAAA,IAAI,CAAC,GAAA,EAAK,MAAM,IAAI,MAAM,wDAAwD,CAAA;AAClF,EAAA,OAAO,GAAA;AACT","file":"index.js","sourcesContent":["/**\n * The only place this package defines a calibrable value.\n *\n * House rule (decisión de Saul, 2026-08-26, born from a measured case in\n * describe.net: one threshold written with TWO DIFFERENT VALUES across four\n * surfaces, and the one charged was not the one the site promised). Nothing\n * else in this package re-types these numbers — modules import them.\n *\n * What does NOT live here, by the same rule: anything that moves a score or a\n * price. This SDK computes neither, so the list is short: `POLICY_VERSION` and\n * the prices are the server's and travel in its responses. We never type a\n * price. See `errors.ts` for what we do with a 402 challenge instead.\n */\n\n/** Where the index answers. Overridable per client for a staging deploy. */\nexport const DEFAULT_BASE_URL = 'https://api.describe.net';\n\n/** Where a human reads the same wallet. Never fetched — only linked. */\nexport const DEFAULT_SITE_URL = 'https://describe.net';\n\n/**\n * 30 s, and the number is not taste — it is the one number of the three live\n * consumers that came with its measurement written down (EM `client.py:19-23`,\n * INC-2026-08-19):\n *\n * * the provider's Lambda cold start was measured at **15,2 s**, so anything\n * under it turns a cold index into a fake outage. An 8 s timeout already\n * broke a real integration once.\n * * its API Gateway integration ceiling is **29 s**, so waiting past 30 buys\n * nothing the gateway will ever deliver.\n * * it is deliberately DISTINCT from the Facilitator's 45 s so two clocks can\n * never expire in the same second and produce an error nobody can attribute.\n *\n * Measured across the ecosystem on 2026-08-30: EM 30 s, MeshRelay 30 000 ms,\n * KarmaKadabra 25 s. Two of three already sit here.\n */\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\n/**\n * 400 ms, **on by default**, and the default is the decision — so here is the\n * argument, because it is the one thing about this package that spends the\n * caller's latency without being asked.\n *\n * The number is not ours: it is what **KarmaKadabra** sleeps before every read\n * (`random.uniform(0, 0.4)`), contributed on 2026-08-30 with the measurement\n * that produced it — *\"27 agentes despiertan al MISMO tiempo por EventBridge y\n * pegan simultáneo contra su límite de rps COMPARTIDO con los otros\n * consumidores. Sin jitter, un enjambre es un DDoS educado.\"* They run the\n * largest fleet against this index, so their calibration beats our taste.\n *\n * ## Why ON, when a library that sleeps unasked is a surprise\n *\n * The surprise is real and it is the honest objection. Three things outweigh it:\n *\n * 1. **The cost of the mistake does not land on whoever makes it.** The rate\n * limit is shared with no per-partner bucket (see `userAgent` below), so an\n * unjittered swarm is paid for by the OTHER consumer, who gets the 429 and\n * has no lever to fix it. When the cost of a default falls on someone who\n * cannot change it, the default has to be the safe one.\n * 2. **Opt-out is discoverable; opt-in is not.** `jitterMs: 0` is one field\n * away and typed. The other direction cannot be found by reading your own\n * code: you learn you needed jitter from someone else's incident, and by\n * then you have already spent their budget. KarmaKadabra's own framing —\n * whoever writes a single script never finds out the problem exists until\n * they have a fleet.\n * 3. **It is bounded and small against this package's own numbers.** At most\n * 400 ms, 200 ms on average, against a 30 000 ms timeout and a provider\n * cold start measured at 15,2 s. And it is the same shape of default this\n * client already ships: `failOpen: true` also changes behaviour without\n * being asked, for the same reason — the safe thing, loudly documented,\n * with one field to turn it off.\n *\n * ## What is NOT written here, on purpose\n *\n * The rate limit itself. KarmaKadabra's own note cited 20 rps, which was the\n * documentation's figure and is now stale (it is 50 sustained / burst 40 since\n * 2026-08-28). A number that has already gone stale once in one hop between two\n * teams does not belong in a constant: **the `RateLimit-Policy` response header\n * is the authority**, and this value is calibrated against a fleet size, not\n * against a ceiling. See the correction in `userAgent`.\n */\nexport const DEFAULT_JITTER_MS = 400;\n\n/**\n * The treasury this SDK will pay, and NOTHING else.\n *\n * Read live from the 402 challenge of `GET /reputation/wallet/{w}` on\n * 2026-08-30 (`recipient`, and `payTo` on all six `accepts[]` entries — base,\n * avalanche, arbitrum, optimism, polygon, celo — identical on every one).\n *\n * Pinning it is the point: an x402 challenge is fetched over the network and\n * names its own recipient, so a client that pays whatever `payTo` arrives will\n * happily pay an attacker who can answer as the API. A challenge whose `payTo`\n * is not this address is `DO_NOT_PAY` — never a retry, never a warning that a\n * caller can ignore.\n *\n * 🔴 THE FAILURE MODE OF PINNING, written down because it will happen: if\n * describe.net rotates its treasury, every published version of this SDK stops\n * paying until it is republished. That is the SAFE direction of the failure\n * (refusing to pay a stranger beats paying one), and the escape hatch is\n * `expectedPayTo` in the client config — a caller who has verified the new\n * address out of band can move without waiting for us.\n */\nexport const TREASURY_EVM = '0xe4dc963c56979E0260fc146b87eE24F18220e545';\n\n/**\n * The chain id that goes in the ERC-8128 keyid of a partner signature.\n *\n * 8453 (Base). Not a preference — it is what the gate accepts:\n * `describe-net/describenet/partner.py:90` sets `CHAIN_ID = 8453` and passes it\n * as the ONLY member of `allowed_chain_ids`, with its own comment explaining\n * that `None` (accept any chain) would be \"innecesariamente laxo para una\n * allowlist de tres servicios propios\". Read 2026-08-30.\n *\n * The payment SDK's own default happens to be 8453 too, and this constant\n * deliberately does not lean on that: this value belongs to describe.net's\n * policy, not to the signer's convenience, and the day one moves the other must\n * not follow by accident. Measured failure mode of getting it wrong: the gate\n * answers `chain_not_allowed` and the route charges — loud, since partner mode\n * throws `DescribePartnerRejected` instead of paying.\n */\nexport const PARTNER_CHAIN_ID = 8453;\n\n/**\n * The environment variable `partnerFromEnv()` reads the signing key from.\n *\n * A variable name is not a secret; the value it holds is. Naming it here means\n * a consumer can grep for it, a deploy manifest can set it, and nobody has to\n * guess — while `partnerFromEnv()` staying the ONLY reader means the key has\n * exactly one path into this package.\n */\nexport const PARTNER_KEY_ENV = 'DESCRIBE_PARTNER_PRIVATE_KEY';\n\n/**\n * The package version, for the `User-Agent`.\n *\n * MeshRelay reads its version from `package.json` at runtime because \"a\n * User-Agent that lies about the version is worse than none\"\n * (`describenet.js:39`). It can afford the `readFileSync`: it is a server, not\n * a bundled library. We cannot — a library that reads its own manifest at\n * runtime either bundles `package.json` into the artifact or breaks in a\n * browser, and this package has to run in a browser.\n *\n * So the constant is typed here and `config.test.ts` asserts it equals\n * `package.json`'s `version`. Same guarantee (the UA cannot lie), paid at test\n * time instead of at runtime. Bumping the version without the constant is a\n * red test, not a silent lie in someone's access log.\n */\nexport const SDK_VERSION = '0.3.0';\n\n/** `uvd-describe-sdk-ts/0.1.0`, plus `(+<product>)` when the caller names itself. */\nexport const SDK_NAME = 'uvd-describe-sdk-ts';\n\n/**\n * Build the `User-Agent`.\n *\n * The provider's rate limit is **shared by every consumer with no per-partner\n * bucket**, so identifying ourselves is the only thing that makes our share of\n * it attributable at all. That is why the UA is on by default and `product` is\n * the one field a caller should bother to fill.\n *\n * ⚠️ CORRECTION 2026-08-30, left written rather than swapped: this comment\n * first said \"20 rps\", copied from `meshrelay/describenet.js:19-20`. The live\n * OpenAPI says **50 requests/second sustained, bursts up to 40**, at the API\n * Gateway edge, and it also says where the truth lives: *\"Every response\n * carries the policy as a header, `RateLimit-Policy: 50;w=1;burst=40` … and\n * **that header is the authority**\"*. So neither number belongs in this file —\n * read the header. Cached free routes (`/health`, `/pricing`, `/leaderboard`,\n * `/stats/*`) are served by CloudFront and do not consume the budget on a hit.\n * The 20 was probably right when MeshRelay wrote it; a dated figure does not\n * stop being stale, it only stops being a lie.\n *\n * ⚠️ It is attribution, not authentication. describe.net has no accounts and\n * no API keys — \"el pago es la autenticación\" — so anyone can send any UA.\n * Never treat this string as identity, on either side.\n */\nexport function userAgent(product?: string): string {\n const base = `${SDK_NAME}/${SDK_VERSION}`;\n const trimmed = (product ?? '').trim();\n return trimmed ? `${base} (+${trimmed})` : base;\n}\n","/**\n * The partner rail — how a product of the house reads describe.net for free.\n *\n * ## What this is, in one paragraph\n *\n * describe.net has no accounts and no API keys, on purpose: *\"el pago es la\n * autenticación\"*. So when Execution Market, MeshRelay and KarmaKadabra\n * deprecated their local reputation maths and became read-dependencies of the\n * index (2026-08-28), the question \"does a service of the house pay like a\n * stranger?\" could not be answered with a token. It was answered with an\n * ALLOWLIST OF PUBLIC ADDRESSES plus a per-request ERC-8128 signature\n * (`describe-net/describenet/partner.py`). The partner holds a dedicated wallet\n * with no funds whose only job is to sign; describe.net holds a list of\n * addresses. **The service custodies no secret of ours** — a breach there leaks\n * a list of things that were already public — and that property, not\n * convenience, is why this is a signature and not the `X-API-Key` everyone\n * reaches for first.\n *\n * This module is the client half. It is the only file in this package with a\n * RUNTIME import of `uvd-x402-sdk`, which is why it lives behind the\n * `uvd-describe-sdk/partner` subpath: the main entry and the `x402` entry keep\n * their zero-runtime-imports property, and a consumer who never signs installs\n * nothing.\n *\n * ## Upstream-first: the primitive already existed, MEASURED before writing\n *\n * `uvd-x402-sdk` 2.75.0 (installed, checked 2026-08-30) exports the whole\n * ERC-8128 signer from `uvd-x402-sdk/erc8128` — `signRequest`,\n * `signRequestWithSigner`, `signRequestWithWallet`, plus the pure base builder\n * and the verifier. So NOTHING is signed in this repo: this file picks a chain\n * id and a nonce and forwards. Not one byte of RFC 9421 canonicalisation is\n * reimplemented here, and if any of it ever needs to change, it changes THERE.\n *\n * Verified end to end, offline, on 2026-08-30: headers produced by\n * `signRequestWithSigner` at chain 8453 verify under the EXACT policy\n * `partner.py` builds (authority `api.describe.net`, `allowed_chain_ids=[8453]`,\n * `max_validity_sec=300`, `clock_skew_future_sec=30`), recovering the signer's\n * address. `partner.test.ts` is that probe, kept as a test.\n *\n * ## The nonce: minted here, and here is the argument\n *\n * The payment SDK requires a nonce and refuses to invent one — *\"a local nonce\n * authenticates against a first-use-wins store and is rejected by an\n * issuer-bound one, which turns a server blip into an auth mystery\"*\n * (`erc8128/signer.ts:15-17`). That reasoning is about servers that HAVE a nonce\n * store. describe.net has none: `PartnerGate` builds its `VerifyPolicy` with no\n * `nonce` field at all (`partner.py:216-223`), and the verifier skips every\n * nonce rule when `policy.nonce is None` — no presence check\n * (`verifier.py:458-462`), no consumption (`verifier.py:304`). Read in the\n * installed PyPI `uvd-x402-sdk` 0.70.0 on 2026-08-30.\n *\n * So there is no store to be unknown to, and a locally minted random nonce is\n * strictly better than the alternative the policy would also accept (none at\n * all): it makes each signature unique, so two identical GETs in the same second\n * do not produce byte-identical headers. This is the caller owning the\n * consequence, which is exactly what `onNonceUnavailable` exists to express in\n * the payment SDK — stated here rather than hidden.\n *\n * 🔴 If describe.net ever adds a nonce store, this line becomes wrong and the\n * failure is loud, not silent: every partner request starts answering 402 with\n * `nonce_unknown` and `DescribePartnerRejected` says so. That is the direction\n * this failure should point.\n *\n * ## What is signed, and the consequence of a custom `baseUrl`\n *\n * The signature covers `@method`, `@authority` and `@path` (plus `@query` when\n * there is one), and `@authority` comes from the URL being requested. The gate\n * pins `api.describe.net` and NEVER derives it from a header (`partner.py:73-84`\n * — deriving an authority from client-controlled input is how a verifier was\n * once made to rebuild a base over an attacker's domain). So a client pointed at\n * any other origin — a staging host, a proxy, the raw execute-api host behind\n * CloudFront — signs an authority the gate does not accept and is charged. That\n * is deliberate on both sides, and it fails LOUDLY here as\n * `DescribePartnerRejected` rather than quietly as a bill.\n */\n\nimport {\n CONFORMANCE_VECTORS_F3_1,\n signRequest,\n signRequestWithSigner,\n} from 'uvd-x402-sdk/erc8128';\n\nimport type { PartnerSigner } from '../client';\nimport { PARTNER_CHAIN_ID, PARTNER_KEY_ENV } from '../config';\n\n/**\n * The signer's typed header object as a plain `Record<string, string>`.\n *\n * Not cosmetic: `Erc8128Headers` declares `'Content-Digest'?: string`, and an\n * interface with an optional member is not assignable to `Record<string,\n * string>` — the dts build says so, loudly (TS2322 at the return, TS2345 at the\n * parameter, which is why the parameter is `object` and not a `Record` of its\n * own). Dropping the undefined entries here is the honest conversion, and it\n * means the client never merges a header whose value is `undefined` into a\n * `fetch` call, which is how a literal `\"undefined\"` ends up on a wire.\n */\nfunction plainHeaders(headers: object): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) {\n if (typeof value === 'string') out[name] = value;\n }\n return out;\n}\n\n/** A 128-bit hex nonce. See the module header for why this is minted locally. */\nfunction mintNonce(): string {\n const bytes = new Uint8Array(16);\n // `globalThis.crypto` is standard in Node >= 18 and in every browser, which\n // is the same floor as this package's `engines`. No import, no polyfill.\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/** What every factory here accepts. Both fields have defaults that are right. */\nexport interface PartnerOptions {\n /**\n * The keyid's chain id. Defaults to `PARTNER_CHAIN_ID` (8453, Base), which is\n * what the gate pins. Override only if describe.net's `CHAIN_ID` moves.\n */\n chainId?: number;\n}\n\n/**\n * The rail, from a signer you already have. **This is the preferred form.**\n *\n * It takes an OBJECT THAT SIGNS, never a key: a browser wallet, an ethers\n * `Wallet` built somewhere else, an OWS vault, a KMS client, a queue that asks a\n * human. The key material never enters this package, never enters\n * `uvd-x402-sdk`'s signer, and cannot end up in a stack trace it produces.\n *\n * ```ts\n * import { DescribeClient } from 'uvd-describe-sdk';\n * import { partnerFromSigner } from 'uvd-describe-sdk/partner';\n *\n * // `wallet` is yours — this package never learns how it holds its key.\n * const describe = new DescribeClient({\n * product: 'meshrelay',\n * partner: partnerFromSigner({\n * address: await wallet.getAddress(),\n * signMessage: (base) => wallet.signMessage(base),\n * }),\n * });\n *\n * // Metered route, no payer, no USDC: the free rail carries it.\n * const detail = await describe.walletBreakdown('0x97cd…0996');\n * ```\n *\n * `signMessage` is an EIP-191 `personal_sign` over the string it is handed and\n * must return `0x` + 130 hex. It is the ONE thing this rail cannot do for you.\n */\nexport function partnerFromSigner(\n signer: {\n /** The signing wallet's address. Public by design — the allowlist is public. */\n address: string;\n /** EIP-191 personal_sign over the signature base. */\n signMessage(message: string): string | Promise<string>;\n } & PartnerOptions,\n): PartnerSigner {\n const { address, signMessage, chainId = PARTNER_CHAIN_ID } = signer;\n return {\n address,\n async sign({ method, url }) {\n return plainHeaders(\n await signRequestWithSigner({\n method,\n url,\n address,\n chainId,\n nonce: mintNonce(),\n signMessage,\n }),\n );\n },\n };\n}\n\n/**\n * The rail, from a private key **the environment holds**.\n *\n * ## Why this reads the variable itself instead of taking a string\n *\n * Because a function that takes a key as an argument is a function somebody\n * calls with a literal. Two DAO wallets were drained in minutes by bots\n * scanning public repositories for `0x` + 64 hex (INC-2026-03-30), and \"it was\n * only for a test\" is how both got there. This signature makes the safe path\n * the only path: the key can come from `process.env` and from nowhere else, so\n * there is no argument to paste one into. If your key lives somewhere better —\n * Secrets Manager, a vault, a hardware signer — fetch it there and use\n * {@link partnerFromSigner}, which never sees a key at all.\n *\n * ```ts\n * // DESCRIBE_PARTNER_PRIVATE_KEY is set in the environment. Never in code.\n * const describe = new DescribeClient({\n * product: 'karmakadabra',\n * partner: partnerFromEnv(),\n * });\n * ```\n *\n * Throws immediately — at wiring time, not at the first request — when the\n * variable is unset or malformed. A partner rail that is going to fail should\n * fail before the process claims to be up.\n *\n * ## 🔴 The shape check, and the measurement that put it here\n *\n * The key is trimmed and checked against `^(0x)?[0-9a-fA-F]{64}$` before it\n * reaches the payment SDK, and that is a SECURITY guard, not politeness.\n * Measured 2026-08-30 with `ethers` 6.17.0, the version `uvd-x402-sdk` 2.75.0\n * pulls in:\n *\n * * `new ethers.Wallet('0x'+64hex)` with a **trailing newline** — the single\n * most common way an env var gets malformed, e.g. `KEY=$(cat file)` —\n * throws `invalid BytesLike value (argument=\"value\", value=\"0xabab…ab\\n\")`.\n * **The entire private key is inside the message, verbatim.**\n * * only a well-formed-but-invalid key reaches the redacted path,\n * `invalid private key (argument=\"privateKey\", value=\"[REDACTED]\")`.\n *\n * So the redaction everyone assumes is there covers the second case and not the\n * first, and the first is the likely one. Trimming closes the newline path; the\n * shape check guarantees that whatever reaches `ethers` is exactly 64 hex\n * characters and can therefore only fail into the REDACTED branch. The error\n * this function throws names the variable and the length and never the value.\n *\n * ⚠️ Reported upstream, not patched there by this session: `signRequest` in\n * `uvd-x402-sdk/erc8128` hands its `privateKey` straight to `new\n * ethers.Wallet()` (`signer.ts:255-258`) and has the same exposure for anyone\n * calling it directly. The house rule is that the fix goes upstream; this guard\n * protects THIS path in the meantime and is not a reimplementation of anything.\n */\nexport function partnerFromEnv(\n options: PartnerOptions & {\n /** Which variable holds the key. Defaults to `DESCRIBE_PARTNER_PRIVATE_KEY`. */\n envVar?: string;\n /** Injectable for tests. Defaults to `process.env`. */\n env?: Record<string, string | undefined>;\n } = {},\n): PartnerSigner {\n const { chainId = PARTNER_CHAIN_ID, envVar = PARTNER_KEY_ENV } = options;\n const env = options.env ?? (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;\n\n const raw = env?.[envVar];\n if (typeof raw !== 'string' || raw.trim() === '') {\n throw new Error(\n `partnerFromEnv: ${envVar} is not set. The partner rail signs every ` +\n 'request with a dedicated wallet; without its key this client is an ' +\n 'anonymous client, and an anonymous client pays. Set the variable, or ' +\n 'use partnerFromSigner() with a signer you build yourself.',\n );\n }\n\n // Trimmed on purpose: a private key has no meaningful surrounding\n // whitespace, and the alternative to trimming is the ethers leak above.\n const key = raw.trim();\n if (!/^(0x)?[0-9a-fA-F]{64}$/.test(key)) {\n // Length and nothing else. Never the value, never a prefix of it, never a\n // \"did you mean\" that echoes it back.\n throw new Error(\n `partnerFromEnv: ${envVar} is not a 32-byte hex private key ` +\n `(got ${key.length} characters after trimming; expected 64, or 66 with ` +\n 'the 0x prefix). The value is deliberately not shown.',\n );\n }\n\n // The address is derived by the payment SDK from the key, so we do not know\n // it here without building a wallet ourselves — which would mean importing\n // `ethers` into this package. It stays undefined; error messages lose one\n // detail and this package keeps its dependency list empty.\n return {\n async sign({ method, url }) {\n return plainHeaders(\n await signRequest({ method, url, chainId, nonce: mintNonce(), privateKey: key }),\n );\n },\n };\n}\n\n/**\n * The synthetic key the payment SDK ships in its ERC-8128 conformance vectors,\n * documented there as a key that never held funds.\n *\n * Exported for one reason: so that a consumer's own tests can exercise the\n * partner rail without anybody typing 64 hex characters into a repository. It\n * is read out of the installed package at call time and is not stored anywhere\n * in this one.\n *\n * 🔴 It is PUBLIC and it is in everybody's `node_modules`. Never fund it, never\n * allowlist it, never use it outside a test.\n */\nexport function syntheticTestKey(): string {\n const key = CONFORMANCE_VECTORS_F3_1.frozen.private_key;\n if (!key) throw new Error('the installed uvd-x402-sdk ships no synthetic test key');\n return key;\n}\n\nexport type { PartnerSigner } from '../client';\nexport { PARTNER_CHAIN_ID, PARTNER_KEY_ENV } from '../config';\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config.ts","../../src/partner/index.ts"],"names":[],"mappings":";;;;;AAyHO,IAAM,gBAAA,GAAmB;AAUzB,IAAM,eAAA,GAAkB;;;ACnC/B,SAAS,aAAa,OAAA,EAAyC;AAC7D,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,OAAO,CAAA,EAAG;AACnD,IAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,GAAA,CAAI,IAAI,CAAA,GAAI,KAAA;AAAA,EAC7C;AACA,EAAA,OAAO,GAAA;AACT;AAGA,SAAS,SAAA,GAAoB;AAC3B,EAAA,MAAM,KAAA,GAAQ,IAAI,UAAA,CAAW,EAAE,CAAA;AAG/B,EAAA,UAAA,CAAW,MAAA,CAAO,gBAAgB,KAAK,CAAA;AACvC,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,KAAA,EAAO,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,SAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA;AAC1E;AAuCO,SAAS,kBACd,MAAA,EAMe;AACf,EAAA,MAAM,EAAE,OAAA,EAAS,WAAA,EAAa,OAAA,GAAU,kBAAiB,GAAI,MAAA;AAC7D,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,MAAM,IAAA,CAAK,EAAE,MAAA,EAAQ,KAAI,EAAG;AAC1B,MAAA,OAAO,YAAA;AAAA,QACL,MAAM,qBAAA,CAAsB;AAAA,UAC1B,MAAA;AAAA,UACA,GAAA;AAAA,UACA,OAAA;AAAA,UACA,OAAA;AAAA,UACA,OAAO,SAAA,EAAU;AAAA,UACjB;AAAA,SACD;AAAA,OACH;AAAA,IACF;AAAA,GACF;AACF;AAsDO,SAAS,cAAA,CACd,OAAA,GAKI,EAAC,EACU;AACf,EAAA,MAAM,EAAE,OAAA,GAAU,gBAAA,EAAkB,MAAA,GAAS,iBAAgB,GAAI,OAAA;AACjE,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,IAAQ,UAAA,CAA0E,OAAA,EAAS,GAAA;AAE/G,EAAA,MAAM,GAAA,GAAM,MAAM,MAAM,CAAA;AACxB,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,CAAI,IAAA,OAAW,EAAA,EAAI;AAChD,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,mBAAmB,MAAM,CAAA,2OAAA;AAAA,KAI3B;AAAA,EACF;AAIA,EAAA,MAAM,GAAA,GAAM,IAAI,IAAA,EAAK;AACrB,EAAA,IAAI,CAAC,wBAAA,CAAyB,IAAA,CAAK,GAAG,CAAA,EAAG;AAGvC,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,gBAAA,EAAmB,MAAM,CAAA,uCAAA,EACf,GAAA,CAAI,MAAM,CAAA,wGAAA;AAAA,KAEtB;AAAA,EACF;AAMA,EAAA,OAAO;AAAA,IACL,MAAM,IAAA,CAAK,EAAE,MAAA,EAAQ,KAAI,EAAG;AAC1B,MAAA,OAAO,YAAA;AAAA,QACL,MAAM,WAAA,CAAY,EAAE,MAAA,EAAQ,GAAA,EAAK,OAAA,EAAS,KAAA,EAAO,SAAA,EAAU,EAAG,UAAA,EAAY,GAAA,EAAK;AAAA,OACjF;AAAA,IACF;AAAA,GACF;AACF;AAcO,SAAS,gBAAA,GAA2B;AACzC,EAAA,MAAM,GAAA,GAAM,yBAAyB,MAAA,CAAO,WAAA;AAC5C,EAAA,IAAI,CAAC,GAAA,EAAK,MAAM,IAAI,MAAM,wDAAwD,CAAA;AAClF,EAAA,OAAO,GAAA;AACT","file":"index.mjs","sourcesContent":["/**\n * The only place this package defines a calibrable value.\n *\n * House rule (decisión de Saul, 2026-08-26, born from a measured case in\n * describe.net: one threshold written with TWO DIFFERENT VALUES across four\n * surfaces, and the one charged was not the one the site promised). Nothing\n * else in this package re-types these numbers — modules import them.\n *\n * What does NOT live here, by the same rule: anything that moves a score or a\n * price. This SDK computes neither, so the list is short: `POLICY_VERSION` and\n * the prices are the server's and travel in its responses. We never type a\n * price. See `errors.ts` for what we do with a 402 challenge instead.\n */\n\n/** Where the index answers. Overridable per client for a staging deploy. */\nexport const DEFAULT_BASE_URL = 'https://api.describe.net';\n\n/** Where a human reads the same wallet. Never fetched — only linked. */\nexport const DEFAULT_SITE_URL = 'https://describe.net';\n\n/**\n * 30 s, and the number is not taste — it is the one number of the three live\n * consumers that came with its measurement written down (EM `client.py:19-23`,\n * INC-2026-08-19):\n *\n * * the provider's Lambda cold start was measured at **15,2 s**, so anything\n * under it turns a cold index into a fake outage. An 8 s timeout already\n * broke a real integration once.\n * * its API Gateway integration ceiling is **29 s**, so waiting past 30 buys\n * nothing the gateway will ever deliver.\n * * it is deliberately DISTINCT from the Facilitator's 45 s so two clocks can\n * never expire in the same second and produce an error nobody can attribute.\n *\n * Measured across the ecosystem on 2026-08-30: EM 30 s, MeshRelay 30 000 ms,\n * KarmaKadabra 25 s. Two of three already sit here.\n */\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\n/**\n * 400 ms, **on by default**, and the default is the decision — so here is the\n * argument, because it is the one thing about this package that spends the\n * caller's latency without being asked.\n *\n * The number is not ours: it is what **KarmaKadabra** sleeps before every read\n * (`random.uniform(0, 0.4)`), contributed on 2026-08-30 with the measurement\n * that produced it — *\"27 agentes despiertan al MISMO tiempo por EventBridge y\n * pegan simultáneo contra su límite de rps COMPARTIDO con los otros\n * consumidores. Sin jitter, un enjambre es un DDoS educado.\"* They run the\n * largest fleet against this index, so their calibration beats our taste.\n *\n * ## Why ON, when a library that sleeps unasked is a surprise\n *\n * The surprise is real and it is the honest objection. Three things outweigh it:\n *\n * 1. **The cost of the mistake does not land on whoever makes it.** The rate\n * limit is shared with no per-partner bucket (see `userAgent` below), so an\n * unjittered swarm is paid for by the OTHER consumer, who gets the 429 and\n * has no lever to fix it. When the cost of a default falls on someone who\n * cannot change it, the default has to be the safe one.\n * 2. **Opt-out is discoverable; opt-in is not.** `jitterMs: 0` is one field\n * away and typed. The other direction cannot be found by reading your own\n * code: you learn you needed jitter from someone else's incident, and by\n * then you have already spent their budget. KarmaKadabra's own framing —\n * whoever writes a single script never finds out the problem exists until\n * they have a fleet.\n * 3. **It is bounded and small against this package's own numbers.** At most\n * 400 ms, 200 ms on average, against a 30 000 ms timeout and a provider\n * cold start measured at 15,2 s. And it is the same shape of default this\n * client already ships: `failOpen: true` also changes behaviour without\n * being asked, for the same reason — the safe thing, loudly documented,\n * with one field to turn it off.\n *\n * ## What is NOT written here, on purpose\n *\n * The rate limit itself. KarmaKadabra's own note cited 20 rps, which was the\n * documentation's figure and is now stale (it is 50 sustained / burst 40 since\n * 2026-08-28). A number that has already gone stale once in one hop between two\n * teams does not belong in a constant: **the `RateLimit-Policy` response header\n * is the authority**, and this value is calibrated against a fleet size, not\n * against a ceiling. See the correction in `userAgent`.\n */\nexport const DEFAULT_JITTER_MS = 400;\n\n/**\n * The treasury this SDK will pay, and NOTHING else.\n *\n * Read live from the 402 challenge of `GET /reputation/wallet/{w}` on\n * 2026-08-30 (`recipient`, and `payTo` on all six `accepts[]` entries — base,\n * avalanche, arbitrum, optimism, polygon, celo — identical on every one).\n *\n * Pinning it is the point: an x402 challenge is fetched over the network and\n * names its own recipient, so a client that pays whatever `payTo` arrives will\n * happily pay an attacker who can answer as the API. A challenge whose `payTo`\n * is not this address is `DO_NOT_PAY` — never a retry, never a warning that a\n * caller can ignore.\n *\n * 🔴 THE FAILURE MODE OF PINNING, written down because it will happen: if\n * describe.net rotates its treasury, every published version of this SDK stops\n * paying until it is republished. That is the SAFE direction of the failure\n * (refusing to pay a stranger beats paying one), and the escape hatch is\n * `expectedPayTo` in the client config — a caller who has verified the new\n * address out of band can move without waiting for us.\n */\nexport const TREASURY_EVM = '0xe4dc963c56979E0260fc146b87eE24F18220e545';\n\n/**\n * The chain id that goes in the ERC-8128 keyid of a partner signature.\n *\n * 8453 (Base). Not a preference — it is what the gate accepts:\n * `describe-net/describenet/partner.py:90` sets `CHAIN_ID = 8453` and passes it\n * as the ONLY member of `allowed_chain_ids`, with its own comment explaining\n * that `None` (accept any chain) would be \"innecesariamente laxo para una\n * allowlist de tres servicios propios\". Read 2026-08-30.\n *\n * The payment SDK's own default happens to be 8453 too, and this constant\n * deliberately does not lean on that: this value belongs to describe.net's\n * policy, not to the signer's convenience, and the day one moves the other must\n * not follow by accident. Measured failure mode of getting it wrong: the gate\n * answers `chain_not_allowed` and the route charges — loud, since partner mode\n * throws `DescribePartnerRejected` instead of paying.\n */\nexport const PARTNER_CHAIN_ID = 8453;\n\n/**\n * The environment variable `partnerFromEnv()` reads the signing key from.\n *\n * A variable name is not a secret; the value it holds is. Naming it here means\n * a consumer can grep for it, a deploy manifest can set it, and nobody has to\n * guess — while `partnerFromEnv()` staying the ONLY reader means the key has\n * exactly one path into this package.\n */\nexport const PARTNER_KEY_ENV = 'DESCRIBE_PARTNER_PRIVATE_KEY';\n\n/**\n * The package version, for the `User-Agent`.\n *\n * MeshRelay reads its version from `package.json` at runtime because \"a\n * User-Agent that lies about the version is worse than none\"\n * (`describenet.js:39`). It can afford the `readFileSync`: it is a server, not\n * a bundled library. We cannot — a library that reads its own manifest at\n * runtime either bundles `package.json` into the artifact or breaks in a\n * browser, and this package has to run in a browser.\n *\n * So the constant is typed here and `config.test.ts` asserts it equals\n * `package.json`'s `version`. Same guarantee (the UA cannot lie), paid at test\n * time instead of at runtime. Bumping the version without the constant is a\n * red test, not a silent lie in someone's access log.\n */\nexport const SDK_VERSION = '0.2.0';\n\n/** `uvd-describe-sdk-ts/0.1.0`, plus `(+<product>)` when the caller names itself. */\nexport const SDK_NAME = 'uvd-describe-sdk-ts';\n\n/**\n * Build the `User-Agent`.\n *\n * The provider's rate limit is **shared by every consumer with no per-partner\n * bucket**, so identifying ourselves is the only thing that makes our share of\n * it attributable at all. That is why the UA is on by default and `product` is\n * the one field a caller should bother to fill.\n *\n * ⚠️ CORRECTION 2026-08-30, left written rather than swapped: this comment\n * first said \"20 rps\", copied from `meshrelay/describenet.js:19-20`. The live\n * OpenAPI says **50 requests/second sustained, bursts up to 40**, at the API\n * Gateway edge, and it also says where the truth lives: *\"Every response\n * carries the policy as a header, `RateLimit-Policy: 50;w=1;burst=40` … and\n * **that header is the authority**\"*. So neither number belongs in this file —\n * read the header. Cached free routes (`/health`, `/pricing`, `/leaderboard`,\n * `/stats/*`) are served by CloudFront and do not consume the budget on a hit.\n * The 20 was probably right when MeshRelay wrote it; a dated figure does not\n * stop being stale, it only stops being a lie.\n *\n * ⚠️ It is attribution, not authentication. describe.net has no accounts and\n * no API keys — \"el pago es la autenticación\" — so anyone can send any UA.\n * Never treat this string as identity, on either side.\n */\nexport function userAgent(product?: string): string {\n const base = `${SDK_NAME}/${SDK_VERSION}`;\n const trimmed = (product ?? '').trim();\n return trimmed ? `${base} (+${trimmed})` : base;\n}\n","/**\n * The partner rail — how a product of the house reads describe.net for free.\n *\n * ## What this is, in one paragraph\n *\n * describe.net has no accounts and no API keys, on purpose: *\"el pago es la\n * autenticación\"*. So when Execution Market, MeshRelay and KarmaKadabra\n * deprecated their local reputation maths and became read-dependencies of the\n * index (2026-08-28), the question \"does a service of the house pay like a\n * stranger?\" could not be answered with a token. It was answered with an\n * ALLOWLIST OF PUBLIC ADDRESSES plus a per-request ERC-8128 signature\n * (`describe-net/describenet/partner.py`). The partner holds a dedicated wallet\n * with no funds whose only job is to sign; describe.net holds a list of\n * addresses. **The service custodies no secret of ours** — a breach there leaks\n * a list of things that were already public — and that property, not\n * convenience, is why this is a signature and not the `X-API-Key` everyone\n * reaches for first.\n *\n * This module is the client half. It is the only file in this package with a\n * RUNTIME import of `uvd-x402-sdk`, which is why it lives behind the\n * `uvd-describe-sdk/partner` subpath: the main entry and the `x402` entry keep\n * their zero-runtime-imports property, and a consumer who never signs installs\n * nothing.\n *\n * ## Upstream-first: the primitive already existed, MEASURED before writing\n *\n * `uvd-x402-sdk` 2.75.0 (installed, checked 2026-08-30) exports the whole\n * ERC-8128 signer from `uvd-x402-sdk/erc8128` — `signRequest`,\n * `signRequestWithSigner`, `signRequestWithWallet`, plus the pure base builder\n * and the verifier. So NOTHING is signed in this repo: this file picks a chain\n * id and a nonce and forwards. Not one byte of RFC 9421 canonicalisation is\n * reimplemented here, and if any of it ever needs to change, it changes THERE.\n *\n * Verified end to end, offline, on 2026-08-30: headers produced by\n * `signRequestWithSigner` at chain 8453 verify under the EXACT policy\n * `partner.py` builds (authority `api.describe.net`, `allowed_chain_ids=[8453]`,\n * `max_validity_sec=300`, `clock_skew_future_sec=30`), recovering the signer's\n * address. `partner.test.ts` is that probe, kept as a test.\n *\n * ## The nonce: minted here, and here is the argument\n *\n * The payment SDK requires a nonce and refuses to invent one — *\"a local nonce\n * authenticates against a first-use-wins store and is rejected by an\n * issuer-bound one, which turns a server blip into an auth mystery\"*\n * (`erc8128/signer.ts:15-17`). That reasoning is about servers that HAVE a nonce\n * store. describe.net has none: `PartnerGate` builds its `VerifyPolicy` with no\n * `nonce` field at all (`partner.py:216-223`), and the verifier skips every\n * nonce rule when `policy.nonce is None` — no presence check\n * (`verifier.py:458-462`), no consumption (`verifier.py:304`). Read in the\n * installed PyPI `uvd-x402-sdk` 0.70.0 on 2026-08-30.\n *\n * So there is no store to be unknown to, and a locally minted random nonce is\n * strictly better than the alternative the policy would also accept (none at\n * all): it makes each signature unique, so two identical GETs in the same second\n * do not produce byte-identical headers. This is the caller owning the\n * consequence, which is exactly what `onNonceUnavailable` exists to express in\n * the payment SDK — stated here rather than hidden.\n *\n * 🔴 If describe.net ever adds a nonce store, this line becomes wrong and the\n * failure is loud, not silent: every partner request starts answering 402 with\n * `nonce_unknown` and `DescribePartnerRejected` says so. That is the direction\n * this failure should point.\n *\n * ## What is signed, and the consequence of a custom `baseUrl`\n *\n * The signature covers `@method`, `@authority` and `@path` (plus `@query` when\n * there is one), and `@authority` comes from the URL being requested. The gate\n * pins `api.describe.net` and NEVER derives it from a header (`partner.py:73-84`\n * — deriving an authority from client-controlled input is how a verifier was\n * once made to rebuild a base over an attacker's domain). So a client pointed at\n * any other origin — a staging host, a proxy, the raw execute-api host behind\n * CloudFront — signs an authority the gate does not accept and is charged. That\n * is deliberate on both sides, and it fails LOUDLY here as\n * `DescribePartnerRejected` rather than quietly as a bill.\n */\n\nimport {\n CONFORMANCE_VECTORS_F3_1,\n signRequest,\n signRequestWithSigner,\n} from 'uvd-x402-sdk/erc8128';\n\nimport type { PartnerSigner } from '../client';\nimport { PARTNER_CHAIN_ID, PARTNER_KEY_ENV } from '../config';\n\n/**\n * The signer's typed header object as a plain `Record<string, string>`.\n *\n * Not cosmetic: `Erc8128Headers` declares `'Content-Digest'?: string`, and an\n * interface with an optional member is not assignable to `Record<string,\n * string>` — the dts build says so, loudly (TS2322 at the return, TS2345 at the\n * parameter, which is why the parameter is `object` and not a `Record` of its\n * own). Dropping the undefined entries here is the honest conversion, and it\n * means the client never merges a header whose value is `undefined` into a\n * `fetch` call, which is how a literal `\"undefined\"` ends up on a wire.\n */\nfunction plainHeaders(headers: object): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) {\n if (typeof value === 'string') out[name] = value;\n }\n return out;\n}\n\n/** A 128-bit hex nonce. See the module header for why this is minted locally. */\nfunction mintNonce(): string {\n const bytes = new Uint8Array(16);\n // `globalThis.crypto` is standard in Node >= 18 and in every browser, which\n // is the same floor as this package's `engines`. No import, no polyfill.\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/** What every factory here accepts. Both fields have defaults that are right. */\nexport interface PartnerOptions {\n /**\n * The keyid's chain id. Defaults to `PARTNER_CHAIN_ID` (8453, Base), which is\n * what the gate pins. Override only if describe.net's `CHAIN_ID` moves.\n */\n chainId?: number;\n}\n\n/**\n * The rail, from a signer you already have. **This is the preferred form.**\n *\n * It takes an OBJECT THAT SIGNS, never a key: a browser wallet, an ethers\n * `Wallet` built somewhere else, an OWS vault, a KMS client, a queue that asks a\n * human. The key material never enters this package, never enters\n * `uvd-x402-sdk`'s signer, and cannot end up in a stack trace it produces.\n *\n * ```ts\n * import { DescribeClient } from 'uvd-describe-sdk';\n * import { partnerFromSigner } from 'uvd-describe-sdk/partner';\n *\n * // `wallet` is yours — this package never learns how it holds its key.\n * const describe = new DescribeClient({\n * product: 'meshrelay',\n * partner: partnerFromSigner({\n * address: await wallet.getAddress(),\n * signMessage: (base) => wallet.signMessage(base),\n * }),\n * });\n *\n * // Metered route, no payer, no USDC: the free rail carries it.\n * const detail = await describe.walletBreakdown('0x97cd…0996');\n * ```\n *\n * `signMessage` is an EIP-191 `personal_sign` over the string it is handed and\n * must return `0x` + 130 hex. It is the ONE thing this rail cannot do for you.\n */\nexport function partnerFromSigner(\n signer: {\n /** The signing wallet's address. Public by design — the allowlist is public. */\n address: string;\n /** EIP-191 personal_sign over the signature base. */\n signMessage(message: string): string | Promise<string>;\n } & PartnerOptions,\n): PartnerSigner {\n const { address, signMessage, chainId = PARTNER_CHAIN_ID } = signer;\n return {\n address,\n async sign({ method, url }) {\n return plainHeaders(\n await signRequestWithSigner({\n method,\n url,\n address,\n chainId,\n nonce: mintNonce(),\n signMessage,\n }),\n );\n },\n };\n}\n\n/**\n * The rail, from a private key **the environment holds**.\n *\n * ## Why this reads the variable itself instead of taking a string\n *\n * Because a function that takes a key as an argument is a function somebody\n * calls with a literal. Two DAO wallets were drained in minutes by bots\n * scanning public repositories for `0x` + 64 hex (INC-2026-03-30), and \"it was\n * only for a test\" is how both got there. This signature makes the safe path\n * the only path: the key can come from `process.env` and from nowhere else, so\n * there is no argument to paste one into. If your key lives somewhere better —\n * Secrets Manager, a vault, a hardware signer — fetch it there and use\n * {@link partnerFromSigner}, which never sees a key at all.\n *\n * ```ts\n * // DESCRIBE_PARTNER_PRIVATE_KEY is set in the environment. Never in code.\n * const describe = new DescribeClient({\n * product: 'karmakadabra',\n * partner: partnerFromEnv(),\n * });\n * ```\n *\n * Throws immediately — at wiring time, not at the first request — when the\n * variable is unset or malformed. A partner rail that is going to fail should\n * fail before the process claims to be up.\n *\n * ## 🔴 The shape check, and the measurement that put it here\n *\n * The key is trimmed and checked against `^(0x)?[0-9a-fA-F]{64}$` before it\n * reaches the payment SDK, and that is a SECURITY guard, not politeness.\n * Measured 2026-08-30 with `ethers` 6.17.0, the version `uvd-x402-sdk` 2.75.0\n * pulls in:\n *\n * * `new ethers.Wallet('0x'+64hex)` with a **trailing newline** — the single\n * most common way an env var gets malformed, e.g. `KEY=$(cat file)` —\n * throws `invalid BytesLike value (argument=\"value\", value=\"0xabab…ab\\n\")`.\n * **The entire private key is inside the message, verbatim.**\n * * only a well-formed-but-invalid key reaches the redacted path,\n * `invalid private key (argument=\"privateKey\", value=\"[REDACTED]\")`.\n *\n * So the redaction everyone assumes is there covers the second case and not the\n * first, and the first is the likely one. Trimming closes the newline path; the\n * shape check guarantees that whatever reaches `ethers` is exactly 64 hex\n * characters and can therefore only fail into the REDACTED branch. The error\n * this function throws names the variable and the length and never the value.\n *\n * ⚠️ Reported upstream, not patched there by this session: `signRequest` in\n * `uvd-x402-sdk/erc8128` hands its `privateKey` straight to `new\n * ethers.Wallet()` (`signer.ts:255-258`) and has the same exposure for anyone\n * calling it directly. The house rule is that the fix goes upstream; this guard\n * protects THIS path in the meantime and is not a reimplementation of anything.\n */\nexport function partnerFromEnv(\n options: PartnerOptions & {\n /** Which variable holds the key. Defaults to `DESCRIBE_PARTNER_PRIVATE_KEY`. */\n envVar?: string;\n /** Injectable for tests. Defaults to `process.env`. */\n env?: Record<string, string | undefined>;\n } = {},\n): PartnerSigner {\n const { chainId = PARTNER_CHAIN_ID, envVar = PARTNER_KEY_ENV } = options;\n const env = options.env ?? (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;\n\n const raw = env?.[envVar];\n if (typeof raw !== 'string' || raw.trim() === '') {\n throw new Error(\n `partnerFromEnv: ${envVar} is not set. The partner rail signs every ` +\n 'request with a dedicated wallet; without its key this client is an ' +\n 'anonymous client, and an anonymous client pays. Set the variable, or ' +\n 'use partnerFromSigner() with a signer you build yourself.',\n );\n }\n\n // Trimmed on purpose: a private key has no meaningful surrounding\n // whitespace, and the alternative to trimming is the ethers leak above.\n const key = raw.trim();\n if (!/^(0x)?[0-9a-fA-F]{64}$/.test(key)) {\n // Length and nothing else. Never the value, never a prefix of it, never a\n // \"did you mean\" that echoes it back.\n throw new Error(\n `partnerFromEnv: ${envVar} is not a 32-byte hex private key ` +\n `(got ${key.length} characters after trimming; expected 64, or 66 with ` +\n 'the 0x prefix). The value is deliberately not shown.',\n );\n }\n\n // The address is derived by the payment SDK from the key, so we do not know\n // it here without building a wallet ourselves — which would mean importing\n // `ethers` into this package. It stays undefined; error messages lose one\n // detail and this package keeps its dependency list empty.\n return {\n async sign({ method, url }) {\n return plainHeaders(\n await signRequest({ method, url, chainId, nonce: mintNonce(), privateKey: key }),\n );\n },\n };\n}\n\n/**\n * The synthetic key the payment SDK ships in its ERC-8128 conformance vectors,\n * documented there as a key that never held funds.\n *\n * Exported for one reason: so that a consumer's own tests can exercise the\n * partner rail without anybody typing 64 hex characters into a repository. It\n * is read out of the installed package at call time and is not stored anywhere\n * in this one.\n *\n * 🔴 It is PUBLIC and it is in everybody's `node_modules`. Never fund it, never\n * allowlist it, never use it outside a test.\n */\nexport function syntheticTestKey(): string {\n const key = CONFORMANCE_VECTORS_F3_1.frozen.private_key;\n if (!key) throw new Error('the installed uvd-x402-sdk ships no synthetic test key');\n return key;\n}\n\nexport type { PartnerSigner } from '../client';\nexport { PARTNER_CHAIN_ID, PARTNER_KEY_ENV } from '../config';\n"]}
1
+ {"version":3,"sources":["../../src/config.ts","../../src/partner/index.ts"],"names":[],"mappings":";;;;;AAyHO,IAAM,gBAAA,GAAmB;AAUzB,IAAM,eAAA,GAAkB;;;ACnC/B,SAAS,aAAa,OAAA,EAAyC;AAC7D,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,OAAO,CAAA,EAAG;AACnD,IAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,GAAA,CAAI,IAAI,CAAA,GAAI,KAAA;AAAA,EAC7C;AACA,EAAA,OAAO,GAAA;AACT;AAGA,SAAS,SAAA,GAAoB;AAC3B,EAAA,MAAM,KAAA,GAAQ,IAAI,UAAA,CAAW,EAAE,CAAA;AAG/B,EAAA,UAAA,CAAW,MAAA,CAAO,gBAAgB,KAAK,CAAA;AACvC,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,KAAA,EAAO,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,SAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA;AAC1E;AAuCO,SAAS,kBACd,MAAA,EAMe;AACf,EAAA,MAAM,EAAE,OAAA,EAAS,WAAA,EAAa,OAAA,GAAU,kBAAiB,GAAI,MAAA;AAC7D,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,MAAM,IAAA,CAAK,EAAE,MAAA,EAAQ,KAAI,EAAG;AAC1B,MAAA,OAAO,YAAA;AAAA,QACL,MAAM,qBAAA,CAAsB;AAAA,UAC1B,MAAA;AAAA,UACA,GAAA;AAAA,UACA,OAAA;AAAA,UACA,OAAA;AAAA,UACA,OAAO,SAAA,EAAU;AAAA,UACjB;AAAA,SACD;AAAA,OACH;AAAA,IACF;AAAA,GACF;AACF;AAsDO,SAAS,cAAA,CACd,OAAA,GAKI,EAAC,EACU;AACf,EAAA,MAAM,EAAE,OAAA,GAAU,gBAAA,EAAkB,MAAA,GAAS,iBAAgB,GAAI,OAAA;AACjE,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,IAAQ,UAAA,CAA0E,OAAA,EAAS,GAAA;AAE/G,EAAA,MAAM,GAAA,GAAM,MAAM,MAAM,CAAA;AACxB,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,CAAI,IAAA,OAAW,EAAA,EAAI;AAChD,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,mBAAmB,MAAM,CAAA,2OAAA;AAAA,KAI3B;AAAA,EACF;AAIA,EAAA,MAAM,GAAA,GAAM,IAAI,IAAA,EAAK;AACrB,EAAA,IAAI,CAAC,wBAAA,CAAyB,IAAA,CAAK,GAAG,CAAA,EAAG;AAGvC,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,gBAAA,EAAmB,MAAM,CAAA,uCAAA,EACf,GAAA,CAAI,MAAM,CAAA,wGAAA;AAAA,KAEtB;AAAA,EACF;AAMA,EAAA,OAAO;AAAA,IACL,MAAM,IAAA,CAAK,EAAE,MAAA,EAAQ,KAAI,EAAG;AAC1B,MAAA,OAAO,YAAA;AAAA,QACL,MAAM,WAAA,CAAY,EAAE,MAAA,EAAQ,GAAA,EAAK,OAAA,EAAS,KAAA,EAAO,SAAA,EAAU,EAAG,UAAA,EAAY,GAAA,EAAK;AAAA,OACjF;AAAA,IACF;AAAA,GACF;AACF;AAcO,SAAS,gBAAA,GAA2B;AACzC,EAAA,MAAM,GAAA,GAAM,yBAAyB,MAAA,CAAO,WAAA;AAC5C,EAAA,IAAI,CAAC,GAAA,EAAK,MAAM,IAAI,MAAM,wDAAwD,CAAA;AAClF,EAAA,OAAO,GAAA;AACT","file":"index.mjs","sourcesContent":["/**\n * The only place this package defines a calibrable value.\n *\n * House rule (decisión de Saul, 2026-08-26, born from a measured case in\n * describe.net: one threshold written with TWO DIFFERENT VALUES across four\n * surfaces, and the one charged was not the one the site promised). Nothing\n * else in this package re-types these numbers — modules import them.\n *\n * What does NOT live here, by the same rule: anything that moves a score or a\n * price. This SDK computes neither, so the list is short: `POLICY_VERSION` and\n * the prices are the server's and travel in its responses. We never type a\n * price. See `errors.ts` for what we do with a 402 challenge instead.\n */\n\n/** Where the index answers. Overridable per client for a staging deploy. */\nexport const DEFAULT_BASE_URL = 'https://api.describe.net';\n\n/** Where a human reads the same wallet. Never fetched — only linked. */\nexport const DEFAULT_SITE_URL = 'https://describe.net';\n\n/**\n * 30 s, and the number is not taste — it is the one number of the three live\n * consumers that came with its measurement written down (EM `client.py:19-23`,\n * INC-2026-08-19):\n *\n * * the provider's Lambda cold start was measured at **15,2 s**, so anything\n * under it turns a cold index into a fake outage. An 8 s timeout already\n * broke a real integration once.\n * * its API Gateway integration ceiling is **29 s**, so waiting past 30 buys\n * nothing the gateway will ever deliver.\n * * it is deliberately DISTINCT from the Facilitator's 45 s so two clocks can\n * never expire in the same second and produce an error nobody can attribute.\n *\n * Measured across the ecosystem on 2026-08-30: EM 30 s, MeshRelay 30 000 ms,\n * KarmaKadabra 25 s. Two of three already sit here.\n */\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\n/**\n * 400 ms, **on by default**, and the default is the decision — so here is the\n * argument, because it is the one thing about this package that spends the\n * caller's latency without being asked.\n *\n * The number is not ours: it is what **KarmaKadabra** sleeps before every read\n * (`random.uniform(0, 0.4)`), contributed on 2026-08-30 with the measurement\n * that produced it — *\"27 agentes despiertan al MISMO tiempo por EventBridge y\n * pegan simultáneo contra su límite de rps COMPARTIDO con los otros\n * consumidores. Sin jitter, un enjambre es un DDoS educado.\"* They run the\n * largest fleet against this index, so their calibration beats our taste.\n *\n * ## Why ON, when a library that sleeps unasked is a surprise\n *\n * The surprise is real and it is the honest objection. Three things outweigh it:\n *\n * 1. **The cost of the mistake does not land on whoever makes it.** The rate\n * limit is shared with no per-partner bucket (see `userAgent` below), so an\n * unjittered swarm is paid for by the OTHER consumer, who gets the 429 and\n * has no lever to fix it. When the cost of a default falls on someone who\n * cannot change it, the default has to be the safe one.\n * 2. **Opt-out is discoverable; opt-in is not.** `jitterMs: 0` is one field\n * away and typed. The other direction cannot be found by reading your own\n * code: you learn you needed jitter from someone else's incident, and by\n * then you have already spent their budget. KarmaKadabra's own framing —\n * whoever writes a single script never finds out the problem exists until\n * they have a fleet.\n * 3. **It is bounded and small against this package's own numbers.** At most\n * 400 ms, 200 ms on average, against a 30 000 ms timeout and a provider\n * cold start measured at 15,2 s. And it is the same shape of default this\n * client already ships: `failOpen: true` also changes behaviour without\n * being asked, for the same reason — the safe thing, loudly documented,\n * with one field to turn it off.\n *\n * ## What is NOT written here, on purpose\n *\n * The rate limit itself. KarmaKadabra's own note cited 20 rps, which was the\n * documentation's figure and is now stale (it is 50 sustained / burst 40 since\n * 2026-08-28). A number that has already gone stale once in one hop between two\n * teams does not belong in a constant: **the `RateLimit-Policy` response header\n * is the authority**, and this value is calibrated against a fleet size, not\n * against a ceiling. See the correction in `userAgent`.\n */\nexport const DEFAULT_JITTER_MS = 400;\n\n/**\n * The treasury this SDK will pay, and NOTHING else.\n *\n * Read live from the 402 challenge of `GET /reputation/wallet/{w}` on\n * 2026-08-30 (`recipient`, and `payTo` on all six `accepts[]` entries — base,\n * avalanche, arbitrum, optimism, polygon, celo — identical on every one).\n *\n * Pinning it is the point: an x402 challenge is fetched over the network and\n * names its own recipient, so a client that pays whatever `payTo` arrives will\n * happily pay an attacker who can answer as the API. A challenge whose `payTo`\n * is not this address is `DO_NOT_PAY` — never a retry, never a warning that a\n * caller can ignore.\n *\n * 🔴 THE FAILURE MODE OF PINNING, written down because it will happen: if\n * describe.net rotates its treasury, every published version of this SDK stops\n * paying until it is republished. That is the SAFE direction of the failure\n * (refusing to pay a stranger beats paying one), and the escape hatch is\n * `expectedPayTo` in the client config — a caller who has verified the new\n * address out of band can move without waiting for us.\n */\nexport const TREASURY_EVM = '0xe4dc963c56979E0260fc146b87eE24F18220e545';\n\n/**\n * The chain id that goes in the ERC-8128 keyid of a partner signature.\n *\n * 8453 (Base). Not a preference — it is what the gate accepts:\n * `describe-net/describenet/partner.py:90` sets `CHAIN_ID = 8453` and passes it\n * as the ONLY member of `allowed_chain_ids`, with its own comment explaining\n * that `None` (accept any chain) would be \"innecesariamente laxo para una\n * allowlist de tres servicios propios\". Read 2026-08-30.\n *\n * The payment SDK's own default happens to be 8453 too, and this constant\n * deliberately does not lean on that: this value belongs to describe.net's\n * policy, not to the signer's convenience, and the day one moves the other must\n * not follow by accident. Measured failure mode of getting it wrong: the gate\n * answers `chain_not_allowed` and the route charges — loud, since partner mode\n * throws `DescribePartnerRejected` instead of paying.\n */\nexport const PARTNER_CHAIN_ID = 8453;\n\n/**\n * The environment variable `partnerFromEnv()` reads the signing key from.\n *\n * A variable name is not a secret; the value it holds is. Naming it here means\n * a consumer can grep for it, a deploy manifest can set it, and nobody has to\n * guess — while `partnerFromEnv()` staying the ONLY reader means the key has\n * exactly one path into this package.\n */\nexport const PARTNER_KEY_ENV = 'DESCRIBE_PARTNER_PRIVATE_KEY';\n\n/**\n * The package version, for the `User-Agent`.\n *\n * MeshRelay reads its version from `package.json` at runtime because \"a\n * User-Agent that lies about the version is worse than none\"\n * (`describenet.js:39`). It can afford the `readFileSync`: it is a server, not\n * a bundled library. We cannot — a library that reads its own manifest at\n * runtime either bundles `package.json` into the artifact or breaks in a\n * browser, and this package has to run in a browser.\n *\n * So the constant is typed here and `config.test.ts` asserts it equals\n * `package.json`'s `version`. Same guarantee (the UA cannot lie), paid at test\n * time instead of at runtime. Bumping the version without the constant is a\n * red test, not a silent lie in someone's access log.\n */\nexport const SDK_VERSION = '0.3.0';\n\n/** `uvd-describe-sdk-ts/0.1.0`, plus `(+<product>)` when the caller names itself. */\nexport const SDK_NAME = 'uvd-describe-sdk-ts';\n\n/**\n * Build the `User-Agent`.\n *\n * The provider's rate limit is **shared by every consumer with no per-partner\n * bucket**, so identifying ourselves is the only thing that makes our share of\n * it attributable at all. That is why the UA is on by default and `product` is\n * the one field a caller should bother to fill.\n *\n * ⚠️ CORRECTION 2026-08-30, left written rather than swapped: this comment\n * first said \"20 rps\", copied from `meshrelay/describenet.js:19-20`. The live\n * OpenAPI says **50 requests/second sustained, bursts up to 40**, at the API\n * Gateway edge, and it also says where the truth lives: *\"Every response\n * carries the policy as a header, `RateLimit-Policy: 50;w=1;burst=40` … and\n * **that header is the authority**\"*. So neither number belongs in this file —\n * read the header. Cached free routes (`/health`, `/pricing`, `/leaderboard`,\n * `/stats/*`) are served by CloudFront and do not consume the budget on a hit.\n * The 20 was probably right when MeshRelay wrote it; a dated figure does not\n * stop being stale, it only stops being a lie.\n *\n * ⚠️ It is attribution, not authentication. describe.net has no accounts and\n * no API keys — \"el pago es la autenticación\" — so anyone can send any UA.\n * Never treat this string as identity, on either side.\n */\nexport function userAgent(product?: string): string {\n const base = `${SDK_NAME}/${SDK_VERSION}`;\n const trimmed = (product ?? '').trim();\n return trimmed ? `${base} (+${trimmed})` : base;\n}\n","/**\n * The partner rail — how a product of the house reads describe.net for free.\n *\n * ## What this is, in one paragraph\n *\n * describe.net has no accounts and no API keys, on purpose: *\"el pago es la\n * autenticación\"*. So when Execution Market, MeshRelay and KarmaKadabra\n * deprecated their local reputation maths and became read-dependencies of the\n * index (2026-08-28), the question \"does a service of the house pay like a\n * stranger?\" could not be answered with a token. It was answered with an\n * ALLOWLIST OF PUBLIC ADDRESSES plus a per-request ERC-8128 signature\n * (`describe-net/describenet/partner.py`). The partner holds a dedicated wallet\n * with no funds whose only job is to sign; describe.net holds a list of\n * addresses. **The service custodies no secret of ours** — a breach there leaks\n * a list of things that were already public — and that property, not\n * convenience, is why this is a signature and not the `X-API-Key` everyone\n * reaches for first.\n *\n * This module is the client half. It is the only file in this package with a\n * RUNTIME import of `uvd-x402-sdk`, which is why it lives behind the\n * `uvd-describe-sdk/partner` subpath: the main entry and the `x402` entry keep\n * their zero-runtime-imports property, and a consumer who never signs installs\n * nothing.\n *\n * ## Upstream-first: the primitive already existed, MEASURED before writing\n *\n * `uvd-x402-sdk` 2.75.0 (installed, checked 2026-08-30) exports the whole\n * ERC-8128 signer from `uvd-x402-sdk/erc8128` — `signRequest`,\n * `signRequestWithSigner`, `signRequestWithWallet`, plus the pure base builder\n * and the verifier. So NOTHING is signed in this repo: this file picks a chain\n * id and a nonce and forwards. Not one byte of RFC 9421 canonicalisation is\n * reimplemented here, and if any of it ever needs to change, it changes THERE.\n *\n * Verified end to end, offline, on 2026-08-30: headers produced by\n * `signRequestWithSigner` at chain 8453 verify under the EXACT policy\n * `partner.py` builds (authority `api.describe.net`, `allowed_chain_ids=[8453]`,\n * `max_validity_sec=300`, `clock_skew_future_sec=30`), recovering the signer's\n * address. `partner.test.ts` is that probe, kept as a test.\n *\n * ## The nonce: minted here, and here is the argument\n *\n * The payment SDK requires a nonce and refuses to invent one — *\"a local nonce\n * authenticates against a first-use-wins store and is rejected by an\n * issuer-bound one, which turns a server blip into an auth mystery\"*\n * (`erc8128/signer.ts:15-17`). That reasoning is about servers that HAVE a nonce\n * store. describe.net has none: `PartnerGate` builds its `VerifyPolicy` with no\n * `nonce` field at all (`partner.py:216-223`), and the verifier skips every\n * nonce rule when `policy.nonce is None` — no presence check\n * (`verifier.py:458-462`), no consumption (`verifier.py:304`). Read in the\n * installed PyPI `uvd-x402-sdk` 0.70.0 on 2026-08-30.\n *\n * So there is no store to be unknown to, and a locally minted random nonce is\n * strictly better than the alternative the policy would also accept (none at\n * all): it makes each signature unique, so two identical GETs in the same second\n * do not produce byte-identical headers. This is the caller owning the\n * consequence, which is exactly what `onNonceUnavailable` exists to express in\n * the payment SDK — stated here rather than hidden.\n *\n * 🔴 If describe.net ever adds a nonce store, this line becomes wrong and the\n * failure is loud, not silent: every partner request starts answering 402 with\n * `nonce_unknown` and `DescribePartnerRejected` says so. That is the direction\n * this failure should point.\n *\n * ## What is signed, and the consequence of a custom `baseUrl`\n *\n * The signature covers `@method`, `@authority` and `@path` (plus `@query` when\n * there is one), and `@authority` comes from the URL being requested. The gate\n * pins `api.describe.net` and NEVER derives it from a header (`partner.py:73-84`\n * — deriving an authority from client-controlled input is how a verifier was\n * once made to rebuild a base over an attacker's domain). So a client pointed at\n * any other origin — a staging host, a proxy, the raw execute-api host behind\n * CloudFront — signs an authority the gate does not accept and is charged. That\n * is deliberate on both sides, and it fails LOUDLY here as\n * `DescribePartnerRejected` rather than quietly as a bill.\n */\n\nimport {\n CONFORMANCE_VECTORS_F3_1,\n signRequest,\n signRequestWithSigner,\n} from 'uvd-x402-sdk/erc8128';\n\nimport type { PartnerSigner } from '../client';\nimport { PARTNER_CHAIN_ID, PARTNER_KEY_ENV } from '../config';\n\n/**\n * The signer's typed header object as a plain `Record<string, string>`.\n *\n * Not cosmetic: `Erc8128Headers` declares `'Content-Digest'?: string`, and an\n * interface with an optional member is not assignable to `Record<string,\n * string>` — the dts build says so, loudly (TS2322 at the return, TS2345 at the\n * parameter, which is why the parameter is `object` and not a `Record` of its\n * own). Dropping the undefined entries here is the honest conversion, and it\n * means the client never merges a header whose value is `undefined` into a\n * `fetch` call, which is how a literal `\"undefined\"` ends up on a wire.\n */\nfunction plainHeaders(headers: object): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) {\n if (typeof value === 'string') out[name] = value;\n }\n return out;\n}\n\n/** A 128-bit hex nonce. See the module header for why this is minted locally. */\nfunction mintNonce(): string {\n const bytes = new Uint8Array(16);\n // `globalThis.crypto` is standard in Node >= 18 and in every browser, which\n // is the same floor as this package's `engines`. No import, no polyfill.\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/** What every factory here accepts. Both fields have defaults that are right. */\nexport interface PartnerOptions {\n /**\n * The keyid's chain id. Defaults to `PARTNER_CHAIN_ID` (8453, Base), which is\n * what the gate pins. Override only if describe.net's `CHAIN_ID` moves.\n */\n chainId?: number;\n}\n\n/**\n * The rail, from a signer you already have. **This is the preferred form.**\n *\n * It takes an OBJECT THAT SIGNS, never a key: a browser wallet, an ethers\n * `Wallet` built somewhere else, an OWS vault, a KMS client, a queue that asks a\n * human. The key material never enters this package, never enters\n * `uvd-x402-sdk`'s signer, and cannot end up in a stack trace it produces.\n *\n * ```ts\n * import { DescribeClient } from 'uvd-describe-sdk';\n * import { partnerFromSigner } from 'uvd-describe-sdk/partner';\n *\n * // `wallet` is yours — this package never learns how it holds its key.\n * const describe = new DescribeClient({\n * product: 'meshrelay',\n * partner: partnerFromSigner({\n * address: await wallet.getAddress(),\n * signMessage: (base) => wallet.signMessage(base),\n * }),\n * });\n *\n * // Metered route, no payer, no USDC: the free rail carries it.\n * const detail = await describe.walletBreakdown('0x97cd…0996');\n * ```\n *\n * `signMessage` is an EIP-191 `personal_sign` over the string it is handed and\n * must return `0x` + 130 hex. It is the ONE thing this rail cannot do for you.\n */\nexport function partnerFromSigner(\n signer: {\n /** The signing wallet's address. Public by design — the allowlist is public. */\n address: string;\n /** EIP-191 personal_sign over the signature base. */\n signMessage(message: string): string | Promise<string>;\n } & PartnerOptions,\n): PartnerSigner {\n const { address, signMessage, chainId = PARTNER_CHAIN_ID } = signer;\n return {\n address,\n async sign({ method, url }) {\n return plainHeaders(\n await signRequestWithSigner({\n method,\n url,\n address,\n chainId,\n nonce: mintNonce(),\n signMessage,\n }),\n );\n },\n };\n}\n\n/**\n * The rail, from a private key **the environment holds**.\n *\n * ## Why this reads the variable itself instead of taking a string\n *\n * Because a function that takes a key as an argument is a function somebody\n * calls with a literal. Two DAO wallets were drained in minutes by bots\n * scanning public repositories for `0x` + 64 hex (INC-2026-03-30), and \"it was\n * only for a test\" is how both got there. This signature makes the safe path\n * the only path: the key can come from `process.env` and from nowhere else, so\n * there is no argument to paste one into. If your key lives somewhere better —\n * Secrets Manager, a vault, a hardware signer — fetch it there and use\n * {@link partnerFromSigner}, which never sees a key at all.\n *\n * ```ts\n * // DESCRIBE_PARTNER_PRIVATE_KEY is set in the environment. Never in code.\n * const describe = new DescribeClient({\n * product: 'karmakadabra',\n * partner: partnerFromEnv(),\n * });\n * ```\n *\n * Throws immediately — at wiring time, not at the first request — when the\n * variable is unset or malformed. A partner rail that is going to fail should\n * fail before the process claims to be up.\n *\n * ## 🔴 The shape check, and the measurement that put it here\n *\n * The key is trimmed and checked against `^(0x)?[0-9a-fA-F]{64}$` before it\n * reaches the payment SDK, and that is a SECURITY guard, not politeness.\n * Measured 2026-08-30 with `ethers` 6.17.0, the version `uvd-x402-sdk` 2.75.0\n * pulls in:\n *\n * * `new ethers.Wallet('0x'+64hex)` with a **trailing newline** — the single\n * most common way an env var gets malformed, e.g. `KEY=$(cat file)` —\n * throws `invalid BytesLike value (argument=\"value\", value=\"0xabab…ab\\n\")`.\n * **The entire private key is inside the message, verbatim.**\n * * only a well-formed-but-invalid key reaches the redacted path,\n * `invalid private key (argument=\"privateKey\", value=\"[REDACTED]\")`.\n *\n * So the redaction everyone assumes is there covers the second case and not the\n * first, and the first is the likely one. Trimming closes the newline path; the\n * shape check guarantees that whatever reaches `ethers` is exactly 64 hex\n * characters and can therefore only fail into the REDACTED branch. The error\n * this function throws names the variable and the length and never the value.\n *\n * ⚠️ Reported upstream, not patched there by this session: `signRequest` in\n * `uvd-x402-sdk/erc8128` hands its `privateKey` straight to `new\n * ethers.Wallet()` (`signer.ts:255-258`) and has the same exposure for anyone\n * calling it directly. The house rule is that the fix goes upstream; this guard\n * protects THIS path in the meantime and is not a reimplementation of anything.\n */\nexport function partnerFromEnv(\n options: PartnerOptions & {\n /** Which variable holds the key. Defaults to `DESCRIBE_PARTNER_PRIVATE_KEY`. */\n envVar?: string;\n /** Injectable for tests. Defaults to `process.env`. */\n env?: Record<string, string | undefined>;\n } = {},\n): PartnerSigner {\n const { chainId = PARTNER_CHAIN_ID, envVar = PARTNER_KEY_ENV } = options;\n const env = options.env ?? (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;\n\n const raw = env?.[envVar];\n if (typeof raw !== 'string' || raw.trim() === '') {\n throw new Error(\n `partnerFromEnv: ${envVar} is not set. The partner rail signs every ` +\n 'request with a dedicated wallet; without its key this client is an ' +\n 'anonymous client, and an anonymous client pays. Set the variable, or ' +\n 'use partnerFromSigner() with a signer you build yourself.',\n );\n }\n\n // Trimmed on purpose: a private key has no meaningful surrounding\n // whitespace, and the alternative to trimming is the ethers leak above.\n const key = raw.trim();\n if (!/^(0x)?[0-9a-fA-F]{64}$/.test(key)) {\n // Length and nothing else. Never the value, never a prefix of it, never a\n // \"did you mean\" that echoes it back.\n throw new Error(\n `partnerFromEnv: ${envVar} is not a 32-byte hex private key ` +\n `(got ${key.length} characters after trimming; expected 64, or 66 with ` +\n 'the 0x prefix). The value is deliberately not shown.',\n );\n }\n\n // The address is derived by the payment SDK from the key, so we do not know\n // it here without building a wallet ourselves — which would mean importing\n // `ethers` into this package. It stays undefined; error messages lose one\n // detail and this package keeps its dependency list empty.\n return {\n async sign({ method, url }) {\n return plainHeaders(\n await signRequest({ method, url, chainId, nonce: mintNonce(), privateKey: key }),\n );\n },\n };\n}\n\n/**\n * The synthetic key the payment SDK ships in its ERC-8128 conformance vectors,\n * documented there as a key that never held funds.\n *\n * Exported for one reason: so that a consumer's own tests can exercise the\n * partner rail without anybody typing 64 hex characters into a repository. It\n * is read out of the installed package at call time and is not stored anywhere\n * in this one.\n *\n * 🔴 It is PUBLIC and it is in everybody's `node_modules`. Never fund it, never\n * allowlist it, never use it outside a test.\n */\nexport function syntheticTestKey(): string {\n const key = CONFORMANCE_VECTORS_F3_1.frozen.private_key;\n if (!key) throw new Error('the installed uvd-x402-sdk ships no synthetic test key');\n return key;\n}\n\nexport type { PartnerSigner } from '../client';\nexport { PARTNER_CHAIN_ID, PARTNER_KEY_ENV } from '../config';\n"]}
@@ -1,5 +1,5 @@
1
1
  import { X402Client } from 'uvd-x402-sdk';
2
- import { X as X402Challenge, E as X402Payer } from '../client-RAhXcpdY.mjs';
2
+ import { X as X402Challenge, J as X402Payer } from '../client-BMfgl1zP.mjs';
3
3
 
4
4
  /**
5
5
  * The canonical payer — the ONLY file in this package that knows `uvd-x402-sdk`
@@ -1,5 +1,5 @@
1
1
  import { X402Client } from 'uvd-x402-sdk';
2
- import { X as X402Challenge, E as X402Payer } from '../client-RAhXcpdY.js';
2
+ import { X as X402Challenge, J as X402Payer } from '../client-BMfgl1zP.js';
3
3
 
4
4
  /**
5
5
  * The canonical payer — the ONLY file in this package that knows `uvd-x402-sdk`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "uvd-describe-sdk",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Read reputation from describe.net — the ERC-8004 index across 11 chains. Free lookups need no dependency; metered lookups pay their 402 through uvd-x402-sdk, or read free over the ERC-8128 partner rail. null is never 0.",
5
5
  "author": "Ultravioleta DAO <ultravioletadao@gmail.com>",
6
6
  "license": "MIT",
package/src/config.ts CHANGED
@@ -146,7 +146,7 @@ export const PARTNER_KEY_ENV = 'DESCRIBE_PARTNER_PRIVATE_KEY';
146
146
  * time instead of at runtime. Bumping the version without the constant is a
147
147
  * red test, not a silent lie in someone's access log.
148
148
  */
149
- export const SDK_VERSION = '0.2.0';
149
+ export const SDK_VERSION = '0.3.0';
150
150
 
151
151
  /** `uvd-describe-sdk-ts/0.1.0`, plus `(+<product>)` when the caller names itself. */
152
152
  export const SDK_NAME = 'uvd-describe-sdk-ts';
package/src/index.ts CHANGED
@@ -154,6 +154,8 @@ export {
154
154
 
155
155
  export type {
156
156
  Activity,
157
+ Freshness,
158
+ FreshnessScope,
157
159
  AgentReputation,
158
160
  Concentration,
159
161
  Confidence,
package/src/parse.ts CHANGED
@@ -54,6 +54,7 @@ import { hashField } from './hashes';
54
54
  import type {
55
55
  Activity,
56
56
  AgentReputation,
57
+ Freshness,
57
58
  Concentration,
58
59
  Confidence,
59
60
  Facet,
@@ -182,6 +183,43 @@ function parseActivity(v: unknown): Activity | null {
182
183
  return { firstRatingAt: optString(v.first_rating_at), lastRatingAt: optString(v.last_rating_at) };
183
184
  }
184
185
 
186
+ /**
187
+ * `null` when the block is absent OR unparseable — never an empty `Freshness`.
188
+ *
189
+ * Same rule as every other parser here: a default that looks like data is how a
190
+ * client stops being able to tell "the server does not publish this" from "the
191
+ * server has no dates for this subject". The second one is information; the
192
+ * first one is not.
193
+ *
194
+ * The counts go through `num()` so a string count from a stricter serialiser
195
+ * still lands as a number: freshness is advisory and must not be the reason a
196
+ * paid response fails to parse.
197
+ */
198
+ function parseFreshness(v: unknown): Freshness | null {
199
+ if (!isObj(v)) return null;
200
+ const scope = isObj(v.scope) ? v.scope : {};
201
+ return {
202
+ scope: {
203
+ kind: optString(scope.kind),
204
+ direction: optString(scope.direction),
205
+ id: optString(scope.id),
206
+ network: optString(scope.network),
207
+ declaredType: optString(scope.declared_type),
208
+ },
209
+ lastReceivedFeedbackAt: optString(v.last_received_feedback_at),
210
+ lastEligibleRatingAt: optString(v.last_eligible_rating_at),
211
+ datedFeedbackCount: num(v.dated_feedback_count),
212
+ undatedFeedbackCount: num(v.undated_feedback_count),
213
+ timestampCoverage: optString(v.timestamp_coverage),
214
+ eligibleDatedCount: num(v.eligible_dated_count),
215
+ eligibleUndatedCount: num(v.eligible_undated_count),
216
+ eligibleTimestampCoverage: optString(v.eligible_timestamp_coverage),
217
+ refreshedAt: optString(v.refreshed_at),
218
+ indexerCheckedAt: optString(v.indexer_checked_at),
219
+ freshnessVersion: optString(v.freshness_version),
220
+ };
221
+ }
222
+
185
223
  function parseSnapshot(v: unknown): Snapshot | null {
186
224
  if (!isObj(v)) return null;
187
225
  const malformed: string[] = [];
@@ -353,6 +391,7 @@ export function parseWalletBreakdown(
353
391
  concentration: parseConcentration(payload.concentration),
354
392
  confidence: parseConfidence(payload.confidence),
355
393
  activity: parseActivity(payload.activity),
394
+ freshness: parseFreshness(payload.freshness),
356
395
  snapshot: parseSnapshot(payload.snapshot),
357
396
  payment,
358
397
  policyVersion: optString(payload.policy_version),
@@ -446,6 +485,8 @@ export function parseHealth(payload: unknown): IndexHealth {
446
485
  orderingPolicy: String(payload.ordering_policy ?? ''),
447
486
  raterWeightPolicy: String(payload.rater_weight_policy ?? ''),
448
487
  confidencePolicy: String(payload.confidence_policy ?? ''),
488
+ credibilityM: optNumber(payload.credibility_m),
489
+ freshness: parseFreshness(payload.freshness),
449
490
  confidenceThresholds: isObj(payload.confidence_thresholds)
450
491
  ? (payload.confidence_thresholds as Record<string, number>)
451
492
  : {},
package/src/types.ts CHANGED
@@ -229,11 +229,74 @@ export interface SelfRated {
229
229
  gap: number | null;
230
230
  }
231
231
 
232
+ /**
233
+ * First and last rating by ON-CHAIN time.
234
+ *
235
+ * `lastRatingAt` is the last **eligible** rating — the one that holds up the
236
+ * score being shown. Since describe.net 2026-09-10 it is documented as a
237
+ * compatibility alias of `Freshness.lastEligibleRatingAt` and keeps that exact
238
+ * meaning for the life of v1. Read `WalletBreakdown.freshness` for the question
239
+ * this pair never could answer: *was this subject described recently, whether
240
+ * or not it counts?*
241
+ */
232
242
  export interface Activity {
233
243
  firstRatingAt: Timestamp;
234
244
  lastRatingAt: Timestamp;
235
245
  }
236
246
 
247
+ /**
248
+ * WHAT the dates are about. A date without a scope is a date that lies.
249
+ *
250
+ * `direction` is the field that matters most: `received` is reputation the
251
+ * subject GOT, `emitted` is the ratings a wallet WROTE
252
+ * (`GET /reputation/rater/{wallet}`). Reading the second as the first turns a
253
+ * busy rater into a much-described subject.
254
+ */
255
+ export interface FreshnessScope {
256
+ kind: string | null;
257
+ direction: string | null;
258
+ id: string | null;
259
+ network: string | null;
260
+ declaredType: string | null;
261
+ }
262
+
263
+ /**
264
+ * WHEN this subject was last described. Two dates, because two questions.
265
+ *
266
+ * - `lastReceivedFeedbackAt` — the last real NewFeedback in scope, whether or
267
+ * not it feeds the score.
268
+ * - `lastEligibleRatingAt` — the last rating that holds up the number shown.
269
+ *
270
+ * When the most recent rating was revoked the two differ, and **that difference
271
+ * is the information**: there was recent activity and the score does not
272
+ * reflect it.
273
+ *
274
+ * NEITHER is `refreshedAt`, which is when the index recomputed its own view and
275
+ * says nothing about the subject.
276
+ *
277
+ * `timestampCoverage` is `none` | `unknown` | `partial` | `complete` over
278
+ * `dated + undated`. **`none` and `unknown` are different facts**: nothing to
279
+ * date versus dates we do not have yet.
280
+ *
281
+ * NO RELATIVE TEXT, deliberately. The API publishes UTC and nothing else, so
282
+ * "3 days ago" is derived at the edge with the reader's clock — a serialised
283
+ * relative string freezes in the first cache.
284
+ */
285
+ export interface Freshness {
286
+ scope: FreshnessScope;
287
+ lastReceivedFeedbackAt: Timestamp;
288
+ lastEligibleRatingAt: Timestamp;
289
+ datedFeedbackCount: number;
290
+ undatedFeedbackCount: number;
291
+ timestampCoverage: string | null;
292
+ eligibleDatedCount: number;
293
+ eligibleUndatedCount: number;
294
+ eligibleTimestampCoverage: string | null;
295
+ refreshedAt: Timestamp;
296
+ indexerCheckedAt: Timestamp;
297
+ freshnessVersion: string | null;
298
+ }
299
+
237
300
  /** One facet (`tag1`), as declared on-chain. */
238
301
  export interface Facet {
239
302
  score: number | null;
@@ -292,6 +355,12 @@ export interface WalletBreakdown extends Sealed {
292
355
  concentration: Concentration | null;
293
356
  confidence: Confidence | null;
294
357
  activity: Activity | null;
358
+ /**
359
+ * WHEN, with its scope. Additive: `activity` above keeps its exact meaning.
360
+ * `null` when the server does not publish the block yet — never an empty
361
+ * object, so "not published" and "no dates" stay distinguishable.
362
+ */
363
+ freshness: Freshness | null;
295
364
  snapshot: Snapshot | null;
296
365
  /** What was actually paid, if anything was. */
297
366
  payment: PaymentEvidence | null;
@@ -459,6 +528,25 @@ export interface IndexHealth {
459
528
  orderingPolicy: string;
460
529
  raterWeightPolicy: string;
461
530
  confidencePolicy: string;
531
+ /**
532
+ * The frozen `M` of the per-chain credibility weight, `Z_k = R_k/(R_k+M)`.
533
+ *
534
+ * REQUIRED in the server schema since `credibility-weight-per-chain@1`
535
+ * (2026-09-04) and untyped here until now — `types.schema.test.ts` caught it
536
+ * the moment the snapshot was refreshed. It ships live because the number is
537
+ * frozen and versioned: recomputing a `finalScore` by hand needs THIS M, not
538
+ * a copy of it that went stale.
539
+ */
540
+ credibilityM: number | null;
541
+ /**
542
+ * WHEN the index as a whole last received a description. The only free,
543
+ * account-less, parameter-less place to read whether describe.net is still
544
+ * taking in descriptions or merely still refreshing its views — the two look
545
+ * identical from the outside, which is the confusion `Freshness` closes.
546
+ *
547
+ * `null` against a server that does not publish it yet.
548
+ */
549
+ freshness: Freshness | null;
462
550
  /** e.g. `{no_ratings: 0, low: 1, medium: 3, high: 6}` — live, never re-typed. */
463
551
  confidenceThresholds: Record<string, number>;
464
552
  /** e.g. `{min_raters: 3, campaign_per_rater: 20, top_share: 0.5, ...}`. */