@0to1pay/fulfillment-sdk 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,45 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import canonicalizeModule from 'canonicalize';
3
+ export const id = randomUUID;
4
+ export const iso = (value) => new Date(value).toISOString();
5
+ export const now = () => new Date().toISOString();
6
+ export const canonical = (value) => {
7
+ const stringify = canonicalizeModule;
8
+ const result = stringify(value);
9
+ if (result === undefined)
10
+ throw new Error('Unable to canonicalize JSON');
11
+ return result;
12
+ };
13
+ export const sha = (bytes) => createHash('sha256').update(bytes).digest();
14
+ export const digest = (value) => sha(canonical(value));
15
+ export const scope = (value) => ({
16
+ merchant_id: value.merchant_id, project_id: value.project_id, environment: value.environment,
17
+ });
18
+ export const params = (value) => [value.merchant_id, value.project_id, value.environment];
19
+ export const SCOPE = 'merchant_id=$1 AND project_id=$2 AND environment=$3';
20
+ export const money = (asset, amount, scale) => ({ asset, amount_atomic: amount, scale });
21
+ export class ApiError extends Error {
22
+ status;
23
+ code;
24
+ constructor(status, code, message = code) {
25
+ super(message);
26
+ this.status = status;
27
+ this.code = code;
28
+ }
29
+ }
30
+ export function requireValue(value, code = 'NOT_FOUND') {
31
+ if (value === undefined || value === null)
32
+ throw new ApiError(404, code, 'Resource not found');
33
+ return value;
34
+ }
35
+ export function requireCondition(condition, status, code, message) {
36
+ if (!condition)
37
+ throw new ApiError(status, code, message);
38
+ }
39
+ export const conflict = (condition, code = 'RESOURCE_CONFLICT') => requireCondition(condition, 409, code);
40
+ export const invalid = (condition, code = 'INVALID_REQUEST') => requireCondition(condition, 400, code);
41
+ export const ASSETS = new Map([['fiat:USD', 2], ['fiat:EUR', 2], ['fiat:GBP', 2], ['fiat:CAD', 2], ['fiat:AUD', 2], ['fiat:JPY', 0]]);
42
+ export const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
43
+ export function isChainProvider(provider) {
44
+ return provider === 'evm' || provider === 'solana' || provider === 'tron';
45
+ }
@@ -0,0 +1,59 @@
1
+ CREATE TABLE IF NOT EXISTS merchant_event_inbox (
2
+ event_id uuid PRIMARY KEY,
3
+ delivery_id uuid NOT NULL,
4
+ body_hash text NOT NULL CHECK (body_hash ~ '^[0-9a-f]{64}$'),
5
+ raw_body bytea NOT NULL,
6
+ received_at timestamptz NOT NULL DEFAULT now()
7
+ );
8
+
9
+ CREATE TABLE IF NOT EXISTS merchant_commands (
10
+ command_id uuid PRIMARY KEY,
11
+ event_id uuid NOT NULL REFERENCES merchant_event_inbox(event_id),
12
+ command_hash text NOT NULL CHECK (command_hash ~ '^[0-9a-f]{64}$'),
13
+ command jsonb NOT NULL,
14
+ execution_id uuid,
15
+ instance_id text,
16
+ lease_token uuid,
17
+ lease_until timestamptz,
18
+ processing_state text NOT NULL DEFAULT 'pending' CHECK (processing_state IN ('pending','complete','exhausted')),
19
+ failure_count integer NOT NULL DEFAULT 0,
20
+ next_check_at timestamptz NOT NULL DEFAULT now(),
21
+ result jsonb,
22
+ completed_at timestamptz,
23
+ CHECK ((execution_id IS NULL) = (instance_id IS NULL)),
24
+ CHECK ((lease_token IS NULL) = (lease_until IS NULL))
25
+ );
26
+
27
+ CREATE INDEX IF NOT EXISTS merchant_commands_due ON merchant_commands(next_check_at)
28
+ WHERE processing_state = 'pending';
29
+
30
+ CREATE TABLE IF NOT EXISTS merchant_fulfillment_resources (
31
+ grant_key uuid PRIMARY KEY,
32
+ merchant_id uuid NOT NULL,
33
+ project_id uuid NOT NULL,
34
+ environment text NOT NULL CHECK (environment IN ('test','live')),
35
+ order_ref text NOT NULL,
36
+ action_ref text NOT NULL,
37
+ target_ref text NOT NULL,
38
+ last_applied_version bigint NOT NULL DEFAULT 0 CHECK (last_applied_version >= 0),
39
+ first_grant jsonb,
40
+ UNIQUE (merchant_id, project_id, environment, order_ref, action_ref)
41
+ );
42
+
43
+ CREATE TABLE IF NOT EXISTS merchant_result_outbox (
44
+ command_id uuid NOT NULL REFERENCES merchant_commands(command_id),
45
+ execution_id uuid PRIMARY KEY,
46
+ payload jsonb NOT NULL,
47
+ resume_command boolean NOT NULL DEFAULT false,
48
+ delivery_state text NOT NULL DEFAULT 'pending' CHECK (delivery_state IN ('pending','delivered','exhausted')),
49
+ next_check_at timestamptz NOT NULL DEFAULT now(),
50
+ lease_token uuid,
51
+ lease_until timestamptz,
52
+ failure_count integer NOT NULL DEFAULT 0,
53
+ platform_receipt_id uuid,
54
+ delivered_at timestamptz,
55
+ CHECK ((lease_token IS NULL) = (lease_until IS NULL))
56
+ );
57
+
58
+ CREATE INDEX IF NOT EXISTS merchant_results_due ON merchant_result_outbox(next_check_at)
59
+ WHERE delivery_state = 'pending';
@@ -0,0 +1,4 @@
1
+ export { DeliveryError, canonicalJson, parseStrictJson, sameScope, sha256, signWebhook, verifyDelivery } from './signature.js';
2
+ export type { DeliveryOptions, DeliveryScope, EventEnvelope, FulfillmentCommand, HeaderMap, WebhookKey } from './signature.js';
3
+ export { FulfillmentInbox, FulfillmentWorker, migrateFulfillmentInbox, transaction } from './postgres.js';
4
+ export type { Effect, EffectCallback, EffectMetadata, FulfillmentWorkerOptions } from './postgres.js';
@@ -0,0 +1,2 @@
1
+ export { DeliveryError, canonicalJson, parseStrictJson, sameScope, sha256, signWebhook, verifyDelivery } from './signature.js';
2
+ export { FulfillmentInbox, FulfillmentWorker, migrateFulfillmentInbox, transaction } from './postgres.js';
@@ -0,0 +1,69 @@
1
+ import type { Pool, PoolClient } from 'pg';
2
+ import type { ZeroToOnePayClient } from '../server-sdk/index.js';
3
+ import { type DeliveryOptions, type FulfillmentCommand, type HeaderMap } from './signature.js';
4
+ export declare function transaction<T>(pool: Pool, fn: (tx: PoolClient) => Promise<T>): Promise<T>;
5
+ export declare function migrateFulfillmentInbox(pool: Pool): Promise<void>;
6
+ export declare function migrateMerchantSchema(pool: Pool, migration: string, file: URL): Promise<void>;
7
+ export declare class FulfillmentInbox {
8
+ private readonly pool;
9
+ private readonly options;
10
+ constructor(pool: Pool, options: DeliveryOptions);
11
+ receive(raw: Buffer, headers: HeaderMap): Promise<{
12
+ duplicate: boolean;
13
+ eventId: string;
14
+ commandId: string | null;
15
+ }>;
16
+ }
17
+ export type EffectMetadata = {
18
+ applied_version: number;
19
+ effect_reference: string;
20
+ applied_at: string;
21
+ };
22
+ export type Effect = ({
23
+ result: 'applied';
24
+ } & EffectMetadata) | {
25
+ result: 'noop';
26
+ reason_code: string;
27
+ } | ({
28
+ result: 'noop';
29
+ reason_code: 'ALREADY_APPLIED';
30
+ } & EffectMetadata) | {
31
+ result: 'failed';
32
+ error_code: string;
33
+ error_message?: string;
34
+ } | {
35
+ result: 'unknown';
36
+ error_code?: string;
37
+ error_message?: string;
38
+ };
39
+ export type EffectCallback = (tx: PoolClient, command: FulfillmentCommand) => Promise<Effect>;
40
+ export type FulfillmentWorkerOptions = {
41
+ pool: Pool;
42
+ client: Pick<ZeroToOnePayClient, 'claimFulfillment' | 'reportFulfillmentResult'>;
43
+ apply: EffectCallback;
44
+ instanceId?: string;
45
+ leaseMs?: number;
46
+ maxRetries?: number;
47
+ renewExpiredTransactionalClaims?: boolean;
48
+ hooks?: {
49
+ afterClaim?: (command: FulfillmentCommand) => Promise<void>;
50
+ afterEffectCommit?: (commandId: string) => Promise<void>;
51
+ };
52
+ };
53
+ export declare class FulfillmentWorker {
54
+ private readonly config;
55
+ private readonly instanceId;
56
+ private readonly leaseMs;
57
+ private readonly maxRetries;
58
+ constructor(config: FulfillmentWorkerOptions);
59
+ processCommand(): Promise<boolean>;
60
+ private recordEffect;
61
+ private applyEffect;
62
+ private retryCommand;
63
+ deliverResult(): Promise<boolean>;
64
+ private isTerminal;
65
+ tick(): Promise<{
66
+ command: boolean;
67
+ receipt: boolean;
68
+ }>;
69
+ }
@@ -0,0 +1,247 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { validateSchema } from '../domain/contract.js';
4
+ import { canonicalJson, DeliveryError, sha256, verifyDelivery } from './signature.js';
5
+ export async function transaction(pool, fn) {
6
+ const tx = await pool.connect();
7
+ try {
8
+ await tx.query('BEGIN');
9
+ const result = await fn(tx);
10
+ await tx.query('COMMIT');
11
+ return result;
12
+ }
13
+ catch (error) {
14
+ await tx.query('ROLLBACK').catch(() => undefined);
15
+ throw error;
16
+ }
17
+ finally {
18
+ tx.release();
19
+ }
20
+ }
21
+ export async function migrateFulfillmentInbox(pool) {
22
+ await migrateMerchantSchema(pool, 'fulfillment-sdk/inbox/001', new URL('./inbox.sql', import.meta.url));
23
+ }
24
+ export async function migrateMerchantSchema(pool, migration, file) {
25
+ const sql = await readFile(file, 'utf8');
26
+ const checksum = sha256(sql);
27
+ await transaction(pool, async (tx) => {
28
+ await tx.query("SELECT pg_advisory_xact_lock(hashtext('stablepay-merchant-migrations'),hashtext(current_schema()))");
29
+ await tx.query(`CREATE TABLE IF NOT EXISTS merchant_schema_migrations (
30
+ migration text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT now())`);
31
+ const applied = await tx.query('SELECT checksum FROM merchant_schema_migrations WHERE migration=$1', [migration]);
32
+ if (applied.rows[0]) {
33
+ if (applied.rows[0].checksum !== checksum)
34
+ throw new Error(`Merchant migration has changed: ${migration}`);
35
+ return;
36
+ }
37
+ await tx.query(sql);
38
+ await tx.query('INSERT INTO merchant_schema_migrations(migration,checksum) VALUES($1,$2)', [migration, checksum]);
39
+ });
40
+ }
41
+ function commandHash(command) {
42
+ const { delivery_status: _delivery, execution_status: _execution, updated_at: _updated, ...immutable } = command;
43
+ return sha256(canonicalJson(immutable));
44
+ }
45
+ export class FulfillmentInbox {
46
+ pool;
47
+ options;
48
+ constructor(pool, options) {
49
+ this.pool = pool;
50
+ this.options = options;
51
+ }
52
+ async receive(raw, headers) {
53
+ const { event, command, bodyHash, deliveryId } = verifyDelivery(raw, headers, this.options);
54
+ return transaction(this.pool, async (tx) => {
55
+ const inserted = await tx.query(`INSERT INTO merchant_event_inbox(event_id,delivery_id,body_hash,raw_body)
56
+ VALUES($1,$2,$3,$4) ON CONFLICT (event_id) DO NOTHING`, [event.event_id, deliveryId, bodyHash, raw]);
57
+ if (!inserted.rowCount) {
58
+ const existing = await tx.query('SELECT body_hash FROM merchant_event_inbox WHERE event_id=$1', [event.event_id]);
59
+ if (existing.rows[0]?.body_hash !== bodyHash)
60
+ throw new DeliveryError(409, 'EVENT_ID_CONFLICT');
61
+ return { duplicate: true, eventId: event.event_id, commandId: command?.command_id ?? null };
62
+ }
63
+ if (command) {
64
+ const digest = commandHash(command);
65
+ const added = await tx.query(`INSERT INTO merchant_commands(command_id,event_id,command_hash,command)
66
+ VALUES($1,$2,$3,$4) ON CONFLICT (command_id) DO NOTHING`, [command.command_id, event.event_id, digest, command]);
67
+ if (!added.rowCount) {
68
+ const existing = await tx.query('SELECT command_hash FROM merchant_commands WHERE command_id=$1', [command.command_id]);
69
+ if (existing.rows[0]?.command_hash !== digest)
70
+ throw new DeliveryError(409, 'COMMAND_ID_CONFLICT');
71
+ }
72
+ }
73
+ return { duplicate: false, eventId: event.event_id, commandId: command?.command_id ?? null };
74
+ });
75
+ }
76
+ }
77
+ const delayMs = (failures) => Math.min(500 * 2 ** Math.min(failures, 7), 60_000);
78
+ export class FulfillmentWorker {
79
+ config;
80
+ instanceId;
81
+ leaseMs;
82
+ maxRetries;
83
+ constructor(config) {
84
+ this.config = config;
85
+ this.instanceId = config.instanceId ?? `merchant-${randomUUID()}`;
86
+ this.leaseMs = config.leaseMs ?? 30_000;
87
+ this.maxRetries = config.maxRetries ?? 16;
88
+ }
89
+ async processCommand() {
90
+ const { pool, client, hooks } = this.config;
91
+ const leased = await pool.query(`WITH next AS (
92
+ SELECT command_id FROM merchant_commands
93
+ WHERE processing_state='pending' AND next_check_at <= now() AND (lease_until IS NULL OR lease_until <= now())
94
+ ORDER BY next_check_at,command_id LIMIT 1 FOR UPDATE SKIP LOCKED
95
+ ) UPDATE merchant_commands AS c SET lease_token=$1, lease_until=now()+$2*interval '1 ms',
96
+ execution_id=COALESCE(c.execution_id,$3), instance_id=COALESCE(c.instance_id,$4)
97
+ FROM next WHERE c.command_id=next.command_id
98
+ RETURNING c.command_id,c.command,c.execution_id,c.instance_id,c.lease_token,c.failure_count`, [randomUUID(), this.leaseMs, randomUUID(), this.instanceId]);
99
+ const job = leased.rows[0];
100
+ if (!job)
101
+ return false;
102
+ let claim;
103
+ let committed = false;
104
+ try {
105
+ claim = await client.claimFulfillment(job.command_id, {
106
+ execution_id: job.execution_id,
107
+ expected_desired_version: job.command.desired_version,
108
+ instance_id: job.instance_id,
109
+ }, `claim:${job.execution_id}`);
110
+ if (claim.command_id !== job.command_id || claim.execution_id !== job.execution_id)
111
+ throw new Error('Claim identity changed');
112
+ await hooks?.afterClaim?.(job.command);
113
+ if (claim.decision === 'expired' || (claim.valid && Date.parse(claim.expires_at) <= Date.now())) {
114
+ throw new ClaimExpired();
115
+ }
116
+ const activeClaim = claim;
117
+ committed = await this.recordEffect(job, activeClaim, async (tx) => {
118
+ const permitted = activeClaim.valid && activeClaim.decision === 'execute' && activeClaim.desired_version === job.command.desired_version;
119
+ if (activeClaim.decision === 'execute' && !permitted)
120
+ throw new Error('Claim version changed');
121
+ return permitted ? this.applyEffect(tx, job.command, Date.parse(activeClaim.expires_at))
122
+ : { result: 'noop', reason_code: activeClaim.decision.toUpperCase() };
123
+ });
124
+ }
125
+ catch (error) {
126
+ if (claim && error instanceof ClaimExpired) {
127
+ const canRenew = this.config.renewExpiredTransactionalClaims === true;
128
+ committed = await this.recordEffect(job, claim, async () => canRenew
129
+ ? { result: 'failed', error_code: 'CLAIM_EXPIRED_WITHOUT_EFFECT' }
130
+ : { result: 'unknown', error_code: 'CLAIM_EXPIRED' }, canRenew);
131
+ }
132
+ else {
133
+ await this.retryCommand(job, error);
134
+ }
135
+ }
136
+ if (committed)
137
+ await hooks?.afterEffectCommit?.(job.command_id);
138
+ return true;
139
+ }
140
+ async recordEffect(job, claim, effect, resume = false) {
141
+ return transaction(this.config.pool, async (tx) => {
142
+ const locked = await tx.query(`SELECT command_id FROM merchant_commands
143
+ WHERE command_id=$1 AND lease_token=$2 AND lease_until > clock_timestamp() AND processing_state='pending' FOR UPDATE`, [job.command_id, job.lease_token]);
144
+ if (!locked.rowCount)
145
+ return false;
146
+ const payload = {
147
+ execution_id: job.execution_id,
148
+ claim_id: claim.claim_id,
149
+ lease_generation: claim.generation,
150
+ ...await effect(tx),
151
+ };
152
+ const schemaError = validateSchema('FulfillmentResultInput', payload);
153
+ if (schemaError)
154
+ throw new Error(`Invalid fulfillment effect: ${schemaError}`);
155
+ await tx.query(`UPDATE merchant_commands SET processing_state='complete',result=$2,completed_at=now(),
156
+ lease_token=NULL,lease_until=NULL WHERE command_id=$1`, [job.command_id, payload]);
157
+ await tx.query(`INSERT INTO merchant_result_outbox(command_id,execution_id,payload,resume_command) VALUES($1,$2,$3,$4)`, [job.command_id, job.execution_id, payload, resume]);
158
+ return true;
159
+ });
160
+ }
161
+ async applyEffect(tx, command, expiresAt) {
162
+ await tx.query(`INSERT INTO merchant_fulfillment_resources(grant_key,merchant_id,project_id,environment,order_ref,action_ref,target_ref)
163
+ VALUES($1,$2,$3,$4,$5,$6,$7) ON CONFLICT DO NOTHING`, [command.grant_key, command.merchant_id, command.project_id,
164
+ command.environment, command.order_ref, command.action_ref, command.target_ref]);
165
+ const result = await tx.query(`SELECT * FROM merchant_fulfillment_resources WHERE grant_key=$1 FOR UPDATE`, [command.grant_key]);
166
+ const resource = result.rows[0];
167
+ if (!resource || resource.merchant_id !== command.merchant_id || resource.project_id !== command.project_id ||
168
+ resource.environment !== command.environment || resource.order_ref !== command.order_ref ||
169
+ resource.action_ref !== command.action_ref || resource.target_ref !== command.target_ref) {
170
+ return { result: 'failed', error_code: 'GRANT_IDENTITY_MISMATCH' };
171
+ }
172
+ if (command.kind === 'grant' && resource.first_grant?.applied_version === command.desired_version &&
173
+ Number(resource.last_applied_version) === command.desired_version) {
174
+ return { result: 'noop', reason_code: 'ALREADY_APPLIED', ...resource.first_grant };
175
+ }
176
+ if (Number(resource.last_applied_version) >= command.desired_version)
177
+ return { result: 'noop', reason_code: 'SUPERSEDED' };
178
+ if (command.kind === 'grant' && resource.first_grant)
179
+ return { result: 'noop', reason_code: 'ALREADY_APPLIED' };
180
+ if (Date.now() >= expiresAt)
181
+ throw new ClaimExpired();
182
+ const effect = await this.config.apply(tx, command);
183
+ if (effect.result === 'applied' && effect.applied_version !== command.desired_version)
184
+ throw new Error('Effect version changed');
185
+ if (effect.result === 'applied' || (effect.result === 'noop' && effect.reason_code === 'NO_EFFECT_REQUIRED')) {
186
+ const firstGrant = effect.result === 'applied' && command.kind === 'grant' ? {
187
+ applied_version: effect.applied_version,
188
+ effect_reference: effect.effect_reference,
189
+ applied_at: effect.applied_at,
190
+ } : null;
191
+ await tx.query(`UPDATE merchant_fulfillment_resources SET last_applied_version=$2, first_grant=COALESCE(first_grant,$3)
192
+ WHERE grant_key=$1`, [command.grant_key, command.desired_version, firstGrant]);
193
+ }
194
+ return effect;
195
+ }
196
+ async retryCommand(job, error) {
197
+ const exhausted = this.isTerminal(error, job.failure_count);
198
+ await this.config.pool.query(`UPDATE merchant_commands SET failure_count=failure_count+1,
199
+ processing_state=$3,next_check_at=now()+$4*interval '1 ms',lease_token=NULL,lease_until=NULL
200
+ WHERE command_id=$1 AND lease_token=$2`, [job.command_id, job.lease_token, exhausted ? 'exhausted' : 'pending',
201
+ delayMs(job.failure_count)]);
202
+ }
203
+ async deliverResult() {
204
+ const { pool, client } = this.config;
205
+ const leased = await pool.query(`WITH next AS (
206
+ SELECT execution_id FROM merchant_result_outbox
207
+ WHERE delivery_state='pending' AND next_check_at<=now() AND (lease_until IS NULL OR lease_until<=now())
208
+ ORDER BY next_check_at,execution_id LIMIT 1 FOR UPDATE SKIP LOCKED
209
+ ) UPDATE merchant_result_outbox AS r SET lease_token=$1,lease_until=now()+$2*interval '1 ms'
210
+ FROM next WHERE r.execution_id=next.execution_id
211
+ RETURNING r.command_id,r.execution_id,r.payload,r.lease_token,r.failure_count,r.resume_command`, [randomUUID(), this.leaseMs]);
212
+ const job = leased.rows[0];
213
+ if (!job)
214
+ return false;
215
+ try {
216
+ const receipt = await client.reportFulfillmentResult(job.command_id, job.payload, `result:${job.execution_id}`);
217
+ if (receipt.command_id !== job.command_id || receipt.execution_id !== job.execution_id)
218
+ throw new Error('Receipt identity changed');
219
+ await transaction(pool, async (tx) => {
220
+ const delivered = await tx.query(`UPDATE merchant_result_outbox SET delivery_state='delivered',platform_receipt_id=$3,
221
+ delivered_at=now(),lease_token=NULL,lease_until=NULL WHERE execution_id=$1 AND lease_token=$2`, [job.execution_id, job.lease_token, receipt.result_id]);
222
+ if (job.resume_command && delivered.rowCount && job.failure_count < this.maxRetries) {
223
+ await tx.query(`UPDATE merchant_commands SET processing_state='pending',execution_id=NULL,instance_id=NULL,
224
+ result=NULL,completed_at=NULL,failure_count=failure_count+1,next_check_at=now()+interval '500 ms'
225
+ WHERE command_id=$1 AND execution_id=$2 AND processing_state='complete' AND failure_count<$3`, [job.command_id, job.execution_id, this.maxRetries]);
226
+ }
227
+ });
228
+ }
229
+ catch (error) {
230
+ await pool.query(`UPDATE merchant_result_outbox SET failure_count=failure_count+1,delivery_state=$3,
231
+ next_check_at=now()+$4*interval '1 ms',lease_token=NULL,lease_until=NULL WHERE execution_id=$1 AND lease_token=$2`, [job.execution_id, job.lease_token, this.isTerminal(error, job.failure_count) ? 'exhausted' : 'pending', delayMs(job.failure_count)]);
232
+ }
233
+ return true;
234
+ }
235
+ isTerminal(error, failures) {
236
+ const upstream = error;
237
+ return failures + 1 >= this.maxRetries || (upstream?.source === 'stablepay' &&
238
+ typeof upstream.status === 'number' && [400, 401, 403, 404, 409].includes(upstream.status));
239
+ }
240
+ async tick() {
241
+ const command = await this.processCommand();
242
+ const receipt = await this.deliverResult();
243
+ return { command, receipt };
244
+ }
245
+ }
246
+ class ClaimExpired extends Error {
247
+ }
@@ -0,0 +1,37 @@
1
+ import type { Schema } from '../server-sdk/index.js';
2
+ export type EventEnvelope = Schema<'EventEnvelope'>;
3
+ export type FulfillmentCommand = Schema<'FulfillmentCommand'>;
4
+ export type DeliveryScope = Pick<EventEnvelope, 'merchant_id' | 'project_id' | 'environment'>;
5
+ export type HeaderMap = Record<string, string | string[] | undefined>;
6
+ export type WebhookKey = {
7
+ secret: Buffer;
8
+ acceptUntil?: number;
9
+ };
10
+ export type DeliveryOptions = {
11
+ scope: DeliveryScope;
12
+ keys: ReadonlyMap<string, WebhookKey>;
13
+ now?: () => number;
14
+ toleranceSeconds?: number;
15
+ maxBodyBytes?: number;
16
+ };
17
+ export declare class DeliveryError extends Error {
18
+ readonly status: number;
19
+ readonly code: string;
20
+ constructor(status: number, code: string);
21
+ }
22
+ export declare const sha256: (value: string | Buffer) => string;
23
+ export declare function canonicalJson(value: unknown): string;
24
+ export declare function parseStrictJson(raw: Buffer): unknown;
25
+ export declare function signWebhook(raw: Buffer, eventId: string, deliveryId: string, timestamp: number, keyId: string, secret: Buffer): {
26
+ 'Content-Type': string;
27
+ 'StablePay-Event-Id': string;
28
+ 'StablePay-Delivery-Id': string;
29
+ 'StablePay-Signature': string;
30
+ };
31
+ export declare function sameScope(scope: DeliveryScope, resource: DeliveryScope): boolean;
32
+ export declare function verifyDelivery(raw: Buffer, headers: HeaderMap, options: DeliveryOptions): {
33
+ event: EventEnvelope;
34
+ command: FulfillmentCommand | null;
35
+ bodyHash: string;
36
+ deliveryId: string;
37
+ };
@@ -0,0 +1,150 @@
1
+ import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
2
+ import { parseTree } from 'jsonc-parser';
3
+ import { validateSchema } from '../domain/contract.js';
4
+ import { canonical } from '../domain/shared.js';
5
+ export class DeliveryError extends Error {
6
+ status;
7
+ code;
8
+ constructor(status, code) {
9
+ super(code);
10
+ this.status = status;
11
+ this.code = code;
12
+ this.name = 'DeliveryError';
13
+ }
14
+ }
15
+ const uuid = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;
16
+ const keyIdPattern = /^[A-Za-z0-9._:-]{1,128}$/;
17
+ const signaturePattern = /^t=(0|[1-9][0-9]{0,14}),kid=([A-Za-z0-9._:-]{1,128}),v1=([0-9a-f]{64})$/;
18
+ const loneSurrogate = /[\uD800-\uDFFF]/u;
19
+ const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
20
+ export const sha256 = (value) => createHash('sha256').update(value).digest('hex');
21
+ function validJson(value, depth = 0) {
22
+ if (depth > 64)
23
+ throw new Error('JSON nesting exceeds the supported limit');
24
+ if (typeof value === 'number' && (!Number.isFinite(value) || (Number.isInteger(value) && !Number.isSafeInteger(value)))) {
25
+ throw new Error('JSON numeric value cannot be represented safely');
26
+ }
27
+ if (typeof value === 'string' && loneSurrogate.test(value))
28
+ throw new Error('Invalid Unicode');
29
+ if (value === null || typeof value === 'boolean' || typeof value === 'string' || typeof value === 'number')
30
+ return;
31
+ if (Array.isArray(value)) {
32
+ for (const item of value)
33
+ validJson(item, depth + 1);
34
+ return;
35
+ }
36
+ if (!value || typeof value !== 'object' || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) {
37
+ throw new Error('Invalid JSON value');
38
+ }
39
+ for (const [key, item] of Object.entries(value)) {
40
+ if (loneSurrogate.test(key))
41
+ throw new Error('Invalid Unicode');
42
+ validJson(item, depth + 1);
43
+ }
44
+ }
45
+ export function canonicalJson(value) {
46
+ validJson(value);
47
+ return canonical(value);
48
+ }
49
+ function assertUniqueProperties(node, depth = 0) {
50
+ if (depth > 64)
51
+ throw new Error('JSON nesting exceeds the supported limit');
52
+ if (node.type === 'object') {
53
+ const known = new Set();
54
+ for (const element of node.children ?? []) {
55
+ const [keyNode, valueNode] = element.children ?? [];
56
+ if (!keyNode || !valueNode || typeof keyNode.value !== 'string' || known.has(keyNode.value)) {
57
+ throw new Error('Duplicate or invalid JSON field');
58
+ }
59
+ known.add(keyNode.value);
60
+ assertUniqueProperties(valueNode, depth + 1);
61
+ }
62
+ }
63
+ else if (node.type === 'array') {
64
+ for (const child of node.children ?? [])
65
+ assertUniqueProperties(child, depth + 1);
66
+ }
67
+ }
68
+ export function parseStrictJson(raw) {
69
+ const decoded = decoder.decode(raw);
70
+ const value = JSON.parse(decoded);
71
+ const errors = [];
72
+ const tree = parseTree(decoded, errors, { disallowComments: true, allowTrailingComma: false });
73
+ if (!tree || errors.length)
74
+ throw new Error('Invalid JSON');
75
+ assertUniqueProperties(tree);
76
+ validJson(value);
77
+ return value;
78
+ }
79
+ function signatureDigest(raw, eventId, deliveryId, timestamp, secret) {
80
+ return createHmac('sha256', secret)
81
+ .update(`stablepay.webhook.v1\n${eventId}\n${deliveryId}\n${timestamp}\n`, 'utf8')
82
+ .update(raw)
83
+ .digest();
84
+ }
85
+ export function signWebhook(raw, eventId, deliveryId, timestamp, keyId, secret) {
86
+ if (!uuid.test(eventId) || !uuid.test(deliveryId) || !Number.isSafeInteger(timestamp) || timestamp < 0 ||
87
+ !keyIdPattern.test(keyId) || secret.length < 32)
88
+ throw new Error('Invalid signing parameters');
89
+ const digest = signatureDigest(raw, eventId, deliveryId, String(timestamp), secret).toString('hex');
90
+ return {
91
+ 'Content-Type': 'application/json',
92
+ 'StablePay-Event-Id': eventId,
93
+ 'StablePay-Delivery-Id': deliveryId,
94
+ 'StablePay-Signature': `t=${timestamp},kid=${keyId},v1=${digest}`,
95
+ };
96
+ }
97
+ function header(headers, expected) {
98
+ const matches = Object.entries(headers).filter(([name]) => name.toLowerCase() === expected);
99
+ if (matches.length !== 1 || typeof matches[0]?.[1] !== 'string')
100
+ throw new DeliveryError(400, 'INVALID_DELIVERY_HEADERS');
101
+ return matches[0][1];
102
+ }
103
+ export function sameScope(scope, resource) {
104
+ return scope.merchant_id === resource.merchant_id && scope.project_id === resource.project_id && scope.environment === resource.environment;
105
+ }
106
+ export function verifyDelivery(raw, headers, options) {
107
+ if (raw.length < 1 || raw.length > (options.maxBodyBytes ?? 1_048_576))
108
+ throw new DeliveryError(413, 'INVALID_DELIVERY_SIZE');
109
+ if (!/^application\/json(?:\s*;\s*charset\s*=\s*utf-8)?$/i.test(header(headers, 'content-type'))) {
110
+ throw new DeliveryError(415, 'INVALID_DELIVERY_TYPE');
111
+ }
112
+ const eventId = header(headers, 'stablepay-event-id');
113
+ const deliveryId = header(headers, 'stablepay-delivery-id');
114
+ const signature = header(headers, 'stablepay-signature');
115
+ if (!uuid.test(eventId) || !uuid.test(deliveryId) || signature.length > 225)
116
+ throw new DeliveryError(400, 'INVALID_DELIVERY_HEADERS');
117
+ const values = signaturePattern.exec(signature);
118
+ if (!values?.[1] || !values[2] || !values[3])
119
+ throw new DeliveryError(401, 'INVALID_SIGNATURE');
120
+ const [, timestamp, keyId, digest] = values;
121
+ const now = options.now?.() ?? Math.floor(Date.now() / 1_000);
122
+ const key = options.keys.get(keyId);
123
+ if (!key || key.secret.length < 32 || (key.acceptUntil !== undefined && now >= key.acceptUntil) ||
124
+ Math.abs(now - Number(timestamp)) > (options.toleranceSeconds ?? 300))
125
+ throw new DeliveryError(401, 'INVALID_SIGNATURE');
126
+ if (!timingSafeEqual(signatureDigest(raw, eventId, deliveryId, timestamp, key.secret), Buffer.from(digest, 'hex'))) {
127
+ throw new DeliveryError(401, 'INVALID_SIGNATURE');
128
+ }
129
+ let value;
130
+ try {
131
+ value = parseStrictJson(raw);
132
+ }
133
+ catch {
134
+ throw new DeliveryError(400, 'INVALID_DELIVERY_BODY');
135
+ }
136
+ if (validateSchema('EventEnvelope', value))
137
+ throw new DeliveryError(400, 'INVALID_DELIVERY_BODY');
138
+ const event = value;
139
+ if (eventId !== event.event_id || !sameScope(options.scope, event))
140
+ throw new DeliveryError(403, 'DELIVERY_SCOPE_MISMATCH');
141
+ if (event.type !== 'fulfillment.requested' || event.data.kind !== 'fulfillment_command') {
142
+ return { event, command: null, bodyHash: sha256(raw), deliveryId };
143
+ }
144
+ const { command } = event.data;
145
+ if (!sameScope(options.scope, command) || command.command_id !== event.resource_id ||
146
+ sha256(canonicalJson(command.payload)) !== command.payload_hash) {
147
+ throw new DeliveryError(403, 'COMMAND_SCOPE_OR_HASH_MISMATCH');
148
+ }
149
+ return { event, command, bodyHash: sha256(raw), deliveryId };
150
+ }