@cross-deck/node 1.5.1 → 1.5.2

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.cjs CHANGED
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,14 +15,6 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
 
30
20
  // src/index.ts
@@ -34,7 +24,6 @@ __export(index_exports, {
34
24
  CROSSDECK_ERROR_CODES: () => CROSSDECK_ERROR_CODES,
35
25
  CrossdeckAuthenticationError: () => CrossdeckAuthenticationError,
36
26
  CrossdeckConfigurationError: () => CrossdeckConfigurationError,
37
- CrossdeckContracts: () => CrossdeckContracts,
38
27
  CrossdeckError: () => CrossdeckError,
39
28
  CrossdeckInternalError: () => CrossdeckInternalError,
40
29
  CrossdeckNetworkError: () => CrossdeckNetworkError,
@@ -374,85 +363,10 @@ function byteLength(s) {
374
363
  return s.length * 4;
375
364
  }
376
365
 
377
- // src/_diagnostic-telemetry.ts
378
- var https = __toESM(require("https"));
379
-
380
366
  // src/_version.ts
381
- var SDK_VERSION = "1.5.1";
367
+ var SDK_VERSION = "1.3.1";
382
368
  var SDK_NAME = "@cross-deck/node";
383
369
 
384
- // src/_diagnostic-telemetry.ts
385
- var DIAGNOSTIC_TELEMETRY_ENDPOINT = "https://api.cross-deck.com/v1/sdk/diagnostic";
386
- var DIAGNOSTIC_TELEMETRY_PUBLISHABLE_KEY = "cd_pub_RELIABILITY_PLACEHOLDER_TO_BE_PROVISIONED";
387
- function isDiagnosticTelemetryEnabled() {
388
- return !DIAGNOSTIC_TELEMETRY_PUBLISHABLE_KEY.startsWith(
389
- "cd_pub_RELIABILITY_PLACEHOLDER"
390
- );
391
- }
392
- var DIAGNOSTIC_TELEMETRY_ALLOWED_KEYS = /* @__PURE__ */ new Set([
393
- "contract_id",
394
- "sdk_version",
395
- "sdk_platform",
396
- "failure_reason",
397
- "run_context",
398
- "run_id",
399
- "test_file",
400
- "test_name",
401
- "device_class"
402
- ]);
403
- function filterDiagnosticPayload(payload) {
404
- const filtered = {};
405
- for (const [k, v] of Object.entries(payload)) {
406
- if (DIAGNOSTIC_TELEMETRY_ALLOWED_KEYS.has(k) && typeof v === "string") {
407
- filtered[k] = v;
408
- }
409
- }
410
- return filtered;
411
- }
412
- function sendDiagnosticTelemetry(payload) {
413
- if (!isDiagnosticTelemetryEnabled()) return;
414
- const filtered = filterDiagnosticPayload(payload);
415
- if (Object.keys(filtered).length === 0) return;
416
- const body = JSON.stringify(filtered);
417
- let parsed;
418
- try {
419
- parsed = new URL(DIAGNOSTIC_TELEMETRY_ENDPOINT);
420
- } catch {
421
- return;
422
- }
423
- try {
424
- const req = https.request({
425
- method: "POST",
426
- hostname: parsed.hostname,
427
- port: parsed.port || 443,
428
- path: parsed.pathname + parsed.search,
429
- // Short timeout — reliability telemetry must never stall the
430
- // host server. A failed POST is acceptable; a hung POST is not.
431
- timeout: 5e3,
432
- headers: {
433
- "Content-Type": "application/json",
434
- "Content-Length": Buffer.byteLength(body, "utf8").toString(),
435
- Authorization: `Bearer ${DIAGNOSTIC_TELEMETRY_PUBLISHABLE_KEY}`,
436
- "Crossdeck-Sdk-Version": `${SDK_NAME}@${SDK_VERSION}`
437
- }
438
- });
439
- req.on("error", () => {
440
- });
441
- req.on("timeout", () => {
442
- try {
443
- req.destroy();
444
- } catch {
445
- }
446
- });
447
- req.on("response", (res) => {
448
- res.resume();
449
- });
450
- req.write(body);
451
- req.end();
452
- } catch {
453
- }
454
- }
455
-
456
370
  // src/http.ts
457
371
  var DEFAULT_BASE_URL = "https://api.cross-deck.com/v1";
458
372
  var DEFAULT_TIMEOUT_MS = 15e3;
@@ -2482,63 +2396,6 @@ var EntitlementCache = class {
2482
2396
  }
2483
2397
  };
2484
2398
 
2485
- // src/consent.ts
2486
- var EMAIL_PATTERN = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
2487
- var CARD_PATTERN = /\b\d(?:[ -]?\d){12,18}\b/g;
2488
- var REPLACEMENT_EMAIL = "<email>";
2489
- var REPLACEMENT_CARD = "<card>";
2490
- function scrubPii(value) {
2491
- if (!value) return value;
2492
- return value.replace(EMAIL_PATTERN, REPLACEMENT_EMAIL).replace(CARD_PATTERN, REPLACEMENT_CARD);
2493
- }
2494
- function scrubPiiFromProperties(properties) {
2495
- const out = {};
2496
- for (const k of Object.keys(properties)) {
2497
- out[k] = scrubValue(properties[k]);
2498
- }
2499
- return out;
2500
- }
2501
- function scrubValue(v) {
2502
- if (typeof v === "string") return scrubPii(v);
2503
- if (Array.isArray(v)) return v.map(scrubValue);
2504
- if (v && typeof v === "object" && v.constructor === Object) {
2505
- return scrubPiiFromProperties(v);
2506
- }
2507
- return v;
2508
- }
2509
-
2510
- // src/idempotency-key.ts
2511
- var import_node_crypto = require("crypto");
2512
- function formatAsUuid(hex) {
2513
- return [
2514
- hex.slice(0, 8),
2515
- hex.slice(8, 12),
2516
- hex.slice(12, 16),
2517
- hex.slice(16, 20),
2518
- hex.slice(20, 32)
2519
- ].join("-");
2520
- }
2521
- function sha256Hex(input) {
2522
- return (0, import_node_crypto.createHash)("sha256").update(input, "utf8").digest("hex");
2523
- }
2524
- function deriveIdempotencyKeyForPurchase(body) {
2525
- let identifier;
2526
- if (body.rail === "apple") {
2527
- identifier = body.signedTransactionInfo ?? "";
2528
- } else if (body.rail === "google") {
2529
- identifier = body.purchaseToken ?? "";
2530
- } else {
2531
- identifier = "";
2532
- }
2533
- if (!identifier) {
2534
- throw new Error(
2535
- `deriveIdempotencyKeyForPurchase: no stable identifier in body (rail=${body.rail}). Apple needs signedTransactionInfo; Google needs purchaseToken.`
2536
- );
2537
- }
2538
- const namespaced = `crossdeck:purchases/sync:${body.rail}:${identifier}`;
2539
- return formatAsUuid(sha256Hex(namespaced));
2540
- }
2541
-
2542
2399
  // src/debug.ts
2543
2400
  var SENSITIVE_KEY_PATTERNS = [
2544
2401
  /^email$/i,
@@ -2598,10 +2455,6 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
2598
2455
  baseUrl;
2599
2456
  appId;
2600
2457
  env;
2601
- /** PII scrubber toggle. Default true — parity with Web/RN/Swift.
2602
- * Pre-v1.4.0 the Node SDK shipped track() payloads UNREDACTED,
2603
- * a privacy contract drift versus the README. */
2604
- scrubPii;
2605
2458
  secretKeyPrefix;
2606
2459
  /**
2607
2460
  * Process-stable pseudo-anonymous ID. Used as the default identity
@@ -2647,15 +2500,6 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
2647
2500
  errorContext = {};
2648
2501
  errorTags = {};
2649
2502
  errorBeforeSend = null;
2650
- /**
2651
- * Dedup gate for `sdk.shutdown`. Both `shutdown()` (async) and
2652
- * `shutdownSync()` need to emit so direct callers of EITHER see
2653
- * the event (the async path's listener guarantees pre-launch
2654
- * tests, the sync path covers `Symbol.dispose` + tests that call
2655
- * `shutdownSync()` directly). Without this flag, `shutdown()`'s
2656
- * tail call into `shutdownSync()` would emit twice.
2657
- */
2658
- didEmitShutdown = false;
2659
2503
  constructor(options) {
2660
2504
  super();
2661
2505
  if (!options.secretKey || !options.secretKey.startsWith("cd_sk_")) {
@@ -2670,7 +2514,6 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
2670
2514
  this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
2671
2515
  this.env = inferEnvFromKey(options.secretKey);
2672
2516
  this.secretKeyPrefix = maskSecretKey(options.secretKey);
2673
- this.scrubPii = options.scrubPii !== false;
2674
2517
  this.http = new HttpClient({
2675
2518
  secretKey: options.secretKey,
2676
2519
  baseUrl: this.baseUrl,
@@ -2710,9 +2553,7 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
2710
2553
  this.eventQueue = new EventQueue({
2711
2554
  http: this.http,
2712
2555
  batchSize: options.eventFlushBatchSize ?? 20,
2713
- // v1.4.0 Phase 3.3 — flush interval default parity at 2000ms
2714
- // across every SDK. Per-instance override stays.
2715
- intervalMs: options.eventFlushIntervalMs ?? 2e3,
2556
+ intervalMs: options.eventFlushIntervalMs ?? 1500,
2716
2557
  envelope: () => ({
2717
2558
  appId: this.appId,
2718
2559
  // Ship env on every batch so the backend can cross-check
@@ -3091,34 +2932,6 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
3091
2932
  * `uncaughtException` has no per-request context; without the
3092
2933
  * auto-fill, the event would be rejected at queue enqueue.
3093
2934
  */
3094
- /**
3095
- * Emit `crossdeck.contract_failed` to the Crossdeck reliability
3096
- * endpoint — single-fire, one-way, never visible in the customer's
3097
- * dashboard. Goes over a dedicated HTTP path with the reliability
3098
- * publishable key embedded at build time; the customer's track()
3099
- * pipeline never carries `crossdeck.*` events. This is the
3100
- * independent-controller flow described in Privacy Policy §6
3101
- * ("Flow B"). The wire shape is fixed by the schema-lock contract
3102
- * at `contracts/diagnostics/contract-failed-payload-schema-lock.json`.
3103
- */
3104
- reportContractFailure(input) {
3105
- const payload = {
3106
- contract_id: input.contractId,
3107
- sdk_version: SDK_VERSION,
3108
- sdk_platform: "node",
3109
- failure_reason: input.failureReason,
3110
- run_context: input.runContext,
3111
- run_id: input.runId
3112
- };
3113
- if (input.testRef) {
3114
- payload.test_file = input.testRef.file;
3115
- payload.test_name = input.testRef.name;
3116
- }
3117
- if (input.deviceClass) {
3118
- payload.device_class = input.deviceClass;
3119
- }
3120
- sendDiagnosticTelemetry(payload);
3121
- }
3122
2935
  track(event) {
3123
2936
  if (!event.name) {
3124
2937
  throw new CrossdeckError({
@@ -3127,8 +2940,7 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
3127
2940
  message: "track(event) requires a non-empty event.name."
3128
2941
  });
3129
2942
  }
3130
- const validated = sanitizePropertyBag(event.properties, "event properties") ?? {};
3131
- const sanitized = this.scrubPii ? scrubPiiFromProperties(validated) : validated;
2943
+ const sanitized = sanitizePropertyBag(event.properties, "event properties") ?? {};
3132
2944
  if (this.debug.enabled) {
3133
2945
  const flagged = findSensitivePropertyKeys(sanitized);
3134
2946
  if (flagged.length > 0) {
@@ -3264,25 +3076,11 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
3264
3076
  });
3265
3077
  }
3266
3078
  const rail = input.rail ?? "apple";
3267
- const body = { ...input, rail };
3268
- const idempotencyKey = options?.idempotencyKey ?? deriveIdempotencyKeyForPurchase(body);
3269
- const result = await this.http.request("POST", "/purchases/sync", {
3270
- body,
3271
- idempotencyKey,
3079
+ return this.http.request("POST", "/purchases/sync", {
3080
+ body: { ...input, rail },
3272
3081
  signal: options?.signal,
3273
3082
  timeoutMs: options?.timeoutMs
3274
3083
  });
3275
- try {
3276
- const sourceProductId = result.entitlements[0]?.source.productId;
3277
- const sourceSubscriptionId = result.entitlements[0]?.source.subscriptionId;
3278
- const props = { rail };
3279
- if (sourceProductId) props.productId = sourceProductId;
3280
- if (sourceSubscriptionId) props.subscriptionId = sourceSubscriptionId;
3281
- if (result.idempotent_replay) props.idempotent_replay = true;
3282
- this.track({ name: "purchase.completed", properties: props });
3283
- } catch {
3284
- }
3285
- return result;
3286
3084
  }
3287
3085
  // ============================================================
3288
3086
  // Manual entitlement controls + audit — direct HTTP
@@ -3574,56 +3372,12 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
3574
3372
  };
3575
3373
  }
3576
3374
  /**
3577
- * Tear down handlers and clear in-memory state.
3578
- *
3579
- * **v1.4.0 bank-grade contract:** `shutdown()` AWAITS `flush()`
3580
- * before dropping the queue, so callers don't silently lose
3581
- * every queued event on a clean shutdown. The pre-v1.4.0
3582
- * behaviour (sync `eventQueue.reset()` with no flush) was the
3583
- * default for both `shutdown()` and `[Symbol.dispose]`; only
3584
- * `await using` + `[Symbol.asyncDispose]` flushed correctly.
3585
- *
3586
- * Production servers should still prefer `await server.flush()`
3587
- * (visible) followed by `server.shutdown()` so the flush
3588
- * outcome is observable — `shutdown()`'s internal flush swallows
3589
- * errors as a best-effort drain.
3590
- *
3591
- * Use [[shutdownSync]] only when the runtime cannot await
3592
- * (e.g. inside `Symbol.dispose` — see below).
3593
- */
3594
- async shutdown(reason = "shutdown") {
3595
- if (!this.didEmitShutdown) {
3596
- this.emit("sdk.shutdown", { reason });
3597
- this.didEmitShutdown = true;
3598
- }
3599
- try {
3600
- await this.flush();
3601
- } catch {
3602
- }
3603
- this.shutdownSync(reason);
3604
- }
3605
- /**
3606
- * Synchronous teardown — drops the in-memory queue WITHOUT
3607
- * flushing, then clears all in-memory state. Used by
3608
- * `[Symbol.dispose]` (which has no await) and tests that need
3609
- * an unconditional sync wipe. Production code should use
3610
- * [[shutdown]] (async) instead so queued events are flushed.
3611
- *
3612
- * A queue with items at sync-shutdown logs a warning recommending
3613
- * `[Symbol.asyncDispose]` or `await server.shutdown()` — silent
3614
- * loss is incompatible with the bank-grade contract.
3375
+ * Tear down handlers and clear in-memory state. Tests + custom
3376
+ * lifecycle callers only. Production code should rely on
3377
+ * `flush-on-exit` instead.
3615
3378
  */
3616
- shutdownSync(reason = "shutdown") {
3617
- if (!this.didEmitShutdown) {
3618
- this.emit("sdk.shutdown", { reason });
3619
- this.didEmitShutdown = true;
3620
- }
3621
- const queuedCount = this.eventQueue.getStats().buffered;
3622
- if (queuedCount > 0 && reason !== "asyncDispose") {
3623
- console.warn(
3624
- `[crossdeck] shutdownSync() dropped ${queuedCount} queued event(s) without flushing. Use \`await server.shutdown()\` or \`await using server = ...\` with \`[Symbol.asyncDispose]\` to drain the buffer before teardown.`
3625
- );
3626
- }
3379
+ shutdown(reason = "shutdown") {
3380
+ this.emit("sdk.shutdown", { reason });
3627
3381
  this.errorTracker?.uninstall();
3628
3382
  this.flushOnExit?.uninstall();
3629
3383
  this.eventQueue.reset();
@@ -3737,28 +3491,28 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
3737
3491
  * // ... use server ...
3738
3492
  * // at end of block, server[Symbol.dispose]() runs automatically
3739
3493
  *
3740
- * **`Symbol.dispose` is synchronous so it CANNOT await the queue
3741
- * flush.** A queue with pending events at sync-dispose time will
3742
- * be DROPPED `shutdownSync` warns to the console when this
3743
- * happens. For the common case of "drain the queue before
3744
- * exit", switch to `await using` + `[Symbol.asyncDispose]` (or
3745
- * call `await server.shutdown()` explicitly before the variable
3746
- * goes out of scope).
3494
+ * `Symbol.dispose` is synchronous so we can't await `flush()` here
3495
+ * for that, use `await using` + `[Symbol.asyncDispose]()`. This
3496
+ * sync variant just calls `shutdown()` (handler cleanup +
3497
+ * in-memory state wipe).
3747
3498
  */
3748
3499
  [Symbol.dispose]() {
3749
- this.shutdownSync("dispose");
3500
+ this.shutdown("dispose");
3750
3501
  }
3751
3502
  /**
3752
3503
  * Async disposal hook — runs when an `await using` declaration
3753
- * exits scope. Awaits the bank-grade `shutdown()` which flushes
3754
- * the queue THEN tears down. Use this variant for any code path
3755
- * that owns queued events at exit (serverless handlers,
3756
- * background workers, end-of-request hooks).
3504
+ * exits scope. Awaits `flush()` THEN runs `shutdown()`. Use this
3505
+ * variant when the caller needs the queue drained before exit
3506
+ * (the common case for serverless handlers).
3757
3507
  *
3758
3508
  * await using server = new CrossdeckServer({ ... });
3759
3509
  */
3760
3510
  async [Symbol.asyncDispose]() {
3761
- await this.shutdown("asyncDispose");
3511
+ try {
3512
+ await this.flush();
3513
+ } catch {
3514
+ }
3515
+ this.shutdown("asyncDispose");
3762
3516
  }
3763
3517
  // ============================================================
3764
3518
  reportCapturedError(captured) {
@@ -4178,43 +3932,18 @@ var _CROSSDECK_ERROR_CODES = Object.freeze([
4178
3932
  retryable: false
4179
3933
  },
4180
3934
  // ----- Webhook verification (Node-specific) -----
4181
- // v1.4.0 Phase 7.2 — distinguishable codes. Pre-v1.4.0 the
4182
- // helper used webhook_invalid_signature for nearly every failure
4183
- // mode so a customer couldn't separate replay-attack signals
4184
- // from wrong-secret signals in alerting.
4185
3935
  {
4186
- code: "webhook_signature_mismatch",
4187
- type: "authentication_error",
4188
- description: "Webhook HMAC didn't verify against any configured secret (wrong-secret / stale rotation signal).",
4189
- resolution: "Confirm the secret matches dashboard \u2192 Webhooks. If you rotated, include both the old and new secret as an array until receivers cut over.",
4190
- retryable: false
4191
- },
4192
- {
4193
- code: "webhook_timestamp_outside_tolerance",
4194
- type: "authentication_error",
4195
- description: "Webhook timestamp drift exceeds the configured replay-tolerance window (default 5 minutes; replay-attack signal).",
4196
- resolution: "Verify NTP on the receiving host. A spike on this code warrants its own alert separate from signature_mismatch \u2014 replay attacks look like this.",
4197
- retryable: false
4198
- },
4199
- {
4200
- code: "webhook_timestamp_missing",
3936
+ code: "webhook_invalid_signature",
4201
3937
  type: "authentication_error",
4202
- description: "Webhook signature header is absent or has no `t=` timestamp segment \u2014 the timestamp gate cannot be verified.",
4203
- resolution: "Confirm the request actually came from Crossdeck (signature headers are always present on real deliveries). A missing header is either a misconfigured intermediary or a forged request.",
3938
+ description: "The webhook signature header did not verify against the supplied secret.",
3939
+ resolution: "Confirm the secret matches the one in your Crossdeck dashboard \u2192 Webhooks page. If the request is genuinely from Crossdeck, the secret is wrong, stale, or recently rotated.",
4204
3940
  retryable: false
4205
3941
  },
4206
3942
  {
4207
- code: "webhook_payload_not_json",
3943
+ code: "webhook_replay_window_exceeded",
4208
3944
  type: "authentication_error",
4209
- description: "Webhook signature verified but the body isn't valid JSON \u2014 payload tampered post-signing or source bug.",
4210
- resolution: "Inspect the raw payload. If it's not JSON, either the request was modified in transit or the sender has a bug \u2014 file a support ticket with the raw body.",
4211
- retryable: false
4212
- },
4213
- {
4214
- code: "webhook_invalid_tolerance",
4215
- type: "configuration_error",
4216
- description: "verifyWebhookSignature() called with a non-finite / negative / above-24h-cap replayToleranceMs (would silently disable replay protection).",
4217
- resolution: "Pass a finite number between 0 and 86_400_000ms (24h). Default (5 minutes) is correct for almost every scenario. Pre-v1.4.0 accepted Infinity/NaN and silently dropped the check.",
3945
+ description: "The webhook timestamp is older than the replay-tolerance window (default 5 minutes).",
3946
+ resolution: "The webhook is either replayed or your receiving clock is wildly skewed. Verify NTP on the receiving host. Increase replayToleranceMs only if you accept the replay-attack risk.",
4218
3947
  retryable: false
4219
3948
  },
4220
3949
  {
@@ -4223,101 +3952,6 @@ var _CROSSDECK_ERROR_CODES = Object.freeze([
4223
3952
  description: "verifyWebhookSignature() was called without a signing secret.",
4224
3953
  resolution: "Pass the secret from your Crossdeck dashboard \u2192 Webhooks page. Never hardcode in source \u2014 read from an env var.",
4225
3954
  retryable: false
4226
- },
4227
- {
4228
- code: "webhook_invalid_signature",
4229
- type: "authentication_error",
4230
- description: "DEPRECATED in v1.4.0 \u2014 split into webhook_signature_mismatch / webhook_timestamp_missing / webhook_timestamp_outside_tolerance / webhook_payload_not_json for alerting clarity.",
4231
- resolution: "Migrate alert rules to the more specific v1.4.0 codes \u2014 they distinguish replay-attack signals from wrong-secret signals.",
4232
- retryable: false
4233
- },
4234
- {
4235
- code: "webhook_replay_window_exceeded",
4236
- type: "authentication_error",
4237
- description: "DEPRECATED in v1.4.0 \u2014 renamed to webhook_timestamp_outside_tolerance.",
4238
- resolution: "Update alerts to webhook_timestamp_outside_tolerance.",
4239
- retryable: false
4240
- },
4241
- // ----- Backend-emitted codes (v1.4.0 Phase 6.2 backfill) -----
4242
- // Mirror of backend/src/api/v1-errors.ts ApiErrorCode. Same set
4243
- // as the Web SDK ships — keep these synchronised so a developer
4244
- // hitting any code via either SDK gets the same remediation.
4245
- {
4246
- code: "missing_api_key",
4247
- type: "authentication_error",
4248
- description: "No Authorization header (or Crossdeck-Api-Key header) on the request.",
4249
- resolution: "Confirm the CrossdeckServer was constructed with a cd_sk_\u2026 secretKey. Re-check env vars in production deployments.",
4250
- retryable: false
4251
- },
4252
- {
4253
- code: "invalid_api_key",
4254
- type: "authentication_error",
4255
- description: "The secret key is malformed, unknown, or doesn't resolve to a project.",
4256
- resolution: "Copy the key from Crossdeck dashboard \u2192 API keys. Server SDK requires cd_sk_test_ / cd_sk_live_ \u2014 client SDK keys (cd_pub_\u2026) won't work on the Node SDK.",
4257
- retryable: false
4258
- },
4259
- {
4260
- code: "key_revoked",
4261
- type: "authentication_error",
4262
- description: "The secret key was revoked in the dashboard.",
4263
- resolution: "Mint a fresh key in dashboard \u2192 API keys \u2192 Create new. The revoked key cannot be reactivated.",
4264
- retryable: false
4265
- },
4266
- {
4267
- code: "env_mismatch",
4268
- type: "permission_error",
4269
- description: "The key's env prefix doesn't match the resolved app's configured env.",
4270
- resolution: "Use a cd_sk_live_ key with a production app, cd_sk_test_ with a sandbox app. Crossing breaks the env lock.",
4271
- retryable: false
4272
- },
4273
- {
4274
- code: "idempotency_key_in_use",
4275
- type: "invalid_request_error",
4276
- description: "An Idempotency-Key was reused for a request with a different body (Stripe-grade contract).",
4277
- resolution: "Server SDK derives keys deterministically from the body since v1.4.0; this should only fire if you passed options.idempotencyKey explicitly. Use a fresh key per logical operation.",
4278
- retryable: false
4279
- },
4280
- {
4281
- code: "rate_limited",
4282
- type: "rate_limit_error",
4283
- description: "Request rate exceeded the project's per-second cap.",
4284
- resolution: "Honour Retry-After (managed retries do this automatically). For custom paths, throttle to <100 req/s/key.",
4285
- retryable: true
4286
- },
4287
- {
4288
- code: "internal_error",
4289
- type: "internal_error",
4290
- description: "Server-side issue. Safe to retry with backoff.",
4291
- resolution: "Managed retries handle this automatically. If a code path surfaces it to your code, contact support with the requestId.",
4292
- retryable: true
4293
- },
4294
- {
4295
- code: "google_not_supported",
4296
- type: "invalid_request_error",
4297
- description: "POST /purchases/sync with rail=google is gated until the Play Developer API reconciliation worker ships.",
4298
- resolution: "Until v1.5+, Google Play purchases verify via Real-time Developer Notifications. The Android SDK auto-track path handles this transparently.",
4299
- retryable: false
4300
- },
4301
- {
4302
- code: "stripe_not_supported",
4303
- type: "invalid_request_error",
4304
- description: "POST /purchases/sync with rail=stripe is unsupported \u2014 Stripe webhooks deliver evidence server-side.",
4305
- resolution: "Wire Stripe via the standard Checkout / Customer Portal flow; Crossdeck reconciles via the platform webhook automatically.",
4306
- retryable: false
4307
- },
4308
- {
4309
- code: "missing_required_param",
4310
- type: "invalid_request_error",
4311
- description: "A required field is absent from the request body.",
4312
- resolution: "The error.message identifies the missing field. Refer to the SDK's TypeScript types for canonical shapes.",
4313
- retryable: false
4314
- },
4315
- {
4316
- code: "invalid_param_value",
4317
- type: "invalid_request_error",
4318
- description: "A field is present but the value failed validation.",
4319
- resolution: "Read error.message for the field + reason. SDK-managed call sites should never emit this \u2014 file a bug if you do.",
4320
- retryable: false
4321
3955
  }
4322
3956
  ]);
4323
3957
  function isCrossdeckErrorCode(code) {
@@ -4329,9 +3963,8 @@ function getErrorCode(code) {
4329
3963
  }
4330
3964
 
4331
3965
  // src/webhooks.ts
4332
- var import_node_crypto2 = require("crypto");
3966
+ var import_node_crypto = require("crypto");
4333
3967
  var DEFAULT_REPLAY_TOLERANCE_MS = 5 * 60 * 1e3;
4334
- var MAX_REPLAY_TOLERANCE_MS = 24 * 60 * 60 * 1e3;
4335
3968
  function verifyWebhookSignature(payload, signatureHeader, secret, options = {}) {
4336
3969
  const secrets = normaliseSecrets(secret);
4337
3970
  if (secrets.length === 0) {
@@ -4341,68 +3974,46 @@ function verifyWebhookSignature(payload, signatureHeader, secret, options = {})
4341
3974
  message: "verifyWebhookSignature requires a non-empty secret. Read it from process.env.CROSSDECK_WEBHOOK_SECRET \u2014 never hardcode in source."
4342
3975
  });
4343
3976
  }
4344
- const requestedTolerance = options.replayToleranceMs;
4345
- let tolerance;
4346
- if (requestedTolerance === void 0) {
4347
- tolerance = DEFAULT_REPLAY_TOLERANCE_MS;
4348
- } else if (typeof requestedTolerance !== "number" || !Number.isFinite(requestedTolerance)) {
4349
- throw new CrossdeckError({
4350
- type: "configuration_error",
4351
- code: "webhook_invalid_tolerance",
4352
- message: `replayToleranceMs must be a finite non-negative number \u2264 ${MAX_REPLAY_TOLERANCE_MS} (24h). Got: ${String(requestedTolerance)}. Pre-v1.4.0 accepted Infinity/NaN/null and silently disabled replay protection \u2014 v1.4.0 rejects loudly.`
4353
- });
4354
- } else if (requestedTolerance < 0) {
4355
- throw new CrossdeckError({
4356
- type: "configuration_error",
4357
- code: "webhook_invalid_tolerance",
4358
- message: `replayToleranceMs must be \u2265 0. Got ${requestedTolerance}.`
4359
- });
4360
- } else if (requestedTolerance > MAX_REPLAY_TOLERANCE_MS) {
4361
- throw new CrossdeckError({
4362
- type: "configuration_error",
4363
- code: "webhook_invalid_tolerance",
4364
- message: `replayToleranceMs must not exceed ${MAX_REPLAY_TOLERANCE_MS}ms (24h). Got ${requestedTolerance}ms \u2014 a window that wide defeats replay protection.`
4365
- });
4366
- } else {
4367
- tolerance = requestedTolerance;
4368
- }
4369
3977
  const header = normaliseHeader(signatureHeader);
4370
3978
  const parsed = parseSignatureHeader(header);
4371
3979
  if (!parsed) {
4372
3980
  throw new CrossdeckError({
4373
3981
  type: "authentication_error",
4374
- code: "webhook_timestamp_missing",
4375
- message: "Webhook signature header is missing, malformed, or has no `t=` timestamp segment. Expected 'Crossdeck-Signature: t=<unix>,v1=<hex>'."
3982
+ code: "webhook_invalid_signature",
3983
+ message: "Webhook signature header is missing or malformed. Expected 'Crossdeck-Signature: t=<unix>,v1=<hex>'."
4376
3984
  });
4377
3985
  }
4378
- const now = (options.now ?? Date.now)();
4379
- const timestampMs = parsed.timestampSec * 1e3;
4380
- const drift = Math.abs(now - timestampMs);
4381
- if (drift > tolerance) {
4382
- throw new CrossdeckError({
4383
- type: "authentication_error",
4384
- code: "webhook_timestamp_outside_tolerance",
4385
- message: `Webhook timestamp is ${drift}ms outside the ${tolerance}ms replay-tolerance window. Either the request is replayed or the receiving clock is skewed \u2014 verify NTP on the host.`
4386
- });
3986
+ const tolerance = options.replayToleranceMs ?? DEFAULT_REPLAY_TOLERANCE_MS;
3987
+ if (tolerance > 0) {
3988
+ const now = (options.now ?? Date.now)();
3989
+ const timestampMs = parsed.timestampSec * 1e3;
3990
+ const drift = Math.abs(now - timestampMs);
3991
+ if (drift > tolerance) {
3992
+ throw new CrossdeckError({
3993
+ type: "authentication_error",
3994
+ code: "webhook_replay_window_exceeded",
3995
+ message: `Webhook timestamp is ${drift}ms outside the ${tolerance}ms replay-tolerance window. Either the request is replayed or the receiving clock is skewed \u2014 verify NTP on the host.`
3996
+ });
3997
+ }
4387
3998
  }
4388
3999
  const signedPayload = `${parsed.timestampSec}.${payload}`;
4389
4000
  const expectedBuf = Buffer.from(parsed.signature, "hex");
4390
4001
  if (expectedBuf.length === 0) {
4391
4002
  throw new CrossdeckError({
4392
4003
  type: "authentication_error",
4393
- code: "webhook_signature_mismatch",
4004
+ code: "webhook_invalid_signature",
4394
4005
  message: "Webhook signature is not a valid hex string."
4395
4006
  });
4396
4007
  }
4397
4008
  const anyMatch = secrets.some((s) => {
4398
- const computed = (0, import_node_crypto2.createHmac)("sha256", s).update(signedPayload).digest();
4399
- return computed.length === expectedBuf.length && (0, import_node_crypto2.timingSafeEqual)(computed, expectedBuf);
4009
+ const computed = (0, import_node_crypto.createHmac)("sha256", s).update(signedPayload).digest();
4010
+ return computed.length === expectedBuf.length && (0, import_node_crypto.timingSafeEqual)(computed, expectedBuf);
4400
4011
  });
4401
4012
  if (!anyMatch) {
4402
4013
  throw new CrossdeckError({
4403
4014
  type: "authentication_error",
4404
- code: "webhook_signature_mismatch",
4405
- message: "Webhook signature did not verify against any configured secret. Confirm the secret matches your Crossdeck dashboard \u2192 Webhooks page (and that you're not on a stale rotation)."
4015
+ code: "webhook_invalid_signature",
4016
+ message: "Webhook signature did not verify. Confirm the secret matches your Crossdeck dashboard \u2192 Webhooks page (and that you're not on a stale rotation)."
4406
4017
  });
4407
4018
  }
4408
4019
  try {
@@ -4410,13 +4021,13 @@ function verifyWebhookSignature(payload, signatureHeader, secret, options = {})
4410
4021
  } catch {
4411
4022
  throw new CrossdeckError({
4412
4023
  type: "authentication_error",
4413
- code: "webhook_payload_not_json",
4024
+ code: "webhook_invalid_signature",
4414
4025
  message: "Webhook signature verified but the payload is not valid JSON. Either the payload was tampered with after signing, or the webhook source is misconfigured."
4415
4026
  });
4416
4027
  }
4417
4028
  }
4418
4029
  function signWebhookPayload(payload, secret, timestampSec) {
4419
- return (0, import_node_crypto2.createHmac)("sha256", secret).update(`${timestampSec}.${payload}`).digest("hex");
4030
+ return (0, import_node_crypto.createHmac)("sha256", secret).update(`${timestampSec}.${payload}`).digest("hex");
4420
4031
  }
4421
4032
  function parseSignatureHeader(header) {
4422
4033
  if (!header) return null;
@@ -4448,594 +4059,36 @@ function normaliseSecrets(input) {
4448
4059
  return arr.filter((s) => typeof s === "string" && s.length > 0);
4449
4060
  }
4450
4061
 
4451
- // src/_contracts-bundled.ts
4452
- var BUNDLED_IN = "@cross-deck/node@1.5.1";
4453
- var SDK_VERSION2 = "1.5.1";
4454
- var BUNDLED_CONTRACTS = Object.freeze([
4455
- {
4456
- "id": "contract-failed-payload-schema-lock",
4457
- "pillar": "diagnostics",
4458
- "status": "enforced",
4459
- "claim": "The `crossdeck.contract_failed` event payload contains ONLY the named diagnostic fields and never any end-user personal data. The wire shape is fixed \u2014 adding a new field requires (1) a pull request that updates this contract's `allowedFields` set, (2) a Privacy Policy \xA76 amendment, and (3) the Customer Disclosure Template / SDK Data Collection Reference \xA7B updates. Per-SDK assertion tests enforce the field set on every release. The `verification_phase` field is a categorical bucket \u2014 values are restricted to `boot` (the SDK self-test ran on Crossdeck.start) or `hot_path` (a verifier observed a real customer-triggered operation). The categorical nature is what preserves the diagnostic-only-not-personal classification. This is the structural guarantee that backs the independent-controller lawful basis in the Privacy Policy: the payload remains diagnostic-only, not personal, so the legitimate-interest analysis stays valid as the SDK evolves.",
4460
- "appliesTo": [
4461
- "web",
4462
- "node",
4463
- "swift",
4464
- "android",
4465
- "react-native"
4466
- ],
4467
- "allowedFields": {
4468
- "required": [
4469
- "contract_id",
4470
- "sdk_version",
4471
- "sdk_platform",
4472
- "failure_reason",
4473
- "run_context",
4474
- "run_id"
4475
- ],
4476
- "optional": [
4477
- "test_file",
4478
- "test_name",
4479
- "device_class",
4480
- "verification_phase"
4481
- ],
4482
- "forbidden": [
4483
- "anonymousId",
4484
- "developerUserId",
4485
- "crossdeckCustomerId",
4486
- "email",
4487
- "ip",
4488
- "user_agent",
4489
- "message",
4490
- "stack",
4491
- "stack_trace",
4492
- "frames",
4493
- "exception_message",
4494
- "url",
4495
- "path",
4496
- "screen",
4497
- "title",
4498
- "label",
4499
- "text",
4500
- "ariaLabel",
4501
- "accessibilityLabel",
4502
- "contentDescription",
4503
- "session_id",
4504
- "sessionId"
4505
- ]
4506
- },
4507
- "transport": "Telemetry is single-fire to the Crossdeck reliability endpoint only \u2014 NOT the customer's appId. The customer's track() pipeline never carries `crossdeck.*` events; the customer's dashboard never shows individual contract failures. Operational telemetry flows one-way to the Crossdeck operations team for SDK reliability purposes (legitimate interest, independent-controller flow per Privacy Policy \xA76). The reliability endpoint is hardcoded at SDK build time; the publishable key for the reliability project is embedded as a constant and rejects writes that don't match the schema.",
4508
- "codeRef": [
4509
- "sdks/web/src/crossdeck.ts",
4510
- "sdks/node/src/crossdeck-server.ts",
4511
- "sdks/swift/Sources/Crossdeck/Crossdeck.swift",
4512
- "sdks/swift/Sources/Crossdeck/_DiagnosticTelemetry.swift",
4513
- "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Crossdeck.kt",
4514
- "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/_DiagnosticTelemetry.kt",
4515
- "sdks/react-native/src/crossdeck.ts",
4516
- "backend/src/api/v1-sdk-diagnostic.ts",
4517
- "sdks/web/src/_diagnostic-telemetry.ts",
4518
- "sdks/node/src/_diagnostic-telemetry.ts",
4519
- "sdks/react-native/src/_diagnostic-telemetry.ts"
4520
- ],
4521
- "testRef": [
4522
- {
4523
- "file": "sdks/web/tests/contract-failed-schema-lock.test.ts",
4524
- "name": "reportContractFailure payload conforms to schema-lock"
4525
- },
4526
- {
4527
- "file": "sdks/node/tests/contract-failed-schema-lock.test.ts",
4528
- "name": "reportContractFailure payload conforms to schema-lock"
4529
- },
4530
- {
4531
- "file": "sdks/swift/Tests/CrossdeckTests/ContractFailedSchemaLockTests.swift",
4532
- "name": "test_reportContractFailure_payloadFieldsAreInAllowList"
4533
- },
4534
- {
4535
- "file": "sdks/swift/Tests/CrossdeckTests/ContractFailedSchemaLockTests.swift",
4536
- "name": "test_reportContractFailure_doesNotEnterCustomerTrackPipeline"
4537
- },
4538
- {
4539
- "file": "sdks/android/crossdeck/src/test/kotlin/com/crossdeck/ContractFailedSchemaLockTest.kt",
4540
- "name": "reportContractFailure payload conforms to schema-lock"
4541
- },
4542
- {
4543
- "file": "sdks/android/crossdeck/src/test/kotlin/com/crossdeck/ContractFailedSchemaLockTest.kt",
4544
- "name": "reportContractFailure does not enter customer track pipeline"
4545
- },
4546
- {
4547
- "file": "sdks/react-native/tests/contract-failed-schema-lock.test.ts",
4548
- "name": "reportContractFailure payload conforms to schema-lock"
4549
- },
4550
- {
4551
- "file": "backend/tests/unit/v1-sdk-diagnostic.test.ts",
4552
- "name": "forbidden fields are enumerated in the schema-lock contract"
4553
- },
4554
- {
4555
- "file": "backend/tests/unit/v1-sdk-diagnostic.test.ts",
4556
- "name": "required fields are enumerated in the schema-lock contract"
4557
- },
4558
- {
4559
- "file": "backend/tests/unit/v1-sdk-diagnostic.test.ts",
4560
- "name": "regression guard: never returns a raw IP"
4561
- },
4562
- {
4563
- "file": "backend/tests/unit/v1-sdk-diagnostic.test.ts",
4564
- "name": "verification_phase is in the optional field set"
4565
- }
4566
- ],
4567
- "registeredAt": "2026-05-27",
4568
- "firstRegisteredIn": "Diagnostic telemetry single-fire + schema-lock \u2014 independent-controller flow",
4569
- "privacyReferences": [
4570
- "legal/privacy/index.html#sdk-diagnostic",
4571
- "legal/customer-disclosure/index.html#flow-b",
4572
- "legal/security/index.html#diagnostic",
4573
- "legal/sdk-data/index.html#b-diagnostic"
4574
- ],
4575
- "bundledIn": "@cross-deck/node@1.5.1"
4576
- },
4577
- {
4578
- "id": "documentation-honesty",
4579
- "pillar": "webhooks",
4580
- "status": "enforced",
4581
- "claim": "Customer-facing documentation honestly tags outbound webhook delivery as ROADMAP (no signer, no worker, no scheduler in backend/src yet). The Node verifier helper exists today for fixture authoring + locking the validation contract surface BEFORE delivery ships \u2014 its jsdoc carries an explicit `[ROADMAP]` disclaimer so a developer reading the source doesn't assume Crossdeck sends webhooks today. The rail-webhooks doc no longer claims state surfaces 'through the dashboard, SDKs, and outbound webhooks' \u2014 outbound is gated to the explicit roadmap section.",
4582
- "appliesTo": [
4583
- "node",
4584
- "backend"
4585
- ],
4586
- "codeRef": [
4587
- "sdks/node/src/webhooks.ts",
4588
- "docs/rail-webhooks/index.html",
4589
- "docs/webhooks-receive/index.html"
4590
- ],
4591
- "testRef": [
4592
- {
4593
- "file": "sdks/node/src/webhooks.ts",
4594
- "name": "[ROADMAP \u2014 v1.4.0 honesty note]"
4595
- },
4596
- {
4597
- "file": "docs/rail-webhooks/index.html",
4598
- "name": "Outbound push-to-your-backend webhooks are <strong>roadmap</strong>"
4599
- },
4600
- {
4601
- "file": "docs/webhooks-receive/index.html",
4602
- "name": "This feature is on the roadmap"
4603
- }
4604
- ],
4605
- "registeredAt": "2026-05-26",
4606
- "firstRegisteredIn": "bank-grade reconciliation v1.4.0 \u2014 phase 7.1",
4607
- "bundledIn": "@cross-deck/node@1.5.1"
4608
- },
4609
- {
4610
- "id": "error-envelope-shape",
4611
- "pillar": "errors",
4612
- "status": "enforced",
4613
- "claim": "Every v1 REST endpoint returns errors in a Stripe-shape envelope: `{ error: { type, code, message, request_id } }` where `type` is one of authentication_error / permission_error / invalid_request_error / rate_limit_error / internal_error (the wire vocabulary in backend/src/api/v1-errors.ts ApiErrorType). HTTP status parity: invalid_request_error \u2192 400, authentication_error \u2192 401, permission_error \u2192 403, rate_limit_error \u2192 429, internal_error \u2192 500. SDK-side clients parse this shape via `crossdeckErrorFromResponse` (Web/Node/RN) / `crossdeckErrorFrom(response:)` (Swift) / `crossdeckErrorFromResponse` (Android) and surface the request_id verbatim so support traces are end-to-end joinable. Firebase callable endpoints (managed-keys / dashboard auth) use the Firebase HttpsError envelope instead \u2014 this contract applies to REST /v1/* only.",
4614
- "appliesTo": [
4615
- "web",
4616
- "node",
4617
- "react-native",
4618
- "swift",
4619
- "android",
4620
- "backend"
4621
- ],
4622
- "codeRef": [
4623
- "backend/src/api/v1-errors.ts",
4624
- "sdks/web/src/errors.ts",
4625
- "sdks/node/src/errors.ts",
4626
- "sdks/react-native/src/errors.ts",
4627
- "sdks/swift/Sources/Crossdeck/Errors.swift",
4628
- "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Errors.kt"
4629
- ],
4630
- "testRef": [
4631
- {
4632
- "file": "sdks/swift/Tests/CrossdeckTests/ErrorsTests.swift",
4633
- "name": "test_errorEnvelope_fallsBackOnGarbageBody"
4634
- },
4635
- {
4636
- "file": "sdks/swift/Tests/CrossdeckTests/ErrorsTests.swift",
4637
- "name": "test_errorEnvelope_reads_XRequestId_fallback"
4638
- },
4639
- {
4640
- "file": "sdks/android/crossdeck/src/test/kotlin/com/crossdeck/ErrorTypeWireVocabTest.kt",
4641
- "name": "backend 500 response parses to INTERNAL_ERROR"
4642
- }
4643
- ],
4644
- "registeredAt": "2026-05-26",
4645
- "firstRegisteredIn": "bank-grade reconciliation v1.4.0 \u2014 phase 8 (codifies existing contract)",
4646
- "bundledIn": "@cross-deck/node@1.5.1"
4647
- },
4648
- {
4649
- "id": "flush-interval-parity",
4650
- "pillar": "analytics",
4651
- "status": "enforced",
4652
- "claim": "Every Crossdeck SDK defaults its event-queue flush interval to 2000ms \u2014 the Stripe-adjacent industry norm. Pre-v1.4.0 the defaults disagreed (Web/Node 1500ms; RN/Swift/Android 5000ms), so cross-platform funnels saw events landing at different cadences. Per-instance override stays \u2014 call sites can still tune it freely.",
4653
- "appliesTo": [
4654
- "web",
4655
- "node",
4656
- "react-native",
4657
- "swift",
4658
- "android"
4659
- ],
4660
- "codeRef": [
4661
- "sdks/web/src/crossdeck.ts",
4662
- "sdks/node/src/crossdeck-server.ts",
4663
- "sdks/react-native/src/crossdeck.ts",
4664
- "sdks/swift/Sources/Crossdeck/EventQueue.swift",
4665
- "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/EventQueue.kt"
4666
- ],
4667
- "testRef": [
4668
- {
4669
- "file": "sdks/swift/Sources/Crossdeck/EventQueue.swift",
4670
- "name": "flushIntervalMs: Int = 2_000"
4671
- },
4672
- {
4673
- "file": "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/EventQueue.kt",
4674
- "name": "flushIntervalMs: Long = 2_000L"
4675
- },
4676
- {
4677
- "file": "sdks/web/src/crossdeck.ts",
4678
- "name": "options.eventFlushIntervalMs ?? 2000"
4679
- },
4680
- {
4681
- "file": "sdks/node/src/crossdeck-server.ts",
4682
- "name": "options.eventFlushIntervalMs ?? 2000"
4683
- },
4684
- {
4685
- "file": "sdks/react-native/src/crossdeck.ts",
4686
- "name": "options.eventFlushIntervalMs ?? 2000"
4687
- }
4688
- ],
4689
- "registeredAt": "2026-05-26",
4690
- "firstRegisteredIn": "bank-grade reconciliation v1.4.0 \u2014 phase 3.3",
4691
- "bundledIn": "@cross-deck/node@1.5.1"
4692
- },
4693
- {
4694
- "id": "idempotency-key-deterministic",
4695
- "pillar": "revenue",
4696
- "status": "enforced",
4697
- "claim": "syncPurchases() on every SDK derives a deterministic Idempotency-Key from the request body (UUID-shaped SHA-256 of `crossdeck:purchases/sync:<rail>:<jws|token>`). Same input -> same key. Backend short-circuits same-key-same-body retries by returning the cached response (status + body) with `idempotent_replay: true` flag in the body AND `Idempotent-Replayed: true` response header. Same-key-different-body returns 400 `idempotency_key_in_use`. 24-hour TTL matches Stripe. Cache only stores 2xx responses \u2014 4xx/5xx pass through so callers can fix bugs and retry. Helper returns nil/throws on missing identifier (no silent random fallback). Cross-SDK parity is CI-pinned: deriveForPurchase('apple', 'eyJ.jws.sig') MUST equal 'a66b1640-efaf-bb4d-1261-6650033bf111' on every SDK.",
4698
- "appliesTo": [
4699
- "web",
4700
- "node",
4701
- "react-native",
4702
- "swift",
4703
- "android",
4704
- "backend"
4705
- ],
4706
- "codeRef": [
4707
- "sdks/web/src/idempotency-key.ts",
4708
- "sdks/web/src/crossdeck.ts",
4709
- "sdks/react-native/src/idempotency-key.ts",
4710
- "sdks/react-native/src/crossdeck.ts",
4711
- "sdks/node/src/idempotency-key.ts",
4712
- "sdks/node/src/crossdeck-server.ts",
4713
- "sdks/swift/Sources/Crossdeck/IdempotencyKey.swift",
4714
- "sdks/swift/Sources/Crossdeck/Crossdeck.swift",
4715
- "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/IdempotencyKey.kt",
4716
- "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Crossdeck.kt",
4717
- "backend/src/lib/idempotency-response-cache.ts",
4718
- "backend/src/api/v1-purchases.ts"
4719
- ],
4720
- "testRef": [
4721
- {
4722
- "file": "sdks/web/tests/idempotency-key.test.ts",
4723
- "name": "cross-SDK oracle \u2014 apple JWS pins canonical vector"
4724
- },
4725
- {
4726
- "file": "sdks/web/tests/idempotency-key.test.ts",
4727
- "name": "is deterministic: same body twice -> identical key"
4728
- },
4729
- {
4730
- "file": "sdks/web/tests/idempotency-key.test.ts",
4731
- "name": "same identifier under different rails -> different keys"
4732
- },
4733
- {
4734
- "file": "sdks/web/tests/idempotency-key.test.ts",
4735
- "name": "never silently falls back to a random key on missing identifier"
4736
- },
4737
- {
4738
- "file": "sdks/react-native/tests/idempotency-key.test.ts",
4739
- "name": "is deterministic"
4740
- },
4741
- {
4742
- "file": "sdks/react-native/tests/idempotency-key.test.ts",
4743
- "name": "cross-SDK oracle \u2014 apple JWS pins canonical vector"
4744
- },
4745
- {
4746
- "file": "sdks/node/tests/idempotency-key.test.ts",
4747
- "name": "is deterministic"
4748
- },
4749
- {
4750
- "file": "sdks/node/tests/idempotency-key.test.ts",
4751
- "name": "rail namespacing prevents cross-rail collisions"
4752
- },
4753
- {
4754
- "file": "sdks/node/tests/idempotency-key.test.ts",
4755
- "name": "apple JWS produces the canonical pinned UUID across all 5 SDKs"
4756
- },
4757
- {
4758
- "file": "backend/tests/unit/idempotency-response-cache.test.ts",
4759
- "name": "is deterministic for the same input"
4760
- },
4761
- {
4762
- "file": "backend/tests/unit/idempotency-response-cache.test.ts",
4763
- "name": "injects idempotent_replay: true into a JSON object body"
4764
- },
4765
- {
4766
- "file": "backend/tests/unit/idempotency-response-cache.test.ts",
4767
- "name": "matches Stripe's 24-hour idempotency window"
4768
- },
4769
- {
4770
- "file": "sdks/swift/Tests/CrossdeckTests/IdempotencyKeyTests.swift",
4771
- "name": "test_crossSdkOracle_appleJWS"
4772
- },
4773
- {
4774
- "file": "sdks/swift/Tests/CrossdeckTests/IdempotencyKeyTests.swift",
4775
- "name": "test_railNamespacing_preventsCrossRailCollisions"
4776
- },
4777
- {
4778
- "file": "sdks/swift/Tests/CrossdeckTests/IdempotencyKeyTests.swift",
4779
- "name": "test_missingIdentifier_returnsNil"
4780
- },
4781
- {
4782
- "file": "sdks/android/crossdeck/src/test/kotlin/com/crossdeck/IdempotencyKeyTest.kt",
4783
- "name": "cross-SDK oracle for apple JWS"
4784
- },
4785
- {
4786
- "file": "sdks/android/crossdeck/src/test/kotlin/com/crossdeck/IdempotencyKeyTest.kt",
4787
- "name": "rail namespacing prevents cross-rail collisions"
4788
- },
4789
- {
4790
- "file": "sdks/android/crossdeck/src/test/kotlin/com/crossdeck/IdempotencyKeyTest.kt",
4791
- "name": "missing identifier returns null - never silent random fallback"
4792
- }
4793
- ],
4794
- "registeredAt": "2026-05-26",
4795
- "firstRegisteredIn": "bank-grade reconciliation v1.4.0 \u2014 phase 2.2.a + 2.2.b + 2.2.c",
4796
- "bundledIn": "@cross-deck/node@1.5.1"
4797
- },
4798
- {
4799
- "id": "node-pii-scrubber",
4800
- "pillar": "analytics",
4801
- "status": "enforced",
4802
- "claim": "Node SDK's track() applies scrubPiiFromProperties on the enqueue path \u2014 parity with Web/RN/Swift. Pre-v1.4.0 the Node SDK was the ONLY one that skipped this, shipping every track() payload UNREDACTED despite the README promising parity. CrossdeckServerOptions.scrubPii defaults to true; explicit false opts out for regulator-required audit trails with a documented blast-radius warning.",
4803
- "appliesTo": [
4804
- "node"
4805
- ],
4806
- "codeRef": [
4807
- "sdks/node/src/crossdeck-server.ts",
4808
- "sdks/node/src/types.ts",
4809
- "sdks/node/src/consent.ts"
4810
- ],
4811
- "testRef": [
4812
- {
4813
- "file": "sdks/node/tests/track-pii-scrub.test.ts",
4814
- "name": "by default redacts email-shaped values to <email>"
4815
- },
4816
- {
4817
- "file": "sdks/node/tests/track-pii-scrub.test.ts",
4818
- "name": "redacts card-number-shaped values to <card>"
4819
- },
4820
- {
4821
- "file": "sdks/node/tests/track-pii-scrub.test.ts",
4822
- "name": "walks nested maps + arrays"
4823
- },
4824
- {
4825
- "file": "sdks/node/tests/track-pii-scrub.test.ts",
4826
- "name": "scrubPii: false preserves the raw payload (opt-out)"
4827
- },
4828
- {
4829
- "file": "sdks/node/tests/track-pii-scrub.test.ts",
4830
- "name": "scrubPii: true is the default when option is omitted"
4831
- }
4832
- ],
4833
- "registeredAt": "2026-05-26",
4834
- "firstRegisteredIn": "bank-grade reconciliation v1.4.0 \u2014 phase 3.1",
4835
- "bundledIn": "@cross-deck/node@1.5.1"
4836
- },
4837
- {
4838
- "id": "node-shutdown-awaits-flush",
4839
- "pillar": "lifecycle",
4840
- "status": "enforced",
4841
- "claim": "Node SDK's async shutdown() awaits the internal flush() before tearing down the queue. A queue with pending events at sync-shutdown time (shutdownSync() or [Symbol.dispose]) logs a console.warn with the dropped-event count \u2014 silent loss is incompatible with the bank-grade contract. [Symbol.asyncDispose] is equivalent to await server.shutdown().",
4842
- "appliesTo": [
4843
- "node"
4844
- ],
4845
- "codeRef": [
4846
- "sdks/node/src/crossdeck-server.ts"
4847
- ],
4848
- "testRef": [
4849
- {
4850
- "file": "sdks/node/tests/shutdown-flush.test.ts",
4851
- "name": "async shutdown() flushes queued events before clearing"
4852
- },
4853
- {
4854
- "file": "sdks/node/tests/shutdown-flush.test.ts",
4855
- "name": "async shutdown() proceeds with teardown even if flush fails"
4856
- },
4857
- {
4858
- "file": "sdks/node/tests/shutdown-flush.test.ts",
4859
- "name": "sync shutdownSync() warns when the buffer has events at teardown"
4860
- },
4861
- {
4862
- "file": "sdks/node/tests/shutdown-flush.test.ts",
4863
- "name": "[Symbol.asyncDispose] equals await server.shutdown()"
4864
- }
4865
- ],
4866
- "registeredAt": "2026-05-26",
4867
- "firstRegisteredIn": "bank-grade reconciliation v1.4.0 \u2014 phase 5.4",
4868
- "bundledIn": "@cross-deck/node@1.5.1"
4869
- },
4870
- {
4871
- "id": "sdk-error-codes-catalogue",
4872
- "pillar": "errors",
4873
- "status": "enforced",
4874
- "claim": "Web + Node SDK error-codes catalogues include EVERY backend-emitted ApiErrorCode with a description + resolution. Pre-v1.4.0 the catalogues documented codes the SDK threw ITSELF but ZERO backend codes \u2014 a developer hitting `invalid_api_key` / `origin_not_allowed` / `bundle_id_not_allowed` / `env_mismatch` / `idempotency_key_in_use` etc. got `undefined` from getErrorCode() and had to hunt for guidance. v1.4.0 backfills the catalogue from backend/src/api/v1-errors.ts so every wire code has a canonical 'what does this mean / what should I do' answer Stripe-style.",
4875
- "appliesTo": [
4876
- "web",
4877
- "node"
4878
- ],
4879
- "codeRef": [
4880
- "sdks/web/src/error-codes.ts",
4881
- "sdks/node/src/error-codes.ts",
4882
- "backend/src/api/v1-errors.ts"
4883
- ],
4884
- "testRef": [
4885
- {
4886
- "file": "sdks/web/tests/error-codes-backfill.test.ts",
4887
- "name": "includes backend code"
4888
- },
4889
- {
4890
- "file": "sdks/web/tests/error-codes-backfill.test.ts",
4891
- "name": "invalid_api_key resolution points at the dashboard"
4892
- },
4893
- {
4894
- "file": "sdks/web/tests/error-codes-backfill.test.ts",
4895
- "name": "idempotency_key_in_use resolution mentions Stripe-grade contract"
4896
- },
4897
- {
4898
- "file": "sdks/web/tests/error-codes-backfill.test.ts",
4899
- "name": "identity-lock codes carry permission_error type"
4900
- },
4901
- {
4902
- "file": "sdks/web/tests/error-codes-backfill.test.ts",
4903
- "name": "no entry has an empty description or resolution"
4904
- }
4905
- ],
4906
- "registeredAt": "2026-05-26",
4907
- "firstRegisteredIn": "bank-grade reconciliation v1.4.0 \u2014 phase 6.2",
4908
- "bundledIn": "@cross-deck/node@1.5.1"
4909
- },
4910
- {
4911
- "id": "sync-purchases-funnel-parity",
4912
- "pillar": "analytics",
4913
- "status": "enforced",
4914
- "claim": "Manual syncPurchases() emits a `purchase.completed` analytics event on success across ALL SDKs (Web / Node / RN / Swift / Android). Pre-v1.4.0 only Swift/Android auto-track emitted it \u2014 Web/Node/RN manual calls + Swift/Android manual calls fired ZERO analytics. Schema mirrors the auto-track event name + rail/productId/subscriptionId so cross-platform funnels reconcile on every payment path. When the backend short-circuits via the v1.4.0 idempotency cache, the event also carries `idempotent_replay: true`.",
4915
- "appliesTo": [
4916
- "web",
4917
- "node",
4918
- "react-native",
4919
- "swift",
4920
- "android"
4921
- ],
4922
- "codeRef": [
4923
- "sdks/web/src/crossdeck.ts",
4924
- "sdks/node/src/crossdeck-server.ts",
4925
- "sdks/react-native/src/crossdeck.ts",
4926
- "sdks/swift/Sources/Crossdeck/Crossdeck.swift",
4927
- "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Crossdeck.kt"
4928
- ],
4929
- "testRef": [
4930
- {
4931
- "file": "sdks/web/tests/sync-purchases-funnel.test.ts",
4932
- "name": "emits purchase.completed after a successful sync"
4933
- },
4934
- {
4935
- "file": "sdks/web/tests/sync-purchases-funnel.test.ts",
4936
- "name": "carries idempotent_replay=true when backend replied from cache"
4937
- }
4938
- ],
4939
- "registeredAt": "2026-05-26",
4940
- "firstRegisteredIn": "bank-grade reconciliation v1.4.0 \u2014 phase 3.5",
4941
- "bundledIn": "@cross-deck/node@1.5.1"
4942
- },
4943
- {
4944
- "id": "verifier-timestamp-mandatory",
4945
- "pillar": "webhooks",
4946
- "status": "enforced",
4947
- "claim": "Node verifyWebhookSignature() enforces a MANDATORY timestamp window. Pre-v1.4.0 the helper silently disabled replay protection on tolerance=0 (`if (tolerance > 0)` skipped the check) and on Infinity/NaN/null (`Math.abs(...) > Infinity = false`). v1.4.0 rejects non-finite / negative / above-24h-cap tolerances at the boundary with typed `webhook_invalid_tolerance` and always runs the drift check. Verification failures are surfaced via distinguishable codes: `webhook_signature_mismatch` (wrong-secret signal), `webhook_timestamp_outside_tolerance` (replay-attack signal \u2014 alert separately), `webhook_timestamp_missing` (header absent/malformed), `webhook_payload_not_json` (tampered post-signing), `webhook_missing_secret`, `webhook_invalid_tolerance` \u2014 replaces the pre-1.4.0 single `webhook_invalid_signature` catch-all.",
4948
- "appliesTo": [
4949
- "node"
4950
- ],
4951
- "codeRef": [
4952
- "sdks/node/src/webhooks.ts",
4953
- "sdks/node/src/error-codes.ts"
4954
- ],
4955
- "testRef": [
4956
- {
4957
- "file": "sdks/node/tests/webhooks.test.ts",
4958
- "name": "tolerance of 0 still enforces the replay window (v1.4.0 \u2014 cannot disable)"
4959
- },
4960
- {
4961
- "file": "sdks/node/tests/webhooks.test.ts",
4962
- "name": "rejects Infinity tolerance (would silently disable replay protection)"
4963
- },
4964
- {
4965
- "file": "sdks/node/tests/webhooks.test.ts",
4966
- "name": "rejects NaN tolerance"
4967
- },
4968
- {
4969
- "file": "sdks/node/tests/webhooks.test.ts",
4970
- "name": "rejects negative tolerance"
4971
- },
4972
- {
4973
- "file": "sdks/node/tests/webhooks.test.ts",
4974
- "name": "rejects tolerance above the 24h cap"
4975
- },
4976
- {
4977
- "file": "sdks/node/tests/webhooks.test.ts",
4978
- "name": "rejects non-number tolerance (null / string)"
4979
- },
4980
- {
4981
- "file": "sdks/node/tests/webhooks.test.ts",
4982
- "name": "accepts tolerance exactly at the 24h cap"
4983
- },
4984
- {
4985
- "file": "sdks/node/tests/webhooks.test.ts",
4986
- "name": "malformed header (no t= or no v1=) throws webhook_timestamp_missing"
4987
- },
4988
- {
4989
- "file": "sdks/node/tests/webhooks.test.ts",
4990
- "name": "valid signature but non-JSON payload throws webhook_payload_not_json"
4991
- }
4992
- ],
4993
- "registeredAt": "2026-05-26",
4994
- "firstRegisteredIn": "bank-grade reconciliation v1.4.0 \u2014 phase 7.2",
4995
- "bundledIn": "@cross-deck/node@1.5.1"
4062
+ // src/consent.ts
4063
+ var EMAIL_PATTERN = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
4064
+ var CARD_PATTERN = /\b\d(?:[ -]?\d){12,18}\b/g;
4065
+ var REPLACEMENT_EMAIL = "<email>";
4066
+ var REPLACEMENT_CARD = "<card>";
4067
+ function scrubPii(value) {
4068
+ if (!value) return value;
4069
+ return value.replace(EMAIL_PATTERN, REPLACEMENT_EMAIL).replace(CARD_PATTERN, REPLACEMENT_CARD);
4070
+ }
4071
+ function scrubPiiFromProperties(properties) {
4072
+ const out = {};
4073
+ for (const k of Object.keys(properties)) {
4074
+ out[k] = scrubValue(properties[k]);
4996
4075
  }
4997
- ]);
4998
-
4999
- // src/contracts.ts
5000
- var CrossdeckContracts = {
5001
- all() {
5002
- return BUNDLED_CONTRACTS.filter((c) => c.status === "enforced");
5003
- },
5004
- allIncludingHistorical() {
5005
- return BUNDLED_CONTRACTS;
5006
- },
5007
- byId(id) {
5008
- return BUNDLED_CONTRACTS.find((c) => c.id === id);
5009
- },
5010
- byPillar(pillar) {
5011
- return BUNDLED_CONTRACTS.filter(
5012
- (c) => c.pillar === pillar && c.status === "enforced"
5013
- );
5014
- },
5015
- withStatus(status) {
5016
- return BUNDLED_CONTRACTS.filter((c) => c.status === status);
5017
- },
5018
- sdkVersion: SDK_VERSION2,
5019
- bundledIn: BUNDLED_IN,
5020
- /**
5021
- * Resolve a failing test back to the contract it exercises.
5022
- * Used by test-framework hooks to find the contract id of a
5023
- * failed contract test so `reportContractFailure(...)` can stamp
5024
- * the right `contract_id` on the emitted event.
5025
- */
5026
- findByTestName(name) {
5027
- return BUNDLED_CONTRACTS.find(
5028
- (c) => c.testRef.some((ref) => ref.name === name)
5029
- );
4076
+ return out;
4077
+ }
4078
+ function scrubValue(v) {
4079
+ if (typeof v === "string") return scrubPii(v);
4080
+ if (Array.isArray(v)) return v.map(scrubValue);
4081
+ if (v && typeof v === "object" && v.constructor === Object) {
4082
+ return scrubPiiFromProperties(v);
5030
4083
  }
5031
- };
4084
+ return v;
4085
+ }
5032
4086
  // Annotate the CommonJS export names for ESM import in node:
5033
4087
  0 && (module.exports = {
5034
4088
  CROSSDECK_API_VERSION,
5035
4089
  CROSSDECK_ERROR_CODES,
5036
4090
  CrossdeckAuthenticationError,
5037
4091
  CrossdeckConfigurationError,
5038
- CrossdeckContracts,
5039
4092
  CrossdeckError,
5040
4093
  CrossdeckInternalError,
5041
4094
  CrossdeckNetworkError,