@burdenoff/be-sdk 2026.1123.3 → 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-B1DRke7D.js → init-4vv4gYEm.js} +2 -2
  24. package/dist/{init-B1DRke7D.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-SvRAUsCQ.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-BfG_SWb_.js → metrics-CQaHT12m.js} +2 -2
  34. package/dist/{metrics-BfG_SWb_.js.map → metrics-CQaHT12m.js.map} +1 -1
  35. package/dist/{metrics-collector-6S-7Smug.js → metrics-collector-DXQrMUle.js} +117 -116
  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-SvRAUsCQ.js.map +0 -1
  69. package/dist/metrics-collector-6S-7Smug.js.map +0 -1
  70. package/dist/middleware-B9eyLP7A.js.map +0 -1
  71. package/dist/rate-limit-CBrK_U5H.js.map +0 -1
@@ -20,12 +20,12 @@ const buildRateLimitKey = (svc, resource, identifier) => `ratelimit:${svc}:${res
20
20
 
21
21
  // src/security/rate-limit/rate-limit.ts
22
22
  /**
23
- * Shared Sliding-Window Rate Limiter
23
+ * Shared Fixed-Window Rate Limiter
24
24
  *
25
- * Valkey-backed sliding window implemented via `INCR + EXPIRE` on the first
26
- * event of a window (same approach as the global-auth-svc service today but
27
- * lifted into `@burdenoff/be-sdk` so wspace-auth-svc and future consumers
28
- * can share it).
25
+ * Valkey-backed fixed window implemented via atomic `INCR + EXPIRE NX` on the
26
+ * first event of a window (same approach as `global-auth-svc` / `src/platform/rateLimit.ts`,
27
+ * lifted into `@burdenoff/be-sdk` so `wspace-auth-svc` and future consumers
28
+ * can share it safely under concurrency).
29
29
  *
30
30
  * Honors `RateLimitMode`:
31
31
  * - `enforce` — throws GraphQLError('RATE_LIMITED') on breach
@@ -40,33 +40,33 @@ const buildRateLimitKey = (svc, resource, identifier) => `ratelimit:${svc}:${res
40
40
  * @category Security
41
41
  */
42
42
  /**
43
- * Low-level: check a rate limit and return the result. Never throws unless
44
- * `failureMode: 'closed'` and the cache is unreachable — and even then it
45
- * returns a non-throwing `{ allowed: false }` so callers stay in control.
43
+ * Low-level: check a rate limit atomically via `INCR` + `EXPIRE NX` and return
44
+ * the result. Never throws unless `failureMode: 'closed'` and the cache is
45
+ * unreachable — and even then it returns a non-throwing `{ allowed: false }` so
46
+ * callers stay in control.
46
47
  */
47
48
  const checkRateLimit = async (deps, identifier, resource, config) => {
48
- const resetAt = new Date(Date.now() + config.windowMs);
49
+ const ttlSeconds = Math.max(1, Math.ceil(config.windowMs / 1e3));
50
+ const fallbackResetAt = new Date(Date.now() + ttlSeconds * 1e3);
49
51
  if (deps.mode === "off") return {
50
52
  allowed: true,
51
53
  remaining: Number.MAX_SAFE_INTEGER,
52
- resetAt,
54
+ resetAt: fallbackResetAt,
53
55
  limit: config.maxRequests
54
56
  };
55
57
  const key = buildRateLimitKey(deps.service, resource, identifier);
56
58
  try {
57
- const current = await deps.cache.get(key);
58
- const count = current ? parseInt(current, 10) || 0 : 0;
59
- if (count >= config.maxRequests) return {
60
- allowed: false,
61
- remaining: 0,
62
- resetAt,
63
- limit: config.maxRequests
64
- };
65
- const ttlSeconds = Math.ceil(config.windowMs / 1e3);
66
- await deps.cache.set(key, String(count + 1), { ttl: ttlSeconds });
59
+ const count = await deps.cache.increment(key);
60
+ if (count === 1) await deps.cache.expireNX(key, ttlSeconds);
61
+ let remainingTtlSeconds = await deps.cache.ttl(key);
62
+ if (remainingTtlSeconds === -1) {
63
+ await deps.cache.expireNX(key, ttlSeconds);
64
+ remainingTtlSeconds = ttlSeconds;
65
+ }
66
+ const resetAt = new Date(Date.now() + (remainingTtlSeconds > 0 ? remainingTtlSeconds : ttlSeconds) * 1e3);
67
67
  return {
68
- allowed: true,
69
- remaining: Math.max(0, config.maxRequests - count - 1),
68
+ allowed: count <= config.maxRequests,
69
+ remaining: Math.max(0, config.maxRequests - count),
70
70
  resetAt,
71
71
  limit: config.maxRequests
72
72
  };
@@ -83,13 +83,13 @@ const checkRateLimit = async (deps, identifier, resource, config) => {
83
83
  if (failureMode === "closed") return {
84
84
  allowed: false,
85
85
  remaining: 0,
86
- resetAt,
86
+ resetAt: fallbackResetAt,
87
87
  limit: config.maxRequests
88
88
  };
89
89
  return {
90
90
  allowed: true,
91
91
  remaining: config.maxRequests,
92
- resetAt,
92
+ resetAt: fallbackResetAt,
93
93
  limit: config.maxRequests
94
94
  };
95
95
  }
@@ -139,4 +139,4 @@ var rate_limit_exports = /* @__PURE__ */ __exportAll({
139
139
  });
140
140
 
141
141
  export { buildRateLimitKey as a, resolveRateLimitModeFromEnv as i, checkRateLimit as n, enforceRateLimit as r, rate_limit_exports as t };
142
- //# sourceMappingURL=rate-limit-CBrK_U5H.js.map
142
+ //# sourceMappingURL=rate-limit-ISSpByjW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limit-ISSpByjW.js","names":[],"sources":["../src/security/rate-limit/keyspace.ts","../src/security/rate-limit/rate-limit.ts","../src/security/rate-limit/index.ts"],"sourcesContent":["/**\n * Rate-Limit Keyspace\n *\n * Canonical cache key builder so auth-svc, wspace-auth-svc, and gateway\n * plugins never collide. Format: `ratelimit:{svc}:{resource}:{identifier}`.\n *\n * `svc` is the short service name (e.g., 'global-auth', 'wspace-auth',\n * 'wspace-public-gateway'). `resource` is the RATE_LIMITS map key. `identifier`\n * is whatever the limit is keyed by (email, userId, ip, etc).\n *\n * @module security/rate-limit/keyspace\n * @category Security\n */\n\nexport const buildRateLimitKey = (svc: string, resource: string, identifier: string): string =>\n `ratelimit:${svc}:${resource}:${identifier}`;\n","/**\n * Shared Fixed-Window Rate Limiter\n *\n * Valkey-backed fixed window implemented via atomic `INCR + EXPIRE NX` on the\n * first event of a window (same approach as `global-auth-svc` / `src/platform/rateLimit.ts`,\n * lifted into `@burdenoff/be-sdk` so `wspace-auth-svc` and future consumers\n * can share it safely under concurrency).\n *\n * Honors `RateLimitMode`:\n * - `enforce` — throws GraphQLError('RATE_LIMITED') on breach\n * - `soft` — counts + logs, returns `allowed: false` but never throws\n * - `off` — short-circuits to `{allowed: true}`\n *\n * Honors `failureMode`:\n * - `open` — Valkey outage: allow + log warning (default for read paths)\n * - `closed` — Valkey outage: reject (auth-critical ops like login/reset)\n *\n * @module security/rate-limit/rate-limit\n * @category Security\n */\n\nimport { GraphQLError } from 'graphql';\n\nimport type { ICacheProvider } from '../../cache/index.js';\nimport { logger } from '../../logger/index.js';\nimport { buildRateLimitKey } from './keyspace.js';\nimport type { RateLimitConfig, RateLimitMode, RateLimitResult } from './types.js';\n\nexport interface RateLimiterDeps {\n cache: Pick<ICacheProvider, 'increment' | 'expireNX' | 'ttl'>;\n /** Short service name (e.g., 'global-auth'). */\n service: string;\n /** Operational mode. */\n mode: RateLimitMode;\n}\n\n/**\n * Low-level: check a rate limit atomically via `INCR` + `EXPIRE NX` and return\n * the result. Never throws unless `failureMode: 'closed'` and the cache is\n * unreachable — and even then it returns a non-throwing `{ allowed: false }` so\n * callers stay in control.\n */\nexport const checkRateLimit = async (\n deps: RateLimiterDeps,\n identifier: string,\n resource: string,\n config: RateLimitConfig\n): Promise<RateLimitResult> => {\n const ttlSeconds = Math.max(1, Math.ceil(config.windowMs / 1000));\n const fallbackResetAt = new Date(Date.now() + ttlSeconds * 1000);\n\n if (deps.mode === 'off') {\n return { allowed: true, remaining: Number.MAX_SAFE_INTEGER, resetAt: fallbackResetAt, limit: config.maxRequests };\n }\n\n const key = buildRateLimitKey(deps.service, resource, identifier);\n\n try {\n // Atomic INCR: each concurrent caller receives a unique sequential count.\n const count = await deps.cache.increment(key);\n if (count === 1) {\n // Stamp the fixed-window TTL once using EXPIRE NX so concurrent or later\n // hits never slide/reset the window expiry.\n await deps.cache.expireNX(key, ttlSeconds);\n }\n\n let remainingTtlSeconds = await deps.cache.ttl(key);\n if (remainingTtlSeconds === -1) {\n // Defensive recovery if a prior caller crashed between INCR and EXPIRE NX.\n // EXPIRE NX is idempotent and will never overwrite an already-set TTL.\n await deps.cache.expireNX(key, ttlSeconds);\n remainingTtlSeconds = ttlSeconds;\n }\n\n const resetAt = new Date(Date.now() + (remainingTtlSeconds > 0 ? remainingTtlSeconds : ttlSeconds) * 1000);\n const allowed = count <= config.maxRequests;\n\n return {\n allowed,\n remaining: Math.max(0, config.maxRequests - count),\n resetAt,\n limit: config.maxRequests,\n };\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err));\n const failureMode = config.failureMode ?? 'open';\n logger.warn('[security/rate-limit] cache error — applying failure mode', {\n service: deps.service,\n resource,\n identifier,\n failureMode,\n error: e.message,\n });\n if (failureMode === 'closed') {\n return { allowed: false, remaining: 0, resetAt: fallbackResetAt, limit: config.maxRequests };\n }\n return {\n allowed: true,\n remaining: config.maxRequests,\n resetAt: fallbackResetAt,\n limit: config.maxRequests,\n };\n }\n};\n\n/**\n * High-level: check a rate limit and throw `GraphQLError(RATE_LIMITED)` on\n * breach. Honors `mode`:\n * - `enforce` throws on breach\n * - `soft` logs the breach but does not throw\n * - `off` short-circuits to allowed\n */\nexport const enforceRateLimit = async (\n deps: RateLimiterDeps,\n identifier: string,\n resource: string,\n config: RateLimitConfig\n): Promise<RateLimitResult> => {\n const result = await checkRateLimit(deps, identifier, resource, config);\n\n if (result.allowed) return result;\n\n if (deps.mode === 'soft') {\n logger.warn('[security/rate-limit] soft-limit breach (not thrown)', {\n service: deps.service,\n resource,\n identifier,\n limit: result.limit,\n });\n return result;\n }\n\n if (deps.mode === 'enforce') {\n throw new GraphQLError('Rate limit exceeded', {\n extensions: {\n code: 'RATE_LIMITED',\n resetAt: result.resetAt.toISOString(),\n limit: result.limit,\n },\n });\n }\n\n return result;\n};\n\n/**\n * Helper: parse `RATE_LIMIT_MODE` env into a typed value.\n * Prod defaults to `enforce`, non-prod to `soft`.\n */\nexport const resolveRateLimitModeFromEnv = (): RateLimitMode => {\n const raw = process.env['RATE_LIMIT_MODE'];\n if (raw === 'enforce' || raw === 'soft' || raw === 'off') return raw;\n return process.env['NODE_ENV'] === 'production' ? 'enforce' : 'soft';\n};\n","/**\n * Shared Rate-Limit — public API\n *\n * Consumed by:\n * - `global-auth-svc` (replaces the local rate-limit service)\n * - `wspace-auth-svc` (new — parity)\n * - Any future service that needs Valkey-backed sliding-window limits\n *\n * For the gateway plugin, use `@burdenoff/be-sdk/gateway/security` instead —\n * it is a different shape (per-request Yoga plugin, token bucket).\n *\n * @module security/rate-limit\n * @category Security\n */\n\nexport { buildRateLimitKey } from './keyspace.js';\nexport { checkRateLimit, enforceRateLimit, resolveRateLimitModeFromEnv, type RateLimiterDeps } from './rate-limit.js';\nexport type { RateLimitConfig, RateLimitMode, RateLimitResult } from './types.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAcA,MAAa,qBAAqB,KAAa,UAAkB,eAC/D,aAAa,IAAI,GAAG,SAAS,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC2BlC,MAAa,iBAAiB,OAC5B,MACA,YACA,UACA,WAC6B;CAC7B,MAAM,aAAa,KAAK,IAAI,GAAG,KAAK,KAAK,OAAO,WAAW,GAAI,CAAC;CAChE,MAAM,kBAAkB,IAAI,KAAK,KAAK,IAAI,IAAI,aAAa,GAAI;CAE/D,IAAI,KAAK,SAAS,OAChB,OAAO;EAAE,SAAS;EAAM,WAAW,OAAO;EAAkB,SAAS;EAAiB,OAAO,OAAO;CAAY;CAGlH,MAAM,MAAM,kBAAkB,KAAK,SAAS,UAAU,UAAU;CAEhE,IAAI;EAEF,MAAM,QAAQ,MAAM,KAAK,MAAM,UAAU,GAAG;EAC5C,IAAI,UAAU,GAGZ,MAAM,KAAK,MAAM,SAAS,KAAK,UAAU;EAG3C,IAAI,sBAAsB,MAAM,KAAK,MAAM,IAAI,GAAG;EAClD,IAAI,wBAAwB,IAAI;GAG9B,MAAM,KAAK,MAAM,SAAS,KAAK,UAAU;GACzC,sBAAsB;EACxB;EAEA,MAAM,UAAU,IAAI,KAAK,KAAK,IAAI,KAAK,sBAAsB,IAAI,sBAAsB,cAAc,GAAI;EAGzG,OAAO;GACL,SAHc,SAAS,OAAO;GAI9B,WAAW,KAAK,IAAI,GAAG,OAAO,cAAc,KAAK;GACjD;GACA,OAAO,OAAO;EAChB;CACF,SAAS,KAAK;EACZ,MAAM,IAAI,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC;EAC5D,MAAM,cAAc,OAAO,eAAe;EAC1C,OAAO,KAAK,6DAA6D;GACvE,SAAS,KAAK;GACd;GACA;GACA;GACA,OAAO,EAAE;EACX,CAAC;EACD,IAAI,gBAAgB,UAClB,OAAO;GAAE,SAAS;GAAO,WAAW;GAAG,SAAS;GAAiB,OAAO,OAAO;EAAY;EAE7F,OAAO;GACL,SAAS;GACT,WAAW,OAAO;GAClB,SAAS;GACT,OAAO,OAAO;EAChB;CACF;AACF;;;;;;;;AASA,MAAa,mBAAmB,OAC9B,MACA,YACA,UACA,WAC6B;CAC7B,MAAM,SAAS,MAAM,eAAe,MAAM,YAAY,UAAU,MAAM;CAEtE,IAAI,OAAO,SAAS,OAAO;CAE3B,IAAI,KAAK,SAAS,QAAQ;EACxB,OAAO,KAAK,wDAAwD;GAClE,SAAS,KAAK;GACd;GACA;GACA,OAAO,OAAO;EAChB,CAAC;EACD,OAAO;CACT;CAEA,IAAI,KAAK,SAAS,WAChB,MAAM,IAAI,aAAa,uBAAuB,EAC5C,YAAY;EACV,MAAM;EACN,SAAS,OAAO,QAAQ,YAAY;EACpC,OAAO,OAAO;CAChB,EACF,CAAC;CAGH,OAAO;AACT;;;;;AAMA,MAAa,oCAAmD;CAC9D,MAAM,MAAM,QAAQ,IAAI;CACxB,IAAI,QAAQ,aAAa,QAAQ,UAAU,QAAQ,OAAO,OAAO;CACjE,OAAO,QAAQ,IAAI,gBAAgB,eAAe,YAAY;AAChE"}
@@ -30,6 +30,67 @@ export interface ResourceCapsConfig {
30
30
  onFallback?: () => void;
31
31
  onBillingFailure?: () => void;
32
32
  }
33
+ export interface ResourceCapTransactionClient {
34
+ $queryRaw?<T = unknown>(query: TemplateStringsArray, ...values: unknown[]): Promise<T>;
35
+ $executeRaw?(query: TemplateStringsArray, ...values: unknown[]): Promise<unknown>;
36
+ $executeRawUnsafe?(query: string, ...values: unknown[]): Promise<unknown>;
37
+ }
38
+ export interface ResourceCapPrismaLike<TTx extends ResourceCapTransactionClient = ResourceCapTransactionClient> {
39
+ $transaction<T>(fn: (tx: TTx) => Promise<T>, options?: {
40
+ maxWait?: number;
41
+ timeout?: number;
42
+ isolationLevel?: string;
43
+ }): Promise<T>;
44
+ }
45
+ export interface EnforceWithinTransactionOptions<TTx extends ResourceCapTransactionClient, TResult> {
46
+ userId: string;
47
+ resource: ResourceName;
48
+ prisma: ResourceCapPrismaLike<TTx>;
49
+ count: (tx: TTx) => Promise<number>;
50
+ create: (tx: TTx, cap: ResourceCap) => Promise<TResult>;
51
+ lockScopeKey?: string;
52
+ transactionOptions?: {
53
+ maxWait?: number;
54
+ timeout?: number;
55
+ isolationLevel?: string;
56
+ };
57
+ }
58
+ export interface EnforceWorkspaceWithinTransactionOptions<TTx extends ResourceCapTransactionClient, TResult> {
59
+ scope: WorkspaceResourceCapScope;
60
+ resource: ResourceName;
61
+ prisma: ResourceCapPrismaLike<TTx>;
62
+ count: (tx: TTx) => Promise<number>;
63
+ create: (tx: TTx, cap: ResourceCap) => Promise<TResult>;
64
+ transactionOptions?: {
65
+ maxWait?: number;
66
+ timeout?: number;
67
+ isolationLevel?: string;
68
+ };
69
+ }
70
+ export interface ResourceCapReservationStore {
71
+ increment(key: string, amount?: number): Promise<number>;
72
+ decrement(key: string, amount?: number): Promise<number>;
73
+ expire(key: string, ttlSeconds: number): Promise<boolean>;
74
+ expireNX?(key: string, ttlSeconds: number): Promise<boolean>;
75
+ evalScript?(script: string, keys: string[], args: string[]): Promise<number>;
76
+ }
77
+ export declare const RESOURCE_CAP_RESERVE_LUA: string;
78
+ export interface ReserveResourceCapOptions {
79
+ store: ResourceCapReservationStore;
80
+ baseCount: number;
81
+ amount?: number;
82
+ ttlSeconds?: number;
83
+ keyPrefix?: string;
84
+ }
85
+ export interface ResourceCapReservation {
86
+ readonly cap: ResourceCap;
87
+ readonly key: string;
88
+ readonly amount: number;
89
+ commit(): Promise<void>;
90
+ release(): Promise<void>;
91
+ }
92
+ export declare function computeResourceCapLockKeys(scopeKey: string, resource: ResourceName): [number, number];
93
+ export declare function acquireResourceCapAdvisoryLock(tx: ResourceCapTransactionClient, scopeKey: string, resource: ResourceName): Promise<[number, number]>;
33
94
  export declare class ResourceCapExceededError extends GraphQLError {
34
95
  constructor(detail: {
35
96
  resource: ResourceName;
@@ -54,7 +115,23 @@ export declare class ResourceCapsModule {
54
115
  configure(config: ResourceCapsConfig): void;
55
116
  hasBillingSource(): boolean;
56
117
  getResourceCap(userId: string, resource: ResourceName): Promise<ResourceCap>;
118
+ assertWithinCap(cap: ResourceCap, currentCount: number): ResourceCap;
57
119
  enforceResourceCap(userId: string, resource: ResourceName, currentCount: number): Promise<ResourceCap>;
120
+ enforceWithinTransaction<TTx extends ResourceCapTransactionClient, TResult>(options: EnforceWithinTransactionOptions<TTx, TResult>): Promise<{
121
+ result: TResult;
122
+ cap: ResourceCap;
123
+ }>;
124
+ enforceWorkspaceWithinTransaction<TTx extends ResourceCapTransactionClient, TResult>(options: EnforceWorkspaceWithinTransactionOptions<TTx, TResult>): Promise<{
125
+ result: TResult;
126
+ cap: ResourceCap;
127
+ }>;
128
+ reserveResourceCap(userId: string, resource: ResourceName, options: ReserveResourceCapOptions): Promise<ResourceCapReservation>;
129
+ reserveWorkspaceResourceCap(scope: WorkspaceResourceCapScope, resource: ResourceName, options: ReserveResourceCapOptions): Promise<ResourceCapReservation>;
130
+ withReservedResourceCap<TResult>(userId: string, resource: ResourceName, options: ReserveResourceCapOptions, action: (cap: ResourceCap) => Promise<TResult>): Promise<{
131
+ result: TResult;
132
+ cap: ResourceCap;
133
+ }>;
134
+ private reserveWithResolvedCap;
58
135
  getWorkspaceResourceCap(scope: WorkspaceResourceCapScope, resource: ResourceName): Promise<ResourceCap>;
59
136
  enforceWorkspaceResourceCap(scope: WorkspaceResourceCapScope, resource: ResourceName, currentCount: number): Promise<ResourceCap>;
60
137
  invalidate(userId: string): void;
@@ -1,6 +1,7 @@
1
- import { n as createCounter } from "../metrics-collector-6S-7Smug.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