glitch-javascript-sdk 3.15.0 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -25,7 +25,9 @@ declare class Requests {
25
25
  static put<T>(url: string, data: any, params?: Record<string, any>): AxiosPromise<Response<T>>;
26
26
  static patch<T>(url: string, data: any, params?: Record<string, any>): AxiosPromise<Response<T>>;
27
27
  static delete<T>(url: string, params?: Record<string, any>): AxiosPromise<Response<T>>;
28
- static uploadFile<T>(url: string, filename: string, file: File | Blob, data?: any, params?: Record<string, any>, onUploadProgress?: (progressEvent: AxiosProgressEvent) => void, options?: Pick<AxiosRequestConfig, 'signal' | 'timeout'>): AxiosPromise<Response<T>>;
28
+ static uploadFile<T>(url: string, filename: string, file: File | Blob, data?: any, params?: Record<string, any>, onUploadProgress?: (progressEvent: AxiosProgressEvent) => void, options?: Pick<AxiosRequestConfig, 'signal' | 'timeout'> & {
29
+ excludeCommunityContext?: boolean;
30
+ }): AxiosPromise<Response<T>>;
29
31
  static postFormData<T>(url: string, formData: FormData, params?: Record<string, any>, onUploadProgress?: (progressEvent: AxiosProgressEvent) => void): AxiosPromise<Response<T>>;
30
32
  static uploadBlob<T>(url: string, filename: string, blob: Blob, data?: any, params?: Record<string, any>, onUploadProgress?: (progressEvent: AxiosProgressEvent) => void): AxiosPromise<Response<T>>;
31
33
  static uploadFileInChunks<T>(file: File, uploadUrl: string, onProgress?: (totalSize: number, amountUploaded: number) => void, data?: any, chunkSize?: number): Promise<void>;
package/dist/index.d.ts CHANGED
@@ -12180,13 +12180,17 @@ declare class FestivalNetworking {
12180
12180
  }
12181
12181
 
12182
12182
  type MicrotransactionEnvironment = 'sandbox' | 'live';
12183
+ type MicrotransactionProviderName = 'stripe' | 'xsolla';
12183
12184
  type MicrotransactionProductType = 'durable' | 'consumable' | 'currency' | 'bundle' | 'pass';
12184
12185
  type MicrotransactionCurrency = 'USD' | 'EUR' | 'GBP' | 'CAD' | 'AUD' | 'JPY' | 'BRL' | 'INR' | 'KRW';
12185
12186
  type MicrotransactionProductStatus = 'draft' | 'active' | 'archived';
12186
- type MicrotransactionPaymentStatus = 'created' | 'action_required' | 'pending' | 'unknown' | 'paid' | 'failed' | 'canceled' | 'refund_pending' | 'partially_refunded' | 'refunded' | 'disputed' | 'quarantined';
12187
+ type MicrotransactionPaymentStatus = 'created' | 'action_required' | 'pending' | 'unknown' | 'paid' | 'failed' | 'canceled' | 'refund_pending' | 'partially_refunded' | 'refunded' | 'disputed' | 'quarantined' | 'refund_review';
12188
+ type MicrotransactionRefundStatus = 'requested' | 'linked' | 'unknown' | 'pending' | 'submitted' | 'succeeded' | 'failed' | 'canceled';
12189
+ type MicrotransactionDeliveryStatus = 'pending' | 'retrying' | 'processing' | 'acknowledged' | 'failed' | 'superseded';
12190
+ type MicrotransactionPayoutStatus = 'pending' | 'transferred' | 'bank_paid' | 'bank_pending' | 'bank_failed' | 'transfer_reversed';
12187
12191
  type MicrotransactionFulfillmentStatus = 'not_ready' | 'pending' | 'delivered' | 'retrying' | 'failed' | 'revoked' | 'partially_recovered';
12188
12192
  type MicrotransactionAbility = 'commerce:read' | 'commerce:write' | 'commerce:finance' | 'commerce:fulfill';
12189
- type MicrotransactionErrorCode = 'authentication_required' | 'permission_denied' | 'human_approval_required' | 'not_found' | 'not_eligible' | 'quote_expired' | 'already_owned' | 'idempotency_conflict' | 'payment_unknown' | 'rate_limited' | 'invalid_revenue_configuration' | 'fulfillment_pending' | 'provider_unavailable';
12193
+ type MicrotransactionErrorCode = 'authentication_required' | 'permission_denied' | 'not_found' | 'not_eligible' | 'quote_expired' | 'already_owned' | 'idempotency_conflict' | 'payment_unknown' | 'rate_limited' | 'invalid_revenue_configuration' | 'fulfillment_pending' | 'provider_unavailable';
12190
12194
  /** The backend's JSON envelope; Axios returns this envelope in response.data. */
12191
12195
  interface MicrotransactionResponse<T> {
12192
12196
  data: T;
@@ -12209,6 +12213,41 @@ interface MicrotransactionSessionOptions extends MicrotransactionRequestOptions
12209
12213
  interface MicrotransactionEnvironmentFilter {
12210
12214
  environment?: MicrotransactionEnvironment;
12211
12215
  }
12216
+ /** Catalog discovery defaults to 200 records per page; absence on page one is not proof a SKU is unused. */
12217
+ interface MicrotransactionProductListFilters {
12218
+ page?: number;
12219
+ per_page?: number;
12220
+ status?: MicrotransactionProductStatus;
12221
+ /** Exact SKU, not a substring search. */
12222
+ sku?: string;
12223
+ }
12224
+ /** Administrative lists default to page 1 / 25 records and are scoped to the authorized title. */
12225
+ interface MicrotransactionManagementListFilters extends MicrotransactionEnvironmentFilter {
12226
+ page?: number;
12227
+ per_page?: number;
12228
+ status?: string;
12229
+ }
12230
+ interface MicrotransactionOrderListFilters extends MicrotransactionManagementListFilters {
12231
+ product_id?: string;
12232
+ status?: MicrotransactionPaymentStatus;
12233
+ payment_status?: MicrotransactionPaymentStatus;
12234
+ }
12235
+ interface MicrotransactionRelatedListFilters extends MicrotransactionManagementListFilters {
12236
+ order_id?: string;
12237
+ }
12238
+ interface MicrotransactionRefundListFilters extends MicrotransactionRelatedListFilters {
12239
+ status?: MicrotransactionRefundStatus;
12240
+ }
12241
+ interface MicrotransactionDeliveryListFilters extends MicrotransactionRelatedListFilters {
12242
+ status?: MicrotransactionDeliveryStatus;
12243
+ }
12244
+ interface MicrotransactionPayoutListFilters extends MicrotransactionRelatedListFilters {
12245
+ status?: MicrotransactionPayoutStatus;
12246
+ }
12247
+ /** @deprecated Optional compatibility field only; no confirmation or human-approval gate is enforced. */
12248
+ interface MicrotransactionLegacyConfirmation {
12249
+ confirm?: boolean;
12250
+ }
12212
12251
  /** Self-only purchase-history filters. Identity comes from authentication, never a user_id argument. */
12213
12252
  interface MicrotransactionMyPurchasesFilters extends MicrotransactionEnvironmentFilter {
12214
12253
  /** Page number, integer 1–10000. Defaults to 1; ordering is created_at DESC, id DESC. */
@@ -12268,7 +12307,7 @@ interface MicrotransactionProductInput {
12268
12307
  starts_at?: string | null;
12269
12308
  ends_at?: string | null;
12270
12309
  max_per_order?: number;
12271
- /** Required for publishing/changing published goods; live approvals also enforced server-side. */
12310
+ /** @deprecated Ignored compatibility field. Title authorization and immutable-data validation remain required. */
12272
12311
  confirm?: boolean;
12273
12312
  }
12274
12313
  interface MicrotransactionProduct extends Omit<MicrotransactionProductInput, 'confirm' | 'status' | 'media_ids'> {
@@ -12281,19 +12320,176 @@ interface MicrotransactionProduct extends Omit<MicrotransactionProductInput, 'co
12281
12320
  created_at: string;
12282
12321
  updated_at: string;
12283
12322
  }
12323
+ /** Read-only collection facts, not tax exemption or a determination of tax owed. */
12324
+ interface MicrotransactionTaxCollection {
12325
+ /** Configured intent stays automatic during a known pending-setup fallback. */
12326
+ requested_mode: 'automatic' | 'disabled';
12327
+ /** Pending setup may disable collection for a NEW order; unknown facts are null and block new automatic checkout. */
12328
+ effective_mode: 'automatic' | 'disabled' | null;
12329
+ status: string;
12330
+ missing_fields: string[];
12331
+ fallback_reason: 'stripe_tax_setup_incomplete' | null;
12332
+ warnings: string[];
12333
+ }
12284
12334
  interface MicrotransactionProvider {
12285
- provider: 'stripe' | 'xsolla';
12335
+ provider: MicrotransactionProviderName;
12286
12336
  environment: MicrotransactionEnvironment;
12287
12337
  configured: boolean;
12288
- approved: boolean;
12338
+ /** Actual external provider/account capability, not a manual approval flag. */
12339
+ available: boolean;
12340
+ enabled: boolean;
12341
+ priority: number;
12289
12342
  countries: string[];
12290
12343
  currencies: string[];
12344
+ minimum_amounts: Record<string, number>;
12291
12345
  channels: string[];
12292
- reason?: string;
12346
+ payment_methods: string[];
12347
+ configuration: MicrotransactionProviderConfiguration;
12348
+ account: {
12349
+ id: string;
12350
+ country: string | null;
12351
+ charges_enabled: boolean;
12352
+ payouts_enabled: boolean;
12353
+ requirements_due: string[];
12354
+ merchant_name?: string | null;
12355
+ } | null;
12356
+ /** The game's payout target. Do not substitute the platform processing account's payouts_enabled. */
12357
+ payout_account: {
12358
+ source: 'platform' | 'user' | 'community' | 'managed';
12359
+ id: string | null;
12360
+ available: boolean;
12361
+ country: string | null;
12362
+ transfers_active: boolean;
12363
+ payouts_enabled: boolean;
12364
+ requirements_due: string[];
12365
+ reasons: string[];
12366
+ };
12367
+ tax: {
12368
+ status: string;
12369
+ missing_fields: string[];
12370
+ };
12371
+ /** Current route facts only. Never use these to reinterpret an existing order's frozen decision. */
12372
+ tax_collection?: MicrotransactionTaxCollection | null;
12373
+ /** Non-blocking collection warnings, separate from reasons and payout_account availability. */
12374
+ warnings?: string[];
12375
+ reasons: string[];
12376
+ checked_at: string | null;
12377
+ revision?: number;
12378
+ }
12379
+ interface MicrotransactionProviderSku {
12380
+ /** Provider SKU, 1–100 characters. */
12381
+ sku: string;
12382
+ currency: MicrotransactionCurrency;
12383
+ amount_minor: number;
12384
+ }
12385
+ interface MicrotransactionProviderConfiguration {
12386
+ /** Requested configuration. Explicit disabled is sandbox-only; pending-setup fallback does not change live configuration to disabled. */
12387
+ tax_mode: 'automatic' | 'disabled';
12388
+ /** Stripe tax code txcd_ followed by exactly eight digits. */
12389
+ tax_code: string | null;
12390
+ payout_source: 'platform' | 'user' | 'community' | 'managed';
12391
+ /** Xsolla public project ID, 1–20 decimal digits. */
12392
+ project_id: string | null;
12393
+ /** Maximum 200 mappings. */
12394
+ sku_map: Record<string, MicrotransactionProviderSku>;
12395
+ }
12396
+ /** Developer preferences and an optional new owned Xsolla webhook secret only; never platform credentials, arbitrary payees, or availability facts. */
12397
+ interface MicrotransactionProviderInput extends Partial<MicrotransactionProviderConfiguration>, MicrotransactionLegacyConfirmation {
12398
+ environment: MicrotransactionEnvironment;
12399
+ enabled?: boolean;
12400
+ priority?: number;
12401
+ countries?: string[];
12402
+ currencies?: MicrotransactionCurrency[];
12403
+ minimum_amounts?: Record<string, number>;
12404
+ /** Write-only NEW owned Xsolla project secret, 16–512 chars, finance scope. Never a platform API key or MCP token; never returned/logged or put in game code. Existing platform/historical bindings cannot be overwritten. */
12405
+ webhook_secret?: string;
12406
+ }
12407
+ interface MicrotransactionProviderOnboardingInput extends MicrotransactionLegacyConfirmation {
12408
+ environment: MicrotransactionEnvironment;
12409
+ country: string;
12410
+ /** Stable caller-created key. Reuse with identical input after uncertain retries; never generate inside a retry. */
12411
+ idempotency_key: string;
12412
+ }
12413
+ interface MicrotransactionProviderOnboarding {
12414
+ title_id: string;
12415
+ provider: 'stripe';
12416
+ environment: MicrotransactionEnvironment;
12417
+ account_id: string;
12418
+ /** Single-use provider onboarding URL on connect.stripe.com; do not log or persist it. */
12419
+ onboarding_url: string;
12420
+ expires_at: string;
12421
+ status: 'requires_provider_onboarding';
12422
+ reused: boolean;
12423
+ }
12424
+ interface MicrotransactionDeliverySettings {
12425
+ title_id: string;
12426
+ environment: MicrotransactionEnvironment;
12427
+ enabled: boolean;
12428
+ url: string | null;
12429
+ signature_algorithm: 'ed25519' | 'hmac-sha256';
12430
+ /** Public verification material only. The private signing key never leaves the server. */
12431
+ verification_public_key: string | null;
12432
+ key_id: string | null;
12433
+ revision: number;
12434
+ configured: boolean;
12435
+ }
12436
+ interface MicrotransactionDeliverySettingsInput extends MicrotransactionLegacyConfirmation {
12437
+ environment: MicrotransactionEnvironment;
12438
+ enabled?: boolean;
12439
+ url?: string | null;
12440
+ }
12441
+ interface MicrotransactionDelivery {
12442
+ id: string;
12443
+ order_id: string;
12444
+ event_type: string;
12445
+ status: MicrotransactionDeliveryStatus;
12446
+ attempts: number;
12447
+ next_attempt_at: string | null;
12448
+ acknowledged_at: string | null;
12449
+ created_at: string;
12450
+ updated_at: string;
12451
+ }
12452
+ /** Replay/acknowledgement return only this safe subset, not the list's timestamps. */
12453
+ type MicrotransactionDeliveryResult = Pick<MicrotransactionDelivery, 'id' | 'order_id' | 'status' | 'event_type' | 'attempts' | 'acknowledged_at'>;
12454
+ interface MicrotransactionRefundRecord {
12455
+ id: string;
12456
+ order_id: string;
12457
+ status: MicrotransactionRefundStatus;
12458
+ amount_minor: number;
12459
+ reason: string;
12460
+ idempotency_key: string | null;
12461
+ record_type: 'request' | 'execution';
12462
+ execution_refund_id: string | null;
12463
+ execution_status: MicrotransactionRefundStatus | null;
12464
+ request_resolution: 'linked_to_execution' | 'not_executed' | null;
12465
+ order_refunded_minor: number | null;
12466
+ failure_code: string | null;
12467
+ created_at: string;
12468
+ updated_at: string;
12469
+ }
12470
+ interface MicrotransactionPayout {
12471
+ id: string;
12472
+ order_id: string;
12473
+ status: MicrotransactionPayoutStatus;
12474
+ amount_minor: number;
12475
+ provider_reference: string | null;
12476
+ created_at: string;
12477
+ updated_at: string;
12478
+ }
12479
+ interface MicrotransactionRefundInput extends MicrotransactionLegacyConfirmation {
12480
+ reason: string;
12481
+ amount_minor?: number;
12482
+ /** REQUIRED stable operation key, scoped to title/order. Reuse identical input on retry; changes conflict. */
12483
+ idempotency_key: string;
12293
12484
  }
12294
12485
  interface MicrotransactionReadiness {
12295
12486
  status: 'disabled' | 'draft' | 'sandbox' | 'ready' | 'live' | 'degraded' | 'suspended';
12487
+ /** Configuration readiness only; not proof of payment, delivery, claim or browser 3DS. */
12296
12488
  ready: boolean;
12489
+ /** Optional on older backends; retains the same configuration meaning as ready. */
12490
+ configuration_ready?: boolean;
12491
+ /** Stored sandbox paid + fulfilled + claimed evidence. Absent means unknown; not browser/3DS certification. */
12492
+ integration_verified?: boolean;
12297
12493
  blockers: string[];
12298
12494
  providers: MicrotransactionProvider[];
12299
12495
  commission_basis_points: 1200;
@@ -12313,8 +12509,9 @@ interface MicrotransactionSettingsInput {
12313
12509
  currencies?: MicrotransactionCurrency[];
12314
12510
  branding?: Omit<MicrotransactionBranding, 'logo_media'>;
12315
12511
  support_email?: string | null;
12512
+ /** @deprecated Legacy delivery alias requiring BOTH commerce:write and commerce:fulfill; prefer updateDeliverySettings/getDeliverySettings. */
12316
12513
  webhook_url?: string | null;
12317
- /** Required for policy/live changes; cannot replace recorded platform approval. */
12514
+ /** @deprecated Ignored compatibility field. Authorized title editors save directly; actual provider/sales restrictions remain. */
12318
12515
  confirm?: boolean;
12319
12516
  }
12320
12517
  interface MicrotransactionSettings extends Omit<Required<MicrotransactionSettingsInput>, 'confirm'> {
@@ -12393,8 +12590,17 @@ interface MicrotransactionOrder {
12393
12590
  paid_at: string | null;
12394
12591
  refunded_minor: number;
12395
12592
  items: MicrotransactionGrant[];
12593
+ /** Frozen decision, also returned inside checkout/session.order. Null/absent for legacy orders; never infer from current provider facts. Warnings do not imply zero tax owed. */
12594
+ tax_collection?: MicrotransactionTaxCollection | null;
12396
12595
  entitlements?: MicrotransactionEntitlement[];
12397
12596
  }
12597
+ interface MicrotransactionOrderDetail extends MicrotransactionOrder {
12598
+ /** Optional, permission-scoped management relationships. Omission is not proof no records exist. */
12599
+ refunds?: Array<Pick<MicrotransactionRefundRecord, 'id' | 'order_id' | 'status'> & Partial<MicrotransactionRefundRecord>>;
12600
+ deliveries?: MicrotransactionDelivery[];
12601
+ payouts?: Array<Pick<MicrotransactionPayout, 'id' | 'order_id' | 'status'> & Partial<MicrotransactionPayout>>;
12602
+ financial_details_included?: boolean;
12603
+ }
12398
12604
  type MicrotransactionGrantUsageStatus = 'unused' | 'partially_used' | 'used_up' | 'owned' | 'expired' | 'revoked' | 'not_delivered' | 'unavailable';
12399
12605
  /** One purchase's server-calculated grant lot, not the player's aggregate inventory balance. */
12400
12606
  interface MicrotransactionGrantUsage {
@@ -12545,8 +12751,10 @@ interface MicrotransactionConsumeInput {
12545
12751
  }
12546
12752
  interface MicrotransactionRefund {
12547
12753
  refund_id: string;
12548
- status: string;
12754
+ status: MicrotransactionRefundStatus;
12549
12755
  order_id: string;
12756
+ idempotency_key: string;
12757
+ failure_code: string | null;
12550
12758
  refund_allocation?: 'pro_rata_all_grants';
12551
12759
  }
12552
12760
  interface MicrotransactionRefundRequest {
@@ -12569,14 +12777,16 @@ interface MicrotransactionEarnings {
12569
12777
  payouts_enabled: boolean;
12570
12778
  reserve_days?: number;
12571
12779
  }
12572
- type MicrotransactionOperation = 'settings.get' | 'settings.update' | 'products.list' | 'products.create' | 'products.update' | 'products.archive' | 'providers.list' | 'readiness.get' | 'orders.list' | 'orders.get' | 'earnings.get' | 'refunds.request' | 'deliveries.replay' | 'integration.get' | 'integration.verify';
12780
+ type MicrotransactionOperation = 'settings.get' | 'settings.update' | 'products.list' | 'products.create' | 'products.update' | 'products.archive' | 'providers.list' | 'providers.update' | 'providers.refresh' | 'providers.onboarding' | 'readiness.get' | 'orders.list' | 'orders.get' | 'orders.reconcile' | 'earnings.get' | 'refunds.list' | 'refunds.get' | 'refunds.create' | 'refunds.request' | 'refunds.reconcile' | 'delivery.settings.get' | 'delivery.settings.update' | 'deliveries.list' | 'deliveries.replay' | 'deliveries.acknowledge' | 'payouts.list' | 'integration.get' | 'integration.verify';
12573
12781
  interface MicrotransactionOperationCapability {
12574
12782
  operation: MicrotransactionOperation;
12575
12783
  description: string;
12576
12784
  ability: MicrotransactionAbility;
12577
12785
  input_schema: Record<string, unknown>;
12578
- requires_confirmation: boolean;
12579
- requires_human_approval: boolean;
12786
+ http_method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
12787
+ mutates: boolean;
12788
+ requires_confirmation: false;
12789
+ requires_human_approval: false;
12580
12790
  examples: Array<Record<string, unknown>>;
12581
12791
  output_description: string;
12582
12792
  }
@@ -12587,8 +12797,9 @@ interface MicrotransactionCapabilities {
12587
12797
  [key: string]: unknown;
12588
12798
  }
12589
12799
  /**
12590
- * Provider-neutral, title-scoped commerce. Configure with user JWT; purchases
12591
- * use a recoverable user account and limited checkout capability. Install/title
12800
+ * Provider-neutral, title-scoped commerce. Guest games configure only the API
12801
+ * base URL, never global account/admin auth. Hosted account pages use their own
12802
+ * user JWT and limited checkout capability; playerToken overrides auth per request. Install/title
12592
12803
  * tokens cannot authorize money, ownership, refunds, or catalog changes.
12593
12804
  *
12594
12805
  * Each result preserves payment versus fulfillment versus settlement. Redirects
@@ -12608,49 +12819,85 @@ declare class Microtransactions {
12608
12819
  static settings(title_id: string, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionSettings>>;
12609
12820
  /** Atomic policy update. Sandbox/off by default. Cannot disable the final working revenue model. */
12610
12821
  static updateSettings(title_id: string, data: MicrotransactionSettingsInput, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionSettings>>;
12611
- /** Read-only country/provider/approval readiness; never enables a provider. */
12822
+ /** Read-only current country/provider capability and revenue readiness; never fabricates availability. */
12612
12823
  static readiness(title_id: string, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionReadiness>>;
12613
- /** Admin list includes drafts and archives. Player clients should use catalog(). */
12824
+ /** Paginated admin catalog including drafts/archives. Default 200, per_page 1–200/page 1–10000. Use exact sku to resolve uncertain creates. */
12825
+ static listProducts(title_id: string, params?: MicrotransactionProductListFilters, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<{
12826
+ products: MicrotransactionProduct[];
12827
+ pagination: MicrotransactionPurchasePagination;
12828
+ }>>;
12829
+ /** @deprecated Compatibility overload for the earlier second-argument request options. */
12614
12830
  static listProducts(title_id: string, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<{
12615
12831
  products: MicrotransactionProduct[];
12832
+ pagination: MicrotransactionPurchasePagination;
12616
12833
  }>>;
12617
12834
  /** Save a catalog product. Prices use integer minor units and attached media must belong to the title. */
12618
12835
  static createProduct(title_id: string, data: MicrotransactionProductInput, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionProduct>>;
12619
12836
  /** Update a product version. Existing order snapshots remain unchanged. */
12620
12837
  static updateProduct(title_id: string, product_id: string, data: Partial<MicrotransactionProductInput>, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionProduct>>;
12621
- /** Archive, never delete financial history. Requires explicit confirmation. */
12622
- static archiveProduct(title_id: string, product_id: string, data: {
12623
- confirm: true;
12624
- }, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionProduct>>;
12625
- /** Public provider metadata only. Credentials and commercial approvals are platform-managed. */
12838
+ /** Direct authorized archive. Never deletes financial history or bypasses the last-revenue-model rule. */
12839
+ static archiveProduct(title_id: string, product_id: string, data?: MicrotransactionLegacyConfirmation, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionProduct>>;
12840
+ /** Actual provider configuration/capability facts; no credentials or manual approval flag. */
12841
+ static providers(title_id: string, params?: MicrotransactionEnvironmentFilter, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<{
12842
+ providers: MicrotransactionProvider[];
12843
+ }>>;
12844
+ /** @deprecated Compatibility overload for the earlier second-argument request options. */
12626
12845
  static providers(title_id: string, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<{
12627
12846
  providers: MicrotransactionProvider[];
12628
12847
  }>>;
12848
+ /** Direct commerce:finance configuration. Saving preferences does not fabricate external capability; inspect available/reasons. */
12849
+ static updateProvider(title_id: string, provider: MicrotransactionProviderName, data: MicrotransactionProviderInput, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionProvider>>;
12850
+ /** Refresh authenticated external provider facts. May update cached state; never creates a payment or invents eligibility. */
12851
+ static refreshProvider(title_id: string, provider: MicrotransactionProviderName, data: {
12852
+ environment: MicrotransactionEnvironment;
12853
+ }, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionProvider>>;
12854
+ /** Start/reuse owned Stripe Connect onboarding with one stable key. Provider KYC is factual setup, not a Glitch approval workflow. */
12855
+ static createProviderOnboarding(title_id: string, data: MicrotransactionProviderOnboardingInput, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionProviderOnboarding>>;
12856
+ /** Read title/environment delivery settings and the Ed25519 PUBLIC verification key. */
12857
+ static getDeliverySettings(title_id: string, params?: MicrotransactionEnvironmentFilter, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionDeliverySettings>>;
12858
+ /** Direct commerce:fulfill setup. Private/metadata network targets and private-key inputs remain forbidden. */
12859
+ static updateDeliverySettings(title_id: string, data: MicrotransactionDeliverySettingsInput, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionDeliverySettings>>;
12860
+ /** Discover safe event IDs/statuses before replay or acknowledge. Page 1–10000, per_page 1–100, default 25. */
12861
+ static listDeliveries(title_id: string, params?: MicrotransactionDeliveryListFilters, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<{
12862
+ deliveries: MicrotransactionDelivery[];
12863
+ pagination: MicrotransactionPurchasePagination;
12864
+ }>>;
12865
+ /** Financially scoped refund operation discovery; pending/unknown is not completed. */
12866
+ static listRefunds(title_id: string, params?: MicrotransactionRefundListFilters, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<{
12867
+ refunds: MicrotransactionRefundRecord[];
12868
+ pagination: MicrotransactionPurchasePagination;
12869
+ }>>;
12870
+ /** Inspect one same-title refund operation. */
12871
+ static getRefund(title_id: string, refund_id: string, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionRefundRecord>>;
12872
+ /** Query/retry the original persisted refund with its existing identity, never generate a new refund key. */
12873
+ static reconcileRefund(title_id: string, refund_id: string, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionRefundRecord>>;
12874
+ /** Discover provider transfer/payout records; transferred funds are not automatically a verified bank payout. */
12875
+ static listPayouts(title_id: string, params?: MicrotransactionPayoutListFilters, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<{
12876
+ payouts: MicrotransactionPayout[];
12877
+ pagination: MicrotransactionPurchasePagination;
12878
+ }>>;
12629
12879
  /** Admin read of separate-currency balances; pending is not withdrawable revenue. */
12630
12880
  static earnings(title_id: string, params?: MicrotransactionEnvironmentFilter, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionEarnings>>;
12631
- /** Admin list, bounded to the server's most recent 100 redacted orders. */
12632
- static listOrders(title_id: string, params?: MicrotransactionEnvironmentFilter, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<{
12881
+ /** Admin paginated redacted orders. Page 1–10000/per_page 1–100 (default 25); own-player history is separate. */
12882
+ static listOrders(title_id: string, params?: MicrotransactionOrderListFilters, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<{
12633
12883
  orders: MicrotransactionOrder[];
12884
+ pagination: MicrotransactionPurchasePagination;
12634
12885
  }>>;
12635
12886
  /** Owner JWT/scoped player token or title admin. An arbitrary order UUID grants no access. */
12636
- static getOrder(title_id: string, order_id: string, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionOrder>>;
12637
- /** Financial admin only; original provider and human approval. Omit amount_minor for remaining full refund; partial amounts are bounded and allocated pro rata. */
12638
- static refundOrder(title_id: string, order_id: string, data: {
12639
- reason: string;
12640
- confirm: true;
12641
- amount_minor?: number;
12642
- }, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionRefund>>;
12887
+ static getOrder(title_id: string, order_id: string, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionOrderDetail>>;
12888
+ /** Financially scoped original-provider reconciliation. Does not reroute or start a different purchase. */
12889
+ static reconcileOrder(title_id: string, order_id: string, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionOrderDetail>>;
12890
+ /** Direct commerce:finance refund. REQUIRED stable idempotency_key; omission is an error, never auto-filled. Same-key changed input conflicts. */
12891
+ static refundOrder(title_id: string, order_id: string, data: MicrotransactionRefundInput, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionRefund>>;
12643
12892
  /** Replay the same immutable event. Receiver must deduplicate event_id. This cannot mint goods. */
12644
- static replayDelivery(title_id: string, delivery_id: string, data: {
12645
- confirm: true;
12646
- }, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<Record<string, unknown>>>;
12647
- /** Public eligible catalog. Sandbox is restricted by backend environment/admin policy. */
12893
+ static replayDelivery(title_id: string, delivery_id: string, data?: MicrotransactionLegacyConfirmation, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionDeliveryResult>>;
12894
+ /** Guest catalog on the exact approved game Origin. Sandbox requires enabled sandbox settings; the backend enforces environment policy. */
12648
12895
  static catalog(title_id: string, params?: MicrotransactionCatalogFilter, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionCatalog>>;
12649
12896
  /** User-authenticated quote. Clients select product/quantity, never monetary values or seller accounts. */
12650
12897
  static createQuote(title_id: string, data: MicrotransactionPurchaseInput, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionQuote>>;
12651
- /** Anonymous-safe opening step only. The hosted UI creates/logs into an account before payment. */
12898
+ /** Guest opening only: browser Origin must equal approved return_origin. Inherits configured global auth; use an isolated credential-free game context. Hosted UI authenticates before payment. */
12652
12899
  static createCheckoutSession(title_id: string, data: MicrotransactionCheckoutSessionInput, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionCreatedCheckoutSession>>;
12653
- /** Anonymous-safe inventory recovery. Opens an in-game hosted sign-in overlay, never creates a charge or requires the game's account JWT. */
12900
+ /** Guest entry to hosted recovery, not inventory access. Exact approved Origin/return_origin required. Owning-account bind remains mandatory, including when commerce is off. Never install an account JWT in the game. */
12654
12901
  static createRestoreSession(title_id: string, data: {
12655
12902
  return_origin: string;
12656
12903
  nonce: string;
@@ -12686,7 +12933,7 @@ declare class Microtransactions {
12686
12933
  /** Record integration proof from a genuinely paid, fulfilled sandbox order with a claimed game handoff. */
12687
12934
  static verifyIntegration(title_id: string, data: {
12688
12935
  order_id: string;
12689
- confirm: true;
12936
+ confirm?: boolean;
12690
12937
  }, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionReadiness>>;
12691
12938
  /** Restore authoritative durable ownership/current consumable balances, never mutable cloud-save balances. */
12692
12939
  static listEntitlements(title_id: string, params?: MicrotransactionEnvironmentFilter, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<{
@@ -12718,10 +12965,10 @@ declare class Microtransactions {
12718
12965
  /** Trusted title server with commerce:fulfill or admin JWT acknowledges the immutable event. */
12719
12966
  static acknowledgeDelivery(title_id: string, delivery_id: string, data: {
12720
12967
  event_id: string;
12721
- }, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<Record<string, unknown>>>;
12722
- /** Title MCP token, never a runtime install token. Describes every argument/schema/ability/approval gate. */
12968
+ }, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionDeliveryResult>>;
12969
+ /** Title MCP token, never a runtime install token. Describes arguments, abilities, mutation semantics and provider facts. */
12723
12970
  static mcpCapabilities(title_id: string, options?: MicrotransactionRequestOptions): AxiosPromise<MicrotransactionResponse<MicrotransactionCapabilities>>;
12724
- /** Execute only an operation discovered in mcpCapabilities. confirm is not financial approval. */
12971
+ /** Execute a discovered authorized operation directly. Legacy confirm is ignored and not forwarded. */
12725
12972
  static mcpOperation<T = Record<string, unknown>>(title_id: string, operation: MicrotransactionOperation, data: {
12726
12973
  arguments: Record<string, unknown>;
12727
12974
  confirm?: boolean;
@@ -12912,7 +13159,9 @@ declare class Requests {
12912
13159
  static put<T>(url: string, data: any, params?: Record<string, any>): AxiosPromise<Response<T>>;
12913
13160
  static patch<T>(url: string, data: any, params?: Record<string, any>): AxiosPromise<Response<T>>;
12914
13161
  static delete<T>(url: string, params?: Record<string, any>): AxiosPromise<Response<T>>;
12915
- static uploadFile<T>(url: string, filename: string, file: File | Blob, data?: any, params?: Record<string, any>, onUploadProgress?: (progressEvent: AxiosProgressEvent) => void, options?: Pick<AxiosRequestConfig, 'signal' | 'timeout'>): AxiosPromise<Response<T>>;
13162
+ static uploadFile<T>(url: string, filename: string, file: File | Blob, data?: any, params?: Record<string, any>, onUploadProgress?: (progressEvent: AxiosProgressEvent) => void, options?: Pick<AxiosRequestConfig, 'signal' | 'timeout'> & {
13163
+ excludeCommunityContext?: boolean;
13164
+ }): AxiosPromise<Response<T>>;
12916
13165
  static postFormData<T>(url: string, formData: FormData, params?: Record<string, any>, onUploadProgress?: (progressEvent: AxiosProgressEvent) => void): AxiosPromise<Response<T>>;
12917
13166
  static uploadBlob<T>(url: string, filename: string, blob: Blob, data?: any, params?: Record<string, any>, onUploadProgress?: (progressEvent: AxiosProgressEvent) => void): AxiosPromise<Response<T>>;
12918
13167
  static uploadFileInChunks<T>(file: File, uploadUrl: string, onProgress?: (totalSize: number, amountUploaded: number) => void, data?: any, chunkSize?: number): Promise<void>;
@@ -13350,4 +13599,4 @@ declare class Glitch {
13350
13599
  };
13351
13600
  }
13352
13601
 
13353
- export { type FestivalApplicationInput, type FestivalApplicationState, type FestivalConversation, type FestivalMediaUpload, type FestivalNetworkingFilters, type FestivalNetworkingProfile, type FestivalNetworkingResponse, type FestivalNetworkingSettings, type FestivalPost, type FestivalPostInput, type FestivalPostKind, type FestivalPostState, type FestivalPreferences, type FestivalReportInput, type FestivalRequestOptions, type FestivalWorkType, type MicrotransactionAbility, type MicrotransactionBranding, type MicrotransactionBridge, type MicrotransactionBridgeOptions, type MicrotransactionCapabilities, type MicrotransactionCatalog, type MicrotransactionCatalogFilter, type MicrotransactionCheckoutInput, type MicrotransactionCheckoutResult, type MicrotransactionCheckoutSession, type MicrotransactionCheckoutSessionInput, type MicrotransactionConsumeInput, type MicrotransactionCreatedCheckoutSession, type MicrotransactionCurrency, type MicrotransactionEarnings, type MicrotransactionEntitlement, type MicrotransactionEnvironment, type MicrotransactionEnvironmentFilter, type MicrotransactionError, type MicrotransactionErrorCode, type MicrotransactionFramePolicy, type MicrotransactionFulfillmentStatus, type MicrotransactionGrant, type MicrotransactionGrantUsage, type MicrotransactionGrantUsageStatus, type MicrotransactionHandoff, type MicrotransactionHandoffClaim, type MicrotransactionHandoffClaimInput, type MicrotransactionMedia, type MicrotransactionMyPurchases, type MicrotransactionMyPurchasesFilters, type MicrotransactionOperation, type MicrotransactionOperationCapability, type MicrotransactionOrder, type MicrotransactionOverlay, type MicrotransactionOverlayOptions, type MicrotransactionPaymentStatus, type MicrotransactionPlayerPurchase, type MicrotransactionPrice, type MicrotransactionProduct, type MicrotransactionProductInput, type MicrotransactionProductStatus, type MicrotransactionProductType, type MicrotransactionProvider, type MicrotransactionPurchaseInput, type MicrotransactionPurchaseMessage, type MicrotransactionPurchasePagination, type MicrotransactionQuote, type MicrotransactionReadiness, type MicrotransactionReadyMessage, type MicrotransactionRefund, type MicrotransactionRefundRequest, type MicrotransactionRequestOptions, type MicrotransactionResponse, type MicrotransactionRestoreBridgeOptions, type MicrotransactionSessionOptions, type MicrotransactionSettings, type MicrotransactionSettingsInput, type MicrotransactionVerifiedSession, createMicrotransactionBridge, createMicrotransactionNonce, createMicrotransactionRestoreBridge, Glitch as default, openMicrotransactionOverlay, openMicrotransactionRestoreOverlay };
13602
+ export { type FestivalApplicationInput, type FestivalApplicationState, type FestivalConversation, type FestivalMediaUpload, type FestivalNetworkingFilters, type FestivalNetworkingProfile, type FestivalNetworkingResponse, type FestivalNetworkingSettings, type FestivalPost, type FestivalPostInput, type FestivalPostKind, type FestivalPostState, type FestivalPreferences, type FestivalReportInput, type FestivalRequestOptions, type FestivalWorkType, type MicrotransactionAbility, type MicrotransactionBranding, type MicrotransactionBridge, type MicrotransactionBridgeOptions, type MicrotransactionCapabilities, type MicrotransactionCatalog, type MicrotransactionCatalogFilter, type MicrotransactionCheckoutInput, type MicrotransactionCheckoutResult, type MicrotransactionCheckoutSession, type MicrotransactionCheckoutSessionInput, type MicrotransactionConsumeInput, type MicrotransactionCreatedCheckoutSession, type MicrotransactionCurrency, type MicrotransactionDelivery, type MicrotransactionDeliveryListFilters, type MicrotransactionDeliveryResult, type MicrotransactionDeliverySettings, type MicrotransactionDeliverySettingsInput, type MicrotransactionDeliveryStatus, type MicrotransactionEarnings, type MicrotransactionEntitlement, type MicrotransactionEnvironment, type MicrotransactionEnvironmentFilter, type MicrotransactionError, type MicrotransactionErrorCode, type MicrotransactionFramePolicy, type MicrotransactionFulfillmentStatus, type MicrotransactionGrant, type MicrotransactionGrantUsage, type MicrotransactionGrantUsageStatus, type MicrotransactionHandoff, type MicrotransactionHandoffClaim, type MicrotransactionHandoffClaimInput, type MicrotransactionLegacyConfirmation, type MicrotransactionManagementListFilters, type MicrotransactionMedia, type MicrotransactionMyPurchases, type MicrotransactionMyPurchasesFilters, type MicrotransactionOperation, type MicrotransactionOperationCapability, type MicrotransactionOrder, type MicrotransactionOrderDetail, type MicrotransactionOrderListFilters, type MicrotransactionOverlay, type MicrotransactionOverlayOptions, type MicrotransactionPaymentStatus, type MicrotransactionPayout, type MicrotransactionPayoutListFilters, type MicrotransactionPayoutStatus, type MicrotransactionPlayerPurchase, type MicrotransactionPrice, type MicrotransactionProduct, type MicrotransactionProductInput, type MicrotransactionProductListFilters, type MicrotransactionProductStatus, type MicrotransactionProductType, type MicrotransactionProvider, type MicrotransactionProviderConfiguration, type MicrotransactionProviderInput, type MicrotransactionProviderName, type MicrotransactionProviderOnboarding, type MicrotransactionProviderOnboardingInput, type MicrotransactionProviderSku, type MicrotransactionPurchaseInput, type MicrotransactionPurchaseMessage, type MicrotransactionPurchasePagination, type MicrotransactionQuote, type MicrotransactionReadiness, type MicrotransactionReadyMessage, type MicrotransactionRefund, type MicrotransactionRefundInput, type MicrotransactionRefundListFilters, type MicrotransactionRefundRecord, type MicrotransactionRefundRequest, type MicrotransactionRefundStatus, type MicrotransactionRelatedListFilters, type MicrotransactionRequestOptions, type MicrotransactionResponse, type MicrotransactionRestoreBridgeOptions, type MicrotransactionSessionOptions, type MicrotransactionSettings, type MicrotransactionSettingsInput, type MicrotransactionTaxCollection, type MicrotransactionVerifiedSession, createMicrotransactionBridge, createMicrotransactionNonce, createMicrotransactionRestoreBridge, Glitch as default, openMicrotransactionOverlay, openMicrotransactionRestoreOverlay };
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Node 24+ example: verify and durably queue Glitch Ed25519 notifications.
3
+ * Run behind your HTTPS reverse proxy. This is NOT an inventory grant engine:
4
+ * a worker/game session refreshes current entitlements with its own authorized
5
+ * player session after durable queue handling. Never apply payload snapshots.
6
+ */
7
+ import { createPublicKey, verify } from 'node:crypto';
8
+ import { createServer } from 'node:http';
9
+ import { DatabaseSync } from 'node:sqlite';
10
+ import { isAbsolute } from 'node:path';
11
+ import { pathToFileURL } from 'node:url';
12
+
13
+ const uuid = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;
14
+ function reject(code, status = 400) { const error = new Error(code); error.code = code; error.status = status; throw error; }
15
+ function decodeBase64(value, length) {
16
+ if (typeof value !== 'string' || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) reject('invalid_base64');
17
+ const bytes = Buffer.from(value, 'base64');
18
+ if (bytes.length !== length || bytes.toString('base64') !== value) reject('invalid_base64');
19
+ return bytes;
20
+ }
21
+
22
+ /** Configuration comes from authenticated delivery-settings, never the message. */
23
+ export function createDeliveryInbox({ titleId, environment, keyId, publicKeyBase64, databasePath }) {
24
+ if (!uuid.test(titleId) || !uuid.test(keyId) || !['sandbox', 'live'].includes(environment)) reject('invalid_receiver_configuration');
25
+ if (typeof databasePath !== 'string' || !isAbsolute(databasePath)) reject('durable_absolute_database_path_required');
26
+ // Ed25519 raw public keys need the standard SubjectPublicKeyInfo DER wrapper.
27
+ const publicKey = createPublicKey({ key: Buffer.concat([
28
+ Buffer.from('302a300506032b6570032100', 'hex'), decodeBase64(publicKeyBase64, 32)
29
+ ]), format: 'der', type: 'spki' });
30
+ const db = new DatabaseSync(databasePath);
31
+ db.exec('PRAGMA busy_timeout=5000');
32
+ db.exec(`CREATE TABLE IF NOT EXISTS commerce_notifications (
33
+ title_id TEXT NOT NULL, environment TEXT NOT NULL, event_id TEXT NOT NULL,
34
+ order_id TEXT NOT NULL, event_type TEXT NOT NULL, order_version INTEGER NOT NULL,
35
+ received_at INTEGER NOT NULL, handled_at INTEGER,
36
+ PRIMARY KEY(title_id, environment, event_id)
37
+ )`);
38
+ const existing = db.prepare('SELECT order_id,event_type FROM commerce_notifications WHERE title_id=? AND environment=? AND event_id=?');
39
+ const insert = db.prepare('INSERT INTO commerce_notifications(title_id,environment,event_id,order_id,event_type,order_version,received_at) VALUES(?,?,?,?,?,?,?)');
40
+
41
+ return {
42
+ /** rawBody must be the EXACT bytes received before any JSON parser. */
43
+ receive(headers, rawBody, nowSeconds = Math.floor(Date.now() / 1000)) {
44
+ if (!Buffer.isBuffer(rawBody) || rawBody.length > 1048576) reject('invalid_body_size', 413);
45
+ const h = Object.fromEntries(Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]));
46
+ if (h['x-glitch-signature-algorithm'] !== 'ed25519' || h['x-glitch-key-id'] !== keyId) reject('unexpected_signing_key_or_algorithm', 401);
47
+ const timestamp = h['x-glitch-timestamp'];
48
+ if (typeof timestamp !== 'string' || !/^[0-9]{1,12}$/.test(timestamp) || Math.abs(nowSeconds - Number(timestamp)) > 300) reject('expired_timestamp', 401);
49
+ const signature = decodeBase64(h['x-glitch-signature'], 64);
50
+ const signed = Buffer.concat([Buffer.from(timestamp + '.', 'ascii'), rawBody]);
51
+ if (!verify(null, signed, publicKey, signature)) reject('invalid_signature', 401);
52
+ let event;
53
+ try { event = JSON.parse(rawBody.toString('utf8')); } catch { reject('invalid_json'); }
54
+ if (!event || event.title_id !== titleId || event.environment !== environment || !uuid.test(event.id || '')
55
+ || event.id !== h['x-glitch-event-id'] || typeof event.type !== 'string'
56
+ || !Number.isSafeInteger(event.order_version) || event.order_version < 0
57
+ || !event.authoritative_order || !uuid.test(event.authoritative_order.id || '')
58
+ || event.authoritative_order.title_id !== titleId || event.authoritative_order.environment !== environment) reject('event_scope_mismatch', 401);
59
+ const orderId = event.authoritative_order.id;
60
+ let duplicate = false;
61
+ db.exec('BEGIN IMMEDIATE');
62
+ try {
63
+ const prior = existing.get(titleId, environment, event.id);
64
+ if (prior) {
65
+ if (prior.order_id !== orderId || prior.event_type !== event.type) reject('event_identity_conflict', 409);
66
+ duplicate = true;
67
+ } else {
68
+ // Queue IDs only. Aggregate balances in an older signed notification
69
+ // are not safe to apply across out-of-order events from other orders.
70
+ insert.run(titleId, environment, event.id, orderId, event.type, event.order_version, nowSeconds);
71
+ }
72
+ db.exec('COMMIT');
73
+ } catch (error) { db.exec('ROLLBACK'); throw error; }
74
+ // Retry bodies may carry refreshed authoritative facts. The stable event
75
+ // identity is deduped; embedded inventory is NEVER reapplied on a retry.
76
+ return { event_id: event.id, duplicate };
77
+ },
78
+ close() { db.close(); },
79
+ };
80
+ }
81
+
82
+ /** Complete HTTP receiver. JSON/body middleware must not run before this handler. */
83
+ export function createDeliveryServer(inbox) {
84
+ return createServer(async (request, response) => {
85
+ if (request.method !== 'POST' || request.url !== '/glitch/commerce') { response.writeHead(404).end(); return; }
86
+ try {
87
+ const chunks = []; let size = 0;
88
+ for await (const chunk of request) {
89
+ size += chunk.length;
90
+ if (size > 1048576) reject('invalid_body_size', 413);
91
+ chunks.push(chunk);
92
+ }
93
+ const acknowledgement = inbox.receive(request.headers, Buffer.concat(chunks));
94
+ response.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
95
+ response.end(JSON.stringify(acknowledgement)); // Only after durable commit.
96
+ } catch (error) {
97
+ response.writeHead(error.status || 500, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
98
+ response.end(JSON.stringify({ error: error.code || 'delivery_handling_failed' }));
99
+ // Do not log raw payload, signatures, credentials or private player data.
100
+ }
101
+ });
102
+ }
103
+
104
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
105
+ process.umask(0o077); // Keep the new application inbox/journal private.
106
+ const inbox = createDeliveryInbox({
107
+ titleId: process.env.GLITCH_TITLE_ID,
108
+ environment: process.env.GLITCH_COMMERCE_ENVIRONMENT,
109
+ keyId: process.env.GLITCH_DELIVERY_KEY_ID,
110
+ publicKeyBase64: process.env.GLITCH_DELIVERY_PUBLIC_KEY,
111
+ databasePath: process.env.GAME_DELIVERY_DATABASE,
112
+ });
113
+ const server = createDeliveryServer(inbox);
114
+ server.listen(Number(process.env.PORT || 8787), '127.0.0.1');
115
+ const stop = () => server.close(() => { inbox.close(); process.exit(0); });
116
+ process.once('SIGINT', stop); process.once('SIGTERM', stop);
117
+ }