@glinr/theauth 0.4.2

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.
@@ -0,0 +1,1711 @@
1
+ export { and, eq, like } from 'drizzle-orm';
2
+ export { createAgentModule } from './agent/index.js';
3
+ import { D as Database, a as DatabaseConfig, K as KavachConfig, b as DelegateInput, P as Permission, c as DelegationChain, d as DidDocument, e as DidKeyPair, f as DidWebConfig, g as AgentDid, S as SignedPayload, V as VerificationResult, C as CreateAgentInput, A 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 PasswordResetModule, y as EmailVerificationModule, z as OneTimeTokenModule, B as SessionFreshnessModule, F as PhoneAuthModule, G as CaptchaModule, W as WebhookModule$1, H as EvaluateInput, I as PolicyDecision, J as InvalidateScope, L as PolicyCacheStats, N as PluginEndpoint, Q as EndpointContext, X as KavachPlugin, Y as SessionConfig, Z as Session } from './types-D1sBnWrs.js';
4
+ export { _ as AdminConfig, $ as AdminUser, a0 as AgentConfig, a1 as ApiKey, a2 as ApiKeyManagerConfig, a3 as ApprovalConfig, a4 as ApprovalModule, a5 as AuthAdapter, a6 as CaptchaConfig, a7 as CaptchaVerifyResult, a8 as CreateTokenInput, a9 as D1DatabaseBinding, aa as EmailOtpConfig, ab as EmailVerificationConfig, ac as KavachHooks, ad as KavachInstance, ae as MagicLinkConfig, af as McpMiddleware, ag as OidcProvider, ah as OneTimeTokenConfig, ai as OneTimeTokenPurpose, aj as OrgConfig, ak as OrgInvitation, al as OrgMember, am as OrgRole, an as Organization, ao as PasskeyConfig, ap as PasskeyCredential, aq as PasswordResetConfig, ar as PermissionConstraints, as as PhoneAuthConfig, at as PluginContext, au as PluginInitResult, av as RevokeTokensResult, aw as SSO_ERROR, ax as SamlProvider, ay as ServiceEndpoint, az as SessionFreshnessConfig, aA as SsoAuditEvent, aB as SsoConfig, aC as SsoConnection, aD as SsoError, aE as TokenValidationResult, aF as TotpConfig, aG as TotpSetup, aH as UsernameAuthConfig, aI as ValidateTokenResult, aJ as VerificationMethod, aK as agentCards, aL as agentDids, aM as agents, aN as apiKeysTable, aO as approvalRequests, aP as auditLogs, aQ as budgetPolicies, aR as classifyViolation, aS as createAdminModule, aT as createApiKeyManagerModule, aU as createApprovalModule, aV as createCaptchaModule, aW as createDatabase, aX as createDatabaseSync, aY as createEmailOtpModule, aZ as createEmailVerificationModule, a_ as createMagicLinkModule, a$ as createOneTimeTokenModule, b0 as createOrgModule, b1 as createPasskeyModule, b2 as createPasswordResetModule, b3 as createPhoneAuthModule, b4 as createSessionFreshnessModule, b5 as createSessionManager, b6 as createSsoModule, b7 as createTotpModule, b8 as createUsernameAuthModule, b9 as delegationChains, ba as emailOtps, bb as magicLinks, bc as mcpServers, bd as oauthAccessTokens, be as oauthAuthorizationCodes, bf as oauthClients, bg as orgInvitations, bh as orgMembers, bi as orgRoles, bj as organizations, bk as passkeyChallenges, bl as passkeyCredentials, bm as permissions, bn as rateLimits, bo as sessions, bp as ssoConnections, bq as tenants, br as totpRecords, bs as trustScores, bt as users } from './types-D1sBnWrs.js';
5
+ export { createAuditModule } from './audit/index.js';
6
+ export { AccessTokenClaims, AdditionalFieldsConfig, AdditionalFieldsModule, AnonymousAuthConfig, AnonymousAuthModule, AuthorizeParams, BearerAuthOptions, BudgetCheckResult, CheckParams, CheckResult, CheckoutOptions, CostAlert, CostAttributionConfig, CostAttributionModule, CostReport, CreateEphemeralSessionInput, CustomSessionConfig, CustomSessionModule, DEFAULT_ATLASSIAN_SCOPES, DEFAULT_DISCORD_SCOPES, DEFAULT_DROPBOX_SCOPES, DEFAULT_FIGMA_SCOPES, DEFAULT_NOTION_SCOPES, DEFAULT_REDDIT_SCOPES, DEFAULT_SLACK_SCOPES, DEFAULT_SPOTIFY_SCOPES, DEFAULT_TWITCH_SCOPES, DEFAULT_ZOOM_SCOPES, DeleteOptions, DeleteResult, DeviceAuthConfig, DeviceAuthModule, DeviceAuthStatus, DeviceCodeResponse, EVENT_TYPES, EndpointGroup, EndpointLimit, EphemeralSession, EphemeralSessionConfig, EphemeralSessionModule, EphemeralSessionValidateResult, EventStreamConfig, EventStreamModule, EventType, ExpandParams, FederatedAgent, FederationConfig, FederationModule, FederationToken, FederationWellKnown, FieldDefinition, GdprModule, GenericOIDCConfig, GetUserClaimsFn, GoogleUser, HeaderAuthOptions, HibpApiError, HibpBreachedError, HibpConfig, HibpModule, InstanceIdentity, IssueFederationTokenInput, JsonWebKeySet, JwtSessionConfig, JwtSessionModule, KVNamespace, KVStore, LastLoginConfig, LastLoginModule, ListObjectsParams, ListSubjectsParams, LoginEvent, LoginMethod, MemoryStore, OAuthAccount, OAuthCallbackResult, OAuthModule, OAuthModuleConfig, OAuthPluginConfig, OAuthProvider, OAuthProviderConfig, OAuthProxyConfig, OAuthProxyError, OAuthProxyModule, OAuthProxyPluginConfig, OAuthTokens, OAuthUserInfo, OidcClient, OidcDiscoveryDocument, OidcProviderConfig, OidcProviderModule, OneTapConfig, OneTapModule, OneTapVerifyError, OpenApiComponents, OpenApiConfig, OpenApiDocument, OpenApiInfo, OpenApiMediaType, OpenApiModule, OpenApiOperation, OpenApiParameter, OpenApiPathItem, OpenApiRequestBody, OpenApiResponse, OpenApiSchema, OpenApiSecurityRequirement, OpenApiSecurityScheme, OpenApiServer, PermissionRuleSet, PolarConfig, PolarModule, PolarSubscription, ProxyTokens, RateLimitConfig, RateLimitMiddlewareOptions, RateLimitPluginConfig, RateLimitResult, RateLimitStore, RateLimiter, ReBACConfig, ReBACModule, RecordCostInput, RecordLoginInput, RegisterClientInput, Relationship, ResourceNode, ScimConfig, ScimGroup, ScimModule, ScimUser, SessionTokens, SessionUser, SiweConfig, SiweModule, SiweVerifyResult, StreamEvent, StripeConfig, StripeModule, SubscriptionInfo, TokenParams, TokenResponse, TrustLevel, TrustedDevice, TrustedDeviceConfig, TrustedDeviceModule, TrustedInstance, TwoFactorConfig, UserDataExport, UserInfoClaims, ValidationResult, VerifiedSession, additionalFields, admin, anonymousAuth, apiKeys, atlassianProvider, auth0Provider, bearerAuth, bitbucketProvider, cognitoProvider, coinbaseProvider, createAdditionalFieldsModule, createAnonymousAuthModule, createAppleProvider, createAtlassianProvider, createCostAttributionModule, createCustomSessionModule, createDeviceAuthModule, createDiscordProvider, createDropboxProvider, createEphemeralSessionModule, createEventStreamModule, createFederationModule, createFigmaProvider, createGdprModule, createGithubProvider, createGitlabProvider, createGoogleProvider, createHibpModule, createJwtSessionModule, createLastLoginModule, createLinkedInProvider, createMicrosoftProvider, createNotionProvider, createOAuthModule, createOAuthProxyModule, createOidcProviderModule, createOneTapModule, createOpenApiModule, createPolarModule, createRateLimiter, createReBACModule, createRedditProvider, createScimModule, createSiweModule, createSlackProvider, createSpotifyProvider, createStripeModule, createTrustedDeviceModule, createTwitchProvider, createTwitterProvider, createZoomProvider, customAuth, customSession, deviceAuth, deviceLabelFromRequest, dropboxProvider, emailOtp, facebookProvider, figmaProvider, gdpr, genericOIDC, headerAuth, huggingfaceProvider, kakaoProvider, kickProvider, kvStore, lineProvider, linearProvider, magicLink, naverProvider, normalizeAtlassianProfile, normalizeDiscordProfile, normalizeDropboxProfile, normalizeFigmaProfile, normalizeNotionProfile, normalizeRedditProfile, normalizeSlackProfile, normalizeSpotifyProfile, normalizeTwitchProfile, normalizeZoomProfile, notionProvider, oauth, oauthProxy, oktaProvider, oneTap, organization, passkey, paypalProvider, polar, polarProvider, railwayProvider, rateLimit, redditProvider, robloxProvider, salesforceProvider, scim, siwe, spotifyProvider, stripe, tiktokProvider, twitchProvider, twoFactor, vercelProvider, vkProvider, wechatProvider, withRateLimit, yahooProvider, zoomProvider } from './auth/index.js';
7
+ export { constantTimeEqual, fromBase64Url, fromHex, generateId, hmacSha1Raw, hmacSha256, hmacSha256Raw, importHmacKey, pbkdf2Hash, pbkdf2Verify, randomBytes, randomBytesHex, sha1, sha256, sha256Raw, toBase64Url, toHex } from './crypto/index.js';
8
+ import { RedirectChainManager } from './redirect/index.js';
9
+ export { RedirectChainState, RedirectConfig, RedirectEntry, createRedirectChain } from './redirect/index.js';
10
+ export { PermissionTemplateName, createPermissionEngine, getPermissionTemplate, permissionTemplates } from './permission/index.js';
11
+ export { AuditCredentialSubject, AuditExportResult, AuditRecord, CredentialFormat, CredentialStatus, CredentialStatusSchema, CredentialSubject, CredentialSubjectSchema, DelegationLink, ExportAuditOptions, ExtractedPermissions, IssueAgentCredentialInput, IssueDelegationCredentialInput, IssuePermissionCredentialInput, KAVACH_AGENT_CREDENTIAL, KAVACH_DELEGATION_CREDENTIAL, KAVACH_PERMISSION_CREDENTIAL, Proof, ProofSchema, THEAUTH_AUDIT_CONTEXT, THEAUTH_AUDIT_CREDENTIAL, VCIssuer, VCIssuerConfig, VCJwtPayload, VCVerifier, VCVerifierConfig, VC_CONTEXT_V1, VC_CONTEXT_V2, VC_TYPE_CREDENTIAL, VC_TYPE_PRESENTATION, VerifiableCredential, VerifiableCredentialSchema, VerifiablePresentation, VerifiablePresentationSchema, VerifiedCredential, VerifiedPresentation, createVCIssuer, createVCVerifier, exportAuditAsVC, listAuditRecords } from './vc/index.js';
12
+ import 'drizzle-orm/sqlite-core';
13
+ import './types-BiUe9e8u.js';
14
+ import 'zod';
15
+ import './standards/index.js';
16
+ import 'jose';
17
+
18
+ interface PrivilegeFinding {
19
+ type: "wildcard_permission" | "unused_permission" | "overly_broad" | "no_constraints" | "no_expiry";
20
+ severity: "info" | "warning" | "critical";
21
+ description: string;
22
+ permission?: {
23
+ resource: string;
24
+ actions: string[];
25
+ };
26
+ }
27
+ interface PrivilegeAnalysis {
28
+ agentId: string;
29
+ agentName: string;
30
+ score: "minimal" | "appropriate" | "over-permissioned" | "wildcard-heavy";
31
+ findings: PrivilegeFinding[];
32
+ recommendations: string[];
33
+ }
34
+ interface PrivilegeSummary {
35
+ total: number;
36
+ byScore: Record<string, number>;
37
+ criticalFindings: number;
38
+ }
39
+ /**
40
+ * Create the least-privilege analyzer.
41
+ *
42
+ * Scans agent permissions against actual audit log usage and surfaces
43
+ * over-permissioned agents, wildcards, and unused grants.
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * const analyzer = createPrivilegeAnalyzer(db);
48
+ * const report = await analyzer.analyzeAgent('agent-123');
49
+ * console.log(report.score, report.recommendations);
50
+ * ```
51
+ */
52
+ declare function createPrivilegeAnalyzer(db: Database): {
53
+ analyzeAgent: (agentId: string, options?: {
54
+ since?: Date;
55
+ }) => Promise<PrivilegeAnalysis>;
56
+ analyzeAll: (options?: {
57
+ since?: Date;
58
+ }) => Promise<PrivilegeAnalysis[]>;
59
+ getSummary: () => Promise<PrivilegeSummary>;
60
+ };
61
+ type PrivilegeAnalyzer = ReturnType<typeof createPrivilegeAnalyzer>;
62
+
63
+ /**
64
+ * Create TheAuth tables if they do not already exist.
65
+ *
66
+ * Uses `CREATE TABLE IF NOT EXISTS` so it is safe to call on every startup.
67
+ * Tables are created in dependency order (no forward-reference FK issues).
68
+ *
69
+ * When `config` is provided, only tables required by the configured features
70
+ * are created. When omitted, all tables are created (backward-compatible
71
+ * behaviour for callers that do not pass a config).
72
+ *
73
+ * @param db Drizzle database instance returned by `createDatabase()`.
74
+ * @param provider The database provider used to build the correct DDL syntax.
75
+ * @param config Optional KavachConfig used to determine which feature tables
76
+ * to create. When absent, all tables are created.
77
+ *
78
+ * @example
79
+ * ```typescript
80
+ * const db = await createDatabase({ provider: 'postgres', url: process.env.DATABASE_URL });
81
+ * await createTables(db, 'postgres');
82
+ * ```
83
+ */
84
+ declare function createTables(db: Database, provider: DatabaseConfig["provider"], config?: KavachConfig): Promise<void>;
85
+
86
+ interface DelegationModuleConfig {
87
+ db: Database;
88
+ }
89
+ /**
90
+ * Create the delegation module.
91
+ * Handles agent-to-agent permission delegation with chain tracking.
92
+ */
93
+ declare function createDelegationModule(config: DelegationModuleConfig): {
94
+ delegate: (input: DelegateInput, parentPermissions: Permission[]) => Promise<DelegationChain>;
95
+ revokeDelegation: (chainId: string) => Promise<void>;
96
+ getEffectivePermissions: (agentId: string) => Promise<Permission[]>;
97
+ listChains: (agentId: string) => Promise<DelegationChain[]>;
98
+ };
99
+
100
+ /**
101
+ * Build a W3C DID Document for a did:key identifier.
102
+ */
103
+ declare function buildDidDocument(did: string, publicKeyJwk: JsonWebKey): DidDocument;
104
+ /**
105
+ * Generate a new did:key identity using Ed25519.
106
+ *
107
+ * Returns the DID, key pair (JWK format), and auto-generated DID document.
108
+ * The private key is returned to the caller and must be stored securely —
109
+ * it is never persisted by TheAuth.
110
+ */
111
+ declare function generateDidKey(): Promise<DidKeyPair>;
112
+ /**
113
+ * Resolve a did:key to its DID document.
114
+ *
115
+ * did:key is self-describing — the public key is embedded in the identifier
116
+ * via multibase(multicodec(raw_key)), so resolution is purely local.
117
+ * Returns null if the DID is malformed.
118
+ */
119
+ declare function resolveDidKey(did: string): DidDocument | null;
120
+
121
+ /**
122
+ * Create the DID module.
123
+ *
124
+ * Provides W3C DID generation (did:key and did:web), storage of the public
125
+ * key + DID document in the database, and signing / verification helpers.
126
+ * Private keys are never stored — they are returned to the caller on
127
+ * generation and must be stored securely elsewhere.
128
+ */
129
+ declare function createDidModule(db: Database, config?: {
130
+ web?: DidWebConfig;
131
+ }): {
132
+ generateKey: (agentId: string) => Promise<{
133
+ agentDid: AgentDid;
134
+ privateKeyJwk: JsonWebKey;
135
+ }>;
136
+ generateWeb: (agentId: string) => Promise<{
137
+ agentDid: AgentDid;
138
+ privateKeyJwk: JsonWebKey;
139
+ }>;
140
+ resolve: (did: string) => Promise<DidDocument | null>;
141
+ getAgentDid: (agentId: string) => Promise<AgentDid | null>;
142
+ sign: (agentId: string, payload: Record<string, unknown>, privateKeyJwk: JsonWebKey) => Promise<SignedPayload>;
143
+ verify: (jws: string, did?: string) => Promise<VerificationResult>;
144
+ createPresentation: (options: {
145
+ agentId: string;
146
+ privateKeyJwk: JsonWebKey;
147
+ capabilities: string[];
148
+ audience?: string;
149
+ expiresIn?: number;
150
+ }) => Promise<string>;
151
+ verifyPresentation: (jwt: string) => Promise<VerificationResult & {
152
+ capabilities?: string[];
153
+ }>;
154
+ };
155
+ type DidModule = ReturnType<typeof createDidModule>;
156
+
157
+ /**
158
+ * Sign a payload as a compact JWS using the agent's DID private key.
159
+ *
160
+ * The JWT header embeds the DID as `iss` and the key fragment as `kid`.
161
+ * Algorithm is always EdDSA (Ed25519).
162
+ */
163
+ declare function signPayload(payload: Record<string, unknown>, privateKeyJwk: JsonWebKey, did: string): Promise<SignedPayload>;
164
+ /**
165
+ * Verify a signed payload using a known public key JWK.
166
+ *
167
+ * Extracts the DID from the `iss` claim and returns the decoded payload
168
+ * on success. Callers are responsible for resolving the correct public key
169
+ * from the DID document before calling this function.
170
+ */
171
+ declare function verifyPayload(jws: string, publicKeyJwk: JsonWebKey): Promise<VerificationResult>;
172
+ /**
173
+ * Create a verifiable presentation JWT.
174
+ *
175
+ * The presentation proves the agent's identity and lists the capabilities
176
+ * they are asserting. It is audience-bound and short-lived by default.
177
+ */
178
+ declare function createPresentation(options: {
179
+ agentId: string;
180
+ did: string;
181
+ privateKeyJwk: JsonWebKey;
182
+ capabilities: string[];
183
+ audience?: string;
184
+ expiresIn?: number;
185
+ }): Promise<string>;
186
+ /**
187
+ * Verify a presentation JWT and extract the claims.
188
+ *
189
+ * Returns the agentId, DID, and capabilities on success.
190
+ */
191
+ declare function verifyPresentation(jwt: string, publicKeyJwk: JsonWebKey): Promise<{
192
+ valid: boolean;
193
+ agentId?: string;
194
+ did?: string;
195
+ capabilities?: string[];
196
+ error?: string;
197
+ }>;
198
+
199
+ /**
200
+ * Generate a did:web identity for an agent.
201
+ *
202
+ * Internally generates an Ed25519 key pair and builds a DID document
203
+ * using the did:web identifier derived from the domain config.
204
+ * The private key is returned to the caller and must be stored securely.
205
+ */
206
+ declare function generateDidWeb(config: DidWebConfig, agentId: string): Promise<DidKeyPair>;
207
+ /**
208
+ * Get the HTTPS URL where a did:web document should be hosted.
209
+ *
210
+ * did:web:example.com → https://example.com/.well-known/did.json
211
+ * did:web:example.com:agents:123 → https://example.com/agents/123/did.json
212
+ */
213
+ declare function getDidWebUrl(did: string): string;
214
+ /**
215
+ * Resolve a did:web by fetching the DID document from the web.
216
+ *
217
+ * Returns null if the fetch fails or the document is malformed.
218
+ * In production, callers should add caching and error handling.
219
+ */
220
+ declare function resolveDidWeb(did: string): Promise<DidDocument | null>;
221
+
222
+ interface EmailTemplate {
223
+ subject: string;
224
+ text: string;
225
+ html: string;
226
+ }
227
+ type EmailTemplateName = "verification" | "passwordReset" | "magicLink" | "emailOtp" | "invitation" | "welcome";
228
+ interface EmailTemplateConfig {
229
+ appName?: string;
230
+ appUrl?: string;
231
+ /** Custom templates override defaults */
232
+ templates?: Partial<Record<EmailTemplateName, (vars: Record<string, string>) => EmailTemplate>>;
233
+ }
234
+ interface EmailTemplates {
235
+ render(name: EmailTemplateName, vars: Record<string, string>): EmailTemplate;
236
+ }
237
+ declare function createEmailTemplates(config?: EmailTemplateConfig): EmailTemplates;
238
+
239
+ interface TranslationKeys {
240
+ "auth.invalidCredentials": string;
241
+ "auth.emailNotVerified": string;
242
+ "auth.accountLocked": string;
243
+ "auth.rateLimited": string;
244
+ "auth.emailAlreadyExists": string;
245
+ "auth.weakPassword": string;
246
+ "auth.tokenExpired": string;
247
+ "auth.tokenInvalid": string;
248
+ "auth.unauthorized": string;
249
+ "agent.notFound": string;
250
+ "agent.revoked": string;
251
+ "agent.limitExceeded": string;
252
+ "agent.permissionDenied": string;
253
+ "twoFactor.invalidCode": string;
254
+ "twoFactor.alreadyEnabled": string;
255
+ "twoFactor.notEnabled": string;
256
+ "email.verification.subject": string;
257
+ "email.passwordReset.subject": string;
258
+ "email.magicLink.subject": string;
259
+ "email.otp.subject": string;
260
+ "email.invitation.subject": string;
261
+ "email.welcome.subject": string;
262
+ "general.serverError": string;
263
+ "general.badRequest": string;
264
+ "general.notFound": string;
265
+ }
266
+ interface I18nConfig {
267
+ /** Default locale (default: "en") */
268
+ defaultLocale?: string;
269
+ /** Custom translations merged on top of built-in defaults */
270
+ translations?: Record<string, Partial<TranslationKeys>>;
271
+ }
272
+ interface I18nModule {
273
+ /** Get a translated string, optionally for a specific locale */
274
+ t(key: keyof TranslationKeys, locale?: string): string;
275
+ /** Get a translated string with variable interpolation */
276
+ t(key: keyof TranslationKeys, vars: Record<string, string>, locale?: string): string;
277
+ /** Add or replace translations for a locale at runtime */
278
+ addLocale(locale: string, translations: Partial<TranslationKeys>): void;
279
+ /** Return all registered locale codes */
280
+ getLocales(): string[];
281
+ }
282
+ declare function createI18n(config?: I18nConfig): I18nModule;
283
+
284
+ declare const de: TranslationKeys;
285
+
286
+ declare const en: TranslationKeys;
287
+
288
+ declare const es: TranslationKeys;
289
+
290
+ declare const fr: TranslationKeys;
291
+
292
+ declare const ja: TranslationKeys;
293
+
294
+ declare const zh: TranslationKeys;
295
+
296
+ /**
297
+ * Create a TheAuth instance.
298
+ *
299
+ * The factory is **async** so it can open database connections for Postgres
300
+ * and MySQL (which require async driver initialisation) and optionally run
301
+ * `CREATE TABLE IF NOT EXISTS` for all schema tables.
302
+ *
303
+ * @example SQLite (simplest)
304
+ * ```typescript
305
+ * import { createKavach } from '@glinr/theauth';
306
+ *
307
+ * const kavach = await createKavach({
308
+ * database: { provider: 'sqlite', url: 'kavach.db' },
309
+ * });
310
+ * ```
311
+ *
312
+ * @example Postgres
313
+ * ```typescript
314
+ * const kavach = await createKavach({
315
+ * database: { provider: 'postgres', url: process.env.DATABASE_URL },
316
+ * });
317
+ * ```
318
+ *
319
+ * @example MySQL – skip auto-migration (tables managed externally)
320
+ * ```typescript
321
+ * const kavach = await createKavach({
322
+ * database: {
323
+ * provider: 'mysql',
324
+ * url: process.env.DATABASE_URL,
325
+ * skipMigrations: true,
326
+ * },
327
+ * });
328
+ * ```
329
+ */
330
+ declare function createKavach(config: KavachConfig): Promise<{
331
+ agent: {
332
+ create(input: CreateAgentInput): ReturnType<(input: CreateAgentInput) => Promise<AgentIdentity & {
333
+ token: string;
334
+ }>>;
335
+ revoke(agentId: string): ReturnType<(agentId: string) => Promise<void>>;
336
+ rotate(agentId: string): ReturnType<(agentId: string) => Promise<AgentIdentity & {
337
+ token: string;
338
+ }>>;
339
+ get: (agentId: string) => Promise<AgentIdentity | null>;
340
+ list: (filter?: AgentFilter) => Promise<AgentIdentity[]>;
341
+ update: (agentId: string, input: UpdateAgentInput) => Promise<AgentIdentity>;
342
+ validateToken: (token: string) => Promise<AgentIdentity | null>;
343
+ };
344
+ authorize: (agentId: string, request: AuthorizeRequest, context?: RequestContext) => Promise<AuthorizeResult>;
345
+ authorizeByToken: (token: string, request: AuthorizeRequest, context?: RequestContext) => Promise<AuthorizeResult>;
346
+ delegate: (input: DelegateInput) => Promise<DelegationChain>;
347
+ delegation: {
348
+ revoke: (chainId: string) => Promise<void>;
349
+ getEffectivePermissions: (agentId: string) => Promise<Permission[]>;
350
+ listChains: (agentId: string) => Promise<DelegationChain[]>;
351
+ };
352
+ audit: {
353
+ query: (filter: AuditFilter) => Promise<AuditEntry[]>;
354
+ export: (options: AuditExportOptions) => Promise<string>;
355
+ cleanup: (options: {
356
+ retentionDays: number;
357
+ }) => Promise<{
358
+ deleted: number;
359
+ }>;
360
+ };
361
+ /**
362
+ * MCP server registration.
363
+ *
364
+ * Register and look up MCP tool servers. Uses the `kavach_mcp_servers`
365
+ * database table — no separate in-memory store needed.
366
+ */
367
+ mcp: {
368
+ /**
369
+ * Register a new MCP tool server.
370
+ *
371
+ * Persists the server entry to the `kavach_mcp_servers` table.
372
+ * The returned record includes the generated `id` and `createdAt`.
373
+ */
374
+ register(input: McpServerInput): Promise<McpServer>;
375
+ /**
376
+ * List all registered MCP servers (active and inactive).
377
+ */
378
+ list(): Promise<McpServer[]>;
379
+ /**
380
+ * Get a single MCP server by ID. Returns null when not found.
381
+ */
382
+ get(id: string): Promise<McpServer | null>;
383
+ };
384
+ /**
385
+ * Least-privilege analyzer.
386
+ *
387
+ * Compare agent permissions against actual audit log usage to surface
388
+ * wildcards, unused grants, and over-permissioned identities.
389
+ */
390
+ analyzer: {
391
+ analyzeAgent: (agentId: string, options?: {
392
+ since?: Date;
393
+ }) => Promise<PrivilegeAnalysis>;
394
+ analyzeAll: (options?: {
395
+ since?: Date;
396
+ }) => Promise<PrivilegeAnalysis[]>;
397
+ getSummary: () => Promise<PrivilegeSummary>;
398
+ };
399
+ /**
400
+ * Human auth integration.
401
+ *
402
+ * `resolveUser` extracts the authenticated human from an inbound HTTP
403
+ * request via the configured adapter. `session` is a full session
404
+ * manager (create / validate / revoke) when `auth.session` was passed
405
+ * to `createKavach()`.
406
+ *
407
+ * @example
408
+ * ```typescript
409
+ * app.use(async (req, res, next) => {
410
+ * const user = await kavach.auth.resolveUser(req);
411
+ * if (!user) return res.status(401).json({ error: 'Unauthorized' });
412
+ * req.user = user;
413
+ * next();
414
+ * });
415
+ * ```
416
+ */
417
+ auth: {
418
+ resolveUser(request: Request): Promise<ResolvedUser | null>;
419
+ session: SessionManager | null;
420
+ };
421
+ /**
422
+ * Resolve a human user from an incoming HTTP request.
423
+ *
424
+ * @deprecated Use `kavach.auth.resolveUser(request)` instead.
425
+ */
426
+ resolveUser(request: Request): Promise<ResolvedUser | null>;
427
+ /** Direct database access for advanced usage */
428
+ db: Database;
429
+ /**
430
+ * Multi-tenant isolation.
431
+ *
432
+ * Create and manage tenants (organizations) that share a single
433
+ * TheAuth instance with full data isolation. Agents can be scoped
434
+ * to a tenant via `tenantId`.
435
+ */
436
+ tenant: {
437
+ create: (input: CreateTenantInput) => Promise<Tenant>;
438
+ get: (tenantId: string) => Promise<Tenant | null>;
439
+ getBySlug: (slug: string) => Promise<Tenant | null>;
440
+ list: () => Promise<Tenant[]>;
441
+ update: (tenantId: string, updates: Partial<CreateTenantInput>) => Promise<Tenant>;
442
+ suspend: (tenantId: string) => Promise<void>;
443
+ activate: (tenantId: string) => Promise<void>;
444
+ };
445
+ /**
446
+ * Agent execution budget policies.
447
+ *
448
+ * Set spending caps (token cost, call counts) per agent, user, or
449
+ * tenant. Exceeded policies trigger a configurable action: warn,
450
+ * throttle, block, or revoke.
451
+ */
452
+ policies: {
453
+ create: (input: CreatePolicyInput) => Promise<BudgetPolicy>;
454
+ get: (policyId: string) => Promise<BudgetPolicy | null>;
455
+ list: (filters?: PolicyFilters) => Promise<BudgetPolicy[]>;
456
+ update: (policyId: string, updates: Partial<BudgetPolicy>) => Promise<BudgetPolicy>;
457
+ remove: (policyId: string) => Promise<void>;
458
+ checkBudget: (agentId: string, tokensCost?: number) => Promise<{
459
+ allowed: boolean;
460
+ reason?: string;
461
+ policy?: BudgetPolicy;
462
+ }>;
463
+ recordUsage: (agentId: string, tokensCost?: number) => Promise<void>;
464
+ resetDaily: () => Promise<{
465
+ reset: number;
466
+ }>;
467
+ resetMonthly: () => Promise<{
468
+ reset: number;
469
+ }>;
470
+ };
471
+ /**
472
+ * CIBA-style async human approval flows.
473
+ *
474
+ * Create pending approval requests, notify humans via webhook or
475
+ * custom handler, and resolve them with approve / deny.
476
+ */
477
+ approval: {
478
+ request: (input: {
479
+ agentId: string;
480
+ userId: string;
481
+ action: string;
482
+ resource: string;
483
+ arguments?: Record<string, unknown>;
484
+ }) => Promise<ApprovalRequest>;
485
+ approve: (requestId: string, respondedBy?: string) => Promise<ApprovalRequest>;
486
+ deny: (requestId: string, respondedBy?: string) => Promise<ApprovalRequest>;
487
+ get: (requestId: string) => Promise<ApprovalRequest | null>;
488
+ listPending: (userId?: string) => Promise<ApprovalRequest[]>;
489
+ cleanup: () => Promise<{
490
+ expired: number;
491
+ }>;
492
+ };
493
+ /**
494
+ * Graduated autonomy trust scoring.
495
+ *
496
+ * Compute and persist 0-100 trust scores derived from audit history,
497
+ * mapped to five levels: untrusted, limited, standard, trusted, elevated.
498
+ */
499
+ trust: {
500
+ computeScore: (agentId: string) => Promise<TrustScore>;
501
+ getScore: (agentId: string) => Promise<TrustScore | null>;
502
+ computeAll: () => Promise<TrustScore[]>;
503
+ getScores: (filters?: {
504
+ level?: string;
505
+ minScore?: number;
506
+ }) => Promise<TrustScore[]>;
507
+ };
508
+ /**
509
+ * W3C Decentralized Identifiers (DID) for agents.
510
+ *
511
+ * Generate did:key or did:web identities, sign payloads, and verify
512
+ * signatures. Private keys are never stored — they are returned to
513
+ * the caller on generation and must be stored securely.
514
+ *
515
+ * @example
516
+ * ```typescript
517
+ * const { agentDid, privateKeyJwk } = await kavach.did.generateKey(agentId);
518
+ * const signed = await kavach.did.sign(agentId, { action: 'read' }, privateKeyJwk);
519
+ * const result = await kavach.did.verify(signed.jws, agentDid.did);
520
+ * ```
521
+ */
522
+ did: {
523
+ generateKey: (agentId: string) => Promise<{
524
+ agentDid: AgentDid;
525
+ privateKeyJwk: JsonWebKey;
526
+ }>;
527
+ generateWeb: (agentId: string) => Promise<{
528
+ agentDid: AgentDid;
529
+ privateKeyJwk: JsonWebKey;
530
+ }>;
531
+ resolve: (did: string) => Promise<DidDocument | null>;
532
+ getAgentDid: (agentId: string) => Promise<AgentDid | null>;
533
+ sign: (agentId: string, payload: Record<string, unknown>, privateKeyJwk: JsonWebKey) => Promise<SignedPayload>;
534
+ verify: (jws: string, did?: string) => Promise<VerificationResult>;
535
+ createPresentation: (options: {
536
+ agentId: string;
537
+ privateKeyJwk: JsonWebKey;
538
+ capabilities: string[];
539
+ audience?: string;
540
+ expiresIn?: number;
541
+ }) => Promise<string>;
542
+ verifyPresentation: (jwt: string) => Promise<VerificationResult & {
543
+ capabilities?: string[];
544
+ }>;
545
+ };
546
+ /**
547
+ * Magic link (passwordless email) authentication.
548
+ *
549
+ * Null when `magicLink` config was not provided or `auth.session` is not
550
+ * configured (sessions are required to issue tokens on verification).
551
+ *
552
+ * @example
553
+ * ```typescript
554
+ * // In your route handler
555
+ * const response = await kavach.magicLink?.handleRequest(request);
556
+ * if (response) return response;
557
+ * ```
558
+ */
559
+ magicLink: MagicLinkModule | null;
560
+ /**
561
+ * Email OTP (one-time password) authentication.
562
+ *
563
+ * Null when `emailOtp` config was not provided or `auth.session` is not
564
+ * configured.
565
+ *
566
+ * @example
567
+ * ```typescript
568
+ * const response = await kavach.emailOtp?.handleRequest(request);
569
+ * if (response) return response;
570
+ * ```
571
+ */
572
+ emailOtp: EmailOtpModule | null;
573
+ /**
574
+ * TOTP two-factor authentication.
575
+ *
576
+ * Null when `totp` config was not provided.
577
+ *
578
+ * @example
579
+ * ```typescript
580
+ * // On setup (show QR code to user)
581
+ * const { secret, uri, backupCodes } = await kavach.totp.setup(userId);
582
+ *
583
+ * // After user scans QR and enters code
584
+ * const { enabled } = await kavach.totp.enable(userId, totpCode);
585
+ *
586
+ * // On login (after password check)
587
+ * const { valid } = await kavach.totp.verify(userId, totpCode);
588
+ * ```
589
+ */
590
+ totp: TotpModule | null;
591
+ /**
592
+ * Passkey / WebAuthn authentication.
593
+ *
594
+ * Null when `passkey` config was not provided.
595
+ *
596
+ * @example
597
+ * ```typescript
598
+ * // Registration — step 1: get options, send to browser
599
+ * const options = await kavach.passkey.getRegistrationOptions(userId, userName);
600
+ *
601
+ * // Registration — step 2: verify browser response
602
+ * const { credential } = await kavach.passkey.verifyRegistration(userId, response);
603
+ *
604
+ * // Authentication — step 1: get options
605
+ * const options = await kavach.passkey.getAuthenticationOptions(userId);
606
+ *
607
+ * // Authentication — step 2: verify browser response
608
+ * const result = await kavach.passkey.verifyAuthentication(response);
609
+ * if (result) console.log('Authenticated user:', result.userId);
610
+ * ```
611
+ */
612
+ passkey: PasskeyModule | null;
613
+ /**
614
+ * Organizations + RBAC.
615
+ *
616
+ * Null when `org` config was not provided.
617
+ *
618
+ * @example
619
+ * ```typescript
620
+ * const org = await kavach.org?.create({ name: 'Acme', slug: 'acme', ownerId: userId });
621
+ * const allowed = await kavach.org?.hasPermission(org.id, userId, 'agents:create');
622
+ * ```
623
+ */
624
+ org: OrgModule | null;
625
+ /**
626
+ * SSO (SAML 2.0 + OIDC) enterprise authentication.
627
+ *
628
+ * Null when `sso` config was not provided.
629
+ *
630
+ * @example
631
+ * ```typescript
632
+ * const conn = await kavach.sso?.createConnection({ orgId, providerId: 'okta', type: 'saml', domain: 'acme.com' });
633
+ * const url = await kavach.sso?.getSamlAuthUrl(conn.id);
634
+ * ```
635
+ */
636
+ sso: SsoModule | null;
637
+ /**
638
+ * Admin module.
639
+ *
640
+ * Null when `admin` config was not provided.
641
+ *
642
+ * @example
643
+ * ```typescript
644
+ * await kavach.admin?.banUser(userId, 'Spam');
645
+ * const { session } = await kavach.admin?.impersonate(adminId, userId);
646
+ * ```
647
+ */
648
+ admin: AdminModule | null;
649
+ /**
650
+ * API key management.
651
+ *
652
+ * Null when `apiKeys` config was not provided.
653
+ *
654
+ * @example
655
+ * ```typescript
656
+ * const { key, apiKey } = await kavach.apiKeys?.create({ userId, name: 'CI', permissions: ['agents:read'] });
657
+ * const result = await kavach.apiKeys?.validate(key);
658
+ * ```
659
+ */
660
+ apiKeys: ApiKeyManagerModule | null;
661
+ /**
662
+ * Username + password authentication.
663
+ *
664
+ * Null when `username` config was not provided or `auth.session` is not
665
+ * configured (sessions are required to issue tokens on sign-in/up).
666
+ *
667
+ * @example
668
+ * ```typescript
669
+ * const response = await kavach.username?.handleRequest(request);
670
+ * if (response) return response;
671
+ * ```
672
+ */
673
+ username: UsernameAuthModule | null;
674
+ /**
675
+ * Password reset (forgot password + reset password).
676
+ *
677
+ * Null when `passwordReset` config was not provided or `auth.session`
678
+ * is not configured.
679
+ *
680
+ * @example
681
+ * ```typescript
682
+ * // In your route handler
683
+ * const response = await kavach.passwordReset?.handleRequest(request);
684
+ * if (response) return response;
685
+ *
686
+ * // Or programmatically
687
+ * await kavach.passwordReset?.requestReset('alice@example.com');
688
+ * await kavach.passwordReset?.resetPassword(token, 'new-password');
689
+ * ```
690
+ */
691
+ passwordReset: PasswordResetModule | null;
692
+ /**
693
+ * Email address verification.
694
+ *
695
+ * Null when `emailVerification` config was not provided.
696
+ *
697
+ * @example
698
+ * ```typescript
699
+ * // Send a verification email after sign-up
700
+ * await kavach.emailVerification?.sendVerification(userId, email);
701
+ *
702
+ * // Confirm from the link in the email
703
+ * const result = await kavach.emailVerification?.verify(token);
704
+ *
705
+ * // Check status
706
+ * const verified = await kavach.emailVerification?.isVerified(userId);
707
+ * ```
708
+ */
709
+ emailVerification: EmailVerificationModule | null;
710
+ /**
711
+ * One-time tokens (email verify, password reset, invitations, custom).
712
+ *
713
+ * Always available. Used internally by password reset but exposed for
714
+ * custom flows (email verification, invitation links, etc.).
715
+ */
716
+ oneTimeTokens: OneTimeTokenModule;
717
+ /**
718
+ * Session freshness enforcement for sensitive operations.
719
+ *
720
+ * Use as middleware before password changes, passkey registration,
721
+ * billing updates, or any action that requires a recently-authenticated
722
+ * session rather than an auto-refreshed one.
723
+ *
724
+ * @example
725
+ * ```typescript
726
+ * const stale = kavach.sessionFreshness.guard(session);
727
+ * if (stale) return stale; // 403 SESSION_NOT_FRESH
728
+ * ```
729
+ */
730
+ sessionFreshness: SessionFreshnessModule;
731
+ /**
732
+ * Phone number (SMS OTP) authentication.
733
+ *
734
+ * Null when `phone` config was not provided or `auth.session` is not
735
+ * configured.
736
+ *
737
+ * @example
738
+ * ```typescript
739
+ * const response = await kavach.phone?.handleRequest(request);
740
+ * if (response) return response;
741
+ * ```
742
+ */
743
+ phone: PhoneAuthModule | null;
744
+ /**
745
+ * Captcha integration (reCAPTCHA, hCaptcha, Cloudflare Turnstile).
746
+ *
747
+ * Null when `captcha` config was not provided.
748
+ *
749
+ * @example
750
+ * ```typescript
751
+ * const result = await kavach.captcha?.verify(token, ip);
752
+ * if (!result?.success) return new Response('Captcha failed', { status: 403 });
753
+ * ```
754
+ */
755
+ captcha: CaptchaModule | null;
756
+ /**
757
+ * Webhook system.
758
+ *
759
+ * Null when `webhooks` config was not provided or the array is empty.
760
+ *
761
+ * @example
762
+ * ```typescript
763
+ * kavach.webhooks?.emit('user.created', { userId: user.id });
764
+ * ```
765
+ */
766
+ webhooks: WebhookModule$1 | null;
767
+ /**
768
+ * Redirect chain manager.
769
+ *
770
+ * Capture the user's original destination before auth redirects, push
771
+ * intermediate steps (onboarding, email verification), and pop them
772
+ * back in order. Cookie-based, works across page transitions and tabs.
773
+ *
774
+ * @example
775
+ * ```typescript
776
+ * // In auth middleware — save where the user was going
777
+ * const setCookie = kavach.redirects.capture(request);
778
+ * return new Response(null, { status: 302, headers: { Location: '/sign-in', 'Set-Cookie': setCookie } });
779
+ *
780
+ * // After sign-in — send user to their original destination
781
+ * const { url, clearCookie } = kavach.redirects.pop(request);
782
+ * const headers: Record<string, string> = { Location: url };
783
+ * if (clearCookie) headers['Set-Cookie'] = clearCookie;
784
+ * return new Response(null, { status: 302, headers });
785
+ * ```
786
+ */
787
+ redirects: RedirectChainManager;
788
+ /**
789
+ * Unified policy engine.
790
+ *
791
+ * Single decision point that combines RBAC role expansion, ABAC constraint
792
+ * evaluation, and ReBAC graph queries. Backed by a process-local LRU cache
793
+ * with deterministic invalidation.
794
+ *
795
+ * @example
796
+ * ```typescript
797
+ * const decision = await kavach.policy.evaluate({
798
+ * subject: { agentId: 'agent-abc' },
799
+ * action: 'read',
800
+ * resource: 'tool:github:list_issues',
801
+ * });
802
+ * if (!decision.allowed) throw new Error(decision.reason);
803
+ *
804
+ * // Flush cached decisions after a permission change
805
+ * kavach.policy.invalidate({ agentId: 'agent-abc' });
806
+ *
807
+ * // Inspect cache health
808
+ * const { hits, misses, size, evictions } = kavach.policy.stats();
809
+ * ```
810
+ */
811
+ policy: {
812
+ evaluate: (input: EvaluateInput) => Promise<PolicyDecision>;
813
+ invalidate: (scope: InvalidateScope) => void;
814
+ stats: () => PolicyCacheStats;
815
+ };
816
+ /**
817
+ * Plugin system.
818
+ *
819
+ * Route incoming HTTP requests through plugin-registered endpoints,
820
+ * retrieve all endpoints for adapter mounting, or access plugin-provided
821
+ * context values.
822
+ *
823
+ * @example
824
+ * ```typescript
825
+ * // In a framework adapter
826
+ * app.all('/kavach/*', async (req) => {
827
+ * const response = await kavach.plugins.handleRequest(req);
828
+ * if (response) return response;
829
+ * return new Response('Not Found', { status: 404 });
830
+ * });
831
+ * ```
832
+ */
833
+ plugins: {
834
+ /** Route a request through plugin endpoints. Returns null if no plugin handles it. */
835
+ handleRequest(request: Request, basePath?: string): Promise<Response | null>;
836
+ /** Get all endpoints registered by plugins (for framework adapter mounting). */
837
+ getEndpoints(): PluginEndpoint[];
838
+ /** Get the merged plugin context (values returned from plugin init). */
839
+ getContext(): Record<string, unknown>;
840
+ /** Access the raw plugin registry (hooks, migrations, etc.). */
841
+ registry: PluginRegistry;
842
+ };
843
+ }>;
844
+ type Kavach = Awaited<ReturnType<typeof createKavach>>;
845
+
846
+ /**
847
+ * OpenAPI 3.1 specification generator for TheAuth REST API.
848
+ *
849
+ * This generates the spec that enables auto-generated SDKs
850
+ * for Python, Go, Java, Rust, etc. via OpenAPI codegen tools.
851
+ */
852
+ interface OpenAPISpec {
853
+ openapi: string;
854
+ info: {
855
+ title: string;
856
+ version: string;
857
+ description: string;
858
+ };
859
+ servers: Array<{
860
+ url: string;
861
+ description: string;
862
+ }>;
863
+ paths: Record<string, Record<string, PathOperation>>;
864
+ components: {
865
+ schemas: Record<string, SchemaObject>;
866
+ securitySchemes: Record<string, SecurityScheme>;
867
+ };
868
+ }
869
+ interface PathOperation {
870
+ summary: string;
871
+ operationId: string;
872
+ tags: string[];
873
+ security?: Array<Record<string, string[]>>;
874
+ parameters?: ParameterObject[];
875
+ requestBody?: {
876
+ required: boolean;
877
+ content: Record<string, {
878
+ schema: SchemaRef;
879
+ }>;
880
+ };
881
+ responses: Record<string, {
882
+ description: string;
883
+ content?: Record<string, {
884
+ schema: SchemaRef;
885
+ }>;
886
+ }>;
887
+ }
888
+ interface ParameterObject {
889
+ name: string;
890
+ in: "query" | "path" | "header";
891
+ required: boolean;
892
+ schema: SchemaRef;
893
+ }
894
+ interface SecurityScheme {
895
+ type: string;
896
+ scheme?: string;
897
+ bearerFormat?: string;
898
+ }
899
+ type SchemaRef = {
900
+ $ref: string;
901
+ } | SchemaObject;
902
+ interface SchemaObject {
903
+ type?: string;
904
+ properties?: Record<string, SchemaRef>;
905
+ required?: string[];
906
+ items?: SchemaRef;
907
+ enum?: string[];
908
+ description?: string;
909
+ format?: string;
910
+ nullable?: boolean;
911
+ }
912
+ /**
913
+ * Generate the full OpenAPI 3.1 specification for the TheAuth REST API.
914
+ */
915
+ declare function generateOpenAPISpec(options?: {
916
+ baseUrl?: string;
917
+ version?: string;
918
+ }): OpenAPISpec;
919
+
920
+ /**
921
+ * Create a plugin router that matches requests to registered plugin endpoints.
922
+ *
923
+ * The router strips `basePath` from the request URL before matching so plugins
924
+ * register paths relative to the mount point (e.g. `/auth/sign-in` instead
925
+ * of `/api/kavach/auth/sign-in`).
926
+ */
927
+ declare function createPluginRouter(endpoints: PluginEndpoint[]): {
928
+ /** Try to handle a request. Returns Response if matched, null if not. */
929
+ handle: (request: Request, basePath: string, endpointCtx: EndpointContext) => Promise<Response | null>;
930
+ /** Get all registered endpoints (for adapter mounting) */
931
+ getEndpoints: () => PluginEndpoint[];
932
+ };
933
+
934
+ interface PluginRegistry {
935
+ endpoints: PluginEndpoint[];
936
+ migrations: string[];
937
+ hooks: {
938
+ onRequest: Array<NonNullable<KavachPlugin["hooks"]>["onRequest"]>;
939
+ onAuthenticate: Array<NonNullable<KavachPlugin["hooks"]>["onAuthenticate"]>;
940
+ onSessionCreate: Array<NonNullable<KavachPlugin["hooks"]>["onSessionCreate"]>;
941
+ onSessionRevoke: Array<NonNullable<KavachPlugin["hooks"]>["onSessionRevoke"]>;
942
+ };
943
+ pluginContext: Record<string, unknown>;
944
+ }
945
+ /**
946
+ * Initialize all plugins and collect their endpoints, migrations, and hooks
947
+ * into a single registry.
948
+ *
949
+ * Calls each plugin's `init()` in registration order. Migrations collected
950
+ * during init are executed before the registry is returned so that any
951
+ * subsequent requests can immediately use plugin tables.
952
+ */
953
+ declare function initializePlugins(plugins: KavachPlugin[], db: Database, config: KavachConfig, sessionManager: SessionManager | null): Promise<PluginRegistry>;
954
+
955
+ interface BudgetPolicy {
956
+ id: string;
957
+ agentId?: string;
958
+ userId?: string;
959
+ tenantId?: string;
960
+ limits: BudgetLimits;
961
+ currentUsage: BudgetUsage;
962
+ action: "warn" | "throttle" | "block" | "revoke";
963
+ status: "active" | "triggered" | "disabled";
964
+ createdAt: Date;
965
+ }
966
+ interface BudgetLimits {
967
+ maxTokensCostPerDay?: number;
968
+ maxTokensCostPerMonth?: number;
969
+ maxCallsPerDay?: number;
970
+ maxCallsPerMonth?: number;
971
+ }
972
+ interface BudgetUsage {
973
+ tokensCostToday: number;
974
+ tokensCostThisMonth: number;
975
+ callsToday: number;
976
+ callsThisMonth: number;
977
+ lastUpdated: string;
978
+ }
979
+ interface CreatePolicyInput {
980
+ agentId?: string;
981
+ userId?: string;
982
+ tenantId?: string;
983
+ limits: BudgetLimits;
984
+ action: "warn" | "throttle" | "block" | "revoke";
985
+ }
986
+ interface PolicyFilters {
987
+ agentId?: string;
988
+ userId?: string;
989
+ tenantId?: string;
990
+ }
991
+ declare function createPolicyModule(db: Database): {
992
+ create: (input: CreatePolicyInput) => Promise<BudgetPolicy>;
993
+ get: (policyId: string) => Promise<BudgetPolicy | null>;
994
+ list: (filters?: PolicyFilters) => Promise<BudgetPolicy[]>;
995
+ update: (policyId: string, updates: Partial<BudgetPolicy>) => Promise<BudgetPolicy>;
996
+ remove: (policyId: string) => Promise<void>;
997
+ checkBudget: (agentId: string, tokensCost?: number) => Promise<{
998
+ allowed: boolean;
999
+ reason?: string;
1000
+ policy?: BudgetPolicy;
1001
+ }>;
1002
+ recordUsage: (agentId: string, tokensCost?: number) => Promise<void>;
1003
+ resetDaily: () => Promise<{
1004
+ reset: number;
1005
+ }>;
1006
+ resetMonthly: () => Promise<{
1007
+ reset: number;
1008
+ }>;
1009
+ };
1010
+
1011
+ /**
1012
+ * Cookie serialization and parsing utilities for TheAuth.
1013
+ *
1014
+ * Pure functions that work with Web API `Request`/`Response` objects and
1015
+ * raw header strings. No framework dependencies.
1016
+ */
1017
+ type SameSite = "strict" | "lax" | "none";
1018
+ interface CookieOptions {
1019
+ /** Prevents JavaScript access to the cookie. Default: true. */
1020
+ httpOnly?: boolean;
1021
+ /**
1022
+ * Restricts transmission to HTTPS. Default: true in production
1023
+ * (when `NODE_ENV === 'production'`), false otherwise.
1024
+ */
1025
+ secure?: boolean;
1026
+ /** Controls cross-site sending. Default: 'lax'. */
1027
+ sameSite?: SameSite;
1028
+ /** Cookie scope path. Default: '/'. */
1029
+ path?: string;
1030
+ /** Cookie scope domain (omitted when not set). */
1031
+ domain?: string;
1032
+ /** Lifetime in seconds from now. Sets both Max-Age and Expires. */
1033
+ maxAge?: number;
1034
+ /** Absolute expiry date (overridden by maxAge when both are set). */
1035
+ expires?: Date;
1036
+ /** Partitioned attribute (CHIPS). */
1037
+ partitioned?: boolean;
1038
+ }
1039
+ /**
1040
+ * Serialize a cookie name/value pair into a `Set-Cookie` header string.
1041
+ *
1042
+ * @param name Cookie name. Must be a valid cookie-name token.
1043
+ * @param value Cookie value. Will be percent-encoded.
1044
+ * @param options Cookie attributes. Defaults to `httpOnly=true`, `secure`
1045
+ * based on `NODE_ENV`, `sameSite=lax`, `path=/`.
1046
+ */
1047
+ declare function serializeCookie(name: string, value: string, options?: CookieOptions): string;
1048
+ /**
1049
+ * Serialize a deletion cookie (zero Max-Age, past Expires) that will
1050
+ * instruct browsers to remove the named cookie.
1051
+ */
1052
+ declare function serializeCookieDeletion(name: string, options?: Omit<CookieOptions, "maxAge" | "expires">): string;
1053
+ /**
1054
+ * Parse a `Cookie` request header string into a name → value map.
1055
+ *
1056
+ * Values are percent-decoded. Unknown or malformed pairs are skipped
1057
+ * silently so that a single bad cookie does not break the entire request.
1058
+ *
1059
+ * @param header The raw value of the `Cookie` header (e.g. `"a=1; b=2"`).
1060
+ */
1061
+ declare function parseCookies(header: string): Record<string, string>;
1062
+ /**
1063
+ * Extract a single cookie value from a `Cookie` header string.
1064
+ *
1065
+ * Returns `undefined` when the cookie is absent.
1066
+ */
1067
+ declare function getCookie(header: string, name: string): string | undefined;
1068
+ /**
1069
+ * Extract cookies from a Web API `Request` object.
1070
+ */
1071
+ declare function parseCookiesFromRequest(request: Request): Record<string, string>;
1072
+
1073
+ /**
1074
+ * CSRF protection utilities for TheAuth.
1075
+ *
1076
+ * Implements two complementary defences:
1077
+ *
1078
+ * 1. **Origin/Referer validation** — checks the inbound request's `Origin`
1079
+ * (or `Referer` as fallback) against a caller-supplied allowlist. This
1080
+ * alone blocks the vast majority of CSRF attacks from browser clients.
1081
+ *
1082
+ * 2. **Double-submit cookie pattern** — a random token is stored in a cookie
1083
+ * AND submitted by the client as a request header (or body field). The
1084
+ * server verifies both values match using a timing-safe comparison.
1085
+ *
1086
+ * Use origin validation first; fall back to token comparison when the origin
1087
+ * header is absent (e.g. same-origin requests on some browsers, server-side
1088
+ * fetch).
1089
+ *
1090
+ * @example
1091
+ * ```typescript
1092
+ * import { generateCsrfToken, validateCsrfToken, validateOrigin } from './csrf.js';
1093
+ *
1094
+ * // On form render: store token in cookie, embed in hidden field.
1095
+ * const token = await generateCsrfToken();
1096
+ *
1097
+ * // On form submit:
1098
+ * const originOk = validateOrigin(request, ['https://app.example.com']);
1099
+ * const tokenOk = validateCsrfToken(submittedToken, cookieToken);
1100
+ * if (!originOk && !tokenOk) throw new Error('CSRF check failed');
1101
+ * ```
1102
+ */
1103
+ interface CsrfValidationResult {
1104
+ valid: boolean;
1105
+ reason?: string;
1106
+ }
1107
+ /**
1108
+ * Generate a cryptographically random CSRF token.
1109
+ *
1110
+ * Uses `crypto.getRandomValues` (Web Crypto API) so it works in both
1111
+ * Node.js ≥ 19 and browser/edge runtimes.
1112
+ *
1113
+ * Returns a URL-safe base64 string (~43 chars).
1114
+ */
1115
+ declare function generateCsrfToken(): string;
1116
+ /**
1117
+ * Validate a CSRF token from the request against the value stored in the
1118
+ * cookie using a constant-time comparison to prevent timing attacks.
1119
+ *
1120
+ * Both `requestToken` and `cookieToken` must be non-empty strings produced
1121
+ * by `generateCsrfToken()`. Any mismatch returns `{ valid: false }`.
1122
+ *
1123
+ * @param requestToken Token submitted with the request (header / body).
1124
+ * @param cookieToken Token read from the CSRF cookie.
1125
+ */
1126
+ declare function validateCsrfToken(requestToken: string, cookieToken: string): CsrfValidationResult;
1127
+ /**
1128
+ * Validate the `Origin` (or `Referer` fallback) header of an incoming
1129
+ * request against a list of trusted origins.
1130
+ *
1131
+ * Rules:
1132
+ * - If `Origin` is present and matches a trusted origin → valid.
1133
+ * - If `Origin` is `"null"` (opaque origin) → invalid.
1134
+ * - If `Origin` is absent, falls back to the `Referer` header.
1135
+ * - If neither header is present → result depends on `allowMissingOrigin`.
1136
+ *
1137
+ * @param request Incoming Web API `Request`.
1138
+ * @param trustedOrigins Array of allowed origins, e.g. `['https://app.example.com']`.
1139
+ * Trailing slashes are stripped before comparison.
1140
+ * @param allowMissingOrigin When `true`, requests without an `Origin` or
1141
+ * `Referer` header are considered valid (useful for
1142
+ * server-to-server calls). Defaults to `false`.
1143
+ */
1144
+ declare function validateOrigin(request: Request, trustedOrigins: string[], allowMissingOrigin?: boolean): CsrfValidationResult;
1145
+
1146
+ /**
1147
+ * Cookie-aware session manager for TheAuth.
1148
+ *
1149
+ * Wraps the lower-level `createSessionManager` with cookie serialization and
1150
+ * optional CSRF protection so callers work with `Request`/`Response` objects
1151
+ * directly rather than managing raw tokens and headers themselves.
1152
+ *
1153
+ * @example
1154
+ * ```typescript
1155
+ * import { createCookieSessionManager } from './manager.js';
1156
+ *
1157
+ * const sessions = createCookieSessionManager(
1158
+ * { secret: process.env.SESSION_SECRET },
1159
+ * db,
1160
+ * );
1161
+ *
1162
+ * // On login
1163
+ * const { session, setCookieHeader } = await sessions.createSession(user.id);
1164
+ * return new Response(null, {
1165
+ * status: 302,
1166
+ * headers: { Location: '/dashboard', 'Set-Cookie': setCookieHeader },
1167
+ * });
1168
+ *
1169
+ * // On each request
1170
+ * const session = await sessions.validateSession(request.headers.get('cookie') ?? '');
1171
+ * if (!session) return new Response('Unauthorized', { status: 401 });
1172
+ *
1173
+ * // On logout
1174
+ * const deleteCookie = sessions.buildLogoutCookie();
1175
+ * return new Response(null, {
1176
+ * status: 302,
1177
+ * headers: { Location: '/login', 'Set-Cookie': deleteCookie },
1178
+ * });
1179
+ * ```
1180
+ */
1181
+
1182
+ interface CookieSessionConfig extends SessionConfig {
1183
+ /**
1184
+ * Name of the session cookie.
1185
+ * Defaults to `"kavach_session"`.
1186
+ */
1187
+ sessionName?: string;
1188
+ /**
1189
+ * Additional cookie attributes applied when setting the session cookie.
1190
+ * `maxAge` is derived from `SessionConfig.maxAge` when not explicitly set.
1191
+ */
1192
+ cookieOptions?: Omit<CookieOptions, "maxAge">;
1193
+ /**
1194
+ * When `true`, `validateSession` automatically refreshes the session
1195
+ * expiry on every successful validation. Defaults to `true`.
1196
+ */
1197
+ autoRefresh?: boolean;
1198
+ }
1199
+ interface CreateSessionResult {
1200
+ /** The persisted session record. */
1201
+ session: Session;
1202
+ /** Ready-to-use `Set-Cookie` header value. */
1203
+ setCookieHeader: string;
1204
+ }
1205
+ interface ValidateSessionResult {
1206
+ /** The valid session, or `null` when the cookie is absent/invalid/expired. */
1207
+ session: Session | null;
1208
+ /**
1209
+ * When `autoRefresh` is enabled and the session was valid, the refreshed
1210
+ * `Set-Cookie` header to forward to the client. `null` otherwise.
1211
+ */
1212
+ refreshCookieHeader: string | null;
1213
+ }
1214
+ interface CookieSessionManager {
1215
+ /**
1216
+ * Create a new session for the given user and return the session record
1217
+ * together with a `Set-Cookie` header string ready to attach to a response.
1218
+ */
1219
+ createSession(userId: string, metadata?: Record<string, unknown>): Promise<CreateSessionResult>;
1220
+ /**
1221
+ * Parse the `Cookie` header, look up the session in the database, and
1222
+ * verify it has not expired.
1223
+ *
1224
+ * When `autoRefresh` is enabled the session is extended on each valid
1225
+ * request and a new `Set-Cookie` header is returned for forwarding.
1226
+ *
1227
+ * @param cookieHeader Raw value of the `Cookie` request header.
1228
+ */
1229
+ validateSession(cookieHeader: string): Promise<ValidateSessionResult>;
1230
+ /**
1231
+ * Extend the session expiry to `now + maxAge`.
1232
+ *
1233
+ * Returns the updated session and a fresh `Set-Cookie` header.
1234
+ * Returns `null` when the session does not exist.
1235
+ */
1236
+ refreshSession(sessionId: string): Promise<{
1237
+ session: Session;
1238
+ setCookieHeader: string;
1239
+ } | null>;
1240
+ /**
1241
+ * Delete a session by ID (server-side) and return a deletion cookie that
1242
+ * will clear the browser cookie on the next response.
1243
+ */
1244
+ revokeSession(sessionId: string): Promise<{
1245
+ deleteCookieHeader: string;
1246
+ }>;
1247
+ /**
1248
+ * Revoke all sessions for the given user.
1249
+ *
1250
+ * Returns a deletion cookie header for clearing the current browser cookie.
1251
+ */
1252
+ revokeAllSessions(userId: string): Promise<{
1253
+ deleteCookieHeader: string;
1254
+ }>;
1255
+ /**
1256
+ * List all non-expired sessions for a user, newest first.
1257
+ */
1258
+ listSessions(userId: string): Promise<Session[]>;
1259
+ /**
1260
+ * Build a `Set-Cookie` header that deletes the session cookie on the client
1261
+ * without any database operation. Useful in error paths.
1262
+ */
1263
+ buildLogoutCookie(): string;
1264
+ /** Expose the underlying low-level session manager for advanced usage. */
1265
+ raw: SessionManager;
1266
+ }
1267
+ /**
1268
+ * Create a cookie-aware session manager.
1269
+ *
1270
+ * Internally delegates all DB operations to `createSessionManager`.
1271
+ *
1272
+ * @param config Cookie-aware session configuration.
1273
+ * @param db Drizzle database instance from `createDatabase()`.
1274
+ */
1275
+ declare function createCookieSessionManager(config: CookieSessionConfig, db: Database): CookieSessionManager;
1276
+
1277
+ /**
1278
+ * Multi-session support for TheAuth.
1279
+ *
1280
+ * Allows users to maintain multiple concurrent sessions (phone, laptop, tablet)
1281
+ * with optional per-user session caps. When the cap is reached, the oldest
1282
+ * session is evicted automatically (configurable).
1283
+ *
1284
+ * Uses the existing `kavach_sessions` table — no additional schema required.
1285
+ *
1286
+ * @example
1287
+ * ```typescript
1288
+ * const multiSession = createMultiSessionModule(
1289
+ * { maxSessions: 5, overflowStrategy: 'evict-oldest' },
1290
+ * db,
1291
+ * sessionManager,
1292
+ * );
1293
+ *
1294
+ * // List all active sessions for a user
1295
+ * const sessionList = await multiSession.listSessions(userId);
1296
+ *
1297
+ * // Sign out everywhere except here
1298
+ * const count = await multiSession.revokeOtherSessions(userId, currentSessionId);
1299
+ * ```
1300
+ */
1301
+
1302
+ interface MultiSessionConfig {
1303
+ /** Max concurrent sessions per user (default: 10) */
1304
+ maxSessions?: number;
1305
+ /** Strategy when max is reached (default: 'evict-oldest') */
1306
+ overflowStrategy?: "reject" | "evict-oldest";
1307
+ }
1308
+ interface SessionInfo {
1309
+ id: string;
1310
+ createdAt: Date;
1311
+ expiresAt: Date;
1312
+ metadata?: Record<string, unknown>;
1313
+ /** Human-readable device string extracted from User-Agent, e.g. "Chrome on macOS" */
1314
+ device?: string;
1315
+ /** IP address recorded at session creation */
1316
+ ip?: string;
1317
+ }
1318
+ interface MultiSessionModule {
1319
+ /** List all non-expired sessions for a user, newest first. */
1320
+ listSessions(userId: string): Promise<SessionInfo[]>;
1321
+ /** Revoke a single session by ID. */
1322
+ revokeSession(sessionId: string): Promise<void>;
1323
+ /** Revoke every session except the given one. Returns the count revoked. */
1324
+ revokeOtherSessions(userId: string, currentSessionId: string): Promise<number>;
1325
+ /** Return the count of active (non-expired) sessions for a user. */
1326
+ getSessionCount(userId: string): Promise<number>;
1327
+ /**
1328
+ * Enforce the session cap before creating a new session.
1329
+ *
1330
+ * Call this before `sessionManager.create()`. If the cap is reached:
1331
+ * - `evict-oldest` deletes the oldest session and resolves.
1332
+ * - `reject` throws a `MultiSessionLimitError`.
1333
+ */
1334
+ enforceSessionLimit(userId: string): Promise<void>;
1335
+ }
1336
+ declare class MultiSessionLimitError extends Error {
1337
+ readonly code = "SESSION_LIMIT_REACHED";
1338
+ constructor(userId: string, max: number);
1339
+ }
1340
+ declare function createMultiSessionModule(config: MultiSessionConfig, db: Database, sessionManager: SessionManager): MultiSessionModule;
1341
+ /**
1342
+ * Build metadata to pass to `sessionManager.create()` that includes
1343
+ * device info extracted from the incoming request.
1344
+ *
1345
+ * @example
1346
+ * ```typescript
1347
+ * const meta = buildSessionMetadata(request, { role: 'admin' });
1348
+ * const { token } = await sessionManager.create(userId, meta);
1349
+ * ```
1350
+ */
1351
+ declare function buildSessionMetadata(request: Request, extra?: Record<string, unknown>): Record<string, unknown>;
1352
+
1353
+ /**
1354
+ * Token family tracking for refresh token reuse detection.
1355
+ *
1356
+ * Each refresh token belongs to a "family" — a chain of rotations that all
1357
+ * originate from the same initial login. When `reuseDetection` is enabled,
1358
+ * presenting an already-used token from a family immediately revokes every
1359
+ * token in that family, because reuse indicates the token was stolen.
1360
+ *
1361
+ * The database table `kavach_refresh_token_families` stores:
1362
+ * - family-level metadata (userId, absolute expiry, revocation status)
1363
+ *
1364
+ * Each individual refresh token row in `kavach_refresh_tokens` links back to
1365
+ * its family via `familyId`.
1366
+ *
1367
+ * @example
1368
+ * ```typescript
1369
+ * const families = createTokenFamilyStore(db);
1370
+ *
1371
+ * // On login — create a new family and issue the first token
1372
+ * const family = await families.createFamily(userId, absoluteExpiresAt);
1373
+ * const token = await families.issueToken(family.id, refreshTokenTTL);
1374
+ *
1375
+ * // On refresh — consume the token (marks it used, issues a new one)
1376
+ * const result = await families.consumeToken(rawToken);
1377
+ * if (result.status === 'reuse') {
1378
+ * // Entire family revoked — force re-login
1379
+ * }
1380
+ * ```
1381
+ */
1382
+
1383
+ interface TokenFamily {
1384
+ id: string;
1385
+ userId: string;
1386
+ /** Absolute expiry — no refresh can extend beyond this date. */
1387
+ absoluteExpiresAt: Date;
1388
+ revoked: boolean;
1389
+ createdAt: Date;
1390
+ }
1391
+ type ConsumeTokenStatus = "ok" /** Token valid, successfully consumed. */ | "expired" /** Token has passed its TTL. */ | "revoked" /** Entire family has been revoked (stolen token detected). */ | "reuse" /** Token was already used — family has now been revoked. */ | "not_found"; /** Token does not exist in the database. */
1392
+ interface ConsumeTokenResult {
1393
+ status: ConsumeTokenStatus;
1394
+ /** Populated when status is `"ok"`. */
1395
+ family?: TokenFamily;
1396
+ }
1397
+ interface TokenFamilyStore {
1398
+ /**
1399
+ * Create a new token family for a user.
1400
+ * Call this once per login to anchor the refresh token chain.
1401
+ */
1402
+ createFamily(userId: string, absoluteExpiresAt: Date): Promise<TokenFamily>;
1403
+ /**
1404
+ * Issue a new opaque refresh token tied to the given family.
1405
+ *
1406
+ * Returns the raw token string (only returned once — never stored in the
1407
+ * clear) and the token's individual expiry date.
1408
+ */
1409
+ issueToken(familyId: string, ttlMs: number): Promise<{
1410
+ rawToken: string;
1411
+ expiresAt: Date;
1412
+ }>;
1413
+ /**
1414
+ * Consume a refresh token.
1415
+ *
1416
+ * - If the token is valid and unused, it is marked `used` and the caller
1417
+ * should immediately call `issueToken` to rotate.
1418
+ * - If the token was already used, the **entire family is revoked** (reuse
1419
+ * detection — token theft assumed).
1420
+ * - If the token has expired or is not found, returns the appropriate status.
1421
+ */
1422
+ consumeToken(rawToken: string): Promise<ConsumeTokenResult>;
1423
+ /**
1424
+ * Revoke all token families (and their tokens) for a user.
1425
+ * Used on logout, password change, or explicit session termination.
1426
+ */
1427
+ revokeFamiliesForUser(userId: string): Promise<void>;
1428
+ /**
1429
+ * Revoke a specific family by ID and all its tokens.
1430
+ */
1431
+ revokeFamily(familyId: string): Promise<void>;
1432
+ /**
1433
+ * Check whether the absolute session timeout has been reached for a family.
1434
+ * Returns `true` when the family is still within its absolute timeout.
1435
+ */
1436
+ isFamilyActive(family: TokenFamily): boolean;
1437
+ }
1438
+ /**
1439
+ * Create a `TokenFamilyStore` backed by the TheAuth database.
1440
+ */
1441
+ declare function createTokenFamilyStore(db: Database): TokenFamilyStore;
1442
+
1443
+ /**
1444
+ * Session refresh endpoint handler for TheAuth.
1445
+ *
1446
+ * Implements `POST /auth/refresh`:
1447
+ * 1. Extracts the refresh token from an httpOnly cookie or the request body.
1448
+ * 2. Validates the token (TTL, reuse detection, absolute timeout).
1449
+ * 3. Issues a new short-lived access token (signed JWT).
1450
+ * 4. Rotates the refresh token (one-time use — the old one is consumed).
1451
+ * 5. Records the rotation in the audit log.
1452
+ *
1453
+ * Token family tracking (via `createTokenFamilyStore`) provides reuse
1454
+ * detection: if an attacker uses a stolen refresh token after the legitimate
1455
+ * user has already rotated it, the entire family is revoked and both parties
1456
+ * are forced to re-authenticate.
1457
+ *
1458
+ * @example
1459
+ * ```typescript
1460
+ * const refresher = createSessionRefresher({
1461
+ * secret: process.env.SESSION_SECRET,
1462
+ * session: {
1463
+ * accessTokenTTL: "15m",
1464
+ * refreshTokenTTL: "30d",
1465
+ * absoluteTimeout: "90d",
1466
+ * rotateRefreshTokens: true,
1467
+ * reuseDetection: true,
1468
+ * },
1469
+ * db,
1470
+ * });
1471
+ *
1472
+ * // In your Hono / Express router:
1473
+ * app.post('/auth/refresh', async (ctx) => {
1474
+ * const result = await refresher.handleRequest(ctx.req.raw);
1475
+ * return result.response;
1476
+ * });
1477
+ * ```
1478
+ */
1479
+
1480
+ interface RefreshSessionConfig {
1481
+ /**
1482
+ * Short-lived access token lifetime.
1483
+ * Parsed duration string, e.g. `"15m"`.
1484
+ * Defaults to `"15m"`.
1485
+ */
1486
+ accessTokenTTL?: string;
1487
+ /**
1488
+ * Long-lived refresh token lifetime.
1489
+ * Parsed duration string, e.g. `"30d"`.
1490
+ * Defaults to `"30d"`.
1491
+ */
1492
+ refreshTokenTTL?: string;
1493
+ /**
1494
+ * When `true` (default), each use of a refresh token rotates it: the old
1495
+ * token is invalidated and a new one is issued.
1496
+ */
1497
+ rotateRefreshTokens?: boolean;
1498
+ /**
1499
+ * Maximum session lifetime regardless of how many times the token is
1500
+ * refreshed. Parsed duration string, e.g. `"90d"`.
1501
+ * Defaults to `"90d"`.
1502
+ */
1503
+ absoluteTimeout?: string;
1504
+ /**
1505
+ * When `true` (default), presenting an already-used refresh token triggers
1506
+ * reuse detection and revokes the entire token family.
1507
+ */
1508
+ reuseDetection?: boolean;
1509
+ /**
1510
+ * Name of the httpOnly cookie that carries the refresh token.
1511
+ * Defaults to `"kavach_refresh"`.
1512
+ */
1513
+ refreshCookieName?: string;
1514
+ /**
1515
+ * Name of the httpOnly cookie that carries the access token (when cookie
1516
+ * transport is used for the access token too).
1517
+ * Defaults to `"kavach_access"`.
1518
+ */
1519
+ accessCookieName?: string;
1520
+ }
1521
+ interface SessionRefresherConfig {
1522
+ /** Signing secret — at least 32 characters. */
1523
+ secret: string;
1524
+ /** Refresh / rotation settings. */
1525
+ session?: RefreshSessionConfig;
1526
+ /** Drizzle database instance. */
1527
+ db: Database;
1528
+ }
1529
+ /** The payload embedded in the short-lived access token JWT. */
1530
+ interface AccessTokenPayload {
1531
+ /** User ID. */
1532
+ sub: string;
1533
+ /** Token family ID — used for server-side token binding. */
1534
+ familyId: string;
1535
+ /** Token type discriminator. */
1536
+ type: "access";
1537
+ }
1538
+ interface RefreshResult {
1539
+ /** Signed access token JWT. */
1540
+ accessToken: string;
1541
+ /** Raw opaque refresh token (only returned once — store in httpOnly cookie). */
1542
+ refreshToken: string;
1543
+ /** Expiry date of the new access token. */
1544
+ accessTokenExpiresAt: Date;
1545
+ /** Expiry date of the new refresh token. */
1546
+ refreshTokenExpiresAt: Date;
1547
+ /** The token family these tokens belong to. */
1548
+ family: TokenFamily;
1549
+ }
1550
+ type RefreshError = "token_missing" | "token_not_found" | "token_expired" | "token_reuse" | "family_revoked" | "absolute_timeout";
1551
+ interface RefreshHandleResult {
1552
+ /** HTTP Response ready to return to the caller. */
1553
+ response: Response;
1554
+ /** Populated on success. */
1555
+ result?: RefreshResult;
1556
+ /** Populated on failure. */
1557
+ error?: RefreshError;
1558
+ }
1559
+ interface SessionRefresher {
1560
+ /**
1561
+ * Low-level refresh — takes a raw refresh token string directly.
1562
+ *
1563
+ * Returns `RefreshResult` on success or throws a `RefreshTokenError`.
1564
+ */
1565
+ refresh(rawRefreshToken: string): Promise<RefreshResult>;
1566
+ /**
1567
+ * High-level HTTP handler.
1568
+ *
1569
+ * Extracts the refresh token from the `Cookie` header (preferred) or the
1570
+ * JSON request body, calls `refresh()`, and returns a `Response` with
1571
+ * appropriate `Set-Cookie` headers.
1572
+ */
1573
+ handleRequest(request: Request): Promise<RefreshHandleResult>;
1574
+ /**
1575
+ * Issue an initial refresh token for a user (called once on login).
1576
+ *
1577
+ * Returns the access token, refresh token, and their expiry dates.
1578
+ */
1579
+ issueInitial(userId: string): Promise<RefreshResult>;
1580
+ /**
1581
+ * Revoke all refresh token families for a user (e.g. on logout or
1582
+ * password change).
1583
+ */
1584
+ revokeAll(userId: string): Promise<void>;
1585
+ }
1586
+ /** Thrown by `SessionRefresher.refresh()` on validation failure. */
1587
+ declare class RefreshTokenError extends Error {
1588
+ readonly code: RefreshError;
1589
+ constructor(code: RefreshError, message: string);
1590
+ }
1591
+ /**
1592
+ * Create a `SessionRefresher` backed by the TheAuth database.
1593
+ */
1594
+ declare function createSessionRefresher(config: SessionRefresherConfig): SessionRefresher;
1595
+
1596
+ interface Tenant {
1597
+ id: string;
1598
+ name: string;
1599
+ slug: string;
1600
+ settings: TenantSettings;
1601
+ status: "active" | "suspended";
1602
+ createdAt: Date;
1603
+ updatedAt: Date;
1604
+ }
1605
+ interface TenantSettings {
1606
+ maxAgents?: number;
1607
+ maxDelegationDepth?: number;
1608
+ auditRetentionDays?: number;
1609
+ allowedAgentTypes?: string[];
1610
+ }
1611
+ interface CreateTenantInput {
1612
+ name: string;
1613
+ slug: string;
1614
+ settings?: Partial<TenantSettings>;
1615
+ }
1616
+ declare function createTenantModule(db: Database): {
1617
+ create: (input: CreateTenantInput) => Promise<Tenant>;
1618
+ get: (tenantId: string) => Promise<Tenant | null>;
1619
+ getBySlug: (slug: string) => Promise<Tenant | null>;
1620
+ list: () => Promise<Tenant[]>;
1621
+ update: (tenantId: string, updates: Partial<CreateTenantInput>) => Promise<Tenant>;
1622
+ suspend: (tenantId: string) => Promise<void>;
1623
+ activate: (tenantId: string) => Promise<void>;
1624
+ };
1625
+
1626
+ interface TrustScore {
1627
+ agentId: string;
1628
+ score: number;
1629
+ level: "untrusted" | "limited" | "standard" | "trusted" | "elevated";
1630
+ factors: {
1631
+ successRate: number;
1632
+ denialRate: number;
1633
+ ageInDays: number;
1634
+ totalCalls: number;
1635
+ anomalyCount: number;
1636
+ lastViolation?: string;
1637
+ };
1638
+ computedAt: string;
1639
+ }
1640
+ interface TrustConfig {
1641
+ /** Score thresholds for levels */
1642
+ thresholds?: {
1643
+ untrusted: number;
1644
+ limited: number;
1645
+ standard: number;
1646
+ trusted: number;
1647
+ elevated: number;
1648
+ };
1649
+ }
1650
+ /**
1651
+ * Create the graduated autonomy trust scoring module.
1652
+ *
1653
+ * Scores are derived from audit log history — success rate, denial rate,
1654
+ * agent age, total call volume, and anomaly count all feed into a 0-100
1655
+ * score mapped to five trust levels.
1656
+ *
1657
+ * @example
1658
+ * ```typescript
1659
+ * const trust = createTrustModule({}, db);
1660
+ * const score = await trust.computeScore(agentId);
1661
+ * console.log(score.level); // 'standard'
1662
+ * ```
1663
+ */
1664
+ declare function createTrustModule(config: TrustConfig, db: Database): {
1665
+ computeScore: (agentId: string) => Promise<TrustScore>;
1666
+ getScore: (agentId: string) => Promise<TrustScore | null>;
1667
+ computeAll: () => Promise<TrustScore[]>;
1668
+ getScores: (filters?: {
1669
+ level?: string;
1670
+ minScore?: number;
1671
+ }) => Promise<TrustScore[]>;
1672
+ };
1673
+ type TrustModule = ReturnType<typeof createTrustModule>;
1674
+
1675
+ 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";
1676
+ interface WebhookConfig {
1677
+ /** Signing secret for HMAC-SHA256 webhook signatures */
1678
+ secret: string;
1679
+ /** Max delivery attempts (default: 3) */
1680
+ maxRetries?: number;
1681
+ /** Timeout per delivery in ms (default: 10000) */
1682
+ timeoutMs?: number;
1683
+ }
1684
+ interface WebhookSubscription {
1685
+ id: string;
1686
+ url: string;
1687
+ events: WebhookEvent[];
1688
+ active: boolean;
1689
+ createdAt: Date;
1690
+ }
1691
+ interface WebhookModule {
1692
+ subscribe(url: string, events: WebhookEvent[]): Promise<WebhookSubscription>;
1693
+ unsubscribe(subscriptionId: string): Promise<void>;
1694
+ list(): Promise<WebhookSubscription[]>;
1695
+ /** Dispatch an event to all matching subscribers (fire-and-forget) */
1696
+ dispatch(event: WebhookEvent, payload: Record<string, unknown>): void;
1697
+ /** Test a webhook URL */
1698
+ test(subscriptionId: string): Promise<{
1699
+ success: boolean;
1700
+ statusCode?: number;
1701
+ error?: string;
1702
+ }>;
1703
+ }
1704
+ declare function createWebhookModule(config: WebhookConfig): WebhookModule;
1705
+ /**
1706
+ * Verify an incoming webhook signature.
1707
+ * Returns true if the signature matches the payload and secret.
1708
+ */
1709
+ declare function verifyWebhookSignature(secret: string, rawBody: string, signature: string): Promise<boolean>;
1710
+
1711
+ export { type AccessTokenPayload, AdminModule, AgentDid, AgentFilter, AgentIdentity, ApiKeyManagerModule, ApprovalRequest, AuditEntry, AuditExportOptions, AuditFilter, AuthorizeRequest, AuthorizeResult, type BudgetLimits, type BudgetPolicy, type BudgetUsage, CaptchaModule, type ConsumeTokenResult, type ConsumeTokenStatus, type CookieOptions, type CookieSessionConfig, type CookieSessionManager, CreateAgentInput, type CreatePolicyInput, type CreateSessionResult, type CreateTenantInput, type CsrfValidationResult, Database, DatabaseConfig, DelegateInput, DelegationChain, DidDocument, DidKeyPair, type DidModule, DidWebConfig, EmailOtpModule, type EmailTemplate, type EmailTemplateConfig, type EmailTemplateName, type EmailTemplates, EmailVerificationModule, EndpointContext, type I18nConfig, type I18nModule, type Kavach, KavachConfig, KavachPlugin, MagicLinkModule, McpServer, McpServerInput, type MultiSessionConfig, MultiSessionLimitError, type MultiSessionModule, OneTimeTokenModule, OrgModule, PasskeyModule, PasswordResetModule, Permission, PhoneAuthModule, PluginEndpoint, type PluginRegistry, type PolicyFilters, type PrivilegeAnalysis, type PrivilegeAnalyzer, type PrivilegeFinding, type PrivilegeSummary, RedirectChainManager, type RefreshError, type RefreshHandleResult, type RefreshResult, type RefreshSessionConfig, RefreshTokenError, ResolvedUser, type SameSite, Session, SessionConfig, SessionFreshnessModule, type SessionInfo, SessionManager, type SessionRefresher, type SessionRefresherConfig, SignedPayload, SsoModule, type Tenant, type TenantSettings, type TokenFamily, type TokenFamilyStore, 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, createSessionRefresher, createTables, createTenantModule, createTokenFamilyStore, 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 };