@siglume/direct-request-payment 0.3.5 → 0.3.6
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.
- package/CHANGELOG.md +45 -0
- package/README.md +55 -31
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/docs/announcement-ja.md +27 -6
- package/docs/api-reference.md +6 -3
- package/docs/merchant-quickstart.md +11 -6
- package/docs/pricing.md +98 -15
- package/docs/security.md +10 -5
- package/examples/express-checkout.ts +4 -2
- package/examples/setup-merchant.ts +9 -1
- package/package.json +8 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,50 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.6 - 2026-06-18
|
|
4
|
+
|
|
5
|
+
Documentation and public-surface cleanup release. No wire-format or API changes;
|
|
6
|
+
challenges and clients from 0.3.x interoperate unchanged.
|
|
7
|
+
|
|
8
|
+
- Documented the Micro / Nano **settlement schedule** in the README and the
|
|
9
|
+
pricing guide: Micro settles weekly, Nano settles monthly, with the closing
|
|
10
|
+
period, timezone, revenue-recognition point, retry / carry-over, and
|
|
11
|
+
rejected / no-charge behavior spelled out. The exact close time, default
|
|
12
|
+
timezone, and settlement lag are marked platform-managed — the platform
|
|
13
|
+
response is the source of truth.
|
|
14
|
+
- Clarified that Micro / Nano provider revenue stays unsettled until the weekly /
|
|
15
|
+
monthly on-chain settlement succeeds, that failed settlements are retried and
|
|
16
|
+
may go past due, and that Siglume does not advance, guarantee, or insure unpaid
|
|
17
|
+
amounts.
|
|
18
|
+
- Reframed the docs as a standalone SDRP payment SDK. Internal implementation
|
|
19
|
+
language was removed from the public surface: the legacy `external_402` mode
|
|
20
|
+
value and the `free` Launch-tier key are now isolated in a single
|
|
21
|
+
"Compatibility Notes" section, and internal batch / ledger terms were dropped.
|
|
22
|
+
- Hardened the examples: they no longer print returned secrets (`setup.env`) and
|
|
23
|
+
no longer return raw `error.message` to the client.
|
|
24
|
+
- Removed `external-402` from the npm / PyPI keywords; added `sdrp`,
|
|
25
|
+
`direct-request-payment`, `micropayments`, `metered-billing`, `jpyc`, `usdc`.
|
|
26
|
+
- Hardened `.gitignore` (`.env`, `.env.*`, `.npmrc`, `.pypirc`, `.venv/`,
|
|
27
|
+
`coverage/`) and removed a developer-specific path from `RELEASING.md`.
|
|
28
|
+
|
|
29
|
+
## 0.3.5 - 2026-06-18
|
|
30
|
+
|
|
31
|
+
- Docs: protocol-first README framing for the SDRP Direct Request Payment SDK.
|
|
32
|
+
|
|
33
|
+
## 0.3.4 - 2026-06-18
|
|
34
|
+
|
|
35
|
+
- Docs: clarified the SDRP pricing structure — a Standard plan is selected, and
|
|
36
|
+
Micro / Nano are applied automatically by amount — across the README and
|
|
37
|
+
pricing guide.
|
|
38
|
+
|
|
39
|
+
## 0.3.3 - 2026-06-18
|
|
40
|
+
|
|
41
|
+
- Docs: SDRP direct-payment framing across the README, API reference, merchant
|
|
42
|
+
quickstart, pricing, and security guides.
|
|
43
|
+
|
|
44
|
+
## 0.3.2 - 2026-06-18
|
|
45
|
+
|
|
46
|
+
- Docs: documented the SDRP Micro / Nano amount-band boundaries.
|
|
47
|
+
|
|
3
48
|
## 0.3.1 - 2026-06-12
|
|
4
49
|
|
|
5
50
|
- Docs: scheduled autopay (`cadence: "daily"`) is documented as an approval
|
package/README.md
CHANGED
|
@@ -5,24 +5,15 @@
|
|
|
5
5
|
|
|
6
6
|
## Protocol Overview
|
|
7
7
|
|
|
8
|
-
Siglume Direct Request Payment is
|
|
9
|
-
want to accept Siglume wallet payments. The merchant fixes the order,
|
|
10
|
-
and currency on its server; the buyer pays with a Siglume wallet;
|
|
11
|
-
applies the correct pricing and settlement path from the payment amount
|
|
12
|
-
execution conditions.
|
|
13
|
-
|
|
14
|
-
During merchant setup, only the **Standard Payment plan** is selected. Micro
|
|
15
|
-
Payment and Nano Payment are not separate choices for the merchant or buyer.
|
|
16
|
-
They are applied automatically by amount.
|
|
8
|
+
Siglume Direct Request Payment (SDRP) is a wallet payment protocol for products
|
|
9
|
+
that want to accept Siglume wallet payments. The merchant fixes the order,
|
|
10
|
+
amount, and currency on its server; the buyer pays with a Siglume wallet;
|
|
11
|
+
Siglume applies the correct pricing and settlement path from the payment amount.
|
|
17
12
|
|
|
18
13
|
Use this package when an external EC site, booking service, membership service,
|
|
19
14
|
or paid API wants to accept Siglume wallet payments without taking custody of
|
|
20
|
-
customer funds.
|
|
21
|
-
|
|
22
|
-
Micro Payment or Nano Payment.
|
|
23
|
-
|
|
24
|
-
The current platform payload still uses the internal mode name `external_402`;
|
|
25
|
-
this SDK sets that value for you when creating a payment requirement.
|
|
15
|
+
customer funds. The SDK creates and verifies one-time and recurring wallet
|
|
16
|
+
payments; it does not hold customer funds or wallets.
|
|
26
17
|
|
|
27
18
|
Payment requirement creation must run in the authenticated buyer's Siglume
|
|
28
19
|
context. Your merchant server must not use a merchant secret or API key to
|
|
@@ -34,7 +25,27 @@ token for setup. `DirectRequestPaymentClient` requires the buyer's Siglume
|
|
|
34
25
|
bearer token for payment requirements. Do not use a Developer Portal `cli_` API
|
|
35
26
|
key with this package.
|
|
36
27
|
|
|
37
|
-
|
|
28
|
+
## Amount-Based Pricing and Settlement
|
|
29
|
+
|
|
30
|
+
Pricing has one structure: you choose a **Standard Payment** plan once during
|
|
31
|
+
setup, and after that the applied fee and the settlement timing follow the
|
|
32
|
+
**payment amount** automatically. There is nothing else to choose.
|
|
33
|
+
|
|
34
|
+
- **Standard Payment** — most payments. Your selected plan's percentage fee,
|
|
35
|
+
settled on-chain immediately after each payment confirms.
|
|
36
|
+
- **Micro Payment** — small payments, applied automatically by amount. A flat
|
|
37
|
+
per-transaction protocol fee, **settled weekly**.
|
|
38
|
+
- **Nano Payment** — very small payments, applied automatically by amount. A
|
|
39
|
+
flat per-usage protocol fee, **settled monthly**.
|
|
40
|
+
|
|
41
|
+
Micro Payment and Nano Payment are not separate products you opt into; they are
|
|
42
|
+
amount bands Siglume applies on your behalf. Your integration code is the same
|
|
43
|
+
regardless of which band a payment falls into. The full fee table and the exact
|
|
44
|
+
weekly / monthly settlement schedule are in [docs/pricing.md](./docs/pricing.md).
|
|
45
|
+
Provider revenue in the Micro and Nano bands is not settled revenue until the
|
|
46
|
+
weekly or monthly on-chain settlement succeeds. Siglume keeps outstanding failed
|
|
47
|
+
settlements for retry under the published policy, but does not advance or
|
|
48
|
+
guarantee provider revenue before settlement succeeds.
|
|
38
49
|
|
|
39
50
|
## What This SDK Covers
|
|
40
51
|
|
|
@@ -78,15 +89,15 @@ amounts differ.
|
|
|
78
89
|
|
|
79
90
|
| Payment amount | Applied automatically | What you select | Fee | Settlement |
|
|
80
91
|
| --- | --- | --- | --- | --- |
|
|
81
|
-
| Over JPY 500 / over USD 3.00, or whenever immediate finality is required | Standard Payment | Select one Standard plan: Launch, Starter, Growth, or Pro | Launch: JPY 0 / USD 0 monthly, 1.8%; Starter: JPY 980 / USD 6 monthly, 1.0%; Growth: JPY 2,980 / USD 18 monthly, 0.7%; Pro: JPY 9,800 / USD 60 monthly, 0.5%. Minimum JPY 30 / USD 0.20 per payment. |
|
|
82
|
-
| JPY 50-500 / about USD 0.30-3.00 | Micro Payment |
|
|
83
|
-
| Under JPY 1 to JPY 49 / under USD 0.01 to about USD 0.30 | Nano Payment |
|
|
92
|
+
| Over JPY 500 / over USD 3.00, or whenever immediate finality is required | Standard Payment | Select one Standard plan: Launch, Starter, Growth, or Pro | Launch: JPY 0 / USD 0 monthly, 1.8%; Starter: JPY 980 / USD 6 monthly, 1.0%; Growth: JPY 2,980 / USD 18 monthly, 0.7%; Pro: JPY 9,800 / USD 60 monthly, 0.5%. Minimum JPY 30 / USD 0.20 per payment. | Settled on-chain immediately after the payment confirms |
|
|
93
|
+
| JPY 50-500 / about USD 0.30-3.00 | Micro Payment | Applied automatically by amount | USD 0.01 / Tx, about JPY 2 | Weekly settlement — see [Settlement schedule](./docs/pricing.md#settlement-schedule) |
|
|
94
|
+
| Under JPY 1 to JPY 49 / under USD 0.01 to about USD 0.30 | Nano Payment | Applied automatically by amount | USD 0.001 / usage, about JPY 0.2 | Monthly settlement — see [Settlement schedule](./docs/pricing.md#settlement-schedule) |
|
|
84
95
|
|
|
85
96
|
A merchant billing mandate is required before accepting payments, even on the
|
|
86
|
-
Launch plan.
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
97
|
+
Launch plan. `fee_bps` returned on a payment requirement is the authoritative
|
|
98
|
+
fee rate for that payment in the merchant's settlement currency. The full fee
|
|
99
|
+
table and the weekly / monthly settlement schedule live in
|
|
100
|
+
[docs/pricing.md](./docs/pricing.md).
|
|
90
101
|
|
|
91
102
|
## Merchant Setup: One SDK Call
|
|
92
103
|
|
|
@@ -110,12 +121,12 @@ const setup = await merchant.setupCheckout({
|
|
|
110
121
|
max_amount_minor: 100000,
|
|
111
122
|
});
|
|
112
123
|
|
|
113
|
-
|
|
114
|
-
//
|
|
115
|
-
//
|
|
116
|
-
//
|
|
117
|
-
//
|
|
118
|
-
|
|
124
|
+
// setup.env holds the merchant key plus the challenge and webhook secrets:
|
|
125
|
+
// SIGLUME_DIRECT_PAYMENT_MERCHANT (not secret)
|
|
126
|
+
// SIGLUME_DIRECT_PAYMENT_CHALLENGE_SECRET (secret)
|
|
127
|
+
// SIGLUME_WEBHOOK_SECRET (secret)
|
|
128
|
+
// Write these to your server-side secret store. Do NOT log the secret values.
|
|
129
|
+
console.log(`Configured merchant: ${setup.env.SIGLUME_DIRECT_PAYMENT_MERCHANT}`);
|
|
119
130
|
```
|
|
120
131
|
|
|
121
132
|
```py
|
|
@@ -136,7 +147,9 @@ setup = merchant.setup_checkout(
|
|
|
136
147
|
max_amount_minor=100000,
|
|
137
148
|
)
|
|
138
149
|
|
|
139
|
-
|
|
150
|
+
# setup["env"] holds the merchant key plus the challenge and webhook secrets.
|
|
151
|
+
# Persist them to your server-side secret store; do not log the secret values.
|
|
152
|
+
print("Configured merchant:", setup["env"]["SIGLUME_DIRECT_PAYMENT_MERCHANT"])
|
|
140
153
|
```
|
|
141
154
|
|
|
142
155
|
Store returned secrets on the merchant server. `challenge_secret` and
|
|
@@ -289,7 +302,8 @@ const recurring = await createDirectRequestPaymentRecurringChallenge({
|
|
|
289
302
|
// POST /v1/sdrp/direct-payments/subscriptions
|
|
290
303
|
// { merchant, amount_minor, currency, cadence: "monthly", challenge }
|
|
291
304
|
// For scheduled autopay, the buyer instead creates a scheduled auto-pay
|
|
292
|
-
// authorization
|
|
305
|
+
// authorization and hands you the schedule_token; your scheduler triggers
|
|
306
|
+
// each occurrence with that token.
|
|
293
307
|
```
|
|
294
308
|
|
|
295
309
|
```py
|
|
@@ -383,6 +397,16 @@ Read [docs/security.md](./docs/security.md) before going live.
|
|
|
383
397
|
- Fulfill orders only from verified webhook data, with idempotency.
|
|
384
398
|
- Treat `fee_bps` returned by Siglume as the runtime fee source of truth.
|
|
385
399
|
|
|
400
|
+
## Compatibility Notes
|
|
401
|
+
|
|
402
|
+
- The Direct Request Payment HTTP endpoints live under
|
|
403
|
+
`/v1/sdrp/direct-payments/...`; the SDK targets them for you.
|
|
404
|
+
- For wire compatibility the platform still tags these payments with the legacy
|
|
405
|
+
mode value `external_402`, and the merchant registry may still expose the
|
|
406
|
+
legacy billing-plan key `free` for the Launch tier. The SDK sets and reads
|
|
407
|
+
these values for you — treat them as compatibility identifiers, not public
|
|
408
|
+
product names.
|
|
409
|
+
|
|
386
410
|
## Documentation
|
|
387
411
|
|
|
388
412
|
- [Merchant quickstart](./docs/merchant-quickstart.md)
|
package/dist/index.cjs
CHANGED
|
@@ -125,7 +125,7 @@ var DirectRequestPaymentClient = class {
|
|
|
125
125
|
this.auth_token = authToken;
|
|
126
126
|
this.base_url = (options.base_url ?? envValue("SIGLUME_API_BASE") ?? DEFAULT_SIGLUME_API_BASE).replace(/\/+$/, "");
|
|
127
127
|
this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15e3));
|
|
128
|
-
this.user_agent = options.user_agent ?? "@siglume/direct-request-payment/0.3.
|
|
128
|
+
this.user_agent = options.user_agent ?? "@siglume/direct-request-payment/0.3.6";
|
|
129
129
|
this.fetch_impl = fetchImpl;
|
|
130
130
|
}
|
|
131
131
|
async createPaymentRequirement(input) {
|
|
@@ -230,7 +230,7 @@ var DirectRequestPaymentMerchantClient = class {
|
|
|
230
230
|
this.auth_token = authToken;
|
|
231
231
|
this.base_url = (options.base_url ?? envValue("SIGLUME_API_BASE") ?? DEFAULT_SIGLUME_API_BASE).replace(/\/+$/, "");
|
|
232
232
|
this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15e3));
|
|
233
|
-
this.user_agent = options.user_agent ?? "@siglume/direct-request-payment/0.3.
|
|
233
|
+
this.user_agent = options.user_agent ?? "@siglume/direct-request-payment/0.3.6";
|
|
234
234
|
this.fetch_impl = fetchImpl;
|
|
235
235
|
}
|
|
236
236
|
async setupMerchant(input) {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export const DEFAULT_SIGLUME_API_BASE = \"https://siglume.com/v1\";\nexport const DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME = \"siglume-external-402-v1\";\n// Recurring (subscription / scheduled autopay) approval uses a DISTINCT scheme\n// with cadence bound into the HMAC, so a one-time checkout challenge can never\n// be replayed as a recurring authorization and vice versa.\nexport const DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME = \"siglume-external-402-recurring-v1\";\nexport const DIRECT_REQUEST_PAYMENT_MODE = \"external_402\";\nexport const DIRECT_REQUEST_PAYMENT_RECEIPT_KIND = \"sdrp_direct_payment\";\nexport const DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND = \"sdrp_direct_payment_allowance\";\nexport const DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE = \"sdrp_direct_payment_requirement\";\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;\n\nexport type DirectRequestPaymentCurrency = \"JPY\" | \"USD\";\nexport type DirectRequestPaymentToken = \"JPYC\" | \"USDC\";\n\nexport interface DirectRequestPaymentChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface ParsedDirectRequestPaymentChallenge {\n scheme: string;\n nonce: string;\n signature: string;\n}\n\n/** \"monthly\" authorizes a Siglume-swept subscription; \"daily\" authorizes\n * merchant-triggered scheduled autopay. It is an approval tag, not a\n * run-count limiter. */\nexport type DirectRequestPaymentRecurringCadence = \"monthly\" | \"daily\";\n\nexport interface DirectRequestPaymentRecurringChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentRecurringChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n cadence: DirectRequestPaymentRecurringCadence;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface Web3TransactionRequest {\n network?: string;\n chain_id?: number;\n from?: string;\n to?: string;\n data?: string;\n value?: string | number;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectPaymentRequirement {\n direct_payment_requirement_id: string;\n requirement_id: string;\n id: string;\n mode: string;\n merchant?: string | null;\n challenge_hash?: string | null;\n buyer_user_id: string;\n agent_id?: string | null;\n product_listing_id: string;\n listing_id: string;\n access_grant_id?: string | null;\n capability_key: string;\n requirement_hash: string;\n request_hash: string;\n siglume_signature: string;\n token_symbol: string;\n currency: string;\n amount_minor: number;\n fee_bps: number;\n status: string;\n expires_at?: string | null;\n confirmed_at?: string | null;\n spent_at?: string | null;\n chain_receipt_id?: string | null;\n transaction_request: Web3TransactionRequest;\n approve_transaction_request?: Web3TransactionRequest | null;\n buyer_confirmation?: string | null;\n non_custodial: boolean;\n metadata_jsonb?: Record<string, unknown>;\n created_at?: string | null;\n updated_at?: string | null;\n}\n\nexport interface DirectPaymentRequirementCreateInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n token_symbol?: DirectRequestPaymentToken | string;\n allowance_amount_minor?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectPaymentVerifyInput {\n receipt_id?: string | null;\n chain_receipt_id?: string | null;\n await_finality?: boolean;\n await_required_status?: string | null;\n await_timeout_seconds?: number;\n await_poll_seconds?: number;\n}\n\nexport interface Web3PreparedTransactionExecutePayload {\n transaction_request: Web3TransactionRequest;\n receipt_kind: string;\n reference_type: typeof DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE;\n reference_id: string;\n metadata?: Record<string, unknown>;\n await_finality?: boolean;\n}\n\nexport interface Web3PreparedTransactionExecuteResult {\n receipt?: Record<string, unknown>;\n finalization?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentClientOptions {\n auth_token?: string;\n base_url?: string;\n fetch?: typeof fetch;\n timeout_ms?: number;\n user_agent?: string;\n}\n\nexport type DirectRequestPaymentBillingPlan = \"launch\" | \"free\" | \"starter\" | \"growth\" | \"pro\";\n\nexport interface DirectRequestPaymentMerchantAccount {\n merchant_account_id: string;\n merchant: string;\n merchant_user_id: string;\n user_wallet_id?: string | null;\n billing_mandate_id?: string | null;\n display_name?: string | null;\n status?: string | null;\n billing_status?: string | null;\n billing_plan?: string | null;\n billing_currency?: string | null;\n token_symbol?: string | null;\n monthly_fee_minor?: number | null;\n settlement_fee_bps?: number | null;\n settlement_fee_min_minor?: number | null;\n included_monthly_payments?: number | null;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentMerchantSetupInput {\n merchant: string;\n display_name?: string;\n billing_plan?: DirectRequestPaymentBillingPlan | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n allowed_currencies?: Record<string, string> | Array<DirectRequestPaymentCurrency | string>;\n webhook_callback_url?: string;\n billing_mandate_cap_minor?: number;\n max_amount_minor?: number;\n}\n\nexport interface DirectRequestPaymentMerchantBillingMandateInput {\n currency?: DirectRequestPaymentCurrency | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n max_amount_minor?: number;\n}\n\nexport interface DirectRequestPaymentMerchantResponse {\n merchant_account: DirectRequestPaymentMerchantAccount;\n challenge_secret?: string | null;\n challenge_secret_created?: boolean;\n created?: boolean | null;\n listing_id?: string | null;\n mandate?: Record<string, unknown> | null;\n next_steps?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscriptionInput {\n callback_url: string;\n description?: string;\n event_types?: string[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscription {\n webhook_subscription_id?: string;\n subscription_id?: string;\n id?: string;\n callback_url?: string;\n signing_secret?: string;\n status?: string;\n event_types?: string[];\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupInput extends DirectRequestPaymentMerchantSetupInput {\n create_webhook_subscription?: boolean;\n prepare_billing_mandate?: boolean;\n webhook_event_types?: string[];\n webhook_description?: string;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupResult {\n merchant: DirectRequestPaymentMerchantResponse;\n billing_mandate?: DirectRequestPaymentMerchantResponse | null;\n webhook_subscription?: DirectRequestPaymentWebhookSubscription | null;\n env: Record<string, string>;\n}\n\nexport interface SiglumeEnvelopeMeta {\n request_id?: string | null;\n trace_id?: string | null;\n [key: string]: unknown;\n}\n\nexport interface WebhookSignatureVerification {\n timestamp: number;\n signature: string;\n}\n\nexport interface DirectRequestPaymentWebhookEvent {\n id: string;\n type: \"direct_payment.confirmed\" | string;\n api_version: string;\n occurred_at: string;\n data: {\n mode?: string;\n merchant?: string;\n direct_payment_requirement_id?: string;\n requirement_id?: string;\n challenge_hash?: string;\n amount_minor?: number;\n currency?: string;\n token_symbol?: string;\n status?: string;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport class SiglumeDirectRequestPaymentError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeDirectRequestPaymentError\";\n }\n}\n\nexport class SiglumeApiError extends SiglumeDirectRequestPaymentError {\n readonly status: number;\n readonly code: string;\n readonly data: unknown;\n\n constructor(message: string, options: { status: number; code?: string; data?: unknown }) {\n super(message);\n this.name = \"SiglumeApiError\";\n this.status = options.status;\n this.code = options.code ?? \"SIGLUME_API_ERROR\";\n this.data = options.data;\n }\n}\n\nexport class SiglumeWebhookSignatureError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookSignatureError\";\n }\n}\n\nexport class SiglumeWebhookPayloadError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookPayloadError\";\n }\n}\n\nexport class DirectRequestPaymentClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A buyer Siglume bearer token is required for Direct Request Payment API calls. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? \"@siglume/direct-request-payment/0.3.5\";\n this.fetch_impl = fetchImpl;\n }\n\n async createPaymentRequirement(input: DirectPaymentRequirementCreateInput): Promise<DirectPaymentRequirement> {\n const payload: Record<string, unknown> = {\n mode: DIRECT_REQUEST_PAYMENT_MODE,\n merchant: normalizeMerchant(input.merchant),\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n currency: normalizeCurrency(input.currency),\n challenge: requireNonEmpty(input.challenge, \"challenge\"),\n };\n if (input.token_symbol !== undefined) {\n payload.token_symbol = normalizeToken(input.token_symbol);\n }\n if (input.allowance_amount_minor !== undefined) {\n payload.allowance_amount_minor = positiveInteger(input.allowance_amount_minor, \"allowance_amount_minor\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectPaymentRequirement>(\"POST\", \"/sdrp/direct-payments/requirements\", payload);\n }\n\n async getPaymentRequirement(requirement_id: string): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"GET\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}`,\n );\n }\n\n async verifyPaymentRequirement(\n requirement_id: string,\n input: DirectPaymentVerifyInput,\n ): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"POST\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}/verify`,\n input,\n );\n }\n\n async executePreparedTransaction(\n payload: Web3PreparedTransactionExecutePayload,\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.request<Web3PreparedTransactionExecuteResult>(\n \"POST\",\n \"/market/web3/transactions/execute-prepared\",\n payload,\n );\n }\n\n async executePaymentTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildPaymentExecutionPayload(requirement, options));\n }\n\n async executeAllowanceTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildAllowanceExecutionPayload(requirement, options));\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport class DirectRequestPaymentMerchantClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_MERCHANT_AUTH_TOKEN\") ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A merchant Siglume bearer token is required for Direct Request Payment merchant setup. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? \"@siglume/direct-request-payment/0.3.5\";\n this.fetch_impl = fetchImpl;\n }\n\n async setupMerchant(input: DirectRequestPaymentMerchantSetupInput): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {\n merchant: normalizeSelfServiceMerchant(input.merchant),\n billing_plan: normalizeBillingPlan(input.billing_plan ?? \"launch\"),\n billing_currency: normalizeCurrency(input.billing_currency ?? \"JPY\"),\n };\n if (input.display_name !== undefined) {\n payload.display_name = requireNonEmpty(input.display_name, \"display_name\");\n }\n if (input.allowed_currencies !== undefined) {\n payload.allowed_currencies = normalizeAllowedCurrencies(input.allowed_currencies);\n }\n if (input.webhook_callback_url !== undefined) {\n payload.webhook_callback_url = requireNonEmpty(input.webhook_callback_url, \"webhook_callback_url\");\n }\n if (input.billing_mandate_cap_minor !== undefined) {\n payload.billing_mandate_cap_minor = positiveInteger(input.billing_mandate_cap_minor, \"billing_mandate_cap_minor\");\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\"POST\", \"/sdrp/direct-payments/merchants\", payload);\n }\n\n async getMerchant(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"GET\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}`,\n );\n }\n\n async rotateChallengeSecret(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/challenge-secret/rotate`,\n );\n }\n\n async prepareBillingMandate(\n merchant: string,\n input: DirectRequestPaymentMerchantBillingMandateInput = {},\n ): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {};\n if (input.currency !== undefined) {\n payload.currency = normalizeCurrency(input.currency);\n }\n if (input.billing_currency !== undefined) {\n payload.billing_currency = normalizeCurrency(input.billing_currency);\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/billing-mandate`,\n payload,\n );\n }\n\n async createWebhookSubscription(\n input: DirectRequestPaymentWebhookSubscriptionInput,\n ): Promise<DirectRequestPaymentWebhookSubscription> {\n const payload: Record<string, unknown> = {\n callback_url: requireNonEmpty(input.callback_url, \"callback_url\"),\n event_types: input.event_types?.length\n ? input.event_types.map((eventType) => requireNonEmpty(eventType, \"event_type\"))\n : [\"direct_payment.confirmed\", \"direct_payment.spent\"],\n };\n if (input.description !== undefined) {\n payload.description = requireNonEmpty(input.description, \"description\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectRequestPaymentWebhookSubscription>(\"POST\", \"/market/webhooks/subscriptions\", payload);\n }\n\n async setupCheckout(input: DirectRequestPaymentCheckoutSetupInput): Promise<DirectRequestPaymentCheckoutSetupResult> {\n const merchant = await this.setupMerchant(input);\n const merchantKey = merchant.merchant_account.merchant;\n const billing_mandate = input.prepare_billing_mandate === false\n ? null\n : await this.prepareBillingMandate(merchantKey, {\n billing_currency: merchant.merchant_account.billing_currency ?? input.billing_currency ?? \"JPY\",\n max_amount_minor: input.max_amount_minor ?? input.billing_mandate_cap_minor,\n });\n const shouldCreateWebhook = input.create_webhook_subscription ?? Boolean(input.webhook_callback_url);\n const webhook_subscription = shouldCreateWebhook && input.webhook_callback_url\n ? await this.createWebhookSubscription({\n callback_url: input.webhook_callback_url,\n description: input.webhook_description ?? `${merchantKey} Direct Request Payment`,\n event_types: input.webhook_event_types,\n metadata: { merchant: merchantKey, sdk: \"@siglume/direct-request-payment\" },\n })\n : null;\n const env: Record<string, string> = {\n SIGLUME_DIRECT_PAYMENT_MERCHANT: merchantKey,\n };\n if (merchant.challenge_secret) {\n env.SIGLUME_DIRECT_PAYMENT_CHALLENGE_SECRET = merchant.challenge_secret;\n }\n const webhookSecret = stringOrNull(webhook_subscription?.signing_secret);\n if (webhookSecret) {\n env.SIGLUME_WEBHOOK_SECRET = webhookSecret;\n }\n return { merchant, billing_mandate, webhook_subscription, env };\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport async function createDirectRequestPaymentChallenge(\n input: DirectRequestPaymentChallengeInput,\n): Promise<DirectRequestPaymentChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = normalizeChallengeNonce(input.nonce);\n const material = `${merchant}:${amount}:${currency}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport function parseDirectRequestPaymentChallenge(challenge: string): ParsedDirectRequestPaymentChallenge {\n const parts = requireNonEmpty(challenge, \"challenge\").split(\":\");\n if (parts.length !== 3) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge must be scheme:nonce:signature.\");\n }\n const [scheme, nonce, signature] = parts;\n if (!scheme || !nonce || !signature) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge is incomplete.\");\n }\n return { scheme, nonce, signature };\n}\n\n/** Merchant-side, ONE-TIME approval of a recurring authorization: amount +\n * currency + cadence are bound into the HMAC. Recurring charges afterwards\n * are deliberately challenge-free; the recurring authorization and the\n * buyer's mandate/budget caps are the per-charge integrity checks. Cadence\n * \"monthly\" = subscription, \"daily\" = scheduled autopay approval tag. */\nexport async function createDirectRequestPaymentRecurringChallenge(\n input: DirectRequestPaymentRecurringChallengeInput,\n): Promise<DirectRequestPaymentRecurringChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentRecurringChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentRecurringChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = normalizeChallengeNonce(input.nonce);\n // MUST stay byte-identical to the server's\n // _external_402_recurring_challenge_signature — both sides change together.\n const material = `${merchant}:${amount}:${currency}:${cadence}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport async function verifyDirectRequestPaymentRecurringChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentRecurringChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n cadence: input.cadence,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function verifyDirectRequestPaymentChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function directRequestPaymentChallengeHash(challenge: string): Promise<string> {\n return sha256Prefixed(requireNonEmpty(challenge, \"challenge\"));\n}\n\nexport async function directRequestPaymentRequestHash(input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n}): Promise<string> {\n const material = `${normalizeMerchant(input.merchant)}${positiveInteger(input.amount_minor, \"amount_minor\")}${normalizeCurrency(input.currency)}${requireNonEmpty(input.challenge, \"challenge\")}`;\n return sha256Prefixed(material);\n}\n\nexport function buildPaymentExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n return buildPreparedTransactionExecutionPayload(requirement, requirement.transaction_request, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildAllowanceExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n const approveRequest = requirement.approve_transaction_request;\n if (!approveRequest || Object.keys(approveRequest).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"This payment requirement does not include an allowance approval transaction.\");\n }\n return buildPreparedTransactionExecutionPayload(requirement, approveRequest, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildPreparedTransactionExecutionPayload(\n requirement: DirectPaymentRequirement,\n transaction_request: Web3TransactionRequest,\n options: {\n receipt_kind: string;\n await_finality?: boolean;\n metadata?: Record<string, unknown>;\n },\n): Web3PreparedTransactionExecutePayload {\n const metadata = {\n ...(isRecord(transaction_request.metadata_jsonb) ? transaction_request.metadata_jsonb : {}),\n ...(options.metadata ?? {}),\n };\n return {\n transaction_request,\n receipt_kind: requireNonEmpty(options.receipt_kind, \"receipt_kind\"),\n reference_type: DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE,\n reference_id: requirement.requirement_id,\n metadata,\n await_finality: Boolean(options.await_finality),\n };\n}\n\nexport async function computeWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp: number },\n): Promise<string> {\n if (!signing_secret) {\n throw new SiglumeWebhookSignatureError(\"SIGLUME webhook signing secret is required.\");\n }\n const timestamp = Math.trunc(options.timestamp);\n const bytes = bodyBytes(body);\n const prefix = new TextEncoder().encode(`${timestamp}.`);\n const payload = new Uint8Array(prefix.length + bytes.length);\n payload.set(prefix, 0);\n payload.set(bytes, prefix.length);\n return hmacSha256Hex(signing_secret, payload);\n}\n\nexport async function buildWebhookSignatureHeader(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp?: number } = {},\n): Promise<string> {\n const timestamp = Math.trunc(options.timestamp ?? Date.now() / 1000);\n const signature = await computeWebhookSignature(signing_secret, body, { timestamp });\n return `t=${timestamp},v1=${signature}`;\n}\n\nexport async function verifyWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<WebhookSignatureVerification> {\n const { timestamp, signature } = parseSignatureHeader(signature_header);\n const toleranceSeconds = Math.max(1, Math.trunc(options.tolerance_seconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS));\n const nowSeconds = Math.trunc(options.now ?? Date.now() / 1000);\n if (Math.abs(nowSeconds - timestamp) > toleranceSeconds) {\n throw new SiglumeWebhookSignatureError(\"Webhook timestamp is outside the allowed tolerance window.\");\n }\n const expected = await computeWebhookSignature(signing_secret, body, { timestamp });\n if (!(await timingSafeEqualHex(expected, signature))) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature did not match.\");\n }\n return { timestamp, signature };\n}\n\nexport function parseDirectRequestPaymentWebhookEvent(payload: unknown): DirectRequestPaymentWebhookEvent {\n const event = requireRecord(payload, \"webhook event\");\n const data = requireRecord(event.data, \"webhook event data\");\n const parsed = {\n ...event,\n id: requireNonEmpty(stringOrNull(event.id) ?? \"\", \"webhook event id\"),\n type: requireNonEmpty(stringOrNull(event.type) ?? \"\", \"webhook event type\"),\n api_version: requireNonEmpty(stringOrNull(event.api_version) ?? \"\", \"webhook api_version\"),\n occurred_at: requireNonEmpty(stringOrNull(event.occurred_at) ?? \"\", \"webhook occurred_at\"),\n data: { ...data },\n } as DirectRequestPaymentWebhookEvent;\n if (parsed.type === \"direct_payment.confirmed\" && parsed.data.mode !== DIRECT_REQUEST_PAYMENT_MODE) {\n throw new SiglumeWebhookPayloadError(\"direct_payment.confirmed webhook must carry data.mode='external_402'.\");\n }\n return parsed;\n}\n\nexport async function verifyDirectRequestPaymentWebhook(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<{ event: DirectRequestPaymentWebhookEvent; verification: WebhookSignatureVerification }> {\n const verification = await verifyWebhookSignature(signing_secret, body, signature_header, options);\n const text = new TextDecoder().decode(bodyBytes(body));\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new SiglumeWebhookPayloadError(\"Webhook body must contain valid JSON.\");\n }\n return { event: parseDirectRequestPaymentWebhookEvent(parsed), verification };\n}\n\nexport const createExternal402Challenge = createDirectRequestPaymentChallenge;\nexport const verifyExternal402Challenge = verifyDirectRequestPaymentChallenge;\nexport const createExternal402RecurringChallenge = createDirectRequestPaymentRecurringChallenge;\nexport const verifyExternal402RecurringChallenge = verifyDirectRequestPaymentRecurringChallenge;\n\nfunction normalizeMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9._-]{0,95}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be a lowercase key using letters, numbers, dot, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeSelfServiceMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9_-]{2,63}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be 3-64 chars using lowercase letters, numbers, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeBillingPlan(value: string): DirectRequestPaymentBillingPlan {\n const plan = requireNonEmpty(value, \"billing_plan\").toLowerCase();\n if (plan === \"launch\" || plan === \"free\" || plan === \"starter\" || plan === \"growth\" || plan === \"pro\") {\n return plan;\n }\n throw new SiglumeDirectRequestPaymentError(\"billing_plan must be launch, starter, growth, or pro.\");\n}\n\nfunction normalizeCurrency(value: string): DirectRequestPaymentCurrency {\n const currency = requireNonEmpty(value, \"currency\").toUpperCase();\n if (currency !== \"JPY\" && currency !== \"USD\") {\n throw new SiglumeDirectRequestPaymentError(\"currency must be JPY or USD.\");\n }\n return currency;\n}\n\nfunction normalizeToken(value: string): DirectRequestPaymentToken {\n const token = requireNonEmpty(value, \"token_symbol\").toUpperCase();\n if (token !== \"JPYC\" && token !== \"USDC\") {\n throw new SiglumeDirectRequestPaymentError(\"token_symbol must be JPYC or USDC.\");\n }\n return token;\n}\n\nfunction normalizeAllowedCurrencies(value: Record<string, string> | Array<DirectRequestPaymentCurrency | string>): Record<string, string> {\n const normalized: Record<string, string> = {};\n if (Array.isArray(value)) {\n for (const item of value) {\n const currency = normalizeCurrency(item);\n normalized[currency] = defaultTokenForCurrency(currency);\n }\n } else if (isRecord(value)) {\n for (const [rawCurrency, rawToken] of Object.entries(value)) {\n normalized[normalizeCurrency(rawCurrency)] = normalizeToken(String(rawToken));\n }\n } else {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must be an array or a currency-to-token object.\");\n }\n if (Object.keys(normalized).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must include at least one currency.\");\n }\n return normalized;\n}\n\nfunction defaultTokenForCurrency(currency: DirectRequestPaymentCurrency): DirectRequestPaymentToken {\n return currency === \"JPY\" ? \"JPYC\" : \"USDC\";\n}\n\nfunction positiveInteger(value: number, name: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a positive safe integer.`);\n }\n return parsed;\n}\n\nfunction requireNonEmpty(value: string, name: string): string {\n const text = String(value ?? \"\").trim();\n if (!text) {\n throw new SiglumeDirectRequestPaymentError(`${name} is required.`);\n }\n return text;\n}\n\nfunction normalizeChallengeNonce(value: string): string {\n const nonce = requireNonEmpty(value, \"nonce\");\n if (nonce.includes(\":\")) {\n throw new SiglumeDirectRequestPaymentError(\"nonce must not contain ':'.\");\n }\n return nonce;\n}\n\nfunction normalizeRecurringCadence(value: string): DirectRequestPaymentRecurringCadence {\n const cadence = requireNonEmpty(value, \"cadence\").toLowerCase();\n if (cadence !== \"monthly\" && cadence !== \"daily\") {\n throw new SiglumeDirectRequestPaymentError(\n 'cadence must be \"monthly\" (subscription) or \"daily\" (scheduled autopay).',\n );\n }\n return cadence;\n}\n\nfunction cloneJsonObject(value: Record<string, unknown>, name: string): Record<string, unknown> {\n try {\n const cloned = JSON.parse(JSON.stringify(value)) as unknown;\n if (!isRecord(cloned)) {\n throw new Error(\"not an object\");\n }\n return cloned;\n } catch (error) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a JSON-serializable object.`);\n }\n}\n\nfunction parseJson(rawText: string): unknown {\n try {\n return JSON.parse(rawText);\n } catch (error) {\n throw new SiglumeApiError(\"Siglume API returned invalid JSON.\", {\n status: 502,\n code: \"INVALID_JSON_RESPONSE\",\n data: rawText,\n });\n }\n}\n\nfunction stringOrNull(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const text = value.trim();\n return text ? text : null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requireRecord(value: unknown, name: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new SiglumeWebhookPayloadError(`${name} must be an object.`);\n }\n return value;\n}\n\nfunction envValue(name: string): string | undefined {\n if (typeof process === \"undefined\") {\n return undefined;\n }\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\nfunction bodyBytes(body: Uint8Array | ArrayBuffer | string | Record<string, unknown>): Uint8Array {\n if (body instanceof Uint8Array) {\n return body;\n }\n if (body instanceof ArrayBuffer) {\n return new Uint8Array(body);\n }\n if (typeof body === \"string\") {\n return new TextEncoder().encode(body);\n }\n if (isRecord(body)) {\n return new TextEncoder().encode(JSON.stringify(body));\n }\n throw new SiglumeWebhookPayloadError(\"Webhook body must be raw bytes, a string, or a JSON object.\");\n}\n\nfunction parseSignatureHeader(signatureHeader: string): { timestamp: number; signature: string } {\n let timestamp: number | null = null;\n let signature: string | null = null;\n for (const item of String(signatureHeader ?? \"\").split(\",\")) {\n const [key, value] = item.trim().split(\"=\", 2);\n if (key === \"t\") {\n const parsed = Number.parseInt(value ?? \"\", 10);\n if (!Number.isFinite(parsed)) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature timestamp is invalid.\");\n }\n timestamp = parsed;\n }\n if (key === \"v1\") {\n signature = String(value ?? \"\").trim();\n }\n }\n if (timestamp === null || !signature) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature header is incomplete.\");\n }\n return { timestamp, signature };\n}\n\nasync function randomNonce(): Promise<string> {\n if (globalThis.crypto?.randomUUID) {\n return globalThis.crypto.randomUUID();\n }\n const bytes = new Uint8Array(16);\n if (globalThis.crypto?.getRandomValues) {\n globalThis.crypto.getRandomValues(bytes);\n } else if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n bytes.set(crypto.randomBytes(16));\n } else {\n throw new SiglumeDirectRequestPaymentError(\"Crypto random number generation is unavailable in this runtime.\");\n }\n return bytesToHex(bytes);\n}\n\nasync function hmacSha256Hex(secret: string, payload: Uint8Array): Promise<string> {\n if (globalThis.crypto?.subtle) {\n const stablePayload = new Uint8Array(payload.byteLength);\n stablePayload.set(payload);\n const key = await globalThis.crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const digest = await globalThis.crypto.subtle.sign(\"HMAC\", key, stablePayload);\n return bytesToHex(new Uint8Array(digest));\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return crypto.createHmac(\"sha256\", secret).update(Buffer.from(payload)).digest(\"hex\");\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for HMAC-SHA256 in this runtime.\");\n}\n\nasync function sha256Prefixed(material: string): Promise<string> {\n const bytes = new TextEncoder().encode(material);\n if (globalThis.crypto?.subtle) {\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n return `sha256:${bytesToHex(new Uint8Array(digest))}`;\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return `sha256:${crypto.createHash(\"sha256\").update(Buffer.from(bytes)).digest(\"hex\")}`;\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for SHA-256 in this runtime.\");\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return [...bytes].map((item) => item.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const normalized = String(hex ?? \"\").trim().toLowerCase();\n if (normalized.length % 2 !== 0 || !/^[0-9a-f]*$/.test(normalized)) {\n throw new SiglumeWebhookSignatureError(\"Hex digest is invalid.\");\n }\n const bytes = new Uint8Array(normalized.length / 2);\n for (let index = 0; index < normalized.length; index += 2) {\n bytes[index / 2] = Number.parseInt(normalized.slice(index, index + 2), 16);\n }\n return bytes;\n}\n\nasync function timingSafeEqualHex(left: string, right: string): Promise<boolean> {\n const leftBytes = hexToBytes(left);\n const rightBytes = hexToBytes(right);\n if (leftBytes.length !== rightBytes.length) {\n return false;\n }\n let diff = 0;\n for (let index = 0; index < leftBytes.length; index += 1) {\n diff |= leftBytes[index]! ^ rightBytes[index]!;\n }\n return diff === 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,IAAM,2BAA2B;AACjC,IAAM,0CAA0C;A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AAM,YAAY,WAAW,IAAI;AACjC,QAAM,aAAa,WAAW,KAAK;AACnC,MAAI,UAAU,WAAW,WAAW,QAAQ;AAC1C,WAAO;AAAA,EACT;AACA,MAAI,OAAO;AACX,WAAS,QAAQ,GAAG,QAAQ,UAAU,QAAQ,SAAS,GAAG;AACxD,YAAQ,UAAU,KAAK,IAAK,WAAW,KAAK;AAAA,EAC9C;AACA,SAAO,SAAS;AAClB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export const DEFAULT_SIGLUME_API_BASE = \"https://siglume.com/v1\";\nexport const DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME = \"siglume-external-402-v1\";\n// Recurring (subscription / scheduled autopay) approval uses a DISTINCT scheme\n// with cadence bound into the HMAC, so a one-time checkout challenge can never\n// be replayed as a recurring authorization and vice versa.\nexport const DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME = \"siglume-external-402-recurring-v1\";\nexport const DIRECT_REQUEST_PAYMENT_MODE = \"external_402\";\nexport const DIRECT_REQUEST_PAYMENT_RECEIPT_KIND = \"sdrp_direct_payment\";\nexport const DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND = \"sdrp_direct_payment_allowance\";\nexport const DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE = \"sdrp_direct_payment_requirement\";\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;\n\nexport type DirectRequestPaymentCurrency = \"JPY\" | \"USD\";\nexport type DirectRequestPaymentToken = \"JPYC\" | \"USDC\";\n\nexport interface DirectRequestPaymentChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface ParsedDirectRequestPaymentChallenge {\n scheme: string;\n nonce: string;\n signature: string;\n}\n\n/** \"monthly\" authorizes a Siglume-swept subscription; \"daily\" authorizes\n * merchant-triggered scheduled autopay. It is an approval tag, not a\n * run-count limiter. */\nexport type DirectRequestPaymentRecurringCadence = \"monthly\" | \"daily\";\n\nexport interface DirectRequestPaymentRecurringChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentRecurringChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n cadence: DirectRequestPaymentRecurringCadence;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface Web3TransactionRequest {\n network?: string;\n chain_id?: number;\n from?: string;\n to?: string;\n data?: string;\n value?: string | number;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectPaymentRequirement {\n direct_payment_requirement_id: string;\n requirement_id: string;\n id: string;\n mode: string;\n merchant?: string | null;\n challenge_hash?: string | null;\n buyer_user_id: string;\n agent_id?: string | null;\n product_listing_id: string;\n listing_id: string;\n access_grant_id?: string | null;\n capability_key: string;\n requirement_hash: string;\n request_hash: string;\n siglume_signature: string;\n token_symbol: string;\n currency: string;\n amount_minor: number;\n fee_bps: number;\n status: string;\n expires_at?: string | null;\n confirmed_at?: string | null;\n spent_at?: string | null;\n chain_receipt_id?: string | null;\n transaction_request: Web3TransactionRequest;\n approve_transaction_request?: Web3TransactionRequest | null;\n buyer_confirmation?: string | null;\n non_custodial: boolean;\n metadata_jsonb?: Record<string, unknown>;\n created_at?: string | null;\n updated_at?: string | null;\n}\n\nexport interface DirectPaymentRequirementCreateInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n token_symbol?: DirectRequestPaymentToken | string;\n allowance_amount_minor?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectPaymentVerifyInput {\n receipt_id?: string | null;\n chain_receipt_id?: string | null;\n await_finality?: boolean;\n await_required_status?: string | null;\n await_timeout_seconds?: number;\n await_poll_seconds?: number;\n}\n\nexport interface Web3PreparedTransactionExecutePayload {\n transaction_request: Web3TransactionRequest;\n receipt_kind: string;\n reference_type: typeof DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE;\n reference_id: string;\n metadata?: Record<string, unknown>;\n await_finality?: boolean;\n}\n\nexport interface Web3PreparedTransactionExecuteResult {\n receipt?: Record<string, unknown>;\n finalization?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentClientOptions {\n auth_token?: string;\n base_url?: string;\n fetch?: typeof fetch;\n timeout_ms?: number;\n user_agent?: string;\n}\n\nexport type DirectRequestPaymentBillingPlan = \"launch\" | \"free\" | \"starter\" | \"growth\" | \"pro\";\n\nexport interface DirectRequestPaymentMerchantAccount {\n merchant_account_id: string;\n merchant: string;\n merchant_user_id: string;\n user_wallet_id?: string | null;\n billing_mandate_id?: string | null;\n display_name?: string | null;\n status?: string | null;\n billing_status?: string | null;\n billing_plan?: string | null;\n billing_currency?: string | null;\n token_symbol?: string | null;\n monthly_fee_minor?: number | null;\n settlement_fee_bps?: number | null;\n settlement_fee_min_minor?: number | null;\n included_monthly_payments?: number | null;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentMerchantSetupInput {\n merchant: string;\n display_name?: string;\n billing_plan?: DirectRequestPaymentBillingPlan | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n allowed_currencies?: Record<string, string> | Array<DirectRequestPaymentCurrency | string>;\n webhook_callback_url?: string;\n billing_mandate_cap_minor?: number;\n max_amount_minor?: number;\n}\n\nexport interface DirectRequestPaymentMerchantBillingMandateInput {\n currency?: DirectRequestPaymentCurrency | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n max_amount_minor?: number;\n}\n\nexport interface DirectRequestPaymentMerchantResponse {\n merchant_account: DirectRequestPaymentMerchantAccount;\n challenge_secret?: string | null;\n challenge_secret_created?: boolean;\n created?: boolean | null;\n listing_id?: string | null;\n mandate?: Record<string, unknown> | null;\n next_steps?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscriptionInput {\n callback_url: string;\n description?: string;\n event_types?: string[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscription {\n webhook_subscription_id?: string;\n subscription_id?: string;\n id?: string;\n callback_url?: string;\n signing_secret?: string;\n status?: string;\n event_types?: string[];\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupInput extends DirectRequestPaymentMerchantSetupInput {\n create_webhook_subscription?: boolean;\n prepare_billing_mandate?: boolean;\n webhook_event_types?: string[];\n webhook_description?: string;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupResult {\n merchant: DirectRequestPaymentMerchantResponse;\n billing_mandate?: DirectRequestPaymentMerchantResponse | null;\n webhook_subscription?: DirectRequestPaymentWebhookSubscription | null;\n env: Record<string, string>;\n}\n\nexport interface SiglumeEnvelopeMeta {\n request_id?: string | null;\n trace_id?: string | null;\n [key: string]: unknown;\n}\n\nexport interface WebhookSignatureVerification {\n timestamp: number;\n signature: string;\n}\n\nexport interface DirectRequestPaymentWebhookEvent {\n id: string;\n type: \"direct_payment.confirmed\" | string;\n api_version: string;\n occurred_at: string;\n data: {\n mode?: string;\n merchant?: string;\n direct_payment_requirement_id?: string;\n requirement_id?: string;\n challenge_hash?: string;\n amount_minor?: number;\n currency?: string;\n token_symbol?: string;\n status?: string;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport class SiglumeDirectRequestPaymentError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeDirectRequestPaymentError\";\n }\n}\n\nexport class SiglumeApiError extends SiglumeDirectRequestPaymentError {\n readonly status: number;\n readonly code: string;\n readonly data: unknown;\n\n constructor(message: string, options: { status: number; code?: string; data?: unknown }) {\n super(message);\n this.name = \"SiglumeApiError\";\n this.status = options.status;\n this.code = options.code ?? \"SIGLUME_API_ERROR\";\n this.data = options.data;\n }\n}\n\nexport class SiglumeWebhookSignatureError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookSignatureError\";\n }\n}\n\nexport class SiglumeWebhookPayloadError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookPayloadError\";\n }\n}\n\nexport class DirectRequestPaymentClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A buyer Siglume bearer token is required for Direct Request Payment API calls. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? \"@siglume/direct-request-payment/0.3.6\";\n this.fetch_impl = fetchImpl;\n }\n\n async createPaymentRequirement(input: DirectPaymentRequirementCreateInput): Promise<DirectPaymentRequirement> {\n const payload: Record<string, unknown> = {\n mode: DIRECT_REQUEST_PAYMENT_MODE,\n merchant: normalizeMerchant(input.merchant),\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n currency: normalizeCurrency(input.currency),\n challenge: requireNonEmpty(input.challenge, \"challenge\"),\n };\n if (input.token_symbol !== undefined) {\n payload.token_symbol = normalizeToken(input.token_symbol);\n }\n if (input.allowance_amount_minor !== undefined) {\n payload.allowance_amount_minor = positiveInteger(input.allowance_amount_minor, \"allowance_amount_minor\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectPaymentRequirement>(\"POST\", \"/sdrp/direct-payments/requirements\", payload);\n }\n\n async getPaymentRequirement(requirement_id: string): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"GET\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}`,\n );\n }\n\n async verifyPaymentRequirement(\n requirement_id: string,\n input: DirectPaymentVerifyInput,\n ): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"POST\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}/verify`,\n input,\n );\n }\n\n async executePreparedTransaction(\n payload: Web3PreparedTransactionExecutePayload,\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.request<Web3PreparedTransactionExecuteResult>(\n \"POST\",\n \"/market/web3/transactions/execute-prepared\",\n payload,\n );\n }\n\n async executePaymentTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildPaymentExecutionPayload(requirement, options));\n }\n\n async executeAllowanceTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildAllowanceExecutionPayload(requirement, options));\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport class DirectRequestPaymentMerchantClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_MERCHANT_AUTH_TOKEN\") ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A merchant Siglume bearer token is required for Direct Request Payment merchant setup. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? \"@siglume/direct-request-payment/0.3.6\";\n this.fetch_impl = fetchImpl;\n }\n\n async setupMerchant(input: DirectRequestPaymentMerchantSetupInput): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {\n merchant: normalizeSelfServiceMerchant(input.merchant),\n billing_plan: normalizeBillingPlan(input.billing_plan ?? \"launch\"),\n billing_currency: normalizeCurrency(input.billing_currency ?? \"JPY\"),\n };\n if (input.display_name !== undefined) {\n payload.display_name = requireNonEmpty(input.display_name, \"display_name\");\n }\n if (input.allowed_currencies !== undefined) {\n payload.allowed_currencies = normalizeAllowedCurrencies(input.allowed_currencies);\n }\n if (input.webhook_callback_url !== undefined) {\n payload.webhook_callback_url = requireNonEmpty(input.webhook_callback_url, \"webhook_callback_url\");\n }\n if (input.billing_mandate_cap_minor !== undefined) {\n payload.billing_mandate_cap_minor = positiveInteger(input.billing_mandate_cap_minor, \"billing_mandate_cap_minor\");\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\"POST\", \"/sdrp/direct-payments/merchants\", payload);\n }\n\n async getMerchant(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"GET\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}`,\n );\n }\n\n async rotateChallengeSecret(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/challenge-secret/rotate`,\n );\n }\n\n async prepareBillingMandate(\n merchant: string,\n input: DirectRequestPaymentMerchantBillingMandateInput = {},\n ): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {};\n if (input.currency !== undefined) {\n payload.currency = normalizeCurrency(input.currency);\n }\n if (input.billing_currency !== undefined) {\n payload.billing_currency = normalizeCurrency(input.billing_currency);\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/billing-mandate`,\n payload,\n );\n }\n\n async createWebhookSubscription(\n input: DirectRequestPaymentWebhookSubscriptionInput,\n ): Promise<DirectRequestPaymentWebhookSubscription> {\n const payload: Record<string, unknown> = {\n callback_url: requireNonEmpty(input.callback_url, \"callback_url\"),\n event_types: input.event_types?.length\n ? input.event_types.map((eventType) => requireNonEmpty(eventType, \"event_type\"))\n : [\"direct_payment.confirmed\", \"direct_payment.spent\"],\n };\n if (input.description !== undefined) {\n payload.description = requireNonEmpty(input.description, \"description\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectRequestPaymentWebhookSubscription>(\"POST\", \"/market/webhooks/subscriptions\", payload);\n }\n\n async setupCheckout(input: DirectRequestPaymentCheckoutSetupInput): Promise<DirectRequestPaymentCheckoutSetupResult> {\n const merchant = await this.setupMerchant(input);\n const merchantKey = merchant.merchant_account.merchant;\n const billing_mandate = input.prepare_billing_mandate === false\n ? null\n : await this.prepareBillingMandate(merchantKey, {\n billing_currency: merchant.merchant_account.billing_currency ?? input.billing_currency ?? \"JPY\",\n max_amount_minor: input.max_amount_minor ?? input.billing_mandate_cap_minor,\n });\n const shouldCreateWebhook = input.create_webhook_subscription ?? Boolean(input.webhook_callback_url);\n const webhook_subscription = shouldCreateWebhook && input.webhook_callback_url\n ? await this.createWebhookSubscription({\n callback_url: input.webhook_callback_url,\n description: input.webhook_description ?? `${merchantKey} Direct Request Payment`,\n event_types: input.webhook_event_types,\n metadata: { merchant: merchantKey, sdk: \"@siglume/direct-request-payment\" },\n })\n : null;\n const env: Record<string, string> = {\n SIGLUME_DIRECT_PAYMENT_MERCHANT: merchantKey,\n };\n if (merchant.challenge_secret) {\n env.SIGLUME_DIRECT_PAYMENT_CHALLENGE_SECRET = merchant.challenge_secret;\n }\n const webhookSecret = stringOrNull(webhook_subscription?.signing_secret);\n if (webhookSecret) {\n env.SIGLUME_WEBHOOK_SECRET = webhookSecret;\n }\n return { merchant, billing_mandate, webhook_subscription, env };\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport async function createDirectRequestPaymentChallenge(\n input: DirectRequestPaymentChallengeInput,\n): Promise<DirectRequestPaymentChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = normalizeChallengeNonce(input.nonce);\n const material = `${merchant}:${amount}:${currency}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport function parseDirectRequestPaymentChallenge(challenge: string): ParsedDirectRequestPaymentChallenge {\n const parts = requireNonEmpty(challenge, \"challenge\").split(\":\");\n if (parts.length !== 3) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge must be scheme:nonce:signature.\");\n }\n const [scheme, nonce, signature] = parts;\n if (!scheme || !nonce || !signature) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge is incomplete.\");\n }\n return { scheme, nonce, signature };\n}\n\n/** Merchant-side, ONE-TIME approval of a recurring authorization: amount +\n * currency + cadence are bound into the HMAC. Recurring charges afterwards\n * are deliberately challenge-free; the recurring authorization and the\n * buyer's mandate/budget caps are the per-charge integrity checks. Cadence\n * \"monthly\" = subscription, \"daily\" = scheduled autopay approval tag. */\nexport async function createDirectRequestPaymentRecurringChallenge(\n input: DirectRequestPaymentRecurringChallengeInput,\n): Promise<DirectRequestPaymentRecurringChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentRecurringChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentRecurringChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = normalizeChallengeNonce(input.nonce);\n // MUST stay byte-identical to the server's\n // _external_402_recurring_challenge_signature — both sides change together.\n const material = `${merchant}:${amount}:${currency}:${cadence}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport async function verifyDirectRequestPaymentRecurringChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentRecurringChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n cadence: input.cadence,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function verifyDirectRequestPaymentChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function directRequestPaymentChallengeHash(challenge: string): Promise<string> {\n return sha256Prefixed(requireNonEmpty(challenge, \"challenge\"));\n}\n\nexport async function directRequestPaymentRequestHash(input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n}): Promise<string> {\n const material = `${normalizeMerchant(input.merchant)}${positiveInteger(input.amount_minor, \"amount_minor\")}${normalizeCurrency(input.currency)}${requireNonEmpty(input.challenge, \"challenge\")}`;\n return sha256Prefixed(material);\n}\n\nexport function buildPaymentExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n return buildPreparedTransactionExecutionPayload(requirement, requirement.transaction_request, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildAllowanceExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n const approveRequest = requirement.approve_transaction_request;\n if (!approveRequest || Object.keys(approveRequest).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"This payment requirement does not include an allowance approval transaction.\");\n }\n return buildPreparedTransactionExecutionPayload(requirement, approveRequest, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildPreparedTransactionExecutionPayload(\n requirement: DirectPaymentRequirement,\n transaction_request: Web3TransactionRequest,\n options: {\n receipt_kind: string;\n await_finality?: boolean;\n metadata?: Record<string, unknown>;\n },\n): Web3PreparedTransactionExecutePayload {\n const metadata = {\n ...(isRecord(transaction_request.metadata_jsonb) ? transaction_request.metadata_jsonb : {}),\n ...(options.metadata ?? {}),\n };\n return {\n transaction_request,\n receipt_kind: requireNonEmpty(options.receipt_kind, \"receipt_kind\"),\n reference_type: DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE,\n reference_id: requirement.requirement_id,\n metadata,\n await_finality: Boolean(options.await_finality),\n };\n}\n\nexport async function computeWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp: number },\n): Promise<string> {\n if (!signing_secret) {\n throw new SiglumeWebhookSignatureError(\"SIGLUME webhook signing secret is required.\");\n }\n const timestamp = Math.trunc(options.timestamp);\n const bytes = bodyBytes(body);\n const prefix = new TextEncoder().encode(`${timestamp}.`);\n const payload = new Uint8Array(prefix.length + bytes.length);\n payload.set(prefix, 0);\n payload.set(bytes, prefix.length);\n return hmacSha256Hex(signing_secret, payload);\n}\n\nexport async function buildWebhookSignatureHeader(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp?: number } = {},\n): Promise<string> {\n const timestamp = Math.trunc(options.timestamp ?? Date.now() / 1000);\n const signature = await computeWebhookSignature(signing_secret, body, { timestamp });\n return `t=${timestamp},v1=${signature}`;\n}\n\nexport async function verifyWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<WebhookSignatureVerification> {\n const { timestamp, signature } = parseSignatureHeader(signature_header);\n const toleranceSeconds = Math.max(1, Math.trunc(options.tolerance_seconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS));\n const nowSeconds = Math.trunc(options.now ?? Date.now() / 1000);\n if (Math.abs(nowSeconds - timestamp) > toleranceSeconds) {\n throw new SiglumeWebhookSignatureError(\"Webhook timestamp is outside the allowed tolerance window.\");\n }\n const expected = await computeWebhookSignature(signing_secret, body, { timestamp });\n if (!(await timingSafeEqualHex(expected, signature))) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature did not match.\");\n }\n return { timestamp, signature };\n}\n\nexport function parseDirectRequestPaymentWebhookEvent(payload: unknown): DirectRequestPaymentWebhookEvent {\n const event = requireRecord(payload, \"webhook event\");\n const data = requireRecord(event.data, \"webhook event data\");\n const parsed = {\n ...event,\n id: requireNonEmpty(stringOrNull(event.id) ?? \"\", \"webhook event id\"),\n type: requireNonEmpty(stringOrNull(event.type) ?? \"\", \"webhook event type\"),\n api_version: requireNonEmpty(stringOrNull(event.api_version) ?? \"\", \"webhook api_version\"),\n occurred_at: requireNonEmpty(stringOrNull(event.occurred_at) ?? \"\", \"webhook occurred_at\"),\n data: { ...data },\n } as DirectRequestPaymentWebhookEvent;\n if (parsed.type === \"direct_payment.confirmed\" && parsed.data.mode !== DIRECT_REQUEST_PAYMENT_MODE) {\n throw new SiglumeWebhookPayloadError(\"direct_payment.confirmed webhook must carry data.mode='external_402'.\");\n }\n return parsed;\n}\n\nexport async function verifyDirectRequestPaymentWebhook(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<{ event: DirectRequestPaymentWebhookEvent; verification: WebhookSignatureVerification }> {\n const verification = await verifyWebhookSignature(signing_secret, body, signature_header, options);\n const text = new TextDecoder().decode(bodyBytes(body));\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new SiglumeWebhookPayloadError(\"Webhook body must contain valid JSON.\");\n }\n return { event: parseDirectRequestPaymentWebhookEvent(parsed), verification };\n}\n\nexport const createExternal402Challenge = createDirectRequestPaymentChallenge;\nexport const verifyExternal402Challenge = verifyDirectRequestPaymentChallenge;\nexport const createExternal402RecurringChallenge = createDirectRequestPaymentRecurringChallenge;\nexport const verifyExternal402RecurringChallenge = verifyDirectRequestPaymentRecurringChallenge;\n\nfunction normalizeMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9._-]{0,95}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be a lowercase key using letters, numbers, dot, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeSelfServiceMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9_-]{2,63}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be 3-64 chars using lowercase letters, numbers, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeBillingPlan(value: string): DirectRequestPaymentBillingPlan {\n const plan = requireNonEmpty(value, \"billing_plan\").toLowerCase();\n if (plan === \"launch\" || plan === \"free\" || plan === \"starter\" || plan === \"growth\" || plan === \"pro\") {\n return plan;\n }\n throw new SiglumeDirectRequestPaymentError(\"billing_plan must be launch, starter, growth, or pro.\");\n}\n\nfunction normalizeCurrency(value: string): DirectRequestPaymentCurrency {\n const currency = requireNonEmpty(value, \"currency\").toUpperCase();\n if (currency !== \"JPY\" && currency !== \"USD\") {\n throw new SiglumeDirectRequestPaymentError(\"currency must be JPY or USD.\");\n }\n return currency;\n}\n\nfunction normalizeToken(value: string): DirectRequestPaymentToken {\n const token = requireNonEmpty(value, \"token_symbol\").toUpperCase();\n if (token !== \"JPYC\" && token !== \"USDC\") {\n throw new SiglumeDirectRequestPaymentError(\"token_symbol must be JPYC or USDC.\");\n }\n return token;\n}\n\nfunction normalizeAllowedCurrencies(value: Record<string, string> | Array<DirectRequestPaymentCurrency | string>): Record<string, string> {\n const normalized: Record<string, string> = {};\n if (Array.isArray(value)) {\n for (const item of value) {\n const currency = normalizeCurrency(item);\n normalized[currency] = defaultTokenForCurrency(currency);\n }\n } else if (isRecord(value)) {\n for (const [rawCurrency, rawToken] of Object.entries(value)) {\n normalized[normalizeCurrency(rawCurrency)] = normalizeToken(String(rawToken));\n }\n } else {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must be an array or a currency-to-token object.\");\n }\n if (Object.keys(normalized).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must include at least one currency.\");\n }\n return normalized;\n}\n\nfunction defaultTokenForCurrency(currency: DirectRequestPaymentCurrency): DirectRequestPaymentToken {\n return currency === \"JPY\" ? \"JPYC\" : \"USDC\";\n}\n\nfunction positiveInteger(value: number, name: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a positive safe integer.`);\n }\n return parsed;\n}\n\nfunction requireNonEmpty(value: string, name: string): string {\n const text = String(value ?? \"\").trim();\n if (!text) {\n throw new SiglumeDirectRequestPaymentError(`${name} is required.`);\n }\n return text;\n}\n\nfunction normalizeChallengeNonce(value: string): string {\n const nonce = requireNonEmpty(value, \"nonce\");\n if (nonce.includes(\":\")) {\n throw new SiglumeDirectRequestPaymentError(\"nonce must not contain ':'.\");\n }\n return nonce;\n}\n\nfunction normalizeRecurringCadence(value: string): DirectRequestPaymentRecurringCadence {\n const cadence = requireNonEmpty(value, \"cadence\").toLowerCase();\n if (cadence !== \"monthly\" && cadence !== \"daily\") {\n throw new SiglumeDirectRequestPaymentError(\n 'cadence must be \"monthly\" (subscription) or \"daily\" (scheduled autopay).',\n );\n }\n return cadence;\n}\n\nfunction cloneJsonObject(value: Record<string, unknown>, name: string): Record<string, unknown> {\n try {\n const cloned = JSON.parse(JSON.stringify(value)) as unknown;\n if (!isRecord(cloned)) {\n throw new Error(\"not an object\");\n }\n return cloned;\n } catch (error) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a JSON-serializable object.`);\n }\n}\n\nfunction parseJson(rawText: string): unknown {\n try {\n return JSON.parse(rawText);\n } catch (error) {\n throw new SiglumeApiError(\"Siglume API returned invalid JSON.\", {\n status: 502,\n code: \"INVALID_JSON_RESPONSE\",\n data: rawText,\n });\n }\n}\n\nfunction stringOrNull(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const text = value.trim();\n return text ? text : null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requireRecord(value: unknown, name: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new SiglumeWebhookPayloadError(`${name} must be an object.`);\n }\n return value;\n}\n\nfunction envValue(name: string): string | undefined {\n if (typeof process === \"undefined\") {\n return undefined;\n }\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\nfunction bodyBytes(body: Uint8Array | ArrayBuffer | string | Record<string, unknown>): Uint8Array {\n if (body instanceof Uint8Array) {\n return body;\n }\n if (body instanceof ArrayBuffer) {\n return new Uint8Array(body);\n }\n if (typeof body === \"string\") {\n return new TextEncoder().encode(body);\n }\n if (isRecord(body)) {\n return new TextEncoder().encode(JSON.stringify(body));\n }\n throw new SiglumeWebhookPayloadError(\"Webhook body must be raw bytes, a string, or a JSON object.\");\n}\n\nfunction parseSignatureHeader(signatureHeader: string): { timestamp: number; signature: string } {\n let timestamp: number | null = null;\n let signature: string | null = null;\n for (const item of String(signatureHeader ?? \"\").split(\",\")) {\n const [key, value] = item.trim().split(\"=\", 2);\n if (key === \"t\") {\n const parsed = Number.parseInt(value ?? \"\", 10);\n if (!Number.isFinite(parsed)) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature timestamp is invalid.\");\n }\n timestamp = parsed;\n }\n if (key === \"v1\") {\n signature = String(value ?? \"\").trim();\n }\n }\n if (timestamp === null || !signature) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature header is incomplete.\");\n }\n return { timestamp, signature };\n}\n\nasync function randomNonce(): Promise<string> {\n if (globalThis.crypto?.randomUUID) {\n return globalThis.crypto.randomUUID();\n }\n const bytes = new Uint8Array(16);\n if (globalThis.crypto?.getRandomValues) {\n globalThis.crypto.getRandomValues(bytes);\n } else if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n bytes.set(crypto.randomBytes(16));\n } else {\n throw new SiglumeDirectRequestPaymentError(\"Crypto random number generation is unavailable in this runtime.\");\n }\n return bytesToHex(bytes);\n}\n\nasync function hmacSha256Hex(secret: string, payload: Uint8Array): Promise<string> {\n if (globalThis.crypto?.subtle) {\n const stablePayload = new Uint8Array(payload.byteLength);\n stablePayload.set(payload);\n const key = await globalThis.crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const digest = await globalThis.crypto.subtle.sign(\"HMAC\", key, stablePayload);\n return bytesToHex(new Uint8Array(digest));\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return crypto.createHmac(\"sha256\", secret).update(Buffer.from(payload)).digest(\"hex\");\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for HMAC-SHA256 in this runtime.\");\n}\n\nasync function sha256Prefixed(material: string): Promise<string> {\n const bytes = new TextEncoder().encode(material);\n if (globalThis.crypto?.subtle) {\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n return `sha256:${bytesToHex(new Uint8Array(digest))}`;\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return `sha256:${crypto.createHash(\"sha256\").update(Buffer.from(bytes)).digest(\"hex\")}`;\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for SHA-256 in this runtime.\");\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return [...bytes].map((item) => item.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const normalized = String(hex ?? \"\").trim().toLowerCase();\n if (normalized.length % 2 !== 0 || !/^[0-9a-f]*$/.test(normalized)) {\n throw new SiglumeWebhookSignatureError(\"Hex digest is invalid.\");\n }\n const bytes = new Uint8Array(normalized.length / 2);\n for (let index = 0; index < normalized.length; index += 2) {\n bytes[index / 2] = Number.parseInt(normalized.slice(index, index + 2), 16);\n }\n return bytes;\n}\n\nasync function timingSafeEqualHex(left: string, right: string): Promise<boolean> {\n const leftBytes = hexToBytes(left);\n const rightBytes = hexToBytes(right);\n if (leftBytes.length !== rightBytes.length) {\n return false;\n }\n let diff = 0;\n for (let index = 0; index < leftBytes.length; index += 1) {\n diff |= leftBytes[index]! ^ rightBytes[index]!;\n }\n return diff === 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,IAAM,2BAA2B;AACjC,IAAM,0CAA0C;AAIhD,IAAM,oDAAoD;AAC1D,IAAM,8BAA8B;AACpC,IAAM,sCAAsC;AAC5C,IAAM,gDAAgD;AACtD,IAAM,wCAAwC;AAC9C,IAAM,oCAAoC;AA+P1C,IAAM,mCAAN,cAA+C,MAAM;AAAA,EAC1D,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,kBAAN,cAA8B,iCAAiC;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,SAAiB,SAA4D;AACvF,UAAM,OAAO;AACb,SAAK,O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
58
58
|
this.base_url = (options.base_url ?? envValue("SIGLUME_API_BASE") ?? DEFAULT_SIGLUME_API_BASE).replace(/\/+$/, "");
|
|
59
59
|
this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15e3));
|
|
60
|
-
this.user_agent = options.user_agent ?? "@siglume/direct-request-payment/0.3.
|
|
60
|
+
this.user_agent = options.user_agent ?? "@siglume/direct-request-payment/0.3.6";
|
|
61
61
|
this.fetch_impl = fetchImpl;
|
|
62
62
|
}
|
|
63
63
|
async createPaymentRequirement(input) {
|
|
@@ -162,7 +162,7 @@ var DirectRequestPaymentMerchantClient = class {
|
|
|
162
162
|
this.auth_token = authToken;
|
|
163
163
|
this.base_url = (options.base_url ?? envValue("SIGLUME_API_BASE") ?? DEFAULT_SIGLUME_API_BASE).replace(/\/+$/, "");
|
|
164
164
|
this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15e3));
|
|
165
|
-
this.user_agent = options.user_agent ?? "@siglume/direct-request-payment/0.3.
|
|
165
|
+
this.user_agent = options.user_agent ?? "@siglume/direct-request-payment/0.3.6";
|
|
166
166
|
this.fetch_impl = fetchImpl;
|
|
167
167
|
}
|
|
168
168
|
async setupMerchant(input) {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export const DEFAULT_SIGLUME_API_BASE = \"https://siglume.com/v1\";\nexport const DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME = \"siglume-external-402-v1\";\n// Recurring (subscription / scheduled autopay) approval uses a DISTINCT scheme\n// with cadence bound into the HMAC, so a one-time checkout challenge can never\n// be replayed as a recurring authorization and vice versa.\nexport const DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME = \"siglume-external-402-recurring-v1\";\nexport const DIRECT_REQUEST_PAYMENT_MODE = \"external_402\";\nexport const DIRECT_REQUEST_PAYMENT_RECEIPT_KIND = \"sdrp_direct_payment\";\nexport const DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND = \"sdrp_direct_payment_allowance\";\nexport const DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE = \"sdrp_direct_payment_requirement\";\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;\n\nexport type DirectRequestPaymentCurrency = \"JPY\" | \"USD\";\nexport type DirectRequestPaymentToken = \"JPYC\" | \"USDC\";\n\nexport interface DirectRequestPaymentChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface ParsedDirectRequestPaymentChallenge {\n scheme: string;\n nonce: string;\n signature: string;\n}\n\n/** \"monthly\" authorizes a Siglume-swept subscription; \"daily\" authorizes\n * merchant-triggered scheduled autopay. It is an approval tag, not a\n * run-count limiter. */\nexport type DirectRequestPaymentRecurringCadence = \"monthly\" | \"daily\";\n\nexport interface DirectRequestPaymentRecurringChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentRecurringChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n cadence: DirectRequestPaymentRecurringCadence;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface Web3TransactionRequest {\n network?: string;\n chain_id?: number;\n from?: string;\n to?: string;\n data?: string;\n value?: string | number;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectPaymentRequirement {\n direct_payment_requirement_id: string;\n requirement_id: string;\n id: string;\n mode: string;\n merchant?: string | null;\n challenge_hash?: string | null;\n buyer_user_id: string;\n agent_id?: string | null;\n product_listing_id: string;\n listing_id: string;\n access_grant_id?: string | null;\n capability_key: string;\n requirement_hash: string;\n request_hash: string;\n siglume_signature: string;\n token_symbol: string;\n currency: string;\n amount_minor: number;\n fee_bps: number;\n status: string;\n expires_at?: string | null;\n confirmed_at?: string | null;\n spent_at?: string | null;\n chain_receipt_id?: string | null;\n transaction_request: Web3TransactionRequest;\n approve_transaction_request?: Web3TransactionRequest | null;\n buyer_confirmation?: string | null;\n non_custodial: boolean;\n metadata_jsonb?: Record<string, unknown>;\n created_at?: string | null;\n updated_at?: string | null;\n}\n\nexport interface DirectPaymentRequirementCreateInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n token_symbol?: DirectRequestPaymentToken | string;\n allowance_amount_minor?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectPaymentVerifyInput {\n receipt_id?: string | null;\n chain_receipt_id?: string | null;\n await_finality?: boolean;\n await_required_status?: string | null;\n await_timeout_seconds?: number;\n await_poll_seconds?: number;\n}\n\nexport interface Web3PreparedTransactionExecutePayload {\n transaction_request: Web3TransactionRequest;\n receipt_kind: string;\n reference_type: typeof DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE;\n reference_id: string;\n metadata?: Record<string, unknown>;\n await_finality?: boolean;\n}\n\nexport interface Web3PreparedTransactionExecuteResult {\n receipt?: Record<string, unknown>;\n finalization?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentClientOptions {\n auth_token?: string;\n base_url?: string;\n fetch?: typeof fetch;\n timeout_ms?: number;\n user_agent?: string;\n}\n\nexport type DirectRequestPaymentBillingPlan = \"launch\" | \"free\" | \"starter\" | \"growth\" | \"pro\";\n\nexport interface DirectRequestPaymentMerchantAccount {\n merchant_account_id: string;\n merchant: string;\n merchant_user_id: string;\n user_wallet_id?: string | null;\n billing_mandate_id?: string | null;\n display_name?: string | null;\n status?: string | null;\n billing_status?: string | null;\n billing_plan?: string | null;\n billing_currency?: string | null;\n token_symbol?: string | null;\n monthly_fee_minor?: number | null;\n settlement_fee_bps?: number | null;\n settlement_fee_min_minor?: number | null;\n included_monthly_payments?: number | null;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentMerchantSetupInput {\n merchant: string;\n display_name?: string;\n billing_plan?: DirectRequestPaymentBillingPlan | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n allowed_currencies?: Record<string, string> | Array<DirectRequestPaymentCurrency | string>;\n webhook_callback_url?: string;\n billing_mandate_cap_minor?: number;\n max_amount_minor?: number;\n}\n\nexport interface DirectRequestPaymentMerchantBillingMandateInput {\n currency?: DirectRequestPaymentCurrency | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n max_amount_minor?: number;\n}\n\nexport interface DirectRequestPaymentMerchantResponse {\n merchant_account: DirectRequestPaymentMerchantAccount;\n challenge_secret?: string | null;\n challenge_secret_created?: boolean;\n created?: boolean | null;\n listing_id?: string | null;\n mandate?: Record<string, unknown> | null;\n next_steps?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscriptionInput {\n callback_url: string;\n description?: string;\n event_types?: string[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscription {\n webhook_subscription_id?: string;\n subscription_id?: string;\n id?: string;\n callback_url?: string;\n signing_secret?: string;\n status?: string;\n event_types?: string[];\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupInput extends DirectRequestPaymentMerchantSetupInput {\n create_webhook_subscription?: boolean;\n prepare_billing_mandate?: boolean;\n webhook_event_types?: string[];\n webhook_description?: string;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupResult {\n merchant: DirectRequestPaymentMerchantResponse;\n billing_mandate?: DirectRequestPaymentMerchantResponse | null;\n webhook_subscription?: DirectRequestPaymentWebhookSubscription | null;\n env: Record<string, string>;\n}\n\nexport interface SiglumeEnvelopeMeta {\n request_id?: string | null;\n trace_id?: string | null;\n [key: string]: unknown;\n}\n\nexport interface WebhookSignatureVerification {\n timestamp: number;\n signature: string;\n}\n\nexport interface DirectRequestPaymentWebhookEvent {\n id: string;\n type: \"direct_payment.confirmed\" | string;\n api_version: string;\n occurred_at: string;\n data: {\n mode?: string;\n merchant?: string;\n direct_payment_requirement_id?: string;\n requirement_id?: string;\n challenge_hash?: string;\n amount_minor?: number;\n currency?: string;\n token_symbol?: string;\n status?: string;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport class SiglumeDirectRequestPaymentError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeDirectRequestPaymentError\";\n }\n}\n\nexport class SiglumeApiError extends SiglumeDirectRequestPaymentError {\n readonly status: number;\n readonly code: string;\n readonly data: unknown;\n\n constructor(message: string, options: { status: number; code?: string; data?: unknown }) {\n super(message);\n this.name = \"SiglumeApiError\";\n this.status = options.status;\n this.code = options.code ?? \"SIGLUME_API_ERROR\";\n this.data = options.data;\n }\n}\n\nexport class SiglumeWebhookSignatureError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookSignatureError\";\n }\n}\n\nexport class SiglumeWebhookPayloadError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookPayloadError\";\n }\n}\n\nexport class DirectRequestPaymentClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A buyer Siglume bearer token is required for Direct Request Payment API calls. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? \"@siglume/direct-request-payment/0.3.5\";\n this.fetch_impl = fetchImpl;\n }\n\n async createPaymentRequirement(input: DirectPaymentRequirementCreateInput): Promise<DirectPaymentRequirement> {\n const payload: Record<string, unknown> = {\n mode: DIRECT_REQUEST_PAYMENT_MODE,\n merchant: normalizeMerchant(input.merchant),\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n currency: normalizeCurrency(input.currency),\n challenge: requireNonEmpty(input.challenge, \"challenge\"),\n };\n if (input.token_symbol !== undefined) {\n payload.token_symbol = normalizeToken(input.token_symbol);\n }\n if (input.allowance_amount_minor !== undefined) {\n payload.allowance_amount_minor = positiveInteger(input.allowance_amount_minor, \"allowance_amount_minor\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectPaymentRequirement>(\"POST\", \"/sdrp/direct-payments/requirements\", payload);\n }\n\n async getPaymentRequirement(requirement_id: string): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"GET\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}`,\n );\n }\n\n async verifyPaymentRequirement(\n requirement_id: string,\n input: DirectPaymentVerifyInput,\n ): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"POST\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}/verify`,\n input,\n );\n }\n\n async executePreparedTransaction(\n payload: Web3PreparedTransactionExecutePayload,\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.request<Web3PreparedTransactionExecuteResult>(\n \"POST\",\n \"/market/web3/transactions/execute-prepared\",\n payload,\n );\n }\n\n async executePaymentTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildPaymentExecutionPayload(requirement, options));\n }\n\n async executeAllowanceTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildAllowanceExecutionPayload(requirement, options));\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport class DirectRequestPaymentMerchantClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_MERCHANT_AUTH_TOKEN\") ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A merchant Siglume bearer token is required for Direct Request Payment merchant setup. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? \"@siglume/direct-request-payment/0.3.5\";\n this.fetch_impl = fetchImpl;\n }\n\n async setupMerchant(input: DirectRequestPaymentMerchantSetupInput): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {\n merchant: normalizeSelfServiceMerchant(input.merchant),\n billing_plan: normalizeBillingPlan(input.billing_plan ?? \"launch\"),\n billing_currency: normalizeCurrency(input.billing_currency ?? \"JPY\"),\n };\n if (input.display_name !== undefined) {\n payload.display_name = requireNonEmpty(input.display_name, \"display_name\");\n }\n if (input.allowed_currencies !== undefined) {\n payload.allowed_currencies = normalizeAllowedCurrencies(input.allowed_currencies);\n }\n if (input.webhook_callback_url !== undefined) {\n payload.webhook_callback_url = requireNonEmpty(input.webhook_callback_url, \"webhook_callback_url\");\n }\n if (input.billing_mandate_cap_minor !== undefined) {\n payload.billing_mandate_cap_minor = positiveInteger(input.billing_mandate_cap_minor, \"billing_mandate_cap_minor\");\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\"POST\", \"/sdrp/direct-payments/merchants\", payload);\n }\n\n async getMerchant(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"GET\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}`,\n );\n }\n\n async rotateChallengeSecret(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/challenge-secret/rotate`,\n );\n }\n\n async prepareBillingMandate(\n merchant: string,\n input: DirectRequestPaymentMerchantBillingMandateInput = {},\n ): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {};\n if (input.currency !== undefined) {\n payload.currency = normalizeCurrency(input.currency);\n }\n if (input.billing_currency !== undefined) {\n payload.billing_currency = normalizeCurrency(input.billing_currency);\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/billing-mandate`,\n payload,\n );\n }\n\n async createWebhookSubscription(\n input: DirectRequestPaymentWebhookSubscriptionInput,\n ): Promise<DirectRequestPaymentWebhookSubscription> {\n const payload: Record<string, unknown> = {\n callback_url: requireNonEmpty(input.callback_url, \"callback_url\"),\n event_types: input.event_types?.length\n ? input.event_types.map((eventType) => requireNonEmpty(eventType, \"event_type\"))\n : [\"direct_payment.confirmed\", \"direct_payment.spent\"],\n };\n if (input.description !== undefined) {\n payload.description = requireNonEmpty(input.description, \"description\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectRequestPaymentWebhookSubscription>(\"POST\", \"/market/webhooks/subscriptions\", payload);\n }\n\n async setupCheckout(input: DirectRequestPaymentCheckoutSetupInput): Promise<DirectRequestPaymentCheckoutSetupResult> {\n const merchant = await this.setupMerchant(input);\n const merchantKey = merchant.merchant_account.merchant;\n const billing_mandate = input.prepare_billing_mandate === false\n ? null\n : await this.prepareBillingMandate(merchantKey, {\n billing_currency: merchant.merchant_account.billing_currency ?? input.billing_currency ?? \"JPY\",\n max_amount_minor: input.max_amount_minor ?? input.billing_mandate_cap_minor,\n });\n const shouldCreateWebhook = input.create_webhook_subscription ?? Boolean(input.webhook_callback_url);\n const webhook_subscription = shouldCreateWebhook && input.webhook_callback_url\n ? await this.createWebhookSubscription({\n callback_url: input.webhook_callback_url,\n description: input.webhook_description ?? `${merchantKey} Direct Request Payment`,\n event_types: input.webhook_event_types,\n metadata: { merchant: merchantKey, sdk: \"@siglume/direct-request-payment\" },\n })\n : null;\n const env: Record<string, string> = {\n SIGLUME_DIRECT_PAYMENT_MERCHANT: merchantKey,\n };\n if (merchant.challenge_secret) {\n env.SIGLUME_DIRECT_PAYMENT_CHALLENGE_SECRET = merchant.challenge_secret;\n }\n const webhookSecret = stringOrNull(webhook_subscription?.signing_secret);\n if (webhookSecret) {\n env.SIGLUME_WEBHOOK_SECRET = webhookSecret;\n }\n return { merchant, billing_mandate, webhook_subscription, env };\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport async function createDirectRequestPaymentChallenge(\n input: DirectRequestPaymentChallengeInput,\n): Promise<DirectRequestPaymentChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = normalizeChallengeNonce(input.nonce);\n const material = `${merchant}:${amount}:${currency}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport function parseDirectRequestPaymentChallenge(challenge: string): ParsedDirectRequestPaymentChallenge {\n const parts = requireNonEmpty(challenge, \"challenge\").split(\":\");\n if (parts.length !== 3) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge must be scheme:nonce:signature.\");\n }\n const [scheme, nonce, signature] = parts;\n if (!scheme || !nonce || !signature) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge is incomplete.\");\n }\n return { scheme, nonce, signature };\n}\n\n/** Merchant-side, ONE-TIME approval of a recurring authorization: amount +\n * currency + cadence are bound into the HMAC. Recurring charges afterwards\n * are deliberately challenge-free; the recurring authorization and the\n * buyer's mandate/budget caps are the per-charge integrity checks. Cadence\n * \"monthly\" = subscription, \"daily\" = scheduled autopay approval tag. */\nexport async function createDirectRequestPaymentRecurringChallenge(\n input: DirectRequestPaymentRecurringChallengeInput,\n): Promise<DirectRequestPaymentRecurringChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentRecurringChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentRecurringChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = normalizeChallengeNonce(input.nonce);\n // MUST stay byte-identical to the server's\n // _external_402_recurring_challenge_signature — both sides change together.\n const material = `${merchant}:${amount}:${currency}:${cadence}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport async function verifyDirectRequestPaymentRecurringChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentRecurringChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n cadence: input.cadence,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function verifyDirectRequestPaymentChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function directRequestPaymentChallengeHash(challenge: string): Promise<string> {\n return sha256Prefixed(requireNonEmpty(challenge, \"challenge\"));\n}\n\nexport async function directRequestPaymentRequestHash(input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n}): Promise<string> {\n const material = `${normalizeMerchant(input.merchant)}${positiveInteger(input.amount_minor, \"amount_minor\")}${normalizeCurrency(input.currency)}${requireNonEmpty(input.challenge, \"challenge\")}`;\n return sha256Prefixed(material);\n}\n\nexport function buildPaymentExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n return buildPreparedTransactionExecutionPayload(requirement, requirement.transaction_request, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildAllowanceExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n const approveRequest = requirement.approve_transaction_request;\n if (!approveRequest || Object.keys(approveRequest).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"This payment requirement does not include an allowance approval transaction.\");\n }\n return buildPreparedTransactionExecutionPayload(requirement, approveRequest, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildPreparedTransactionExecutionPayload(\n requirement: DirectPaymentRequirement,\n transaction_request: Web3TransactionRequest,\n options: {\n receipt_kind: string;\n await_finality?: boolean;\n metadata?: Record<string, unknown>;\n },\n): Web3PreparedTransactionExecutePayload {\n const metadata = {\n ...(isRecord(transaction_request.metadata_jsonb) ? transaction_request.metadata_jsonb : {}),\n ...(options.metadata ?? {}),\n };\n return {\n transaction_request,\n receipt_kind: requireNonEmpty(options.receipt_kind, \"receipt_kind\"),\n reference_type: DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE,\n reference_id: requirement.requirement_id,\n metadata,\n await_finality: Boolean(options.await_finality),\n };\n}\n\nexport async function computeWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp: number },\n): Promise<string> {\n if (!signing_secret) {\n throw new SiglumeWebhookSignatureError(\"SIGLUME webhook signing secret is required.\");\n }\n const timestamp = Math.trunc(options.timestamp);\n const bytes = bodyBytes(body);\n const prefix = new TextEncoder().encode(`${timestamp}.`);\n const payload = new Uint8Array(prefix.length + bytes.length);\n payload.set(prefix, 0);\n payload.set(bytes, prefix.length);\n return hmacSha256Hex(signing_secret, payload);\n}\n\nexport async function buildWebhookSignatureHeader(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp?: number } = {},\n): Promise<string> {\n const timestamp = Math.trunc(options.timestamp ?? Date.now() / 1000);\n const signature = await computeWebhookSignature(signing_secret, body, { timestamp });\n return `t=${timestamp},v1=${signature}`;\n}\n\nexport async function verifyWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<WebhookSignatureVerification> {\n const { timestamp, signature } = parseSignatureHeader(signature_header);\n const toleranceSeconds = Math.max(1, Math.trunc(options.tolerance_seconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS));\n const nowSeconds = Math.trunc(options.now ?? Date.now() / 1000);\n if (Math.abs(nowSeconds - timestamp) > toleranceSeconds) {\n throw new SiglumeWebhookSignatureError(\"Webhook timestamp is outside the allowed tolerance window.\");\n }\n const expected = await computeWebhookSignature(signing_secret, body, { timestamp });\n if (!(await timingSafeEqualHex(expected, signature))) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature did not match.\");\n }\n return { timestamp, signature };\n}\n\nexport function parseDirectRequestPaymentWebhookEvent(payload: unknown): DirectRequestPaymentWebhookEvent {\n const event = requireRecord(payload, \"webhook event\");\n const data = requireRecord(event.data, \"webhook event data\");\n const parsed = {\n ...event,\n id: requireNonEmpty(stringOrNull(event.id) ?? \"\", \"webhook event id\"),\n type: requireNonEmpty(stringOrNull(event.type) ?? \"\", \"webhook event type\"),\n api_version: requireNonEmpty(stringOrNull(event.api_version) ?? \"\", \"webhook api_version\"),\n occurred_at: requireNonEmpty(stringOrNull(event.occurred_at) ?? \"\", \"webhook occurred_at\"),\n data: { ...data },\n } as DirectRequestPaymentWebhookEvent;\n if (parsed.type === \"direct_payment.confirmed\" && parsed.data.mode !== DIRECT_REQUEST_PAYMENT_MODE) {\n throw new SiglumeWebhookPayloadError(\"direct_payment.confirmed webhook must carry data.mode='external_402'.\");\n }\n return parsed;\n}\n\nexport async function verifyDirectRequestPaymentWebhook(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<{ event: DirectRequestPaymentWebhookEvent; verification: WebhookSignatureVerification }> {\n const verification = await verifyWebhookSignature(signing_secret, body, signature_header, options);\n const text = new TextDecoder().decode(bodyBytes(body));\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new SiglumeWebhookPayloadError(\"Webhook body must contain valid JSON.\");\n }\n return { event: parseDirectRequestPaymentWebhookEvent(parsed), verification };\n}\n\nexport const createExternal402Challenge = createDirectRequestPaymentChallenge;\nexport const verifyExternal402Challenge = verifyDirectRequestPaymentChallenge;\nexport const createExternal402RecurringChallenge = createDirectRequestPaymentRecurringChallenge;\nexport const verifyExternal402RecurringChallenge = verifyDirectRequestPaymentRecurringChallenge;\n\nfunction normalizeMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9._-]{0,95}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be a lowercase key using letters, numbers, dot, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeSelfServiceMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9_-]{2,63}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be 3-64 chars using lowercase letters, numbers, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeBillingPlan(value: string): DirectRequestPaymentBillingPlan {\n const plan = requireNonEmpty(value, \"billing_plan\").toLowerCase();\n if (plan === \"launch\" || plan === \"free\" || plan === \"starter\" || plan === \"growth\" || plan === \"pro\") {\n return plan;\n }\n throw new SiglumeDirectRequestPaymentError(\"billing_plan must be launch, starter, growth, or pro.\");\n}\n\nfunction normalizeCurrency(value: string): DirectRequestPaymentCurrency {\n const currency = requireNonEmpty(value, \"currency\").toUpperCase();\n if (currency !== \"JPY\" && currency !== \"USD\") {\n throw new SiglumeDirectRequestPaymentError(\"currency must be JPY or USD.\");\n }\n return currency;\n}\n\nfunction normalizeToken(value: string): DirectRequestPaymentToken {\n const token = requireNonEmpty(value, \"token_symbol\").toUpperCase();\n if (token !== \"JPYC\" && token !== \"USDC\") {\n throw new SiglumeDirectRequestPaymentError(\"token_symbol must be JPYC or USDC.\");\n }\n return token;\n}\n\nfunction normalizeAllowedCurrencies(value: Record<string, string> | Array<DirectRequestPaymentCurrency | string>): Record<string, string> {\n const normalized: Record<string, string> = {};\n if (Array.isArray(value)) {\n for (const item of value) {\n const currency = normalizeCurrency(item);\n normalized[currency] = defaultTokenForCurrency(currency);\n }\n } else if (isRecord(value)) {\n for (const [rawCurrency, rawToken] of Object.entries(value)) {\n normalized[normalizeCurrency(rawCurrency)] = normalizeToken(String(rawToken));\n }\n } else {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must be an array or a currency-to-token object.\");\n }\n if (Object.keys(normalized).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must include at least one currency.\");\n }\n return normalized;\n}\n\nfunction defaultTokenForCurrency(currency: DirectRequestPaymentCurrency): DirectRequestPaymentToken {\n return currency === \"JPY\" ? \"JPYC\" : \"USDC\";\n}\n\nfunction positiveInteger(value: number, name: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a positive safe integer.`);\n }\n return parsed;\n}\n\nfunction requireNonEmpty(value: string, name: string): string {\n const text = String(value ?? \"\").trim();\n if (!text) {\n throw new SiglumeDirectRequestPaymentError(`${name} is required.`);\n }\n return text;\n}\n\nfunction normalizeChallengeNonce(value: string): string {\n const nonce = requireNonEmpty(value, \"nonce\");\n if (nonce.includes(\":\")) {\n throw new SiglumeDirectRequestPaymentError(\"nonce must not contain ':'.\");\n }\n return nonce;\n}\n\nfunction normalizeRecurringCadence(value: string): DirectRequestPaymentRecurringCadence {\n const cadence = requireNonEmpty(value, \"cadence\").toLowerCase();\n if (cadence !== \"monthly\" && cadence !== \"daily\") {\n throw new SiglumeDirectRequestPaymentError(\n 'cadence must be \"monthly\" (subscription) or \"daily\" (scheduled autopay).',\n );\n }\n return cadence;\n}\n\nfunction cloneJsonObject(value: Record<string, unknown>, name: string): Record<string, unknown> {\n try {\n const cloned = JSON.parse(JSON.stringify(value)) as unknown;\n if (!isRecord(cloned)) {\n throw new Error(\"not an object\");\n }\n return cloned;\n } catch (error) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a JSON-serializable object.`);\n }\n}\n\nfunction parseJson(rawText: string): unknown {\n try {\n return JSON.parse(rawText);\n } catch (error) {\n throw new SiglumeApiError(\"Siglume API returned invalid JSON.\", {\n status: 502,\n code: \"INVALID_JSON_RESPONSE\",\n data: rawText,\n });\n }\n}\n\nfunction stringOrNull(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const text = value.trim();\n return text ? text : null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requireRecord(value: unknown, name: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new SiglumeWebhookPayloadError(`${name} must be an object.`);\n }\n return value;\n}\n\nfunction envValue(name: string): string | undefined {\n if (typeof process === \"undefined\") {\n return undefined;\n }\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\nfunction bodyBytes(body: Uint8Array | ArrayBuffer | string | Record<string, unknown>): Uint8Array {\n if (body instanceof Uint8Array) {\n return body;\n }\n if (body instanceof ArrayBuffer) {\n return new Uint8Array(body);\n }\n if (typeof body === \"string\") {\n return new TextEncoder().encode(body);\n }\n if (isRecord(body)) {\n return new TextEncoder().encode(JSON.stringify(body));\n }\n throw new SiglumeWebhookPayloadError(\"Webhook body must be raw bytes, a string, or a JSON object.\");\n}\n\nfunction parseSignatureHeader(signatureHeader: string): { timestamp: number; signature: string } {\n let timestamp: number | null = null;\n let signature: string | null = null;\n for (const item of String(signatureHeader ?? \"\").split(\",\")) {\n const [key, value] = item.trim().split(\"=\", 2);\n if (key === \"t\") {\n const parsed = Number.parseInt(value ?? \"\", 10);\n if (!Number.isFinite(parsed)) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature timestamp is invalid.\");\n }\n timestamp = parsed;\n }\n if (key === \"v1\") {\n signature = String(value ?? \"\").trim();\n }\n }\n if (timestamp === null || !signature) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature header is incomplete.\");\n }\n return { timestamp, signature };\n}\n\nasync function randomNonce(): Promise<string> {\n if (globalThis.crypto?.randomUUID) {\n return globalThis.crypto.randomUUID();\n }\n const bytes = new Uint8Array(16);\n if (globalThis.crypto?.getRandomValues) {\n globalThis.crypto.getRandomValues(bytes);\n } else if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n bytes.set(crypto.randomBytes(16));\n } else {\n throw new SiglumeDirectRequestPaymentError(\"Crypto random number generation is unavailable in this runtime.\");\n }\n return bytesToHex(bytes);\n}\n\nasync function hmacSha256Hex(secret: string, payload: Uint8Array): Promise<string> {\n if (globalThis.crypto?.subtle) {\n const stablePayload = new Uint8Array(payload.byteLength);\n stablePayload.set(payload);\n const key = await globalThis.crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const digest = await globalThis.crypto.subtle.sign(\"HMAC\", key, stablePayload);\n return bytesToHex(new Uint8Array(digest));\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return crypto.createHmac(\"sha256\", secret).update(Buffer.from(payload)).digest(\"hex\");\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for HMAC-SHA256 in this runtime.\");\n}\n\nasync function sha256Prefixed(material: string): Promise<string> {\n const bytes = new TextEncoder().encode(material);\n if (globalThis.crypto?.subtle) {\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n return `sha256:${bytesToHex(new Uint8Array(digest))}`;\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return `sha256:${crypto.createHash(\"sha256\").update(Buffer.from(bytes)).digest(\"hex\")}`;\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for SHA-256 in this runtime.\");\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return [...bytes].map((item) => item.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const normalized = String(hex ?? \"\").trim().toLowerCase();\n if (normalized.length % 2 !== 0 || !/^[0-9a-f]*$/.test(normalized)) {\n throw new SiglumeWebhookSignatureError(\"Hex digest is invalid.\");\n }\n const bytes = new Uint8Array(normalized.length / 2);\n for (let index = 0; index < normalized.length; index += 2) {\n bytes[index / 2] = Number.parseInt(normalized.slice(index, index + 2), 16);\n }\n return bytes;\n}\n\nasync function timingSafeEqualHex(left: string, right: string): Promise<boolean> {\n const leftBytes = hexToBytes(left);\n const rightBytes = hexToBytes(right);\n if (leftBytes.length !== rightBytes.length) {\n return false;\n }\n let diff = 0;\n for (let index = 0; index < leftBytes.length; index += 1) {\n diff |= leftBytes[index]! ^ rightBytes[index]!;\n }\n return diff === 0;\n}\n"],"mappings":";AAAO,IAAM,2BAA2B;AACjC,IAAM,0CAA0C;AAIhD,IAAM,oDAAoD;AAC1D,IAAM,8BAA8B;AACpC,IAAM,sCAAsC;AAC5C,IAAM,gDAAgD;AACtD,IAAM,wCAAwC;AAC9C,IAAM,o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MAAI,OAAO;AACX,WAAS,QAAQ,GAAG,QAAQ,UAAU,QAAQ,SAAS,GAAG;AACxD,YAAQ,UAAU,KAAK,IAAK,WAAW,KAAK;AAAA,EAC9C;AACA,SAAO,SAAS;AAClB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export const DEFAULT_SIGLUME_API_BASE = \"https://siglume.com/v1\";\nexport const DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME = \"siglume-external-402-v1\";\n// Recurring (subscription / scheduled autopay) approval uses a DISTINCT scheme\n// with cadence bound into the HMAC, so a one-time checkout challenge can never\n// be replayed as a recurring authorization and vice versa.\nexport const DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME = \"siglume-external-402-recurring-v1\";\nexport const DIRECT_REQUEST_PAYMENT_MODE = \"external_402\";\nexport const DIRECT_REQUEST_PAYMENT_RECEIPT_KIND = \"sdrp_direct_payment\";\nexport const DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND = \"sdrp_direct_payment_allowance\";\nexport const DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE = \"sdrp_direct_payment_requirement\";\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;\n\nexport type DirectRequestPaymentCurrency = \"JPY\" | \"USD\";\nexport type DirectRequestPaymentToken = \"JPYC\" | \"USDC\";\n\nexport interface DirectRequestPaymentChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface ParsedDirectRequestPaymentChallenge {\n scheme: string;\n nonce: string;\n signature: string;\n}\n\n/** \"monthly\" authorizes a Siglume-swept subscription; \"daily\" authorizes\n * merchant-triggered scheduled autopay. It is an approval tag, not a\n * run-count limiter. */\nexport type DirectRequestPaymentRecurringCadence = \"monthly\" | \"daily\";\n\nexport interface DirectRequestPaymentRecurringChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentRecurringChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n cadence: DirectRequestPaymentRecurringCadence;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface Web3TransactionRequest {\n network?: string;\n chain_id?: number;\n from?: string;\n to?: string;\n data?: string;\n value?: string | number;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectPaymentRequirement {\n direct_payment_requirement_id: string;\n requirement_id: string;\n id: string;\n mode: string;\n merchant?: string | null;\n challenge_hash?: string | null;\n buyer_user_id: string;\n agent_id?: string | null;\n product_listing_id: string;\n listing_id: string;\n access_grant_id?: string | null;\n capability_key: string;\n requirement_hash: string;\n request_hash: string;\n siglume_signature: string;\n token_symbol: string;\n currency: string;\n amount_minor: number;\n fee_bps: number;\n status: string;\n expires_at?: string | null;\n confirmed_at?: string | null;\n spent_at?: string | null;\n chain_receipt_id?: string | null;\n transaction_request: Web3TransactionRequest;\n approve_transaction_request?: Web3TransactionRequest | null;\n buyer_confirmation?: string | null;\n non_custodial: boolean;\n metadata_jsonb?: Record<string, unknown>;\n created_at?: string | null;\n updated_at?: string | null;\n}\n\nexport interface DirectPaymentRequirementCreateInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n token_symbol?: DirectRequestPaymentToken | string;\n allowance_amount_minor?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectPaymentVerifyInput {\n receipt_id?: string | null;\n chain_receipt_id?: string | null;\n await_finality?: boolean;\n await_required_status?: string | null;\n await_timeout_seconds?: number;\n await_poll_seconds?: number;\n}\n\nexport interface Web3PreparedTransactionExecutePayload {\n transaction_request: Web3TransactionRequest;\n receipt_kind: string;\n reference_type: typeof DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE;\n reference_id: string;\n metadata?: Record<string, unknown>;\n await_finality?: boolean;\n}\n\nexport interface Web3PreparedTransactionExecuteResult {\n receipt?: Record<string, unknown>;\n finalization?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentClientOptions {\n auth_token?: string;\n base_url?: string;\n fetch?: typeof fetch;\n timeout_ms?: number;\n user_agent?: string;\n}\n\nexport type DirectRequestPaymentBillingPlan = \"launch\" | \"free\" | \"starter\" | \"growth\" | \"pro\";\n\nexport interface DirectRequestPaymentMerchantAccount {\n merchant_account_id: string;\n merchant: string;\n merchant_user_id: string;\n user_wallet_id?: string | null;\n billing_mandate_id?: string | null;\n display_name?: string | null;\n status?: string | null;\n billing_status?: string | null;\n billing_plan?: string | null;\n billing_currency?: string | null;\n token_symbol?: string | null;\n monthly_fee_minor?: number | null;\n settlement_fee_bps?: number | null;\n settlement_fee_min_minor?: number | null;\n included_monthly_payments?: number | null;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentMerchantSetupInput {\n merchant: string;\n display_name?: string;\n billing_plan?: DirectRequestPaymentBillingPlan | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n allowed_currencies?: Record<string, string> | Array<DirectRequestPaymentCurrency | string>;\n webhook_callback_url?: string;\n billing_mandate_cap_minor?: number;\n max_amount_minor?: number;\n}\n\nexport interface DirectRequestPaymentMerchantBillingMandateInput {\n currency?: DirectRequestPaymentCurrency | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n max_amount_minor?: number;\n}\n\nexport interface DirectRequestPaymentMerchantResponse {\n merchant_account: DirectRequestPaymentMerchantAccount;\n challenge_secret?: string | null;\n challenge_secret_created?: boolean;\n created?: boolean | null;\n listing_id?: string | null;\n mandate?: Record<string, unknown> | null;\n next_steps?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscriptionInput {\n callback_url: string;\n description?: string;\n event_types?: string[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscription {\n webhook_subscription_id?: string;\n subscription_id?: string;\n id?: string;\n callback_url?: string;\n signing_secret?: string;\n status?: string;\n event_types?: string[];\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupInput extends DirectRequestPaymentMerchantSetupInput {\n create_webhook_subscription?: boolean;\n prepare_billing_mandate?: boolean;\n webhook_event_types?: string[];\n webhook_description?: string;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupResult {\n merchant: DirectRequestPaymentMerchantResponse;\n billing_mandate?: DirectRequestPaymentMerchantResponse | null;\n webhook_subscription?: DirectRequestPaymentWebhookSubscription | null;\n env: Record<string, string>;\n}\n\nexport interface SiglumeEnvelopeMeta {\n request_id?: string | null;\n trace_id?: string | null;\n [key: string]: unknown;\n}\n\nexport interface WebhookSignatureVerification {\n timestamp: number;\n signature: string;\n}\n\nexport interface DirectRequestPaymentWebhookEvent {\n id: string;\n type: \"direct_payment.confirmed\" | string;\n api_version: string;\n occurred_at: string;\n data: {\n mode?: string;\n merchant?: string;\n direct_payment_requirement_id?: string;\n requirement_id?: string;\n challenge_hash?: string;\n amount_minor?: number;\n currency?: string;\n token_symbol?: string;\n status?: string;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport class SiglumeDirectRequestPaymentError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeDirectRequestPaymentError\";\n }\n}\n\nexport class SiglumeApiError extends SiglumeDirectRequestPaymentError {\n readonly status: number;\n readonly code: string;\n readonly data: unknown;\n\n constructor(message: string, options: { status: number; code?: string; data?: unknown }) {\n super(message);\n this.name = \"SiglumeApiError\";\n this.status = options.status;\n this.code = options.code ?? \"SIGLUME_API_ERROR\";\n this.data = options.data;\n }\n}\n\nexport class SiglumeWebhookSignatureError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookSignatureError\";\n }\n}\n\nexport class SiglumeWebhookPayloadError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookPayloadError\";\n }\n}\n\nexport class DirectRequestPaymentClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A buyer Siglume bearer token is required for Direct Request Payment API calls. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? \"@siglume/direct-request-payment/0.3.6\";\n this.fetch_impl = fetchImpl;\n }\n\n async createPaymentRequirement(input: DirectPaymentRequirementCreateInput): Promise<DirectPaymentRequirement> {\n const payload: Record<string, unknown> = {\n mode: DIRECT_REQUEST_PAYMENT_MODE,\n merchant: normalizeMerchant(input.merchant),\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n currency: normalizeCurrency(input.currency),\n challenge: requireNonEmpty(input.challenge, \"challenge\"),\n };\n if (input.token_symbol !== undefined) {\n payload.token_symbol = normalizeToken(input.token_symbol);\n }\n if (input.allowance_amount_minor !== undefined) {\n payload.allowance_amount_minor = positiveInteger(input.allowance_amount_minor, \"allowance_amount_minor\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectPaymentRequirement>(\"POST\", \"/sdrp/direct-payments/requirements\", payload);\n }\n\n async getPaymentRequirement(requirement_id: string): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"GET\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}`,\n );\n }\n\n async verifyPaymentRequirement(\n requirement_id: string,\n input: DirectPaymentVerifyInput,\n ): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"POST\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}/verify`,\n input,\n );\n }\n\n async executePreparedTransaction(\n payload: Web3PreparedTransactionExecutePayload,\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.request<Web3PreparedTransactionExecuteResult>(\n \"POST\",\n \"/market/web3/transactions/execute-prepared\",\n payload,\n );\n }\n\n async executePaymentTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildPaymentExecutionPayload(requirement, options));\n }\n\n async executeAllowanceTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildAllowanceExecutionPayload(requirement, options));\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport class DirectRequestPaymentMerchantClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_MERCHANT_AUTH_TOKEN\") ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A merchant Siglume bearer token is required for Direct Request Payment merchant setup. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? \"@siglume/direct-request-payment/0.3.6\";\n this.fetch_impl = fetchImpl;\n }\n\n async setupMerchant(input: DirectRequestPaymentMerchantSetupInput): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {\n merchant: normalizeSelfServiceMerchant(input.merchant),\n billing_plan: normalizeBillingPlan(input.billing_plan ?? \"launch\"),\n billing_currency: normalizeCurrency(input.billing_currency ?? \"JPY\"),\n };\n if (input.display_name !== undefined) {\n payload.display_name = requireNonEmpty(input.display_name, \"display_name\");\n }\n if (input.allowed_currencies !== undefined) {\n payload.allowed_currencies = normalizeAllowedCurrencies(input.allowed_currencies);\n }\n if (input.webhook_callback_url !== undefined) {\n payload.webhook_callback_url = requireNonEmpty(input.webhook_callback_url, \"webhook_callback_url\");\n }\n if (input.billing_mandate_cap_minor !== undefined) {\n payload.billing_mandate_cap_minor = positiveInteger(input.billing_mandate_cap_minor, \"billing_mandate_cap_minor\");\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\"POST\", \"/sdrp/direct-payments/merchants\", payload);\n }\n\n async getMerchant(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"GET\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}`,\n );\n }\n\n async rotateChallengeSecret(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/challenge-secret/rotate`,\n );\n }\n\n async prepareBillingMandate(\n merchant: string,\n input: DirectRequestPaymentMerchantBillingMandateInput = {},\n ): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {};\n if (input.currency !== undefined) {\n payload.currency = normalizeCurrency(input.currency);\n }\n if (input.billing_currency !== undefined) {\n payload.billing_currency = normalizeCurrency(input.billing_currency);\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/billing-mandate`,\n payload,\n );\n }\n\n async createWebhookSubscription(\n input: DirectRequestPaymentWebhookSubscriptionInput,\n ): Promise<DirectRequestPaymentWebhookSubscription> {\n const payload: Record<string, unknown> = {\n callback_url: requireNonEmpty(input.callback_url, \"callback_url\"),\n event_types: input.event_types?.length\n ? input.event_types.map((eventType) => requireNonEmpty(eventType, \"event_type\"))\n : [\"direct_payment.confirmed\", \"direct_payment.spent\"],\n };\n if (input.description !== undefined) {\n payload.description = requireNonEmpty(input.description, \"description\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectRequestPaymentWebhookSubscription>(\"POST\", \"/market/webhooks/subscriptions\", payload);\n }\n\n async setupCheckout(input: DirectRequestPaymentCheckoutSetupInput): Promise<DirectRequestPaymentCheckoutSetupResult> {\n const merchant = await this.setupMerchant(input);\n const merchantKey = merchant.merchant_account.merchant;\n const billing_mandate = input.prepare_billing_mandate === false\n ? null\n : await this.prepareBillingMandate(merchantKey, {\n billing_currency: merchant.merchant_account.billing_currency ?? input.billing_currency ?? \"JPY\",\n max_amount_minor: input.max_amount_minor ?? input.billing_mandate_cap_minor,\n });\n const shouldCreateWebhook = input.create_webhook_subscription ?? Boolean(input.webhook_callback_url);\n const webhook_subscription = shouldCreateWebhook && input.webhook_callback_url\n ? await this.createWebhookSubscription({\n callback_url: input.webhook_callback_url,\n description: input.webhook_description ?? `${merchantKey} Direct Request Payment`,\n event_types: input.webhook_event_types,\n metadata: { merchant: merchantKey, sdk: \"@siglume/direct-request-payment\" },\n })\n : null;\n const env: Record<string, string> = {\n SIGLUME_DIRECT_PAYMENT_MERCHANT: merchantKey,\n };\n if (merchant.challenge_secret) {\n env.SIGLUME_DIRECT_PAYMENT_CHALLENGE_SECRET = merchant.challenge_secret;\n }\n const webhookSecret = stringOrNull(webhook_subscription?.signing_secret);\n if (webhookSecret) {\n env.SIGLUME_WEBHOOK_SECRET = webhookSecret;\n }\n return { merchant, billing_mandate, webhook_subscription, env };\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport async function createDirectRequestPaymentChallenge(\n input: DirectRequestPaymentChallengeInput,\n): Promise<DirectRequestPaymentChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = normalizeChallengeNonce(input.nonce);\n const material = `${merchant}:${amount}:${currency}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport function parseDirectRequestPaymentChallenge(challenge: string): ParsedDirectRequestPaymentChallenge {\n const parts = requireNonEmpty(challenge, \"challenge\").split(\":\");\n if (parts.length !== 3) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge must be scheme:nonce:signature.\");\n }\n const [scheme, nonce, signature] = parts;\n if (!scheme || !nonce || !signature) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge is incomplete.\");\n }\n return { scheme, nonce, signature };\n}\n\n/** Merchant-side, ONE-TIME approval of a recurring authorization: amount +\n * currency + cadence are bound into the HMAC. Recurring charges afterwards\n * are deliberately challenge-free; the recurring authorization and the\n * buyer's mandate/budget caps are the per-charge integrity checks. Cadence\n * \"monthly\" = subscription, \"daily\" = scheduled autopay approval tag. */\nexport async function createDirectRequestPaymentRecurringChallenge(\n input: DirectRequestPaymentRecurringChallengeInput,\n): Promise<DirectRequestPaymentRecurringChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentRecurringChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentRecurringChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = normalizeChallengeNonce(input.nonce);\n // MUST stay byte-identical to the server's\n // _external_402_recurring_challenge_signature — both sides change together.\n const material = `${merchant}:${amount}:${currency}:${cadence}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport async function verifyDirectRequestPaymentRecurringChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentRecurringChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n cadence: input.cadence,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function verifyDirectRequestPaymentChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function directRequestPaymentChallengeHash(challenge: string): Promise<string> {\n return sha256Prefixed(requireNonEmpty(challenge, \"challenge\"));\n}\n\nexport async function directRequestPaymentRequestHash(input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n}): Promise<string> {\n const material = `${normalizeMerchant(input.merchant)}${positiveInteger(input.amount_minor, \"amount_minor\")}${normalizeCurrency(input.currency)}${requireNonEmpty(input.challenge, \"challenge\")}`;\n return sha256Prefixed(material);\n}\n\nexport function buildPaymentExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n return buildPreparedTransactionExecutionPayload(requirement, requirement.transaction_request, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildAllowanceExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n const approveRequest = requirement.approve_transaction_request;\n if (!approveRequest || Object.keys(approveRequest).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"This payment requirement does not include an allowance approval transaction.\");\n }\n return buildPreparedTransactionExecutionPayload(requirement, approveRequest, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildPreparedTransactionExecutionPayload(\n requirement: DirectPaymentRequirement,\n transaction_request: Web3TransactionRequest,\n options: {\n receipt_kind: string;\n await_finality?: boolean;\n metadata?: Record<string, unknown>;\n },\n): Web3PreparedTransactionExecutePayload {\n const metadata = {\n ...(isRecord(transaction_request.metadata_jsonb) ? transaction_request.metadata_jsonb : {}),\n ...(options.metadata ?? {}),\n };\n return {\n transaction_request,\n receipt_kind: requireNonEmpty(options.receipt_kind, \"receipt_kind\"),\n reference_type: DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE,\n reference_id: requirement.requirement_id,\n metadata,\n await_finality: Boolean(options.await_finality),\n };\n}\n\nexport async function computeWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp: number },\n): Promise<string> {\n if (!signing_secret) {\n throw new SiglumeWebhookSignatureError(\"SIGLUME webhook signing secret is required.\");\n }\n const timestamp = Math.trunc(options.timestamp);\n const bytes = bodyBytes(body);\n const prefix = new TextEncoder().encode(`${timestamp}.`);\n const payload = new Uint8Array(prefix.length + bytes.length);\n payload.set(prefix, 0);\n payload.set(bytes, prefix.length);\n return hmacSha256Hex(signing_secret, payload);\n}\n\nexport async function buildWebhookSignatureHeader(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp?: number } = {},\n): Promise<string> {\n const timestamp = Math.trunc(options.timestamp ?? Date.now() / 1000);\n const signature = await computeWebhookSignature(signing_secret, body, { timestamp });\n return `t=${timestamp},v1=${signature}`;\n}\n\nexport async function verifyWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<WebhookSignatureVerification> {\n const { timestamp, signature } = parseSignatureHeader(signature_header);\n const toleranceSeconds = Math.max(1, Math.trunc(options.tolerance_seconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS));\n const nowSeconds = Math.trunc(options.now ?? Date.now() / 1000);\n if (Math.abs(nowSeconds - timestamp) > toleranceSeconds) {\n throw new SiglumeWebhookSignatureError(\"Webhook timestamp is outside the allowed tolerance window.\");\n }\n const expected = await computeWebhookSignature(signing_secret, body, { timestamp });\n if (!(await timingSafeEqualHex(expected, signature))) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature did not match.\");\n }\n return { timestamp, signature };\n}\n\nexport function parseDirectRequestPaymentWebhookEvent(payload: unknown): DirectRequestPaymentWebhookEvent {\n const event = requireRecord(payload, \"webhook event\");\n const data = requireRecord(event.data, \"webhook event data\");\n const parsed = {\n ...event,\n id: requireNonEmpty(stringOrNull(event.id) ?? \"\", \"webhook event id\"),\n type: requireNonEmpty(stringOrNull(event.type) ?? \"\", \"webhook event type\"),\n api_version: requireNonEmpty(stringOrNull(event.api_version) ?? \"\", \"webhook api_version\"),\n occurred_at: requireNonEmpty(stringOrNull(event.occurred_at) ?? \"\", \"webhook occurred_at\"),\n data: { ...data },\n } as DirectRequestPaymentWebhookEvent;\n if (parsed.type === \"direct_payment.confirmed\" && parsed.data.mode !== DIRECT_REQUEST_PAYMENT_MODE) {\n throw new SiglumeWebhookPayloadError(\"direct_payment.confirmed webhook must carry data.mode='external_402'.\");\n }\n return parsed;\n}\n\nexport async function verifyDirectRequestPaymentWebhook(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<{ event: DirectRequestPaymentWebhookEvent; verification: WebhookSignatureVerification }> {\n const verification = await verifyWebhookSignature(signing_secret, body, signature_header, options);\n const text = new TextDecoder().decode(bodyBytes(body));\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new SiglumeWebhookPayloadError(\"Webhook body must contain valid JSON.\");\n }\n return { event: parseDirectRequestPaymentWebhookEvent(parsed), verification };\n}\n\nexport const createExternal402Challenge = createDirectRequestPaymentChallenge;\nexport const verifyExternal402Challenge = verifyDirectRequestPaymentChallenge;\nexport const createExternal402RecurringChallenge = createDirectRequestPaymentRecurringChallenge;\nexport const verifyExternal402RecurringChallenge = verifyDirectRequestPaymentRecurringChallenge;\n\nfunction normalizeMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9._-]{0,95}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be a lowercase key using letters, numbers, dot, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeSelfServiceMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9_-]{2,63}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be 3-64 chars using lowercase letters, numbers, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeBillingPlan(value: string): DirectRequestPaymentBillingPlan {\n const plan = requireNonEmpty(value, \"billing_plan\").toLowerCase();\n if (plan === \"launch\" || plan === \"free\" || plan === \"starter\" || plan === \"growth\" || plan === \"pro\") {\n return plan;\n }\n throw new SiglumeDirectRequestPaymentError(\"billing_plan must be launch, starter, growth, or pro.\");\n}\n\nfunction normalizeCurrency(value: string): DirectRequestPaymentCurrency {\n const currency = requireNonEmpty(value, \"currency\").toUpperCase();\n if (currency !== \"JPY\" && currency !== \"USD\") {\n throw new SiglumeDirectRequestPaymentError(\"currency must be JPY or USD.\");\n }\n return currency;\n}\n\nfunction normalizeToken(value: string): DirectRequestPaymentToken {\n const token = requireNonEmpty(value, \"token_symbol\").toUpperCase();\n if (token !== \"JPYC\" && token !== \"USDC\") {\n throw new SiglumeDirectRequestPaymentError(\"token_symbol must be JPYC or USDC.\");\n }\n return token;\n}\n\nfunction normalizeAllowedCurrencies(value: Record<string, string> | Array<DirectRequestPaymentCurrency | string>): Record<string, string> {\n const normalized: Record<string, string> = {};\n if (Array.isArray(value)) {\n for (const item of value) {\n const currency = normalizeCurrency(item);\n normalized[currency] = defaultTokenForCurrency(currency);\n }\n } else if (isRecord(value)) {\n for (const [rawCurrency, rawToken] of Object.entries(value)) {\n normalized[normalizeCurrency(rawCurrency)] = normalizeToken(String(rawToken));\n }\n } else {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must be an array or a currency-to-token object.\");\n }\n if (Object.keys(normalized).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must include at least one currency.\");\n }\n return normalized;\n}\n\nfunction defaultTokenForCurrency(currency: DirectRequestPaymentCurrency): DirectRequestPaymentToken {\n return currency === \"JPY\" ? \"JPYC\" : \"USDC\";\n}\n\nfunction positiveInteger(value: number, name: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a positive safe integer.`);\n }\n return parsed;\n}\n\nfunction requireNonEmpty(value: string, name: string): string {\n const text = String(value ?? \"\").trim();\n if (!text) {\n throw new SiglumeDirectRequestPaymentError(`${name} is required.`);\n }\n return text;\n}\n\nfunction normalizeChallengeNonce(value: string): string {\n const nonce = requireNonEmpty(value, \"nonce\");\n if (nonce.includes(\":\")) {\n throw new SiglumeDirectRequestPaymentError(\"nonce must not contain ':'.\");\n }\n return nonce;\n}\n\nfunction normalizeRecurringCadence(value: string): DirectRequestPaymentRecurringCadence {\n const cadence = requireNonEmpty(value, \"cadence\").toLowerCase();\n if (cadence !== \"monthly\" && cadence !== \"daily\") {\n throw new SiglumeDirectRequestPaymentError(\n 'cadence must be \"monthly\" (subscription) or \"daily\" (scheduled autopay).',\n );\n }\n return cadence;\n}\n\nfunction cloneJsonObject(value: Record<string, unknown>, name: string): Record<string, unknown> {\n try {\n const cloned = JSON.parse(JSON.stringify(value)) as unknown;\n if (!isRecord(cloned)) {\n throw new Error(\"not an object\");\n }\n return cloned;\n } catch (error) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a JSON-serializable object.`);\n }\n}\n\nfunction parseJson(rawText: string): unknown {\n try {\n return JSON.parse(rawText);\n } catch (error) {\n throw new SiglumeApiError(\"Siglume API returned invalid JSON.\", {\n status: 502,\n code: \"INVALID_JSON_RESPONSE\",\n data: rawText,\n });\n }\n}\n\nfunction stringOrNull(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const text = value.trim();\n return text ? text : null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requireRecord(value: unknown, name: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new SiglumeWebhookPayloadError(`${name} must be an object.`);\n }\n return value;\n}\n\nfunction envValue(name: string): string | undefined {\n if (typeof process === \"undefined\") {\n return undefined;\n }\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\nfunction bodyBytes(body: Uint8Array | ArrayBuffer | string | Record<string, unknown>): Uint8Array {\n if (body instanceof Uint8Array) {\n return body;\n }\n if (body instanceof ArrayBuffer) {\n return new Uint8Array(body);\n }\n if (typeof body === \"string\") {\n return new TextEncoder().encode(body);\n }\n if (isRecord(body)) {\n return new TextEncoder().encode(JSON.stringify(body));\n }\n throw new SiglumeWebhookPayloadError(\"Webhook body must be raw bytes, a string, or a JSON object.\");\n}\n\nfunction parseSignatureHeader(signatureHeader: string): { timestamp: number; signature: string } {\n let timestamp: number | null = null;\n let signature: string | null = null;\n for (const item of String(signatureHeader ?? \"\").split(\",\")) {\n const [key, value] = item.trim().split(\"=\", 2);\n if (key === \"t\") {\n const parsed = Number.parseInt(value ?? \"\", 10);\n if (!Number.isFinite(parsed)) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature timestamp is invalid.\");\n }\n timestamp = parsed;\n }\n if (key === \"v1\") {\n signature = String(value ?? \"\").trim();\n }\n }\n if (timestamp === null || !signature) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature header is incomplete.\");\n }\n return { timestamp, signature };\n}\n\nasync function randomNonce(): Promise<string> {\n if (globalThis.crypto?.randomUUID) {\n return globalThis.crypto.randomUUID();\n }\n const bytes = new Uint8Array(16);\n if (globalThis.crypto?.getRandomValues) {\n globalThis.crypto.getRandomValues(bytes);\n } else if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n bytes.set(crypto.randomBytes(16));\n } else {\n throw new SiglumeDirectRequestPaymentError(\"Crypto random number generation is unavailable in this runtime.\");\n }\n return bytesToHex(bytes);\n}\n\nasync function hmacSha256Hex(secret: string, payload: Uint8Array): Promise<string> {\n if (globalThis.crypto?.subtle) {\n const stablePayload = new Uint8Array(payload.byteLength);\n stablePayload.set(payload);\n const key = await globalThis.crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const digest = await globalThis.crypto.subtle.sign(\"HMAC\", key, stablePayload);\n return bytesToHex(new Uint8Array(digest));\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return crypto.createHmac(\"sha256\", secret).update(Buffer.from(payload)).digest(\"hex\");\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for HMAC-SHA256 in this runtime.\");\n}\n\nasync function sha256Prefixed(material: string): Promise<string> {\n const bytes = new TextEncoder().encode(material);\n if (globalThis.crypto?.subtle) {\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n return `sha256:${bytesToHex(new Uint8Array(digest))}`;\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return `sha256:${crypto.createHash(\"sha256\").update(Buffer.from(bytes)).digest(\"hex\")}`;\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for SHA-256 in this runtime.\");\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return [...bytes].map((item) => item.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const normalized = String(hex ?? \"\").trim().toLowerCase();\n if (normalized.length % 2 !== 0 || !/^[0-9a-f]*$/.test(normalized)) {\n throw new SiglumeWebhookSignatureError(\"Hex digest is invalid.\");\n }\n const bytes = new Uint8Array(normalized.length / 2);\n for (let index = 0; index < normalized.length; index += 2) {\n bytes[index / 2] = Number.parseInt(normalized.slice(index, index + 2), 16);\n }\n return bytes;\n}\n\nasync function timingSafeEqualHex(left: string, right: string): Promise<boolean> {\n const leftBytes = hexToBytes(left);\n const rightBytes = hexToBytes(right);\n if (leftBytes.length !== rightBytes.length) {\n return false;\n }\n let diff = 0;\n for (let index = 0; index < leftBytes.length; index += 1) {\n diff |= leftBytes[index]! ^ rightBytes[index]!;\n }\n return diff === 0;\n}\n"],"mappings":";AAAO,IAAM,2BAA2B;AACjC,IAAM,0CAA0C;AAIhD,IAAM,oDAAoD;AAC1D,IAAM,8BAA8B;AACpC,IAAM,sCAAsC;AAC5C,IAAM,gDAAgD;AACtD,IAAM,wCAAwC;AAC9C,IAAM,oCAAoC;AA+P1C,IAAM,mCAAN,cAA+C,MAAM;AAAA,EAC1D,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,kBAAN,cAA8B,iCAAiC;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,SAAiB,SAA4D;AACvF,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ;AACtB,SAAK,OAAO,QAAQ,QAAQ;AAC5B,SAAK,OAAO,QAAQ;AAAA,EACtB;AACF;AAEO,IAAM,+BAAN,cAA2C,iCAAiC;AAAA,EACjF,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,6BAAN,cAAyC,iCAAiC;AAAA,EAC/E,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,6BAAN,MAAiC;AAAA,EAC7B;AAAA,EACA;AAAA,E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E;AAC7E;AAEA,SAAS,WAAW,KAAyB;AAC3C,QAAM,aAAa,OAAO,OAAO,EAAE,EAAE,KAAK,EAAE,YAAY;AACxD,MAAI,WAAW,SAAS,MAAM,KAAK,CAAC,cAAc,KAAK,UAAU,GAAG;AAClE,UAAM,IAAI,6BAA6B,wBAAwB;AAAA,EACjE;AACA,QAAM,QAAQ,IAAI,WAAW,WAAW,SAAS,CAAC;AAClD,WAAS,QAAQ,GAAG,QAAQ,WAAW,QAAQ,SAAS,GAAG;AACzD,UAAM,QAAQ,CAAC,IAAI,OAAO,SAAS,WAAW,MAAM,OAAO,QAAQ,CAAC,GAAG,EAAE;AAAA,EAC3E;AACA,SAAO;AACT;AAEA,eAAe,mBAAmB,MAAc,OAAiC;AAC/E,QAAM,YAAY,WAAW,IAAI;AACjC,QAAM,aAAa,WAAW,KAAK;AACnC,MAAI,UAAU,WAAW,WAAW,QAAQ;AAC1C,WAAO;AAAA,EACT;AACA,MAAI,OAAO;AACX,WAAS,QAAQ,GAAG,QAAQ,UAAU,QAAQ,SAAS,GAAG;AACxD,YAAQ,UAAU,KAAK,IAAK,WAAW,KAAK;AAAA,EAC9C;AACA,SAAO,SAAS;AAClB;","names":[]}
|
package/docs/announcement-ja.md
CHANGED
|
@@ -31,11 +31,30 @@ Siglume Direct Request Payment は、merchantが注文・金額・通貨をサ
|
|
|
31
31
|
|
|
32
32
|
| 決済金額 | 自動適用 | 選択するもの | 料金 | 精算 |
|
|
33
33
|
| --- | --- | --- | --- | --- |
|
|
34
|
-
| JPY 500超 / USD 3.00超、または即時finalityが必要 | Standard Payment / 通常決済 | Launch / Starter / Growth / Pro から1つ | Launch 1.8%、Starter 1.0%、Growth 0.7%、Pro 0.5%。最低 JPY 30 / USD 0.20 |
|
|
35
|
-
| JPY 50-500 / 約USD 0.30-3.00 | Micro Payment / マイクロペイメント | 選択不要。金額で自動適用 | USD 0.01 / Tx、約JPY 2 |
|
|
36
|
-
| JPY 1未満-49 / USD 0.01未満-約USD 0.30 | Nano Payment / ナノペイメント | 選択不要。金額で自動適用 | USD 0.001 / usage、約JPY 0.2 |
|
|
34
|
+
| JPY 500超 / USD 3.00超、または即時finalityが必要 | Standard Payment / 通常決済 | Launch / Starter / Growth / Pro から1つ | Launch 1.8%、Starter 1.0%、Growth 0.7%、Pro 0.5%。最低 JPY 30 / USD 0.20 | 決済確定後すぐにオンチェーンで精算 |
|
|
35
|
+
| JPY 50-500 / 約USD 0.30-3.00 | Micro Payment / マイクロペイメント | 選択不要。金額で自動適用 | USD 0.01 / Tx、約JPY 2 | **週次**でまとめて精算([精算スケジュール](#精算スケジュール)参照) |
|
|
36
|
+
| JPY 1未満-49 / USD 0.01未満-約USD 0.30 | Nano Payment / ナノペイメント | 選択不要。金額で自動適用 | USD 0.001 / usage、約JPY 0.2 | **月次**でまとめて精算([精算スケジュール](#精算スケジュール)参照) |
|
|
37
37
|
|
|
38
|
-
Micro / Nano
|
|
38
|
+
Standard Payment は1決済ごとに精算します。Micro / Nano は金額帯で自動適用され、週次 / 月次でまとめて精算されます。締め・支払いタイミングは下の「精算スケジュール」を参照してください。なお、少額の支払いは実行前に購入者ウォレットの予算が確認され、予算・scope・金額帯のいずれかが満たされない場合はその場で拒否され、課金は発生しません(リクエストは実行されません)。
|
|
39
|
+
|
|
40
|
+
## 精算スケジュール
|
|
41
|
+
|
|
42
|
+
3つの帯は「確定した決済がいつ精算ウォレットに着金するか」が異なります。
|
|
43
|
+
|
|
44
|
+
| 帯 | 周期 | 締め期間 | 着金タイミング |
|
|
45
|
+
| --- | --- | --- | --- |
|
|
46
|
+
| Standard Payment | 都度 | — | 各決済の確定直後にオンチェーン精算 |
|
|
47
|
+
| Micro Payment | 週次 | カレンダー週(現状は月曜 00:00 〜 翌週月曜 00:00) | 週が締まった後、受取先・出品ごとに集約してオンチェーン精算(1件以上) |
|
|
48
|
+
| Nano Payment | 月次 | カレンダー月(現状は1日 00:00 〜 翌月1日 00:00) | 月が締まった後、受取先・出品ごとに集約してオンチェーン精算(1件以上) |
|
|
49
|
+
|
|
50
|
+
- **締め期間**: Micro は1カレンダー週(月曜始まり)、Nano は1カレンダー月(1日始まり)でまとめます。正確な締め時刻はプラットフォーム管理で変更されうるため、下記「確定事項と可変事項」を参照してください。
|
|
51
|
+
- **タイムゾーン**: 締めの境界は購入者が設定した精算タイムゾーン(現状の既定は UTC)で判定され、購入者ごとに境界が少しずれることがあります。既定タイムゾーンはプラットフォーム管理で変更されることがあります。
|
|
52
|
+
- **精算バッチ/支払い実行**: 期間が締まった後、その期間分を受取先・出品・トークンごとに集約し(1件以上)、次の精算パスで自動的にオンチェーン送金します。締めと送金の間には短い(プラットフォーム管理の)遅延があります。
|
|
53
|
+
- **売上として確認できる時点**: Micro/Nano の支払いはオンチェーン精算が確定して初めて確定売上になります。それまでは「未精算」です。プラットフォームの精算ステータス/Webhook を正本としてください。
|
|
54
|
+
- **休日・失敗・再試行・繰越**: オンチェーン精算のため銀行休業日の影響はなく、曜日に関係なくカレンダー境界で締まります。精算が失敗した場合(例: 精算時に購入者ウォレットの予算が不足/無効)は自動で再試行され、その購入者の同一トークンの Micro/Nano は未解決の精算が片付くまで一時停止します。未精算額が消えることはなく、失敗した精算に紐づいたまま、再試行成功時に支払われます。
|
|
55
|
+
- **rejected / 課金なし**: 購入者ウォレットの予算は **グロス額**(料金+プロトコルフィー)で消費され、受理時から精算確定まで確保されます。予算・scope・金額帯が満たされない場合は **課金なしで拒否**され、リクエストは実行されず、精算にも計上されません。
|
|
56
|
+
|
|
57
|
+
**確定事項と可変事項**: 周期は固定です(**Micro は週次、Nano は月次**。確定はオンチェーン精算後)。正確な締め時刻、既定タイムゾーン、締めから送金までの遅延、再試行間隔はプラットフォーム側で管理され変更されうるため、暦をハードコードせずプラットフォームの精算ステータスと `fee_bps` を正本としてください。
|
|
39
58
|
|
|
40
59
|
## 最短導入
|
|
41
60
|
|
|
@@ -55,10 +74,12 @@ const setup = await merchant.setupCheckout({
|
|
|
55
74
|
max_amount_minor: 100000,
|
|
56
75
|
});
|
|
57
76
|
|
|
58
|
-
|
|
77
|
+
// setup.env には merchant key と challenge / webhook secret が入ります。
|
|
78
|
+
// secret はサーバー側の secret store に保存し、値はログ出力しないでください。
|
|
79
|
+
console.log(`Configured merchant: ${setup.env.SIGLUME_DIRECT_PAYMENT_MERCHANT}`);
|
|
59
80
|
```
|
|
60
81
|
|
|
61
|
-
`setup.env` に、サーバー側で保存すべき `SIGLUME_DIRECT_PAYMENT_MERCHANT`、`SIGLUME_DIRECT_PAYMENT_CHALLENGE_SECRET`、`SIGLUME_WEBHOOK_SECRET` が返ります。
|
|
82
|
+
`setup.env` に、サーバー側で保存すべき `SIGLUME_DIRECT_PAYMENT_MERCHANT`、`SIGLUME_DIRECT_PAYMENT_CHALLENGE_SECRET`、`SIGLUME_WEBHOOK_SECRET` が返ります。secret 値はログに出さず、secret store に保存してください。
|
|
62
83
|
|
|
63
84
|
## 料金
|
|
64
85
|
|
package/docs/api-reference.md
CHANGED
|
@@ -229,8 +229,9 @@ Use it with the authenticated buyer's Siglume bearer token. Developer Portal
|
|
|
229
229
|
`cli_` API keys are not accepted by these buyer-authenticated routes.
|
|
230
230
|
|
|
231
231
|
This client creates SDRP Standard Payment requirements for external merchant
|
|
232
|
-
checkout flows. Micro Payment and Nano Payment
|
|
233
|
-
|
|
232
|
+
checkout flows. Micro Payment and Nano Payment are applied automatically by
|
|
233
|
+
amount and settled on a weekly / monthly cadence; they are not created explicitly
|
|
234
|
+
through this client.
|
|
234
235
|
|
|
235
236
|
Payment requirements include `fee_bps` from the Siglume platform. The SDK does
|
|
236
237
|
not calculate merchant plan fees locally; see [Pricing](./pricing.md).
|
|
@@ -257,7 +258,9 @@ Calls:
|
|
|
257
258
|
POST /v1/sdrp/direct-payments/requirements
|
|
258
259
|
```
|
|
259
260
|
|
|
260
|
-
The SDK
|
|
261
|
+
The SDK sets the platform-required mode value for you; you do not pass it. (For
|
|
262
|
+
wire compatibility this is still the legacy `external_402` value — see the
|
|
263
|
+
README "Compatibility Notes".)
|
|
261
264
|
|
|
262
265
|
Input:
|
|
263
266
|
|
|
@@ -7,7 +7,7 @@ external merchant.
|
|
|
7
7
|
|
|
8
8
|
- Merchant server: owns the order, amount, currency, challenge secret, webhook
|
|
9
9
|
endpoint, and order fulfillment.
|
|
10
|
-
- Buyer: owns the Siglume wallet that pays the
|
|
10
|
+
- Buyer: owns the Siglume wallet that pays the on-chain payment transaction.
|
|
11
11
|
- Siglume: creates the payment requirement, prepares the wallet transaction,
|
|
12
12
|
verifies the receipt, and emits signed webhooks.
|
|
13
13
|
|
|
@@ -15,9 +15,10 @@ The merchant server must not create charges with a customer wallet. It signs the
|
|
|
15
15
|
order challenge; the buyer-facing Siglume payment flow pays it.
|
|
16
16
|
|
|
17
17
|
This quickstart is for SDRP Standard Payment in an external merchant product.
|
|
18
|
-
Micro Payment and Nano Payment
|
|
19
|
-
|
|
20
|
-
|
|
18
|
+
Micro Payment and Nano Payment are applied automatically by amount and settled on
|
|
19
|
+
a weekly / monthly cadence (see [Pricing](./pricing.md#settlement-schedule)); they
|
|
20
|
+
are not browser checkout requirements you create with this SDK. Their provider
|
|
21
|
+
revenue remains unsettled until the later on-chain settlement succeeds.
|
|
21
22
|
|
|
22
23
|
## 1. Run Merchant Setup
|
|
23
24
|
|
|
@@ -42,7 +43,9 @@ const setup = await merchantClient.setupCheckout({
|
|
|
42
43
|
max_amount_minor: 100000,
|
|
43
44
|
});
|
|
44
45
|
|
|
45
|
-
|
|
46
|
+
// setup.env holds the merchant key plus the challenge and webhook secrets.
|
|
47
|
+
// Store them in your server-side secret manager; do not log the secret values.
|
|
48
|
+
console.log(`Configured merchant: ${setup.env.SIGLUME_DIRECT_PAYMENT_MERCHANT}`);
|
|
46
49
|
```
|
|
47
50
|
|
|
48
51
|
Python:
|
|
@@ -65,7 +68,9 @@ setup = merchant_client.setup_checkout(
|
|
|
65
68
|
max_amount_minor=100000,
|
|
66
69
|
)
|
|
67
70
|
|
|
68
|
-
|
|
71
|
+
# setup["env"] holds the merchant key plus the challenge and webhook secrets.
|
|
72
|
+
# Persist them to your server-side secret store; do not log the secret values.
|
|
73
|
+
print("Configured merchant:", setup["env"]["SIGLUME_DIRECT_PAYMENT_MERCHANT"])
|
|
69
74
|
```
|
|
70
75
|
|
|
71
76
|
`setupCheckout` / `setup_checkout` performs:
|
package/docs/pricing.md
CHANGED
|
@@ -26,13 +26,14 @@ quoted per currency.
|
|
|
26
26
|
|
|
27
27
|
| Payment amount | Applied automatically | What you select | Fee | Settlement |
|
|
28
28
|
| --- | --- | --- | --- | --- |
|
|
29
|
-
| Over JPY 500 / over USD 3.00, or whenever immediate finality is required | Standard Payment | Select one Standard plan: Launch, Starter, Growth, or Pro | Launch: JPY 0 / USD 0 monthly, 1.8%; Starter: JPY 980 / USD 6 monthly, 1.0%; Growth: JPY 2,980 / USD 18 monthly, 0.7%; Pro: JPY 9,800 / USD 60 monthly, 0.5%. Minimum JPY 30 / USD 0.20 per payment. |
|
|
30
|
-
| JPY 50-500 / about USD 0.30-3.00 | Micro Payment |
|
|
31
|
-
| Under JPY 1 to JPY 49 / under USD 0.01 to about USD 0.30 | Nano Payment |
|
|
29
|
+
| Over JPY 500 / over USD 3.00, or whenever immediate finality is required | Standard Payment | Select one Standard plan: Launch, Starter, Growth, or Pro | Launch: JPY 0 / USD 0 monthly, 1.8%; Starter: JPY 980 / USD 6 monthly, 1.0%; Growth: JPY 2,980 / USD 18 monthly, 0.7%; Pro: JPY 9,800 / USD 60 monthly, 0.5%. Minimum JPY 30 / USD 0.20 per payment. | Settled on-chain immediately after the payment confirms |
|
|
30
|
+
| JPY 50-500 / about USD 0.30-3.00 | Micro Payment | Applied automatically by amount | USD 0.01 / Tx, about JPY 2 | Aggregated and settled **weekly** (see [Settlement schedule](#settlement-schedule)) |
|
|
31
|
+
| Under JPY 1 to JPY 49 / under USD 0.01 to about USD 0.30 | Nano Payment | Applied automatically by amount | USD 0.001 / usage, about JPY 0.2 | Aggregated and settled **monthly** (see [Settlement schedule](#settlement-schedule)) |
|
|
32
32
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
33
|
+
Standard Payment settles per payment. Micro Payment and Nano Payment are
|
|
34
|
+
aggregated and settled on a fixed weekly / monthly cadence — see
|
|
35
|
+
[Settlement schedule](#settlement-schedule) for exactly when each band closes,
|
|
36
|
+
when revenue becomes settled, and how rejected requests behave.
|
|
36
37
|
|
|
37
38
|
USD pricing is the JPY tier converted at roughly 160 JPY/USD and rounded to
|
|
38
39
|
clean price points that keep the same 1:3:10 tier ratio.
|
|
@@ -41,21 +42,95 @@ If no paid plan is selected during merchant setup, the merchant account uses the
|
|
|
41
42
|
Launch plan. A merchant billing mandate is still required before accepting
|
|
42
43
|
payments so Siglume can collect the monthly base fee automatically.
|
|
43
44
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
included a free monthly allowance of 100 payments; that allowance has been
|
|
48
|
-
retired — the platform `fee_bps` response is always the source of truth.)
|
|
49
|
-
|
|
50
|
-
Per-payment fees are collected during payment settlement through the
|
|
51
|
-
DirectPaymentHub split. The merchant receives the net amount after that fee.
|
|
52
|
-
Monthly base fees are collected separately through the merchant billing mandate.
|
|
45
|
+
Per-payment fees are deducted at settlement, so the merchant receives the net
|
|
46
|
+
amount for each payment. Monthly base fees are collected separately through the
|
|
47
|
+
merchant billing mandate.
|
|
53
48
|
|
|
54
49
|
The same fee schedule applies in JPY and USD. The Siglume platform returns
|
|
55
50
|
`fee_bps` in the merchant's settlement currency on every payment requirement, so
|
|
56
51
|
the SDK never has to know which currency table to read — it just trusts the
|
|
57
52
|
value Siglume returns.
|
|
58
53
|
|
|
54
|
+
## Settlement schedule
|
|
55
|
+
|
|
56
|
+
Standard Payment, Micro Payment, and Nano Payment differ mainly in *when* a
|
|
57
|
+
confirmed payment turns into money in your settlement wallet.
|
|
58
|
+
|
|
59
|
+
| Band | Cadence | Period | You are paid |
|
|
60
|
+
| --- | --- | --- | --- |
|
|
61
|
+
| Standard Payment | Per payment | n/a | On-chain, immediately after each payment confirms |
|
|
62
|
+
| Micro Payment | Weekly | Buyer settlement timezone Monday 00:00 to the next Monday 00:00; default timezone is UTC | After the week closes, in aggregated on-chain settlement(s) grouped per buyer, payee, token, and period |
|
|
63
|
+
| Nano Payment | Monthly | Buyer settlement timezone 1st 00:00 to the 1st of the next month 00:00; default timezone is UTC | After the month closes, in aggregated on-chain settlement(s) grouped per buyer, payee, token, and period |
|
|
64
|
+
|
|
65
|
+
### Micro weekly settlement
|
|
66
|
+
|
|
67
|
+
- **Closing period.** Micro-band payments accrue across one calendar week:
|
|
68
|
+
Monday 00:00 to the following Monday 00:00 in the buyer settlement timezone.
|
|
69
|
+
- **Timezone.** Period boundaries are evaluated in the buyer's configured
|
|
70
|
+
settlement timezone, defaulting to UTC, so different buyers can close on
|
|
71
|
+
slightly different local boundaries.
|
|
72
|
+
- **Settlement.** After the week closes, Siglume aggregates that week's Micro
|
|
73
|
+
payments — grouped per buyer, payee, token, and period — into on-chain
|
|
74
|
+
settlement(s). Aggregation and payment run automatically on the next settlement
|
|
75
|
+
pass after the period closes; there is a short, platform-managed lag between
|
|
76
|
+
the close and the on-chain transaction.
|
|
77
|
+
- **Revenue recognition.** A Micro payment is final only once its weekly
|
|
78
|
+
settlement confirms on-chain. Until then it is accrued, not settled.
|
|
79
|
+
|
|
80
|
+
### Nano monthly settlement
|
|
81
|
+
|
|
82
|
+
- **Closing period.** Nano-band payments accrue across one calendar month:
|
|
83
|
+
the 1st at 00:00 to the 1st of the next month at 00:00 in the buyer
|
|
84
|
+
settlement timezone.
|
|
85
|
+
- **Timezone.** As with Micro, period boundaries use the buyer's configured
|
|
86
|
+
settlement timezone, defaulting to UTC.
|
|
87
|
+
- **Settlement.** After the month closes, Siglume aggregates that month's Nano
|
|
88
|
+
payments — grouped per buyer, payee, token, and period — into on-chain
|
|
89
|
+
settlement(s), on the next settlement pass after the period closes.
|
|
90
|
+
- **Revenue recognition.** A Nano payment is final only once its monthly
|
|
91
|
+
settlement confirms on-chain.
|
|
92
|
+
|
|
93
|
+
### Failures, retries, and carry-over
|
|
94
|
+
|
|
95
|
+
- Settlement is on-chain, so there are no banking-holiday gaps — periods close on
|
|
96
|
+
the calendar boundary regardless of weekday.
|
|
97
|
+
- If a settlement fails because of insufficient balance, insufficient allowance,
|
|
98
|
+
inactive BudgetVault authorization, a per-payout cap, or an on-chain failure,
|
|
99
|
+
the affected batch is treated as past due. Siglume currently retries every 6
|
|
100
|
+
hours for up to 28 automatic attempts. After that, the batch remains past due
|
|
101
|
+
and requires manual resolution before another attempt.
|
|
102
|
+
- While a buyer has an unresolved failed Micro/Nano settlement for the same
|
|
103
|
+
payment band and token, new Micro/Nano usage is paused with the machine-readable
|
|
104
|
+
error `METERED_SETTLEMENT_PAST_DUE`; the provider API is not called.
|
|
105
|
+
- Outstanding amounts remain attached to the failed settlement and are retried
|
|
106
|
+
under this policy. They are not settled revenue, and Siglume does not advance,
|
|
107
|
+
guarantee, or insure provider revenue before on-chain settlement succeeds.
|
|
108
|
+
|
|
109
|
+
### Rejected / no-charge behavior
|
|
110
|
+
|
|
111
|
+
Micro and Nano run a budget check before the buyer's paid request is fulfilled:
|
|
112
|
+
|
|
113
|
+
- A buyer's wallet budget is consumed at the **gross amount** (your price plus
|
|
114
|
+
the protocol fee), held from the moment a request is accepted until its
|
|
115
|
+
settlement confirms.
|
|
116
|
+
- If the buyer's budget, scope, or amount band does not allow a request, it is
|
|
117
|
+
**rejected with no charge**: the request is not fulfilled, no amount is
|
|
118
|
+
accrued, and nothing is added to a settlement. A buyer near their budget
|
|
119
|
+
ceiling can have a request rejected even though earlier requests in the same
|
|
120
|
+
period succeeded.
|
|
121
|
+
- Treat Siglume's settled status and webhooks as the source of truth for what has
|
|
122
|
+
actually been paid.
|
|
123
|
+
|
|
124
|
+
### What is fixed vs platform-managed
|
|
125
|
+
|
|
126
|
+
The cadence is fixed: **Micro settles weekly, Nano settles monthly**, and a
|
|
127
|
+
payment is final only after its on-chain settlement confirms. The buyer-timezone
|
|
128
|
+
period boundaries and the current retry policy above are the public behavior as
|
|
129
|
+
of 2026-06-18. The scheduler lag between a period close and the on-chain
|
|
130
|
+
transaction is platform-managed; treat the platform's settlement status and
|
|
131
|
+
`fee_bps` response as authoritative rather than hard-coding local revenue
|
|
132
|
+
recognition.
|
|
133
|
+
|
|
59
134
|
## SDK Behavior
|
|
60
135
|
|
|
61
136
|
The SDK does not calculate merchant invoices or enforce plan limits locally.
|
|
@@ -72,3 +147,11 @@ The trial pricing is intended for:
|
|
|
72
147
|
- Membership services
|
|
73
148
|
- Paid API access
|
|
74
149
|
- Scheduled autopay for external merchant workflows
|
|
150
|
+
|
|
151
|
+
## Compatibility note
|
|
152
|
+
|
|
153
|
+
The Siglume API and merchant registry may still expose the legacy `billing_plan`
|
|
154
|
+
value `free` for the Launch tier. Treat `free` as a wire-compatibility key, not a
|
|
155
|
+
public plan name. (Until 2026-06-12 the Launch plan included a free monthly
|
|
156
|
+
allowance of 100 payments; that allowance has been retired — the platform
|
|
157
|
+
`fee_bps` response is always the source of truth.)
|
package/docs/security.md
CHANGED
|
@@ -106,9 +106,14 @@ Direct Request Payment is not:
|
|
|
106
106
|
- escrow
|
|
107
107
|
- a platform balance
|
|
108
108
|
- a card payment fallback
|
|
109
|
-
- the Micro Payment or Nano Payment meter
|
|
110
109
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
110
|
+
Each payment is an individual wallet payment backed by an on-chain receipt. Small
|
|
111
|
+
payments in the Micro and Nano amount bands are aggregated and settled on a
|
|
112
|
+
weekly / monthly cadence instead of one transaction at a time (see the
|
|
113
|
+
[pricing guide](./pricing.md#settlement-schedule)), but they are still wallet
|
|
114
|
+
payments, not a stored balance. Before a small payment is fulfilled, Siglume
|
|
115
|
+
checks the buyer's wallet budget and fails closed when it is invalid, so a
|
|
116
|
+
rejected request is never charged. Provider revenue for Micro and Nano remains
|
|
117
|
+
unsettled until the weekly or monthly on-chain settlement succeeds; Siglume does
|
|
118
|
+
not advance or guarantee revenue when a buyer's balance, allowance, BudgetVault
|
|
119
|
+
authorization, cap, or on-chain transaction fails.
|
|
@@ -99,8 +99,10 @@ app.post("/siglume/webhook", express.raw({ type: "application/json" }), asyncRou
|
|
|
99
99
|
}));
|
|
100
100
|
|
|
101
101
|
app.use((error: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
|
|
102
|
-
|
|
103
|
-
|
|
102
|
+
// Log the detail server-side; never return raw error messages to the client —
|
|
103
|
+
// a payment error can otherwise leak internal API details or configuration.
|
|
104
|
+
console.error("checkout error:", error);
|
|
105
|
+
res.status(500).json({ error: "internal_error" });
|
|
104
106
|
});
|
|
105
107
|
|
|
106
108
|
app.listen(port);
|
|
@@ -14,4 +14,12 @@ const setup = await merchant.setupCheckout({
|
|
|
14
14
|
create_webhook_subscription: Boolean(process.env.SIGLUME_DIRECT_PAYMENT_WEBHOOK_URL),
|
|
15
15
|
});
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
// setup.env contains the merchant key PLUS the challenge and webhook secrets.
|
|
18
|
+
// Store these in your server-side secret manager. Never log the secret values —
|
|
19
|
+
// log only non-secret confirmation.
|
|
20
|
+
const env = setup.env ?? {};
|
|
21
|
+
console.log("Merchant configured:", {
|
|
22
|
+
merchant: env.SIGLUME_DIRECT_PAYMENT_MERCHANT,
|
|
23
|
+
challenge_secret: env.SIGLUME_DIRECT_PAYMENT_CHALLENGE_SECRET ? "****" : undefined,
|
|
24
|
+
webhook_secret: env.SIGLUME_WEBHOOK_SECRET ? "****" : undefined,
|
|
25
|
+
});
|
package/package.json
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@siglume/direct-request-payment",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.6",
|
|
4
4
|
"description": "SDK for the Siglume Direct Request Payment SDRP payment protocol",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"siglume",
|
|
7
|
+
"sdrp",
|
|
8
|
+
"direct-request-payment",
|
|
7
9
|
"payment",
|
|
8
|
-
"
|
|
9
|
-
"
|
|
10
|
+
"micropayments",
|
|
11
|
+
"metered-billing",
|
|
10
12
|
"wallet",
|
|
13
|
+
"jpyc",
|
|
14
|
+
"usdc",
|
|
15
|
+
"checkout",
|
|
11
16
|
"sdk"
|
|
12
17
|
],
|
|
13
18
|
"license": "MIT",
|