kavachos 0.0.1

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.js ADDED
@@ -0,0 +1,862 @@
1
+ import { createAgentModule } from './chunk-DTCKF26N.js';
2
+ export { createAgentModule } from './chunk-DTCKF26N.js';
3
+ import { createPermissionEngine } from './chunk-D2LJLY7F.js';
4
+ export { createPermissionEngine, getPermissionTemplate, permissionTemplates } from './chunk-D2LJLY7F.js';
5
+ import { createAuditModule } from './chunk-XW2X3O53.js';
6
+ export { createAuditModule } from './chunk-XW2X3O53.js';
7
+ import { schema_exports, delegationChains } from './chunk-XSYYQH75.js';
8
+ export { agents, auditLogs, delegationChains, mcpServers, oauthAccessTokens, oauthAuthorizationCodes, oauthClients, permissions, rateLimits, users } from './chunk-XSYYQH75.js';
9
+ import './chunk-PZ5AY32C.js';
10
+ import BetterSqlite3 from 'better-sqlite3';
11
+ import { drizzle } from 'drizzle-orm/better-sqlite3';
12
+ import { randomUUID } from 'crypto';
13
+ import { and, eq } from 'drizzle-orm';
14
+
15
+ async function createDatabase(config) {
16
+ if (config.provider === "sqlite") {
17
+ const sqlite = new BetterSqlite3(config.url);
18
+ sqlite.pragma("journal_mode = WAL");
19
+ sqlite.pragma("foreign_keys = ON");
20
+ return drizzle(sqlite, { schema: schema_exports });
21
+ }
22
+ if (config.provider === "postgres") {
23
+ const { Pool } = await import('pg').catch(() => {
24
+ throw new Error(
25
+ 'KavachOS: provider "postgres" requires the "pg" package. Install it with: npm install pg'
26
+ );
27
+ });
28
+ const { drizzle } = await import('drizzle-orm/node-postgres');
29
+ const pool = new Pool({ connectionString: config.url });
30
+ return drizzle(pool);
31
+ }
32
+ if (config.provider === "mysql") {
33
+ const mysql2 = await import('mysql2/promise').catch(() => {
34
+ throw new Error(
35
+ 'KavachOS: provider "mysql" requires the "mysql2" package. Install it with: npm install mysql2'
36
+ );
37
+ });
38
+ const { drizzle } = await import('drizzle-orm/mysql2');
39
+ const pool = mysql2.createPool(config.url);
40
+ return drizzle(pool);
41
+ }
42
+ throw new Error(
43
+ `KavachOS: unsupported database provider "${config.provider}". Valid values are "sqlite", "postgres", "mysql".`
44
+ );
45
+ }
46
+ function createDatabaseSync(config) {
47
+ if (config.provider !== "sqlite") {
48
+ throw new Error(
49
+ `createDatabaseSync() only supports SQLite. Use the async createDatabase() for provider "${config.provider}".`
50
+ );
51
+ }
52
+ const sqlite = new BetterSqlite3(config.url);
53
+ sqlite.pragma("journal_mode = WAL");
54
+ sqlite.pragma("foreign_keys = ON");
55
+ return drizzle(sqlite, { schema: schema_exports });
56
+ }
57
+
58
+ // src/db/migrations.ts
59
+ function buildStatements(provider) {
60
+ const isPostgres = provider === "postgres";
61
+ const isMysql = provider === "mysql";
62
+ const ts = isPostgres ? "TIMESTAMPTZ" : isMysql ? "DATETIME(3)" : "INTEGER";
63
+ const tsNull = ts;
64
+ const json = isPostgres ? "JSONB" : isMysql ? "JSON" : "TEXT";
65
+ const bool = isPostgres ? "BOOLEAN" : isMysql ? "TINYINT(1)" : "INTEGER";
66
+ const ifne = "IF NOT EXISTS";
67
+ return [
68
+ // ------------------------------------------------------------------
69
+ // kavach_users
70
+ // ------------------------------------------------------------------
71
+ `CREATE TABLE ${ifne} kavach_users (
72
+ id TEXT NOT NULL PRIMARY KEY,
73
+ email TEXT NOT NULL UNIQUE,
74
+ name TEXT,
75
+ external_id TEXT,
76
+ external_provider TEXT,
77
+ metadata ${json},
78
+ created_at ${ts} NOT NULL,
79
+ updated_at ${ts} NOT NULL
80
+ )`,
81
+ // ------------------------------------------------------------------
82
+ // kavach_agents
83
+ // ------------------------------------------------------------------
84
+ `CREATE TABLE ${ifne} kavach_agents (
85
+ id TEXT NOT NULL PRIMARY KEY,
86
+ owner_id TEXT NOT NULL REFERENCES kavach_users(id),
87
+ name TEXT NOT NULL,
88
+ type TEXT NOT NULL,
89
+ status TEXT NOT NULL DEFAULT 'active',
90
+ token_hash TEXT NOT NULL,
91
+ token_prefix TEXT NOT NULL,
92
+ expires_at ${tsNull},
93
+ last_active_at ${tsNull},
94
+ metadata ${json},
95
+ created_at ${ts} NOT NULL,
96
+ updated_at ${ts} NOT NULL
97
+ )`,
98
+ // ------------------------------------------------------------------
99
+ // kavach_permissions
100
+ // ------------------------------------------------------------------
101
+ `CREATE TABLE ${ifne} kavach_permissions (
102
+ id TEXT NOT NULL PRIMARY KEY,
103
+ agent_id TEXT NOT NULL REFERENCES kavach_agents(id) ON DELETE CASCADE,
104
+ resource TEXT NOT NULL,
105
+ actions ${json} NOT NULL,
106
+ constraints ${json},
107
+ created_at ${ts} NOT NULL
108
+ )`,
109
+ // ------------------------------------------------------------------
110
+ // kavach_delegation_chains
111
+ // ------------------------------------------------------------------
112
+ `CREATE TABLE ${ifne} kavach_delegation_chains (
113
+ id TEXT NOT NULL PRIMARY KEY,
114
+ from_agent_id TEXT NOT NULL REFERENCES kavach_agents(id),
115
+ to_agent_id TEXT NOT NULL REFERENCES kavach_agents(id),
116
+ permissions ${json} NOT NULL,
117
+ depth INTEGER NOT NULL DEFAULT 1,
118
+ max_depth INTEGER NOT NULL DEFAULT 3,
119
+ status TEXT NOT NULL DEFAULT 'active',
120
+ expires_at ${ts} NOT NULL,
121
+ created_at ${ts} NOT NULL
122
+ )`,
123
+ // ------------------------------------------------------------------
124
+ // kavach_audit_logs
125
+ // ------------------------------------------------------------------
126
+ `CREATE TABLE ${ifne} kavach_audit_logs (
127
+ id TEXT NOT NULL PRIMARY KEY,
128
+ agent_id TEXT NOT NULL REFERENCES kavach_agents(id),
129
+ user_id TEXT NOT NULL REFERENCES kavach_users(id),
130
+ action TEXT NOT NULL,
131
+ resource TEXT NOT NULL,
132
+ parameters ${json},
133
+ result TEXT NOT NULL,
134
+ reason TEXT,
135
+ duration_ms INTEGER NOT NULL,
136
+ tokens_cost INTEGER,
137
+ ip TEXT,
138
+ user_agent TEXT,
139
+ timestamp ${ts} NOT NULL
140
+ )`,
141
+ // ------------------------------------------------------------------
142
+ // kavach_rate_limits
143
+ // ------------------------------------------------------------------
144
+ `CREATE TABLE ${ifne} kavach_rate_limits (
145
+ id TEXT NOT NULL PRIMARY KEY,
146
+ agent_id TEXT NOT NULL REFERENCES kavach_agents(id) ON DELETE CASCADE,
147
+ resource TEXT NOT NULL,
148
+ window_start ${ts} NOT NULL,
149
+ count INTEGER NOT NULL DEFAULT 0
150
+ )`,
151
+ // ------------------------------------------------------------------
152
+ // kavach_mcp_servers
153
+ // ------------------------------------------------------------------
154
+ `CREATE TABLE ${ifne} kavach_mcp_servers (
155
+ id TEXT NOT NULL PRIMARY KEY,
156
+ name TEXT NOT NULL,
157
+ endpoint TEXT NOT NULL UNIQUE,
158
+ tools ${json} NOT NULL,
159
+ auth_required ${bool} NOT NULL DEFAULT ${isPostgres ? "TRUE" : "1"},
160
+ rate_limit_rpm INTEGER,
161
+ status TEXT NOT NULL DEFAULT 'active',
162
+ created_at ${ts} NOT NULL,
163
+ updated_at ${ts} NOT NULL
164
+ )`,
165
+ // ------------------------------------------------------------------
166
+ // kavach_oauth_clients
167
+ // ------------------------------------------------------------------
168
+ `CREATE TABLE ${ifne} kavach_oauth_clients (
169
+ id TEXT NOT NULL PRIMARY KEY,
170
+ client_id TEXT NOT NULL UNIQUE,
171
+ client_secret TEXT,
172
+ client_name TEXT,
173
+ client_uri TEXT,
174
+ redirect_uris ${json} NOT NULL,
175
+ grant_types ${json} NOT NULL,
176
+ response_types ${json} NOT NULL,
177
+ token_endpoint_auth_method TEXT NOT NULL DEFAULT 'client_secret_basic',
178
+ type TEXT NOT NULL DEFAULT 'confidential',
179
+ disabled ${bool} NOT NULL DEFAULT ${isPostgres ? "FALSE" : "0"},
180
+ metadata ${json},
181
+ created_at ${ts} NOT NULL,
182
+ updated_at ${ts} NOT NULL
183
+ )`,
184
+ // ------------------------------------------------------------------
185
+ // kavach_oauth_access_tokens
186
+ // ------------------------------------------------------------------
187
+ `CREATE TABLE ${ifne} kavach_oauth_access_tokens (
188
+ id TEXT NOT NULL PRIMARY KEY,
189
+ access_token TEXT NOT NULL UNIQUE,
190
+ refresh_token TEXT UNIQUE,
191
+ client_id TEXT NOT NULL REFERENCES kavach_oauth_clients(client_id),
192
+ user_id TEXT NOT NULL REFERENCES kavach_users(id),
193
+ scopes TEXT NOT NULL,
194
+ resource TEXT,
195
+ access_token_expires_at ${ts} NOT NULL,
196
+ refresh_token_expires_at ${tsNull},
197
+ created_at ${ts} NOT NULL
198
+ )`,
199
+ // ------------------------------------------------------------------
200
+ // kavach_oauth_authorization_codes
201
+ // ------------------------------------------------------------------
202
+ `CREATE TABLE ${ifne} kavach_oauth_authorization_codes (
203
+ id TEXT NOT NULL PRIMARY KEY,
204
+ code TEXT NOT NULL UNIQUE,
205
+ client_id TEXT NOT NULL REFERENCES kavach_oauth_clients(client_id),
206
+ user_id TEXT NOT NULL REFERENCES kavach_users(id),
207
+ redirect_uri TEXT NOT NULL,
208
+ scopes TEXT NOT NULL,
209
+ code_challenge TEXT,
210
+ code_challenge_method TEXT,
211
+ resource TEXT,
212
+ expires_at ${ts} NOT NULL,
213
+ created_at ${ts} NOT NULL
214
+ )`
215
+ ];
216
+ }
217
+ async function createTables(db, provider) {
218
+ const statements = buildStatements(provider);
219
+ if (provider === "sqlite") {
220
+ const session = db.session;
221
+ if (session?.client?.exec) {
222
+ session.client.exec(statements.join(";\n") + ";");
223
+ return;
224
+ }
225
+ const anyDb2 = db;
226
+ for (const sql of statements) {
227
+ await anyDb2.run(sql);
228
+ }
229
+ return;
230
+ }
231
+ const anyDb = db;
232
+ if (provider === "postgres") {
233
+ const client = anyDb.$client ?? anyDb.session?.client;
234
+ if (!client) {
235
+ throw new Error(
236
+ "KavachOS createTables: cannot access underlying pg client from Drizzle instance."
237
+ );
238
+ }
239
+ for (const sql of statements) {
240
+ await client.query(sql);
241
+ }
242
+ return;
243
+ }
244
+ if (provider === "mysql") {
245
+ const client = anyDb.$client ?? anyDb.session?.client;
246
+ if (!client) {
247
+ throw new Error(
248
+ "KavachOS createTables: cannot access underlying mysql2 client from Drizzle instance."
249
+ );
250
+ }
251
+ for (const sql of statements) {
252
+ await client.execute(sql);
253
+ }
254
+ return;
255
+ }
256
+ throw new Error(`createTables: unsupported provider "${provider}"`);
257
+ }
258
+ function isPermissionSubset(parentPerms, childPerms) {
259
+ for (const childPerm of childPerms) {
260
+ const parentMatch = parentPerms.find((p) => {
261
+ if (!isResourceSubset(p.resource, childPerm.resource)) return false;
262
+ for (const action of childPerm.actions) {
263
+ if (!p.actions.includes(action) && !p.actions.includes("*")) return false;
264
+ }
265
+ return true;
266
+ });
267
+ if (!parentMatch) return false;
268
+ }
269
+ return true;
270
+ }
271
+ function isResourceSubset(parentResource, childResource) {
272
+ if (parentResource === "*") return true;
273
+ if (parentResource === childResource) return true;
274
+ const parentParts = parentResource.split(":");
275
+ const childParts = childResource.split(":");
276
+ for (let i = 0; i < parentParts.length; i++) {
277
+ if (parentParts[i] === "*") return true;
278
+ if (parentParts[i] !== childParts[i]) return false;
279
+ }
280
+ return parentParts.length <= childParts.length;
281
+ }
282
+ function createDelegationModule(config) {
283
+ const { db } = config;
284
+ async function delegate(input, parentPermissions) {
285
+ if (!isPermissionSubset(parentPermissions, input.permissions)) {
286
+ throw new Error(
287
+ "Delegated permissions must be a subset of the parent agent's permissions. A child agent cannot have more access than its parent."
288
+ );
289
+ }
290
+ const existingChains = await db.select().from(delegationChains).where(
291
+ and(eq(delegationChains.toAgentId, input.fromAgent), eq(delegationChains.status, "active"))
292
+ );
293
+ const currentDepth = existingChains.length > 0 ? Math.max(...existingChains.map((c) => c.depth)) + 1 : 1;
294
+ const maxDepth = input.maxDepth ?? 3;
295
+ if (currentDepth > maxDepth) {
296
+ throw new Error(
297
+ `Delegation depth ${currentDepth} exceeds maximum allowed depth of ${maxDepth}. This prevents infinite delegation chains.`
298
+ );
299
+ }
300
+ const id = randomUUID();
301
+ const now = /* @__PURE__ */ new Date();
302
+ await db.insert(delegationChains).values({
303
+ id,
304
+ fromAgentId: input.fromAgent,
305
+ toAgentId: input.toAgent,
306
+ permissions: input.permissions.map((p) => ({
307
+ resource: p.resource,
308
+ actions: p.actions
309
+ })),
310
+ depth: currentDepth,
311
+ maxDepth,
312
+ status: "active",
313
+ expiresAt: input.expiresAt,
314
+ createdAt: now
315
+ });
316
+ return {
317
+ id,
318
+ fromAgent: input.fromAgent,
319
+ toAgent: input.toAgent,
320
+ permissions: input.permissions,
321
+ expiresAt: input.expiresAt,
322
+ depth: currentDepth,
323
+ createdAt: now
324
+ };
325
+ }
326
+ async function revokeDelegation(chainId) {
327
+ const chain = await db.select().from(delegationChains).where(eq(delegationChains.id, chainId)).limit(1);
328
+ if (!chain[0]) throw new Error(`Delegation chain ${chainId} not found.`);
329
+ await db.update(delegationChains).set({ status: "revoked" }).where(eq(delegationChains.id, chainId));
330
+ const childChains = await db.select().from(delegationChains).where(
331
+ and(
332
+ eq(delegationChains.fromAgentId, chain[0].toAgentId),
333
+ eq(delegationChains.status, "active")
334
+ )
335
+ );
336
+ for (const child of childChains) {
337
+ await revokeDelegation(child.id);
338
+ }
339
+ }
340
+ async function getEffectivePermissions(agentId) {
341
+ const chains = await db.select().from(delegationChains).where(and(eq(delegationChains.toAgentId, agentId), eq(delegationChains.status, "active")));
342
+ const now = /* @__PURE__ */ new Date();
343
+ const activeChains = chains.filter((c) => c.expiresAt > now);
344
+ const delegatedPerms = [];
345
+ for (const chain of activeChains) {
346
+ for (const perm of chain.permissions) {
347
+ delegatedPerms.push({
348
+ resource: perm.resource,
349
+ actions: perm.actions
350
+ });
351
+ }
352
+ }
353
+ return delegatedPerms;
354
+ }
355
+ async function listChains(agentId) {
356
+ const chains = await db.select().from(delegationChains).where(eq(delegationChains.fromAgentId, agentId));
357
+ return chains.map((c) => ({
358
+ id: c.id,
359
+ fromAgent: c.fromAgentId,
360
+ toAgent: c.toAgentId,
361
+ permissions: c.permissions.map((p) => ({
362
+ resource: p.resource,
363
+ actions: p.actions
364
+ })),
365
+ expiresAt: c.expiresAt,
366
+ depth: c.depth,
367
+ createdAt: c.createdAt
368
+ }));
369
+ }
370
+ return { delegate, revokeDelegation, getEffectivePermissions, listChains };
371
+ }
372
+
373
+ // src/kavach.ts
374
+ async function createKavach(config) {
375
+ const db = await createDatabase(config.database);
376
+ if (!config.database.skipMigrations) {
377
+ await createTables(db, config.database.provider);
378
+ }
379
+ const agentConfig = {
380
+ db,
381
+ maxPerUser: config.agents?.maxPerUser ?? 10,
382
+ defaultPermissions: config.agents?.defaultPermissions ?? [],
383
+ tokenExpiry: config.agents?.tokenExpiry ?? "24h"
384
+ };
385
+ const agentModule = createAgentModule(agentConfig);
386
+ const permissionEngine = createPermissionEngine({
387
+ db,
388
+ auditAll: config.agents?.auditAll ?? true
389
+ });
390
+ const auditModule = createAuditModule({ db });
391
+ const delegationModule = createDelegationModule({ db });
392
+ async function authorize(agentId, request) {
393
+ const agent = await agentModule.get(agentId);
394
+ if (!agent) {
395
+ return {
396
+ allowed: false,
397
+ reason: `Agent "${agentId}" not found`,
398
+ auditId: ""
399
+ };
400
+ }
401
+ if (agent.status !== "active") {
402
+ return {
403
+ allowed: false,
404
+ reason: `Agent "${agent.name}" is ${agent.status}`,
405
+ auditId: ""
406
+ };
407
+ }
408
+ return permissionEngine.authorize(agent, request);
409
+ }
410
+ async function authorizeByToken(token, request) {
411
+ const agent = await agentModule.validateToken(token);
412
+ if (!agent) {
413
+ return {
414
+ allowed: false,
415
+ reason: "Invalid or expired agent token",
416
+ auditId: ""
417
+ };
418
+ }
419
+ return permissionEngine.authorize(agent, request);
420
+ }
421
+ async function delegate(input) {
422
+ const parentAgent = await agentModule.get(input.fromAgent);
423
+ if (!parentAgent) throw new Error(`Parent agent "${input.fromAgent}" not found`);
424
+ if (parentAgent.status !== "active") {
425
+ throw new Error(`Parent agent "${parentAgent.name}" is ${parentAgent.status}`);
426
+ }
427
+ return delegationModule.delegate(input, parentAgent.permissions);
428
+ }
429
+ return {
430
+ agent: {
431
+ create: agentModule.create,
432
+ get: agentModule.get,
433
+ list: agentModule.list,
434
+ update: agentModule.update,
435
+ revoke: agentModule.revoke,
436
+ rotate: agentModule.rotate,
437
+ validateToken: agentModule.validateToken
438
+ },
439
+ authorize,
440
+ authorizeByToken,
441
+ delegate,
442
+ delegation: {
443
+ revoke: delegationModule.revokeDelegation,
444
+ getEffectivePermissions: delegationModule.getEffectivePermissions,
445
+ listChains: delegationModule.listChains
446
+ },
447
+ audit: {
448
+ query: (filter) => auditModule.query(filter),
449
+ export: (options) => auditModule.export(options)
450
+ },
451
+ /** Direct database access for advanced usage */
452
+ db
453
+ };
454
+ }
455
+
456
+ // src/openapi.ts
457
+ function generateOpenAPISpec(options) {
458
+ const baseUrl = options?.baseUrl ?? "http://localhost:3000";
459
+ const version = options?.version ?? "0.0.1";
460
+ return {
461
+ openapi: "3.1.0",
462
+ info: {
463
+ title: "KavachOS API",
464
+ version,
465
+ description: "The Auth OS for AI Agents. Identity, permissions, delegation, and audit for the agentic era."
466
+ },
467
+ servers: [{ url: baseUrl, description: "KavachOS API Server" }],
468
+ paths: {
469
+ "/agents": {
470
+ post: {
471
+ summary: "Create a new agent",
472
+ operationId: "createAgent",
473
+ tags: ["Agents"],
474
+ security: [{ BearerAuth: [] }],
475
+ requestBody: {
476
+ required: true,
477
+ content: {
478
+ "application/json": { schema: { $ref: "#/components/schemas/CreateAgentInput" } }
479
+ }
480
+ },
481
+ responses: {
482
+ "201": {
483
+ description: "Agent created",
484
+ content: {
485
+ "application/json": {
486
+ schema: { $ref: "#/components/schemas/AgentWithToken" }
487
+ }
488
+ }
489
+ },
490
+ "400": { description: "Invalid input" },
491
+ "429": { description: "Max agents per user exceeded" }
492
+ }
493
+ },
494
+ get: {
495
+ summary: "List agents",
496
+ operationId: "listAgents",
497
+ tags: ["Agents"],
498
+ security: [{ BearerAuth: [] }],
499
+ parameters: [
500
+ { name: "userId", in: "query", required: false, schema: { type: "string" } },
501
+ {
502
+ name: "status",
503
+ in: "query",
504
+ required: false,
505
+ schema: { type: "string", enum: ["active", "revoked", "expired"] }
506
+ },
507
+ {
508
+ name: "type",
509
+ in: "query",
510
+ required: false,
511
+ schema: { type: "string", enum: ["autonomous", "delegated", "service"] }
512
+ }
513
+ ],
514
+ responses: {
515
+ "200": {
516
+ description: "List of agents",
517
+ content: {
518
+ "application/json": {
519
+ schema: { type: "array", items: { $ref: "#/components/schemas/Agent" } }
520
+ }
521
+ }
522
+ }
523
+ }
524
+ }
525
+ },
526
+ "/agents/{id}": {
527
+ get: {
528
+ summary: "Get agent by ID",
529
+ operationId: "getAgent",
530
+ tags: ["Agents"],
531
+ security: [{ BearerAuth: [] }],
532
+ parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
533
+ responses: {
534
+ "200": {
535
+ description: "Agent details",
536
+ content: { "application/json": { schema: { $ref: "#/components/schemas/Agent" } } }
537
+ },
538
+ "404": { description: "Agent not found" }
539
+ }
540
+ },
541
+ patch: {
542
+ summary: "Update agent",
543
+ operationId: "updateAgent",
544
+ tags: ["Agents"],
545
+ security: [{ BearerAuth: [] }],
546
+ parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
547
+ requestBody: {
548
+ required: true,
549
+ content: {
550
+ "application/json": { schema: { $ref: "#/components/schemas/UpdateAgentInput" } }
551
+ }
552
+ },
553
+ responses: {
554
+ "200": {
555
+ description: "Agent updated",
556
+ content: { "application/json": { schema: { $ref: "#/components/schemas/Agent" } } }
557
+ }
558
+ }
559
+ },
560
+ delete: {
561
+ summary: "Revoke agent",
562
+ operationId: "revokeAgent",
563
+ tags: ["Agents"],
564
+ security: [{ BearerAuth: [] }],
565
+ parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
566
+ responses: { "204": { description: "Agent revoked" } }
567
+ }
568
+ },
569
+ "/agents/{id}/rotate": {
570
+ post: {
571
+ summary: "Rotate agent token",
572
+ operationId: "rotateAgentToken",
573
+ tags: ["Agents"],
574
+ security: [{ BearerAuth: [] }],
575
+ parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
576
+ responses: {
577
+ "200": {
578
+ description: "New token issued",
579
+ content: {
580
+ "application/json": { schema: { $ref: "#/components/schemas/AgentWithToken" } }
581
+ }
582
+ }
583
+ }
584
+ }
585
+ },
586
+ "/authorize": {
587
+ post: {
588
+ summary: "Authorize an agent action",
589
+ operationId: "authorize",
590
+ tags: ["Authorization"],
591
+ requestBody: {
592
+ required: true,
593
+ content: {
594
+ "application/json": { schema: { $ref: "#/components/schemas/AuthorizeRequest" } }
595
+ }
596
+ },
597
+ responses: {
598
+ "200": {
599
+ description: "Authorization result",
600
+ content: {
601
+ "application/json": { schema: { $ref: "#/components/schemas/AuthorizeResult" } }
602
+ }
603
+ }
604
+ }
605
+ }
606
+ },
607
+ "/authorize/token": {
608
+ post: {
609
+ summary: "Authorize by agent token",
610
+ operationId: "authorizeByToken",
611
+ tags: ["Authorization"],
612
+ security: [{ AgentToken: [] }],
613
+ requestBody: {
614
+ required: true,
615
+ content: {
616
+ "application/json": {
617
+ schema: {
618
+ type: "object",
619
+ properties: {
620
+ action: { type: "string" },
621
+ resource: { type: "string" },
622
+ arguments: { type: "object" }
623
+ },
624
+ required: ["action", "resource"]
625
+ }
626
+ }
627
+ }
628
+ },
629
+ responses: {
630
+ "200": {
631
+ description: "Authorization result",
632
+ content: {
633
+ "application/json": { schema: { $ref: "#/components/schemas/AuthorizeResult" } }
634
+ }
635
+ }
636
+ }
637
+ }
638
+ },
639
+ "/audit": {
640
+ get: {
641
+ summary: "Query audit logs",
642
+ operationId: "queryAudit",
643
+ tags: ["Audit"],
644
+ security: [{ BearerAuth: [] }],
645
+ parameters: [
646
+ { name: "agentId", in: "query", required: false, schema: { type: "string" } },
647
+ { name: "userId", in: "query", required: false, schema: { type: "string" } },
648
+ {
649
+ name: "since",
650
+ in: "query",
651
+ required: false,
652
+ schema: { type: "string", format: "date-time" }
653
+ },
654
+ {
655
+ name: "until",
656
+ in: "query",
657
+ required: false,
658
+ schema: { type: "string", format: "date-time" }
659
+ },
660
+ {
661
+ name: "result",
662
+ in: "query",
663
+ required: false,
664
+ schema: { type: "string", enum: ["allowed", "denied", "rate_limited"] }
665
+ },
666
+ { name: "limit", in: "query", required: false, schema: { type: "integer" } },
667
+ { name: "offset", in: "query", required: false, schema: { type: "integer" } }
668
+ ],
669
+ responses: {
670
+ "200": {
671
+ description: "Audit log entries",
672
+ content: {
673
+ "application/json": {
674
+ schema: { type: "array", items: { $ref: "#/components/schemas/AuditEntry" } }
675
+ }
676
+ }
677
+ }
678
+ }
679
+ }
680
+ },
681
+ "/delegations": {
682
+ post: {
683
+ summary: "Create delegation chain",
684
+ operationId: "createDelegation",
685
+ tags: ["Delegation"],
686
+ security: [{ BearerAuth: [] }],
687
+ requestBody: {
688
+ required: true,
689
+ content: {
690
+ "application/json": { schema: { $ref: "#/components/schemas/DelegateInput" } }
691
+ }
692
+ },
693
+ responses: {
694
+ "201": {
695
+ description: "Delegation created",
696
+ content: {
697
+ "application/json": { schema: { $ref: "#/components/schemas/DelegationChain" } }
698
+ }
699
+ }
700
+ }
701
+ }
702
+ }
703
+ },
704
+ components: {
705
+ schemas: {
706
+ CreateAgentInput: {
707
+ type: "object",
708
+ required: ["ownerId", "name", "type", "permissions"],
709
+ properties: {
710
+ ownerId: { type: "string" },
711
+ name: { type: "string" },
712
+ type: { type: "string", enum: ["autonomous", "delegated", "service"] },
713
+ permissions: { type: "array", items: { $ref: "#/components/schemas/Permission" } },
714
+ expiresAt: { type: "string", format: "date-time", nullable: true },
715
+ metadata: { type: "object" }
716
+ }
717
+ },
718
+ UpdateAgentInput: {
719
+ type: "object",
720
+ properties: {
721
+ name: { type: "string" },
722
+ permissions: { type: "array", items: { $ref: "#/components/schemas/Permission" } },
723
+ expiresAt: { type: "string", format: "date-time", nullable: true },
724
+ metadata: { type: "object" }
725
+ }
726
+ },
727
+ Agent: {
728
+ type: "object",
729
+ properties: {
730
+ id: { type: "string" },
731
+ ownerId: { type: "string" },
732
+ name: { type: "string" },
733
+ type: { type: "string", enum: ["autonomous", "delegated", "service"] },
734
+ status: { type: "string", enum: ["active", "revoked", "expired"] },
735
+ permissions: { type: "array", items: { $ref: "#/components/schemas/Permission" } },
736
+ expiresAt: { type: "string", format: "date-time", nullable: true },
737
+ createdAt: { type: "string", format: "date-time" },
738
+ updatedAt: { type: "string", format: "date-time" }
739
+ }
740
+ },
741
+ AgentWithToken: {
742
+ type: "object",
743
+ description: "Agent identity with the token (only returned on create/rotate)",
744
+ properties: {
745
+ id: { type: "string" },
746
+ token: {
747
+ type: "string",
748
+ description: "Agent token (kv_ prefix). Store securely - not retrievable after creation."
749
+ },
750
+ name: { type: "string" },
751
+ type: { type: "string" },
752
+ status: { type: "string" },
753
+ permissions: { type: "array", items: { $ref: "#/components/schemas/Permission" } }
754
+ }
755
+ },
756
+ Permission: {
757
+ type: "object",
758
+ required: ["resource", "actions"],
759
+ properties: {
760
+ resource: {
761
+ type: "string",
762
+ description: "Resource pattern (e.g. mcp:github:*, tool:file_read)"
763
+ },
764
+ actions: {
765
+ type: "array",
766
+ items: { type: "string" },
767
+ description: "Allowed actions (read, write, execute, delete, *)"
768
+ },
769
+ constraints: { $ref: "#/components/schemas/PermissionConstraints" }
770
+ }
771
+ },
772
+ PermissionConstraints: {
773
+ type: "object",
774
+ properties: {
775
+ maxCallsPerHour: { type: "integer" },
776
+ allowedArgPatterns: { type: "array", items: { type: "string" } },
777
+ requireApproval: { type: "boolean" },
778
+ timeWindow: {
779
+ type: "object",
780
+ properties: {
781
+ start: { type: "string", description: "HH:MM format" },
782
+ end: { type: "string", description: "HH:MM format" }
783
+ }
784
+ },
785
+ ipAllowlist: { type: "array", items: { type: "string" } }
786
+ }
787
+ },
788
+ AuthorizeRequest: {
789
+ type: "object",
790
+ required: ["agentId", "action", "resource"],
791
+ properties: {
792
+ agentId: { type: "string" },
793
+ action: { type: "string" },
794
+ resource: { type: "string" },
795
+ arguments: { type: "object" }
796
+ }
797
+ },
798
+ AuthorizeResult: {
799
+ type: "object",
800
+ properties: {
801
+ allowed: { type: "boolean" },
802
+ reason: { type: "string", nullable: true },
803
+ auditId: { type: "string" }
804
+ }
805
+ },
806
+ AuditEntry: {
807
+ type: "object",
808
+ properties: {
809
+ id: { type: "string" },
810
+ agentId: { type: "string" },
811
+ userId: { type: "string" },
812
+ action: { type: "string" },
813
+ resource: { type: "string" },
814
+ parameters: { type: "object" },
815
+ result: { type: "string", enum: ["allowed", "denied", "rate_limited"] },
816
+ durationMs: { type: "integer" },
817
+ timestamp: { type: "string", format: "date-time" }
818
+ }
819
+ },
820
+ DelegateInput: {
821
+ type: "object",
822
+ required: ["fromAgent", "toAgent", "permissions", "expiresAt"],
823
+ properties: {
824
+ fromAgent: { type: "string" },
825
+ toAgent: { type: "string" },
826
+ permissions: { type: "array", items: { $ref: "#/components/schemas/Permission" } },
827
+ expiresAt: { type: "string", format: "date-time" },
828
+ maxDepth: { type: "integer" }
829
+ }
830
+ },
831
+ DelegationChain: {
832
+ type: "object",
833
+ properties: {
834
+ id: { type: "string" },
835
+ fromAgent: { type: "string" },
836
+ toAgent: { type: "string" },
837
+ permissions: { type: "array", items: { $ref: "#/components/schemas/Permission" } },
838
+ depth: { type: "integer" },
839
+ expiresAt: { type: "string", format: "date-time" },
840
+ createdAt: { type: "string", format: "date-time" }
841
+ }
842
+ }
843
+ },
844
+ securitySchemes: {
845
+ BearerAuth: {
846
+ type: "http",
847
+ scheme: "bearer",
848
+ bearerFormat: "JWT"
849
+ },
850
+ AgentToken: {
851
+ type: "http",
852
+ scheme: "bearer",
853
+ bearerFormat: "KavachOS Agent Token (kv_...)"
854
+ }
855
+ }
856
+ }
857
+ };
858
+ }
859
+
860
+ export { createDatabase, createDatabaseSync, createDelegationModule, createKavach, createTables, generateOpenAPISpec };
861
+ //# sourceMappingURL=index.js.map
862
+ //# sourceMappingURL=index.js.map