@lumoauth/backend 1.1.0 → 1.2.0

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/README.md CHANGED
@@ -133,7 +133,7 @@ from `LUMOAUTH_URL` and `LUMOAUTH_SECRET_KEY`.
133
133
  | `approvals` | Push approval for agent actions (agent credentials only) | `require`, `create`, `getStatus`, `wait` |
134
134
  | `delegation` | Act for a user with RFC 8693 token exchange | `getConsentUrl`, `handleConsentCallback`, `setUserToken`, `exchange`, `request`, `delegateToSubAgent`, `revoke`, `revokeAll` |
135
135
  | `jit` | Just-in-time permissions | `createTask`, `requestPermission`, `getRequestStatus`, `getToken`, `evaluateTask`, `completeTask`, `listPendingRequests` |
136
- | `mcp` | Tokens for secured MCP servers | `getToken`, `getTokenDetailed`. The server ID is the MCP server's https URL, which becomes the token's `aud` |
136
+ | `mcp` | Secured MCP servers | `getToken`, `getTokenDetailed`. The server ID is the MCP server's https URL, which becomes the token's `aud`. `authorizeTool({ serverId, subject, tool })` checks one tool call. The `secretKey` must be the MCP server's own client-credentials token with `mcp:authorize`. A deny returns `allowed: false` |
137
137
 
138
138
  `lumo.clearCache()` clears the permission cache. The parameters, return
139
139
  values and required credentials of every method are in the
package/dist/index.d.mts CHANGED
@@ -95,7 +95,7 @@ declare class LumoAuthBackend {
95
95
  readonly delegation: DelegationModule;
96
96
  /** Just-in-Time permissions — ephemeral tasks and scoped tokens. */
97
97
  readonly jit: JitModule;
98
- /** Token exchange for secured MCP servers. */
98
+ /** MCP servers: token exchange and per-tool checks (`authorizeTool`). */
99
99
  readonly mcp: McpModule;
100
100
  private readonly http;
101
101
  private readonly baseUrl;
package/dist/index.d.ts CHANGED
@@ -95,7 +95,7 @@ declare class LumoAuthBackend {
95
95
  readonly delegation: DelegationModule;
96
96
  /** Just-in-Time permissions — ephemeral tasks and scoped tokens. */
97
97
  readonly jit: JitModule;
98
- /** Token exchange for secured MCP servers. */
98
+ /** MCP servers: token exchange and per-tool checks (`authorizeTool`). */
99
99
  readonly mcp: McpModule;
100
100
  private readonly http;
101
101
  private readonly baseUrl;
package/dist/index.js CHANGED
@@ -78,7 +78,8 @@ var LumoAuthBackend = class {
78
78
  baseUrl: this.baseUrl,
79
79
  orgId,
80
80
  token: this.secretProvider,
81
- fetch: config.fetch
81
+ fetch: config.fetch,
82
+ http: this.http
82
83
  });
83
84
  this.delegation = new import_shared2.DelegationModule({
84
85
  baseUrl: this.baseUrl,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../../../node_modules/tsup/assets/cjs_shims.js","../src/backend.ts","../src/guard.ts"],"sourcesContent":["// @lumoauth/backend — the server SDK.\n//\n// The counterpart to @lumoauth/client. This package expects server\n// credentials (a tenant API key, `lmk_…`, or a machine token) and refuses to\n// construct in a browser, so a server credential cannot reach a client bundle\n// by accident.\n//\n// For the full REST surface — every admin endpoint, SCIM, audit logs — use\n// the `lumo.api` escape hatch, which lazily loads the generated client\n// `@lumoauth/api-client` pre-configured with this backend's credential. It is\n// declared as an optional peer dependency because the generated client is not\n// yet published to a registry.\n// TODO(publish): once @lumoauth/api-client is published, drop\n// `peerDependenciesMeta.optional` in package.json so installs pull it in by\n// default (the lazy getter already handles both cases).\n\nexport {\n LumoAuthBackend,\n type LumoAuthBackendConfig,\n type LumoAuthApiEscapeHatch,\n} from './backend';\nexport { assertServerOnly } from './guard';\n\n// The full isomorphic surface: authorization modules, OAuth/PKCE helpers,\n// schemas, errors, and the HTTP client.\nexport * from '@lumoauth/shared';\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","import {\n HttpClient,\n type HttpClientConfig,\n PermissionsModule,\n type PermissionsModuleOptions,\n ZanzibarModule,\n AbacModule,\n AuthModule,\n type AuthModuleConfig,\n AgentsModule,\n ApprovalsModule,\n DelegationModule,\n JitModule,\n McpModule,\n LumoAuthConfigError,\n} from '@lumoauth/shared';\nimport { createRequire } from 'node:module';\nimport { assertServerOnly } from './guard';\n\nexport interface LumoAuthBackendConfig {\n /**\n * Base URL of your LumoAuth instance.\n * @example \"https://app.lumoauth.dev\"\n */\n baseUrl: string;\n\n /**\n * Server credential — a tenant API key (`lmk_…`) or a machine access\n * token. Unlike the browser client, this may be a long-lived secret.\n *\n * Load it from the environment. Never inline it, and never expose it\n * through a framework's public-env mechanism (`NEXT_PUBLIC_*`, `VITE_*`).\n */\n secretKey: string | (() => string | Promise<string>);\n\n /** Organization slug. Required for org-scoped surfaces (ABAC, agents). */\n orgId?: string;\n\n /** OAuth client ID, when using the auth or delegation modules server-side. */\n clientId?: string;\n\n /**\n * OAuth client secret for confidential flows — required by\n * `delegation` for the consent-code exchange and revocation.\n */\n clientSecret?: string;\n\n /** OAuth callback URL for the delegation consent flow. */\n redirectUri?: string;\n\n /** Request timeout in milliseconds. */\n timeout?: number;\n\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n\n /** Extra headers applied to every request. */\n headers?: Record<string, string>;\n\n /** Permission cache configuration; `false` disables caching. */\n cache?: boolean | PermissionsModuleOptions['cache'];\n}\n\n/**\n * The generated OpenAPI client (`@lumoauth/api-client`), pre-configured with\n * this backend's base URL and credential. Loosely typed here so the backend\n * package does not take a compile-time dependency on the generated code.\n */\nexport interface LumoAuthApiEscapeHatch {\n /** The raw `@lumoauth/api-client` module (`AgentsApi`, `AdminUsersApi`, …). */\n readonly module: Record<string, unknown>;\n /** A `Configuration` instance carrying this backend's baseUrl + credential. */\n readonly configuration: unknown;\n /**\n * Instantiate a generated API class with this backend's configuration.\n *\n * ```ts\n * const { AdminUsersApi } = lumo.api.module;\n * const users = lumo.api.create(AdminUsersApi);\n * ```\n */\n create<T>(apiClass: new (configuration?: unknown) => T): T;\n}\n\n/**\n * Server-side LumoAuth client.\n *\n * Same authorization surface as `@lumoauth/client`, but credentialed for a\n * server and guarded against browser construction.\n *\n * ```ts\n * // app/api/documents/route.ts\n * import { LumoAuthBackend } from '@lumoauth/backend';\n *\n * const lumo = new LumoAuthBackend({\n * baseUrl: process.env.LUMOAUTH_URL!,\n * secretKey: process.env.LUMOAUTH_SECRET_KEY!,\n * orgId: 'acme-corp',\n * });\n *\n * const allowed = await lumo.permissions.check('documents.edit');\n * ```\n *\n * For admin operations (users, roles, webhooks, audit logs) use the `api`\n * escape hatch — the ~200 generated endpoints are already typed and\n * regenerated from the OpenAPI spec.\n */\nexport class LumoAuthBackend {\n /** RBAC permission checks. */\n public readonly permissions: PermissionsModule;\n /** Zanzibar-style (ReBAC) relationship checks. */\n public readonly zanzibar: ZanzibarModule;\n /** ABAC policy evaluation and attribute management. */\n public readonly abac: AbacModule;\n /** OAuth 2.0 — token exchange and refresh, including confidential clients. */\n public readonly auth: AuthModule;\n /** Agent identity — ask/isAllowed, self-inspection, registration. */\n public readonly agents: AgentsModule;\n /** Push-approval-for-agent-actions. */\n public readonly approvals: ApprovalsModule;\n /** Chain of Agency — RFC 8693 delegation and nested agent chains. */\n public readonly delegation: DelegationModule;\n /** Just-in-Time permissions — ephemeral tasks and scoped tokens. */\n public readonly jit: JitModule;\n /** Token exchange for secured MCP servers. */\n public readonly mcp: McpModule;\n\n private readonly http: HttpClient;\n private readonly baseUrl: string;\n private readonly secretProvider: () => string | Promise<string>;\n private apiInstance: LumoAuthApiEscapeHatch | null = null;\n\n constructor(config: LumoAuthBackendConfig) {\n assertServerOnly('LumoAuthBackend');\n\n if (!config.baseUrl) {\n throw new LumoAuthConfigError('baseUrl is required');\n }\n if (!config.secretKey) {\n throw new LumoAuthConfigError(\n 'secretKey is required. For browser code use @lumoauth/client with a user access token instead.',\n );\n }\n\n this.baseUrl = config.baseUrl.replace(/\\/+$/, '');\n this.secretProvider =\n typeof config.secretKey === 'function'\n ? config.secretKey\n : () => config.secretKey as string;\n\n const httpConfig: HttpClientConfig = {\n baseUrl: config.baseUrl,\n token: config.secretKey,\n timeout: config.timeout,\n fetch: config.fetch,\n headers: config.headers,\n };\n this.http = new HttpClient(httpConfig);\n\n const orgId = config.orgId ?? '';\n\n this.permissions = new PermissionsModule(this.http, { cache: config.cache });\n this.zanzibar = new ZanzibarModule(this.http);\n this.abac = new AbacModule(this.http, orgId);\n this.agents = new AgentsModule(this.http, orgId);\n this.approvals = new ApprovalsModule(this.http, orgId);\n this.jit = new JitModule(this.http, orgId);\n this.mcp = new McpModule({\n baseUrl: this.baseUrl,\n orgId,\n token: this.secretProvider,\n fetch: config.fetch,\n });\n this.delegation = new DelegationModule({\n baseUrl: this.baseUrl,\n orgId,\n clientId: config.clientId ?? '',\n clientSecret: config.clientSecret,\n redirectUri: config.redirectUri,\n agentToken: this.secretProvider,\n fetch: config.fetch,\n });\n\n const authConfig: AuthModuleConfig = {\n baseUrl: config.baseUrl,\n orgId,\n clientId: config.clientId ?? '',\n fetch: config.fetch,\n };\n this.auth = new AuthModule(authConfig);\n }\n\n /**\n * @deprecated Renamed to {@link agents}. This alias will be removed\n * before 2.0.\n */\n get agent(): AgentsModule {\n return this.agents;\n }\n\n /**\n * Escape hatch to the full generated REST surface (`@lumoauth/api-client`)\n * — every admin endpoint, SCIM, audit logs — pre-configured with this\n * backend's base URL and credential.\n *\n * Loaded lazily on first access so apps that never reach for it don't\n * pay for it. Requires `@lumoauth/api-client` to be installed:\n *\n * ```sh\n * npm install @lumoauth/api-client\n * ```\n */\n get api(): LumoAuthApiEscapeHatch {\n if (!this.apiInstance) {\n this.apiInstance = this.loadApiClient();\n }\n return this.apiInstance;\n }\n\n /** Clear all server-side caches. */\n clearCache(): void {\n this.permissions.clearCache();\n }\n\n // ── Internal ──────────────────────────────────────────────────────\n\n private loadApiClient(): LumoAuthApiEscapeHatch {\n let mod: Record<string, unknown>;\n try {\n // Works from both the CJS build (__dirname) and the ESM build\n // (import.meta.url). `@lumoauth/backend` is Node-only, so\n // node:module is always available, and module resolution walks\n // up from this package to the host app's node_modules.\n const requireFn: NodeRequire = createRequire(\n typeof __dirname === 'string' ? `${__dirname}/` : import.meta.url,\n );\n mod = requireFn('@lumoauth/api-client') as Record<string, unknown>;\n } catch (error) {\n throw new LumoAuthConfigError(\n 'lumo.api requires the generated client `@lumoauth/api-client`, which is not installed. ' +\n 'Install it with `npm install @lumoauth/api-client` (it covers the full REST surface — ' +\n 'admin endpoints, SCIM, audit logs) and try again. ' +\n `Original error: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n const ConfigurationCtor = mod.Configuration as\n | (new (params: Record<string, unknown>) => unknown)\n | undefined;\n if (typeof ConfigurationCtor !== 'function') {\n throw new LumoAuthConfigError(\n '@lumoauth/api-client was found but does not export `Configuration` — ' +\n 'is the installed version compatible (>=0.1.0)?',\n );\n }\n\n // The backend credential may be an API key (lmk_…, sent as X-API-Key)\n // or a bearer token (sent as Authorization). The generated client\n // emits a header for every configured scheme, so only the slot\n // matching the credential's shape may be populated.\n const params: Record<string, unknown> = { basePath: this.baseUrl };\n const probe = this.secretProvider();\n if (typeof probe === 'string') {\n if (probe.startsWith('lmk_')) {\n params.apiKey = () => this.secretProvider();\n } else {\n params.accessToken = () => this.secretProvider();\n }\n } else {\n // Async provider: shape unknown until first resolution. Route by\n // shape per call, then drop the mismatched slot so subsequent\n // requests carry exactly one auth header.\n params.apiKey = async () => {\n const secret = await probe;\n if (!secret.startsWith('lmk_')) {\n (configuration as { apiKey?: unknown }).apiKey = undefined;\n return undefined;\n }\n (configuration as { accessToken?: unknown }).accessToken = undefined;\n return this.secretProvider();\n };\n params.accessToken = async () => {\n const secret = await probe;\n if (secret.startsWith('lmk_')) {\n (configuration as { accessToken?: unknown }).accessToken = undefined;\n return '';\n }\n (configuration as { apiKey?: unknown }).apiKey = undefined;\n return this.secretProvider();\n };\n }\n\n const configuration = new ConfigurationCtor(params);\n\n return {\n module: mod,\n configuration,\n create<T>(apiClass: new (configuration?: unknown) => T): T {\n return new apiClass(configuration);\n },\n };\n }\n}\n","import { LumoAuthConfigError } from '@lumoauth/shared';\n\n/**\n * Refuse to run server-credentialed code in a browser.\n *\n * This is the mirror of `@lumoauth/client`'s guard. That one stops a server\n * credential reaching browser code; this one stops browser code reaching for a\n * server credential in the first place.\n *\n * The check is intentionally `window.document` rather than just `window`:\n * some server runtimes define a bare `window` global, and failing there would\n * be a false positive on a legitimate server.\n *\n * Web Workers and edge runtimes have no `document`, so they pass. That is\n * deliberate — an edge function is a server, and it is a supported place to\n * hold a secret. What this catches is the case that actually leaks: a module\n * that ends up in a bundle served to a real browser.\n */\nexport function assertServerOnly(what: string): void {\n if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {\n throw new LumoAuthConfigError(\n `${what} is server-only and was constructed in a browser. ` +\n '@lumoauth/backend holds credentials that authenticate as your ' +\n 'entire organization, so it must never ship to the client. Import ' +\n '@lumoauth/client in browser code, and keep this import in a route ' +\n 'handler, server component, or API route.',\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,YAAY,MAAM,WAC1E,SAAS,cAAc,MACvB,IAAI,IAAI,WAAW,SAAS,OAAO,EAAE;AAEtC,IAAM,gBAAgC,iCAAiB;;;ACZ9D,IAAAA,iBAeO;AACP,yBAA8B;;;AChB9B,oBAAoC;AAkB7B,SAAS,iBAAiB,MAAoB;AACjD,MAAI,OAAO,WAAW,eAAe,OAAO,OAAO,aAAa,aAAa;AACzE,UAAM,IAAI;AAAA,MACN,GAAG,IAAI;AAAA,IAKX;AAAA,EACJ;AAC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AAY;AACxB,cAAM,SAAS,MAAM;AACrB,YAAI,CAAC,OAAO,WAAW,MAAM,GAAG;AAC5B,UAAC,cAAuC,SAAS;AACjD,iBAAO;AAAA,QACX;AACA,QAAC,cAA4C,cAAc;AAC3D,eAAO,KAAK,eAAe;AAAA,MAC/B;AACA,aAAO,cAAc,YAAY;AAC7B,cAAM,SAAS,MAAM;AACrB,YAAI,OAAO,WAAW,MAAM,GAAG;AAC3B,UAAC,cAA4C,cAAc;AAC3D,iBAAO;AAAA,QACX;AACA,QAAC,cAAuC,SAAS;AACjD,eAAO,KAAK,eAAe;AAAA,MAC/B;AAAA,IACJ;AAEA,UAAM,gBAAgB,IAAI,kBAAkB,MAAM;AAElD,WAAO;AAAA,MACH,QAAQ;AAAA,MACR;AAAA,MACA,OAAU,UAAiD;AACvD,eAAO,IAAI,SAAS,aAAa;AAAA,MACrC;AAAA,IACJ;AAAA,EACJ;AACJ;;;AFrRA,0BAAc,6BAzBd;","names":["import_shared"]}
1
+ {"version":3,"sources":["../src/index.ts","../../../node_modules/tsup/assets/cjs_shims.js","../src/backend.ts","../src/guard.ts"],"sourcesContent":["// @lumoauth/backend — the server SDK.\n//\n// The counterpart to @lumoauth/client. This package expects server\n// credentials (a tenant API key, `lmk_…`, or a machine token) and refuses to\n// construct in a browser, so a server credential cannot reach a client bundle\n// by accident.\n//\n// For the full REST surface — every admin endpoint, SCIM, audit logs — use\n// the `lumo.api` escape hatch, which lazily loads the generated client\n// `@lumoauth/api-client` pre-configured with this backend's credential. It is\n// declared as an optional peer dependency because the generated client is not\n// yet published to a registry.\n// TODO(publish): once @lumoauth/api-client is published, drop\n// `peerDependenciesMeta.optional` in package.json so installs pull it in by\n// default (the lazy getter already handles both cases).\n\nexport {\n LumoAuthBackend,\n type LumoAuthBackendConfig,\n type LumoAuthApiEscapeHatch,\n} from './backend';\nexport { assertServerOnly } from './guard';\n\n// The full isomorphic surface: authorization modules, OAuth/PKCE helpers,\n// schemas, errors, and the HTTP client.\nexport * from '@lumoauth/shared';\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","import {\n HttpClient,\n type HttpClientConfig,\n PermissionsModule,\n type PermissionsModuleOptions,\n ZanzibarModule,\n AbacModule,\n AuthModule,\n type AuthModuleConfig,\n AgentsModule,\n ApprovalsModule,\n DelegationModule,\n JitModule,\n McpModule,\n LumoAuthConfigError,\n} from '@lumoauth/shared';\nimport { createRequire } from 'node:module';\nimport { assertServerOnly } from './guard';\n\nexport interface LumoAuthBackendConfig {\n /**\n * Base URL of your LumoAuth instance.\n * @example \"https://app.lumoauth.dev\"\n */\n baseUrl: string;\n\n /**\n * Server credential — a tenant API key (`lmk_…`) or a machine access\n * token. Unlike the browser client, this may be a long-lived secret.\n *\n * Load it from the environment. Never inline it, and never expose it\n * through a framework's public-env mechanism (`NEXT_PUBLIC_*`, `VITE_*`).\n */\n secretKey: string | (() => string | Promise<string>);\n\n /** Organization slug. Required for org-scoped surfaces (ABAC, agents). */\n orgId?: string;\n\n /** OAuth client ID, when using the auth or delegation modules server-side. */\n clientId?: string;\n\n /**\n * OAuth client secret for confidential flows — required by\n * `delegation` for the consent-code exchange and revocation.\n */\n clientSecret?: string;\n\n /** OAuth callback URL for the delegation consent flow. */\n redirectUri?: string;\n\n /** Request timeout in milliseconds. */\n timeout?: number;\n\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n\n /** Extra headers applied to every request. */\n headers?: Record<string, string>;\n\n /** Permission cache configuration; `false` disables caching. */\n cache?: boolean | PermissionsModuleOptions['cache'];\n}\n\n/**\n * The generated OpenAPI client (`@lumoauth/api-client`), pre-configured with\n * this backend's base URL and credential. Loosely typed here so the backend\n * package does not take a compile-time dependency on the generated code.\n */\nexport interface LumoAuthApiEscapeHatch {\n /** The raw `@lumoauth/api-client` module (`AgentsApi`, `AdminUsersApi`, …). */\n readonly module: Record<string, unknown>;\n /** A `Configuration` instance carrying this backend's baseUrl + credential. */\n readonly configuration: unknown;\n /**\n * Instantiate a generated API class with this backend's configuration.\n *\n * ```ts\n * const { AdminUsersApi } = lumo.api.module;\n * const users = lumo.api.create(AdminUsersApi);\n * ```\n */\n create<T>(apiClass: new (configuration?: unknown) => T): T;\n}\n\n/**\n * Server-side LumoAuth client.\n *\n * Same authorization surface as `@lumoauth/client`, but credentialed for a\n * server and guarded against browser construction.\n *\n * ```ts\n * // app/api/documents/route.ts\n * import { LumoAuthBackend } from '@lumoauth/backend';\n *\n * const lumo = new LumoAuthBackend({\n * baseUrl: process.env.LUMOAUTH_URL!,\n * secretKey: process.env.LUMOAUTH_SECRET_KEY!,\n * orgId: 'acme-corp',\n * });\n *\n * const allowed = await lumo.permissions.check('documents.edit');\n * ```\n *\n * For admin operations (users, roles, webhooks, audit logs) use the `api`\n * escape hatch — the ~200 generated endpoints are already typed and\n * regenerated from the OpenAPI spec.\n */\nexport class LumoAuthBackend {\n /** RBAC permission checks. */\n public readonly permissions: PermissionsModule;\n /** Zanzibar-style (ReBAC) relationship checks. */\n public readonly zanzibar: ZanzibarModule;\n /** ABAC policy evaluation and attribute management. */\n public readonly abac: AbacModule;\n /** OAuth 2.0 — token exchange and refresh, including confidential clients. */\n public readonly auth: AuthModule;\n /** Agent identity — ask/isAllowed, self-inspection, registration. */\n public readonly agents: AgentsModule;\n /** Push-approval-for-agent-actions. */\n public readonly approvals: ApprovalsModule;\n /** Chain of Agency — RFC 8693 delegation and nested agent chains. */\n public readonly delegation: DelegationModule;\n /** Just-in-Time permissions — ephemeral tasks and scoped tokens. */\n public readonly jit: JitModule;\n /** MCP servers: token exchange and per-tool checks (`authorizeTool`). */\n public readonly mcp: McpModule;\n\n private readonly http: HttpClient;\n private readonly baseUrl: string;\n private readonly secretProvider: () => string | Promise<string>;\n private apiInstance: LumoAuthApiEscapeHatch | null = null;\n\n constructor(config: LumoAuthBackendConfig) {\n assertServerOnly('LumoAuthBackend');\n\n if (!config.baseUrl) {\n throw new LumoAuthConfigError('baseUrl is required');\n }\n if (!config.secretKey) {\n throw new LumoAuthConfigError(\n 'secretKey is required. For browser code use @lumoauth/client with a user access token instead.',\n );\n }\n\n this.baseUrl = config.baseUrl.replace(/\\/+$/, '');\n this.secretProvider =\n typeof config.secretKey === 'function'\n ? config.secretKey\n : () => config.secretKey as string;\n\n const httpConfig: HttpClientConfig = {\n baseUrl: config.baseUrl,\n token: config.secretKey,\n timeout: config.timeout,\n fetch: config.fetch,\n headers: config.headers,\n };\n this.http = new HttpClient(httpConfig);\n\n const orgId = config.orgId ?? '';\n\n this.permissions = new PermissionsModule(this.http, { cache: config.cache });\n this.zanzibar = new ZanzibarModule(this.http);\n this.abac = new AbacModule(this.http, orgId);\n this.agents = new AgentsModule(this.http, orgId);\n this.approvals = new ApprovalsModule(this.http, orgId);\n this.jit = new JitModule(this.http, orgId);\n this.mcp = new McpModule({\n baseUrl: this.baseUrl,\n orgId,\n token: this.secretProvider,\n fetch: config.fetch,\n http: this.http,\n });\n this.delegation = new DelegationModule({\n baseUrl: this.baseUrl,\n orgId,\n clientId: config.clientId ?? '',\n clientSecret: config.clientSecret,\n redirectUri: config.redirectUri,\n agentToken: this.secretProvider,\n fetch: config.fetch,\n });\n\n const authConfig: AuthModuleConfig = {\n baseUrl: config.baseUrl,\n orgId,\n clientId: config.clientId ?? '',\n fetch: config.fetch,\n };\n this.auth = new AuthModule(authConfig);\n }\n\n /**\n * @deprecated Renamed to {@link agents}. This alias will be removed\n * before 2.0.\n */\n get agent(): AgentsModule {\n return this.agents;\n }\n\n /**\n * Escape hatch to the full generated REST surface (`@lumoauth/api-client`)\n * — every admin endpoint, SCIM, audit logs — pre-configured with this\n * backend's base URL and credential.\n *\n * Loaded lazily on first access so apps that never reach for it don't\n * pay for it. Requires `@lumoauth/api-client` to be installed:\n *\n * ```sh\n * npm install @lumoauth/api-client\n * ```\n */\n get api(): LumoAuthApiEscapeHatch {\n if (!this.apiInstance) {\n this.apiInstance = this.loadApiClient();\n }\n return this.apiInstance;\n }\n\n /** Clear all server-side caches. */\n clearCache(): void {\n this.permissions.clearCache();\n }\n\n // ── Internal ──────────────────────────────────────────────────────\n\n private loadApiClient(): LumoAuthApiEscapeHatch {\n let mod: Record<string, unknown>;\n try {\n // Works from both the CJS build (__dirname) and the ESM build\n // (import.meta.url). `@lumoauth/backend` is Node-only, so\n // node:module is always available, and module resolution walks\n // up from this package to the host app's node_modules.\n const requireFn: NodeRequire = createRequire(\n typeof __dirname === 'string' ? `${__dirname}/` : import.meta.url,\n );\n mod = requireFn('@lumoauth/api-client') as Record<string, unknown>;\n } catch (error) {\n throw new LumoAuthConfigError(\n 'lumo.api requires the generated client `@lumoauth/api-client`, which is not installed. ' +\n 'Install it with `npm install @lumoauth/api-client` (it covers the full REST surface — ' +\n 'admin endpoints, SCIM, audit logs) and try again. ' +\n `Original error: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n const ConfigurationCtor = mod.Configuration as\n | (new (params: Record<string, unknown>) => unknown)\n | undefined;\n if (typeof ConfigurationCtor !== 'function') {\n throw new LumoAuthConfigError(\n '@lumoauth/api-client was found but does not export `Configuration` — ' +\n 'is the installed version compatible (>=0.1.0)?',\n );\n }\n\n // The backend credential may be an API key (lmk_…, sent as X-API-Key)\n // or a bearer token (sent as Authorization). The generated client\n // emits a header for every configured scheme, so only the slot\n // matching the credential's shape may be populated.\n const params: Record<string, unknown> = { basePath: this.baseUrl };\n const probe = this.secretProvider();\n if (typeof probe === 'string') {\n if (probe.startsWith('lmk_')) {\n params.apiKey = () => this.secretProvider();\n } else {\n params.accessToken = () => this.secretProvider();\n }\n } else {\n // Async provider: shape unknown until first resolution. Route by\n // shape per call, then drop the mismatched slot so subsequent\n // requests carry exactly one auth header.\n params.apiKey = async () => {\n const secret = await probe;\n if (!secret.startsWith('lmk_')) {\n (configuration as { apiKey?: unknown }).apiKey = undefined;\n return undefined;\n }\n (configuration as { accessToken?: unknown }).accessToken = undefined;\n return this.secretProvider();\n };\n params.accessToken = async () => {\n const secret = await probe;\n if (secret.startsWith('lmk_')) {\n (configuration as { accessToken?: unknown }).accessToken = undefined;\n return '';\n }\n (configuration as { apiKey?: unknown }).apiKey = undefined;\n return this.secretProvider();\n };\n }\n\n const configuration = new ConfigurationCtor(params);\n\n return {\n module: mod,\n configuration,\n create<T>(apiClass: new (configuration?: unknown) => T): T {\n return new apiClass(configuration);\n },\n };\n }\n}\n","import { LumoAuthConfigError } from '@lumoauth/shared';\n\n/**\n * Refuse to run server-credentialed code in a browser.\n *\n * This is the mirror of `@lumoauth/client`'s guard. That one stops a server\n * credential reaching browser code; this one stops browser code reaching for a\n * server credential in the first place.\n *\n * The check is intentionally `window.document` rather than just `window`:\n * some server runtimes define a bare `window` global, and failing there would\n * be a false positive on a legitimate server.\n *\n * Web Workers and edge runtimes have no `document`, so they pass. That is\n * deliberate — an edge function is a server, and it is a supported place to\n * hold a secret. What this catches is the case that actually leaks: a module\n * that ends up in a bundle served to a real browser.\n */\nexport function assertServerOnly(what: string): void {\n if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {\n throw new LumoAuthConfigError(\n `${what} is server-only and was constructed in a browser. ` +\n '@lumoauth/backend holds credentials that authenticate as your ' +\n 'entire organization, so it must never ship to the client. Import ' +\n '@lumoauth/client in browser code, and keep this import in a route ' +\n 'handler, server component, or API route.',\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,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,YAAM,IAAI;AAAA,QACN;AAAA,MAEJ;AAAA,IACJ;AAMA,UAAM,SAAkC,EAAE,UAAU,KAAK,QAAQ;AACjE,UAAM,QAAQ,KAAK,eAAe;AAClC,QAAI,OAAO,UAAU,UAAU;AAC3B,UAAI,MAAM,WAAW,MAAM,GAAG;AAC1B,eAAO,SAAS,MAAM,KAAK,eAAe;AAAA,MAC9C,OAAO;AACH,eAAO,cAAc,MAAM,KAAK,eAAe;AAAA,MACnD;AAAA,IACJ,OAAO;AAIH,aAAO,SAAS,YAAY;AACxB,cAAM,SAAS,MAAM;AACrB,YAAI,CAAC,OAAO,WAAW,MAAM,GAAG;AAC5B,UAAC,cAAuC,SAAS;AACjD,iBAAO;AAAA,QACX;AACA,QAAC,cAA4C,cAAc;AAC3D,eAAO,KAAK,eAAe;AAAA,MAC/B;AACA,aAAO,cAAc,YAAY;AAC7B,cAAM,SAAS,MAAM;AACrB,YAAI,OAAO,WAAW,MAAM,GAAG;AAC3B,UAAC,cAA4C,cAAc;AAC3D,iBAAO;AAAA,QACX;AACA,QAAC,cAAuC,SAAS;AACjD,eAAO,KAAK,eAAe;AAAA,MAC/B;AAAA,IACJ;AAEA,UAAM,gBAAgB,IAAI,kBAAkB,MAAM;AAElD,WAAO;AAAA,MACH,QAAQ;AAAA,MACR;AAAA,MACA,OAAU,UAAiD;AACvD,eAAO,IAAI,SAAS,aAAa;AAAA,MACrC;AAAA,IACJ;AAAA,EACJ;AACJ;;;AFtRA,0BAAc,6BAzBd;","names":["import_shared"]}
package/dist/index.mjs CHANGED
@@ -65,7 +65,8 @@ var LumoAuthBackend = class {
65
65
  baseUrl: this.baseUrl,
66
66
  orgId,
67
67
  token: this.secretProvider,
68
- fetch: config.fetch
68
+ fetch: config.fetch,
69
+ http: this.http
69
70
  });
70
71
  this.delegation = new DelegationModule({
71
72
  baseUrl: this.baseUrl,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/tsup/assets/esm_shims.js","../src/backend.ts","../src/guard.ts","../src/index.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","import {\n HttpClient,\n type HttpClientConfig,\n PermissionsModule,\n type PermissionsModuleOptions,\n ZanzibarModule,\n AbacModule,\n AuthModule,\n type AuthModuleConfig,\n AgentsModule,\n ApprovalsModule,\n DelegationModule,\n JitModule,\n McpModule,\n LumoAuthConfigError,\n} from '@lumoauth/shared';\nimport { createRequire } from 'node:module';\nimport { assertServerOnly } from './guard';\n\nexport interface LumoAuthBackendConfig {\n /**\n * Base URL of your LumoAuth instance.\n * @example \"https://app.lumoauth.dev\"\n */\n baseUrl: string;\n\n /**\n * Server credential — a tenant API key (`lmk_…`) or a machine access\n * token. Unlike the browser client, this may be a long-lived secret.\n *\n * Load it from the environment. Never inline it, and never expose it\n * through a framework's public-env mechanism (`NEXT_PUBLIC_*`, `VITE_*`).\n */\n secretKey: string | (() => string | Promise<string>);\n\n /** Organization slug. Required for org-scoped surfaces (ABAC, agents). */\n orgId?: string;\n\n /** OAuth client ID, when using the auth or delegation modules server-side. */\n clientId?: string;\n\n /**\n * OAuth client secret for confidential flows — required by\n * `delegation` for the consent-code exchange and revocation.\n */\n clientSecret?: string;\n\n /** OAuth callback URL for the delegation consent flow. */\n redirectUri?: string;\n\n /** Request timeout in milliseconds. */\n timeout?: number;\n\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n\n /** Extra headers applied to every request. */\n headers?: Record<string, string>;\n\n /** Permission cache configuration; `false` disables caching. */\n cache?: boolean | PermissionsModuleOptions['cache'];\n}\n\n/**\n * The generated OpenAPI client (`@lumoauth/api-client`), pre-configured with\n * this backend's base URL and credential. Loosely typed here so the backend\n * package does not take a compile-time dependency on the generated code.\n */\nexport interface LumoAuthApiEscapeHatch {\n /** The raw `@lumoauth/api-client` module (`AgentsApi`, `AdminUsersApi`, …). */\n readonly module: Record<string, unknown>;\n /** A `Configuration` instance carrying this backend's baseUrl + credential. */\n readonly configuration: unknown;\n /**\n * Instantiate a generated API class with this backend's configuration.\n *\n * ```ts\n * const { AdminUsersApi } = lumo.api.module;\n * const users = lumo.api.create(AdminUsersApi);\n * ```\n */\n create<T>(apiClass: new (configuration?: unknown) => T): T;\n}\n\n/**\n * Server-side LumoAuth client.\n *\n * Same authorization surface as `@lumoauth/client`, but credentialed for a\n * server and guarded against browser construction.\n *\n * ```ts\n * // app/api/documents/route.ts\n * import { LumoAuthBackend } from '@lumoauth/backend';\n *\n * const lumo = new LumoAuthBackend({\n * baseUrl: process.env.LUMOAUTH_URL!,\n * secretKey: process.env.LUMOAUTH_SECRET_KEY!,\n * orgId: 'acme-corp',\n * });\n *\n * const allowed = await lumo.permissions.check('documents.edit');\n * ```\n *\n * For admin operations (users, roles, webhooks, audit logs) use the `api`\n * escape hatch — the ~200 generated endpoints are already typed and\n * regenerated from the OpenAPI spec.\n */\nexport class LumoAuthBackend {\n /** RBAC permission checks. */\n public readonly permissions: PermissionsModule;\n /** Zanzibar-style (ReBAC) relationship checks. */\n public readonly zanzibar: ZanzibarModule;\n /** ABAC policy evaluation and attribute management. */\n public readonly abac: AbacModule;\n /** OAuth 2.0 — token exchange and refresh, including confidential clients. */\n public readonly auth: AuthModule;\n /** Agent identity — ask/isAllowed, self-inspection, registration. */\n public readonly agents: AgentsModule;\n /** Push-approval-for-agent-actions. */\n public readonly approvals: ApprovalsModule;\n /** Chain of Agency — RFC 8693 delegation and nested agent chains. */\n public readonly delegation: DelegationModule;\n /** Just-in-Time permissions — ephemeral tasks and scoped tokens. */\n public readonly jit: JitModule;\n /** Token exchange for secured MCP servers. */\n public readonly mcp: McpModule;\n\n private readonly http: HttpClient;\n private readonly baseUrl: string;\n private readonly secretProvider: () => string | Promise<string>;\n private apiInstance: LumoAuthApiEscapeHatch | null = null;\n\n constructor(config: LumoAuthBackendConfig) {\n assertServerOnly('LumoAuthBackend');\n\n if (!config.baseUrl) {\n throw new LumoAuthConfigError('baseUrl is required');\n }\n if (!config.secretKey) {\n throw new LumoAuthConfigError(\n 'secretKey is required. For browser code use @lumoauth/client with a user access token instead.',\n );\n }\n\n this.baseUrl = config.baseUrl.replace(/\\/+$/, '');\n this.secretProvider =\n typeof config.secretKey === 'function'\n ? config.secretKey\n : () => config.secretKey as string;\n\n const httpConfig: HttpClientConfig = {\n baseUrl: config.baseUrl,\n token: config.secretKey,\n timeout: config.timeout,\n fetch: config.fetch,\n headers: config.headers,\n };\n this.http = new HttpClient(httpConfig);\n\n const orgId = config.orgId ?? '';\n\n this.permissions = new PermissionsModule(this.http, { cache: config.cache });\n this.zanzibar = new ZanzibarModule(this.http);\n this.abac = new AbacModule(this.http, orgId);\n this.agents = new AgentsModule(this.http, orgId);\n this.approvals = new ApprovalsModule(this.http, orgId);\n this.jit = new JitModule(this.http, orgId);\n this.mcp = new McpModule({\n baseUrl: this.baseUrl,\n orgId,\n token: this.secretProvider,\n fetch: config.fetch,\n });\n this.delegation = new DelegationModule({\n baseUrl: this.baseUrl,\n orgId,\n clientId: config.clientId ?? '',\n clientSecret: config.clientSecret,\n redirectUri: config.redirectUri,\n agentToken: this.secretProvider,\n fetch: config.fetch,\n });\n\n const authConfig: AuthModuleConfig = {\n baseUrl: config.baseUrl,\n orgId,\n clientId: config.clientId ?? '',\n fetch: config.fetch,\n };\n this.auth = new AuthModule(authConfig);\n }\n\n /**\n * @deprecated Renamed to {@link agents}. This alias will be removed\n * before 2.0.\n */\n get agent(): AgentsModule {\n return this.agents;\n }\n\n /**\n * Escape hatch to the full generated REST surface (`@lumoauth/api-client`)\n * — every admin endpoint, SCIM, audit logs — pre-configured with this\n * backend's base URL and credential.\n *\n * Loaded lazily on first access so apps that never reach for it don't\n * pay for it. Requires `@lumoauth/api-client` to be installed:\n *\n * ```sh\n * npm install @lumoauth/api-client\n * ```\n */\n get api(): LumoAuthApiEscapeHatch {\n if (!this.apiInstance) {\n this.apiInstance = this.loadApiClient();\n }\n return this.apiInstance;\n }\n\n /** Clear all server-side caches. */\n clearCache(): void {\n this.permissions.clearCache();\n }\n\n // ── Internal ──────────────────────────────────────────────────────\n\n private loadApiClient(): LumoAuthApiEscapeHatch {\n let mod: Record<string, unknown>;\n try {\n // Works from both the CJS build (__dirname) and the ESM build\n // (import.meta.url). `@lumoauth/backend` is Node-only, so\n // node:module is always available, and module resolution walks\n // up from this package to the host app's node_modules.\n const requireFn: NodeRequire = createRequire(\n typeof __dirname === 'string' ? `${__dirname}/` : import.meta.url,\n );\n mod = requireFn('@lumoauth/api-client') as Record<string, unknown>;\n } catch (error) {\n throw new LumoAuthConfigError(\n 'lumo.api requires the generated client `@lumoauth/api-client`, which is not installed. ' +\n 'Install it with `npm install @lumoauth/api-client` (it covers the full REST surface — ' +\n 'admin endpoints, SCIM, audit logs) and try again. ' +\n `Original error: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n const ConfigurationCtor = mod.Configuration as\n | (new (params: Record<string, unknown>) => unknown)\n | undefined;\n if (typeof ConfigurationCtor !== 'function') {\n throw new LumoAuthConfigError(\n '@lumoauth/api-client was found but does not export `Configuration` — ' +\n 'is the installed version compatible (>=0.1.0)?',\n );\n }\n\n // The backend credential may be an API key (lmk_…, sent as X-API-Key)\n // or a bearer token (sent as Authorization). The generated client\n // emits a header for every configured scheme, so only the slot\n // matching the credential's shape may be populated.\n const params: Record<string, unknown> = { basePath: this.baseUrl };\n const probe = this.secretProvider();\n if (typeof probe === 'string') {\n if (probe.startsWith('lmk_')) {\n params.apiKey = () => this.secretProvider();\n } else {\n params.accessToken = () => this.secretProvider();\n }\n } else {\n // Async provider: shape unknown until first resolution. Route by\n // shape per call, then drop the mismatched slot so subsequent\n // requests carry exactly one auth header.\n params.apiKey = async () => {\n const secret = await probe;\n if (!secret.startsWith('lmk_')) {\n (configuration as { apiKey?: unknown }).apiKey = undefined;\n return undefined;\n }\n (configuration as { accessToken?: unknown }).accessToken = undefined;\n return this.secretProvider();\n };\n params.accessToken = async () => {\n const secret = await probe;\n if (secret.startsWith('lmk_')) {\n (configuration as { accessToken?: unknown }).accessToken = undefined;\n return '';\n }\n (configuration as { apiKey?: unknown }).apiKey = undefined;\n return this.secretProvider();\n };\n }\n\n const configuration = new ConfigurationCtor(params);\n\n return {\n module: mod,\n configuration,\n create<T>(apiClass: new (configuration?: unknown) => T): T {\n return new apiClass(configuration);\n },\n };\n }\n}\n","import { LumoAuthConfigError } from '@lumoauth/shared';\n\n/**\n * Refuse to run server-credentialed code in a browser.\n *\n * This is the mirror of `@lumoauth/client`'s guard. That one stops a server\n * credential reaching browser code; this one stops browser code reaching for a\n * server credential in the first place.\n *\n * The check is intentionally `window.document` rather than just `window`:\n * some server runtimes define a bare `window` global, and failing there would\n * be a false positive on a legitimate server.\n *\n * Web Workers and edge runtimes have no `document`, so they pass. That is\n * deliberate — an edge function is a server, and it is a supported place to\n * hold a secret. What this catches is the case that actually leaks: a module\n * that ends up in a bundle served to a real browser.\n */\nexport function assertServerOnly(what: string): void {\n if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {\n throw new LumoAuthConfigError(\n `${what} is server-only and was constructed in a browser. ` +\n '@lumoauth/backend holds credentials that authenticate as your ' +\n 'entire organization, so it must never ship to the client. Import ' +\n '@lumoauth/client in browser code, and keep this import in a route ' +\n 'handler, server component, or API route.',\n );\n }\n}\n","// @lumoauth/backend — the server SDK.\n//\n// The counterpart to @lumoauth/client. This package expects server\n// credentials (a tenant API key, `lmk_…`, or a machine token) and refuses to\n// construct in a browser, so a server credential cannot reach a client bundle\n// by accident.\n//\n// For the full REST surface — every admin endpoint, SCIM, audit logs — use\n// the `lumo.api` escape hatch, which lazily loads the generated client\n// `@lumoauth/api-client` pre-configured with this backend's credential. It is\n// declared as an optional peer dependency because the generated client is not\n// yet published to a registry.\n// TODO(publish): once @lumoauth/api-client is published, drop\n// `peerDependenciesMeta.optional` in package.json so installs pull it in by\n// default (the lazy getter already handles both cases).\n\nexport {\n LumoAuthBackend,\n type LumoAuthBackendConfig,\n type LumoAuthApiEscapeHatch,\n} from './backend';\nexport { assertServerOnly } from './guard';\n\n// The full isomorphic surface: authorization modules, OAuth/PKCE helpers,\n// schemas, errors, and the HTTP client.\nexport * from '@lumoauth/shared';\n"],"mappings":";AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAE9B,IAAM,cAAc,MAAM,cAAc,YAAY,GAAG;AACvD,IAAM,aAAa,MAAM,KAAK,QAAQ,YAAY,CAAC;AAE5C,IAAM,YAA4B,2BAAW;;;ACPpD;AAAA,EACI;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,uBAAAA;AAAA,OACG;AACP,SAAS,qBAAqB;;;AChB9B,SAAS,2BAA2B;AAkB7B,SAAS,iBAAiB,MAAoB;AACjD,MAAI,OAAO,WAAW,eAAe,OAAO,OAAO,aAAa,aAAa;AACzE,UAAM,IAAI;AAAA,MACN,GAAG,IAAI;AAAA,IAKX;AAAA,EACJ;AACJ;;;AD+EO,IAAM,kBAAN,MAAsB;AAAA,EAyBzB,YAAY,QAA+B;AAF3C,SAAQ,cAA6C;AAGjD,qBAAiB,iBAAiB;AAElC,QAAI,CAAC,OAAO,SAAS;AACjB,YAAM,IAAIC,qBAAoB,qBAAqB;AAAA,IACvD;AACA,QAAI,CAAC,OAAO,WAAW;AACnB,YAAM,IAAIA;AAAA,QACN;AAAA,MACJ;AAAA,IACJ;AAEA,SAAK,UAAU,OAAO,QAAQ,QAAQ,QAAQ,EAAE;AAChD,SAAK,iBACD,OAAO,OAAO,cAAc,aACtB,OAAO,YACP,MAAM,OAAO;AAEvB,UAAM,aAA+B;AAAA,MACjC,SAAS,OAAO;AAAA,MAChB,OAAO,OAAO;AAAA,MACd,SAAS,OAAO;AAAA,MAChB,OAA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,UAAiD;AACvD,eAAO,IAAI,SAAS,aAAa;AAAA,MACrC;AAAA,IACJ;AAAA,EACJ;AACJ;;;AErRA,cAAc;","names":["LumoAuthConfigError","LumoAuthConfigError"]}
1
+ {"version":3,"sources":["../../../node_modules/tsup/assets/esm_shims.js","../src/backend.ts","../src/guard.ts","../src/index.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","import {\n HttpClient,\n type HttpClientConfig,\n PermissionsModule,\n type PermissionsModuleOptions,\n ZanzibarModule,\n AbacModule,\n AuthModule,\n type AuthModuleConfig,\n AgentsModule,\n ApprovalsModule,\n DelegationModule,\n JitModule,\n McpModule,\n LumoAuthConfigError,\n} from '@lumoauth/shared';\nimport { createRequire } from 'node:module';\nimport { assertServerOnly } from './guard';\n\nexport interface LumoAuthBackendConfig {\n /**\n * Base URL of your LumoAuth instance.\n * @example \"https://app.lumoauth.dev\"\n */\n baseUrl: string;\n\n /**\n * Server credential — a tenant API key (`lmk_…`) or a machine access\n * token. Unlike the browser client, this may be a long-lived secret.\n *\n * Load it from the environment. Never inline it, and never expose it\n * through a framework's public-env mechanism (`NEXT_PUBLIC_*`, `VITE_*`).\n */\n secretKey: string | (() => string | Promise<string>);\n\n /** Organization slug. Required for org-scoped surfaces (ABAC, agents). */\n orgId?: string;\n\n /** OAuth client ID, when using the auth or delegation modules server-side. */\n clientId?: string;\n\n /**\n * OAuth client secret for confidential flows — required by\n * `delegation` for the consent-code exchange and revocation.\n */\n clientSecret?: string;\n\n /** OAuth callback URL for the delegation consent flow. */\n redirectUri?: string;\n\n /** Request timeout in milliseconds. */\n timeout?: number;\n\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n\n /** Extra headers applied to every request. */\n headers?: Record<string, string>;\n\n /** Permission cache configuration; `false` disables caching. */\n cache?: boolean | PermissionsModuleOptions['cache'];\n}\n\n/**\n * The generated OpenAPI client (`@lumoauth/api-client`), pre-configured with\n * this backend's base URL and credential. Loosely typed here so the backend\n * package does not take a compile-time dependency on the generated code.\n */\nexport interface LumoAuthApiEscapeHatch {\n /** The raw `@lumoauth/api-client` module (`AgentsApi`, `AdminUsersApi`, …). */\n readonly module: Record<string, unknown>;\n /** A `Configuration` instance carrying this backend's baseUrl + credential. */\n readonly configuration: unknown;\n /**\n * Instantiate a generated API class with this backend's configuration.\n *\n * ```ts\n * const { AdminUsersApi } = lumo.api.module;\n * const users = lumo.api.create(AdminUsersApi);\n * ```\n */\n create<T>(apiClass: new (configuration?: unknown) => T): T;\n}\n\n/**\n * Server-side LumoAuth client.\n *\n * Same authorization surface as `@lumoauth/client`, but credentialed for a\n * server and guarded against browser construction.\n *\n * ```ts\n * // app/api/documents/route.ts\n * import { LumoAuthBackend } from '@lumoauth/backend';\n *\n * const lumo = new LumoAuthBackend({\n * baseUrl: process.env.LUMOAUTH_URL!,\n * secretKey: process.env.LUMOAUTH_SECRET_KEY!,\n * orgId: 'acme-corp',\n * });\n *\n * const allowed = await lumo.permissions.check('documents.edit');\n * ```\n *\n * For admin operations (users, roles, webhooks, audit logs) use the `api`\n * escape hatch — the ~200 generated endpoints are already typed and\n * regenerated from the OpenAPI spec.\n */\nexport class LumoAuthBackend {\n /** RBAC permission checks. */\n public readonly permissions: PermissionsModule;\n /** Zanzibar-style (ReBAC) relationship checks. */\n public readonly zanzibar: ZanzibarModule;\n /** ABAC policy evaluation and attribute management. */\n public readonly abac: AbacModule;\n /** OAuth 2.0 — token exchange and refresh, including confidential clients. */\n public readonly auth: AuthModule;\n /** Agent identity — ask/isAllowed, self-inspection, registration. */\n public readonly agents: AgentsModule;\n /** Push-approval-for-agent-actions. */\n public readonly approvals: ApprovalsModule;\n /** Chain of Agency — RFC 8693 delegation and nested agent chains. */\n public readonly delegation: DelegationModule;\n /** Just-in-Time permissions — ephemeral tasks and scoped tokens. */\n public readonly jit: JitModule;\n /** MCP servers: token exchange and per-tool checks (`authorizeTool`). */\n public readonly mcp: McpModule;\n\n private readonly http: HttpClient;\n private readonly baseUrl: string;\n private readonly secretProvider: () => string | Promise<string>;\n private apiInstance: LumoAuthApiEscapeHatch | null = null;\n\n constructor(config: LumoAuthBackendConfig) {\n assertServerOnly('LumoAuthBackend');\n\n if (!config.baseUrl) {\n throw new LumoAuthConfigError('baseUrl is required');\n }\n if (!config.secretKey) {\n throw new LumoAuthConfigError(\n 'secretKey is required. For browser code use @lumoauth/client with a user access token instead.',\n );\n }\n\n this.baseUrl = config.baseUrl.replace(/\\/+$/, '');\n this.secretProvider =\n typeof config.secretKey === 'function'\n ? config.secretKey\n : () => config.secretKey as string;\n\n const httpConfig: HttpClientConfig = {\n baseUrl: config.baseUrl,\n token: config.secretKey,\n timeout: config.timeout,\n fetch: config.fetch,\n headers: config.headers,\n };\n this.http = new HttpClient(httpConfig);\n\n const orgId = config.orgId ?? '';\n\n this.permissions = new PermissionsModule(this.http, { cache: config.cache });\n this.zanzibar = new ZanzibarModule(this.http);\n this.abac = new AbacModule(this.http, orgId);\n this.agents = new AgentsModule(this.http, orgId);\n this.approvals = new ApprovalsModule(this.http, orgId);\n this.jit = new JitModule(this.http, orgId);\n this.mcp = new McpModule({\n baseUrl: this.baseUrl,\n orgId,\n token: this.secretProvider,\n fetch: config.fetch,\n http: this.http,\n });\n this.delegation = new DelegationModule({\n baseUrl: this.baseUrl,\n orgId,\n clientId: config.clientId ?? '',\n clientSecret: config.clientSecret,\n redirectUri: config.redirectUri,\n agentToken: this.secretProvider,\n fetch: config.fetch,\n });\n\n const authConfig: AuthModuleConfig = {\n baseUrl: config.baseUrl,\n orgId,\n clientId: config.clientId ?? '',\n fetch: config.fetch,\n };\n this.auth = new AuthModule(authConfig);\n }\n\n /**\n * @deprecated Renamed to {@link agents}. This alias will be removed\n * before 2.0.\n */\n get agent(): AgentsModule {\n return this.agents;\n }\n\n /**\n * Escape hatch to the full generated REST surface (`@lumoauth/api-client`)\n * — every admin endpoint, SCIM, audit logs — pre-configured with this\n * backend's base URL and credential.\n *\n * Loaded lazily on first access so apps that never reach for it don't\n * pay for it. Requires `@lumoauth/api-client` to be installed:\n *\n * ```sh\n * npm install @lumoauth/api-client\n * ```\n */\n get api(): LumoAuthApiEscapeHatch {\n if (!this.apiInstance) {\n this.apiInstance = this.loadApiClient();\n }\n return this.apiInstance;\n }\n\n /** Clear all server-side caches. */\n clearCache(): void {\n this.permissions.clearCache();\n }\n\n // ── Internal ──────────────────────────────────────────────────────\n\n private loadApiClient(): LumoAuthApiEscapeHatch {\n let mod: Record<string, unknown>;\n try {\n // Works from both the CJS build (__dirname) and the ESM build\n // (import.meta.url). `@lumoauth/backend` is Node-only, so\n // node:module is always available, and module resolution walks\n // up from this package to the host app's node_modules.\n const requireFn: NodeRequire = createRequire(\n typeof __dirname === 'string' ? `${__dirname}/` : import.meta.url,\n );\n mod = requireFn('@lumoauth/api-client') as Record<string, unknown>;\n } catch (error) {\n throw new LumoAuthConfigError(\n 'lumo.api requires the generated client `@lumoauth/api-client`, which is not installed. ' +\n 'Install it with `npm install @lumoauth/api-client` (it covers the full REST surface — ' +\n 'admin endpoints, SCIM, audit logs) and try again. ' +\n `Original error: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n const ConfigurationCtor = mod.Configuration as\n | (new (params: Record<string, unknown>) => unknown)\n | undefined;\n if (typeof ConfigurationCtor !== 'function') {\n throw new LumoAuthConfigError(\n '@lumoauth/api-client was found but does not export `Configuration` — ' +\n 'is the installed version compatible (>=0.1.0)?',\n );\n }\n\n // The backend credential may be an API key (lmk_…, sent as X-API-Key)\n // or a bearer token (sent as Authorization). The generated client\n // emits a header for every configured scheme, so only the slot\n // matching the credential's shape may be populated.\n const params: Record<string, unknown> = { basePath: this.baseUrl };\n const probe = this.secretProvider();\n if (typeof probe === 'string') {\n if (probe.startsWith('lmk_')) {\n params.apiKey = () => this.secretProvider();\n } else {\n params.accessToken = () => this.secretProvider();\n }\n } else {\n // Async provider: shape unknown until first resolution. Route by\n // shape per call, then drop the mismatched slot so subsequent\n // requests carry exactly one auth header.\n params.apiKey = async () => {\n const secret = await probe;\n if (!secret.startsWith('lmk_')) {\n (configuration as { apiKey?: unknown }).apiKey = undefined;\n return undefined;\n }\n (configuration as { accessToken?: unknown }).accessToken = undefined;\n return this.secretProvider();\n };\n params.accessToken = async () => {\n const secret = await probe;\n if (secret.startsWith('lmk_')) {\n (configuration as { accessToken?: unknown }).accessToken = undefined;\n return '';\n }\n (configuration as { apiKey?: unknown }).apiKey = undefined;\n return this.secretProvider();\n };\n }\n\n const configuration = new ConfigurationCtor(params);\n\n return {\n module: mod,\n configuration,\n create<T>(apiClass: new (configuration?: unknown) => T): T {\n return new apiClass(configuration);\n },\n };\n }\n}\n","import { LumoAuthConfigError } from '@lumoauth/shared';\n\n/**\n * Refuse to run server-credentialed code in a browser.\n *\n * This is the mirror of `@lumoauth/client`'s guard. That one stops a server\n * credential reaching browser code; this one stops browser code reaching for a\n * server credential in the first place.\n *\n * The check is intentionally `window.document` rather than just `window`:\n * some server runtimes define a bare `window` global, and failing there would\n * be a false positive on a legitimate server.\n *\n * Web Workers and edge runtimes have no `document`, so they pass. That is\n * deliberate — an edge function is a server, and it is a supported place to\n * hold a secret. What this catches is the case that actually leaks: a module\n * that ends up in a bundle served to a real browser.\n */\nexport function assertServerOnly(what: string): void {\n if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {\n throw new LumoAuthConfigError(\n `${what} is server-only and was constructed in a browser. ` +\n '@lumoauth/backend holds credentials that authenticate as your ' +\n 'entire organization, so it must never ship to the client. Import ' +\n '@lumoauth/client in browser code, and keep this import in a route ' +\n 'handler, server component, or API route.',\n );\n }\n}\n","// @lumoauth/backend — the server SDK.\n//\n// The counterpart to @lumoauth/client. This package expects server\n// credentials (a tenant API key, `lmk_…`, or a machine token) and refuses to\n// construct in a browser, so a server credential cannot reach a client bundle\n// by accident.\n//\n// For the full REST surface — every admin endpoint, SCIM, audit logs — use\n// the `lumo.api` escape hatch, which lazily loads the generated client\n// `@lumoauth/api-client` pre-configured with this backend's credential. It is\n// declared as an optional peer dependency because the generated client is not\n// yet published to a registry.\n// TODO(publish): once @lumoauth/api-client is published, drop\n// `peerDependenciesMeta.optional` in package.json so installs pull it in by\n// default (the lazy getter already handles both cases).\n\nexport {\n LumoAuthBackend,\n type LumoAuthBackendConfig,\n type LumoAuthApiEscapeHatch,\n} from './backend';\nexport { assertServerOnly } from './guard';\n\n// The full isomorphic surface: authorization modules, OAuth/PKCE helpers,\n// schemas, errors, and the HTTP client.\nexport * from '@lumoauth/shared';\n"],"mappings":";AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAE9B,IAAM,cAAc,MAAM,cAAc,YAAY,GAAG;AACvD,IAAM,aAAa,MAAM,KAAK,QAAQ,YAAY,CAAC;AAE5C,IAAM,YAA4B,2BAAW;;;ACPpD;AAAA,EACI;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,uBAAAA;AAAA,OACG;AACP,SAAS,qBAAqB;;;AChB9B,SAAS,2BAA2B;AAkB7B,SAAS,iBAAiB,MAAoB;AACjD,MAAI,OAAO,WAAW,eAAe,OAAO,OAAO,aAAa,aAAa;AACzE,UAAM,IAAI;AAAA,MACN,GAAG,IAAI;AAAA,IAKX;AAAA,EACJ;AACJ;;;AD+EO,IAAM,kBAAN,MAAsB;AAAA,EAyBzB,YAAY,QAA+B;AAF3C,SAAQ,cAA6C;AAGjD,qBAAiB,iBAAiB;AAElC,QAAI,CAAC,OAAO,SAAS;AACjB,YAAM,IAAIC,qBAAoB,qBAAqB;AAAA,IACvD;AACA,QAAI,CAAC,OAAO,WAAW;AACnB,YAAM,IAAIA;AAAA,QACN;AAAA,MACJ;AAAA,IACJ;AAEA,S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AW,MAAM,GAAG;AAC3B,UAAC,cAA4C,cAAc;AAC3D,iBAAO;AAAA,QACX;AACA,QAAC,cAAuC,SAAS;AACjD,eAAO,KAAK,eAAe;AAAA,MAC/B;AAAA,IACJ;AAEA,UAAM,gBAAgB,IAAI,kBAAkB,MAAM;AAElD,WAAO;AAAA,MACH,QAAQ;AAAA,MACR;AAAA,MACA,OAAU,UAAiD;AACvD,eAAO,IAAI,SAAS,aAAa;AAAA,MACrC;AAAA,IACJ;AAAA,EACJ;AACJ;;;AEtRA,cAAc;","names":["LumoAuthConfigError","LumoAuthConfigError"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lumoauth/backend",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Official LumoAuth server SDK — token verification and server-side auth. Never import this from browser code.",
5
5
  "license": "MIT",
6
6
  "author": "LumoAuth",