Auto-generated from source code as of 2026-11-13 (v12.9.4) File:
FRAMEWORK-API.md— compact, machine-readable API surface for Claude Code
CoreModule.forRoot(options: Partial<IServerOptions>, overrides?: ICoreModuleOverrides):DynamicModule(deprecated)CoreModule.forRoot(AuthService: any, AuthModule: any, options: Partial<IServerOptions>, overrides?: ICoreModuleOverrides):DynamicModule
ai?:boolean | IAi— Configuration for the AI assistant module.appUrl?:string— Base URL of the frontend/app application.apiTokens?:boolean | IApiTokens(default:undefined (disabled)) — API tokens: bearer credentials for machine clients and embedded pages that cannot carry a sessionauth?:IAuth— Authentication system configurationautomaticObjectIdFiltering?:boolean— Automatically detect ObjectIds in string values in FilterQueriesbaseUrl?:string— Base URL of the API server.betterAuth?:boolean | IBetterAuth(default:undefined (enabled with defaults)) — Configuration for better-auth authentication framework.bodyParser?:IBodyParserConfig— Size limits for request bodies.brevo?:{ apiKey: string; exclude?: RegExp; maxRetries?: number; sender: { email: str...— Configuration for Brevocompression?:boolean | compression.CompressionOptions— Whether to use the compression middleware package to enable gzip compression.configEndpoint?:boolean(default:undefined (answers only inlocal,ciande2e)) — Whether a project'sGET /configmay answer (12.5.0+). The route lives in project code (the starter'scookies?:boolean | ICookiesConfig(default:true) — Cookie configuration for authentication handling.cors?:boolean | ICorsConfig(default:undefined (enabled with auto-derived origins)) — CORS (Cross-Origin Resource Sharing) configuration.cronJobs?:Record<string, string | false | 0 | CronJobConfigWithTimeZone<null, null> | C...— Cron jobs configuration object with the name of the cron job function as keydatabase?:string | false | IDatabaseConfig(default:undefined (themongooseconfiguration)) — Data sources: where models are stored.debugProcessInput?:boolean(default:false) — When true, logs a debug message when prepareInput() changes the input type during process().email?:{ defaultReplyTo?: string; defaultSender?: { email?: string; name?: string; }...— SMTP and template configuration for sending emailsenv?:string— Environmentversion?:string— Semantic version of the running build (e.g. from package.json / meta.json).errorCode?:IErrorCode— Configuration for the error code moduleexecAfterInit?:string— Exec a command after server is initializedfile?:IFileConfig— Configuration of the file module: where the bytes live (storage) and whofilter?:{ maxLimit?: number; }— Filter configuration and defaultsgraphQl?:false | { driver?: ApolloDriverConfig; enableSubscriptionAuth?: boolean; maxC...— Configuration of the GraphQL modulehealthCheck?:{ configs?: { build?: { enabled?: boolean; }; database?: { enabled?: boolean;...— Whether to activate health check endpointshostname?:string— Hostname of the serverhub?:boolean | IHubConfig(default:undefined (disabled)) — Hub admin area (operator cockpit).ignoreSelectionsForPopulate?:boolean— Ignore selections in fieldSelectionjwt?:IJwt & JwtModuleOptions & { refresh?: IJwt & { renewal?: boolean; }; sameToke...— Configuration of JavaScript Web Token (JWT) moduleloadLocalConfig?:string | boolean(default:false) — Load a local configuration file and merge it over this environment's configurationlogExceptions?:boolean— Log exceptions (for better debugging)mongoose?:{ collation?: CollationOptions; modelDocumentation?: boolean; options?: Mongo...— Configuration for MongoosemultiTenancy?:IMultiTenancy(default:undefined (disabled)) — Multi-tenancy configuration for tenant-based data isolation.permissions?:boolean | IPermissions(default:undefined (disabled)) — Permissions report module (development tool).port?:number— Port number of the serverredis?:boolean | IRedisConfig(default:undefined (disabled)) — Optional central Redis connection used by all distributed featuress3?:IS3Config(default:undefined (disabled)) — Optional central S3-compatible object storage (AWS S3, MinIO, ...).security?:{ allowPrivateOutboundTargets?: boolean; checkResponseInterceptor?: boolean |...— Configuration for security pipes and interceptorssha256?:boolean— Whether to enable verification and automatic encryption for received passwords that are not in sha256 formatshutdownDelayMs?:number(default:0 (no delay)) — Delay in milliseconds between receiving a shutdown signal and starting thestaticAssets?:{ options?: ServeStaticOptions; path?: string; }— Configuration for useStaticAssetssync?:boolean | ISync— Offline sync (docs/offline-sync-protocol.md):GET/POST /sync/{model}for the models whose service carriesswagger?:boolean(default:undefined (served only inlocal,ciande2e)) — WhethersetupSwagger()serves the API documentation (12.7.0+), decided byisSwaggerEnabled().systemSetup?:ISystemSetup— System setup configuration for initial admin creation.templates?:{ engine?: string; path?: string; }— TemplatestrustProxy?:string | number | boolean | string[](default:false (Express default — the forwarded chain is not trusted)) — Expresstrust proxysetting — how far up theX-Forwarded-Forchain this app believes.tus?:boolean | ITusConfig— TUS resumable upload configuration.
When passkey is enabled, trustedOrigins is required (compile-time enforcement).
passkey?:IBetterAuthPasskeyDisabled— Passkey/WebAuthn configuration (DISABLED or not configured).trustedOrigins?:string[]— Trusted origins for CORS configuration.
legacyEndpoints?:IAuthLegacyEndpoints— Configuration for legacy auth endpointspreventUserEnumeration?:boolean(default:false (backward compatible - specific error messages)) — Prevent user enumeration via unified error messagespasswordReset?:IAuthPasswordReset— Password-reset request behaviour.rateLimit?:IAuthRateLimit(default:{ enabled: false }) — Rate limiting configuration for Legacy Auth endpoints
enabled?:boolean(default:true (when config object is present)) — Explicitly disable multi-tenancy even when config is present.excludeSchemas?:string[](default:[]) — Model names (NOT collection names) to exclude from tenant filtering.headerName?:string(default:'x-tenant-id') — Header name for tenant selection.membershipModel?:string(default:'TenantMember') — Mongoose model name for the membership collection.adminBypass?:boolean(default:true) — Whether system admins (RoleEnum.ADMIN) bypass the membership check.roleHierarchy?:Record<string, number>(default:{ member: 1, manager: 2, owner: 3 }) — Custom role hierarchy for tenant membership roles.globalOnlyRoles?:string[](default:[] (only RoleEnum.ADMIN is global)) — Project-defined roles that carry GLOBAL (platform-wide) authority.strictMembershipRoles?:boolean(default:false) — Refuse membership roles that are not declared anywhere (deny by default).additionalMembershipRoles?:string[](default:[]) — Membership roles that are valid but carry no hierarchy level (exact-match roles).cacheTtlMs?:number(default:30000 (30 seconds)) — TTL in milliseconds for the tenant guard's in-memory membership cache.isTenantActive?:(tenantId: string, context: { connection: Connection; store: (modelName: stri...(default:undefined (every tenant is active)) — Whether a tenant may be used at all — the hook that makes a DEACTIVATED tenant stop working.
additionalErrorRegistry?:Record<string, { code: string; message: string; translations: { [locale: stri...— Additional error registry to merge with core LTNS_* errorsautoRegister?:boolean(default:true) — Automatically register the ErrorCodeModule in CoreModule
privateKey?:string— Private keypublicKey?:string— Public keysecret?:string— Secret to encrypt the JWTsecretOrKeyProvider?:(request: Record<string, any>, rawJwtToken: string, done: (err: any, secret: ...— JWT ProvidersecretOrPrivateKey?:string— Alias of secret (for backwards compatibility)signInOptions?:JwtSignOptions— SignIn Options like expiresIn
enabled?:boolean(default:true) — Whether cookies are enabled.exposeTokenInBody?:boolean(default:false) — Whether to include the session token in the response body when cookies are enabled.
allowAll?:boolean(default:false) — Allow all origins by mirroring the request Origin header back.allowedOrigins?:string[]— Additional allowed origins beyondappUrlandbaseUrl.deriveAppUrl?:boolean(default:true) — WhetherappUrlmay be auto-derived frombaseUrlwhen it is not set explicitly.enabled?:boolean(default:true) — Whether CORS is enabled.
allowedBaseUrlHosts?:string | string[]— Optional SSRF allowlist for connection base URLs. When set (non-empty), theaudit?:boolean(default:false) — Persist an audit record (aiInteractions) for every prompt run (admin-readable).budget?:{ period?: "day" | "month" | "none"; tenant?: { maxPrompts?: number; maxToken...— Token/prompt budgets for AI prompts, enforced before a run (HTTP 429 + translatedcapabilityDriftCheck?:boolean(default:false) — Opt-in boot self-check: after startup, probe each enabled connection that declaresconfirmation?:{ mutating?: { default?: boolean; enforced?: boolean; }; }— Confirmation policy for mutating tool actions (create/update/delete).documentation?:string— System documentation injected into the system prompt to inform the LLMdefaultConnection?:IAiDefaultConnection— Optional one-time seed for a default connection (see {@link IAiDefaultConnection}).defaultMode?:"auto" | "plan"(default:'auto') — Default execution mode when the client does not specify one.enabled?:boolean— Explicitly disable while keeping the config (default: enabled when present).encryptionSecret?:string— Pass-phrase used to derive the AES-256-GCM key for encrypting connection APIcontextWindow?:number(default:8192) — Fallback total context window (input + output tokens) used to budget theclaudeCli?:{ bin?: string; extraArgs?: string[]; maxBudgetUsd?: number; }— Optional config for theClaudeCliProvider(LLM backend that invokes a localcompaction?:boolean(default:true) — LLM-driven context compaction: when a session would overflow the connection'sdeferToolSchemas?:boolean(default:false) — Defer the parameter schemas of tools out of the system prompt. With many toolsdeferToolSummaryChars?:number(default:0) — Maximum characters per tool description in the DEFERRED catalognativeToolCatalog?:"full" | "names"(default:'names') — What the system prompt's tool catalog holds for a connection with NATIVE tool calling in auto mode (12.3.0+).maxIterations?:number(default:5) — Maximum number of agent-loop iterations (tool round-trips).maxRunMs?:number(default:0) — Wall-clock ceiling for ONE prompt run, in milliseconds. Checked before eachmaxToolResultChars?:number(default:12000) — Maximum characters of a tool-results payload fed back to the model.promptLearning?:{ autoApply?: boolean; enabled?: boolean; minOccurrences?: number; }— Governed self-improvement loop for the system prompt. The orchestrator recordsmcp?:boolean | { confirmation?: boolean | { default?: boolean; enforced?: boolean;...(default:false) — Expose the tool registry as an MCP server at/ai/mcp(Streamable HTTP) forrateLimit?:IAiRateLimit— Rate limiting for prompts.systemPrompt?:string— Base system prompt prepended to every conversation.
enabled?:boolean— Explicitly disable while keeping the config (default: enabled when present).max?:number(default:20) — Maximum number of prompts per window per user.windowSeconds?:number(default:60) — Window length in seconds.
apiKey?:string— Inline plaintext API key (encrypted on seed). PreferapiKeyEnvinstead.apiKeyEnv?:string— Name of an environment variable holding the API key (e.g. 'AI_API_KEY').baseUrl:string— Base URL of the OpenAI-compatible endpoint.capabilities?:string[]— Capability tags (free-form, e.g. 'analysis', 'vision').contextWindow?:number— Total context window (input + output tokens) the model supports. Drives thedefaultMaxTokens?:number— Default maximum number of tokens for completions.defaultTemperature?:number— Default sampling temperature.description?:string— Human-readable description.model:string— Model id sent to the backend (e.g. 'gpt-oss-120b').name:string— Human-readable connection name.providerType?:string— Provider type (default 'openai-compatible').supportsJsonResponse?:boolean— Native JSON / structured-output support. Omit to auto-detect by probing thesupportsNativeTools?:boolean— Native function/tool-calling support. Omit to auto-detect by probing thesupportsVision?:boolean— Whether the model supports image input.
access?:"authenticated" | "custom" | "owner" | "public" | "tenant"(default:'custom') — WHICH PROJECT CLASS this deployment is — the per-file rule, as a declaration instead of code.deleteRoles?:string[](default:['admin']) — Roles allowed to DELETE files (deleteFilemutation).downloadCaching?:"none" | "revalidate"(default:'none') — Browser caching of file downloads (GET /files/id/:id,GET /files/:filename).downloadIdleTimeoutMs?:number(default:30000) — Time in milliseconds a download stream fromCoreFileService.getFileStream()/getFileStreamByName()maydownloadRoles?:string[](default:['admin']) — Roles allowed to DOWNLOAD files and read file infostorage?:"filesystem" | "gridfs" | "s3"(default:derived — see above) — Storage driver for CoreFileService. Three equivalent options:storageDir?:string(default:'uploads/files') — Directory for the'filesystem'storage driver.uploadRoles?:string[](default:['admin']) — Roles allowed to UPLOAD files (uploadFile/uploadFilesmutations).
db?:number(default:0) — Redis database indexenabled?:boolean(default:true (when config object is present)) — Whether Redis is enabled.host?:string(default:'localhost') — Redis hostkeyPrefix?:string(default:the slugifiednamefrom package.json, or 'nest-server' if unreadable) — Prefix prepended to every framework-managed Redis keyoptions?:Record<string, unknown>(default:undefined) — Additional ioredis options passed through to the client constructorpassword?:string(default:undefined (no auth)) — Redis passwordport?:number(default:6379) — Redis porturl?:string(default:undefined) — Full Redis connection URL (e.g. 'redis://user:pass@host:6379/0').username?:string(default:undefined) — Redis username (Redis 6+ ACL)
accessKeyId?:string(default:undefined) — Access key ID.autoCreateBucket?:boolean(default:false) — Create the configured buckets at startup when they do not exist.bucket:string— Bucket for files stored via CoreFileServiceconnectionTimeoutMs?:number(default:15000) — Upper bound in milliseconds for ONE attempt of a request to get a socket: the time it WAITS for a free socket ofdownloadIdleTimeoutMs?:number(default:30000) — Time in milliseconds a download stream from S3 (CoreS3Service.getObject(), and with itenabled?:boolean(default:true (when config object is present)) — Whether S3 is enabled.endpoint?:string(default:undefined) — Custom endpoint URL for S3-compatible services (MinIO, RustFS, ...).forcePathStyle?:boolean(default:false) — Use path-style addressing (required by most self-hosted S3 services).maxSockets?:number(default:200) — Maximum number of concurrent sockets to the S3 endpoint (per protocol). Requests beyond it wait for apresignedDownloads?:boolean | { enabled?: boolean; expiresInSeconds?: number; }(default:false) — Serve downloads as presigned URL redirects instead of streamingregion?:string(default:'us-east-1') — AWS regionsecretAccessKey?:string(default:undefined) — Secret access key.socketTimeoutMs?:number(default:120000) — Time in milliseconds a socket to S3 may stay without any traffic before the SDK destroys it — thestagingBucket?:string(default:same asbucket``) — Bucket used as staging area for resumable TUS uploads.
allowedHeaders?:string[](default:[] (no additional headers needed)) — Additional allowed HTTP headers for TUS requests (beyondallowedOrigins?:string[](default:undefined (derived from the API CORS configuration)) — Origins the tus handler may answer a cross-origin request with (Access-Control-Allow-Origin).allowedTypes?:string[](default:undefined (all types allowed)) — Allowed MIME types for uploads.checksum?:boolean(default:true) — Checksum extension configuration.concatenation?:boolean(default:true) — Concatenation extension configuration.creation?:boolean | ITusCreationConfig(default:true) — Creation extension configuration.creationWithUpload?:boolean(default:true) — Creation With Upload extension configuration.enabled?:boolean(default:true (enabled by default)) — Whether tus uploads are enabled.expiration?:boolean | ITusExpirationConfig(default:{ expiresIn: '24h' }) — Expiration extension configuration.maxSize?:number(default:50 * 1024 * 1024 * 1024 (50 GB)) — Maximum upload size in bytespath?:string(default:'/tus') — Base path for tus endpoints (11.42.9+):relativeLocation?:boolean(default:false) — Hand out upload URLs (Location) without scheme and host —/tus/<id>instead ofroles?:string[](default:['s_user']) — Roles allowed to use the tus endpoints (create, write, read offset, terminate).s3Staging?:boolean(default:true (when S3 is usable)) — Stage upload chunks in the configured S3 bucket (IServerOptions.s3,termination?:boolean(default:true) — Termination extension configuration.uploadDir?:string(default:'uploads/tus') — Directory for temporary upload chunks.
apiToken?:{ model?: Type<any>; service?: Type<any>; }— Override API token collaborators with project-specific subclasses (apiTokensconfig).sync?:{ controller?: Type<any>; hintsController?: Type<any>; resolver?: Type<any>; ...— Override the offline sync endpoints, the hint subscription and their service (syncconfig).ai?:{ budgetService?: Type<any>; connectionResolver?: Type<any>; connectionServic...— Override AI module collaborators with project-specific subclasses.betterAuth?:{ controller?: Type<any>; resolver?: Type<any>; }— Override BetterAuth controller and/or resolver.errorCode?:{ controller?: Type<any>; service?: Type<any>; }— Override ErrorCode controller and/or service.hub?:{ actionsController?: Type<any>; actionsService?: Type<any>; controller?: Typ...— Override Hub controllers and/or services with project-specific subclasses.
authenticatorAttachment?:"cross-platform" | "platform"(default:undefined (both allowed)) — Authenticator attachment preference.challengeStorage?:"cookie" | "database"(default:'database') — Where to store WebAuthn challenges.challengeTtlSeconds?:number(default:300 (5 minutes)) — TTL in seconds for database-stored challenges.enabled?:boolean(default:true (when config block is present)) — Whether passkey authentication is enabled.origin?:string— Origin URL for WebAuthn.residentKey?:"discouraged" | "preferred" | "required"(default:'preferred') — Resident key (discoverable credential) requirement.rpId?:string— Relying Party ID (usually the domain without protocol).rpName?:string— Relying Party Name (displayed to users)userVerification?:"discouraged" | "preferred" | "required"(default:'preferred') — User verification requirement.webAuthnChallengeCookie?:string(default:'better-auth-passkey') — Key of Better-Auth's WebAuthn challenge cookie. Better-Auth puts its cookie prefix in front of it
appName?:string(default:'Nest Server') — App name shown in authenticator apps.enabled?:boolean(default:true (enabled by default when BetterAuth is active)) — Whether 2FA is enabled.
enabled?:boolean(default:true (enabled by default when BetterAuth is active)) — Whether JWT plugin is enabled.expiresIn?:string(default:'15m') — JWT expiration time
appName?:string(default:undefined (the formatted package.json name, 'Nest Server' without one)) — The application name in the verification and password-reset mails: the subject (` - Verify your emailautoSignInAfterVerification?:boolean(default:false) — WhetherGET /iam/verify-emailsigns in the browser that opens the verification link.brevoTemplateId?:number(default:undefined (uses SMTP/EJS templates)) — Brevo template ID for verification emails.callbackURL?:string(default:'/auth/verify-email') — Frontend callback URL for email verification.enabled?:boolean(default:true (enabled by default when BetterAuth is active)) — Whether email verification is enabled.expiresIn?:number(default:86400 (24 hours)) — Time in seconds until the verification link expires.locale?:string(default:'en') — Locale for the verification email template.passwordResetBrevoTemplateId?:number(default:undefined (uses SMTP/EJS templates)) — Brevo transactional template ID for the PASSWORD-RESET mail.passwordResetLink?:string | false(default:<appUrl>/auth/reset-password?token={token}) — Where the password-reset mail sends the recipient.resendCooldownSeconds?:number(default:60) — Cooldown in seconds between resend requests for the same email address.template?:string(default:'email-verification') — Custom template name for the verification email.
enabled?:boolean(default:true when arateLimitobject is present, false when it is absent) — Whether rate limiting is enabled.max?:number(default:10) — Maximum number of requests within the time windowmaxEntries?:number(default:10000) — Maximum number of distinct counters this limiter may hold — the bound on the keyspace amessage?:string— Custom message when rate limit is exceededskipEndpoints?:string[]— Endpoints to skip rate limiting entirelystrictEndpoints?:string[]— Endpoints to apply stricter rate limiting (e.g., sign-in, sign-up)windowSeconds?:number— Time window in seconds
enabled?:boolean(default:true (enabled by default when BetterAuth is active)) — Whether sign-up checks are enabled.requiredFields?:string[](default:['termsAndPrivacyAccepted']) — Fields that must be provided and truthy during sign-up.
defaultValue?:unknown— Default value for the fieldfieldName?:string— Database field name (if different from key)input?:boolean(default:true (Better-Auth default when omitted)) — Whether a client may supply this field's value via Better-Auth's native input parsingrequired?:boolean— Whether this field is requiredtype:BetterAuthFieldType— Field type
checkRights?:booleancollation?:CollationOptionscreate?:booleancreateId?:stringcurrentUser?:{ [key: string]: any; id: string; roles?: string[]; }fieldSelection?:FieldSelectionexpectedVersion?:numberforce?:booleanincludeTombstones?:booleaninputType?:new (...params: any[]) => anyoutputType?:new (...params: any[]) => anypopulate?:string | PopulateOptions | (string | PopulateOptions)[]prepareInput?:PrepareInputOptionsprepareOutput?:PrepareOutputOptionsprocessFieldSelection?:{ dbModel?: Model<any>; ignoreSelections?: boolean; model?: new (...args: any...pubSub?:booleanraw?:booleanroles?:string | string[]select?:string | string[] | Record<string, number | boolean | object>setCreateOrUpdateUserId?:boolean
Base class for all services. Located at src/core/common/services/crud.service.ts.
Generic: CrudService<Model, CreateInput, UpdateInput>
async aggregate(pipeline: PipelineStage[], serviceOptions?: ServiceOptions & { aggregateOptions?: AggregateOptions; }):Promise<T>— Aggregateasync aggregateForce(pipeline: PipelineStage[], serviceOptions?: ServiceOptions):Promise<T>— Aggregate without checks or restrictionsasync aggregateRaw(pipeline: PipelineStage[], serviceOptions?: ServiceOptions):Promise<T>— Aggregate without checks, restrictions or preparationsasync create(input: PlainObject<CreateInput>, serviceOptions?: ServiceOptions):Promise<Model>— Create itemasync createForce(input: PlainObject<CreateInput>, serviceOptions?: ServiceOptions):Promise<Model>— Create item without checks or restrictionsasync createRaw(input: PlainObject<CreateInput>, serviceOptions?: ServiceOptions):Promise<Model>— Create item without checks, restrictions or preparationsdistinct(property: string, serviceOptions?: ServiceOptions):Promise<string[]>— Get distinct values of a propertyasync get(id: string, serviceOptions?: ServiceOptions):Promise<Model>— Get item by IDasync getForce(id: string, serviceOptions?: ServiceOptions):Promise<Model>— Get item by ID without checks or restrictionsasync getRaw(id: string, serviceOptions?: ServiceOptions):Promise<Model>— Get item by ID without checks, restrictions or preparationsasync find(filter?: FilterArgs | { filterQuery?: QueryFilter<any>; queryOptions?: QueryOptions; s..., serviceOptions?: ServiceOptions):Promise<Model[]>— Get items via filterasync findForce(filter?: FilterArgs | { filterQuery?: QueryFilter<any>; queryOptions?: QueryOptions; s..., serviceOptions?: ServiceOptions):Promise<Model[]>— Get items via filter without checks or restrictionsasync findRaw(filter?: FilterArgs | { filterQuery?: QueryFilter<any>; queryOptions?: QueryOptions; s..., serviceOptions?: ServiceOptions):Promise<Model[]>— Get items via filter without checks, restrictions or preparationsasync findAndCount(filter?: FilterArgs | { filterQuery?: QueryFilter<any>; queryOptions?: QueryOptions; s..., serviceOptions?: ServiceOptions):Promise<{ items: Model[]; pagination: PaginationInfo; totalCount: number; }>— Get items and total count via filterasync findAndCountForce(filter?: FilterArgs | { filterQuery?: QueryFilter<any>; queryOptions?: QueryOptions; s..., serviceOptions?: ServiceOptions):Promise<{ items: Model[]; pagination: PaginationInfo; totalCount: number; }>— Get items and total count via filter without checks or restrictionsasync findAndCountRaw(filter?: FilterArgs | { filterQuery?: QueryFilter<any>; queryOptions?: QueryOptions; s..., serviceOptions?: ServiceOptions):Promise<{ items: Model[]; pagination: PaginationInfo; totalCount: number; }>— Get items and total count via filter without checks, restrictions or preparationsasync findAndUpdate(filter: FilterArgs | { filterQuery?: QueryFilter<any>; queryOptions?: QueryOptions; s..., update: PlainObject<UpdateInput>, serviceOptions?: ServiceOptions):Promise<Model[]>— Find and updateasync findAndUpdateForce(filter: FilterArgs | { filterQuery?: QueryFilter<any>; queryOptions?: QueryOptions; s..., update: PlainObject<UpdateInput>, serviceOptions?: ServiceOptions):Promise<Model[]>— Find and update without checks or restrictionsasync findAndUpdateRaw(filter: FilterArgs | { filterQuery?: QueryFilter<any>; queryOptions?: QueryOptions; s..., update: PlainObject<UpdateInput>, serviceOptions?: ServiceOptions):Promise<Model[]>— Find and update without checks, restrictions or preparationsasync findOne(filter?: FilterArgs | { filterQuery?: QueryFilter<any>; queryOptions?: QueryOptions; }, serviceOptions?: ServiceOptions):Promise<Model>— Find one item via filterasync findOneForce(filter?: FilterArgs | { filterQuery?: QueryFilter<any>; queryOptions?: QueryOptions; s..., serviceOptions?: ServiceOptions):Promise<Model>— Find one item via filter without checks or restrictionsasync findOneRaw(filter?: FilterArgs | { filterQuery?: QueryFilter<any>; queryOptions?: QueryOptions; s..., serviceOptions?: ServiceOptions):Promise<Model>— Find one item via filter without checks, restrictions or preparationsgetModel():MongooseModel<Document<Types.ObjectId, any, any, Record<string, any>, {}> & M...— Get service model to process queries directly.getNativeCollection(reason: string):Collection<Document>— Get the native MongoDB Collection, bypassing all Mongoose plugins.getNativeConnection(reason: string):Connection— Get the Mongoose Connection (which provides access to the native MongoDB Db and MongoClient).validateNativeAccessReason(reason: string, method: string):voidasync read(input: string | FilterArgs | { filterQuery?: QueryFilter<any>; queryOptions?: QueryO..., serviceOptions?: ServiceOptions):Promise<Model | Model[]>— CRUD alias for get or findasync readForce(input: string | FilterArgs | { filterQuery?: QueryFilter<any>; queryOptions?: QueryO..., serviceOptions?: ServiceOptions):Promise<Model | Model[]>— CRUD alias for getForce or findForceasync readRaw(input: string | FilterArgs | { filterQuery?: QueryFilter<any>; queryOptions?: QueryO..., serviceOptions?: ServiceOptions):Promise<Model | Model[]>— CRUD alias for getRaw or findRawasync update(id: string, input: PlainObject<UpdateInput>, serviceOptions?: ServiceOptions):Promise<Model>— Update item via IDasync updateForce(id: string, input: PlainObject<UpdateInput>, serviceOptions?: ServiceOptions):Promise<Model>— Update item via ID without checks or restrictionsasync updateRaw(id: string, input: PlainObject<UpdateInput>, serviceOptions?: ServiceOptions):Promise<Model>— Update item via ID without checks, restrictions or preparationsasync delete(id: string, serviceOptions?: ServiceOptions):Promise<Model>— Delete item via IDwithTombstones(query: Q, serviceOptions?: ServiceOptions):Q— A Mongoose query or aggregation that also sees tombstones when the caller asked (includeTombstones)expectedVersionOf(serviceOptions?: ServiceOptions):number—serviceOptions.expectedVersion, checked; only a synchronized model has a versionassertVersion(id: string, stored: any, expectedVersion: number):void— The early answer to a conditional change on a record that already has another versionversionConflict(id: string):neversyncAccessSnapshot(stored: Record<string, any>):Record<string, any>— The tenant and scope fields of a stored record as they are BEFORE a write — taken beforemergePlain(), whichasync reportSyncAccessMove(stored: Record<string, any>, written: Record<string, any>):Promise<void>— Tell the sync module that this write took a synchronized record away from users who could see it: moved toreportSyncChange(records: Record<string, any>[]):void— Tell the sync module that a write of a synchronized record succeeded, so the subscribers of its hints learn of itsyncChanged(created: R):R—reportSyncChange()for a created record, which it answersasync removeOrTombstone(id: string, expectedVersion: number):Promise<void>— Delete through the store: a synchronized model's record becomes a tombstone (conditional onexpectedVersion),async deleteForce(id: string, serviceOptions?: ServiceOptions):Promise<Model>— Delete item via ID without checks or restrictionsasync deleteRaw(id: string, serviceOptions?: ServiceOptions):Promise<Model>— Delete item via ID without checks, restrictions or preparationsasync pushToArray(id: string | Types.ObjectId | { id?: any; _id?: any; }, field: string, items: any, options?: { $slice?: number; $position?: number; $sort?: Record<string, 1 | -1>; }):Promise<void>— Append items to an array field without loading the full array.async pullFromArray(id: string | Types.ObjectId | { id?: any; _id?: any; }, field: string, condition: any):Promise<void>— Remove items from an array field.async processQueryOrDocument(queryOrDocument: Document<Types.ObjectId, any, any, Record<string, any>, {}> | Document<Types...., serviceOptions?: ServiceOptions):Promise<T>— Execute, populate and map Mongoose query or document(s) with serviceOptionsassertMongooseStore(method: string):void— Refuse an API that only exists on MongoDB when the main model is stored elsewhere. The Mongoose model may still
Variants: Each method has three variants:
method()— Standard: appliessecurityCheck(), respects permissionsmethodForce()— BypassessecurityCheck(), still applies input validationmethodRaw()— Direct database access, no security or validation
| Module | Docs | Path |
|---|---|---|
ai |
README, CHECKLIST | src/core/modules/ai/ |
api-token |
README, CHECKLIST | src/core/modules/api-token/ |
auth |
README | src/core/modules/auth/ |
better-auth |
README, CHECKLIST | src/core/modules/better-auth/ |
error-code |
CHECKLIST | src/core/modules/error-code/ |
file |
README, CHECKLIST | src/core/modules/file/ |
health-check |
— | src/core/modules/health-check/ |
hub |
README, CHECKLIST | src/core/modules/hub/ |
migrate |
README | src/core/modules/migrate/ |
permissions |
README, CHECKLIST | src/core/modules/permissions/ |
sync |
README, CHECKLIST | src/core/modules/sync/ |
system-setup |
README, CHECKLIST | src/core/modules/system-setup/ |
tenant |
README, CHECKLIST | src/core/modules/tenant/ |
tus |
README, CHECKLIST | src/core/modules/tus/ |
user |
— | src/core/modules/user/ |
One 401/403 policy across all permission layers (role guards, tenant guard, check(),
checkRestricted(), model securityCheck()):
| Situation | Status | Message |
|---|---|---|
| Requester is not authenticated | 401 | ErrorCode.UNAUTHORIZED |
| Requester is authenticated but lacks a right | 403 | ErrorCode.ACCESS_DENIED |
S_NO_ONE (locked for everyone, even admins) |
403 always | ErrorCode.ACCESS_DENIED |
Never hand-roll the decision — use accessDeniedException(user). It returns the native
ForbiddenException / UnauthorizedException, so instanceof checks and @Catch(...) filters
in consuming projects keep working.
| Export | Purpose | Path |
|---|---|---|
ExpiredRefreshTokenException |
Exception for expired refresh token | src/core/modules/auth/exceptions/expired-refresh-token.exception.ts |
ExpiredTokenException |
Exception for expired token | src/core/modules/auth/exceptions/expired-token.exception.ts |
InvalidTokenException |
Exception for invalid token | src/core/modules/auth/exceptions/invalid-token.exception.ts |
LegacyAuthDisabledException |
Exception thrown when Legacy Auth endpoints are accessed but disabled | src/core/modules/auth/exceptions/legacy-auth-disabled.exception.ts |
accessDeniedException() |
Creates the access error that matches the requester's auth state (RFC 9110, mirrors RolesGuard): | src/core/common/exceptions/access-denied.exception.ts |
| File | Purpose |
|---|---|
src/core.module.ts |
CoreModule.forRoot() — module registration |
src/core/common/interfaces/server-options.interface.ts |
All config interfaces |
src/core/common/interfaces/service-options.interface.ts |
ServiceOptions interface |
src/core/common/services/crud.service.ts |
CrudService base class |
src/core/common/services/config.service.ts |
ConfigService (global) |
src/core/common/decorators/ |
@Restricted, @Roles, @CurrentUser, @UnifiedField |
src/core/common/exceptions/ |
accessDeniedException — the 401/403 policy |
src/core/common/interceptors/ |
CheckResponse, CheckSecurity, ResponseModel |
src/core/common/helpers/process-diagnostics.helper.ts |
installProcessDiagnostics() / handleFatalBootstrapError — opt-in, wire into your own main.ts |
docs/REQUEST-LIFECYCLE.md |
Complete request lifecycle |
docs/security-overrides.md |
pnpm overrides are NOT inherited — which entries your project still needs |
.claude/rules/ |
Detailed rules for architecture, security, testing |