@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
@@ -0,0 +1,671 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { AttoError } from '../domain/errors.js';
3
+ const PURPOSES = new Set([
4
+ 'login', 'API-key creation', 'API-key rotation', 'API-key revocation',
5
+ 'link authorizer', 'link new identity', 'unlink',
6
+ 'payout address enrollment', 'payout address selection', 'payout address disablement',
7
+ 'withdrawal creation', 'administrator public moderation', 'administrator task cancellation or expiry',
8
+ 'administrator dispute opening', 'administrator dispute resolution', 'product purchase', 'product refund',
9
+ ]);
10
+ const SCOPES = new Set([
11
+ 'tasks:read', 'applications:read', 'applications:apply', 'applications:withdraw',
12
+ 'tasks:draft:write', 'tasks:publish', 'submissions:write', 'submissions:read',
13
+ 'activity:read', 'activity:write', 'balances:read',
14
+ 'files:read', 'files:write', 'products:read', 'products:write', 'products:publish', 'products:purchase',
15
+ 'purchases:read', 'purchases:refund',
16
+ ]);
17
+ const SHOP_SCOPES = new Set([
18
+ 'files:read', 'files:write', 'products:read', 'products:write', 'products:publish', 'products:purchase',
19
+ 'purchases:read', 'purchases:refund',
20
+ ]);
21
+ /** Exact typed validation shared by Marketplace's terminal and native signers. */
22
+ export function validateMarketplaceUserProofApproval(input, options) {
23
+ const request = parseRequest(input, options.network);
24
+ const purposes = new Set(['login', 'API-key creation', 'API-key rotation', 'API-key revocation',
25
+ 'link authorizer', 'link new identity', 'unlink', 'payout address enrollment', 'payout address selection',
26
+ 'payout address disablement', 'withdrawal creation', 'product purchase', 'product refund']);
27
+ const atto = options.network === 'ATTO';
28
+ if (!purposes.has(request.purpose) || (request.action.authority !== undefined && request.action.authority !== 'SELLER')
29
+ || request.controller.network !== options.network || !Number.isSafeInteger(request.controller.index)
30
+ || request.controller.index < 0 || request.controller.index > (atto ? 0x7fff_ffff : 0xffff_ffff)
31
+ || !(atto ? /^atto:\/\/[a-z2-7]{61}$/.test(request.controller.address)
32
+ : /^nano_[13][13456789abcdefghijkmnopqrstuwxyz]{59}$/.test(request.controller.address))
33
+ || !uuid(request.accountId) || !uuid(request.identityId)
34
+ || parseOrigin(request.marketplaceOrigin) !== request.marketplaceOrigin
35
+ || request.transport !== 'AGENT_API' || request.proofOrigin !== null
36
+ || !/^[^\r\n\0]{1,255}$/.test(request.audience) || request.audience.trim() !== request.audience
37
+ || (atto ? options.nativeNetwork !== 'live' : !['nano:mainnet', 'nano:dev'].includes(options.nativeNetwork)))
38
+ throw protocolFailure();
39
+ if (request.action.kind === 'credential' && record(request.action.command).operation !== request.action.operation)
40
+ throw protocolFailure();
41
+ const message = parseProofMessage(request, atto ? 'Marketplace Agent Controller Proof v1' : 'Nano Marketplace Agent Controller Proof v1');
42
+ if (message.purpose !== request.purpose || expectedPurpose(request.action) !== request.purpose
43
+ || message.audience !== request.audience || message.address !== request.controller.address
44
+ || message.network !== options.nativeNetwork || message.challengeId !== request.challenge.challengeId
45
+ || message.issuedAt !== request.challenge.issuedAt || message.expiresAt !== request.challenge.expiresAt
46
+ || message.bindingHash !== bindingHash(request))
47
+ throw protocolFailure();
48
+ const issued = millis(request.challenge.issuedAt), expires = millis(request.challenge.expiresAt);
49
+ if (expires <= issued || expires - issued > 300_000 || issued > (options.now ?? Date.now()) + 30_000
50
+ || (!options.allowExpired && expires <= (options.now ?? Date.now()))) {
51
+ throw new AttoError('MARKETPLACE_APPROVAL_EXPIRED', 'The Marketplace approval challenge has expired or is outside its five-minute lifetime. Request a new challenge.');
52
+ }
53
+ return request;
54
+ }
55
+ export function inspectMarketplaceProofApproval(input, connection, knownAddress) {
56
+ const request = parseRequest(input);
57
+ const origin = parseOrigin(request.marketplaceOrigin);
58
+ if (origin !== request.marketplaceOrigin)
59
+ throw protocolFailure();
60
+ const login = request.purpose === 'login';
61
+ if (request.action.kind === 'identity-link'
62
+ && (![request.action.authorizingAddress, request.action.newIdentityAddress].every(address => typeof address === 'string' && /^atto:\/\/[a-z2-7]{61}$/.test(address))))
63
+ throw protocolFailure();
64
+ const newIdentityApproval = request.action.kind === 'identity-link' && request.action.operation === 'NEW_IDENTITY';
65
+ if (!PURPOSES.has(request.purpose) || request.controller.network !== 'ATTO'
66
+ || !Number.isSafeInteger(request.controller.index) || request.controller.index < 0 || request.controller.index > 0x7fff_ffff
67
+ || !/^atto:\/\/[a-z2-7]{61}$/.test(request.controller.address)
68
+ || knownAddress(request.controller.index) !== request.controller.address) {
69
+ throw protocolFailure();
70
+ }
71
+ if (request.transport === 'BROWSER') {
72
+ if (!request.proofOrigin || request.proofOrigin !== request.audience || parseOrigin(request.proofOrigin) !== request.proofOrigin)
73
+ throw protocolFailure();
74
+ if (connection) {
75
+ if (!browserOriginAllowed(connection, request.proofOrigin)) {
76
+ throw new AttoError('MARKETPLACE_APPROVAL_MISMATCH', 'This browser origin is not provisioned on the connected Marketplace account.');
77
+ }
78
+ }
79
+ else if (request.proofOrigin !== origin) {
80
+ throw new AttoError('MARKETPLACE_APPROVAL_MISMATCH', 'Cross-origin browser approvals require a locally provisioned Marketplace connection.');
81
+ }
82
+ }
83
+ else if (request.proofOrigin !== null || !/^[^\r\n\0]{1,255}$/.test(request.audience) || request.audience.trim() !== request.audience) {
84
+ throw protocolFailure();
85
+ }
86
+ if (!login) {
87
+ if (!connection || !uuid(request.accountId) || !uuid(request.identityId)
88
+ || request.accountId !== connection.accountId || request.identityId !== connection.identityId
89
+ || origin !== new URL(connection.apiUrl).origin
90
+ || (!newIdentityApproval && (request.controller.address !== connection.controllerAddress
91
+ || request.controller.index !== connection.controllerIndex)))
92
+ throw new AttoError('MARKETPLACE_APPROVAL_MISMATCH', 'This approval is for a different connected Marketplace account or controller.');
93
+ if (newIdentityApproval && (request.action.authorizingIdentityId !== connection.identityId
94
+ || request.action.authorizingAddress !== connection.controllerAddress)) {
95
+ throw new AttoError('MARKETPLACE_APPROVAL_MISMATCH', 'A new-controller proof must be paired with the connected account authorizer.');
96
+ }
97
+ if (request.transport === 'AGENT_API' && request.audience !== connection.audience)
98
+ throw new AttoError('MARKETPLACE_APPROVAL_MISMATCH', 'This approval uses a different Agent API audience.');
99
+ }
100
+ else if (!uuid(request.accountId) || !uuid(request.identityId)) {
101
+ throw protocolFailure();
102
+ }
103
+ else if (connection && (origin !== new URL(connection.apiUrl).origin
104
+ || request.accountId !== connection.accountId || request.identityId !== connection.identityId
105
+ || request.controller.address !== connection.controllerAddress || request.controller.index !== connection.controllerIndex
106
+ || (request.transport === 'AGENT_API' && request.audience !== connection.audience))) {
107
+ throw new AttoError('MARKETPLACE_APPROVAL_MISMATCH', 'This login request is for a different connected Marketplace origin.');
108
+ }
109
+ const message = parseProofMessage(request);
110
+ const expected = expectedPurpose(request.action);
111
+ if (message.purpose !== request.purpose || message.audience !== request.audience
112
+ || message.address !== request.controller.address || message.challengeId !== request.challenge.challengeId
113
+ || message.issuedAt !== request.challenge.issuedAt || message.expiresAt !== request.challenge.expiresAt
114
+ || message.network !== 'live' || expected !== request.purpose)
115
+ throw protocolFailure();
116
+ const issuedAt = millis(request.challenge.issuedAt);
117
+ const expiresAt = millis(request.challenge.expiresAt);
118
+ const now = Date.now();
119
+ if (issuedAt > now + 30_000 || expiresAt <= now || expiresAt <= issuedAt || expiresAt - issuedAt > 300_000) {
120
+ throw new AttoError('MARKETPLACE_APPROVAL_EXPIRED', 'The Marketplace approval challenge has expired or is outside its five-minute lifetime. Request a new challenge.');
121
+ }
122
+ const binding = bindingHash(request);
123
+ if (binding === undefined ? message.bindingHash !== undefined : message.bindingHash !== binding)
124
+ throw protocolFailure();
125
+ const preview = {
126
+ profileId: request.profileId, handoffId: request.handoffId, marketplaceOrigin: request.marketplaceOrigin,
127
+ transport: request.transport, proofOrigin: request.proofOrigin, audience: request.audience,
128
+ controller: request.controller, purpose: request.purpose, challengeId: request.challenge.challengeId,
129
+ issuedAt: request.challenge.issuedAt, expiresAt: request.challenge.expiresAt, action: request.action,
130
+ ...(request.accountId ? { accountId: request.accountId } : {}),
131
+ ...(request.identityId ? { identityId: request.identityId } : {}),
132
+ };
133
+ return { request: request, preview };
134
+ }
135
+ export function approvalRequestDigest(request) {
136
+ return sha256(canonicalJson(request));
137
+ }
138
+ export function createMarketplaceProofApprovalResponse(request, signature) {
139
+ if (typeof signature !== 'string' || signature.length < 32 || signature.length > 4096 || /[\r\n\0]/.test(signature))
140
+ throw protocolFailure();
141
+ return { version: 1, type: 'marketplace-controller-approval-response', profileId: request.profileId,
142
+ handoffId: request.handoffId, requestDigest: approvalRequestDigest(request),
143
+ challengeId: request.challenge.challengeId, message: request.challenge.message, signature,
144
+ controllerAddress: request.controller.address, controllerIndex: request.controller.index };
145
+ }
146
+ export function canonicalJson(value) {
147
+ if (value === null || typeof value !== 'object')
148
+ return JSON.stringify(value);
149
+ if (Array.isArray(value))
150
+ return `[${value.map(canonicalJson).join(',')}]`;
151
+ const record = value;
152
+ return `{${Object.keys(record).sort().map(key => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(',')}}`;
153
+ }
154
+ function parseRequest(input, network = 'ATTO') {
155
+ const value = record(input);
156
+ if (!onlyKeys(value, ['version', 'type', 'profileId', 'handoffId', 'marketplaceOrigin', 'transport', 'proofOrigin', 'audience', 'accountId', 'identityId', 'controller', 'purpose', 'action', 'challenge'])
157
+ || value.version !== 1 || value.type !== 'marketplace-controller-approval-request'
158
+ || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/.test(String(value.profileId))
159
+ || !/^[a-f0-9]{32}$/.test(String(value.handoffId))
160
+ || (value.transport !== 'AGENT_API' && value.transport !== 'BROWSER')
161
+ || typeof value.audience !== 'string' || value.audience.length > 255 || typeof value.purpose !== 'string'
162
+ || !record(value.controller) || !record(value.action) || !record(value.challenge))
163
+ throw protocolFailure();
164
+ const controller = value.controller;
165
+ const action = value.action;
166
+ const challenge = value.challenge;
167
+ if (!onlyKeys(controller, ['network', 'address', 'index']) || !onlyKeys(challenge, ['challengeId', 'message', 'issuedAt', 'expiresAt'])
168
+ || !validActionKeys(action) || controller.network !== network || typeof controller.address !== 'string' || typeof controller.index !== 'number'
169
+ || typeof challenge.challengeId !== 'string' || !uuid(challenge.challengeId) || typeof challenge.message !== 'string' || challenge.message.length > 4096
170
+ || typeof challenge.issuedAt !== 'string' || typeof challenge.expiresAt !== 'string'
171
+ || !(value.proofOrigin === null || typeof value.proofOrigin === 'string')
172
+ || !(value.accountId === undefined || typeof value.accountId === 'string')
173
+ || !(value.identityId === undefined || typeof value.identityId === 'string'))
174
+ throw protocolFailure();
175
+ return value;
176
+ }
177
+ function parseProofMessage(request, header = 'Marketplace Agent Controller Proof v1') {
178
+ const lines = request.challenge.message.split('\n');
179
+ if (lines.length !== 9 && lines.length !== 10)
180
+ throw protocolFailure();
181
+ if (lines[0] !== header || !lines[1]?.startsWith('Audience: ')
182
+ || !lines[2]?.startsWith('Network: ') || !lines[3]?.startsWith('Address: ')
183
+ || !lines[4]?.startsWith('Purpose: ') || !lines[5]?.startsWith('Request ID: '))
184
+ throw protocolFailure();
185
+ const hasBinding = lines[6]?.startsWith('Binding Hash: ') === true;
186
+ const nonceIndex = hasBinding ? 7 : 6;
187
+ if ((hasBinding && lines.length !== 10) || (!hasBinding && lines.length !== 9)
188
+ || !/^Nonce: [0-9a-f]{64}$/.test(lines[nonceIndex] ?? '')
189
+ || !lines[nonceIndex + 1]?.startsWith('Issued At: ')
190
+ || !lines[nonceIndex + 2]?.startsWith('Expiration Time: '))
191
+ throw protocolFailure();
192
+ const bindingHash = hasBinding ? lines[6].slice('Binding Hash: '.length) : undefined;
193
+ if (bindingHash !== undefined && !/^[0-9a-f]{64}$/.test(bindingHash))
194
+ throw protocolFailure();
195
+ return {
196
+ audience: lines[1].slice('Audience: '.length), network: lines[2].slice('Network: '.length),
197
+ address: lines[3].slice('Address: '.length), purpose: lines[4].slice('Purpose: '.length),
198
+ challengeId: lines[5].slice('Request ID: '.length), ...(bindingHash ? { bindingHash } : {}),
199
+ issuedAt: lines[nonceIndex + 1].slice('Issued At: '.length),
200
+ expiresAt: lines[nonceIndex + 2].slice('Expiration Time: '.length),
201
+ };
202
+ }
203
+ function expectedPurpose(action) {
204
+ switch (action.kind) {
205
+ case 'login': return 'login';
206
+ case 'identity-link': return action.operation === 'AUTHORIZE' ? 'link authorizer'
207
+ : action.operation === 'NEW_IDENTITY' ? 'link new identity' : '';
208
+ case 'identity-unlink': return 'unlink';
209
+ case 'credential': return { CREATE: 'API-key creation', ROTATE: 'API-key rotation', REVOKE: 'API-key revocation' }[String(action.operation)] ?? '';
210
+ case 'payout-address': return { ENROLL: 'payout address enrollment', SELECT: 'payout address selection', DISABLE: 'payout address disablement' }[String(record(action.command).action)] ?? '';
211
+ case 'withdrawal': return 'withdrawal creation';
212
+ case 'adminModeration': return 'administrator public moderation';
213
+ case 'adminTaskClose': return 'administrator task cancellation or expiry';
214
+ case 'adminDisputeOpen': return 'administrator dispute opening';
215
+ case 'adminDisputeResolution': return 'administrator dispute resolution';
216
+ case 'productPurchase': return 'product purchase';
217
+ case 'productRefund': return 'product refund';
218
+ default: return '';
219
+ }
220
+ }
221
+ function validActionKeys(action) {
222
+ if (action.kind === 'login')
223
+ return onlyKeys(action, ['kind', 'network', 'address']);
224
+ if (action.kind === 'identity-link')
225
+ return onlyKeys(action, ['kind', 'operation', 'linkId', 'authorizingIdentityId', 'authorizingAddress', 'newIdentityAddress']);
226
+ if (action.kind === 'identity-unlink')
227
+ return onlyKeys(action, ['kind', 'targetIdentityId', 'authorizingIdentityId']);
228
+ if (action.kind === 'credential') {
229
+ if (!onlyKeys(action, ['kind', 'operation', 'command']))
230
+ return false;
231
+ const command = record(action.command);
232
+ if (!onlyKeys(command, ['operation', 'idempotencyKey', 'targetApiKeyId', 'credential']))
233
+ return false;
234
+ if (command.credential === undefined)
235
+ return true;
236
+ return onlyKeys(record(command.credential), ['name', 'expiresInDays', 'scopes', 'publishAttoLimit', 'publishXnoLimit',
237
+ 'applyAttoLimit', 'applyXnoLimit', 'purchaseAttoLimit', 'purchaseXnoLimit', 'productPublishAttoLimit', 'productPublishXnoLimit']);
238
+ }
239
+ if (action.kind === 'payout-address') {
240
+ return onlyKeys(action, ['kind', 'command', 'network', 'canonicalTargetAddress'])
241
+ && onlyKeys(record(action.command), ['action', 'asset', 'idempotencyKey', 'address', 'destinationId', 'expectedSelectionVersion', 'network']);
242
+ }
243
+ if (action.kind === 'withdrawal') {
244
+ return onlyKeys(action, ['kind', 'command', 'network', 'destinationAddress'])
245
+ && onlyKeys(record(action.command), ['asset', 'atomicAmount', 'destinationId', 'expectedSelectionVersion', 'idempotencyKey', 'network']);
246
+ }
247
+ if (action.kind === 'adminModeration')
248
+ return onlyKeys(action, ['kind', 'targetKind', 'action', 'targetId', 'expectedTargetVersion', 'expectedModerationVersion', 'reason', 'idempotencyKey']);
249
+ if (action.kind === 'adminTaskClose')
250
+ return onlyKeys(action, ['kind', 'taskId', 'action', 'expectedVersion', 'reason', 'idempotencyKey']);
251
+ if (action.kind === 'adminDisputeOpen')
252
+ return onlyKeys(action, ['kind', 'taskId', 'expectedEngagementVersion', 'representedAgentId', 'reason', 'statement', 'evidenceUrls', 'auditReason', 'idempotencyKey']);
253
+ if (action.kind === 'adminDisputeResolution')
254
+ return onlyKeys(action, ['kind', 'disputeId', 'expectedDisputeVersion', 'outcome', 'rationale', 'idempotencyKey']);
255
+ if (action.kind === 'productPurchase')
256
+ return hasExactKeys(action, ['kind', 'releaseId', 'expectedReleaseHash', 'sellerAgentId', 'asset', 'grossAtomic', 'feeAtomic', 'netAtomic', 'idempotencyKey']);
257
+ if (action.kind === 'productRefund')
258
+ return hasExactKeys(action, ['kind', 'purchaseId', 'expectedPurchaseVersion', 'authority', 'buyerAgentId', 'sellerAgentId', 'asset', 'grossAtomic',
259
+ 'feeAtomic', 'netAtomic', 'originalPurchaseReceiptHash', 'idempotencyKey']);
260
+ return false;
261
+ }
262
+ function bindingHash(request) {
263
+ const action = request.action;
264
+ if (action.kind === 'login') {
265
+ if (action.network !== request.controller.network || action.address !== request.controller.address
266
+ || !uuid(request.accountId) || !uuid(request.identityId))
267
+ throw protocolFailure();
268
+ return sha256(['signer-controller-enrollment-v1', request.accountId, request.identityId].join('\n'));
269
+ }
270
+ if (!request.accountId || !request.identityId)
271
+ throw protocolFailure();
272
+ if (action.kind === 'productPurchase') {
273
+ const releaseId = uuid(action.releaseId);
274
+ const sellerAgentId = uuid(action.sellerAgentId);
275
+ const key = uuid(action.idempotencyKey);
276
+ if (!releaseId || !sellerAgentId || !isSha256Hex(action.expectedReleaseHash) || !isAsset(action.asset)
277
+ || !validProductAtomicTerms(action.grossAtomic, action.feeAtomic, action.netAtomic) || !key)
278
+ throw protocolFailure();
279
+ return lengthPrefixedSha256(['marketplace-product-purchase-approval-v1', request.accountId, request.identityId,
280
+ releaseId, action.expectedReleaseHash, action.asset, action.grossAtomic, key]);
281
+ }
282
+ if (action.kind === 'productRefund') {
283
+ const purchaseId = uuid(action.purchaseId);
284
+ const version = safeVersion(action.expectedPurchaseVersion);
285
+ const buyerAgentId = uuid(action.buyerAgentId);
286
+ const sellerAgentId = uuid(action.sellerAgentId);
287
+ const key = uuid(action.idempotencyKey);
288
+ if (!purchaseId || version === undefined || (action.authority !== 'SELLER' && action.authority !== 'ADMIN')
289
+ || !buyerAgentId || !sellerAgentId || !isAsset(action.asset)
290
+ || !validProductAtomicTerms(action.grossAtomic, action.feeAtomic, action.netAtomic)
291
+ || !isSha256Hex(action.originalPurchaseReceiptHash) || !key)
292
+ throw protocolFailure();
293
+ return lengthPrefixedSha256(['marketplace-product-refund-approval-v1', action.authority, request.accountId,
294
+ request.identityId, purchaseId, action.originalPurchaseReceiptHash, String(version), action.asset,
295
+ action.grossAtomic, key]);
296
+ }
297
+ if (action.kind === 'identity-link') {
298
+ const operation = action.operation;
299
+ const linkId = uuid(action.linkId);
300
+ const authorizingIdentityId = uuid(action.authorizingIdentityId);
301
+ const authorizingAddress = action.authorizingAddress;
302
+ const newIdentityAddress = action.newIdentityAddress;
303
+ if (!['AUTHORIZE', 'NEW_IDENTITY'].includes(String(operation)) || !linkId
304
+ || !authorizingIdentityId || authorizingIdentityId !== request.identityId
305
+ || typeof authorizingAddress !== 'string' || !identityNetwork(authorizingAddress)
306
+ || typeof newIdentityAddress !== 'string' || !identityNetwork(newIdentityAddress)
307
+ || authorizingAddress === newIdentityAddress
308
+ || (operation === 'AUTHORIZE' && request.controller.address !== authorizingAddress)
309
+ || (operation === 'NEW_IDENTITY' && request.controller.address !== newIdentityAddress))
310
+ throw protocolFailure();
311
+ return sha256([request.accountId, linkId, `${identityNetwork(authorizingAddress)}:${authorizingAddress}`,
312
+ `${identityNetwork(newIdentityAddress)}:${newIdentityAddress}`].join('\n'));
313
+ }
314
+ if (action.kind === 'identity-unlink') {
315
+ const targetIdentityId = uuid(action.targetIdentityId);
316
+ const authorizingIdentityId = uuid(action.authorizingIdentityId);
317
+ if (!targetIdentityId || !authorizingIdentityId || authorizingIdentityId !== request.identityId
318
+ || targetIdentityId === authorizingIdentityId)
319
+ throw protocolFailure();
320
+ return sha256(`unlink\n${request.accountId}\n${targetIdentityId}\n${authorizingIdentityId}`);
321
+ }
322
+ if (action.kind === 'credential') {
323
+ const command = record(action.command);
324
+ const operation = String(command.operation);
325
+ const key = uuid(command.idempotencyKey);
326
+ const target = command.targetApiKeyId === undefined ? '' : uuid(command.targetApiKeyId);
327
+ if (!key || target === false || (operation === 'CREATE') !== (command.credential !== undefined)
328
+ || (operation === 'CREATE') !== (target === ''))
329
+ throw protocolFailure();
330
+ let payload = '';
331
+ if (operation === 'CREATE') {
332
+ const credential = record(command.credential);
333
+ const name = typeof credential.name === 'string' ? javaTrim(credential.name) : '';
334
+ const expiresInDays = credential.expiresInDays;
335
+ const scopes = credential.scopes;
336
+ if (!name || name.length > 64 || /[\x00-\x1f\x7f]/.test(name)
337
+ || typeof expiresInDays !== 'number' || !Number.isSafeInteger(expiresInDays) || expiresInDays < 1 || expiresInDays > 365
338
+ || !Array.isArray(scopes) || scopes.length === 0 || scopes.some(scope => typeof scope !== 'string' || !SCOPES.has(scope))
339
+ || new Set(scopes).size !== scopes.length)
340
+ throw protocolFailure();
341
+ const publishAttoLimit = atomicOrEmpty(credential.publishAttoLimit);
342
+ const publishXnoLimit = atomicOrEmpty(credential.publishXnoLimit);
343
+ const applyAttoLimit = atomicOrEmpty(credential.applyAttoLimit);
344
+ const applyXnoLimit = atomicOrEmpty(credential.applyXnoLimit);
345
+ const purchaseAttoLimit = atomicOrEmpty(credential.purchaseAttoLimit);
346
+ const purchaseXnoLimit = atomicOrEmpty(credential.purchaseXnoLimit);
347
+ const productPublishAttoLimit = atomicOrEmpty(credential.productPublishAttoLimit);
348
+ const productPublishXnoLimit = atomicOrEmpty(credential.productPublishXnoLimit);
349
+ if ((scopes.includes('tasks:publish')) !== Boolean(publishAttoLimit || publishXnoLimit)
350
+ || (scopes.includes('applications:apply')) !== Boolean(applyAttoLimit || applyXnoLimit)
351
+ || (scopes.includes('products:purchase')) !== Boolean(purchaseAttoLimit || purchaseXnoLimit)
352
+ || (Boolean(productPublishAttoLimit || productPublishXnoLimit) && !scopes.includes('products:publish')))
353
+ throw protocolFailure();
354
+ const orderedFields = [name, String(expiresInDays), [...scopes].sort().join(','), publishAttoLimit, publishXnoLimit, applyAttoLimit];
355
+ payload = productPublishAttoLimit || productPublishXnoLimit
356
+ ? ['agent-credential-v4', ...orderedFields, applyXnoLimit, purchaseAttoLimit, purchaseXnoLimit,
357
+ productPublishAttoLimit, productPublishXnoLimit].join('\n')
358
+ : scopes.some(scope => SHOP_SCOPES.has(scope))
359
+ ? ['agent-credential-v3', ...orderedFields, applyXnoLimit, purchaseAttoLimit, purchaseXnoLimit].join('\n')
360
+ : ['agent-credential-v2', ...orderedFields, applyXnoLimit].join('\n');
361
+ }
362
+ return sha256(['agent-credential-v1', request.accountId, request.identityId, operation,
363
+ target || '', key, payload].join('\n'));
364
+ }
365
+ if (action.kind === 'payout-address') {
366
+ const command = record(action.command);
367
+ const actionName = String(command.action);
368
+ const asset = String(command.asset);
369
+ const key = uuid(command.idempotencyKey);
370
+ const destinationId = command.destinationId === undefined ? '' : uuid(command.destinationId);
371
+ const version = command.expectedSelectionVersion;
372
+ const network = action.network;
373
+ const address = action.canonicalTargetAddress;
374
+ if (!['ENROLL', 'SELECT', 'DISABLE'].includes(actionName) || !['ATTO', 'XNO'].includes(asset) || !key
375
+ || destinationId === false || typeof network !== 'string' || typeof address !== 'string' || !address
376
+ || (command.network !== undefined && command.network !== network)
377
+ || !(version === undefined || (typeof version === 'number' && Number.isSafeInteger(version) && version >= 0))
378
+ || (actionName === 'ENROLL') !== (typeof command.address === 'string')
379
+ || (actionName === 'ENROLL') !== (destinationId === ''))
380
+ throw protocolFailure();
381
+ return sha256(['payout-address-v1', request.accountId, request.identityId, actionName, asset,
382
+ network, destinationId || '', address, version === undefined ? '' : String(version), key].join('\n'));
383
+ }
384
+ if (action.kind === 'withdrawal') {
385
+ const command = record(action.command);
386
+ const asset = String(command.asset);
387
+ const amount = command.atomicAmount;
388
+ const destinationId = uuid(command.destinationId);
389
+ const key = uuid(command.idempotencyKey);
390
+ const version = command.expectedSelectionVersion;
391
+ const network = action.network;
392
+ const address = action.destinationAddress;
393
+ if (!['ATTO', 'XNO'].includes(asset) || typeof amount !== 'string' || !/^[1-9][0-9]{0,64}$/.test(amount)
394
+ || !destinationId || !key || typeof version !== 'number' || !Number.isSafeInteger(version) || version < 0
395
+ || typeof network !== 'string' || typeof address !== 'string' || !address
396
+ || (command.network !== undefined && command.network !== network))
397
+ throw protocolFailure();
398
+ return sha256(['withdrawal-create-v2', request.accountId, request.identityId, asset, amount,
399
+ network, destinationId, address, String(version), key].join('\n'));
400
+ }
401
+ if (action.kind === 'adminModeration') {
402
+ const targetKind = action.targetKind;
403
+ const operation = action.action;
404
+ const targetId = uuid(action.targetId);
405
+ const targetVersion = safeVersion(action.expectedTargetVersion);
406
+ const moderationVersion = safeVersion(action.expectedModerationVersion);
407
+ const reason = boundedAsciiSpaceReason(action.reason, 1_000);
408
+ const key = uuid(action.idempotencyKey);
409
+ if ((targetKind !== 'TASK' && targetKind !== 'PROFILE')
410
+ || !['HIDE', 'RESTORE', 'SUSPEND'].includes(String(operation))
411
+ || (targetKind === 'TASK' && operation === 'SUSPEND')
412
+ || !targetId || targetVersion === undefined || moderationVersion === undefined || reason === undefined || !key) {
413
+ throw protocolFailure();
414
+ }
415
+ return lengthPrefixedSha256(['marketplace-admin-public-moderation-v1', request.accountId,
416
+ request.identityId, targetKind, targetId, String(operation), String(targetVersion),
417
+ String(moderationVersion), reason, key]);
418
+ }
419
+ if (action.kind === 'adminTaskClose') {
420
+ const taskId = uuid(action.taskId);
421
+ const operation = action.action;
422
+ const version = safeVersion(action.expectedVersion);
423
+ const reason = boundedAsciiSpaceReason(action.reason, 1_000);
424
+ const key = uuid(action.idempotencyKey);
425
+ if (!taskId || (operation !== 'CANCEL' && operation !== 'EXPIRE')
426
+ || version === undefined || reason === undefined || !key)
427
+ throw protocolFailure();
428
+ return lengthPrefixedSha256(['marketplace-admin-task-close-v1', request.accountId, request.identityId,
429
+ taskId, operation, String(version), reason, key]);
430
+ }
431
+ if (action.kind === 'adminDisputeOpen') {
432
+ const taskId = uuid(action.taskId);
433
+ const engagementVersion = safeVersion(action.expectedEngagementVersion);
434
+ const representedAgentId = uuid(action.representedAgentId);
435
+ const reason = action.reason;
436
+ const key = uuid(action.idempotencyKey);
437
+ const statement = boundedDisputeText(action.statement);
438
+ const auditReason = boundedDisputeText(action.auditReason);
439
+ const evidence = canonicalEvidenceUrls(action.evidenceUrls);
440
+ if (!taskId || engagementVersion === undefined || !representedAgentId
441
+ || (reason !== 'NON_DELIVERY' && reason !== 'DELIVERABLE_MISMATCH' && reason !== 'OTHER')
442
+ || !key || statement === undefined || auditReason === undefined || evidence === undefined)
443
+ throw protocolFailure();
444
+ return lengthPrefixedSha256(['dispute-admin-open-v1', request.accountId, request.identityId, taskId,
445
+ String(engagementVersion), representedAgentId, reason, key, statement, auditReason, ...evidence]);
446
+ }
447
+ if (action.kind === 'adminDisputeResolution') {
448
+ const disputeId = uuid(action.disputeId);
449
+ const version = safeVersion(action.expectedDisputeVersion);
450
+ const outcome = action.outcome;
451
+ const rationale = boundedDisputeText(action.rationale);
452
+ const key = uuid(action.idempotencyKey);
453
+ if (!disputeId || version === undefined || (outcome !== 'WORKER_AWARD' && outcome !== 'BUYER_REFUND')
454
+ || rationale === undefined || !key)
455
+ throw protocolFailure();
456
+ return lengthPrefixedSha256(['dispute-admin-resolve-v1', request.accountId, request.identityId,
457
+ disputeId, String(version), outcome, rationale, key]);
458
+ }
459
+ throw protocolFailure();
460
+ }
461
+ function browserOriginAllowed(connection, proofOrigin) {
462
+ const apiOrigin = new URL(connection.apiUrl).origin;
463
+ const allowed = connection.browserOrigins ?? [apiOrigin];
464
+ return allowed.includes(proofOrigin);
465
+ }
466
+ function safeVersion(value) {
467
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
468
+ }
469
+ function isAsset(value) {
470
+ return value === 'ATTO' || value === 'XNO';
471
+ }
472
+ function isSha256Hex(value) {
473
+ return typeof value === 'string' && /^[0-9a-f]{64}$/.test(value);
474
+ }
475
+ function validProductAtomicTerms(gross, fee, net) {
476
+ if (typeof gross !== 'string' || !/^[1-9][0-9]{0,64}$/.test(gross)
477
+ || typeof fee !== 'string' || !/^(?:0|[1-9][0-9]{0,64})$/.test(fee)
478
+ || typeof net !== 'string' || !/^[1-9][0-9]{0,64}$/.test(net))
479
+ return false;
480
+ return BigInt(gross) === BigInt(fee) + BigInt(net);
481
+ }
482
+ function hasExactKeys(value, keys) {
483
+ const actual = Object.keys(value);
484
+ return actual.length === keys.length && actual.every(key => keys.includes(key));
485
+ }
486
+ function boundedAsciiSpaceReason(value, maximumCodePoints) {
487
+ if (typeof value !== 'string' || /[\u0000-\u001f\u007f]/.test(value))
488
+ return undefined;
489
+ const normalized = value.replace(/^ +| +$/g, '');
490
+ return [...normalized].length >= 1 && [...normalized].length <= maximumCodePoints ? normalized : undefined;
491
+ }
492
+ function boundedDisputeText(value) {
493
+ if (typeof value !== 'string' || value.includes('\0'))
494
+ return undefined;
495
+ const normalized = normalizeDisputeText(value);
496
+ return [...normalized].length >= 1 && [...normalized].length <= 2_000 ? normalized : undefined;
497
+ }
498
+ export function normalizeDisputeText(value) {
499
+ const characters = [...value];
500
+ let first = 0;
501
+ let last = characters.length;
502
+ while (first < last && isKotlinWhitespace(characters[first]))
503
+ first++;
504
+ while (last > first && isKotlinWhitespace(characters[last - 1]))
505
+ last--;
506
+ return characters.slice(first, last).join('');
507
+ }
508
+ function isKotlinWhitespace(character) {
509
+ const point = character.codePointAt(0);
510
+ return (point >= 0x0009 && point <= 0x000d) || (point >= 0x001c && point <= 0x0020)
511
+ || point === 0x00a0 || point === 0x1680 || (point >= 0x2000 && point <= 0x200a)
512
+ || point === 0x2028 || point === 0x2029 || point === 0x202f || point === 0x205f || point === 0x3000;
513
+ }
514
+ function canonicalEvidenceUrls(value) {
515
+ if (!Array.isArray(value) || value.length > 5 || value.some(item => typeof item !== 'string'))
516
+ return undefined;
517
+ const urls = [];
518
+ for (const item of value) {
519
+ if (item.length < 1 || item.length > 2_048)
520
+ return undefined;
521
+ const canonical = backendEvidenceUrl(item);
522
+ if (!canonical)
523
+ return undefined;
524
+ urls.push(canonical);
525
+ }
526
+ return new Set(urls).size === urls.length ? urls : undefined;
527
+ }
528
+ export function normalizeEvidenceUrls(value) {
529
+ return canonicalEvidenceUrls(value);
530
+ }
531
+ function backendEvidenceUrl(raw) {
532
+ // java.net.URI.toASCIIString emits non-ASCII URI text in NFC form before
533
+ // escaping its UTF-8 bytes. Keep the same spelling behavior for the
534
+ // backend's length-prefixed approval binding.
535
+ const normalized = raw.normalize('NFC');
536
+ const match = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)(.*)$/su.exec(normalized);
537
+ if (!match || match[1].toLowerCase() !== 'https')
538
+ return undefined;
539
+ const authority = match[2];
540
+ if (!authority || authority.includes('@') || !validUriCharacters(normalized))
541
+ return undefined;
542
+ const serverAuthority = /^([^:\[\]@/?#]+)(?::([0-9]*))?$/u.exec(authority);
543
+ if (!serverAuthority)
544
+ return undefined;
545
+ const rawHost = serverAuthority[1];
546
+ const portText = serverAuthority[2];
547
+ if (portText !== undefined && portText !== '') {
548
+ const port = Number(portText);
549
+ if (!Number.isSafeInteger(port) || port < 1 || port > 65_535)
550
+ return undefined;
551
+ }
552
+ const host = rawHost.toLowerCase();
553
+ const labels = host.split('.');
554
+ if (labels.length < 2 || labels.some(label => !label || label.length > 63
555
+ || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label))
556
+ || labels.at(-1).length < 2 || /^\d+$/.test(labels.at(-1))
557
+ || ['localhost', 'local', 'internal', 'test', 'invalid'].includes(labels.at(-1))
558
+ || /^[0-9.]+$/.test(host) || host.includes(':'))
559
+ return undefined;
560
+ return toAsciiUri(normalized);
561
+ }
562
+ function validUriCharacters(value) {
563
+ const match = /^[A-Za-z][A-Za-z0-9+.-]*:\/\/([^/?#]*)(.*)$/su.exec(value);
564
+ if (!match)
565
+ return false;
566
+ const suffix = match[2];
567
+ const fragmentAt = suffix.indexOf('#');
568
+ if (fragmentAt >= 0 && suffix.indexOf('#', fragmentAt + 1) >= 0)
569
+ return false;
570
+ const queryAt = suffix.indexOf('?');
571
+ const pathEnd = Math.min(queryAt < 0 ? suffix.length : queryAt, fragmentAt < 0 ? suffix.length : fragmentAt);
572
+ const path = suffix.slice(0, pathEnd);
573
+ if (path !== '' && !path.startsWith('/'))
574
+ return false;
575
+ const query = queryAt >= 0 && (fragmentAt < 0 || queryAt < fragmentAt)
576
+ ? suffix.slice(queryAt + 1, fragmentAt < 0 ? suffix.length : fragmentAt) : undefined;
577
+ const fragment = fragmentAt >= 0 ? suffix.slice(fragmentAt + 1) : undefined;
578
+ const authority = match[1];
579
+ return validUriPart(authority, 'authority')
580
+ && validUriPart(path, 'path')
581
+ && (query === undefined || validUriPart(query, 'query'))
582
+ && (fragment === undefined || validUriPart(fragment, 'fragment'));
583
+ }
584
+ function validUriPart(value, part) {
585
+ for (let index = 0; index < value.length;) {
586
+ const point = value.codePointAt(index);
587
+ const character = String.fromCodePoint(point);
588
+ if (point <= 0x20 || (point >= 0x7f && point <= 0x9f) || (point >= 0xd800 && point <= 0xdfff))
589
+ return false;
590
+ if (point <= 0x7f) {
591
+ const allowed = part === 'authority'
592
+ ? /^[A-Za-z0-9.:-]$/
593
+ : part === 'path'
594
+ ? /^[A-Za-z0-9\-._~!$&'()*+,;=:@/%]$/
595
+ : /^[A-Za-z0-9\-._~!$&'()*+,;=:@/?%\[\]]$/;
596
+ if (!allowed.test(character))
597
+ return false;
598
+ }
599
+ if (character === '%' && !/^[0-9A-Fa-f]{2}$/.test(value.slice(index + 1, index + 3)))
600
+ return false;
601
+ index += character.length;
602
+ }
603
+ return true;
604
+ }
605
+ function toAsciiUri(value) {
606
+ return [...value].map(character => {
607
+ const point = character.codePointAt(0);
608
+ if (point <= 0x7f)
609
+ return character;
610
+ return [...Buffer.from(character, 'utf8')].map(byte => `%${byte.toString(16).toUpperCase().padStart(2, '0')}`).join('');
611
+ }).join('');
612
+ }
613
+ function lengthPrefixedSha256(fields) {
614
+ const digest = createHash('sha256');
615
+ for (const field of fields) {
616
+ const bytes = Buffer.from(field, 'utf8');
617
+ const length = Buffer.alloc(4);
618
+ length.writeUInt32BE(bytes.length);
619
+ digest.update(length);
620
+ digest.update(bytes);
621
+ }
622
+ return digest.digest('hex');
623
+ }
624
+ function parseOrigin(value) {
625
+ let parsed;
626
+ try {
627
+ parsed = new URL(value);
628
+ }
629
+ catch {
630
+ throw protocolFailure();
631
+ }
632
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname.toLowerCase());
633
+ if (parsed.username || parsed.password || parsed.pathname !== '/' || parsed.search || parsed.hash
634
+ || (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && loopback)))
635
+ throw protocolFailure();
636
+ return parsed.origin;
637
+ }
638
+ function atomicOrEmpty(value) {
639
+ if (value === undefined || value === null)
640
+ return '';
641
+ if (typeof value !== 'string' || !/^[1-9][0-9]{0,64}$/.test(value))
642
+ throw protocolFailure();
643
+ return value;
644
+ }
645
+ function record(value) {
646
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
647
+ throw protocolFailure();
648
+ return value;
649
+ }
650
+ function onlyKeys(value, keys) {
651
+ return Object.keys(value).every(key => keys.includes(key));
652
+ }
653
+ function uuid(value) {
654
+ return typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value) ? value : false;
655
+ }
656
+ function millis(value) {
657
+ const result = Date.parse(value);
658
+ if (!Number.isSafeInteger(result) || result <= 0)
659
+ throw protocolFailure();
660
+ return result;
661
+ }
662
+ function javaTrim(value) { return value.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g, ''); }
663
+ function sha256(value) { return createHash('sha256').update(value, 'utf8').digest('hex'); }
664
+ function protocolFailure() { return new AttoError('MARKETPLACE_APPROVAL_PROTOCOL', 'This typed Marketplace wallet-approval request is invalid. Request a fresh approval file from Marketplace.'); }
665
+ function identityNetwork(address) {
666
+ if (/^atto:\/\/[a-z2-7]{61}$/.test(address))
667
+ return 'atto:live';
668
+ if (/^nano_[13][13456789abcdefghijkmnopqrstuwxyz]{59}$/.test(address))
669
+ return 'nano:mainnet';
670
+ return undefined;
671
+ }