@burdenoff/be-sdk 2026.1123.3 → 2026.1123.5

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 (94) 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/export/index.js +1 -1
  7. package/dist/{export-lqKewsuF.js → export-D3EySJjJ.js} +2 -2
  8. package/dist/{export-lqKewsuF.js.map → export-D3EySJjJ.js.map} +1 -1
  9. package/dist/feature-flags/index.d.ts +1 -1
  10. package/dist/gateway/index.d.ts +2 -2
  11. package/dist/gateway/index.js +2 -2
  12. package/dist/gateway/security/index.d.ts +1 -1
  13. package/dist/gateway/security/index.js +1 -1
  14. package/dist/{gateway-2en8Gx_a.js → gateway-B9p8PD82.js} +2 -2
  15. package/dist/{gateway-2en8Gx_a.js.map → gateway-B9p8PD82.js.map} +1 -1
  16. package/dist/graph/index.d.ts +1 -1
  17. package/dist/graph/index.js +2 -2
  18. package/dist/{graph-Egewc_K7.js → graph-BdoM7_90.js} +2 -2
  19. package/dist/{graph-Egewc_K7.js.map → graph-BdoM7_90.js.map} +1 -1
  20. package/dist/{index-HeUeEsMU.d.ts → index-BaskMO3C.d.ts} +8 -2
  21. package/dist/{index-479i3w77.d.ts → index-BgOU0pxB.d.ts} +30 -5
  22. package/dist/{index-FKohsiex.d.ts → index-BrRQe24P.d.ts} +3 -2
  23. package/dist/{index-BiTzGUZP.d.ts → index-BwgBHUuX.d.ts} +2 -2
  24. package/dist/{index-DMeQh75K.d.ts → index-CIayzveI.d.ts} +1 -1
  25. package/dist/{index-DSA8h4W3.d.ts → index-CUiL43SY.d.ts} +2 -2
  26. package/dist/{index-DWER4-_x.d.ts → index-C_WEvMzP.d.ts} +1 -1
  27. package/dist/{index-CzMD97-N.d.ts → index-CkQieKSy.d.ts} +16 -2
  28. package/dist/{index-DqpCL9kD.d.ts → index-Cl2L2P47.d.ts} +1 -1
  29. package/dist/{index-nP7g1FZm.d.ts → index-DFEKBKBE.d.ts} +4 -1
  30. package/dist/{index-DhFP_AIB.d.ts → index-DkitHCtV.d.ts} +1 -1
  31. package/dist/{index-oJMtR3nl.d.ts → index-XkPephwV.d.ts} +1 -1
  32. package/dist/{index-C0qLquY0.d.ts → index-srSv2xNE.d.ts} +2 -1
  33. package/dist/index.d.ts +11 -11
  34. package/dist/index.js +11 -11
  35. package/dist/init/index.js +1 -1
  36. package/dist/{init-B1DRke7D.js → init-DaHOxzwF.js} +3 -3
  37. package/dist/{init-B1DRke7D.js.map → init-DaHOxzwF.js.map} +1 -1
  38. package/dist/instrumentation/index.d.ts +2 -2
  39. package/dist/instrumentation/index.js +3 -3
  40. package/dist/{instrumentation-SvRAUsCQ.js → instrumentation-C738xDj8.js} +45 -6
  41. package/dist/instrumentation-C738xDj8.js.map +1 -0
  42. package/dist/lake/index.d.ts +52 -3
  43. package/dist/lake/index.js +238 -9
  44. package/dist/lake/index.js.map +1 -1
  45. package/dist/metrics/index.js +1 -1
  46. package/dist/{metrics-BfG_SWb_.js → metrics-CQaHT12m.js} +2 -2
  47. package/dist/{metrics-BfG_SWb_.js.map → metrics-CQaHT12m.js.map} +1 -1
  48. package/dist/{metrics-collector-6S-7Smug.js → metrics-collector-DXQrMUle.js} +117 -116
  49. package/dist/metrics-collector-DXQrMUle.js.map +1 -0
  50. package/dist/{middleware-B9eyLP7A.js → middleware-z8KzMFU_.js} +95 -5
  51. package/dist/middleware-z8KzMFU_.js.map +1 -0
  52. package/dist/prisma/index.d.ts +3 -3
  53. package/dist/prisma/index.js +3 -3
  54. package/dist/{prisma-CML_Prrn.js → prisma-J-ZUmVWJ.js} +4 -2
  55. package/dist/{prisma-CML_Prrn.js.map → prisma-J-ZUmVWJ.js.map} +1 -1
  56. package/dist/{rate-limit-CBrK_U5H.js → rate-limit-ISSpByjW.js} +25 -25
  57. package/dist/rate-limit-ISSpByjW.js.map +1 -0
  58. package/dist/resource-caps/index.d.ts +77 -0
  59. package/dist/resource-caps/index.js +235 -31
  60. package/dist/resource-caps/index.js.map +1 -1
  61. package/dist/security/index.d.ts +1 -1
  62. package/dist/security/index.js +1 -1
  63. package/dist/security/rate-limit/index.d.ts +1 -1
  64. package/dist/security/rate-limit/index.js +1 -1
  65. package/dist/{security-DIG-95Ic.js → security-casihGNW.js} +24 -8
  66. package/dist/{security-DIG-95Ic.js.map → security-casihGNW.js.map} +1 -1
  67. package/dist/server/index.d.ts +4 -4
  68. package/dist/server/index.js +112 -6
  69. package/dist/server/index.js.map +1 -1
  70. package/dist/tags/index.d.ts +1 -1
  71. package/dist/tags/index.js +1 -1
  72. package/dist/{tags-CbijgoqR.js → tags-C316oA9r.js} +14 -3
  73. package/dist/{tags-CbijgoqR.js.map → tags-C316oA9r.js.map} +1 -1
  74. package/dist/telemetry/index.d.ts +1 -1
  75. package/dist/telemetry/index.js +1 -1
  76. package/dist/tracker/index.d.ts +2 -2
  77. package/dist/tracker/index.js +2 -2
  78. package/dist/{tracker-BXW8-5Yx.js → tracker-B1fEAM3i.js} +2 -2
  79. package/dist/{tracker-BXW8-5Yx.js.map → tracker-B1fEAM3i.js.map} +1 -1
  80. package/dist/{types-De_pO1Wz.d.ts → types-BWN8tMdF.d.ts} +5 -1
  81. package/dist/usage/index.d.ts +1 -1
  82. package/dist/usage/index.js +1 -1
  83. package/dist/{usage-ygkKsxdd.js → usage-BK7eyP42.js} +2 -2
  84. package/dist/{usage-ygkKsxdd.js.map → usage-BK7eyP42.js.map} +1 -1
  85. package/dist/utils/index.d.ts +2 -2
  86. package/dist/utils/index.js +2 -2
  87. package/dist/{utils-DL85Tnbn.js → utils-DpW6K_iB.js} +24 -7
  88. package/dist/{utils-DL85Tnbn.js.map → utils-DpW6K_iB.js.map} +1 -1
  89. package/package.json +1 -1
  90. package/dist/auth-C5ctwSLp.js.map +0 -1
  91. package/dist/instrumentation-SvRAUsCQ.js.map +0 -1
  92. package/dist/metrics-collector-6S-7Smug.js.map +0 -1
  93. package/dist/middleware-B9eyLP7A.js.map +0 -1
  94. package/dist/rate-limit-CBrK_U5H.js.map +0 -1
@@ -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,M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AgB,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
+ {"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;E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AA6C,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
@@ -1166,17 +1166,31 @@ const shutdownOtel = async () => {
1166
1166
  };
1167
1167
  /**
1168
1168
  * Returns an Envelop plugin that adds spans around parse/validate/execute.
1169
- * Returns an empty plugin when @envelop/opentelemetry is absent.
1169
+ *
1170
+ * The spans go to the process-wide tracer provider, which the service's
1171
+ * telemetry bootstrap (NodeSDK) registers. The provider has to be passed in
1172
+ * explicitly: when `useOpenTelemetry` gets none it builds its own
1173
+ * `BasicTracerProvider` with a `ConsoleSpanExporter`, so every operation's
1174
+ * spans would be printed to stdout and never reach the collector. That
1175
+ * fallback also calls `addSpanProcessor` and `register`, which no longer exist
1176
+ * on `@opentelemetry/sdk-trace-base` 2.x (BOFF-14727).
1177
+ *
1178
+ * Returns an empty plugin, with a warning that carries the load error, when
1179
+ * `@envelop/opentelemetry` or `@opentelemetry/api` cannot be loaded.
1170
1180
  */
1171
- const createOtelPlugin = async (cfg) => {
1181
+ const createOtelPlugin = async (cfg, loadPeer = importOptionalPeer) => {
1172
1182
  if (!cfg.enabled) return {};
1173
1183
  try {
1174
- const mod = await importOptionalPeer("@envelop/opentelemetry");
1175
- if (typeof mod.useOpenTelemetry !== "function") {
1184
+ const [envelopMod, apiMod] = await Promise.all([loadPeer("@envelop/opentelemetry"), loadPeer("@opentelemetry/api")]);
1185
+ if (typeof envelopMod?.useOpenTelemetry !== "function") {
1176
1186
  logger.warn("[gateway-security] @envelop/opentelemetry has unexpected shape — plugin skipped");
1177
1187
  return {};
1178
1188
  }
1179
- return mod.useOpenTelemetry({
1189
+ if (typeof apiMod?.trace?.getTracerProvider !== "function") {
1190
+ logger.warn("[gateway-security] @opentelemetry/api has unexpected shape — plugin skipped");
1191
+ return {};
1192
+ }
1193
+ const plugin = envelopMod.useOpenTelemetry({
1180
1194
  spans: {
1181
1195
  execute: true,
1182
1196
  parse: true,
@@ -1184,10 +1198,12 @@ const createOtelPlugin = async (cfg) => {
1184
1198
  subscribe: true
1185
1199
  },
1186
1200
  resolvers: false
1187
- });
1201
+ }, apiMod.trace.getTracerProvider());
1202
+ logger.info("[gateway-security] @envelop/opentelemetry plugin loaded", { serviceName: cfg.serviceName });
1203
+ return plugin;
1188
1204
  } catch (err) {
1189
1205
  const e = err instanceof Error ? err : new Error(String(err));
1190
- logger.warn("[gateway-security] @envelop/opentelemetry not installed — plugin skipped", { error: e.message });
1206
+ logger.warn("[gateway-security] @envelop/opentelemetry could not be loaded — plugin skipped", { error: e.message });
1191
1207
  return {};
1192
1208
  }
1193
1209
  };
@@ -1644,4 +1660,4 @@ var security_exports = /* @__PURE__ */ __exportAll({
1644
1660
  });
1645
1661
 
1646
1662
  export { DEFAULT_COST_MAP as C, resolveTiersFromEnv as S, resolveActor as T, getSecurityValkey as _, createQueryComplexityPlugin as a, resolveSecurityOptionsFromEnv as b, shutdownOtel as c, __resetMetricsForTest as d, getMetrics as f, __setSecurityValkeyForTest as g, MemoryValkey as h, createRateLimitPlugin as i, createOperationTimeoutPlugin as l, scrapeMetrics as m, buildSecurityPlugins as n, createOtelPlugin as o, initializeMetrics as p, checkRateLimit as r, initializeOtel as s, security_exports as t, createArmorPlugins as u, initializeSecurityValkey as v, mergeCostMap as w, DEFAULT_TIERS as x, DEFAULT_ARMOR_CONFIG as y };
1647
- //# sourceMappingURL=security-DIG-95Ic.js.map
1663
+ //# sourceMappingURL=security-casihGNW.js.map