@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.
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +1 -1
- package/dist/{auth-C5ctwSLp.js → auth-DqD4_tHM.js} +39 -6
- package/dist/auth-DqD4_tHM.js.map +1 -0
- package/dist/{client-BgAEvDC2.d.ts → client-NknQrWsP.d.ts} +3 -1
- package/dist/feature-flags/index.d.ts +1 -1
- package/dist/graph/index.d.ts +1 -1
- package/dist/graph/index.js +2 -2
- package/dist/{graph-Egewc_K7.js → graph-BdoM7_90.js} +2 -2
- package/dist/{graph-Egewc_K7.js.map → graph-BdoM7_90.js.map} +1 -1
- package/dist/{index-HeUeEsMU.d.ts → index-BaskMO3C.d.ts} +8 -2
- package/dist/{index-479i3w77.d.ts → index-BgOU0pxB.d.ts} +30 -5
- package/dist/{index-FKohsiex.d.ts → index-BrRQe24P.d.ts} +3 -2
- package/dist/{index-BiTzGUZP.d.ts → index-BwgBHUuX.d.ts} +2 -2
- package/dist/{index-DMeQh75K.d.ts → index-CIayzveI.d.ts} +1 -1
- package/dist/{index-DSA8h4W3.d.ts → index-CUiL43SY.d.ts} +2 -2
- package/dist/{index-CzMD97-N.d.ts → index-CkQieKSy.d.ts} +16 -2
- package/dist/{index-nP7g1FZm.d.ts → index-DFEKBKBE.d.ts} +4 -1
- package/dist/{index-DhFP_AIB.d.ts → index-DkitHCtV.d.ts} +1 -1
- package/dist/index.d.ts +8 -8
- package/dist/index.js +7 -7
- package/dist/init/index.js +1 -1
- package/dist/{init-B1DRke7D.js → init-4vv4gYEm.js} +2 -2
- package/dist/{init-B1DRke7D.js.map → init-4vv4gYEm.js.map} +1 -1
- package/dist/instrumentation/index.d.ts +2 -2
- package/dist/instrumentation/index.js +3 -3
- package/dist/{instrumentation-SvRAUsCQ.js → instrumentation-C738xDj8.js} +45 -6
- package/dist/instrumentation-C738xDj8.js.map +1 -0
- package/dist/lake/index.d.ts +52 -3
- package/dist/lake/index.js +238 -9
- package/dist/lake/index.js.map +1 -1
- package/dist/metrics/index.js +1 -1
- package/dist/{metrics-BfG_SWb_.js → metrics-CQaHT12m.js} +2 -2
- package/dist/{metrics-BfG_SWb_.js.map → metrics-CQaHT12m.js.map} +1 -1
- package/dist/{metrics-collector-6S-7Smug.js → metrics-collector-DXQrMUle.js} +117 -116
- package/dist/metrics-collector-DXQrMUle.js.map +1 -0
- package/dist/{middleware-B9eyLP7A.js → middleware-z8KzMFU_.js} +95 -5
- package/dist/middleware-z8KzMFU_.js.map +1 -0
- package/dist/prisma/index.d.ts +3 -3
- package/dist/prisma/index.js +3 -3
- package/dist/{prisma-CML_Prrn.js → prisma-J-ZUmVWJ.js} +4 -2
- package/dist/{prisma-CML_Prrn.js.map → prisma-J-ZUmVWJ.js.map} +1 -1
- package/dist/{rate-limit-CBrK_U5H.js → rate-limit-ISSpByjW.js} +25 -25
- package/dist/rate-limit-ISSpByjW.js.map +1 -0
- package/dist/resource-caps/index.d.ts +77 -0
- package/dist/resource-caps/index.js +235 -31
- package/dist/resource-caps/index.js.map +1 -1
- package/dist/security/index.d.ts +1 -1
- package/dist/security/index.js +1 -1
- package/dist/security/rate-limit/index.d.ts +1 -1
- package/dist/security/rate-limit/index.js +1 -1
- package/dist/server/index.d.ts +4 -4
- package/dist/server/index.js +112 -6
- package/dist/server/index.js.map +1 -1
- package/dist/tags/index.d.ts +1 -1
- package/dist/tags/index.js +1 -1
- package/dist/{tags-CbijgoqR.js → tags-C316oA9r.js} +14 -3
- package/dist/{tags-CbijgoqR.js.map → tags-C316oA9r.js.map} +1 -1
- package/dist/telemetry/index.d.ts +1 -1
- package/dist/telemetry/index.js +1 -1
- package/dist/{types-De_pO1Wz.d.ts → types-BWN8tMdF.d.ts} +5 -1
- package/dist/utils/index.d.ts +2 -2
- package/dist/utils/index.js +2 -2
- package/dist/{utils-DL85Tnbn.js → utils-DpW6K_iB.js} +24 -7
- package/dist/{utils-DL85Tnbn.js.map → utils-DpW6K_iB.js.map} +1 -1
- package/package.json +1 -1
- package/dist/auth-C5ctwSLp.js.map +0 -1
- package/dist/instrumentation-SvRAUsCQ.js.map +0 -1
- package/dist/metrics-collector-6S-7Smug.js.map +0 -1
- package/dist/middleware-B9eyLP7A.js.map +0 -1
- 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;CACn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Y;CAC3B,IAAI,OAAO,UAAU,OAAO,QAAQ,OAAO;CAE3C,IAAI,OAAO,gBAAgB,OAAO,cAAc,OAAO,SAAS,OAAO,QACrE,OAAO;CAET,OAAO;AACT;AAEA,SAAS,kBAAkB,KAAuF;CAChH,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO,CAAC;CAC7C,MAAM,MAA6C,CAAC;CACpD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,GAAG,GAC3C,IAAI,OAAO,yBAAyB,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,GACpF,IAAI,OAAuB,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC;CAG5D,OAAO;AACT;AAMA,IAAI,kBAA6C;;;;;AAMjD,SAAgB,gBAAgB,QAAiD;CAC/E,IAAI,CAAC,iBACH,kBAAkB,IAAI,mBAAmB,MAAM;MAC1C,IAAI,QAIT,gBAAgB,UAAU,MAAM;CAElC,OAAO;AACT;;;;;;;AAQA,SAAgB,sBAAsB,QAAgD;CACpF,MAAM,WAAW,gBAAgB;CACjC,SAAS,UAAU,MAAM;CACzB,OAAO;AACT;;AAGA,SAAgB,8BAAoC;CAClD,kBAAkB;AACpB"}
|
|
1
|
+
{"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;EA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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"}
|
package/dist/security/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as index_d_exports } from "../index-
|
|
1
|
+
import { t as index_d_exports } from "../index-DkitHCtV.js";
|
|
2
2
|
export { index_d_exports as RateLimit };
|
package/dist/security/index.js
CHANGED
|
@@ -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-
|
|
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-
|
|
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
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { C as VerifiedDelegationContext, D as WorkspaceGuardConfig, E as YogaPlugin, O as WorkspaceMembershipValidation, S as ServerInstance, T as WspaceGraphQLContext, _ as RESTEndpoint, a as IActor, b as ServerI18nConfig, c as IOrganization, d as ITenant, f as ITracking, g as PrismaClientConstructor, h as ModuleGraphConfig, i as GraphQLContext, k as createWorkspaceGuardPlugin, l as IProduct, m as JWTPayload, n as ConsentContext, o as IContextFilterInput, p as IWorkspace, r as ElysiaApp, s as IOperationContext, t as ActorProvenance, u as IProject, v as ServerConfig, w as WorkspaceSecret, x as ServerInfo, y as ServerDefinition } from "../types-
|
|
2
|
-
import { n as PrismaClientBase } from "../client-
|
|
1
|
+
import { C as VerifiedDelegationContext, D as WorkspaceGuardConfig, E as YogaPlugin, O as WorkspaceMembershipValidation, S as ServerInstance, T as WspaceGraphQLContext, _ as RESTEndpoint, a as IActor, b as ServerI18nConfig, c as IOrganization, d as ITenant, f as ITracking, g as PrismaClientConstructor, h as ModuleGraphConfig, i as GraphQLContext, k as createWorkspaceGuardPlugin, l as IProduct, m as JWTPayload, n as ConsentContext, o as IContextFilterInput, p as IWorkspace, r as ElysiaApp, s as IOperationContext, t as ActorProvenance, u as IProject, v as ServerConfig, w as WorkspaceSecret, x as ServerInfo, y as ServerDefinition } from "../types-BWN8tMdF.js";
|
|
2
|
+
import { n as PrismaClientBase } from "../client-NknQrWsP.js";
|
|
3
3
|
import { a as ActorOrigin, c as readAssistantSessionAttribution, i as ASSISTANT_SESSION_ID_HEADER, l as toAssistantSessionAttribution, n as AI_ASSISTANT_ACTOR_ORIGIN, o as AssistantSessionAttribution, r as ASSISTANT_CORRELATION_ID_HEADER, s as parseAssistantSessionHeaders, t as ACTOR_ORIGIN_HEADER } from "../assistant-session-DA5ZKJOr.js";
|
|
4
4
|
import { r as I18nContext, s as LocaleCode } from "../types-DgaQqvxo.js";
|
|
5
|
-
import { $ as
|
|
5
|
+
import { $ as configureServerAuth, A as assertDsarOrchestrator, B as getContextOptions, C as DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, D as DsarOrchestratorRejectionReason, E as DsarOrchestratorOptions, F as getDelegatedPrincipal, G as PayloadTooLargeError, H as DEFAULT_RAW_BODY_MAX_BYTES, I as resolveOnBehalfOf, J as createRawBodyRouter, K as RawBodyResolution, L as ContextBuilderOptions, M as isDsarOrchestratorActor, N as resolveDsarCallerIdentity, O as ResolvedDsarCaller, P as DelegatedPrincipal, Q as resolveMaxRequestBodySize, R as buildContext, S as DSAR_ALLOWED_ORCHESTRATORS_ENV, T as DsarOrchestratorForbiddenError, U as MAX_IDLE_TIMEOUT_SECONDS, V as DEFAULT_MAX_REQUEST_BODY_SIZE, W as OrdinaryRoute, X as readBoundedRawBody, Y as extendRequestIdleTimeout, Z as resolveBodyLimitBytes, _ as MutationAuditPluginOptions, a as UserFacingErrorOptions, at as configureDefaultAuth, b as sanitizeAuditValue, c as createHumanReadableErrorPlugin, ct as generateSymmetricSecret, d as normalizeExecutionResultErrors, dt as tenantCheck, et as createServer, f as normalizeGraphQLResponse, ft as verifyJWT, g as MUTATION_AUDIT_RESOURCE_TYPE, h as MUTATION_AUDIT_ACTIVITY_TYPE, i as NormalizedErrorState, it as configureAuth, j as getAllowedDsarOrchestrators, k as VERIFIED_SERVICE_IDENTITY_HEADER, l as formatHttpError, lt as orgCheck, m as toUserFacingGraphQLError, n as HttpErrorPayload, nt as FetchWorkspaceSecretFn, o as UserFacingGraphQLError, ot as decodeJWT, p as normalizeGraphQLResponsePayload, pt as workspaceCheck, q as RawBodyRouter, r as HttpErrorResult, rt as authCheck, s as createHttpErrorResponse, st as fetchWorkspaceSecret, t as ErrorNormalizationOptions, tt as AuthConfig, u as normalizeError, ut as requireWorkspace, v as createMutationAuditPlugin, w as DsarOrchestratorContext, x as DEFAULT_DSAR_ORCHESTRATOR_ID, y as getMutationFieldNames, z as configureContext } from "../index-CkQieKSy.js";
|
|
6
6
|
import { t as suppressMutationAudit } from "../explicit-activity-scope-D8VeGGpt.js";
|
|
7
|
-
export { ACTOR_ORIGIN_HEADER, AI_ASSISTANT_ACTOR_ORIGIN, ASSISTANT_CORRELATION_ID_HEADER, ASSISTANT_SESSION_ID_HEADER, type ActorOrigin, type ActorProvenance, type AssistantSessionAttribution, type AuthConfig, type ConsentContext, type ContextBuilderOptions, DEFAULT_DSAR_ORCHESTRATOR_ID, DSAR_ALLOWED_ORCHESTRATORS_ENV, DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, type DelegatedPrincipal, type DsarOrchestratorContext, DsarOrchestratorForbiddenError, type DsarOrchestratorOptions, type DsarOrchestratorRejectionReason, type ElysiaApp, type ErrorNormalizationOptions, type FetchWorkspaceSecretFn, type GraphQLContext, type HttpErrorPayload, type HttpErrorResult, type I18nContext, type IActor, type IContextFilterInput, type IOperationContext, type IOrganization, type IProduct, type IProject, type ITenant, type ITracking, type IWorkspace, type JWTPayload, type LocaleCode, MAX_IDLE_TIMEOUT_SECONDS, MUTATION_AUDIT_ACTIVITY_TYPE, MUTATION_AUDIT_RESOURCE_TYPE, type ModuleGraphConfig, type MutationAuditPluginOptions, type NormalizedErrorState, type OrdinaryRoute, type PrismaClientBase, type PrismaClientConstructor, type RESTEndpoint, type RawBodyResolution, type RawBodyRouter, type ResolvedDsarCaller, type ServerConfig, type ServerDefinition, type ServerI18nConfig, type ServerInfo, type ServerInstance, type UserFacingErrorOptions, UserFacingGraphQLError, VERIFIED_SERVICE_IDENTITY_HEADER, type VerifiedDelegationContext, type WorkspaceGuardConfig, type WorkspaceMembershipValidation, type WorkspaceSecret, type WspaceGraphQLContext, type YogaPlugin, assertDsarOrchestrator, authCheck, buildContext, configureAuth, configureContext, configureDefaultAuth, configureServerAuth, createHttpErrorResponse, createHumanReadableErrorPlugin, createMutationAuditPlugin, createRawBodyRouter, createServer, createWorkspaceGuardPlugin, decodeJWT, extendRequestIdleTimeout, fetchWorkspaceSecret, formatHttpError, generateSymmetricSecret, getAllowedDsarOrchestrators, getContextOptions, getDelegatedPrincipal, getMutationFieldNames, isDsarOrchestratorActor, normalizeError, normalizeExecutionResultErrors, normalizeGraphQLResponse, normalizeGraphQLResponsePayload, orgCheck, parseAssistantSessionHeaders, readAssistantSessionAttribution, requireWorkspace, resolveDsarCallerIdentity, resolveOnBehalfOf, sanitizeAuditValue, suppressMutationAudit, tenantCheck, toAssistantSessionAttribution, toUserFacingGraphQLError, verifyJWT, workspaceCheck };
|
|
7
|
+
export { ACTOR_ORIGIN_HEADER, AI_ASSISTANT_ACTOR_ORIGIN, ASSISTANT_CORRELATION_ID_HEADER, ASSISTANT_SESSION_ID_HEADER, type ActorOrigin, type ActorProvenance, type AssistantSessionAttribution, type AuthConfig, type ConsentContext, type ContextBuilderOptions, DEFAULT_DSAR_ORCHESTRATOR_ID, DEFAULT_MAX_REQUEST_BODY_SIZE, DEFAULT_RAW_BODY_MAX_BYTES, DSAR_ALLOWED_ORCHESTRATORS_ENV, DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, type DelegatedPrincipal, type DsarOrchestratorContext, DsarOrchestratorForbiddenError, type DsarOrchestratorOptions, type DsarOrchestratorRejectionReason, type ElysiaApp, type ErrorNormalizationOptions, type FetchWorkspaceSecretFn, type GraphQLContext, type HttpErrorPayload, type HttpErrorResult, type I18nContext, type IActor, type IContextFilterInput, type IOperationContext, type IOrganization, type IProduct, type IProject, type ITenant, type ITracking, type IWorkspace, type JWTPayload, type LocaleCode, MAX_IDLE_TIMEOUT_SECONDS, MUTATION_AUDIT_ACTIVITY_TYPE, MUTATION_AUDIT_RESOURCE_TYPE, type ModuleGraphConfig, type MutationAuditPluginOptions, type NormalizedErrorState, type OrdinaryRoute, PayloadTooLargeError, type PrismaClientBase, type PrismaClientConstructor, type RESTEndpoint, type RawBodyResolution, type RawBodyRouter, type ResolvedDsarCaller, type ServerConfig, type ServerDefinition, type ServerI18nConfig, type ServerInfo, type ServerInstance, type UserFacingErrorOptions, UserFacingGraphQLError, VERIFIED_SERVICE_IDENTITY_HEADER, type VerifiedDelegationContext, type WorkspaceGuardConfig, type WorkspaceMembershipValidation, type WorkspaceSecret, type WspaceGraphQLContext, type YogaPlugin, assertDsarOrchestrator, authCheck, buildContext, configureAuth, configureContext, configureDefaultAuth, configureServerAuth, createHttpErrorResponse, createHumanReadableErrorPlugin, createMutationAuditPlugin, createRawBodyRouter, createServer, createWorkspaceGuardPlugin, decodeJWT, extendRequestIdleTimeout, fetchWorkspaceSecret, formatHttpError, generateSymmetricSecret, getAllowedDsarOrchestrators, getContextOptions, getDelegatedPrincipal, getMutationFieldNames, isDsarOrchestratorActor, normalizeError, normalizeExecutionResultErrors, normalizeGraphQLResponse, normalizeGraphQLResponsePayload, orgCheck, parseAssistantSessionHeaders, readAssistantSessionAttribution, readBoundedRawBody, requireWorkspace, resolveBodyLimitBytes, resolveDsarCallerIdentity, resolveMaxRequestBodySize, resolveOnBehalfOf, sanitizeAuditValue, suppressMutationAudit, tenantCheck, toAssistantSessionAttribution, toUserFacingGraphQLError, verifyJWT, workspaceCheck };
|
package/dist/server/index.js
CHANGED
|
@@ -4,8 +4,8 @@ import { c as ACTOR_ORIGIN_HEADER, d as ASSISTANT_SESSION_ID_HEADER, f as parseA
|
|
|
4
4
|
import { h as withWorkspaceContext, m as setWorkspaceContext } from "../workspace-extension-COrC0dYi.js";
|
|
5
5
|
import { ContextManager } from "../context/index.js";
|
|
6
6
|
import { l as I18n } from "../i18n-BBMYFd0P.js";
|
|
7
|
-
import {
|
|
8
|
-
import { t as getWorkspaceQuotaRegistry } from "../metrics-
|
|
7
|
+
import { l as getMetricsRegistry } from "../metrics-collector-DXQrMUle.js";
|
|
8
|
+
import { t as getWorkspaceQuotaRegistry } from "../metrics-CQaHT12m.js";
|
|
9
9
|
import { t as collectPromDefaultMetrics } from "../bun-runtime-metrics-CPy5D6NT.js";
|
|
10
10
|
import { a as VERIFIED_SERVICE_IDENTITY_HEADER, c as isDsarOrchestratorActor, i as DsarOrchestratorForbiddenError, l as resolveDsarCallerIdentity, n as DSAR_ALLOWED_ORCHESTRATORS_ENV, o as assertDsarOrchestrator, r as DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, s as getAllowedDsarOrchestrators, t as DEFAULT_DSAR_ORCHESTRATOR_ID } from "../dsar-orchestrator-BlOSa9A_.js";
|
|
11
11
|
import { i as suppressMutationAudit, r as runInExplicitActivityScope, t as createExplicitActivityScope } from "../explicit-activity-scope-DikJ7NAE.js";
|
|
@@ -827,6 +827,95 @@ function rememberRequestServer(request, server) {
|
|
|
827
827
|
}
|
|
828
828
|
/** Bun caps a connection's idle timeout at 255 seconds. */
|
|
829
829
|
const MAX_IDLE_TIMEOUT_SECONDS = 255;
|
|
830
|
+
/** Default maximum body size buffered for `rawBody: true` REST endpoints (1 MiB). */
|
|
831
|
+
const DEFAULT_RAW_BODY_MAX_BYTES = 1048576;
|
|
832
|
+
/** Default server-wide Bun `maxRequestBodySize` ceiling (10 MiB, down from Bun's 128 MiB default). */
|
|
833
|
+
const DEFAULT_MAX_REQUEST_BODY_SIZE = 10485760;
|
|
834
|
+
/**
|
|
835
|
+
* Thrown by {@link readBoundedRawBody} when a `rawBody: true` request declares
|
|
836
|
+
* or streams more bytes than its configured limit.
|
|
837
|
+
*/
|
|
838
|
+
var PayloadTooLargeError = class extends Error {
|
|
839
|
+
status = 413;
|
|
840
|
+
code = "PAYLOAD_TOO_LARGE";
|
|
841
|
+
maxBodyBytes;
|
|
842
|
+
constructor(maxBodyBytes) {
|
|
843
|
+
super(`Request body exceeds maximum allowed size of ${maxBodyBytes} bytes`);
|
|
844
|
+
this.name = "PayloadTooLargeError";
|
|
845
|
+
this.maxBodyBytes = maxBodyBytes;
|
|
846
|
+
}
|
|
847
|
+
};
|
|
848
|
+
/**
|
|
849
|
+
* Validate and normalize a configured byte cap. Rejects negative, NaN, or
|
|
850
|
+
* non-finite values by falling back to `fallback`.
|
|
851
|
+
*/
|
|
852
|
+
function resolveBodyLimitBytes(configured, fallback) {
|
|
853
|
+
if (typeof configured === "number" && Number.isFinite(configured) && configured >= 0) return Math.floor(configured);
|
|
854
|
+
return fallback;
|
|
855
|
+
}
|
|
856
|
+
/**
|
|
857
|
+
* Compute the explicit `maxRequestBodySize` to pass to `app.listen()` /
|
|
858
|
+
* `Bun.serve()`, honoring an explicit server override or automatically sizing
|
|
859
|
+
* to fit any opted-in large `rawBody` endpoint while staying well below Bun's
|
|
860
|
+
* 128 MiB default.
|
|
861
|
+
*/
|
|
862
|
+
function resolveMaxRequestBodySize(config, endpoints = []) {
|
|
863
|
+
if (typeof config.maxRequestBodySize === "number" && Number.isFinite(config.maxRequestBodySize) && config.maxRequestBodySize > 0) return Math.floor(config.maxRequestBodySize);
|
|
864
|
+
const defaultRawLimit = resolveBodyLimitBytes(config.maxBodyBytes, DEFAULT_RAW_BODY_MAX_BYTES);
|
|
865
|
+
let highestRawLimit = defaultRawLimit;
|
|
866
|
+
for (const endpoint of endpoints) {
|
|
867
|
+
if (!endpoint.rawBody) continue;
|
|
868
|
+
const limit = resolveBodyLimitBytes(endpoint.maxBodyBytes, defaultRawLimit);
|
|
869
|
+
if (limit > highestRawLimit) highestRawLimit = limit;
|
|
870
|
+
}
|
|
871
|
+
return Math.max(DEFAULT_MAX_REQUEST_BODY_SIZE, highestRawLimit);
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* Read a request's raw body as UTF-8 while strictly enforcing `maxBodyBytes`.
|
|
875
|
+
*
|
|
876
|
+
* 1. Pre-rejects immediately on an oversized `Content-Length` header without
|
|
877
|
+
* buffering any chunks.
|
|
878
|
+
* 2. Streams `request.body` chunk-by-chunk, counting raw UTF-8 bytes and
|
|
879
|
+
* cancelling the stream immediately on overflow (handles chunked transfer
|
|
880
|
+
* encoding and spoofed/missing `Content-Length`).
|
|
881
|
+
*/
|
|
882
|
+
async function readBoundedRawBody(request, maxBodyBytes = DEFAULT_RAW_BODY_MAX_BYTES) {
|
|
883
|
+
const limit = resolveBodyLimitBytes(maxBodyBytes, DEFAULT_RAW_BODY_MAX_BYTES);
|
|
884
|
+
const contentLengthHeader = request.headers.get("content-length")?.trim();
|
|
885
|
+
if (contentLengthHeader && /^\d+$/.test(contentLengthHeader)) {
|
|
886
|
+
if (Number.parseInt(contentLengthHeader, 10) > limit) {
|
|
887
|
+
if (request.body) await request.body.cancel().catch(() => void 0);
|
|
888
|
+
throw new PayloadTooLargeError(limit);
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
if (!request.body) return "";
|
|
892
|
+
const reader = request.body.getReader();
|
|
893
|
+
const chunks = [];
|
|
894
|
+
let totalBytes = 0;
|
|
895
|
+
try {
|
|
896
|
+
for (;;) {
|
|
897
|
+
const { done, value } = await reader.read();
|
|
898
|
+
if (done) break;
|
|
899
|
+
if (!value || value.byteLength === 0) continue;
|
|
900
|
+
totalBytes += value.byteLength;
|
|
901
|
+
if (totalBytes > limit) {
|
|
902
|
+
await reader.cancel().catch(() => void 0);
|
|
903
|
+
throw new PayloadTooLargeError(limit);
|
|
904
|
+
}
|
|
905
|
+
chunks.push(value);
|
|
906
|
+
}
|
|
907
|
+
} finally {
|
|
908
|
+
reader.releaseLock();
|
|
909
|
+
}
|
|
910
|
+
if (totalBytes === 0) return "";
|
|
911
|
+
const combined = new Uint8Array(totalBytes);
|
|
912
|
+
let offset = 0;
|
|
913
|
+
for (const chunk of chunks) {
|
|
914
|
+
combined.set(chunk, offset);
|
|
915
|
+
offset += chunk.byteLength;
|
|
916
|
+
}
|
|
917
|
+
return new TextDecoder("utf-8").decode(combined);
|
|
918
|
+
}
|
|
830
919
|
/**
|
|
831
920
|
* Let one raw-body request stay idle for longer than the server default (Elysia's Bun adapter sets
|
|
832
921
|
* 30 s). For handlers that legitimately hold a request open — a webhook answering with its
|
|
@@ -1434,6 +1523,8 @@ async function createServer(definition) {
|
|
|
1434
1523
|
]
|
|
1435
1524
|
}));
|
|
1436
1525
|
const rawBodyRouter = createRawBodyRouter(restEndpoints || [], () => app.routes);
|
|
1526
|
+
const defaultRawBodyMaxBytes = resolveBodyLimitBytes(config.maxBodyBytes, DEFAULT_RAW_BODY_MAX_BYTES);
|
|
1527
|
+
const maxRequestBodySize = resolveMaxRequestBodySize(config, restEndpoints || []);
|
|
1437
1528
|
app.onRequest(async ({ request, server }) => {
|
|
1438
1529
|
const pathname = new URL(request.url).pathname;
|
|
1439
1530
|
logger.debug(`[Server] onRequest: ${request.method} ${pathname}`);
|
|
@@ -1475,7 +1566,8 @@ async function createServer(definition) {
|
|
|
1475
1566
|
rememberRequestServer(request, server);
|
|
1476
1567
|
const isHead = request.method === "HEAD";
|
|
1477
1568
|
try {
|
|
1478
|
-
const
|
|
1569
|
+
const endpointMaxBodyBytes = resolveBodyLimitBytes(rawBodyEndpoint.maxBodyBytes, defaultRawBodyMaxBytes);
|
|
1570
|
+
const rawBody = await readBoundedRawBody(request, endpointMaxBodyBytes);
|
|
1479
1571
|
const context = await buildContext(request);
|
|
1480
1572
|
const result = await rawBodyEndpoint.handler(request, context, rawBody);
|
|
1481
1573
|
if (result instanceof Response) {
|
|
@@ -1496,8 +1588,21 @@ async function createServer(definition) {
|
|
|
1496
1588
|
headers
|
|
1497
1589
|
});
|
|
1498
1590
|
} catch (error) {
|
|
1591
|
+
if (error instanceof PayloadTooLargeError) {
|
|
1592
|
+
logger.warn(`[Server] Raw body endpoint payload too large (${pathname})`, { maxBodyBytes: error.maxBodyBytes });
|
|
1593
|
+
return new Response(isHead ? null : JSON.stringify({
|
|
1594
|
+
error: "Payload too large",
|
|
1595
|
+
code: error.code,
|
|
1596
|
+
maxBodyBytes: error.maxBodyBytes
|
|
1597
|
+
}), {
|
|
1598
|
+
status: 413,
|
|
1599
|
+
headers: {
|
|
1600
|
+
"Content-Type": "application/json",
|
|
1601
|
+
...corsHeaders
|
|
1602
|
+
}
|
|
1603
|
+
});
|
|
1604
|
+
}
|
|
1499
1605
|
logger.error(`[Server] Raw body endpoint error (${pathname}):`, error);
|
|
1500
|
-
const corsHeaders = buildCorsHeaders();
|
|
1501
1606
|
const formatted = formatHttpError(error, {
|
|
1502
1607
|
serviceName: config.serviceName,
|
|
1503
1608
|
environment: config.environment
|
|
@@ -1665,7 +1770,8 @@ async function createServer(definition) {
|
|
|
1665
1770
|
serverStartTime = /* @__PURE__ */ new Date();
|
|
1666
1771
|
app.listen({
|
|
1667
1772
|
port,
|
|
1668
|
-
hostname: host
|
|
1773
|
+
hostname: host,
|
|
1774
|
+
maxRequestBodySize
|
|
1669
1775
|
});
|
|
1670
1776
|
serverInstance.server = app.server;
|
|
1671
1777
|
logger.info(`🚀 ${config.serviceName} is running at http://${host}:${port}${graphqlEndpoint}`);
|
|
@@ -2129,5 +2235,5 @@ function createMutationAuditPlugin(options) {
|
|
|
2129
2235
|
} };
|
|
2130
2236
|
}
|
|
2131
2237
|
|
|
2132
|
-
export { ACTOR_ORIGIN_HEADER, AI_ASSISTANT_ACTOR_ORIGIN, ASSISTANT_CORRELATION_ID_HEADER, ASSISTANT_SESSION_ID_HEADER, DEFAULT_DSAR_ORCHESTRATOR_ID, DSAR_ALLOWED_ORCHESTRATORS_ENV, DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, DsarOrchestratorForbiddenError, MAX_IDLE_TIMEOUT_SECONDS, MUTATION_AUDIT_ACTIVITY_TYPE, MUTATION_AUDIT_RESOURCE_TYPE, UserFacingGraphQLError, VERIFIED_SERVICE_IDENTITY_HEADER, assertDsarOrchestrator, authCheck, buildContext, configureAuth, configureContext, configureDefaultAuth, configureServerAuth, createHttpErrorResponse, createHumanReadableErrorPlugin, createMutationAuditPlugin, createRawBodyRouter, createServer, createWorkspaceGuardPlugin, decodeJWT, extendRequestIdleTimeout, fetchWorkspaceSecret, formatHttpError, generateSymmetricSecret, getAllowedDsarOrchestrators, getContextOptions, getDelegatedPrincipal, getMutationFieldNames, isDsarOrchestratorActor, normalizeError, normalizeExecutionResultErrors, normalizeGraphQLResponse, normalizeGraphQLResponsePayload, orgCheck, parseAssistantSessionHeaders, readAssistantSessionAttribution, requireWorkspace, resolveDsarCallerIdentity, resolveOnBehalfOf, sanitizeAuditValue, suppressMutationAudit, tenantCheck, toAssistantSessionAttribution, toUserFacingGraphQLError, verifyJWT, workspaceCheck };
|
|
2238
|
+
export { ACTOR_ORIGIN_HEADER, AI_ASSISTANT_ACTOR_ORIGIN, ASSISTANT_CORRELATION_ID_HEADER, ASSISTANT_SESSION_ID_HEADER, DEFAULT_DSAR_ORCHESTRATOR_ID, DEFAULT_MAX_REQUEST_BODY_SIZE, DEFAULT_RAW_BODY_MAX_BYTES, DSAR_ALLOWED_ORCHESTRATORS_ENV, DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, DsarOrchestratorForbiddenError, MAX_IDLE_TIMEOUT_SECONDS, MUTATION_AUDIT_ACTIVITY_TYPE, MUTATION_AUDIT_RESOURCE_TYPE, PayloadTooLargeError, UserFacingGraphQLError, VERIFIED_SERVICE_IDENTITY_HEADER, assertDsarOrchestrator, authCheck, buildContext, configureAuth, configureContext, configureDefaultAuth, configureServerAuth, createHttpErrorResponse, createHumanReadableErrorPlugin, createMutationAuditPlugin, createRawBodyRouter, createServer, createWorkspaceGuardPlugin, decodeJWT, extendRequestIdleTimeout, fetchWorkspaceSecret, formatHttpError, generateSymmetricSecret, getAllowedDsarOrchestrators, getContextOptions, getDelegatedPrincipal, getMutationFieldNames, isDsarOrchestratorActor, normalizeError, normalizeExecutionResultErrors, normalizeGraphQLResponse, normalizeGraphQLResponsePayload, orgCheck, parseAssistantSessionHeaders, readAssistantSessionAttribution, readBoundedRawBody, requireWorkspace, resolveBodyLimitBytes, resolveDsarCallerIdentity, resolveMaxRequestBodySize, resolveOnBehalfOf, sanitizeAuditValue, suppressMutationAudit, tenantCheck, toAssistantSessionAttribution, toUserFacingGraphQLError, verifyJWT, workspaceCheck };
|
|
2133
2239
|
//# sourceMappingURL=index.js.map
|