@facto-to/connect 0.0.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,634 @@
1
+ import { MandateUseCase, MandateLimitPeriod, ExchangeLinkCodeResponse, PaymentCapabilityRequestProperties, PaymentCapabilityResponse, MandateAuthorizationSessionStatus, MandateStatus, MandatePaymentStatus, MandateDeclineReason } from '@facto-to/engine-wire';
2
+ export { MandateAuthorizationSessionStatus as MandateAuthorizationStatus, MandateDeclineReason, MandateLimitPeriod, MandatePaymentStatus, MandateStatus, MandateUseCase, PaymentReadinessNotReadyReason } from '@facto-to/engine-wire';
3
+
4
+ /**
5
+ * Customer-facing environment vocabulary (ADR-0077): the published Facto
6
+ * environments are `dev` and `production`, and `'sandbox'` is the documented
7
+ * public name for the dev environment — "sandbox naming, dev interface".
8
+ * `'sandbox'` and `'dev'` are interchangeable selectors for one environment:
9
+ * both resolve the dev endpoints (`https://dev-api.facto.to`, hosted Connect
10
+ * `https://dev.facto.to`) and the `/api/dev/*` route family. `'sandbox'` is
11
+ * the recommended spelling in public documentation; `'dev'` is the
12
+ * infrastructure name passed through unchanged.
13
+ *
14
+ * `staging` and the former `'custom'` selector are retired. Local, private,
15
+ * and staging deployments pass explicit `apiBaseUrl` and `hostedConnectUrl`
16
+ * overrides, which are valid with any environment value and take precedence
17
+ * over the published endpoint tables.
18
+ */
19
+ type FactoConnectEnvironment = 'dev' | 'production' | 'sandbox';
20
+ /** Canonical infrastructure names keying the published endpoint tables. */
21
+ type PublishedFactoConnectEnvironment = 'dev' | 'production';
22
+ type FactoConnectTransport = (input: string, init?: RequestInit) => Promise<Response>;
23
+ declare const FACTO_CONNECT_API_BASE_URLS: Readonly<Record<PublishedFactoConnectEnvironment, string>>;
24
+ declare const FACTO_CONNECT_HOSTED_URLS: Readonly<Record<PublishedFactoConnectEnvironment, string>>;
25
+ interface FactoConnectServerOptions {
26
+ appId: string;
27
+ clientId: string;
28
+ clientSecret: string;
29
+ /**
30
+ * Required. `'sandbox'` (the documented public test environment name) and
31
+ * `'dev'` select the same environment and resolve the same published dev
32
+ * endpoints; `'production'` resolves the production endpoints. ADR-0077:
33
+ * "sandbox naming, dev interface". There is no default: omission throws at
34
+ * construction instead of silently targeting production over the retired
35
+ * legacy `/api/external/*` routes, and `'staging'` is retired from the
36
+ * customer-facing vocabulary.
37
+ *
38
+ * The former `'custom'` selector is retired. For a local, private, or
39
+ * staging deployment keep any environment value and pass both explicit
40
+ * URL overrides, e.g.:
41
+ *
42
+ * ```ts
43
+ * createFactoConnectServer({
44
+ * ...credentials,
45
+ * environment: 'sandbox',
46
+ * apiBaseUrl: 'http://127.0.0.1:8080',
47
+ * hostedConnectUrl: 'http://127.0.0.1:5173',
48
+ * })
49
+ * ```
50
+ */
51
+ environment: FactoConnectEnvironment;
52
+ /**
53
+ * Explicit endpoint overrides for local, private, or staging deployments.
54
+ * Valid with any `environment` value and take precedence over the
55
+ * published endpoint tables (an override naming a *different* published
56
+ * environment's endpoint is still rejected as a conflict).
57
+ */
58
+ apiBaseUrl?: string;
59
+ hostedConnectUrl?: string;
60
+ /** Injectable server-side transport. Defaults to `globalThis.fetch`. */
61
+ transport?: FactoConnectTransport;
62
+ /** Alias for `transport`, matching the public Dev SDK contract. */
63
+ fetch?: FactoConnectTransport;
64
+ /** Per-request deadline in milliseconds. Omit to leave deadline control to the caller transport. */
65
+ timeoutMs?: number;
66
+ /** Retry policy for safe GET requests and POST requests carrying an idempotency key. */
67
+ retry?: ServerRetryOptions;
68
+ /** Cancels in-flight requests and retry delays. */
69
+ signal?: AbortSignal;
70
+ }
71
+ interface HostedConnectUrlInput {
72
+ appId: string;
73
+ state: string;
74
+ nonce: string;
75
+ /** Display-only merchant identity for the shopper. Not used for authentication or exchange. */
76
+ customerEmail?: string;
77
+ /** Display-only merchant identity for the shopper. Not used for authentication or exchange. */
78
+ customerUsername?: string;
79
+ /** Hosted Connect origin for the target environment. Required: there is no implicit default. */
80
+ hostedConnectUrl: string;
81
+ }
82
+ interface CreateHostedConnectUrlInput {
83
+ state: string;
84
+ nonce: string;
85
+ /** Display-only merchant identity for the shopper. Not used for authentication or exchange. */
86
+ customerEmail?: string;
87
+ /** Display-only merchant identity for the shopper. Not used for authentication or exchange. */
88
+ customerUsername?: string;
89
+ hostedConnectUrl?: string;
90
+ }
91
+ interface ExchangeLinkCodeInput {
92
+ code: string;
93
+ state: string;
94
+ nonce: string;
95
+ }
96
+ /**
97
+ * Merchant-safe link-code exchange result.
98
+ *
99
+ * This is the pinned engine `ExchangeLinkCodeResponse` verbatim — see
100
+ * `./generated/engine-wire`. New integrations persist `userLinkRef` (and the
101
+ * Dev-only `cardRef` when present); `factoUserId`,
102
+ * `factoServerWalletAddress`, and `cardRef` are transition-only and the wire
103
+ * declares each one independently optional AND nullable, so `null` is a legal
104
+ * value here and must not be narrowed away.
105
+ */
106
+ type ExchangeLinkCodeResult = ExchangeLinkCodeResponse;
107
+ /**
108
+ * Payment-readiness response. The pinned engine `PaymentCapabilityResponse`
109
+ * verbatim: `notReadyReason` carries the closed
110
+ * `PaymentReadinessNotReadyReason` enum and is optional + nullable, and the
111
+ * legacy identity pair is optional + nullable.
112
+ */
113
+ type PaymentCapability = PaymentCapabilityResponse;
114
+
115
+ /**
116
+ * Caller-facing shape of the wire `PaymentCapabilityRequest` target. The SDK
117
+ * injects `app_id` from its own configuration, so callers supply the wallet
118
+ * address alone for the legacy shape.
119
+ */
120
+ interface PaymentCapabilityInputProperties {
121
+ /** GA shape: opaque user-link reference minted by the link-code exchange. */
122
+ userLinkRef?: PaymentCapabilityRequestProperties['userLinkRef'];
123
+ /** Legacy shape: Facto server wallet address of the linked user. */
124
+ factoServerWalletAddress?: PaymentCapabilityRequestProperties['facto_server_wallet_address'];
125
+ }
126
+ /**
127
+ * Mirrors the wire's INCLUSIVE sibling `anyOf`: legacy-only, GA-only, and the
128
+ * mixed migration shape are all accepted, and only an empty target is rejected.
129
+ * Do not collapse this into an exclusive union with `never` members — the
130
+ * engine contract has no `oneOf` and no `additionalProperties: false`.
131
+ */
132
+ type PaymentCapabilityInput = PaymentCapabilityInputProperties & (Required<Pick<PaymentCapabilityInputProperties, 'factoServerWalletAddress'>> | Required<Pick<PaymentCapabilityInputProperties, 'userLinkRef'>>);
133
+ type PaymentOptionsInput = ({
134
+ userLinkRef: string;
135
+ grantRef?: never;
136
+ } | {
137
+ userLinkRef?: never;
138
+ grantRef: string;
139
+ }) & {
140
+ /** Intended charge amount (decimal-USDC string). When set, the engine returns
141
+ * only options that can actually clear this amount (balance/allowance/limits). */
142
+ amount?: string;
143
+ assetSymbol?: string;
144
+ };
145
+ interface MerchantPaymentOption {
146
+ paymentOptionId: string;
147
+ label: string;
148
+ ready: boolean;
149
+ isDefault: boolean;
150
+ chainId: number;
151
+ chainLabel: string;
152
+ protocolLabel: string;
153
+ assetSymbol: string;
154
+ /**
155
+ * @deprecated Read `settlementPath`. The engine marks this field a duplicate
156
+ * of the settlement axis kept only for wire compatibility
157
+ * (Facto-to/facto#265), and it is the field that will be removed. When a
158
+ * response carries only `settlementPath`, this mirrors it.
159
+ */
160
+ spendMode: string;
161
+ /** How an accepted payment settles. Direct-only on the merchant surface. */
162
+ settlementPath: string;
163
+ blockingReason?: string;
164
+ }
165
+ interface MerchantPaymentOptions {
166
+ paymentOptions: MerchantPaymentOption[];
167
+ selectedPaymentOptionId?: string;
168
+ }
169
+ type CheckoutStatus = 'pending' | 'charged' | 'expired' | 'cancelled';
170
+ type CreateCheckoutSessionInput = ({
171
+ userLinkRef: string;
172
+ factoServerWalletAddress?: never;
173
+ } | {
174
+ userLinkRef?: never;
175
+ factoServerWalletAddress: string;
176
+ }) & {
177
+ amount: string;
178
+ assetSymbol?: string;
179
+ orderRef?: string;
180
+ returnUrl?: string;
181
+ };
182
+ interface CheckoutSession {
183
+ sessionId: string;
184
+ checkoutUrl: string;
185
+ status: 'pending';
186
+ amount: string;
187
+ assetSymbol: string;
188
+ orderRef: string | null;
189
+ }
190
+ interface CheckoutSessionStatus {
191
+ sessionId: string;
192
+ status: CheckoutStatus;
193
+ amount: string;
194
+ assetSymbol: string;
195
+ orderRef: string | null;
196
+ chargeId: string | null;
197
+ confirmedAt: string | null;
198
+ }
199
+
200
+ interface MandateLimits {
201
+ perTxAmount: string;
202
+ periodAmount: string;
203
+ period: MandateLimitPeriod;
204
+ }
205
+ interface CreateMandateAuthorizationSessionRequest {
206
+ appId: string;
207
+ externalCustomerRef: string;
208
+ /**
209
+ * Display-only shopper identity, shown on the consent screens and copied
210
+ * onto the grant if the shopper connects inline (reversed-order flow).
211
+ * Never an identifier: not matched against Facto accounts and not part of
212
+ * any authorization decision. Mirrors the pinned engine wire request.
213
+ */
214
+ customerEmail?: string;
215
+ customerUsername?: string;
216
+ requestedUseCases: MandateUseCase[];
217
+ defaultLimits: MandateLimits;
218
+ returnUrl: string;
219
+ state: string;
220
+ }
221
+ type CreateMandateAuthorizationSessionInput = Omit<CreateMandateAuthorizationSessionRequest, 'appId'>;
222
+ interface MandateAuthorizationSession {
223
+ sessionId: string;
224
+ authorizationUrl: string;
225
+ status: MandateAuthorizationSessionStatus;
226
+ mandateId?: string;
227
+ /** Present once a shopper has approved. In the reversed-order flow this
228
+ * poll response is the only channel where the merchant backend learns the
229
+ * link ref — no link-code exchange happens. */
230
+ userLinkRef?: string;
231
+ expiresAt: string;
232
+ state: string;
233
+ }
234
+ interface MerchantPaymentPathProjection {
235
+ ready: boolean;
236
+ summary: string;
237
+ blockingReason?: string;
238
+ }
239
+ interface MerchantMandate {
240
+ mandateId: string;
241
+ appId: string;
242
+ status: MandateStatus;
243
+ allowedUseCases: MandateUseCase[];
244
+ limits: MandateLimits;
245
+ paymentPath: MerchantPaymentPathProjection;
246
+ createdAt: string;
247
+ expiresAt?: string;
248
+ }
249
+ interface CreateMandatePaymentRequest {
250
+ mandateId: string;
251
+ merchantPaymentRef: string;
252
+ amount: string;
253
+ currency: 'USDC';
254
+ useCase: MandateUseCase;
255
+ paymentOptionId?: string;
256
+ description?: string;
257
+ metadata?: Record<string, string>;
258
+ }
259
+ interface CreateMandatePaymentInput extends CreateMandatePaymentRequest {
260
+ idempotencyKey: string;
261
+ }
262
+ interface MandatePayment {
263
+ paymentId: string;
264
+ mandateId: string;
265
+ merchantPaymentRef: string;
266
+ status: MandatePaymentStatus;
267
+ amount: string;
268
+ currency: string;
269
+ useCase: MandateUseCase;
270
+ chargeId?: string;
271
+ /** On-chain settlement tx hash, present once the payment reaches a terminal status. */
272
+ txHash?: string;
273
+ declineReason?: MandateDeclineReason;
274
+ finalityEtaSeconds?: number;
275
+ /** Timestamp the payment reached a terminal status. */
276
+ terminalAt?: string;
277
+ createdAt: string;
278
+ updatedAt?: string;
279
+ }
280
+ type MandatePaymentStatusListener = (payment: MandatePayment) => void;
281
+ interface OnMandatePaymentStatusOptions {
282
+ /** Delay before the first poll and the base for backoff, in ms (default 1000). */
283
+ initialIntervalMs?: number;
284
+ /** Upper bound on the poll delay after backoff, in ms (default 8000). */
285
+ maxIntervalMs?: number;
286
+ /** Multiplier applied to the delay after each poll (default 1.5). */
287
+ backoffFactor?: number;
288
+ /** Hard cap on total polling time, in ms (default 300000). Resolves with the
289
+ * latest (possibly non-terminal) payment when hit. */
290
+ timeoutMs?: number;
291
+ /** Cancels polling; the returned promise rejects with an AbortError. */
292
+ signal?: AbortSignal;
293
+ }
294
+ /** Cursor page envelope shared by every GA list endpoint. */
295
+ interface Page<T> {
296
+ data: T[];
297
+ hasMore: boolean;
298
+ }
299
+ interface CursorListFilter {
300
+ limit?: number;
301
+ startingAfter?: string;
302
+ }
303
+ interface MerchantPaymentListFilter extends CursorListFilter {
304
+ createdAfter?: string;
305
+ createdBefore?: string;
306
+ authorizationId?: string;
307
+ status?: MandatePaymentStatus;
308
+ }
309
+ interface PaymentAuthorizationListFilter extends CursorListFilter {
310
+ userLinkRef?: string;
311
+ status?: MandateStatus;
312
+ }
313
+ type RefundReason = 'requested_by_customer' | 'duplicate' | 'fraudulent' | 'other';
314
+ type RefundStatus = 'pending' | 'succeeded' | 'failed';
315
+ interface CreateRefundInput {
316
+ paymentId: string;
317
+ /** Omit for a full refund of the remaining amount. */
318
+ amount?: string;
319
+ reason?: RefundReason;
320
+ merchantRefundRef?: string;
321
+ idempotencyKey: string;
322
+ }
323
+ interface Refund {
324
+ refundId: string;
325
+ paymentId: string;
326
+ status: RefundStatus;
327
+ amount: string;
328
+ currency: string;
329
+ reason?: RefundReason;
330
+ merchantRefundRef?: string;
331
+ createdAt: string;
332
+ }
333
+ interface RefundListFilter extends CursorListFilter {
334
+ paymentId?: string;
335
+ }
336
+ type WebhookEventType = 'user_link.revoked' | 'payment_authorization.activated' | 'payment_authorization.updated' | 'payment_authorization.revoked' | 'checkout_session.completed' | 'checkout_session.expired' | 'payment.succeeded' | 'payment.failed' | 'refund.succeeded' | 'refund.failed';
337
+ interface CreateWebhookEndpointInput {
338
+ url: string;
339
+ enabledEvents: WebhookEventType[];
340
+ }
341
+ interface WebhookEndpoint {
342
+ webhookEndpointId: string;
343
+ url: string;
344
+ enabledEvents: WebhookEventType[];
345
+ status: 'enabled' | 'disabled';
346
+ createdAt: string;
347
+ }
348
+ interface WebhookEndpointWithSecret extends WebhookEndpoint {
349
+ /** Returned exactly once from create/rotate. Store server-side only. */
350
+ secret: string;
351
+ }
352
+ type DevCapabilityName = 'fixtures' | 'synthetic_identity' | 'faucet' | 'simulation' | 'money_loop' | 'webhook_test_delivery';
353
+ type DevCapabilityStatus = 'unavailable' | 'degraded' | 'ready';
354
+ type DevEvidenceLevel = 'contract' | 'implemented' | 'deployed' | 'verified';
355
+ /** Current public evidence projection for one Dev capability. */
356
+ interface DevCapability {
357
+ name: DevCapabilityName;
358
+ status: DevCapabilityStatus;
359
+ evidenceLevel: DevEvidenceLevel;
360
+ reasonCode?: string | null;
361
+ verifiedAt?: string | null;
362
+ limits?: Record<string, string | number | boolean | null>;
363
+ }
364
+ /** Read-only Dev availability and evidence projection. */
365
+ interface DevCapabilities {
366
+ environment: 'dev';
367
+ contractVersion: '2026-07-09';
368
+ capabilities: DevCapability[];
369
+ checkedAt: string;
370
+ }
371
+ /** Dev endpoints accept USDC decimal strings only. */
372
+ interface DevMoney {
373
+ amount: string;
374
+ currency: 'USDC';
375
+ }
376
+ interface FundDevUserInput {
377
+ userLinkRef: string;
378
+ amount: DevMoney;
379
+ idempotencyKey: string;
380
+ }
381
+ type DevSimulationScenario = 'approved' | 'declined_setup' | 'declined_limit' | 'payment_failed';
382
+ type DevSimulationExecutionMode = 'pre_admission' | 'onchain_test_assets';
383
+ type DevSimulationStatus = 'accepted' | 'processing' | 'succeeded' | 'failed' | 'declined';
384
+ interface SimulateDevChargeInput {
385
+ userLinkRef: string;
386
+ cardRef?: string;
387
+ amount: DevMoney;
388
+ scenario: DevSimulationScenario;
389
+ merchantReference?: string;
390
+ idempotencyKey: string;
391
+ }
392
+ /** A Dev simulation is not a MerchantPayment and has no production settlement meaning. */
393
+ interface DevSimulation {
394
+ simulationId: string;
395
+ scenario: DevSimulationScenario;
396
+ executionMode: DevSimulationExecutionMode;
397
+ status: DevSimulationStatus;
398
+ reasonCode: string | null;
399
+ authorizationRef: string | null;
400
+ chargeRef: string | null;
401
+ createdAt: string;
402
+ updatedAt: string;
403
+ }
404
+ interface DevFaucetTransfer {
405
+ faucetTransferId: string;
406
+ userLinkRef: string;
407
+ amount: DevMoney;
408
+ status: 'accepted' | 'broadcast' | 'confirmed' | 'failed';
409
+ createdAt: string;
410
+ }
411
+ interface SendWebhookTestDeliveryInput {
412
+ webhookEndpointId: string;
413
+ message?: string;
414
+ }
415
+ interface WebhookTestDeliveryAccepted {
416
+ eventId: string;
417
+ deliveryId: string;
418
+ status: 'queued';
419
+ createdAt: string;
420
+ }
421
+ interface FactoConnectServerClient {
422
+ createHostedConnectUrl(input: CreateHostedConnectUrlInput): string;
423
+ /** GA operation name for exchanging a one-time user-link code. */
424
+ exchangeUserLinkCode(input: ExchangeLinkCodeInput): Promise<ExchangeLinkCodeResult>;
425
+ /** GA operation name for reading payment readiness. */
426
+ getPaymentReadiness(input: PaymentCapabilityInput): Promise<PaymentCapability>;
427
+ /** GA operation name for creating a payment authorization session. */
428
+ createAuthorizationSession(input: CreateMandateAuthorizationSessionInput): Promise<MandateAuthorizationSession>;
429
+ /** GA operation name for reading a payment authorization session. */
430
+ getAuthorizationSession(sessionId: string): Promise<MandateAuthorizationSession>;
431
+ /** GA operation name for reading one payment authorization. */
432
+ getPaymentAuthorization(authorizationId: string): Promise<MerchantMandate>;
433
+ /** GA operation name for creating an authorized merchant payment. */
434
+ createMerchantPayment(input: CreateMandatePaymentInput): Promise<MandatePayment>;
435
+ /** GA operation name for reading one merchant payment. */
436
+ getMerchantPayment(paymentId: string): Promise<MandatePayment>;
437
+ /** @deprecated Use `exchangeUserLinkCode`. */
438
+ exchangeLinkCode(input: ExchangeLinkCodeInput): Promise<ExchangeLinkCodeResult>;
439
+ /** @deprecated Use `getPaymentReadiness`. */
440
+ getPaymentCapability(input: PaymentCapabilityInput): Promise<PaymentCapability>;
441
+ createCheckoutSession(input: CreateCheckoutSessionInput): Promise<CheckoutSession>;
442
+ getCheckoutSession(id: string): Promise<CheckoutSessionStatus>;
443
+ /** @deprecated Use `createAuthorizationSession`. */
444
+ createMandateAuthorizationSession(input: CreateMandateAuthorizationSessionInput): Promise<MandateAuthorizationSession>;
445
+ /** @deprecated Use `getAuthorizationSession`. */
446
+ getMandateAuthorizationSession(sessionId: string): Promise<MandateAuthorizationSession>;
447
+ /** @deprecated Use `getPaymentAuthorization`. */
448
+ getMerchantMandate(mandateId: string): Promise<MerchantMandate>;
449
+ listPaymentOptions(input: PaymentOptionsInput): Promise<MerchantPaymentOptions>;
450
+ /** @deprecated Use `createMerchantPayment`. */
451
+ createMandatePayment(input: CreateMandatePaymentInput): Promise<MandatePayment>;
452
+ /** @deprecated Use `getMerchantPayment`. */
453
+ getMandatePayment(paymentId: string): Promise<MandatePayment>;
454
+ /**
455
+ * Short-poll a mandate payment until it reaches a terminal status. `listener`
456
+ * is invoked with the payment on the first poll and on every status change;
457
+ * the returned promise resolves with the terminal payment (or the latest
458
+ * payment if `timeoutMs` elapses first). Polling backs off between requests
459
+ * and stops on terminal status, timeout, or abort.
460
+ */
461
+ onStatus(paymentId: string, listener: MandatePaymentStatusListener, options?: OnMandatePaymentStatusOptions): Promise<MandatePayment>;
462
+ /** Revoke a user link the merchant no longer needs (GA-only). */
463
+ revokeUserLink(userLinkRef: string): Promise<void>;
464
+ /** List merchant payments (reconciliation source of truth). */
465
+ listMerchantPayments(filter?: MerchantPaymentListFilter): Promise<Page<MandatePayment>>;
466
+ /** List payment authorizations (mandates) for this app. */
467
+ listPaymentAuthorizations(filter?: PaymentAuthorizationListFilter): Promise<Page<MerchantMandate>>;
468
+ /** Create a refund against a succeeded payment (partial-capable). */
469
+ createRefund(input: CreateRefundInput): Promise<Refund>;
470
+ getRefund(refundId: string): Promise<Refund>;
471
+ listRefunds(filter?: RefundListFilter): Promise<Page<Refund>>;
472
+ /** Register a webhook endpoint. The signing secret is returned exactly once. */
473
+ createWebhookEndpoint(input: CreateWebhookEndpointInput): Promise<WebhookEndpointWithSecret>;
474
+ listWebhookEndpoints(): Promise<WebhookEndpoint[]>;
475
+ getWebhookEndpoint(webhookEndpointId: string): Promise<WebhookEndpoint>;
476
+ deleteWebhookEndpoint(webhookEndpointId: string): Promise<void>;
477
+ /** Rotate the signing secret; the previous secret verifies for 24h. */
478
+ rotateWebhookSecret(webhookEndpointId: string): Promise<WebhookEndpointWithSecret>;
479
+ /** Read the Dev capability/evidence projection. Dev environment only. */
480
+ getDevCapabilities(): Promise<DevCapabilities>;
481
+ /** Request test-only USDC for an app-owned synthetic linked user. Dev only. */
482
+ fundDevUser(input: FundDevUserInput): Promise<DevFaucetTransfer>;
483
+ /** Create a Dev simulation, distinct from a MerchantPayment. Dev only. */
484
+ simulateDevCharge(input: SimulateDevChargeInput): Promise<DevSimulation>;
485
+ /** Read an app-owned Dev simulation. Dev only. */
486
+ getDevSimulation(simulationId: string): Promise<DevSimulation>;
487
+ /** Queue a signed no-business-state `test.ping`. Dev environment only. */
488
+ sendWebhookTestDelivery(input: SendWebhookTestDeliveryInput): Promise<WebhookTestDeliveryAccepted>;
489
+ }
490
+ type FactoConnectServerErrorCode = 'FACTO_CONFIG_INVALID' | 'FACTO_ENGINE_REQUEST_FAILED' | 'FACTO_ENGINE_RESPONSE_INVALID' | 'FACTO_REQUEST_ABORTED' | 'FACTO_STATUS_POLL_ABORTED';
491
+ declare class FactoConnectServerError extends Error {
492
+ readonly code: FactoConnectServerErrorCode;
493
+ readonly retryable: boolean;
494
+ readonly status?: number;
495
+ readonly details?: unknown;
496
+ /** Seconds from the `Retry-After` response header on a 429, when present. */
497
+ readonly retryAfterSeconds?: number;
498
+ constructor(code: FactoConnectServerErrorCode, message: string, options: {
499
+ retryable: boolean;
500
+ status?: number;
501
+ details?: unknown;
502
+ retryAfterSeconds?: number;
503
+ });
504
+ }
505
+ /**
506
+ * Options for {@link withServerRetry} and the server client's safe automatic
507
+ * retry policy. GET calls and idempotency-keyed POST calls use these defaults.
508
+ */
509
+ interface ServerRetryOptions {
510
+ /** Max retry attempts after the first try (default 2). */
511
+ maxRetries?: number;
512
+ /** Base backoff in ms for the exponential fallback (default 200). */
513
+ baseDelayMs?: number;
514
+ /** Backoff cap in ms (default 5000). */
515
+ maxDelayMs?: number;
516
+ /** Honor the server's `Retry-After` when present (default true). */
517
+ respectRetryAfter?: boolean;
518
+ /** Abort waiting/retrying. */
519
+ signal?: AbortSignal;
520
+ /** Invoked before each retry sleep. */
521
+ onRetry?: (info: {
522
+ attempt: number;
523
+ error: FactoConnectServerError;
524
+ delayMs: number;
525
+ }) => void;
526
+ /** Injectable delay (tests). Defaults to a `setTimeout` sleep that respects `signal`. */
527
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
528
+ }
529
+ /**
530
+ * Opt-in retry wrapper for any server-client call. Retries a
531
+ * {@link FactoConnectServerError} whose `retryable` is true (429 / 5xx),
532
+ * honoring `Retry-After` when the server sent it, otherwise exponential backoff
533
+ * with jitter. Non-retryable errors and non-Facto errors are rethrown
534
+ * immediately. The server client applies the same policy only to GET calls and
535
+ * POST calls carrying `Idempotency-Key`; this standalone wrapper remains useful
536
+ * for callers composing their own safe operation:
537
+ *
538
+ * ```ts
539
+ * const payment = await withServerRetry(() => facto.createMandatePayment(input))
540
+ * ```
541
+ */
542
+ declare function withServerRetry<T>(fn: () => Promise<T>, options?: ServerRetryOptions): Promise<T>;
543
+ declare function buildHostedConnectUrl(input: HostedConnectUrlInput): string;
544
+ declare function createFactoConnectServer(options: FactoConnectServerOptions): FactoConnectServerClient;
545
+ /** Whether a mandate payment status is terminal (no further transitions). */
546
+ declare function isTerminalMandatePaymentStatus(status: MandatePaymentStatus): boolean;
547
+ /**
548
+ * Sign a raw Facto webhook payload using the same `t/v1` format accepted by
549
+ * {@link verifyWebhookSignature}. This helper is server-only and intended for
550
+ * deterministic fixtures and partner webhook tests.
551
+ */
552
+ declare function signWebhookPayload(rawBody: string | Uint8Array, secret: string, timestamp?: number): string;
553
+ /**
554
+ * Verify a Facto webhook `Facto-Signature` header against the raw request body
555
+ * (spec 012 webhook contract). Recompute `HMAC-SHA256(secret, "{t}.{raw_body}")`
556
+ * over the EXACT raw bytes, compare in constant time, and reject stale
557
+ * timestamps. Verify BEFORE parsing JSON. During a secret rotation the header
558
+ * may carry two `v1` entries; verification passes if any matches.
559
+ *
560
+ * @param rawBody the exact request body bytes (string or Buffer)
561
+ * @param header the `Facto-Signature` header value (`t=..,v1=..[,v1=..]`)
562
+ * @param secret the endpoint signing secret
563
+ * @param toleranceSeconds max clock skew (default 300s)
564
+ */
565
+ declare function verifyWebhookSignature(rawBody: string | Uint8Array, header: string, secret: string, toleranceSeconds?: number): boolean;
566
+ /** A public Ed25519 JWK (OKP) as served by the Facto connect-hint JWKS. */
567
+ interface FactoCardProgramConnectJwk {
568
+ kty: string;
569
+ crv: string;
570
+ x: string;
571
+ kid?: string;
572
+ alg?: string;
573
+ use?: string;
574
+ }
575
+ /**
576
+ * The Facto connect-hint JWK set, served (public, no auth) at
577
+ * `GET /.well-known/facto-card-program-connect/jwks.json`.
578
+ */
579
+ interface FactoCardProgramConnectJwks {
580
+ keys: FactoCardProgramConnectJwk[];
581
+ }
582
+ /**
583
+ * How the caller supplies the Facto JWKS: an in-memory `{ keys }` set, a JWKS URL
584
+ * string to fetch (public GET, no auth), or a resolver that returns the set.
585
+ */
586
+ type FactoCardProgramConnectJwksInput = FactoCardProgramConnectJwks | string | (() => FactoCardProgramConnectJwks | Promise<FactoCardProgramConnectJwks>);
587
+ interface VerifyFactoCardProgramConnectHintInput {
588
+ /** The compact EdDSA JWS the Facto user handed the partner. */
589
+ connectHint: string;
590
+ /** The Facto JWKS: an in-memory `{ keys }` set, a JWKS URL to fetch, or a resolver. */
591
+ jwks: FactoCardProgramConnectJwksInput;
592
+ /**
593
+ * The partner's own connection audience — its environment-unique program code.
594
+ * The hint's `aud` MUST equal this; a mismatch is rejected. Required, because a
595
+ * hint is only meaningful for the program it was scoped to.
596
+ */
597
+ audience: string;
598
+ /** Expected issuer. Defaults to `'facto'`. */
599
+ issuer?: string;
600
+ /** Verification clock (unix milliseconds or `Date`). Defaults to `Date.now()`. */
601
+ now?: number | Date;
602
+ /** Clock-skew tolerance in seconds applied to the expiry check. Defaults to `0`. */
603
+ clockToleranceSeconds?: number;
604
+ }
605
+ interface FactoCardProgramConnectHint {
606
+ /** The opaque program the hint is scoped to (`cprog_...`). */
607
+ programRef: string;
608
+ /** Pairwise-opaque subject (`facto-user:<hex>`); NEVER the raw Facto user id. */
609
+ pairwiseSubject: string;
610
+ /** Single-use nonce; the caller MUST enforce single-use against its own store. */
611
+ nonce: string;
612
+ /** Absolute expiry (`exp`) as an RFC 3339 / ISO-8601 timestamp. */
613
+ expiresAt: string;
614
+ }
615
+ type FactoConnectHintErrorCode = 'FACTO_HINT_INPUT_INVALID' | 'FACTO_HINT_JWKS_INVALID' | 'FACTO_HINT_MALFORMED' | 'FACTO_HINT_UNSUPPORTED_ALG' | 'FACTO_HINT_SIGNATURE_INVALID' | 'FACTO_HINT_ISSUER_MISMATCH' | 'FACTO_HINT_AUDIENCE_MISMATCH' | 'FACTO_HINT_EXPIRED' | 'FACTO_HINT_CLAIMS_INVALID';
616
+ declare class FactoConnectHintError extends Error {
617
+ readonly code: FactoConnectHintErrorCode;
618
+ readonly details?: unknown;
619
+ constructor(code: FactoConnectHintErrorCode, message: string, options?: {
620
+ details?: unknown;
621
+ });
622
+ }
623
+ /**
624
+ * Verify a Facto-initiated card-program connect-hint (Feature 020 slice C2).
625
+ *
626
+ * Validates the Ed25519 signature against the Facto JWKS, enforces `iss` / `aud`
627
+ * / `exp`, and returns the safe claims. The returned `pairwiseSubject` is the
628
+ * pairwise-opaque HMAC subject (never the raw Facto user id) the partner binds to
629
+ * its own cardholder; the returned `nonce` MUST be enforced single-use by the
630
+ * caller against its own store.
631
+ */
632
+ declare function verifyFactoCardProgramConnectHint(input: VerifyFactoCardProgramConnectHintInput): Promise<FactoCardProgramConnectHint>;
633
+
634
+ export { type CheckoutSession, type CheckoutSessionStatus, type CheckoutStatus, type CreateCheckoutSessionInput, type CreateHostedConnectUrlInput, type CreateMandateAuthorizationSessionInput, type CreateMandateAuthorizationSessionRequest, type CreateMandatePaymentInput, type CreateMandatePaymentRequest, type CreateRefundInput, type CreateWebhookEndpointInput, type CursorListFilter, type DevCapabilities, type DevCapability, type DevCapabilityName, type DevCapabilityStatus, type DevEvidenceLevel, type DevFaucetTransfer, type DevMoney, type DevSimulation, type DevSimulationExecutionMode, type DevSimulationScenario, type DevSimulationStatus, type ExchangeLinkCodeInput, type ExchangeLinkCodeResult, FACTO_CONNECT_API_BASE_URLS, FACTO_CONNECT_HOSTED_URLS, type FactoCardProgramConnectHint, type FactoCardProgramConnectJwk, type FactoCardProgramConnectJwks, type FactoCardProgramConnectJwksInput, type FactoConnectEnvironment, FactoConnectHintError, type FactoConnectHintErrorCode, type FactoConnectServerClient, FactoConnectServerError, type FactoConnectServerErrorCode, type FactoConnectServerOptions, type FactoConnectTransport, type FundDevUserInput, type HostedConnectUrlInput, type MandateAuthorizationSession, type MandateLimits, type MandatePayment, type MandatePaymentStatusListener, type MerchantMandate, type MerchantPaymentListFilter, type MerchantPaymentOption, type MerchantPaymentOptions, type MerchantPaymentPathProjection, type OnMandatePaymentStatusOptions, type Page, type PaymentAuthorizationListFilter, type PaymentCapability, type PaymentCapabilityInput, type PaymentOptionsInput, type Refund, type RefundListFilter, type RefundReason, type RefundStatus, type SendWebhookTestDeliveryInput, type ServerRetryOptions, type SimulateDevChargeInput, type VerifyFactoCardProgramConnectHintInput, type WebhookEndpoint, type WebhookEndpointWithSecret, type WebhookEventType, type WebhookTestDeliveryAccepted, buildHostedConnectUrl, createFactoConnectServer, createFactoConnectServer as default, isTerminalMandatePaymentStatus, signWebhookPayload, verifyFactoCardProgramConnectHint, verifyWebhookSignature, withServerRetry };