@attocash/cli 0.6.0 → 0.8.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.
@@ -0,0 +1,122 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { z } from 'zod';
4
+ import { AttoError } from '../domain/errors.js';
5
+ import { parseJsonObject } from './strict-json.js';
6
+ const hash = z.string().regex(/^[a-fA-F0-9]{64}$/);
7
+ const integer = z.string().regex(/^(0|[1-9][0-9]*)$/);
8
+ const termsSchema = z.strictObject({ paymentId: z.string().uuid(), purpose: z.enum(['PUBLICATION_FEE', 'SHOP_ORDER', 'TASK_MILESTONE', 'BUYER_REFUND']),
9
+ sourceReference: z.string().min(1).max(512), ownerAccountId: z.string().uuid(), asset: z.enum(['ATTO', 'XNO']), network: z.string(),
10
+ senderAddress: z.string().min(1).max(160), recipientAddress: z.string().min(1).max(160), amountAtomic: z.string().regex(/^[1-9][0-9]{0,38}$/),
11
+ termsHash: hash, versionHash: hash, baselineHeight: integer, baselineFrontier: hash.nullable() });
12
+ export const MARKETPLACE_BINDING = 'marketplace-binding';
13
+ function invalid(message = 'The x402 offer differs from the frozen Marketplace payment.') { throw new AttoError('PAYMENT_PROTOCOL', message); }
14
+ function object(value) { if (!value || typeof value !== 'object' || Array.isArray(value))
15
+ invalid(); return value; }
16
+ export function decodePaymentHeader(header) {
17
+ if (typeof header !== 'string' || header.length < 1 || header.length > 90_000 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(header))
18
+ invalid('Invalid x402 header.');
19
+ const bytes = Buffer.from(header, 'base64');
20
+ if (bytes.length > 65_536 || bytes.toString('base64') !== header)
21
+ invalid('Invalid x402 header.');
22
+ try {
23
+ return parseJsonObject(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
24
+ }
25
+ catch {
26
+ return invalid('Invalid x402 JSON.');
27
+ }
28
+ }
29
+ export function parseRelayOffer(request, allowExpired = false, now = Date.now()) {
30
+ const terms = termsSchema.parse(request.terms);
31
+ let origin;
32
+ try {
33
+ origin = new URL(request.origin);
34
+ }
35
+ catch {
36
+ return invalid();
37
+ }
38
+ if (origin.origin !== request.origin || origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash
39
+ || !/^https?:$/.test(origin.protocol) || (origin.protocol === 'http:' && !['localhost', '127.0.0.1', '[::1]'].includes(origin.hostname))
40
+ || typeof request.audience !== 'string' || request.audience.length < 1 || request.audience.length > 255
41
+ || request.requestId !== terms.paymentId || !/^[A-Za-z0-9_-]{16,128}$/.test(request.requestId))
42
+ invalid();
43
+ if (terms.asset === 'ATTO' ? !/^atto:(live|beta|dev|local)$/.test(terms.network) || BigInt(terms.amountAtomic) > (1n << 64n) - 1n
44
+ : !/^nano:(mainnet|dev)$/.test(terms.network) || BigInt(terms.amountAtomic) > (1n << 128n) - 1n)
45
+ invalid();
46
+ const raw = decodePaymentHeader(request.paymentRequired), resource = object(raw.resource);
47
+ if (raw.x402Version !== 2 || resource.url !== `${request.origin}/v1/agent/payments/${terms.paymentId}`
48
+ || !Array.isArray(raw.accepts) || raw.accepts.length !== 1)
49
+ invalid();
50
+ const accepted = object(raw.accepts[0]);
51
+ if (accepted.scheme !== 'exact' || accepted.network !== terms.network || accepted.asset !== (terms.asset === 'ATTO' ? 'atto' : 'XNO')
52
+ || accepted.payTo !== terms.recipientAddress || accepted.amount !== terms.amountAtomic
53
+ || accepted.maxTimeoutSeconds !== (terms.asset === 'ATTO' ? 60 : 300))
54
+ invalid();
55
+ if (terms.asset === 'ATTO' && !isDeepStrictEqual(accepted.extra, { assetTransferMethod: 'native', paymentFlow: 'authorization' }))
56
+ invalid();
57
+ // Nano proposal3432@96f65c29 does not declare transfer-method/flow metadata.
58
+ if (terms.asset === 'XNO' && accepted.extra !== undefined)
59
+ invalid('Unsupported Nano x402 profile metadata.');
60
+ const extensions = object(raw.extensions);
61
+ if (Object.keys(extensions).sort().join(',') !== 'marketplace-binding,payment-identifier')
62
+ invalid('Unsupported x402 extension.');
63
+ const identifier = object(extensions['payment-identifier']), idInfo = object(identifier.info);
64
+ object(identifier.schema);
65
+ if (idInfo.required !== true || Object.keys(idInfo).some(key => !['required', 'id'].includes(key))
66
+ || (idInfo.id !== undefined && idInfo.id !== request.requestId))
67
+ invalid();
68
+ const binding = object(extensions[MARKETPLACE_BINDING]), info = object(binding.info);
69
+ object(binding.schema);
70
+ const { offerExpiresAt, ...boundTerms } = info;
71
+ if (!isDeepStrictEqual(boundTerms, { required: true, version: 1, ...terms }) || Object.keys(binding).sort().join(',') !== 'info,schema'
72
+ || typeof offerExpiresAt !== 'string' || !/^\d{4}-\d\d-\d\dT/.test(offerExpiresAt))
73
+ invalid();
74
+ const expiresAt = Date.parse(offerExpiresAt);
75
+ if (!Number.isSafeInteger(expiresAt) || (!allowExpired && expiresAt <= now))
76
+ invalid('The unused x402 offer expired. Recover the original request before preparing a replacement.');
77
+ return { header: request.paymentRequired, raw, terms, expiresAt };
78
+ }
79
+ /** Only an unused, expired offer window can change; every other offered byte remains semantically identical. */
80
+ export function validateRelayOfferRefresh(previous, next, now = Date.now()) {
81
+ const definition = (request) => ({ requestId: request.requestId, origin: request.origin, audience: request.audience, terms: request.terms, index: request.index });
82
+ const oldOffer = parseRelayOffer(previous, true, now), freshOffer = parseRelayOffer(next, false, now);
83
+ const withoutWindow = (offer) => {
84
+ const extensions = object(offer.raw.extensions), binding = object(extensions[MARKETPLACE_BINDING]);
85
+ const { offerExpiresAt: _unused, ...info } = object(binding.info);
86
+ return { ...offer.raw, extensions: { ...extensions, [MARKETPLACE_BINDING]: { ...binding, info } } };
87
+ };
88
+ if (oldOffer.expiresAt > now || freshOffer.expiresAt <= oldOffer.expiresAt || !isDeepStrictEqual(definition(previous), definition(next))
89
+ || !isDeepStrictEqual(withoutWindow(oldOffer), withoutWindow(freshOffer)))
90
+ invalid('Only an expired unused offer window may be refreshed for the original payment.');
91
+ }
92
+ export function relayEvidenceBinding(terms, transactionHash) {
93
+ return createHash('sha256').update(['Marketplace payment evidence v1', terms.paymentId, terms.versionHash, terms.termsHash,
94
+ terms.ownerAccountId, terms.network, terms.senderAddress, terms.recipientAddress, terms.amountAtomic, transactionHash.toLowerCase()].join('\n')).digest('hex');
95
+ }
96
+ export function validateRelayProof(offer, transactionHash, audience, proof, allowExpired = false, now = Date.now()) {
97
+ const parsed = z.strictObject({ challengeId: z.string().uuid(), message: z.string().min(1).max(4096), signature: z.string().regex(/^[a-fA-F0-9]{128}$/) }).safeParse(proof);
98
+ if (!parsed.success)
99
+ invalid('Invalid payment proof.');
100
+ const lines = proof.message.split('\n'), p = offer.terms;
101
+ if (lines.length !== 10 || /[\r\0]/.test(proof.message) || lines[0] !== `${p.asset === 'ATTO' ? '' : 'Nano '}Marketplace Agent Controller Proof v1`
102
+ || lines[1] !== `Audience: ${audience}` || lines[2] !== `Network: ${p.asset === 'ATTO' ? 'live' : p.network}`
103
+ || lines[3] !== `Address: ${p.senderAddress}` || lines[4] !== 'Purpose: payment evidence' || lines[5] !== `Request ID: ${proof.challengeId}`
104
+ || lines[6] !== `Binding Hash: ${relayEvidenceBinding(p, transactionHash)}` || !/^Nonce: [a-f0-9]{64}$/.test(lines[7])
105
+ || !lines[8].startsWith('Issued At: ') || !lines[9].startsWith('Expiration Time: '))
106
+ invalid('Payment proof differs from the original candidate or audience.');
107
+ const issued = Date.parse(lines[8].slice(11)), expires = Date.parse(lines[9].slice(17));
108
+ if (!Number.isSafeInteger(issued) || !Number.isSafeInteger(expires) || expires <= issued || expires - issued > 300_000
109
+ || (!allowExpired && (issued > now + 30_000 || expires <= now)))
110
+ invalid('Payment proof expired or has invalid timing.');
111
+ }
112
+ export function relayPaymentPayload(offer, requestId, payload, proof) {
113
+ const extensions = object(offer.raw.extensions), identifier = object(extensions['payment-identifier']), binding = object(extensions[MARKETPLACE_BINDING]);
114
+ const raw = { x402Version: 2, resource: offer.raw.resource, accepted: offer.raw.accepts[0], payload,
115
+ extensions: { ...extensions, 'payment-identifier': { ...identifier, info: { ...object(identifier.info), id: requestId } },
116
+ [MARKETPLACE_BINDING]: { ...binding, proof } } };
117
+ const json = JSON.stringify(raw);
118
+ if (Buffer.byteLength(json) > 65_536)
119
+ invalid('The x402 payload exceeds its byte limit.');
120
+ return Buffer.from(json).toString('base64');
121
+ }
122
+ export function relayProofFromHeader(header) { return object(object(decodePaymentHeader(header).extensions)[MARKETPLACE_BINDING]).proof; }
@@ -0,0 +1,2 @@
1
+ /** JSON.parse semantics with duplicate-field rejection, bounded depth, and no trailing tokens. */
2
+ export declare function parseJsonObject(text: string): Record<string, unknown>;
@@ -0,0 +1,96 @@
1
+ const MAX_JSON_BYTES = 1_000_000;
2
+ function objectValue(value) {
3
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
4
+ throw new Error('Expected a JSON object');
5
+ return value;
6
+ }
7
+ /** JSON.parse semantics with duplicate-field rejection, bounded depth, and no trailing tokens. */
8
+ export function parseJsonObject(text) {
9
+ if (Buffer.byteLength(text, 'utf8') > MAX_JSON_BYTES)
10
+ throw new Error('JSON input exceeds its byte limit');
11
+ // JSON.parse performs complete syntax validation. The second pass checks the
12
+ // source keys before duplicate names can be discarded by object construction.
13
+ const result = objectValue(JSON.parse(text));
14
+ let offset = 0;
15
+ const primitive = /(?:true|false|null|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)/y;
16
+ const whitespace = () => { while (/[\x20\x09\x0a\x0d]/.test(text[offset] ?? '!'))
17
+ offset++; };
18
+ const quoted = () => {
19
+ whitespace();
20
+ if (text[offset] !== '"')
21
+ throw new Error('Invalid JSON string');
22
+ const start = offset++;
23
+ // Whole-document JSON.parse already validated escapes; locate only the token boundary.
24
+ while (offset < text.length) {
25
+ const character = text[offset++];
26
+ if (character === '\\')
27
+ offset++;
28
+ else if (character === '"')
29
+ return JSON.parse(text.slice(start, offset));
30
+ }
31
+ throw new Error('Invalid JSON string');
32
+ };
33
+ const scan = (depth) => {
34
+ if (depth > 64)
35
+ throw new Error('JSON nesting exceeds its limit');
36
+ whitespace();
37
+ const character = text[offset];
38
+ if (character === '{') {
39
+ offset++;
40
+ whitespace();
41
+ if (text[offset] === '}') {
42
+ offset++;
43
+ return;
44
+ }
45
+ const keys = new Set();
46
+ while (true) {
47
+ const key = quoted();
48
+ if (keys.has(key))
49
+ throw new Error('Duplicate JSON field');
50
+ keys.add(key);
51
+ whitespace();
52
+ if (text[offset++] !== ':')
53
+ throw new Error('Invalid JSON object');
54
+ scan(depth + 1);
55
+ whitespace();
56
+ if (text[offset] === '}') {
57
+ offset++;
58
+ return;
59
+ }
60
+ if (text[offset++] !== ',')
61
+ throw new Error('Invalid JSON object');
62
+ }
63
+ }
64
+ if (character === '[') {
65
+ offset++;
66
+ whitespace();
67
+ if (text[offset] === ']') {
68
+ offset++;
69
+ return;
70
+ }
71
+ while (true) {
72
+ scan(depth + 1);
73
+ whitespace();
74
+ if (text[offset] === ']') {
75
+ offset++;
76
+ return;
77
+ }
78
+ if (text[offset++] !== ',')
79
+ throw new Error('Invalid JSON array');
80
+ }
81
+ }
82
+ if (character === '"') {
83
+ quoted();
84
+ return;
85
+ }
86
+ primitive.lastIndex = offset;
87
+ if (!primitive.exec(text))
88
+ throw new Error('Invalid JSON value');
89
+ offset = primitive.lastIndex;
90
+ };
91
+ scan(0);
92
+ whitespace();
93
+ if (offset !== text.length)
94
+ throw new Error('Trailing JSON input');
95
+ return result;
96
+ }
@@ -33,3 +33,31 @@ export declare function withUnchangedMarketplaceWalletSetup<T>(options: {
33
33
  expected: MarketplaceWalletSetupSnapshot;
34
34
  terminalConfirmed: true;
35
35
  }, action: () => Promise<T>): Promise<T>;
36
+ export declare function marketplacePaymentsUsable(value: MarketplaceWalletSetupSnapshot): boolean;
37
+ export type MarketplacePaymentMode = 'login-only' | 'limited' | 'unlimited';
38
+ export interface MarketplacePaymentIntent {
39
+ policy?: SpendingPolicy;
40
+ resumeProposalId?: string;
41
+ requiresPolicy: boolean;
42
+ }
43
+ export interface MarketplacePaymentPlan {
44
+ review: string;
45
+ validate(): Promise<void>;
46
+ commit(): Promise<MarketplaceWalletSetupSnapshot>;
47
+ }
48
+ export declare function marketplaceSpendingPolicyBounded(policy: SpendingPolicy): boolean;
49
+ /** Keep terminal cap correction on the native owner's positive ATTO amount semantics. */
50
+ export declare function validateMarketplacePaymentCap(value: string): void;
51
+ /** Pick existing intent before a caller asks for caps. This does not approve or replace a proposal. */
52
+ export declare function inspectMarketplacePaymentIntent(before: MarketplaceWalletSetupSnapshot, mode: MarketplacePaymentMode): MarketplacePaymentIntent;
53
+ /** Native authority stays unchanged until the caller commits its final, locally approved review. */
54
+ export declare function prepareMarketplacePayments(options: {
55
+ expected: MarketplaceWalletSetupSnapshot;
56
+ mode: MarketplacePaymentMode;
57
+ policy?: SpendingPolicy;
58
+ resumeProposalId?: string;
59
+ previousProposal?: {
60
+ id: string;
61
+ expiresAt: number;
62
+ };
63
+ }): Promise<MarketplacePaymentPlan>;
@@ -4,6 +4,8 @@ import { isDeepStrictEqual } from 'node:util';
4
4
  import { DatabaseSync } from 'node:sqlite';
5
5
  import { AttoAddress } from '@attocash/commons-core';
6
6
  import { requireTerminal } from '../cli/terminal.js';
7
+ import { AttoApplication } from '../application/app.js';
8
+ import { amountRaw } from '../domain/amount.js';
7
9
  import { AttoError } from '../domain/errors.js';
8
10
  import { SpendLedger } from '../spending/ledger.js';
9
11
  import { inspectWalletProfile } from '../storage/profiles.js';
@@ -117,3 +119,191 @@ export async function withUnchangedMarketplaceWalletSetup(options, action) {
117
119
  return action();
118
120
  });
119
121
  }
122
+ export function marketplacePaymentsUsable(value) {
123
+ return value.access === 'spend' && value.pool.indexes.includes(value.index);
124
+ }
125
+ export function marketplaceSpendingPolicyBounded(policy) {
126
+ return policy.perRequest !== null || policy.rolling.length > 0;
127
+ }
128
+ /** Keep terminal cap correction on the native owner's positive ATTO amount semantics. */
129
+ export function validateMarketplacePaymentCap(value) { amountRaw(value); }
130
+ /** Pick existing intent before a caller asks for caps. This does not approve or replace a proposal. */
131
+ export function inspectMarketplacePaymentIntent(before, mode) {
132
+ validatePaymentMode(mode);
133
+ if (mode === 'login-only')
134
+ return { policy: structuredClone(before.policy), requiresPolicy: false };
135
+ if (before.access === 'spend' && before.pool.indexes.includes(before.index)
136
+ && marketplaceSpendingPolicyBounded(before.policy) === (mode === 'limited')) {
137
+ return { policy: structuredClone(before.policy), requiresPolicy: false };
138
+ }
139
+ const pending = before.proposal;
140
+ if (pending?.status === 'pending' && proposalMatchesPaymentMode(before, pending, mode)) {
141
+ return { policy: structuredClone(pending.policy), resumeProposalId: pending.id, requiresPolicy: false };
142
+ }
143
+ if (mode === 'unlimited')
144
+ return { policy: { perRequest: null, rolling: [] }, requiresPolicy: false };
145
+ return marketplaceSpendingPolicyBounded(before.policy)
146
+ ? { policy: structuredClone(before.policy), requiresPolicy: false }
147
+ : { requiresPolicy: true };
148
+ }
149
+ /** Native authority stays unchanged until the caller commits its final, locally approved review. */
150
+ export async function prepareMarketplacePayments(options) {
151
+ validatePaymentMode(options.mode);
152
+ if (options.resumeProposalId !== undefined && (typeof options.resumeProposalId !== 'string' || !options.resumeProposalId)) {
153
+ throw new AttoError('INVALID_INPUT', 'A pending native proposal requires its exact nonempty proposal ID.');
154
+ }
155
+ if (options.previousProposal !== undefined && (!options.previousProposal || typeof options.previousProposal.id !== 'string'
156
+ || !options.previousProposal.id || !Number.isSafeInteger(options.previousProposal.expiresAt) || options.previousProposal.expiresAt < 0)) {
157
+ throw new AttoError('INVALID_INPUT', 'The previous pending native proposal reference is invalid.');
158
+ }
159
+ const before = structuredClone(options.expected), mode = options.mode;
160
+ const previousChanged = Boolean(options.previousProposal && (before.proposal?.status !== 'pending'
161
+ || before.proposal.id !== options.previousProposal.id || before.proposal.expiresAt !== options.previousProposal.expiresAt
162
+ || Date.now() >= options.previousProposal.expiresAt));
163
+ const intent = inspectMarketplacePaymentIntent(before, mode);
164
+ if (mode === 'login-only' && (options.policy !== undefined || options.resumeProposalId !== undefined)) {
165
+ throw new AttoError('INVALID_POLICY', 'Login-only setup does not change native payment settings.');
166
+ }
167
+ const policy = structuredClone(options.policy !== undefined ? options.policy : intent.policy);
168
+ if (!policy)
169
+ throw new AttoError('INVALID_POLICY', 'Limited spending requires a bounded policy.');
170
+ validateRequestedPolicy(policy);
171
+ if (mode === 'limited' && !marketplaceSpendingPolicyBounded(policy)) {
172
+ throw new AttoError('INVALID_POLICY', 'Limited spending requires a bounded policy.');
173
+ }
174
+ if (mode === 'unlimited' && marketplaceSpendingPolicyBounded(policy)) {
175
+ throw new AttoError('INVALID_POLICY', 'Unlimited spending requires an explicitly unbounded policy.');
176
+ }
177
+ const resumeId = options.resumeProposalId ?? (isDeepStrictEqual(policy, intent.policy) ? intent.resumeProposalId : undefined);
178
+ const resume = resumeId ? before.proposal : null;
179
+ if (resumeId && (!resume || resume.id !== resumeId || !proposalMatchesPaymentMode(before, resume, mode)
180
+ || !isDeepStrictEqual(policy, resume.policy))) {
181
+ throw new AttoError('PROPOSAL_STALE', 'The pending native settings do not match the selected spending mode and exact policy. Review setup again.');
182
+ }
183
+ const requested = mode === 'login-only' ? {
184
+ policy: before.policy, access: before.access, pool: before.pool, messageSigningIndexes: before.messageSigningIndexes,
185
+ } : resume ? {
186
+ policy, access: resume.access, pool: resume.pool ?? before.pool, messageSigningIndexes: resume.messageSigningIndexes ?? [],
187
+ } : {
188
+ policy, access: 'spend',
189
+ pool: before.pool.indexes.includes(before.index) ? before.pool
190
+ : { ...before.pool, indexes: [...before.pool.indexes, before.index].sort((a, b) => a - b) },
191
+ messageSigningIndexes: before.messageSigningIndexes,
192
+ };
193
+ if (requested.pool.indexes.length > 100)
194
+ throw new AttoError('INVALID_POOL', 'The native payment pool already has 100 accounts. Review its pool in advanced wallet setup before adding this selected account.');
195
+ const changesAuthority = !isDeepStrictEqual(requested, {
196
+ policy: before.policy, access: before.access, pool: before.pool, messageSigningIndexes: before.messageSigningIndexes,
197
+ });
198
+ if (requested.pool.indexes.length > 100)
199
+ throw new AttoError('INVALID_POOL', 'The shared native payment pool already contains the maximum of 100 accounts. Review its pool in the Atto CLI before adding this account.');
200
+ const check = (store) => {
201
+ assertSnapshot(store, before);
202
+ if (resume)
203
+ new SpendLedger(store).reviewProposal(resume.id, proposalWallet(before));
204
+ };
205
+ // Inspection uses only the existing public state owner, never application startup or credentials.
206
+ await withExistingWallet(before, async (store) => { check(store); });
207
+ let committed;
208
+ return {
209
+ review: marketplacePaymentReview(before, requested, mode, resume, changesAuthority, previousChanged),
210
+ async validate() {
211
+ await withExistingWallet(before, async (store) => {
212
+ if (committed)
213
+ assertSnapshot(store, committed);
214
+ else
215
+ check(store);
216
+ });
217
+ },
218
+ async commit() {
219
+ if (committed)
220
+ return withExistingWallet(before, async (store) => {
221
+ assertSnapshot(store, committed);
222
+ return structuredClone(committed);
223
+ });
224
+ // Login-only and already-effective authority preserve any unrelated pending proposal.
225
+ if (!resume && !changesAuthority)
226
+ return withExistingWallet(before, async (store) => { check(store); return snapshot(store, before.index); });
227
+ await withExistingWallet(before, async (store) => { check(store); });
228
+ const application = new AttoApplication({ directory: before.directory });
229
+ try {
230
+ let approvalSnapshot = before;
231
+ const proposal = resume ?? await application.store.withWalletLock(async () => {
232
+ check(application.store);
233
+ const proposed = application.ledger.proposePolicy(policy, 'spend', proposalWallet(before), requested.pool, requested.messageSigningIndexes);
234
+ approvalSnapshot = snapshot(application.store, before.index);
235
+ return proposed;
236
+ });
237
+ await application.reviewLimitsProposal(proposal.id);
238
+ await application.approveLimitsProposal(proposal.id, () => assertSnapshot(application.store, approvalSnapshot), () => {
239
+ committed = snapshot(application.store, before.index);
240
+ });
241
+ return structuredClone(committed);
242
+ }
243
+ finally {
244
+ await application.close();
245
+ }
246
+ },
247
+ };
248
+ }
249
+ function validatePaymentMode(mode) {
250
+ if (!['login-only', 'limited', 'unlimited'].includes(mode))
251
+ throw new AttoError('INVALID_INPUT', 'Choose login-only, limited, or unlimited spending.');
252
+ }
253
+ function validateRequestedPolicy(policy) {
254
+ if (!policy || typeof policy !== 'object' || policy.perRequest === undefined || !Array.isArray(policy.rolling)) {
255
+ throw new AttoError('INVALID_POLICY', 'Provide a per-request limit or null and an array of rolling limits.');
256
+ }
257
+ try {
258
+ if (policy.perRequest !== null) {
259
+ if (!['ATTO', 'RAW'].includes(policy.perRequest.unit))
260
+ throw new Error();
261
+ amountRaw(policy.perRequest.amount, policy.perRequest.unit, true);
262
+ }
263
+ for (const rule of policy.rolling) {
264
+ if (!rule || !Number.isSafeInteger(rule.days) || rule.days <= 0 || !Number.isSafeInteger(rule.days * 86_400_000))
265
+ throw new Error();
266
+ if (!['ATTO', 'RAW'].includes(rule.unit))
267
+ throw new Error();
268
+ amountRaw(rule.amount, rule.unit, true);
269
+ }
270
+ }
271
+ catch {
272
+ throw new AttoError('INVALID_POLICY', 'Limits require valid decimal amounts, explicit ATTO or RAW units, and positive whole days.');
273
+ }
274
+ }
275
+ function proposalWallet(before) {
276
+ return { directory: before.directory, walletFingerprint: before.fingerprint, network: before.settings.network };
277
+ }
278
+ function proposalMatchesPaymentMode(before, proposal, mode) {
279
+ return proposal.status === 'pending' && proposal.access === 'spend'
280
+ && proposal.directory === before.directory && proposal.walletFingerprint === before.fingerprint && proposal.network === before.settings.network
281
+ && proposal.baseRevision === before.authorityRevision && Date.now() < proposal.expiresAt
282
+ && (mode === 'limited' ? marketplaceSpendingPolicyBounded(proposal.policy) : mode === 'unlimited' && !marketplaceSpendingPolicyBounded(proposal.policy))
283
+ && (proposal.pool ?? before.pool).indexes.includes(before.index)
284
+ && isDeepStrictEqual(proposal.messageSigningIndexes ?? [], before.messageSigningIndexes);
285
+ }
286
+ function marketplacePaymentReview(before, requested, mode, resume, changesAuthority, previousChanged) {
287
+ const enablesSpend = before.access === 'read-only' && requested.access === 'spend';
288
+ const pending = before.proposal?.status === 'pending' ? before.proposal : null;
289
+ return `Atto wallet: ${before.address}\nAccount index: ${before.index} | Network: ${before.network}\n`
290
+ + (previousChanged ? 'Previous pending native settings changed or expired; the current terms require fresh approval.\n' : '')
291
+ + (mode === 'login-only' ? `Login only: native payment settings stay unchanged.\nCurrent limits: ${before.formattedLimits}\n`
292
+ : `Native payment access: ${before.access} → ${requested.access}\nCurrent limits: ${before.formattedLimits}\nRequested limits: ${formatSpendingPolicy(requested.policy)}\n`)
293
+ + (mode === 'unlimited' ? 'Unlimited spending permits the available balance, including future deposits, to be spent.\n' : '')
294
+ + (enablesSpend ? `Native payments become enabled for pool indexes ${requested.pool.indexes.join(', ')}; consolidation ${requested.pool.consolidate ? 'enabled' : 'disabled'}.\n`
295
+ : !isDeepStrictEqual(before.policy, requested.policy) ? `Shared native spending limits apply to pool indexes ${requested.pool.indexes.join(', ')}; consolidation ${requested.pool.consolidate ? 'enabled' : 'disabled'}.\n` : '')
296
+ + (enablesSpend && requested.messageSigningIndexes.length ? `Previously approved native generic message signing becomes available for account indexes ${requested.messageSigningIndexes.join(', ')}.\n` : '')
297
+ + (!isDeepStrictEqual(before.pool, requested.pool) ? `Payment pool: indexes ${before.pool.indexes.join(', ')} → ${requested.pool.indexes.join(', ')}; consolidation ${before.pool.consolidate ? 'enabled' : 'disabled'} → ${requested.pool.consolidate ? 'enabled' : 'disabled'}\n` : '')
298
+ + (resume ? `${previousChanged ? 'Approve the current pending native settings' : 'Resume the exact existing pending native settings'}, expiring ${new Date(resume.expiresAt).toISOString()}.\n` : '')
299
+ + (pending && !resume && changesAuthority ? `This replaces the existing pending native settings only after approval.\n`
300
+ + `Pending native settings to replace: access ${pending.access}; ${formatSpendingPolicy(pending.policy)}; payment pool indexes ${(pending.pool ?? before.pool).indexes.join(', ')}; consolidation ${(pending.pool ?? before.pool).consolidate ? 'enabled' : 'disabled'}; expires ${new Date(pending.expiresAt).toISOString()}.\n`
301
+ + ((pending.messageSigningIndexes ?? []).length ? `Pending generic message signing indexes to replace: ${pending.messageSigningIndexes.join(', ')}.\n` : '') : '')
302
+ + (previousChanged && pending && !resume && !changesAuthority ? `Current pending native settings remain unchanged: access ${pending.access}; ${formatSpendingPolicy(pending.policy)}; payment pool indexes ${(pending.pool ?? before.pool).indexes.join(', ')}; consolidation ${(pending.pool ?? before.pool).consolidate ? 'enabled' : 'disabled'}; expires ${new Date(pending.expiresAt).toISOString()}.\n`
303
+ + ((pending.messageSigningIndexes ?? []).length ? `Current pending generic message signing indexes: ${pending.messageSigningIndexes.join(', ')}.\n` : '') : '')
304
+ + (mode !== 'login-only' ? 'These limits and payment history are shared with CLI payments.\n' : '');
305
+ }
306
+ function assertSnapshot(store, before) {
307
+ if (!isDeepStrictEqual(before, snapshot(store, before.index)))
308
+ throw new AttoError('PROPOSAL_STALE', 'The shared wallet settings, identity, authority or pending proposal changed during review. Run setup again.');
309
+ }
@@ -20,6 +20,8 @@ export declare function parseAttoExactRequirement(input: {
20
20
  network: AttoPaymentNetwork;
21
21
  amountRaw: string;
22
22
  }): AttoExactRequirement;
23
+ /** Build the x402 string profile directly from exact Commons values, leaving native JSON untouched. */
24
+ export declare function wireTransaction(transaction: AttoTransaction): Record<string, unknown>;
23
25
  export declare function paymentPayload(requirement: AttoExactRequirement, paymentIdentifier: string, transaction: AttoTransaction): {
24
26
  json: string;
25
27
  header: string;
@@ -89,7 +89,7 @@ export function parseAttoExactRequirement(input) {
89
89
  };
90
90
  }
91
91
  /** Build the x402 string profile directly from exact Commons values, leaving native JSON untouched. */
92
- function wireTransaction(transaction) {
92
+ export function wireTransaction(transaction) {
93
93
  const block = transaction.block;
94
94
  if (!(block instanceof AttoSendBlock))
95
95
  throw new AttoError('MARKETPLACE_PROTOCOL', 'An ATTO payment must be a native SEND.');
@@ -13,6 +13,8 @@ export interface ConsolidationStep {
13
13
  status: PaymentStepStatus;
14
14
  hash?: string;
15
15
  blockJson?: string;
16
+ transactionJson?: string;
17
+ candidateBinding?: string;
16
18
  result?: unknown;
17
19
  publishedAt?: number;
18
20
  }
@@ -26,3 +28,10 @@ export declare function validatePaymentPlan(plan: PaymentPlan, parent: {
26
28
  index: number;
27
29
  sourceAddress?: string;
28
30
  }): void;
31
+ /** Optional for released block-only journals; new candidates retain exact native bytes. */
32
+ export declare function validateNativeCandidate(record: {
33
+ hash?: string;
34
+ blockJson?: string;
35
+ transactionJson?: string;
36
+ candidateBinding?: string;
37
+ }): void;
@@ -37,6 +37,7 @@ export function validatePaymentPlan(plan, parent) {
37
37
  if (accountAddresses.has(step.index) && accountAddresses.get(step.index) !== step.sourceAddress)
38
38
  throw new Error('Inconsistent step account.');
39
39
  accountAddresses.set(step.index, step.sourceAddress);
40
+ validateNativeCandidate(step);
40
41
  if (step.hash !== undefined && (typeof step.hash !== 'string' || !step.hash || typeof step.blockJson !== 'string' || !step.blockJson))
41
42
  throw new Error('Invalid recorded step.');
42
43
  if (['signed', 'published', 'unknown'].includes(step.status) && !step.hash)
@@ -67,3 +68,13 @@ export function validatePaymentPlan(plan, parent) {
67
68
  if (sentRaw !== receivedRaw || [...steps.values()].some(step => step.kind === 'send' && !received.has(step.id)))
68
69
  throw new Error('Incomplete consolidation plan.');
69
70
  }
71
+ /** Optional for released block-only journals; new candidates retain exact native bytes. */
72
+ export function validateNativeCandidate(record) {
73
+ if (record.transactionJson === undefined && record.candidateBinding === undefined)
74
+ return;
75
+ if (!record.hash || !record.blockJson || typeof record.transactionJson !== 'string'
76
+ || Buffer.byteLength(record.transactionJson, 'utf8') < 1 || Buffer.byteLength(record.transactionJson, 'utf8') > 65_536
77
+ || typeof record.candidateBinding !== 'string' || !/^[a-f0-9]{64}$/.test(record.candidateBinding)) {
78
+ throw new Error('Invalid retained native candidate.');
79
+ }
80
+ }
@@ -1,4 +1,5 @@
1
1
  import { type AttoPaymentNetwork } from './atto-x402.js';
2
+ import { type RelayRecord } from '../marketplace/relay.js';
2
3
  import { type DestinationBinding } from './destination.js';
3
4
  import type { StateStore } from '../storage/state.js';
4
5
  import type { AccountPool, SpendingPolicy } from '../wallet/types.js';
@@ -14,6 +15,8 @@ export interface SendRecord {
14
15
  status: 'reserved' | 'signed' | 'published' | 'unknown' | 'failed';
15
16
  hash?: string;
16
17
  blockJson?: string;
18
+ transactionJson?: string;
19
+ candidateBinding?: string;
17
20
  result?: unknown;
18
21
  publishedAt?: number;
19
22
  sourceAddress?: string;
@@ -23,6 +26,7 @@ export interface SendRecord {
23
26
  selection?: 'automatic' | 'explicit';
24
27
  plan?: PaymentPlan;
25
28
  external?: ExternalPaymentRecord | LegacyExternalPaymentRecord;
29
+ relay?: RelayRecord;
26
30
  }
27
31
  export interface ExternalPaymentRecord {
28
32
  kind: 'marketplace-topup' | 'marketplace-intent';
@@ -62,7 +66,7 @@ export interface ExternalPaymentSecrets {
62
66
  paymentJson?: string;
63
67
  paymentSignature?: string;
64
68
  }
65
- export type SendReservation = Pick<SendRecord, 'id' | 'index' | 'destination' | 'raw' | 'createdAt'> & Partial<Pick<SendRecord, 'sourceAddress' | 'network' | 'metadata' | 'quote' | 'selection' | 'plan' | 'destinationBinding'>> & {
69
+ export type SendReservation = Pick<SendRecord, 'id' | 'index' | 'destination' | 'raw' | 'createdAt'> & Partial<Pick<SendRecord, 'sourceAddress' | 'network' | 'metadata' | 'quote' | 'selection' | 'plan' | 'destinationBinding' | 'relay'>> & {
66
70
  external?: ExternalPaymentRecord;
67
71
  };
68
72
  export type McpAccess = 'read-only' | 'spend';
@@ -116,7 +120,11 @@ export declare class SpendLedger {
116
120
  items: SendRecord[];
117
121
  nextCursor?: string;
118
122
  };
119
- signed(id: string, hash: string, blockJson: string): void;
123
+ signed(id: string, hash: string, blockJson: string, transactionJson?: string, candidateBinding?: string): void;
124
+ /** The exact final header is immutable before any caller may submit it to Market. */
125
+ authorizeRelay(id: string, paymentSignature: string): void;
126
+ /** Caller holds the same account/wallet locks used by signing and candidate persistence. */
127
+ refreshUnusedRelay(id: string, relay: RelayRecord): void;
120
128
  /** Persist the exact offered requirement before any external SEND is signed. */
121
129
  externalChallenge(id: string, requirementJson: string, owner: Omit<ExternalPaymentSecrets, 'requirementJson' | 'transactionJson' | 'paymentJson' | 'paymentSignature' | 'paymentKind'>): void;
122
130
  /** Exact signed bytes and the attempt fence commit atomically before HTTP submission. */
@@ -140,7 +148,7 @@ export declare class SpendLedger {
140
148
  fail(id: string): void;
141
149
  /** Caller must first prove a different canonical block at this block's height. */
142
150
  reject(id: string): void;
143
- stepSigned(id: string, stepId: string, hash: string, blockJson: string): void;
151
+ stepSigned(id: string, stepId: string, hash: string, blockJson: string, transactionJson?: string, candidateBinding?: string): void;
144
152
  stepComplete(id: string, stepId: string, result: unknown, publishedAt: number): void;
145
153
  stepUncertain(id: string, stepId: string): void;
146
154
  /** Caller must prove this internal block conflicts with the canonical chain.