@attocash/cli 0.7.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.
@@ -74,7 +74,7 @@ export declare class AttoApplication {
74
74
  pool: AccountPool;
75
75
  messageSigningIndexes: number[];
76
76
  }>;
77
- approveLimitsProposal(id: string): Promise<{
77
+ approveLimitsProposal(id: string, validateReviewedState?: () => void, inspectApprovedState?: () => void): Promise<{
78
78
  policy: SpendingPolicy;
79
79
  mcpAccess: McpAccess;
80
80
  pool: AccountPool;
@@ -156,15 +156,17 @@ export class AttoApplication {
156
156
  messageSigningIndexes: this.ledger.messageSigningIndexes(),
157
157
  }));
158
158
  }
159
- async approveLimitsProposal(id) {
159
+ async approveLimitsProposal(id, validateReviewedState, inspectApprovedState) {
160
160
  this.requireLocalApproval();
161
161
  return this.store.withWalletLock(async () => {
162
+ validateReviewedState?.();
162
163
  const proposal = this.ledger.reviewProposal(id, this.proposalWallet());
163
164
  if (proposal.status === 'pending' && proposal.pool) {
164
165
  for (const index of proposal.pool.indexes)
165
166
  await this.deriveAddress(index);
166
167
  }
167
168
  this.ledger.approveProposal(id, this.proposalWallet());
169
+ inspectApprovedState?.();
168
170
  return this.ledger.usage();
169
171
  });
170
172
  }
@@ -12,7 +12,7 @@ export declare function signMarketplaceAttoController(options: {
12
12
  request: unknown;
13
13
  terminalConfirmed: true;
14
14
  }): Promise<import("./marketplace/proof-approval.js").MarketplaceProofApprovalResponse>;
15
- export { inspectMarketplaceWalletSetup, withUnchangedMarketplaceWalletSetup, type MarketplaceWalletSetupSnapshot } from './marketplace/wallet-setup.js';
15
+ export { inspectMarketplaceWalletSetup, withUnchangedMarketplaceWalletSetup, marketplacePaymentsUsable, marketplaceSpendingPolicyBounded, validateMarketplacePaymentCap, inspectMarketplacePaymentIntent, prepareMarketplacePayments, type MarketplaceWalletSetupSnapshot, type MarketplacePaymentMode, type MarketplacePaymentIntent, type MarketplacePaymentPlan } from './marketplace/wallet-setup.js';
16
16
  export { assertPrivatePermissions, assertPrivatePermissionsBatch, securePrivatePermissions, syncPrivateDirectory, type PrivatePath } from './storage/private-permissions.js';
17
17
  export { parseRelayOffer, decodePaymentHeader, relayPaymentPayload, relayProofFromHeader, relayEvidenceBinding, validateRelayProof, validateRelayOfferRefresh, MARKETPLACE_BINDING, type RelayRequest, type RelayTerms, type RelayProof, type RelayRecord } from './marketplace/relay.js';
18
18
  export { parseJsonObject } from './marketplace/strict-json.js';
@@ -39,7 +39,7 @@ export async function signMarketplaceAttoController(options) {
39
39
  await application.close();
40
40
  }
41
41
  }
42
- export { inspectMarketplaceWalletSetup, withUnchangedMarketplaceWalletSetup } from './marketplace/wallet-setup.js';
42
+ export { inspectMarketplaceWalletSetup, withUnchangedMarketplaceWalletSetup, marketplacePaymentsUsable, marketplaceSpendingPolicyBounded, validateMarketplacePaymentCap, inspectMarketplacePaymentIntent, prepareMarketplacePayments } from './marketplace/wallet-setup.js';
43
43
  export { assertPrivatePermissions, assertPrivatePermissionsBatch, securePrivatePermissions, syncPrivateDirectory } from './storage/private-permissions.js';
44
44
  export { parseRelayOffer, decodePaymentHeader, relayPaymentPayload, relayProofFromHeader, relayEvidenceBinding, validateRelayProof, validateRelayOfferRefresh, MARKETPLACE_BINDING } from './marketplace/relay.js';
45
45
  export { parseJsonObject } from './marketplace/strict-json.js';
@@ -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
+ }
@@ -10,4 +10,6 @@ export interface MarketplaceRecoverySource extends WalletProfile {
10
10
  export declare function withMarketplaceRecoverySeed<T>(source: string | MarketplaceRecoverySource, action: (seed: Uint8Array, source: MarketplaceRecoverySource) => T | Promise<T>): Promise<T>;
11
11
  /** Offline initialization for an explicitly selected Marketplace recovery root.
12
12
  * Recovery words remain in the existing protected terminal workflow. */
13
- export declare function initializeMarketplaceRecoveryWallet(directory: string): Promise<MarketplaceRecoverySource>;
13
+ export declare function initializeMarketplaceRecoveryWallet(directory: string, options?: {
14
+ method?: 'create' | 'import';
15
+ }): Promise<MarketplaceRecoverySource>;
@@ -67,13 +67,14 @@ export async function withMarketplaceRecoverySeed(source, action) {
67
67
  }
68
68
  /** Offline initialization for an explicitly selected Marketplace recovery root.
69
69
  * Recovery words remain in the existing protected terminal workflow. */
70
- export async function initializeMarketplaceRecoveryWallet(directory) {
70
+ export async function initializeMarketplaceRecoveryWallet(directory, options = {}) {
71
71
  requireTerminal();
72
72
  const profile = inspectWalletProfile(directory);
73
73
  // Existing source failures must never become an implicit replacement wallet.
74
74
  if (existsSync(join(profile.directory, 'state.sqlite')))
75
75
  return withMarketplaceRecoverySeed(profile.directory, (_seed, binding) => binding);
76
- const method = await terminalPrompt('Recovery phrase: [1] Create new (default), [2] Import existing: ') || '1';
76
+ const method = options.method ? (options.method === 'import' ? '2' : '1')
77
+ : await terminalPrompt('Recovery phrase: [1] Create new (default), [2] Import existing: ') || '1';
77
78
  if (method !== '1' && method !== '2')
78
79
  throw new AttoError('INVALID_INPUT', 'Choose 1 or 2.');
79
80
  if (await terminalPrompt('Type yes to store this shared recovery phrase in the OS password store: ') !== 'yes') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@attocash/cli",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Atto wallet CLI and reusable wallet engine with local key custody and shared spending limits",
5
5
  "license": "BSD-3-Clause",
6
6
  "type": "module",