Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/CI.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ jobs:
if: matrix.suite == 'unit'
run: npm run lint

- name: Typecheck JSDoc (once on the unit job)
if: matrix.suite == 'unit'
run: npm run typecheck

- name: Run tests
run: |
case "${{ matrix.suite }}" in
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ Tests are organized per module in `modules/*/tests/`. In CI the test job runs as
```bash
npm run lint # Check code quality (read-only)
npm run lint:fix # Auto-fix code quality issues
npm run typecheck # Check JSDoc types with tsc (read-only, CI)
npm run format # Format code with Prettier
```

Expand Down
2 changes: 1 addition & 1 deletion config/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ const initGlobalConfig = async () => {
config = deepMerge(config, environmentConfigVars);

// read package.json for project information
const packageJSON = JSON.parse(readFileSync(path.resolve('./package.json')));
const packageJSON = JSON.parse(readFileSync(path.resolve('./package.json'), 'utf8'));
config = deepMerge(config, { package: packageJSON });
// Initialize global globbed files
config = deepMerge(config, { files: await configHelper.initGlobalConfigFiles(assets) });
Expand Down
2 changes: 1 addition & 1 deletion lib/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const startMongoose = async () => {

/**
* Establish ExpressJS powered web server
* @return {object} app
* @return {Promise<import('express').Express>} app
*/
const startExpress = async () => {
try {
Expand Down
31 changes: 15 additions & 16 deletions lib/helpers/AppError.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,22 @@ const AppErrorCodes = {
serverError: 'SERVER_ERROR',
};

/**
* @desc Custom error class with Node + Express
* @param {String} message error
* @param {Object} options
* @param {*} [options.details] - structured/whitelisted or curated-internal data (see
* `lib/helpers/responses.js#getDescription` — its `details`-derived text is
* production-gated, issue #4059)
* @param {number} [options.status] - HTTP status code
* @param {string} [options.code] - stable domain error code
* @param {string} [options.description] - deliberately-authored, user-facing text a
* throw site chooses explicitly — NOT gated by `getDescription`'s production check
* (same precedence as an explicit `description` argument to `responses.error`; see
* that function's own doc comment). Use this for authored copy a real user should
* see in every environment; use `details` for internal/curated data instead.
*/

class AppError extends Error {
/**
* @desc Custom error class with Node + Express
* @param {String} message error
* @param {Object} [options]
* @param {*} [options.details] - structured/whitelisted or curated-internal data (see
* `lib/helpers/responses.js#getDescription` — its `details`-derived text is
* production-gated, issue #4059)
* @param {number} [options.status] - HTTP status code
* @param {string} [options.code] - stable domain error code
* @param {string} [options.description] - deliberately-authored, user-facing text a
* throw site chooses explicitly — NOT gated by `getDescription`'s production check
* (same precedence as an explicit `description` argument to `responses.error`; see
* that function's own doc comment). Use this for authored copy a real user should
* see in every environment; use `details` for internal/curated data instead.
*/
constructor(message, { details, status, code, description } = {}) {
super(message);
// Set HTTP status code
Expand Down
2 changes: 1 addition & 1 deletion lib/helpers/abilities.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* Serialize CASL abilities to a JSON-safe array compatible with createMongoAbility().
* @param {import('@casl/ability').MongoAbility} ability - The CASL ability instance
* @returns {Array<{action: string, subject: string, conditions?: Object, inverted?: boolean}>} Array of serialized rules
* @returns {Array<{action: string|string[], subject: import('@casl/ability').SubjectType|import('@casl/ability').SubjectType[], conditions?: Object, inverted?: boolean}>} Array of serialized rules
*/
const serializeAbilities = (ability) =>
ability.rules.map((rule) => ({
Expand Down
10 changes: 5 additions & 5 deletions lib/helpers/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,18 @@ const getGlobbedPaths = async (globPatterns, excludes) => {
output = _.union(output, await getGlobbedPaths(globPattern, excludes));
}
} else if (_.isString(globPatterns)) {
if (urlRegex.test(globPatterns)) {
output.push(globPatterns);
if (urlRegex.test(/** @type {string} */ (globPatterns))) {
output.push(/** @type {string} */ (globPatterns));
} else {
let files = glob.sync(globPatterns.replace(/\\/g, '/'));
let files = glob.sync(/** @type {string} */ (globPatterns).replace(/\\/g, '/'));
if (excludes) {
files = files.map((file) => {
if (_.isArray(excludes)) {
excludes.forEach((exclude) => {
/** @type {string[]} */ (excludes).forEach((exclude) => {
file = file.replace(exclude, '');
});
} else {
file = file.replace(excludes, '');
file = file.replace(/** @type {string} */ (excludes), '');
}
return file;
});
Expand Down
4 changes: 2 additions & 2 deletions lib/helpers/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import fs from 'fs';

/**
* @desc readFile from path
* @param {String} file path
* @return {String} file
* @param {String} path - file path
* @return {Promise<String>} file content
*/
const readFile = async (path) =>
new Promise((resolve, reject) => {
Expand Down
2 changes: 1 addition & 1 deletion lib/helpers/mailer/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ const render = async (key, params, { subject } = {}) => {
* @param {Object<string,string>} [mail.headers] - Custom headers (e.g.
* `List-Unsubscribe`), forwarded to the provider as-is; absent means
* today's behavior (no headers on the payload).
* @param {Array} [mail.attachments] - Optional attachments array
* @param {Object[]} [mail.attachments] - Optional attachments array
* @param {string} mail.attachments[].filename - Attachment filename
* @param {string|Buffer} mail.attachments[].content - Attachment content (string or Buffer)
* @returns {Promise<Object|null>} The send result, or null if not configured
Expand Down
2 changes: 1 addition & 1 deletion lib/helpers/mailer/provider.nodemailer.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export default class NodemailerProvider {
* payload (not sent as an empty/undefined field) when absent
* @param {Object<string,string>} [mail.headers] - Custom headers; omitted from the
* payload when absent
* @param {Array} [mail.attachments] - Optional attachments
* @param {Object[]} [mail.attachments] - Optional attachments
* @param {string} mail.attachments[].filename - Filename
* @param {string|Buffer} mail.attachments[].content - Attachment content (string or Buffer)
* @returns {Promise<Object>} Nodemailer send result
Expand Down
3 changes: 1 addition & 2 deletions lib/helpers/mailer/provider.resend.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ export default class ResendProvider {
* Create a Resend mail provider instance.
* @param {Object} options - Resend provider options
* @param {string} options.apiKey - Resend API key
* @returns {void}
*/
constructor(options) {
if (!options?.apiKey) throw new Error('Resend provider requires an apiKey');
Expand All @@ -23,7 +22,7 @@ export default class ResendProvider {
* payload (not sent as an empty/undefined field) when absent
* @param {Object<string,string>} [mail.headers] - Custom headers; omitted from the
* payload when absent
* @param {Array} [mail.attachments] - Optional attachments
* @param {Object[]} [mail.attachments] - Optional attachments
* @param {string} mail.attachments[].filename - Filename
* @param {string|Buffer} mail.attachments[].content - Content (string or Buffer)
* @returns {Promise<Object>} Resend API response data
Expand Down
5 changes: 3 additions & 2 deletions lib/helpers/responses.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import UNSAFE_KEYS from './unsafeKeys.js';
/**
* @desc Function res success
* @param {Object} res - Express response object
* @param {String} success message
* @param {String} message - success message
* @return {Object} type, message and data
*/
const success = (res, message) => (data) => {
Expand Down Expand Up @@ -283,7 +283,7 @@ const safeStringify = (value) => {
* longer has to hand-write a title that must stay in sync with a dynamic
* status. An explicit title is unchanged; the omitted-title fallback
* changes from `error.message` to `STATUS_CODES[status]` (#4009).
* @param {string} description - Optional detailed error description
* @param {string} [description] - Optional detailed error description
* @returns {Object} type, message, code, status, errorCode, description and (when
* any whitelisted key was present) details
*/
Expand All @@ -304,6 +304,7 @@ const error = (res, httpStatus, message, description) => (error = {}) => {
rawDetails = undefined;
}
const whitelistedDetails = pickWhitelistedDetails(rawDetails);
/** @type {{type: string, message: string, code: number, status: number, errorCode: string, description: string, details?: Object, error?: string}} */
const result = {
type: 'error',
// Explicit title wins (backward compatible with every existing call
Expand Down
10 changes: 5 additions & 5 deletions lib/middlewares/policy.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,17 @@ const methodToAction = {

/**
* Registry of ability builder functions discovered from module policy files.
* Each entry is { fn, guest } where fn(user, membership, { can, cannot }) is called
* for authenticated users and guest({ can, cannot }) is called for unauthenticated visitors.
* @type {Array<{fn?: Function, guest?: Function}>}
* Each entry is { abilities, guestAbilities } where abilities(user, membership, { can, cannot }) is called
* for authenticated users and guestAbilities({ can, cannot }) is called for unauthenticated visitors.
* @type {Array<{abilities?: Function, guestAbilities?: Function}>}
*/
const abilitiesRegistry = [];

/**
* Registry of document-level subject resolvers.
* Each entry maps a req property to a CASL subject type string.
* Modules register themselves via registerDocumentSubject() during startup.
* @type {Array<{reqProperty: string, subjectType: string}>}
* @type {Array<{reqProperty: string, subjectType: string, guard?: Function}>}
*/
const documentSubjectRegistry = [];

Expand Down Expand Up @@ -184,7 +184,7 @@ const resolveSubject = (req) => {
* @param {Object} req - Express request object
* @param {Object} res - Express response object
* @param {Function} next - Express next middleware function
* @returns {void}
* @returns {Promise<void>}
*/
const isAllowed = async (req, res, next) => {
const action = methodToAction[req.method.toLowerCase()];
Expand Down
5 changes: 2 additions & 3 deletions lib/middlewares/rateLimiter.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,8 @@ const defaultKeyGenerator = (req) => req.user?._id?.toString() || ipKeyGenerator
/**
* @desc Proxy that lazily creates rate-limit middleware for each named profile.
* Returns the configured limiter or a passthrough when the profile is missing.
* @param {Object} target - Internal cache of created limiters
* @param {string|symbol} name - The rate-limit profile name to look up
* @returns {Function} Express middleware (rate limiter or passthrough)
* Each property read (e.g. `limiters.api`) yields an Express middleware.
* @type {Record<string, import('express').RequestHandler>}
*/
const limiters = new Proxy({}, {
get(target, name) {
Expand Down
6 changes: 3 additions & 3 deletions lib/services/analytics.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ const track = (distinctId, event, properties, groups) => {
* 3. `req.posthogContext.source` (set by posthogContextMiddleware)
* 4. `'system'` default
*
* @param {Object} params - Event parameters
* @param {string} params.distinctId - User or anonymous identifier
* @param {string} params.event - Event name
* @param {Object} [params] - Event parameters
* @param {string} [params.distinctId] - User or anonymous identifier (no-op when missing)
* @param {string} [params.event] - Event name (no-op when missing)
* @param {Object} [params.properties] - Additional event properties (win over defaults)
* @param {import('express').Request} [params.req] - Optional Express request for context injection
* @param {string} [params.source] - Explicit source override (wins over req + properties)
Expand Down
1 change: 1 addition & 0 deletions lib/services/distributedLock.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const LockSchema = new mongoose.Schema(
// MongoDB TTL index — auto-deletes expired docs so stale locks don't accumulate.
LockSchema.index({ lockedUntil: 1 }, { expireAfterSeconds: 0 });

/** @type {import('mongoose').Model<{_id: string, lockedAt: Date, lockedUntil: Date, holder: string}>} */
export const CronLock = mongoose.models.CronLock ?? mongoose.model('CronLock', LockSchema);

/**
Expand Down
3 changes: 1 addition & 2 deletions lib/services/express.js
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,6 @@ const initHelmetHeaders = (app) => {
helmet.hsts({
maxAge: SIX_MONTHS,
includeSubDomains: true,
force: true,
}),
);
app.disable('x-powered-by');
Expand Down Expand Up @@ -397,7 +396,7 @@ const init = async () => {
// Initialize Modules configuration
await initModulesConfiguration(app);
// Initialize modules server authorization policies
await initModulesServerPolicies(app);
await initModulesServerPolicies();
// Initialize modules server routes
await initModulesServerRoutes(app);
// Mount error tracker handler (PostHog Error Tracking) — must be after routes
Expand Down
19 changes: 16 additions & 3 deletions lib/services/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,20 @@ const consoleFormat = useJson
? winston.format.combine(winston.format.timestamp(), winston.format.json())
: winston.format.combine(winston.format.colorize(), winston.format.simple());

/**
* The winston logger plus the helpers this module attaches to it.
* @typedef {Omit<winston.Logger, 'stream'> & {
* stream: { write: (msg: string) => void },
* getLogOptions: () => object | false,
* setupFileLogger: () => boolean,
* getMorganOptions: () => { stream: { write: (msg: string) => void } },
* getLogFormat: () => string,
* }} AppLogger
*/

// Instantiating the default winston application logger with the Console
// transport

/* eslint new-cap: 0 */
const logger = new winston.createLogger({
const winstonLogger = winston.createLogger({
level: logLevel,
transports: [
new winston.transports.Console({
Expand All @@ -39,6 +48,10 @@ const logger = new winston.createLogger({
exitOnError: false,
});

// The helpers below are attached after creation and `stream` is replaced,
// hence the cast through unknown.
const logger = /** @type {AppLogger} */ (/** @type {unknown} */ (winstonLogger));

if (config?.analytics?.posthog?.errorTracking === true) {
logger.add(new PostHogErrorTransport());
}
Expand Down
2 changes: 1 addition & 1 deletion lib/services/migrations.js
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ const runMigration = async (filePath, executed) => {
* {@link claimMigration}; without it, concurrent runners can execute the same
* migration twice. Delegates to the repository so the service layer never
* touches Mongoose directly.
* @returns {Promise<void>} Resolves once indexes have been synchronised.
* @returns {Promise<string[]>} Names of indexes dropped during sync.
*/
const ensureMigrationIndexes = () => migrationRepository.syncIndexes();

Expand Down
4 changes: 2 additions & 2 deletions lib/services/mongoose.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const INDEX_CONFLICT_CODE_NAMES = new Set(['IndexOptionsConflict', 'IndexKeySpec
/**
* @desc Whether an index-build rejection is a same-name conflict with a
* pre-existing index (see {@link INDEX_CONFLICT_CODES}).
* @param {Error} err - rejection from `Model#init()`
* @param {Error & {code?: number, codeName?: string}} err - rejection from `Model#init()`
* @returns {boolean} true when the error is an index-name conflict
*/
const isIndexConflictError = (err) => INDEX_CONFLICT_CODES.has(err?.code) || INDEX_CONFLICT_CODE_NAMES.has(err?.codeName);
Expand All @@ -57,7 +57,7 @@ const isIndexConflictError = (err) => INDEX_CONFLICT_CODES.has(err?.code) || IND
* throws: spec enumeration failures are logged and swallowed, since this runs
* on a boot path that must proceed to the migration runner (#4004).
* @param {string} modelName - name of the model whose index build conflicted
* @param {Error} err - the conflict rejection from `Model#init()`
* @param {Error & {code?: number, codeName?: string}} err - the conflict rejection from `Model#init()`
* @returns {Promise<void>} resolves once the conflict has been logged
*/
const logIndexConflict = async (modelName, err) => {
Expand Down
8 changes: 5 additions & 3 deletions lib/services/multer.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,19 @@ import gridfsService from './gridfs.js';
/**
* @desc File filter
* @param {Array} formats - array of accepted mimetype string
* @return {callback}
* @param {number} size - max accepted size in bytes
* @return {Function} multer fileFilter(req, file, cb)
*/
const fileFilter = (formats, size) => (req, file, cb) => {
const fileSize = parseInt(req.headers['content-length'], 10);
if (fileSize > size) {
/** @type {Error & {code?: string}} */
const err = new Error(`Only files lower than ${size / (1024 * 1024)}mo are allowed`);
err.code = 'SERVICE_ERROR';
return cb(err, false);
}
if (!formats.includes(file.mimetype)) {
/** @type {Error & {code?: string}} */
const err = new Error(`Only ${formats} files allowed`);
err.code = 'SERVICE_ERROR';
return cb(err, false);
Expand All @@ -29,9 +32,8 @@ const fileFilter = (formats, size) => (req, file, cb) => {

/**
* @desc file upload middleware
* @param {String} name - key data name in form-data
* @param {Object} config - multer config
* @return {callback}
* @return {Function} async Express middleware(req, res, next)
*/
const create = (config) => async (req, res, next) => {
// condif
Expand Down
1 change: 1 addition & 0 deletions modules/audit/repositories/audit.repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ const validate = (data) => AuditSchema.AuditLog.safeParse(data);
const create = (data) => {
const parsed = validate(data);
if (!parsed.success) {
/** @type {Error & {validationErrors?: Object}} */
const err = new Error('AuditLog validation failed');
err.validationErrors = parsed.error.flatten();
throw err;
Expand Down
4 changes: 2 additions & 2 deletions modules/audit/services/audit.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import AuditRepository from '../repositories/audit.repository.js';
/**
* @function log
* @description Record an audit log entry. No-op when audit is disabled.
* @param {Object} params
* @param {string} params.action - Action identifier (e.g. 'auth.login', 'billing.subscribe')
* @param {Object} [params]
* @param {string} [params.action] - Action identifier (no-op when missing) (e.g. 'auth.login', 'billing.subscribe')
* @param {string} [params.userId] - ID of the acting user
* @param {string} [params.organizationId] - ID of the organization context
* @param {string} [params.ip] - IP address of the request
Expand Down
2 changes: 1 addition & 1 deletion modules/billing/lib/billing.stripe-errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const NON_TRANSIENT_STRIPE_ERROR_CLASSES = new Set([
* retrying. StripeCardError (402) is intentionally excluded — some decline codes
* (processing_error, issuer_unavailable) are transient.
*
* @param {unknown} err
* @param {{type?: string, rawType?: string}|null|undefined} err - Stripe SDK error or raw API error object
* @returns {boolean}
*/
export function isNonTransientStripeError(err) {
Expand Down
1 change: 1 addition & 0 deletions modules/billing/lib/stripe.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ let stripeClient = null;
const getStripe = () => {
if (stripeClient) return stripeClient;
if (!config.stripe?.secretKey) return null;
// @ts-expect-error stripe-node types only accept its latest apiVersion; pinning an older one is supported (stripe-node README)
stripeClient = new Stripe(config.stripe.secretKey, { apiVersion: '2026-04-22.dahlia' });
return stripeClient;
};
Expand Down
Loading
Loading