uvd-describe-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/parse.ts ADDED
@@ -0,0 +1,388 @@
1
+ /**
2
+ * Wire JSON → typed shape.
3
+ *
4
+ * Three rules, and each one is a bug that already happened somewhere:
5
+ *
6
+ * 1. **`null` survives.** `optNumber` returns `null` for `null` and NEVER `0`.
7
+ * Every `|| 0` in a parser is an invariant-7 violation waiting for its first
8
+ * unrated wallet.
9
+ * 2. **Unknown fields survive.** Every result keeps `raw`. The server may add a
10
+ * field tomorrow and a consumer must not wait for our release to read it.
11
+ * 3. **A body that is not the shape we asked for is `unparseable`, not
12
+ * garbage-in-silence.** The failure that has to be impossible here is a
13
+ * response that parses "successfully" into an object full of zeros.
14
+ * 4. **A hash field that is not a hash is dropped and MARKED, never passed
15
+ * through.** Added 2026-08-30 from KarmaKadabra's *"el 200 sin tx"*. The
16
+ * typed field goes `null` — nobody builds an explorer link out of garbage —
17
+ * and its wire name goes into the `malformedHashes` of the object that owns
18
+ * it, so that **absent** (`null`, list empty) stays distinguishable from
19
+ * **malformed** (`null`, name in the list). It is rule 1 one level down: the
20
+ * absence of a value and a value that is nonsense are different facts, and
21
+ * collapsing them is the failure this file exists to prevent. See
22
+ * `hashes.ts`, and `client.ts` for how the fact reaches the caller.
23
+ */
24
+
25
+ import { CAVEAT_SCOPE_FREE, CAVEAT_SCOPE_METERED, type Caveat } from './caveats';
26
+ import { DescribeUnparseable } from './errors';
27
+ import { hashField } from './hashes';
28
+ import type {
29
+ Activity,
30
+ AgentReputation,
31
+ Concentration,
32
+ Confidence,
33
+ Facet,
34
+ HealthChain,
35
+ IndexHealth,
36
+ LeaderboardRow,
37
+ Ownership,
38
+ PaymentEvidence,
39
+ Rating,
40
+ SelfRated,
41
+ Snapshot,
42
+ WalletBreakdown,
43
+ WalletChainRow,
44
+ WalletReputation,
45
+ } from './types';
46
+
47
+ type Obj = Record<string, unknown>;
48
+
49
+ const isObj = (v: unknown): v is Obj => typeof v === 'object' && v !== null && !Array.isArray(v);
50
+
51
+ /**
52
+ * `null` in, `null` out. The single most load-bearing line of this file.
53
+ *
54
+ * A missing score is `null`; a present score is a number. There is no third
55
+ * branch, and in particular there is no branch that produces `0`.
56
+ *
57
+ * Verified discriminant on 2026-08-30 by mounting the bad state: replacing the
58
+ * body below with `Number(v ?? 0)` turns three tests in `client.test.ts`
59
+ * ("R1 — null never 0") red, including the one that asserts an unrated wallet
60
+ * stays distinguishable from a wallet actually scored zero. A green suite with
61
+ * this function broken is not reachable, which is the only reason to trust the
62
+ * green one.
63
+ */
64
+ function optNumber(v: unknown): number | null {
65
+ if (v === null || v === undefined) return null;
66
+ const n = Number(v);
67
+ return Number.isFinite(n) ? n : null;
68
+ }
69
+
70
+ function num(v: unknown, fallback = 0): number {
71
+ const n = Number(v);
72
+ return Number.isFinite(n) ? n : fallback;
73
+ }
74
+
75
+ function optString(v: unknown): string | null {
76
+ return typeof v === 'string' ? v : null;
77
+ }
78
+
79
+ function strArray(v: unknown): string[] | null {
80
+ return Array.isArray(v) ? v.map(String) : null;
81
+ }
82
+
83
+ /**
84
+ * Caveats, keeping BOTH halves.
85
+ *
86
+ * EM's Python reference keeps only the `code` (`types.py:269-273`) so nobody
87
+ * can render the volatile prose. That is right for a reconciler and wrong for
88
+ * an SDK: a UI has to print SOMETHING, and if we drop `text` every consumer
89
+ * re-writes the eight strings by hand — the duplication this package exists to
90
+ * remove, and in the one field the index says may change without notice. So we
91
+ * carry both and the docs say which is the contract (`caveats.ts`).
92
+ *
93
+ * An entry that is not `{code, text}` is dropped rather than guessed at: a
94
+ * caveat we cannot name is a caveat we cannot let anyone branch on.
95
+ */
96
+ function parseCaveats(v: unknown): Caveat[] {
97
+ if (!Array.isArray(v)) return [];
98
+ const out: Caveat[] = [];
99
+ for (const entry of v) {
100
+ if (isObj(entry) && typeof entry.code === 'string') {
101
+ out.push({ code: entry.code, text: typeof entry.text === 'string' ? entry.text : '' });
102
+ }
103
+ }
104
+ return out;
105
+ }
106
+
107
+ function parseFacets(v: unknown): Record<string, Facet> {
108
+ if (!isObj(v)) return {};
109
+ const out: Record<string, Facet> = {};
110
+ for (const [key, raw] of Object.entries(v)) {
111
+ if (!isObj(raw)) continue;
112
+ out[key] = {
113
+ score: optNumber(raw.score),
114
+ count: num(raw.count),
115
+ distinctRaters: num(raw.distinct_raters),
116
+ revokedCount: num(raw.revoked_count),
117
+ outOfDomainCount: num(raw.out_of_domain_count),
118
+ selfRatedCount: num(raw.self_rated_count),
119
+ direction: optString(raw.direction),
120
+ directionCategory: optString(raw.direction_category),
121
+ directionMeaning: optString(raw.direction_meaning),
122
+ };
123
+ }
124
+ return out;
125
+ }
126
+
127
+ function parseSelfRated(v: unknown): SelfRated | null {
128
+ if (!isObj(v)) return null;
129
+ return { count: num(v.count), score: optNumber(v.score), gap: optNumber(v.gap) };
130
+ }
131
+
132
+ function parseConcentration(v: unknown): Concentration | null {
133
+ if (!isObj(v)) return null;
134
+ return {
135
+ distinctRaters: num(v.distinct_raters),
136
+ topClientShare: optNumber(v.top_client_share),
137
+ topClient: optString(v.top_client),
138
+ };
139
+ }
140
+
141
+ function parseConfidence(v: unknown): Confidence | null {
142
+ if (!isObj(v)) return null;
143
+ const iv = v.interval;
144
+ return {
145
+ band: String(v.band ?? ''),
146
+ distinctRaters: num(v.distinct_raters),
147
+ interval: isObj(iv) ? { lower: num(iv.lower), upper: num(iv.upper) } : null,
148
+ thresholds: isObj(v.thresholds) ? (v.thresholds as Record<string, number>) : {},
149
+ advice: String(v.advice ?? ''),
150
+ confidencePolicy: String(v.confidence_policy ?? ''),
151
+ };
152
+ }
153
+
154
+ function parseActivity(v: unknown): Activity | null {
155
+ if (!isObj(v)) return null;
156
+ return { firstRatingAt: optString(v.first_rating_at), lastRatingAt: optString(v.last_rating_at) };
157
+ }
158
+
159
+ function parseSnapshot(v: unknown): Snapshot | null {
160
+ if (!isObj(v)) return null;
161
+ const malformed: string[] = [];
162
+ return {
163
+ id: num(v.id),
164
+ // A bare sha256 hexdigest, no `0x` (`aggregate.py:1920`). This one is worth
165
+ // validating precisely because it is the citable field: two snapshots with
166
+ // the same digest are supposed to say the same thing, and a comparison
167
+ // between two garbage strings can agree by accident.
168
+ inputsDigest: hashField(v, 'inputs_digest', malformed),
169
+ policyVersion: String(v.policy_version ?? ''),
170
+ computedAt: String(v.computed_at ?? ''),
171
+ malformedHashes: malformed,
172
+ };
173
+ }
174
+
175
+ function parseOwnership(v: unknown): Ownership | null {
176
+ if (!isObj(v)) return null;
177
+ return {
178
+ ownerUpdatedBlock: num(v.owner_updated_block),
179
+ identityTransferred: typeof v.identity_transferred === 'boolean' ? v.identity_transferred : null,
180
+ inheritedReviewCount: num(v.inherited_review_count),
181
+ inheritedScore: optNumber(v.inherited_score),
182
+ currentEraReviewCount: num(v.current_era_review_count),
183
+ currentEraScore: optNumber(v.current_era_score),
184
+ undeterminedReviewCount: num(v.undetermined_review_count),
185
+ inheritedShare: optNumber(v.inherited_share),
186
+ };
187
+ }
188
+
189
+ /**
190
+ * One rating, with its THREE hash fields shape-validated.
191
+ *
192
+ * KarmaKadabra's contribution (2026-08-30): a `tx_hash` that is not a hash is a
193
+ * 200 that did not do the thing, and *"si nosotros no chequeáramos el tx,
194
+ * habríamos contado 14 ratings que no existen"*. Anything that is not a hash
195
+ * becomes `null` and its wire name goes into the rating's `malformedHashes` —
196
+ * never an exception, because one bad accessory field must not destroy a
197
+ * decomposition the caller paid for. See `hashes.ts` for the four legitimate
198
+ * shapes and for why an EVM-only regex would have flagged all of Solana.
199
+ */
200
+ function parseRatings(v: unknown): Rating[] {
201
+ if (!Array.isArray(v)) return [];
202
+ return v.filter(isObj).map((r) => {
203
+ const malformed: string[] = [];
204
+ return {
205
+ client: String(r.client ?? ''),
206
+ feedbackIndex: num(r.feedback_index),
207
+ value: num(r.value),
208
+ valueDecimals: num(r.value_decimals),
209
+ normalizedValue: optNumber(r.normalized_value),
210
+ tag1: optString(r.tag1),
211
+ tag2: optString(r.tag2),
212
+ isRevoked: r.is_revoked === true,
213
+ isSelf: r.is_self === true,
214
+ txHash: hashField(r, 'tx_hash', malformed),
215
+ blockNumber: optNumber(r.block_number),
216
+ logIndex: optNumber(r.log_index),
217
+ feedbackUri: optString(r.feedback_uri),
218
+ issuerHost: optString(r.issuer_host),
219
+ issuer: optString(r.issuer),
220
+ issuerOrg: optString(r.issuer_org),
221
+ feedbackHash: hashField(r, 'feedback_hash', malformed),
222
+ revokedTx: hashField(r, 'revoked_tx', malformed),
223
+ malformedHashes: malformed,
224
+ };
225
+ });
226
+ }
227
+
228
+ // ---------------------------------------------------------------------------
229
+
230
+ /** `GET /wallets/{wallet}/chains`. Requires `wallet` — everything else may be absent. */
231
+ export function parseWalletReputation(payload: unknown): WalletReputation {
232
+ if (!isObj(payload) || typeof payload.wallet !== 'string') {
233
+ throw new DescribeUnparseable('wallet-chains response is missing its essential shape (wallet)');
234
+ }
235
+ const rows = Array.isArray(payload.chains) ? payload.chains : [];
236
+ const chains: WalletChainRow[] = rows.filter(isObj).map((row) => ({
237
+ network: String(row.network ?? ''),
238
+ agentCount: num(row.agent_count),
239
+ agentIds: strArray(row.agent_ids),
240
+ finalScore: optNumber(row.final_score),
241
+ totalReviews: num(row.total_reviews),
242
+ distinctRaters: num(row.distinct_raters),
243
+ }));
244
+
245
+ return {
246
+ wallet: payload.wallet,
247
+ chains,
248
+ globalScore: optNumber(payload.global_score),
249
+ distinctRaters: optNumber(payload.distinct_raters),
250
+ identityCount: num(payload.identity_count),
251
+ chainsWithIdentity: num(payload.chains_with_identity),
252
+ chainsWithReputation: num(payload.chains_with_reputation),
253
+ totalReviews: num(payload.total_reviews),
254
+ policyVersion: optString(payload.policy_version),
255
+ caveats: parseCaveats(payload.caveats),
256
+ caveatScope: CAVEAT_SCOPE_FREE,
257
+ source: optString(payload.source),
258
+ refreshedAt: optString(payload.refreshed_at),
259
+ raw: payload,
260
+ };
261
+ }
262
+
263
+ /** `GET /reputation/wallet/{wallet}` — metered. */
264
+ export function parseWalletBreakdown(
265
+ payload: unknown,
266
+ payment: PaymentEvidence | null,
267
+ ): WalletBreakdown {
268
+ if (!isObj(payload) || typeof payload.wallet !== 'string') {
269
+ throw new DescribeUnparseable('wallet-breakdown response is missing its essential shape (wallet)');
270
+ }
271
+ return {
272
+ wallet: payload.wallet,
273
+ finalScore: optNumber(payload.final_score),
274
+ weightedScore: optNumber(payload.weighted_score),
275
+ raterWeightPolicy: String(payload.rater_weight_policy ?? ''),
276
+ chainCount: num(payload.chain_count),
277
+ totalReviews: num(payload.total_reviews),
278
+ perChain: isObj(payload.per_chain) ? payload.per_chain : {},
279
+ facets: parseFacets(payload.facets),
280
+ selfRated: parseSelfRated(payload.self_rated),
281
+ concentration: parseConcentration(payload.concentration),
282
+ confidence: parseConfidence(payload.confidence),
283
+ activity: parseActivity(payload.activity),
284
+ snapshot: parseSnapshot(payload.snapshot),
285
+ payment,
286
+ policyVersion: optString(payload.policy_version),
287
+ caveats: parseCaveats(payload.caveats),
288
+ caveatScope: CAVEAT_SCOPE_METERED,
289
+ source: optString(payload.source),
290
+ refreshedAt: optString(payload.refreshed_at),
291
+ raw: payload,
292
+ };
293
+ }
294
+
295
+ /** `GET /reputation/agent/{network}/{agent_id}` — metered. */
296
+ export function parseAgentReputation(
297
+ payload: unknown,
298
+ payment: PaymentEvidence | null,
299
+ ): AgentReputation {
300
+ if (!isObj(payload) || payload.agent_id === undefined) {
301
+ throw new DescribeUnparseable('agent response is missing its essential shape (agent_id)');
302
+ }
303
+ return {
304
+ network: String(payload.network ?? ''),
305
+ agentId: String(payload.agent_id),
306
+ currentOwner: optString(payload.current_owner),
307
+ declaredType: optString(payload.declared_type),
308
+ agentUri: optString(payload.agent_uri),
309
+ indexedIdentity: payload.indexed_identity === true,
310
+ score: optNumber(payload.score),
311
+ reviewCount: num(payload.review_count),
312
+ revokedCount: num(payload.revoked_count),
313
+ outOfDomainCount: num(payload.out_of_domain_count),
314
+ selfRated: parseSelfRated(payload.self_rated),
315
+ facets: parseFacets(payload.facets),
316
+ concentration: parseConcentration(payload.concentration),
317
+ ownership: parseOwnership(payload.ownership),
318
+ confidence: parseConfidence(payload.confidence),
319
+ ratings: parseRatings(payload.ratings),
320
+ payment,
321
+ policyVersion: optString(payload.policy_version),
322
+ caveats: parseCaveats(payload.caveats),
323
+ caveatScope: CAVEAT_SCOPE_METERED,
324
+ source: optString(payload.source),
325
+ refreshedAt: optString(payload.refreshed_at),
326
+ raw: payload,
327
+ };
328
+ }
329
+
330
+ /**
331
+ * `GET /leaderboard` — a bare JSON array (verified live 2026-08-30: 100 rows,
332
+ * no envelope). NOT `{rows: [...]}`, which is what a reader expecting a
333
+ * paginated shape would assume.
334
+ */
335
+ export function parseLeaderboard(payload: unknown): LeaderboardRow[] {
336
+ if (!Array.isArray(payload)) {
337
+ throw new DescribeUnparseable('leaderboard response is not an array');
338
+ }
339
+ return payload.filter(isObj).map((row) => ({
340
+ rank: num(row.rank),
341
+ wallet: String(row.wallet ?? ''),
342
+ finalScore: optNumber(row.final_score),
343
+ shrunkScore: optNumber(row.shrunk_score),
344
+ distinctRaters: num(row.distinct_raters),
345
+ chainCount: num(row.chain_count),
346
+ totalReviews: num(row.total_reviews),
347
+ networks: Array.isArray(row.networks) ? row.networks.map(String) : [],
348
+ declaredTypes: Array.isArray(row.declared_types)
349
+ ? row.declared_types.map((t) => (typeof t === 'string' ? t : null))
350
+ : [],
351
+ raw: row,
352
+ }));
353
+ }
354
+
355
+ /** `GET /health`. */
356
+ export function parseHealth(payload: unknown): IndexHealth {
357
+ if (!isObj(payload) || typeof payload.status !== 'string') {
358
+ throw new DescribeUnparseable('health response is missing its essential shape (status)');
359
+ }
360
+ const chains: HealthChain[] = (Array.isArray(payload.chains) ? payload.chains : [])
361
+ .filter(isObj)
362
+ .map((row) => ({
363
+ network: String(row.network ?? ''),
364
+ lastScannedBlock: optNumber(row.last_scanned_block),
365
+ updatedAt: optString(row.updated_at),
366
+ nextSyncAt: optString(row.next_sync_at),
367
+ lastError: optString(row.last_error),
368
+ raw: row,
369
+ }));
370
+
371
+ return {
372
+ status: payload.status,
373
+ policyVersion: String(payload.policy_version ?? ''),
374
+ orderingPolicy: String(payload.ordering_policy ?? ''),
375
+ raterWeightPolicy: String(payload.rater_weight_policy ?? ''),
376
+ confidencePolicy: String(payload.confidence_policy ?? ''),
377
+ confidenceThresholds: isObj(payload.confidence_thresholds)
378
+ ? (payload.confidence_thresholds as Record<string, number>)
379
+ : {},
380
+ readingPolicy: isObj(payload.reading_policy) ? payload.reading_policy : {},
381
+ buildSha: optString(payload.build_sha),
382
+ agents: num(payload.agents),
383
+ feedbackEntries: num(payload.feedback_entries),
384
+ indexerPeriodSeconds: optNumber(payload.indexer_period_seconds),
385
+ chains,
386
+ raw: payload,
387
+ };
388
+ }
@@ -0,0 +1,295 @@
1
+ /**
2
+ * The partner rail — how a product of the house reads describe.net for free.
3
+ *
4
+ * ## What this is, in one paragraph
5
+ *
6
+ * describe.net has no accounts and no API keys, on purpose: *"el pago es la
7
+ * autenticación"*. So when Execution Market, MeshRelay and KarmaKadabra
8
+ * deprecated their local reputation maths and became read-dependencies of the
9
+ * index (2026-08-28), the question "does a service of the house pay like a
10
+ * stranger?" could not be answered with a token. It was answered with an
11
+ * ALLOWLIST OF PUBLIC ADDRESSES plus a per-request ERC-8128 signature
12
+ * (`describe-net/describenet/partner.py`). The partner holds a dedicated wallet
13
+ * with no funds whose only job is to sign; describe.net holds a list of
14
+ * addresses. **The service custodies no secret of ours** — a breach there leaks
15
+ * a list of things that were already public — and that property, not
16
+ * convenience, is why this is a signature and not the `X-API-Key` everyone
17
+ * reaches for first.
18
+ *
19
+ * This module is the client half. It is the only file in this package with a
20
+ * RUNTIME import of `uvd-x402-sdk`, which is why it lives behind the
21
+ * `uvd-describe-sdk/partner` subpath: the main entry and the `x402` entry keep
22
+ * their zero-runtime-imports property, and a consumer who never signs installs
23
+ * nothing.
24
+ *
25
+ * ## Upstream-first: the primitive already existed, MEASURED before writing
26
+ *
27
+ * `uvd-x402-sdk` 2.75.0 (installed, checked 2026-08-30) exports the whole
28
+ * ERC-8128 signer from `uvd-x402-sdk/erc8128` — `signRequest`,
29
+ * `signRequestWithSigner`, `signRequestWithWallet`, plus the pure base builder
30
+ * and the verifier. So NOTHING is signed in this repo: this file picks a chain
31
+ * id and a nonce and forwards. Not one byte of RFC 9421 canonicalisation is
32
+ * reimplemented here, and if any of it ever needs to change, it changes THERE.
33
+ *
34
+ * Verified end to end, offline, on 2026-08-30: headers produced by
35
+ * `signRequestWithSigner` at chain 8453 verify under the EXACT policy
36
+ * `partner.py` builds (authority `api.describe.net`, `allowed_chain_ids=[8453]`,
37
+ * `max_validity_sec=300`, `clock_skew_future_sec=30`), recovering the signer's
38
+ * address. `partner.test.ts` is that probe, kept as a test.
39
+ *
40
+ * ## The nonce: minted here, and here is the argument
41
+ *
42
+ * The payment SDK requires a nonce and refuses to invent one — *"a local nonce
43
+ * authenticates against a first-use-wins store and is rejected by an
44
+ * issuer-bound one, which turns a server blip into an auth mystery"*
45
+ * (`erc8128/signer.ts:15-17`). That reasoning is about servers that HAVE a nonce
46
+ * store. describe.net has none: `PartnerGate` builds its `VerifyPolicy` with no
47
+ * `nonce` field at all (`partner.py:216-223`), and the verifier skips every
48
+ * nonce rule when `policy.nonce is None` — no presence check
49
+ * (`verifier.py:458-462`), no consumption (`verifier.py:304`). Read in the
50
+ * installed PyPI `uvd-x402-sdk` 0.70.0 on 2026-08-30.
51
+ *
52
+ * So there is no store to be unknown to, and a locally minted random nonce is
53
+ * strictly better than the alternative the policy would also accept (none at
54
+ * all): it makes each signature unique, so two identical GETs in the same second
55
+ * do not produce byte-identical headers. This is the caller owning the
56
+ * consequence, which is exactly what `onNonceUnavailable` exists to express in
57
+ * the payment SDK — stated here rather than hidden.
58
+ *
59
+ * 🔴 If describe.net ever adds a nonce store, this line becomes wrong and the
60
+ * failure is loud, not silent: every partner request starts answering 402 with
61
+ * `nonce_unknown` and `DescribePartnerRejected` says so. That is the direction
62
+ * this failure should point.
63
+ *
64
+ * ## What is signed, and the consequence of a custom `baseUrl`
65
+ *
66
+ * The signature covers `@method`, `@authority` and `@path` (plus `@query` when
67
+ * there is one), and `@authority` comes from the URL being requested. The gate
68
+ * pins `api.describe.net` and NEVER derives it from a header (`partner.py:73-84`
69
+ * — deriving an authority from client-controlled input is how a verifier was
70
+ * once made to rebuild a base over an attacker's domain). So a client pointed at
71
+ * any other origin — a staging host, a proxy, the raw execute-api host behind
72
+ * CloudFront — signs an authority the gate does not accept and is charged. That
73
+ * is deliberate on both sides, and it fails LOUDLY here as
74
+ * `DescribePartnerRejected` rather than quietly as a bill.
75
+ */
76
+
77
+ import {
78
+ CONFORMANCE_VECTORS_F3_1,
79
+ signRequest,
80
+ signRequestWithSigner,
81
+ } from 'uvd-x402-sdk/erc8128';
82
+
83
+ import type { PartnerSigner } from '../client';
84
+ import { PARTNER_CHAIN_ID, PARTNER_KEY_ENV } from '../config';
85
+
86
+ /**
87
+ * The signer's typed header object as a plain `Record<string, string>`.
88
+ *
89
+ * Not cosmetic: `Erc8128Headers` declares `'Content-Digest'?: string`, and an
90
+ * interface with an optional member is not assignable to `Record<string,
91
+ * string>` — the dts build says so, loudly (TS2322 at the return, TS2345 at the
92
+ * parameter, which is why the parameter is `object` and not a `Record` of its
93
+ * own). Dropping the undefined entries here is the honest conversion, and it
94
+ * means the client never merges a header whose value is `undefined` into a
95
+ * `fetch` call, which is how a literal `"undefined"` ends up on a wire.
96
+ */
97
+ function plainHeaders(headers: object): Record<string, string> {
98
+ const out: Record<string, string> = {};
99
+ for (const [name, value] of Object.entries(headers)) {
100
+ if (typeof value === 'string') out[name] = value;
101
+ }
102
+ return out;
103
+ }
104
+
105
+ /** A 128-bit hex nonce. See the module header for why this is minted locally. */
106
+ function mintNonce(): string {
107
+ const bytes = new Uint8Array(16);
108
+ // `globalThis.crypto` is standard in Node >= 18 and in every browser, which
109
+ // is the same floor as this package's `engines`. No import, no polyfill.
110
+ globalThis.crypto.getRandomValues(bytes);
111
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
112
+ }
113
+
114
+ /** What every factory here accepts. Both fields have defaults that are right. */
115
+ export interface PartnerOptions {
116
+ /**
117
+ * The keyid's chain id. Defaults to `PARTNER_CHAIN_ID` (8453, Base), which is
118
+ * what the gate pins. Override only if describe.net's `CHAIN_ID` moves.
119
+ */
120
+ chainId?: number;
121
+ }
122
+
123
+ /**
124
+ * The rail, from a signer you already have. **This is the preferred form.**
125
+ *
126
+ * It takes an OBJECT THAT SIGNS, never a key: a browser wallet, an ethers
127
+ * `Wallet` built somewhere else, an OWS vault, a KMS client, a queue that asks a
128
+ * human. The key material never enters this package, never enters
129
+ * `uvd-x402-sdk`'s signer, and cannot end up in a stack trace it produces.
130
+ *
131
+ * ```ts
132
+ * import { DescribeClient } from 'uvd-describe-sdk';
133
+ * import { partnerFromSigner } from 'uvd-describe-sdk/partner';
134
+ *
135
+ * // `wallet` is yours — this package never learns how it holds its key.
136
+ * const describe = new DescribeClient({
137
+ * product: 'meshrelay',
138
+ * partner: partnerFromSigner({
139
+ * address: await wallet.getAddress(),
140
+ * signMessage: (base) => wallet.signMessage(base),
141
+ * }),
142
+ * });
143
+ *
144
+ * // Metered route, no payer, no USDC: the free rail carries it.
145
+ * const detail = await describe.walletBreakdown('0x97cd…0996');
146
+ * ```
147
+ *
148
+ * `signMessage` is an EIP-191 `personal_sign` over the string it is handed and
149
+ * must return `0x` + 130 hex. It is the ONE thing this rail cannot do for you.
150
+ */
151
+ export function partnerFromSigner(
152
+ signer: {
153
+ /** The signing wallet's address. Public by design — the allowlist is public. */
154
+ address: string;
155
+ /** EIP-191 personal_sign over the signature base. */
156
+ signMessage(message: string): string | Promise<string>;
157
+ } & PartnerOptions,
158
+ ): PartnerSigner {
159
+ const { address, signMessage, chainId = PARTNER_CHAIN_ID } = signer;
160
+ return {
161
+ address,
162
+ async sign({ method, url }) {
163
+ return plainHeaders(
164
+ await signRequestWithSigner({
165
+ method,
166
+ url,
167
+ address,
168
+ chainId,
169
+ nonce: mintNonce(),
170
+ signMessage,
171
+ }),
172
+ );
173
+ },
174
+ };
175
+ }
176
+
177
+ /**
178
+ * The rail, from a private key **the environment holds**.
179
+ *
180
+ * ## Why this reads the variable itself instead of taking a string
181
+ *
182
+ * Because a function that takes a key as an argument is a function somebody
183
+ * calls with a literal. Two DAO wallets were drained in minutes by bots
184
+ * scanning public repositories for `0x` + 64 hex (INC-2026-03-30), and "it was
185
+ * only for a test" is how both got there. This signature makes the safe path
186
+ * the only path: the key can come from `process.env` and from nowhere else, so
187
+ * there is no argument to paste one into. If your key lives somewhere better —
188
+ * Secrets Manager, a vault, a hardware signer — fetch it there and use
189
+ * {@link partnerFromSigner}, which never sees a key at all.
190
+ *
191
+ * ```ts
192
+ * // DESCRIBE_PARTNER_PRIVATE_KEY is set in the environment. Never in code.
193
+ * const describe = new DescribeClient({
194
+ * product: 'karmakadabra',
195
+ * partner: partnerFromEnv(),
196
+ * });
197
+ * ```
198
+ *
199
+ * Throws immediately — at wiring time, not at the first request — when the
200
+ * variable is unset or malformed. A partner rail that is going to fail should
201
+ * fail before the process claims to be up.
202
+ *
203
+ * ## 🔴 The shape check, and the measurement that put it here
204
+ *
205
+ * The key is trimmed and checked against `^(0x)?[0-9a-fA-F]{64}$` before it
206
+ * reaches the payment SDK, and that is a SECURITY guard, not politeness.
207
+ * Measured 2026-08-30 with `ethers` 6.17.0, the version `uvd-x402-sdk` 2.75.0
208
+ * pulls in:
209
+ *
210
+ * * `new ethers.Wallet('0x'+64hex)` with a **trailing newline** — the single
211
+ * most common way an env var gets malformed, e.g. `KEY=$(cat file)` —
212
+ * throws `invalid BytesLike value (argument="value", value="0xabab…ab\n")`.
213
+ * **The entire private key is inside the message, verbatim.**
214
+ * * only a well-formed-but-invalid key reaches the redacted path,
215
+ * `invalid private key (argument="privateKey", value="[REDACTED]")`.
216
+ *
217
+ * So the redaction everyone assumes is there covers the second case and not the
218
+ * first, and the first is the likely one. Trimming closes the newline path; the
219
+ * shape check guarantees that whatever reaches `ethers` is exactly 64 hex
220
+ * characters and can therefore only fail into the REDACTED branch. The error
221
+ * this function throws names the variable and the length and never the value.
222
+ *
223
+ * ⚠️ Reported upstream, not patched there by this session: `signRequest` in
224
+ * `uvd-x402-sdk/erc8128` hands its `privateKey` straight to `new
225
+ * ethers.Wallet()` (`signer.ts:255-258`) and has the same exposure for anyone
226
+ * calling it directly. The house rule is that the fix goes upstream; this guard
227
+ * protects THIS path in the meantime and is not a reimplementation of anything.
228
+ */
229
+ export function partnerFromEnv(
230
+ options: PartnerOptions & {
231
+ /** Which variable holds the key. Defaults to `DESCRIBE_PARTNER_PRIVATE_KEY`. */
232
+ envVar?: string;
233
+ /** Injectable for tests. Defaults to `process.env`. */
234
+ env?: Record<string, string | undefined>;
235
+ } = {},
236
+ ): PartnerSigner {
237
+ const { chainId = PARTNER_CHAIN_ID, envVar = PARTNER_KEY_ENV } = options;
238
+ const env = options.env ?? (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;
239
+
240
+ const raw = env?.[envVar];
241
+ if (typeof raw !== 'string' || raw.trim() === '') {
242
+ throw new Error(
243
+ `partnerFromEnv: ${envVar} is not set. The partner rail signs every ` +
244
+ 'request with a dedicated wallet; without its key this client is an ' +
245
+ 'anonymous client, and an anonymous client pays. Set the variable, or ' +
246
+ 'use partnerFromSigner() with a signer you build yourself.',
247
+ );
248
+ }
249
+
250
+ // Trimmed on purpose: a private key has no meaningful surrounding
251
+ // whitespace, and the alternative to trimming is the ethers leak above.
252
+ const key = raw.trim();
253
+ if (!/^(0x)?[0-9a-fA-F]{64}$/.test(key)) {
254
+ // Length and nothing else. Never the value, never a prefix of it, never a
255
+ // "did you mean" that echoes it back.
256
+ throw new Error(
257
+ `partnerFromEnv: ${envVar} is not a 32-byte hex private key ` +
258
+ `(got ${key.length} characters after trimming; expected 64, or 66 with ` +
259
+ 'the 0x prefix). The value is deliberately not shown.',
260
+ );
261
+ }
262
+
263
+ // The address is derived by the payment SDK from the key, so we do not know
264
+ // it here without building a wallet ourselves — which would mean importing
265
+ // `ethers` into this package. It stays undefined; error messages lose one
266
+ // detail and this package keeps its dependency list empty.
267
+ return {
268
+ async sign({ method, url }) {
269
+ return plainHeaders(
270
+ await signRequest({ method, url, chainId, nonce: mintNonce(), privateKey: key }),
271
+ );
272
+ },
273
+ };
274
+ }
275
+
276
+ /**
277
+ * The synthetic key the payment SDK ships in its ERC-8128 conformance vectors,
278
+ * documented there as a key that never held funds.
279
+ *
280
+ * Exported for one reason: so that a consumer's own tests can exercise the
281
+ * partner rail without anybody typing 64 hex characters into a repository. It
282
+ * is read out of the installed package at call time and is not stored anywhere
283
+ * in this one.
284
+ *
285
+ * 🔴 It is PUBLIC and it is in everybody's `node_modules`. Never fund it, never
286
+ * allowlist it, never use it outside a test.
287
+ */
288
+ export function syntheticTestKey(): string {
289
+ const key = CONFORMANCE_VECTORS_F3_1.frozen.private_key;
290
+ if (!key) throw new Error('the installed uvd-x402-sdk ships no synthetic test key');
291
+ return key;
292
+ }
293
+
294
+ export type { PartnerSigner } from '../client';
295
+ export { PARTNER_CHAIN_ID, PARTNER_KEY_ENV } from '../config';