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
13 changes: 6 additions & 7 deletions modules/auth/controllers/auth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')();
Expand Down Expand Up @@ -584,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,
});
};

/**
Expand Down Expand Up @@ -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<void>} Sends JSON response indicating verification success or failure
*/
const verifyEmail = async (req, res) => {
try {
Expand Down Expand Up @@ -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<void>} Sends JSON response confirming the email was resent or an error
*/
const resendVerification = async (req, res) => {
try {
Expand Down
4 changes: 2 additions & 2 deletions modules/auth/services/auth.eligibility.js
Original file line number Diff line number Diff line change
Expand Up @@ -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<any>)} fn
* @param {(ctx: { email?: string, body?: Object, req?: Object, oauth?: Object, signupOpen?: boolean }) => (any|Promise<any>)} fn
* @returns {void}
*/
export const registerSignupEligibility = (fn) => {
Expand All @@ -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<any|null>} the first non-null check result, or null
*/
export const assertSignupEligible = async (ctx) => {
Expand Down
4 changes: 2 additions & 2 deletions modules/auth/services/auth.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '';
Expand Down
4 changes: 2 additions & 2 deletions modules/auth/tests/auth.integration.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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={}');
Expand Down Expand Up @@ -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,
Expand All @@ -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={}');
Expand Down
6 changes: 3 additions & 3 deletions modules/billing/lib/billing.isoWeek.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
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));
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')}`;
};

Expand Down
1 change: 1 addition & 0 deletions modules/billing/lib/billing.planResolver.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const validPlans = new Set(config.billing?.plans || ['free', 'starter', 'pro', '
* @returns {Record<string, string>} priceId → planId map (built once at module init)
*/
export const buildPriceIdToPlanMap = () => {
/** @type {Record<string, string>} */
const map = {};
const stripePrices = config.stripe?.prices || {};
for (const [planId, intervals] of Object.entries(stripePrices)) {
Expand Down
1 change: 1 addition & 0 deletions modules/billing/lib/billing.retry.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
* false for a thrown error, the error is rethrown immediately without
* further attempts or delay.
*
* @template T
* @param {() => Promise<T>} fn - Async function to attempt.
* @param {object} [opts]
* @param {number} [opts.attempts=3] - Maximum number of attempts (including the first call).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>}
*/
export async function up() {
const db = mongoose.connection.db;
const subscriptions = db.collection('subscriptions');
/** @type {import('mongodb').Collection<ExtraBalanceRawDoc>} */
const extraBalances = db.collection('billingextrabalances');

const cursor = subscriptions.find(
Expand Down Expand Up @@ -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<ExtraBalanceRawDoc>} */ (db.collection('billingextrabalances')).updateMany(
{ 'ledger.source': GRANT_SOURCE },
{ $pull: { ledger: { source: GRANT_SOURCE } } },
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Array<{_id: {organizationId: *, weekKey: string}, count: number, ids: Array}>>}
* @returns {Promise<Array<{_id: {organizationId: import('mongodb').ObjectId, weekKey: string}, count: number, ids: Array<import('mongodb').ObjectId>}>>}
*/
const findWeekKeyDuplicates = (usages) =>
usages
/** @type {Promise<Array<{_id: {organizationId: import('mongodb').ObjectId, weekKey: string}, count: number, ids: Array<import('mongodb').ObjectId>}>>} */ (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).
Expand Down
4 changes: 2 additions & 2 deletions modules/billing/models/billing.subscription.model.mongoose.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
},

Expand Down
32 changes: 28 additions & 4 deletions modules/billing/repositories/billing.subscription.repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -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<SubscriptionDoc>} */ (mongoose.model('Subscription'));

const defaultPopulate = [
{
Expand Down Expand Up @@ -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) => {
Expand All @@ -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<Array<{organization: string, currentPeriodStart: Date, lastResetAt: Date|null}>>}
* @returns {PromiseLike<Array<{organization: import('mongoose').Types.ObjectId, currentPeriodStart: Date, lastResetAt: Date|null}>>}
* A thenable lean query (awaited by the caller).
*/
// biome-ignore lint/correctness/useQwikValidLexicalScope: false positive — Node.js repository, not Qwik
const findAllDueForResetByLastReset = (now) => {
Expand Down Expand Up @@ -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<Array<{_id: string, organization: string}>>}
* @returns {PromiseLike<Array<{_id: import('mongoose').Types.ObjectId, organization: import('mongoose').Types.ObjectId}>>}
* A thenable lean query (awaited by the caller).
*/
// biome-ignore lint/correctness/useQwikValidLexicalScope: false positive — Node.js repository, not Qwik
const findStaleDunning = (threshold) => {
Expand Down
5 changes: 3 additions & 2 deletions modules/billing/services/billing.extra.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
});
Expand Down
15 changes: 8 additions & 7 deletions modules/billing/services/billing.referral.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down Expand Up @@ -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:<invitationId>:<side>` 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
Expand Down Expand Up @@ -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}>}
Expand Down
4 changes: 3 additions & 1 deletion modules/billing/services/billing.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>} Portal session URL
*/
const createPortalSession = async (organization, returnUrl) => {
Expand Down Expand Up @@ -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';
Expand All @@ -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';
Expand Down
2 changes: 2 additions & 0 deletions modules/invitations/controllers/invitations.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<void>} Sends HTTP 200 with { valid, email } or 422 on error
Expand Down
17 changes: 16 additions & 1 deletion modules/invitations/repositories/invitations.repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -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<InvitationDoc>} */ (mongoose.model('Invitation'));

/**
* @desc Create an invitation document
Expand Down
Loading
Loading