@redditech/x402-solana 0.0.0-stage → 0.1.1

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 (46) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/LICENSE +21 -0
  3. package/README.md +301 -2
  4. package/dist/budget-policy.d.ts +68 -0
  5. package/dist/budget-policy.js +234 -0
  6. package/dist/buyer.d.ts +54 -0
  7. package/dist/buyer.js +147 -0
  8. package/dist/client.d.ts +80 -0
  9. package/dist/client.js +225 -0
  10. package/dist/direct-auth.d.ts +94 -0
  11. package/dist/direct-auth.js +120 -0
  12. package/dist/direct-payment.d.ts +33 -0
  13. package/dist/direct-payment.js +65 -0
  14. package/dist/ed25519.d.ts +6 -0
  15. package/dist/ed25519.js +42 -0
  16. package/dist/escrow-http.d.ts +125 -0
  17. package/dist/escrow-http.js +192 -0
  18. package/dist/escrow-readiness.d.ts +132 -0
  19. package/dist/escrow-readiness.js +171 -0
  20. package/dist/index.d.ts +26 -0
  21. package/dist/index.js +42 -0
  22. package/dist/jupiter.d.ts +36 -0
  23. package/dist/jupiter.js +120 -0
  24. package/dist/metered.d.ts +58 -0
  25. package/dist/metered.js +82 -0
  26. package/dist/middleware.d.ts +9 -0
  27. package/dist/middleware.js +71 -0
  28. package/dist/nonce.d.ts +57 -0
  29. package/dist/nonce.js +123 -0
  30. package/dist/payment.d.ts +202 -0
  31. package/dist/payment.js +967 -0
  32. package/dist/provider.d.ts +371 -0
  33. package/dist/provider.js +492 -0
  34. package/dist/rating.d.ts +552 -0
  35. package/dist/rating.js +829 -0
  36. package/dist/session-auth.d.ts +168 -0
  37. package/dist/session-auth.js +341 -0
  38. package/dist/session.d.ts +220 -0
  39. package/dist/session.js +297 -0
  40. package/dist/spl-token-observer.d.ts +70 -0
  41. package/dist/spl-token-observer.js +319 -0
  42. package/dist/token-escrow.d.ts +125 -0
  43. package/dist/token-escrow.js +163 -0
  44. package/dist/types.d.ts +148 -0
  45. package/dist/types.js +2 -0
  46. package/package.json +109 -4
package/dist/index.js ADDED
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ /**
3
+ * @redditech/x402-solana - HTTP 402 primitives for Solana-oriented RAP workflows.
4
+ *
5
+ * Repo-local v0.1 OSS candidate. Clean-checkout smoke must stay local and
6
+ * must not imply npm publication, live payment, custody, mainnet, or
7
+ * settlement-finality readiness.
8
+ */
9
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13
+ desc = { enumerable: true, get: function() { return m[k]; } };
14
+ }
15
+ Object.defineProperty(o, k2, desc);
16
+ }) : (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ o[k2] = m[k];
19
+ }));
20
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
21
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
22
+ };
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ __exportStar(require("./types"), exports);
25
+ __exportStar(require("./nonce"), exports);
26
+ __exportStar(require("./payment"), exports);
27
+ __exportStar(require("./direct-payment"), exports);
28
+ __exportStar(require("./metered"), exports);
29
+ __exportStar(require("./buyer"), exports);
30
+ __exportStar(require("./spl-token-observer"), exports);
31
+ __exportStar(require("./middleware"), exports);
32
+ __exportStar(require("./jupiter"), exports);
33
+ __exportStar(require("./client"), exports);
34
+ __exportStar(require("./budget-policy"), exports);
35
+ __exportStar(require("./token-escrow"), exports);
36
+ __exportStar(require("./escrow-http"), exports);
37
+ __exportStar(require("./escrow-readiness"), exports);
38
+ __exportStar(require("./provider"), exports);
39
+ __exportStar(require("./rating"), exports);
40
+ __exportStar(require("./session"), exports);
41
+ __exportStar(require("./session-auth"), exports);
42
+ __exportStar(require("./direct-auth"), exports);
@@ -0,0 +1,36 @@
1
+ import { X402Request } from './types';
2
+ export interface JupiterSwapRequest {
3
+ inputMint: string;
4
+ outputMint: string;
5
+ amount: string;
6
+ userPublicKey: string;
7
+ slippageBps?: number;
8
+ }
9
+ export interface JupiterSwapResult {
10
+ orderId: string;
11
+ executeId: string;
12
+ inAmount: string;
13
+ outAmount: string;
14
+ }
15
+ export interface SwapClient {
16
+ swap(request: JupiterSwapRequest): Promise<JupiterSwapResult>;
17
+ }
18
+ export interface JupiterSwapClientOptions {
19
+ apiBaseUrl?: string;
20
+ quoteApiBaseUrl?: string;
21
+ apiKey?: string;
22
+ fetchImpl?: typeof fetch;
23
+ }
24
+ export declare function resolveMint(symbolOrMint: string): string;
25
+ export declare class JupiterSwapV2Client implements SwapClient {
26
+ private apiBaseUrl;
27
+ private quoteApiBaseUrl;
28
+ private apiKey?;
29
+ private fetchImpl;
30
+ constructor(options?: JupiterSwapClientOptions);
31
+ private buildHeaders;
32
+ private swapViaOrderExecute;
33
+ private swapViaQuote;
34
+ swap(request: JupiterSwapRequest): Promise<JupiterSwapResult>;
35
+ }
36
+ export declare function needsAutoSwap(request: X402Request): boolean;
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.JupiterSwapV2Client = void 0;
4
+ exports.resolveMint = resolveMint;
5
+ exports.needsAutoSwap = needsAutoSwap;
6
+ const SYMBOL_TO_MINT = {
7
+ SOL: 'So11111111111111111111111111111111111111112',
8
+ USDC: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
9
+ };
10
+ function resolveMint(symbolOrMint) {
11
+ const normalized = symbolOrMint.trim();
12
+ const upper = normalized.toUpperCase();
13
+ return SYMBOL_TO_MINT[upper] || normalized;
14
+ }
15
+ class JupiterSwapV2Client {
16
+ constructor(options = {}) {
17
+ this.apiBaseUrl = options.apiBaseUrl || 'https://api.jup.ag/swap/v2';
18
+ this.quoteApiBaseUrl = options.quoteApiBaseUrl || 'https://lite-api.jup.ag/swap/v1';
19
+ this.apiKey = options.apiKey || process.env.JUPITER_API_KEY?.trim();
20
+ this.fetchImpl = options.fetchImpl || fetch;
21
+ }
22
+ buildHeaders() {
23
+ const headers = { 'content-type': 'application/json' };
24
+ if (this.apiKey) {
25
+ headers['x-api-key'] = this.apiKey;
26
+ }
27
+ return headers;
28
+ }
29
+ async swapViaOrderExecute(request) {
30
+ const orderRes = await this.fetchImpl(`${this.apiBaseUrl}/order`, {
31
+ method: 'POST',
32
+ headers: this.buildHeaders(),
33
+ body: JSON.stringify({
34
+ inputMint: request.inputMint,
35
+ outputMint: request.outputMint,
36
+ amount: request.amount,
37
+ taker: request.userPublicKey,
38
+ slippageBps: request.slippageBps ?? 50,
39
+ }),
40
+ });
41
+ if (orderRes.status === 404) {
42
+ throw new Error('Jupiter order failed (404)');
43
+ }
44
+ if (!orderRes.ok) {
45
+ throw new Error(`Jupiter order failed (${orderRes.status})`);
46
+ }
47
+ const orderJson = (await orderRes.json());
48
+ const orderId = orderJson.requestId || orderJson.orderId || orderJson.id;
49
+ if (!orderId) {
50
+ throw new Error('Jupiter order response missing request id');
51
+ }
52
+ const executeTx = orderJson.transaction || orderJson.tx;
53
+ if (!executeTx) {
54
+ return {
55
+ orderId,
56
+ executeId: `exec_pending_${Date.now().toString(36)}`,
57
+ inAmount: orderJson.inAmount || request.amount,
58
+ outAmount: orderJson.outAmount || '0',
59
+ };
60
+ }
61
+ const executeRes = await this.fetchImpl(`${this.apiBaseUrl}/execute`, {
62
+ method: 'POST',
63
+ headers: this.buildHeaders(),
64
+ body: JSON.stringify({
65
+ requestId: orderId,
66
+ signedTransaction: executeTx,
67
+ }),
68
+ });
69
+ if (!executeRes.ok) {
70
+ throw new Error(`Jupiter execute failed (${executeRes.status})`);
71
+ }
72
+ const executeJson = (await executeRes.json());
73
+ return {
74
+ orderId,
75
+ executeId: executeJson.executeId || executeJson.requestId || executeJson.id || `exec_${Date.now().toString(36)}`,
76
+ inAmount: orderJson.inAmount || request.amount,
77
+ outAmount: executeJson.outputAmountResult || executeJson.outAmount || orderJson.outAmount || '0',
78
+ };
79
+ }
80
+ async swapViaQuote(request) {
81
+ const query = new URLSearchParams({
82
+ inputMint: request.inputMint,
83
+ outputMint: request.outputMint,
84
+ amount: request.amount,
85
+ slippageBps: String(request.slippageBps ?? 50),
86
+ });
87
+ const quoteRes = await this.fetchImpl(`${this.quoteApiBaseUrl}/quote?${query.toString()}`, {
88
+ method: 'GET',
89
+ headers: this.apiKey ? { 'x-api-key': this.apiKey } : undefined,
90
+ });
91
+ if (!quoteRes.ok) {
92
+ throw new Error(`Jupiter quote failed (${quoteRes.status})`);
93
+ }
94
+ const quoteJson = (await quoteRes.json());
95
+ return {
96
+ orderId: `quote_${Date.now().toString(36)}_${quoteJson.contextSlot ?? 'na'}`,
97
+ executeId: `quote_only_${Array.isArray(quoteJson.routePlan) ? quoteJson.routePlan.length : 0}`,
98
+ inAmount: quoteJson.inAmount || request.amount,
99
+ outAmount: quoteJson.outAmount || '0',
100
+ };
101
+ }
102
+ async swap(request) {
103
+ try {
104
+ return await this.swapViaOrderExecute(request);
105
+ }
106
+ catch (error) {
107
+ const message = error instanceof Error ? error.message : String(error);
108
+ if (!message.includes('404') && !message.includes('fetch failed')) {
109
+ throw error;
110
+ }
111
+ return this.swapViaQuote(request);
112
+ }
113
+ }
114
+ }
115
+ exports.JupiterSwapV2Client = JupiterSwapV2Client;
116
+ function needsAutoSwap(request) {
117
+ const payerCurrency = (request.payerCurrency || request.currency).toUpperCase();
118
+ const settlementCurrency = request.currency.toUpperCase();
119
+ return Boolean(request.autoSwap && payerCurrency !== settlementCurrency);
120
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Per-token pricing for a listing, as most AI inference services price. Prices
3
+ * are decimal amounts of `currency` per million tokens, with at most the
4
+ * currency's own number of decimal places.
5
+ */
6
+ export interface PerTokenPrice {
7
+ currency: string;
8
+ inputPerMillion: string;
9
+ outputPerMillion: string;
10
+ }
11
+ export interface TokenCounts {
12
+ inputTokens: number;
13
+ outputTokens: number;
14
+ }
15
+ /**
16
+ * Cost of `counts` tokens in base units of the price currency, rounded up to
17
+ * the next base unit so a provider is never paid less than its listed rate.
18
+ */
19
+ export declare function tokenCostBaseUnits(price: PerTokenPrice, counts: TokenCounts): bigint;
20
+ export interface MeteredQuote {
21
+ currency: string;
22
+ /** Expected cost of the estimated token counts. */
23
+ estimatedCost: string;
24
+ /** The most the buyer authorises, which is what an escrow locks. */
25
+ maxCharge: string;
26
+ /** Protocol fee if the estimate holds, taken out of the provider's share. */
27
+ estimatedFee: string;
28
+ }
29
+ /**
30
+ * What a buyer sees before a metered call: the estimated cost and the maximum
31
+ * it authorises. The maximum must cover the estimate.
32
+ */
33
+ export declare function quoteMeteredCall(price: PerTokenPrice, estimate: TokenCounts, maxCharge: string, atMs?: number): MeteredQuote;
34
+ export interface MeteredSettlement {
35
+ currency: string;
36
+ inputTokens: number;
37
+ outputTokens: number;
38
+ /** Cost of the tokens actually used, at the listed rates. */
39
+ actualCost: string;
40
+ /** What the buyer pays: the actual cost, never more than the authorised maximum. */
41
+ charged: string;
42
+ /** The scheduled rate of `charged` (2.5% until 1 April 2027, then 5%), rounded down; at most 0.1 SOL for SOL. Goes to the treasury. */
43
+ fee: string;
44
+ /** `charged` less the fee. */
45
+ provider: string;
46
+ /** Authorised maximum less `charged`, returned to the buyer. */
47
+ refund: string;
48
+ /** True when the actual cost went above the maximum and the charge was held to it. */
49
+ capped: boolean;
50
+ /** `charged` in base units: the amount to pass to the escrow program's settle instruction. */
51
+ chargedBaseUnits: bigint;
52
+ }
53
+ /**
54
+ * Works out a metered call once the response is in and the real token counts
55
+ * are known. This is the same split the escrow program applies on-chain when
56
+ * the payee settles with `chargedBaseUnits`.
57
+ */
58
+ export declare function settleMeteredCall(price: PerTokenPrice, usage: TokenCounts, maxCharge: string, atMs?: number): MeteredSettlement;
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.tokenCostBaseUnits = tokenCostBaseUnits;
4
+ exports.quoteMeteredCall = quoteMeteredCall;
5
+ exports.settleMeteredCall = settleMeteredCall;
6
+ const payment_1 = require("./payment");
7
+ const MILLION = BigInt(1000000);
8
+ function perMillionUnits(value, decimals) {
9
+ if (value === '0')
10
+ return BigInt(0);
11
+ const units = (0, payment_1.decimalToBaseUnits)(value, decimals);
12
+ if (units === undefined)
13
+ throw new Error(`per-million price must be a non-negative amount with at most ${decimals} decimal places`);
14
+ return units;
15
+ }
16
+ function count(value, name) {
17
+ if (!Number.isSafeInteger(value) || value < 0)
18
+ throw new Error(`${name} must be a whole number of tokens`);
19
+ return BigInt(value);
20
+ }
21
+ function currencyDecimals(currency) {
22
+ const decimals = (0, payment_1.directPaymentCurrency)(currency)?.decimals;
23
+ if (decimals === undefined)
24
+ throw new Error(`unsupported currency: ${currency}`);
25
+ return decimals;
26
+ }
27
+ /**
28
+ * Cost of `counts` tokens in base units of the price currency, rounded up to
29
+ * the next base unit so a provider is never paid less than its listed rate.
30
+ */
31
+ function tokenCostBaseUnits(price, counts) {
32
+ const decimals = currencyDecimals(price.currency);
33
+ const scaled = count(counts.inputTokens, 'inputTokens') * perMillionUnits(price.inputPerMillion, decimals) +
34
+ count(counts.outputTokens, 'outputTokens') * perMillionUnits(price.outputPerMillion, decimals);
35
+ return (scaled + MILLION - BigInt(1)) / MILLION;
36
+ }
37
+ /**
38
+ * What a buyer sees before a metered call: the estimated cost and the maximum
39
+ * it authorises. The maximum must cover the estimate.
40
+ */
41
+ function quoteMeteredCall(price, estimate, maxCharge, atMs = Date.now()) {
42
+ const decimals = currencyDecimals(price.currency);
43
+ const estimated = tokenCostBaseUnits(price, estimate);
44
+ const max = (0, payment_1.decimalToBaseUnits)(maxCharge, decimals);
45
+ if (max === undefined)
46
+ throw new Error(`maxCharge must be a positive ${price.currency} amount with at most ${decimals} decimal places`);
47
+ if (max < estimated)
48
+ throw new Error('maxCharge must be at least the estimated cost');
49
+ return {
50
+ currency: price.currency,
51
+ estimatedCost: (0, payment_1.baseUnitsToDecimal)(estimated, decimals),
52
+ maxCharge: (0, payment_1.baseUnitsToDecimal)(max, decimals),
53
+ estimatedFee: (0, payment_1.baseUnitsToDecimal)((0, payment_1.protocolFeeBaseUnits)(estimated, (0, payment_1.protocolFeeBpsAt)(atMs), (0, payment_1.protocolFeeCapBaseUnits)(price.currency)), decimals),
54
+ };
55
+ }
56
+ /**
57
+ * Works out a metered call once the response is in and the real token counts
58
+ * are known. This is the same split the escrow program applies on-chain when
59
+ * the payee settles with `chargedBaseUnits`.
60
+ */
61
+ function settleMeteredCall(price, usage, maxCharge, atMs = Date.now()) {
62
+ const decimals = currencyDecimals(price.currency);
63
+ const max = (0, payment_1.decimalToBaseUnits)(maxCharge, decimals);
64
+ if (max === undefined)
65
+ throw new Error(`maxCharge must be a positive ${price.currency} amount with at most ${decimals} decimal places`);
66
+ const actual = tokenCostBaseUnits(price, usage);
67
+ const charged = actual > max ? max : actual;
68
+ const fee = (0, payment_1.protocolFeeBaseUnits)(charged, (0, payment_1.protocolFeeBpsAt)(atMs), (0, payment_1.protocolFeeCapBaseUnits)(price.currency));
69
+ const text = (units) => (0, payment_1.baseUnitsToDecimal)(units, decimals);
70
+ return {
71
+ currency: price.currency,
72
+ inputTokens: usage.inputTokens,
73
+ outputTokens: usage.outputTokens,
74
+ actualCost: text(actual),
75
+ charged: text(charged),
76
+ fee: text(fee),
77
+ provider: text(charged - fee),
78
+ refund: text(max - charged),
79
+ capped: actual > max,
80
+ chargedBaseUnits: charged,
81
+ };
82
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Express middleware for x402 payment processing
3
+ * Intercepts requests with x402-request header, validates, and sends payment
4
+ */
5
+ export declare function createX402Middleware(): (req: any, res: any, next: any) => Promise<any>;
6
+ /**
7
+ * Helper: Create x402-request header from components
8
+ */
9
+ export declare function createX402Header(amount: number, paymentAddress: string, nonce: string, currency?: string): string;
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createX402Middleware = createX402Middleware;
4
+ exports.createX402Header = createX402Header;
5
+ const payment_1 = require("./payment");
6
+ const nonce_1 = require("./nonce");
7
+ /**
8
+ * Express middleware for x402 payment processing
9
+ * Intercepts requests with x402-request header, validates, and sends payment
10
+ */
11
+ function createX402Middleware() {
12
+ return async (req, res, next) => {
13
+ // Check for x402-request header
14
+ const header = req.headers['x402-request'];
15
+ if (!header) {
16
+ return next(); // Not an x402 payment request, continue
17
+ }
18
+ try {
19
+ // Parse the header
20
+ const x402req = (0, payment_1.parseX402Header)(header);
21
+ // Validate payment address format
22
+ if (!(0, payment_1.isValidPaymentAddress)(x402req.paymentAddress)) {
23
+ return res.status(400).json({
24
+ error: 'invalid_request',
25
+ detail: 'paymentAddress format invalid',
26
+ });
27
+ }
28
+ // Check for replay attack (duplicate nonce)
29
+ if (!(0, nonce_1.checkAndStoreNonce)(x402req.nonce)) {
30
+ return res.status(409).json({
31
+ error: 'duplicate_nonce',
32
+ detail: 'This nonce has already been used',
33
+ });
34
+ }
35
+ // Send the payment (Phase 2 will implement actual Solana transfer)
36
+ const receipt = await (0, payment_1.sendPayment)(x402req);
37
+ // Set response headers
38
+ res.setHeader('x402-payment', JSON.stringify(receipt));
39
+ res.status(200).json({
40
+ message: 'payment_processed',
41
+ receipt,
42
+ });
43
+ }
44
+ catch (error) {
45
+ // Handle different error types
46
+ if (error.message.includes('JSON')) {
47
+ return res.status(400).json({
48
+ error: 'invalid_request',
49
+ detail: error.message,
50
+ });
51
+ }
52
+ if (error.message.includes('timeout')) {
53
+ return res.status(503).json({
54
+ error: 'rpc_timeout',
55
+ detail: 'Payment confirmation timeout',
56
+ });
57
+ }
58
+ // Generic error
59
+ return res.status(400).json({
60
+ error: 'invalid_request',
61
+ detail: error.message,
62
+ });
63
+ }
64
+ };
65
+ }
66
+ /**
67
+ * Helper: Create x402-request header from components
68
+ */
69
+ function createX402Header(amount, paymentAddress, nonce, currency = 'SOL') {
70
+ return JSON.stringify({ amount, currency, paymentAddress, nonce });
71
+ }
@@ -0,0 +1,57 @@
1
+ import type { NonceReplayStore } from './types';
2
+ export declare class MemoryNonceReplayStore implements NonceReplayStore {
3
+ private readonly seen;
4
+ checkAndStore(nonce: string): boolean;
5
+ checkAndStoreAll(keys: string[]): boolean;
6
+ clear(): void;
7
+ get size(): number;
8
+ }
9
+ /**
10
+ * Check if nonce has been seen before, and store it if new.
11
+ * @returns true if nonce is new, false if duplicate.
12
+ */
13
+ export declare function checkAndStoreNonce(nonce: string): boolean;
14
+ export declare const defaultNonceReplayStore: NonceReplayStore;
15
+ /**
16
+ * Records all keys for one payment. Uses the store's atomic `checkAndStoreAll`
17
+ * when it has one; otherwise records them one by one, in order, which can leave
18
+ * the earlier keys recorded if a later one is refused or fails.
19
+ */
20
+ export declare function checkAndStoreReplayKeys(store: NonceReplayStore, keys: string[]): Promise<boolean>;
21
+ /** Clear all stored nonces (for testing). */
22
+ export declare function clearNonces(): void;
23
+ /** Get count of stored nonces (for debugging). */
24
+ export declare function getNonceCount(): number;
25
+ /** Result shape of a database remote procedure call, as returned by supabase-js `rpc`. */
26
+ export interface ReplayRpcResult {
27
+ data: unknown;
28
+ error: unknown;
29
+ }
30
+ export interface DatabaseReplayStoreOptions {
31
+ /**
32
+ * Calls a database function by name. With supabase-js, pass
33
+ * `(fn, args) => client.rpc(fn, args)` using a server-side client.
34
+ */
35
+ rpc: (fn: string, args: Record<string, unknown>) => PromiseLike<ReplayRpcResult>;
36
+ /** Defaults to `replay_check_and_store`, which takes `p_key` and returns a boolean. */
37
+ functionName?: string;
38
+ /**
39
+ * Defaults to `replay_check_and_store_all`, which takes `p_keys` (a text array),
40
+ * inserts all of them or none, and returns a boolean.
41
+ */
42
+ batchFunctionName?: string;
43
+ }
44
+ /**
45
+ * Durable replay store backed by an atomic database function, so a key is
46
+ * accepted once across restarts and across every instance of the service.
47
+ * Fails closed: a database error or an unexpected answer throws, and the payment
48
+ * is not accepted.
49
+ */
50
+ export declare class DatabaseReplayStore implements NonceReplayStore {
51
+ private readonly options;
52
+ private readonly functionName;
53
+ private readonly batchFunctionName;
54
+ constructor(options: DatabaseReplayStoreOptions);
55
+ checkAndStoreAll(keys: string[]): Promise<boolean>;
56
+ checkAndStore(key: string): Promise<boolean>;
57
+ }
package/dist/nonce.js ADDED
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DatabaseReplayStore = exports.defaultNonceReplayStore = exports.MemoryNonceReplayStore = void 0;
4
+ exports.checkAndStoreNonce = checkAndStoreNonce;
5
+ exports.checkAndStoreReplayKeys = checkAndStoreReplayKeys;
6
+ exports.clearNonces = clearNonces;
7
+ exports.getNonceCount = getNonceCount;
8
+ /**
9
+ * In-memory nonce store for replay protection.
10
+ * In production, callers should provide a persistent store (Redis/DB) with TTL.
11
+ */
12
+ const seenNonces = new Set();
13
+ class MemoryNonceReplayStore {
14
+ constructor() {
15
+ this.seen = new Set();
16
+ }
17
+ checkAndStore(nonce) {
18
+ if (this.seen.has(nonce))
19
+ return false;
20
+ this.seen.add(nonce);
21
+ return true;
22
+ }
23
+ checkAndStoreAll(keys) {
24
+ assertDistinctKeys(keys);
25
+ if (keys.some((key) => this.seen.has(key)))
26
+ return false;
27
+ for (const key of keys)
28
+ this.seen.add(key);
29
+ return true;
30
+ }
31
+ clear() {
32
+ this.seen.clear();
33
+ }
34
+ get size() {
35
+ return this.seen.size;
36
+ }
37
+ }
38
+ exports.MemoryNonceReplayStore = MemoryNonceReplayStore;
39
+ /**
40
+ * Check if nonce has been seen before, and store it if new.
41
+ * @returns true if nonce is new, false if duplicate.
42
+ */
43
+ function checkAndStoreNonce(nonce) {
44
+ if (seenNonces.has(nonce))
45
+ return false;
46
+ seenNonces.add(nonce);
47
+ return true;
48
+ }
49
+ exports.defaultNonceReplayStore = {
50
+ checkAndStore: checkAndStoreNonce,
51
+ checkAndStoreAll(keys) {
52
+ assertDistinctKeys(keys);
53
+ if (keys.some((key) => seenNonces.has(key)))
54
+ return false;
55
+ for (const key of keys)
56
+ seenNonces.add(key);
57
+ return true;
58
+ },
59
+ };
60
+ function assertDistinctKeys(keys) {
61
+ if (!Array.isArray(keys) || keys.length === 0)
62
+ throw new Error('at least one replay key is required');
63
+ if (keys.some((key) => typeof key !== 'string' || key.length === 0))
64
+ throw new Error('replay key must be a non-empty string');
65
+ if (new Set(keys).size !== keys.length)
66
+ throw new Error('replay keys must be distinct');
67
+ }
68
+ /**
69
+ * Records all keys for one payment. Uses the store's atomic `checkAndStoreAll`
70
+ * when it has one; otherwise records them one by one, in order, which can leave
71
+ * the earlier keys recorded if a later one is refused or fails.
72
+ */
73
+ async function checkAndStoreReplayKeys(store, keys) {
74
+ assertDistinctKeys(keys);
75
+ if (store.checkAndStoreAll)
76
+ return store.checkAndStoreAll(keys);
77
+ for (const key of keys) {
78
+ if (!(await store.checkAndStore(key)))
79
+ return false;
80
+ }
81
+ return true;
82
+ }
83
+ /** Clear all stored nonces (for testing). */
84
+ function clearNonces() {
85
+ seenNonces.clear();
86
+ }
87
+ /** Get count of stored nonces (for debugging). */
88
+ function getNonceCount() {
89
+ return seenNonces.size;
90
+ }
91
+ /**
92
+ * Durable replay store backed by an atomic database function, so a key is
93
+ * accepted once across restarts and across every instance of the service.
94
+ * Fails closed: a database error or an unexpected answer throws, and the payment
95
+ * is not accepted.
96
+ */
97
+ class DatabaseReplayStore {
98
+ constructor(options) {
99
+ this.options = options;
100
+ this.functionName = options.functionName ?? 'replay_check_and_store';
101
+ this.batchFunctionName = options.batchFunctionName ?? 'replay_check_and_store_all';
102
+ }
103
+ async checkAndStoreAll(keys) {
104
+ assertDistinctKeys(keys);
105
+ const { data, error } = await this.options.rpc(this.batchFunctionName, { p_keys: keys });
106
+ if (error)
107
+ throw new Error('replay store is unavailable; payment cannot be accepted');
108
+ if (typeof data !== 'boolean')
109
+ throw new Error('replay store returned an unexpected answer; payment cannot be accepted');
110
+ return data;
111
+ }
112
+ async checkAndStore(key) {
113
+ if (typeof key !== 'string' || key.length === 0)
114
+ throw new Error('replay key must be a non-empty string');
115
+ const { data, error } = await this.options.rpc(this.functionName, { p_key: key });
116
+ if (error)
117
+ throw new Error('replay store is unavailable; payment cannot be accepted');
118
+ if (typeof data !== 'boolean')
119
+ throw new Error('replay store returned an unexpected answer; payment cannot be accepted');
120
+ return data;
121
+ }
122
+ }
123
+ exports.DatabaseReplayStore = DatabaseReplayStore;