@attocash/cli 0.2.2 → 0.3.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.
Files changed (137) hide show
  1. package/README.md +157 -5
  2. package/dist/application/app.d.ts +34 -3
  3. package/dist/application/app.js +142 -125
  4. package/dist/application/operations.d.ts +3 -0
  5. package/dist/application/operations.js +30 -8
  6. package/dist/cli/cli.d.ts +1 -0
  7. package/dist/cli/cli.js +101 -13
  8. package/dist/cli/onboarding.d.ts +13 -0
  9. package/dist/cli/onboarding.js +99 -2
  10. package/dist/cli/output.js +18 -2
  11. package/dist/doctor/profile.js +2 -1
  12. package/dist/internal-marketplace.d.ts +25 -0
  13. package/dist/internal-marketplace.js +50 -0
  14. package/dist/marketplace/approval-files.d.ts +3 -0
  15. package/dist/marketplace/approval-files.js +97 -0
  16. package/dist/marketplace/approval-preview.d.ts +2 -0
  17. package/dist/marketplace/approval-preview.js +86 -0
  18. package/dist/marketplace/proof-approval.d.ts +82 -0
  19. package/dist/marketplace/proof-approval.js +671 -0
  20. package/dist/marketplace/topups.d.ts +82 -0
  21. package/dist/marketplace/topups.js +485 -0
  22. package/dist/network/batching.d.ts +2 -0
  23. package/dist/network/batching.js +23 -0
  24. package/dist/network/entry.d.ts +2 -0
  25. package/dist/network/entry.js +35 -0
  26. package/dist/network/reader.d.ts +2 -0
  27. package/dist/network/reader.js +125 -37
  28. package/dist/spending/approval.d.ts +35 -0
  29. package/dist/spending/approval.js +25 -0
  30. package/dist/spending/atto-x402.d.ts +31 -0
  31. package/dist/spending/atto-x402.js +174 -0
  32. package/dist/spending/ledger.d.ts +74 -2
  33. package/dist/spending/ledger.js +298 -7
  34. package/dist/spending/payments.d.ts +105 -5
  35. package/dist/spending/payments.js +795 -11
  36. package/dist/storage/recovery-seed.d.ts +13 -0
  37. package/dist/storage/recovery-seed.js +93 -0
  38. package/dist/storage/state.d.ts +4 -0
  39. package/dist/storage/state.js +32 -2
  40. package/dist/wallet/receive.d.ts +39 -0
  41. package/dist/wallet/receive.js +264 -0
  42. package/dist/wallet/signing.d.ts +1 -0
  43. package/dist/wallet/signing.js +37 -21
  44. package/dist/wallet/types.d.ts +1 -0
  45. package/node_modules/@attocash/commons-core/Kotlin-DateTime-library-kotlinx-datetime.mjs +1922 -1918
  46. package/node_modules/@attocash/commons-core/Kotlin-DateTime-library-kotlinx-datetime.mjs.map +1 -1
  47. package/node_modules/@attocash/commons-core/README.md +9 -0
  48. package/node_modules/@attocash/commons-core/commons-commons-core.d.mts +10 -0
  49. package/node_modules/@attocash/commons-core/commons-commons-core.mjs +2543 -2434
  50. package/node_modules/@attocash/commons-core/commons-commons-core.mjs.map +1 -1
  51. package/node_modules/@attocash/commons-core/kotlin-kotlin-stdlib.mjs +4695 -4227
  52. package/node_modules/@attocash/commons-core/kotlin-kotlin-stdlib.mjs.map +1 -1
  53. package/node_modules/@attocash/commons-core/kotlin_org_jetbrains_kotlin_kotlin_dom_api_compat.mjs.map +1 -1
  54. package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-bytestring.mjs +60 -60
  55. package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-bytestring.mjs.map +1 -1
  56. package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-core.mjs +651 -631
  57. package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-core.mjs.map +1 -1
  58. package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-core.mjs +2294 -2295
  59. package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-core.mjs.map +1 -1
  60. package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  61. package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  62. package/node_modules/@attocash/commons-core/package.json +1 -1
  63. package/node_modules/@attocash/commons-node/commons-commons-node.d.mts +1 -0
  64. package/node_modules/@attocash/commons-node/commons-commons-node.mjs +873 -847
  65. package/node_modules/@attocash/commons-node/commons-commons-node.mjs.map +1 -1
  66. package/node_modules/@attocash/commons-node/kotlin-logging.mjs +109 -109
  67. package/node_modules/@attocash/commons-node/kotlin-logging.mjs.map +1 -1
  68. package/node_modules/@attocash/commons-node/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  69. package/node_modules/@attocash/commons-node/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  70. package/node_modules/@attocash/commons-node/package.json +3 -3
  71. package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.d.mts +1 -0
  72. package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.mjs +674 -640
  73. package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.mjs.map +1 -1
  74. package/node_modules/@attocash/commons-node-remote/kotlin-logging.mjs +109 -109
  75. package/node_modules/@attocash/commons-node-remote/kotlin-logging.mjs.map +1 -1
  76. package/node_modules/@attocash/commons-node-remote/kotlinx-browser.mjs.map +1 -1
  77. package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
  78. package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  79. package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  80. package/node_modules/@attocash/commons-node-remote/package.json +4 -4
  81. package/node_modules/@attocash/commons-transport/commons-commons-transport.d.mts +1 -0
  82. package/node_modules/@attocash/commons-transport/commons-commons-transport.mjs +52 -51
  83. package/node_modules/@attocash/commons-transport/commons-commons-transport.mjs.map +1 -1
  84. package/node_modules/@attocash/commons-transport/kotlinx-atomicfu.mjs +13 -13
  85. package/node_modules/@attocash/commons-transport/kotlinx-atomicfu.mjs.map +1 -1
  86. package/node_modules/@attocash/commons-transport/kotlinx-browser.mjs.map +1 -1
  87. package/node_modules/@attocash/commons-transport/kotlinx-coroutines-core.mjs +2639 -2608
  88. package/node_modules/@attocash/commons-transport/kotlinx-coroutines-core.mjs.map +1 -1
  89. package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
  90. package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  91. package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  92. package/node_modules/@attocash/commons-transport/ktor-ktor-client-content-negotiation.mjs +411 -196
  93. package/node_modules/@attocash/commons-transport/ktor-ktor-client-content-negotiation.mjs.map +1 -1
  94. package/node_modules/@attocash/commons-transport/ktor-ktor-client-core.mjs +2115 -1976
  95. package/node_modules/@attocash/commons-transport/ktor-ktor-client-core.mjs.map +1 -1
  96. package/node_modules/@attocash/commons-transport/ktor-ktor-events.mjs +7 -7
  97. package/node_modules/@attocash/commons-transport/ktor-ktor-events.mjs.map +1 -1
  98. package/node_modules/@attocash/commons-transport/ktor-ktor-http-cio.mjs +385 -384
  99. package/node_modules/@attocash/commons-transport/ktor-ktor-http-cio.mjs.map +1 -1
  100. package/node_modules/@attocash/commons-transport/ktor-ktor-http.mjs +1261 -1185
  101. package/node_modules/@attocash/commons-transport/ktor-ktor-http.mjs.map +1 -1
  102. package/node_modules/@attocash/commons-transport/ktor-ktor-io.mjs +668 -656
  103. package/node_modules/@attocash/commons-transport/ktor-ktor-io.mjs.map +1 -1
  104. package/node_modules/@attocash/commons-transport/ktor-ktor-openapi-schema.mjs +89 -0
  105. package/node_modules/@attocash/commons-transport/ktor-ktor-openapi-schema.mjs.map +1 -0
  106. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx-json.mjs +9 -9
  107. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx-json.mjs.map +1 -1
  108. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx.mjs +120 -128
  109. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx.mjs.map +1 -1
  110. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization.mjs +46 -49
  111. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization.mjs.map +1 -1
  112. package/node_modules/@attocash/commons-transport/ktor-ktor-sse.mjs.map +1 -1
  113. package/node_modules/@attocash/commons-transport/ktor-ktor-utils.mjs +1041 -985
  114. package/node_modules/@attocash/commons-transport/ktor-ktor-utils.mjs.map +1 -1
  115. package/node_modules/@attocash/commons-transport/ktor-ktor-websocket-serialization.mjs.map +1 -1
  116. package/node_modules/@attocash/commons-transport/ktor-ktor-websockets.mjs +530 -455
  117. package/node_modules/@attocash/commons-transport/ktor-ktor-websockets.mjs.map +1 -1
  118. package/node_modules/@attocash/commons-transport/package.json +4 -4
  119. package/node_modules/@attocash/commons-worker/commons-commons-worker.d.mts +1 -0
  120. package/node_modules/@attocash/commons-worker/commons-commons-worker.mjs +230 -226
  121. package/node_modules/@attocash/commons-worker/commons-commons-worker.mjs.map +1 -1
  122. package/node_modules/@attocash/commons-worker/kotlin-logging.mjs +109 -109
  123. package/node_modules/@attocash/commons-worker/kotlin-logging.mjs.map +1 -1
  124. package/node_modules/@attocash/commons-worker/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  125. package/node_modules/@attocash/commons-worker/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  126. package/node_modules/@attocash/commons-worker/package.json +3 -3
  127. package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.d.mts +1 -0
  128. package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.mjs +91 -86
  129. package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.mjs.map +1 -1
  130. package/node_modules/@attocash/commons-worker-remote/kotlin-logging.mjs +109 -109
  131. package/node_modules/@attocash/commons-worker-remote/kotlin-logging.mjs.map +1 -1
  132. package/node_modules/@attocash/commons-worker-remote/kotlinx-browser.mjs.map +1 -1
  133. package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
  134. package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  135. package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  136. package/node_modules/@attocash/commons-worker-remote/package.json +4 -4
  137. package/package.json +9 -5
package/dist/cli/cli.js CHANGED
@@ -12,6 +12,9 @@ import { approveLimitsProposal, rejectLimitsProposal } from './onboarding.js';
12
12
  import { formatHumanResult } from './output.js';
13
13
  import { configureHelp, commandErrorMessage } from './help.js';
14
14
  import { runDoctor } from '../doctor/doctor.js';
15
+ import { readMarketplaceProofApprovalRequest, writeMarketplaceProofApprovalResponse } from '../marketplace/approval-files.js';
16
+ import { formatMarketplaceApprovalPreview } from '../marketplace/approval-preview.js';
17
+ export { formatMarketplaceApprovalPreview } from '../marketplace/approval-preview.js';
15
18
  function number(value) {
16
19
  if (!/^\d+$/.test(value) || !Number.isSafeInteger(Number(value)))
17
20
  throw new InvalidArgumentError('Use an unsigned integer.');
@@ -109,12 +112,13 @@ export async function runCli(argv = process.argv) {
109
112
  wallet.command('configure').description('Update public settings')
110
113
  .option('--network <name>', 'LIVE, BETA, DEV, or LOCAL')
111
114
  .option('--node-url <url>', 'Node HTTP(S) URL')
115
+ .option('--node-batch-size <size>', 'Accounts/ranges per request (1-1000), or auto: official gateways 5, custom nodes 1000', value => value === 'auto' ? value : number(value))
112
116
  .option('--worker-url <url>', 'Work server HTTP(S) URL')
113
117
  .option('--representative <address>', 'Default representative for opening accounts; use representative change for existing accounts')
114
118
  .option('--auto-receive', 'Enable automatic receiving in receiving sessions')
115
119
  .option('--no-auto-receive', 'Disable automatic receiving')
116
120
  .option('--min-receive-raw <amount>', 'Minimum automatically received amount in RAW')
117
- .action(options => call('wallet_configure', options));
121
+ .action(options => call('wallet_configure', { ...options, ...(options.nodeBatchSize === 'auto' ? { nodeBatchSize: null } : {}) }));
118
122
  wallet.command('create').description('Create and store a new mnemonic; display recovery words in this terminal')
119
123
  .action(async () => {
120
124
  requireTerminal();
@@ -212,13 +216,13 @@ export async function runCli(argv = process.argv) {
212
216
  .option('--search <text>', 'Match addresses, names, and entity names case-insensitively')
213
217
  .option('--refresh', 'Refresh global data, bypassing freshness and retry backoff')
214
218
  .action(options => call('labels_list', options));
215
- program.command('account [address]').description('Read an account by address or key index')
216
- .option('--index <index>', 'Saved wallet account index (default: 0)', number).action((address, options) => call('account_get', { address, ...options }));
219
+ addressOptions(program.command('account [address]').description('Read full account snapshots by address, key index, or a batch of addresses'))
220
+ .action((address, options) => call('account_get', { address, ...options }));
217
221
  addressOptions(program.command('balances').description('Read balances and total for active wallet accounts by default'))
218
222
  .option('--all', 'Include every saved address, including inactive accounts').action(options => call('balances_get', options));
219
- program.command('transaction <hash>').description('Read a network transaction').action(hash => call('transaction_get', { hash }));
220
- program.command('entry <hash>').description('Read an account entry').action(hash => call('entry_get', { hash }));
221
- listOptions(program.command('history [event]').description('Read wallet account entries by default; event can be entry or transaction'))
223
+ program.command('transaction <hash>').description('Read a raw signed protocol transaction; use entry for action history').action(hash => call('transaction_get', { hash }));
224
+ program.command('entry <hash>').description('Read an action entry with owner, sender/receiver or new representative, and transfer amount').action(hash => call('entry_get', { hash }));
225
+ listOptions(program.command('history [event]').description('Read action entries by default; choose transaction for raw signed protocol records'))
222
226
  .option('--cursor <cursor>', 'Continue a previous history page with the same filters')
223
227
  .option('--from-height <height>', 'Inclusive starting height')
224
228
  .option('--to-height <height>', 'Inclusive ending height')
@@ -268,6 +272,47 @@ export async function runCli(argv = process.argv) {
268
272
  });
269
273
  });
270
274
  program.command('metrics').description('Read public Atto market metrics').action(() => call('metrics_get'));
275
+ const marketplace = program.command('marketplace').description('Fund and inspect the configured Marketplace account');
276
+ marketplace.command('connect').description('Connect this wallet to Marketplace in a local terminal')
277
+ .requiredOption('--api-url <url>', 'Marketplace /v1/agent/topups URL')
278
+ .requiredOption('--audience <audience>', 'Exact Marketplace controller-proof audience')
279
+ .option('--browser-origin <origin>', 'Allow this exact browser origin for typed proof approvals (repeatable)', (origin, previous) => [...previous, origin], [])
280
+ .option('--controller-index <index>', 'Saved wallet controller account index (default: 0)', number, 0)
281
+ .action(async (options) => {
282
+ requireTerminal();
283
+ const result = await app().connectMarketplace({ apiUrl: options.apiUrl, audience: options.audience,
284
+ controllerIndex: options.controllerIndex, ...(options.browserOrigin?.length ? { browserOrigins: options.browserOrigin } : {}) });
285
+ output(result, 'marketplace_connect');
286
+ });
287
+ marketplace.command('topup <amount>').description('Fund the configured Marketplace ATTO account under wallet spending limits')
288
+ .option('--unit <unit>', 'ATTO (default) or RAW')
289
+ .option('--request-id <id>', 'Payment ID (generated if omitted); reuse it after uncertainty')
290
+ .option('--index <index>', 'Source account index (defaults to the approved pool)', number)
291
+ .action(async (amount, options) => {
292
+ const requestId = options.requestId ?? randomUUID();
293
+ const input = compact({ amount, unit: options.unit, requestId, index: options.index });
294
+ parseOperation('marketplace_topup', input);
295
+ sendRequestId = requestId;
296
+ process.stderr.write(program.opts().json ? `${JSON.stringify({ progress: { requestId } })}\n`
297
+ : `Marketplace top-up request ID: ${requestId}\n`);
298
+ await call('marketplace_topup', input);
299
+ });
300
+ marketplace.command('status <request-id>').description('Read and reconcile a Marketplace top-up by its original request ID')
301
+ .action(requestId => call('marketplace_topup_status', { requestId }));
302
+ marketplace.command('approve <request-file>').description('Review and sign one exact typed Marketplace controller-proof request')
303
+ .action(async (requestFile) => {
304
+ requireTerminal();
305
+ const request = readMarketplaceProofApprovalRequest(requestFile);
306
+ const { preview } = app().inspectMarketplaceProofApproval(request);
307
+ process.stderr.write(`${formatMarketplaceApprovalPreview(preview)}\n`);
308
+ if (await terminalPrompt('Type approve to sign this exact Marketplace challenge: ') !== 'approve') {
309
+ throw new AttoError('CANCELLED', 'No Marketplace wallet approval was signed.');
310
+ }
311
+ const response = await app().approveMarketplaceProof(request);
312
+ const responseFile = writeMarketplaceProofApprovalResponse(requestFile, response);
313
+ output({ approved: true, responseFile, handoffId: preview.handoffId,
314
+ challengeId: preview.challengeId, expiresAt: preview.expiresAt }, 'marketplace_approve');
315
+ });
271
316
  program.command('quote').description('Preview a USD-to-Atto conversion using the indicative market price; does not send funds')
272
317
  .requiredOption('--usd <amount>', 'Exact USD amount')
273
318
  .action(options => call('price_quote', { amount: options.usd }));
@@ -292,13 +337,39 @@ export async function runCli(argv = process.argv) {
292
337
  representative.command('change <address>').description('Publish a representative change for an existing account')
293
338
  .option('--index <index>', 'Wallet account index (default: 0)', number)
294
339
  .action((representative, options) => call('representative_change', { representative, ...options }));
340
+ const message = program.command('message').description('Sign or verify exact Atto message bytes');
341
+ const messageSource = (options) => {
342
+ if ((options.text !== undefined) === (options.hex !== undefined)) {
343
+ throw new AttoError('INVALID_INPUT', 'Supply exactly one of --text or --hex.');
344
+ }
345
+ return options.text !== undefined ? { message: options.text } : { messageHex: options.hex };
346
+ };
347
+ message.command('sign').description('Sign a UTF-8 message or exact bytes using a locally approved account index')
348
+ .requiredOption('--index <index>', 'Saved wallet account index', number)
349
+ .option('--text <message>', 'Exact UTF-8 message; whitespace is preserved')
350
+ .option('--hex <bytes>', 'Exact message bytes as even-length hexadecimal; empty bytes are allowed')
351
+ .action(options => call('message_sign', { index: options.index, ...messageSource(options) }));
352
+ message.command('verify').description('Verify exact UTF-8 message or byte hex without wallet credentials')
353
+ .option('--address <address>', 'Atto address corresponding to the signing public key')
354
+ .option('--public-key <hex>', '64-character public key in hexadecimal')
355
+ .requiredOption('--signature <hex>', '128-character signature in hexadecimal')
356
+ .option('--text <message>', 'Exact UTF-8 message; whitespace is preserved')
357
+ .option('--hex <bytes>', 'Exact message bytes as even-length hexadecimal; empty bytes are allowed')
358
+ .action(options => {
359
+ if ((options.address !== undefined) === (options.publicKey !== undefined)) {
360
+ throw new AttoError('INVALID_INPUT', 'Supply exactly one of --address or --public-key.');
361
+ }
362
+ return call('message_verify', { ...(options.address !== undefined ? { address: options.address } : { publicKey: options.publicKey }),
363
+ signature: options.signature, ...messageSource(options) });
364
+ });
295
365
  const limits = program.command('limits').description('Shared spending budgets and usage');
296
366
  limits.command('status').description('Read active limits, spending usage, and pending proposals').action(() => call('limits_get'));
297
367
  const proposeAndApprove = async (update) => {
298
368
  requireTerminal();
299
369
  const current = await app().call('limits_get');
300
370
  const changes = update(current);
301
- const { proposal } = await app().call('limits_propose', compact({ policy: changes.policy ?? current.policy, access: changes.access ?? current.mcpAccess, pool: changes.pool }));
371
+ const { proposal } = await app().call('limits_propose', compact({ policy: changes.policy ?? current.policy, access: changes.access ?? current.mcpAccess,
372
+ pool: changes.pool, messageSigningIndexes: changes.messageSigningIndexes }));
302
373
  output(await approveLimitsProposal({ id: proposal.id, directory: app().store.directory }));
303
374
  };
304
375
  limits.command('set').description('Review and confirm limit changes; omitted rules are preserved')
@@ -307,18 +378,26 @@ export async function runCli(argv = process.argv) {
307
378
  .option('--unit <unit>', 'ATTO (default) or RAW for the supplied amount flags')
308
379
  .option('--input <json>', 'Replace the entire policy using JSON: {"perRequest":null,"rolling":[]}')
309
380
  .option('--access <mode>', 'MCP access: read-only or spend; defaults to current access')
381
+ .option('--message-signing-indexes <indexes>', 'Grant message signing for comma-separated indexes, or use none to clear', value => {
382
+ const trimmed = value.trim();
383
+ if (trimmed.toLowerCase() === 'none')
384
+ return [];
385
+ if (!trimmed)
386
+ throw new InvalidArgumentError('Use comma-separated indexes or none.');
387
+ return trimmed.split(',').map(entry => number(entry.trim()));
388
+ })
310
389
  .action(async (options) => {
311
390
  if (options.input !== undefined && [options.perPayment, options.daily, options.unit].some(value => value !== undefined))
312
391
  throw new AttoError('INVALID_INPUT', 'Choose policy JSON or amount flags, not both.');
313
- if ([options.input, options.perPayment, options.daily, options.access].every(value => value === undefined))
314
- throw new AttoError('INVALID_INPUT', 'Supply --per-payment, --daily, --input, or --access.');
392
+ if ([options.input, options.perPayment, options.daily, options.access, options.messageSigningIndexes].every(value => value === undefined))
393
+ throw new AttoError('INVALID_INPUT', 'Supply --per-payment, --daily, --input, --access, or --message-signing-indexes.');
315
394
  if (options.unit !== undefined && options.perPayment === undefined && options.daily === undefined)
316
395
  throw new AttoError('INVALID_INPUT', '--unit requires --per-payment or --daily.');
317
396
  return proposeAndApprove(current => ({
318
397
  policy: options.input !== undefined ? json(options.input) : {
319
398
  perRequest: options.perPayment === undefined ? current.policy.perRequest : { amount: options.perPayment, unit: options.unit ?? 'ATTO' },
320
399
  rolling: options.daily === undefined ? current.policy.rolling : [...current.policy.rolling.filter(rule => rule.days !== 1), { days: 1, amount: options.daily, unit: options.unit ?? 'ATTO' }],
321
- }, access: options.access,
400
+ }, access: options.access, messageSigningIndexes: options.messageSigningIndexes,
322
401
  }));
323
402
  });
324
403
  limits.command('clear').description('Remove all spending limits, preserving historical usage')
@@ -375,9 +454,10 @@ export async function runCli(argv = process.argv) {
375
454
  });
376
455
  program.command('operations [name]').description('List shared operations or inspect one input schema')
377
456
  .action(name => {
457
+ const visible = operations.filter(operation => !operation.internalOnly);
378
458
  if (name === undefined)
379
- return output(operations.map(({ name, description, readOnly }) => ({ name, description, readOnly })), 'operations');
380
- const operation = operations.find(operation => operation.name === name);
459
+ return output(visible.map(({ name, description, readOnly }) => ({ name, description, readOnly })), 'operations');
460
+ const operation = visible.find(operation => operation.name === name);
381
461
  if (!operation)
382
462
  throw new AttoError('UNKNOWN_OPERATION', 'Unknown Atto operation. Run atto operations to list available names.');
383
463
  output({ name: operation.name, description: operation.description, readOnly: operation.readOnly, inputSchema: z.toJSONSchema(operation.schema, { io: 'input' }) });
@@ -407,7 +487,15 @@ export async function runCli(argv = process.argv) {
407
487
  'atto labels': 'atto labels set 1 \"Savings\"\n atto labels list --all',
408
488
  'atto labels set': 'atto labels set 1 \"Savings\"', 'atto labels remove': 'atto labels remove 1',
409
489
  'atto labels show': 'atto labels show 1', 'atto labels list': 'atto labels list --all --search treasury',
490
+ 'atto message': 'atto message sign --index 0 --text "exact challenge"\n atto message verify --public-key <hex> --signature <hex> --hex <bytes>',
491
+ 'atto message sign': 'atto message sign --index 0 --text "exact challenge"',
492
+ 'atto message verify': 'atto message verify --public-key <hex> --signature <hex> --text "exact challenge"',
410
493
  'atto send': 'atto send <address> 1\n atto send --to-index 1 --amount 1\n atto send --to-label "Savings" --amount 1\n atto send <address> --usd 1',
494
+ 'atto marketplace': 'atto marketplace connect --api-url https://marketplace.example/v1/agent/topups --audience marketplace --controller-index 0 --browser-origin https://site.example\n atto marketplace topup 1 --request-id marketplace-funding-001\n atto marketplace status marketplace-funding-001',
495
+ 'atto marketplace connect': 'atto marketplace connect --api-url https://marketplace.example/v1/agent/topups --audience marketplace --controller-index 0 --browser-origin https://site.example',
496
+ 'atto marketplace topup': 'atto marketplace topup 1 --request-id marketplace-funding-001',
497
+ 'atto marketplace status': 'atto marketplace status marketplace-funding-001',
498
+ 'atto marketplace approve': 'atto marketplace approve ./marketplace-approval-request.json',
411
499
  'atto metrics': 'atto metrics', 'atto quote': 'atto quote --usd 1',
412
500
  'atto terms': 'atto terms show', 'atto terms show': 'atto terms show',
413
501
  'atto terms accept': 'atto terms accept --version <version-shown-by-terms-show> --accepted',
@@ -416,7 +504,7 @@ export async function runCli(argv = process.argv) {
416
504
  'atto representative weight': 'atto representative weight <address>',
417
505
  'atto representative change': 'atto representative change <address> --index 0',
418
506
  'atto limits': 'atto limits status', 'atto limits status': 'atto limits status',
419
- 'atto limits set': 'atto limits set --per-payment 10 --daily 25', 'atto limits clear': 'atto limits clear',
507
+ 'atto limits set': 'atto limits set --per-payment 10 --daily 25\n atto limits set --message-signing-indexes 0,1\n atto limits set --message-signing-indexes none', 'atto limits clear': 'atto limits clear',
420
508
  'atto limits approve': 'atto limits approve <proposal-id>', 'atto limits reject': 'atto limits reject <proposal-id>',
421
509
  'atto pool': 'atto pool status', 'atto pool status': 'atto pool status',
422
510
  'atto pool configure': 'atto pool configure --indexes 0,1 --consolidate\n atto pool configure --no-consolidate',
@@ -1,3 +1,4 @@
1
+ import type { WalletSettings } from '../wallet/types.js';
1
2
  export { formatHumanResult } from './output.js';
2
3
  export { configureHelp, commandErrorMessage } from './help.js';
3
4
  interface ProposalOptions {
@@ -11,3 +12,15 @@ export declare function rejectLimitsProposal({ id, directory }: ProposalOptions)
11
12
  export declare function setupMcp({ directory }: {
12
13
  directory?: string;
13
14
  }): Promise<unknown>;
15
+ /** Configure the local wallet profile used by Marketplace's private MCP integration. */
16
+ export declare function setupMarketplaceWallet({ directory, controllerIndex, reuseExisting, configuration, typedControllerApprovals, }: {
17
+ directory: string;
18
+ controllerIndex: number;
19
+ reuseExisting?: boolean;
20
+ configuration?: Pick<WalletSettings, 'network' | 'nodeUrl' | 'workerUrl'>;
21
+ typedControllerApprovals?: boolean;
22
+ }): Promise<{
23
+ directory: string;
24
+ address: string;
25
+ index: number;
26
+ }>;
@@ -1,4 +1,6 @@
1
- import { resolve } from 'node:path';
1
+ import { existsSync } from 'node:fs';
2
+ import { isAbsolute, join, resolve } from 'node:path';
3
+ import { isDeepStrictEqual } from 'node:util';
2
4
  import { AttoApplication } from '../application/app.js';
3
5
  import { amountRaw } from '../domain/amount.js';
4
6
  import { AttoError } from '../domain/errors.js';
@@ -40,11 +42,13 @@ function showProposal(review) {
40
42
  `Requested limits: ${formatPolicy(proposal.policy)}`,
41
43
  `Current pool: indexes ${review.pool.indexes.join(', ')}; consolidation ${review.pool.consolidate ? 'enabled' : 'disabled'}`,
42
44
  `Requested pool: indexes ${(proposal.pool ?? review.pool).indexes.join(', ')}; consolidation ${(proposal.pool ?? review.pool).consolidate ? 'enabled' : 'disabled'}`,
45
+ `Current message-signing indexes: ${review.messageSigningIndexes.join(', ') || 'none'}`,
46
+ `Requested message-signing indexes: ${(proposal.messageSigningIndexes ?? []).join(', ') || 'none'}`,
43
47
  '',
44
48
  ].join('\n'));
45
49
  }
46
50
  async function approve(application, id) {
47
- process.stderr.write('\nReview this exact limits proposal. These spending limits are shared with CLI payments in this profile.\n');
51
+ process.stderr.write('\nReview this exact limits proposal. Spending limits are shared with CLI payments in this profile; message-signing indexes authorize exact-byte ATTO signatures for those keys.\n');
48
52
  showProposal(await application.reviewLimitsProposal(id));
49
53
  await confirm('Type yes to approve this exact proposal: ');
50
54
  return application.approveLimitsProposal(id);
@@ -142,3 +146,96 @@ export async function setupMcp({ directory }) {
142
146
  await application.close();
143
147
  }
144
148
  }
149
+ /** Configure the local wallet profile used by Marketplace's private MCP integration. */
150
+ export async function setupMarketplaceWallet({ directory, controllerIndex, reuseExisting = false, configuration, typedControllerApprovals = false, }) {
151
+ requireTerminal();
152
+ if (!directory || !isAbsolute(directory)) {
153
+ throw new AttoError('INVALID_INPUT', 'Marketplace wallet setup requires an explicit absolute wallet directory.');
154
+ }
155
+ if (!Number.isSafeInteger(controllerIndex) || controllerIndex < 0 || controllerIndex > 2_147_483_647) {
156
+ throw new AttoError('INVALID_INPUT', 'The Marketplace controller index must be a nonnegative integer.');
157
+ }
158
+ const selectedDirectory = resolve(directory);
159
+ if (!reuseExisting && selectedDirectory === resolve(defaultCliDirectory())) {
160
+ throw new AttoError('PROFILE_CONFLICT', 'Marketplace wallet setup cannot use the default CLI wallet directory. Choose a dedicated absolute directory.');
161
+ }
162
+ if (reuseExisting && !existsSync(join(selectedDirectory, 'state.sqlite'))) {
163
+ throw new AttoError('WALLET_NOT_INITIALIZED', 'The selected CLI wallet is not initialized. Choose an existing wallet or use dedicated wallet setup.');
164
+ }
165
+ const profile = resolveWalletProfile(selectedDirectory);
166
+ display({ directory: profile.directory, action: 'Configure local Marketplace wallet' });
167
+ const application = new AttoApplication({ directory: profile.directory });
168
+ try {
169
+ const status = await application.call('wallet_status');
170
+ if (reuseExisting && !status.initialized) {
171
+ throw new AttoError('WALLET_NOT_INITIALIZED', 'The selected CLI wallet is not initialized. Choose an existing wallet or use dedicated wallet setup.');
172
+ }
173
+ if (reuseExisting && configuration
174
+ && (configuration.network !== status.settings.network || configuration.nodeUrl !== status.settings.nodeUrl
175
+ || configuration.workerUrl !== status.settings.workerUrl)) {
176
+ throw new AttoError('PROFILE_CONFLICT', 'The selected CLI wallet settings do not match the requested Marketplace network, node, and worker. Reuse preserves existing wallet settings.');
177
+ }
178
+ if (reuseExisting) {
179
+ process.stderr.write('This reuses the existing CLI wallet in place and shares its funds, spending grants, payment journals, and account pool. Keys and wallet settings stay in this profile.\n');
180
+ display({ identity: status.identity, settings: status.settings, credentialService: profile.credentialService });
181
+ }
182
+ else {
183
+ await initializeWallet(application, profile.directory);
184
+ if (configuration)
185
+ await application.call('wallet_configure', configuration);
186
+ }
187
+ const controller = await application.call('address_derive', { index: controllerIndex });
188
+ process.stderr.write([
189
+ typedControllerApprovals
190
+ ? 'This setup proposes bounded native spending. Marketplace controller actions require separate terminal approval.'
191
+ : 'This setup proposes bounded MCP spending and message signing for one controller account.',
192
+ ...(typedControllerApprovals ? [] : ['ATTO message_sign requires spend access; read-only access cannot use it.']),
193
+ 'Marketplace controller account: index ' + String(controller.index) + ' (' + JSON.stringify(controller.address) + ').',
194
+ '',
195
+ ].join('\n'));
196
+ // Reading limits_get reconciles payments. Reuse onboarding only inspects
197
+ // saved authority, leaving existing payment journals untouched.
198
+ const usage = reuseExisting ? {
199
+ policy: application.ledger.policy(), pool: application.ledger.pool(),
200
+ access: application.ledger.mcpAccess(), messageSigningIndexes: application.ledger.messageSigningIndexes(),
201
+ } : await application.call('limits_get');
202
+ if (reuseExisting) {
203
+ process.stderr.write([
204
+ `Current MCP access: ${usage.access}`,
205
+ `Current limits: ${formatPolicy(usage.policy)}`,
206
+ `Current message-signing indexes: ${usage.messageSigningIndexes.join(', ') || 'none'}`,
207
+ '',
208
+ ].join('\n'));
209
+ }
210
+ const pool = await configurePool(usage.pool);
211
+ const hasBoundedPolicy = usage.policy.perRequest !== null || usage.policy.rolling.length > 0;
212
+ const keepPolicy = reuseExisting && hasBoundedPolicy
213
+ && await choose('Spending policy: [1] Keep current bounded limits (default), [2] Set new bounded limits: ') === '1';
214
+ if (reuseExisting && !hasBoundedPolicy)
215
+ process.stderr.write('The current policy is unlimited. Marketplace setup requires explicit bounded spending limits and spend access approval.\n');
216
+ const policy = keepPolicy ? usage.policy : await boundedPolicy();
217
+ const messageSigningIndexes = typedControllerApprovals ? usage.messageSigningIndexes : reuseExisting
218
+ ? [...new Set([...usage.messageSigningIndexes, controllerIndex])].sort((a, b) => a - b) : [controllerIndex];
219
+ const proposal = reuseExisting ? await application.store.withWalletLock(async () => {
220
+ // Fail rather than replacing authority changed by another CLI/MCP session
221
+ // while the user was answering terminal prompts.
222
+ if (!isDeepStrictEqual(usage, {
223
+ policy: application.ledger.policy(), pool: application.ledger.pool(),
224
+ access: application.ledger.mcpAccess(), messageSigningIndexes: application.ledger.messageSigningIndexes(),
225
+ }) || !isDeepStrictEqual(status.settings, application.store.get('settings'))
226
+ || !isDeepStrictEqual(status.identity, application.store.get('identity'))) {
227
+ throw new AttoError('PROPOSAL_STALE', 'The shared wallet settings or authority changed during setup. Review the current wallet and run setup again.');
228
+ }
229
+ return application.ledger.proposePolicy(policy, 'spend', {
230
+ directory: profile.directory, walletFingerprint: status.identity.fingerprint, network: status.settings.network,
231
+ }, pool, messageSigningIndexes);
232
+ }) : (await application.call('limits_propose', {
233
+ policy, access: 'spend', pool, messageSigningIndexes,
234
+ })).proposal;
235
+ await approve(application, proposal.id);
236
+ return { directory: profile.directory, address: controller.address, index: controller.index };
237
+ }
238
+ finally {
239
+ await application.close();
240
+ }
241
+ }
@@ -1,6 +1,7 @@
1
1
  import { modelAddress } from '../labels/presentation.js';
2
2
  import { AttoBlock } from '@attocash/commons-core';
3
3
  import { amountOutput } from '../domain/amount.js';
4
+ import { resolveNodeBatchSize } from '../network/batching.js';
4
5
  function record(value) {
5
6
  return value !== null && typeof value === 'object' && !Array.isArray(value);
6
7
  }
@@ -23,6 +24,7 @@ function label(key) {
23
24
  }
24
25
  function transactionSummary(value) {
25
26
  const block = record(value.block) ? value.block : value;
27
+ const subject = block.subjectAddress ?? modelAddress(block, 'subject');
26
28
  let hash = value.hash;
27
29
  if (!hash && record(value.block)) {
28
30
  try {
@@ -32,8 +34,11 @@ function transactionSummary(value) {
32
34
  }
33
35
  return Object.fromEntries(Object.entries({
34
36
  type: block.type ?? block.blockType, network: block.network,
35
- address: modelAddress(block), destination: modelAddress(block, 'receiver'), subject: modelAddress(block, 'subject'),
36
- representative: modelAddress(block, 'representative'), amount: block.amount,
37
+ address: block.address ?? modelAddress(block),
38
+ sender: block.subjectRole === 'sender' ? subject : undefined,
39
+ destination: block.subjectRole === 'receiver' ? subject : modelAddress(block, 'receiver'),
40
+ subject: block.subjectRole ? undefined : subject,
41
+ representative: block.subjectRole === 'representative' ? subject : modelAddress(block, 'representative'), amount: block.amount,
37
42
  balance: block.balance, previousBalance: block.previousBalance,
38
43
  height: block.height, timestamp: block.timestamp, hash, sendHash: block.sendHash,
39
44
  }).filter(([, value]) => value !== undefined));
@@ -141,6 +146,8 @@ function formatUnlabeledHumanResult(result, operation) {
141
146
  representative: result.settings.representative,
142
147
  minReceiveRaw: result.settings.minReceiveRaw,
143
148
  nodeUrl: result.settings.nodeUrl,
149
+ nodeBatchSize: result.settings.nodeBatchSize ?? 'Automatic',
150
+ effectiveNodeBatchSize: result.effectiveNodeBatchSize,
144
151
  workerUrl: result.settings.workerUrl,
145
152
  addresses: Array.isArray(result.addresses) ? result.addresses.map(addressSummary) : result.addresses,
146
153
  pool: result.pool,
@@ -149,6 +156,10 @@ function formatUnlabeledHumanResult(result, operation) {
149
156
  const notice = operation === 'wallet_receive' ? 'Automatic receiving session. Press Ctrl+C to stop.\n' : '';
150
157
  return notice + fields(values).join('\n') + '\n';
151
158
  }
159
+ if (operation === 'wallet_configure' && typeof result.nodeUrl === 'string') {
160
+ return fields({ ...result, nodeBatchSize: result.nodeBatchSize ?? 'Automatic',
161
+ effectiveNodeBatchSize: resolveNodeBatchSize(result) }).join('\n') + '\n';
162
+ }
152
163
  if (operation === 'address_list' && Array.isArray(result.addresses)) {
153
164
  if (!result.addresses.length)
154
165
  return 'No wallet addresses. Create or import a wallet first.\n';
@@ -173,6 +184,11 @@ function formatUnlabeledHumanResult(result, operation) {
173
184
  return fields({ network: result.network, labels: Object.entries(result.addressLabels).map(([address, value]) => ({ address, ...(record(value) ? value : {}) })), directoryStatus: result.globalDirectory }).join('\n') + '\n';
174
185
  }
175
186
  if (operation === 'account_get') {
187
+ if (Array.isArray(result.accounts)) {
188
+ return fields({ accounts: result.accounts.map(value => record(value) && record(value.account)
189
+ ? { ...transactionSummary(value.account), address: value.address, lastTransactionHash: value.account.lastTransactionHash }
190
+ : { address: record(value) ? value.address : undefined, status: 'Account is not open on the network' }) }).join('\n') + '\n';
191
+ }
176
192
  if (!record(result.account))
177
193
  return 'Account is not open on the network. Receiving funds opens an account.\n';
178
194
  return fields({ ...transactionSummary(result.account), lastTransactionHash: result.account.lastTransactionHash }).join('\n') + '\n';
@@ -31,7 +31,8 @@ export function readDoctorProfile(directory) {
31
31
  const state = new DatabaseSync(file, { readOnly: true });
32
32
  try {
33
33
  state.exec('PRAGMA busy_timeout = 1000; BEGIN;');
34
- if (state.prepare('PRAGMA user_version').get()?.user_version !== 1)
34
+ const version = state.prepare('PRAGMA user_version').get()?.user_version;
35
+ if (version !== 1 && version !== 2)
35
36
  throw new AttoError('STATE_VERSION', 'This wallet state requires a supported Atto CLI version.');
36
37
  const get = (key) => {
37
38
  const row = state.prepare('SELECT value FROM settings WHERE key = ?').get(key);
@@ -0,0 +1,25 @@
1
+ import { internalOperations } from './application/operations.js';
2
+ import type { ApplicationSession } from './core.js';
3
+ import type { InternalMarketplacePaymentConfig } from './spending/payments.js';
4
+ export { internalOperations };
5
+ export type { InternalMarketplacePaymentConfig };
6
+ export type { MarketplaceIntentPayment, MarketplaceIntentPaymentFailure, MarketplaceIntentPendingSignature, MarketplaceIntentPaymentStatus } from './spending/payments.js';
7
+ /** Narrow private child facade. Additional authority can only restrict the normal MCP grants. */
8
+ export declare function createInternalMarketplaceWalletApplication(options: {
9
+ directory?: string;
10
+ authorizeWrite: (status: unknown) => void;
11
+ internalMarketplacePayment?: InternalMarketplacePaymentConfig;
12
+ }): ApplicationSession;
13
+ /** Runtime facade reserved for the configured Marketplace MCP private stdio child. */
14
+ export declare function createInternalMarketplacePaymentApplication(options: {
15
+ directory?: string;
16
+ internalMarketplacePayment: InternalMarketplacePaymentConfig;
17
+ }): ApplicationSession;
18
+ export { withMarketplaceRecoverySeed, initializeMarketplaceRecoveryWallet, type MarketplaceRecoverySource } from './storage/recovery-seed.js';
19
+ export { validateMarketplaceUserProofApproval, type MarketplaceUserProofApprovalRequest } from './marketplace/proof-approval.js';
20
+ /** Private, terminal-only typed signer. Public CLI/MCP operations remain unchanged. */
21
+ export declare function signMarketplaceAttoController(options: {
22
+ directory: string;
23
+ request: unknown;
24
+ terminalConfirmed: true;
25
+ }): Promise<import("./marketplace/proof-approval.js").MarketplaceProofApprovalResponse>;
@@ -0,0 +1,50 @@
1
+ import { AttoApplication } from './application/app.js';
2
+ import { AttoError } from './domain/errors.js';
3
+ import { internalOperations } from './application/operations.js';
4
+ export { internalOperations };
5
+ const marketplaceWalletOperations = new Set([
6
+ 'wallet_status', 'balances_get', 'receivables_list', 'send', 'journal_get', 'limits_get', 'receive',
7
+ 'marketplace_pay_intent', 'marketplace_pay_intent_status', 'message_sign',
8
+ ]);
9
+ /** Narrow private child facade. Additional authority can only restrict the normal MCP grants. */
10
+ export function createInternalMarketplaceWalletApplication(options) {
11
+ if (typeof options.authorizeWrite !== 'function')
12
+ throw new AttoError('INVALID_INPUT', 'Private wallet write authorization is required.');
13
+ const application = new AttoApplication({
14
+ directory: options.directory, access: 'mcp', internalMarketplaceReceiveSafety: true, receivingAllowed: () => false,
15
+ internalMarketplaceAuthorizeWrite: options.authorizeWrite,
16
+ ...(options.internalMarketplacePayment ? { internalMarketplacePayment: options.internalMarketplacePayment } : {}),
17
+ });
18
+ return {
19
+ async call(name, input) {
20
+ if (!marketplaceWalletOperations.has(name))
21
+ throw new AttoError('UNKNOWN_OPERATION', 'Unknown private Marketplace wallet operation.');
22
+ return application.call(name, input);
23
+ },
24
+ start: application.start.bind(application),
25
+ close: application.close.bind(application),
26
+ };
27
+ }
28
+ /** Runtime facade reserved for the configured Marketplace MCP private stdio child. */
29
+ export function createInternalMarketplacePaymentApplication(options) {
30
+ const application = new AttoApplication({ ...options, access: 'mcp' });
31
+ return {
32
+ call: application.call.bind(application),
33
+ start: application.start.bind(application),
34
+ close: application.close.bind(application),
35
+ };
36
+ }
37
+ export { withMarketplaceRecoverySeed, initializeMarketplaceRecoveryWallet } from './storage/recovery-seed.js';
38
+ export { validateMarketplaceUserProofApproval } from './marketplace/proof-approval.js';
39
+ /** Private, terminal-only typed signer. Public CLI/MCP operations remain unchanged. */
40
+ export async function signMarketplaceAttoController(options) {
41
+ if (options.terminalConfirmed !== true || !process.stdin.isTTY || !process.stderr.isTTY)
42
+ throw new Error('Local terminal approval is required.');
43
+ const application = new AttoApplication({ directory: options.directory });
44
+ try {
45
+ return await application.approveMarketplaceOwnedProof(options.request);
46
+ }
47
+ finally {
48
+ await application.close();
49
+ }
50
+ }
@@ -0,0 +1,3 @@
1
+ import type { MarketplaceProofApprovalRequest, MarketplaceProofApprovalResponse } from './proof-approval.js';
2
+ export declare function readMarketplaceProofApprovalRequest(pathValue: string): MarketplaceProofApprovalRequest;
3
+ export declare function writeMarketplaceProofApprovalResponse(requestPathValue: string, response: MarketplaceProofApprovalResponse): string;
@@ -0,0 +1,97 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, openSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { basename, dirname, join, resolve } from 'node:path';
4
+ import { AttoError } from '../domain/errors.js';
5
+ const MAX_REQUEST_BYTES = 32_768;
6
+ const PRIVATE_FILE_MODE = 0o600;
7
+ export function readMarketplaceProofApprovalRequest(pathValue) {
8
+ if (typeof pathValue !== 'string' || pathValue.length > 4096 || pathValue.includes('\0'))
9
+ throw invalidFile();
10
+ const path = resolve(pathValue);
11
+ let descriptor;
12
+ try {
13
+ const before = lstatSync(path);
14
+ if (!before.isFile() || before.isSymbolicLink() || !ownedByCurrentUser(before.uid)
15
+ || (before.mode & 0o022) !== 0 || before.size < 2 || before.size > MAX_REQUEST_BYTES)
16
+ throw invalidFile();
17
+ descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
18
+ const info = fstatSync(descriptor);
19
+ if (!info.isFile() || info.dev !== before.dev || info.ino !== before.ino || !ownedByCurrentUser(info.uid)
20
+ || (info.mode & 0o022) !== 0 || info.size < 2 || info.size > MAX_REQUEST_BYTES)
21
+ throw invalidFile();
22
+ const bytes = readFileSync(descriptor);
23
+ if (bytes.length > MAX_REQUEST_BYTES)
24
+ throw invalidFile();
25
+ const parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
26
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
27
+ throw invalidFile();
28
+ return parsed;
29
+ }
30
+ catch (error) {
31
+ if (error instanceof AttoError)
32
+ throw error;
33
+ throw invalidFile();
34
+ }
35
+ finally {
36
+ if (descriptor !== undefined)
37
+ closeSync(descriptor);
38
+ }
39
+ }
40
+ export function writeMarketplaceProofApprovalResponse(requestPathValue, response) {
41
+ const requestPath = resolve(requestPathValue);
42
+ const requestName = basename(requestPath);
43
+ if (!/^[a-f0-9]{32}\.request\.json$/.test(requestName) || requestName.slice(0, 32) !== response.handoffId)
44
+ throw invalidFile();
45
+ const directoryPath = dirname(requestPath);
46
+ const directory = lstatSync(directoryPath);
47
+ const request = lstatSync(requestPath);
48
+ if (!directory.isDirectory() || directory.isSymbolicLink() || !ownedByCurrentUser(directory.uid)
49
+ || (directory.mode & 0o022) !== 0 || !request.isFile() || request.isSymbolicLink() || !ownedByCurrentUser(request.uid))
50
+ throw invalidFile();
51
+ const responsePath = join(directoryPath, `${response.handoffId}.response.json`);
52
+ const temporaryPath = join(directoryPath, `.${randomBytes(16).toString('hex')}.tmp`);
53
+ let descriptor;
54
+ try {
55
+ descriptor = openSync(temporaryPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, PRIVATE_FILE_MODE);
56
+ fchmodSync(descriptor, PRIVATE_FILE_MODE);
57
+ writeFileSync(descriptor, `${JSON.stringify(response)}\n`, { encoding: 'utf8' });
58
+ fsyncSync(descriptor);
59
+ closeSync(descriptor);
60
+ descriptor = undefined;
61
+ try {
62
+ linkSync(temporaryPath, responsePath);
63
+ }
64
+ catch (error) {
65
+ if (error.code === 'EEXIST')
66
+ throw new AttoError('MARKETPLACE_APPROVAL_EXISTS', 'An approval response file already exists. Keep the exact response or request a new Marketplace challenge.');
67
+ throw error;
68
+ }
69
+ const directoryFd = openSync(directoryPath, constants.O_RDONLY | constants.O_DIRECTORY);
70
+ try {
71
+ fsyncSync(directoryFd);
72
+ }
73
+ finally {
74
+ closeSync(directoryFd);
75
+ }
76
+ return responsePath;
77
+ }
78
+ catch (error) {
79
+ if (error instanceof AttoError)
80
+ throw error;
81
+ throw new AttoError('MARKETPLACE_APPROVAL_FILE', 'The signed response could not be stored in a private response file.');
82
+ }
83
+ finally {
84
+ if (descriptor !== undefined)
85
+ closeSync(descriptor);
86
+ try {
87
+ unlinkSync(temporaryPath);
88
+ }
89
+ catch { /* No temp file remains if link failed or cleanup already ran. */ }
90
+ }
91
+ }
92
+ function ownedByCurrentUser(uid) {
93
+ return typeof process.getuid === 'function' && uid === process.getuid();
94
+ }
95
+ function invalidFile() {
96
+ return new AttoError('MARKETPLACE_APPROVAL_FILE', 'Use the exact private Marketplace approval request file from its configured handoff directory.');
97
+ }
@@ -0,0 +1,2 @@
1
+ import { type MarketplaceProofApprovalPreview } from './proof-approval.js';
2
+ export declare function formatMarketplaceApprovalPreview(preview: MarketplaceProofApprovalPreview): string;