@siglume/direct-request-payment 0.3.4 → 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/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.4\";\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.4\";\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,EACA;AAAA,EACA;A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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":[]}
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;AA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xD,YAAQ,UAAU,KAAK,IAAK,WAAW,KAAK;AAAA,EAC9C;AACA,SAAO,SAAS;AAClB;","names":[]}
@@ -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 | DirectPaymentHubで即時オンチェーン分配 |
35
- | JPY 50-500 / 約USD 0.30-3.00 | Micro Payment / マイクロペイメント | 選択不要。金額で自動適用 | USD 0.01 / Tx、約JPY 2 | meter gate後、週次後精算 |
36
- | JPY 1未満-49 / USD 0.01未満-約USD 0.30 | Nano Payment / ナノペイメント | 選択不要。金額で自動適用 | USD 0.001 / usage、約JPY 0.2 | meter gate後、月次後精算 |
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 ではAPI実行前にSDRPのmeter gateを通し、予算やscopeに失敗した場合は `rejected_no_charge` として記録され、provider APIは呼ばれません。
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
- console.log(setup.env);
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
 
@@ -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 use the SDRP meter gate and are
233
- not created through this merchant checkout client.
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 sends `mode="external_402"` internally.
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 DirectPaymentHub transaction.
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 use the SDRP metered-payment server flow instead.
19
- Micro/Nano run a server-side meter gate before provider execution and settle
20
- later; they are not browser checkout requirements created by this merchant SDK.
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
- console.log(setup.env);
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
- print(setup["env"])
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. | Immediate on-chain split through DirectPaymentHub after payment confirmation |
30
- | JPY 50-500 / about USD 0.30-3.00 | Micro Payment | No selection. Applied automatically by amount. | USD 0.01 / Tx, about JPY 2 | Meter gate before provider execution; weekly delayed settlement |
31
- | Under JPY 1 to JPY 49 / under USD 0.01 to about USD 0.30 | Nano Payment | No selection. Applied automatically by amount. | USD 0.001 / usage, about JPY 0.2 | Meter gate before provider execution; monthly delayed settlement |
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
- For Micro Payment and Nano Payment, the SDRP meter gate runs before provider
34
- execution. Budget or scope failures are recorded as `rejected_no_charge`; the
35
- provider API is not called and no pending provider revenue is created.
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
- The current Siglume API and merchant registry may still expose the internal
45
- `billing_plan` value `free` for the Launch tier. Treat `free` as an internal
46
- compatibility key, not the public plan name. (Until 2026-06-12 the Launch plan
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
- It is a Standard Payment wallet gate backed by an on-chain receipt. Micro
112
- Payment and Nano Payment are SDRP amount bands with internal-meter,
113
- delayed-settlement behavior; they must fail closed before provider API
114
- execution when the buyer's metered budget, scope, or amount band is invalid.
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
- const message = error instanceof Error ? error.message : "internal_error";
103
- res.status(500).json({ error: message });
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);