@atxp/common 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ import type { Account, PaymentMaker } from './types.js';
2
+ import type { FetchLike, AccountId, Source } from './types.js';
3
+ export declare class ATXPAccount implements Account {
4
+ accountId: AccountId;
5
+ paymentMakers: PaymentMaker[];
6
+ origin: string;
7
+ token: string;
8
+ fetchFn: FetchLike;
9
+ private unqualifiedAccountId;
10
+ constructor(connectionString: string, opts?: {
11
+ fetchFn?: FetchLike;
12
+ });
13
+ /**
14
+ * Get sources for this account by calling the accounts service
15
+ */
16
+ getSources(): Promise<Source[]>;
17
+ }
18
+ //# sourceMappingURL=atxpAccount.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"atxpAccount.d.ts","sourceRoot":"","sources":["../src/atxpAccount.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AACxD,OAAO,KAAK,EAAE,SAAS,EAAY,SAAS,EAAyC,MAAM,EAAE,MAAM,YAAY,CAAC;AA2IhH,qBAAa,WAAY,YAAW,OAAO;IACzC,SAAS,EAAE,SAAS,CAAC;IACrB,aAAa,EAAE,YAAY,EAAE,CAAC;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,SAAS,CAAC;IACnB,OAAO,CAAC,oBAAoB,CAAS;gBAEzB,gBAAgB,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,SAAS,CAAC;KAAE;IAkBrE;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;CAuBtC"}
@@ -0,0 +1,156 @@
1
+ function toBasicAuth(token) {
2
+ // Basic auth is base64("username:password"), password is blank
3
+ const b64 = Buffer.from(`${token}:`).toString('base64');
4
+ return `Basic ${b64}`;
5
+ }
6
+ function parseConnectionString(connectionString) {
7
+ const url = new URL(connectionString);
8
+ const origin = url.origin;
9
+ const token = url.searchParams.get('connection_token') || '';
10
+ const accountId = url.searchParams.get('account_id');
11
+ if (!token) {
12
+ throw new Error('ATXPAccount: connection string missing connection token');
13
+ }
14
+ if (!accountId) {
15
+ throw new Error('ATXPAccount: connection string missing account id');
16
+ }
17
+ return { origin, token, accountId };
18
+ }
19
+ class ATXPHttpPaymentMaker {
20
+ constructor(origin, token, fetchFn = fetch) {
21
+ this.origin = origin;
22
+ this.token = token;
23
+ this.fetchFn = fetchFn;
24
+ }
25
+ async getSourceAddress(params) {
26
+ // Call the /address_for_payment endpoint to get the source address for this account
27
+ const response = await this.fetchFn(`${this.origin}/address_for_payment`, {
28
+ method: 'POST',
29
+ headers: {
30
+ 'Authorization': toBasicAuth(this.token),
31
+ 'Content-Type': 'application/json',
32
+ },
33
+ body: JSON.stringify({
34
+ amount: params.amount.toString(),
35
+ currency: params.currency,
36
+ receiver: params.receiver,
37
+ memo: params.memo,
38
+ }),
39
+ });
40
+ if (!response.ok) {
41
+ const text = await response.text();
42
+ throw new Error(`ATXPAccount: /address_for_payment failed: ${response.status} ${response.statusText} ${text}`);
43
+ }
44
+ const json = await response.json();
45
+ if (!json?.sourceAddress) {
46
+ throw new Error('ATXPAccount: /address_for_payment did not return sourceAddress');
47
+ }
48
+ return json.sourceAddress;
49
+ }
50
+ async makePayment(destinations, memo, paymentRequestId) {
51
+ // Make a payment via the /pay endpoint with multiple destinations
52
+ const response = await this.fetchFn(`${this.origin}/pay`, {
53
+ method: 'POST',
54
+ headers: {
55
+ 'Authorization': toBasicAuth(this.token),
56
+ 'Content-Type': 'application/json',
57
+ },
58
+ body: JSON.stringify({
59
+ destinations: destinations.map(d => ({
60
+ chain: d.chain,
61
+ address: d.address,
62
+ amount: d.amount.toString(),
63
+ currency: d.currency
64
+ })),
65
+ memo,
66
+ ...(paymentRequestId && { paymentRequestId })
67
+ }),
68
+ });
69
+ if (!response.ok) {
70
+ const text = await response.text();
71
+ throw new Error(`ATXPAccount: /pay failed: ${response.status} ${response.statusText} ${text}`);
72
+ }
73
+ const json = await response.json();
74
+ const transactionId = json.transactionId;
75
+ if (!transactionId) {
76
+ throw new Error('ATXPAccount: /pay did not return transactionId or txHash');
77
+ }
78
+ if (!json?.chain) {
79
+ throw new Error('ATXPAccount: /pay did not return chain');
80
+ }
81
+ if (!json?.currency) {
82
+ throw new Error('ATXPAccount: /pay did not return currency');
83
+ }
84
+ return {
85
+ transactionId,
86
+ ...(json.transactionSubId ? { transactionSubId: json.transactionSubId } : {}),
87
+ chain: json.chain,
88
+ currency: json.currency
89
+ };
90
+ }
91
+ async generateJWT(params) {
92
+ const response = await this.fetchFn(`${this.origin}/sign`, {
93
+ method: 'POST',
94
+ headers: {
95
+ 'Authorization': toBasicAuth(this.token),
96
+ 'Content-Type': 'application/json',
97
+ },
98
+ body: JSON.stringify({
99
+ paymentRequestId: params.paymentRequestId,
100
+ codeChallenge: params.codeChallenge,
101
+ ...(params.accountId ? { accountId: params.accountId } : {}),
102
+ }),
103
+ });
104
+ if (!response.ok) {
105
+ const text = await response.text();
106
+ throw new Error(`ATXPAccount: /sign failed: ${response.status} ${response.statusText} ${text}`);
107
+ }
108
+ const json = await response.json();
109
+ if (!json?.jwt) {
110
+ throw new Error('ATXPAccount: /sign did not return jwt');
111
+ }
112
+ return json.jwt;
113
+ }
114
+ }
115
+ class ATXPAccount {
116
+ constructor(connectionString, opts) {
117
+ const { origin, token, accountId } = parseConnectionString(connectionString);
118
+ const fetchFn = opts?.fetchFn ?? fetch;
119
+ // Store for use in X402 payment creation
120
+ this.origin = origin;
121
+ this.token = token;
122
+ this.fetchFn = fetchFn;
123
+ // Format accountId as network:address
124
+ // Connection string provides just the atxp_acct_xxx part (no prefix for UI)
125
+ this.unqualifiedAccountId = accountId;
126
+ this.accountId = `atxp:${accountId}`;
127
+ this.paymentMakers = [
128
+ new ATXPHttpPaymentMaker(origin, token, fetchFn)
129
+ ];
130
+ }
131
+ /**
132
+ * Get sources for this account by calling the accounts service
133
+ */
134
+ async getSources() {
135
+ // Use the unqualified account ID (without atxp: prefix) for the API call
136
+ const response = await this.fetchFn(`${this.origin}/account/${this.unqualifiedAccountId}/sources`, {
137
+ method: 'GET',
138
+ headers: {
139
+ 'Accept': 'application/json',
140
+ }
141
+ });
142
+ if (!response.ok) {
143
+ const text = await response.text();
144
+ throw new Error(`ATXPAccount: /account/${this.unqualifiedAccountId}/sources failed: ${response.status} ${response.statusText} ${text}`);
145
+ }
146
+ const json = await response.json();
147
+ // The accounts service returns the sources array directly, not wrapped in an object
148
+ if (!Array.isArray(json)) {
149
+ throw new Error(`ATXPAccount: /account/${this.unqualifiedAccountId}/sources did not return sources array`);
150
+ }
151
+ return json;
152
+ }
153
+ }
154
+
155
+ export { ATXPAccount };
156
+ //# sourceMappingURL=atxpAccount.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"atxpAccount.js","sources":["../src/atxpAccount.ts"],"sourcesContent":[null],"names":[],"mappings":"AAIA,SAAS,WAAW,CAAC,KAAa,EAAA;;AAEhC,IAAA,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,CAAA,EAAG,KAAK,CAAA,CAAA,CAAG,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC;IACvD,OAAO,CAAA,MAAA,EAAS,GAAG,CAAA,CAAE;AACvB;AAEA,SAAS,qBAAqB,CAAC,gBAAwB,EAAA;AACrD,IAAA,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,gBAAgB,CAAC;AACrC,IAAA,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM;AACzB,IAAA,MAAM,KAAK,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,kBAAkB,CAAC,IAAI,EAAE;IAC5D,MAAM,SAAS,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,YAAY,CAAC;IACpD,IAAI,CAAC,KAAK,EAAE;AACV,QA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E,KAAK;AACb,YAAA,OAAO,EAAE;AACP,gBAAA,QAAQ,EAAE,kBAAkB;AAC7B;AACF,SAAA,CAAC;AAEF,QAAA,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;AAChB,YAAA,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE;AAClC,YAAA,MAAM,IAAI,KAAK,CAAC,yBAAyB,IAAI,CAAC,oBAAoB,CAAA,iBAAA,EAAoB,QAAQ,CAAC,MAAM,CAAA,CAAA,EAAI,QAAQ,CAAC,UAAU,IAAI,IAAI,CAAA,CAAE,CAAC;QACzI;AAEA,QAAA,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAc;;QAG9C,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;YACxB,MAAM,IAAI,KAAK,CAAC,CAAA,sBAAA,EAAyB,IAAI,CAAC,oBAAoB,CAAA,qCAAA,CAAuC,CAAC;QAC5G;AAEA,QAAA,OAAO,IAAI;IACb;AACD;;;;"}
@@ -0,0 +1,41 @@
1
+ import type { AccountId } from './types.js';
2
+ export interface ES256KJWTPayload {
3
+ sub: string;
4
+ iss: string;
5
+ aud: string;
6
+ iat: number;
7
+ exp: number;
8
+ code_challenge?: string;
9
+ payment_request_id?: string;
10
+ account_id?: AccountId;
11
+ source_address?: string;
12
+ }
13
+ /**
14
+ * Build the unsigned JWT message that needs to be signed
15
+ *
16
+ * @param params Parameters for building the JWT message
17
+ * @returns Object containing the message to sign and the encoded header/payload
18
+ */
19
+ export declare function buildES256KJWTMessage(params: {
20
+ walletAddress: string;
21
+ codeChallenge: string;
22
+ paymentRequestId: string;
23
+ accountId?: AccountId | null;
24
+ }): {
25
+ message: string;
26
+ headerB64: string;
27
+ payloadB64: string;
28
+ };
29
+ /**
30
+ * Complete an ES256K JWT with a signature
31
+ *
32
+ * @param params Parameters for completing the JWT
33
+ * @param params.message The message that was signed (header.payload)
34
+ * @param params.signature The ECDSA signature from personal_sign (0x... 130 hex chars / 65 bytes)
35
+ * @returns Complete ES256K JWT string
36
+ */
37
+ export declare function completeES256KJWT(params: {
38
+ message: string;
39
+ signature: string;
40
+ }): string;
41
+ //# sourceMappingURL=es256kJwtHelper.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"es256kJwtHelper.d.ts","sourceRoot":"","sources":["../src/es256kJwtHelper.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAkB5C,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,UAAU,CAAC,EAAE,SAAS,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE;IAC5C,aAAa,EAAE,MAAM,CAAC;IACtB,aAAa,EAAE,MAAM,CAAC;IACtB,gBAAgB,EAAE,MAAM,CAAC;IACzB,SAAS,CAAC,EAAE,SAAS,GAAG,IAAI,CAAC;CAC9B,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAsC7D;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE;IACxC,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CACnB,GAAG,MAAM,CAsCT"}
@@ -0,0 +1,135 @@
1
+ /**
2
+ * ES256K JWT Helper for Browser Wallets
3
+ *
4
+ * This module provides functions to create ES256K JWTs for Ethereum EOA (Externally Owned Account)
5
+ * wallets in browser environments. Unlike EIP-1271 which is designed for smart contract wallets,
6
+ * ES256K works with standard ECDSA signatures from wallets like MetaMask.
7
+ *
8
+ * The auth server verifies these JWTs using cryptographic signature recovery, which:
9
+ * - Works with standard 65-byte ECDSA signatures (r, s, v)
10
+ * - Doesn't require smart contract calls
11
+ * - Is faster and more efficient for EOA wallets
12
+ */
13
+ const ISSUER = 'atxp.ai';
14
+ const AUDIENCE = 'https://auth.atxp.ai';
15
+ /**
16
+ * Build the unsigned JWT message that needs to be signed
17
+ *
18
+ * @param params Parameters for building the JWT message
19
+ * @returns Object containing the message to sign and the encoded header/payload
20
+ */
21
+ function buildES256KJWTMessage(params) {
22
+ const now = Math.floor(Date.now() / 1000);
23
+ // Build the payload
24
+ const payload = {
25
+ sub: params.accountId || params.walletAddress,
26
+ iss: ISSUER,
27
+ aud: AUDIENCE,
28
+ iat: now,
29
+ exp: now + 120, // 2 minutes expiration
30
+ };
31
+ // Add optional fields only if they have values
32
+ if (params.codeChallenge) {
33
+ payload.code_challenge = params.codeChallenge;
34
+ }
35
+ if (params.paymentRequestId) {
36
+ payload.payment_request_id = params.paymentRequestId;
37
+ }
38
+ if (params.accountId) {
39
+ payload.account_id = params.accountId;
40
+ payload.source_address = params.walletAddress;
41
+ }
42
+ // Create JWT header
43
+ const header = {
44
+ alg: 'ES256K',
45
+ typ: 'JWT'
46
+ };
47
+ // Encode header and payload as base64url
48
+ const headerB64 = base64urlEncode(JSON.stringify(header));
49
+ const payloadB64 = base64urlEncode(JSON.stringify(payload));
50
+ // The message to sign is header.payload
51
+ const message = `${headerB64}.${payloadB64}`;
52
+ return { message, headerB64, payloadB64 };
53
+ }
54
+ /**
55
+ * Complete an ES256K JWT with a signature
56
+ *
57
+ * @param params Parameters for completing the JWT
58
+ * @param params.message The message that was signed (header.payload)
59
+ * @param params.signature The ECDSA signature from personal_sign (0x... 130 hex chars / 65 bytes)
60
+ * @returns Complete ES256K JWT string
61
+ */
62
+ function completeES256KJWT(params) {
63
+ // Convert the signature from hex to base64url
64
+ // The signature from personal_sign is in format: 0x + r (32 bytes) + s (32 bytes) + v (1 byte)
65
+ // For JWT ES256K, we need just r + s in base64url format (v is implicit)
66
+ let signature = params.signature;
67
+ if (signature.startsWith('0x')) {
68
+ signature = signature.slice(2);
69
+ }
70
+ // Validate signature length (should be 130 hex chars = 65 bytes)
71
+ if (signature.length !== 130) {
72
+ throw new Error(`Invalid signature length: expected 130 hex chars, got ${signature.length}`);
73
+ }
74
+ // Extract r and s (first 64 bytes, ignore v which is the last byte)
75
+ const rHex = signature.slice(0, 64);
76
+ const sHex = signature.slice(64, 128);
77
+ const vHex = signature.slice(128, 130);
78
+ // Convert r and s to bytes
79
+ const rBytes = hexToBytes(rHex);
80
+ const sBytes = hexToBytes(sHex);
81
+ const vByte = parseInt(vHex, 16);
82
+ // Normalize v to 0 or 1 (MetaMask returns 27/28, but we need 0/1)
83
+ const vNormalized = vByte >= 27 ? vByte - 27 : vByte;
84
+ // Combine r + s + v as a single byte array
85
+ const signatureBytes = new Uint8Array(65);
86
+ signatureBytes.set(rBytes, 0);
87
+ signatureBytes.set(sBytes, 32);
88
+ signatureBytes[64] = vNormalized;
89
+ // Encode as base64url
90
+ const signatureB64 = base64urlEncodeBytes(signatureBytes);
91
+ // Construct the JWT
92
+ return `${params.message}.${signatureB64}`;
93
+ }
94
+ /**
95
+ * Base64URL encode a string
96
+ */
97
+ function base64urlEncode(str) {
98
+ // Convert string to bytes
99
+ const bytes = new TextEncoder().encode(str);
100
+ return base64urlEncodeBytes(bytes);
101
+ }
102
+ /**
103
+ * Base64URL encode a byte array
104
+ */
105
+ function base64urlEncodeBytes(bytes) {
106
+ // Convert to base64
107
+ let base64 = '';
108
+ if (typeof Buffer !== 'undefined') {
109
+ // Node.js environment
110
+ base64 = Buffer.from(bytes).toString('base64');
111
+ }
112
+ else {
113
+ // Browser environment
114
+ const binary = Array.from(bytes).map(b => String.fromCharCode(b)).join('');
115
+ base64 = btoa(binary);
116
+ }
117
+ // Convert base64 to base64url (replace +/= with -_)
118
+ return base64
119
+ .replace(/\+/g, '-')
120
+ .replace(/\//g, '_')
121
+ .replace(/=/g, '');
122
+ }
123
+ /**
124
+ * Convert hex string to bytes
125
+ */
126
+ function hexToBytes(hex) {
127
+ const bytes = new Uint8Array(hex.length / 2);
128
+ for (let i = 0; i < hex.length; i += 2) {
129
+ bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
130
+ }
131
+ return bytes;
132
+ }
133
+
134
+ export { buildES256KJWTMessage, completeES256KJWT };
135
+ //# sourceMappingURL=es256kJwtHelper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"es256kJwtHelper.js","sources":["../src/es256kJwtHelper.ts"],"sourcesContent":[null],"names":[],"mappings":"AAEA;;;;;;;;;;;AAWG;AAEH,MAAM,MAAM,GAAG,SAAS;AACxB,MAAM,QAAQ,GAAG,sBAAsB;AAcvC;;;;;AAKG;AACG,SAAU,qBAAqB,CAAC,MAKrC,EAAA;AACC,IAAA,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;;AAGzC,IAAA,MAAM,OAAO,GAAqB;AAChC,QAAA,GAAG,EAAE,MAAM,CAAC,SAAS,IAAI,MAAM,CAAC,aAAa;AAC7C,QAAA,GAAG,EAAE,MAAM;AACX,QAAA,GAAG,EAAE,QAAQ;AACb,QAAA,GAAG,EAAE,GAAG;AACR,QAAA,GAAG,EAAE,GAAG,GAAG,GAAG;KACf;;AAGD,IAAA,IAAI,MAAM,CAAC,aAAa,EAAE;AACxB,QAAA,OAAO,CAAC,cAAc,GAAG,MAAM,CAAC,aAAa;IAC/C;AACA,IAAA,IAAI,MAAM,CAAC,gBAAgB,EAAE;AAC3B,QAAA,OAAO,CAAC,kBAAkB,GAAG,MAAM,CAAC,gBAAgB;IACtD;AACA,IAAA,IAAI,MAAM,CAAC,SAAS,EAAE;AACpB,QAAA,OAAO,CAAC,UAAU,GAAG,MAAM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