@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.
- package/README.md +157 -5
- package/dist/application/app.d.ts +34 -3
- package/dist/application/app.js +142 -125
- package/dist/application/operations.d.ts +3 -0
- package/dist/application/operations.js +30 -8
- package/dist/cli/cli.d.ts +1 -0
- package/dist/cli/cli.js +101 -13
- package/dist/cli/onboarding.d.ts +13 -0
- package/dist/cli/onboarding.js +99 -2
- package/dist/cli/output.js +18 -2
- package/dist/doctor/profile.js +2 -1
- package/dist/internal-marketplace.d.ts +25 -0
- package/dist/internal-marketplace.js +50 -0
- package/dist/marketplace/approval-files.d.ts +3 -0
- package/dist/marketplace/approval-files.js +97 -0
- package/dist/marketplace/approval-preview.d.ts +2 -0
- package/dist/marketplace/approval-preview.js +86 -0
- package/dist/marketplace/proof-approval.d.ts +82 -0
- package/dist/marketplace/proof-approval.js +671 -0
- package/dist/marketplace/topups.d.ts +82 -0
- package/dist/marketplace/topups.js +485 -0
- package/dist/network/batching.d.ts +2 -0
- package/dist/network/batching.js +23 -0
- package/dist/network/entry.d.ts +2 -0
- package/dist/network/entry.js +35 -0
- package/dist/network/reader.d.ts +2 -0
- package/dist/network/reader.js +125 -37
- package/dist/spending/approval.d.ts +35 -0
- package/dist/spending/approval.js +25 -0
- package/dist/spending/atto-x402.d.ts +31 -0
- package/dist/spending/atto-x402.js +174 -0
- package/dist/spending/ledger.d.ts +74 -2
- package/dist/spending/ledger.js +298 -7
- package/dist/spending/payments.d.ts +105 -5
- package/dist/spending/payments.js +795 -11
- package/dist/storage/recovery-seed.d.ts +13 -0
- package/dist/storage/recovery-seed.js +93 -0
- package/dist/storage/state.d.ts +4 -0
- package/dist/storage/state.js +32 -2
- package/dist/wallet/receive.d.ts +39 -0
- package/dist/wallet/receive.js +264 -0
- package/dist/wallet/signing.d.ts +1 -0
- package/dist/wallet/signing.js +37 -21
- package/dist/wallet/types.d.ts +1 -0
- package/node_modules/@attocash/commons-core/Kotlin-DateTime-library-kotlinx-datetime.mjs +1922 -1918
- package/node_modules/@attocash/commons-core/Kotlin-DateTime-library-kotlinx-datetime.mjs.map +1 -1
- package/node_modules/@attocash/commons-core/README.md +9 -0
- package/node_modules/@attocash/commons-core/commons-commons-core.d.mts +10 -0
- package/node_modules/@attocash/commons-core/commons-commons-core.mjs +2543 -2434
- package/node_modules/@attocash/commons-core/commons-commons-core.mjs.map +1 -1
- package/node_modules/@attocash/commons-core/kotlin-kotlin-stdlib.mjs +4695 -4227
- package/node_modules/@attocash/commons-core/kotlin-kotlin-stdlib.mjs.map +1 -1
- package/node_modules/@attocash/commons-core/kotlin_org_jetbrains_kotlin_kotlin_dom_api_compat.mjs.map +1 -1
- package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-bytestring.mjs +60 -60
- package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-bytestring.mjs.map +1 -1
- package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-core.mjs +651 -631
- package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-core.mjs.map +1 -1
- package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-core.mjs +2294 -2295
- package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-core.mjs.map +1 -1
- package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
- package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
- package/node_modules/@attocash/commons-core/package.json +1 -1
- package/node_modules/@attocash/commons-node/commons-commons-node.d.mts +1 -0
- package/node_modules/@attocash/commons-node/commons-commons-node.mjs +873 -847
- package/node_modules/@attocash/commons-node/commons-commons-node.mjs.map +1 -1
- package/node_modules/@attocash/commons-node/kotlin-logging.mjs +109 -109
- package/node_modules/@attocash/commons-node/kotlin-logging.mjs.map +1 -1
- package/node_modules/@attocash/commons-node/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
- package/node_modules/@attocash/commons-node/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
- package/node_modules/@attocash/commons-node/package.json +3 -3
- package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.d.mts +1 -0
- package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.mjs +674 -640
- package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.mjs.map +1 -1
- package/node_modules/@attocash/commons-node-remote/kotlin-logging.mjs +109 -109
- package/node_modules/@attocash/commons-node-remote/kotlin-logging.mjs.map +1 -1
- package/node_modules/@attocash/commons-node-remote/kotlinx-browser.mjs.map +1 -1
- package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
- package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
- package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
- package/node_modules/@attocash/commons-node-remote/package.json +4 -4
- package/node_modules/@attocash/commons-transport/commons-commons-transport.d.mts +1 -0
- package/node_modules/@attocash/commons-transport/commons-commons-transport.mjs +52 -51
- package/node_modules/@attocash/commons-transport/commons-commons-transport.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/kotlinx-atomicfu.mjs +13 -13
- package/node_modules/@attocash/commons-transport/kotlinx-atomicfu.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/kotlinx-browser.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/kotlinx-coroutines-core.mjs +2639 -2608
- package/node_modules/@attocash/commons-transport/kotlinx-coroutines-core.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
- package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-client-content-negotiation.mjs +411 -196
- package/node_modules/@attocash/commons-transport/ktor-ktor-client-content-negotiation.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-client-core.mjs +2115 -1976
- package/node_modules/@attocash/commons-transport/ktor-ktor-client-core.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-events.mjs +7 -7
- package/node_modules/@attocash/commons-transport/ktor-ktor-events.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-http-cio.mjs +385 -384
- package/node_modules/@attocash/commons-transport/ktor-ktor-http-cio.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-http.mjs +1261 -1185
- package/node_modules/@attocash/commons-transport/ktor-ktor-http.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-io.mjs +668 -656
- package/node_modules/@attocash/commons-transport/ktor-ktor-io.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-openapi-schema.mjs +89 -0
- package/node_modules/@attocash/commons-transport/ktor-ktor-openapi-schema.mjs.map +1 -0
- package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx-json.mjs +9 -9
- package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx-json.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx.mjs +120 -128
- package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-serialization.mjs +46 -49
- package/node_modules/@attocash/commons-transport/ktor-ktor-serialization.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-sse.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-utils.mjs +1041 -985
- package/node_modules/@attocash/commons-transport/ktor-ktor-utils.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-websocket-serialization.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-websockets.mjs +530 -455
- package/node_modules/@attocash/commons-transport/ktor-ktor-websockets.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/package.json +4 -4
- package/node_modules/@attocash/commons-worker/commons-commons-worker.d.mts +1 -0
- package/node_modules/@attocash/commons-worker/commons-commons-worker.mjs +230 -226
- package/node_modules/@attocash/commons-worker/commons-commons-worker.mjs.map +1 -1
- package/node_modules/@attocash/commons-worker/kotlin-logging.mjs +109 -109
- package/node_modules/@attocash/commons-worker/kotlin-logging.mjs.map +1 -1
- package/node_modules/@attocash/commons-worker/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
- package/node_modules/@attocash/commons-worker/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
- package/node_modules/@attocash/commons-worker/package.json +3 -3
- package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.d.mts +1 -0
- package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.mjs +91 -86
- package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.mjs.map +1 -1
- package/node_modules/@attocash/commons-worker-remote/kotlin-logging.mjs +109 -109
- package/node_modules/@attocash/commons-worker-remote/kotlin-logging.mjs.map +1 -1
- package/node_modules/@attocash/commons-worker-remote/kotlinx-browser.mjs.map +1 -1
- package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
- package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
- package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
- package/node_modules/@attocash/commons-worker-remote/package.json +4 -4
- package/package.json +9 -5
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { WalletAddress, WalletSettings } from '../wallet/types.js';
|
|
2
|
+
import type { StateStore } from '../storage/state.js';
|
|
3
|
+
import type { AttoSeed } from '@attocash/commons-core';
|
|
4
|
+
import { type AttoExactRequirement } from '../spending/atto-x402.js';
|
|
5
|
+
import { type MarketplaceProofApprovalResponse } from './proof-approval.js';
|
|
6
|
+
export interface MarketplaceConnection {
|
|
7
|
+
version: 1;
|
|
8
|
+
apiUrl: string;
|
|
9
|
+
audience: string;
|
|
10
|
+
controllerIndex: number;
|
|
11
|
+
controllerAddress: string;
|
|
12
|
+
accountId: string;
|
|
13
|
+
agentId: string;
|
|
14
|
+
identityId: string;
|
|
15
|
+
walletFingerprint: string;
|
|
16
|
+
browserOrigins?: string[];
|
|
17
|
+
}
|
|
18
|
+
export interface MarketplaceTopUpStatus {
|
|
19
|
+
intentId: string;
|
|
20
|
+
asset: string;
|
|
21
|
+
network: string;
|
|
22
|
+
amountAtomic: string;
|
|
23
|
+
state: 'PENDING' | 'ACCEPTED' | 'SETTLED' | 'REJECTED';
|
|
24
|
+
expiresAt: string;
|
|
25
|
+
sendHash: string | null;
|
|
26
|
+
payer: string | null;
|
|
27
|
+
paymentState: 'PENDING' | 'ACCEPTED' | 'SETTLED' | 'REJECTED' | null;
|
|
28
|
+
receivePending: boolean | null;
|
|
29
|
+
discrepancy: string | null;
|
|
30
|
+
receiveStatus: 'PENDING' | 'ACCEPTED' | 'SETTLED' | 'REJECTED' | null;
|
|
31
|
+
}
|
|
32
|
+
export interface TopUpChallenge {
|
|
33
|
+
status: MarketplaceTopUpStatus;
|
|
34
|
+
requirementHeader: string;
|
|
35
|
+
requirement: AttoExactRequirement;
|
|
36
|
+
}
|
|
37
|
+
export interface MarketplaceWalletAccess {
|
|
38
|
+
settings(): WalletSettings;
|
|
39
|
+
addresses(): WalletAddress[];
|
|
40
|
+
seed(): Promise<AttoSeed>;
|
|
41
|
+
mcp: boolean;
|
|
42
|
+
}
|
|
43
|
+
export declare function validateMarketplaceApiUrl(value: string, network: WalletSettings['network']): string;
|
|
44
|
+
export declare class MarketplaceTopUpClient {
|
|
45
|
+
private readonly store;
|
|
46
|
+
private readonly wallet;
|
|
47
|
+
private session?;
|
|
48
|
+
constructor(store: StateStore, wallet: MarketplaceWalletAccess);
|
|
49
|
+
connect(input: {
|
|
50
|
+
apiUrl: string;
|
|
51
|
+
audience: string;
|
|
52
|
+
controllerIndex: number;
|
|
53
|
+
browserOrigins?: string[];
|
|
54
|
+
}): Promise<MarketplaceConnection>;
|
|
55
|
+
connection(): MarketplaceConnection;
|
|
56
|
+
inspectProofApproval(input: unknown): {
|
|
57
|
+
request: import("./proof-approval.js").MarketplaceProofApprovalRequest;
|
|
58
|
+
preview: import("./proof-approval.js").MarketplaceProofApprovalPreview;
|
|
59
|
+
};
|
|
60
|
+
signProofApproval(input: unknown): Promise<MarketplaceProofApprovalResponse>;
|
|
61
|
+
challenge(connection: MarketplaceConnection, paymentIdentifier: string, amountRaw: string): Promise<{
|
|
62
|
+
status: MarketplaceTopUpStatus;
|
|
63
|
+
challenge?: TopUpChallenge;
|
|
64
|
+
}>;
|
|
65
|
+
pay(connection: MarketplaceConnection, status: MarketplaceTopUpStatus, paymentIdentifier: string, paymentHeader: string, expected: {
|
|
66
|
+
hash: string;
|
|
67
|
+
network: string;
|
|
68
|
+
payer: string;
|
|
69
|
+
}, beforeSubmit: () => Promise<void>): Promise<MarketplaceTopUpStatus>;
|
|
70
|
+
status(connection: MarketplaceConnection, intentId: string, paymentIdentifier: string, amountRaw: string, network: string, expected?: {
|
|
71
|
+
hash: string;
|
|
72
|
+
payer: string;
|
|
73
|
+
}): Promise<MarketplaceTopUpStatus>;
|
|
74
|
+
private authorize;
|
|
75
|
+
private login;
|
|
76
|
+
private authUrl;
|
|
77
|
+
private fetchJson;
|
|
78
|
+
private decodeObject;
|
|
79
|
+
private assertStatusBinding;
|
|
80
|
+
private httpFailure;
|
|
81
|
+
private sessionKey;
|
|
82
|
+
}
|
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { derivedSigner } from '../wallet/signing.js';
|
|
3
|
+
import { AttoError } from '../domain/errors.js';
|
|
4
|
+
import { parseAttoExactRequirement } from '../spending/atto-x402.js';
|
|
5
|
+
import { createMarketplaceProofApprovalResponse, inspectMarketplaceProofApproval, } from './proof-approval.js';
|
|
6
|
+
const CONNECTION_KEY = 'marketplace.topups.connection';
|
|
7
|
+
const RESPONSE_BYTES = 65_536;
|
|
8
|
+
const REQUEST_TIMEOUT_MS = 15_000;
|
|
9
|
+
function object(value) {
|
|
10
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
11
|
+
? value : undefined;
|
|
12
|
+
}
|
|
13
|
+
function uuid(value) {
|
|
14
|
+
return typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value);
|
|
15
|
+
}
|
|
16
|
+
function instant(value) {
|
|
17
|
+
if (typeof value !== 'string')
|
|
18
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid session or intent expiry.');
|
|
19
|
+
const parsed = Date.parse(value);
|
|
20
|
+
if (!Number.isSafeInteger(parsed) || parsed < 0)
|
|
21
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid session or intent expiry.');
|
|
22
|
+
return parsed;
|
|
23
|
+
}
|
|
24
|
+
function safeToken(value) {
|
|
25
|
+
return typeof value === 'string' && value.length >= 16 && value.length <= 8192 && !/[\r\n\0]/.test(value);
|
|
26
|
+
}
|
|
27
|
+
function networkFor(settings) {
|
|
28
|
+
if (settings.network === 'LIVE')
|
|
29
|
+
return 'atto:live';
|
|
30
|
+
if (settings.network === 'LOCAL')
|
|
31
|
+
return 'atto:local';
|
|
32
|
+
throw new AttoError('MARKETPLACE_NETWORK', 'Marketplace top-ups support the configured LIVE or isolated LOCAL ATTO network only.');
|
|
33
|
+
}
|
|
34
|
+
export function validateMarketplaceApiUrl(value, network) {
|
|
35
|
+
let url;
|
|
36
|
+
try {
|
|
37
|
+
url = new URL(value);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
throw new AttoError('MARKETPLACE_CONFIGURATION', 'Use the absolute Marketplace /v1/agent/topups URL.');
|
|
41
|
+
}
|
|
42
|
+
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname.toLowerCase());
|
|
43
|
+
if (url.username || url.password || url.search || url.hash || url.pathname.replace(/\/+$/, '') !== '/v1/agent/topups'
|
|
44
|
+
|| (url.protocol !== 'https:' && !(url.protocol === 'http:' && network === 'LOCAL' && loopback))) {
|
|
45
|
+
throw new AttoError('MARKETPLACE_CONFIGURATION', 'Use an HTTPS Marketplace /v1/agent/topups URL; HTTP is allowed only for loopback on an isolated LOCAL wallet.');
|
|
46
|
+
}
|
|
47
|
+
return `${url.origin}/v1/agent/topups`;
|
|
48
|
+
}
|
|
49
|
+
function validateBrowserOrigins(value, network) {
|
|
50
|
+
if (!Array.isArray(value) || value.length < 1 || value.length > 8
|
|
51
|
+
|| value.some(origin => typeof origin !== 'string')) {
|
|
52
|
+
throw new AttoError('MARKETPLACE_CONFIGURATION', 'Configure between 1 and 8 exact browser origins.');
|
|
53
|
+
}
|
|
54
|
+
const origins = value.map(origin => {
|
|
55
|
+
const text = origin;
|
|
56
|
+
let parsed;
|
|
57
|
+
try {
|
|
58
|
+
parsed = new URL(text);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
throw new AttoError('MARKETPLACE_CONFIGURATION', 'Browser origins must be canonical HTTPS origins or loopback HTTP for an isolated LOCAL wallet.');
|
|
62
|
+
}
|
|
63
|
+
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname.toLowerCase());
|
|
64
|
+
if (parsed.origin !== text || parsed.hostname.includes('*') || parsed.username || parsed.password
|
|
65
|
+
|| parsed.pathname !== '/' || parsed.search || parsed.hash
|
|
66
|
+
|| (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && network === 'LOCAL' && loopback))) {
|
|
67
|
+
throw new AttoError('MARKETPLACE_CONFIGURATION', 'Browser origins must be canonical HTTPS origins or loopback HTTP for an isolated LOCAL wallet.');
|
|
68
|
+
}
|
|
69
|
+
return text;
|
|
70
|
+
});
|
|
71
|
+
if (new Set(origins).size !== origins.length) {
|
|
72
|
+
throw new AttoError('MARKETPLACE_CONFIGURATION', 'Browser origins must not contain duplicates.');
|
|
73
|
+
}
|
|
74
|
+
return origins;
|
|
75
|
+
}
|
|
76
|
+
export class MarketplaceTopUpClient {
|
|
77
|
+
store;
|
|
78
|
+
wallet;
|
|
79
|
+
session;
|
|
80
|
+
constructor(store, wallet) {
|
|
81
|
+
this.store = store;
|
|
82
|
+
this.wallet = wallet;
|
|
83
|
+
}
|
|
84
|
+
async connect(input) {
|
|
85
|
+
if (this.wallet.mcp)
|
|
86
|
+
throw new AttoError('LOCAL_APPROVAL_REQUIRED', 'Configure the Marketplace connection from a local terminal.');
|
|
87
|
+
const apiUrl = validateMarketplaceApiUrl(input.apiUrl, this.wallet.settings().network);
|
|
88
|
+
if (!Number.isSafeInteger(input.controllerIndex) || input.controllerIndex < 0 || input.controllerIndex > 0x7fff_ffff
|
|
89
|
+
|| typeof input.audience !== 'string' || input.audience.length < 1 || input.audience.length > 255
|
|
90
|
+
|| input.audience.trim() !== input.audience || /[\r\n\0]/.test(input.audience)) {
|
|
91
|
+
throw new AttoError('MARKETPLACE_CONFIGURATION', 'Choose a saved controller index and a single-line API audience of at most 255 characters.');
|
|
92
|
+
}
|
|
93
|
+
const browserOrigins = input.browserOrigins === undefined
|
|
94
|
+
? undefined : validateBrowserOrigins(input.browserOrigins, this.wallet.settings().network);
|
|
95
|
+
const controller = this.wallet.addresses().find(address => address.index === input.controllerIndex);
|
|
96
|
+
const identity = this.store.get('identity');
|
|
97
|
+
if (!controller || !identity)
|
|
98
|
+
throw new AttoError('ADDRESS_NOT_DERIVED', 'Derive the controller address in this wallet before connecting Marketplace.');
|
|
99
|
+
const candidate = {
|
|
100
|
+
version: 1, apiUrl, audience: input.audience, controllerIndex: controller.index,
|
|
101
|
+
controllerAddress: controller.address, walletFingerprint: identity.fingerprint,
|
|
102
|
+
...(browserOrigins ? { browserOrigins } : {}),
|
|
103
|
+
};
|
|
104
|
+
const session = await this.login(candidate);
|
|
105
|
+
const connection = { ...candidate, accountId: session.accountId, agentId: session.agentId, identityId: session.identityId };
|
|
106
|
+
this.store.set(CONNECTION_KEY, connection);
|
|
107
|
+
this.session = { key: this.sessionKey(connection), value: session };
|
|
108
|
+
return connection;
|
|
109
|
+
}
|
|
110
|
+
connection() {
|
|
111
|
+
const value = this.store.get(CONNECTION_KEY);
|
|
112
|
+
try {
|
|
113
|
+
if (!value || value.version !== 1 || !Number.isSafeInteger(value.controllerIndex) || value.controllerIndex < 0
|
|
114
|
+
|| !uuid(value.accountId) || !uuid(value.agentId) || !uuid(value.identityId) || typeof value.walletFingerprint !== 'string')
|
|
115
|
+
throw new Error();
|
|
116
|
+
const canonicalUrl = validateMarketplaceApiUrl(value.apiUrl, this.wallet.settings().network);
|
|
117
|
+
if (canonicalUrl !== value.apiUrl || typeof value.audience !== 'string' || !value.audience
|
|
118
|
+
|| value.audience.length > 255 || value.audience.trim() !== value.audience || /[\r\n\0]/.test(value.audience))
|
|
119
|
+
throw new Error();
|
|
120
|
+
if (value.browserOrigins !== undefined) {
|
|
121
|
+
const canonicalOrigins = validateBrowserOrigins(value.browserOrigins, this.wallet.settings().network);
|
|
122
|
+
if (JSON.stringify(canonicalOrigins) !== JSON.stringify(value.browserOrigins))
|
|
123
|
+
throw new Error();
|
|
124
|
+
}
|
|
125
|
+
const identity = this.store.get('identity');
|
|
126
|
+
const controller = this.wallet.addresses().find(address => address.index === value.controllerIndex);
|
|
127
|
+
if (!identity || identity.fingerprint !== value.walletFingerprint || !controller
|
|
128
|
+
|| controller.address !== value.controllerAddress) {
|
|
129
|
+
throw new AttoError('MARKETPLACE_RECONNECT_REQUIRED', 'The wallet or configured controller changed. Reconnect Marketplace from a local terminal.');
|
|
130
|
+
}
|
|
131
|
+
return value;
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
if (error instanceof AttoError)
|
|
135
|
+
throw error;
|
|
136
|
+
throw new AttoError('MARKETPLACE_NOT_CONNECTED', 'Connect this wallet to Marketplace from a local terminal before using top-ups.');
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
inspectProofApproval(input) {
|
|
140
|
+
if (this.wallet.mcp)
|
|
141
|
+
throw new AttoError('LOCAL_APPROVAL_REQUIRED', 'Approve Marketplace wallet proofs from the local terminal.');
|
|
142
|
+
const candidate = input !== null && typeof input === 'object' && !Array.isArray(input)
|
|
143
|
+
? input : {};
|
|
144
|
+
let connection;
|
|
145
|
+
try {
|
|
146
|
+
connection = this.connection();
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
if (!(candidate.purpose === 'login' && error instanceof AttoError && error.code === 'MARKETPLACE_NOT_CONNECTED'))
|
|
150
|
+
throw error;
|
|
151
|
+
}
|
|
152
|
+
return inspectMarketplaceProofApproval(input, connection, index => this.wallet.addresses().find(address => address.index === index)?.address);
|
|
153
|
+
}
|
|
154
|
+
async signProofApproval(input) {
|
|
155
|
+
if (this.wallet.mcp)
|
|
156
|
+
throw new AttoError('LOCAL_APPROVAL_REQUIRED', 'Approve Marketplace wallet proofs from the local terminal.');
|
|
157
|
+
const { request } = this.inspectProofApproval(input);
|
|
158
|
+
const seed = await this.wallet.seed();
|
|
159
|
+
try {
|
|
160
|
+
const signer = await derivedSigner(seed, request.controller.index);
|
|
161
|
+
if (signer.address.value !== request.controller.address)
|
|
162
|
+
throw new AttoError('WALLET_MISMATCH', 'The Marketplace approval controller does not match this wallet key.');
|
|
163
|
+
const signature = (await signer.signMessage(new Int8Array(Buffer.from(request.challenge.message, 'utf8')))).toString();
|
|
164
|
+
return createMarketplaceProofApprovalResponse(request, signature);
|
|
165
|
+
}
|
|
166
|
+
finally {
|
|
167
|
+
seed.value.fill(0);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
async challenge(connection, paymentIdentifier, amountRaw) {
|
|
171
|
+
if (!/^[A-Za-z0-9_-]{16,128}$/.test(paymentIdentifier) || !/^[1-9]\d*$/.test(amountRaw)) {
|
|
172
|
+
throw new AttoError('INVALID_INPUT', 'Marketplace top-ups require a positive RAW amount and a 16-128 character payment identifier.');
|
|
173
|
+
}
|
|
174
|
+
const network = networkFor(this.wallet.settings());
|
|
175
|
+
const session = await this.authorize(connection);
|
|
176
|
+
const response = await this.fetchJson(connection.apiUrl, connection.apiUrl, 'POST', session.accessToken, {
|
|
177
|
+
asset: 'ATTO', amountAtomic: amountRaw, paymentIdentifier,
|
|
178
|
+
});
|
|
179
|
+
const status = parseTopUpStatus(response.json);
|
|
180
|
+
this.assertStatusBinding(status, paymentIdentifier, amountRaw, network);
|
|
181
|
+
if (response.status !== 402)
|
|
182
|
+
return { status };
|
|
183
|
+
const requirementHeader = response.headers.get('payment-required');
|
|
184
|
+
if (!requirementHeader)
|
|
185
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace omitted the required ATTO payment challenge.');
|
|
186
|
+
const requirement = parseAttoExactRequirement({ header: requirementHeader, apiUrl: connection.apiUrl,
|
|
187
|
+
intentId: status.intentId, network, amountRaw });
|
|
188
|
+
return { status, challenge: { status, requirementHeader, requirement } };
|
|
189
|
+
}
|
|
190
|
+
async pay(connection, status, paymentIdentifier, paymentHeader, expected, beforeSubmit) {
|
|
191
|
+
const session = await this.authorize(connection);
|
|
192
|
+
const url = `${connection.apiUrl}/${status.intentId}`;
|
|
193
|
+
await beforeSubmit();
|
|
194
|
+
const response = await this.fetchJson(connection.apiUrl, url, 'POST', session.accessToken, undefined, { 'PAYMENT-SIGNATURE': paymentHeader });
|
|
195
|
+
const updated = parseTopUpStatus(response.json);
|
|
196
|
+
this.assertStatusBinding(updated, paymentIdentifier, status.amountAtomic, expected.network, {
|
|
197
|
+
intentId: status.intentId, hash: expected.hash, payer: expected.payer, requirePayment: true,
|
|
198
|
+
});
|
|
199
|
+
if (![200, 202, 409].includes(response.status))
|
|
200
|
+
throw this.httpFailure(response.status);
|
|
201
|
+
const paymentResponse = response.headers.get('payment-response');
|
|
202
|
+
if (paymentResponse === null) {
|
|
203
|
+
if (response.status === 202 && updated.state === 'PENDING' && updated.paymentState === 'PENDING')
|
|
204
|
+
return updated;
|
|
205
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace omitted the payment receipt without an exact pending payment status.');
|
|
206
|
+
}
|
|
207
|
+
const receipt = this.decodeObject(paymentResponse);
|
|
208
|
+
const paymentApplied = updated.state === 'ACCEPTED' || updated.state === 'SETTLED';
|
|
209
|
+
const pending = updated.state === 'PENDING';
|
|
210
|
+
const rejected = updated.state === 'REJECTED';
|
|
211
|
+
const responseMatchesState = (response.status === 200 && paymentApplied)
|
|
212
|
+
|| (response.status === 202 && pending) || (response.status === 409 && rejected);
|
|
213
|
+
if (!responseMatchesState || receipt.success !== paymentApplied || typeof receipt.transaction !== 'string'
|
|
214
|
+
|| receipt.transaction.toUpperCase() !== expected.hash.toUpperCase()
|
|
215
|
+
|| receipt.network !== expected.network || receipt.payer !== expected.payer
|
|
216
|
+
|| updated.sendHash?.toUpperCase() !== receipt.transaction.toUpperCase() || updated.payer !== receipt.payer
|
|
217
|
+
|| (receipt.errorReason !== undefined && typeof receipt.errorReason !== 'string')) {
|
|
218
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned a receipt for a different ATTO payment.');
|
|
219
|
+
}
|
|
220
|
+
return updated;
|
|
221
|
+
}
|
|
222
|
+
async status(connection, intentId, paymentIdentifier, amountRaw, network, expected) {
|
|
223
|
+
const session = await this.authorize(connection);
|
|
224
|
+
if (!uuid(intentId))
|
|
225
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'The saved Marketplace intent ID is invalid.');
|
|
226
|
+
const response = await this.fetchJson(connection.apiUrl, `${connection.apiUrl}/${intentId}`, 'GET', session.accessToken);
|
|
227
|
+
if (response.status !== 200)
|
|
228
|
+
throw this.httpFailure(response.status);
|
|
229
|
+
const status = parseTopUpStatus(response.json);
|
|
230
|
+
this.assertStatusBinding(status, paymentIdentifier, amountRaw, network, {
|
|
231
|
+
intentId, hash: expected?.hash, payer: expected?.payer,
|
|
232
|
+
});
|
|
233
|
+
return status;
|
|
234
|
+
}
|
|
235
|
+
async authorize(connection) {
|
|
236
|
+
const key = this.sessionKey(connection);
|
|
237
|
+
const cached = this.session?.key === key ? this.session.value : undefined;
|
|
238
|
+
if (cached && cached.accessExpiresAt > Date.now() + 30_000)
|
|
239
|
+
return cached;
|
|
240
|
+
if (cached && cached.refreshExpiresAt > Date.now() + 30_000) {
|
|
241
|
+
try {
|
|
242
|
+
const response = await this.fetchJson(connection.apiUrl, this.authUrl(connection.apiUrl, 'sessions/refresh'), 'POST', undefined, { refreshToken: cached.refreshToken });
|
|
243
|
+
if (response.status !== 200)
|
|
244
|
+
throw this.httpFailure(response.status);
|
|
245
|
+
const refresh = object(response.json);
|
|
246
|
+
if (!refresh || !safeToken(refresh.accessToken) || !safeToken(refresh.refreshToken))
|
|
247
|
+
throw new Error();
|
|
248
|
+
const value = { ...cached, accessToken: refresh.accessToken,
|
|
249
|
+
accessExpiresAt: instant(refresh.accessExpiresAt), refreshToken: refresh.refreshToken,
|
|
250
|
+
refreshExpiresAt: instant(refresh.refreshExpiresAt) };
|
|
251
|
+
if (value.accessExpiresAt <= Date.now() || value.refreshExpiresAt < value.accessExpiresAt)
|
|
252
|
+
throw new Error();
|
|
253
|
+
this.session = { key, value };
|
|
254
|
+
return value;
|
|
255
|
+
}
|
|
256
|
+
catch (error) {
|
|
257
|
+
if (!(error instanceof AttoError) || error.code !== 'MARKETPLACE_HTTP'
|
|
258
|
+
|| ![400, 401, 403].includes(error.details?.httpStatus ?? 0))
|
|
259
|
+
throw error;
|
|
260
|
+
// A rejected rotating refresh token falls back to a new wallet proof.
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
const value = await this.login(connection);
|
|
264
|
+
if (value.accountId !== connection.accountId || value.agentId !== connection.agentId || value.identityId !== connection.identityId) {
|
|
265
|
+
throw new AttoError('MARKETPLACE_IDENTITY_CHANGED', 'Marketplace authenticated a different account or controller. Reconnect from a local terminal.');
|
|
266
|
+
}
|
|
267
|
+
this.session = { key, value };
|
|
268
|
+
return value;
|
|
269
|
+
}
|
|
270
|
+
async login(connection) {
|
|
271
|
+
const networkForAddress = 'ATTO';
|
|
272
|
+
const response = await this.fetchJson(connection.apiUrl, this.authUrl(connection.apiUrl, 'challenges'), 'POST', undefined, { network: networkForAddress, address: connection.controllerAddress });
|
|
273
|
+
if (response.status !== 200)
|
|
274
|
+
throw this.httpFailure(response.status);
|
|
275
|
+
const challenge = parseProofChallenge(response.json, connection);
|
|
276
|
+
const seed = await this.wallet.seed();
|
|
277
|
+
let signature;
|
|
278
|
+
try {
|
|
279
|
+
const signer = await derivedSigner(seed, connection.controllerIndex);
|
|
280
|
+
if (signer.address.value !== connection.controllerAddress) {
|
|
281
|
+
throw new AttoError('WALLET_MISMATCH', 'The configured controller does not match its wallet key.');
|
|
282
|
+
}
|
|
283
|
+
signature = (await signer.signMessage(new Int8Array(Buffer.from(challenge.message, 'utf8')))).toString();
|
|
284
|
+
}
|
|
285
|
+
finally {
|
|
286
|
+
seed.value.fill(0);
|
|
287
|
+
}
|
|
288
|
+
const sessionResponse = await this.fetchJson(connection.apiUrl, this.authUrl(connection.apiUrl, 'sessions'), 'POST', undefined, { challengeId: challenge.challengeId, message: challenge.message, signature });
|
|
289
|
+
if (sessionResponse.status !== 200)
|
|
290
|
+
throw this.httpFailure(sessionResponse.status);
|
|
291
|
+
const value = parseSession(sessionResponse.json);
|
|
292
|
+
if (value.accountId !== challenge.accountId || value.identityId !== challenge.controllerId) {
|
|
293
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned a session outside the signed controller enrollment.');
|
|
294
|
+
}
|
|
295
|
+
if (value.accessExpiresAt <= Date.now() || value.refreshExpiresAt < value.accessExpiresAt) {
|
|
296
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an expired controller session.');
|
|
297
|
+
}
|
|
298
|
+
return value;
|
|
299
|
+
}
|
|
300
|
+
authUrl(apiUrl, suffix) {
|
|
301
|
+
const api = new URL(apiUrl);
|
|
302
|
+
return `${api.origin}/v1/agent/auth/${suffix}`;
|
|
303
|
+
}
|
|
304
|
+
async fetchJson(apiUrl, urlValue, method, accessToken, body, extraHeaders = {}) {
|
|
305
|
+
const api = new URL(apiUrl);
|
|
306
|
+
let url;
|
|
307
|
+
try {
|
|
308
|
+
url = new URL(urlValue);
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
throw new AttoError('MARKETPLACE_RESOURCE_MISMATCH', 'Marketplace request URL is invalid.');
|
|
312
|
+
}
|
|
313
|
+
const topupsPath = api.pathname;
|
|
314
|
+
const agentPath = topupsPath.replace(/\/topups$/, '');
|
|
315
|
+
const allowed = new Set([topupsPath, `${agentPath}/auth/challenges`, `${agentPath}/auth/sessions`,
|
|
316
|
+
`${agentPath}/auth/sessions/refresh`]);
|
|
317
|
+
const intentPath = new RegExp(`^${topupsPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`);
|
|
318
|
+
if (url.origin !== api.origin || url.username || url.password || url.search || url.hash
|
|
319
|
+
|| (!allowed.has(url.pathname) && !intentPath.test(url.pathname))) {
|
|
320
|
+
throw new AttoError('MARKETPLACE_RESOURCE_MISMATCH', 'Marketplace request escaped the configured HTTPS origin.');
|
|
321
|
+
}
|
|
322
|
+
const headers = { accept: 'application/json', ...extraHeaders };
|
|
323
|
+
if (accessToken)
|
|
324
|
+
headers.authorization = `Bearer ${accessToken}`;
|
|
325
|
+
if (body)
|
|
326
|
+
headers['content-type'] = 'application/json';
|
|
327
|
+
let response;
|
|
328
|
+
try {
|
|
329
|
+
response = await fetch(url, { method, headers, ...(body ? { body: JSON.stringify(body) } : {}),
|
|
330
|
+
redirect: 'error', signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
|
331
|
+
}
|
|
332
|
+
catch {
|
|
333
|
+
throw new AttoError('MARKETPLACE_UNAVAILABLE', 'The configured Marketplace endpoint could not be reached. Reuse the same request ID to recover an uncertain payment.');
|
|
334
|
+
}
|
|
335
|
+
if (response.url && new URL(response.url).origin !== api.origin) {
|
|
336
|
+
await response.body?.cancel();
|
|
337
|
+
throw new AttoError('MARKETPLACE_RESOURCE_MISMATCH', 'Marketplace redirected away from the configured origin.');
|
|
338
|
+
}
|
|
339
|
+
let raw;
|
|
340
|
+
try {
|
|
341
|
+
raw = await readBounded(response, RESPONSE_BYTES);
|
|
342
|
+
}
|
|
343
|
+
catch {
|
|
344
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid or oversized response.');
|
|
345
|
+
}
|
|
346
|
+
let json;
|
|
347
|
+
try {
|
|
348
|
+
json = raw ? JSON.parse(raw) : null;
|
|
349
|
+
}
|
|
350
|
+
catch {
|
|
351
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid response.');
|
|
352
|
+
}
|
|
353
|
+
const serverCode = object(json)?.error;
|
|
354
|
+
if (response.status === 403 && serverCode === 'signer_request_rejected') {
|
|
355
|
+
throw new AttoError('SIGNER_REQUEST_REJECTED', 'The Marketplace signer rejected this request. Check the exact controller approval and signer configuration before retrying.', { httpStatus: 403, serverCode });
|
|
356
|
+
}
|
|
357
|
+
if (response.status === 503 && serverCode === 'signer_unavailable') {
|
|
358
|
+
throw new AttoError('SIGNER_UNAVAILABLE', 'The Marketplace signer is temporarily unavailable. Retry the original request with its arguments unchanged.', { httpStatus: 503, serverCode });
|
|
359
|
+
}
|
|
360
|
+
return { status: response.status, headers: response.headers, json };
|
|
361
|
+
}
|
|
362
|
+
decodeObject(header) {
|
|
363
|
+
if (header.length < 1 || header.length > 90_000 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(header)) {
|
|
364
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid payment receipt.');
|
|
365
|
+
}
|
|
366
|
+
const bytes = Buffer.from(header, 'base64');
|
|
367
|
+
if (bytes.toString('base64') !== header || bytes.length < 1 || bytes.length > RESPONSE_BYTES) {
|
|
368
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid payment receipt.');
|
|
369
|
+
}
|
|
370
|
+
let value;
|
|
371
|
+
try {
|
|
372
|
+
value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
|
|
373
|
+
}
|
|
374
|
+
catch {
|
|
375
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid payment receipt.');
|
|
376
|
+
}
|
|
377
|
+
const result = object(value);
|
|
378
|
+
if (!result)
|
|
379
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid payment receipt.');
|
|
380
|
+
return result;
|
|
381
|
+
}
|
|
382
|
+
assertStatusBinding(status, paymentIdentifier, amountRaw, network, expected) {
|
|
383
|
+
const terminal = status.state === 'ACCEPTED' || status.state === 'SETTLED';
|
|
384
|
+
if (status.asset !== 'ATTO' || status.network !== network || status.amountAtomic !== amountRaw
|
|
385
|
+
|| !uuid(status.intentId) || !/^[1-9]\d*$/.test(status.amountAtomic)
|
|
386
|
+
|| !paymentIdentifier || instant(status.expiresAt) < 0
|
|
387
|
+
|| (expected?.intentId !== undefined && status.intentId !== expected.intentId)
|
|
388
|
+
|| (expected?.hash !== undefined && status.sendHash !== null
|
|
389
|
+
&& status.sendHash.toUpperCase() !== expected.hash.toUpperCase())
|
|
390
|
+
|| (expected?.payer !== undefined && status.payer !== null && status.payer !== expected.payer)
|
|
391
|
+
|| (expected && !expected.hash && (status.sendHash !== null || status.payer !== null))
|
|
392
|
+
|| (expected && terminal && (!expected.hash || !expected.payer
|
|
393
|
+
|| status.sendHash?.toUpperCase() !== expected.hash.toUpperCase() || status.payer !== expected.payer))
|
|
394
|
+
|| (expected && status.paymentState !== null && (!expected.hash || !expected.payer
|
|
395
|
+
|| status.sendHash?.toUpperCase() !== expected.hash.toUpperCase() || status.payer !== expected.payer))
|
|
396
|
+
|| (expected?.requirePayment && (!expected.hash || !expected.payer
|
|
397
|
+
|| status.paymentState === null
|
|
398
|
+
|| status.sendHash?.toUpperCase() !== expected.hash.toUpperCase() || status.payer !== expected.payer))) {
|
|
399
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned a top-up status for a different payment.');
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
httpFailure(status) {
|
|
403
|
+
return new AttoError('MARKETPLACE_HTTP', `Marketplace returned HTTP ${status}. Reuse the same request ID to inspect or recover the payment.`, { httpStatus: status });
|
|
404
|
+
}
|
|
405
|
+
sessionKey(connection) {
|
|
406
|
+
return JSON.stringify([connection.apiUrl, connection.audience, connection.controllerAddress,
|
|
407
|
+
connection.accountId ?? null, connection.agentId ?? null, connection.identityId ?? null]);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
async function readBounded(response, maxBytes) {
|
|
411
|
+
if (!response.body)
|
|
412
|
+
return '';
|
|
413
|
+
const reader = response.body.getReader();
|
|
414
|
+
const chunks = [];
|
|
415
|
+
let size = 0;
|
|
416
|
+
try {
|
|
417
|
+
for (;;) {
|
|
418
|
+
const { done, value } = await reader.read();
|
|
419
|
+
if (done)
|
|
420
|
+
break;
|
|
421
|
+
size += value.byteLength;
|
|
422
|
+
if (size > maxBytes)
|
|
423
|
+
throw new Error('response too large');
|
|
424
|
+
chunks.push(value);
|
|
425
|
+
}
|
|
426
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks));
|
|
427
|
+
}
|
|
428
|
+
finally {
|
|
429
|
+
await reader.cancel().catch(() => undefined);
|
|
430
|
+
reader.releaseLock();
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
function parseTopUpStatus(input) {
|
|
434
|
+
const value = object(input);
|
|
435
|
+
const states = ['PENDING', 'ACCEPTED', 'SETTLED', 'REJECTED'];
|
|
436
|
+
const paymentStates = ['PENDING', 'ACCEPTED', 'SETTLED', 'REJECTED'];
|
|
437
|
+
if (!value || !uuid(value.intentId) || typeof value.asset !== 'string' || typeof value.network !== 'string'
|
|
438
|
+
|| typeof value.amountAtomic !== 'string' || !states.includes(String(value.state))
|
|
439
|
+
|| typeof value.expiresAt !== 'string'
|
|
440
|
+
|| (value.sendHash !== null && typeof value.sendHash !== 'string')
|
|
441
|
+
|| (value.payer !== null && typeof value.payer !== 'string')
|
|
442
|
+
|| (value.paymentState !== null && !paymentStates.includes(String(value.paymentState)))
|
|
443
|
+
|| (value.receivePending !== null && typeof value.receivePending !== 'boolean')
|
|
444
|
+
|| (value.discrepancy !== null && typeof value.discrepancy !== 'string')
|
|
445
|
+
|| !(value.receiveStatus === null || ['PENDING', 'ACCEPTED', 'SETTLED', 'REJECTED'].includes(String(value.receiveStatus)))) {
|
|
446
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid top-up status.');
|
|
447
|
+
}
|
|
448
|
+
instant(value.expiresAt);
|
|
449
|
+
return value;
|
|
450
|
+
}
|
|
451
|
+
function parseProofChallenge(input, connection) {
|
|
452
|
+
const value = object(input);
|
|
453
|
+
if (!value || !uuid(value.challengeId) || !uuid(value.accountId) || !uuid(value.controllerId) || typeof value.message !== 'string'
|
|
454
|
+
|| typeof value.issuedAt !== 'string' || typeof value.expiresAt !== 'string') {
|
|
455
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid controller proof challenge.');
|
|
456
|
+
}
|
|
457
|
+
const match = /^Marketplace Agent Controller Proof v1\nAudience: ([^\n]+)\nNetwork: live\nAddress: (atto:\/\/[a-z2-7]{61})\nPurpose: login\nRequest ID: ([0-9a-f-]{36})\nBinding Hash: ([0-9a-f]{64})\nNonce: ([0-9a-f]{64})\nIssued At: ([^\n]+)\nExpiration Time: ([^\n]+)$/.exec(value.message);
|
|
458
|
+
if (!match || match[1] !== connection.audience || match[2] !== connection.controllerAddress
|
|
459
|
+
|| match[3] !== value.challengeId || match[4] !== createHash('sha256').update(['signer-controller-enrollment-v1', value.accountId, value.controllerId].join('\n'), 'utf8').digest('hex')
|
|
460
|
+
|| match[6] !== value.issuedAt || match[7] !== value.expiresAt
|
|
461
|
+
|| (connection.accountId !== undefined && value.accountId !== connection.accountId)
|
|
462
|
+
|| (connection.identityId !== undefined && value.controllerId !== connection.identityId)) {
|
|
463
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned a controller proof outside the configured audience or identity.');
|
|
464
|
+
}
|
|
465
|
+
const issuedAt = instant(value.issuedAt);
|
|
466
|
+
const expiresAt = instant(value.expiresAt);
|
|
467
|
+
const now = Date.now();
|
|
468
|
+
if (issuedAt > now + 30_000 || expiresAt <= now || expiresAt <= issuedAt || expiresAt - issuedAt > 300_000) {
|
|
469
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an expired or out-of-window controller proof.');
|
|
470
|
+
}
|
|
471
|
+
return value;
|
|
472
|
+
}
|
|
473
|
+
function parseSession(input) {
|
|
474
|
+
const value = object(input);
|
|
475
|
+
if (!value || !uuid(value.accountId) || !uuid(value.agentId) || !uuid(value.identityId)
|
|
476
|
+
|| typeof value.accountState !== 'string' || value.accountState === 'CLOSED'
|
|
477
|
+
|| !safeToken(value.accessToken) || !safeToken(value.refreshToken)) {
|
|
478
|
+
throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid controller session.');
|
|
479
|
+
}
|
|
480
|
+
return {
|
|
481
|
+
accountId: value.accountId, agentId: value.agentId, identityId: value.identityId,
|
|
482
|
+
accessToken: value.accessToken, accessExpiresAt: instant(value.accessExpiresAt),
|
|
483
|
+
refreshToken: value.refreshToken, refreshExpiresAt: instant(value.refreshExpiresAt),
|
|
484
|
+
};
|
|
485
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { AttoError } from '../domain/errors.js';
|
|
2
|
+
const officialGatekeepers = new Set([
|
|
3
|
+
'gatekeeper.live.application.atto.cash',
|
|
4
|
+
'gatekeeper.beta.application.atto.cash',
|
|
5
|
+
'gatekeeper.dev.application.atto.cash',
|
|
6
|
+
]);
|
|
7
|
+
export function resolveNodeBatchSize(settings) {
|
|
8
|
+
if (settings.nodeBatchSize !== undefined && settings.nodeBatchSize !== null) {
|
|
9
|
+
if (!Number.isInteger(settings.nodeBatchSize) || settings.nodeBatchSize < 1 || settings.nodeBatchSize > 1000) {
|
|
10
|
+
throw new AttoError('INVALID_BATCH_SIZE', 'Node batch size must be an integer from 1 to 1000, or auto.');
|
|
11
|
+
}
|
|
12
|
+
return settings.nodeBatchSize;
|
|
13
|
+
}
|
|
14
|
+
let hostname;
|
|
15
|
+
try {
|
|
16
|
+
hostname = new URL(settings.nodeUrl).hostname.replace(/\.$/, '');
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
throw new AttoError('INVALID_NODE_URL', 'Configure a valid node URL.');
|
|
20
|
+
}
|
|
21
|
+
// Private gateways cannot be identified by hostname; configure their limit explicitly.
|
|
22
|
+
return officialGatekeepers.has(hostname) ? 5 : 1000;
|
|
23
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { AttoAlgorithm, AttoPublicKey } from '@attocash/commons-core';
|
|
2
|
+
import { amountOutput } from '../domain/amount.js';
|
|
3
|
+
const subjectRoles = { SEND: 'receiver', OPEN: 'sender', RECEIVE: 'sender', CHANGE: 'representative' };
|
|
4
|
+
/** Add action details to an exact, serialized account entry without changing protocol fields. */
|
|
5
|
+
export function publicEntry(value) {
|
|
6
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
7
|
+
return value;
|
|
8
|
+
const entry = value;
|
|
9
|
+
if (typeof entry.blockType !== 'string' || !Object.hasOwn(subjectRoles, entry.blockType)
|
|
10
|
+
|| typeof entry.hash !== 'string' || typeof entry.height !== 'string'
|
|
11
|
+
|| !/^\d+$/.test(entry.height) || !['number', 'string'].includes(typeof entry.timestamp)
|
|
12
|
+
|| typeof entry.algorithm !== 'string' || typeof entry.publicKey !== 'string'
|
|
13
|
+
|| typeof entry.subjectAlgorithm !== 'string' || typeof entry.subjectPublicKey !== 'string'
|
|
14
|
+
|| typeof entry.previousBalance !== 'string' || !/^\d+$/.test(entry.previousBalance)
|
|
15
|
+
|| typeof entry.balance !== 'string' || !/^\d+$/.test(entry.balance))
|
|
16
|
+
return value;
|
|
17
|
+
let address;
|
|
18
|
+
let subjectAddress;
|
|
19
|
+
try {
|
|
20
|
+
address = AttoPublicKey.Companion.parse(entry.publicKey).toAddress(AttoAlgorithm.valueOf(entry.algorithm)).value;
|
|
21
|
+
subjectAddress = AttoPublicKey.Companion.parse(entry.subjectPublicKey).toAddress(AttoAlgorithm.valueOf(entry.subjectAlgorithm)).value;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
const action = entry.blockType;
|
|
27
|
+
const previous = BigInt(entry.previousBalance);
|
|
28
|
+
const balance = BigInt(entry.balance);
|
|
29
|
+
const raw = action === 'SEND' ? previous - balance : balance - previous;
|
|
30
|
+
return {
|
|
31
|
+
address, subjectAddress, subjectRole: subjectRoles[action],
|
|
32
|
+
...(action !== 'CHANGE' ? { amount: amountOutput(raw.toString()) } : {}),
|
|
33
|
+
...entry,
|
|
34
|
+
};
|
|
35
|
+
}
|
package/dist/network/reader.d.ts
CHANGED
|
@@ -16,11 +16,13 @@ export declare class NodeReader {
|
|
|
16
16
|
private request;
|
|
17
17
|
private get;
|
|
18
18
|
account(address: string, signal?: AbortSignal): Promise<AttoAccount | null>;
|
|
19
|
+
accounts(addresses: string[], signal?: AbortSignal): Promise<(AttoAccount | null)[]>;
|
|
19
20
|
now(signal?: AbortSignal): Promise<AttoInstant>;
|
|
20
21
|
transaction(hash: string, signal?: AbortSignal): Promise<AttoTransaction | null>;
|
|
21
22
|
entry(hash: string, signal?: AbortSignal): Promise<AttoAccountEntry | null>;
|
|
22
23
|
voterWeight(address: string): Promise<unknown>;
|
|
23
24
|
stream(filter: StreamFilter, onEvent: (model: Model) => void, signal: AbortSignal): Promise<void>;
|
|
25
|
+
private subscription;
|
|
24
26
|
list(request: ListRequest, signal?: AbortSignal): Promise<{
|
|
25
27
|
items: unknown[];
|
|
26
28
|
nextCursor?: string;
|