Build MerchantFlow onboarding CRM foundation

This commit is contained in:
Oleksandr Prokhorenko
2026-09-24 16:43:22 +03:00
commit 3aa47d825f
78 changed files with 10739 additions and 0 deletions
+28
View File
@@ -0,0 +1,28 @@
{
"name": "@merchantflow/api",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "node ../../scripts/dev-api.mjs",
"build": "tsc",
"typecheck": "tsc --noEmit",
"test": "node --test test/unit.test.mjs"
},
"dependencies": {
"@merchantflow/contracts": "workspace:*",
"@merchantflow/database": "workspace:*",
"@nestjs/common": "11.2.6",
"@nestjs/core": "11.2.6",
"@nestjs/platform-express": "11.2.6",
"cookie-parser": "1.4.7",
"dotenv": "17.4.2",
"reflect-metadata": "0.2.2",
"rxjs": "7.8.2",
"zod": "4.6.5"
},
"devDependencies": {
"@types/cookie-parser": "1.4.10",
"@types/express": "5.0.6"
}
}
+14
View File
@@ -0,0 +1,14 @@
import type { User } from '@merchantflow/contracts';
import type { Prisma } from '@merchantflow/database';
export function merchantScope(user: User): Prisma.MerchantWhereInput {
switch (user.role) {
case 'HEAD_OF_SALES':
return {};
case 'COMPLIANCE_OFFICER':
return { status: { in: ['KYB', 'COMPLIANCE_REVIEW'] } };
case 'ACCOUNT_MANAGER':
return { ownerId: user.id };
default:
return { id: '__no_access__' };
}
}
+60
View File
@@ -0,0 +1,60 @@
import 'reflect-metadata';
import {
Module,
Controller,
Get,
Inject,
Injectable,
type OnApplicationShutdown,
} from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import cookieParser from 'cookie-parser';
import { createDatabase, PrismaClient } from '@merchantflow/database';
import { AuthController, AuthService, SessionGuard } from './auth.js';
import { CrmController } from './crm.js';
import { DATABASE, ApiError, ErrorFilter } from './shared.js';
import { env } from './env.js';
@Controller('health')
class HealthController {
constructor(@Inject(DATABASE) private readonly db: PrismaClient) {}
@Get() async health() {
try {
await this.db.$queryRaw`SELECT 1`;
return { status: 'ok', database: 'connected' };
} catch {
throw new ApiError('DATABASE_UNAVAILABLE', 503);
}
}
}
@Injectable()
class DatabaseLifecycle implements OnApplicationShutdown {
constructor(@Inject(DATABASE) private readonly db: PrismaClient) {}
async onApplicationShutdown() {
await this.db.$disconnect();
}
}
@Module({
controllers: [HealthController, AuthController, CrmController],
providers: [
{ provide: DATABASE, useFactory: () => createDatabase(env.DATABASE_URL) },
DatabaseLifecycle,
AuthService,
SessionGuard,
],
})
class AppModule {}
export async function createApp() {
const app = await NestFactory.create(AppModule, { logger: ['error', 'warn', 'log'] });
app.setGlobalPrefix('api');
app.use(cookieParser());
app.use(
(_req: unknown, res: { setHeader: (key: string, value: string) => void }, next: () => void) => {
res.setHeader('Cache-Control', 'no-store');
res.setHeader('X-Content-Type-Options', 'nosniff');
next();
},
);
app.useGlobalFilters(new ErrorFilter());
app.enableShutdownHooks();
return app;
}
+117
View File
@@ -0,0 +1,117 @@
import {
Injectable,
Inject,
Controller,
Post,
Get,
Body,
Req,
Res,
UseGuards,
type CanActivate,
type ExecutionContext,
} from '@nestjs/common';
import { createHash, randomBytes } from 'node:crypto';
import type { Request, Response } from 'express';
import { PrismaClient, hashPassword, verifyPassword } from '@merchantflow/database';
import { loginSchema } from '@merchantflow/contracts';
import { DATABASE, ApiError, type AuthRequest } from './shared.js';
import { env } from './env.js';
export const publicUser = { id: true, name: true, email: true, role: true } as const;
const sessionId = (token: string) => createHash('sha256').update(token).digest('hex');
const cookieName = 'mf_session';
const cookieOptions = {
httpOnly: true,
sameSite: 'lax' as const,
secure: env.NODE_ENV === 'production',
path: '/api',
};
const dummyHash = hashPassword('invalid-account-placeholder');
@Injectable()
export class AuthService {
private attempts = new Map<string, { count: number; until: number }>();
constructor(@Inject(DATABASE) private readonly db: PrismaClient) {}
async current(token: unknown) {
if (typeof token !== 'string' || !/^[a-f0-9]{64}$/.test(token))
throw new ApiError('UNAUTHORIZED', 401);
const session = await this.db.session.findUnique({
where: { id: sessionId(token) },
include: { user: { select: publicUser } },
});
if (!session || session.expiresAt.getTime() <= Date.now())
throw new ApiError('UNAUTHORIZED', 401);
return session.user;
}
async login(body: unknown, request: Request, response: Response) {
this.checkOrigin(request);
const input = loginSchema.parse(body);
const key = request.ip ?? 'local';
const now = Date.now();
for (const [ip, value] of this.attempts) if (value.until <= now) this.attempts.delete(ip);
const attempt = this.attempts.get(key) ?? { count: 0, until: now + 300000 };
if (attempt.count >= 20) throw new ApiError('TOO_MANY_REQUESTS', 429);
attempt.count++;
this.attempts.set(key, attempt);
const user = await this.db.user.findUnique({ where: { email: input.email } });
const valid = verifyPassword(input.password, user?.passwordHash ?? dummyHash);
if (!user || !valid) throw new ApiError('INVALID_CREDENTIALS', 401);
this.attempts.delete(key);
await this.revoke(request.cookies?.[cookieName]);
await this.db.session.deleteMany({ where: { expiresAt: { lt: new Date() } } });
const token = randomBytes(32).toString('hex');
await this.db.session.create({
data: { id: sessionId(token), userId: user.id, expiresAt: new Date(now + 8 * 3600000) },
});
response.cookie(cookieName, token, { ...cookieOptions, maxAge: 8 * 3600000 });
return { id: user.id, name: user.name, email: user.email, role: user.role };
}
async revoke(token: unknown) {
if (typeof token === 'string')
await this.db.session.deleteMany({ where: { id: sessionId(token) } });
}
checkOrigin(req: Request) {
const allowed = new Set([env.APP_ORIGIN]);
const origin = new URL(env.APP_ORIGIN);
if (env.NODE_ENV !== 'production' && ['localhost', '127.0.0.1'].includes(origin.hostname)) {
origin.hostname = origin.hostname === 'localhost' ? '127.0.0.1' : 'localhost';
allowed.add(origin.origin);
}
if (
(req.headers.origin && !allowed.has(req.headers.origin)) ||
req.headers['sec-fetch-site'] === 'cross-site'
)
throw new ApiError('FORBIDDEN', 403);
}
async logout(request: Request, response: Response) {
this.checkOrigin(request);
await this.revoke(request.cookies?.[cookieName]);
response.clearCookie(cookieName, cookieOptions);
}
}
@Injectable()
export class SessionGuard implements CanActivate {
constructor(private readonly auth: AuthService) {}
async canActivate(context: ExecutionContext) {
const req = context.switchToHttp().getRequest<AuthRequest>();
req.user = await this.auth.current(req.cookies?.[cookieName]);
return true;
}
}
@Controller('auth')
export class AuthController {
constructor(private readonly auth: AuthService) {}
@Post('login') login(
@Body() body: unknown,
@Req() req: Request,
@Res({ passthrough: true }) res: Response,
) {
return this.auth.login(body, req, res);
}
@Post('logout') async logout(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
await this.auth.logout(req, res);
return { ok: true };
}
@UseGuards(SessionGuard) @Get('me') me(@Req() req: AuthRequest) {
return req.user;
}
}
+175
View File
@@ -0,0 +1,175 @@
import { Controller, Get, Inject, Param, Query, Req, UseGuards } from '@nestjs/common';
import { PrismaClient, type Prisma } from '@merchantflow/database';
import { statuses, merchantQuerySchema, taskQuerySchema } from '@merchantflow/contracts';
import { SessionGuard } from './auth.js';
import { DATABASE, ApiError, type AuthRequest } from './shared.js';
import { merchantScope } from './access.js';
const merchantSelect = {
id: true,
name: true,
website: true,
industry: true,
country: true,
contactName: true,
contactEmail: true,
status: true,
createdAt: true,
stageEnteredAt: true,
owner: { select: { id: true, name: true } },
} as const;
const eventSelect = {
id: true,
fromStatus: true,
toStatus: true,
occurredAt: true,
note: true,
merchant: { select: { id: true, name: true } },
actor: { select: { name: true } },
} as const;
const taskSelect = {
id: true,
title: true,
status: true,
dueAt: true,
remindAt: true,
completedAt: true,
merchant: { select: { id: true, name: true } },
assignee: { select: { name: true } },
} as const;
@UseGuards(SessionGuard)
@Controller()
export class CrmController {
constructor(@Inject(DATABASE) private readonly db: PrismaClient) {}
@Get('merchants') async merchants(@Req() req: AuthRequest, @Query() query: unknown) {
const { page, search, status } = merchantQuerySchema.parse(query);
const where: Prisma.MerchantWhereInput = {
AND: [
merchantScope(req.user),
...(status ? [{ status }] : []),
...(search
? [
{
OR: [
{ name: { contains: search, mode: 'insensitive' as const } },
{ contactEmail: { contains: search, mode: 'insensitive' as const } },
],
},
]
: []),
],
};
const [items, total] = await this.db.$transaction([
this.db.merchant.findMany({
where,
select: merchantSelect,
orderBy: [{ createdAt: 'desc' }, { id: 'asc' }],
take: 8,
skip: (page - 1) * 8,
}),
this.db.merchant.count({ where }),
]);
return { items, total, page, pageSize: 8 };
}
@Get('merchants/:id') async detail(@Req() req: AuthRequest, @Param('id') id: string) {
const merchant = await this.db.merchant.findFirst({
where: { AND: [merchantScope(req.user), { id }] },
select: {
...merchantSelect,
checklist: {
select: { id: true, documentCode: true, state: true, note: true },
orderBy: { documentCode: 'asc' },
},
notes: {
select: { id: true, text: true, createdAt: true, author: { select: { name: true } } },
orderBy: { createdAt: 'desc' },
},
events: { select: eventSelect, orderBy: { occurredAt: 'desc' } },
tasks: { select: taskSelect, orderBy: { dueAt: 'asc' } },
},
});
if (!merchant) throw new ApiError('NOT_FOUND', 404);
return merchant;
}
@Get('pipeline') pipeline(@Req() req: AuthRequest) {
return this.db.merchant.findMany({
where: merchantScope(req.user),
select: merchantSelect,
orderBy: { stageEnteredAt: 'asc' },
});
}
@Get('tasks') tasks(@Req() req: AuthRequest, @Query() query: unknown) {
const { filter } = taskQuerySchema.parse(query);
const where: Prisma.TaskWhereInput = { merchant: merchantScope(req.user) };
if (filter === 'DONE') where.status = 'DONE';
if (['OPEN', 'OVERDUE', 'UPCOMING'].includes(filter)) where.status = 'OPEN';
if (filter === 'OVERDUE') where.dueAt = { lt: new Date() };
if (filter === 'UPCOMING') where.dueAt = { gte: new Date() };
return this.db.task.findMany({
where,
select: taskSelect,
orderBy: [{ status: 'asc' }, { dueAt: 'asc' }],
});
}
@Get('review-queue') reviewQueue(@Req() req: AuthRequest) {
if (req.user.role !== 'COMPLIANCE_OFFICER') throw new ApiError('FORBIDDEN', 403);
return this.db.merchant.findMany({
where: { AND: [merchantScope(req.user), { status: 'COMPLIANCE_REVIEW' }] },
select: merchantSelect,
orderBy: [{ stageEnteredAt: 'asc' }, { id: 'asc' }],
});
}
@Get('dashboard') async dashboard(@Req() req: AuthRequest) {
const scope = merchantScope(req.user);
const distributionQuery = this.db.merchant.groupBy({
by: ['status'],
orderBy: { status: 'asc' },
where: scope,
_count: { _all: true },
});
const [
merchantCount,
reviewCount,
overdueTasks,
transitionsLast30Days,
distribution,
recentEvents,
upcomingTasks,
] = await this.db.$transaction([
this.db.merchant.count({ where: scope }),
this.db.merchant.count({ where: { AND: [scope, { status: 'COMPLIANCE_REVIEW' }] } }),
this.db.task.count({ where: { merchant: scope, status: 'OPEN', dueAt: { lt: new Date() } } }),
this.db.statusEvent.count({
where: {
merchant: scope,
fromStatus: { not: null },
occurredAt: { gte: new Date(Date.now() - 30 * 86400000) },
},
}),
distributionQuery,
this.db.statusEvent.findMany({
where: { merchant: scope },
select: eventSelect,
orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }],
take: 6,
}),
this.db.task.findMany({
where: { merchant: scope, status: 'OPEN' },
select: taskSelect,
orderBy: { dueAt: 'asc' },
take: 4,
}),
]);
return {
merchantCount,
reviewCount,
overdueTasks,
transitionsLast30Days,
distribution: statuses.map((status) => ({
status,
count: distribution.find((d) => d.status === status)?._count._all ?? 0,
})),
recentEvents,
upcomingTasks,
};
}
}
+13
View File
@@ -0,0 +1,13 @@
import { config } from 'dotenv';
import { z } from 'zod';
config({ path: new URL('../../../.env', import.meta.url).pathname, quiet: true });
export const env = z
.object({
DATABASE_URL: z
.url()
.default('postgresql://merchantflow:merchantflow_local@localhost:55440/merchantflow'),
API_PORT: z.coerce.number().default(3001),
APP_ORIGIN: z.url().default('http://localhost:5173'),
NODE_ENV: z.string().default('development'),
})
.parse(process.env);
+5
View File
@@ -0,0 +1,5 @@
import { createApp } from './app.js';
import { env } from './env.js';
const app = await createApp();
await app.listen(env.API_PORT, '127.0.0.1');
console.log(`MerchantFlow API: http://localhost:${env.API_PORT}/api/health`);
+42
View File
@@ -0,0 +1,42 @@
import { Catch, HttpException, type ExceptionFilter, type ArgumentsHost } from '@nestjs/common';
import type { Request, Response } from 'express';
import type { User } from '@merchantflow/contracts';
import { ZodError } from 'zod';
export const DATABASE = Symbol('DATABASE');
export interface AuthRequest extends Request {
user: User;
}
export class ApiError extends HttpException {
constructor(code: string, status: number) {
super({ code }, status);
}
}
@Catch()
export class ErrorFilter implements ExceptionFilter {
catch(error: unknown, host: ArgumentsHost) {
const response = host.switchToHttp().getResponse<Response>();
if (error instanceof ZodError) {
response.status(400).json({
code: 'VALIDATION_ERROR',
issues: error.issues.map((i) => ({
path: i.path.join('.'),
code: i.message.startsWith('validation.') ? i.message : 'validation.invalid',
})),
});
return;
}
if (error instanceof ApiError) {
response.status(error.getStatus()).json(error.getResponse());
return;
}
if (error instanceof HttpException) {
const status = error.getStatus();
response.status(status).json({
code: status === 404 ? 'NOT_FOUND' : status === 400 ? 'VALIDATION_ERROR' : 'INTERNAL_ERROR',
});
return;
}
console.error('API request failed', error instanceof Error ? error.message : 'Unknown error');
response.status(500).json({ code: 'INTERNAL_ERROR' });
}
}
+232
View File
@@ -0,0 +1,232 @@
import { before, after, test } from 'node:test';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { createDatabase } from '@merchantflow/database';
import { roles, statuses, documentCodes } from '@merchantflow/contracts';
import {
Role,
MerchantStatus,
DocumentCode,
} from '../../../packages/database/dist/generated/prisma/enums.js';
if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test'))
throw new Error('Integration tests require the isolated merchantflow_test database');
const db = createDatabase(process.env.DATABASE_URL);
let app, base;
const cookies = {};
async function request(path, cookie, options = {}) {
const response = await fetch(`${base}${path}`, {
...options,
headers: {
...(cookie ? { cookie } : {}),
...(options.body ? { 'content-type': 'application/json' } : {}),
...options.headers,
},
});
return { status: response.status, body: await response.json(), response };
}
async function login(account, password = 'MerchantFlow123!') {
return request('/auth/login', null, {
method: 'POST',
body: JSON.stringify({ email: `${account}@merchantflow.test`, password }),
});
}
before(async () => {
const { createApp } = await import('../dist/app.js');
app = await createApp();
await app.listen(0, '127.0.0.1');
base = (await app.getUrl()) + '/api';
for (const account of ['head', 'compliance', 'manager1', 'manager2']) {
const r = await login(account);
assert.equal(r.status, 201);
cookies[account] = r.response.headers.get('set-cookie').split(';')[0];
}
});
after(async () => {
await app?.close();
await db.$disconnect();
});
test('Prisma and browser contracts agree on canonical codes', () => {
assert.deepEqual(Object.values(Role), [...roles]);
assert.deepEqual(Object.values(MerchantStatus), [...statuses]);
assert.deepEqual(Object.values(DocumentCode), [...documentCodes]);
});
test('health checks the database and every CRM endpoint requires a session', async () => {
assert.deepEqual((await request('/health')).body, { status: 'ok', database: 'connected' });
for (const path of [
'/auth/me',
'/dashboard',
'/merchants',
'/merchants/merchant-01',
'/pipeline',
'/tasks',
'/review-queue',
])
assert.equal((await request(path)).status, 401, path);
});
test('login validates, sets protected cookies, and rejects incorrect credentials and cross-origin writes', async () => {
assert.equal((await login('head', 'incorrect')).status, 401);
const invalid = await request('/auth/login', null, {
method: 'POST',
body: '{"email":"wrong","password":""}',
});
assert.equal(invalid.status, 400);
assert.equal(invalid.body.code, 'VALIDATION_ERROR');
const r = await login('head');
const cookie = r.response.headers.get('set-cookie');
assert.match(cookie, /HttpOnly/i);
assert.match(cookie, /SameSite=Lax/i);
assert.match(cookie, /Path=\/api/i);
assert.equal(
(
await request('/auth/logout', cookies.head, {
method: 'POST',
headers: { origin: 'https://untrusted.example' },
})
).status,
403,
);
});
for (const [account, total] of [
['head', 18],
['manager1', 9],
['manager2', 9],
['compliance', 4],
])
test(`${account}: all reads, details, history, tasks and metrics respect the scope`, async () => {
const cookie = cookies[account];
const expected = (await db.merchant.findMany()).filter((m) =>
account === 'head' || account === 'compliance'
? account === 'head' || ['KYB', 'COMPLIANCE_REVIEW'].includes(m.status)
: m.ownerId === `user-${account}`,
);
assert.equal(expected.length, total);
const ids = expected.map((m) => m.id);
const list = await request('/merchants', cookie);
assert.equal(list.status, 200);
assert.equal(list.body.total, total);
assert.ok(list.body.items.every((m) => ids.includes(m.id)));
assert.equal(list.body.items.length, Math.min(total, 8));
if (total > 8) {
const second = await request('/merchants?page=2', cookie);
assert.ok(second.body.items.length > 0);
assert.ok(
second.body.items.every((m) => !list.body.items.some((first) => first.id === m.id)),
);
}
const pipeline = (await request('/pipeline', cookie)).body;
assert.deepEqual(pipeline.map((m) => m.id).sort(), [...ids].sort());
const tasks = (await request('/tasks', cookie)).body;
assert.equal(tasks.length, total * 2);
assert.ok(tasks.every((t) => ids.includes(t.merchant.id)));
for (const m of expected) {
const detail = (await request(`/merchants/${m.id}`, cookie)).body;
assert.equal(detail.id, m.id);
assert.equal(detail.checklist.length, 4);
assert.ok(detail.events.every((e) => e.merchant.id === m.id));
assert.ok(detail.tasks.every((t) => t.merchant.id === m.id));
assert.ok(!JSON.stringify(detail).includes('passwordHash'));
}
const dashboard = (await request('/dashboard', cookie)).body;
assert.equal(dashboard.merchantCount, total);
assert.equal(
dashboard.reviewCount,
expected.filter((m) => m.status === 'COMPLIANCE_REVIEW').length,
);
assert.equal(
dashboard.overdueTasks,
await db.task.count({
where: { merchantId: { in: ids }, status: 'OPEN', dueAt: { lt: new Date() } },
}),
);
assert.equal(
dashboard.transitionsLast30Days,
await db.statusEvent.count({
where: {
merchantId: { in: ids },
fromStatus: { not: null },
occurredAt: { gte: new Date(Date.now() - 30 * 86400000) },
},
}),
);
assert.equal(
dashboard.distribution.reduce((sum, x) => sum + x.count, 0),
total,
);
assert.ok(dashboard.recentEvents.every((e) => ids.includes(e.merchant.id)));
assert.ok(dashboard.upcomingTasks.every((t) => ids.includes(t.merchant.id)));
const hidden = (await db.merchant.findMany()).find((m) => !ids.includes(m.id));
if (hidden) {
assert.equal((await request(`/merchants/${hidden.id}`, cookie)).status, 404);
assert.equal(
(await request(`/merchants?search=${encodeURIComponent(hidden.name)}`, cookie)).body.total,
0,
);
}
assert.equal(
(await request('/review-queue', cookie)).status,
account === 'compliance' ? 200 : 403,
);
});
test('filters are validated and review queue is oldest first', async () => {
const cookie = cookies.head;
for (const query of ['page=-1', 'status=Live', 'page=1.5'])
assert.equal((await request(`/merchants?${query}`, cookie)).status, 400);
assert.equal((await request('/tasks?filter=invalid', cookie)).status, 400);
const live = (await request('/merchants?status=LIVE', cookie)).body;
assert.equal(live.total, 2);
const done = (await request('/tasks?filter=DONE', cookie)).body;
assert.ok(done.every((t) => t.status === 'DONE'));
const overdue = (await request('/tasks?filter=OVERDUE', cookie)).body;
assert.ok(overdue.every((t) => t.status === 'OPEN' && new Date(t.dueAt) < new Date()));
const queue = (await request('/review-queue', cookies.compliance)).body;
assert.equal(queue.length, 2);
assert.ok(queue.every((m) => m.status === 'COMPLIANCE_REVIEW'));
assert.ok(new Date(queue[0].stageEnteredAt) <= new Date(queue[1].stageEnteredAt));
});
test('seed is repeatable without modifying records; history includes correction and terminal outcomes', async () => {
const snapshot = await db.merchant.findMany({
orderBy: { id: 'asc' },
include: { events: { orderBy: { id: 'asc' } } },
});
const result = spawnSync('pnpm', ['--filter', '@merchantflow/database', 'seed'], {
env: process.env,
encoding: 'utf8',
});
assert.equal(result.status, 0, result.stderr);
assert.equal(await db.user.count(), 4);
assert.equal(await db.merchant.count(), 18);
assert.deepEqual(
await db.merchant.findMany({
orderBy: { id: 'asc' },
include: { events: { orderBy: { id: 'asc' } } },
}),
snapshot,
);
assert.ok(
snapshot.some((m) =>
m.events.some((e) => e.fromStatus === 'COMPLIANCE_REVIEW' && e.toStatus === 'KYB'),
),
);
assert.ok(!snapshot.some((m) => m.events.some((e) => e.fromStatus === 'LIVE')));
});
test('expired, logged-out and replaced sessions cannot be reused', async () => {
const r = await login('manager1');
const cookie = r.response.headers.get('set-cookie').split(';')[0];
const token = cookie.split('=')[1];
await db.session.update({
where: { id: createHash('sha256').update(token).digest('hex') },
data: { expiresAt: new Date(0) },
});
assert.equal((await request('/auth/me', cookie)).status, 401);
const fresh = await login('manager1');
const freshCookie = fresh.response.headers.get('set-cookie').split(';')[0];
assert.equal((await request('/auth/logout', freshCookie, { method: 'POST' })).status, 201);
assert.equal((await request('/pipeline', freshCookie)).status, 401);
const replacement = await request('/auth/login', cookies.manager2, {
method: 'POST',
body: JSON.stringify({ email: '[email protected]', password: 'MerchantFlow123!' }),
});
assert.equal(replacement.status, 201);
assert.equal((await request('/auth/me', cookies.manager2)).status, 401);
});
+21
View File
@@ -0,0 +1,21 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { merchantScope } from '../dist/access.js';
import { hashPassword, verifyPassword } from '@merchantflow/database';
test('passwords use distinct salts and reject incorrect values', () => {
const hash = hashPassword('example-password');
assert.notEqual(hash, hashPassword('example-password'));
assert.equal(verifyPassword('example-password', hash), true);
assert.equal(verifyPassword('wrong', hash), false);
assert.equal(verifyPassword('wrong', 'broken'), false);
});
test('every role receives its exact merchant scope', () => {
assert.deepEqual(merchantScope({ role: 'HEAD_OF_SALES' }), {});
assert.deepEqual(merchantScope({ role: 'ACCOUNT_MANAGER', id: 'manager-1' }), {
ownerId: 'manager-1',
});
assert.deepEqual(merchantScope({ role: 'COMPLIANCE_OFFICER' }), {
status: { in: ['KYB', 'COMPLIANCE_REVIEW'] },
});
assert.deepEqual(merchantScope({ role: 'unexpected' }), { id: '__no_access__' });
});
+13
View File
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"rootDir": "src",
"outDir": "dist",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"sourceMap": true
},
"include": ["src"]
}