import { ErrorFactory } from "./errors.mjs"; import { RLSConfig, Rules } from "./tenancy.mjs"; import { SecurityPolicyContext } from "./querying/security.mjs"; import { CustomBuilder } from "convex-helpers/server/zod4"; import { ActionBuilder, DefaultFunctionArgs, DocumentByInfo, GenericActionCtx, GenericDataModel, GenericMutationCtx, GenericQueryCtx, GenericTableInfo, IndexNames, IndexRange, IndexRangeBuilder, MutationBuilder, NamedIndex, PaginationOptions, PaginationResult, Query, QueryBuilder, QueryInitializer, TableNamesInDataModel, UserIdentity } from "convex/server"; import { Triggers } from "convex-helpers/server/triggers"; //#region src/auth.d.ts /** The default vocabulary; every app can supply its own via the Role generic. */ export type DefaultRole = 'reader' | 'writer' | 'admin'; export type Actor = Readonly<{ userId: string; organizationId: string; role: Role; }>; export type AuthBundle = Readonly<{ identity: UserIdentity; user: Readonly<{ id: string; }>; org: Readonly<{ organizationId: string; role: Role; }>; role: Role; actor: Actor; /** The resolved tenant — security.tenancy.resolve, or the organization id. */ tenant: string; }>; /** * The bundle handed to security rules. Service principals (serviceQuery / * serviceMutation) may carry extra host-supplied fields beside the standard * bundle; rules read them as unknown and narrow as needed. */ export type SecurityBundle = AuthBundle & ServiceExtras; /** Extra fields a host factory attaches to a service principal. */ export type ServiceExtras = Readonly>; /** * A trusted host factory producing the principal a service function runs as. * `args` are the raw (unparsed) arguments of the invocation, so the host can * derive the scope (e.g. a client id) from them. Never accept the principal * itself from the caller — only derive it. */ export type ServicePrincipal> = (ctx: Ctx, args: DefaultFunctionArgs) => (AuthBundle & Extra) | Promise & Extra>; /** * Row-level security configuration. Tenant isolation and role-level rules * compose (AND) onto the same wrapped database: queries get a wrapped * reader, mutations get triggers first, then a wrapped writer. */ export type SecurityConfig = { /** * Tenant isolation. `tables` is THE registry: every listed table gets * read/insert/modify gated on row.tenant === ctx.tenant. Pair with * tenantTable (schema) and tenantOwnership (triggers) on the same list. */ tenancy?: { tables: readonly TableNamesInDataModel[]; /** Maps the auth bundle to the tenant; defaults to org.organizationId. */ resolve?: (bundle: Omit, 'tenant'>) => string; }; /** * Role-level (or any policy) rules derived from the authenticated bundle, * composed AND-wise with tenant isolation. E.g. gate `modify` on a table * to admin roles. */ rules?: (bundle: SecurityBundle) => Rules, DataModel>; /** * Policy for tables with no rule. Defaults to 'deny' when tenancy is * configured (unlisted tables are unreachable — fail closed), 'allow' * otherwise. */ defaultPolicy?: RLSConfig['defaultPolicy']; }; type AnyAuthContext = GenericQueryCtx | GenericMutationCtx | GenericActionCtx; /** * Configuration for createAuthReaders: everything createAuthFunctions takes * except the mutation builders and trigger wrapping, so a module built from * it never has to import the trigger registry. */ export type AuthReadersConfig = { /** The consumer's generated function builders (from ./_generated/server). */ query: QueryBuilder; action: ActionBuilder; internalQuery: QueryBuilder; internalAction: ActionBuilder; /** * Resolves the synchronized principal, e.g. (ctx) => authKit.getAuthUser(ctx). * The already-resolved, non-null identity is supplied as a second argument. * Callbacks may ignore it; using it can avoid a redundant identity lookup. */ getAuthUser: (ctx: AnyAuthContext, identity: UserIdentity) => Promise<{ id: string; } | null>; /** * Maps an identity role slug onto the app's role vocabulary. Returning * null rejects the caller with FORBIDDEN — unknown roles never pass. */ mapRole: (roleSlug?: string) => Role | null; /** Roles allowed through the admin* constructors. */ adminRoles: readonly NoInfer[]; /** * Live membership check for actions (queries/mutations trust the JWT). * Authentication fails closed with FORBIDDEN when verification errors. * Omit to let actions trust the JWT like queries do. */ verifyMembership?: (input: { userId: string; organizationId: string; }) => Promise<{ organizationId: string; roleSlug: string; } | null>; /** * Resolves organization authority from the app's own data for identity * providers whose tokens carry no org claims. When configured, its result * overrides claim-based resolution; null or an error rejects with FORBIDDEN * (fail closed). In actions the ctx has no db — resolve via ctx.runQuery. */ resolveOrganization?: (input: { ctx: AnyAuthContext; identity: UserIdentity; user: { id: string; }; }) => Promise<{ organizationId: string; roleSlug: string; } | null>; /** Host error policy; defaults to throwing KitError. */ errors?: ErrorFactory; /** Upper bound for include() reads. */ maxIncludedQueryRows?: number; /** * Row-level security: tenant isolation (from a table registry) and * role-level rules, applied structurally inside every auth*, role*, * admin*, and service* constructor. system* constructors stay unwrapped * (trusted). */ security?: SecurityConfig; }; /** A reader config plus the mutation builders and trigger wrapping. */ export type AuthFunctionsConfig = AuthReadersConfig & { mutation: MutationBuilder; internalMutation: MutationBuilder; /** * Application trigger registry. When set, every authMutation, * roleMutation, and systemMutation write runs through triggers.wrapDB — * evaluations registered on tables fire structurally. */ triggers?: Triggers; /** Lower-level alternative to `triggers`: a custom ctx wrapper. */ wrapDB?: (ctx: GenericMutationCtx) => GenericMutationCtx; }; /** WorkOS-style default: `member` writes; reader/writer/admin pass through. */ export declare function defaultRoleMap(roleSlug?: string): DefaultRole | null; export type IncludedQuery = { when(value: Value | null | undefined, select: (query: QueryInitializer
, value: Value) => Query
): IncludedQuery
; matching>(indexName: IndexName, indexRange?: (query: IndexRangeBuilder, NamedIndex>) => IndexRange, shouldMatch?: boolean): IncludedQuery
; otherwise(select: (query: QueryInitializer
) => Query
): Query
; resolve(): Query
; execute(limit: number): Promise[]>; execute(limit: number, transform: (data: Awaited['take']>>) => Result | Promise): Promise; /** * Cursor pagination over the selected indexed query. numItems is bounded * by the same maxRows policy as execute(). Under row-level security a * page may be shorter than numItems (rejected rows are filtered after * pagination); cursors remain correct. Pair with paginated(dto) from * cvx-kit/zod-table for the boundary schemas. */ paginate(opts: PaginationOptions): Promise>>; paginate(opts: PaginationOptions, transform: (page: DocumentByInfo
[]) => Item[] | Promise): Promise>; }; export type Include =
(query: QueryInitializer
) => IncludedQuery
; /** * Keep native contexts symbolic in published declarations. Inferred spreads * copy build-time Convex methods and override the consumer's native context. */ export type AuthFunctions = { include: Include; authenticatedUser: (ctx: AnyAuthContext) => Promise>; authQuery: CustomBuilder<'query', {}, GenericQueryCtx & AuthBundle & { include: Include; }, {}, GenericQueryCtx, 'public', object>; authMutation: CustomBuilder<'mutation', {}, GenericMutationCtx & AuthBundle & { include: Include; }, {}, GenericMutationCtx, 'public', object>; authAction: CustomBuilder<'action', {}, GenericActionCtx & AuthBundle, {}, GenericActionCtx, 'public', object>; roleQuery: (...allowed: readonly Role[]) => AuthFunctions['authQuery']; roleMutation: (...allowed: readonly Role[]) => AuthFunctions['authMutation']; roleAction: (...allowed: readonly Role[]) => AuthFunctions['authAction']; adminQuery: AuthFunctions['authQuery']; adminMutation: AuthFunctions['authMutation']; adminAction: AuthFunctions['authAction']; /** * Internal query running as a host-supplied service principal with the * app's security rules fully applied. No identity lookup; the trusted * host's factory is the only principal source. */ serviceQuery: = {}>(principal: ServicePrincipal, Role, Extra>) => ServiceQuery; /** Internal mutation running as a service principal: triggers first, then the secured writer. */ serviceMutation: = {}>(principal: ServicePrincipal, Role, Extra>) => ServiceMutation; systemQuery: CustomBuilder<'query', {}, GenericQueryCtx & { include: Include; }, {}, GenericQueryCtx, 'internal', object>; systemMutation: CustomBuilder<'mutation', {}, GenericMutationCtx & { include: Include; }, {}, GenericMutationCtx, 'internal', object>; systemAction: CustomBuilder<'action', {}, GenericActionCtx, {}, GenericActionCtx, 'internal', object>; }; /** The read-only constructors: everything AuthFunctions has except mutations. */ export type AuthReaders = Omit, `${string}Mutation`>; export type ServiceQuery = {}> = CustomBuilder<'query', {}, GenericQueryCtx & AuthBundle & Extra & { include: Include; }, {}, GenericQueryCtx, 'internal', object>; export type ServiceMutation = {}> = CustomBuilder<'mutation', {}, GenericMutationCtx & AuthBundle & Extra & { include: Include; }, {}, GenericMutationCtx, 'internal', object>; /** Builds an include() that selects the first matching indexed query and bounds the read. */ export declare function createInclude(options?: { errors?: ErrorFactory; maxRows?: number; }): Include; /** * Builds the auth-aware function constructors from the host's injected * policy: identity resolution, the app's own role vocabulary, live * membership verification for actions, trigger wrapping for mutations, * and errors. Role-based access is first-class — every constructor family * has a role-gated variant (roleQuery/roleMutation/roleAction), and the * admin* constructors are just that gate applied to config.adminRoles. */ export declare function createAuthFunctions(config: AuthFunctionsConfig): AuthFunctions; /** * Builds the read-only constructors (queries and actions) from the same * policy as createAuthFunctions, without mutation builders or triggers. * Identity, tenancy, rules, role gates, membership checks and errors are the * same implementation, so a module built from these never imports the * trigger registry or the domains it pulls in. */ export declare function createAuthReaders(config: AuthReadersConfig): AuthReaders; //#endregion export type { SecurityPolicyContext }; //# sourceMappingURL=auth.d.mts.map