@0to1pay/server-sdk 0.0.0-stage → 1.0.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.
@@ -0,0 +1,27 @@
1
+ export interface Ref {
2
+ $ref: string;
3
+ }
4
+ export interface ContractOperation {
5
+ operationId: string;
6
+ 'x-required-scope'?: string;
7
+ requestBody?: {
8
+ required?: boolean;
9
+ content: Record<string, {
10
+ schema: Ref;
11
+ }>;
12
+ };
13
+ parameters?: Ref[];
14
+ responses: Record<string, {
15
+ content?: Record<string, {
16
+ schema: Ref;
17
+ }>;
18
+ }>;
19
+ }
20
+ export declare const openapi: {
21
+ paths: Record<string, Partial<Record<"get" | "post", ContractOperation>>>;
22
+ components: {
23
+ schemas: Record<string, object>;
24
+ };
25
+ };
26
+ export declare function validateSchema(name: string, data: unknown): string | undefined;
27
+ export declare function check(ref: Ref | undefined, data: unknown): string | undefined;
@@ -0,0 +1,19 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import * as ajv2020 from 'ajv/dist/2020.js';
3
+ import * as formatModule from 'ajv-formats';
4
+ import { parse } from 'yaml';
5
+ export const openapi = parse(readFileSync(new URL('../../contracts/openapi.yaml', import.meta.url), 'utf8'));
6
+ const Ajv = ajv2020.default;
7
+ const formats = formatModule.default;
8
+ const ajv = new Ajv({ strict: false, allErrors: true });
9
+ formats(ajv);
10
+ ajv.addSchema({ $id: 'https://contracts.stablepay.invalid/v1', components: openapi.components });
11
+ export function validateSchema(name, data) {
12
+ const schema = ajv.getSchema('https://contracts.stablepay.invalid/v1#/components/schemas/' + name);
13
+ if (!schema)
14
+ throw new Error('Unknown OpenAPI schema ' + name);
15
+ return schema(data) ? undefined : ajv.errorsText(schema.errors);
16
+ }
17
+ export function check(ref, data) {
18
+ return ref?.$ref ? validateSchema(ref.$ref.split('/').at(-1), data) : undefined;
19
+ }
@@ -0,0 +1,184 @@
1
+ import type { components, operations } from './schema.js';
2
+ export type { components, operations, paths } from './schema.js';
3
+ export type Schema<K extends keyof components['schemas']> = components['schemas'][K];
4
+ type PrivateOperation = 'ingestProviderWebhook' | 'receiveStablePayEvent';
5
+ type OperationName = Exclude<keyof operations, PrivateOperation>;
6
+ type JsonContent<T> = T extends {
7
+ content: {
8
+ 'application/json': infer V;
9
+ };
10
+ } ? V : never;
11
+ type ParametersOf<K extends OperationName> = operations[K]['parameters'];
12
+ type RequiredPath<K extends OperationName> = ParametersOf<K> extends {
13
+ path: infer V;
14
+ } ? {
15
+ path: V;
16
+ } : {
17
+ path?: never;
18
+ };
19
+ type Body<K extends OperationName> = operations[K] extends {
20
+ requestBody: infer V;
21
+ } ? {
22
+ body: JsonContent<V>;
23
+ } : {
24
+ body?: never;
25
+ };
26
+ type Idempotency<K extends OperationName> = ParametersOf<K> extends {
27
+ header: {
28
+ 'Idempotency-Key': string;
29
+ };
30
+ } ? {
31
+ idempotencyKey: string;
32
+ } : {
33
+ idempotencyKey?: never;
34
+ };
35
+ type ResponseOf<K extends OperationName> = JsonContent<operations[K]['responses'][Extract<keyof operations[K]['responses'], 200 | 201 | 202>]>;
36
+ type OperationInput<K extends OperationName> = RequiredPath<K> & Body<K> & Idempotency<K> & {
37
+ query?: ParametersOf<K>['query'];
38
+ signal?: AbortSignal;
39
+ };
40
+ export declare class ZeroToOnePayError extends Error {
41
+ readonly status: number;
42
+ readonly code: string;
43
+ readonly requestId?: string | undefined;
44
+ readonly source = "stablepay";
45
+ constructor(status: number, code: string, requestId?: string | undefined);
46
+ }
47
+ export declare class ZeroToOnePayContractError extends Error {
48
+ readonly code: 'REQUEST_SCHEMA' | 'RESPONSE_SCHEMA' | 'UNRECOGNIZED_OPERATION';
49
+ constructor(code: 'REQUEST_SCHEMA' | 'RESPONSE_SCHEMA' | 'UNRECOGNIZED_OPERATION', detail: string);
50
+ }
51
+ export interface ZeroToOnePayClientOptions {
52
+ origin: string;
53
+ apiKey: string;
54
+ timeoutMs?: number;
55
+ fetch?: typeof globalThis.fetch;
56
+ }
57
+ export declare class ZeroToOnePayClient {
58
+ private readonly options;
59
+ private readonly origin;
60
+ private readonly request;
61
+ constructor(options: ZeroToOnePayClientOptions);
62
+ call<K extends OperationName>(operation: K, input: OperationInput<K>): Promise<ResponseOf<K>>;
63
+ createPayment(body: Schema<'CreatePayment'>, idempotencyKey: string): Promise<{
64
+ merchant_id: string;
65
+ project_id: string;
66
+ environment: components["schemas"]["Environment"];
67
+ payment_id: string;
68
+ order_ref: string;
69
+ order_revision: number;
70
+ customer_ref: string;
71
+ price: components["schemas"]["Money"];
72
+ allowed_connections: string[];
73
+ policy_ref: string;
74
+ lifecycle: "open" | "expired" | "canceled" | "closed";
75
+ funding_status: "unfunded" | "partial" | "funded" | "excess";
76
+ verification: components["schemas"]["Verification"];
77
+ decision: components["schemas"]["Decision"];
78
+ fulfillment: components["schemas"]["FulfillmentSummary"];
79
+ fulfillment_spec: components["schemas"]["FulfillmentSpec"];
80
+ adjustments: components["schemas"]["Adjustment"][];
81
+ expires_at: string;
82
+ created_at: string;
83
+ updated_at: string;
84
+ resource_version: number;
85
+ }>;
86
+ getPayment(payment_id: string): Promise<{
87
+ merchant_id: string;
88
+ project_id: string;
89
+ environment: components["schemas"]["Environment"];
90
+ payment_id: string;
91
+ order_ref: string;
92
+ order_revision: number;
93
+ customer_ref: string;
94
+ price: components["schemas"]["Money"];
95
+ allowed_connections: string[];
96
+ policy_ref: string;
97
+ lifecycle: "open" | "expired" | "canceled" | "closed";
98
+ funding_status: "unfunded" | "partial" | "funded" | "excess";
99
+ verification: components["schemas"]["Verification"];
100
+ decision: components["schemas"]["Decision"];
101
+ fulfillment: components["schemas"]["FulfillmentSummary"];
102
+ fulfillment_spec: components["schemas"]["FulfillmentSpec"];
103
+ adjustments: components["schemas"]["Adjustment"][];
104
+ expires_at: string;
105
+ created_at: string;
106
+ updated_at: string;
107
+ resource_version: number;
108
+ }>;
109
+ createQuote(payment_id: string, body: Schema<'CreateQuote'>, idempotencyKey: string): Promise<{
110
+ merchant_id: string;
111
+ project_id: string;
112
+ environment: components["schemas"]["Environment"];
113
+ quote_id: string;
114
+ payment_id: string;
115
+ connection_id: string;
116
+ pricing_revision: number;
117
+ payable: components["schemas"]["Money"];
118
+ chain?: components["schemas"]["ChainQuoteTerms"];
119
+ recipient_account: string;
120
+ pricing_terms_hash: string;
121
+ expires_at: string;
122
+ created_at: string;
123
+ }>;
124
+ createAttempt(payment_id: string, body: Schema<'CreateAttempt'>, idempotencyKey: string): Promise<{
125
+ attempt: components["schemas"]["Attempt"];
126
+ operation: components["schemas"]["Operation"] | null;
127
+ }>;
128
+ attachExternalAttempt(payment_id: string, body: Schema<'AttachExternalAttempt'>, idempotencyKey: string): Promise<{
129
+ merchant_id: string;
130
+ project_id: string;
131
+ environment: components["schemas"]["Environment"];
132
+ attempt_id: string;
133
+ payment_id: string;
134
+ quote_id: string;
135
+ connection_id: string;
136
+ mode: "managed" | "external";
137
+ execution_status: "created" | "requires_action" | "processing" | "unknown" | "succeeded" | "failed" | "canceled";
138
+ operation_id: string | null;
139
+ external_resources: components["schemas"]["ExternalResource"][];
140
+ binding: components["schemas"]["Binding"];
141
+ next_action: components["schemas"]["NextAction"];
142
+ created_at: string;
143
+ updated_at: string;
144
+ resource_version: number;
145
+ }>;
146
+ claimFulfillment(command_id: string, body: Schema<'ClaimRequest'>, idempotencyKey: string): Promise<{
147
+ claim_id: string;
148
+ command_id: string;
149
+ execution_id: string;
150
+ decision: "execute" | "superseded" | "blocked" | "review_required" | "expired";
151
+ valid: boolean;
152
+ generation: number;
153
+ decision_version: number;
154
+ desired_version: number;
155
+ issued_at: string;
156
+ expires_at: string;
157
+ reason_codes: string[];
158
+ }>;
159
+ reportFulfillmentResult(command_id: string, body: Schema<'FulfillmentResultInput'>, idempotencyKey: string): Promise<{
160
+ result_id: string;
161
+ command_id: string;
162
+ execution_id: string;
163
+ result: "applied" | "noop" | "failed" | "unknown";
164
+ reason_code: string | null;
165
+ applied_version: number | null;
166
+ effect_reference: string | null;
167
+ applied_at: string | null;
168
+ received_at: string;
169
+ review_required: boolean;
170
+ reason_codes: string[];
171
+ } & ({
172
+ applied_version?: null;
173
+ effect_reference?: null;
174
+ applied_at?: null;
175
+ } | {
176
+ applied_version?: number;
177
+ effect_reference?: string;
178
+ applied_at?: string;
179
+ })>;
180
+ }
181
+ export { recipientProofMessage, type RecipientProof } from './recipient-proof.js';
182
+ export { solanaRecipientProofMessage } from './solana-recipient-proof.js';
183
+ export { tronRecipientProofMessage } from './tron-recipient-proof.js';
184
+ export { ZeroToOnePayClient as PaymentToFulfillmentClient, ZeroToOnePayContractError as PaymentToFulfillmentContractError, ZeroToOnePayError as PaymentToFulfillmentError, type ZeroToOnePayClientOptions as PaymentToFulfillmentClientOptions, };
@@ -0,0 +1,160 @@
1
+ import { openapi, validateSchema } from '../domain/contract.js';
2
+ const spec = openapi;
3
+ const operationsByName = new Map();
4
+ for (const [path, item] of Object.entries(spec.paths)) {
5
+ for (const method of ['get', 'post']) {
6
+ const route = item[method];
7
+ if (!route?.operationId)
8
+ continue;
9
+ operationsByName.set(route.operationId, {
10
+ path, method, route, parameters: [...(item.parameters ?? []), ...(route.parameters ?? [])],
11
+ });
12
+ }
13
+ }
14
+ const keyPattern = /^[A-Za-z0-9._:-]{16,128}$/;
15
+ export class ZeroToOnePayError extends Error {
16
+ status;
17
+ code;
18
+ requestId;
19
+ source = 'stablepay';
20
+ constructor(status, code, requestId) {
21
+ super(`0to1Pay request failed (${status} ${code})`);
22
+ this.status = status;
23
+ this.code = code;
24
+ this.requestId = requestId;
25
+ this.name = 'ZeroToOnePayError';
26
+ }
27
+ }
28
+ export class ZeroToOnePayContractError extends Error {
29
+ code;
30
+ constructor(code, detail) {
31
+ super(detail);
32
+ this.code = code;
33
+ this.name = 'ZeroToOnePayContractError';
34
+ }
35
+ }
36
+ function checked(schema, value, code) {
37
+ if (!schema?.$ref?.startsWith('#/components/schemas/')) {
38
+ throw new ZeroToOnePayContractError(code, '0to1Pay schema reference is unavailable');
39
+ }
40
+ const message = validateSchema(schema.$ref.slice('#/components/schemas/'.length), value);
41
+ if (message)
42
+ throw new ZeroToOnePayContractError(code, message);
43
+ }
44
+ export class ZeroToOnePayClient {
45
+ options;
46
+ origin;
47
+ request;
48
+ constructor(options) {
49
+ this.options = options;
50
+ this.origin = new URL(options.origin);
51
+ const loopback = ['127.0.0.1', 'localhost', '[::1]'].includes(this.origin.hostname);
52
+ if ((this.origin.protocol !== 'https:' && !(loopback && this.origin.protocol === 'http:')) ||
53
+ this.origin.username || this.origin.password || this.origin.pathname !== '/' ||
54
+ this.origin.search || this.origin.hash) {
55
+ throw new Error('Invalid 0to1Pay API origin');
56
+ }
57
+ if (!options.apiKey || /\s/.test(options.apiKey))
58
+ throw new Error('Missing or invalid 0to1Pay server key');
59
+ this.request = options.fetch ?? globalThis.fetch;
60
+ }
61
+ async call(operation, input) {
62
+ const endpoint = operationsByName.get(operation);
63
+ if (!endpoint)
64
+ throw new ZeroToOnePayContractError('UNRECOGNIZED_OPERATION', 'Unknown 0to1Pay operation');
65
+ const { method, path, route, parameters } = endpoint;
66
+ const inputPath = input.path;
67
+ const inputQuery = input.query;
68
+ const consumedQuery = new Set();
69
+ for (const parameterSource of parameters) {
70
+ const parameter = parameterSource.$ref
71
+ ? spec.components.parameters[parameterSource.$ref.split('/').at(-1) ?? '']
72
+ : parameterSource;
73
+ if (!parameter?.name)
74
+ continue;
75
+ const value = parameter.in === 'path' ? inputPath?.[parameter.name]
76
+ : parameter.in === 'query' ? inputQuery?.[parameter.name]
77
+ : parameter.name === 'Idempotency-Key' ? input.idempotencyKey : undefined;
78
+ if (parameter.in === 'query' && value !== undefined)
79
+ consumedQuery.add(parameter.name);
80
+ if (value === undefined && !parameter.required)
81
+ continue;
82
+ const { schema } = parameter;
83
+ if (value === undefined || (schema?.format === 'uuid' &&
84
+ (typeof value !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value))) ||
85
+ (schema?.type === 'integer' && (!Number.isSafeInteger(value) ||
86
+ Number(value) < Number(schema.minimum ?? Number.MIN_SAFE_INTEGER) ||
87
+ Number(value) > Number(schema.maximum ?? Number.MAX_SAFE_INTEGER))) ||
88
+ (schema?.type === 'string' && (typeof value !== 'string' ||
89
+ value.length < Number(schema.minLength ?? 0) || value.length > Number(schema.maxLength ?? Infinity) ||
90
+ (typeof schema.pattern === 'string' && !new RegExp(schema.pattern).test(value)) ||
91
+ (Array.isArray(schema.enum) && !schema.enum.includes(value))))) {
92
+ throw new ZeroToOnePayContractError('REQUEST_SCHEMA', `Invalid ${parameter.name}`);
93
+ }
94
+ }
95
+ const url = new URL(`/v1${path.replace(/\{([^}]+)\}/g, (_, name) => encodeURIComponent(inputPath?.[name] ?? ''))}`, this.origin);
96
+ for (const name of consumedQuery)
97
+ url.searchParams.set(name, String(inputQuery?.[name]));
98
+ const headers = { accept: 'application/json', authorization: `Bearer ${this.options.apiKey}` };
99
+ if (input.idempotencyKey) {
100
+ if (!keyPattern.test(input.idempotencyKey))
101
+ throw new ZeroToOnePayContractError('REQUEST_SCHEMA', 'Invalid Idempotency-Key');
102
+ headers['idempotency-key'] = input.idempotencyKey;
103
+ }
104
+ let body;
105
+ if (route.requestBody) {
106
+ checked(route.requestBody.content?.['application/json']?.schema, input.body, 'REQUEST_SCHEMA');
107
+ headers['content-type'] = 'application/json';
108
+ body = JSON.stringify(input.body);
109
+ }
110
+ const timeout = AbortSignal.timeout(this.options.timeoutMs ?? 15_000);
111
+ const response = await this.request(url, {
112
+ method, headers, body, redirect: 'error',
113
+ signal: input.signal ? AbortSignal.any([timeout, input.signal]) : timeout,
114
+ });
115
+ let payload;
116
+ try {
117
+ payload = await response.json();
118
+ }
119
+ catch {
120
+ if (!response.ok)
121
+ throw new ZeroToOnePayError(response.status, 'UPSTREAM_NON_JSON');
122
+ throw new ZeroToOnePayContractError('RESPONSE_SCHEMA', '0to1Pay returned an invalid JSON response');
123
+ }
124
+ if (!response.ok) {
125
+ if (validateSchema('Error', payload))
126
+ throw new ZeroToOnePayError(response.status, 'UPSTREAM_ERROR');
127
+ const { error } = payload;
128
+ const code = /^[A-Z0-9_]{1,128}$/.test(error.code) ? error.code : 'UPSTREAM_ERROR';
129
+ throw new ZeroToOnePayError(response.status, code, error.request_id);
130
+ }
131
+ checked(route.responses[String(response.status)]?.content?.['application/json']?.schema, payload, 'RESPONSE_SCHEMA');
132
+ return payload;
133
+ }
134
+ createPayment(body, idempotencyKey) {
135
+ return this.call('createPayment', { body, idempotencyKey });
136
+ }
137
+ getPayment(payment_id) {
138
+ return this.call('getPayment', { path: { payment_id } });
139
+ }
140
+ createQuote(payment_id, body, idempotencyKey) {
141
+ return this.call('createQuote', { path: { payment_id }, body, idempotencyKey });
142
+ }
143
+ createAttempt(payment_id, body, idempotencyKey) {
144
+ return this.call('createAttempt', { path: { payment_id }, body, idempotencyKey });
145
+ }
146
+ attachExternalAttempt(payment_id, body, idempotencyKey) {
147
+ return this.call('attachExternalAttempt', { path: { payment_id }, body, idempotencyKey });
148
+ }
149
+ claimFulfillment(command_id, body, idempotencyKey) {
150
+ return this.call('claimFulfillment', { path: { command_id }, body, idempotencyKey });
151
+ }
152
+ reportFulfillmentResult(command_id, body, idempotencyKey) {
153
+ return this.call('reportFulfillmentResult', { path: { command_id }, body, idempotencyKey });
154
+ }
155
+ }
156
+ export { recipientProofMessage } from './recipient-proof.js';
157
+ export { solanaRecipientProofMessage } from './solana-recipient-proof.js';
158
+ export { tronRecipientProofMessage } from './tron-recipient-proof.js';
159
+ // Keep the SDK exports used by existing merchant integrations.
160
+ export { ZeroToOnePayClient as PaymentToFulfillmentClient, ZeroToOnePayContractError as PaymentToFulfillmentContractError, ZeroToOnePayError as PaymentToFulfillmentError, };
@@ -0,0 +1,10 @@
1
+ export interface RecipientProof {
2
+ origin: string;
3
+ merchant_id: string;
4
+ project_id: string;
5
+ environment: 'test' | 'live';
6
+ connection_id: string;
7
+ chain_id: number;
8
+ address: string;
9
+ }
10
+ export declare function recipientProofMessage(input: RecipientProof): string;
@@ -0,0 +1,24 @@
1
+ const ethereumAddress = /^0x[0-9a-f]{40}$/i;
2
+ const zeroAddress = /^0x0{40}$/i;
3
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
4
+ export function recipientProofMessage(input) {
5
+ const origin = new URL(input.origin);
6
+ if (!['https:', 'http:'].includes(origin.protocol) || origin.origin !== input.origin ||
7
+ ![input.merchant_id, input.project_id, input.connection_id].every(value => uuid.test(value)) ||
8
+ !['test', 'live'].includes(input.environment) || !Number.isSafeInteger(input.chain_id) || input.chain_id <= 0 ||
9
+ !ethereumAddress.test(input.address) || zeroAddress.test(input.address)) {
10
+ throw new Error('INVALID_RECIPIENT_PROOF_SCOPE');
11
+ }
12
+ return [
13
+ 'StablePay recipient registration v1',
14
+ 'I authorize the use of this address for one order on this StablePay connection.',
15
+ '',
16
+ 'Origin: ' + origin.origin,
17
+ 'Merchant: ' + input.merchant_id.toLowerCase(),
18
+ 'Project: ' + input.project_id.toLowerCase(),
19
+ 'Environment: ' + input.environment,
20
+ 'Connection: ' + input.connection_id.toLowerCase(),
21
+ 'Chain: eip155:' + input.chain_id,
22
+ 'Address: ' + input.address.toLowerCase(),
23
+ ].join('\n');
24
+ }