@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
@@ -0,0 +1,168 @@
1
+ import { PublicKey, TransactionInstruction } from '@solana/web3.js';
2
+ import type { HeaderReader } from './provider';
3
+ export declare const SESSION_DELEGATION_HEADER = "x402-session-delegation";
4
+ export declare const SESSION_SIGNATURE_HEADER = "x402-session-signature";
5
+ /** The longest a delegation may run. A session settles before its refund window anyway. */
6
+ export declare const MAX_SESSION_DELEGATION_SECONDS: number;
7
+ /**
8
+ * How long a buyer client should let a delegation run unless it has a reason
9
+ * to choose otherwise: a day, well short of the maximum, because anyone holding
10
+ * the session key can sign for the payer until then. Keep the key in memory
11
+ * only (never in localStorage or on disk), and sign a new delegation when it runs out.
12
+ */
13
+ export declare const DEFAULT_DELEGATION_SECONDS: number;
14
+ /** Buyer side: the `expiresAt` for a new delegation, `seconds` (default a day) from `nowMs`. */
15
+ export declare function delegationExpiresAt(nowMs?: number, seconds?: number): number;
16
+ /**
17
+ * `call`: a session call. `call-close`: a session call that also asks the
18
+ * provider to settle the session after answering it. `close`, `read`: session
19
+ * requests without a call. `single`: a single metered call, sequence 0.
20
+ */
21
+ export type SessionAction = 'call' | 'call-close' | 'close' | 'read' | 'single';
22
+ /** The action a session call is signed under: `call-close` when it asks to close the session. */
23
+ export declare function sessionCallAction(close: boolean): SessionAction;
24
+ export interface SessionDelegation {
25
+ /** The genesis hash of the cluster the escrow is on (`SOLANA_GENESIS_HASHES[network]`). */
26
+ genesisHash: string;
27
+ escrow: string;
28
+ provider: string;
29
+ sessionKey: string;
30
+ /** Whole seconds since the epoch. */
31
+ expiresAt: number;
32
+ }
33
+ export type SessionAuthFailure = {
34
+ ok: false;
35
+ reason: 'session_auth_required' | 'session_auth_invalid' | 'session_auth_expired';
36
+ message: string;
37
+ };
38
+ /** The text the payer wallet signs to hand a session to `sessionKey`. */
39
+ export declare function sessionDelegationMessage(d: SessionDelegation): string;
40
+ /** SHA-256 of a request body, hex. An empty body hashes as zero bytes. */
41
+ export declare function sessionBodyHash(body?: Uint8Array | string): string;
42
+ /** The bytes the session key signs for one request. `sequence` is the call number for `call` and `call-close`, and 0 for `close`, `read` and `single`. */
43
+ export declare function sessionRequestMessage(input: {
44
+ genesisHash: string;
45
+ action: SessionAction;
46
+ escrow: string;
47
+ sequence: number;
48
+ bodyHash: string;
49
+ }): string;
50
+ export type Signer = (message: Uint8Array) => Uint8Array | Promise<Uint8Array>;
51
+ /** Buyer side: the delegation header value, signed by the payer wallet. Use `delegationExpiresAt()` for `expiresAt`. */
52
+ export declare function sessionDelegationHeaderValue(d: SessionDelegation, signWithPayer: Signer): Promise<string>;
53
+ /** Buyer side: the signature header value for one request, signed by the session key. */
54
+ export declare function sessionSignatureHeaderValue(input: {
55
+ genesisHash: string;
56
+ action: SessionAction;
57
+ escrow: string;
58
+ sequence: number;
59
+ body?: Uint8Array | string;
60
+ }, signWithSessionKey: Signer): Promise<string>;
61
+ /**
62
+ * Provider side: checks that a session request is signed by a key the payer
63
+ * handed this session to. Returns the session key on success. `payer` and
64
+ * `escrow` come from the payment header (the lock check then confirms them on
65
+ * chain); `provider` is this provider's payee wallet; `genesisHash` is the
66
+ * genesis hash of the cluster this provider checked it is on; `body` is the raw
67
+ * request body exactly as received.
68
+ */
69
+ export declare function verifySessionRequest(input: SessionRequestInput): {
70
+ ok: true;
71
+ sessionKey: string;
72
+ expiresAt: number;
73
+ } | SessionAuthFailure;
74
+ export interface SessionRequestInput {
75
+ headers: HeaderReader;
76
+ genesisHash: string;
77
+ action: SessionAction;
78
+ escrow: PublicKey;
79
+ payer: PublicKey;
80
+ provider: PublicKey;
81
+ sequence: number;
82
+ body?: Uint8Array | string;
83
+ nowMs: number;
84
+ }
85
+ /**
86
+ * Buyer side, single metered call: both headers for one call on the lock
87
+ * `escrow`. With no `sessionKey`, the payer signs the request too (fine for a
88
+ * server-held keypair; a browser wallet would then sign twice, so pass a
89
+ * fresh key there and keep it for the call).
90
+ */
91
+ export declare function paidCallAuthHeaders(input: {
92
+ /** The genesis hash of the cluster the escrow is on. */
93
+ genesisHash: string;
94
+ escrow: string;
95
+ provider: string;
96
+ body: Uint8Array | string;
97
+ payer: string;
98
+ signWithPayer: Signer;
99
+ sessionKey?: {
100
+ publicKey: string;
101
+ sign: Signer;
102
+ };
103
+ expiresAt?: number;
104
+ nowMs?: number;
105
+ }): Promise<Record<string, string>>;
106
+ /** Provider side, single metered call: `verifySessionRequest` with action `single` and sequence 0. */
107
+ export declare function verifyPaidCallRequest(input: Omit<Parameters<typeof verifySessionRequest>[0], 'action' | 'sequence'>): ReturnType<typeof verifySessionRequest>;
108
+ /** The SPL Memo program (v2), which fails unless every account it names has signed. */
109
+ export declare const MEMO_PROGRAM_ID: PublicKey;
110
+ export declare const SESSION_DELEGATION_MEMO_PREFIX = "reddi-session/2 delegate ";
111
+ /** The memo text that binds a delegation to the transaction that carries it. */
112
+ export declare function sessionDelegationMemo(d: SessionDelegation): string;
113
+ /** Buyer side: the memo instruction to add to the lock transaction, signed by the payer. */
114
+ export declare function sessionDelegationMemoInstruction(d: SessionDelegation, payer: PublicKey): TransactionInstruction;
115
+ /** Buyer side: the delegation header for a delegation proved by the confirmed lock transaction `lockSignature`. */
116
+ export declare function lockBoundDelegationHeaderValue(d: SessionDelegation, lockSignature: string): string;
117
+ /** What the provider needs to know about a confirmed transaction. */
118
+ export interface ConfirmedTransactionFacts {
119
+ /** True when the transaction failed. */
120
+ failed: boolean;
121
+ /** Base58 addresses that signed the transaction. */
122
+ signers: string[];
123
+ /** Base58 addresses of every account the transaction names, including loaded lookup-table addresses. */
124
+ accounts: string[];
125
+ /** Each Memo program instruction: its UTF-8 text and the base58 accounts it names. */
126
+ memos: {
127
+ text: string;
128
+ accounts: string[];
129
+ }[];
130
+ /** The slot the transaction landed in, when the reader knows it. */
131
+ slot?: bigint;
132
+ }
133
+ /** Reads a confirmed transaction by signature, or null when the cluster does not have it (yet). Throws when the chain cannot be read. */
134
+ export type TransactionFactsReader = (signature: string) => Promise<ConfirmedTransactionFacts | null>;
135
+ /** A `TransactionFactsReader` over `Connection.getTransaction` at `confirmed`. */
136
+ export declare function transactionFactsReader(connection: {
137
+ getTransaction: (signature: string, options: {
138
+ commitment: 'confirmed' | 'finalized';
139
+ maxSupportedTransactionVersion: number;
140
+ }) => Promise<unknown>;
141
+ }, commitment?: 'confirmed' | 'finalized'): TransactionFactsReader;
142
+ /**
143
+ * Provider side: `verifySessionRequest`, and also a delegation proved by the
144
+ * memo in its lock transaction. Without `readTransaction` a lock-bound
145
+ * delegation is refused. It may run before or after the lock check: either
146
+ * way the caller must still check the lock, which is what shows the escrow
147
+ * named here is this payer's lock.
148
+ *
149
+ * An escrow address can be used again once a lock ends. Pass the escrow's
150
+ * `created_slot` as `escrowCreatedSlot` to require that the lock transaction
151
+ * is the one that created this escrow. When the escrow is read later, compare
152
+ * the returned `lockSlot` with its `created_slot` instead.
153
+ */
154
+ export declare function verifySessionRequestWithTransactions(input: SessionRequestInput & {
155
+ readTransaction?: TransactionFactsReader;
156
+ escrowCreatedSlot?: bigint;
157
+ }): Promise<{
158
+ ok: true;
159
+ sessionKey: string;
160
+ expiresAt: number;
161
+ lockSlot?: bigint;
162
+ } | SessionAuthFailure | {
163
+ ok: false;
164
+ reason: 'payment_check_unavailable';
165
+ message: string;
166
+ }>;
167
+ /** Provider side, single metered call: `verifySessionRequestWithTransactions` with action `single` and sequence 0. */
168
+ export declare function verifyPaidCallRequestWithTransactions(input: Omit<Parameters<typeof verifySessionRequestWithTransactions>[0], 'action' | 'sequence'>): ReturnType<typeof verifySessionRequestWithTransactions>;
@@ -0,0 +1,341 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SESSION_DELEGATION_MEMO_PREFIX = exports.MEMO_PROGRAM_ID = exports.DEFAULT_DELEGATION_SECONDS = exports.MAX_SESSION_DELEGATION_SECONDS = exports.SESSION_SIGNATURE_HEADER = exports.SESSION_DELEGATION_HEADER = void 0;
4
+ exports.delegationExpiresAt = delegationExpiresAt;
5
+ exports.sessionCallAction = sessionCallAction;
6
+ exports.sessionDelegationMessage = sessionDelegationMessage;
7
+ exports.sessionBodyHash = sessionBodyHash;
8
+ exports.sessionRequestMessage = sessionRequestMessage;
9
+ exports.sessionDelegationHeaderValue = sessionDelegationHeaderValue;
10
+ exports.sessionSignatureHeaderValue = sessionSignatureHeaderValue;
11
+ exports.verifySessionRequest = verifySessionRequest;
12
+ exports.paidCallAuthHeaders = paidCallAuthHeaders;
13
+ exports.verifyPaidCallRequest = verifyPaidCallRequest;
14
+ exports.sessionDelegationMemo = sessionDelegationMemo;
15
+ exports.sessionDelegationMemoInstruction = sessionDelegationMemoInstruction;
16
+ exports.lockBoundDelegationHeaderValue = lockBoundDelegationHeaderValue;
17
+ exports.transactionFactsReader = transactionFactsReader;
18
+ exports.verifySessionRequestWithTransactions = verifySessionRequestWithTransactions;
19
+ exports.verifyPaidCallRequestWithTransactions = verifyPaidCallRequestWithTransactions;
20
+ /**
21
+ * Proof that a paid call comes from the buyer that locked the escrow: every
22
+ * call of a session, and a single metered call (action `single`, #866).
23
+ *
24
+ * The lock's escrow, payer and nonce are public once it confirms, so they
25
+ * cannot show who is calling. The buyer makes a fresh ed25519 key for the
26
+ * session and has its payer wallet sign, once, a delegation naming the
27
+ * escrow, the provider, that key and an expiry (a plain-text message, so a
28
+ * browser wallet can sign it with `signMessage`). Every call, close and read
29
+ * then carries a signature by the session key over the action, the escrow,
30
+ * the call number and the SHA-256 of the request body. The provider checks
31
+ * both before it reserves a call, and the session keeps the first key it saw,
32
+ * so a second delegation cannot take over a session already started.
33
+ *
34
+ * Both messages name the cluster by its genesis hash, so a signature made for
35
+ * one network is refused on every other, even where the program id, escrow
36
+ * address and provider are the same.
37
+ *
38
+ * Headers:
39
+ * - `x402-session-delegation`: base64 of JSON `{network, escrow, provider, sessionKey, expiresAt, signature}`;
40
+ * `network` is the cluster's genesis hash;
41
+ * `expiresAt` is whole seconds since the epoch, `signature` base64 of the payer's signature over
42
+ * `sessionDelegationMessage(...)`.
43
+ * - `x402-session-signature`: base64 of the session key's signature over `sessionRequestMessage(...)`.
44
+ *
45
+ * Verification uses Node's crypto; signing takes a callback, so the buyer can
46
+ * sign with a wallet adapter, a Keypair or anything else.
47
+ */
48
+ const crypto_1 = require("crypto");
49
+ const web3_js_1 = require("@solana/web3.js");
50
+ const ed25519_1 = require("./ed25519");
51
+ exports.SESSION_DELEGATION_HEADER = 'x402-session-delegation';
52
+ exports.SESSION_SIGNATURE_HEADER = 'x402-session-signature';
53
+ /** The longest a delegation may run. A session settles before its refund window anyway. */
54
+ exports.MAX_SESSION_DELEGATION_SECONDS = 7 * 24 * 60 * 60;
55
+ /**
56
+ * How long a buyer client should let a delegation run unless it has a reason
57
+ * to choose otherwise: a day, well short of the maximum, because anyone holding
58
+ * the session key can sign for the payer until then. Keep the key in memory
59
+ * only (never in localStorage or on disk), and sign a new delegation when it runs out.
60
+ */
61
+ exports.DEFAULT_DELEGATION_SECONDS = 24 * 60 * 60;
62
+ /** Buyer side: the `expiresAt` for a new delegation, `seconds` (default a day) from `nowMs`. */
63
+ function delegationExpiresAt(nowMs = Date.now(), seconds = exports.DEFAULT_DELEGATION_SECONDS) {
64
+ if (!Number.isSafeInteger(seconds) || seconds <= 0 || seconds > exports.MAX_SESSION_DELEGATION_SECONDS) {
65
+ throw new Error(`a delegation runs for 1 to ${exports.MAX_SESSION_DELEGATION_SECONDS} seconds`);
66
+ }
67
+ return Math.floor(nowMs / 1000) + seconds;
68
+ }
69
+ /** The action a session call is signed under: `call-close` when it asks to close the session. */
70
+ function sessionCallAction(close) {
71
+ return close ? 'call-close' : 'call';
72
+ }
73
+ /** The text the payer wallet signs to hand a session to `sessionKey`. */
74
+ function sessionDelegationMessage(d) {
75
+ return [
76
+ 'Reddi Agent Protocol session',
77
+ 'I let this session key make paid calls on my escrow lock.',
78
+ `network: ${d.genesisHash}`,
79
+ `escrow: ${d.escrow}`,
80
+ `provider: ${d.provider}`,
81
+ `session key: ${d.sessionKey}`,
82
+ `expires: ${new Date(d.expiresAt * 1000).toISOString()}`,
83
+ ].join('\n');
84
+ }
85
+ /** SHA-256 of a request body, hex. An empty body hashes as zero bytes. */
86
+ function sessionBodyHash(body = '') {
87
+ return (0, crypto_1.createHash)('sha256').update(typeof body === 'string' ? Buffer.from(body, 'utf8') : Buffer.from(body)).digest('hex');
88
+ }
89
+ /** The bytes the session key signs for one request. `sequence` is the call number for `call` and `call-close`, and 0 for `close`, `read` and `single`. */
90
+ function sessionRequestMessage(input) {
91
+ return ['reddi-session/2', input.genesisHash, input.action, input.escrow, String(input.sequence), input.bodyHash].join('\n');
92
+ }
93
+ /** Buyer side: the delegation header value, signed by the payer wallet. Use `delegationExpiresAt()` for `expiresAt`. */
94
+ async function sessionDelegationHeaderValue(d, signWithPayer) {
95
+ const signature = await signWithPayer(new TextEncoder().encode(sessionDelegationMessage(d)));
96
+ const { genesisHash, ...rest } = d;
97
+ return Buffer.from(JSON.stringify({ network: genesisHash, ...rest, signature: Buffer.from(signature).toString('base64') }), 'utf8').toString('base64');
98
+ }
99
+ /** Buyer side: the signature header value for one request, signed by the session key. */
100
+ async function sessionSignatureHeaderValue(input, signWithSessionKey) {
101
+ const message = sessionRequestMessage({ genesisHash: input.genesisHash, action: input.action, escrow: input.escrow, sequence: input.sequence, bodyHash: sessionBodyHash(input.body) });
102
+ return Buffer.from(await signWithSessionKey(new TextEncoder().encode(message))).toString('base64');
103
+ }
104
+ /**
105
+ * Provider side: checks that a session request is signed by a key the payer
106
+ * handed this session to. Returns the session key on success. `payer` and
107
+ * `escrow` come from the payment header (the lock check then confirms them on
108
+ * chain); `provider` is this provider's payee wallet; `genesisHash` is the
109
+ * genesis hash of the cluster this provider checked it is on; `body` is the raw
110
+ * request body exactly as received.
111
+ */
112
+ function verifySessionRequest(input) {
113
+ const parsed = parseSessionRequest(input);
114
+ if (!parsed.ok)
115
+ return parsed;
116
+ if (parsed.proof.kind !== 'signature') {
117
+ return { ok: false, reason: 'session_auth_invalid', message: 'This delegation is proved by a lock transaction memo, which this check cannot read. Use verifySessionRequestWithTransactions.' };
118
+ }
119
+ if (!(0, ed25519_1.ed25519Verify)(input.payer, new TextEncoder().encode(sessionDelegationMessage(parsed.delegation)), parsed.proof.signature)) {
120
+ return { ok: false, reason: 'session_auth_invalid', message: "The session delegation is not signed by the escrow's payer." };
121
+ }
122
+ return { ok: true, sessionKey: parsed.delegation.sessionKey, expiresAt: parsed.delegation.expiresAt };
123
+ }
124
+ /**
125
+ * Everything but the payer's consent: the delegation's shape, network,
126
+ * escrow, provider and expiry, and the session key's signature over this request.
127
+ */
128
+ function parseSessionRequest(input) {
129
+ const delegationValue = input.headers.get(exports.SESSION_DELEGATION_HEADER);
130
+ const signatureValue = input.headers.get(exports.SESSION_SIGNATURE_HEADER);
131
+ if (!delegationValue || !signatureValue) {
132
+ return { ok: false, reason: 'session_auth_required', message: `Paid requests must carry ${exports.SESSION_DELEGATION_HEADER} (the payer wallet's delegation to a session key) and ${exports.SESSION_SIGNATURE_HEADER} (that key's signature over this request).` };
133
+ }
134
+ const invalid = (message) => ({ ok: false, reason: 'session_auth_invalid', message });
135
+ const raw = (0, ed25519_1.decodeBase64)(delegationValue);
136
+ if (!raw)
137
+ return invalid('The session delegation is not base64.');
138
+ let parsed;
139
+ try {
140
+ const value = JSON.parse(raw.toString('utf8'));
141
+ if (!value || typeof value !== 'object' || Array.isArray(value))
142
+ return invalid('The session delegation is not an object.');
143
+ parsed = value;
144
+ }
145
+ catch {
146
+ return invalid('The session delegation is not JSON.');
147
+ }
148
+ if (typeof parsed.network !== 'string' || parsed.network.length === 0)
149
+ return invalid('The session delegation names no network. Sign a new one with this client version.');
150
+ if (parsed.network !== input.genesisHash)
151
+ return invalid('The session delegation was signed for another network.');
152
+ const escrow = (0, ed25519_1.publicKeyOf)(parsed.escrow);
153
+ const provider = (0, ed25519_1.publicKeyOf)(parsed.provider);
154
+ const sessionKey = (0, ed25519_1.publicKeyOf)(parsed.sessionKey);
155
+ const expiresAt = parsed.expiresAt;
156
+ let proof;
157
+ if (parsed.signature !== undefined && parsed.lockSignature !== undefined)
158
+ return invalid('A session delegation carries a signature or a lockSignature, not both.');
159
+ if (typeof parsed.signature === 'string') {
160
+ const signature = (0, ed25519_1.decodeBase64)(parsed.signature);
161
+ if (signature)
162
+ proof = { kind: 'signature', signature };
163
+ }
164
+ else if (typeof parsed.lockSignature === 'string' && TX_SIGNATURE.test(parsed.lockSignature)) {
165
+ proof = { kind: 'lock-memo', lockSignature: parsed.lockSignature };
166
+ }
167
+ if (!escrow || !provider || !sessionKey || typeof expiresAt !== 'number' || !Number.isSafeInteger(expiresAt) || !proof) {
168
+ return invalid('The session delegation needs escrow, provider, sessionKey, a whole-second expiresAt and a signature (or the lockSignature of a lock that carries its memo).');
169
+ }
170
+ if (!escrow.equals(input.escrow))
171
+ return invalid('The session delegation names another escrow.');
172
+ if (!provider.equals(input.provider))
173
+ return invalid('The session delegation names another provider.');
174
+ const nowSeconds = Math.floor(input.nowMs / 1000);
175
+ if (expiresAt <= nowSeconds)
176
+ return { ok: false, reason: 'session_auth_expired', message: 'The session delegation has expired. Sign a new one with the payer wallet.' };
177
+ if (expiresAt > nowSeconds + exports.MAX_SESSION_DELEGATION_SECONDS)
178
+ return invalid(`A session delegation may run for at most ${exports.MAX_SESSION_DELEGATION_SECONDS} seconds.`);
179
+ const delegation = { genesisHash: input.genesisHash, escrow: escrow.toBase58(), provider: provider.toBase58(), sessionKey: sessionKey.toBase58(), expiresAt };
180
+ const requestSignature = (0, ed25519_1.decodeBase64)(signatureValue);
181
+ const message = sessionRequestMessage({ genesisHash: input.genesisHash, action: input.action, escrow: delegation.escrow, sequence: input.sequence, bodyHash: sessionBodyHash(input.body) });
182
+ if (!requestSignature || !(0, ed25519_1.ed25519Verify)(sessionKey, new TextEncoder().encode(message), requestSignature)) {
183
+ return invalid('The request is not signed by the session key, or was changed after signing.');
184
+ }
185
+ return { ok: true, delegation, proof };
186
+ }
187
+ /**
188
+ * Buyer side, single metered call: both headers for one call on the lock
189
+ * `escrow`. With no `sessionKey`, the payer signs the request too (fine for a
190
+ * server-held keypair; a browser wallet would then sign twice, so pass a
191
+ * fresh key there and keep it for the call).
192
+ */
193
+ async function paidCallAuthHeaders(input) {
194
+ const key = input.sessionKey ?? { publicKey: input.payer, sign: input.signWithPayer };
195
+ const expiresAt = input.expiresAt ?? Math.floor((input.nowMs ?? Date.now()) / 1000) + 600;
196
+ return {
197
+ [exports.SESSION_DELEGATION_HEADER]: await sessionDelegationHeaderValue({ genesisHash: input.genesisHash, escrow: input.escrow, provider: input.provider, sessionKey: key.publicKey, expiresAt }, input.signWithPayer),
198
+ [exports.SESSION_SIGNATURE_HEADER]: await sessionSignatureHeaderValue({ genesisHash: input.genesisHash, action: 'single', escrow: input.escrow, sequence: 0, body: input.body }, key.sign),
199
+ };
200
+ }
201
+ /** Provider side, single metered call: `verifySessionRequest` with action `single` and sequence 0. */
202
+ function verifyPaidCallRequest(input) {
203
+ return verifySessionRequest({ ...input, action: 'single', sequence: 0 });
204
+ }
205
+ /*
206
+ * Transaction-bound delegation (#925, Solana Pay transaction requests).
207
+ *
208
+ * A Solana Pay transaction request lets a phone wallet sign a transaction our
209
+ * server builds, but it cannot sign a separate message. So the lock
210
+ * transaction itself carries the delegation: a Memo program instruction whose
211
+ * text is `reddi-session/2 delegate <sha256 hex of sessionDelegationMessage(d)>`
212
+ * (the message names the network's genesis hash, so the memo binds it too)
213
+ * and which names the payer as a required signer. The payer's signature on
214
+ * that transaction is then its consent to exactly that escrow, provider,
215
+ * session key and expiry, as a `signMessage` signature would be. The header
216
+ * carries `lockSignature` (the transaction signature) in place of `signature`.
217
+ *
218
+ * The provider checks: the transaction confirmed without error, the payer
219
+ * signed it, it holds that memo instruction with the payer among the memo's
220
+ * signers, and it touches the escrow account (so the memo travels with this
221
+ * lock and no other).
222
+ */
223
+ /** The SPL Memo program (v2), which fails unless every account it names has signed. */
224
+ exports.MEMO_PROGRAM_ID = new web3_js_1.PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');
225
+ exports.SESSION_DELEGATION_MEMO_PREFIX = 'reddi-session/2 delegate ';
226
+ const TX_SIGNATURE = /^[1-9A-HJ-NP-Za-km-z]{64,88}$/;
227
+ /** The memo text that binds a delegation to the transaction that carries it. */
228
+ function sessionDelegationMemo(d) {
229
+ return exports.SESSION_DELEGATION_MEMO_PREFIX + (0, crypto_1.createHash)('sha256').update(sessionDelegationMessage(d), 'utf8').digest('hex');
230
+ }
231
+ /** Buyer side: the memo instruction to add to the lock transaction, signed by the payer. */
232
+ function sessionDelegationMemoInstruction(d, payer) {
233
+ return new web3_js_1.TransactionInstruction({
234
+ programId: exports.MEMO_PROGRAM_ID,
235
+ keys: [{ pubkey: payer, isSigner: true, isWritable: false }],
236
+ data: Buffer.from(sessionDelegationMemo(d), 'utf8'),
237
+ });
238
+ }
239
+ /** Buyer side: the delegation header for a delegation proved by the confirmed lock transaction `lockSignature`. */
240
+ function lockBoundDelegationHeaderValue(d, lockSignature) {
241
+ if (!TX_SIGNATURE.test(lockSignature))
242
+ throw new Error('lockSignature must be a base58 transaction signature');
243
+ const { genesisHash, ...rest } = d;
244
+ return Buffer.from(JSON.stringify({ network: genesisHash, ...rest, lockSignature }), 'utf8').toString('base64');
245
+ }
246
+ /** A `TransactionFactsReader` over `Connection.getTransaction` at `confirmed`. */
247
+ function transactionFactsReader(connection, commitment = 'confirmed') {
248
+ return async (signature) => {
249
+ const tx = (await connection.getTransaction(signature, { commitment, maxSupportedTransactionVersion: 0 }));
250
+ if (!tx)
251
+ return null;
252
+ const message = tx.transaction.message;
253
+ const statics = (message.staticAccountKeys ?? message.accountKeys ?? []).map((k) => k.toBase58());
254
+ const loaded = tx.meta?.loadedAddresses ? [...tx.meta.loadedAddresses.writable, ...tx.meta.loadedAddresses.readonly].map((k) => k.toBase58()) : [];
255
+ const accounts = [...statics, ...loaded];
256
+ const compiled = message.compiledInstructions
257
+ ?? (message.instructions ?? []).map((ix) => ({ programIdIndex: ix.programIdIndex, accountKeyIndexes: ix.accounts, data: bs58Decode(ix.data) }));
258
+ const memos = compiled
259
+ .filter((ix) => accounts[ix.programIdIndex] === exports.MEMO_PROGRAM_ID.toBase58())
260
+ .map((ix) => ({ text: Buffer.from(ix.data).toString('utf8'), accounts: ix.accountKeyIndexes.map((i) => accounts[i] ?? '') }));
261
+ return {
262
+ failed: tx.meta === null || tx.meta.err !== null,
263
+ signers: statics.slice(0, message.header.numRequiredSignatures),
264
+ accounts,
265
+ memos,
266
+ ...(typeof tx.slot === 'number' ? { slot: BigInt(tx.slot) } : {}),
267
+ };
268
+ };
269
+ }
270
+ function bs58Decode(value) {
271
+ // Legacy messages carry instruction data as base58; PublicKey's decoder is not exported, so decode by hand.
272
+ const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
273
+ let n = BigInt(0);
274
+ for (const c of value) {
275
+ const i = ALPHABET.indexOf(c);
276
+ if (i < 0)
277
+ return new Uint8Array();
278
+ n = n * BigInt(58) + BigInt(i);
279
+ }
280
+ const bytes = [];
281
+ while (n > BigInt(0)) {
282
+ bytes.unshift(Number(n % BigInt(256)));
283
+ n /= BigInt(256);
284
+ }
285
+ for (const c of value) {
286
+ if (c !== '1')
287
+ break;
288
+ bytes.unshift(0);
289
+ }
290
+ return Uint8Array.from(bytes);
291
+ }
292
+ /**
293
+ * Provider side: `verifySessionRequest`, and also a delegation proved by the
294
+ * memo in its lock transaction. Without `readTransaction` a lock-bound
295
+ * delegation is refused. It may run before or after the lock check: either
296
+ * way the caller must still check the lock, which is what shows the escrow
297
+ * named here is this payer's lock.
298
+ *
299
+ * An escrow address can be used again once a lock ends. Pass the escrow's
300
+ * `created_slot` as `escrowCreatedSlot` to require that the lock transaction
301
+ * is the one that created this escrow. When the escrow is read later, compare
302
+ * the returned `lockSlot` with its `created_slot` instead.
303
+ */
304
+ async function verifySessionRequestWithTransactions(input) {
305
+ const parsed = parseSessionRequest(input);
306
+ if (!parsed.ok)
307
+ return parsed;
308
+ if (parsed.proof.kind === 'signature')
309
+ return verifySessionRequest(input);
310
+ const invalid = (message) => ({ ok: false, reason: 'session_auth_invalid', message });
311
+ if (!input.readTransaction)
312
+ return invalid('This provider does not take delegations proved by a lock transaction. Sign the delegation with the payer wallet.');
313
+ let facts;
314
+ try {
315
+ facts = await input.readTransaction(parsed.proof.lockSignature);
316
+ }
317
+ catch {
318
+ return { ok: false, reason: 'payment_check_unavailable', message: 'The chain could not be read. Nothing was accepted; present the same request again.' };
319
+ }
320
+ if (!facts)
321
+ return invalid('The lock transaction named by the delegation is not confirmed yet.');
322
+ if (facts.failed)
323
+ return invalid('The lock transaction named by the delegation failed.');
324
+ const payer = input.payer.toBase58();
325
+ if (!facts.signers.includes(payer))
326
+ return invalid("The lock transaction was not signed by the escrow's payer.");
327
+ if (!facts.accounts.includes(input.escrow.toBase58()))
328
+ return invalid('The lock transaction does not touch this escrow.');
329
+ const memo = sessionDelegationMemo(parsed.delegation);
330
+ if (!facts.memos.some((m) => m.text === memo && m.accounts.includes(payer))) {
331
+ return invalid('The lock transaction carries no memo for this delegation signed by the payer.');
332
+ }
333
+ if (input.escrowCreatedSlot !== undefined && facts.slot !== input.escrowCreatedSlot) {
334
+ return invalid('The lock transaction did not create this escrow: its slot does not match the escrow\'s created slot.');
335
+ }
336
+ return { ok: true, sessionKey: parsed.delegation.sessionKey, expiresAt: parsed.delegation.expiresAt, ...(facts.slot !== undefined ? { lockSlot: facts.slot } : {}) };
337
+ }
338
+ /** Provider side, single metered call: `verifySessionRequestWithTransactions` with action `single` and sequence 0. */
339
+ function verifyPaidCallRequestWithTransactions(input) {
340
+ return verifySessionRequestWithTransactions({ ...input, action: 'single', sequence: 0 });
341
+ }