@lelu-auth/lelu 0.1.4 → 0.1.6

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/index.mjs CHANGED
@@ -223,6 +223,128 @@ var LeluClient = class {
223
223
  return false;
224
224
  }
225
225
  }
226
+ // ── Audit log ──────────────────────────────────────────────────────────────
227
+ /**
228
+ * Lists audit events from the platform API.
229
+ * Requires the platform service to be running (not just the engine).
230
+ */
231
+ async listAuditEvents(req = {}) {
232
+ const params = new URLSearchParams();
233
+ if (req.limit !== void 0) params.set("limit", req.limit.toString());
234
+ if (req.cursor !== void 0) params.set("cursor", req.cursor.toString());
235
+ if (req.actor) params.set("actor", req.actor);
236
+ if (req.action) params.set("action", req.action);
237
+ if (req.decision) params.set("decision", req.decision);
238
+ if (req.traceId) params.set("trace_id", req.traceId);
239
+ if (req.from) params.set("from", req.from);
240
+ if (req.to) params.set("to", req.to);
241
+ const headers = this.headers();
242
+ if (req.tenantId) {
243
+ headers["X-Tenant-ID"] = req.tenantId;
244
+ }
245
+ const ctrl = new AbortController();
246
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
247
+ try {
248
+ const url = `${this.baseUrl}/api/v1/audit${params.toString() ? `?${params.toString()}` : ""}`;
249
+ const res = await fetch(url, {
250
+ method: "GET",
251
+ headers,
252
+ signal: ctrl.signal
253
+ });
254
+ const data = await this.parseResponse(res);
255
+ return {
256
+ events: data.events || [],
257
+ count: data.count,
258
+ limit: data.limit,
259
+ cursor: data.cursor,
260
+ nextCursor: data.next_cursor
261
+ };
262
+ } finally {
263
+ clearTimeout(timer);
264
+ }
265
+ }
266
+ // ─── Policy Management ────────────────────────────────────────────────────────
267
+ async listPolicies(req = {}) {
268
+ const headers = this.headers();
269
+ if (req.tenantId) {
270
+ headers["X-Tenant-ID"] = req.tenantId;
271
+ }
272
+ const ctrl = new AbortController();
273
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
274
+ try {
275
+ const res = await fetch(`${this.baseUrl}/api/v1/policies`, {
276
+ method: "GET",
277
+ headers,
278
+ signal: ctrl.signal
279
+ });
280
+ const data = await this.parseResponse(res);
281
+ return {
282
+ policies: data.policies || [],
283
+ count: data.count
284
+ };
285
+ } finally {
286
+ clearTimeout(timer);
287
+ }
288
+ }
289
+ async getPolicy(req) {
290
+ const headers = this.headers();
291
+ if (req.tenantId) {
292
+ headers["X-Tenant-ID"] = req.tenantId;
293
+ }
294
+ const ctrl = new AbortController();
295
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
296
+ try {
297
+ const res = await fetch(`${this.baseUrl}/api/v1/policies/${encodeURIComponent(req.name)}`, {
298
+ method: "GET",
299
+ headers,
300
+ signal: ctrl.signal
301
+ });
302
+ return await this.parseResponse(res);
303
+ } finally {
304
+ clearTimeout(timer);
305
+ }
306
+ }
307
+ async upsertPolicy(req) {
308
+ const headers = this.headers();
309
+ if (req.tenantId) {
310
+ headers["X-Tenant-ID"] = req.tenantId;
311
+ }
312
+ const body = {
313
+ content: req.content,
314
+ version: req.version || "1.0"
315
+ };
316
+ const ctrl = new AbortController();
317
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
318
+ try {
319
+ const res = await fetch(`${this.baseUrl}/api/v1/policies/${encodeURIComponent(req.name)}`, {
320
+ method: "PUT",
321
+ headers,
322
+ body: JSON.stringify(body),
323
+ signal: ctrl.signal
324
+ });
325
+ return await this.parseResponse(res);
326
+ } finally {
327
+ clearTimeout(timer);
328
+ }
329
+ }
330
+ async deletePolicy(req) {
331
+ const headers = this.headers();
332
+ if (req.tenantId) {
333
+ headers["X-Tenant-ID"] = req.tenantId;
334
+ }
335
+ const ctrl = new AbortController();
336
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
337
+ try {
338
+ const res = await fetch(`${this.baseUrl}/api/v1/policies/${encodeURIComponent(req.name)}`, {
339
+ method: "DELETE",
340
+ headers,
341
+ signal: ctrl.signal
342
+ });
343
+ return await this.parseResponse(res);
344
+ } finally {
345
+ clearTimeout(timer);
346
+ }
347
+ }
226
348
  // ── HTTP helpers ───────────────────────────────────────────────────────────
227
349
  headers() {
228
350
  const h = { "Content-Type": "application/json" };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/vercel/index.ts","../src/types.ts","../src/client.ts","../src/index.ts"],"names":[],"mappings":";;;AAgGO,SAAS,WACd,IAAA,EAC+C;AAC/C,EAAA,MAAM,EAAE,MAAA,EAAQ,KAAA,EAAO,MAAA,EAAQ,WAAU,GAAI,IAAA;AAE7C,EAAA,MAAM,OAAA,GAAyD;AAAA,IAC7D,UAAA,EAAY,KAAK,IAAA,CAAK,UAAA;AAAA,IAEtB,MAAM,OAAA,CACJ,IAAA,EACA,OAAA,EACqC;AAErC,MAAA,MAAM,UAAA,GACJ,OAAO,IAAA,CAAK,UAAA,KAAe,UAAA,GACvB,KAAK,UAAA,CAAW,IAAI,CAAA,GACnB,IAAA,CAAK,UAAA,IAAc,CAAA;AAE1B,MAAA,IAAI,QAAA;AACJ,MAAA,IAAI;AACF,QAAA,QAAA,GAAW,MAAM,OAAO,cAAA,CAAe;AAAA,UACrC,KAAA;AAAA,UACA,MAAA;AAAA,UACA,OAAA,EAAS,EAAE,UAAA,EAAY,SAAA;AAAU,SAClC,CAAA;AAAA,MACH,SAAS,GAAA,EAAK;AAEZ,QAAA,OAAO;AAAA,UACL,OAAA,EAAS,KAAA;AAAA,UACT,MAAA,EAAQ,CAAA,iCAAA,EAAoC,MAAA,CAAO,GAAG,CAAC,CAAA,CAAA;AAAA,UACvD,mBAAA,EAAqB;AAAA,SACvB;AAAA,MACF;AAGA,MAAA,IAAI,SAAS,mBAAA,EAAqB;AAChC,QAAA,OAAO;AAAA,UACL,OAAA,EAAS,KAAA;AAAA,UACT,MAAA,EACE,CAAA,QAAA,EAAW,MAAM,CAAA,aAAA,EAAgB,KAAK,CAAA,sCAAA,EAC3B,QAAA,CAAS,MAAM,CAAA,cAAA,EAAA,CAAkB,UAAA,GAA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AA,EAAQ,KAAA;AAAA,QACR,OAAA,EAAS,KAAK,OAAA,EAAQ;AAAA,QACtB,QAAQ,IAAA,CAAK;AAAA,OACd,CAAA;AACD,MAAA,OAAO,IAAA,CAAK,cAAiB,GAAG,CAAA;AAAA,IAClC,CAAA,SAAE;AACA,MAAA,YAAA,CAAa,KAAK,CAAA;AAAA,IACpB;AAAA,EACF;AAAA,EAEA,MAAc,cAAiB,GAAA,EAA2B;AACxD,IAAA,MAAM,IAAA,GAAQ,MAAM,GAAA,CAAI,IAAA,EAAK;AAC7B,IAAA,IAAI,CAAC,IAAI,EAAA,EAAI;AACX,MAAA,MAAM,IAAI,eAAA;AAAA,QACP,IAAA,CAAK,OAAO,CAAA,IAAgB,cAAA;AAAA,QAC7B,GAAA,CAAI,MAAA;AAAA,QACJ;AAAA,OACF;AAAA,IACF;AACA,IAAA,OAAO,IAAA;AAAA,EACT;AACF;;;ACjOO,SAAS,aAAa,MAAA,EAAmC;AAC9D,EAAA,OAAO,IAAI,WAAW,MAAM,CAAA;AAC9B","file":"index.mjs","sourcesContent":["/**\r\n * Vercel AI SDK integration for Lelu — Confidence-Aware Auth.\r\n *\r\n * Wraps a Vercel AI SDK `tool()` definition with a Lelu authorization\r\n * gate. The wrapped tool runs the original `execute` function only when\r\n * Lelu allows it; otherwise it returns a structured refusal object that\r\n * the model can inspect and self-correct on.\r\n *\r\n * @example\r\n * ```ts\r\n * import { tool } from 'ai';\r\n * import { z } from 'zod';\r\n * import { LeluClient } from '@lelu-auth/lelu';\r\n * import { secureTool } from 'lelu/vercel';\r\n *\r\n * const lelu = new LeluClient({ baseUrl: 'http://localhost:8082' });\r\n *\r\n * const refundTool = secureTool({\r\n * client: lelu,\r\n * actor: 'invoice_bot',\r\n * action: 'invoice:refund',\r\n * confidence: 0.92,\r\n * tool: tool({\r\n * description: 'Process a customer refund',\r\n * parameters: z.object({ invoiceId: z.string() }),\r\n * execute: async ({ invoiceId }) => ({ refunded: invoiceId }),\r\n * }),\r\n * });\r\n *\r\n * // Use in streamText / generateText:\r\n * const result = await streamText({\r\n * model: openai('gpt-4o'),\r\n * tools: { refundTool },\r\n * });\r\n * ```\r\n */\r\n\r\nimport { LeluClient } from \"../client.js\";\r\n\r\n// ─── Minimal Vercel AI SDK tool type ──────────────────────────────────────────\r\n\r\n/**\r\n * The minimal shape of a Vercel AI SDK `tool()` return value.\r\n * We keep this local to avoid a hard dependency on `ai`.\r\n */\r\nexport interface VercelTool<TArgs = unknown, TResult = unknown> {\r\n description?: string;\r\n parameters: unknown;\r\n execute?: (args: TArgs, options?: unknown) => Promise<TResult>;\r\n}\r\n\r\n// ─── Denied / Review result shape ─────────────────────────────────────────────\r\n\r\nexport interface LeluDeniedResult {\r\n /** Always `false` when the tool was blocked. */\r\n allowed: false;\r\n /** Human/LLM-readable denial reason. */\r\n reason: string;\r\n /** Whether the action is queued for human review. */\r\n requiresHumanReview: boolean;\r\n /** The downgraded scope when confidence caused a downgrade. */\r\n downgradedScope?: string;\r\n}\r\n\r\n// ─── Options ──────────────────────────────────────────────────────────────────\r\n\r\nexport interface SecureToolOptions<TArgs = unknown, TResult = unknown> {\r\n /** Configured Lelu client. */\r\n client: LeluClient;\r\n /** The agent actor / scope registered in Lelu policy. */\r\n actor: string;\r\n /** The permission string being checked. */\r\n action: string;\r\n /**\r\n * LLM confidence score (0.0–1.0). Can be a static number or a function\r\n * receiving the parsed tool arguments, allowing dynamic confidence based\r\n * on the actual call. Defaults to `1.0`.\r\n */\r\n confidence?: number | ((args: TArgs) => number);\r\n /** Optional user ID the agent is acting on behalf of. */\r\n actingFor?: string;\r\n /** The original Vercel AI SDK tool to wrap. */\r\n tool: VercelTool<TArgs, TResult>;\r\n}\r\n\r\n// ─── secureTool ───────────────────────────────────────────────────────────────\r\n\r\n/**\r\n * Wraps a Vercel AI SDK `tool()` with Lelu Confidence-Aware Auth.\r\n *\r\n * Returns a new tool object with the same `description` and `parameters`\r\n * but with an `execute` function that gates through Lelu first.\r\n *\r\n * On denial the tool returns a `LeluDeniedResult` object (not a throw) so\r\n * the model sees a structured response it can reason about.\r\n */\r\nexport function secureTool<TArgs = unknown, TResult = unknown>(\r\n opts: SecureToolOptions<TArgs, TResult>\r\n): VercelTool<TArgs, TResult | LeluDeniedResult> {\r\n const { client, actor, action, actingFor } = opts;\r\n\r\n const wrapped: VercelTool<TArgs, TResult | LeluDeniedResult> = {\r\n parameters: opts.tool.parameters,\r\n\r\n async execute(\r\n args: TArgs,\r\n options?: unknown\r\n ): Promise<TResult | LeluDeniedResult> {\r\n // Resolve confidence — static number or dynamic function.\r\n const confidence =\r\n typeof opts.confidence === \"function\"\r\n ? opts.confidence(args)\r\n : (opts.confidence ?? 1.0);\r\n\r\n let decision;\r\n try {\r\n decision = await client.agentAuthorize({\r\n actor,\r\n action,\r\n context: { confidence, actingFor },\r\n });\r\n } catch (err) {\r\n // Fail open with a structured denial so the model can handle it.\r\n return {\r\n allowed: false,\r\n reason: `Lelu authorization check failed: ${String(err)}`,\r\n requiresHumanReview: false,\r\n };\r\n }\r\n\r\n // ── Human review required ──────────────────────────────────────────\r\n if (decision.requiresHumanReview) {\r\n return {\r\n allowed: false,\r\n reason:\r\n `Action '${action}' for agent '${actor}' is queued for human review. ` +\r\n `Reason: ${decision.reason}. Confidence: ${(confidence * 100).toFixed(0)}%.`,\r\n requiresHumanReview: true,\r\n };\r\n }\r\n\r\n // ── Hard deny ─────────────────────────────────────────────────────\r\n if (!decision.allowed) {\r\n const denied: LeluDeniedResult = {\r\n allowed: false,\r\n reason:\r\n `Action '${action}' was denied for agent '${actor}'. ` +\r\n `Reason: ${decision.reason}.`,\r\n requiresHumanReview: false,\r\n };\r\n if (decision.downgradedScope !== undefined) {\r\n denied.downgradedScope = decision.downgradedScope;\r\n }\r\n return {\r\n ...denied,\r\n };\r\n }\r\n\r\n // ── Authorized — run original execute ─────────────────────────────\r\n if (!opts.tool.execute) {\r\n throw new Error(\r\n `[Lelu] secureTool: the wrapped tool '${action}' has no execute function.`\r\n );\r\n }\r\n return opts.tool.execute(args, options);\r\n },\r\n };\r\n\r\n if (opts.tool.description !== undefined) {\r\n wrapped.description = opts.tool.description;\r\n }\r\n\r\n return wrapped;\r\n}\r\n","import { z } from \"zod\";\r\n\r\n// ─── Request / Response schemas ───────────────────────────────────────────────\r\n\r\nexport const AuthRequestSchema = z.object({\r\n userId: z.string().min(1, \"userId is required\"),\r\n action: z.string().min(1, \"action is required\"),\r\n resource: z.record(z.string()).optional(),\r\n});\r\n\r\nexport const AgentContextSchema = z.object({\r\n /** LLM confidence score — 0.0 to 1.0 */\r\n confidence: z.number().min(0).max(1),\r\n /** User the agent is acting on behalf of */\r\n actingFor: z.string().optional(),\r\n /** Requested agent scope */\r\n scope: z.string().optional(),\r\n});\r\n\r\nexport const AgentAuthRequestSchema = z.object({\r\n actor: z.string().min(1, \"actor is required\"),\r\n action: z.string().min(1, \"action is required\"),\r\n resource: z.record(z.string()).optional(),\r\n context: AgentContextSchema,\r\n});\r\n\r\nexport const MintTokenRequestSchema = z.object({\r\n scope: z.string().min(1),\r\n actingFor: z.string().optional(),\r\n ttlSeconds: z.number().int().positive().optional(),\r\n});\r\n\r\nexport const DelegateScopeRequestSchema = z.object({\r\n delegator: z.string().min(1, \"delegator is required\"),\r\n delegatee: z.string().min(1, \"delegatee is required\"),\r\n scopedTo: z.array(z.string().min(1)).optional(),\r\n ttlSeconds: z.number().int().positive().optional(),\r\n confidence: z.number().min(0).max(1).optional(),\r\n actingFor: z.string().optional(),\r\n tenantId: z.string().optional(),\r\n});\r\n\r\n// ─── Decision types ───────────────────────────────────────────────────────────\r\n\r\nexport interface AuthDecision {\r\n allowed: boolean;\r\n reason: string;\r\n traceId: string;\r\n}\r\n\r\nexport interface AgentAuthDecision {\r\n allowed: boolean;\r\n reason: string;\r\n traceId: string;\r\n downgradedScope: string | undefined;\r\n requiresHumanReview: boolean;\r\n confidenceUsed: number;\r\n}\r\n\r\nexport interface MintTokenResult {\r\n token: string;\r\n tokenId: string;\r\n expiresAt: Date;\r\n}\r\n\r\nexport interface DelegateScopeRequest {\r\n /** Agent delegating the scope */\r\n delegator: string;\r\n /** Agent receiving the constrained sub-scope */\r\n delegatee: string;\r\n /** Actions to grant (must be subset of policy's can_delegate.scoped_to) */\r\n scopedTo?: string[];\r\n /** Token TTL in seconds — capped by the policy's max_ttl_seconds */\r\n ttlSeconds?: number;\r\n /** Delegator's confidence score — checked against require_confidence_above */\r\n confidence?: number;\r\n /** User the delegated agent acts on behalf of */\r\n actingFor?: string;\r\n tenantId?: string;\r\n}\r\n\r\nexport interface DelegateScopeResult {\r\n token: string;\r\n tokenId: string;\r\n expiresAt: Date;\r\n delegator: string;\r\n delegatee: string;\r\n grantedScopes: string[];\r\n traceId: string;\r\n}\r\n\r\nexport interface RevokeTokenResult {\r\n success: boolean;\r\n}\r\n\r\n// ─── Typed Input types ───────────────────────────────────────────────────────\r\n\r\nexport type AuthRequest = z.infer<typeof AuthRequestSchema>;\r\nexport type AgentAuthRequest = z.infer<typeof AgentAuthRequestSchema>;\r\nexport type AgentContext = z.infer<typeof AgentContextSchema>;\r\nexport type MintTokenRequest = z.infer<typeof MintTokenRequestSchema>;\r\n\r\n// ─── Client config ────────────────────────────────────────────────────────────\r\n\r\nexport interface ClientConfig {\r\n /** Base URL of the Auth Permission Engine (defaults to LELU_BASE_URL env var, else http://localhost:8080) */\r\n baseUrl?: string;\r\n /** Request timeout in milliseconds (default: 5000) */\r\n timeoutMs?: number;\r\n /** Optional bearer token for authenticating with the engine */\r\n apiKey?: string;\r\n}\r\n\r\n// ─── Error type ───────────────────────────────────────────────────────────────\r\n\r\nexport class AuthEngineError extends Error {\r\n constructor(\r\n message: string,\r\n public readonly status?: number,\r\n public readonly details?: unknown\r\n ) {\r\n super(message);\r\n this.name = \"AuthEngineError\";\r\n }\r\n}\r\n","import {\r\n AuthEngineError,\r\n AuthRequestSchema,\r\n AgentAuthRequestSchema,\r\n MintTokenRequestSchema,\r\n DelegateScopeRequestSchema,\r\n type AuthDecision,\r\n type AgentAuthDecision,\r\n type MintTokenResult,\r\n type DelegateScopeResult,\r\n type DelegateScopeRequest,\r\n type RevokeTokenResult,\r\n type AuthRequest,\r\n type AgentAuthRequest,\r\n type MintTokenRequest,\r\n type ClientConfig,\r\n} from \"./types.js\";\r\n\r\n// ─── Client ───────────────────────────────────────────────────────────────────\r\n\r\n/**\r\n * LeluClient is the core SDK entry-point. It communicates with the local\r\n * Auth Permission Engine sidecar over HTTP/JSON.\r\n *\r\n * @example\r\n * ```ts\r\n * const lelu = new LeluClient({ baseUrl: \"http://localhost:8080\" });\r\n *\r\n * const decision = await lelu.agentAuthorize({\r\n * actor: \"invoice_bot\",\r\n * action: \"approve_refunds\",\r\n * context: { confidence: 0.92, actingFor: \"user_123\" },\r\n * });\r\n *\r\n * if (!decision.allowed) {\r\n * console.log(decision.reason);\r\n * }\r\n * ```\r\n */\r\nexport class LeluClient {\r\n private readonly baseUrl: string;\r\n private readonly timeoutMs: number;\r\n private readonly apiKey: string | undefined;\r\n\r\n constructor(cfg: ClientConfig = {}) {\r\n const envBaseUrl =\r\n typeof process !== \"undefined\" && process.env\r\n ? process.env[\"LELU_BASE_URL\"]\r\n : undefined;\r\n this.baseUrl = (cfg.baseUrl ?? envBaseUrl ?? \"http://localhost:8080\").replace(/\\/$/, \"\");\r\n this.timeoutMs = cfg.timeoutMs ?? 5_000;\r\n this.apiKey = cfg.apiKey;\r\n }\r\n\r\n // ── Human authorization ────────────────────────────────────────────────────\r\n\r\n /**\r\n * Checks whether a human user is permitted to perform an action.\r\n */\r\n async authorize(req: AuthRequest): Promise<AuthDecision> {\r\n const validated = AuthRequestSchema.parse(req);\r\n const body = {\r\n user_id: validated.userId,\r\n action: validated.action,\r\n resource: validated.resource,\r\n };\r\n const data = await this.post<{\r\n allowed: boolean;\r\n reason: string;\r\n trace_id: string;\r\n }>(\"/v1/authorize\", body);\r\n\r\n return {\r\n allowed: data.allowed,\r\n reason: data.reason,\r\n traceId: data.trace_id,\r\n };\r\n }\r\n\r\n // ── Agent authorization ────────────────────────────────────────────────────\r\n\r\n /**\r\n * Checks whether an AI agent is permitted to perform an action, taking the\r\n * confidence score into account (Confidence-Aware Auth ★).\r\n */\r\n async agentAuthorize(req: AgentAuthRequest): Promise<AgentAuthDecision> {\r\n const validated = AgentAuthRequestSchema.parse(req);\r\n const body = {\r\n actor: validated.actor,\r\n action: validated.action,\r\n resource: validated.resource,\r\n confidence: validated.context.confidence,\r\n acting_for: validated.context.actingFor,\r\n scope: validated.context.scope,\r\n };\r\n const data = await this.post<{\r\n allowed: boolean;\r\n reason: string;\r\n trace_id: string;\r\n downgraded_scope?: string;\r\n requires_human_review: boolean;\r\n confidence_used: number;\r\n }>(\"/v1/agent/authorize\", body);\r\n\r\n return {\r\n allowed: data.allowed,\r\n reason: data.reason,\r\n traceId: data.trace_id,\r\n downgradedScope: data.downgraded_scope,\r\n requiresHumanReview: data.requires_human_review,\r\n confidenceUsed: data.confidence_used,\r\n };\r\n }\r\n\r\n // ── JIT Token minting ──────────────────────────────────────────────────────\r\n\r\n /**\r\n * Mints a scoped JWT for an agent with an optional TTL.\r\n * Default TTL is 60 seconds.\r\n */\r\n async mintToken(req: MintTokenRequest): Promise<MintTokenResult> {\r\n const validated = MintTokenRequestSchema.parse(req);\r\n const body = {\r\n scope: validated.scope,\r\n acting_for: validated.actingFor,\r\n ttl_seconds: validated.ttlSeconds ?? 60,\r\n };\r\n const data = await this.post<{\r\n token: string;\r\n token_id: string;\r\n expires_at: number;\r\n }>(\"/v1/tokens/mint\", body);\r\n\r\n return {\r\n token: data.token,\r\n tokenId: data.token_id,\r\n expiresAt: new Date(data.expires_at * 1000),\r\n };\r\n }\r\n\r\n // ── Token revocation ───────────────────────────────────────────────────────\r\n\r\n /**\r\n * Immediately revokes a JIT token by its ID.\r\n */\r\n async revokeToken(tokenId: string): Promise<RevokeTokenResult> {\r\n const data = await this.delete<{ success: boolean }>(\r\n `/v1/tokens/${encodeURIComponent(tokenId)}`\r\n );\r\n return { success: data.success };\r\n }\r\n\r\n // ── Multi-agent delegation ─────────────────────────────────────────────────\r\n\r\n /**\r\n * Delegates a constrained sub-scope from one agent to another.\r\n *\r\n * Validates the delegation rule in the loaded policy, caps the TTL to the\r\n * policy maximum, and mints a child JIT token scoped to the granted actions.\r\n *\r\n * The delegator's `confidence` score is checked against the policy's\r\n * `require_confidence_above` before delegation is granted.\r\n */\r\n async delegateScope(req: DelegateScopeRequest): Promise<DelegateScopeResult> {\r\n const validated = DelegateScopeRequestSchema.parse(req);\r\n const body = {\r\n delegator: validated.delegator,\r\n delegatee: validated.delegatee,\r\n scoped_to: validated.scopedTo ?? [],\r\n ttl_seconds: validated.ttlSeconds ?? 60,\r\n confidence: validated.confidence ?? 1.0,\r\n acting_for: validated.actingFor ?? \"\",\r\n tenant_id: validated.tenantId ?? \"\",\r\n };\r\n const data = await this.post<{\r\n token: string;\r\n token_id: string;\r\n expires_at: number;\r\n delegator: string;\r\n delegatee: string;\r\n granted_scopes: string[];\r\n trace_id: string;\r\n }>(\"/v1/agent/delegate\", body);\r\n\r\n return {\r\n token: data.token,\r\n tokenId: data.token_id,\r\n expiresAt: new Date(data.expires_at * 1000),\r\n delegator: data.delegator,\r\n delegatee: data.delegatee,\r\n grantedScopes: data.granted_scopes,\r\n traceId: data.trace_id,\r\n };\r\n }\r\n\r\n // ── Health check ───────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Returns true if the engine is reachable and healthy.\r\n */\r\n async isHealthy(): Promise<boolean> {\r\n try {\r\n const data = await this.get<{ status: string }>(\"/healthz\");\r\n return data.status === \"ok\";\r\n } catch {\r\n return false;\r\n }\r\n }\r\n\r\n // ── HTTP helpers ───────────────────────────────────────────────────────────\r\n\r\n private headers(): Record<string, string> {\r\n const h: Record<string, string> = { \"Content-Type\": \"application/json\" };\r\n if (this.apiKey) {\r\n h[\"Authorization\"] = `Bearer ${this.apiKey}`;\r\n }\r\n return h;\r\n }\r\n\r\n private async post<T>(path: string, body: unknown): Promise<T> {\r\n const ctrl = new AbortController();\r\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\r\n try {\r\n const res = await fetch(`${this.baseUrl}${path}`, {\r\n method: \"POST\",\r\n headers: this.headers(),\r\n body: JSON.stringify(body),\r\n signal: ctrl.signal,\r\n });\r\n return this.parseResponse<T>(res);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n }\r\n\r\n private async delete<T>(path: string): Promise<T> {\r\n const ctrl = new AbortController();\r\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\r\n try {\r\n const res = await fetch(`${this.baseUrl}${path}`, {\r\n method: \"DELETE\",\r\n headers: this.headers(),\r\n signal: ctrl.signal,\r\n });\r\n return this.parseResponse<T>(res);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n }\r\n\r\n private async get<T>(path: string): Promise<T> {\r\n const ctrl = new AbortController();\r\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\r\n try {\r\n const res = await fetch(`${this.baseUrl}${path}`, {\r\n method: \"GET\",\r\n headers: this.headers(),\r\n signal: ctrl.signal,\r\n });\r\n return this.parseResponse<T>(res);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n }\r\n\r\n private async parseResponse<T>(res: Response): Promise<T> {\r\n const json = (await res.json()) as Record<string, unknown>;\r\n if (!res.ok) {\r\n throw new AuthEngineError(\r\n (json[\"error\"] as string) ?? \"engine error\",\r\n res.status,\r\n json\r\n );\r\n }\r\n return json as T;\r\n }\r\n}\r\n","// Auth Permission Engine — TypeScript SDK\r\n// Public API surface\r\n\r\n// ─── Vercel AI SDK integration ────────────────────────────────────────────────\r\n// Import via: import { secureTool } from 'lelu/vercel'\r\n// (tree-shakeable — does not add weight to non-Vercel users)\r\nexport { secureTool } from \"./vercel/index.js\";\r\nexport type { SecureToolOptions, LeluDeniedResult, VercelTool } from \"./vercel/index.js\";\r\n\r\nexport { LeluClient } from \"./client.js\";\r\n\r\nexport type {\r\n AuthRequest,\r\n AgentAuthRequest,\r\n AgentContext,\r\n MintTokenRequest,\r\n DelegateScopeRequest,\r\n AuthDecision,\r\n AgentAuthDecision,\r\n MintTokenResult,\r\n DelegateScopeResult,\r\n RevokeTokenResult,\r\n ClientConfig,\r\n} from \"./types.js\";\r\n\r\nexport {\r\n AuthEngineError,\r\n AuthRequestSchema,\r\n AgentAuthRequestSchema,\r\n AgentContextSchema,\r\n MintTokenRequestSchema,\r\n DelegateScopeRequestSchema,\r\n} from \"./types.js\";\r\n\r\n// ─── Convenience factory ──────────────────────────────────────────────────────\r\n\r\nimport { LeluClient } from \"./client.js\";\r\nimport type { ClientConfig } from \"./types.js\";\r\n\r\n/**\r\n * Creates a LeluClient with the given configuration.\r\n * Equivalent to `new LeluClient(config)`.\r\n *\r\n * @example\r\n * ```ts\r\n * import { createClient } from \"@lelu-auth/lelu\";\r\n *\r\n * const lelu = createClient({ baseUrl: \"http://localhost:8080\" });\r\n * const { allowed } = await lelu.agentAuthorize({ ... });\r\n * ```\r\n */\r\nexport function createClient(config?: ClientConfig): LeluClient {\r\n return new LeluClient(config);\r\n}\r\n"]}
1
+ {"version":3,"sources":["../src/vercel/index.ts","../src/types.ts","../src/client.ts","../src/index.ts"],"names":[],"mappings":";;;AAgGO,SAAS,WACd,IAAA,EAC+C;AAC/C,EAAA,MAAM,EAAE,MAAA,EAAQ,KAAA,EAAO,MAAA,EAAQ,WAAU,GAAI,IAAA;AAE7C,EAAA,MAAM,OAAA,GAAyD;AAAA,IAC7D,UAAA,EAAY,KAAK,IAAA,CAAK,UAAA;AAAA,IAEtB,MAAM,OAAA,CACJ,IAAA,EACA,OAAA,EACqC;AAErC,MAAA,MAAM,UAAA,GACJ,OAAO,IAAA,CAAK,UAAA,KAAe,UAAA,GACvB,KAAK,UAAA,CAAW,IAAI,CAAA,GACnB,IAAA,CAAK,UAAA,IAAc,CAAA;AAE1B,MAAA,IAAI,QAAA;AACJ,MAAA,IAAI;AACF,QAAA,QAAA,GAAW,MAAM,OAAO,cAAA,CAAe;AAAA,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AA,QAC7B,GAAA,CAAI,MAAA;AAAA,QACJ;AAAA,OACF;AAAA,IACF;AACA,IAAA,OAAO,IAAA;AAAA,EACT;AACF;;;ACjYO,SAAS,aAAa,MAAA,EAAmC;AAC9D,EAAA,OAAO,IAAI,WAAW,MAAM,CAAA;AAC9B","file":"index.mjs","sourcesContent":["/**\r\n * Vercel AI SDK integration for Lelu — Confidence-Aware Auth.\r\n *\r\n * Wraps a Vercel AI SDK `tool()` definition with a Lelu authorization\r\n * gate. The wrapped tool runs the original `execute` function only when\r\n * Lelu allows it; otherwise it returns a structured refusal object that\r\n * the model can inspect and self-correct on.\r\n *\r\n * @example\r\n * ```ts\r\n * import { tool } from 'ai';\r\n * import { z } from 'zod';\r\n * import { LeluClient } from '@lelu-auth/lelu';\r\n * import { secureTool } from 'lelu/vercel';\r\n *\r\n * const lelu = new LeluClient({ baseUrl: 'http://localhost:8082' });\r\n *\r\n * const refundTool = secureTool({\r\n * client: lelu,\r\n * actor: 'invoice_bot',\r\n * action: 'invoice:refund',\r\n * confidence: 0.92,\r\n * tool: tool({\r\n * description: 'Process a customer refund',\r\n * parameters: z.object({ invoiceId: z.string() }),\r\n * execute: async ({ invoiceId }) => ({ refunded: invoiceId }),\r\n * }),\r\n * });\r\n *\r\n * // Use in streamText / generateText:\r\n * const result = await streamText({\r\n * model: openai('gpt-4o'),\r\n * tools: { refundTool },\r\n * });\r\n * ```\r\n */\r\n\r\nimport { LeluClient } from \"../client.js\";\r\n\r\n// ─── Minimal Vercel AI SDK tool type ──────────────────────────────────────────\r\n\r\n/**\r\n * The minimal shape of a Vercel AI SDK `tool()` return value.\r\n * We keep this local to avoid a hard dependency on `ai`.\r\n */\r\nexport interface VercelTool<TArgs = unknown, TResult = unknown> {\r\n description?: string;\r\n parameters: unknown;\r\n execute?: (args: TArgs, options?: unknown) => Promise<TResult>;\r\n}\r\n\r\n// ─── Denied / Review result shape ─────────────────────────────────────────────\r\n\r\nexport interface LeluDeniedResult {\r\n /** Always `false` when the tool was blocked. */\r\n allowed: false;\r\n /** Human/LLM-readable denial reason. */\r\n reason: string;\r\n /** Whether the action is queued for human review. */\r\n requiresHumanReview: boolean;\r\n /** The downgraded scope when confidence caused a downgrade. */\r\n downgradedScope?: string;\r\n}\r\n\r\n// ─── Options ──────────────────────────────────────────────────────────────────\r\n\r\nexport interface SecureToolOptions<TArgs = unknown, TResult = unknown> {\r\n /** Configured Lelu client. */\r\n client: LeluClient;\r\n /** The agent actor / scope registered in Lelu policy. */\r\n actor: string;\r\n /** The permission string being checked. */\r\n action: string;\r\n /**\r\n * LLM confidence score (0.0–1.0). Can be a static number or a function\r\n * receiving the parsed tool arguments, allowing dynamic confidence based\r\n * on the actual call. Defaults to `1.0`.\r\n */\r\n confidence?: number | ((args: TArgs) => number);\r\n /** Optional user ID the agent is acting on behalf of. */\r\n actingFor?: string;\r\n /** The original Vercel AI SDK tool to wrap. */\r\n tool: VercelTool<TArgs, TResult>;\r\n}\r\n\r\n// ─── secureTool ───────────────────────────────────────────────────────────────\r\n\r\n/**\r\n * Wraps a Vercel AI SDK `tool()` with Lelu Confidence-Aware Auth.\r\n *\r\n * Returns a new tool object with the same `description` and `parameters`\r\n * but with an `execute` function that gates through Lelu first.\r\n *\r\n * On denial the tool returns a `LeluDeniedResult` object (not a throw) so\r\n * the model sees a structured response it can reason about.\r\n */\r\nexport function secureTool<TArgs = unknown, TResult = unknown>(\r\n opts: SecureToolOptions<TArgs, TResult>\r\n): VercelTool<TArgs, TResult | LeluDeniedResult> {\r\n const { client, actor, action, actingFor } = opts;\r\n\r\n const wrapped: VercelTool<TArgs, TResult | LeluDeniedResult> = {\r\n parameters: opts.tool.parameters,\r\n\r\n async execute(\r\n args: TArgs,\r\n options?: unknown\r\n ): Promise<TResult | LeluDeniedResult> {\r\n // Resolve confidence — static number or dynamic function.\r\n const confidence =\r\n typeof opts.confidence === \"function\"\r\n ? opts.confidence(args)\r\n : (opts.confidence ?? 1.0);\r\n\r\n let decision;\r\n try {\r\n decision = await client.agentAuthorize({\r\n actor,\r\n action,\r\n context: { confidence, actingFor },\r\n });\r\n } catch (err) {\r\n // Fail open with a structured denial so the model can handle it.\r\n return {\r\n allowed: false,\r\n reason: `Lelu authorization check failed: ${String(err)}`,\r\n requiresHumanReview: false,\r\n };\r\n }\r\n\r\n // ── Human review required ──────────────────────────────────────────\r\n if (decision.requiresHumanReview) {\r\n return {\r\n allowed: false,\r\n reason:\r\n `Action '${action}' for agent '${actor}' is queued for human review. ` +\r\n `Reason: ${decision.reason}. Confidence: ${(confidence * 100).toFixed(0)}%.`,\r\n requiresHumanReview: true,\r\n };\r\n }\r\n\r\n // ── Hard deny ─────────────────────────────────────────────────────\r\n if (!decision.allowed) {\r\n const denied: LeluDeniedResult = {\r\n allowed: false,\r\n reason:\r\n `Action '${action}' was denied for agent '${actor}'. ` +\r\n `Reason: ${decision.reason}.`,\r\n requiresHumanReview: false,\r\n };\r\n if (decision.downgradedScope !== undefined) {\r\n denied.downgradedScope = decision.downgradedScope;\r\n }\r\n return {\r\n ...denied,\r\n };\r\n }\r\n\r\n // ── Authorized — run original execute ─────────────────────────────\r\n if (!opts.tool.execute) {\r\n throw new Error(\r\n `[Lelu] secureTool: the wrapped tool '${action}' has no execute function.`\r\n );\r\n }\r\n return opts.tool.execute(args, options);\r\n },\r\n };\r\n\r\n if (opts.tool.description !== undefined) {\r\n wrapped.description = opts.tool.description;\r\n }\r\n\r\n return wrapped;\r\n}\r\n","import { z } from \"zod\";\r\n\r\n// ─── Request / Response schemas ───────────────────────────────────────────────\r\n\r\nexport const AuthRequestSchema = z.object({\r\n userId: z.string().min(1, \"userId is required\"),\r\n action: z.string().min(1, \"action is required\"),\r\n resource: z.record(z.string()).optional(),\r\n});\r\n\r\nexport const AgentContextSchema = z.object({\r\n /** LLM confidence score — 0.0 to 1.0 */\r\n confidence: z.number().min(0).max(1),\r\n /** User the agent is acting on behalf of */\r\n actingFor: z.string().optional(),\r\n /** Requested agent scope */\r\n scope: z.string().optional(),\r\n});\r\n\r\nexport const AgentAuthRequestSchema = z.object({\r\n actor: z.string().min(1, \"actor is required\"),\r\n action: z.string().min(1, \"action is required\"),\r\n resource: z.record(z.string()).optional(),\r\n context: AgentContextSchema,\r\n});\r\n\r\nexport const MintTokenRequestSchema = z.object({\r\n scope: z.string().min(1),\r\n actingFor: z.string().optional(),\r\n ttlSeconds: z.number().int().positive().optional(),\r\n});\r\n\r\nexport const DelegateScopeRequestSchema = z.object({\r\n delegator: z.string().min(1, \"delegator is required\"),\r\n delegatee: z.string().min(1, \"delegatee is required\"),\r\n scopedTo: z.array(z.string().min(1)).optional(),\r\n ttlSeconds: z.number().int().positive().optional(),\r\n confidence: z.number().min(0).max(1).optional(),\r\n actingFor: z.string().optional(),\r\n tenantId: z.string().optional(),\r\n});\r\n\r\n// ─── Decision types ───────────────────────────────────────────────────────────\r\n\r\nexport interface AuthDecision {\r\n allowed: boolean;\r\n reason: string;\r\n traceId: string;\r\n}\r\n\r\nexport interface AgentAuthDecision {\r\n allowed: boolean;\r\n reason: string;\r\n traceId: string;\r\n downgradedScope: string | undefined;\r\n requiresHumanReview: boolean;\r\n confidenceUsed: number;\r\n}\r\n\r\nexport interface MintTokenResult {\r\n token: string;\r\n tokenId: string;\r\n expiresAt: Date;\r\n}\r\n\r\nexport interface DelegateScopeRequest {\r\n /** Agent delegating the scope */\r\n delegator: string;\r\n /** Agent receiving the constrained sub-scope */\r\n delegatee: string;\r\n /** Actions to grant (must be subset of policy's can_delegate.scoped_to) */\r\n scopedTo?: string[];\r\n /** Token TTL in seconds — capped by the policy's max_ttl_seconds */\r\n ttlSeconds?: number;\r\n /** Delegator's confidence score — checked against require_confidence_above */\r\n confidence?: number;\r\n /** User the delegated agent acts on behalf of */\r\n actingFor?: string;\r\n tenantId?: string;\r\n}\r\n\r\nexport interface DelegateScopeResult {\r\n token: string;\r\n tokenId: string;\r\n expiresAt: Date;\r\n delegator: string;\r\n delegatee: string;\r\n grantedScopes: string[];\r\n traceId: string;\r\n}\r\n\r\nexport interface RevokeTokenResult {\r\n success: boolean;\r\n}\r\n\r\n// ─── Audit types ──────────────────────────────────────────────────────────────\r\n\r\nexport interface AuditEvent {\r\n id: number;\r\n tenantId: string;\r\n traceId: string;\r\n timestamp: string;\r\n actor: string;\r\n action: string;\r\n resource?: Record<string, string>;\r\n confidenceScore?: number;\r\n decision: string; // \"allowed\" | \"denied\" | \"human_review\"\r\n reason?: string;\r\n downgradedScope?: string;\r\n latencyMs: number;\r\n engineVersion?: string;\r\n policyVersion?: string;\r\n createdAt: string;\r\n}\r\n\r\nexport interface ListAuditEventsRequest {\r\n /** Maximum number of events to return (default: 20, max: 500) */\r\n limit?: number;\r\n /** Pagination cursor (offset) */\r\n cursor?: number;\r\n /** Filter by actor */\r\n actor?: string;\r\n /** Filter by action */\r\n action?: string;\r\n /** Filter by decision */\r\n decision?: string;\r\n /** Filter by trace ID */\r\n traceId?: string;\r\n /** Filter events from this timestamp (ISO 8601) */\r\n from?: string;\r\n /** Filter events to this timestamp (ISO 8601) */\r\n to?: string;\r\n /** Tenant ID (defaults to \"default\") */\r\n tenantId?: string;\r\n}\r\n\r\nexport interface ListAuditEventsResult {\r\n events: AuditEvent[];\r\n count: number;\r\n limit: number;\r\n cursor: number;\r\n nextCursor: number;\r\n}\r\n\r\n// ─── Typed Input types ───────────────────────────────────────────────────────\r\n\r\nexport type AuthRequest = z.infer<typeof AuthRequestSchema>;\r\nexport type AgentAuthRequest = z.infer<typeof AgentAuthRequestSchema>;\r\nexport type AgentContext = z.infer<typeof AgentContextSchema>;\r\nexport type MintTokenRequest = z.infer<typeof MintTokenRequestSchema>;\r\n\r\n// ─── Client config ────────────────────────────────────────────────────────────\r\n\r\nexport interface ClientConfig {\r\n /** Base URL of the Auth Permission Engine (defaults to LELU_BASE_URL env var, else http://localhost:8080) */\r\n baseUrl?: string;\r\n /** Request timeout in milliseconds (default: 5000) */\r\n timeoutMs?: number;\r\n /** Optional bearer token for authenticating with the engine */\r\n apiKey?: string;\r\n}\r\n\r\n// ─── Error type ───────────────────────────────────────────────────────────────\r\n\r\n// ─── Policy types ─────────────────────────────────────────────────────────────\r\n\r\nexport interface Policy {\r\n id: string;\r\n tenantId: string;\r\n name: string;\r\n content: string;\r\n version: string;\r\n hmacSha256: string;\r\n createdAt: string;\r\n updatedAt: string;\r\n}\r\n\r\nexport interface ListPoliciesRequest {\r\n /** Tenant ID (defaults to \"default\") */\r\n tenantId?: string;\r\n}\r\n\r\nexport interface ListPoliciesResult {\r\n policies: Policy[];\r\n count: number;\r\n}\r\n\r\nexport interface GetPolicyRequest {\r\n /** Policy name */\r\n name: string;\r\n /** Tenant ID (defaults to \"default\") */\r\n tenantId?: string;\r\n}\r\n\r\nexport interface UpsertPolicyRequest {\r\n /** Policy name */\r\n name: string;\r\n /** Policy content (Rego code) */\r\n content: string;\r\n /** Policy version (defaults to \"1.0\") */\r\n version?: string;\r\n /** Tenant ID (defaults to \"default\") */\r\n tenantId?: string;\r\n}\r\n\r\nexport interface DeletePolicyRequest {\r\n /** Policy name */\r\n name: string;\r\n /** Tenant ID (defaults to \"default\") */\r\n tenantId?: string;\r\n}\r\n\r\nexport interface DeletePolicyResult {\r\n deleted: boolean;\r\n}\r\n\r\n// ─── Error type ───────────────────────────────────────────────────────────────\r\n\r\nexport class AuthEngineError extends Error {\r\n constructor(\r\n message: string,\r\n public readonly status?: number,\r\n public readonly details?: unknown\r\n ) {\r\n super(message);\r\n this.name = \"AuthEngineError\";\r\n }\r\n}\r\n// ─── Policy types ─────────────────────────────────────────────────────────────\r\n\r\nexport interface Policy {\r\n id: string;\r\n tenantId: string;\r\n name: string;\r\n content: string;\r\n version: string;\r\n hmacSha256: string;\r\n createdAt: string;\r\n updatedAt: string;\r\n}\r\n\r\nexport interface ListPoliciesRequest {\r\n /** Tenant ID (defaults to \"default\") */\r\n tenantId?: string;\r\n}\r\n\r\nexport interface ListPoliciesResult {\r\n policies: Policy[];\r\n count: number;\r\n}\r\n\r\nexport interface GetPolicyRequest {\r\n /** Policy name */\r\n name: string;\r\n /** Tenant ID (defaults to \"default\") */\r\n tenantId?: string;\r\n}\r\n\r\nexport interface UpsertPolicyRequest {\r\n /** Policy name */\r\n name: string;\r\n /** Policy content (Rego code) */\r\n content: string;\r\n /** Policy version (defaults to \"1.0\") */\r\n version?: string;\r\n /** Tenant ID (defaults to \"default\") */\r\n tenantId?: string;\r\n}\r\n\r\nexport interface DeletePolicyRequest {\r\n /** Policy name */\r\n name: string;\r\n /** Tenant ID (defaults to \"default\") */\r\n tenantId?: string;\r\n}\r\n\r\nexport interface DeletePolicyResult {\r\n deleted: boolean;\r\n}\r\n","import {\r\n AuthEngineError,\r\n AuthRequestSchema,\r\n AgentAuthRequestSchema,\r\n MintTokenRequestSchema,\r\n DelegateScopeRequestSchema,\r\n type AuthDecision,\r\n type AgentAuthDecision,\r\n type MintTokenResult,\r\n type DelegateScopeResult,\r\n type DelegateScopeRequest,\r\n type RevokeTokenResult,\r\n type AuthRequest,\r\n type AgentAuthRequest,\r\n type MintTokenRequest,\r\n type ClientConfig,\r\n type AuditEvent,\r\n type ListAuditEventsRequest,\r\n type ListAuditEventsResult,\r\n type Policy,\r\n type ListPoliciesRequest,\r\n type ListPoliciesResult,\r\n type GetPolicyRequest,\r\n type UpsertPolicyRequest,\r\n type DeletePolicyRequest,\r\n type DeletePolicyResult,\r\n} from \"./types.js\";\r\n\r\n// ─── Client ───────────────────────────────────────────────────────────────────\r\n\r\n/**\r\n * LeluClient is the core SDK entry-point. It communicates with the local\r\n * Auth Permission Engine sidecar over HTTP/JSON.\r\n *\r\n * @example\r\n * ```ts\r\n * const lelu = new LeluClient({ baseUrl: \"http://localhost:8080\" });\r\n *\r\n * const decision = await lelu.agentAuthorize({\r\n * actor: \"invoice_bot\",\r\n * action: \"approve_refunds\",\r\n * context: { confidence: 0.92, actingFor: \"user_123\" },\r\n * });\r\n *\r\n * if (!decision.allowed) {\r\n * console.log(decision.reason);\r\n * }\r\n * ```\r\n */\r\nexport class LeluClient {\r\n private readonly baseUrl: string;\r\n private readonly timeoutMs: number;\r\n private readonly apiKey: string | undefined;\r\n\r\n constructor(cfg: ClientConfig = {}) {\r\n const envBaseUrl =\r\n typeof process !== \"undefined\" && process.env\r\n ? process.env[\"LELU_BASE_URL\"]\r\n : undefined;\r\n this.baseUrl = (cfg.baseUrl ?? envBaseUrl ?? \"http://localhost:8080\").replace(/\\/$/, \"\");\r\n this.timeoutMs = cfg.timeoutMs ?? 5_000;\r\n this.apiKey = cfg.apiKey;\r\n }\r\n\r\n // ── Human authorization ────────────────────────────────────────────────────\r\n\r\n /**\r\n * Checks whether a human user is permitted to perform an action.\r\n */\r\n async authorize(req: AuthRequest): Promise<AuthDecision> {\r\n const validated = AuthRequestSchema.parse(req);\r\n const body = {\r\n user_id: validated.userId,\r\n action: validated.action,\r\n resource: validated.resource,\r\n };\r\n const data = await this.post<{\r\n allowed: boolean;\r\n reason: string;\r\n trace_id: string;\r\n }>(\"/v1/authorize\", body);\r\n\r\n return {\r\n allowed: data.allowed,\r\n reason: data.reason,\r\n traceId: data.trace_id,\r\n };\r\n }\r\n\r\n // ── Agent authorization ────────────────────────────────────────────────────\r\n\r\n /**\r\n * Checks whether an AI agent is permitted to perform an action, taking the\r\n * confidence score into account (Confidence-Aware Auth ★).\r\n */\r\n async agentAuthorize(req: AgentAuthRequest): Promise<AgentAuthDecision> {\r\n const validated = AgentAuthRequestSchema.parse(req);\r\n const body = {\r\n actor: validated.actor,\r\n action: validated.action,\r\n resource: validated.resource,\r\n confidence: validated.context.confidence,\r\n acting_for: validated.context.actingFor,\r\n scope: validated.context.scope,\r\n };\r\n const data = await this.post<{\r\n allowed: boolean;\r\n reason: string;\r\n trace_id: string;\r\n downgraded_scope?: string;\r\n requires_human_review: boolean;\r\n confidence_used: number;\r\n }>(\"/v1/agent/authorize\", body);\r\n\r\n return {\r\n allowed: data.allowed,\r\n reason: data.reason,\r\n traceId: data.trace_id,\r\n downgradedScope: data.downgraded_scope,\r\n requiresHumanReview: data.requires_human_review,\r\n confidenceUsed: data.confidence_used,\r\n };\r\n }\r\n\r\n // ── JIT Token minting ──────────────────────────────────────────────────────\r\n\r\n /**\r\n * Mints a scoped JWT for an agent with an optional TTL.\r\n * Default TTL is 60 seconds.\r\n */\r\n async mintToken(req: MintTokenRequest): Promise<MintTokenResult> {\r\n const validated = MintTokenRequestSchema.parse(req);\r\n const body = {\r\n scope: validated.scope,\r\n acting_for: validated.actingFor,\r\n ttl_seconds: validated.ttlSeconds ?? 60,\r\n };\r\n const data = await this.post<{\r\n token: string;\r\n token_id: string;\r\n expires_at: number;\r\n }>(\"/v1/tokens/mint\", body);\r\n\r\n return {\r\n token: data.token,\r\n tokenId: data.token_id,\r\n expiresAt: new Date(data.expires_at * 1000),\r\n };\r\n }\r\n\r\n // ── Token revocation ───────────────────────────────────────────────────────\r\n\r\n /**\r\n * Immediately revokes a JIT token by its ID.\r\n */\r\n async revokeToken(tokenId: string): Promise<RevokeTokenResult> {\r\n const data = await this.delete<{ success: boolean }>(\r\n `/v1/tokens/${encodeURIComponent(tokenId)}`\r\n );\r\n return { success: data.success };\r\n }\r\n\r\n // ── Multi-agent delegation ─────────────────────────────────────────────────\r\n\r\n /**\r\n * Delegates a constrained sub-scope from one agent to another.\r\n *\r\n * Validates the delegation rule in the loaded policy, caps the TTL to the\r\n * policy maximum, and mints a child JIT token scoped to the granted actions.\r\n *\r\n * The delegator's `confidence` score is checked against the policy's\r\n * `require_confidence_above` before delegation is granted.\r\n */\r\n async delegateScope(req: DelegateScopeRequest): Promise<DelegateScopeResult> {\r\n const validated = DelegateScopeRequestSchema.parse(req);\r\n const body = {\r\n delegator: validated.delegator,\r\n delegatee: validated.delegatee,\r\n scoped_to: validated.scopedTo ?? [],\r\n ttl_seconds: validated.ttlSeconds ?? 60,\r\n confidence: validated.confidence ?? 1.0,\r\n acting_for: validated.actingFor ?? \"\",\r\n tenant_id: validated.tenantId ?? \"\",\r\n };\r\n const data = await this.post<{\r\n token: string;\r\n token_id: string;\r\n expires_at: number;\r\n delegator: string;\r\n delegatee: string;\r\n granted_scopes: string[];\r\n trace_id: string;\r\n }>(\"/v1/agent/delegate\", body);\r\n\r\n return {\r\n token: data.token,\r\n tokenId: data.token_id,\r\n expiresAt: new Date(data.expires_at * 1000),\r\n delegator: data.delegator,\r\n delegatee: data.delegatee,\r\n grantedScopes: data.granted_scopes,\r\n traceId: data.trace_id,\r\n };\r\n }\r\n\r\n // ── Health check ───────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Returns true if the engine is reachable and healthy.\r\n */\r\n async isHealthy(): Promise<boolean> {\r\n try {\r\n const data = await this.get<{ status: string }>(\"/healthz\");\r\n return data.status === \"ok\";\r\n } catch {\r\n return false;\r\n }\r\n }\r\n\r\n // ── Audit log ──────────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Lists audit events from the platform API.\r\n * Requires the platform service to be running (not just the engine).\r\n */\r\n async listAuditEvents(req: ListAuditEventsRequest = {}): Promise<ListAuditEventsResult> {\r\n const params = new URLSearchParams();\r\n \r\n if (req.limit !== undefined) params.set(\"limit\", req.limit.toString());\r\n if (req.cursor !== undefined) params.set(\"cursor\", req.cursor.toString());\r\n if (req.actor) params.set(\"actor\", req.actor);\r\n if (req.action) params.set(\"action\", req.action);\r\n if (req.decision) params.set(\"decision\", req.decision);\r\n if (req.traceId) params.set(\"trace_id\", req.traceId);\r\n if (req.from) params.set(\"from\", req.from);\r\n if (req.to) params.set(\"to\", req.to);\r\n\r\n const headers = this.headers();\r\n if (req.tenantId) {\r\n headers[\"X-Tenant-ID\"] = req.tenantId;\r\n }\r\n\r\n const ctrl = new AbortController();\r\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\r\n try {\r\n const url = `${this.baseUrl}/api/v1/audit${params.toString() ? `?${params.toString()}` : \"\"}`;\r\n const res = await fetch(url, {\r\n method: \"GET\",\r\n headers,\r\n signal: ctrl.signal,\r\n });\r\n \r\n const data = await this.parseResponse<{\r\n events: AuditEvent[];\r\n count: number;\r\n limit: number;\r\n cursor: number;\r\n next_cursor: number;\r\n }>(res);\r\n\r\n return {\r\n events: data.events || [],\r\n count: data.count,\r\n limit: data.limit,\r\n cursor: data.cursor,\r\n nextCursor: data.next_cursor,\r\n };\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n }\r\n\r\n // ─── Policy Management ────────────────────────────────────────────────────────\r\n\r\n async listPolicies(req: ListPoliciesRequest = {}): Promise<ListPoliciesResult> {\r\n const headers = this.headers();\r\n if (req.tenantId) {\r\n headers[\"X-Tenant-ID\"] = req.tenantId;\r\n }\r\n\r\n const ctrl = new AbortController();\r\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\r\n try {\r\n const res = await fetch(`${this.baseUrl}/api/v1/policies`, {\r\n method: \"GET\",\r\n headers,\r\n signal: ctrl.signal,\r\n });\r\n \r\n const data = await this.parseResponse<{\r\n policies: Policy[];\r\n count: number;\r\n }>(res);\r\n\r\n return {\r\n policies: data.policies || [],\r\n count: data.count,\r\n };\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n }\r\n\r\n async getPolicy(req: GetPolicyRequest): Promise<Policy> {\r\n const headers = this.headers();\r\n if (req.tenantId) {\r\n headers[\"X-Tenant-ID\"] = req.tenantId;\r\n }\r\n\r\n const ctrl = new AbortController();\r\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\r\n try {\r\n const res = await fetch(`${this.baseUrl}/api/v1/policies/${encodeURIComponent(req.name)}`, {\r\n method: \"GET\",\r\n headers,\r\n signal: ctrl.signal,\r\n });\r\n \r\n return await this.parseResponse<Policy>(res);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n }\r\n\r\n async upsertPolicy(req: UpsertPolicyRequest): Promise<Policy> {\r\n const headers = this.headers();\r\n if (req.tenantId) {\r\n headers[\"X-Tenant-ID\"] = req.tenantId;\r\n }\r\n\r\n const body = {\r\n content: req.content,\r\n version: req.version || \"1.0\"\r\n };\r\n\r\n const ctrl = new AbortController();\r\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\r\n try {\r\n const res = await fetch(`${this.baseUrl}/api/v1/policies/${encodeURIComponent(req.name)}`, {\r\n method: \"PUT\",\r\n headers,\r\n body: JSON.stringify(body),\r\n signal: ctrl.signal,\r\n });\r\n \r\n return await this.parseResponse<Policy>(res);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n }\r\n\r\n async deletePolicy(req: DeletePolicyRequest): Promise<DeletePolicyResult> {\r\n const headers = this.headers();\r\n if (req.tenantId) {\r\n headers[\"X-Tenant-ID\"] = req.tenantId;\r\n }\r\n\r\n const ctrl = new AbortController();\r\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\r\n try {\r\n const res = await fetch(`${this.baseUrl}/api/v1/policies/${encodeURIComponent(req.name)}`, {\r\n method: \"DELETE\",\r\n headers,\r\n signal: ctrl.signal,\r\n });\r\n \r\n return await this.parseResponse<DeletePolicyResult>(res);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n }\r\n\r\n // ── HTTP helpers ───────────────────────────────────────────────────────────\r\n\r\n private headers(): Record<string, string> {\r\n const h: Record<string, string> = { \"Content-Type\": \"application/json\" };\r\n if (this.apiKey) {\r\n h[\"Authorization\"] = `Bearer ${this.apiKey}`;\r\n }\r\n return h;\r\n }\r\n\r\n private async post<T>(path: string, body: unknown): Promise<T> {\r\n const ctrl = new AbortController();\r\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\r\n try {\r\n const res = await fetch(`${this.baseUrl}${path}`, {\r\n method: \"POST\",\r\n headers: this.headers(),\r\n body: JSON.stringify(body),\r\n signal: ctrl.signal,\r\n });\r\n return this.parseResponse<T>(res);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n }\r\n\r\n private async delete<T>(path: string): Promise<T> {\r\n const ctrl = new AbortController();\r\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\r\n try {\r\n const res = await fetch(`${this.baseUrl}${path}`, {\r\n method: \"DELETE\",\r\n headers: this.headers(),\r\n signal: ctrl.signal,\r\n });\r\n return this.parseResponse<T>(res);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n }\r\n\r\n private async get<T>(path: string): Promise<T> {\r\n const ctrl = new AbortController();\r\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\r\n try {\r\n const res = await fetch(`${this.baseUrl}${path}`, {\r\n method: \"GET\",\r\n headers: this.headers(),\r\n signal: ctrl.signal,\r\n });\r\n return this.parseResponse<T>(res);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n }\r\n\r\n private async parseResponse<T>(res: Response): Promise<T> {\r\n const json = (await res.json()) as Record<string, unknown>;\r\n if (!res.ok) {\r\n throw new AuthEngineError(\r\n (json[\"error\"] as string) ?? \"engine error\",\r\n res.status,\r\n json\r\n );\r\n }\r\n return json as T;\r\n }\r\n}\r\n","// Auth Permission Engine — TypeScript SDK\r\n// Public API surface\r\n\r\n// ─── Vercel AI SDK integration ────────────────────────────────────────────────\r\n// Import via: import { secureTool } from 'lelu/vercel'\r\n// (tree-shakeable — does not add weight to non-Vercel users)\r\nexport { secureTool } from \"./vercel/index.js\";\r\nexport type { SecureToolOptions, LeluDeniedResult, VercelTool } from \"./vercel/index.js\";\r\n\r\nexport { LeluClient } from \"./client.js\";\r\n\r\nexport type {\r\n AuthRequest,\r\n AgentAuthRequest,\r\n AgentContext,\r\n MintTokenRequest,\r\n DelegateScopeRequest,\r\n AuthDecision,\r\n AgentAuthDecision,\r\n MintTokenResult,\r\n DelegateScopeResult,\r\n RevokeTokenResult,\r\n ClientConfig,\r\n AuditEvent,\r\n ListAuditEventsRequest,\r\n ListAuditEventsResult,\r\n} from \"./types.js\";\r\n\r\nexport {\r\n AuthEngineError,\r\n AuthRequestSchema,\r\n AgentAuthRequestSchema,\r\n AgentContextSchema,\r\n MintTokenRequestSchema,\r\n DelegateScopeRequestSchema,\r\n} from \"./types.js\";\r\n\r\n// ─── Convenience factory ──────────────────────────────────────────────────────\r\n\r\nimport { LeluClient } from \"./client.js\";\r\nimport type { ClientConfig } from \"./types.js\";\r\n\r\n/**\r\n * Creates a LeluClient with the given configuration.\r\n * Equivalent to `new LeluClient(config)`.\r\n *\r\n * @example\r\n * ```ts\r\n * import { createClient } from \"@lelu-auth/lelu\";\r\n *\r\n * const lelu = createClient({ baseUrl: \"http://localhost:8080\" });\r\n * const { allowed } = await lelu.agentAuthorize({ ... });\r\n * ```\r\n */\r\nexport function createClient(config?: ClientConfig): LeluClient {\r\n return new LeluClient(config);\r\n}\r\n"]}
@@ -1,4 +1,4 @@
1
- import { L as LeluClient } from '../client-DL75VVER.mjs';
1
+ import { L as LeluClient } from '../client-DauLJ9a4.mjs';
2
2
  import 'zod';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { L as LeluClient } from '../client-DL75VVER.js';
1
+ import { L as LeluClient } from '../client-DauLJ9a4.js';
2
2
  import 'zod';
3
3
 
4
4
  /**
@@ -173,6 +173,128 @@ var LeluClient = class {
173
173
  return false;
174
174
  }
175
175
  }
176
+ // ── Audit log ──────────────────────────────────────────────────────────────
177
+ /**
178
+ * Lists audit events from the platform API.
179
+ * Requires the platform service to be running (not just the engine).
180
+ */
181
+ async listAuditEvents(req = {}) {
182
+ const params = new URLSearchParams();
183
+ if (req.limit !== void 0) params.set("limit", req.limit.toString());
184
+ if (req.cursor !== void 0) params.set("cursor", req.cursor.toString());
185
+ if (req.actor) params.set("actor", req.actor);
186
+ if (req.action) params.set("action", req.action);
187
+ if (req.decision) params.set("decision", req.decision);
188
+ if (req.traceId) params.set("trace_id", req.traceId);
189
+ if (req.from) params.set("from", req.from);
190
+ if (req.to) params.set("to", req.to);
191
+ const headers = this.headers();
192
+ if (req.tenantId) {
193
+ headers["X-Tenant-ID"] = req.tenantId;
194
+ }
195
+ const ctrl = new AbortController();
196
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
197
+ try {
198
+ const url = `${this.baseUrl}/api/v1/audit${params.toString() ? `?${params.toString()}` : ""}`;
199
+ const res = await fetch(url, {
200
+ method: "GET",
201
+ headers,
202
+ signal: ctrl.signal
203
+ });
204
+ const data = await this.parseResponse(res);
205
+ return {
206
+ events: data.events || [],
207
+ count: data.count,
208
+ limit: data.limit,
209
+ cursor: data.cursor,
210
+ nextCursor: data.next_cursor
211
+ };
212
+ } finally {
213
+ clearTimeout(timer);
214
+ }
215
+ }
216
+ // ─── Policy Management ────────────────────────────────────────────────────────
217
+ async listPolicies(req = {}) {
218
+ const headers = this.headers();
219
+ if (req.tenantId) {
220
+ headers["X-Tenant-ID"] = req.tenantId;
221
+ }
222
+ const ctrl = new AbortController();
223
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
224
+ try {
225
+ const res = await fetch(`${this.baseUrl}/api/v1/policies`, {
226
+ method: "GET",
227
+ headers,
228
+ signal: ctrl.signal
229
+ });
230
+ const data = await this.parseResponse(res);
231
+ return {
232
+ policies: data.policies || [],
233
+ count: data.count
234
+ };
235
+ } finally {
236
+ clearTimeout(timer);
237
+ }
238
+ }
239
+ async getPolicy(req) {
240
+ const headers = this.headers();
241
+ if (req.tenantId) {
242
+ headers["X-Tenant-ID"] = req.tenantId;
243
+ }
244
+ const ctrl = new AbortController();
245
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
246
+ try {
247
+ const res = await fetch(`${this.baseUrl}/api/v1/policies/${encodeURIComponent(req.name)}`, {
248
+ method: "GET",
249
+ headers,
250
+ signal: ctrl.signal
251
+ });
252
+ return await this.parseResponse(res);
253
+ } finally {
254
+ clearTimeout(timer);
255
+ }
256
+ }
257
+ async upsertPolicy(req) {
258
+ const headers = this.headers();
259
+ if (req.tenantId) {
260
+ headers["X-Tenant-ID"] = req.tenantId;
261
+ }
262
+ const body = {
263
+ content: req.content,
264
+ version: req.version || "1.0"
265
+ };
266
+ const ctrl = new AbortController();
267
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
268
+ try {
269
+ const res = await fetch(`${this.baseUrl}/api/v1/policies/${encodeURIComponent(req.name)}`, {
270
+ method: "PUT",
271
+ headers,
272
+ body: JSON.stringify(body),
273
+ signal: ctrl.signal
274
+ });
275
+ return await this.parseResponse(res);
276
+ } finally {
277
+ clearTimeout(timer);
278
+ }
279
+ }
280
+ async deletePolicy(req) {
281
+ const headers = this.headers();
282
+ if (req.tenantId) {
283
+ headers["X-Tenant-ID"] = req.tenantId;
284
+ }
285
+ const ctrl = new AbortController();
286
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
287
+ try {
288
+ const res = await fetch(`${this.baseUrl}/api/v1/policies/${encodeURIComponent(req.name)}`, {
289
+ method: "DELETE",
290
+ headers,
291
+ signal: ctrl.signal
292
+ });
293
+ return await this.parseResponse(res);
294
+ } finally {
295
+ clearTimeout(timer);
296
+ }
297
+ }
176
298
  // ── HTTP helpers ───────────────────────────────────────────────────────────
177
299
  headers() {
178
300
  const h = { "Content-Type": "application/json" };