chore: relocate backend into apps/api ahead of monorepo merge
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
'use strict';
|
||||
|
||||
// ── Regression tests for item-specific entitlement (Tier Plans v2) ──────────
|
||||
// Before this change, canAccessCourse/canAccessUnit/canAccessLesson unlocked
|
||||
// content purely off tier RANK (any active Premium purchase unlocked every
|
||||
// premium-tagged course). Now a Tier Plan purchase only grants the EXACT
|
||||
// items its bundle contained at purchase time (recorded in
|
||||
// user_tier_grants) — plain tier rank alone must no longer be sufficient.
|
||||
// These tests exercise the real controller/model objects (Sequelize doesn't
|
||||
// connect until a query actually runs) and stub only the specific static
|
||||
// methods each scenario touches, via jest.spyOn.
|
||||
|
||||
const { Course } = require('../../models/courses/courses.associations');
|
||||
const { mdl_UserTierGrants } = require('../../models/tiers/tier.associations');
|
||||
const mdl_UserTiers = require('../../models/tiers/user_tiers.mdl');
|
||||
const mdl_TierCategories = require('../../models/tiers/tier_categories.mdl');
|
||||
const { mdl_UserGroupMembers } = require('../../models/users/user_groups.mdl');
|
||||
const mdl_Product = require('../../models/courses/products.mdl');
|
||||
const mdl_CoursePurchase = require('../../models/courses/course_purchases.mdl');
|
||||
|
||||
const { canAccessCourse } = require('../../controllers/client/courses.controller');
|
||||
|
||||
function mockActiveTierUnused() {
|
||||
jest.spyOn(mdl_UserTiers, 'findAll').mockResolvedValue([]);
|
||||
jest.spyOn(mdl_TierCategories, 'findAll').mockResolvedValue([]);
|
||||
jest.spyOn(mdl_UserGroupMembers, 'findAll').mockResolvedValue([]);
|
||||
}
|
||||
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
|
||||
describe('canAccessCourse() — item-specific entitlement', () => {
|
||||
test('free/ungated course is always accessible, no grant lookup needed', async () => {
|
||||
jest.spyOn(Course, 'findOne').mockResolvedValue({ subscription: 'free', status: 'published' });
|
||||
const grantSpy = jest.spyOn(mdl_UserTierGrants, 'findOne');
|
||||
|
||||
const result = await canAccessCourse(1, 100);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(grantSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('unpublished course is never accessible regardless of entitlement', async () => {
|
||||
jest.spyOn(Course, 'findOne').mockResolvedValue({ subscription: 'premium', status: 'draft' });
|
||||
|
||||
const result = await canAccessCourse(1, 100);
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test('premium course with no grant, no purchase, no active tier → denied (tier rank alone no longer grants access)', async () => {
|
||||
jest.spyOn(Course, 'findOne').mockResolvedValue({ subscription: 'premium', status: 'published' });
|
||||
jest.spyOn(mdl_UserTierGrants, 'findOne').mockResolvedValue(null);
|
||||
jest.spyOn(mdl_Product, 'findOne').mockResolvedValue(null);
|
||||
mockActiveTierUnused();
|
||||
|
||||
const result = await canAccessCourse(1, 100);
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test('premium course unlocked by an item-specific grant for THIS exact course', async () => {
|
||||
jest.spyOn(Course, 'findOne').mockResolvedValue({ subscription: 'premium', status: 'published' });
|
||||
jest.spyOn(mdl_UserTierGrants, 'findOne').mockResolvedValue({ item_id: 100 }); // active grant found
|
||||
mockActiveTierUnused();
|
||||
|
||||
const result = await canAccessCourse(1, 100);
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
test('premium course still unlocked via a valid individual (a la carte) purchase, unrelated to any tier grant', async () => {
|
||||
jest.spyOn(Course, 'findOne').mockResolvedValue({ subscription: 'premium', status: 'published' });
|
||||
jest.spyOn(mdl_UserTierGrants, 'findOne').mockResolvedValue(null);
|
||||
jest.spyOn(mdl_Product, 'findOne').mockResolvedValue({ id: 55 });
|
||||
jest.spyOn(mdl_CoursePurchase, 'findOne').mockResolvedValue({ id: 1 });
|
||||
mockActiveTierUnused();
|
||||
|
||||
const result = await canAccessCourse(1, 100);
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
'use strict';
|
||||
|
||||
// ── Regression test for the "declined payment still granted access" bug ──────
|
||||
// PayPal's v2 capture-order endpoint can respond with HTTP 2xx even when the
|
||||
// charge itself was declined or held for review — the failure only shows up
|
||||
// in the response body's status field (e.g. capture.status: "DECLINED" or
|
||||
// "PENDING"), not as a thrown HTTP error. Before the fix, captureOrder() only
|
||||
// guarded against a *thrown* error from the provider and unconditionally
|
||||
// granted the tier on any non-throwing response. These tests pin the fix:
|
||||
// a non-COMPLETED capture must mark the payment failed and must NOT create
|
||||
// or extend a user_tiers row.
|
||||
|
||||
jest.mock('../../models/tiers/tier_categories.mdl', () => ({}));
|
||||
jest.mock('../../models/tiers/tier_plans.mdl', () => ({ findOne: jest.fn() }));
|
||||
jest.mock('../../models/tiers/user_tiers.mdl', () => ({ findOne: jest.fn(), create: jest.fn() }));
|
||||
jest.mock('../../models/tiers/payments.mdl', () => ({ findOne: jest.fn() }));
|
||||
jest.mock('../../models/system_badges/system_badges.mdl', () => ({}));
|
||||
jest.mock('../../models/assets/assets.mdl', () => ({}));
|
||||
jest.mock('../../models/notifications/user_notification.mdl', () => ({ create: jest.fn() }));
|
||||
jest.mock('../../services/achievements.service', () => ({ onTierActivated: jest.fn() }));
|
||||
jest.mock('../../models/courses/courses.mdl', () => ({ Course: {} }));
|
||||
jest.mock('../../services/payment.service', () => ({ captureOrder: jest.fn() }));
|
||||
jest.mock('../../data/notifications.data', () => ({ NOTIFICATION_REGISTRY: {} }));
|
||||
jest.mock('../../models/tiers/tier.associations', () => ({}));
|
||||
// captureOrder now snapshots the plan's bundle into user_tier_grants on every
|
||||
// successful capture (Tier Plans v2 item-specific entitlement) — mocked out
|
||||
// here since these tests only pin the payment-status gating behavior.
|
||||
jest.mock('../../services/tierGrants.service', () => ({ snapshotPlanGrants: jest.fn() }));
|
||||
|
||||
const mdl_UserTiers = require('../../models/tiers/user_tiers.mdl');
|
||||
const mdl_Payments = require('../../models/tiers/payments.mdl');
|
||||
const paymentSvc = require('../../services/payment.service');
|
||||
const controller = require('../../controllers/client/tiers.controller');
|
||||
|
||||
function mockRes() {
|
||||
const res = {};
|
||||
res.status = jest.fn().mockReturnValue(res);
|
||||
res.json = jest.fn().mockReturnValue(res);
|
||||
return res;
|
||||
}
|
||||
|
||||
function makePayment(overrides = {}) {
|
||||
return {
|
||||
payment_id: 1,
|
||||
plan_id: 10,
|
||||
provider: 'paypal',
|
||||
provider_payload: { order_id: 'ORDER-1' },
|
||||
plan: { plan_id: 10, tier: 'premium', duration_days: 30, is_active: true },
|
||||
update: jest.fn().mockResolvedValue(true),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
describe('captureOrder() — declined/incomplete captures must not grant access', () => {
|
||||
|
||||
test('capture.status "DECLINED" marks the payment failed and creates no tier', async () => {
|
||||
const payment = makePayment();
|
||||
mdl_Payments.findOne.mockResolvedValue(payment);
|
||||
paymentSvc.captureOrder.mockResolvedValue({
|
||||
status: 'COMPLETED', // outer order status can still say COMPLETED
|
||||
purchase_units: [{ payments: { captures: [{ id: 'CAP-1', status: 'DECLINED' }] } }],
|
||||
});
|
||||
|
||||
const req = { user: { user_id: 1 }, body: { order_id: 'ORDER-1' } };
|
||||
const res = mockRes();
|
||||
|
||||
await controller.captureOrder(req, res);
|
||||
|
||||
expect(mdl_UserTiers.create).not.toHaveBeenCalled();
|
||||
expect(payment.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ status: 'failed' })
|
||||
);
|
||||
expect(res.status).toHaveBeenCalledWith(402);
|
||||
});
|
||||
|
||||
test('capture.status "PENDING" (e.g. eCheck review) also withholds access', async () => {
|
||||
const payment = makePayment();
|
||||
mdl_Payments.findOne.mockResolvedValue(payment);
|
||||
paymentSvc.captureOrder.mockResolvedValue({
|
||||
status: 'COMPLETED',
|
||||
purchase_units: [{ payments: { captures: [{ id: 'CAP-2', status: 'PENDING' }] } }],
|
||||
});
|
||||
|
||||
const req = { user: { user_id: 1 }, body: { order_id: 'ORDER-1' } };
|
||||
const res = mockRes();
|
||||
|
||||
await controller.captureOrder(req, res);
|
||||
|
||||
expect(mdl_UserTiers.create).not.toHaveBeenCalled();
|
||||
expect(payment.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ status: 'failed' })
|
||||
);
|
||||
expect(res.status).toHaveBeenCalledWith(402);
|
||||
});
|
||||
|
||||
test('capture.status "COMPLETED" still grants the tier (control case)', async () => {
|
||||
const payment = makePayment();
|
||||
mdl_Payments.findOne.mockResolvedValue(payment);
|
||||
mdl_UserTiers.findOne.mockResolvedValue(null); // no existing active tier
|
||||
mdl_UserTiers.create.mockResolvedValue({ tier_id: 99, tier: 'premium', expires_at: new Date() });
|
||||
paymentSvc.captureOrder.mockResolvedValue({
|
||||
status: 'COMPLETED',
|
||||
payer: { payer_id: 'PAYER-1' },
|
||||
purchase_units: [{ payments: { captures: [{ id: 'CAP-3', status: 'COMPLETED' }] } }],
|
||||
});
|
||||
|
||||
const req = { user: { user_id: 1 }, body: { order_id: 'ORDER-1' } };
|
||||
const res = mockRes();
|
||||
|
||||
await controller.captureOrder(req, res);
|
||||
|
||||
expect(mdl_UserTiers.create).toHaveBeenCalled();
|
||||
expect(payment.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ status: 'completed' })
|
||||
);
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
'use strict';
|
||||
|
||||
jest.mock('../../models/tiers/payments.mdl', () => ({ findAll: jest.fn() }));
|
||||
jest.mock('../../models/courses/course_purchases.mdl', () => ({ findAll: jest.fn() }));
|
||||
|
||||
const mdl_Payments = require('../../models/tiers/payments.mdl');
|
||||
const mdl_CoursePurchase = require('../../models/courses/course_purchases.mdl');
|
||||
const job = require('../../cron/jobs/fail_stale_payments.cron');
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
test('marks stale pending payments and purchases as failed', async () => {
|
||||
const payment = { provider_payload: { order_id: 'O-1' }, update: jest.fn().mockResolvedValue(true) };
|
||||
const purchase = { provider_payload: { order_id: 'O-2' }, update: jest.fn().mockResolvedValue(true) };
|
||||
|
||||
mdl_Payments.findAll.mockResolvedValue([payment]);
|
||||
mdl_CoursePurchase.findAll.mockResolvedValue([purchase]);
|
||||
|
||||
await job.run();
|
||||
|
||||
expect(payment.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
status: 'failed',
|
||||
provider_payload: expect.objectContaining({ failed_reason: 'abandoned_checkout' }),
|
||||
})
|
||||
);
|
||||
expect(purchase.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
status: 'failed',
|
||||
provider_payload: expect.objectContaining({ failed_reason: 'abandoned_checkout' }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test('does nothing when there are no stale rows', async () => {
|
||||
mdl_Payments.findAll.mockResolvedValue([]);
|
||||
mdl_CoursePurchase.findAll.mockResolvedValue([]);
|
||||
|
||||
await expect(job.run()).resolves.not.toThrow();
|
||||
});
|
||||
@@ -0,0 +1,258 @@
|
||||
'use strict';
|
||||
|
||||
// Set env BEFORE requiring the middleware (ALLOWED array is built at load time)
|
||||
process.env.ORIGIN_GUARD_DISABLED = 'false';
|
||||
process.env.NODE_ENV = 'development';
|
||||
process.env.ALLOWED_ORIGINS = 'http://localhost:5173,http://localhost:3024';
|
||||
|
||||
const originGuard = require('../../middleware/originGuard.middleware');
|
||||
|
||||
// ── Mock helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
function makeReq({ method = 'GET', headers = {} } = {}) {
|
||||
return { method, headers };
|
||||
}
|
||||
|
||||
function makeRes() {
|
||||
const res = {
|
||||
_status: null,
|
||||
_body: null,
|
||||
status(code) { this._status = code; return this; },
|
||||
json(body) { this._body = body; return this; },
|
||||
};
|
||||
return res;
|
||||
}
|
||||
|
||||
// Minimal headers that represent a real browser fetch() call (SPA → API).
|
||||
// localhost:5173 → localhost:3024 is same-site (same eTLD+1, different port).
|
||||
const BROWSER_HEADERS = {
|
||||
'sec-fetch-site': 'same-site',
|
||||
'sec-fetch-mode': 'cors',
|
||||
'sec-fetch-dest': 'empty',
|
||||
'accept-language': 'en-US,en;q=0.9',
|
||||
};
|
||||
|
||||
// ── Tests ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('originGuard middleware', () => {
|
||||
|
||||
// ── Layer 1a: Sec-Fetch-Site presence + value ─────────────────────────────
|
||||
|
||||
test('1. GET with no Sec-Fetch-Site → 403 (Layer 1a: header absent)', () => {
|
||||
const req = makeReq({ method: 'GET', headers: {} });
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
|
||||
originGuard(req, res, next);
|
||||
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(403);
|
||||
expect(res._body).toMatchObject({ status: 'error', message: 'Forbidden.' });
|
||||
});
|
||||
|
||||
test('2. GET with Sec-Fetch-Site: cross-site → 403 (Layer 1a: cross-site rejected)', () => {
|
||||
const req = makeReq({ method: 'GET', headers: { 'sec-fetch-site': 'cross-site' } });
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
|
||||
originGuard(req, res, next);
|
||||
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(403);
|
||||
expect(res._body).toMatchObject({ status: 'error', message: 'Forbidden.' });
|
||||
});
|
||||
|
||||
// ── Layer 1b: Fetch Metadata family completeness + valid combo ────────────
|
||||
|
||||
test('3. GET with Sec-Fetch-Site but missing Mode and Dest → 403 (Layer 1b: incomplete family)', () => {
|
||||
const req = makeReq({ method: 'GET', headers: { 'sec-fetch-site': 'same-site' } });
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
|
||||
originGuard(req, res, next);
|
||||
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(403);
|
||||
expect(res._body).toMatchObject({ status: 'error', message: 'Forbidden.' });
|
||||
});
|
||||
|
||||
test('4. GET with Sec-Fetch-Site + Mode but missing Dest → 403 (Layer 1b: partial family)', () => {
|
||||
const req = makeReq({
|
||||
method: 'GET',
|
||||
headers: { 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors' },
|
||||
});
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
|
||||
originGuard(req, res, next);
|
||||
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(403);
|
||||
});
|
||||
|
||||
test('5. GET with impossible combo (cors + document) → 403 (Layer 1b: invalid combination)', () => {
|
||||
const req = makeReq({
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'sec-fetch-site': 'same-site',
|
||||
'sec-fetch-mode': 'cors',
|
||||
'sec-fetch-dest': 'document',
|
||||
'accept-language': 'en-US',
|
||||
},
|
||||
});
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
|
||||
originGuard(req, res, next);
|
||||
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(403);
|
||||
});
|
||||
|
||||
test('6. GET with no-cors mode → 403 (Layer 1b: no-cors not expected on API server)', () => {
|
||||
const req = makeReq({
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'sec-fetch-site': 'same-site',
|
||||
'sec-fetch-mode': 'no-cors',
|
||||
'sec-fetch-dest': 'empty',
|
||||
'accept-language': 'en-US',
|
||||
},
|
||||
});
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
|
||||
originGuard(req, res, next);
|
||||
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(403);
|
||||
});
|
||||
|
||||
// ── Layer 2: Browser presence signals ────────────────────────────────────
|
||||
|
||||
test('7. GET with valid Fetch Metadata but no Sec-CH-UA and no Accept-Language → 403 (Layer 2: no browser fingerprint)', () => {
|
||||
const req = makeReq({
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'sec-fetch-site': 'same-site',
|
||||
'sec-fetch-mode': 'cors',
|
||||
'sec-fetch-dest': 'empty',
|
||||
},
|
||||
});
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
|
||||
originGuard(req, res, next);
|
||||
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(403);
|
||||
expect(res._body).toMatchObject({ status: 'error', message: 'Forbidden.' });
|
||||
});
|
||||
|
||||
// ── Layer 3: Origin allowlist ─────────────────────────────────────────────
|
||||
|
||||
test('8. POST with full browser headers but foreign Origin → 403 (Layer 3: unlisted origin)', () => {
|
||||
const req = makeReq({
|
||||
method: 'POST',
|
||||
headers: { ...BROWSER_HEADERS, 'origin': 'http://attacker.com' },
|
||||
});
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
|
||||
originGuard(req, res, next);
|
||||
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(403);
|
||||
expect(res._body).toMatchObject({ status: 'error', message: 'Forbidden.' });
|
||||
});
|
||||
|
||||
test('9. POST with full browser headers but missing Origin → 403 (Layer 3: no origin header)', () => {
|
||||
const req = makeReq({ method: 'POST', headers: { ...BROWSER_HEADERS } });
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
|
||||
originGuard(req, res, next);
|
||||
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(403);
|
||||
});
|
||||
|
||||
// ── Happy paths ───────────────────────────────────────────────────────────
|
||||
|
||||
test('10. GET with full browser headers (Accept-Language path) → passes', () => {
|
||||
const req = makeReq({ method: 'GET', headers: { ...BROWSER_HEADERS } });
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
|
||||
originGuard(req, res, next);
|
||||
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
expect(res._status).toBeNull();
|
||||
});
|
||||
|
||||
test('11. GET with Sec-CH-UA instead of Accept-Language (Chromium path) → passes', () => {
|
||||
const req = makeReq({
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'sec-fetch-site': 'same-site',
|
||||
'sec-fetch-mode': 'cors',
|
||||
'sec-fetch-dest': 'empty',
|
||||
'sec-ch-ua': '"Chromium";v="137", "Not/A)Brand";v="24"',
|
||||
},
|
||||
});
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
|
||||
originGuard(req, res, next);
|
||||
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
expect(res._status).toBeNull();
|
||||
});
|
||||
|
||||
test('12. POST with full browser headers and allowed Origin → passes', () => {
|
||||
const req = makeReq({
|
||||
method: 'POST',
|
||||
headers: { ...BROWSER_HEADERS, 'origin': 'http://localhost:5173' },
|
||||
});
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
|
||||
originGuard(req, res, next);
|
||||
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
expect(res._status).toBeNull();
|
||||
});
|
||||
|
||||
test('13. Direct browser navigation (navigate + document, site: none) → passes', () => {
|
||||
const req = makeReq({
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'sec-fetch-site': 'none',
|
||||
'sec-fetch-mode': 'navigate',
|
||||
'sec-fetch-dest': 'document',
|
||||
'sec-fetch-user': '?1',
|
||||
'accept-language': 'en-US,en;q=0.9',
|
||||
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
||||
},
|
||||
});
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
|
||||
originGuard(req, res, next);
|
||||
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
expect(res._status).toBeNull();
|
||||
});
|
||||
|
||||
test('14. OPTIONS preflight → passes immediately (handled by cors())', () => {
|
||||
const req = makeReq({ method: 'OPTIONS', headers: {} });
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
|
||||
originGuard(req, res, next);
|
||||
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
expect(res._status).toBeNull();
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
'use strict';
|
||||
|
||||
// courses.routes.js used to re-declare `router.use(authenticate, requireAdmin(), adminLimiter)`
|
||||
// on top of the guard chain admin.routes.js already applies to every mounted admin sub-router.
|
||||
// That double-application silently halved the effective adminLimiter budget (each request
|
||||
// incremented the shared store twice) and surfaced as premature "Too many admin requests"
|
||||
// errors. This suite locks in the invariant: the guard chain is applied exactly once, in
|
||||
// admin.routes.js, and never re-declared by the sub-routers it mounts.
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
const { authenticate } = require('../../middleware/auth.middleware');
|
||||
const { adminLimiter } = require('../../middleware/rateLimiter.middleware');
|
||||
|
||||
const adminRoutesDir = path.join(__dirname, '../../routes/admin');
|
||||
|
||||
// Every admin sub-router mounted by admin.routes.js, discovered dynamically so newly
|
||||
// added route files are covered automatically.
|
||||
const subRouterFiles = fs
|
||||
.readdirSync(adminRoutesDir)
|
||||
.filter((f) => f.endsWith('.routes.js') && f !== 'admin.routes.js');
|
||||
|
||||
function stackHandles(router) {
|
||||
return router.stack.map((layer) => layer.handle);
|
||||
}
|
||||
|
||||
describe('admin sub-routers do not re-declare inherited guards', () => {
|
||||
test.each(subRouterFiles)('%s does not re-apply authenticate or adminLimiter', (file) => {
|
||||
const router = require(path.join(adminRoutesDir, file));
|
||||
const handles = stackHandles(router);
|
||||
|
||||
expect(handles).not.toContain(authenticate);
|
||||
expect(handles).not.toContain(adminLimiter);
|
||||
});
|
||||
|
||||
// Explicit named cases for clarity: the one that broke, plus known-good references.
|
||||
test('courses.routes.js (regression case) has no top-level guard layer', () => {
|
||||
const router = require(path.join(adminRoutesDir, 'courses.routes.js'));
|
||||
const handles = stackHandles(router);
|
||||
|
||||
expect(handles).not.toContain(authenticate);
|
||||
expect(handles).not.toContain(adminLimiter);
|
||||
});
|
||||
|
||||
test('units.routes.js (already correct) has no top-level guard layer', () => {
|
||||
const router = require(path.join(adminRoutesDir, 'units.routes.js'));
|
||||
const handles = stackHandles(router);
|
||||
|
||||
expect(handles).not.toContain(authenticate);
|
||||
expect(handles).not.toContain(adminLimiter);
|
||||
});
|
||||
|
||||
test('lessons.routes.js (already correct) has no top-level guard layer', () => {
|
||||
const router = require(path.join(adminRoutesDir, 'lessons.routes.js'));
|
||||
const handles = stackHandles(router);
|
||||
|
||||
expect(handles).not.toContain(authenticate);
|
||||
expect(handles).not.toContain(adminLimiter);
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin.routes.js applies the guard chain exactly once', () => {
|
||||
test('authenticate and adminLimiter each appear exactly one time in the stack', () => {
|
||||
const adminRouter = require(path.join(adminRoutesDir, 'admin.routes.js'));
|
||||
const handles = stackHandles(adminRouter);
|
||||
|
||||
const authCount = handles.filter((h) => h === authenticate).length;
|
||||
const limitCount = handles.filter((h) => h === adminLimiter).length;
|
||||
|
||||
expect(authCount).toBe(1);
|
||||
expect(limitCount).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
'use strict';
|
||||
|
||||
const {
|
||||
requireClient,
|
||||
requireStaff,
|
||||
requireAdmin,
|
||||
requireOwnerOrStaff,
|
||||
requireOwnerOrAdmin,
|
||||
} = require('../../middleware/rbac.middleware');
|
||||
|
||||
// ── Mock helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
function makeRes() {
|
||||
const res = {
|
||||
_status: null,
|
||||
_body: null,
|
||||
status(code) { this._status = code; return this; },
|
||||
json(body) { this._body = body; return this; },
|
||||
};
|
||||
return res;
|
||||
}
|
||||
|
||||
function makeReq(accType = null, userId = null, paramId = null) {
|
||||
return {
|
||||
user: accType ? { user_id: userId, acc_type: accType } : null,
|
||||
params: { id: paramId },
|
||||
};
|
||||
}
|
||||
|
||||
// ── requireClient ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe('requireClient()', () => {
|
||||
test('user role → passes', () => {
|
||||
const next = jest.fn();
|
||||
requireClient()(makeReq('user'), makeRes(), next);
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('staff role → passes', () => {
|
||||
const next = jest.fn();
|
||||
requireClient()(makeReq('staff'), makeRes(), next);
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('admin role → passes', () => {
|
||||
const next = jest.fn();
|
||||
requireClient()(makeReq('admin'), makeRes(), next);
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('no req.user → 401', () => {
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
requireClient()(makeReq(null), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ── requireStaff ──────────────────────────────────────────────────────────────
|
||||
|
||||
describe('requireStaff()', () => {
|
||||
test('staff role → passes', () => {
|
||||
const next = jest.fn();
|
||||
requireStaff()(makeReq('staff'), makeRes(), next);
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('admin role → passes', () => {
|
||||
const next = jest.fn();
|
||||
requireStaff()(makeReq('admin'), makeRes(), next);
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('user role → 403', () => {
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
requireStaff()(makeReq('user'), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(403);
|
||||
});
|
||||
|
||||
test('no req.user → 401', () => {
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
requireStaff()(makeReq(null), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ── requireAdmin ──────────────────────────────────────────────────────────────
|
||||
|
||||
describe('requireAdmin()', () => {
|
||||
test('admin role → passes', () => {
|
||||
const next = jest.fn();
|
||||
requireAdmin()(makeReq('admin'), makeRes(), next);
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('staff role → 403', () => {
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
requireAdmin()(makeReq('staff'), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(403);
|
||||
});
|
||||
|
||||
test('user role → 403', () => {
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
requireAdmin()(makeReq('user'), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(403);
|
||||
});
|
||||
|
||||
test('no req.user → 401', () => {
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
requireAdmin()(makeReq(null), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ── requireOwnerOrStaff ───────────────────────────────────────────────────────
|
||||
|
||||
describe('requireOwnerOrStaff()', () => {
|
||||
test('owner (user) accessing own resource → passes', () => {
|
||||
const next = jest.fn();
|
||||
const req = { user: { user_id: 10, acc_type: 'user' }, params: { id: '10' } };
|
||||
requireOwnerOrStaff()(req, makeRes(), next);
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('staff accessing another user\'s resource → passes', () => {
|
||||
const next = jest.fn();
|
||||
const req = { user: { user_id: 2, acc_type: 'staff' }, params: { id: '99' } };
|
||||
requireOwnerOrStaff()(req, makeRes(), next);
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('admin accessing another user\'s resource → passes', () => {
|
||||
const next = jest.fn();
|
||||
const req = { user: { user_id: 1, acc_type: 'admin' }, params: { id: '99' } };
|
||||
requireOwnerOrStaff()(req, makeRes(), next);
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('user accessing another user\'s resource → 403', () => {
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
const req = { user: { user_id: 10, acc_type: 'user' }, params: { id: '99' } };
|
||||
requireOwnerOrStaff()(req, res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(403);
|
||||
});
|
||||
|
||||
test('no req.user → 401', () => {
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
const req = { user: null, params: { id: '10' } };
|
||||
requireOwnerOrStaff()(req, res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ── requireOwnerOrAdmin ───────────────────────────────────────────────────────
|
||||
|
||||
describe('requireOwnerOrAdmin()', () => {
|
||||
test('owner (user) accessing own resource → passes', () => {
|
||||
const next = jest.fn();
|
||||
const req = { user: { user_id: 10, acc_type: 'user' }, params: { id: '10' } };
|
||||
requireOwnerOrAdmin()(req, makeRes(), next);
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('admin accessing another user\'s resource → passes', () => {
|
||||
const next = jest.fn();
|
||||
const req = { user: { user_id: 1, acc_type: 'admin' }, params: { id: '99' } };
|
||||
requireOwnerOrAdmin()(req, makeRes(), next);
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('staff (non-owner) accessing another user\'s resource → 403', () => {
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
const req = { user: { user_id: 2, acc_type: 'staff' }, params: { id: '99' } };
|
||||
requireOwnerOrAdmin()(req, res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(403);
|
||||
});
|
||||
|
||||
test('no req.user → 401', () => {
|
||||
const res = makeRes();
|
||||
const next = jest.fn();
|
||||
const req = { user: null, params: { id: '10' } };
|
||||
requireOwnerOrAdmin()(req, res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res._status).toBe(401);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
'use strict';
|
||||
|
||||
// ── Integration test: paypal.provider.js against a mocked HTTP boundary ───────
|
||||
// Only axios (the true external boundary) is mocked — everything else in the
|
||||
// provider (token exchange, URL selection, request shaping) runs for real.
|
||||
// This is what tells us the provider is ready to go live: wrong env vars, a
|
||||
// broken sandbox/live switch, or a malformed request body will fail here
|
||||
// exactly like it would against the real PayPal API.
|
||||
|
||||
jest.mock('axios');
|
||||
|
||||
const BASE_ENV = {
|
||||
PAYPAL_CLIENT_ID: 'test-client-id',
|
||||
PAYPAL_CLIENT_SECRET: 'test-client-secret',
|
||||
PAYPAL_BRAND_NAME: 'STARR',
|
||||
FRONTEND_URL: 'https://app.new-starr.test',
|
||||
};
|
||||
|
||||
// BASE_URL is computed once at module load time from PAYPAL_ENV, so every
|
||||
// test that cares about sandbox/live must reset the module registry first.
|
||||
// axios must be re-required from the same fresh registry, otherwise its mock
|
||||
// calls land on a different automock instance than the one the provider uses.
|
||||
function loadProvider(envOverrides = {}) {
|
||||
jest.resetModules();
|
||||
Object.assign(process.env, BASE_ENV, envOverrides);
|
||||
const axios = require('axios');
|
||||
const provider = require('../../providers/paypal.provider');
|
||||
return { provider, axios };
|
||||
}
|
||||
|
||||
function mockAccessToken(axios, token = 'test-access-token') {
|
||||
axios.post.mockImplementationOnce((url) => {
|
||||
expect(url).toMatch(/\/v1\/oauth2\/token$/);
|
||||
return Promise.resolve({ data: { access_token: token } });
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
delete process.env.PAYPAL_ENV;
|
||||
});
|
||||
|
||||
// ── Config: sandbox vs live host selection ────────────────────────────────────
|
||||
|
||||
describe('environment / config wiring', () => {
|
||||
|
||||
test('defaults to the sandbox host when PAYPAL_ENV is unset', async () => {
|
||||
const { provider, axios } = loadProvider({});
|
||||
mockAccessToken(axios);
|
||||
axios.post.mockResolvedValueOnce({ data: {} });
|
||||
|
||||
await provider.createOrder({ amount: 10, referenceId: 'ref-1' });
|
||||
|
||||
expect(axios.post.mock.calls[0][0]).toBe('https://api-m.sandbox.paypal.com/v1/oauth2/token');
|
||||
expect(axios.post.mock.calls[1][0]).toBe('https://api-m.sandbox.paypal.com/v2/checkout/orders');
|
||||
});
|
||||
|
||||
test('switches to the live host when PAYPAL_ENV=live', async () => {
|
||||
const { provider, axios } = loadProvider({ PAYPAL_ENV: 'live' });
|
||||
mockAccessToken(axios);
|
||||
axios.post.mockResolvedValueOnce({ data: {} });
|
||||
|
||||
await provider.createOrder({ amount: 10, referenceId: 'ref-1' });
|
||||
|
||||
expect(axios.post.mock.calls[0][0]).toBe('https://api-m.paypal.com/v1/oauth2/token');
|
||||
expect(axios.post.mock.calls[1][0]).toBe('https://api-m.paypal.com/v2/checkout/orders');
|
||||
});
|
||||
|
||||
test('token request authenticates with PAYPAL_CLIENT_ID / PAYPAL_CLIENT_SECRET via HTTP Basic auth', async () => {
|
||||
const { provider, axios } = loadProvider({});
|
||||
mockAccessToken(axios);
|
||||
axios.post.mockResolvedValueOnce({ data: {} });
|
||||
|
||||
await provider.createOrder({ amount: 10, referenceId: 'ref-1' });
|
||||
|
||||
const [, , config] = axios.post.mock.calls[0];
|
||||
expect(config.auth).toEqual({ username: 'test-client-id', password: 'test-client-secret' });
|
||||
expect(config.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
|
||||
});
|
||||
|
||||
test('a rejected token exchange (bad credentials) surfaces as a rejected promise, not a silent failure', async () => {
|
||||
const { provider, axios } = loadProvider({});
|
||||
axios.post.mockRejectedValueOnce(new Error('401 invalid_client'));
|
||||
|
||||
await expect(provider.createOrder({ amount: 10, referenceId: 'ref-1' }))
|
||||
.rejects.toThrow('401 invalid_client');
|
||||
});
|
||||
});
|
||||
|
||||
// ── createOrder ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('createOrder()', () => {
|
||||
|
||||
test('sends a CAPTURE intent order with the reference id, amount and currency', async () => {
|
||||
const { provider, axios } = loadProvider({});
|
||||
mockAccessToken(axios, 'tok-abc');
|
||||
axios.post.mockResolvedValueOnce({ data: { id: 'ORDER-1', status: 'CREATED' } });
|
||||
|
||||
const result = await provider.createOrder({
|
||||
amount: 19.99,
|
||||
currency: 'PHP',
|
||||
referenceId: 'plan-42',
|
||||
});
|
||||
|
||||
const [url, body, config] = axios.post.mock.calls[1];
|
||||
expect(url).toBe('https://api-m.sandbox.paypal.com/v2/checkout/orders');
|
||||
expect(body.intent).toBe('CAPTURE');
|
||||
expect(body.purchase_units[0]).toMatchObject({
|
||||
reference_id: 'plan-42',
|
||||
amount: { currency_code: 'PHP', value: '19.99' },
|
||||
});
|
||||
expect(config.headers.Authorization).toBe('Bearer tok-abc');
|
||||
expect(result).toEqual({ id: 'ORDER-1', status: 'CREATED' });
|
||||
});
|
||||
|
||||
test('defaults currency to USD when not provided', async () => {
|
||||
const { provider, axios } = loadProvider({});
|
||||
mockAccessToken(axios);
|
||||
axios.post.mockResolvedValueOnce({ data: {} });
|
||||
|
||||
await provider.createOrder({ amount: 5, referenceId: 'ref-1' });
|
||||
|
||||
const [, body] = axios.post.mock.calls[1];
|
||||
expect(body.purchase_units[0].amount.currency_code).toBe('USD');
|
||||
});
|
||||
|
||||
test('falls back to FRONTEND_URL for return/cancel urls when not provided', async () => {
|
||||
const { provider, axios } = loadProvider({});
|
||||
mockAccessToken(axios);
|
||||
axios.post.mockResolvedValueOnce({ data: {} });
|
||||
|
||||
await provider.createOrder({ amount: 5, referenceId: 'ref-1' });
|
||||
|
||||
const [, body] = axios.post.mock.calls[1];
|
||||
expect(body.application_context.return_url).toBe('https://app.new-starr.test/plans/checkout');
|
||||
expect(body.application_context.cancel_url).toBe('https://app.new-starr.test/plans/checkout?cancelled=true');
|
||||
});
|
||||
|
||||
test('honors explicit return/cancel urls when provided', async () => {
|
||||
const { provider, axios } = loadProvider({});
|
||||
mockAccessToken(axios);
|
||||
axios.post.mockResolvedValueOnce({ data: {} });
|
||||
|
||||
await provider.createOrder({
|
||||
amount: 5, referenceId: 'ref-1',
|
||||
returnUrl: 'https://custom.test/ok',
|
||||
cancelUrl: 'https://custom.test/cancel',
|
||||
});
|
||||
|
||||
const [, body] = axios.post.mock.calls[1];
|
||||
expect(body.application_context.return_url).toBe('https://custom.test/ok');
|
||||
expect(body.application_context.cancel_url).toBe('https://custom.test/cancel');
|
||||
});
|
||||
});
|
||||
|
||||
// ── captureOrder ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe('captureOrder()', () => {
|
||||
|
||||
test('posts to the order capture endpoint with a bearer token and returns the capture payload', async () => {
|
||||
const { provider, axios } = loadProvider({});
|
||||
mockAccessToken(axios, 'tok-xyz');
|
||||
axios.post.mockResolvedValueOnce({ data: { id: 'ORDER-1', status: 'COMPLETED' } });
|
||||
|
||||
const result = await provider.captureOrder('ORDER-1');
|
||||
|
||||
const [url, body, config] = axios.post.mock.calls[1];
|
||||
expect(url).toBe('https://api-m.sandbox.paypal.com/v2/checkout/orders/ORDER-1/capture');
|
||||
expect(body).toEqual({});
|
||||
expect(config.headers.Authorization).toBe('Bearer tok-xyz');
|
||||
expect(result).toEqual({ id: 'ORDER-1', status: 'COMPLETED' });
|
||||
});
|
||||
});
|
||||
|
||||
// ── refundCapture ──────────────────────────────────────────────────────────────
|
||||
|
||||
describe('refundCapture()', () => {
|
||||
|
||||
test('posts a refund with the given amount and currency', async () => {
|
||||
const { provider, axios } = loadProvider({});
|
||||
mockAccessToken(axios);
|
||||
axios.post.mockResolvedValueOnce({ data: { id: 'REFUND-1', status: 'COMPLETED' } });
|
||||
|
||||
const result = await provider.refundCapture('CAPTURE-1', 9.5, 'PHP');
|
||||
|
||||
const [url, body] = axios.post.mock.calls[1];
|
||||
expect(url).toBe('https://api-m.sandbox.paypal.com/v2/payments/captures/CAPTURE-1/refund');
|
||||
expect(body).toEqual({ amount: { value: '9.5', currency_code: 'PHP' } });
|
||||
expect(result).toEqual({ id: 'REFUND-1', status: 'COMPLETED' });
|
||||
});
|
||||
|
||||
test('defaults currency to USD when not provided', async () => {
|
||||
const { provider, axios } = loadProvider({});
|
||||
mockAccessToken(axios);
|
||||
axios.post.mockResolvedValueOnce({ data: {} });
|
||||
|
||||
await provider.refundCapture('CAPTURE-1', 9.5);
|
||||
|
||||
const [, body] = axios.post.mock.calls[1];
|
||||
expect(body.amount.currency_code).toBe('USD');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
'use strict';
|
||||
|
||||
// ── Provider contract test ────────────────────────────────────────────────────
|
||||
// This suite is the "gate" for onboarding new payment providers. It does not
|
||||
// hardcode "paypal" as the only case — it walks registry.list() and asserts
|
||||
// every registered provider satisfies the shape payment.service.js relies on.
|
||||
// Drop a second provider into providers/registry.js and this file validates it
|
||||
// for free, with zero new test code required.
|
||||
|
||||
const registry = require('../../providers/registry');
|
||||
|
||||
const REQUIRED_METHODS = ['createOrder', 'captureOrder', 'refundCapture'];
|
||||
|
||||
describe('payment provider registry', () => {
|
||||
|
||||
test('lists at least one provider', () => {
|
||||
expect(registry.list().length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('currently registers paypal', () => {
|
||||
expect(registry.list()).toContain('paypal');
|
||||
});
|
||||
|
||||
test('get() returns the provider module for a known name', () => {
|
||||
const provider = registry.get('paypal');
|
||||
expect(provider).toBeDefined();
|
||||
});
|
||||
|
||||
test('get() throws a descriptive error for an unknown provider', () => {
|
||||
expect(() => registry.get('stripe')).toThrow(/Unknown payment provider: "stripe"/);
|
||||
});
|
||||
|
||||
test('unknown-provider error lists the available providers so misconfiguration is easy to diagnose', () => {
|
||||
try {
|
||||
registry.get('does-not-exist');
|
||||
throw new Error('expected registry.get to throw');
|
||||
} catch (err) {
|
||||
registry.list().forEach((name) => {
|
||||
expect(err.message).toContain(name);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe.each(registry.list())('provider contract: %s', (name) => {
|
||||
const provider = registry.get(name);
|
||||
|
||||
test.each(REQUIRED_METHODS)('exposes %s as a function', (method) => {
|
||||
expect(typeof provider[method]).toBe('function');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,235 @@
|
||||
'use strict';
|
||||
|
||||
// ── Env vars must be set BEFORE the service loads (enabled flags read process.env at load time)
|
||||
process.env.DB_HOST = 'test-db-host';
|
||||
process.env.DB_PORT = '5432';
|
||||
process.env.S3_ENDPOINT = 'http://test-s3:3900';
|
||||
process.env.S3_PUBLIC_URL = 'https://cdn.example.com';
|
||||
process.env.S3_BUCKET = 'test-bucket';
|
||||
process.env.GOOGLE_CLIENT_ID = 'test-client-id';
|
||||
process.env.GMAIL_REFRESH_TOKEN = 'test-refresh-token';
|
||||
process.env.REDIS_URL = 'redis://127.0.0.1:6379';
|
||||
|
||||
// ── Mock all infrastructure before the service module loads ───────────────────
|
||||
jest.mock('../../config/db.config', () => ({ authenticate: jest.fn() }));
|
||||
jest.mock('../../config/redis.config', () => ({ ping: jest.fn() }));
|
||||
jest.mock('../../services/s3.service', () => ({ ping: jest.fn() }));
|
||||
jest.mock('../../services/email.service', () => ({ ping: jest.fn() }));
|
||||
|
||||
const db = require('../../config/db.config');
|
||||
const cache = require('../../config/redis.config');
|
||||
const { ping: s3 } = require('../../services/s3.service');
|
||||
const { ping: smtp } = require('../../services/email.service'); // alias kept for test-body brevity; JSON key is now "email"
|
||||
const { runDashboard, runReadiness } = require('../../services/health.service');
|
||||
|
||||
// ── Reset mocks between tests ─────────────────────────────────────────────────
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
// ── Preset helpers ────────────────────────────────────────────────────────────
|
||||
const resolve = (fn) => fn.mockResolvedValue();
|
||||
|
||||
function allHealthy() {
|
||||
resolve(db.authenticate);
|
||||
cache.ping.mockResolvedValue('PONG');
|
||||
resolve(s3);
|
||||
resolve(smtp);
|
||||
}
|
||||
|
||||
// ── runDashboard ──────────────────────────────────────────────────────────────
|
||||
|
||||
describe('runDashboard()', () => {
|
||||
|
||||
test('all healthy → status=healthy, HTTP 200', async () => {
|
||||
allHealthy();
|
||||
const { httpStatus, body } = await runDashboard();
|
||||
expect(httpStatus).toBe(200);
|
||||
expect(body.status).toBe('healthy');
|
||||
});
|
||||
|
||||
test('database down (critical) → status=unhealthy, HTTP 503', async () => {
|
||||
db.authenticate.mockRejectedValue(new Error('Connection refused'));
|
||||
cache.ping.mockResolvedValue('PONG');
|
||||
resolve(s3);
|
||||
resolve(smtp);
|
||||
|
||||
const { httpStatus, body } = await runDashboard();
|
||||
expect(httpStatus).toBe(503);
|
||||
expect(body.status).toBe('unhealthy');
|
||||
});
|
||||
|
||||
test('S3 down (non-critical) → status=degraded, HTTP 200', async () => {
|
||||
resolve(db.authenticate);
|
||||
cache.ping.mockResolvedValue('PONG');
|
||||
s3.mockRejectedValue(new Error('S3 storage unavailable'));
|
||||
resolve(smtp);
|
||||
|
||||
const { httpStatus, body } = await runDashboard();
|
||||
expect(httpStatus).toBe(200);
|
||||
expect(body.status).toBe('degraded');
|
||||
});
|
||||
|
||||
test('SMTP down (non-critical) → degraded, HTTP 200', async () => {
|
||||
resolve(db.authenticate);
|
||||
cache.ping.mockResolvedValue('PONG');
|
||||
resolve(s3);
|
||||
smtp.mockRejectedValue(new Error('SMTP unreachable'));
|
||||
|
||||
const { httpStatus, body } = await runDashboard();
|
||||
expect(httpStatus).toBe(200);
|
||||
expect(body.status).toBe('degraded');
|
||||
});
|
||||
|
||||
test('both DB and S3 down → unhealthy (critical takes precedence), HTTP 503', async () => {
|
||||
db.authenticate.mockRejectedValue(new Error('refused'));
|
||||
cache.ping.mockResolvedValue('PONG');
|
||||
s3.mockRejectedValue(new Error('s3 down'));
|
||||
resolve(smtp);
|
||||
|
||||
const { httpStatus, body } = await runDashboard();
|
||||
expect(httpStatus).toBe(503);
|
||||
expect(body.status).toBe('unhealthy');
|
||||
});
|
||||
|
||||
test('body has app, system, uptime, timestamp, services', async () => {
|
||||
allHealthy();
|
||||
const { body } = await runDashboard();
|
||||
expect(body).toHaveProperty('app');
|
||||
expect(body).toHaveProperty('system');
|
||||
expect(body).toHaveProperty('uptime');
|
||||
expect(body).toHaveProperty('timestamp');
|
||||
expect(body).toHaveProperty('services');
|
||||
});
|
||||
|
||||
test('app info has correct shape', async () => {
|
||||
allHealthy();
|
||||
const { body } = await runDashboard();
|
||||
expect(body.app).toMatchObject({
|
||||
name: expect.any(String),
|
||||
version: expect.any(String),
|
||||
environment: expect.any(String),
|
||||
node_version: expect.stringMatching(/^v\d+/),
|
||||
pid: expect.any(Number),
|
||||
});
|
||||
});
|
||||
|
||||
test('database connection label is "established" when healthy', async () => {
|
||||
allHealthy();
|
||||
const { body } = await runDashboard();
|
||||
expect(body.services.database.connection).toBe('established');
|
||||
});
|
||||
|
||||
test('database connection label is "unavailable" when down', async () => {
|
||||
db.authenticate.mockRejectedValue(new Error('refused'));
|
||||
cache.ping.mockResolvedValue('PONG');
|
||||
resolve(s3);
|
||||
resolve(smtp);
|
||||
|
||||
const { body } = await runDashboard();
|
||||
expect(body.services.database.connection).toBe('unavailable');
|
||||
});
|
||||
|
||||
test('latency_ms is a non-negative number for enabled checks', async () => {
|
||||
allHealthy();
|
||||
const { body } = await runDashboard();
|
||||
expect(typeof body.services.database.latency_ms).toBe('number');
|
||||
expect(body.services.database.latency_ms).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
test('timestamp is a valid ISO 8601 string', async () => {
|
||||
allHealthy();
|
||||
const { body } = await runDashboard();
|
||||
expect(new Date(body.timestamp).toISOString()).toBe(body.timestamp);
|
||||
});
|
||||
});
|
||||
|
||||
// ── runReadiness ──────────────────────────────────────────────────────────────
|
||||
|
||||
describe('runReadiness()', () => {
|
||||
|
||||
test('all healthy → status=healthy, HTTP 200', async () => {
|
||||
allHealthy();
|
||||
const { httpStatus, body } = await runReadiness();
|
||||
expect(httpStatus).toBe(200);
|
||||
expect(body.status).toBe('healthy');
|
||||
});
|
||||
|
||||
test('database down → HTTP 503', async () => {
|
||||
db.authenticate.mockRejectedValue(new Error('refused'));
|
||||
cache.ping.mockResolvedValue('PONG');
|
||||
resolve(s3);
|
||||
resolve(smtp);
|
||||
|
||||
const { httpStatus } = await runReadiness();
|
||||
expect(httpStatus).toBe(503);
|
||||
});
|
||||
|
||||
test('S3 down → HTTP 200, degraded — non-critical stays routable', async () => {
|
||||
resolve(db.authenticate);
|
||||
cache.ping.mockResolvedValue('PONG');
|
||||
s3.mockRejectedValue(new Error('S3 storage unavailable'));
|
||||
resolve(smtp);
|
||||
|
||||
const { httpStatus, body } = await runReadiness();
|
||||
expect(httpStatus).toBe(200);
|
||||
expect(body.status).toBe('degraded');
|
||||
});
|
||||
|
||||
test('body has version, uptime, timestamp, checks, memory', async () => {
|
||||
allHealthy();
|
||||
const { body } = await runReadiness();
|
||||
expect(body).toHaveProperty('version');
|
||||
expect(body).toHaveProperty('uptime');
|
||||
expect(body).toHaveProperty('timestamp');
|
||||
expect(body).toHaveProperty('checks');
|
||||
expect(body).toHaveProperty('memory');
|
||||
});
|
||||
|
||||
test('checks object has database, cache, storage, email keys', async () => {
|
||||
allHealthy();
|
||||
const { body } = await runReadiness();
|
||||
['database', 'cache', 'storage', 'email'].forEach((key) => {
|
||||
expect(body.checks).toHaveProperty(key);
|
||||
});
|
||||
});
|
||||
|
||||
test('memory snapshot has heap_used_mb, heap_total_mb, rss_mb, external_mb', async () => {
|
||||
allHealthy();
|
||||
const { body } = await runReadiness();
|
||||
expect(body.memory).toMatchObject({
|
||||
heap_used_mb: expect.any(Number),
|
||||
heap_total_mb: expect.any(Number),
|
||||
rss_mb: expect.any(Number),
|
||||
external_mb: expect.any(Number),
|
||||
});
|
||||
});
|
||||
|
||||
test('database check entry has status=unhealthy and critical=true when DB fails', async () => {
|
||||
db.authenticate.mockRejectedValue(new Error('refused'));
|
||||
cache.ping.mockResolvedValue('PONG');
|
||||
resolve(s3);
|
||||
resolve(smtp);
|
||||
|
||||
const { body } = await runReadiness();
|
||||
expect(body.checks.database.status).toBe('unhealthy');
|
||||
expect(body.checks.database.critical).toBe(true);
|
||||
});
|
||||
|
||||
test('storage check entry has status=unhealthy and critical=false when S3 fails', async () => {
|
||||
resolve(db.authenticate);
|
||||
cache.ping.mockResolvedValue('PONG');
|
||||
s3.mockRejectedValue(new Error('S3 storage unavailable'));
|
||||
resolve(smtp);
|
||||
|
||||
const { body } = await runReadiness();
|
||||
expect(body.checks.storage.status).toBe('unhealthy');
|
||||
expect(body.checks.storage.critical).toBe(false);
|
||||
});
|
||||
|
||||
test('cache check entry has status=skipped when redis is null (CACHE_DRIVER=memory)', async () => {
|
||||
allHealthy();
|
||||
const { body } = await runReadiness();
|
||||
// cache mock returns { ping: fn } so it is enabled; but the skipped test
|
||||
// is covered when redis module exports null — we verify the shape here instead
|
||||
expect(['healthy', 'skipped']).toContain(body.checks.cache.status);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
'use strict';
|
||||
|
||||
// ── Integration test: payment.service.js → providers/registry → paypal.provider ──
|
||||
// Only the DB models and axios (the two real external boundaries) are mocked.
|
||||
// registry.js and paypal.provider.js run unmodified, so this proves the full
|
||||
// orchestration chain (service → registry lookup → provider → HTTP) is wired
|
||||
// correctly end to end, not just that each piece works in isolation.
|
||||
|
||||
process.env.PAYPAL_CLIENT_ID = 'test-client-id';
|
||||
process.env.PAYPAL_CLIENT_SECRET = 'test-client-secret';
|
||||
process.env.FRONTEND_URL = 'https://app.new-starr.test';
|
||||
|
||||
const axios = require('axios');
|
||||
jest.mock('axios');
|
||||
|
||||
jest.mock('../../models/tiers/payment_policies.mdl', () => ({ findOne: jest.fn() }));
|
||||
jest.mock('../../models/tiers/payments.mdl', () => ({ count: jest.fn() }));
|
||||
|
||||
const mdl_PaymentPolicies = require('../../models/tiers/payment_policies.mdl');
|
||||
const mdl_Payments = require('../../models/tiers/payments.mdl');
|
||||
const paymentService = require('../../services/payment.service');
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
function mockAccessToken(token = 'tok-abc') {
|
||||
axios.post.mockImplementationOnce((url) => {
|
||||
expect(url).toMatch(/\/v1\/oauth2\/token$/);
|
||||
return Promise.resolve({ data: { access_token: token } });
|
||||
});
|
||||
}
|
||||
|
||||
// ── Provider delegation ─────────────────────────────────────────────────────────
|
||||
|
||||
describe('provider delegation (registry → paypal.provider → axios)', () => {
|
||||
|
||||
test('createOrder("paypal", ...) reaches PayPal\'s create-order endpoint', async () => {
|
||||
mockAccessToken();
|
||||
axios.post.mockResolvedValueOnce({ data: { id: 'ORDER-1', status: 'CREATED' } });
|
||||
|
||||
const result = await paymentService.createOrder('paypal', { amount: 25, referenceId: 'plan-1' });
|
||||
|
||||
expect(axios.post.mock.calls[1][0]).toBe('https://api-m.sandbox.paypal.com/v2/checkout/orders');
|
||||
expect(result).toEqual({ id: 'ORDER-1', status: 'CREATED' });
|
||||
});
|
||||
|
||||
test('captureOrder("paypal", ...) reaches PayPal\'s capture endpoint', async () => {
|
||||
mockAccessToken();
|
||||
axios.post.mockResolvedValueOnce({ data: { id: 'ORDER-1', status: 'COMPLETED' } });
|
||||
|
||||
const result = await paymentService.captureOrder('paypal', 'ORDER-1');
|
||||
|
||||
expect(axios.post.mock.calls[1][0]).toBe('https://api-m.sandbox.paypal.com/v2/checkout/orders/ORDER-1/capture');
|
||||
expect(result).toEqual({ id: 'ORDER-1', status: 'COMPLETED' });
|
||||
});
|
||||
|
||||
test('refundCapture("paypal", ...) reaches PayPal\'s refund endpoint', async () => {
|
||||
mockAccessToken();
|
||||
axios.post.mockResolvedValueOnce({ data: { id: 'REFUND-1', status: 'COMPLETED' } });
|
||||
|
||||
const result = await paymentService.refundCapture('paypal', 'CAPTURE-1', 10, 'USD');
|
||||
|
||||
expect(axios.post.mock.calls[1][0]).toBe('https://api-m.sandbox.paypal.com/v2/payments/captures/CAPTURE-1/refund');
|
||||
expect(result).toEqual({ id: 'REFUND-1', status: 'COMPLETED' });
|
||||
});
|
||||
|
||||
test('an unconfigured/unknown provider name fails fast with a descriptive error instead of hitting axios', () => {
|
||||
expect(() => paymentService.createOrder('stripe', { amount: 25, referenceId: 'plan-1' }))
|
||||
.toThrow(/Unknown payment provider: "stripe"/);
|
||||
expect(axios.post).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Refund policy ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('refund policy', () => {
|
||||
|
||||
test('falls back to the 5-minute default window when no policy is configured', () => {
|
||||
expect(paymentService.getRefundWindowMs(null)).toBe(5 * 60_000);
|
||||
expect(paymentService.isRefundAllowed(null)).toBe(true);
|
||||
});
|
||||
|
||||
test('honors a custom policy window and unit', () => {
|
||||
const policy = { refund_policy: { allowed: false, window_value: 2, window_unit: 'hours' } };
|
||||
expect(paymentService.getRefundWindowMs(policy)).toBe(2 * 3_600_000);
|
||||
expect(paymentService.isRefundAllowed(policy)).toBe(false);
|
||||
});
|
||||
|
||||
test('getPolicyForPlan() looks up the policy by plan_id', async () => {
|
||||
mdl_PaymentPolicies.findOne.mockResolvedValue({ plan_id: 7 });
|
||||
const policy = await paymentService.getPolicyForPlan(7);
|
||||
expect(mdl_PaymentPolicies.findOne).toHaveBeenCalledWith({ where: { plan_id: 7 } });
|
||||
expect(policy).toEqual({ plan_id: 7 });
|
||||
});
|
||||
});
|
||||
|
||||
// ── Promo evaluation ───────────────────────────────────────────────────────────
|
||||
|
||||
describe('evaluatePromo()', () => {
|
||||
const plan = { plan_id: 1, price: 100 };
|
||||
|
||||
test('rejects when no code is provided', async () => {
|
||||
const result = await paymentService.evaluatePromo({}, plan, '');
|
||||
expect(result).toEqual({ valid: false, reason: 'No promo code provided.' });
|
||||
});
|
||||
|
||||
test('rejects an unknown code', async () => {
|
||||
const policy = { promo_rules: [] };
|
||||
const result = await paymentService.evaluatePromo(policy, plan, 'BOGUS');
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.reason).toBe('Invalid promo code.');
|
||||
});
|
||||
|
||||
test('applies a flat discount', async () => {
|
||||
const policy = { promo_rules: [{ code: 'FLAT10', type: 'flat', value: 10 }] };
|
||||
mdl_Payments.count.mockResolvedValue(0);
|
||||
|
||||
const result = await paymentService.evaluatePromo(policy, plan, 'flat10');
|
||||
expect(result).toMatchObject({ valid: true, code: 'FLAT10', discount: 10 });
|
||||
});
|
||||
|
||||
test('applies a percent discount capped by max_discount', async () => {
|
||||
const policy = { promo_rules: [{ code: 'PCT50', type: 'percent', value: 50, max_discount: 30 }] };
|
||||
mdl_Payments.count.mockResolvedValue(0);
|
||||
|
||||
const result = await paymentService.evaluatePromo(policy, plan, 'PCT50');
|
||||
expect(result).toMatchObject({ valid: true, discount: 30 });
|
||||
});
|
||||
|
||||
test('rejects an expired code', async () => {
|
||||
const policy = { promo_rules: [{ code: 'OLD', type: 'flat', value: 5, expires_at: '2000-01-01' }] };
|
||||
const result = await paymentService.evaluatePromo(policy, plan, 'OLD');
|
||||
expect(result).toMatchObject({ valid: false, reason: 'Promo code has expired.' });
|
||||
});
|
||||
|
||||
test('rejects once max_uses has been reached', async () => {
|
||||
const policy = { promo_rules: [{ code: 'LIMITED', type: 'flat', value: 5, max_uses: 2 }] };
|
||||
mdl_Payments.count.mockResolvedValue(2);
|
||||
|
||||
const result = await paymentService.evaluatePromo(policy, plan, 'LIMITED');
|
||||
expect(result).toMatchObject({ valid: false, reason: 'Promo code has reached its usage limit.' });
|
||||
});
|
||||
|
||||
test('rejects when the subtotal is below min_amount', async () => {
|
||||
const policy = { promo_rules: [{ code: 'BIGSPEND', type: 'flat', value: 5, min_amount: 200 }] };
|
||||
mdl_Payments.count.mockResolvedValue(0);
|
||||
|
||||
const result = await paymentService.evaluatePromo(policy, plan, 'BIGSPEND');
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.reason).toMatch(/minimum purchase/);
|
||||
});
|
||||
|
||||
test('evaluates against effectivePrice (localized currency) instead of plan.price when provided', async () => {
|
||||
const policy = { promo_rules: [{ code: 'PCT10', type: 'percent', value: 10 }] };
|
||||
mdl_Payments.count.mockResolvedValue(0);
|
||||
|
||||
const result = await paymentService.evaluatePromo(policy, plan, 'PCT10', 50);
|
||||
expect(result.discount).toBe(5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
'use strict';
|
||||
|
||||
// ── Regression tests for the "revoke plan access, no refund" feature ────────
|
||||
// revokePlanSubscriberAccess() must replicate revokeTier's single-record
|
||||
// "auto-downgrade to Free only if the user holds no other active tier" rule
|
||||
// (controllers/admin/tiers.controller.js) instead of blanket-downgrading
|
||||
// everyone, and must fire exactly one in-app notification batch plus one
|
||||
// email per affected user.
|
||||
|
||||
jest.mock('../../models/tiers/user_tiers.mdl', () => ({
|
||||
findAll: jest.fn(),
|
||||
update: jest.fn(),
|
||||
bulkCreate: jest.fn(),
|
||||
}));
|
||||
jest.mock('../../models/users/users.mdl', () => ({ findAll: jest.fn() }));
|
||||
jest.mock('../../models/notifications/user_notification.mdl', () => ({ bulkCreate: jest.fn() }));
|
||||
jest.mock('../../services/email.service', () => ({ sendEmail: jest.fn().mockResolvedValue(true) }));
|
||||
|
||||
const mdl_UserTiers = require('../../models/tiers/user_tiers.mdl');
|
||||
const mdl_Users = require('../../models/users/users.mdl');
|
||||
const UserNotification = require('../../models/notifications/user_notification.mdl');
|
||||
const { sendEmail } = require('../../services/email.service');
|
||||
|
||||
const { revokePlanSubscriberAccess, revokePlanSubscriberAccessBulk } = require('../../services/planAccess.service');
|
||||
|
||||
function makePlan(overrides = {}) {
|
||||
return { plan_id: 10, label: 'Premium – 1 Month', ...overrides };
|
||||
}
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
describe('revokePlanSubscriberAccess()', () => {
|
||||
test('no active subscribers → no-op, returns zero count', async () => {
|
||||
mdl_UserTiers.findAll.mockResolvedValue([]);
|
||||
|
||||
const result = await revokePlanSubscriberAccess(makePlan(), 99);
|
||||
|
||||
expect(result).toEqual({ revoked_user_count: 0 });
|
||||
expect(mdl_UserTiers.update).not.toHaveBeenCalled();
|
||||
expect(UserNotification.bulkCreate).not.toHaveBeenCalled();
|
||||
expect(sendEmail).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('a user with ONLY this plan active gets auto-downgraded to Free', async () => {
|
||||
mdl_UserTiers.findAll
|
||||
.mockResolvedValueOnce([{ tier_id: 1, user_id: 5, plan_id: 10 }]) // active rows for the plan
|
||||
.mockResolvedValueOnce([]); // grouped "still active elsewhere" check — none
|
||||
mdl_Users.findAll.mockResolvedValue([{ user_id: 5, email: 'a@b.com', personal_info: { name: { full_name: 'Ana' } } }]);
|
||||
|
||||
const result = await revokePlanSubscriberAccess(makePlan(), 99);
|
||||
|
||||
expect(mdl_UserTiers.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ status: 'revoked', revoked_by: 99 }),
|
||||
{ where: { tier_id: [1] } }
|
||||
);
|
||||
expect(mdl_UserTiers.bulkCreate).toHaveBeenCalledWith([
|
||||
expect.objectContaining({ user_id: '5', tier: 'free', status: 'active' }),
|
||||
]);
|
||||
expect(result).toEqual({ revoked_user_count: 1 });
|
||||
});
|
||||
|
||||
test('a user with ANOTHER concurrently-active plan does NOT get downgraded', async () => {
|
||||
mdl_UserTiers.findAll
|
||||
.mockResolvedValueOnce([{ tier_id: 2, user_id: 6, plan_id: 10 }])
|
||||
.mockResolvedValueOnce([{ user_id: 6 }]); // still holds a different active tier
|
||||
mdl_Users.findAll.mockResolvedValue([{ user_id: 6, email: 'c@d.com', personal_info: {} }]);
|
||||
|
||||
await revokePlanSubscriberAccess(makePlan(), 99);
|
||||
|
||||
expect(mdl_UserTiers.bulkCreate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('fires exactly one notification batch and one email per affected user', async () => {
|
||||
mdl_UserTiers.findAll
|
||||
.mockResolvedValueOnce([
|
||||
{ tier_id: 1, user_id: 5, plan_id: 10 },
|
||||
{ tier_id: 2, user_id: 6, plan_id: 10 },
|
||||
])
|
||||
.mockResolvedValueOnce([{ user_id: 5 }, { user_id: 6 }]);
|
||||
mdl_Users.findAll.mockResolvedValue([
|
||||
{ user_id: 5, email: 'a@b.com', personal_info: {} },
|
||||
{ user_id: 6, email: 'c@d.com', personal_info: {} },
|
||||
]);
|
||||
|
||||
const result = await revokePlanSubscriberAccess(makePlan(), 99);
|
||||
|
||||
expect(UserNotification.bulkCreate).toHaveBeenCalledTimes(1);
|
||||
expect(UserNotification.bulkCreate.mock.calls[0][0]).toHaveLength(2);
|
||||
expect(sendEmail).toHaveBeenCalledTimes(2);
|
||||
expect(sendEmail).toHaveBeenCalledWith(expect.objectContaining({ to: 'a@b.com', type: 'TIER_ACCESS_REVOKED' }));
|
||||
expect(result).toEqual({ revoked_user_count: 2 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('revokePlanSubscriberAccessBulk() — N+1 regression', () => {
|
||||
test('query count stays flat regardless of plan/subscriber count (no per-user or per-plan loop)', async () => {
|
||||
const plans = [
|
||||
{ plan_id: 10, label: 'Premium – 1 Month' },
|
||||
{ plan_id: 11, label: 'Premium – 1 Year' },
|
||||
{ plan_id: 12, label: 'Basic' },
|
||||
];
|
||||
const activeRows = Array.from({ length: 25 }, (_, i) => ({
|
||||
tier_id: i + 1,
|
||||
user_id: i + 1,
|
||||
plan_id: plans[i % plans.length].plan_id,
|
||||
}));
|
||||
mdl_UserTiers.findAll
|
||||
.mockResolvedValueOnce(activeRows) // active rows across all 3 plans
|
||||
.mockResolvedValueOnce([]); // grouped "still active" check — nobody else active
|
||||
mdl_Users.findAll.mockResolvedValue(
|
||||
activeRows.map((r) => ({ user_id: r.user_id, email: `${r.user_id}@x.com`, personal_info: {} })),
|
||||
);
|
||||
|
||||
const result = await revokePlanSubscriberAccessBulk(plans, 99);
|
||||
|
||||
// Exactly 2 findAll calls total (active rows + grouped still-active check),
|
||||
// 1 bulk update, 1 bulk downgrade create, 1 notification bulkCreate —
|
||||
// no matter how many plans/users were involved.
|
||||
expect(mdl_UserTiers.findAll).toHaveBeenCalledTimes(2);
|
||||
expect(mdl_UserTiers.update).toHaveBeenCalledTimes(1);
|
||||
expect(mdl_UserTiers.bulkCreate).toHaveBeenCalledTimes(1);
|
||||
expect(mdl_UserTiers.bulkCreate.mock.calls[0][0]).toHaveLength(25);
|
||||
expect(UserNotification.bulkCreate).toHaveBeenCalledTimes(1);
|
||||
expect(UserNotification.bulkCreate.mock.calls[0][0]).toHaveLength(25);
|
||||
expect(result).toEqual({ revoked_user_count: 25 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
'use strict';
|
||||
|
||||
const { fmtDate, fmtDateTime, fmtTime } = require('../../utils/datetime.util');
|
||||
|
||||
const ISO = '2026-06-20T14:30:00.000Z'; // Saturday, June 20, 2026, 2:30 PM UTC
|
||||
|
||||
// ── fmtDate ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('fmtDate()', () => {
|
||||
test('null → returns —', () => {
|
||||
expect(fmtDate(null)).toBe('—');
|
||||
});
|
||||
|
||||
test('empty string → returns —', () => {
|
||||
expect(fmtDate('')).toBe('—');
|
||||
});
|
||||
|
||||
test('formats year correctly', () => {
|
||||
expect(fmtDate(ISO)).toContain('2026');
|
||||
});
|
||||
|
||||
test('formats month correctly (June)', () => {
|
||||
expect(fmtDate(ISO)).toContain('June');
|
||||
});
|
||||
|
||||
test('formats day correctly (20)', () => {
|
||||
expect(fmtDate(ISO)).toContain('20');
|
||||
});
|
||||
|
||||
test('accepts Date object as well as ISO string', () => {
|
||||
const d = new Date(ISO);
|
||||
expect(fmtDate(d)).toContain('2026');
|
||||
});
|
||||
});
|
||||
|
||||
// ── fmtDateTime ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe('fmtDateTime()', () => {
|
||||
test('null → returns —', () => {
|
||||
expect(fmtDateTime(null)).toBe('—');
|
||||
});
|
||||
|
||||
test('contains date portion', () => {
|
||||
expect(fmtDateTime(ISO)).toContain('2026');
|
||||
expect(fmtDateTime(ISO)).toContain('June');
|
||||
});
|
||||
|
||||
test('contains time portion (2:30 PM UTC)', () => {
|
||||
const out = fmtDateTime(ISO);
|
||||
expect(out).toMatch(/2:30/);
|
||||
expect(out).toContain('UTC');
|
||||
});
|
||||
});
|
||||
|
||||
// ── fmtTime ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('fmtTime()', () => {
|
||||
test('null → returns —', () => {
|
||||
expect(fmtTime(null)).toBe('—');
|
||||
});
|
||||
|
||||
test('outputs time with AM/PM', () => {
|
||||
expect(fmtTime(ISO)).toMatch(/\d+:\d{2}\s*(AM|PM)/);
|
||||
});
|
||||
|
||||
test('contains timezone label (UTC)', () => {
|
||||
expect(fmtTime(ISO)).toContain('UTC');
|
||||
});
|
||||
|
||||
test('locale option changes output', () => {
|
||||
const en = fmtTime(ISO, { locale: 'en-US' });
|
||||
expect(en).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
'use strict';
|
||||
|
||||
const { generateOTP, getOTPExpiry, isOTPExpired } = require('../../utils/otp.util');
|
||||
|
||||
// ── generateOTP ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe('generateOTP()', () => {
|
||||
test('returns a 6-character string', () => {
|
||||
expect(generateOTP()).toHaveLength(6);
|
||||
});
|
||||
|
||||
test('contains only digits', () => {
|
||||
expect(generateOTP()).toMatch(/^\d{6}$/);
|
||||
});
|
||||
|
||||
test('value is within 000000-999999', () => {
|
||||
const n = Number(generateOTP());
|
||||
expect(n).toBeGreaterThanOrEqual(0);
|
||||
expect(n).toBeLessThanOrEqual(999999);
|
||||
});
|
||||
|
||||
test('zero-pads values under 100000', () => {
|
||||
// Run many samples to catch low values; deterministic check via string length
|
||||
for (let i = 0; i < 50; i++) {
|
||||
expect(generateOTP()).toHaveLength(6);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ── getOTPExpiry ──────────────────────────────────────────────────────────────
|
||||
|
||||
describe('getOTPExpiry()', () => {
|
||||
test('returns a Date instance', () => {
|
||||
expect(getOTPExpiry()).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
test('expiry is in the future', () => {
|
||||
expect(getOTPExpiry().getTime()).toBeGreaterThan(Date.now());
|
||||
});
|
||||
|
||||
test('default offset is approximately 10 minutes', () => {
|
||||
const before = Date.now();
|
||||
const expiry = getOTPExpiry().getTime();
|
||||
const after = Date.now();
|
||||
const tenMin = 10 * 60 * 1000;
|
||||
expect(expiry).toBeGreaterThanOrEqual(before + tenMin - 100);
|
||||
expect(expiry).toBeLessThanOrEqual(after + tenMin + 100);
|
||||
});
|
||||
|
||||
test('custom minutes are respected', () => {
|
||||
const before = Date.now();
|
||||
const expiry = getOTPExpiry(5).getTime();
|
||||
const fiveMin = 5 * 60 * 1000;
|
||||
expect(expiry).toBeGreaterThanOrEqual(before + fiveMin - 100);
|
||||
});
|
||||
});
|
||||
|
||||
// ── isOTPExpired ──────────────────────────────────────────────────────────────
|
||||
|
||||
describe('isOTPExpired()', () => {
|
||||
test('null → expired (true)', () => {
|
||||
expect(isOTPExpired(null)).toBe(true);
|
||||
});
|
||||
|
||||
test('undefined → expired (true)', () => {
|
||||
expect(isOTPExpired(undefined)).toBe(true);
|
||||
});
|
||||
|
||||
test('past date → expired (true)', () => {
|
||||
const past = new Date(Date.now() - 60_000);
|
||||
expect(isOTPExpired(past)).toBe(true);
|
||||
});
|
||||
|
||||
test('future date → not expired (false)', () => {
|
||||
const future = new Date(Date.now() + 60_000);
|
||||
expect(isOTPExpired(future)).toBe(false);
|
||||
});
|
||||
|
||||
test('accepts ISO string as well as Date', () => {
|
||||
const future = new Date(Date.now() + 60_000).toISOString();
|
||||
expect(isOTPExpired(future)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
'use strict';
|
||||
|
||||
const R = require('../../utils/response.util');
|
||||
|
||||
function makeRes() {
|
||||
const res = {
|
||||
_status: null,
|
||||
_body: null,
|
||||
status(code) { this._status = code; return this; },
|
||||
json(body) { this._body = body; return this; },
|
||||
};
|
||||
return res;
|
||||
}
|
||||
|
||||
// ── R.success ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('R.success()', () => {
|
||||
test('default status is 200', () => {
|
||||
const res = makeRes();
|
||||
R.success(res, 'OK');
|
||||
expect(res._status).toBe(200);
|
||||
});
|
||||
|
||||
test('envelope shape: status=success, message, data', () => {
|
||||
const res = makeRes();
|
||||
R.success(res, 'Created', { id: 1 }, 201);
|
||||
expect(res._body).toEqual({ status: 'success', message: 'Created', data: { id: 1 } });
|
||||
});
|
||||
|
||||
test('custom status code is used', () => {
|
||||
const res = makeRes();
|
||||
R.success(res, 'Created', null, 201);
|
||||
expect(res._status).toBe(201);
|
||||
});
|
||||
|
||||
test('data is null when omitted', () => {
|
||||
const res = makeRes();
|
||||
R.success(res, 'OK');
|
||||
expect(res._body.data).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ── R.error ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('R.error()', () => {
|
||||
test('default status is 500', () => {
|
||||
const res = makeRes();
|
||||
R.error(res, 'Something broke');
|
||||
expect(res._status).toBe(500);
|
||||
});
|
||||
|
||||
test('envelope shape: status=error, message', () => {
|
||||
const res = makeRes();
|
||||
R.error(res, 'Not found', 404);
|
||||
expect(res._body).toMatchObject({ status: 'error', message: 'Not found' });
|
||||
expect(res._status).toBe(404);
|
||||
});
|
||||
|
||||
test('errors field is absent when not provided', () => {
|
||||
const res = makeRes();
|
||||
R.error(res, 'Bad request', 400);
|
||||
expect(res._body).not.toHaveProperty('errors');
|
||||
});
|
||||
|
||||
test('errors field is included when provided', () => {
|
||||
const res = makeRes();
|
||||
const errs = [{ field: 'email', msg: 'Invalid' }];
|
||||
R.error(res, 'Validation failed', 422, errs);
|
||||
expect(res._body.errors).toEqual(errs);
|
||||
});
|
||||
});
|
||||
|
||||
// ── R.validationError ─────────────────────────────────────────────────────────
|
||||
|
||||
describe('R.validationError()', () => {
|
||||
test('status is always 422', () => {
|
||||
const res = makeRes();
|
||||
R.validationError(res, []);
|
||||
expect(res._status).toBe(422);
|
||||
});
|
||||
|
||||
test('envelope shape: status=error, message=Validation failed, errors', () => {
|
||||
const res = makeRes();
|
||||
const errs = [{ field: 'name', msg: 'Required' }];
|
||||
R.validationError(res, errs);
|
||||
expect(res._body).toEqual({
|
||||
status: 'error',
|
||||
message: 'Validation failed',
|
||||
errors: errs,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
'use strict';
|
||||
|
||||
// Set secrets BEFORE requiring — jwt.sign/verify reads process.env at call time
|
||||
// but we want a clean, isolated secret that does not change across test runs.
|
||||
process.env.JWT_SECRET = 'test-jwt-secret-32chars-padding!!';
|
||||
process.env.JWT_REFRESH_SECRET = 'test-refresh-secret-32chars-pad!!';
|
||||
process.env.JWT_EXPIRES_IN = '15m';
|
||||
process.env.JWT_REFRESH_EXPIRES_IN = '7d';
|
||||
|
||||
const jwt = require('jsonwebtoken');
|
||||
const {
|
||||
generateTokens,
|
||||
verifyAccessToken,
|
||||
verifyRefreshToken,
|
||||
hashToken,
|
||||
shouldRotateRefreshToken,
|
||||
} = require('../../utils/token.util');
|
||||
|
||||
const MOCK_USER = { user_id: 1, email: 'test@example.com', acc_type: 'user', reg_type: 'system' };
|
||||
|
||||
// ── generateTokens ────────────────────────────────────────────────────────────
|
||||
|
||||
describe('generateTokens()', () => {
|
||||
test('returns accessToken and refreshToken strings', () => {
|
||||
const { accessToken, refreshToken } = generateTokens(MOCK_USER);
|
||||
expect(typeof accessToken).toBe('string');
|
||||
expect(typeof refreshToken).toBe('string');
|
||||
});
|
||||
|
||||
test('accessToken contains correct payload fields', () => {
|
||||
const { accessToken } = generateTokens(MOCK_USER);
|
||||
const decoded = jwt.decode(accessToken);
|
||||
expect(decoded.user_id).toBe(MOCK_USER.user_id);
|
||||
expect(decoded.email).toBe(MOCK_USER.email);
|
||||
expect(decoded.acc_type).toBe(MOCK_USER.acc_type);
|
||||
expect(decoded.reg_type).toBe(MOCK_USER.reg_type);
|
||||
});
|
||||
|
||||
test('refreshToken contains only user_id', () => {
|
||||
const { refreshToken } = generateTokens(MOCK_USER);
|
||||
const decoded = jwt.decode(refreshToken);
|
||||
expect(decoded.user_id).toBe(MOCK_USER.user_id);
|
||||
expect(decoded.email).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ── verifyAccessToken ─────────────────────────────────────────────────────────
|
||||
|
||||
describe('verifyAccessToken()', () => {
|
||||
test('valid token → returns decoded payload', () => {
|
||||
const { accessToken } = generateTokens(MOCK_USER);
|
||||
const decoded = verifyAccessToken(accessToken);
|
||||
expect(decoded.user_id).toBe(MOCK_USER.user_id);
|
||||
});
|
||||
|
||||
test('tampered token → throws JsonWebTokenError', () => {
|
||||
const { accessToken } = generateTokens(MOCK_USER);
|
||||
expect(() => verifyAccessToken(accessToken + 'tampered')).toThrow();
|
||||
});
|
||||
|
||||
test('expired token → throws TokenExpiredError', () => {
|
||||
const expired = jwt.sign(
|
||||
{ user_id: 99, exp: Math.floor(Date.now() / 1000) - 10 },
|
||||
process.env.JWT_SECRET
|
||||
);
|
||||
let err;
|
||||
try { verifyAccessToken(expired); } catch (e) { err = e; }
|
||||
expect(err.name).toBe('TokenExpiredError');
|
||||
});
|
||||
|
||||
test('token signed with wrong secret → throws', () => {
|
||||
const bad = jwt.sign({ user_id: 1 }, 'wrong-secret');
|
||||
expect(() => verifyAccessToken(bad)).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ── verifyRefreshToken ────────────────────────────────────────────────────────
|
||||
|
||||
describe('verifyRefreshToken()', () => {
|
||||
test('valid refresh token → returns payload with user_id', () => {
|
||||
const { refreshToken } = generateTokens(MOCK_USER);
|
||||
const decoded = verifyRefreshToken(refreshToken);
|
||||
expect(decoded.user_id).toBe(MOCK_USER.user_id);
|
||||
});
|
||||
|
||||
test('access token used as refresh token → throws (different secret)', () => {
|
||||
const { accessToken } = generateTokens(MOCK_USER);
|
||||
expect(() => verifyRefreshToken(accessToken)).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ── hashToken ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('hashToken()', () => {
|
||||
test('returns a 64-character hex string (SHA-256)', () => {
|
||||
expect(hashToken('some-token')).toMatch(/^[a-f0-9]{64}$/);
|
||||
});
|
||||
|
||||
test('is deterministic — same input produces same hash', () => {
|
||||
expect(hashToken('abc')).toBe(hashToken('abc'));
|
||||
});
|
||||
|
||||
test('different inputs produce different hashes', () => {
|
||||
expect(hashToken('token-a')).not.toBe(hashToken('token-b'));
|
||||
});
|
||||
});
|
||||
|
||||
// ── shouldRotateRefreshToken ──────────────────────────────────────────────────
|
||||
|
||||
describe('shouldRotateRefreshToken()', () => {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
test('expires in 10 minutes (within 1-day threshold) → should rotate', () => {
|
||||
const decoded = { exp: now + 600 };
|
||||
expect(shouldRotateRefreshToken(decoded, 1)).toBe(true);
|
||||
});
|
||||
|
||||
test('expires in 5 days (well beyond 1-day threshold) → should not rotate', () => {
|
||||
const decoded = { exp: now + 5 * 24 * 60 * 60 };
|
||||
expect(shouldRotateRefreshToken(decoded, 1)).toBe(false);
|
||||
});
|
||||
|
||||
test('custom threshold is respected', () => {
|
||||
const decoded = { exp: now + 2 * 24 * 60 * 60 }; // 2 days left
|
||||
expect(shouldRotateRefreshToken(decoded, 3)).toBe(true); // 3-day threshold → rotate
|
||||
expect(shouldRotateRefreshToken(decoded, 1)).toBe(false); // 1-day threshold → don't rotate
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user