@burdenoff/be-sdk 2026.1123.2 → 2026.1123.4

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.
Files changed (71) hide show
  1. package/dist/auth/index.d.ts +1 -1
  2. package/dist/auth/index.js +1 -1
  3. package/dist/{auth-C5ctwSLp.js → auth-DqD4_tHM.js} +39 -6
  4. package/dist/auth-DqD4_tHM.js.map +1 -0
  5. package/dist/{client-BgAEvDC2.d.ts → client-NknQrWsP.d.ts} +3 -1
  6. package/dist/feature-flags/index.d.ts +1 -1
  7. package/dist/graph/index.d.ts +1 -1
  8. package/dist/graph/index.js +2 -2
  9. package/dist/{graph-Egewc_K7.js → graph-BdoM7_90.js} +2 -2
  10. package/dist/{graph-Egewc_K7.js.map → graph-BdoM7_90.js.map} +1 -1
  11. package/dist/{index-HeUeEsMU.d.ts → index-BaskMO3C.d.ts} +8 -2
  12. package/dist/{index-479i3w77.d.ts → index-BgOU0pxB.d.ts} +30 -5
  13. package/dist/{index-FKohsiex.d.ts → index-BrRQe24P.d.ts} +3 -2
  14. package/dist/{index-BiTzGUZP.d.ts → index-BwgBHUuX.d.ts} +2 -2
  15. package/dist/{index-DMeQh75K.d.ts → index-CIayzveI.d.ts} +1 -1
  16. package/dist/{index-DSA8h4W3.d.ts → index-CUiL43SY.d.ts} +2 -2
  17. package/dist/{index-CzMD97-N.d.ts → index-CkQieKSy.d.ts} +16 -2
  18. package/dist/{index-nP7g1FZm.d.ts → index-DFEKBKBE.d.ts} +4 -1
  19. package/dist/{index-DhFP_AIB.d.ts → index-DkitHCtV.d.ts} +1 -1
  20. package/dist/index.d.ts +8 -8
  21. package/dist/index.js +7 -7
  22. package/dist/init/index.js +1 -1
  23. package/dist/{init-BCLZQ1Gz.js → init-4vv4gYEm.js} +2 -2
  24. package/dist/{init-BCLZQ1Gz.js.map → init-4vv4gYEm.js.map} +1 -1
  25. package/dist/instrumentation/index.d.ts +2 -2
  26. package/dist/instrumentation/index.js +3 -3
  27. package/dist/{instrumentation-xkkmDgJ0.js → instrumentation-C738xDj8.js} +45 -6
  28. package/dist/instrumentation-C738xDj8.js.map +1 -0
  29. package/dist/lake/index.d.ts +52 -3
  30. package/dist/lake/index.js +238 -9
  31. package/dist/lake/index.js.map +1 -1
  32. package/dist/metrics/index.js +1 -1
  33. package/dist/{metrics-BrLwNUrb.js → metrics-CQaHT12m.js} +2 -2
  34. package/dist/{metrics-BrLwNUrb.js.map → metrics-CQaHT12m.js.map} +1 -1
  35. package/dist/{metrics-collector-C2eShrlW.js → metrics-collector-DXQrMUle.js} +216 -139
  36. package/dist/metrics-collector-DXQrMUle.js.map +1 -0
  37. package/dist/{middleware-B9eyLP7A.js → middleware-z8KzMFU_.js} +95 -5
  38. package/dist/middleware-z8KzMFU_.js.map +1 -0
  39. package/dist/prisma/index.d.ts +3 -3
  40. package/dist/prisma/index.js +3 -3
  41. package/dist/{prisma-CML_Prrn.js → prisma-J-ZUmVWJ.js} +4 -2
  42. package/dist/{prisma-CML_Prrn.js.map → prisma-J-ZUmVWJ.js.map} +1 -1
  43. package/dist/{rate-limit-CBrK_U5H.js → rate-limit-ISSpByjW.js} +25 -25
  44. package/dist/rate-limit-ISSpByjW.js.map +1 -0
  45. package/dist/resource-caps/index.d.ts +77 -0
  46. package/dist/resource-caps/index.js +235 -31
  47. package/dist/resource-caps/index.js.map +1 -1
  48. package/dist/security/index.d.ts +1 -1
  49. package/dist/security/index.js +1 -1
  50. package/dist/security/rate-limit/index.d.ts +1 -1
  51. package/dist/security/rate-limit/index.js +1 -1
  52. package/dist/server/index.d.ts +4 -4
  53. package/dist/server/index.js +112 -6
  54. package/dist/server/index.js.map +1 -1
  55. package/dist/tags/index.d.ts +1 -1
  56. package/dist/tags/index.js +1 -1
  57. package/dist/{tags-CbijgoqR.js → tags-C316oA9r.js} +14 -3
  58. package/dist/{tags-CbijgoqR.js.map → tags-C316oA9r.js.map} +1 -1
  59. package/dist/telemetry/index.d.ts +1 -1
  60. package/dist/telemetry/index.js +1 -1
  61. package/dist/{types-De_pO1Wz.d.ts → types-BWN8tMdF.d.ts} +5 -1
  62. package/dist/utils/index.d.ts +2 -2
  63. package/dist/utils/index.js +2 -2
  64. package/dist/{utils-DL85Tnbn.js → utils-DpW6K_iB.js} +24 -7
  65. package/dist/{utils-DL85Tnbn.js.map → utils-DpW6K_iB.js.map} +1 -1
  66. package/package.json +1 -1
  67. package/dist/auth-C5ctwSLp.js.map +0 -1
  68. package/dist/instrumentation-xkkmDgJ0.js.map +0 -1
  69. package/dist/metrics-collector-C2eShrlW.js.map +0 -1
  70. package/dist/middleware-B9eyLP7A.js.map +0 -1
  71. package/dist/rate-limit-CBrK_U5H.js.map +0 -1
@@ -1,6 +1,7 @@
1
- import { n as createCounter } from "../metrics-collector-C2eShrlW.js";
1
+ import { a as createCounter } from "../metrics-collector-DXQrMUle.js";
2
2
  import { a as logger } from "../logger-B6rCpb7D.js";
3
3
  import { GraphQLError } from "graphql";
4
+ import { createHash } from "node:crypto";
4
5
 
5
6
  // src/resource-caps/index.ts
6
7
  /**
@@ -18,10 +19,16 @@ import { GraphQLError } from "graphql";
18
19
  *
19
20
  * @example
20
21
  * ```ts
21
- * import { resourceCaps } from '@burdenoff/be-sdk/resource-caps';
22
+ * import { getResourceCaps } from '@burdenoff/be-sdk/resource-caps';
22
23
  *
23
- * const { limit } = await resourceCaps.getResourceCap(userId, 'tag');
24
- * await resourceCaps.enforceResourceCap(userId, 'tag', currentCount);
24
+ * // Preferred: enforce atomically inside a serialized Prisma transaction
25
+ * const { result: created } = await getResourceCaps().enforceWithinTransaction({
26
+ * userId,
27
+ * resource: 'vibe',
28
+ * prisma,
29
+ * count: (tx) => tx.vibe.count({ where: { createdBy: userId, deletedAt: null } }),
30
+ * create: (tx) => tx.vibe.create({ data }),
31
+ * });
25
32
  * ```
26
33
  */
27
34
  /**
@@ -106,6 +113,62 @@ const RESOURCE_CAP_DEFAULTS = {
106
113
  }
107
114
  };
108
115
  /**
116
+ * Atomic Valkey/Redis Lua script for cross-store cap reservation.
117
+ *
118
+ * KEYS[1]: reservation counter key
119
+ * ARGV[1]: baseCount (authoritative persisted count observed prior to reserve)
120
+ * ARGV[2]: limit (cap.limit)
121
+ * ARGV[3]: amount to reserve (usually 1)
122
+ * ARGV[4]: ttlSeconds (safety expiry so crashed workers never leak slots forever)
123
+ *
124
+ * Returns the new total reserved count on success, or -1 if reserving would
125
+ * exceed `limit`.
126
+ */
127
+ const RESOURCE_CAP_RESERVE_LUA = `
128
+ local current = tonumber(redis.call('GET', KEYS[1]) or '0')
129
+ local baseCount = tonumber(ARGV[1])
130
+ local limit = tonumber(ARGV[2])
131
+ local delta = tonumber(ARGV[3])
132
+ local ttl = tonumber(ARGV[4])
133
+ if (baseCount + current + delta) > limit then
134
+ return -1
135
+ end
136
+ local nextVal = redis.call('INCRBY', KEYS[1], delta)
137
+ redis.call('EXPIRE', KEYS[1], ttl)
138
+ return nextVal
139
+ `.trim();
140
+ /**
141
+ * Derive two deterministic signed 32-bit PostgreSQL advisory-lock keys for a
142
+ * `(scopeKey, resource)` pair so `pg_advisory_xact_lock(int4, int4)` serializes
143
+ * concurrent creates for the same scope and resource without blocking unrelated
144
+ * tenants or resources.
145
+ */
146
+ function computeResourceCapLockKeys(scopeKey, resource) {
147
+ const digest = createHash("sha256").update(`boff:rcap:${scopeKey}:${resource}`).digest();
148
+ return [digest.readInt32BE(0), digest.readInt32BE(4)];
149
+ }
150
+ /**
151
+ * Acquire a transaction-scoped PostgreSQL advisory lock for `(scopeKey, resource)`
152
+ * inside an active Prisma interactive transaction. The lock is held until the
153
+ * transaction commits or rolls back.
154
+ */
155
+ async function acquireResourceCapAdvisoryLock(tx, scopeKey, resource) {
156
+ const [key1, key2] = computeResourceCapLockKeys(scopeKey, resource);
157
+ if (typeof tx.$queryRaw === "function") {
158
+ await tx.$queryRaw`SELECT pg_advisory_xact_lock(${key1}::int4, ${key2}::int4)`;
159
+ return [key1, key2];
160
+ }
161
+ if (typeof tx.$executeRaw === "function") {
162
+ await tx.$executeRaw`SELECT pg_advisory_xact_lock(${key1}::int4, ${key2}::int4)`;
163
+ return [key1, key2];
164
+ }
165
+ if (typeof tx.$executeRawUnsafe === "function") {
166
+ await tx.$executeRawUnsafe("SELECT pg_advisory_xact_lock($1::int4, $2::int4)", key1, key2);
167
+ return [key1, key2];
168
+ }
169
+ throw new Error("acquireResourceCapAdvisoryLock: transaction client must provide $queryRaw, $executeRaw, or $executeRawUnsafe");
170
+ }
171
+ /**
109
172
  * Thrown when an entity create operation would push the user past the cap.
110
173
  * The matching GraphQL error has extensions.code = RESOURCE_CAP_EXCEEDED
111
174
  * so clients can detect and route to an upgrade flow.
@@ -206,32 +269,188 @@ var ResourceCapsModule = class {
206
269
  };
207
270
  }
208
271
  /**
209
- * Throws ResourceCapExceededError when currentCount >= limit.
210
- * Use BEFORE the create transaction to avoid orphan rows.
272
+ * Compare a caller-supplied count against a resolved {@link ResourceCap} and
273
+ * throw {@link ResourceCapExceededError} when `currentCount >= cap.limit`.
274
+ *
275
+ * Safe ONLY when `currentCount` was measured inside the same serialized
276
+ * transaction (after {@link acquireResourceCapAdvisoryLock} or under
277
+ * `Serializable` isolation) as the insert.
211
278
  */
212
- async enforceResourceCap(userId, resource, currentCount) {
213
- const cap = await this.getResourceCap(userId, resource);
279
+ assertWithinCap(cap, currentCount) {
214
280
  if (currentCount >= cap.limit) {
215
281
  this.enforcementCounter.inc({
216
- resource,
282
+ resource: cap.resource,
217
283
  plan_tier: cap.planTier,
218
284
  result: "denied"
219
285
  });
220
286
  throw new ResourceCapExceededError({
221
- resource,
287
+ resource: cap.resource,
222
288
  currentCount,
223
289
  limit: cap.limit,
224
290
  planName: cap.planName
225
291
  });
226
292
  }
227
293
  this.enforcementCounter.inc({
228
- resource,
294
+ resource: cap.resource,
229
295
  plan_tier: cap.planTier,
230
296
  result: "allowed"
231
297
  });
232
298
  return cap;
233
299
  }
234
300
  /**
301
+ * Throws ResourceCapExceededError when currentCount >= limit.
302
+ *
303
+ * @deprecated Non-atomic when called outside a serialized transaction: concurrent
304
+ * creates can observe the same stale `currentCount` and bypass plan quotas (BOFF-16045).
305
+ * Use {@link enforceWithinTransaction} (for PostgreSQL/Prisma creates) or
306
+ * {@link reserveResourceCap} / {@link withReservedResourceCap} (for cross-store creates).
307
+ * If you manage your own Prisma transaction, pre-resolve {@link getResourceCap},
308
+ * call {@link acquireResourceCapAdvisoryLock} inside `$transaction`, count, and
309
+ * call {@link assertWithinCap}.
310
+ */
311
+ async enforceResourceCap(userId, resource, currentCount) {
312
+ const cap = await this.getResourceCap(userId, resource);
313
+ return this.assertWithinCap(cap, currentCount);
314
+ }
315
+ /**
316
+ * Atomically enforce a user-scoped resource cap and insert the resource inside
317
+ * a single Prisma transaction serialized by a per-`(user, resource)` PostgreSQL
318
+ * advisory lock (`pg_advisory_xact_lock`).
319
+ *
320
+ * The billing plan cap is pre-resolved BEFORE opening the transaction so no
321
+ * external RPC runs while holding database locks.
322
+ */
323
+ async enforceWithinTransaction(options) {
324
+ const { userId, resource, prisma, count, create, lockScopeKey, transactionOptions } = options;
325
+ const cap = await this.getResourceCap(userId, resource);
326
+ const scopeKey = lockScopeKey ?? `user:${userId}`;
327
+ return {
328
+ result: await prisma.$transaction(async (tx) => {
329
+ await acquireResourceCapAdvisoryLock(tx, scopeKey, resource);
330
+ const currentCount = await count(tx);
331
+ this.assertWithinCap(cap, currentCount);
332
+ return create(tx, cap);
333
+ }, transactionOptions),
334
+ cap
335
+ };
336
+ }
337
+ /**
338
+ * Atomically enforce a workspace-scoped resource cap and insert the resource
339
+ * inside a single Prisma transaction serialized by a per-`(workspace, resource)`
340
+ * PostgreSQL advisory lock (`pg_advisory_xact_lock`).
341
+ */
342
+ async enforceWorkspaceWithinTransaction(options) {
343
+ const { scope, resource, prisma, count, create, transactionOptions } = options;
344
+ const cap = await this.getWorkspaceResourceCap(scope, resource);
345
+ const scopeKey = `workspace:${scope.workspaceId}`;
346
+ return {
347
+ result: await prisma.$transaction(async (tx) => {
348
+ await acquireResourceCapAdvisoryLock(tx, scopeKey, resource);
349
+ const currentCount = await count(tx);
350
+ this.assertWithinCap(cap, currentCount);
351
+ return create(tx, cap);
352
+ }, transactionOptions),
353
+ cap
354
+ };
355
+ }
356
+ /**
357
+ * Atomically reserve a user-scoped resource cap slot in Valkey/Redis for
358
+ * cross-store creates (e.g., sandboxes) that cannot share one SQL transaction.
359
+ * Always call `reservation.commit()` on success or `reservation.release()` on
360
+ * failure, or prefer {@link withReservedResourceCap}.
361
+ */
362
+ async reserveResourceCap(userId, resource, options) {
363
+ const cap = await this.getResourceCap(userId, resource);
364
+ return this.reserveWithResolvedCap(cap, `user:${userId}`, options);
365
+ }
366
+ /**
367
+ * Atomically reserve a workspace-scoped resource cap slot in Valkey/Redis for
368
+ * cross-store creates.
369
+ */
370
+ async reserveWorkspaceResourceCap(scope, resource, options) {
371
+ const cap = await this.getWorkspaceResourceCap(scope, resource);
372
+ return this.reserveWithResolvedCap(cap, `workspace:${scope.workspaceId}`, options);
373
+ }
374
+ /**
375
+ * Reserve a user-scoped cap slot, run `action`, commit on success, and
376
+ * automatically release the slot if `action` throws.
377
+ */
378
+ async withReservedResourceCap(userId, resource, options, action) {
379
+ const reservation = await this.reserveResourceCap(userId, resource, options);
380
+ try {
381
+ const result = await action(reservation.cap);
382
+ await reservation.commit();
383
+ return {
384
+ result,
385
+ cap: reservation.cap
386
+ };
387
+ } catch (error) {
388
+ await reservation.release();
389
+ throw error;
390
+ }
391
+ }
392
+ async reserveWithResolvedCap(cap, scopeKey, options) {
393
+ const amount = Math.max(1, Math.floor(options.amount ?? 1));
394
+ const ttlSeconds = Math.max(1, Math.floor(options.ttlSeconds ?? 120));
395
+ const key = `${options.keyPrefix ?? "rcap:res"}:${scopeKey}:${cap.resource}`;
396
+ const baseCount = Math.max(0, Math.floor(options.baseCount));
397
+ if (typeof options.store.evalScript === "function") {
398
+ if (await options.store.evalScript(RESOURCE_CAP_RESERVE_LUA, [key], [
399
+ String(baseCount),
400
+ String(cap.limit),
401
+ String(amount),
402
+ String(ttlSeconds)
403
+ ]) < 0) {
404
+ this.enforcementCounter.inc({
405
+ resource: cap.resource,
406
+ plan_tier: cap.planTier,
407
+ result: "denied"
408
+ });
409
+ throw new ResourceCapExceededError({
410
+ resource: cap.resource,
411
+ currentCount: cap.limit,
412
+ limit: cap.limit,
413
+ planName: cap.planName
414
+ });
415
+ }
416
+ } else {
417
+ const inFlightAfterIncrement = await options.store.increment(key, amount);
418
+ await options.store.expire(key, ttlSeconds);
419
+ if (baseCount + inFlightAfterIncrement > cap.limit) {
420
+ await options.store.decrement(key, amount).catch(() => void 0);
421
+ this.enforcementCounter.inc({
422
+ resource: cap.resource,
423
+ plan_tier: cap.planTier,
424
+ result: "denied"
425
+ });
426
+ throw new ResourceCapExceededError({
427
+ resource: cap.resource,
428
+ currentCount: baseCount + inFlightAfterIncrement - amount,
429
+ limit: cap.limit,
430
+ planName: cap.planName
431
+ });
432
+ }
433
+ }
434
+ this.enforcementCounter.inc({
435
+ resource: cap.resource,
436
+ plan_tier: cap.planTier,
437
+ result: "allowed"
438
+ });
439
+ let settled = false;
440
+ const releaseOnce = async () => {
441
+ if (settled) return;
442
+ settled = true;
443
+ await options.store.decrement(key, amount).catch(() => void 0);
444
+ };
445
+ return {
446
+ cap,
447
+ key,
448
+ amount,
449
+ commit: releaseOnce,
450
+ release: releaseOnce
451
+ };
452
+ }
453
+ /**
235
454
  * Resolve a workspace-scoped resource cap from the workspace's owner
236
455
  * organization plan, regardless of which actor triggered the action.
237
456
  *
@@ -272,28 +491,13 @@ var ResourceCapsModule = class {
272
491
  * Throws ResourceCapExceededError when currentCount >= limit for a
273
492
  * workspace-scoped resource. The cap is resolved from the workspace owner's
274
493
  * organization plan, so the answer is stable across members.
494
+ *
495
+ * @deprecated Non-atomic when called outside a serialized transaction (BOFF-16045).
496
+ * Prefer {@link enforceWorkspaceWithinTransaction} or {@link reserveWorkspaceResourceCap}.
275
497
  */
276
498
  async enforceWorkspaceResourceCap(scope, resource, currentCount) {
277
499
  const cap = await this.getWorkspaceResourceCap(scope, resource);
278
- if (currentCount >= cap.limit) {
279
- this.enforcementCounter.inc({
280
- resource,
281
- plan_tier: cap.planTier,
282
- result: "denied"
283
- });
284
- throw new ResourceCapExceededError({
285
- resource,
286
- currentCount,
287
- limit: cap.limit,
288
- planName: cap.planName
289
- });
290
- }
291
- this.enforcementCounter.inc({
292
- resource,
293
- plan_tier: cap.planTier,
294
- result: "allowed"
295
- });
296
- return cap;
500
+ return this.assertWithinCap(cap, currentCount);
297
501
  }
298
502
  /** Invalidate cache for a user (e.g. after plan upgrade) */
299
503
  invalidate(userId) {
@@ -427,5 +631,5 @@ function __resetResourceCapsForTests() {
427
631
  defaultInstance = null;
428
632
  }
429
633
 
430
- export { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, __resetResourceCapsForTests, configureResourceCaps, getResourceCaps };
634
+ export { RESOURCE_CAP_DEFAULTS, RESOURCE_CAP_RESERVE_LUA, ResourceCapExceededError, ResourceCapsModule, __resetResourceCapsForTests, acquireResourceCapAdvisoryLock, computeResourceCapLockKeys, configureResourceCaps, getResourceCaps };
431
635
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/resource-caps/index.ts"],"sourcesContent":["/**\n * Resource Caps Module\n *\n * Enforces per-user / per-workspace resource ceilings to prevent unbounded\n * resource use on a multi-tenant SaaS. Caps come from the user's billing plan\n * (resolved via global-billing-svc) and fall back to static defaults defined\n * here when the plan lookup fails or the resource isn't overridden.\n *\n * Two plan tiers exist by default:\n * - free: tight per-user / per-workspace ceilings\n * - paid (default): ~100x looser; individual paid plans can override via the\n * `Plan.resourceCaps` JSON column in global-billing-svc.\n *\n * @example\n * ```ts\n * import { resourceCaps } from '@burdenoff/be-sdk/resource-caps';\n *\n * const { limit } = await resourceCaps.getResourceCap(userId, 'tag');\n * await resourceCaps.enforceResourceCap(userId, 'tag', currentCount);\n * ```\n */\n\nimport { GraphQLError } from 'graphql';\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport { createCounter } from '../instrumentation/metrics-collector.js';\nimport { logger } from '../logger/index.js';\n\n// ---------------------------------------------------------------------------\n// Resource registry\n// ---------------------------------------------------------------------------\n\n/**\n * Canonical resource names. Adding a new capped resource? Append it here,\n * extend RESOURCE_CAP_DEFAULTS, and reference it from the relevant svc.\n */\nexport type ResourceName =\n | 'workspace' // per user\n | 'workspaceMember' // per workspace\n | 'sandbox' // per user\n | 'vibe' // per user\n | 'agent' // per workspace\n | 'conversation' // per user/day\n | 'message' // per user/day\n | 'tag' // per workspace\n | 'file' // per user (count only)\n | 'group' // per workspace\n | 'calendar' // per user\n | 'scheduledTask' // per user\n | 'form' // per user\n | 'apiKey' // per user\n | 'webhook'; // per workspace\n\nexport type PlanTier = 'free' | 'paid';\n\nexport interface ResourceCapDefaults {\n free: number;\n paidDefault: number;\n /** Optional scope hint used by callers when wiring guards */\n scope: 'user' | 'workspace' | 'user/day';\n}\n\n/**\n * Static fallback caps. Real values may be overridden per plan in\n * global-billing-svc Plan.resourceCaps JSON.\n */\nexport const RESOURCE_CAP_DEFAULTS: Record<ResourceName, ResourceCapDefaults> = {\n workspace: { free: 3, paidDefault: 50, scope: 'user' },\n workspaceMember: { free: 500, paidDefault: 500, scope: 'workspace' },\n sandbox: { free: 2, paidDefault: 50, scope: 'user' },\n vibe: { free: 10, paidDefault: 500, scope: 'user' },\n agent: { free: 2, paidDefault: 20, scope: 'workspace' },\n conversation: { free: 20, paidDefault: 2000, scope: 'user/day' },\n message: { free: 200, paidDefault: 20000, scope: 'user/day' },\n tag: { free: 50, paidDefault: 5000, scope: 'workspace' },\n file: { free: 100, paidDefault: 10000, scope: 'user' },\n group: { free: 5, paidDefault: 500, scope: 'workspace' },\n calendar: { free: 3, paidDefault: 100, scope: 'user' },\n scheduledTask: { free: 5, paidDefault: 500, scope: 'user' },\n form: { free: 5, paidDefault: 500, scope: 'user' },\n apiKey: { free: 2, paidDefault: 50, scope: 'user' },\n webhook: { free: 2, paidDefault: 100, scope: 'workspace' },\n};\n\n// ---------------------------------------------------------------------------\n// Types & errors\n// ---------------------------------------------------------------------------\n\nexport interface ResourceCap {\n resource: ResourceName;\n limit: number;\n planName: string;\n planTier: PlanTier;\n /** True when the cap came from defaults, not from the billing service */\n isFallback: boolean;\n /** Why the fallback was used, when isFallback is true */\n fallbackReason?: 'clientless' | 'billing_error';\n}\n\n/**\n * Scope for workspace-scoped resource caps. The cap is derived from the plan of\n * the workspace's owning organization, not from whichever actor happens to be\n * making the request, so two members of the same workspace always see the same\n * limit (BOFF-4808).\n */\nexport interface WorkspaceResourceCapScope {\n /** Stable workspace identifier; used as the cache key. */\n workspaceId: string;\n /**\n * Organization that owns the workspace and whose billing plan determines the\n * cap. This is the `organizationId` from global-tenant-svc's Workspace type\n * (or `orgId` from wspace-workspace-svc's Workspace type).\n */\n organizationId: string;\n}\n\n/**\n * Layer-aware transport for the `userBillingPlan` lookup. Given the GraphQL\n * document + variables, returns the response `data` object (or null). Preferred\n * over `client`: the SDK bootstrap wires this to a same-layer (global) or\n * cross-layer (wspace→global) gateway call so billing is reachable from every\n * service without any per-call-site wiring (BOFF-4805).\n */\nexport type BillingPlanTransport = (query: string, variables: Record<string, unknown>) => Promise<unknown>;\n\nexport interface ResourceCapsConfig {\n client?: BurdenoffGraphQLClient;\n /** Preferred billing lookup path; see {@link BillingPlanTransport}. */\n transport?: BillingPlanTransport;\n /** Optional in-memory TTL for plan lookups; defaults to 60s */\n cacheTtlMs?: number;\n /**\n * Plan tier used when the module has no billing source (clientless). This is\n * the misconfiguration path: services should always bootstrap with a billing\n * transport. Defaults to `free` so a clientless service is visibly broken in\n * tests, while still not hard-blocking local unit tests.\n */\n clientlessTier?: PlanTier;\n /**\n * Plan tier used when a billing source is configured but the lookup fails\n * (network error, billing service down, etc.). Defaults to `paid` so a\n * transient billing outage does not silently downgrade paid customers to the\n * tightest free-tier caps (fail-open with alerting; BOFF-4805/4809).\n */\n billingFailureTier?: PlanTier;\n /**\n * Telemetry hook invoked when the module cannot reach billing (no transport /\n * client) and collapses to the clientless fallback. Wired to a metric counter\n * by observability so an unwired/broken integration is visible (BOFF-4809).\n */\n onFallback?: () => void;\n /**\n * Telemetry hook invoked when a billing source is configured but the lookup\n * fails (billing error fallback to the paid default).\n */\n onBillingFailure?: () => void;\n}\n\ninterface CachedPlan {\n planName: string;\n planTier: PlanTier;\n overrides: Partial<Record<ResourceName, number>>;\n fetchedAt: number;\n isFallback: boolean;\n fallbackReason?: 'clientless' | 'billing_error';\n}\n\n/**\n * Thrown when an entity create operation would push the user past the cap.\n * The matching GraphQL error has extensions.code = RESOURCE_CAP_EXCEEDED\n * so clients can detect and route to an upgrade flow.\n */\nexport class ResourceCapExceededError extends GraphQLError {\n constructor(detail: { resource: ResourceName; currentCount: number; limit: number; planName: string }) {\n super(\n `Resource cap exceeded for ${detail.resource}: ${detail.currentCount}/${detail.limit} on plan '${detail.planName}'.`,\n {\n extensions: {\n code: 'RESOURCE_CAP_EXCEEDED',\n userMessage: \"You've reached your plan limit. Upgrade your plan to continue.\",\n technicalMessage: `Resource cap exceeded for ${detail.resource}: ${detail.currentCount}/${detail.limit} on plan '${detail.planName}'.`,\n resource: detail.resource,\n currentCount: detail.currentCount,\n limit: detail.limit,\n planName: detail.planName,\n },\n }\n );\n this.name = 'ResourceCapExceededError';\n }\n}\n\n// ---------------------------------------------------------------------------\n// Module\n// ---------------------------------------------------------------------------\n\nconst PLAN_QUERY = /* GraphQL */ `\n query GetUserPlanForCaps($userId: ID!) {\n userBillingPlan(userId: $userId) {\n planName\n tier\n resourceCaps\n }\n }\n`;\n\ninterface PlanQueryResponse {\n userBillingPlan?: {\n planName?: string | null;\n tier?: string | null;\n resourceCaps?: Record<string, number> | null;\n } | null;\n}\n\ntype PlanNode = NonNullable<PlanQueryResponse['userBillingPlan']>;\n\nexport class ResourceCapsModule {\n private client?: BurdenoffGraphQLClient;\n private transport?: BillingPlanTransport;\n private cacheTtlMs: number;\n private clientlessTier: PlanTier;\n private billingFailureTier: PlanTier;\n private onFallback?: () => void;\n private onBillingFailure?: () => void;\n private warnedClientless = false;\n private readonly planCache = new Map<string, CachedPlan>();\n private readonly planResolutionCounter;\n private readonly enforcementCounter;\n\n constructor(config: ResourceCapsConfig = {}) {\n this.client = config.client;\n this.transport = config.transport;\n this.cacheTtlMs = config.cacheTtlMs ?? 60_000;\n this.clientlessTier = config.clientlessTier ?? 'free';\n this.billingFailureTier = config.billingFailureTier ?? 'paid';\n this.onFallback = config.onFallback;\n this.onBillingFailure = config.onBillingFailure;\n this.planResolutionCounter = createCounter(\n 'resource_caps.plan_resolution_total',\n 'Total number of billing plan resolutions for resource caps'\n );\n this.enforcementCounter = createCounter(\n 'resource_caps.enforcement_total',\n 'Total number of resource cap enforcement checks'\n );\n }\n\n /**\n * (Re)bind runtime dependencies on an already-constructed module. The SDK\n * bootstrap uses this to prime the process-wide singleton with a billing\n * transport even if an early caller already lazily created it clientless\n * (a bare `getResourceCaps(config)` ignores config once the instance exists).\n * Clears the plan cache so stale fallback entries don't linger.\n */\n configure(config: ResourceCapsConfig): void {\n if (config.client !== undefined) this.client = config.client;\n if (config.transport !== undefined) this.transport = config.transport;\n if (config.onFallback !== undefined) this.onFallback = config.onFallback;\n if (config.onBillingFailure !== undefined) this.onBillingFailure = config.onBillingFailure;\n if (typeof config.cacheTtlMs === 'number') this.cacheTtlMs = config.cacheTtlMs;\n if (config.clientlessTier) this.clientlessTier = config.clientlessTier;\n if (config.billingFailureTier) this.billingFailureTier = config.billingFailureTier;\n if (this.hasBillingSource()) this.warnedClientless = false;\n this.planCache.clear();\n }\n\n /** True when the module can actually reach billing (has a transport or client). */\n hasBillingSource(): boolean {\n return Boolean(this.transport || this.client);\n }\n\n /**\n * Resolve the cap for a given resource for the supplied user.\n * Order: plan-override → plan-tier-default → static free default.\n */\n async getResourceCap(userId: string, resource: ResourceName): Promise<ResourceCap> {\n if (!userId) {\n throw new Error('getResourceCap: userId is required');\n }\n const defaults = RESOURCE_CAP_DEFAULTS[resource];\n if (!defaults) {\n throw new Error(`getResourceCap: unknown resource '${resource}'`);\n }\n\n const plan = await this.resolvePlan(userId);\n const override = plan.overrides[resource];\n if (typeof override === 'number' && override >= 0) {\n return {\n resource,\n limit: override,\n planName: plan.planName,\n planTier: plan.planTier,\n isFallback: plan.isFallback,\n fallbackReason: plan.fallbackReason,\n };\n }\n\n const limit = plan.planTier === 'paid' ? defaults.paidDefault : defaults.free;\n return {\n resource,\n limit,\n planName: plan.planName,\n planTier: plan.planTier,\n isFallback: plan.isFallback,\n fallbackReason: plan.fallbackReason,\n };\n }\n\n /**\n * Throws ResourceCapExceededError when currentCount >= limit.\n * Use BEFORE the create transaction to avoid orphan rows.\n */\n async enforceResourceCap(userId: string, resource: ResourceName, currentCount: number): Promise<ResourceCap> {\n const cap = await this.getResourceCap(userId, resource);\n if (currentCount >= cap.limit) {\n this.enforcementCounter.inc({\n resource,\n plan_tier: cap.planTier,\n result: 'denied',\n });\n throw new ResourceCapExceededError({\n resource,\n currentCount,\n limit: cap.limit,\n planName: cap.planName,\n });\n }\n this.enforcementCounter.inc({\n resource,\n plan_tier: cap.planTier,\n result: 'allowed',\n });\n return cap;\n }\n\n /**\n * Resolve a workspace-scoped resource cap from the workspace's owner\n * organization plan, regardless of which actor triggered the action.\n *\n * @example\n * ```ts\n * const { limit } = await caps.getWorkspaceResourceCap(\n * { workspaceId: 'ws-1', organizationId: 'org-1' },\n * 'group'\n * );\n * ```\n */\n async getWorkspaceResourceCap(scope: WorkspaceResourceCapScope, resource: ResourceName): Promise<ResourceCap> {\n const { workspaceId, organizationId } = scope;\n if (!workspaceId) {\n throw new Error('getWorkspaceResourceCap: workspaceId is required');\n }\n if (!organizationId) {\n throw new Error('getWorkspaceResourceCap: organizationId is required');\n }\n const defaults = RESOURCE_CAP_DEFAULTS[resource];\n if (!defaults) {\n throw new Error(`getWorkspaceResourceCap: unknown resource '${resource}'`);\n }\n\n const plan = await this.resolvePlan(organizationId, this.workspaceCacheKey(workspaceId));\n const override = plan.overrides[resource];\n if (typeof override === 'number' && override >= 0) {\n return {\n resource,\n limit: override,\n planName: plan.planName,\n planTier: plan.planTier,\n isFallback: plan.isFallback,\n fallbackReason: plan.fallbackReason,\n };\n }\n\n const limit = plan.planTier === 'paid' ? defaults.paidDefault : defaults.free;\n return {\n resource,\n limit,\n planName: plan.planName,\n planTier: plan.planTier,\n isFallback: plan.isFallback,\n fallbackReason: plan.fallbackReason,\n };\n }\n\n /**\n * Throws ResourceCapExceededError when currentCount >= limit for a\n * workspace-scoped resource. The cap is resolved from the workspace owner's\n * organization plan, so the answer is stable across members.\n */\n async enforceWorkspaceResourceCap(\n scope: WorkspaceResourceCapScope,\n resource: ResourceName,\n currentCount: number\n ): Promise<ResourceCap> {\n const cap = await this.getWorkspaceResourceCap(scope, resource);\n if (currentCount >= cap.limit) {\n this.enforcementCounter.inc({\n resource,\n plan_tier: cap.planTier,\n result: 'denied',\n });\n throw new ResourceCapExceededError({\n resource,\n currentCount,\n limit: cap.limit,\n planName: cap.planName,\n });\n }\n this.enforcementCounter.inc({\n resource,\n plan_tier: cap.planTier,\n result: 'allowed',\n });\n return cap;\n }\n\n /** Invalidate cache for a user (e.g. after plan upgrade) */\n invalidate(userId: string): void {\n this.planCache.delete(userId);\n }\n\n /** Invalidate cache for a workspace (e.g. after workspace plan change) */\n invalidateWorkspace(workspaceId: string): void {\n this.planCache.delete(this.workspaceCacheKey(workspaceId));\n }\n\n /** Clear entire plan cache */\n invalidateAll(): void {\n this.planCache.clear();\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private workspaceCacheKey(workspaceId: string): string {\n return `workspace:${workspaceId}`;\n }\n\n private async resolvePlan(userId: string, cacheKey?: string): Promise<CachedPlan> {\n const key = cacheKey ?? userId;\n const cached = this.planCache.get(key);\n if (cached && Date.now() - cached.fetchedAt < this.cacheTtlMs) {\n return cached;\n }\n\n const plan = await this.fetchPlan(userId);\n this.planCache.set(key, plan);\n return plan;\n }\n\n private async fetchPlan(userId: string): Promise<CachedPlan> {\n // No billing source wired → every cap silently collapses to the configured\n // clientless tier. Warn loudly (once) so an unwired/broken integration\n // can't hide in prod (BOFF-4805/4809).\n if (!this.hasBillingSource()) {\n this.warnClientlessOnce();\n this.planResolutionCounter.inc({ result: 'fallback', reason: 'clientless' });\n return this.fallbackPlan(this.clientlessTier, 'clientless');\n }\n try {\n const planNode = await this.fetchPlanNode(userId);\n if (!planNode) {\n logger.warn('resource-caps: plan lookup returned null; falling back to paid defaults', {\n userId,\n });\n this.onBillingFailure?.();\n this.planResolutionCounter.inc({ result: 'fallback', reason: 'billing_error' });\n return this.fallbackPlan(this.billingFailureTier, 'billing_error');\n }\n const tier = normaliseTier(planNode.tier, this.billingFailureTier);\n const overrides = sanitizeOverrides(planNode.resourceCaps);\n this.planResolutionCounter.inc({ result: 'billing' });\n return {\n planName: planNode.planName ?? (tier === 'paid' ? 'paid' : 'free'),\n planTier: tier,\n overrides,\n fetchedAt: Date.now(),\n isFallback: false,\n };\n } catch (err) {\n logger.warn('resource-caps: plan lookup failed; falling back to paid defaults', {\n err,\n userId,\n });\n this.onBillingFailure?.();\n this.planResolutionCounter.inc({ result: 'fallback', reason: 'billing_error' });\n return this.fallbackPlan(this.billingFailureTier, 'billing_error');\n }\n }\n\n /**\n * Resolve the raw `userBillingPlan` node via the injected transport (preferred)\n * or the legacy direct client. Guarded by {@link hasBillingSource} in the\n * caller, so at least one path is present here.\n */\n private async fetchPlanNode(userId: string): Promise<PlanNode | null> {\n if (this.transport) {\n const data = (await this.transport(PLAN_QUERY, { userId })) as PlanQueryResponse | null | undefined;\n return data?.userBillingPlan ?? null;\n }\n if (this.client) {\n const res = await this.client.query<PlanQueryResponse>(PLAN_QUERY, { userId });\n return res?.userBillingPlan ?? null;\n }\n return null;\n }\n\n private warnClientlessOnce(): void {\n if (this.warnedClientless) return;\n this.warnedClientless = true;\n logger.warn(\n 'resource-caps: running WITHOUT a billing transport/client — every resource cap will use the ' +\n 'free-tier fallback regardless of the customer plan. Ensure initializeBurdenoffSDK() ran with a ' +\n 'layer/gateway configured (BOFF-4805).'\n );\n this.onFallback?.();\n }\n\n private fallbackPlan(tier: PlanTier, reason: 'clientless' | 'billing_error'): CachedPlan {\n return {\n planName: tier === 'paid' ? 'fallback-paid' : 'fallback-free',\n planTier: tier,\n overrides: {},\n fetchedAt: Date.now(),\n isFallback: true,\n fallbackReason: reason,\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction normaliseTier(raw: string | null | undefined, fallback: PlanTier): PlanTier {\n if (!raw) return fallback;\n const lc = raw.toLowerCase();\n if (lc === 'free' || lc === 'paid') return lc;\n // Treat anything non-free as paid (enterprise, business, pro, etc.)\n if (lc === 'enterprise' || lc === 'business' || lc === 'pro' || lc === 'team') {\n return 'paid';\n }\n return fallback;\n}\n\nfunction sanitizeOverrides(raw: Record<string, number> | null | undefined): Partial<Record<ResourceName, number>> {\n if (!raw || typeof raw !== 'object') return {};\n const out: Partial<Record<ResourceName, number>> = {};\n for (const [key, value] of Object.entries(raw)) {\n if (key in RESOURCE_CAP_DEFAULTS && typeof value === 'number' && Number.isFinite(value)) {\n out[key as ResourceName] = Math.max(0, Math.floor(value));\n }\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Convenience singleton\n// ---------------------------------------------------------------------------\n\nlet defaultInstance: ResourceCapsModule | null = null;\n\n/**\n * Obtain a process-wide singleton. The first call binds the GraphQL client\n * (typically the SDK's internal client). Later calls return the same instance.\n */\nexport function getResourceCaps(config?: ResourceCapsConfig): ResourceCapsModule {\n if (!defaultInstance) {\n defaultInstance = new ResourceCapsModule(config);\n } else if (config) {\n // Previously the config was silently dropped once the singleton existed —\n // the root cause of BOFF-4805 where the billing client could never be bound\n // after a lazy first construction. Apply it instead.\n defaultInstance.configure(config);\n }\n return defaultInstance;\n}\n\n/**\n * Prime/rebind the process-wide singleton with billing connectivity. Call once\n * during SDK bootstrap. Unlike a bare `getResourceCaps(config)` on a fresh\n * process, this is explicit about the intent to (re)wire and is safe to call\n * after the singleton was already lazily created clientless.\n */\nexport function configureResourceCaps(config: ResourceCapsConfig): ResourceCapsModule {\n const instance = getResourceCaps();\n instance.configure(config);\n return instance;\n}\n\n/** Reset the singleton (for tests) */\nexport function __resetResourceCapsForTests(): void {\n defaultInstance = null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEA,MAAa,wBAAmE;CAC9E,WAAW;EAAE,MAAM;EAAG,aAAa;EAAI,OAAO;CAAO;CACrD,iBAAiB;EAAE,MAAM;EAAK,aAAa;EAAK,OAAO;CAAY;CACnE,SAAS;EAAE,MAAM;EAAG,aAAa;EAAI,OAAO;CAAO;CACnD,MAAM;EAAE,MAAM;EAAI,aAAa;EAAK,OAAO;CAAO;CAClD,OAAO;EAAE,MAAM;EAAG,aAAa;EAAI,OAAO;CAAY;CACtD,cAAc;EAAE,MAAM;EAAI,aAAa;EAAM,OAAO;CAAW;CAC/D,SAAS;EAAE,MAAM;EAAK,aAAa;EAAO,OAAO;CAAW;CAC5D,KAAK;EAAE,MAAM;EAAI,aAAa;EAAM,OAAO;CAAY;CACvD,MAAM;EAAE,MAAM;EAAK,aAAa;EAAO,OAAO;CAAO;CACrD,OAAO;EAAE,MAAM;EAAG,aAAa;EAAK,OAAO;CAAY;CACvD,UAAU;EAAE,MAAM;EAAG,aAAa;EAAK,OAAO;CAAO;CACrD,eAAe;EAAE,MAAM;EAAG,aAAa;EAAK,OAAO;CAAO;CAC1D,MAAM;EAAE,MAAM;EAAG,aAAa;EAAK,OAAO;CAAO;CACjD,QAAQ;EAAE,MAAM;EAAG,aAAa;EAAI,OAAO;CAAO;CAClD,SAAS;EAAE,MAAM;EAAG,aAAa;EAAK,OAAO;CAAY;AAC3D;;;;;;AA0FA,IAAa,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;CAClD,kBAAkB;AACpB"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/resource-caps/index.ts"],"sourcesContent":["/**\n * Resource Caps Module\n *\n * Enforces per-user / per-workspace resource ceilings to prevent unbounded\n * resource use on a multi-tenant SaaS. Caps come from the user's billing plan\n * (resolved via global-billing-svc) and fall back to static defaults defined\n * here when the plan lookup fails or the resource isn't overridden.\n *\n * Two plan tiers exist by default:\n * - free: tight per-user / per-workspace ceilings\n * - paid (default): ~100x looser; individual paid plans can override via the\n * `Plan.resourceCaps` JSON column in global-billing-svc.\n *\n * @example\n * ```ts\n * import { getResourceCaps } from '@burdenoff/be-sdk/resource-caps';\n *\n * // Preferred: enforce atomically inside a serialized Prisma transaction\n * const { result: created } = await getResourceCaps().enforceWithinTransaction({\n * userId,\n * resource: 'vibe',\n * prisma,\n * count: (tx) => tx.vibe.count({ where: { createdBy: userId, deletedAt: null } }),\n * create: (tx) => tx.vibe.create({ data }),\n * });\n * ```\n */\n\nimport { createHash } from 'node:crypto';\nimport { GraphQLError } from 'graphql';\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport { createCounter } from '../instrumentation/metrics-collector.js';\nimport { logger } from '../logger/index.js';\n\n// ---------------------------------------------------------------------------\n// Resource registry\n// ---------------------------------------------------------------------------\n\n/**\n * Canonical resource names. Adding a new capped resource? Append it here,\n * extend RESOURCE_CAP_DEFAULTS, and reference it from the relevant svc.\n */\nexport type ResourceName =\n | 'workspace' // per user\n | 'workspaceMember' // per workspace\n | 'sandbox' // per user\n | 'vibe' // per user\n | 'agent' // per workspace\n | 'conversation' // per user/day\n | 'message' // per user/day\n | 'tag' // per workspace\n | 'file' // per user (count only)\n | 'group' // per workspace\n | 'calendar' // per user\n | 'scheduledTask' // per user\n | 'form' // per user\n | 'apiKey' // per user\n | 'webhook'; // per workspace\n\nexport type PlanTier = 'free' | 'paid';\n\nexport interface ResourceCapDefaults {\n free: number;\n paidDefault: number;\n /** Optional scope hint used by callers when wiring guards */\n scope: 'user' | 'workspace' | 'user/day';\n}\n\n/**\n * Static fallback caps. Real values may be overridden per plan in\n * global-billing-svc Plan.resourceCaps JSON.\n */\nexport const RESOURCE_CAP_DEFAULTS: Record<ResourceName, ResourceCapDefaults> = {\n workspace: { free: 3, paidDefault: 50, scope: 'user' },\n workspaceMember: { free: 500, paidDefault: 500, scope: 'workspace' },\n sandbox: { free: 2, paidDefault: 50, scope: 'user' },\n vibe: { free: 10, paidDefault: 500, scope: 'user' },\n agent: { free: 2, paidDefault: 20, scope: 'workspace' },\n conversation: { free: 20, paidDefault: 2000, scope: 'user/day' },\n message: { free: 200, paidDefault: 20000, scope: 'user/day' },\n tag: { free: 50, paidDefault: 5000, scope: 'workspace' },\n file: { free: 100, paidDefault: 10000, scope: 'user' },\n group: { free: 5, paidDefault: 500, scope: 'workspace' },\n calendar: { free: 3, paidDefault: 100, scope: 'user' },\n scheduledTask: { free: 5, paidDefault: 500, scope: 'user' },\n form: { free: 5, paidDefault: 500, scope: 'user' },\n apiKey: { free: 2, paidDefault: 50, scope: 'user' },\n webhook: { free: 2, paidDefault: 100, scope: 'workspace' },\n};\n\n// ---------------------------------------------------------------------------\n// Types & errors\n// ---------------------------------------------------------------------------\n\nexport interface ResourceCap {\n resource: ResourceName;\n limit: number;\n planName: string;\n planTier: PlanTier;\n /** True when the cap came from defaults, not from the billing service */\n isFallback: boolean;\n /** Why the fallback was used, when isFallback is true */\n fallbackReason?: 'clientless' | 'billing_error';\n}\n\n/**\n * Scope for workspace-scoped resource caps. The cap is derived from the plan of\n * the workspace's owning organization, not from whichever actor happens to be\n * making the request, so two members of the same workspace always see the same\n * limit (BOFF-4808).\n */\nexport interface WorkspaceResourceCapScope {\n /** Stable workspace identifier; used as the cache key. */\n workspaceId: string;\n /**\n * Organization that owns the workspace and whose billing plan determines the\n * cap. This is the `organizationId` from global-tenant-svc's Workspace type\n * (or `orgId` from wspace-workspace-svc's Workspace type).\n */\n organizationId: string;\n}\n\n/**\n * Layer-aware transport for the `userBillingPlan` lookup. Given the GraphQL\n * document + variables, returns the response `data` object (or null). Preferred\n * over `client`: the SDK bootstrap wires this to a same-layer (global) or\n * cross-layer (wspace→global) gateway call so billing is reachable from every\n * service without any per-call-site wiring (BOFF-4805).\n */\nexport type BillingPlanTransport = (query: string, variables: Record<string, unknown>) => Promise<unknown>;\n\nexport interface ResourceCapsConfig {\n client?: BurdenoffGraphQLClient;\n /** Preferred billing lookup path; see {@link BillingPlanTransport}. */\n transport?: BillingPlanTransport;\n /** Optional in-memory TTL for plan lookups; defaults to 60s */\n cacheTtlMs?: number;\n /**\n * Plan tier used when the module has no billing source (clientless). This is\n * the misconfiguration path: services should always bootstrap with a billing\n * transport. Defaults to `free` so a clientless service is visibly broken in\n * tests, while still not hard-blocking local unit tests.\n */\n clientlessTier?: PlanTier;\n /**\n * Plan tier used when a billing source is configured but the lookup fails\n * (network error, billing service down, etc.). Defaults to `paid` so a\n * transient billing outage does not silently downgrade paid customers to the\n * tightest free-tier caps (fail-open with alerting; BOFF-4805/4809).\n */\n billingFailureTier?: PlanTier;\n /**\n * Telemetry hook invoked when the module cannot reach billing (no transport /\n * client) and collapses to the clientless fallback. Wired to a metric counter\n * by observability so an unwired/broken integration is visible (BOFF-4809).\n */\n onFallback?: () => void;\n /**\n * Telemetry hook invoked when a billing source is configured but the lookup\n * fails (billing error fallback to the paid default).\n */\n onBillingFailure?: () => void;\n}\n\ninterface CachedPlan {\n planName: string;\n planTier: PlanTier;\n overrides: Partial<Record<ResourceName, number>>;\n fetchedAt: number;\n isFallback: boolean;\n fallbackReason?: 'clientless' | 'billing_error';\n}\n\n/**\n * Minimal transactional Prisma client surface required for atomic resource-cap\n * enforcement via PostgreSQL transaction-scoped advisory locks.\n */\nexport interface ResourceCapTransactionClient {\n $queryRaw?<T = unknown>(query: TemplateStringsArray, ...values: unknown[]): Promise<T>;\n $executeRaw?(query: TemplateStringsArray, ...values: unknown[]): Promise<unknown>;\n $executeRawUnsafe?(query: string, ...values: unknown[]): Promise<unknown>;\n}\n\n/**\n * Minimal Prisma client interface supporting interactive transactions.\n */\nexport interface ResourceCapPrismaLike<TTx extends ResourceCapTransactionClient = ResourceCapTransactionClient> {\n $transaction<T>(\n fn: (tx: TTx) => Promise<T>,\n options?: { maxWait?: number; timeout?: number; isolationLevel?: string }\n ): Promise<T>;\n}\n\nexport interface EnforceWithinTransactionOptions<TTx extends ResourceCapTransactionClient, TResult> {\n userId: string;\n resource: ResourceName;\n prisma: ResourceCapPrismaLike<TTx>;\n /** Count existing resources INSIDE the locked transaction. */\n count: (tx: TTx) => Promise<number>;\n /** Insert the resource INSIDE the same locked transaction after the cap passes. */\n create: (tx: TTx, cap: ResourceCap) => Promise<TResult>;\n /** Optional custom lock scope key (defaults to `user:${userId}`). */\n lockScopeKey?: string;\n /** Optional Prisma `$transaction` options (e.g. timeout, maxWait, isolationLevel). */\n transactionOptions?: { maxWait?: number; timeout?: number; isolationLevel?: string };\n}\n\nexport interface EnforceWorkspaceWithinTransactionOptions<TTx extends ResourceCapTransactionClient, TResult> {\n scope: WorkspaceResourceCapScope;\n resource: ResourceName;\n prisma: ResourceCapPrismaLike<TTx>;\n /** Count existing workspace resources INSIDE the locked transaction. */\n count: (tx: TTx) => Promise<number>;\n /** Insert the resource INSIDE the same locked transaction after the cap passes. */\n create: (tx: TTx, cap: ResourceCap) => Promise<TResult>;\n /** Optional Prisma `$transaction` options (e.g. timeout, maxWait, isolationLevel). */\n transactionOptions?: { maxWait?: number; timeout?: number; isolationLevel?: string };\n}\n\n/**\n * Atomic counter store for cross-store resource-cap reservations (e.g.,\n * sandboxes or external provisioning that cannot share a single PostgreSQL\n * transaction). Satisfied by `ICacheProvider` (Valkey/Memory) and optional\n * Lua-capable Redis/Valkey clients.\n */\nexport interface ResourceCapReservationStore {\n increment(key: string, amount?: number): Promise<number>;\n decrement(key: string, amount?: number): Promise<number>;\n expire(key: string, ttlSeconds: number): Promise<boolean>;\n expireNX?(key: string, ttlSeconds: number): Promise<boolean>;\n /**\n * Optional single-round-trip Lua script evaluator. When supplied,\n * {@link RESOURCE_CAP_RESERVE_LUA} executes atomically server-side.\n */\n evalScript?(script: string, keys: string[], args: string[]): Promise<number>;\n}\n\n/**\n * Atomic Valkey/Redis Lua script for cross-store cap reservation.\n *\n * KEYS[1]: reservation counter key\n * ARGV[1]: baseCount (authoritative persisted count observed prior to reserve)\n * ARGV[2]: limit (cap.limit)\n * ARGV[3]: amount to reserve (usually 1)\n * ARGV[4]: ttlSeconds (safety expiry so crashed workers never leak slots forever)\n *\n * Returns the new total reserved count on success, or -1 if reserving would\n * exceed `limit`.\n */\nexport const RESOURCE_CAP_RESERVE_LUA = `\nlocal current = tonumber(redis.call('GET', KEYS[1]) or '0')\nlocal baseCount = tonumber(ARGV[1])\nlocal limit = tonumber(ARGV[2])\nlocal delta = tonumber(ARGV[3])\nlocal ttl = tonumber(ARGV[4])\nif (baseCount + current + delta) > limit then\n return -1\nend\nlocal nextVal = redis.call('INCRBY', KEYS[1], delta)\nredis.call('EXPIRE', KEYS[1], ttl)\nreturn nextVal\n`.trim();\n\nexport interface ReserveResourceCapOptions {\n store: ResourceCapReservationStore;\n /** Current persisted count from the authoritative store. */\n baseCount: number;\n /** Number of slots to reserve (default: 1). */\n amount?: number;\n /** Safety TTL in seconds so crashed callers never leak slots permanently (default: 120). */\n ttlSeconds?: number;\n /** Optional key prefix (default: 'rcap:res'). */\n keyPrefix?: string;\n}\n\nexport interface ResourceCapReservation {\n readonly cap: ResourceCap;\n readonly key: string;\n readonly amount: number;\n /** Mark the create as persisted and release the in-flight reservation slot. */\n commit(): Promise<void>;\n /** Release the in-flight reservation slot after a failed create. */\n release(): Promise<void>;\n}\n\n/**\n * Derive two deterministic signed 32-bit PostgreSQL advisory-lock keys for a\n * `(scopeKey, resource)` pair so `pg_advisory_xact_lock(int4, int4)` serializes\n * concurrent creates for the same scope and resource without blocking unrelated\n * tenants or resources.\n */\nexport function computeResourceCapLockKeys(scopeKey: string, resource: ResourceName): [number, number] {\n const digest = createHash('sha256').update(`boff:rcap:${scopeKey}:${resource}`).digest();\n return [digest.readInt32BE(0), digest.readInt32BE(4)];\n}\n\n/**\n * Acquire a transaction-scoped PostgreSQL advisory lock for `(scopeKey, resource)`\n * inside an active Prisma interactive transaction. The lock is held until the\n * transaction commits or rolls back.\n */\nexport async function acquireResourceCapAdvisoryLock(\n tx: ResourceCapTransactionClient,\n scopeKey: string,\n resource: ResourceName\n): Promise<[number, number]> {\n const [key1, key2] = computeResourceCapLockKeys(scopeKey, resource);\n if (typeof tx.$queryRaw === 'function') {\n await tx.$queryRaw`SELECT pg_advisory_xact_lock(${key1}::int4, ${key2}::int4)`;\n return [key1, key2];\n }\n if (typeof tx.$executeRaw === 'function') {\n await tx.$executeRaw`SELECT pg_advisory_xact_lock(${key1}::int4, ${key2}::int4)`;\n return [key1, key2];\n }\n if (typeof tx.$executeRawUnsafe === 'function') {\n await tx.$executeRawUnsafe('SELECT pg_advisory_xact_lock($1::int4, $2::int4)', key1, key2);\n return [key1, key2];\n }\n throw new Error(\n 'acquireResourceCapAdvisoryLock: transaction client must provide $queryRaw, $executeRaw, or $executeRawUnsafe'\n );\n}\n\n/**\n * Thrown when an entity create operation would push the user past the cap.\n * The matching GraphQL error has extensions.code = RESOURCE_CAP_EXCEEDED\n * so clients can detect and route to an upgrade flow.\n */\nexport class ResourceCapExceededError extends GraphQLError {\n constructor(detail: { resource: ResourceName; currentCount: number; limit: number; planName: string }) {\n super(\n `Resource cap exceeded for ${detail.resource}: ${detail.currentCount}/${detail.limit} on plan '${detail.planName}'.`,\n {\n extensions: {\n code: 'RESOURCE_CAP_EXCEEDED',\n userMessage: \"You've reached your plan limit. Upgrade your plan to continue.\",\n technicalMessage: `Resource cap exceeded for ${detail.resource}: ${detail.currentCount}/${detail.limit} on plan '${detail.planName}'.`,\n resource: detail.resource,\n currentCount: detail.currentCount,\n limit: detail.limit,\n planName: detail.planName,\n },\n }\n );\n this.name = 'ResourceCapExceededError';\n }\n}\n\n// ---------------------------------------------------------------------------\n// Module\n// ---------------------------------------------------------------------------\n\nconst PLAN_QUERY = /* GraphQL */ `\n query GetUserPlanForCaps($userId: ID!) {\n userBillingPlan(userId: $userId) {\n planName\n tier\n resourceCaps\n }\n }\n`;\n\ninterface PlanQueryResponse {\n userBillingPlan?: {\n planName?: string | null;\n tier?: string | null;\n resourceCaps?: Record<string, number> | null;\n } | null;\n}\n\ntype PlanNode = NonNullable<PlanQueryResponse['userBillingPlan']>;\n\nexport class ResourceCapsModule {\n private client?: BurdenoffGraphQLClient;\n private transport?: BillingPlanTransport;\n private cacheTtlMs: number;\n private clientlessTier: PlanTier;\n private billingFailureTier: PlanTier;\n private onFallback?: () => void;\n private onBillingFailure?: () => void;\n private warnedClientless = false;\n private readonly planCache = new Map<string, CachedPlan>();\n private readonly planResolutionCounter;\n private readonly enforcementCounter;\n\n constructor(config: ResourceCapsConfig = {}) {\n this.client = config.client;\n this.transport = config.transport;\n this.cacheTtlMs = config.cacheTtlMs ?? 60_000;\n this.clientlessTier = config.clientlessTier ?? 'free';\n this.billingFailureTier = config.billingFailureTier ?? 'paid';\n this.onFallback = config.onFallback;\n this.onBillingFailure = config.onBillingFailure;\n this.planResolutionCounter = createCounter(\n 'resource_caps.plan_resolution_total',\n 'Total number of billing plan resolutions for resource caps'\n );\n this.enforcementCounter = createCounter(\n 'resource_caps.enforcement_total',\n 'Total number of resource cap enforcement checks'\n );\n }\n\n /**\n * (Re)bind runtime dependencies on an already-constructed module. The SDK\n * bootstrap uses this to prime the process-wide singleton with a billing\n * transport even if an early caller already lazily created it clientless\n * (a bare `getResourceCaps(config)` ignores config once the instance exists).\n * Clears the plan cache so stale fallback entries don't linger.\n */\n configure(config: ResourceCapsConfig): void {\n if (config.client !== undefined) this.client = config.client;\n if (config.transport !== undefined) this.transport = config.transport;\n if (config.onFallback !== undefined) this.onFallback = config.onFallback;\n if (config.onBillingFailure !== undefined) this.onBillingFailure = config.onBillingFailure;\n if (typeof config.cacheTtlMs === 'number') this.cacheTtlMs = config.cacheTtlMs;\n if (config.clientlessTier) this.clientlessTier = config.clientlessTier;\n if (config.billingFailureTier) this.billingFailureTier = config.billingFailureTier;\n if (this.hasBillingSource()) this.warnedClientless = false;\n this.planCache.clear();\n }\n\n /** True when the module can actually reach billing (has a transport or client). */\n hasBillingSource(): boolean {\n return Boolean(this.transport || this.client);\n }\n\n /**\n * Resolve the cap for a given resource for the supplied user.\n * Order: plan-override → plan-tier-default → static free default.\n */\n async getResourceCap(userId: string, resource: ResourceName): Promise<ResourceCap> {\n if (!userId) {\n throw new Error('getResourceCap: userId is required');\n }\n const defaults = RESOURCE_CAP_DEFAULTS[resource];\n if (!defaults) {\n throw new Error(`getResourceCap: unknown resource '${resource}'`);\n }\n\n const plan = await this.resolvePlan(userId);\n const override = plan.overrides[resource];\n if (typeof override === 'number' && override >= 0) {\n return {\n resource,\n limit: override,\n planName: plan.planName,\n planTier: plan.planTier,\n isFallback: plan.isFallback,\n fallbackReason: plan.fallbackReason,\n };\n }\n\n const limit = plan.planTier === 'paid' ? defaults.paidDefault : defaults.free;\n return {\n resource,\n limit,\n planName: plan.planName,\n planTier: plan.planTier,\n isFallback: plan.isFallback,\n fallbackReason: plan.fallbackReason,\n };\n }\n\n /**\n * Compare a caller-supplied count against a resolved {@link ResourceCap} and\n * throw {@link ResourceCapExceededError} when `currentCount >= cap.limit`.\n *\n * Safe ONLY when `currentCount` was measured inside the same serialized\n * transaction (after {@link acquireResourceCapAdvisoryLock} or under\n * `Serializable` isolation) as the insert.\n */\n assertWithinCap(cap: ResourceCap, currentCount: number): ResourceCap {\n if (currentCount >= cap.limit) {\n this.enforcementCounter.inc({\n resource: cap.resource,\n plan_tier: cap.planTier,\n result: 'denied',\n });\n throw new ResourceCapExceededError({\n resource: cap.resource,\n currentCount,\n limit: cap.limit,\n planName: cap.planName,\n });\n }\n this.enforcementCounter.inc({\n resource: cap.resource,\n plan_tier: cap.planTier,\n result: 'allowed',\n });\n return cap;\n }\n\n /**\n * Throws ResourceCapExceededError when currentCount >= limit.\n *\n * @deprecated Non-atomic when called outside a serialized transaction: concurrent\n * creates can observe the same stale `currentCount` and bypass plan quotas (BOFF-16045).\n * Use {@link enforceWithinTransaction} (for PostgreSQL/Prisma creates) or\n * {@link reserveResourceCap} / {@link withReservedResourceCap} (for cross-store creates).\n * If you manage your own Prisma transaction, pre-resolve {@link getResourceCap},\n * call {@link acquireResourceCapAdvisoryLock} inside `$transaction`, count, and\n * call {@link assertWithinCap}.\n */\n async enforceResourceCap(userId: string, resource: ResourceName, currentCount: number): Promise<ResourceCap> {\n const cap = await this.getResourceCap(userId, resource);\n return this.assertWithinCap(cap, currentCount);\n }\n\n /**\n * Atomically enforce a user-scoped resource cap and insert the resource inside\n * a single Prisma transaction serialized by a per-`(user, resource)` PostgreSQL\n * advisory lock (`pg_advisory_xact_lock`).\n *\n * The billing plan cap is pre-resolved BEFORE opening the transaction so no\n * external RPC runs while holding database locks.\n */\n async enforceWithinTransaction<TTx extends ResourceCapTransactionClient, TResult>(\n options: EnforceWithinTransactionOptions<TTx, TResult>\n ): Promise<{ result: TResult; cap: ResourceCap }> {\n const { userId, resource, prisma, count, create, lockScopeKey, transactionOptions } = options;\n const cap = await this.getResourceCap(userId, resource);\n const scopeKey = lockScopeKey ?? `user:${userId}`;\n\n const result = await prisma.$transaction(async (tx) => {\n await acquireResourceCapAdvisoryLock(tx, scopeKey, resource);\n const currentCount = await count(tx);\n this.assertWithinCap(cap, currentCount);\n return create(tx, cap);\n }, transactionOptions);\n\n return { result, cap };\n }\n\n /**\n * Atomically enforce a workspace-scoped resource cap and insert the resource\n * inside a single Prisma transaction serialized by a per-`(workspace, resource)`\n * PostgreSQL advisory lock (`pg_advisory_xact_lock`).\n */\n async enforceWorkspaceWithinTransaction<TTx extends ResourceCapTransactionClient, TResult>(\n options: EnforceWorkspaceWithinTransactionOptions<TTx, TResult>\n ): Promise<{ result: TResult; cap: ResourceCap }> {\n const { scope, resource, prisma, count, create, transactionOptions } = options;\n const cap = await this.getWorkspaceResourceCap(scope, resource);\n const scopeKey = `workspace:${scope.workspaceId}`;\n\n const result = await prisma.$transaction(async (tx) => {\n await acquireResourceCapAdvisoryLock(tx, scopeKey, resource);\n const currentCount = await count(tx);\n this.assertWithinCap(cap, currentCount);\n return create(tx, cap);\n }, transactionOptions);\n\n return { result, cap };\n }\n\n /**\n * Atomically reserve a user-scoped resource cap slot in Valkey/Redis for\n * cross-store creates (e.g., sandboxes) that cannot share one SQL transaction.\n * Always call `reservation.commit()` on success or `reservation.release()` on\n * failure, or prefer {@link withReservedResourceCap}.\n */\n async reserveResourceCap(\n userId: string,\n resource: ResourceName,\n options: ReserveResourceCapOptions\n ): Promise<ResourceCapReservation> {\n const cap = await this.getResourceCap(userId, resource);\n return this.reserveWithResolvedCap(cap, `user:${userId}`, options);\n }\n\n /**\n * Atomically reserve a workspace-scoped resource cap slot in Valkey/Redis for\n * cross-store creates.\n */\n async reserveWorkspaceResourceCap(\n scope: WorkspaceResourceCapScope,\n resource: ResourceName,\n options: ReserveResourceCapOptions\n ): Promise<ResourceCapReservation> {\n const cap = await this.getWorkspaceResourceCap(scope, resource);\n return this.reserveWithResolvedCap(cap, `workspace:${scope.workspaceId}`, options);\n }\n\n /**\n * Reserve a user-scoped cap slot, run `action`, commit on success, and\n * automatically release the slot if `action` throws.\n */\n async withReservedResourceCap<TResult>(\n userId: string,\n resource: ResourceName,\n options: ReserveResourceCapOptions,\n action: (cap: ResourceCap) => Promise<TResult>\n ): Promise<{ result: TResult; cap: ResourceCap }> {\n const reservation = await this.reserveResourceCap(userId, resource, options);\n try {\n const result = await action(reservation.cap);\n await reservation.commit();\n return { result, cap: reservation.cap };\n } catch (error) {\n await reservation.release();\n throw error;\n }\n }\n\n private async reserveWithResolvedCap(\n cap: ResourceCap,\n scopeKey: string,\n options: ReserveResourceCapOptions\n ): Promise<ResourceCapReservation> {\n const amount = Math.max(1, Math.floor(options.amount ?? 1));\n const ttlSeconds = Math.max(1, Math.floor(options.ttlSeconds ?? 120));\n const prefix = options.keyPrefix ?? 'rcap:res';\n const key = `${prefix}:${scopeKey}:${cap.resource}`;\n const baseCount = Math.max(0, Math.floor(options.baseCount));\n\n if (typeof options.store.evalScript === 'function') {\n const reserved = await options.store.evalScript(\n RESOURCE_CAP_RESERVE_LUA,\n [key],\n [String(baseCount), String(cap.limit), String(amount), String(ttlSeconds)]\n );\n if (reserved < 0) {\n this.enforcementCounter.inc({\n resource: cap.resource,\n plan_tier: cap.planTier,\n result: 'denied',\n });\n throw new ResourceCapExceededError({\n resource: cap.resource,\n currentCount: cap.limit,\n limit: cap.limit,\n planName: cap.planName,\n });\n }\n } else {\n const inFlightAfterIncrement = await options.store.increment(key, amount);\n await options.store.expire(key, ttlSeconds);\n if (baseCount + inFlightAfterIncrement > cap.limit) {\n await options.store.decrement(key, amount).catch(() => undefined);\n this.enforcementCounter.inc({\n resource: cap.resource,\n plan_tier: cap.planTier,\n result: 'denied',\n });\n throw new ResourceCapExceededError({\n resource: cap.resource,\n currentCount: baseCount + inFlightAfterIncrement - amount,\n limit: cap.limit,\n planName: cap.planName,\n });\n }\n }\n\n this.enforcementCounter.inc({\n resource: cap.resource,\n plan_tier: cap.planTier,\n result: 'allowed',\n });\n\n let settled = false;\n const releaseOnce = async (): Promise<void> => {\n if (settled) return;\n settled = true;\n await options.store.decrement(key, amount).catch(() => undefined);\n };\n\n return {\n cap,\n key,\n amount,\n commit: releaseOnce,\n release: releaseOnce,\n };\n }\n\n /**\n * Resolve a workspace-scoped resource cap from the workspace's owner\n * organization plan, regardless of which actor triggered the action.\n *\n * @example\n * ```ts\n * const { limit } = await caps.getWorkspaceResourceCap(\n * { workspaceId: 'ws-1', organizationId: 'org-1' },\n * 'group'\n * );\n * ```\n */\n async getWorkspaceResourceCap(scope: WorkspaceResourceCapScope, resource: ResourceName): Promise<ResourceCap> {\n const { workspaceId, organizationId } = scope;\n if (!workspaceId) {\n throw new Error('getWorkspaceResourceCap: workspaceId is required');\n }\n if (!organizationId) {\n throw new Error('getWorkspaceResourceCap: organizationId is required');\n }\n const defaults = RESOURCE_CAP_DEFAULTS[resource];\n if (!defaults) {\n throw new Error(`getWorkspaceResourceCap: unknown resource '${resource}'`);\n }\n\n const plan = await this.resolvePlan(organizationId, this.workspaceCacheKey(workspaceId));\n const override = plan.overrides[resource];\n if (typeof override === 'number' && override >= 0) {\n return {\n resource,\n limit: override,\n planName: plan.planName,\n planTier: plan.planTier,\n isFallback: plan.isFallback,\n fallbackReason: plan.fallbackReason,\n };\n }\n\n const limit = plan.planTier === 'paid' ? defaults.paidDefault : defaults.free;\n return {\n resource,\n limit,\n planName: plan.planName,\n planTier: plan.planTier,\n isFallback: plan.isFallback,\n fallbackReason: plan.fallbackReason,\n };\n }\n\n /**\n * Throws ResourceCapExceededError when currentCount >= limit for a\n * workspace-scoped resource. The cap is resolved from the workspace owner's\n * organization plan, so the answer is stable across members.\n *\n * @deprecated Non-atomic when called outside a serialized transaction (BOFF-16045).\n * Prefer {@link enforceWorkspaceWithinTransaction} or {@link reserveWorkspaceResourceCap}.\n */\n async enforceWorkspaceResourceCap(\n scope: WorkspaceResourceCapScope,\n resource: ResourceName,\n currentCount: number\n ): Promise<ResourceCap> {\n const cap = await this.getWorkspaceResourceCap(scope, resource);\n return this.assertWithinCap(cap, currentCount);\n }\n\n /** Invalidate cache for a user (e.g. after plan upgrade) */\n invalidate(userId: string): void {\n this.planCache.delete(userId);\n }\n\n /** Invalidate cache for a workspace (e.g. after workspace plan change) */\n invalidateWorkspace(workspaceId: string): void {\n this.planCache.delete(this.workspaceCacheKey(workspaceId));\n }\n\n /** Clear entire plan cache */\n invalidateAll(): void {\n this.planCache.clear();\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private workspaceCacheKey(workspaceId: string): string {\n return `workspace:${workspaceId}`;\n }\n\n private async resolvePlan(userId: string, cacheKey?: string): Promise<CachedPlan> {\n const key = cacheKey ?? userId;\n const cached = this.planCache.get(key);\n if (cached && Date.now() - cached.fetchedAt < this.cacheTtlMs) {\n return cached;\n }\n\n const plan = await this.fetchPlan(userId);\n this.planCache.set(key, plan);\n return plan;\n }\n\n private async fetchPlan(userId: string): Promise<CachedPlan> {\n // No billing source wired → every cap silently collapses to the configured\n // clientless tier. Warn loudly (once) so an unwired/broken integration\n // can't hide in prod (BOFF-4805/4809).\n if (!this.hasBillingSource()) {\n this.warnClientlessOnce();\n this.planResolutionCounter.inc({ result: 'fallback', reason: 'clientless' });\n return this.fallbackPlan(this.clientlessTier, 'clientless');\n }\n try {\n const planNode = await this.fetchPlanNode(userId);\n if (!planNode) {\n logger.warn('resource-caps: plan lookup returned null; falling back to paid defaults', {\n userId,\n });\n this.onBillingFailure?.();\n this.planResolutionCounter.inc({ result: 'fallback', reason: 'billing_error' });\n return this.fallbackPlan(this.billingFailureTier, 'billing_error');\n }\n const tier = normaliseTier(planNode.tier, this.billingFailureTier);\n const overrides = sanitizeOverrides(planNode.resourceCaps);\n this.planResolutionCounter.inc({ result: 'billing' });\n return {\n planName: planNode.planName ?? (tier === 'paid' ? 'paid' : 'free'),\n planTier: tier,\n overrides,\n fetchedAt: Date.now(),\n isFallback: false,\n };\n } catch (err) {\n logger.warn('resource-caps: plan lookup failed; falling back to paid defaults', {\n err,\n userId,\n });\n this.onBillingFailure?.();\n this.planResolutionCounter.inc({ result: 'fallback', reason: 'billing_error' });\n return this.fallbackPlan(this.billingFailureTier, 'billing_error');\n }\n }\n\n /**\n * Resolve the raw `userBillingPlan` node via the injected transport (preferred)\n * or the legacy direct client. Guarded by {@link hasBillingSource} in the\n * caller, so at least one path is present here.\n */\n private async fetchPlanNode(userId: string): Promise<PlanNode | null> {\n if (this.transport) {\n const data = (await this.transport(PLAN_QUERY, { userId })) as PlanQueryResponse | null | undefined;\n return data?.userBillingPlan ?? null;\n }\n if (this.client) {\n const res = await this.client.query<PlanQueryResponse>(PLAN_QUERY, { userId });\n return res?.userBillingPlan ?? null;\n }\n return null;\n }\n\n private warnClientlessOnce(): void {\n if (this.warnedClientless) return;\n this.warnedClientless = true;\n logger.warn(\n 'resource-caps: running WITHOUT a billing transport/client — every resource cap will use the ' +\n 'free-tier fallback regardless of the customer plan. Ensure initializeBurdenoffSDK() ran with a ' +\n 'layer/gateway configured (BOFF-4805).'\n );\n this.onFallback?.();\n }\n\n private fallbackPlan(tier: PlanTier, reason: 'clientless' | 'billing_error'): CachedPlan {\n return {\n planName: tier === 'paid' ? 'fallback-paid' : 'fallback-free',\n planTier: tier,\n overrides: {},\n fetchedAt: Date.now(),\n isFallback: true,\n fallbackReason: reason,\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction normaliseTier(raw: string | null | undefined, fallback: PlanTier): PlanTier {\n if (!raw) return fallback;\n const lc = raw.toLowerCase();\n if (lc === 'free' || lc === 'paid') return lc;\n // Treat anything non-free as paid (enterprise, business, pro, etc.)\n if (lc === 'enterprise' || lc === 'business' || lc === 'pro' || lc === 'team') {\n return 'paid';\n }\n return fallback;\n}\n\nfunction sanitizeOverrides(raw: Record<string, number> | null | undefined): Partial<Record<ResourceName, number>> {\n if (!raw || typeof raw !== 'object') return {};\n const out: Partial<Record<ResourceName, number>> = {};\n for (const [key, value] of Object.entries(raw)) {\n if (key in RESOURCE_CAP_DEFAULTS && typeof value === 'number' && Number.isFinite(value)) {\n out[key as ResourceName] = Math.max(0, Math.floor(value));\n }\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Convenience singleton\n// ---------------------------------------------------------------------------\n\nlet defaultInstance: ResourceCapsModule | null = null;\n\n/**\n * Obtain a process-wide singleton. The first call binds the GraphQL client\n * (typically the SDK's internal client). Later calls return the same instance.\n */\nexport function getResourceCaps(config?: ResourceCapsConfig): ResourceCapsModule {\n if (!defaultInstance) {\n defaultInstance = new ResourceCapsModule(config);\n } else if (config) {\n // Previously the config was silently dropped once the singleton existed —\n // the root cause of BOFF-4805 where the billing client could never be bound\n // after a lazy first construction. Apply it instead.\n defaultInstance.configure(config);\n }\n return defaultInstance;\n}\n\n/**\n * Prime/rebind the process-wide singleton with billing connectivity. Call once\n * during SDK bootstrap. Unlike a bare `getResourceCaps(config)` on a fresh\n * process, this is explicit about the intent to (re)wire and is safe to call\n * after the singleton was already lazily created clientless.\n */\nexport function configureResourceCaps(config: ResourceCapsConfig): ResourceCapsModule {\n const instance = getResourceCaps();\n instance.configure(config);\n return instance;\n}\n\n/** Reset the singleton (for tests) */\nexport function __resetResourceCapsForTests(): void {\n defaultInstance = null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyEA,MAAa,wBAAmE;CAC9E,WAAW;EAAE,MAAM;EAAG,aAAa;EAAI,OAAO;CAAO;CACrD,iBAAiB;EAAE,MAAM;EAAK,aAAa;EAAK,OAAO;CAAY;CACnE,SAAS;EAAE,MAAM;EAAG,aAAa;EAAI,OAAO;CAAO;CACnD,MAAM;EAAE,MAAM;EAAI,aAAa;EAAK,OAAO;CAAO;CAClD,OAAO;EAAE,MAAM;EAAG,aAAa;EAAI,OAAO;CAAY;CACtD,cAAc;EAAE,MAAM;EAAI,aAAa;EAAM,OAAO;CAAW;CAC/D,SAAS;EAAE,MAAM;EAAK,aAAa;EAAO,OAAO;CAAW;CAC5D,KAAK;EAAE,MAAM;EAAI,aAAa;EAAM,OAAO;CAAY;CACvD,MAAM;EAAE,MAAM;EAAK,aAAa;EAAO,OAAO;CAAO;CACrD,OAAO;EAAE,MAAM;EAAG,aAAa;EAAK,OAAO;CAAY;CACvD,UAAU;EAAE,MAAM;EAAG,aAAa;EAAK,OAAO;CAAO;CACrD,eAAe;EAAE,MAAM;EAAG,aAAa;EAAK,OAAO;CAAO;CAC1D,MAAM;EAAE,MAAM;EAAG,aAAa;EAAK,OAAO;CAAO;CACjD,QAAQ;EAAE,MAAM;EAAG,aAAa;EAAI,OAAO;CAAO;CAClD,SAAS;EAAE,MAAM;EAAG,aAAa;EAAK,OA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kBAAkB;EAC3B,KAAK,mBAAmB;EACxB,OAAO,KACL,kOAGF;EACA,KAAK,aAAa;CACpB;CAEA,AAAQ,aAAa,MAAgB,QAAoD;EACvF,OAAO;GACL,UAAU,SAAS,SAAS,kBAAkB;GAC9C,UAAU;GACV,WAAW,CAAC;GACZ,WAAW,KAAK,IAAI;GACpB,YAAY;GACZ,gBAAgB;EAClB;CACF;AACF;AAMA,SAAS,cAAc,KAAgC,UAA8B;CACnF,IAAI,CAAC,KAAK,OAAO;CACjB,MAAM,KAAK,IAAI,YAAY;CAC3B,IAAI,OAAO,UAAU,OAAO,QAAQ,OAAO;CAE3C,IAAI,OAAO,gBAAgB,OAAO,cAAc,OAAO,SAAS,OAAO,QACrE,OAAO;CAET,OAAO;AACT;AAEA,SAAS,kBAAkB,KAAuF;CAChH,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO,CAAC;CAC7C,MAAM,MAA6C,CAAC;CACpD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,GAAG,GAC3C,IAAI,OAAO,yBAAyB,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,GACpF,IAAI,OAAuB,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC;CAG5D,OAAO;AACT;AAMA,IAAI,kBAA6C;;;;;AAMjD,SAAgB,gBAAgB,QAAiD;CAC/E,IAAI,CAAC,iBACH,kBAAkB,IAAI,mBAAmB,MAAM;MAC1C,IAAI,QAIT,gBAAgB,UAAU,MAAM;CAElC,OAAO;AACT;;;;;;;AAQA,SAAgB,sBAAsB,QAAgD;CACpF,MAAM,WAAW,gBAAgB;CACjC,SAAS,UAAU,MAAM;CACzB,OAAO;AACT;;AAGA,SAAgB,8BAAoC;CAClD,kBAAkB;AACpB"}
@@ -1,2 +1,2 @@
1
- import { t as index_d_exports } from "../index-DhFP_AIB.js";
1
+ import { t as index_d_exports } from "../index-DkitHCtV.js";
2
2
  export { index_d_exports as RateLimit };
@@ -1,4 +1,4 @@
1
- import { t as rate_limit_exports } from "../rate-limit-CBrK_U5H.js";
1
+ import { t as rate_limit_exports } from "../rate-limit-ISSpByjW.js";
2
2
 
3
3
  export { rate_limit_exports as RateLimit };
4
4
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- import { a as resolveRateLimitModeFromEnv, c as RateLimitResult, i as enforceRateLimit, l as buildRateLimitKey, n as RateLimiterDeps, o as RateLimitConfig, r as checkRateLimit, s as RateLimitMode } from "../../index-DhFP_AIB.js";
1
+ import { a as resolveRateLimitModeFromEnv, c as RateLimitResult, i as enforceRateLimit, l as buildRateLimitKey, n as RateLimiterDeps, o as RateLimitConfig, r as checkRateLimit, s as RateLimitMode } from "../../index-DkitHCtV.js";
2
2
  export { type RateLimitConfig, type RateLimitMode, type RateLimitResult, type RateLimiterDeps, buildRateLimitKey, checkRateLimit, enforceRateLimit, resolveRateLimitModeFromEnv };
@@ -1,4 +1,4 @@
1
- import { a as buildRateLimitKey, i as resolveRateLimitModeFromEnv, n as checkRateLimit, r as enforceRateLimit } from "../../rate-limit-CBrK_U5H.js";
1
+ import { a as buildRateLimitKey, i as resolveRateLimitModeFromEnv, n as checkRateLimit, r as enforceRateLimit } from "../../rate-limit-ISSpByjW.js";
2
2
 
3
3
  export { buildRateLimitKey, checkRateLimit, enforceRateLimit, resolveRateLimitModeFromEnv };
4
4
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
- import { C as VerifiedDelegationContext, D as WorkspaceGuardConfig, E as YogaPlugin, O as WorkspaceMembershipValidation, S as ServerInstance, T as WspaceGraphQLContext, _ as RESTEndpoint, a as IActor, b as ServerI18nConfig, c as IOrganization, d as ITenant, f as ITracking, g as PrismaClientConstructor, h as ModuleGraphConfig, i as GraphQLContext, k as createWorkspaceGuardPlugin, l as IProduct, m as JWTPayload, n as ConsentContext, o as IContextFilterInput, p as IWorkspace, r as ElysiaApp, s as IOperationContext, t as ActorProvenance, u as IProject, v as ServerConfig, w as WorkspaceSecret, x as ServerInfo, y as ServerDefinition } from "../types-De_pO1Wz.js";
2
- import { n as PrismaClientBase } from "../client-BgAEvDC2.js";
1
+ import { C as VerifiedDelegationContext, D as WorkspaceGuardConfig, E as YogaPlugin, O as WorkspaceMembershipValidation, S as ServerInstance, T as WspaceGraphQLContext, _ as RESTEndpoint, a as IActor, b as ServerI18nConfig, c as IOrganization, d as ITenant, f as ITracking, g as PrismaClientConstructor, h as ModuleGraphConfig, i as GraphQLContext, k as createWorkspaceGuardPlugin, l as IProduct, m as JWTPayload, n as ConsentContext, o as IContextFilterInput, p as IWorkspace, r as ElysiaApp, s as IOperationContext, t as ActorProvenance, u as IProject, v as ServerConfig, w as WorkspaceSecret, x as ServerInfo, y as ServerDefinition } from "../types-BWN8tMdF.js";
2
+ import { n as PrismaClientBase } from "../client-NknQrWsP.js";
3
3
  import { a as ActorOrigin, c as readAssistantSessionAttribution, i as ASSISTANT_SESSION_ID_HEADER, l as toAssistantSessionAttribution, n as AI_ASSISTANT_ACTOR_ORIGIN, o as AssistantSessionAttribution, r as ASSISTANT_CORRELATION_ID_HEADER, s as parseAssistantSessionHeaders, t as ACTOR_ORIGIN_HEADER } from "../assistant-session-DA5ZKJOr.js";
4
4
  import { r as I18nContext, s as LocaleCode } from "../types-DgaQqvxo.js";
5
- import { $ as configureDefaultAuth, A as assertDsarOrchestrator, B as getContextOptions, C as DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, D as DsarOrchestratorRejectionReason, E as DsarOrchestratorOptions, F as getDelegatedPrincipal, G as createRawBodyRouter, H as OrdinaryRoute, I as resolveOnBehalfOf, J as createServer, K as extendRequestIdleTimeout, L as ContextBuilderOptions, M as isDsarOrchestratorActor, N as resolveDsarCallerIdentity, O as ResolvedDsarCaller, P as DelegatedPrincipal, Q as configureAuth, R as buildContext, S as DSAR_ALLOWED_ORCHESTRATORS_ENV, T as DsarOrchestratorForbiddenError, U as RawBodyResolution, V as MAX_IDLE_TIMEOUT_SECONDS, W as RawBodyRouter, X as FetchWorkspaceSecretFn, Y as AuthConfig, Z as authCheck, _ as MutationAuditPluginOptions, a as UserFacingErrorOptions, at as tenantCheck, b as sanitizeAuditValue, c as createHumanReadableErrorPlugin, d as normalizeExecutionResultErrors, et as decodeJWT, f as normalizeGraphQLResponse, g as MUTATION_AUDIT_RESOURCE_TYPE, h as MUTATION_AUDIT_ACTIVITY_TYPE, i as NormalizedErrorState, it as requireWorkspace, j as getAllowedDsarOrchestrators, k as VERIFIED_SERVICE_IDENTITY_HEADER, l as formatHttpError, m as toUserFacingGraphQLError, n as HttpErrorPayload, nt as generateSymmetricSecret, o as UserFacingGraphQLError, ot as verifyJWT, p as normalizeGraphQLResponsePayload, q as configureServerAuth, r as HttpErrorResult, rt as orgCheck, s as createHttpErrorResponse, st as workspaceCheck, t as ErrorNormalizationOptions, tt as fetchWorkspaceSecret, u as normalizeError, v as createMutationAuditPlugin, w as DsarOrchestratorContext, x as DEFAULT_DSAR_ORCHESTRATOR_ID, y as getMutationFieldNames, z as configureContext } from "../index-CzMD97-N.js";
5
+ import { $ as configureServerAuth, A as assertDsarOrchestrator, B as getContextOptions, C as DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, D as DsarOrchestratorRejectionReason, E as DsarOrchestratorOptions, F as getDelegatedPrincipal, G as PayloadTooLargeError, H as DEFAULT_RAW_BODY_MAX_BYTES, I as resolveOnBehalfOf, J as createRawBodyRouter, K as RawBodyResolution, L as ContextBuilderOptions, M as isDsarOrchestratorActor, N as resolveDsarCallerIdentity, O as ResolvedDsarCaller, P as DelegatedPrincipal, Q as resolveMaxRequestBodySize, R as buildContext, S as DSAR_ALLOWED_ORCHESTRATORS_ENV, T as DsarOrchestratorForbiddenError, U as MAX_IDLE_TIMEOUT_SECONDS, V as DEFAULT_MAX_REQUEST_BODY_SIZE, W as OrdinaryRoute, X as readBoundedRawBody, Y as extendRequestIdleTimeout, Z as resolveBodyLimitBytes, _ as MutationAuditPluginOptions, a as UserFacingErrorOptions, at as configureDefaultAuth, b as sanitizeAuditValue, c as createHumanReadableErrorPlugin, ct as generateSymmetricSecret, d as normalizeExecutionResultErrors, dt as tenantCheck, et as createServer, f as normalizeGraphQLResponse, ft as verifyJWT, g as MUTATION_AUDIT_RESOURCE_TYPE, h as MUTATION_AUDIT_ACTIVITY_TYPE, i as NormalizedErrorState, it as configureAuth, j as getAllowedDsarOrchestrators, k as VERIFIED_SERVICE_IDENTITY_HEADER, l as formatHttpError, lt as orgCheck, m as toUserFacingGraphQLError, n as HttpErrorPayload, nt as FetchWorkspaceSecretFn, o as UserFacingGraphQLError, ot as decodeJWT, p as normalizeGraphQLResponsePayload, pt as workspaceCheck, q as RawBodyRouter, r as HttpErrorResult, rt as authCheck, s as createHttpErrorResponse, st as fetchWorkspaceSecret, t as ErrorNormalizationOptions, tt as AuthConfig, u as normalizeError, ut as requireWorkspace, v as createMutationAuditPlugin, w as DsarOrchestratorContext, x as DEFAULT_DSAR_ORCHESTRATOR_ID, y as getMutationFieldNames, z as configureContext } from "../index-CkQieKSy.js";
6
6
  import { t as suppressMutationAudit } from "../explicit-activity-scope-D8VeGGpt.js";
7
- export { ACTOR_ORIGIN_HEADER, AI_ASSISTANT_ACTOR_ORIGIN, ASSISTANT_CORRELATION_ID_HEADER, ASSISTANT_SESSION_ID_HEADER, type ActorOrigin, type ActorProvenance, type AssistantSessionAttribution, type AuthConfig, type ConsentContext, type ContextBuilderOptions, DEFAULT_DSAR_ORCHESTRATOR_ID, DSAR_ALLOWED_ORCHESTRATORS_ENV, DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, type DelegatedPrincipal, type DsarOrchestratorContext, DsarOrchestratorForbiddenError, type DsarOrchestratorOptions, type DsarOrchestratorRejectionReason, type ElysiaApp, type ErrorNormalizationOptions, type FetchWorkspaceSecretFn, type GraphQLContext, type HttpErrorPayload, type HttpErrorResult, type I18nContext, type IActor, type IContextFilterInput, type IOperationContext, type IOrganization, type IProduct, type IProject, type ITenant, type ITracking, type IWorkspace, type JWTPayload, type LocaleCode, MAX_IDLE_TIMEOUT_SECONDS, MUTATION_AUDIT_ACTIVITY_TYPE, MUTATION_AUDIT_RESOURCE_TYPE, type ModuleGraphConfig, type MutationAuditPluginOptions, type NormalizedErrorState, type OrdinaryRoute, type PrismaClientBase, type PrismaClientConstructor, type RESTEndpoint, type RawBodyResolution, type RawBodyRouter, type ResolvedDsarCaller, type ServerConfig, type ServerDefinition, type ServerI18nConfig, type ServerInfo, type ServerInstance, type UserFacingErrorOptions, UserFacingGraphQLError, VERIFIED_SERVICE_IDENTITY_HEADER, type VerifiedDelegationContext, type WorkspaceGuardConfig, type WorkspaceMembershipValidation, type WorkspaceSecret, type WspaceGraphQLContext, type YogaPlugin, assertDsarOrchestrator, authCheck, buildContext, configureAuth, configureContext, configureDefaultAuth, configureServerAuth, createHttpErrorResponse, createHumanReadableErrorPlugin, createMutationAuditPlugin, createRawBodyRouter, createServer, createWorkspaceGuardPlugin, decodeJWT, extendRequestIdleTimeout, fetchWorkspaceSecret, formatHttpError, generateSymmetricSecret, getAllowedDsarOrchestrators, getContextOptions, getDelegatedPrincipal, getMutationFieldNames, isDsarOrchestratorActor, normalizeError, normalizeExecutionResultErrors, normalizeGraphQLResponse, normalizeGraphQLResponsePayload, orgCheck, parseAssistantSessionHeaders, readAssistantSessionAttribution, requireWorkspace, resolveDsarCallerIdentity, resolveOnBehalfOf, sanitizeAuditValue, suppressMutationAudit, tenantCheck, toAssistantSessionAttribution, toUserFacingGraphQLError, verifyJWT, workspaceCheck };
7
+ export { ACTOR_ORIGIN_HEADER, AI_ASSISTANT_ACTOR_ORIGIN, ASSISTANT_CORRELATION_ID_HEADER, ASSISTANT_SESSION_ID_HEADER, type ActorOrigin, type ActorProvenance, type AssistantSessionAttribution, type AuthConfig, type ConsentContext, type ContextBuilderOptions, DEFAULT_DSAR_ORCHESTRATOR_ID, DEFAULT_MAX_REQUEST_BODY_SIZE, DEFAULT_RAW_BODY_MAX_BYTES, DSAR_ALLOWED_ORCHESTRATORS_ENV, DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, type DelegatedPrincipal, type DsarOrchestratorContext, DsarOrchestratorForbiddenError, type DsarOrchestratorOptions, type DsarOrchestratorRejectionReason, type ElysiaApp, type ErrorNormalizationOptions, type FetchWorkspaceSecretFn, type GraphQLContext, type HttpErrorPayload, type HttpErrorResult, type I18nContext, type IActor, type IContextFilterInput, type IOperationContext, type IOrganization, type IProduct, type IProject, type ITenant, type ITracking, type IWorkspace, type JWTPayload, type LocaleCode, MAX_IDLE_TIMEOUT_SECONDS, MUTATION_AUDIT_ACTIVITY_TYPE, MUTATION_AUDIT_RESOURCE_TYPE, type ModuleGraphConfig, type MutationAuditPluginOptions, type NormalizedErrorState, type OrdinaryRoute, PayloadTooLargeError, type PrismaClientBase, type PrismaClientConstructor, type RESTEndpoint, type RawBodyResolution, type RawBodyRouter, type ResolvedDsarCaller, type ServerConfig, type ServerDefinition, type ServerI18nConfig, type ServerInfo, type ServerInstance, type UserFacingErrorOptions, UserFacingGraphQLError, VERIFIED_SERVICE_IDENTITY_HEADER, type VerifiedDelegationContext, type WorkspaceGuardConfig, type WorkspaceMembershipValidation, type WorkspaceSecret, type WspaceGraphQLContext, type YogaPlugin, assertDsarOrchestrator, authCheck, buildContext, configureAuth, configureContext, configureDefaultAuth, configureServerAuth, createHttpErrorResponse, createHumanReadableErrorPlugin, createMutationAuditPlugin, createRawBodyRouter, createServer, createWorkspaceGuardPlugin, decodeJWT, extendRequestIdleTimeout, fetchWorkspaceSecret, formatHttpError, generateSymmetricSecret, getAllowedDsarOrchestrators, getContextOptions, getDelegatedPrincipal, getMutationFieldNames, isDsarOrchestratorActor, normalizeError, normalizeExecutionResultErrors, normalizeGraphQLResponse, normalizeGraphQLResponsePayload, orgCheck, parseAssistantSessionHeaders, readAssistantSessionAttribution, readBoundedRawBody, requireWorkspace, resolveBodyLimitBytes, resolveDsarCallerIdentity, resolveMaxRequestBodySize, resolveOnBehalfOf, sanitizeAuditValue, suppressMutationAudit, tenantCheck, toAssistantSessionAttribution, toUserFacingGraphQLError, verifyJWT, workspaceCheck };