@me2em/core 1.0.0-rc.1 → 1.0.0-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/attestation.ts +154 -2
- package/src/handle.ts +27 -0
- package/src/identity.ts +26 -0
- package/src/index.ts +15 -0
- package/src/payment.ts +326 -0
- package/src/wallet-binding.ts +70 -0
package/dist/index.d.ts
CHANGED
|
@@ -35,4 +35,5 @@ export * as crypto from './crypto/index.js';
|
|
|
35
35
|
*/
|
|
36
36
|
export { generateSeedPhrase, normalizeSeedPhrase, validateSeedPhrase, get64ByteSeedFromMnemonic, type SeedStrength, type SeedValidationResult } from './seed.js';
|
|
37
37
|
export { wordlist } from '@scure/bip39/wordlists/english';
|
|
38
|
+
export { base64urlEncode, base64urlDecode } from './util.js';
|
|
38
39
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,KAAK,cAAc,EAAE,KAAK,qBAAqB,EAAE,KAAK,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACpH,OAAO,EAAE,SAAS,EAAE,KAAK,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,YAAY,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,cAAc,EAAE,KAAK,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACzG,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,KAAK,gBAAgB,EAAE,KAAK,kBAAkB,EAAE,KAAK,oBAAoB,EAAE,KAAK,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAC9M,OAAO,KAAK,MAAM,MAAM,mBAAmB,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,kBAAkB,EAClB,yBAAyB,EACzB,KAAK,YAAY,EACjB,KAAK,oBAAoB,EAC1B,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,KAAK,cAAc,EAAE,KAAK,qBAAqB,EAAE,KAAK,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACpH,OAAO,EAAE,SAAS,EAAE,KAAK,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,YAAY,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,cAAc,EAAE,KAAK,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACzG,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,KAAK,gBAAgB,EAAE,KAAK,kBAAkB,EAAE,KAAK,oBAAoB,EAAE,KAAK,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAC9M,OAAO,KAAK,MAAM,MAAM,mBAAmB,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,kBAAkB,EAClB,yBAAyB,EACzB,KAAK,YAAY,EACjB,KAAK,oBAAoB,EAC1B,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -34,4 +34,5 @@ export * as crypto from './crypto/index.js';
|
|
|
34
34
|
*/
|
|
35
35
|
export { generateSeedPhrase, normalizeSeedPhrase, validateSeedPhrase, get64ByteSeedFromMnemonic } from './seed.js';
|
|
36
36
|
export { wordlist } from '@scure/bip39/wordlists/english';
|
|
37
|
+
export { base64urlEncode, base64urlDecode } from './util.js';
|
|
37
38
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,MAAM,EAAiF,MAAM,aAAa,CAAC;AACpH,OAAO,EAAE,SAAS,EAA0B,MAAM,gBAAgB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAE,OAAO,EAAoE,MAAM,cAAc,CAAC;AACzG,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,uBAAuB,EAAoG,MAAM,kBAAkB,CAAC;AAC9M,OAAO,KAAK,MAAM,MAAM,mBAAmB,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,kBAAkB,EAClB,yBAAyB,EAG1B,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,MAAM,EAAiF,MAAM,aAAa,CAAC;AACpH,OAAO,EAAE,SAAS,EAA0B,MAAM,gBAAgB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAE,OAAO,EAAoE,MAAM,cAAc,CAAC;AACzG,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,uBAAuB,EAAoG,MAAM,kBAAkB,CAAC;AAC9M,OAAO,KAAK,MAAM,MAAM,mBAAmB,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,kBAAkB,EAClB,yBAAyB,EAG1B,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC"}
|
package/package.json
CHANGED
package/src/attestation.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { base64urlEncode, base64urlDecode, randomUUID, safeJsonParse } from './u
|
|
|
8
8
|
import { ed } from './crypto/init.js';
|
|
9
9
|
import type { Signer } from './types.js';
|
|
10
10
|
import { AttestationError, type AttestationErrorCode } from './errors.js';
|
|
11
|
+
import { getWalletAdapter, isValidChain } from './payment.js';
|
|
11
12
|
|
|
12
13
|
export { AttestationError, type AttestationErrorCode, type AttestationLevel } from './errors.js';
|
|
13
14
|
|
|
@@ -50,6 +51,17 @@ export interface AttestationPayload {
|
|
|
50
51
|
iat: number;
|
|
51
52
|
exp: number;
|
|
52
53
|
jti: string;
|
|
54
|
+
/**
|
|
55
|
+
* v1 optional extensions (specs/v1.0.md §5.1) — the canonical tail of
|
|
56
|
+
* the serialization order: `…, jti, subjectWallet, subjectWalletChain,
|
|
57
|
+
* subjectWalletPath`. Absent fields are omitted entirely (never
|
|
58
|
+
* `null`, never `""`); tokens without them are byte-identical to the
|
|
59
|
+
* pre-extension format. Pairing (address ⇔ chain, path ⇒ address) is
|
|
60
|
+
* enforced at issue time; decode tolerates any string values.
|
|
61
|
+
*/
|
|
62
|
+
subjectWallet?: string;
|
|
63
|
+
subjectWalletChain?: string;
|
|
64
|
+
subjectWalletPath?: string;
|
|
53
65
|
}
|
|
54
66
|
|
|
55
67
|
function throwFormat(code: AttestationErrorCode, msg: string): never {
|
|
@@ -112,6 +124,104 @@ function parseToken(token: string): ParseResult {
|
|
|
112
124
|
return { payloadBytes, signatureBytes, payload };
|
|
113
125
|
}
|
|
114
126
|
|
|
127
|
+
/**
|
|
128
|
+
* Validates the v1 optional wallet extensions (§5.1) passed in
|
|
129
|
+
* `Attestation.issue` opts. No-op when all three are absent. Order is
|
|
130
|
+
* normative:
|
|
131
|
+
*
|
|
132
|
+
* 1. Pairing (§5.1 rule 2) — `subjectWallet` and `subjectWalletChain`
|
|
133
|
+
* together or not at all (a chain without an address is invalid);
|
|
134
|
+
* `subjectWalletPath` only with an address. These checks PRECEDE any
|
|
135
|
+
* adapter lookup.
|
|
136
|
+
* 2. Structural (rule 4) — every present field is a non-empty string
|
|
137
|
+
* without any whitespace character (the full `\s` class: space, tab,
|
|
138
|
+
* newline, vertical tab, form feed, carriage return, NBSP and other
|
|
139
|
+
* Unicode space separators).
|
|
140
|
+
* 3. CAIP-2 grammar (rule 4) — `subjectWalletChain` via
|
|
141
|
+
* `isValidChain` (namespace `[-a-z0-9]{3,8}`, reference
|
|
142
|
+
* `[-a-zA-Z0-9]{1,64}`).
|
|
143
|
+
* 4. Adapter-aware, fail-closed (rule 5) — when an adapter is
|
|
144
|
+
* registered for the exact chain value, the address MUST pass
|
|
145
|
+
* `adapter.isValidAddress()`; otherwise issuance applies rules 1–3
|
|
146
|
+
* only (identity-only context). On-curve is deliberately not checked
|
|
147
|
+
* here — it belongs to wallet-binding verification.
|
|
148
|
+
*/
|
|
149
|
+
function validateWalletOpts(
|
|
150
|
+
opts?: { subjectWallet?: string; subjectWalletChain?: string; subjectWalletPath?: string }
|
|
151
|
+
): { subjectWallet?: string; subjectWalletChain?: string; subjectWalletPath?: string } {
|
|
152
|
+
const { subjectWallet, subjectWalletChain, subjectWalletPath } = opts ?? {};
|
|
153
|
+
|
|
154
|
+
// 1. Pairing — before any adapter lookup: the wallet fields are issued
|
|
155
|
+
// in pairs (both or none), and a derivation path requires an address.
|
|
156
|
+
// The nested guards keep every failure message distinct and let the
|
|
157
|
+
// compiler narrow `subjectWallet` / `subjectWalletChain` to `string`
|
|
158
|
+
// for steps 2–4 (no casts).
|
|
159
|
+
if (subjectWallet === undefined) {
|
|
160
|
+
if (subjectWalletChain !== undefined) {
|
|
161
|
+
throwFormat(
|
|
162
|
+
'MALFORMED',
|
|
163
|
+
'subjectWalletChain without subjectWallet — the wallet fields are issued in pairs (both or none)'
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
if (subjectWalletPath !== undefined) {
|
|
167
|
+
throwFormat(
|
|
168
|
+
'MALFORMED',
|
|
169
|
+
'subjectWalletPath without subjectWallet — a derivation path requires an address'
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
return {};
|
|
173
|
+
}
|
|
174
|
+
if (subjectWalletChain === undefined) {
|
|
175
|
+
throwFormat(
|
|
176
|
+
'MALFORMED',
|
|
177
|
+
'subjectWallet without subjectWalletChain — the wallet fields are issued in pairs (both or none)'
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// 2. Structural: string type, non-empty, no whitespace (full \s class).
|
|
182
|
+
// The wallet and chain are both present here (pairing above); the typeof
|
|
183
|
+
// checks stay as a fail-closed runtime defense for untyped JS callers.
|
|
184
|
+
const present: Array<[string, string]> = [
|
|
185
|
+
['subjectWallet', subjectWallet],
|
|
186
|
+
['subjectWalletChain', subjectWalletChain],
|
|
187
|
+
];
|
|
188
|
+
if (subjectWalletPath !== undefined) present.push(['subjectWalletPath', subjectWalletPath]);
|
|
189
|
+
for (const [field, value] of present) {
|
|
190
|
+
if (typeof value !== 'string') {
|
|
191
|
+
throwFormat('MALFORMED', `${field} must be a string`);
|
|
192
|
+
}
|
|
193
|
+
if (value.length === 0) {
|
|
194
|
+
throwFormat('MALFORMED', `${field} must not be empty`);
|
|
195
|
+
}
|
|
196
|
+
if (/\s/.test(value)) {
|
|
197
|
+
throwFormat(
|
|
198
|
+
'MALFORMED',
|
|
199
|
+
`${field} must not contain whitespace (space, tab, newline, NBSP or any other \\s character)`
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// 3. CAIP-2 grammar for the chain (grammar lives in core — v1.2 §0.3).
|
|
205
|
+
if (!isValidChain(subjectWalletChain)) {
|
|
206
|
+
throwFormat(
|
|
207
|
+
'MALFORMED',
|
|
208
|
+
`subjectWalletChain is not a valid CAIP-2 chain id: ${JSON.stringify(subjectWalletChain)}`
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// 4. Adapter-aware validation, fail-closed (§5.1 rule 5). Exact-CAIP-2
|
|
213
|
+
// registry lookup; without a registered adapter only rules 1–3 apply.
|
|
214
|
+
const adapter = getWalletAdapter(subjectWalletChain);
|
|
215
|
+
if (adapter !== null && !adapter.isValidAddress(subjectWallet)) {
|
|
216
|
+
throwFormat(
|
|
217
|
+
'MALFORMED',
|
|
218
|
+
`subjectWallet failed adapter address validation for ${adapter.chain}`
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return { subjectWallet, subjectWalletChain, subjectWalletPath };
|
|
223
|
+
}
|
|
224
|
+
|
|
115
225
|
/**
|
|
116
226
|
* A parent-signed statement binding a derived child key to a name and a
|
|
117
227
|
* grant. Chains of attestations (`Identity → Handle → SubHandle`) allow
|
|
@@ -237,6 +347,21 @@ export class Attestation {
|
|
|
237
347
|
throwFormat('MALFORMED', `jti exceeds the maximum length of ${MAX_JTI_LENGTH} characters`);
|
|
238
348
|
}
|
|
239
349
|
|
|
350
|
+
// v1 optional extensions (§5.1) — decode tolerance: when present,
|
|
351
|
+
// the fields must be strings; pairing, grammar and on-curve checks
|
|
352
|
+
// are deliberately NOT repeated at decode. A verifier that does not
|
|
353
|
+
// implement the extension MUST NOT reject tokens carrying it — the
|
|
354
|
+
// fields are payload bytes covered by the signature (§4).
|
|
355
|
+
if (payload.subjectWallet !== undefined && typeof payload.subjectWallet !== 'string') {
|
|
356
|
+
throwFormat('MALFORMED', 'Invalid field: subjectWallet');
|
|
357
|
+
}
|
|
358
|
+
if (payload.subjectWalletChain !== undefined && typeof payload.subjectWalletChain !== 'string') {
|
|
359
|
+
throwFormat('MALFORMED', 'Invalid field: subjectWalletChain');
|
|
360
|
+
}
|
|
361
|
+
if (payload.subjectWalletPath !== undefined && typeof payload.subjectWalletPath !== 'string') {
|
|
362
|
+
throwFormat('MALFORMED', 'Invalid field: subjectWalletPath');
|
|
363
|
+
}
|
|
364
|
+
|
|
240
365
|
return payload;
|
|
241
366
|
}
|
|
242
367
|
|
|
@@ -314,7 +439,14 @@ export class Attestation {
|
|
|
314
439
|
* @param grant - Constraints enforced by verifiers (Mode 2).
|
|
315
440
|
* @param opts - Lifetime control: `ttlSeconds` (default one year),
|
|
316
441
|
* `expiresAt` (overrides `ttlSeconds`), `jti` (default random UUID),
|
|
317
|
-
* `now` (fixed clock for deterministic tests).
|
|
442
|
+
* `now` (fixed clock for deterministic tests). Optional wallet
|
|
443
|
+
* extensions (specs/v1.0.md §5.1): `subjectWallet`,
|
|
444
|
+
* `subjectWalletChain` (exact CAIP-2) and `subjectWalletPath` —
|
|
445
|
+
* emitted in that canonical order after `jti`; absent fields are
|
|
446
|
+
* omitted (byte-identity for tokens without them). Pairing and
|
|
447
|
+
* structural rules are enforced at issue time; when an adapter is
|
|
448
|
+
* registered for the chain, the address must pass
|
|
449
|
+
* `adapter.isValidAddress()` (fail-closed).
|
|
318
450
|
* @returns The attestation with `payload`, `token` and `jti` accessors.
|
|
319
451
|
* @throws {AttestationError} `MALFORMED`/`FORMAT` if the grant is
|
|
320
452
|
* structurally invalid (bad scopes/TTL/audiences or a wildcard
|
|
@@ -335,7 +467,10 @@ export class Attestation {
|
|
|
335
467
|
subjectPublicKey: Uint8Array,
|
|
336
468
|
subjectName: string,
|
|
337
469
|
grant: AttestationGrant,
|
|
338
|
-
opts?: {
|
|
470
|
+
opts?: {
|
|
471
|
+
ttlSeconds?: number; expiresAt?: number; jti?: string; now?: number;
|
|
472
|
+
subjectWallet?: string; subjectWalletChain?: string; subjectWalletPath?: string;
|
|
473
|
+
}
|
|
339
474
|
): Promise<Attestation> {
|
|
340
475
|
if (typeof (signer as Signer | undefined)?.sign !== 'function') {
|
|
341
476
|
throw new TypeError(
|
|
@@ -382,6 +517,12 @@ export class Attestation {
|
|
|
382
517
|
}
|
|
383
518
|
}
|
|
384
519
|
|
|
520
|
+
// Validate the v1 optional wallet extensions (§5.1): pairing first
|
|
521
|
+
// (precedes any adapter lookup), then structural checks, CAIP-2
|
|
522
|
+
// grammar and the fail-closed adapter check. Runs only when at
|
|
523
|
+
// least one wallet field is present.
|
|
524
|
+
const walletFields = validateWalletOpts(opts);
|
|
525
|
+
|
|
385
526
|
const now = opts?.now ?? Math.floor(Date.now() / 1000);
|
|
386
527
|
const exp = opts?.expiresAt ?? (now + (opts?.ttlSeconds ?? 31536000));
|
|
387
528
|
const jti = opts?.jti ?? randomUUID();
|
|
@@ -403,6 +544,17 @@ export class Attestation {
|
|
|
403
544
|
jti,
|
|
404
545
|
};
|
|
405
546
|
|
|
547
|
+
// Canonical tail order (§5.1 rule 1): wallet fields follow jti in
|
|
548
|
+
// exactly this order; absent fields are omitted entirely — tokens
|
|
549
|
+
// without them stay byte-identical to the pre-extension format.
|
|
550
|
+
if (walletFields.subjectWallet !== undefined) {
|
|
551
|
+
payload.subjectWallet = walletFields.subjectWallet;
|
|
552
|
+
payload.subjectWalletChain = walletFields.subjectWalletChain;
|
|
553
|
+
if (walletFields.subjectWalletPath !== undefined) {
|
|
554
|
+
payload.subjectWalletPath = walletFields.subjectWalletPath;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
|
|
406
558
|
const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
|
|
407
559
|
const signature = await signer.sign(payloadBytes);
|
|
408
560
|
const payloadB64 = base64urlEncode(payloadBytes);
|
package/src/handle.ts
CHANGED
|
@@ -26,6 +26,7 @@ import { DERIVATION_PATHS } from './crypto/derivation-paths.js';
|
|
|
26
26
|
import { Attestation, type AttestationGrant } from './attestation.js';
|
|
27
27
|
import { DisposedError } from './disposed-error.js';
|
|
28
28
|
import { AttestationError } from './errors.js';
|
|
29
|
+
import { bindEntityWallet, getEntityWallet, type WalletDescriptor } from './payment.js';
|
|
29
30
|
import type { Signer } from './types.js';
|
|
30
31
|
import { base64urlEncode, INSPECT_SYMBOL } from './util.js';
|
|
31
32
|
|
|
@@ -273,6 +274,32 @@ export class Handle implements Signer {
|
|
|
273
274
|
return undefined;
|
|
274
275
|
}
|
|
275
276
|
|
|
277
|
+
/**
|
|
278
|
+
* Binds a wallet to this Handle (payment layer, Документ 2 v1.2 §3).
|
|
279
|
+
*
|
|
280
|
+
* The descriptor is copied — later caller-side mutation does not
|
|
281
|
+
* change what was bound. Storage is in-memory (WeakMap keyed by the
|
|
282
|
+
* instance) and non-persistent: after a restart the binding is gone
|
|
283
|
+
* and the application re-binds. SubHandles inherit this method.
|
|
284
|
+
* Entities hold no seed and cannot derive — they only read back what
|
|
285
|
+
* was bound via {@link getWallet}.
|
|
286
|
+
*
|
|
287
|
+
* @throws {TypeError} If `descriptor` lacks a non-empty string
|
|
288
|
+
* `chain`/`address`.
|
|
289
|
+
*/
|
|
290
|
+
bindWallet(descriptor: WalletDescriptor): void {
|
|
291
|
+
bindEntityWallet(this, descriptor);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Returns the wallet bound to this Handle for the exact CAIP-2
|
|
296
|
+
* `chain`, or `null`. The adapter registry is not consulted — this
|
|
297
|
+
* reads the binding only. SubHandles inherit this method.
|
|
298
|
+
*/
|
|
299
|
+
getWallet(chain: string): WalletDescriptor | null {
|
|
300
|
+
return getEntityWallet(this, chain);
|
|
301
|
+
}
|
|
302
|
+
|
|
276
303
|
/**
|
|
277
304
|
* Validates session options against this Handle's constraints.
|
|
278
305
|
* Handle has no constraints.
|
package/src/identity.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { normalizeName } from './canonical-name.js';
|
|
|
7
7
|
import { Attestation, type AttestationGrant } from './attestation.js';
|
|
8
8
|
import { DisposedError } from './disposed-error.js';
|
|
9
9
|
import { AttestationError } from './errors.js';
|
|
10
|
+
import { bindEntityWallet, getEntityWallet, type WalletDescriptor } from './payment.js';
|
|
10
11
|
import type { Signer } from './types.js';
|
|
11
12
|
import { base64urlEncode, INSPECT_SYMBOL } from './util.js';
|
|
12
13
|
|
|
@@ -229,6 +230,31 @@ export class Identity implements Signer {
|
|
|
229
230
|
return new Uint8Array(this.#publicKey);
|
|
230
231
|
}
|
|
231
232
|
|
|
233
|
+
/**
|
|
234
|
+
* Binds a wallet to this Identity (payment layer, Документ 2 v1.2 §3).
|
|
235
|
+
*
|
|
236
|
+
* The descriptor is copied — later caller-side mutation does not
|
|
237
|
+
* change what was bound. Storage is in-memory (WeakMap keyed by the
|
|
238
|
+
* instance) and non-persistent: after a restart the binding is gone
|
|
239
|
+
* and the application re-binds. Entities hold no seed and cannot
|
|
240
|
+
* derive — they only read back what was bound via {@link getWallet}.
|
|
241
|
+
*
|
|
242
|
+
* @throws {TypeError} If `descriptor` lacks a non-empty string
|
|
243
|
+
* `chain`/`address`.
|
|
244
|
+
*/
|
|
245
|
+
bindWallet(descriptor: WalletDescriptor): void {
|
|
246
|
+
bindEntityWallet(this, descriptor);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Returns the wallet bound to this Identity for the exact CAIP-2
|
|
251
|
+
* `chain`, or `null`. The adapter registry is not consulted — this
|
|
252
|
+
* reads the binding only.
|
|
253
|
+
*/
|
|
254
|
+
getWallet(chain: string): WalletDescriptor | null {
|
|
255
|
+
return getEntityWallet(this, chain);
|
|
256
|
+
}
|
|
257
|
+
|
|
232
258
|
/**
|
|
233
259
|
* Permanently destroys this Identity's key material.
|
|
234
260
|
*
|
package/src/index.ts
CHANGED
|
@@ -5,6 +5,20 @@ export { DisposedError } from './disposed-error.js';
|
|
|
5
5
|
export type { Signer } from './types.js';
|
|
6
6
|
export { Session, type SessionOptions, type SessionPayload, type RevocationChecker } from './session.js';
|
|
7
7
|
export { Attestation, AttestationError, ATTESTATION_TYPE, ATTESTATION_MAX_PAYLOAD, type AttestationGrant, type AttestationPayload, type AttestationErrorCode, type AttestationLevel } from './attestation.js';
|
|
8
|
+
export {
|
|
9
|
+
registerWalletAdapter,
|
|
10
|
+
getWalletAdapter,
|
|
11
|
+
isValidChain,
|
|
12
|
+
parseChain,
|
|
13
|
+
type WalletDescriptor,
|
|
14
|
+
type WalletEntityRef,
|
|
15
|
+
type WalletAdapter,
|
|
16
|
+
type PaymentAdapter,
|
|
17
|
+
type PaymentFailureReason,
|
|
18
|
+
type PaymentRequest,
|
|
19
|
+
type PaymentResult,
|
|
20
|
+
} from './payment.js';
|
|
21
|
+
export { verifyWalletBinding, type WalletBindingOptions } from './wallet-binding.js';
|
|
8
22
|
export * as crypto from './crypto/index.js';
|
|
9
23
|
|
|
10
24
|
/**
|
|
@@ -43,3 +57,4 @@ export {
|
|
|
43
57
|
type SeedValidationResult
|
|
44
58
|
} from './seed.js';
|
|
45
59
|
export { wordlist } from '@scure/bip39/wordlists/english';
|
|
60
|
+
export { base64urlEncode, base64urlDecode } from './util.js';
|
package/src/payment.ts
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
// payment.ts
|
|
2
|
+
//
|
|
3
|
+
// Payment-layer primitives (Документ 2 v1.2 §8): the wallet/payment
|
|
4
|
+
// adapter interfaces, CAIP-2 grammar helpers, the process-wide adapter
|
|
5
|
+
// registry and the in-memory wallet-binding storage. Pure interfaces and
|
|
6
|
+
// stateless helpers — no network, no chain code. Chain-specific values
|
|
7
|
+
// (e.g. `solana:mainnet-beta`) live in the chain packages (solano,
|
|
8
|
+
// monero); core pins only the grammar.
|
|
9
|
+
//
|
|
10
|
+
// Module-graph note: this module imports NOTHING from the rest of src/
|
|
11
|
+
// (it is a dependency leaf). `attestation.ts` reaches into it for the
|
|
12
|
+
// fail-closed wallet validation; the default wallet-binding check lives
|
|
13
|
+
// in `wallet-binding.ts` so that no runtime import cycle can form.
|
|
14
|
+
|
|
15
|
+
import type { Attestation } from './attestation.js';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A chain wallet bound to an entity (Документ 2 v1.2 §8).
|
|
19
|
+
*
|
|
20
|
+
* `chain` is an exact CAIP-2 chain id (e.g. `solana:mainnet-beta`) —
|
|
21
|
+
* the same grammar {@link isValidChain} checks and the same key form the
|
|
22
|
+
* adapter registry uses. `address` format is defined by the chain
|
|
23
|
+
* (base58 / bech32 / …).
|
|
24
|
+
*/
|
|
25
|
+
export interface WalletDescriptor {
|
|
26
|
+
/** Exact CAIP-2 chain id of the wallet. */
|
|
27
|
+
readonly chain: string;
|
|
28
|
+
/** On-chain address in the chain's own format. */
|
|
29
|
+
readonly address: string;
|
|
30
|
+
/** Derivation path for deterministically derived wallets (optional). */
|
|
31
|
+
readonly derivationPath?: string;
|
|
32
|
+
/** Free-form label (e.g. the entity name) for diagnostics. */
|
|
33
|
+
readonly label?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Protocol-level reference to an attested entity, used when an adapter
|
|
38
|
+
* derives or resolves wallets (Документ 2 v1.2 §8). `id` is the
|
|
39
|
+
* base64url-encoded 32-byte public key (the same form as attestation
|
|
40
|
+
* `subjectId` / session `hId`).
|
|
41
|
+
*/
|
|
42
|
+
export interface WalletEntityRef {
|
|
43
|
+
/** base64url of the entity's 32-byte Ed25519 public key. */
|
|
44
|
+
readonly id: string;
|
|
45
|
+
/** Which entity layer the reference points to. */
|
|
46
|
+
readonly kind: 'identity' | 'handle' | 'subhandle';
|
|
47
|
+
/** Canonical entity name. */
|
|
48
|
+
readonly name: string;
|
|
49
|
+
/** Full derivation path — present for SubHandles (`[handleName, subName]`). */
|
|
50
|
+
readonly path?: string[];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* A chain adapter registered for exactly one CAIP-2 chain
|
|
55
|
+
* (Документ 2 v1.2 §2). `core` never imports chain packages; chain
|
|
56
|
+
* packages register adapters into the process-wide registry
|
|
57
|
+
* ({@link registerWalletAdapter}) and the payment layer resolves them
|
|
58
|
+
* by exact key ({@link getWalletAdapter}).
|
|
59
|
+
*/
|
|
60
|
+
export interface WalletAdapter {
|
|
61
|
+
/** Exact CAIP-2 chain this adapter handles — also its registry key. */
|
|
62
|
+
readonly chain: string;
|
|
63
|
+
/**
|
|
64
|
+
* Resolves (derives or attaches) the entity's wallet on this chain.
|
|
65
|
+
* Deterministic adapters require `opts.seed`; without it they reject
|
|
66
|
+
* with `TypeError`. Attach-only adapters ignore `seed`.
|
|
67
|
+
*/
|
|
68
|
+
resolveWallet(
|
|
69
|
+
entity: WalletEntityRef,
|
|
70
|
+
opts?: { seed?: Uint8Array; index?: number }
|
|
71
|
+
): Promise<WalletDescriptor>;
|
|
72
|
+
/** Structural address check (format only — no network, no on-curve). */
|
|
73
|
+
isValidAddress(address: string): boolean;
|
|
74
|
+
/**
|
|
75
|
+
* Optional: chain-scoped index allocation from used derivation paths
|
|
76
|
+
* (v1.2 §2.2). The adapter parses its own path formats; an empty input
|
|
77
|
+
* — or an input that is empty after filtering to the adapter's own
|
|
78
|
+
* paths — yields `0`; otherwise `max(indexes) + 1` (holes are never
|
|
79
|
+
* reused); paths the adapter cannot parse are ignored, never thrown
|
|
80
|
+
* on. Callers filter paths by `subjectWalletChain` before handing them
|
|
81
|
+
* over. `core` performs NO fallback when the method is absent —
|
|
82
|
+
* index allocation is caller responsibility.
|
|
83
|
+
*/
|
|
84
|
+
nextIndex?(usedPaths: string[]): number;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* A wallet adapter that can also execute and verify payments
|
|
89
|
+
* (Документ 2 v1.2 §5). Knowledge of attestations is deliberately kept
|
|
90
|
+
* out of `pay`: the buyer link is `verifyWalletBinding` on the app side,
|
|
91
|
+
* execution control is `verifyPayment` on the recipient side.
|
|
92
|
+
*/
|
|
93
|
+
export interface PaymentAdapter extends WalletAdapter {
|
|
94
|
+
/**
|
|
95
|
+
* Programmatically spends from a wallet the adapter CONTROLS
|
|
96
|
+
* (derived or imported keys). `from` is non-null. External wallets
|
|
97
|
+
* (browser extensions) do not go through `pay` — they follow the
|
|
98
|
+
* chain-specific request-URL flow. On success `txRef` is non-empty;
|
|
99
|
+
* on failure `pay` throws (v1.2 §5.1).
|
|
100
|
+
*/
|
|
101
|
+
pay(from: WalletDescriptor, request: PaymentRequest): Promise<string>;
|
|
102
|
+
/**
|
|
103
|
+
* Idempotent pure read of the chain state for a confirmed transaction
|
|
104
|
+
* (v1.2 §5.3): repeating the call with the same `txRef` yields the
|
|
105
|
+
* same result. The normative check order and failure reasons are
|
|
106
|
+
* pinned by v1.2 §5.4 (`NOT_FOUND` → `REFERENCE_MISMATCH` →
|
|
107
|
+
* `EXPIRED` → `REPLAYED` → `WRONG_RECIPIENT` → `UNDERPAID` →
|
|
108
|
+
* success). Chain-level `REPLAYED` is detected by the adapter;
|
|
109
|
+
* order-level deduplication stays with the application.
|
|
110
|
+
*/
|
|
111
|
+
verifyPayment(txRef: string, request: PaymentRequest): Promise<PaymentResult>;
|
|
112
|
+
/**
|
|
113
|
+
* Optional stronger wallet-binding verification. The core default
|
|
114
|
+
* (see {@link verifyWalletBinding} in `wallet-binding.ts`) is the
|
|
115
|
+
* attestation token's signature + subject agreement + address
|
|
116
|
+
* equality; adapters may add chain-specific strength (e.g. on-curve
|
|
117
|
+
* checks). NOT invoked implicitly by transport layers (v1.2 §6).
|
|
118
|
+
*/
|
|
119
|
+
verifyWalletBinding?(
|
|
120
|
+
wallet: WalletDescriptor,
|
|
121
|
+
entity: WalletEntityRef,
|
|
122
|
+
attestation: Attestation
|
|
123
|
+
): Promise<boolean>;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Machine-readable reasons a payment failed verification (v1.2 §5.4).
|
|
128
|
+
* `REFERENCE_MISMATCH` is the v1.2 addition: the transaction exists but
|
|
129
|
+
* is not an execution of THIS request. Fail-safe rule for consumers:
|
|
130
|
+
* unknown runtime values MUST be treated as `REJECTED` (never as
|
|
131
|
+
* success).
|
|
132
|
+
*/
|
|
133
|
+
export type PaymentFailureReason =
|
|
134
|
+
| 'NOT_FOUND' | 'UNDERPAID' | 'WRONG_RECIPIENT' | 'WRONG_ASSET'
|
|
135
|
+
| 'EXPIRED' | 'REPLAYED' | 'CHAIN_UNAVAILABLE' | 'REJECTED'
|
|
136
|
+
| 'REFERENCE_MISMATCH';
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* A signed-off payment demand (v1.2 §0.1): every parameter a verifier
|
|
140
|
+
* needs comes from this artifact — nothing is negotiated out-of-band.
|
|
141
|
+
* All payment parameters live in signed data; the wire shape is pinned
|
|
142
|
+
* here and unchanged from Документ 2 v1.0 (v1.2 §12).
|
|
143
|
+
*/
|
|
144
|
+
export interface PaymentRequest {
|
|
145
|
+
/** Exact CAIP-2 chain the request is payable on. */
|
|
146
|
+
readonly chain: string;
|
|
147
|
+
/** Recipient address on that chain. */
|
|
148
|
+
readonly payTo: string;
|
|
149
|
+
/** Amount as a decimal string in whole token units (NOT the smallest denomination). */
|
|
150
|
+
readonly amount: string;
|
|
151
|
+
/** Asset identifier — the chain-native asset or a token id (e.g. SPL mint, base58). */
|
|
152
|
+
readonly asset: string;
|
|
153
|
+
/**
|
|
154
|
+
* Correlation key included in the payment transaction (for Solana: a
|
|
155
|
+
* base58-encoded 32-byte reference key). Chain-level `REPLAYED`
|
|
156
|
+
* detection keys on it; order-level deduplication keys on it too.
|
|
157
|
+
*/
|
|
158
|
+
readonly reference: string;
|
|
159
|
+
/** Unix seconds — payments observed after this are `EXPIRED` (block time first, observed time as fallback). */
|
|
160
|
+
readonly expiresAt: number;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Outcome of {@link PaymentAdapter.verifyPayment}. `observedAt` is the
|
|
165
|
+
* adapter's observation time (unix seconds) — informational, never part
|
|
166
|
+
* of validation (v1.2 §5.2); `reason` is present exactly on failure.
|
|
167
|
+
*
|
|
168
|
+
* Provisional shape note (ТЗ-2): the final composition of the success
|
|
169
|
+
* branch (e.g. extra informational fields) is reconciled with
|
|
170
|
+
* Документ 2 v1.0 §3.3 when `verifyPayment` is implemented (Ф4);
|
|
171
|
+
* `observedAt` and the failure `reason` are pinned by v1.2 §5.2/§5.4.
|
|
172
|
+
*/
|
|
173
|
+
export type PaymentResult =
|
|
174
|
+
| { readonly status: 'success'; readonly observedAt: number }
|
|
175
|
+
| {
|
|
176
|
+
readonly status: 'failure';
|
|
177
|
+
readonly reason: PaymentFailureReason;
|
|
178
|
+
readonly observedAt: number;
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
// ---------------------------------------------------------------------------
|
|
182
|
+
// CAIP-2 grammar (v1.2 §0.3) — grammar only, no chain values.
|
|
183
|
+
// ---------------------------------------------------------------------------
|
|
184
|
+
|
|
185
|
+
const CAIP2_NAMESPACE_RE = /^[a-z0-9-]{3,8}$/; // [-a-z0-9]{3,8}
|
|
186
|
+
const CAIP2_REFERENCE_RE = /^[a-zA-Z0-9-]{1,64}$/; // [-a-zA-Z0-9]{1,64}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Parses a CAIP-2 chain id (`namespace:reference`) per the grammar
|
|
190
|
+
* pinned in v1.2 §0.3: namespace `[-a-z0-9]{3,8}`, reference
|
|
191
|
+
* `[-a-zA-Z0-9]{1,64}`. Returns `null` for anything else — including
|
|
192
|
+
* wrong case (`Solana:mainnet-beta`), an empty reference
|
|
193
|
+
* (`solana:`), a short namespace (`s:x`) or embedded colons.
|
|
194
|
+
*
|
|
195
|
+
* @example
|
|
196
|
+
* ```ts
|
|
197
|
+
* parseChain('solana:mainnet-beta'); // { namespace: 'solana', reference: 'mainnet-beta' }
|
|
198
|
+
* parseChain('solana'); // null
|
|
199
|
+
* ```
|
|
200
|
+
*/
|
|
201
|
+
export function parseChain(chain: string): { namespace: string; reference: string } | null {
|
|
202
|
+
if (typeof chain !== 'string') return null;
|
|
203
|
+
const colon = chain.indexOf(':');
|
|
204
|
+
if (colon < 0) return null;
|
|
205
|
+
const namespace = chain.slice(0, colon);
|
|
206
|
+
const reference = chain.slice(colon + 1);
|
|
207
|
+
if (!CAIP2_NAMESPACE_RE.test(namespace)) return null;
|
|
208
|
+
if (!CAIP2_REFERENCE_RE.test(reference)) return null;
|
|
209
|
+
return { namespace, reference };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** CAIP-2 grammar check — {@link parseChain} as a predicate. */
|
|
213
|
+
export function isValidChain(chain: string): boolean {
|
|
214
|
+
return parseChain(chain) !== null;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// ---------------------------------------------------------------------------
|
|
218
|
+
// Adapter registry (v1.2 §2.1) — process-wide, exact-CAIP-2 keys.
|
|
219
|
+
// ---------------------------------------------------------------------------
|
|
220
|
+
|
|
221
|
+
const REGISTRY_SYMBOL = Symbol.for('me2em.paymentAdapters');
|
|
222
|
+
|
|
223
|
+
function getRegistry(): Map<string, WalletAdapter> {
|
|
224
|
+
const holder = globalThis as unknown as Record<symbol, unknown>;
|
|
225
|
+
const existing = holder[REGISTRY_SYMBOL];
|
|
226
|
+
if (existing instanceof Map) return existing as Map<string, WalletAdapter>;
|
|
227
|
+
// First reach in this isolate: create the shared map. globalThis +
|
|
228
|
+
// Symbol.for make the registry survive duplicate module copies (even
|
|
229
|
+
// different bundles) within one process; it stays per-isolate on
|
|
230
|
+
// edge/serverless runtimes.
|
|
231
|
+
const created = new Map<string, WalletAdapter>();
|
|
232
|
+
holder[REGISTRY_SYMBOL] = created;
|
|
233
|
+
return created;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Registers a wallet adapter under its exact `adapter.chain` key
|
|
238
|
+
* (v1.2 §2.1). Last-wins: a later registration for the same chain
|
|
239
|
+
* replaces the earlier one. ⚠️ Security note: last-wins means ANY code
|
|
240
|
+
* in the process can replace the adapter of a busy chain — registering
|
|
241
|
+
* is a privilege of the application's trusted code; do not import
|
|
242
|
+
* untrusted dependencies before registration.
|
|
243
|
+
*
|
|
244
|
+
* @returns A disposer removing the record this call created. The
|
|
245
|
+
* disposer is idempotent and removes nothing if a later registration
|
|
246
|
+
* has already replaced the record (it never removes someone else's
|
|
247
|
+
* adapter).
|
|
248
|
+
* @throws {TypeError} If `adapter` is not an object with a non-empty
|
|
249
|
+
* string `chain` and callable `resolveWallet`/`isValidAddress`.
|
|
250
|
+
*/
|
|
251
|
+
export function registerWalletAdapter(adapter: WalletAdapter): () => void {
|
|
252
|
+
if (adapter === null || typeof adapter !== 'object') {
|
|
253
|
+
throw new TypeError('registerWalletAdapter: adapter must be an object');
|
|
254
|
+
}
|
|
255
|
+
if (typeof adapter.chain !== 'string' || adapter.chain.length === 0) {
|
|
256
|
+
throw new TypeError('registerWalletAdapter: adapter.chain must be a non-empty string');
|
|
257
|
+
}
|
|
258
|
+
if (typeof adapter.resolveWallet !== 'function' || typeof adapter.isValidAddress !== 'function') {
|
|
259
|
+
throw new TypeError('registerWalletAdapter: adapter must implement resolveWallet and isValidAddress');
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const registry = getRegistry();
|
|
263
|
+
registry.set(adapter.chain, adapter); // last-wins
|
|
264
|
+
let disposed = false;
|
|
265
|
+
return () => {
|
|
266
|
+
if (disposed) return;
|
|
267
|
+
disposed = true;
|
|
268
|
+
if (registry.get(adapter.chain) === adapter) registry.delete(adapter.chain);
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Looks up the adapter registered for the exact CAIP-2 `chain` value.
|
|
274
|
+
* No aliasing, no prefix matching — `solana:mainnet-beta` and
|
|
275
|
+
* `solana:devnet` are different keys. Returns `null` when nothing is
|
|
276
|
+
* registered.
|
|
277
|
+
*/
|
|
278
|
+
export function getWalletAdapter(chain: string): WalletAdapter | null {
|
|
279
|
+
return getRegistry().get(chain) ?? null;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// ---------------------------------------------------------------------------
|
|
283
|
+
// Wallet-binding storage (v1.2 §3) — WeakMap, in-memory, non-persistent.
|
|
284
|
+
// ---------------------------------------------------------------------------
|
|
285
|
+
|
|
286
|
+
const boundWallets = new WeakMap<object, Map<string, WalletDescriptor>>();
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Binds a wallet descriptor to an entity instance. Internal delegate for
|
|
290
|
+
* `Identity.bindWallet` / `Handle.bindWallet` (SubHandle inherits).
|
|
291
|
+
* The descriptor is COPIED (`{ ...descriptor }`) so later caller-side
|
|
292
|
+
* mutation cannot change what was bound (v1.2 §3.2). Storage is
|
|
293
|
+
* in-memory and non-persistent: after a restart the binding is gone and
|
|
294
|
+
* the application re-binds (React: effect/context).
|
|
295
|
+
*
|
|
296
|
+
* @throws {TypeError} If `descriptor` is not an object with non-empty
|
|
297
|
+
* string `chain` and `address`.
|
|
298
|
+
*/
|
|
299
|
+
export function bindEntityWallet(entity: object, descriptor: WalletDescriptor): void {
|
|
300
|
+
if (descriptor === null || typeof descriptor !== 'object') {
|
|
301
|
+
throw new TypeError('bindWallet: descriptor must be an object');
|
|
302
|
+
}
|
|
303
|
+
if (typeof descriptor.chain !== 'string' || descriptor.chain.length === 0) {
|
|
304
|
+
throw new TypeError('bindWallet: descriptor.chain must be a non-empty string');
|
|
305
|
+
}
|
|
306
|
+
if (typeof descriptor.address !== 'string' || descriptor.address.length === 0) {
|
|
307
|
+
throw new TypeError('bindWallet: descriptor.address must be a non-empty string');
|
|
308
|
+
}
|
|
309
|
+
let perChain = boundWallets.get(entity);
|
|
310
|
+
if (perChain === undefined) {
|
|
311
|
+
perChain = new Map<string, WalletDescriptor>();
|
|
312
|
+
boundWallets.set(entity, perChain);
|
|
313
|
+
}
|
|
314
|
+
perChain.set(descriptor.chain, { ...descriptor });
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Returns the wallet descriptor bound to the entity for the exact
|
|
319
|
+
* `chain`, or `null`. Internal delegate for `getWallet` methods. The
|
|
320
|
+
* adapter registry is NOT consulted here — this reads the binding only
|
|
321
|
+
* (adapters matter at derivation time, not at binding-read time).
|
|
322
|
+
* Entities hold no seed and cannot derive — they read what was bound.
|
|
323
|
+
*/
|
|
324
|
+
export function getEntityWallet(entity: object, chain: string): WalletDescriptor | null {
|
|
325
|
+
return boundWallets.get(entity)?.get(chain) ?? null;
|
|
326
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// wallet-binding.ts
|
|
2
|
+
//
|
|
3
|
+
// Default wallet-binding verification for the payment layer
|
|
4
|
+
// (Документ 2 v1.2 §6): the core default combines the attestation
|
|
5
|
+
// token's signature with subject agreement and address equality.
|
|
6
|
+
// Chain adapters MAY override `PaymentAdapter.verifyWalletBinding` with
|
|
7
|
+
// stronger checks (on-curve validation, Mode 1 re-derivation from
|
|
8
|
+
// `subjectWalletPath`); Mode 2 verifiers (root public key only) accept
|
|
9
|
+
// path↔address consistency on the strength of the Identity signature —
|
|
10
|
+
// a deliberate v1 limitation. Transport layers (x402) never invoke this
|
|
11
|
+
// implicitly; regulatory / compliance flows call it explicitly.
|
|
12
|
+
//
|
|
13
|
+
// This module lives apart from payment.ts so the runtime module graph
|
|
14
|
+
// stays acyclic: payment.ts is a leaf, attestation.ts imports payment.ts
|
|
15
|
+
// (fail-closed wallet validation), and only this module pulls in the
|
|
16
|
+
// Attestation class itself.
|
|
17
|
+
|
|
18
|
+
import { Attestation } from './attestation.js';
|
|
19
|
+
import type { WalletDescriptor, WalletEntityRef } from './payment.js';
|
|
20
|
+
|
|
21
|
+
/** Options for the default {@link verifyWalletBinding}. */
|
|
22
|
+
export interface WalletBindingOptions {
|
|
23
|
+
/**
|
|
24
|
+
* Ed25519 public key of the attestation ISSUER — the root Identity
|
|
25
|
+
* public key for Identity→Handle attestations, the Handle public key
|
|
26
|
+
* for Handle→SubHandle attestations.
|
|
27
|
+
*/
|
|
28
|
+
issuerPublicKey: Uint8Array;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Default wallet-binding check (v1.2 §6): answers "does this attestation
|
|
33
|
+
* bind this wallet to this entity?".
|
|
34
|
+
*
|
|
35
|
+
* Order of the three fail-closed checks:
|
|
36
|
+
*
|
|
37
|
+
* 1. **Signature** — the token verifies against the expected issuer
|
|
38
|
+
* public key (`Attestation.verifySignature`).
|
|
39
|
+
* 2. **Subject agreement** — the attestation must attest THIS entity
|
|
40
|
+
* (`payload.subjectId === entity.id`); without it any valid
|
|
41
|
+
* attestation of a different subject would "bind" its wallet here.
|
|
42
|
+
* 3. **Address equality** — `payload.subjectWallet` string-equals the
|
|
43
|
+
* wallet address to be bound; an attestation without wallet fields
|
|
44
|
+
* fails (undefined never equals an address).
|
|
45
|
+
*
|
|
46
|
+
* On-curve checking and path re-derivation are NOT part of the default —
|
|
47
|
+
* they are adapter overrides (Mode 1) per v1.2 §6/§6.1.
|
|
48
|
+
*
|
|
49
|
+
* @returns `false` on every failed check — never throws for a
|
|
50
|
+
* verification mismatch (only structural token errors surface as
|
|
51
|
+
* `AttestationError` from `verifySignature`/decode, per its contract).
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```ts
|
|
55
|
+
* const ok = await verifyWalletBinding(wallet, entity, attestation, {
|
|
56
|
+
* issuerPublicKey: rootIdentity.getPublicKey(),
|
|
57
|
+
* });
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
export async function verifyWalletBinding(
|
|
61
|
+
wallet: WalletDescriptor,
|
|
62
|
+
entity: WalletEntityRef,
|
|
63
|
+
attestation: Attestation,
|
|
64
|
+
opts: WalletBindingOptions
|
|
65
|
+
): Promise<boolean> {
|
|
66
|
+
const signatureOk = await Attestation.verifySignature(attestation.token, opts.issuerPublicKey);
|
|
67
|
+
if (!signatureOk) return false;
|
|
68
|
+
if (attestation.payload.subjectId !== entity.id) return false;
|
|
69
|
+
return attestation.payload.subjectWallet === wallet.address;
|
|
70
|
+
}
|