kavachos 0.0.2 → 0.0.3

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.d.ts CHANGED
@@ -1,15 +1,59 @@
1
1
  export { createAgentModule } from './agent/index.js';
2
- import { D as Database, a as DatabaseConfig, b as DelegateInput, P as Permission, c as DelegationChain, K as KavachConfig, C as CreateAgentInput, A as AgentIdentity, d as AgentFilter, U as UpdateAgentInput, e as AuthorizeRequest, R as RequestContext, f as AuthorizeResult, g as AuditFilter, h as AuditEntry, i as AuditExportOptions, M as McpServerInput, j as McpServer, S as SessionManager } from './types-WP-mKSdQ.js';
3
- export { k as AgentConfig, l as DatabaseConfig, m as KavachInstance, n as McpMiddleware, o as PermissionConstraints, p as Session, q as SessionConfig, T as TokenValidationResult, r as agents, s as auditLogs, t as createDatabase, u as createDatabaseSync, v as createSessionManager, w as delegationChains, x as mcpServers, y as oauthAccessTokens, z as oauthAuthorizationCodes, B as oauthClients, E as permissions, F as rateLimits, G as sessions, H as users } from './types-WP-mKSdQ.js';
2
+ import { D as Database, a as DatabaseConfig, b as DelegateInput, P as Permission, c as DelegationChain, d as DidDocument, e as DidKeyPair, f as DidWebConfig, A as AgentDid, S as SignedPayload, V as VerificationResult, K as KavachConfig, C as CreateAgentInput, g as AgentIdentity, h as AgentFilter, U as UpdateAgentInput, i as AuthorizeRequest, R as RequestContext, j as AuthorizeResult, k as AuditFilter, l as AuditEntry, m as AuditExportOptions, M as McpServerInput, n as McpServer, o as ResolvedUser, p as SessionManager, q as ApprovalRequest, r as MagicLinkModule, E as EmailOtpModule, T as TotpModule, s as PasskeyModule, O as OrgModule, t as SsoModule, u as AdminModule, v as ApiKeyManagerModule, w as UsernameAuthModule, x as PhoneAuthModule, y as CaptchaModule, W as WebhookModule$1, z as PluginEndpoint, B as EndpointContext, F as KavachPlugin, G as SessionConfig, H as Session } from './types-Xk83hv4O.js';
3
+ export { I as AdminConfig, J as AdminUser, L as AgentConfig, N as ApiKey, Q as ApiKeyManagerConfig, X as ApprovalConfig, Y as ApprovalModule, Z as AuthAdapter, _ as CaptchaConfig, $ as CaptchaVerifyResult, a0 as DatabaseConfig, a1 as EmailOtpConfig, a2 as KavachHooks, a3 as KavachInstance, a4 as MagicLinkConfig, a5 as McpMiddleware, a6 as OidcProvider, a7 as OrgConfig, a8 as OrgInvitation, a9 as OrgMember, aa as OrgRole, ab as Organization, ac as PasskeyConfig, ad as PasskeyCredential, ae as PermissionConstraints, af as PhoneAuthConfig, ag as PluginContext, ah as PluginInitResult, ai as SSO_ERROR, aj as SamlProvider, ak as ServiceEndpoint, al as SsoAuditEvent, am as SsoConfig, an as SsoConnection, ao as SsoError, ap as TokenValidationResult, aq as TotpConfig, ar as TotpSetup, as as UsernameAuthConfig, at as VerificationMethod, au as agentCards, av as agentDids, aw as agents, ax as apiKeysTable, ay as approvalRequests, az as auditLogs, aA as budgetPolicies, aB as classifyViolation, aC as createAdminModule, aD as createApiKeyManagerModule, aE as createApprovalModule, aF as createCaptchaModule, aG as createDatabase, aH as createDatabaseSync, aI as createEmailOtpModule, aJ as createMagicLinkModule, aK as createOrgModule, aL as createPasskeyModule, aM as createPhoneAuthModule, aN as createSessionManager, aO as createSsoModule, aP as createTotpModule, aQ as createUsernameAuthModule, aR as delegationChains, aS as emailOtps, aT as magicLinks, aU as mcpServers, aV as oauthAccessTokens, aW as oauthAuthorizationCodes, aX as oauthClients, aY as orgInvitations, aZ as orgMembers, a_ as orgRoles, a$ as organizations, b0 as passkeyChallenges, b1 as passkeyCredentials, b2 as permissions, b3 as rateLimits, b4 as sessions, b5 as ssoConnections, b6 as tenants, b7 as totpRecords, b8 as trustScores, b9 as users } from './types-Xk83hv4O.js';
4
4
  export { createAuditModule } from './audit/index.js';
5
- export { BearerAuthOptions, HeaderAuthOptions, bearerAuth, customAuth, headerAuth } from './auth/index.js';
6
- import { R as ResolvedUser } from './types-_7hIICee.js';
7
- export { A as AuthAdapter } from './types-_7hIICee.js';
5
+ export { AccessTokenClaims, AdditionalFieldsConfig, AdditionalFieldsModule, AnonymousAuthConfig, AnonymousAuthModule, AuthorizeParams, BearerAuthOptions, CheckoutOptions, CreateTokenInput, CustomSessionConfig, CustomSessionModule, DeleteOptions, DeleteResult, DeviceAuthConfig, DeviceAuthModule, DeviceAuthStatus, DeviceCodeResponse, EndpointGroup, FieldDefinition, GdprModule, GetUserClaimsFn, GoogleUser, HeaderAuthOptions, HibpApiError, HibpBreachedError, HibpConfig, HibpModule, JsonWebKeySet, JwtSessionConfig, JwtSessionModule, LastLoginConfig, LastLoginModule, LoginEvent, LoginMethod, OAuthProxyConfig, OAuthProxyError, OAuthProxyModule, OAuthProxyPluginConfig, OidcClient, OidcDiscoveryDocument, OidcProviderConfig, OidcProviderModule, OneTapConfig, OneTapModule, OneTapVerifyError, OneTimeTokenConfig, OneTimeTokenModule, OneTimeTokenPurpose, OpenApiComponents, OpenApiConfig, OpenApiDocument, OpenApiInfo, OpenApiMediaType, OpenApiModule, OpenApiOperation, OpenApiParameter, OpenApiPathItem, OpenApiRequestBody, OpenApiResponse, OpenApiSchema, OpenApiSecurityRequirement, OpenApiSecurityScheme, OpenApiServer, PolarConfig, PolarModule, PolarSubscription, ProxyTokens, RateLimitConfig, RateLimitMiddlewareOptions, RateLimitResult, RateLimiter, RecordLoginInput, RegisterClientInput, RevokeTokensResult, ScimConfig, ScimGroup, ScimModule, ScimUser, SessionTokens, SessionUser, SiweConfig, SiweModule, SiweVerifyResult, StripeConfig, StripeModule, SubscriptionInfo, TokenParams, TokenResponse, TrustedDevice, TrustedDeviceConfig, TrustedDeviceModule, TwoFactorConfig, UserDataExport, UserInfoClaims, ValidateTokenResult, ValidationResult, VerifiedSession, additionalFields, admin, anonymousAuth, apiKeys, bearerAuth, createAdditionalFieldsModule, createAnonymousAuthModule, createCustomSessionModule, createDeviceAuthModule, createGdprModule, createHibpModule, createJwtSessionModule, createLastLoginModule, createOAuthProxyModule, createOidcProviderModule, createOneTapModule, createOneTimeTokenModule, createOpenApiModule, createPolarModule, createRateLimiter, createScimModule, createSiweModule, createStripeModule, createTrustedDeviceModule, customAuth, customSession, deviceAuth, deviceLabelFromRequest, emailOtp, gdpr, headerAuth, magicLink, oauthProxy, oneTap, organization, passkey, polar, scim, siwe, stripe, twoFactor, withRateLimit } from './auth/index.js';
8
6
  export { PermissionTemplateName, createPermissionEngine, getPermissionTemplate, permissionTemplates } from './permission/index.js';
9
- import './types-B4sQA44H.js';
10
- import 'zod';
11
7
  import 'drizzle-orm/better-sqlite3';
12
8
  import 'drizzle-orm/sqlite-core';
9
+ import './types-mwupB57A.js';
10
+ import 'zod';
11
+ import 'jose';
12
+
13
+ interface PrivilegeFinding {
14
+ type: "wildcard_permission" | "unused_permission" | "overly_broad" | "no_constraints" | "no_expiry";
15
+ severity: "info" | "warning" | "critical";
16
+ description: string;
17
+ permission?: {
18
+ resource: string;
19
+ actions: string[];
20
+ };
21
+ }
22
+ interface PrivilegeAnalysis {
23
+ agentId: string;
24
+ agentName: string;
25
+ score: "minimal" | "appropriate" | "over-permissioned" | "wildcard-heavy";
26
+ findings: PrivilegeFinding[];
27
+ recommendations: string[];
28
+ }
29
+ interface PrivilegeSummary {
30
+ total: number;
31
+ byScore: Record<string, number>;
32
+ criticalFindings: number;
33
+ }
34
+ /**
35
+ * Create the least-privilege analyzer.
36
+ *
37
+ * Scans agent permissions against actual audit log usage and surfaces
38
+ * over-permissioned agents, wildcards, and unused grants.
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * const analyzer = createPrivilegeAnalyzer(db);
43
+ * const report = await analyzer.analyzeAgent('agent-123');
44
+ * console.log(report.score, report.recommendations);
45
+ * ```
46
+ */
47
+ declare function createPrivilegeAnalyzer(db: Database): {
48
+ analyzeAgent: (agentId: string, options?: {
49
+ since?: Date;
50
+ }) => Promise<PrivilegeAnalysis>;
51
+ analyzeAll: (options?: {
52
+ since?: Date;
53
+ }) => Promise<PrivilegeAnalysis[]>;
54
+ getSummary: () => Promise<PrivilegeSummary>;
55
+ };
56
+ type PrivilegeAnalyzer = ReturnType<typeof createPrivilegeAnalyzer>;
13
57
 
14
58
  /**
15
59
  * Create all KavachOS tables if they do not already exist.
@@ -42,6 +86,202 @@ declare function createDelegationModule(config: DelegationModuleConfig): {
42
86
  listChains: (agentId: string) => Promise<DelegationChain[]>;
43
87
  };
44
88
 
89
+ /**
90
+ * Build a W3C DID Document for a did:key identifier.
91
+ */
92
+ declare function buildDidDocument(did: string, publicKeyJwk: JsonWebKey): DidDocument;
93
+ /**
94
+ * Generate a new did:key identity using Ed25519.
95
+ *
96
+ * Returns the DID, key pair (JWK format), and auto-generated DID document.
97
+ * The private key is returned to the caller and must be stored securely —
98
+ * it is never persisted by KavachOS.
99
+ */
100
+ declare function generateDidKey(): Promise<DidKeyPair>;
101
+ /**
102
+ * Resolve a did:key to its DID document.
103
+ *
104
+ * did:key is self-describing — the public key is embedded in the identifier
105
+ * via multibase(multicodec(raw_key)), so resolution is purely local.
106
+ * Returns null if the DID is malformed.
107
+ */
108
+ declare function resolveDidKey(did: string): DidDocument | null;
109
+
110
+ /**
111
+ * Create the DID module.
112
+ *
113
+ * Provides W3C DID generation (did:key and did:web), storage of the public
114
+ * key + DID document in the database, and signing / verification helpers.
115
+ * Private keys are never stored — they are returned to the caller on
116
+ * generation and must be stored securely elsewhere.
117
+ */
118
+ declare function createDidModule(db: Database, config?: {
119
+ web?: DidWebConfig;
120
+ }): {
121
+ generateKey: (agentId: string) => Promise<{
122
+ agentDid: AgentDid;
123
+ privateKeyJwk: JsonWebKey;
124
+ }>;
125
+ generateWeb: (agentId: string) => Promise<{
126
+ agentDid: AgentDid;
127
+ privateKeyJwk: JsonWebKey;
128
+ }>;
129
+ resolve: (did: string) => Promise<DidDocument | null>;
130
+ getAgentDid: (agentId: string) => Promise<AgentDid | null>;
131
+ sign: (agentId: string, payload: Record<string, unknown>, privateKeyJwk: JsonWebKey) => Promise<SignedPayload>;
132
+ verify: (jws: string, did?: string) => Promise<VerificationResult>;
133
+ createPresentation: (options: {
134
+ agentId: string;
135
+ privateKeyJwk: JsonWebKey;
136
+ capabilities: string[];
137
+ audience?: string;
138
+ expiresIn?: number;
139
+ }) => Promise<string>;
140
+ verifyPresentation: (jwt: string) => Promise<VerificationResult & {
141
+ capabilities?: string[];
142
+ }>;
143
+ };
144
+ type DidModule = ReturnType<typeof createDidModule>;
145
+
146
+ /**
147
+ * Sign a payload as a compact JWS using the agent's DID private key.
148
+ *
149
+ * The JWT header embeds the DID as `iss` and the key fragment as `kid`.
150
+ * Algorithm is always EdDSA (Ed25519).
151
+ */
152
+ declare function signPayload(payload: Record<string, unknown>, privateKeyJwk: JsonWebKey, did: string): Promise<SignedPayload>;
153
+ /**
154
+ * Verify a signed payload using a known public key JWK.
155
+ *
156
+ * Extracts the DID from the `iss` claim and returns the decoded payload
157
+ * on success. Callers are responsible for resolving the correct public key
158
+ * from the DID document before calling this function.
159
+ */
160
+ declare function verifyPayload(jws: string, publicKeyJwk: JsonWebKey): Promise<VerificationResult>;
161
+ /**
162
+ * Create a verifiable presentation JWT.
163
+ *
164
+ * The presentation proves the agent's identity and lists the capabilities
165
+ * they are asserting. It is audience-bound and short-lived by default.
166
+ */
167
+ declare function createPresentation(options: {
168
+ agentId: string;
169
+ did: string;
170
+ privateKeyJwk: JsonWebKey;
171
+ capabilities: string[];
172
+ audience?: string;
173
+ expiresIn?: number;
174
+ }): Promise<string>;
175
+ /**
176
+ * Verify a presentation JWT and extract the claims.
177
+ *
178
+ * Returns the agentId, DID, and capabilities on success.
179
+ */
180
+ declare function verifyPresentation(jwt: string, publicKeyJwk: JsonWebKey): Promise<{
181
+ valid: boolean;
182
+ agentId?: string;
183
+ did?: string;
184
+ capabilities?: string[];
185
+ error?: string;
186
+ }>;
187
+
188
+ /**
189
+ * Generate a did:web identity for an agent.
190
+ *
191
+ * Internally generates an Ed25519 key pair and builds a DID document
192
+ * using the did:web identifier derived from the domain config.
193
+ * The private key is returned to the caller and must be stored securely.
194
+ */
195
+ declare function generateDidWeb(config: DidWebConfig, agentId: string): Promise<DidKeyPair>;
196
+ /**
197
+ * Get the HTTPS URL where a did:web document should be hosted.
198
+ *
199
+ * did:web:example.com → https://example.com/.well-known/did.json
200
+ * did:web:example.com:agents:123 → https://example.com/agents/123/did.json
201
+ */
202
+ declare function getDidWebUrl(did: string): string;
203
+ /**
204
+ * Resolve a did:web by fetching the DID document from the web.
205
+ *
206
+ * Returns null if the fetch fails or the document is malformed.
207
+ * In production, callers should add caching and error handling.
208
+ */
209
+ declare function resolveDidWeb(did: string): Promise<DidDocument | null>;
210
+
211
+ interface EmailTemplate {
212
+ subject: string;
213
+ text: string;
214
+ html: string;
215
+ }
216
+ type EmailTemplateName = "verification" | "passwordReset" | "magicLink" | "emailOtp" | "invitation" | "welcome";
217
+ interface EmailTemplateConfig {
218
+ appName?: string;
219
+ appUrl?: string;
220
+ /** Custom templates override defaults */
221
+ templates?: Partial<Record<EmailTemplateName, (vars: Record<string, string>) => EmailTemplate>>;
222
+ }
223
+ interface EmailTemplates {
224
+ render(name: EmailTemplateName, vars: Record<string, string>): EmailTemplate;
225
+ }
226
+ declare function createEmailTemplates(config?: EmailTemplateConfig): EmailTemplates;
227
+
228
+ interface TranslationKeys {
229
+ "auth.invalidCredentials": string;
230
+ "auth.emailNotVerified": string;
231
+ "auth.accountLocked": string;
232
+ "auth.rateLimited": string;
233
+ "auth.emailAlreadyExists": string;
234
+ "auth.weakPassword": string;
235
+ "auth.tokenExpired": string;
236
+ "auth.tokenInvalid": string;
237
+ "auth.unauthorized": string;
238
+ "agent.notFound": string;
239
+ "agent.revoked": string;
240
+ "agent.limitExceeded": string;
241
+ "agent.permissionDenied": string;
242
+ "twoFactor.invalidCode": string;
243
+ "twoFactor.alreadyEnabled": string;
244
+ "twoFactor.notEnabled": string;
245
+ "email.verification.subject": string;
246
+ "email.passwordReset.subject": string;
247
+ "email.magicLink.subject": string;
248
+ "email.otp.subject": string;
249
+ "email.invitation.subject": string;
250
+ "email.welcome.subject": string;
251
+ "general.serverError": string;
252
+ "general.badRequest": string;
253
+ "general.notFound": string;
254
+ }
255
+ interface I18nConfig {
256
+ /** Default locale (default: "en") */
257
+ defaultLocale?: string;
258
+ /** Custom translations merged on top of built-in defaults */
259
+ translations?: Record<string, Partial<TranslationKeys>>;
260
+ }
261
+ interface I18nModule {
262
+ /** Get a translated string, optionally for a specific locale */
263
+ t(key: keyof TranslationKeys, locale?: string): string;
264
+ /** Get a translated string with variable interpolation */
265
+ t(key: keyof TranslationKeys, vars: Record<string, string>, locale?: string): string;
266
+ /** Add or replace translations for a locale at runtime */
267
+ addLocale(locale: string, translations: Partial<TranslationKeys>): void;
268
+ /** Return all registered locale codes */
269
+ getLocales(): string[];
270
+ }
271
+ declare function createI18n(config?: I18nConfig): I18nModule;
272
+
273
+ declare const de: TranslationKeys;
274
+
275
+ declare const en: TranslationKeys;
276
+
277
+ declare const es: TranslationKeys;
278
+
279
+ declare const fr: TranslationKeys;
280
+
281
+ declare const ja: TranslationKeys;
282
+
283
+ declare const zh: TranslationKeys;
284
+
45
285
  /**
46
286
  * Create a KavachOS instance.
47
287
  *
@@ -78,16 +318,16 @@ declare function createDelegationModule(config: DelegationModuleConfig): {
78
318
  */
79
319
  declare function createKavach(config: KavachConfig): Promise<{
80
320
  agent: {
81
- create: (input: CreateAgentInput) => Promise<AgentIdentity & {
321
+ create(input: CreateAgentInput): ReturnType<(input: CreateAgentInput) => Promise<AgentIdentity & {
82
322
  token: string;
83
- }>;
323
+ }>>;
324
+ revoke(agentId: string): ReturnType<(agentId: string) => Promise<void>>;
325
+ rotate(agentId: string): ReturnType<(agentId: string) => Promise<AgentIdentity & {
326
+ token: string;
327
+ }>>;
84
328
  get: (agentId: string) => Promise<AgentIdentity | null>;
85
329
  list: (filter?: AgentFilter) => Promise<AgentIdentity[]>;
86
330
  update: (agentId: string, input: UpdateAgentInput) => Promise<AgentIdentity>;
87
- revoke: (agentId: string) => Promise<void>;
88
- rotate: (agentId: string) => Promise<AgentIdentity & {
89
- token: string;
90
- }>;
91
331
  validateToken: (token: string) => Promise<AgentIdentity | null>;
92
332
  };
93
333
  authorize: (agentId: string, request: AuthorizeRequest, context?: RequestContext) => Promise<AuthorizeResult>;
@@ -130,6 +370,21 @@ declare function createKavach(config: KavachConfig): Promise<{
130
370
  */
131
371
  get(id: string): Promise<McpServer | null>;
132
372
  };
373
+ /**
374
+ * Least-privilege analyzer.
375
+ *
376
+ * Compare agent permissions against actual audit log usage to surface
377
+ * wildcards, unused grants, and over-permissioned identities.
378
+ */
379
+ analyzer: {
380
+ analyzeAgent: (agentId: string, options?: {
381
+ since?: Date;
382
+ }) => Promise<PrivilegeAnalysis>;
383
+ analyzeAll: (options?: {
384
+ since?: Date;
385
+ }) => Promise<PrivilegeAnalysis[]>;
386
+ getSummary: () => Promise<PrivilegeSummary>;
387
+ };
133
388
  /**
134
389
  * Human auth integration.
135
390
  *
@@ -160,6 +415,314 @@ declare function createKavach(config: KavachConfig): Promise<{
160
415
  resolveUser(request: Request): Promise<ResolvedUser | null>;
161
416
  /** Direct database access for advanced usage */
162
417
  db: Database;
418
+ /**
419
+ * Multi-tenant isolation.
420
+ *
421
+ * Create and manage tenants (organizations) that share a single
422
+ * KavachOS instance with full data isolation. Agents can be scoped
423
+ * to a tenant via `tenantId`.
424
+ */
425
+ tenant: {
426
+ create: (input: CreateTenantInput) => Promise<Tenant>;
427
+ get: (tenantId: string) => Promise<Tenant | null>;
428
+ getBySlug: (slug: string) => Promise<Tenant | null>;
429
+ list: () => Promise<Tenant[]>;
430
+ update: (tenantId: string, updates: Partial<CreateTenantInput>) => Promise<Tenant>;
431
+ suspend: (tenantId: string) => Promise<void>;
432
+ activate: (tenantId: string) => Promise<void>;
433
+ };
434
+ /**
435
+ * Agent execution budget policies.
436
+ *
437
+ * Set spending caps (token cost, call counts) per agent, user, or
438
+ * tenant. Exceeded policies trigger a configurable action: warn,
439
+ * throttle, block, or revoke.
440
+ */
441
+ policies: {
442
+ create: (input: CreatePolicyInput) => Promise<BudgetPolicy>;
443
+ get: (policyId: string) => Promise<BudgetPolicy | null>;
444
+ list: (filters?: PolicyFilters) => Promise<BudgetPolicy[]>;
445
+ update: (policyId: string, updates: Partial<BudgetPolicy>) => Promise<BudgetPolicy>;
446
+ remove: (policyId: string) => Promise<void>;
447
+ checkBudget: (agentId: string, tokensCost?: number) => Promise<{
448
+ allowed: boolean;
449
+ reason?: string;
450
+ policy?: BudgetPolicy;
451
+ }>;
452
+ recordUsage: (agentId: string, tokensCost?: number) => Promise<void>;
453
+ resetDaily: () => Promise<{
454
+ reset: number;
455
+ }>;
456
+ resetMonthly: () => Promise<{
457
+ reset: number;
458
+ }>;
459
+ };
460
+ /**
461
+ * CIBA-style async human approval flows.
462
+ *
463
+ * Create pending approval requests, notify humans via webhook or
464
+ * custom handler, and resolve them with approve / deny.
465
+ */
466
+ approval: {
467
+ request: (input: {
468
+ agentId: string;
469
+ userId: string;
470
+ action: string;
471
+ resource: string;
472
+ arguments?: Record<string, unknown>;
473
+ }) => Promise<ApprovalRequest>;
474
+ approve: (requestId: string, respondedBy?: string) => Promise<ApprovalRequest>;
475
+ deny: (requestId: string, respondedBy?: string) => Promise<ApprovalRequest>;
476
+ get: (requestId: string) => Promise<ApprovalRequest | null>;
477
+ listPending: (userId?: string) => Promise<ApprovalRequest[]>;
478
+ cleanup: () => Promise<{
479
+ expired: number;
480
+ }>;
481
+ };
482
+ /**
483
+ * Graduated autonomy trust scoring.
484
+ *
485
+ * Compute and persist 0-100 trust scores derived from audit history,
486
+ * mapped to five levels: untrusted, limited, standard, trusted, elevated.
487
+ */
488
+ trust: {
489
+ computeScore: (agentId: string) => Promise<TrustScore>;
490
+ getScore: (agentId: string) => Promise<TrustScore | null>;
491
+ computeAll: () => Promise<TrustScore[]>;
492
+ getScores: (filters?: {
493
+ level?: string;
494
+ minScore?: number;
495
+ }) => Promise<TrustScore[]>;
496
+ };
497
+ /**
498
+ * W3C Decentralized Identifiers (DID) for agents.
499
+ *
500
+ * Generate did:key or did:web identities, sign payloads, and verify
501
+ * signatures. Private keys are never stored — they are returned to
502
+ * the caller on generation and must be stored securely.
503
+ *
504
+ * @example
505
+ * ```typescript
506
+ * const { agentDid, privateKeyJwk } = await kavach.did.generateKey(agentId);
507
+ * const signed = await kavach.did.sign(agentId, { action: 'read' }, privateKeyJwk);
508
+ * const result = await kavach.did.verify(signed.jws, agentDid.did);
509
+ * ```
510
+ */
511
+ did: {
512
+ generateKey: (agentId: string) => Promise<{
513
+ agentDid: AgentDid;
514
+ privateKeyJwk: JsonWebKey;
515
+ }>;
516
+ generateWeb: (agentId: string) => Promise<{
517
+ agentDid: AgentDid;
518
+ privateKeyJwk: JsonWebKey;
519
+ }>;
520
+ resolve: (did: string) => Promise<DidDocument | null>;
521
+ getAgentDid: (agentId: string) => Promise<AgentDid | null>;
522
+ sign: (agentId: string, payload: Record<string, unknown>, privateKeyJwk: JsonWebKey) => Promise<SignedPayload>;
523
+ verify: (jws: string, did?: string) => Promise<VerificationResult>;
524
+ createPresentation: (options: {
525
+ agentId: string;
526
+ privateKeyJwk: JsonWebKey;
527
+ capabilities: string[];
528
+ audience?: string;
529
+ expiresIn?: number;
530
+ }) => Promise<string>;
531
+ verifyPresentation: (jwt: string) => Promise<VerificationResult & {
532
+ capabilities?: string[];
533
+ }>;
534
+ };
535
+ /**
536
+ * Magic link (passwordless email) authentication.
537
+ *
538
+ * Null when `magicLink` config was not provided or `auth.session` is not
539
+ * configured (sessions are required to issue tokens on verification).
540
+ *
541
+ * @example
542
+ * ```typescript
543
+ * // In your route handler
544
+ * const response = await kavach.magicLink?.handleRequest(request);
545
+ * if (response) return response;
546
+ * ```
547
+ */
548
+ magicLink: MagicLinkModule | null;
549
+ /**
550
+ * Email OTP (one-time password) authentication.
551
+ *
552
+ * Null when `emailOtp` config was not provided or `auth.session` is not
553
+ * configured.
554
+ *
555
+ * @example
556
+ * ```typescript
557
+ * const response = await kavach.emailOtp?.handleRequest(request);
558
+ * if (response) return response;
559
+ * ```
560
+ */
561
+ emailOtp: EmailOtpModule | null;
562
+ /**
563
+ * TOTP two-factor authentication.
564
+ *
565
+ * Null when `totp` config was not provided.
566
+ *
567
+ * @example
568
+ * ```typescript
569
+ * // On setup (show QR code to user)
570
+ * const { secret, uri, backupCodes } = await kavach.totp.setup(userId);
571
+ *
572
+ * // After user scans QR and enters code
573
+ * const { enabled } = await kavach.totp.enable(userId, totpCode);
574
+ *
575
+ * // On login (after password check)
576
+ * const { valid } = await kavach.totp.verify(userId, totpCode);
577
+ * ```
578
+ */
579
+ totp: TotpModule | null;
580
+ /**
581
+ * Passkey / WebAuthn authentication.
582
+ *
583
+ * Null when `passkey` config was not provided.
584
+ *
585
+ * @example
586
+ * ```typescript
587
+ * // Registration — step 1: get options, send to browser
588
+ * const options = await kavach.passkey.getRegistrationOptions(userId, userName);
589
+ *
590
+ * // Registration — step 2: verify browser response
591
+ * const { credential } = await kavach.passkey.verifyRegistration(userId, response);
592
+ *
593
+ * // Authentication — step 1: get options
594
+ * const options = await kavach.passkey.getAuthenticationOptions(userId);
595
+ *
596
+ * // Authentication — step 2: verify browser response
597
+ * const result = await kavach.passkey.verifyAuthentication(response);
598
+ * if (result) console.log('Authenticated user:', result.userId);
599
+ * ```
600
+ */
601
+ passkey: PasskeyModule | null;
602
+ /**
603
+ * Organizations + RBAC.
604
+ *
605
+ * Null when `org` config was not provided.
606
+ *
607
+ * @example
608
+ * ```typescript
609
+ * const org = await kavach.org?.create({ name: 'Acme', slug: 'acme', ownerId: userId });
610
+ * const allowed = await kavach.org?.hasPermission(org.id, userId, 'agents:create');
611
+ * ```
612
+ */
613
+ org: OrgModule | null;
614
+ /**
615
+ * SSO (SAML 2.0 + OIDC) enterprise authentication.
616
+ *
617
+ * Null when `sso` config was not provided.
618
+ *
619
+ * @example
620
+ * ```typescript
621
+ * const conn = await kavach.sso?.createConnection({ orgId, providerId: 'okta', type: 'saml', domain: 'acme.com' });
622
+ * const url = await kavach.sso?.getSamlAuthUrl(conn.id);
623
+ * ```
624
+ */
625
+ sso: SsoModule | null;
626
+ /**
627
+ * Admin module.
628
+ *
629
+ * Null when `admin` config was not provided.
630
+ *
631
+ * @example
632
+ * ```typescript
633
+ * await kavach.admin?.banUser(userId, 'Spam');
634
+ * const { session } = await kavach.admin?.impersonate(adminId, userId);
635
+ * ```
636
+ */
637
+ admin: AdminModule | null;
638
+ /**
639
+ * API key management.
640
+ *
641
+ * Null when `apiKeys` config was not provided.
642
+ *
643
+ * @example
644
+ * ```typescript
645
+ * const { key, apiKey } = await kavach.apiKeys?.create({ userId, name: 'CI', permissions: ['agents:read'] });
646
+ * const result = await kavach.apiKeys?.validate(key);
647
+ * ```
648
+ */
649
+ apiKeys: ApiKeyManagerModule | null;
650
+ /**
651
+ * Username + password authentication.
652
+ *
653
+ * Null when `username` config was not provided or `auth.session` is not
654
+ * configured (sessions are required to issue tokens on sign-in/up).
655
+ *
656
+ * @example
657
+ * ```typescript
658
+ * const response = await kavach.username?.handleRequest(request);
659
+ * if (response) return response;
660
+ * ```
661
+ */
662
+ username: UsernameAuthModule | null;
663
+ /**
664
+ * Phone number (SMS OTP) authentication.
665
+ *
666
+ * Null when `phone` config was not provided or `auth.session` is not
667
+ * configured.
668
+ *
669
+ * @example
670
+ * ```typescript
671
+ * const response = await kavach.phone?.handleRequest(request);
672
+ * if (response) return response;
673
+ * ```
674
+ */
675
+ phone: PhoneAuthModule | null;
676
+ /**
677
+ * Captcha integration (reCAPTCHA, hCaptcha, Cloudflare Turnstile).
678
+ *
679
+ * Null when `captcha` config was not provided.
680
+ *
681
+ * @example
682
+ * ```typescript
683
+ * const result = await kavach.captcha?.verify(token, ip);
684
+ * if (!result?.success) return new Response('Captcha failed', { status: 403 });
685
+ * ```
686
+ */
687
+ captcha: CaptchaModule | null;
688
+ /**
689
+ * Webhook system.
690
+ *
691
+ * Null when `webhooks` config was not provided or the array is empty.
692
+ *
693
+ * @example
694
+ * ```typescript
695
+ * kavach.webhooks?.emit('user.created', { userId: user.id });
696
+ * ```
697
+ */
698
+ webhooks: WebhookModule$1 | null;
699
+ /**
700
+ * Plugin system.
701
+ *
702
+ * Route incoming HTTP requests through plugin-registered endpoints,
703
+ * retrieve all endpoints for adapter mounting, or access plugin-provided
704
+ * context values.
705
+ *
706
+ * @example
707
+ * ```typescript
708
+ * // In a framework adapter
709
+ * app.all('/kavach/*', async (req) => {
710
+ * const response = await kavach.plugins.handleRequest(req);
711
+ * if (response) return response;
712
+ * return new Response('Not Found', { status: 404 });
713
+ * });
714
+ * ```
715
+ */
716
+ plugins: {
717
+ /** Route a request through plugin endpoints. Returns null if no plugin handles it. */
718
+ handleRequest(request: Request, basePath?: string): Promise<Response | null>;
719
+ /** Get all endpoints registered by plugins (for framework adapter mounting). */
720
+ getEndpoints(): PluginEndpoint[];
721
+ /** Get the merged plugin context (values returned from plugin init). */
722
+ getContext(): Record<string, unknown>;
723
+ /** Access the raw plugin registry (hooks, migrations, etc.). */
724
+ registry: PluginRegistry;
725
+ };
163
726
  }>;
164
727
  type Kavach = Awaited<ReturnType<typeof createKavach>>;
165
728
 
@@ -237,4 +800,552 @@ declare function generateOpenAPISpec(options?: {
237
800
  version?: string;
238
801
  }): OpenAPISpec;
239
802
 
240
- export { AgentFilter, AgentIdentity, AuditEntry, AuditExportOptions, AuditFilter, AuthorizeRequest, AuthorizeResult, CreateAgentInput, Database, DelegateInput, DelegationChain, type Kavach, KavachConfig, McpServer, McpServerInput, Permission, ResolvedUser, SessionManager, UpdateAgentInput, createDelegationModule, createKavach, createTables, generateOpenAPISpec };
803
+ /**
804
+ * Create a plugin router that matches requests to registered plugin endpoints.
805
+ *
806
+ * The router strips `basePath` from the request URL before matching so plugins
807
+ * register paths relative to the mount point (e.g. `/auth/sign-in` instead
808
+ * of `/api/kavach/auth/sign-in`).
809
+ */
810
+ declare function createPluginRouter(endpoints: PluginEndpoint[]): {
811
+ /** Try to handle a request. Returns Response if matched, null if not. */
812
+ handle: (request: Request, basePath: string, endpointCtx: EndpointContext) => Promise<Response | null>;
813
+ /** Get all registered endpoints (for adapter mounting) */
814
+ getEndpoints: () => PluginEndpoint[];
815
+ };
816
+
817
+ interface PluginRegistry {
818
+ endpoints: PluginEndpoint[];
819
+ migrations: string[];
820
+ hooks: {
821
+ onRequest: Array<NonNullable<KavachPlugin["hooks"]>["onRequest"]>;
822
+ onAuthenticate: Array<NonNullable<KavachPlugin["hooks"]>["onAuthenticate"]>;
823
+ onSessionCreate: Array<NonNullable<KavachPlugin["hooks"]>["onSessionCreate"]>;
824
+ onSessionRevoke: Array<NonNullable<KavachPlugin["hooks"]>["onSessionRevoke"]>;
825
+ };
826
+ pluginContext: Record<string, unknown>;
827
+ }
828
+ /**
829
+ * Initialize all plugins and collect their endpoints, migrations, and hooks
830
+ * into a single registry.
831
+ *
832
+ * Calls each plugin's `init()` in registration order. Migrations collected
833
+ * during init are executed before the registry is returned so that any
834
+ * subsequent requests can immediately use plugin tables.
835
+ */
836
+ declare function initializePlugins(plugins: KavachPlugin[], db: Database, config: KavachConfig): Promise<PluginRegistry>;
837
+
838
+ interface BudgetPolicy {
839
+ id: string;
840
+ agentId?: string;
841
+ userId?: string;
842
+ tenantId?: string;
843
+ limits: BudgetLimits;
844
+ currentUsage: BudgetUsage;
845
+ action: "warn" | "throttle" | "block" | "revoke";
846
+ status: "active" | "triggered" | "disabled";
847
+ createdAt: Date;
848
+ }
849
+ interface BudgetLimits {
850
+ maxTokensCostPerDay?: number;
851
+ maxTokensCostPerMonth?: number;
852
+ maxCallsPerDay?: number;
853
+ maxCallsPerMonth?: number;
854
+ }
855
+ interface BudgetUsage {
856
+ tokensCostToday: number;
857
+ tokensCostThisMonth: number;
858
+ callsToday: number;
859
+ callsThisMonth: number;
860
+ lastUpdated: string;
861
+ }
862
+ interface CreatePolicyInput {
863
+ agentId?: string;
864
+ userId?: string;
865
+ tenantId?: string;
866
+ limits: BudgetLimits;
867
+ action: "warn" | "throttle" | "block" | "revoke";
868
+ }
869
+ interface PolicyFilters {
870
+ agentId?: string;
871
+ userId?: string;
872
+ tenantId?: string;
873
+ }
874
+ declare function createPolicyModule(db: Database): {
875
+ create: (input: CreatePolicyInput) => Promise<BudgetPolicy>;
876
+ get: (policyId: string) => Promise<BudgetPolicy | null>;
877
+ list: (filters?: PolicyFilters) => Promise<BudgetPolicy[]>;
878
+ update: (policyId: string, updates: Partial<BudgetPolicy>) => Promise<BudgetPolicy>;
879
+ remove: (policyId: string) => Promise<void>;
880
+ checkBudget: (agentId: string, tokensCost?: number) => Promise<{
881
+ allowed: boolean;
882
+ reason?: string;
883
+ policy?: BudgetPolicy;
884
+ }>;
885
+ recordUsage: (agentId: string, tokensCost?: number) => Promise<void>;
886
+ resetDaily: () => Promise<{
887
+ reset: number;
888
+ }>;
889
+ resetMonthly: () => Promise<{
890
+ reset: number;
891
+ }>;
892
+ };
893
+
894
+ /**
895
+ * Cookie serialization and parsing utilities for KavachOS.
896
+ *
897
+ * Pure functions that work with Web API `Request`/`Response` objects and
898
+ * raw header strings. No framework dependencies.
899
+ */
900
+ type SameSite = "strict" | "lax" | "none";
901
+ interface CookieOptions {
902
+ /** Prevents JavaScript access to the cookie. Default: true. */
903
+ httpOnly?: boolean;
904
+ /**
905
+ * Restricts transmission to HTTPS. Default: true in production
906
+ * (when `NODE_ENV === 'production'`), false otherwise.
907
+ */
908
+ secure?: boolean;
909
+ /** Controls cross-site sending. Default: 'lax'. */
910
+ sameSite?: SameSite;
911
+ /** Cookie scope path. Default: '/'. */
912
+ path?: string;
913
+ /** Cookie scope domain (omitted when not set). */
914
+ domain?: string;
915
+ /** Lifetime in seconds from now. Sets both Max-Age and Expires. */
916
+ maxAge?: number;
917
+ /** Absolute expiry date (overridden by maxAge when both are set). */
918
+ expires?: Date;
919
+ /** Partitioned attribute (CHIPS). */
920
+ partitioned?: boolean;
921
+ }
922
+ /**
923
+ * Serialize a cookie name/value pair into a `Set-Cookie` header string.
924
+ *
925
+ * @param name Cookie name. Must be a valid cookie-name token.
926
+ * @param value Cookie value. Will be percent-encoded.
927
+ * @param options Cookie attributes. Defaults to `httpOnly=true`, `secure`
928
+ * based on `NODE_ENV`, `sameSite=lax`, `path=/`.
929
+ */
930
+ declare function serializeCookie(name: string, value: string, options?: CookieOptions): string;
931
+ /**
932
+ * Serialize a deletion cookie (zero Max-Age, past Expires) that will
933
+ * instruct browsers to remove the named cookie.
934
+ */
935
+ declare function serializeCookieDeletion(name: string, options?: Omit<CookieOptions, "maxAge" | "expires">): string;
936
+ /**
937
+ * Parse a `Cookie` request header string into a name → value map.
938
+ *
939
+ * Values are percent-decoded. Unknown or malformed pairs are skipped
940
+ * silently so that a single bad cookie does not break the entire request.
941
+ *
942
+ * @param header The raw value of the `Cookie` header (e.g. `"a=1; b=2"`).
943
+ */
944
+ declare function parseCookies(header: string): Record<string, string>;
945
+ /**
946
+ * Extract a single cookie value from a `Cookie` header string.
947
+ *
948
+ * Returns `undefined` when the cookie is absent.
949
+ */
950
+ declare function getCookie(header: string, name: string): string | undefined;
951
+ /**
952
+ * Extract cookies from a Web API `Request` object.
953
+ */
954
+ declare function parseCookiesFromRequest(request: Request): Record<string, string>;
955
+
956
+ /**
957
+ * CSRF protection utilities for KavachOS.
958
+ *
959
+ * Implements two complementary defences:
960
+ *
961
+ * 1. **Origin/Referer validation** — checks the inbound request's `Origin`
962
+ * (or `Referer` as fallback) against a caller-supplied allowlist. This
963
+ * alone blocks the vast majority of CSRF attacks from browser clients.
964
+ *
965
+ * 2. **Double-submit cookie pattern** — a random token is stored in a cookie
966
+ * AND submitted by the client as a request header (or body field). The
967
+ * server verifies both values match using a timing-safe comparison.
968
+ *
969
+ * Use origin validation first; fall back to token comparison when the origin
970
+ * header is absent (e.g. same-origin requests on some browsers, server-side
971
+ * fetch).
972
+ *
973
+ * @example
974
+ * ```typescript
975
+ * import { generateCsrfToken, validateCsrfToken, validateOrigin } from './csrf.js';
976
+ *
977
+ * // On form render: store token in cookie, embed in hidden field.
978
+ * const token = await generateCsrfToken();
979
+ *
980
+ * // On form submit:
981
+ * const originOk = validateOrigin(request, ['https://app.example.com']);
982
+ * const tokenOk = validateCsrfToken(submittedToken, cookieToken);
983
+ * if (!originOk && !tokenOk) throw new Error('CSRF check failed');
984
+ * ```
985
+ */
986
+ interface CsrfValidationResult {
987
+ valid: boolean;
988
+ reason?: string;
989
+ }
990
+ /**
991
+ * Generate a cryptographically random CSRF token.
992
+ *
993
+ * Uses `crypto.getRandomValues` (Web Crypto API) so it works in both
994
+ * Node.js ≥ 19 and browser/edge runtimes.
995
+ *
996
+ * Returns a URL-safe base64 string (~43 chars).
997
+ */
998
+ declare function generateCsrfToken(): string;
999
+ /**
1000
+ * Validate a CSRF token from the request against the value stored in the
1001
+ * cookie using a constant-time comparison to prevent timing attacks.
1002
+ *
1003
+ * Both `requestToken` and `cookieToken` must be non-empty strings produced
1004
+ * by `generateCsrfToken()`. Any mismatch returns `{ valid: false }`.
1005
+ *
1006
+ * @param requestToken Token submitted with the request (header / body).
1007
+ * @param cookieToken Token read from the CSRF cookie.
1008
+ */
1009
+ declare function validateCsrfToken(requestToken: string, cookieToken: string): CsrfValidationResult;
1010
+ /**
1011
+ * Validate the `Origin` (or `Referer` fallback) header of an incoming
1012
+ * request against a list of trusted origins.
1013
+ *
1014
+ * Rules:
1015
+ * - If `Origin` is present and matches a trusted origin → valid.
1016
+ * - If `Origin` is `"null"` (opaque origin) → invalid.
1017
+ * - If `Origin` is absent, falls back to the `Referer` header.
1018
+ * - If neither header is present → result depends on `allowMissingOrigin`.
1019
+ *
1020
+ * @param request Incoming Web API `Request`.
1021
+ * @param trustedOrigins Array of allowed origins, e.g. `['https://app.example.com']`.
1022
+ * Trailing slashes are stripped before comparison.
1023
+ * @param allowMissingOrigin When `true`, requests without an `Origin` or
1024
+ * `Referer` header are considered valid (useful for
1025
+ * server-to-server calls). Defaults to `false`.
1026
+ */
1027
+ declare function validateOrigin(request: Request, trustedOrigins: string[], allowMissingOrigin?: boolean): CsrfValidationResult;
1028
+
1029
+ /**
1030
+ * Cookie-aware session manager for KavachOS.
1031
+ *
1032
+ * Wraps the lower-level `createSessionManager` with cookie serialization and
1033
+ * optional CSRF protection so callers work with `Request`/`Response` objects
1034
+ * directly rather than managing raw tokens and headers themselves.
1035
+ *
1036
+ * @example
1037
+ * ```typescript
1038
+ * import { createCookieSessionManager } from './manager.js';
1039
+ *
1040
+ * const sessions = createCookieSessionManager(
1041
+ * { secret: process.env.SESSION_SECRET },
1042
+ * db,
1043
+ * );
1044
+ *
1045
+ * // On login
1046
+ * const { session, setCookieHeader } = await sessions.createSession(user.id);
1047
+ * return new Response(null, {
1048
+ * status: 302,
1049
+ * headers: { Location: '/dashboard', 'Set-Cookie': setCookieHeader },
1050
+ * });
1051
+ *
1052
+ * // On each request
1053
+ * const session = await sessions.validateSession(request.headers.get('cookie') ?? '');
1054
+ * if (!session) return new Response('Unauthorized', { status: 401 });
1055
+ *
1056
+ * // On logout
1057
+ * const deleteCookie = sessions.buildLogoutCookie();
1058
+ * return new Response(null, {
1059
+ * status: 302,
1060
+ * headers: { Location: '/login', 'Set-Cookie': deleteCookie },
1061
+ * });
1062
+ * ```
1063
+ */
1064
+
1065
+ interface CookieSessionConfig extends SessionConfig {
1066
+ /**
1067
+ * Name of the session cookie.
1068
+ * Defaults to `"kavach_session"`.
1069
+ */
1070
+ sessionName?: string;
1071
+ /**
1072
+ * Additional cookie attributes applied when setting the session cookie.
1073
+ * `maxAge` is derived from `SessionConfig.maxAge` when not explicitly set.
1074
+ */
1075
+ cookieOptions?: Omit<CookieOptions, "maxAge">;
1076
+ /**
1077
+ * When `true`, `validateSession` automatically refreshes the session
1078
+ * expiry on every successful validation. Defaults to `true`.
1079
+ */
1080
+ autoRefresh?: boolean;
1081
+ }
1082
+ interface CreateSessionResult {
1083
+ /** The persisted session record. */
1084
+ session: Session;
1085
+ /** Ready-to-use `Set-Cookie` header value. */
1086
+ setCookieHeader: string;
1087
+ }
1088
+ interface ValidateSessionResult {
1089
+ /** The valid session, or `null` when the cookie is absent/invalid/expired. */
1090
+ session: Session | null;
1091
+ /**
1092
+ * When `autoRefresh` is enabled and the session was valid, the refreshed
1093
+ * `Set-Cookie` header to forward to the client. `null` otherwise.
1094
+ */
1095
+ refreshCookieHeader: string | null;
1096
+ }
1097
+ interface CookieSessionManager {
1098
+ /**
1099
+ * Create a new session for the given user and return the session record
1100
+ * together with a `Set-Cookie` header string ready to attach to a response.
1101
+ */
1102
+ createSession(userId: string, metadata?: Record<string, unknown>): Promise<CreateSessionResult>;
1103
+ /**
1104
+ * Parse the `Cookie` header, look up the session in the database, and
1105
+ * verify it has not expired.
1106
+ *
1107
+ * When `autoRefresh` is enabled the session is extended on each valid
1108
+ * request and a new `Set-Cookie` header is returned for forwarding.
1109
+ *
1110
+ * @param cookieHeader Raw value of the `Cookie` request header.
1111
+ */
1112
+ validateSession(cookieHeader: string): Promise<ValidateSessionResult>;
1113
+ /**
1114
+ * Extend the session expiry to `now + maxAge`.
1115
+ *
1116
+ * Returns the updated session and a fresh `Set-Cookie` header.
1117
+ * Returns `null` when the session does not exist.
1118
+ */
1119
+ refreshSession(sessionId: string): Promise<{
1120
+ session: Session;
1121
+ setCookieHeader: string;
1122
+ } | null>;
1123
+ /**
1124
+ * Delete a session by ID (server-side) and return a deletion cookie that
1125
+ * will clear the browser cookie on the next response.
1126
+ */
1127
+ revokeSession(sessionId: string): Promise<{
1128
+ deleteCookieHeader: string;
1129
+ }>;
1130
+ /**
1131
+ * Revoke all sessions for the given user.
1132
+ *
1133
+ * Returns a deletion cookie header for clearing the current browser cookie.
1134
+ */
1135
+ revokeAllSessions(userId: string): Promise<{
1136
+ deleteCookieHeader: string;
1137
+ }>;
1138
+ /**
1139
+ * List all non-expired sessions for a user, newest first.
1140
+ */
1141
+ listSessions(userId: string): Promise<Session[]>;
1142
+ /**
1143
+ * Build a `Set-Cookie` header that deletes the session cookie on the client
1144
+ * without any database operation. Useful in error paths.
1145
+ */
1146
+ buildLogoutCookie(): string;
1147
+ /** Expose the underlying low-level session manager for advanced usage. */
1148
+ raw: SessionManager;
1149
+ }
1150
+ /**
1151
+ * Create a cookie-aware session manager.
1152
+ *
1153
+ * Internally delegates all DB operations to `createSessionManager`.
1154
+ *
1155
+ * @param config Cookie-aware session configuration.
1156
+ * @param db Drizzle database instance from `createDatabase()`.
1157
+ */
1158
+ declare function createCookieSessionManager(config: CookieSessionConfig, db: Database): CookieSessionManager;
1159
+
1160
+ /**
1161
+ * Multi-session support for KavachOS.
1162
+ *
1163
+ * Allows users to maintain multiple concurrent sessions (phone, laptop, tablet)
1164
+ * with optional per-user session caps. When the cap is reached, the oldest
1165
+ * session is evicted automatically (configurable).
1166
+ *
1167
+ * Uses the existing `kavach_sessions` table — no additional schema required.
1168
+ *
1169
+ * @example
1170
+ * ```typescript
1171
+ * const multiSession = createMultiSessionModule(
1172
+ * { maxSessions: 5, overflowStrategy: 'evict-oldest' },
1173
+ * db,
1174
+ * sessionManager,
1175
+ * );
1176
+ *
1177
+ * // List all active sessions for a user
1178
+ * const sessionList = await multiSession.listSessions(userId);
1179
+ *
1180
+ * // Sign out everywhere except here
1181
+ * const count = await multiSession.revokeOtherSessions(userId, currentSessionId);
1182
+ * ```
1183
+ */
1184
+
1185
+ interface MultiSessionConfig {
1186
+ /** Max concurrent sessions per user (default: 10) */
1187
+ maxSessions?: number;
1188
+ /** Strategy when max is reached (default: 'evict-oldest') */
1189
+ overflowStrategy?: "reject" | "evict-oldest";
1190
+ }
1191
+ interface SessionInfo {
1192
+ id: string;
1193
+ createdAt: Date;
1194
+ expiresAt: Date;
1195
+ metadata?: Record<string, unknown>;
1196
+ /** Human-readable device string extracted from User-Agent, e.g. "Chrome on macOS" */
1197
+ device?: string;
1198
+ /** IP address recorded at session creation */
1199
+ ip?: string;
1200
+ }
1201
+ interface MultiSessionModule {
1202
+ /** List all non-expired sessions for a user, newest first. */
1203
+ listSessions(userId: string): Promise<SessionInfo[]>;
1204
+ /** Revoke a single session by ID. */
1205
+ revokeSession(sessionId: string): Promise<void>;
1206
+ /** Revoke every session except the given one. Returns the count revoked. */
1207
+ revokeOtherSessions(userId: string, currentSessionId: string): Promise<number>;
1208
+ /** Return the count of active (non-expired) sessions for a user. */
1209
+ getSessionCount(userId: string): Promise<number>;
1210
+ /**
1211
+ * Enforce the session cap before creating a new session.
1212
+ *
1213
+ * Call this before `sessionManager.create()`. If the cap is reached:
1214
+ * - `evict-oldest` deletes the oldest session and resolves.
1215
+ * - `reject` throws a `MultiSessionLimitError`.
1216
+ */
1217
+ enforceSessionLimit(userId: string): Promise<void>;
1218
+ }
1219
+ declare class MultiSessionLimitError extends Error {
1220
+ readonly code = "SESSION_LIMIT_REACHED";
1221
+ constructor(userId: string, max: number);
1222
+ }
1223
+ declare function createMultiSessionModule(config: MultiSessionConfig, db: Database, sessionManager: SessionManager): MultiSessionModule;
1224
+ /**
1225
+ * Build metadata to pass to `sessionManager.create()` that includes
1226
+ * device info extracted from the incoming request.
1227
+ *
1228
+ * @example
1229
+ * ```typescript
1230
+ * const meta = buildSessionMetadata(request, { role: 'admin' });
1231
+ * const { token } = await sessionManager.create(userId, meta);
1232
+ * ```
1233
+ */
1234
+ declare function buildSessionMetadata(request: Request, extra?: Record<string, unknown>): Record<string, unknown>;
1235
+
1236
+ interface Tenant {
1237
+ id: string;
1238
+ name: string;
1239
+ slug: string;
1240
+ settings: TenantSettings;
1241
+ status: "active" | "suspended";
1242
+ createdAt: Date;
1243
+ updatedAt: Date;
1244
+ }
1245
+ interface TenantSettings {
1246
+ maxAgents?: number;
1247
+ maxDelegationDepth?: number;
1248
+ auditRetentionDays?: number;
1249
+ allowedAgentTypes?: string[];
1250
+ }
1251
+ interface CreateTenantInput {
1252
+ name: string;
1253
+ slug: string;
1254
+ settings?: Partial<TenantSettings>;
1255
+ }
1256
+ declare function createTenantModule(db: Database): {
1257
+ create: (input: CreateTenantInput) => Promise<Tenant>;
1258
+ get: (tenantId: string) => Promise<Tenant | null>;
1259
+ getBySlug: (slug: string) => Promise<Tenant | null>;
1260
+ list: () => Promise<Tenant[]>;
1261
+ update: (tenantId: string, updates: Partial<CreateTenantInput>) => Promise<Tenant>;
1262
+ suspend: (tenantId: string) => Promise<void>;
1263
+ activate: (tenantId: string) => Promise<void>;
1264
+ };
1265
+
1266
+ interface TrustScore {
1267
+ agentId: string;
1268
+ score: number;
1269
+ level: "untrusted" | "limited" | "standard" | "trusted" | "elevated";
1270
+ factors: {
1271
+ successRate: number;
1272
+ denialRate: number;
1273
+ ageInDays: number;
1274
+ totalCalls: number;
1275
+ anomalyCount: number;
1276
+ lastViolation?: string;
1277
+ };
1278
+ computedAt: string;
1279
+ }
1280
+ interface TrustConfig {
1281
+ /** Score thresholds for levels */
1282
+ thresholds?: {
1283
+ untrusted: number;
1284
+ limited: number;
1285
+ standard: number;
1286
+ trusted: number;
1287
+ elevated: number;
1288
+ };
1289
+ }
1290
+ /**
1291
+ * Create the graduated autonomy trust scoring module.
1292
+ *
1293
+ * Scores are derived from audit log history — success rate, denial rate,
1294
+ * agent age, total call volume, and anomaly count all feed into a 0-100
1295
+ * score mapped to five trust levels.
1296
+ *
1297
+ * @example
1298
+ * ```typescript
1299
+ * const trust = createTrustModule({}, db);
1300
+ * const score = await trust.computeScore(agentId);
1301
+ * console.log(score.level); // 'standard'
1302
+ * ```
1303
+ */
1304
+ declare function createTrustModule(config: TrustConfig, db: Database): {
1305
+ computeScore: (agentId: string) => Promise<TrustScore>;
1306
+ getScore: (agentId: string) => Promise<TrustScore | null>;
1307
+ computeAll: () => Promise<TrustScore[]>;
1308
+ getScores: (filters?: {
1309
+ level?: string;
1310
+ minScore?: number;
1311
+ }) => Promise<TrustScore[]>;
1312
+ };
1313
+ type TrustModule = ReturnType<typeof createTrustModule>;
1314
+
1315
+ type WebhookEvent = "user.created" | "user.deleted" | "user.updated" | "agent.created" | "agent.revoked" | "agent.rotated" | "session.created" | "session.revoked" | "auth.login" | "auth.logout" | "auth.failed" | "delegation.created" | "delegation.revoked" | "org.created" | "org.member.added" | "org.member.removed";
1316
+ interface WebhookConfig {
1317
+ /** Signing secret for HMAC-SHA256 webhook signatures */
1318
+ secret: string;
1319
+ /** Max delivery attempts (default: 3) */
1320
+ maxRetries?: number;
1321
+ /** Timeout per delivery in ms (default: 10000) */
1322
+ timeoutMs?: number;
1323
+ }
1324
+ interface WebhookSubscription {
1325
+ id: string;
1326
+ url: string;
1327
+ events: WebhookEvent[];
1328
+ active: boolean;
1329
+ createdAt: Date;
1330
+ }
1331
+ interface WebhookModule {
1332
+ subscribe(url: string, events: WebhookEvent[]): Promise<WebhookSubscription>;
1333
+ unsubscribe(subscriptionId: string): Promise<void>;
1334
+ list(): Promise<WebhookSubscription[]>;
1335
+ /** Dispatch an event to all matching subscribers (fire-and-forget) */
1336
+ dispatch(event: WebhookEvent, payload: Record<string, unknown>): void;
1337
+ /** Test a webhook URL */
1338
+ test(subscriptionId: string): Promise<{
1339
+ success: boolean;
1340
+ statusCode?: number;
1341
+ error?: string;
1342
+ }>;
1343
+ }
1344
+ declare function createWebhookModule(config: WebhookConfig): WebhookModule;
1345
+ /**
1346
+ * Verify an incoming webhook signature.
1347
+ * Returns true if the signature matches the payload and secret.
1348
+ */
1349
+ declare function verifyWebhookSignature(secret: string, rawBody: string, signature: string): Promise<boolean>;
1350
+
1351
+ export { AdminModule, AgentDid, AgentFilter, AgentIdentity, ApiKeyManagerModule, ApprovalRequest, AuditEntry, AuditExportOptions, AuditFilter, AuthorizeRequest, AuthorizeResult, type BudgetLimits, type BudgetPolicy, type BudgetUsage, CaptchaModule, type CookieOptions, type CookieSessionConfig, type CookieSessionManager, CreateAgentInput, type CreatePolicyInput, type CreateSessionResult, type CreateTenantInput, type CsrfValidationResult, Database, DelegateInput, DelegationChain, DidDocument, DidKeyPair, type DidModule, DidWebConfig, EmailOtpModule, type EmailTemplate, type EmailTemplateConfig, type EmailTemplateName, type EmailTemplates, EndpointContext, type I18nConfig, type I18nModule, type Kavach, KavachConfig, KavachPlugin, MagicLinkModule, McpServer, McpServerInput, type MultiSessionConfig, MultiSessionLimitError, type MultiSessionModule, OrgModule, PasskeyModule, Permission, PhoneAuthModule, PluginEndpoint, type PluginRegistry, type PolicyFilters, type PrivilegeAnalysis, type PrivilegeAnalyzer, type PrivilegeFinding, type PrivilegeSummary, ResolvedUser, type SameSite, Session, SessionConfig, type SessionInfo, SessionManager, SignedPayload, SsoModule, type Tenant, type TenantSettings, TotpModule, type TranslationKeys, type TrustConfig, type TrustModule, type TrustScore, UpdateAgentInput, UsernameAuthModule, type ValidateSessionResult, VerificationResult, type WebhookConfig, type WebhookEvent, type WebhookModule, type WebhookSubscription, buildDidDocument, buildSessionMetadata, createCookieSessionManager, createDelegationModule, createDidModule, createEmailTemplates, createI18n, createKavach, createMultiSessionModule, createPluginRouter, createPolicyModule, createPresentation, createPrivilegeAnalyzer, createTables, createTenantModule, createTrustModule, createWebhookModule, de, en, es, fr, generateCsrfToken, generateDidKey, generateDidWeb, generateOpenAPISpec, getCookie, getDidWebUrl, initializePlugins, ja, parseCookies, parseCookiesFromRequest, resolveDidKey, resolveDidWeb, serializeCookie, serializeCookieDeletion, signPayload, validateCsrfToken, validateOrigin, verifyPayload, verifyPresentation, verifyWebhookSignature, zh };