@me2em/core 1.0.0-rc.2 → 1.0.0-rc.4

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.
@@ -0,0 +1,215 @@
1
+ import type { Attestation } from './attestation.js';
2
+ /**
3
+ * A chain wallet bound to an entity (Документ 2 v1.2 §8).
4
+ *
5
+ * `chain` is an exact CAIP-2 chain id (e.g. `solana:mainnet-beta`) —
6
+ * the same grammar {@link isValidChain} checks and the same key form the
7
+ * adapter registry uses. `address` format is defined by the chain
8
+ * (base58 / bech32 / …).
9
+ */
10
+ export interface WalletDescriptor {
11
+ /** Exact CAIP-2 chain id of the wallet. */
12
+ readonly chain: string;
13
+ /** On-chain address in the chain's own format. */
14
+ readonly address: string;
15
+ /** Derivation path for deterministically derived wallets (optional). */
16
+ readonly derivationPath?: string;
17
+ /** Free-form label (e.g. the entity name) for diagnostics. */
18
+ readonly label?: string;
19
+ }
20
+ /**
21
+ * Protocol-level reference to an attested entity, used when an adapter
22
+ * derives or resolves wallets (Документ 2 v1.2 §8). `id` is the
23
+ * base64url-encoded 32-byte public key (the same form as attestation
24
+ * `subjectId` / session `hId`).
25
+ */
26
+ export interface WalletEntityRef {
27
+ /** base64url of the entity's 32-byte Ed25519 public key. */
28
+ readonly id: string;
29
+ /** Which entity layer the reference points to. */
30
+ readonly kind: 'identity' | 'handle' | 'subhandle';
31
+ /** Canonical entity name. */
32
+ readonly name: string;
33
+ /** Full derivation path — present for SubHandles (`[handleName, subName]`). */
34
+ readonly path?: string[];
35
+ }
36
+ /**
37
+ * A chain adapter registered for exactly one CAIP-2 chain
38
+ * (Документ 2 v1.2 §2). `core` never imports chain packages; chain
39
+ * packages register adapters into the process-wide registry
40
+ * ({@link registerWalletAdapter}) and the payment layer resolves them
41
+ * by exact key ({@link getWalletAdapter}).
42
+ */
43
+ export interface WalletAdapter {
44
+ /** Exact CAIP-2 chain this adapter handles — also its registry key. */
45
+ readonly chain: string;
46
+ /**
47
+ * Resolves (derives or attaches) the entity's wallet on this chain.
48
+ * Deterministic adapters require `opts.seed`; without it they reject
49
+ * with `TypeError`. Attach-only adapters ignore `seed`.
50
+ */
51
+ resolveWallet(entity: WalletEntityRef, opts?: {
52
+ seed?: Uint8Array;
53
+ index?: number;
54
+ }): Promise<WalletDescriptor>;
55
+ /** Structural address check (format only — no network, no on-curve). */
56
+ isValidAddress(address: string): boolean;
57
+ /**
58
+ * Optional: chain-scoped index allocation from used derivation paths
59
+ * (v1.2 §2.2). The adapter parses its own path formats; an empty input
60
+ * — or an input that is empty after filtering to the adapter's own
61
+ * paths — yields `0`; otherwise `max(indexes) + 1` (holes are never
62
+ * reused); paths the adapter cannot parse are ignored, never thrown
63
+ * on. Callers filter paths by `subjectWalletChain` before handing them
64
+ * over. `core` performs NO fallback when the method is absent —
65
+ * index allocation is caller responsibility.
66
+ */
67
+ nextIndex?(usedPaths: string[]): number;
68
+ }
69
+ /**
70
+ * A wallet adapter that can also execute and verify payments
71
+ * (Документ 2 v1.2 §5). Knowledge of attestations is deliberately kept
72
+ * out of `pay`: the buyer link is `verifyWalletBinding` on the app side,
73
+ * execution control is `verifyPayment` on the recipient side.
74
+ */
75
+ export interface PaymentAdapter extends WalletAdapter {
76
+ /**
77
+ * Programmatically spends from a wallet the adapter CONTROLS
78
+ * (derived or imported keys). `from` is non-null. External wallets
79
+ * (browser extensions) do not go through `pay` — they follow the
80
+ * chain-specific request-URL flow. On success `txRef` is non-empty;
81
+ * on failure `pay` throws (v1.2 §5.1).
82
+ */
83
+ pay(from: WalletDescriptor, request: PaymentRequest): Promise<string>;
84
+ /**
85
+ * Idempotent pure read of the chain state for a confirmed transaction
86
+ * (v1.2 §5.3): repeating the call with the same `txRef` yields the
87
+ * same result. The normative check order and failure reasons are
88
+ * pinned by v1.2 §5.4 (`NOT_FOUND` → `REFERENCE_MISMATCH` →
89
+ * `EXPIRED` → `REPLAYED` → `WRONG_RECIPIENT` → `UNDERPAID` →
90
+ * success). Chain-level `REPLAYED` is detected by the adapter;
91
+ * order-level deduplication stays with the application.
92
+ */
93
+ verifyPayment(txRef: string, request: PaymentRequest): Promise<PaymentResult>;
94
+ /**
95
+ * Optional stronger wallet-binding verification. The core default
96
+ * (see {@link verifyWalletBinding} in `wallet-binding.ts`) is the
97
+ * attestation token's signature + subject agreement + address
98
+ * equality; adapters may add chain-specific strength (e.g. on-curve
99
+ * checks). NOT invoked implicitly by transport layers (v1.2 §6).
100
+ */
101
+ verifyWalletBinding?(wallet: WalletDescriptor, entity: WalletEntityRef, attestation: Attestation): Promise<boolean>;
102
+ }
103
+ /**
104
+ * Machine-readable reasons a payment failed verification (v1.2 §5.4).
105
+ * `REFERENCE_MISMATCH` is the v1.2 addition: the transaction exists but
106
+ * is not an execution of THIS request. Fail-safe rule for consumers:
107
+ * unknown runtime values MUST be treated as `REJECTED` (never as
108
+ * success).
109
+ */
110
+ export type PaymentFailureReason = 'NOT_FOUND' | 'UNDERPAID' | 'WRONG_RECIPIENT' | 'WRONG_ASSET' | 'EXPIRED' | 'REPLAYED' | 'CHAIN_UNAVAILABLE' | 'REJECTED' | 'REFERENCE_MISMATCH';
111
+ /**
112
+ * A signed-off payment demand (v1.2 §0.1): every parameter a verifier
113
+ * needs comes from this artifact — nothing is negotiated out-of-band.
114
+ * All payment parameters live in signed data; the wire shape is pinned
115
+ * here and unchanged from Документ 2 v1.0 (v1.2 §12).
116
+ */
117
+ export interface PaymentRequest {
118
+ /** Exact CAIP-2 chain the request is payable on. */
119
+ readonly chain: string;
120
+ /** Recipient address on that chain. */
121
+ readonly payTo: string;
122
+ /** Amount as a decimal string in whole token units (NOT the smallest denomination). */
123
+ readonly amount: string;
124
+ /** Asset identifier — the chain-native asset or a token id (e.g. SPL mint, base58). */
125
+ readonly asset: string;
126
+ /**
127
+ * Correlation key included in the payment transaction (for Solana: a
128
+ * base58-encoded 32-byte reference key). Chain-level `REPLAYED`
129
+ * detection keys on it; order-level deduplication keys on it too.
130
+ */
131
+ readonly reference: string;
132
+ /** Unix seconds — payments observed after this are `EXPIRED` (block time first, observed time as fallback). */
133
+ readonly expiresAt: number;
134
+ }
135
+ /**
136
+ * Outcome of {@link PaymentAdapter.verifyPayment}. `observedAt` is the
137
+ * adapter's observation time (unix seconds) — informational, never part
138
+ * of validation (v1.2 §5.2); `reason` is present exactly on failure.
139
+ *
140
+ * Provisional shape note (ТЗ-2): the final composition of the success
141
+ * branch (e.g. extra informational fields) is reconciled with
142
+ * Документ 2 v1.0 §3.3 when `verifyPayment` is implemented (Ф4);
143
+ * `observedAt` and the failure `reason` are pinned by v1.2 §5.2/§5.4.
144
+ */
145
+ export type PaymentResult = {
146
+ readonly status: 'success';
147
+ readonly observedAt: number;
148
+ } | {
149
+ readonly status: 'failure';
150
+ readonly reason: PaymentFailureReason;
151
+ readonly observedAt: number;
152
+ };
153
+ /**
154
+ * Parses a CAIP-2 chain id (`namespace:reference`) per the grammar
155
+ * pinned in v1.2 §0.3: namespace `[-a-z0-9]{3,8}`, reference
156
+ * `[-a-zA-Z0-9]{1,64}`. Returns `null` for anything else — including
157
+ * wrong case (`Solana:mainnet-beta`), an empty reference
158
+ * (`solana:`), a short namespace (`s:x`) or embedded colons.
159
+ *
160
+ * @example
161
+ * ```ts
162
+ * parseChain('solana:mainnet-beta'); // { namespace: 'solana', reference: 'mainnet-beta' }
163
+ * parseChain('solana'); // null
164
+ * ```
165
+ */
166
+ export declare function parseChain(chain: string): {
167
+ namespace: string;
168
+ reference: string;
169
+ } | null;
170
+ /** CAIP-2 grammar check — {@link parseChain} as a predicate. */
171
+ export declare function isValidChain(chain: string): boolean;
172
+ /**
173
+ * Registers a wallet adapter under its exact `adapter.chain` key
174
+ * (v1.2 §2.1). Last-wins: a later registration for the same chain
175
+ * replaces the earlier one. ⚠️ Security note: last-wins means ANY code
176
+ * in the process can replace the adapter of a busy chain — registering
177
+ * is a privilege of the application's trusted code; do not import
178
+ * untrusted dependencies before registration.
179
+ *
180
+ * @returns A disposer removing the record this call created. The
181
+ * disposer is idempotent and removes nothing if a later registration
182
+ * has already replaced the record (it never removes someone else's
183
+ * adapter).
184
+ * @throws {TypeError} If `adapter` is not an object with a non-empty
185
+ * string `chain` and callable `resolveWallet`/`isValidAddress`.
186
+ */
187
+ export declare function registerWalletAdapter(adapter: WalletAdapter): () => void;
188
+ /**
189
+ * Looks up the adapter registered for the exact CAIP-2 `chain` value.
190
+ * No aliasing, no prefix matching — `solana:mainnet-beta` and
191
+ * `solana:devnet` are different keys. Returns `null` when nothing is
192
+ * registered.
193
+ */
194
+ export declare function getWalletAdapter(chain: string): WalletAdapter | null;
195
+ /**
196
+ * Binds a wallet descriptor to an entity instance. Internal delegate for
197
+ * `Identity.bindWallet` / `Handle.bindWallet` (SubHandle inherits).
198
+ * The descriptor is COPIED (`{ ...descriptor }`) so later caller-side
199
+ * mutation cannot change what was bound (v1.2 §3.2). Storage is
200
+ * in-memory and non-persistent: after a restart the binding is gone and
201
+ * the application re-binds (React: effect/context).
202
+ *
203
+ * @throws {TypeError} If `descriptor` is not an object with non-empty
204
+ * string `chain` and `address`.
205
+ */
206
+ export declare function bindEntityWallet(entity: object, descriptor: WalletDescriptor): void;
207
+ /**
208
+ * Returns the wallet descriptor bound to the entity for the exact
209
+ * `chain`, or `null`. Internal delegate for `getWallet` methods. The
210
+ * adapter registry is NOT consulted here — this reads the binding only
211
+ * (adapters matter at derivation time, not at binding-read time).
212
+ * Entities hold no seed and cannot derive — they read what was bound.
213
+ */
214
+ export declare function getEntityWallet(entity: object, chain: string): WalletDescriptor | null;
215
+ //# sourceMappingURL=payment.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"payment.d.ts","sourceRoot":"","sources":["../src/payment.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAEpD;;;;;;;GAOG;AACH,MAAM,WAAW,gBAAgB;IAC/B,2CAA2C;IAC3C,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,kDA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GAAG,OAAO,CAEnD;AAqBD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,aAAa,GAAG,MAAM,IAAI,CAmBxE;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,GAAG,IAAI,CAEpE;AAQD;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,gBAAgB,GAAG,IAAI,CAgBnF;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,gBAAgB,GAAG,IAAI,CAEtF"}
@@ -0,0 +1,154 @@
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
+ // CAIP-2 grammar (v1.2 §0.3) — grammar only, no chain values.
16
+ // ---------------------------------------------------------------------------
17
+ const CAIP2_NAMESPACE_RE = /^[a-z0-9-]{3,8}$/; // [-a-z0-9]{3,8}
18
+ const CAIP2_REFERENCE_RE = /^[a-zA-Z0-9-]{1,64}$/; // [-a-zA-Z0-9]{1,64}
19
+ /**
20
+ * Parses a CAIP-2 chain id (`namespace:reference`) per the grammar
21
+ * pinned in v1.2 §0.3: namespace `[-a-z0-9]{3,8}`, reference
22
+ * `[-a-zA-Z0-9]{1,64}`. Returns `null` for anything else — including
23
+ * wrong case (`Solana:mainnet-beta`), an empty reference
24
+ * (`solana:`), a short namespace (`s:x`) or embedded colons.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * parseChain('solana:mainnet-beta'); // { namespace: 'solana', reference: 'mainnet-beta' }
29
+ * parseChain('solana'); // null
30
+ * ```
31
+ */
32
+ export function parseChain(chain) {
33
+ if (typeof chain !== 'string')
34
+ return null;
35
+ const colon = chain.indexOf(':');
36
+ if (colon < 0)
37
+ return null;
38
+ const namespace = chain.slice(0, colon);
39
+ const reference = chain.slice(colon + 1);
40
+ if (!CAIP2_NAMESPACE_RE.test(namespace))
41
+ return null;
42
+ if (!CAIP2_REFERENCE_RE.test(reference))
43
+ return null;
44
+ return { namespace, reference };
45
+ }
46
+ /** CAIP-2 grammar check — {@link parseChain} as a predicate. */
47
+ export function isValidChain(chain) {
48
+ return parseChain(chain) !== null;
49
+ }
50
+ // ---------------------------------------------------------------------------
51
+ // Adapter registry (v1.2 §2.1) — process-wide, exact-CAIP-2 keys.
52
+ // ---------------------------------------------------------------------------
53
+ const REGISTRY_SYMBOL = Symbol.for('me2em.paymentAdapters');
54
+ function getRegistry() {
55
+ const holder = globalThis;
56
+ const existing = holder[REGISTRY_SYMBOL];
57
+ if (existing instanceof Map)
58
+ return existing;
59
+ // First reach in this isolate: create the shared map. globalThis +
60
+ // Symbol.for make the registry survive duplicate module copies (even
61
+ // different bundles) within one process; it stays per-isolate on
62
+ // edge/serverless runtimes.
63
+ const created = new Map();
64
+ holder[REGISTRY_SYMBOL] = created;
65
+ return created;
66
+ }
67
+ /**
68
+ * Registers a wallet adapter under its exact `adapter.chain` key
69
+ * (v1.2 §2.1). Last-wins: a later registration for the same chain
70
+ * replaces the earlier one. ⚠️ Security note: last-wins means ANY code
71
+ * in the process can replace the adapter of a busy chain — registering
72
+ * is a privilege of the application's trusted code; do not import
73
+ * untrusted dependencies before registration.
74
+ *
75
+ * @returns A disposer removing the record this call created. The
76
+ * disposer is idempotent and removes nothing if a later registration
77
+ * has already replaced the record (it never removes someone else's
78
+ * adapter).
79
+ * @throws {TypeError} If `adapter` is not an object with a non-empty
80
+ * string `chain` and callable `resolveWallet`/`isValidAddress`.
81
+ */
82
+ export function registerWalletAdapter(adapter) {
83
+ if (adapter === null || typeof adapter !== 'object') {
84
+ throw new TypeError('registerWalletAdapter: adapter must be an object');
85
+ }
86
+ if (typeof adapter.chain !== 'string' || adapter.chain.length === 0) {
87
+ throw new TypeError('registerWalletAdapter: adapter.chain must be a non-empty string');
88
+ }
89
+ if (typeof adapter.resolveWallet !== 'function' || typeof adapter.isValidAddress !== 'function') {
90
+ throw new TypeError('registerWalletAdapter: adapter must implement resolveWallet and isValidAddress');
91
+ }
92
+ const registry = getRegistry();
93
+ registry.set(adapter.chain, adapter); // last-wins
94
+ let disposed = false;
95
+ return () => {
96
+ if (disposed)
97
+ return;
98
+ disposed = true;
99
+ if (registry.get(adapter.chain) === adapter)
100
+ registry.delete(adapter.chain);
101
+ };
102
+ }
103
+ /**
104
+ * Looks up the adapter registered for the exact CAIP-2 `chain` value.
105
+ * No aliasing, no prefix matching — `solana:mainnet-beta` and
106
+ * `solana:devnet` are different keys. Returns `null` when nothing is
107
+ * registered.
108
+ */
109
+ export function getWalletAdapter(chain) {
110
+ return getRegistry().get(chain) ?? null;
111
+ }
112
+ // ---------------------------------------------------------------------------
113
+ // Wallet-binding storage (v1.2 §3) — WeakMap, in-memory, non-persistent.
114
+ // ---------------------------------------------------------------------------
115
+ const boundWallets = new WeakMap();
116
+ /**
117
+ * Binds a wallet descriptor to an entity instance. Internal delegate for
118
+ * `Identity.bindWallet` / `Handle.bindWallet` (SubHandle inherits).
119
+ * The descriptor is COPIED (`{ ...descriptor }`) so later caller-side
120
+ * mutation cannot change what was bound (v1.2 §3.2). Storage is
121
+ * in-memory and non-persistent: after a restart the binding is gone and
122
+ * the application re-binds (React: effect/context).
123
+ *
124
+ * @throws {TypeError} If `descriptor` is not an object with non-empty
125
+ * string `chain` and `address`.
126
+ */
127
+ export function bindEntityWallet(entity, descriptor) {
128
+ if (descriptor === null || typeof descriptor !== 'object') {
129
+ throw new TypeError('bindWallet: descriptor must be an object');
130
+ }
131
+ if (typeof descriptor.chain !== 'string' || descriptor.chain.length === 0) {
132
+ throw new TypeError('bindWallet: descriptor.chain must be a non-empty string');
133
+ }
134
+ if (typeof descriptor.address !== 'string' || descriptor.address.length === 0) {
135
+ throw new TypeError('bindWallet: descriptor.address must be a non-empty string');
136
+ }
137
+ let perChain = boundWallets.get(entity);
138
+ if (perChain === undefined) {
139
+ perChain = new Map();
140
+ boundWallets.set(entity, perChain);
141
+ }
142
+ perChain.set(descriptor.chain, { ...descriptor });
143
+ }
144
+ /**
145
+ * Returns the wallet descriptor bound to the entity for the exact
146
+ * `chain`, or `null`. Internal delegate for `getWallet` methods. The
147
+ * adapter registry is NOT consulted here — this reads the binding only
148
+ * (adapters matter at derivation time, not at binding-read time).
149
+ * Entities hold no seed and cannot derive — they read what was bound.
150
+ */
151
+ export function getEntityWallet(entity, chain) {
152
+ return boundWallets.get(entity)?.get(chain) ?? null;
153
+ }
154
+ //# sourceMappingURL=payment.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"payment.js","sourceRoot":"","sources":["../src/payment.ts"],"names":[],"mappings":"AAAA,aAAa;AACb,EAAE;AACF,oEAAoE;AACpE,uEAAuE;AACvE,yEAAyE;AACzE,uEAAuE;AACvE,mEAAmE;AACnE,uCAAuC;AACvC,EAAE;AACF,uEAAuE;AACvE,sEAAsE;AACtE,wEAAwE;AACxE,mEAAmE;AAwKnE,8EAA8E;AAC9E,8DAA8D;AAC9D,8EAA8E;AAE9E,MAAM,kBAAkB,GAAG,kBAAkB,CAAC,CAAG,iBAAiB;AAClE,MAAM,kBAAkB,GAAG,sBAAsB,CAAC,CAAC,qBAAqB;AAExE;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,UAAU,CAAC,KAAa;IACtC,IAAI,OAAO,KAAK,KAAK,QA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,MAAM,IAAI,SAAS,CAAC,0CAA0C,CAAC,CAAC;IAClE,CAAC;IACD,IAAI,OAAO,UAAU,CAAC,KAAK,KAAK,QAAQ,IAAI,UAAU,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1E,MAAM,IAAI,SAAS,CAAC,yDAAyD,CAAC,CAAC;IACjF,CAAC;IACD,IAAI,OAAO,UAAU,CAAC,OAAO,KAAK,QAAQ,IAAI,UAAU,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC9E,MAAM,IAAI,SAAS,CAAC,2DAA2D,CAAC,CAAC;IACnF,CAAC;IACD,IAAI,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACxC,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC3B,QAAQ,GAAG,IAAI,GAAG,EAA4B,CAAC;QAC/C,YAAY,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACrC,CAAC;IACD,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,EAAE,EAAE,GAAG,UAAU,EAAE,CAAC,CAAC;AACpD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAAC,MAAc,EAAE,KAAa;IAC3D,OAAO,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,GAAG,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC;AACtD,CAAC"}
@@ -0,0 +1,42 @@
1
+ import { Attestation } from './attestation.js';
2
+ import type { WalletDescriptor, WalletEntityRef } from './payment.js';
3
+ /** Options for the default {@link verifyWalletBinding}. */
4
+ export interface WalletBindingOptions {
5
+ /**
6
+ * Ed25519 public key of the attestation ISSUER — the root Identity
7
+ * public key for Identity→Handle attestations, the Handle public key
8
+ * for Handle→SubHandle attestations.
9
+ */
10
+ issuerPublicKey: Uint8Array;
11
+ }
12
+ /**
13
+ * Default wallet-binding check (v1.2 §6): answers "does this attestation
14
+ * bind this wallet to this entity?".
15
+ *
16
+ * Order of the three fail-closed checks:
17
+ *
18
+ * 1. **Signature** — the token verifies against the expected issuer
19
+ * public key (`Attestation.verifySignature`).
20
+ * 2. **Subject agreement** — the attestation must attest THIS entity
21
+ * (`payload.subjectId === entity.id`); without it any valid
22
+ * attestation of a different subject would "bind" its wallet here.
23
+ * 3. **Address equality** — `payload.subjectWallet` string-equals the
24
+ * wallet address to be bound; an attestation without wallet fields
25
+ * fails (undefined never equals an address).
26
+ *
27
+ * On-curve checking and path re-derivation are NOT part of the default —
28
+ * they are adapter overrides (Mode 1) per v1.2 §6/§6.1.
29
+ *
30
+ * @returns `false` on every failed check — never throws for a
31
+ * verification mismatch (only structural token errors surface as
32
+ * `AttestationError` from `verifySignature`/decode, per its contract).
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * const ok = await verifyWalletBinding(wallet, entity, attestation, {
37
+ * issuerPublicKey: rootIdentity.getPublicKey(),
38
+ * });
39
+ * ```
40
+ */
41
+ export declare function verifyWalletBinding(wallet: WalletDescriptor, entity: WalletEntityRef, attestation: Attestation, opts: WalletBindingOptions): Promise<boolean>;
42
+ //# sourceMappingURL=wallet-binding.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wallet-binding.d.ts","sourceRoot":"","sources":["../src/wallet-binding.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAEtE,2DAA2D;AAC3D,MAAM,WAAW,oBAAoB;IACnC;;;;OAIG;IACH,eAAe,EAAE,UAAU,CAAC;CAC7B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,mBAAmB,CACvC,MAAM,EAAE,gBAAgB,EACxB,MAAM,EAAE,eAAe,EACvB,WAAW,EAAE,WAAW,EACxB,IAAI,EAAE,oBAAoB,GACzB,OAAO,CAAC,OAAO,CAAC,CAKlB"}
@@ -0,0 +1,55 @@
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
+ import { Attestation } from './attestation.js';
18
+ /**
19
+ * Default wallet-binding check (v1.2 §6): answers "does this attestation
20
+ * bind this wallet to this entity?".
21
+ *
22
+ * Order of the three fail-closed checks:
23
+ *
24
+ * 1. **Signature** — the token verifies against the expected issuer
25
+ * public key (`Attestation.verifySignature`).
26
+ * 2. **Subject agreement** — the attestation must attest THIS entity
27
+ * (`payload.subjectId === entity.id`); without it any valid
28
+ * attestation of a different subject would "bind" its wallet here.
29
+ * 3. **Address equality** — `payload.subjectWallet` string-equals the
30
+ * wallet address to be bound; an attestation without wallet fields
31
+ * fails (undefined never equals an address).
32
+ *
33
+ * On-curve checking and path re-derivation are NOT part of the default —
34
+ * they are adapter overrides (Mode 1) per v1.2 §6/§6.1.
35
+ *
36
+ * @returns `false` on every failed check — never throws for a
37
+ * verification mismatch (only structural token errors surface as
38
+ * `AttestationError` from `verifySignature`/decode, per its contract).
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * const ok = await verifyWalletBinding(wallet, entity, attestation, {
43
+ * issuerPublicKey: rootIdentity.getPublicKey(),
44
+ * });
45
+ * ```
46
+ */
47
+ export async function verifyWalletBinding(wallet, entity, attestation, opts) {
48
+ const signatureOk = await Attestation.verifySignature(attestation.token, opts.issuerPublicKey);
49
+ if (!signatureOk)
50
+ return false;
51
+ if (attestation.payload.subjectId !== entity.id)
52
+ return false;
53
+ return attestation.payload.subjectWallet === wallet.address;
54
+ }
55
+ //# sourceMappingURL=wallet-binding.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wallet-binding.js","sourceRoot":"","sources":["../src/wallet-binding.ts"],"names":[],"mappings":"AAAA,oBAAoB;AACpB,EAAE;AACF,4DAA4D;AAC5D,kEAAkE;AAClE,iEAAiE;AACjE,wEAAwE;AACxE,kEAAkE;AAClE,uEAAuE;AACvE,uEAAuE;AACvE,wEAAwE;AACxE,gEAAgE;AAChE,EAAE;AACF,sEAAsE;AACtE,yEAAyE;AACzE,qEAAqE;AACrE,4BAA4B;AAE5B,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAa/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CACvC,MAAwB,EACxB,MAAuB,EACvB,WAAwB,EACxB,IAA0B;IAE1B,MAAM,WAAW,GAAG,MAAM,WAAW,CAAC,eAAe,CAAC,WAAW,CAAC,KAAK,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC;IAC/F,IAAI,CAAC,WAAW;QAAE,OAAO,KAAK,CAAC;IAC/B,IAAI,WAAW,CAAC,OAAO,CAAC,SAAS,KAAK,MAAM,CAAC,EAAE;QAAE,OAAO,KAAK,CAAC;IAC9D,OAAO,WAAW,CAAC,OAAO,CAAC,aAAa,KAAK,MAAM,CAAC,OAAO,CAAC;AAC9D,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@me2em/core",
3
- "version": "1.0.0-rc.2",
3
+ "version": "1.0.0-rc.4",
4
4
  "description": "Core primitives for the Me2eM authorization protocol: Identity, Handle, and Session",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",