@cross-deck/node 1.3.1 → 1.5.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.
package/dist/index.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
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
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
@@ -24,6 +34,7 @@ __export(index_exports, {
24
34
  CROSSDECK_ERROR_CODES: () => CROSSDECK_ERROR_CODES,
25
35
  CrossdeckAuthenticationError: () => CrossdeckAuthenticationError,
26
36
  CrossdeckConfigurationError: () => CrossdeckConfigurationError,
37
+ CrossdeckContracts: () => CrossdeckContracts,
27
38
  CrossdeckError: () => CrossdeckError,
28
39
  CrossdeckInternalError: () => CrossdeckInternalError,
29
40
  CrossdeckNetworkError: () => CrossdeckNetworkError,
@@ -363,10 +374,85 @@ function byteLength(s) {
363
374
  return s.length * 4;
364
375
  }
365
376
 
377
+ // src/_diagnostic-telemetry.ts
378
+ var https = __toESM(require("https"));
379
+
366
380
  // src/_version.ts
367
- var SDK_VERSION = "1.3.1";
381
+ var SDK_VERSION = "1.5.1";
368
382
  var SDK_NAME = "@cross-deck/node";
369
383
 
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
+
370
456
  // src/http.ts
371
457
  var DEFAULT_BASE_URL = "https://api.cross-deck.com/v1";
372
458
  var DEFAULT_TIMEOUT_MS = 15e3;
@@ -2396,6 +2482,63 @@ var EntitlementCache = class {
2396
2482
  }
2397
2483
  };
2398
2484
 
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
+
2399
2542
  // src/debug.ts
2400
2543
  var SENSITIVE_KEY_PATTERNS = [
2401
2544
  /^email$/i,
@@ -2455,6 +2598,10 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
2455
2598
  baseUrl;
2456
2599
  appId;
2457
2600
  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;
2458
2605
  secretKeyPrefix;
2459
2606
  /**
2460
2607
  * Process-stable pseudo-anonymous ID. Used as the default identity
@@ -2500,6 +2647,15 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
2500
2647
  errorContext = {};
2501
2648
  errorTags = {};
2502
2649
  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;
2503
2659
  constructor(options) {
2504
2660
  super();
2505
2661
  if (!options.secretKey || !options.secretKey.startsWith("cd_sk_")) {
@@ -2514,6 +2670,7 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
2514
2670
  this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
2515
2671
  this.env = inferEnvFromKey(options.secretKey);
2516
2672
  this.secretKeyPrefix = maskSecretKey(options.secretKey);
2673
+ this.scrubPii = options.scrubPii !== false;
2517
2674
  this.http = new HttpClient({
2518
2675
  secretKey: options.secretKey,
2519
2676
  baseUrl: this.baseUrl,
@@ -2553,7 +2710,9 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
2553
2710
  this.eventQueue = new EventQueue({
2554
2711
  http: this.http,
2555
2712
  batchSize: options.eventFlushBatchSize ?? 20,
2556
- intervalMs: options.eventFlushIntervalMs ?? 1500,
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,
2557
2716
  envelope: () => ({
2558
2717
  appId: this.appId,
2559
2718
  // Ship env on every batch so the backend can cross-check
@@ -2932,6 +3091,34 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
2932
3091
  * `uncaughtException` has no per-request context; without the
2933
3092
  * auto-fill, the event would be rejected at queue enqueue.
2934
3093
  */
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
+ }
2935
3122
  track(event) {
2936
3123
  if (!event.name) {
2937
3124
  throw new CrossdeckError({
@@ -2940,7 +3127,8 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
2940
3127
  message: "track(event) requires a non-empty event.name."
2941
3128
  });
2942
3129
  }
2943
- const sanitized = sanitizePropertyBag(event.properties, "event properties") ?? {};
3130
+ const validated = sanitizePropertyBag(event.properties, "event properties") ?? {};
3131
+ const sanitized = this.scrubPii ? scrubPiiFromProperties(validated) : validated;
2944
3132
  if (this.debug.enabled) {
2945
3133
  const flagged = findSensitivePropertyKeys(sanitized);
2946
3134
  if (flagged.length > 0) {
@@ -3076,11 +3264,25 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
3076
3264
  });
3077
3265
  }
3078
3266
  const rail = input.rail ?? "apple";
3079
- return this.http.request("POST", "/purchases/sync", {
3080
- body: { ...input, rail },
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,
3081
3272
  signal: options?.signal,
3082
3273
  timeoutMs: options?.timeoutMs
3083
3274
  });
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;
3084
3286
  }
3085
3287
  // ============================================================
3086
3288
  // Manual entitlement controls + audit — direct HTTP
@@ -3372,12 +3574,56 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
3372
3574
  };
3373
3575
  }
3374
3576
  /**
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.
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.
3378
3615
  */
3379
- shutdown(reason = "shutdown") {
3380
- this.emit("sdk.shutdown", { reason });
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
+ }
3381
3627
  this.errorTracker?.uninstall();
3382
3628
  this.flushOnExit?.uninstall();
3383
3629
  this.eventQueue.reset();
@@ -3491,28 +3737,28 @@ var CrossdeckServer = class extends import_node_events.EventEmitter {
3491
3737
  * // ... use server ...
3492
3738
  * // at end of block, server[Symbol.dispose]() runs automatically
3493
3739
  *
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).
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).
3498
3747
  */
3499
3748
  [Symbol.dispose]() {
3500
- this.shutdown("dispose");
3749
+ this.shutdownSync("dispose");
3501
3750
  }
3502
3751
  /**
3503
3752
  * Async disposal hook — runs when an `await using` declaration
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).
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).
3507
3757
  *
3508
3758
  * await using server = new CrossdeckServer({ ... });
3509
3759
  */
3510
3760
  async [Symbol.asyncDispose]() {
3511
- try {
3512
- await this.flush();
3513
- } catch {
3514
- }
3515
- this.shutdown("asyncDispose");
3761
+ await this.shutdown("asyncDispose");
3516
3762
  }
3517
3763
  // ============================================================
3518
3764
  reportCapturedError(captured) {
@@ -3932,18 +4178,43 @@ var _CROSSDECK_ERROR_CODES = Object.freeze([
3932
4178
  retryable: false
3933
4179
  },
3934
4180
  // ----- 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.
3935
4185
  {
3936
- code: "webhook_invalid_signature",
4186
+ code: "webhook_signature_mismatch",
3937
4187
  type: "authentication_error",
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.",
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.",
3940
4190
  retryable: false
3941
4191
  },
3942
4192
  {
3943
- code: "webhook_replay_window_exceeded",
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",
3944
4201
  type: "authentication_error",
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.",
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.",
4204
+ retryable: false
4205
+ },
4206
+ {
4207
+ code: "webhook_payload_not_json",
4208
+ 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.",
3947
4218
  retryable: false
3948
4219
  },
3949
4220
  {
@@ -3952,6 +4223,101 @@ var _CROSSDECK_ERROR_CODES = Object.freeze([
3952
4223
  description: "verifyWebhookSignature() was called without a signing secret.",
3953
4224
  resolution: "Pass the secret from your Crossdeck dashboard \u2192 Webhooks page. Never hardcode in source \u2014 read from an env var.",
3954
4225
  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
3955
4321
  }
3956
4322
  ]);
3957
4323
  function isCrossdeckErrorCode(code) {
@@ -3963,8 +4329,9 @@ function getErrorCode(code) {
3963
4329
  }
3964
4330
 
3965
4331
  // src/webhooks.ts
3966
- var import_node_crypto = require("crypto");
4332
+ var import_node_crypto2 = require("crypto");
3967
4333
  var DEFAULT_REPLAY_TOLERANCE_MS = 5 * 60 * 1e3;
4334
+ var MAX_REPLAY_TOLERANCE_MS = 24 * 60 * 60 * 1e3;
3968
4335
  function verifyWebhookSignature(payload, signatureHeader, secret, options = {}) {
3969
4336
  const secrets = normaliseSecrets(secret);
3970
4337
  if (secrets.length === 0) {
@@ -3974,46 +4341,68 @@ function verifyWebhookSignature(payload, signatureHeader, secret, options = {})
3974
4341
  message: "verifyWebhookSignature requires a non-empty secret. Read it from process.env.CROSSDECK_WEBHOOK_SECRET \u2014 never hardcode in source."
3975
4342
  });
3976
4343
  }
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
+ }
3977
4369
  const header = normaliseHeader(signatureHeader);
3978
4370
  const parsed = parseSignatureHeader(header);
3979
4371
  if (!parsed) {
3980
4372
  throw new CrossdeckError({
3981
4373
  type: "authentication_error",
3982
- code: "webhook_invalid_signature",
3983
- message: "Webhook signature header is missing or malformed. Expected 'Crossdeck-Signature: t=<unix>,v1=<hex>'."
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>'."
3984
4376
  });
3985
4377
  }
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
- }
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
+ });
3998
4387
  }
3999
4388
  const signedPayload = `${parsed.timestampSec}.${payload}`;
4000
4389
  const expectedBuf = Buffer.from(parsed.signature, "hex");
4001
4390
  if (expectedBuf.length === 0) {
4002
4391
  throw new CrossdeckError({
4003
4392
  type: "authentication_error",
4004
- code: "webhook_invalid_signature",
4393
+ code: "webhook_signature_mismatch",
4005
4394
  message: "Webhook signature is not a valid hex string."
4006
4395
  });
4007
4396
  }
4008
4397
  const anyMatch = secrets.some((s) => {
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);
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);
4011
4400
  });
4012
4401
  if (!anyMatch) {
4013
4402
  throw new CrossdeckError({
4014
4403
  type: "authentication_error",
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)."
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)."
4017
4406
  });
4018
4407
  }
4019
4408
  try {
@@ -4021,13 +4410,13 @@ function verifyWebhookSignature(payload, signatureHeader, secret, options = {})
4021
4410
  } catch {
4022
4411
  throw new CrossdeckError({
4023
4412
  type: "authentication_error",
4024
- code: "webhook_invalid_signature",
4413
+ code: "webhook_payload_not_json",
4025
4414
  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."
4026
4415
  });
4027
4416
  }
4028
4417
  }
4029
4418
  function signWebhookPayload(payload, secret, timestampSec) {
4030
- return (0, import_node_crypto.createHmac)("sha256", secret).update(`${timestampSec}.${payload}`).digest("hex");
4419
+ return (0, import_node_crypto2.createHmac)("sha256", secret).update(`${timestampSec}.${payload}`).digest("hex");
4031
4420
  }
4032
4421
  function parseSignatureHeader(header) {
4033
4422
  if (!header) return null;
@@ -4059,36 +4448,594 @@ function normaliseSecrets(input) {
4059
4448
  return arr.filter((s) => typeof s === "string" && s.length > 0);
4060
4449
  }
4061
4450
 
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]);
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"
4075
4996
  }
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);
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
+ );
4083
5030
  }
4084
- return v;
4085
- }
5031
+ };
4086
5032
  // Annotate the CommonJS export names for ESM import in node:
4087
5033
  0 && (module.exports = {
4088
5034
  CROSSDECK_API_VERSION,
4089
5035
  CROSSDECK_ERROR_CODES,
4090
5036
  CrossdeckAuthenticationError,
4091
5037
  CrossdeckConfigurationError,
5038
+ CrossdeckContracts,
4092
5039
  CrossdeckError,
4093
5040
  CrossdeckInternalError,
4094
5041
  CrossdeckNetworkError,