import type { HydratedDocument, Model, Schema } from 'mongoose'; import mongoose from 'mongoose'; import type { ExtractProperty, GetModelTypeFromClass, GetModelTypeLiteFromSchema } from '../modules/BaseModel.ts'; import { BaseModel } from '../modules/BaseModel.ts'; import type { TI18n } from '../services/i18n/types.ts'; /** * Hash a token for storage/lookup. Tokens are high-entropy random values, so a * fast hash (SHA-256) is correct here — brute-force is infeasible and a slow * KDF would only add latency. Stored hashed so a DB read leak can't be replayed * as live bearer tokens. Exported so callers that match tokens directly (e.g. * logout's `$pull`) hash the same way. * * NOTE: `token` is ALWAYS a `createRandomToken()` output (256-bit `randomBytes`), * never a user-chosen password — including the `passwordRecoveryToken` / * `verificationToken` / `sessionToken` values that flow in. CodeQL's * `js/insufficient-password-hash` assumes low-entropy, human-chosen input and so * does not apply: a slow password KDF (bcrypt/scrypt/Argon2) would protect * nothing across a 2^256 search space. Real user passwords are hashed separately * with `hashPassword` (a proper KDF) in the `save` pre-hook below. */ export declare const hashToken: (token: string) => string; export type UserModelLite = GetModelTypeLiteFromSchema>; export type TUser = GetModelTypeFromClass; type UserSchemaDocument = InstanceType; type RawDocumentOf = T extends Model ? Raw : never; type UserSchemaRawDocument = RawDocumentOf; export type UserAuthField = 'email' | 'password' | 'sessionTokens' | 'verificationTokens' | 'passwordRecoveryTokens'; /** * Schema-derived fields used by the framework's auth statics and instance * methods. `TField` lets each operation expose only the paths it actually * needs; omitting it selects the complete auth field set. The `Pick` is a * structural behavior capability, not a separately maintained model shape, so * `User.modelSchema` remains the single source of truth. */ export type UserAuthDoc = Pick; /** Schema-derived hydrated fields the instance-side auth helpers bind to. */ export type UserAuthInstance = Pick & { save: () => Promise; }; /** * Any Mongoose `User` model an auth static can bind to: one whose documents * carry its selected {@link UserAuthDoc} fields. The framework's own `User` and * a replacement that supports that operation both satisfy it. * * `TSchema` is deliberately `unknown`. Since Mongoose 9.8.1, leaving that * generic as its `any` default reconstructs a fully typed `Model.schema`; that * makes otherwise-compatible models invariant in their complete raw schema. * These auth helpers never touch `schema`, so hiding only that unused surface * preserves the useful Model operations and the caller's concrete * `InstanceType` without requiring every customized User to have exactly the * framework schema. */ export type UserAuthModel = Model, object, object, object, HydratedDocument>, unknown>; /** * The fields `getPublic` reads, as a plain object (a `Pick` of the framework * document — NOT the Mongoose `Document` type, whose invariance would reject an * additive project model). Binding `this` to this keeps `getPublic`'s return * types PRECISE for every caller while still letting a project model that keeps * these fields reuse it. A model that reshapes them (e.g. an i18n `name`) * doesn't match and overrides `getPublic` with its own public shape. */ export type UserPublicDoc = Pick, 'avatar' | 'name' | 'email' | 'id' | 'isVerified' | 'permissions' | 'locale'>; /** * Augmentation point so `req.appInfo.user` follows a project's OWN `User` model * when it replaces the framework's. `node src/cli.ts generatetypes` emits this * automatically into `genTypes.d.ts` (mirroring how it types * `app.getModel('User')`); declare it by hand only if you don't run codegen. * `User` must be the hydrated DOCUMENT type, so wrap the model class in * `InstanceType>`: * * import type { GetModelTypeFromClass } from '@adaptivestone/framework/modules/BaseModel.js'; * declare module '@adaptivestone/framework/models/User.js' { * interface AppModels { * User: InstanceType>; * } * } */ export interface AppModels { } /** * The `User` instance type middlewares contribute to `req.appInfo.user`: the * project's own model when known (via `AppModels`), otherwise the framework's. * Keeps `appInfo.user` in sync with `app.getModel('User')`. */ export type AppUser = AppModels extends { User: infer U; } ? U : InstanceType; /** * The framework's default `User` model — and the intended customization point. * Two supported ways to replace it with a project model (drop yours in the * app's `models/` folder under the name `User`; codegen rebinds `getModel`, * `req.appInfo.user`, and `AppModels` to it): * * 1. **Add fields** — `extends User`, spread the schema, append your own: * ```ts * class User extends FrameworkUser { * static get modelSchema() { * return { ...FrameworkUser.modelSchema, company: { type: String } } as const; * } * } * ``` * The inherited auth statics & instance methods keep working as-is. * * 2. **Reshape fields** (e.g. an i18n `name`, a singular `role`) — TypeScript * can't express a field-type *replacement* through `extends` (the static-side * getter override is checked covariantly → TS2417), so **compose**: extend * {@link BaseModel} and reuse the auth logic by spreading it in. * ```ts * class User extends BaseModel { * static get modelSchema() { return { ...your reshaped schema } as const; } * static get modelStatics() { return { ...FrameworkUser.modelStatics } as const; } * static get modelInstanceMethods() { return { ...FrameworkUser.modelInstanceMethods } as const; } * static initHooks(schema: Schema) { FrameworkUser.initHooks(schema); } * } * ``` * The spread statics/methods are typed structurally ({@link UserAuthDoc} / * {@link UserAuthModel}), so they stay callable on your model without casts. */ declare class User extends BaseModel { static initHooks(schema: Schema): void; static get modelSchema(): { readonly avatar: { readonly type: StringConstructor; readonly maxlength: 255; }; readonly name: { readonly first: { readonly type: StringConstructor; readonly maxlength: 255; }; readonly last: { readonly type: StringConstructor; readonly maxlength: 255; }; readonly nick: { readonly minlength: 3; readonly maxlength: 255; readonly type: StringConstructor; readonly index: { readonly unique: true; readonly partialFilterExpression: { readonly 'name.nick': { readonly $type: 'string'; }; }; }; }; }; readonly password: StringConstructor; readonly email: { readonly type: StringConstructor; readonly maxlength: 255; readonly index: { readonly unique: true; readonly partialFilterExpression: { readonly email: { readonly $type: 'string'; }; }; }; }; readonly sessionTokens: readonly [{ readonly token: StringConstructor; readonly valid: DateConstructor; }]; readonly verificationTokens: readonly [{ readonly until: DateConstructor; readonly token: StringConstructor; }]; readonly passwordRecoveryTokens: readonly [{ readonly until: DateConstructor; readonly token: StringConstructor; }]; readonly permissions: readonly [StringConstructor]; readonly roles: readonly [StringConstructor]; readonly isVerified: { readonly type: BooleanConstructor; readonly default: false; }; readonly locale: { readonly type: StringConstructor; readonly default: 'en'; }; readonly languages: readonly [StringConstructor]; }; static get modelStatics(): { /** * Get user by email and password * @param {string} email * @param {string} password * @returns {Promise | false>} */ readonly getUserByEmailAndPassword: >(this: T, email: string, password: string) => Promise>; /** * Get user by token * @param {string} * @returns {Promise | false>} */ readonly getUserByToken: >(this: T, token: string) => Promise>; /** * Get user by email * @param {string} * @returns {Promise | false>} */ readonly getUserByEmail: >(this: T, email: string) => Promise>; /** * Get user by password recovery token and consume the token. Pass * `{ save: false }` to skip the write: the token is removed only from the * returned document, and your own `save()` persists it with your changes. * @param {string} passwordRecoveryToken * @param {{ save?: boolean }} [options] * @returns {Promise>} * @throws {Error} `User not exists` when no live token matches. */ readonly getUserByPasswordRecoveryToken: >(this: T, passwordRecoveryToken: string, options?: { save?: boolean; }) => Promise>; /** * Get user by verification token and consume the token. Pass * `{ save: false }` to skip the write: the token is removed only from the * returned document, and your own `save()` persists it with your changes. * @param {string} verificationToken * @param {{ save?: boolean }} [options] * @returns {Promise>} * @throws {Error} `User not exists` when no live token matches. */ readonly getUserByVerificationToken: >(this: T, verificationToken: string, options?: { save?: boolean; }) => Promise>; }; static get modelInstanceMethods(): { /** * Generate a session token for the user and save the document. Rejects * with a 400 `BadRequestError`, the wrong-password answer, when the stored * password changed after this document was read. * @returns {Object} */ readonly generateToken: (this: UserAuthInstance & Pick) => Promise<{ token: string; valid: Date; }>; /** * Send password recovery email * @param {Object} * @param {TI18n} * @param {string} i18n.language * @returns {Promise} */ readonly sendPasswordRecoveryEmail: (this: UserAuthInstance & { name?: { nick?: string | null; } | null; }, i18n: TI18n) => Promise; /** * Send verification email * @param {Object} * @param {TI18n} i18n * @param {string} i18n.language * @returns {Promise} */ readonly sendVerificationEmail: (this: UserAuthInstance & { name?: { nick?: string | null; } | null; }, i18n: TI18n) => Promise; /** * Get public user data * @returns {Object} */ readonly getPublic: (this: UserPublicDoc) => { avatar: string | null | undefined; name: Omit<{ _id: mongoose.Types.ObjectId; first?: string | null | undefined; last?: string | null | undefined; nick?: string | null | undefined; }, "_id"> | null | undefined; email: string | null | undefined; id: string; isVerified: boolean; permissions: mongoose.Types.Array; locale: string; }; }; } export declare const userHelpers: { /** * Generate user verification token * @param {InstanceType} userMongoose * @returns {Promise<{ token: string; until: number }>} */ generateUserVerificationToken: (userMongoose: UserAuthInstance) => Promise<{ token: string; until: number; }>; /** * Get user by id * @param {string} * @returns {Promise | false>} */ generateUserPasswordRecoveryToken: (userMongoose: UserAuthInstance) => Promise<{ token: string; until: number; }>; }; export default User;