From 426ea6b460960b3dd67ee2bf43b350710a04ab0c Mon Sep 17 00:00:00 2001 From: Pierre Brisorgueil Date: Thu, 12 Nov 2026 15:34:22 +0100 Subject: [PATCH 1/2] ci(typecheck): check JSDoc types in the remaining stack modules (part 2, WIP) Add auth, users, invitations, billing, organizations, uploads to tsconfig.check.json and fix their JSDoc: stale param names, async returns, typed Mongoose models via JSDoc casts, Error extra fields, optional params. No behaviour change (comment-stripped emit identical apart from JSDoc cast parentheses). 3 tsc errors left, held for a decision: an object-first winston call in auth (real log bug) and Date arithmetic in billing isoWeekKey. Refs pierreb-devkit/Node#4270 --- modules/auth/controllers/auth.controller.js | 5 ++- modules/auth/services/auth.eligibility.js | 4 +-- modules/auth/services/auth.service.js | 4 +-- modules/billing/lib/billing.isoWeek.js | 4 +-- modules/billing/lib/billing.planResolver.js | 1 + modules/billing/lib/billing.retry.js | 1 + ...nt-signup-credits-to-existing-free-orgs.js | 14 +++++++- ...8120000-fix-usage-weekkey-index-partial.js | 6 ++-- .../billing.subscription.model.mongoose.js | 4 +-- .../billing.subscription.repository.js | 32 ++++++++++++++++--- .../billing/services/billing.extra.service.js | 5 +-- .../services/billing.referral.service.js | 15 +++++---- modules/billing/services/billing.service.js | 4 ++- .../controllers/invitations.controller.js | 2 ++ .../repositories/invitations.repository.js | 17 +++++++++- .../controllers/organizations.controller.js | 20 ++++++------ .../organizations.membership.controller.js | 12 +++---- .../20260310120000-organizations-init.js | 22 ++++++++++--- .../models/organizations.model.mongoose.js | 2 +- .../uploads/controllers/uploads.controller.js | 4 +-- .../repositories/uploads.repository.js | 32 +++++++++++++------ modules/uploads/services/uploads.service.js | 10 +++--- .../controllers/users.account.controller.js | 1 + tsconfig.check.json | 2 +- 24 files changed, 153 insertions(+), 70 deletions(-) diff --git a/modules/auth/controllers/auth.controller.js b/modules/auth/controllers/auth.controller.js index 7ac885880..c37a648e9 100644 --- a/modules/auth/controllers/auth.controller.js +++ b/modules/auth/controllers/auth.controller.js @@ -124,7 +124,6 @@ const signinAuthenticate = (req, res, next) => { * @desc Endpoint to ask the service to connect a user * @param {Object} req - Express request object * @param {Object} res - Express response object - * @param {Function} next - Express next middleware function */ const signin = async (req, res) => { if (!config.sign.in) return responses.error(res, 404, 'Signin error', 'Login is currently deactivated')(); @@ -755,7 +754,7 @@ const getConfig = async (req, res) => { * @desc Endpoint to verify a user email address using a token * @param {Object} req - Express request object (req.params.token) * @param {Object} res - Express response object - * @returns {void} Sends JSON response indicating verification success or failure + * @returns {Promise} Sends JSON response indicating verification success or failure */ const verifyEmail = async (req, res) => { try { @@ -791,7 +790,7 @@ const verifyEmail = async (req, res) => { * @desc Endpoint to resend the verification email for the authenticated user * @param {Object} req - Express request object (req.user must be set) * @param {Object} res - Express response object - * @returns {void} Sends JSON response confirming the email was resent or an error + * @returns {Promise} Sends JSON response confirming the email was resent or an error */ const resendVerification = async (req, res) => { try { diff --git a/modules/auth/services/auth.eligibility.js b/modules/auth/services/auth.eligibility.js index 3caf31d49..2bbc72793 100644 --- a/modules/auth/services/auth.eligibility.js +++ b/modules/auth/services/auth.eligibility.js @@ -16,7 +16,7 @@ const checks = []; /** * Register a signup eligibility check. Each fn(ctx) may throw an AppError to block * signup, and/or return a result object (opaque to auth) — or undefined. - * @param {(ctx: { email?: string, body?: Object, req?: Object, oauth?: Object }) => (any|Promise)} fn + * @param {(ctx: { email?: string, body?: Object, req?: Object, oauth?: Object, signupOpen?: boolean }) => (any|Promise)} fn * @returns {void} */ export const registerSignupEligibility = (fn) => { @@ -40,7 +40,7 @@ export const registerSignupEligibility = (fn) => { * check aborts the whole chain and blocks signup — even a check that runs AFTER * an earlier one already resolved a non-null result. Throwing is "block signup", * not "I have no opinion"; return `undefined` for the latter. Order matters. - * @param {{ email?: string, body?: Object, req?: Object, oauth?: Object }} ctx + * @param {{ email?: string, body?: Object, req?: Object, oauth?: Object, signupOpen?: boolean }} ctx - `signupOpen`: public signup is open, so an invite is presented but not required * @returns {Promise} the first non-null check result, or null */ export const assertSignupEligible = async (ctx) => { diff --git a/modules/auth/services/auth.service.js b/modules/auth/services/auth.service.js index 23360e7eb..ba1ef7e86 100644 --- a/modules/auth/services/auth.service.js +++ b/modules/auth/services/auth.service.js @@ -140,9 +140,9 @@ const checkPassword = (password) => { /** * @desc Seed : Function to generateRandomPassphrase * Generates a random passphrase that passes the zxcvbn test - * Returns a promise that resolves with the generated passphrase, or rejects with an error if something goes wrong. + * Returns the generated passphrase, or throws if it fails the strength test. * NOTE: Passphrases are only tested against the required zxcvbn strength tests, and not the optional tests. - * @return {Promise} user + * @return {string} the generated passphrase */ const generateRandomPassphrase = () => { let password = ''; diff --git a/modules/billing/lib/billing.isoWeek.js b/modules/billing/lib/billing.isoWeek.js index e638fcf7f..616abc15b 100644 --- a/modules/billing/lib/billing.isoWeek.js +++ b/modules/billing/lib/billing.isoWeek.js @@ -1,11 +1,11 @@ +const MS_PER_DAY = 86_400_000; + /** * @function isoWeekKey * @description Compute the ISO 8601 week key in YYYY-Www format. * @param {Date} date - Date to compute. * @returns {string} ISO week key. */ -const MS_PER_DAY = 86_400_000; - export const isoWeekKey = (date) => { const d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate())); d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7)); diff --git a/modules/billing/lib/billing.planResolver.js b/modules/billing/lib/billing.planResolver.js index f3c402510..58468bbe6 100644 --- a/modules/billing/lib/billing.planResolver.js +++ b/modules/billing/lib/billing.planResolver.js @@ -24,6 +24,7 @@ const validPlans = new Set(config.billing?.plans || ['free', 'starter', 'pro', ' * @returns {Record} priceId → planId map (built once at module init) */ export const buildPriceIdToPlanMap = () => { + /** @type {Record} */ const map = {}; const stripePrices = config.stripe?.prices || {}; for (const [planId, intervals] of Object.entries(stripePrices)) { diff --git a/modules/billing/lib/billing.retry.js b/modules/billing/lib/billing.retry.js index d5448869b..0fa7047cd 100644 --- a/modules/billing/lib/billing.retry.js +++ b/modules/billing/lib/billing.retry.js @@ -10,6 +10,7 @@ * false for a thrown error, the error is rethrown immediately without * further attempts or delay. * + * @template T * @param {() => Promise} fn - Async function to attempt. * @param {object} [opts] * @param {number} [opts.attempts=3] - Maximum number of attempts (including the first call). diff --git a/modules/billing/migrations/20260511224500-grant-signup-credits-to-existing-free-orgs.js b/modules/billing/migrations/20260511224500-grant-signup-credits-to-existing-free-orgs.js index 978547f3e..af3be7993 100644 --- a/modules/billing/migrations/20260511224500-grant-signup-credits-to-existing-free-orgs.js +++ b/modules/billing/migrations/20260511224500-grant-signup-credits-to-existing-free-orgs.js @@ -22,12 +22,24 @@ import mongoose from 'mongoose'; const SIGNUP_GRANT_AMOUNT = 500; const GRANT_SOURCE = 'signup_grant'; +/** + * Raw `billingextrabalances` document fields this migration writes (driver level, no Mongoose). + * @typedef {Object} ExtraBalanceRawDoc + * @property {import('mongodb').ObjectId} organization + * @property {Array<{kind: string, amount: number, source?: string, refId?: string, at: Date}>} ledger + * @property {number} cachedBalance + * @property {Date} cachedBalanceAt + * @property {Date} [createdAt] + * @property {Date} [updatedAt] + */ + /** * @returns {Promise} */ export async function up() { const db = mongoose.connection.db; const subscriptions = db.collection('subscriptions'); + /** @type {import('mongodb').Collection} */ const extraBalances = db.collection('billingextrabalances'); const cursor = subscriptions.find( @@ -107,7 +119,7 @@ export async function up() { export async function down() { const db = mongoose.connection.db; - const result = await db.collection('billingextrabalances').updateMany( + const result = await /** @type {import('mongodb').Collection} */ (db.collection('billingextrabalances')).updateMany( { 'ledger.source': GRANT_SOURCE }, { $pull: { ledger: { source: GRANT_SOURCE } } }, ); diff --git a/modules/billing/migrations/20260728120000-fix-usage-weekkey-index-partial.js b/modules/billing/migrations/20260728120000-fix-usage-weekkey-index-partial.js index e4a8a08b0..383cf6c61 100644 --- a/modules/billing/migrations/20260728120000-fix-usage-weekkey-index-partial.js +++ b/modules/billing/migrations/20260728120000-fix-usage-weekkey-index-partial.js @@ -34,16 +34,16 @@ const isExactTargetIndex = (ix) => * unique partial index would reject. Shared by the upfront pre-check (a) and * the post-createIndex E11000 re-derivation, so both report the identical set. * @param {import('mongodb').Collection} usages - the billingusages collection. - * @returns {Promise>} + * @returns {Promise}>>} */ const findWeekKeyDuplicates = (usages) => - usages + /** @type {Promise}>>} */ (usages .aggregate([ { $match: { weekKey: { $exists: true } } }, { $group: { _id: { organizationId: '$organizationId', weekKey: '$weekKey' }, count: { $sum: 1 }, ids: { $push: '$_id' } } }, { $match: { count: { $gt: 1 } } }, ]) - .toArray(); + .toArray()); /** * Migration: working (organizationId, weekKey) meter-mode partial-unique index (#3991). diff --git a/modules/billing/models/billing.subscription.model.mongoose.js b/modules/billing/models/billing.subscription.model.mongoose.js index 31eae837a..241f7561d 100644 --- a/modules/billing/models/billing.subscription.model.mongoose.js +++ b/modules/billing/models/billing.subscription.model.mongoose.js @@ -29,12 +29,12 @@ const SubscriptionMongoose = new Schema( }, plan: { type: String, - enum: config.billing.plans, + enum: /** @type {string[]} */ (config.billing.plans), default: 'free', }, status: { type: String, - enum: config.billing.statuses, + enum: /** @type {string[]} */ (config.billing.statuses), default: 'active', }, diff --git a/modules/billing/repositories/billing.subscription.repository.js b/modules/billing/repositories/billing.subscription.repository.js index 6b444582b..9ba98aa31 100644 --- a/modules/billing/repositories/billing.subscription.repository.js +++ b/modules/billing/repositories/billing.subscription.repository.js @@ -4,7 +4,29 @@ import mongoose from 'mongoose'; import { bumpEventMarkers } from '../lib/billing.markerBump.js'; -const Subscription = mongoose.model('Subscription'); +/** + * Stored Subscription fields (see billing.subscription.model.mongoose.js). + * @typedef {Object} SubscriptionDoc + * @property {import('mongoose').Types.ObjectId} organization + * @property {string} [stripeCustomerId] + * @property {string} [stripeSubscriptionId] + * @property {string} plan + * @property {string} status + * @property {string} [planVersion] + * @property {Date|null} currentPeriodStart + * @property {Date|null} pastDueSince + * @property {Date|null} lastResetAt + * @property {number|null} lastSubscriptionEventCreatedAt + * @property {string|null} lastSubscriptionEventId + * @property {number|null} lastInvoiceEventCreatedAt + * @property {string|null} lastInvoiceEventId + * @property {Date|null} adminUpdatedAt + * @property {import('mongoose').Types.ObjectId|null} adminUpdatedBy + * @property {boolean|null} cancelAtPeriodEnd + * @property {Date|null} cancelAt + */ + +const Subscription = /** @type {import('mongoose').Model} */ (mongoose.model('Subscription')); const defaultPopulate = [ { @@ -119,7 +141,7 @@ const findByStripeSubscriptionId = (stripeSubscriptionId) => { * subscription (see `failClosedStatuses` in `../lib/constants.js`) without * a second query (#4151). * @param {String} organizationId - The organization ID. - * @returns {Promise<{plan: string, status: string}|null>} A lean plain object, or null. + * @returns {Promise<{plan: string, status: string}|null>|null} A lean plain object, or null (also returned synchronously for an invalid id). */ // biome-ignore lint/correctness/useQwikValidLexicalScope: false positive — Node.js repository, not Qwik const findPlan = (organizationId) => { @@ -134,7 +156,8 @@ const findPlan = (organizationId) => { * because resetWeek derives the next usage period from that timestamp. * Returns lean plain objects (no population) for performance. * @param {Date} now - The current timestamp used to compute the stale-reset threshold. - * @returns {Promise>} + * @returns {PromiseLike>} + * A thenable lean query (awaited by the caller). */ // biome-ignore lint/correctness/useQwikValidLexicalScope: false positive — Node.js repository, not Qwik const findAllDueForResetByLastReset = (now) => { @@ -180,7 +203,8 @@ const updateLastResetAt = (organizationId, date) => { * Used by the dunning sweep cron to transition stale past_due subs to 'unpaid'. * Returns lean plain objects for performance. * @param {Date} threshold - Subscriptions with pastDueSince <= threshold are returned. - * @returns {Promise>} + * @returns {PromiseLike>} + * A thenable lean query (awaited by the caller). */ // biome-ignore lint/correctness/useQwikValidLexicalScope: false positive — Node.js repository, not Qwik const findStaleDunning = (threshold) => { diff --git a/modules/billing/services/billing.extra.service.js b/modules/billing/services/billing.extra.service.js index ec50b1933..8d1223b06 100644 --- a/modules/billing/services/billing.extra.service.js +++ b/modules/billing/services/billing.extra.service.js @@ -53,12 +53,13 @@ const creditPack = async (orgId, packId, stripeSessionId) => { * @param {string} orgId - The organization ObjectId (string). * @param {number} units - Meter units to debit (must be > 0). * @param {string} refId - Unique reference for this debit (idempotency key). - * @returns {Promise<{doc: Object|null, applied: boolean}>} Updated doc and whether debit was applied. + * @returns {Promise<{doc: Object|null, applied: boolean, reason?: string}>} Updated doc and whether debit was applied + * (`reason: 'duplicate_step'` on a refId replay). */ // biome-ignore lint/correctness/useQwikValidLexicalScope: false positive — Node.js service, not Qwik const debit = (orgId, units, refId) => retryWithBackoff(() => BillingExtraBalanceRepository.debit(orgId, units, refId), { - shouldRetry: (err) => + shouldRetry: /** @param {Error & {code?: string}} err - error thrown by the repository debit */ (err) => !(typeof err?.message === 'string' && err.message.startsWith('invalid argument')) && err?.code !== 'ORGANIZATION_NOT_FOUND', }); diff --git a/modules/billing/services/billing.referral.service.js b/modules/billing/services/billing.referral.service.js index 9eea68173..9a2fb6f46 100644 --- a/modules/billing/services/billing.referral.service.js +++ b/modules/billing/services/billing.referral.service.js @@ -92,6 +92,7 @@ const expectedGrantKeys = (record, cfg) => { if (!described) return []; const { root, referrerId, refereeId, referrerSuffix = '' } = described; const keys = referralKeys(root); + /** @type {Array<{side: 'referrer'|'referee', key: string}>} */ const expected = []; // Referee side — needs configured units and a referee user (legacy rows may have none). if (cfg.refereeUnits > 0 && refereeId) expected.push({ side: 'referee', key: keys.referee }); @@ -285,10 +286,10 @@ const grantRecord = async (record, referrerId, refereeId, cfg) => { * `grantRecord`). No-op (`skipped:'disabled'`) when * `config.billing.referral.enabled` is false. Each side is keyed * `referral::` so replays can never double-credit. - * @param {Object} payload - The `invitation.accepted` payload (or its cron reconstruction). - * @param {string} payload.invitationId - The accepted invitation id (idempotency root). - * @param {string|null} payload.invitedBy - The inviter user id, or null. - * @param {string|null} payload.acceptedUserId - The referee (just-created user) id, or null for legacy/cron rows. + * @param {Object} [payload] - The `invitation.accepted` payload (or its cron reconstruction). + * @param {string} [payload.invitationId] - The accepted invitation id (idempotency root); skipped (`no_invitation_id`) when missing. + * @param {string|null} [payload.invitedBy] - The inviter user id, or null. + * @param {string|null} [payload.acceptedUserId] - The referee (just-created user) id, or null for legacy/cron rows. * @returns {Promise<{skipped?: string, referrer?: Object, referee?: Object}>} */ // biome-ignore lint/correctness/useQwikValidLexicalScope: false positive — Node.js service, not Qwik @@ -349,9 +350,9 @@ const linkBudget = async (referredBy, cap) => { * (`cap_reached`; a user whose own referrer grant already landed is never * locked out of finishing their referee side). May reject on infrastructure * errors — callers own their failure handling. - * @param {Object} payload - * @param {string} payload.userId - The referred (just-signed-up) user id. - * @param {string} payload.referredBy - The referrer user id. + * @param {Object} [payload] + * @param {string} [payload.userId] - The referred (just-signed-up) user id; skipped (`no_link`) when missing. + * @param {string} [payload.referredBy] - The referrer user id; skipped (`no_link`) when missing. * @param {Object|null} [payload.invitation] - The caller's already-fetched accepted * invitation for this user (null = looked up, none). Omit to look it up here. * @returns {Promise<{skipped?: string, referrer?: Object, referee?: Object}>} diff --git a/modules/billing/services/billing.service.js b/modules/billing/services/billing.service.js index 83938450b..7a9f8197e 100644 --- a/modules/billing/services/billing.service.js +++ b/modules/billing/services/billing.service.js @@ -94,7 +94,7 @@ const _ensureStripeCustomer = async (stripe, organization) => { /** * @desc Create a Stripe Customer Portal session for the given organization * @param {Object} organization - The organization document - * @param {String} returnUrl - Optional URL to redirect back to after portal + * @param {String} [returnUrl] - Optional URL to redirect back to after portal * @returns {Promise} Portal session URL */ const createPortalSession = async (organization, returnUrl) => { @@ -149,6 +149,7 @@ const createCheckout = async (organization, priceId, successUrl, cancelUrl) => { const blockStatuses = ['active', 'trialing', 'past_due']; if (existingForBlock?.stripeSubscriptionId && blockStatuses.includes(existingForBlock.status)) { const portalUrl = await createPortalSession(organization); + /** @type {Error & {statusCode?: number, code?: string, portalUrl?: string}} */ const err = new Error('Subscription already active'); err.statusCode = 409; err.code = 'subscription_already_active'; @@ -172,6 +173,7 @@ const createCheckout = async (organization, priceId, successUrl, cancelUrl) => { const blockingSub = liveSubs.data.find((s) => ['active', 'trialing'].includes(s.status)); if (blockingSub) { const portalUrl = await createPortalSession(organization); + /** @type {Error & {statusCode?: number, code?: string, portalUrl?: string}} */ const err = new Error('Subscription already active'); err.statusCode = 409; err.code = 'subscription_already_active'; diff --git a/modules/invitations/controllers/invitations.controller.js b/modules/invitations/controllers/invitations.controller.js index f19d22797..88f3090d6 100644 --- a/modules/invitations/controllers/invitations.controller.js +++ b/modules/invitations/controllers/invitations.controller.js @@ -9,6 +9,7 @@ import InvitationService from '../services/invitations.service.js'; /** * @desc Admin: create + email a signup invitation * @param {Object} req - Express request object + * @param {Object} req.body - Request body * @param {string} req.body.email - Email address to invite * @param {Object} req.user - Authenticated admin user * @param {Object} res - Express response object @@ -119,6 +120,7 @@ const resend = async (req, res) => { /** * @desc Public: report whether a token is a valid invite (+ prefill email) * @param {Object} req - Express request object + * @param {Object} req.params - Route parameters * @param {string} req.params.token - Invitation token to verify * @param {Object} res - Express response object * @returns {Promise} Sends HTTP 200 with { valid, email } or 422 on error diff --git a/modules/invitations/repositories/invitations.repository.js b/modules/invitations/repositories/invitations.repository.js index 8dc64ab31..a284b764e 100644 --- a/modules/invitations/repositories/invitations.repository.js +++ b/modules/invitations/repositories/invitations.repository.js @@ -3,7 +3,22 @@ */ import mongoose from 'mongoose'; -const Invitation = mongoose.model('Invitation'); +/** + * Stored Invitation fields (see invitations.model.mongoose.js). + * @typedef {Object} InvitationDoc + * @property {string} email + * @property {string} token + * @property {import('mongoose').Types.ObjectId|null} invitedBy + * @property {Date} expiresAt + * @property {Date|null} usedAt + * @property {Date|null} consumingAt + * @property {Date|null} acceptedAt + * @property {import('mongoose').Types.ObjectId|null} acceptedUserId + * @property {Date|null} revokedAt + * @property {'pending'|'accepted'|'revoked'} status + */ + +const Invitation = /** @type {import('mongoose').Model} */ (mongoose.model('Invitation')); /** * @desc Create an invitation document diff --git a/modules/organizations/controllers/organizations.controller.js b/modules/organizations/controllers/organizations.controller.js index 4a4919af5..04048d766 100644 --- a/modules/organizations/controllers/organizations.controller.js +++ b/modules/organizations/controllers/organizations.controller.js @@ -25,7 +25,7 @@ const tokenCookieOptions = { * @description Endpoint to fetch the list of organizations the current user belongs to. * @param {Object} req - Express request object * @param {Object} res - Express response object - * @returns {void} + * @returns {Promise} */ const list = async (req, res) => { try { @@ -41,7 +41,7 @@ const list = async (req, res) => { * @description Endpoint to create a new organization. The creator becomes the owner. * @param {Object} req - Express request object * @param {Object} res - Express response object - * @returns {void} + * @returns {Promise} */ const create = async (req, res) => { try { @@ -78,7 +78,7 @@ const get = (req, res) => { * @description Endpoint to update an existing organization. * @param {Object} req - Express request object * @param {Object} res - Express response object - * @returns {void} + * @returns {Promise} */ const update = async (req, res) => { try { @@ -102,7 +102,7 @@ const update = async (req, res) => { * @description Endpoint to delete an existing organization. * @param {Object} req - Express request object * @param {Object} res - Express response object - * @returns {void} + * @returns {Promise} */ const remove = async (req, res) => { try { @@ -130,7 +130,7 @@ const remove = async (req, res) => { * @description Platform admin endpoint to list all organizations. * @param {Object} req - Express request object * @param {Object} res - Express response object - * @returns {void} + * @returns {Promise} */ const adminList = async (req, res) => { try { @@ -181,7 +181,7 @@ const organizationByPage = async (req, res, next, params) => { * @description Endpoint to search organizations by name. * @param {Object} req - Express request object * @param {Object} res - Express response object - * @returns {void} + * @returns {Promise} */ const search = async (req, res) => { try { @@ -209,7 +209,7 @@ const search = async (req, res) => { * @param {Object} res - Express response object * @param {Function} next - Express next middleware function * @param {String} id - ID of the organization to fetch - * @returns {void} + * @returns {Promise} */ const organizationByID = async (req, res, next, id) => { try { @@ -237,7 +237,7 @@ const organizationByID = async (req, res, next, id) => { * for the new org context, and returns the updated user with abilities. * @param {Object} req - Express request object * @param {Object} res - Express response object - * @returns {void} + * @returns {Promise} */ const switchOrganization = async (req, res) => { try { @@ -291,7 +291,7 @@ const switchOrganization = async (req, res) => { * @description Endpoint to leave an organization. * @param {Object} req - Express request object * @param {Object} res - Express response object - * @returns {void} + * @returns {Promise} */ const leave = async (req, res) => { try { @@ -313,7 +313,7 @@ const leave = async (req, res) => { * @param {Object} req - Express request object * @param {Object} res - Express response object * @param {Function} next - Express next middleware function - * @returns {void} + * @returns {Promise} */ const loadMembership = async (req, res, next) => { if (req.organization && req.user && !req.membership) { diff --git a/modules/organizations/controllers/organizations.membership.controller.js b/modules/organizations/controllers/organizations.membership.controller.js index 3cbc9f3bf..ae49f0e96 100644 --- a/modules/organizations/controllers/organizations.membership.controller.js +++ b/modules/organizations/controllers/organizations.membership.controller.js @@ -12,7 +12,7 @@ import { MEMBERSHIP_ROLES } from '../lib/constants.js'; * @description Endpoint to fetch all members of an organization. * @param {Object} req - Express request object * @param {Object} res - Express response object - * @returns {void} + * @returns {Promise} */ const list = async (req, res) => { try { @@ -35,7 +35,7 @@ const list = async (req, res) => { * Returns minimal identity (id, displayName, email) for a match, or null. * @param {Object} req - Express request object * @param {Object} res - Express response object - * @returns {void} + * @returns {Promise} */ const findUserByEmail = async (req, res) => { try { @@ -81,7 +81,7 @@ const findUserByEmail = async (req, res) => { * and would otherwise pass for any user who holds that grant in the same org. * @param {Object} req - Express request object * @param {Object} res - Express response object - * @returns {void} + * @returns {Promise} */ const addMember = async (req, res) => { try { @@ -125,7 +125,7 @@ const addMember = async (req, res) => { * @description Endpoint to change the role of a member in an organization. * @param {Object} req - Express request object * @param {Object} res - Express response object - * @returns {void} + * @returns {Promise} */ const updateRole = async (req, res) => { try { @@ -150,7 +150,7 @@ const updateRole = async (req, res) => { * @description Endpoint to remove a member from an organization. * @param {Object} req - Express request object * @param {Object} res - Express response object - * @returns {void} + * @returns {Promise} */ const remove = async (req, res) => { try { @@ -181,7 +181,7 @@ const remove = async (req, res) => { * @param {Object} res - Express response object * @param {Function} next - Express next middleware function * @param {String} id - ID of the membership to fetch - * @returns {void} + * @returns {Promise} */ const memberByID = async (req, res, next, id) => { try { diff --git a/modules/organizations/migrations/20260310120000-organizations-init.js b/modules/organizations/migrations/20260310120000-organizations-init.js index 1a87af4c9..ed0b83e49 100644 --- a/modules/organizations/migrations/20260310120000-organizations-init.js +++ b/modules/organizations/migrations/20260310120000-organizations-init.js @@ -5,6 +5,16 @@ import mongoose from 'mongoose'; import { generateOrganizationSlug } from '../helpers/organizations.slug.js'; +/** + * Fields this migration reads/writes on each collection (see each module's model). + * @typedef {import('mongoose').Types.ObjectId} ObjectId + * @typedef {import('mongoose').Model<{firstName?: string, lastName?: string, currentOrganization?: ObjectId|null}>} UserModel + * @typedef {import('mongoose').Model<{name: string, slug: string, createdBy?: ObjectId}>} OrganizationModel + * @typedef {import('mongoose').Model<{userId: ObjectId, organizationId: ObjectId, role: string, status?: string}>} MembershipModel + * @typedef {import('mongoose').Model<{user?: ObjectId, organizationId?: ObjectId|null}>} TaskModel + * @typedef {import('mongoose').Model<{metadata?: {user?: ObjectId, organizationId?: ObjectId|null}}>} UploadModel + */ + /** * Migration: Create default organizations for existing users. * For each user without a membership, creates a personal organization @@ -16,9 +26,9 @@ import { generateOrganizationSlug } from '../helpers/organizations.slug.js'; * @returns {Promise} Resolves when all records have been created/updated. */ export async function up() { - const User = mongoose.model('User'); - const Organization = mongoose.model('Organization'); - const Membership = mongoose.model('Membership'); + const User = /** @type {UserModel} */ (mongoose.model('User')); + const Organization = /** @type {OrganizationModel} */ (mongoose.model('Organization')); + const Membership = /** @type {MembershipModel} */ (mongoose.model('Membership')); // ── Step 1: Find users who don't have any membership yet ────────── const allMemberships = await Membership.find({}, 'userId').lean(); @@ -69,9 +79,10 @@ export async function up() { } // ── Step 3: Backfill organizationId on tasks without one ────────── + /** @type {TaskModel|null} */ let Task; try { - Task = mongoose.model('Task'); + Task = /** @type {TaskModel} */ (mongoose.model('Task')); } catch { // Task model not registered — skip task backfill only Task = null; @@ -94,9 +105,10 @@ export async function up() { } // ── Step 4: Backfill organizationId on uploads without one ────────── + /** @type {UploadModel|null} */ let Upload; try { - Upload = mongoose.model('Uploads'); + Upload = /** @type {UploadModel} */ (mongoose.model('Uploads')); } catch { // Upload model not registered — skip upload backfill only Upload = null; diff --git a/modules/organizations/models/organizations.model.mongoose.js b/modules/organizations/models/organizations.model.mongoose.js index e1c1410bd..67b22918e 100644 --- a/modules/organizations/models/organizations.model.mongoose.js +++ b/modules/organizations/models/organizations.model.mongoose.js @@ -36,7 +36,7 @@ const OrganizationMongoose = new Schema( }, plan: { type: String, - enum: config.billing.plans, + enum: /** @type {string[]} */ (config.billing.plans), default: 'free', }, meterExempt: { diff --git a/modules/uploads/controllers/uploads.controller.js b/modules/uploads/controllers/uploads.controller.js index e0af281b2..e43ae902c 100644 --- a/modules/uploads/controllers/uploads.controller.js +++ b/modules/uploads/controllers/uploads.controller.js @@ -139,7 +139,7 @@ const remove = async (req, res) => { * @param {Object} req - Express request object * @param {Object} res - Express response object * @param {Function} next - Express next middleware function - * @param {String} filename - upload filename + * @param {String} uploadName - upload filename */ const uploadByName = async (req, res, next, uploadName) => { try { @@ -159,7 +159,7 @@ const uploadByName = async (req, res, next, uploadName) => { * @param {Object} req - Express request object * @param {Object} res - Express response object * @param {Function} next - Express next middleware function - * @param {String} filename & params - upload filename & eventual params (two max) filename-maxSize-options.png + * @param {String} uploadImageName - upload filename & eventual params (two max) filename-maxSize-options.png */ const uploadByImageName = async (req, res, next, uploadImageName) => { try { diff --git a/modules/uploads/repositories/uploads.repository.js b/modules/uploads/repositories/uploads.repository.js index aa7d7ff1e..c72cabf6d 100644 --- a/modules/uploads/repositories/uploads.repository.js +++ b/modules/uploads/repositories/uploads.repository.js @@ -6,7 +6,19 @@ import mongoose from 'mongoose'; import AppError from '../../../lib/helpers/AppError.js'; import logger from '../../../lib/services/logger.js'; -const Uploads = mongoose.model('Uploads'); +/** + * Stored GridFS file fields (see uploads.model.mongoose.js). + * @typedef {Object} UploadDoc + * @property {number} length + * @property {number} chunkSize + * @property {Date} uploadDate + * @property {string} [md5] + * @property {string} filename + * @property {string} [contentType] + * @property {{user?: import('mongoose').Types.ObjectId, organizationId?: import('mongoose').Types.ObjectId, kind?: string, contentType?: string}} [metadata] + */ + +const Uploads = /** @type {import('mongoose').Model} */ (mongoose.model('Uploads')); const bucket = new mongoose.mongo.GridFSBucket(mongoose.connection.db, { bucketName: 'uploads', @@ -29,14 +41,14 @@ const list = async (filter) => { /** * @desc Function to get an upload from db * @param {String} uploadName - * @return {Stream} upload + * @return {Promise} upload */ const get = (uploadName) => Uploads.findOne({ filename: uploadName }).exec(); /** * @desc Function to get an upload stream from db - * @param {Object} Upload - * @return {Stream} upload + * @param {Object} upload - an Upload doc (with `_id`) + * @return {import('mongodb').GridFSBucketReadStream} upload */ const getStream = (upload) => { try { @@ -65,9 +77,9 @@ const isFileNotFound = (err) => err?.name === 'MongoRuntimeError' && typeof err. /** * @desc Function to update an upload in db - * @param {ObjectID} upload ID + * @param {import('mongoose').Types.ObjectId|string} id - upload ID * @param {Object} update - * @return {Object} upload updated + * @return {Promise} upload updated */ const update = (id, update) => Uploads.findOneAndUpdate({ _id: id }, update, { returnDocument: 'after' }).exec(); @@ -84,7 +96,7 @@ const update = (id, update) => Uploads.findOneAndUpdate({ _id: id }, update, { r * @param {Object} upload - an Upload doc (with `_id`), or a bare lookup key * (e.g. `{ filename }`); `null`/`undefined`/`{}` are also valid — all * resolve to a lookup that matches nothing and hit the no-op path below - * @return {Object} a no-op marker ({ deletedCount: 0, notFound: true }) when + * @return {Promise} a no-op marker ({ deletedCount: 0, notFound: true }) when * no matching file was found, or otherwise whatever the underlying GridFS * bucket delete resolves with (unchanged from before this no-op path was * added — callers on the delete-success path never relied on a specific @@ -133,7 +145,7 @@ const remove = async (upload) => { /** * @desc Function to remove uploads of one user in db * @param {Object} filter - * @return {Object} confirmation of delete + * @return {Promise<{deletedCount: number}>} confirmation of delete */ const deleteMany = async (filter) => { const uploads = await list(filter); @@ -155,9 +167,9 @@ const deleteMany = async (filter) => { /** * @desc Function to purge uploads by kind if they are not referenced in another collection * @param {String} kind - metadata kind to match - * @param {collection} collection - name of the collection to check reference presence + * @param {String} collection - name of the collection to check reference presence * @param {String} key - name of the key to check id - * @return {Object} confirmation of delete + * @return {Promise<{deletedCount: number}>} confirmation of delete */ const purge = async (kind, collection, key) => { const toDelete = await Uploads.aggregate([ diff --git a/modules/uploads/services/uploads.service.js b/modules/uploads/services/uploads.service.js index d0ece1233..4952dd82e 100644 --- a/modules/uploads/services/uploads.service.js +++ b/modules/uploads/services/uploads.service.js @@ -32,7 +32,7 @@ const get = async (uploadName) => { /** * @desc Function to ask repository to get stream of chunks data - * @param {Object} Upload + * @param {Object} upload - an Upload doc (with `_id`) * @return {Promise} result stream */ const getStream = async (upload) => { @@ -42,9 +42,9 @@ const getStream = async (upload) => { /** * @desc Function to ask repository to update an upload - * @param {Object} req.file - * @param {Object} User - * @param {String} kind, upload configuration path (important for futur transformations) + * @param {Object} file - the uploaded file (req.file) + * @param {Object} user - the authenticated user + * @param {String} [kind] - upload configuration path (important for futur transformations) * @return {Promise} Upload */ const update = async (file, user, kind) => { @@ -61,7 +61,7 @@ const update = async (file, user, kind) => { /** * @desc Function to ask repository to remove chunks data - * @param {Object} Upload + * @param {Object} upload - an Upload doc, or a bare lookup key (e.g. `{ filename }`) * @return {Promise} confirmation of delete */ const remove = async (upload) => { diff --git a/modules/users/controllers/users.account.controller.js b/modules/users/controllers/users.account.controller.js index ebfd680ed..e9cd5c00d 100644 --- a/modules/users/controllers/users.account.controller.js +++ b/modules/users/controllers/users.account.controller.js @@ -64,6 +64,7 @@ const me = (req, res) => { // TODO create proper passport mock: See https://gist.github.com/mweibel/5219403 // providerData (OAuth access+refresh tokens, see auth/strategies/local/{google,apple}.js) // is intentionally NOT whitelisted here — never forward it to the client (#3963). + /** @type {{id: string, provider: string, roles: string[], avatar: string, email: string, lastName: string, firstName: string, complementary: Object, emailPreferences: Object, bio?: string, position?: string, terms?: Date, referralCode?: string}|null} */ let user = null; if (req.user) { user = { diff --git a/tsconfig.check.json b/tsconfig.check.json index c584ca021..667de4028 100644 --- a/tsconfig.check.json +++ b/tsconfig.check.json @@ -9,6 +9,6 @@ "moduleResolution": "nodenext", "target": "es2024" }, - "include": ["lib", "config", "server.js", "modules/core", "modules/home", "modules/audit", "modules/public", "modules/tasks"], + "include": ["lib", "config", "server.js", "modules/core", "modules/home", "modules/audit", "modules/public", "modules/tasks", "modules/auth", "modules/users", "modules/invitations", "modules/billing", "modules/organizations", "modules/uploads"], "exclude": ["node_modules", "**/tests/**", "**/*.tests.js"] } From 94b6d5bb261056aa8eeb2d2229a837bd69e69fff Mon Sep 17 00:00:00 2001 From: Pierre Brisorgueil Date: Thu, 12 Nov 2026 15:39:05 +0100 Subject: [PATCH 2/2] fix(auth): log OAuth callback failures with the message first Closes pierreb-devkit/Node#4270 --- modules/auth/controllers/auth.controller.js | 8 ++++---- modules/auth/tests/auth.integration.tests.js | 4 ++-- modules/billing/lib/billing.isoWeek.js | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/modules/auth/controllers/auth.controller.js b/modules/auth/controllers/auth.controller.js index c37a648e9..da692a65c 100644 --- a/modules/auth/controllers/auth.controller.js +++ b/modules/auth/controllers/auth.controller.js @@ -583,10 +583,10 @@ const oauthErrorRedirect = (res, err, fallbackTitle) => { * @returns {void} */ const logOAuthCallbackFailure = (strategy, errArg) => { - logger.error( - { err: { message: errArg?.message, code: errArg?.code, stack: errArg?.stack }, strategy }, - 'OAuth callback failed', - ); + logger.error('OAuth callback failed', { + err: { message: errArg?.message, code: errArg?.code, stack: errArg?.stack }, + strategy, + }); }; /** diff --git a/modules/auth/tests/auth.integration.tests.js b/modules/auth/tests/auth.integration.tests.js index 97b366317..21d906ece 100644 --- a/modules/auth/tests/auth.integration.tests.js +++ b/modules/auth/tests/auth.integration.tests.js @@ -751,6 +751,7 @@ describe('Auth integration tests:', () => { await AuthController.oauthCallback(mockReq, mockRes, () => {}); expect(loggerSpy).toHaveBeenCalledWith( + 'OAuth callback failed', expect.objectContaining({ err: expect.objectContaining({ message: 'token exchange failed', @@ -759,7 +760,6 @@ describe('Auth integration tests:', () => { }), strategy: 'google', }), - 'OAuth callback failed', ); expect(redirectCalls[0].code).toBe(302); expect(redirectCalls[0].url).not.toContain('error={}'); @@ -866,6 +866,7 @@ describe('Auth integration tests:', () => { await AuthController.oauthCallback(mockReq, mockRes, () => {}); expect(loggerSpy).toHaveBeenCalledWith( + 'OAuth callback failed', expect.objectContaining({ err: expect.objectContaining({ message: undefined, @@ -874,7 +875,6 @@ describe('Auth integration tests:', () => { }), strategy: 'google', }), - 'OAuth callback failed', ); expect(redirectCalls[0].code).toBe(302); expect(redirectCalls[0].url).not.toContain('error={}'); diff --git a/modules/billing/lib/billing.isoWeek.js b/modules/billing/lib/billing.isoWeek.js index 616abc15b..dd80ec385 100644 --- a/modules/billing/lib/billing.isoWeek.js +++ b/modules/billing/lib/billing.isoWeek.js @@ -10,7 +10,7 @@ export const isoWeekKey = (date) => { const d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate())); d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7)); const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1)); - const weekNum = Math.ceil(((d - yearStart) / MS_PER_DAY + 1) / 7); + const weekNum = Math.ceil(((d.getTime() - yearStart.getTime()) / MS_PER_DAY + 1) / 7); return `${d.getUTCFullYear()}-W${String(weekNum).padStart(2, '0')}`; };