Initial commit: multi-company financial management system
Root company app (src/, client/) — GL foundation, AR, and AP: - Segmented Chart of Accounts (Sage 300-style), double-entry PostingService with three-layer balance enforcement (app validation, CHECK constraints, deferred DB trigger), gap-free document numbering, RBAC with branch restrictions. - Accounts Receivable: Customers, Invoices, Credit Notes, Receipts with allocation, all posting through PostingService. - Accounts Payable: Suppliers, Supplier Invoices, Debit Notes, Payments with allocation, mirroring AR's posting pattern. - Tax Codes shared between AR and AP. - Company-app login is a token handoff from the Account Manager (RS256, single-use, company-scoped) rather than a local password. - Frontend reskinned to the approved mockup: navy sidebar, dashboard, tree-view Chart of Accounts, Customer/Supplier 360 pages. Account Manager (manager/, manager/client/) — central login gateway: - Password + TOTP 2FA + Google/Microsoft OAuth, company picker, and the RS256 handoff token issuance that the company app verifies. Covered by unit + integration tests against a real Postgres database (GL balance invariants, AR/AP posting correctness and allocation limits, the full handoff exchange including replay/cross-company/expiry/forgery rejection). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tq2DbEvzHzs13jDFhLaX44
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
import cors from 'cors';
|
||||
import express, { Express } from 'express';
|
||||
import helmet from 'helmet';
|
||||
import { errorHandler } from './middleware/errorHandler';
|
||||
import { authRouter } from './modules/auth/auth.routes';
|
||||
import { companiesRouter } from './modules/companies/companies.routes';
|
||||
|
||||
export function createApp(): Express {
|
||||
const app = express();
|
||||
|
||||
app.use(helmet());
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
|
||||
app.get('/health', (req, res) => res.json({ status: 'ok' }));
|
||||
|
||||
app.use('/api/auth', authRouter);
|
||||
app.use('/api/companies', companiesRouter);
|
||||
|
||||
app.use((req, res) => res.status(404).json({ error: 'Not found' }));
|
||||
app.use(errorHandler);
|
||||
|
||||
return app;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import 'dotenv/config';
|
||||
import path from 'path';
|
||||
|
||||
function required(name: string): string {
|
||||
const value = process.env[name];
|
||||
if (!value) {
|
||||
throw new Error(`Missing required environment variable: ${name}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export const env = {
|
||||
port: Number(process.env.PORT ?? 5100),
|
||||
databaseUrl: required('DATABASE_URL'),
|
||||
|
||||
jwtAccessSecret: required('JWT_ACCESS_SECRET'),
|
||||
jwtRefreshSecret: required('JWT_REFRESH_SECRET'),
|
||||
jwtAccessTtl: process.env.JWT_ACCESS_TTL ?? '15m',
|
||||
jwtRefreshTtl: process.env.JWT_REFRESH_TTL ?? '7d',
|
||||
|
||||
handoffPrivateKeyPath: path.resolve(process.cwd(), process.env.HANDOFF_PRIVATE_KEY_PATH ?? './keys/handoff-private.pem'),
|
||||
handoffPublicKeyPath: path.resolve(process.cwd(), process.env.HANDOFF_PUBLIC_KEY_PATH ?? './keys/handoff-public.pem'),
|
||||
handoffTokenTtlSeconds: Number(process.env.HANDOFF_TOKEN_TTL_SECONDS ?? 90),
|
||||
|
||||
totpIssuer: process.env.TOTP_ISSUER ?? 'Cross Financial Manager',
|
||||
|
||||
googleClientId: process.env.GOOGLE_CLIENT_ID ?? '',
|
||||
googleClientSecret: process.env.GOOGLE_CLIENT_SECRET ?? '',
|
||||
googleRedirectUri: process.env.GOOGLE_REDIRECT_URI ?? '',
|
||||
|
||||
microsoftClientId: process.env.MICROSOFT_CLIENT_ID ?? '',
|
||||
microsoftClientSecret: process.env.MICROSOFT_CLIENT_SECRET ?? '',
|
||||
microsoftTenant: process.env.MICROSOFT_TENANT ?? 'common',
|
||||
microsoftRedirectUri: process.env.MICROSOFT_REDIRECT_URI ?? '',
|
||||
|
||||
managerWebUrl: process.env.MANAGER_WEB_URL ?? 'http://localhost:5174',
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
|
||||
type Handler = (req: Request, res: Response, next: NextFunction) => Promise<void> | void;
|
||||
|
||||
/** Wraps an async route/controller handler so a rejected promise reaches errorHandler via next(). */
|
||||
export function asyncHandler(handler: Handler) {
|
||||
return (req: Request, res: Response, next: NextFunction): void => {
|
||||
Promise.resolve(handler(req, res, next)).catch(next);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import fs from 'fs';
|
||||
import crypto from 'crypto';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { env } from '../config/env';
|
||||
|
||||
export interface HandoffTokenClaims {
|
||||
sub: string; // resolved company-local email
|
||||
pid: number; // Person.id
|
||||
cid: number; // Company.id
|
||||
companySlug: string;
|
||||
}
|
||||
|
||||
let cachedPrivateKey: string | null = null;
|
||||
|
||||
function loadPrivateKey(): string {
|
||||
if (cachedPrivateKey) return cachedPrivateKey;
|
||||
if (!fs.existsSync(env.handoffPrivateKeyPath)) {
|
||||
throw new Error(
|
||||
`Handoff private key not found at ${env.handoffPrivateKeyPath}. Run "npm run generate-handoff-keys" first.`,
|
||||
);
|
||||
}
|
||||
cachedPrivateKey = fs.readFileSync(env.handoffPrivateKeyPath, 'utf8');
|
||||
return cachedPrivateKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mints a short-lived, single-use RS256 handoff token. Only the Manager ever holds the private
|
||||
* key — every company app holds only the public key and can verify but never mint, so
|
||||
* compromising one isolated company instance can't be used to forge a session for any other.
|
||||
*/
|
||||
export function signHandoffToken(claims: HandoffTokenClaims): { token: string; jti: string } {
|
||||
const jti = crypto.randomUUID();
|
||||
const token = jwt.sign(claims, loadPrivateKey(), {
|
||||
algorithm: 'RS256',
|
||||
expiresIn: env.handoffTokenTtlSeconds,
|
||||
jwtid: jti,
|
||||
});
|
||||
return { token, jti };
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import jwt, { SignOptions } from 'jsonwebtoken';
|
||||
import { env } from '../config/env';
|
||||
|
||||
type Purpose = 'access' | 'refresh' | '2fa_challenge';
|
||||
|
||||
interface SessionTokenPayload {
|
||||
sub: string;
|
||||
purpose: Purpose;
|
||||
}
|
||||
|
||||
function sign(personId: number, purpose: Purpose, secret: string, ttl: string | number): string {
|
||||
const options: SignOptions = { expiresIn: ttl as SignOptions['expiresIn'] };
|
||||
return jwt.sign({ sub: String(personId), purpose } satisfies SessionTokenPayload, secret, options);
|
||||
}
|
||||
|
||||
/** Verifies the token AND that it was issued for the expected purpose — a 2FA-challenge token
|
||||
* must never be accepted as a real access token, and vice versa. */
|
||||
function verify(token: string, secret: string, expectedPurpose: Purpose): number {
|
||||
const payload = jwt.verify(token, secret) as unknown as SessionTokenPayload;
|
||||
if (payload.purpose !== expectedPurpose) {
|
||||
throw new Error(`Expected a ${expectedPurpose} token, got ${payload.purpose}`);
|
||||
}
|
||||
return Number(payload.sub);
|
||||
}
|
||||
|
||||
export const signAccessToken = (personId: number): string => sign(personId, 'access', env.jwtAccessSecret, env.jwtAccessTtl);
|
||||
export const signRefreshToken = (personId: number): string => sign(personId, 'refresh', env.jwtRefreshSecret, env.jwtRefreshTtl);
|
||||
export const verifyAccessToken = (token: string): number => verify(token, env.jwtAccessSecret, 'access');
|
||||
export const verifyRefreshToken = (token: string): number => verify(token, env.jwtRefreshSecret, 'refresh');
|
||||
|
||||
/** A short-lived token identifying a person who passed password auth but still owes a 2FA code. */
|
||||
export const signTwoFactorChallengeToken = (personId: number): string =>
|
||||
sign(personId, '2fa_challenge', env.jwtAccessSecret, '5m');
|
||||
export const verifyTwoFactorChallengeToken = (token: string): number => verify(token, env.jwtAccessSecret, '2fa_challenge');
|
||||
|
||||
/**
|
||||
* CSRF protection for the OAuth authorize/callback round trip, without needing server-side
|
||||
* session storage: a self-verifying signed nonce, not tied to any person yet.
|
||||
*/
|
||||
export function signOAuthStateToken(): string {
|
||||
return jwt.sign({ purpose: 'oauth_state', nonce: Math.random().toString(36).slice(2) }, env.jwtAccessSecret, {
|
||||
expiresIn: '10m',
|
||||
});
|
||||
}
|
||||
export function verifyOAuthStateToken(token: string): boolean {
|
||||
try {
|
||||
const payload = jwt.verify(token, env.jwtAccessSecret) as { purpose?: string };
|
||||
return payload.purpose === 'oauth_state';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { env } from '../config/env';
|
||||
import { signOAuthStateToken, verifyOAuthStateToken } from './jwt';
|
||||
|
||||
export interface OAuthProfile {
|
||||
providerAccountId: string;
|
||||
email: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export class OAuthStateError extends Error {
|
||||
constructor() {
|
||||
super('Invalid or expired OAuth state');
|
||||
this.name = 'OAuthStateError';
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Google
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function googleAuthorizeUrl(): string {
|
||||
const state = signOAuthStateToken();
|
||||
const params = new URLSearchParams({
|
||||
client_id: env.googleClientId,
|
||||
redirect_uri: env.googleRedirectUri,
|
||||
response_type: 'code',
|
||||
scope: 'openid email profile',
|
||||
state,
|
||||
access_type: 'online',
|
||||
prompt: 'select_account',
|
||||
});
|
||||
return `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
|
||||
}
|
||||
|
||||
export async function exchangeGoogleCode(code: string, state: string): Promise<OAuthProfile> {
|
||||
if (!verifyOAuthStateToken(state)) throw new OAuthStateError();
|
||||
|
||||
const tokenResponse = await fetch('https://oauth2.googleapis.com/token', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({
|
||||
client_id: env.googleClientId,
|
||||
client_secret: env.googleClientSecret,
|
||||
code,
|
||||
redirect_uri: env.googleRedirectUri,
|
||||
grant_type: 'authorization_code',
|
||||
}),
|
||||
});
|
||||
if (!tokenResponse.ok) throw new Error(`Google token exchange failed: ${await tokenResponse.text()}`);
|
||||
const { access_token: accessToken } = (await tokenResponse.json()) as { access_token: string };
|
||||
|
||||
const userInfoResponse = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
if (!userInfoResponse.ok) throw new Error(`Google userinfo fetch failed: ${await userInfoResponse.text()}`);
|
||||
const profile = (await userInfoResponse.json()) as { sub: string; email: string; name?: string };
|
||||
|
||||
return { providerAccountId: profile.sub, email: profile.email, name: profile.name ?? profile.email };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Microsoft (Azure AD v2.0 endpoint)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function microsoftAuthorizeUrl(): string {
|
||||
const state = signOAuthStateToken();
|
||||
const params = new URLSearchParams({
|
||||
client_id: env.microsoftClientId,
|
||||
redirect_uri: env.microsoftRedirectUri,
|
||||
response_type: 'code',
|
||||
scope: 'openid email profile',
|
||||
state,
|
||||
response_mode: 'query',
|
||||
});
|
||||
return `https://login.microsoftonline.com/${env.microsoftTenant}/oauth2/v2.0/authorize?${params.toString()}`;
|
||||
}
|
||||
|
||||
export async function exchangeMicrosoftCode(code: string, state: string): Promise<OAuthProfile> {
|
||||
if (!verifyOAuthStateToken(state)) throw new OAuthStateError();
|
||||
|
||||
const tokenResponse = await fetch(`https://login.microsoftonline.com/${env.microsoftTenant}/oauth2/v2.0/token`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({
|
||||
client_id: env.microsoftClientId,
|
||||
client_secret: env.microsoftClientSecret,
|
||||
code,
|
||||
redirect_uri: env.microsoftRedirectUri,
|
||||
grant_type: 'authorization_code',
|
||||
}),
|
||||
});
|
||||
if (!tokenResponse.ok) throw new Error(`Microsoft token exchange failed: ${await tokenResponse.text()}`);
|
||||
const { access_token: accessToken } = (await tokenResponse.json()) as { access_token: string };
|
||||
|
||||
const userInfoResponse = await fetch('https://graph.microsoft.com/oidc/userinfo', {
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
if (!userInfoResponse.ok) throw new Error(`Microsoft userinfo fetch failed: ${await userInfoResponse.text()}`);
|
||||
const profile = (await userInfoResponse.json()) as { sub: string; email: string; name?: string };
|
||||
|
||||
return { providerAccountId: profile.sub, email: profile.email, name: profile.name ?? profile.email };
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
declare global {
|
||||
// eslint-disable-next-line no-var
|
||||
var __managerPrisma__: PrismaClient | undefined;
|
||||
}
|
||||
|
||||
export const prisma = global.__managerPrisma__ ?? new PrismaClient();
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
global.__managerPrisma__ = prisma;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { authenticator } from 'otplib';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import crypto from 'crypto';
|
||||
import { env } from '../config/env';
|
||||
|
||||
export function generateTotpSecret(): string {
|
||||
return authenticator.generateSecret();
|
||||
}
|
||||
|
||||
export function totpKeyUri(accountEmail: string, secret: string): string {
|
||||
return authenticator.keyuri(accountEmail, env.totpIssuer, secret);
|
||||
}
|
||||
|
||||
export function verifyTotpToken(token: string, secret: string): boolean {
|
||||
try {
|
||||
return authenticator.check(token, secret);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const BACKUP_CODE_COUNT = 10;
|
||||
|
||||
/** Returns { plainCodes, hashedCodes } — plainCodes shown to the person once, hashedCodes stored. */
|
||||
export async function generateBackupCodes(): Promise<{ plainCodes: string[]; hashedCodes: string[] }> {
|
||||
const plainCodes = Array.from({ length: BACKUP_CODE_COUNT }, () => crypto.randomBytes(5).toString('hex'));
|
||||
const hashedCodes = await Promise.all(plainCodes.map((code) => bcrypt.hash(code, 10)));
|
||||
return { plainCodes, hashedCodes };
|
||||
}
|
||||
|
||||
/** Returns the index of the matching hashed backup code, or -1 if none matched. */
|
||||
export async function findMatchingBackupCode(code: string, hashedCodes: string[]): Promise<number> {
|
||||
for (let i = 0; i < hashedCodes.length; i += 1) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
if (await bcrypt.compare(code, hashedCodes[i])) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
import { prisma } from '../lib/prisma';
|
||||
import { verifyAccessToken } from '../lib/jwt';
|
||||
import { AuthPerson } from '../types/express';
|
||||
|
||||
export async function loadAuthPerson(personId: number): Promise<AuthPerson | null> {
|
||||
const person = await prisma.person.findUnique({ where: { id: personId } });
|
||||
if (!person || !person.isActive) return null;
|
||||
return { id: person.id, email: person.email, fullName: person.fullName, isOperator: person.isOperator };
|
||||
}
|
||||
|
||||
export async function requireAuth(req: Request, res: Response, next: NextFunction): Promise<void> {
|
||||
const header = req.headers.authorization;
|
||||
if (!header?.startsWith('Bearer ')) {
|
||||
res.status(401).json({ error: 'Missing bearer token' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const personId = verifyAccessToken(header.slice('Bearer '.length));
|
||||
const person = await loadAuthPerson(personId);
|
||||
if (!person) {
|
||||
res.status(401).json({ error: 'Person not found or inactive' });
|
||||
return;
|
||||
}
|
||||
req.person = person;
|
||||
next();
|
||||
} catch {
|
||||
res.status(401).json({ error: 'Invalid or expired token' });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
import { Prisma } from '@prisma/client';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
export function errorHandler(error: unknown, req: Request, res: Response, next: NextFunction): void {
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
if (error.code === 'P2002') {
|
||||
res.status(409).json({ error: 'A record with this value already exists', meta: error.meta });
|
||||
return;
|
||||
}
|
||||
if (error.code === 'P2025') {
|
||||
res.status(404).json({ error: 'Record not found' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
|
||||
export function requireOperator(req: Request, res: Response, next: NextFunction): void {
|
||||
if (!req.person) {
|
||||
res.status(401).json({ error: 'Not authenticated' });
|
||||
return;
|
||||
}
|
||||
if (!req.person.isOperator) {
|
||||
res.status(403).json({ error: 'Operator access required' });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
import { AnyZodObject, ZodError } from 'zod';
|
||||
|
||||
type Section = 'body' | 'query' | 'params';
|
||||
|
||||
export function validate(schema: AnyZodObject, section: Section = 'body') {
|
||||
return (req: Request, res: Response, next: NextFunction): void => {
|
||||
try {
|
||||
req[section] = schema.parse(req[section]);
|
||||
next();
|
||||
} catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
res.status(400).json({ error: 'Validation failed', details: error.flatten() });
|
||||
return;
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { z } from 'zod';
|
||||
import * as authService from './auth.service';
|
||||
import { googleAuthorizeUrl, microsoftAuthorizeUrl, exchangeGoogleCode, exchangeMicrosoftCode } from '../../lib/oauth';
|
||||
import { env } from '../../config/env';
|
||||
|
||||
export const loginSchema = z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(1),
|
||||
});
|
||||
|
||||
export const twoFactorVerifySchema = z.object({
|
||||
twoFactorToken: z.string().min(1),
|
||||
code: z.string().min(1),
|
||||
});
|
||||
|
||||
export const twoFactorEnableSchema = z.object({
|
||||
code: z.string().min(1),
|
||||
});
|
||||
|
||||
export const refreshSchema = z.object({
|
||||
refreshToken: z.string().min(1),
|
||||
});
|
||||
|
||||
export async function loginHandler(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const { email, password } = req.body as z.infer<typeof loginSchema>;
|
||||
res.json(await authService.login(email, password));
|
||||
} catch (error) {
|
||||
if (error instanceof authService.InvalidCredentialsError) {
|
||||
res.status(401).json({ error: error.message });
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function twoFactorVerifyHandler(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const { twoFactorToken, code } = req.body as z.infer<typeof twoFactorVerifySchema>;
|
||||
res.json(await authService.completeTwoFactorChallenge(twoFactorToken, code));
|
||||
} catch (error) {
|
||||
if (error instanceof authService.InvalidTwoFactorCodeError) {
|
||||
res.status(401).json({ error: error.message });
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function refreshHandler(req: Request, res: Response): void {
|
||||
try {
|
||||
const { refreshToken } = req.body as z.infer<typeof refreshSchema>;
|
||||
res.json({ accessToken: authService.refreshSessionToken(refreshToken) });
|
||||
} catch {
|
||||
res.status(401).json({ error: 'Invalid or expired refresh token' });
|
||||
}
|
||||
}
|
||||
|
||||
export function meHandler(req: Request, res: Response): void {
|
||||
res.json({ person: req.person });
|
||||
}
|
||||
|
||||
export async function twoFactorEnrollHandler(req: Request, res: Response): Promise<void> {
|
||||
const enrollment = await authService.startTwoFactorEnrollment(req.person!.id, req.person!.email);
|
||||
res.json(enrollment);
|
||||
}
|
||||
|
||||
export async function twoFactorEnableHandler(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const { code } = req.body as z.infer<typeof twoFactorEnableSchema>;
|
||||
const backupCodes = await authService.confirmTwoFactorEnrollment(req.person!.id, code);
|
||||
res.json({ backupCodes });
|
||||
} catch (error) {
|
||||
if (error instanceof authService.InvalidTwoFactorCodeError) {
|
||||
res.status(401).json({ error: error.message });
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function redirectWithLoginResult(res: Response, result: Awaited<ReturnType<typeof authService.login>>): void {
|
||||
const url = new URL('/oauth/callback', env.managerWebUrl);
|
||||
if (result.requiresTwoFactor) {
|
||||
url.searchParams.set('twoFactorToken', result.twoFactorToken);
|
||||
} else {
|
||||
url.searchParams.set('accessToken', result.accessToken);
|
||||
url.searchParams.set('refreshToken', result.refreshToken);
|
||||
}
|
||||
res.redirect(url.toString());
|
||||
}
|
||||
|
||||
export function googleAuthorizeHandler(req: Request, res: Response): void {
|
||||
res.redirect(googleAuthorizeUrl());
|
||||
}
|
||||
|
||||
export async function googleCallbackHandler(req: Request, res: Response): Promise<void> {
|
||||
const { code, state } = req.query as { code?: string; state?: string };
|
||||
if (!code || !state) {
|
||||
res.status(400).json({ error: 'Missing code or state' });
|
||||
return;
|
||||
}
|
||||
const profile = await exchangeGoogleCode(code, state);
|
||||
const result = await authService.handleOAuthCallback('GOOGLE', profile);
|
||||
redirectWithLoginResult(res, result);
|
||||
}
|
||||
|
||||
export function microsoftAuthorizeHandler(req: Request, res: Response): void {
|
||||
res.redirect(microsoftAuthorizeUrl());
|
||||
}
|
||||
|
||||
export async function microsoftCallbackHandler(req: Request, res: Response): Promise<void> {
|
||||
const { code, state } = req.query as { code?: string; state?: string };
|
||||
if (!code || !state) {
|
||||
res.status(400).json({ error: 'Missing code or state' });
|
||||
return;
|
||||
}
|
||||
const profile = await exchangeMicrosoftCode(code, state);
|
||||
const result = await authService.handleOAuthCallback('MICROSOFT', profile);
|
||||
redirectWithLoginResult(res, result);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Router } from 'express';
|
||||
import { requireAuth } from '../../middleware/auth';
|
||||
import { validate } from '../../middleware/validate';
|
||||
import { asyncHandler } from '../../lib/asyncHandler';
|
||||
import {
|
||||
googleAuthorizeHandler,
|
||||
googleCallbackHandler,
|
||||
loginHandler,
|
||||
loginSchema,
|
||||
meHandler,
|
||||
microsoftAuthorizeHandler,
|
||||
microsoftCallbackHandler,
|
||||
refreshHandler,
|
||||
refreshSchema,
|
||||
twoFactorEnableHandler,
|
||||
twoFactorEnableSchema,
|
||||
twoFactorEnrollHandler,
|
||||
twoFactorVerifyHandler,
|
||||
twoFactorVerifySchema,
|
||||
} from './auth.controller';
|
||||
|
||||
export const authRouter = Router();
|
||||
|
||||
authRouter.post('/login', validate(loginSchema), asyncHandler(loginHandler));
|
||||
authRouter.post('/2fa/verify', validate(twoFactorVerifySchema), asyncHandler(twoFactorVerifyHandler));
|
||||
authRouter.post('/refresh', validate(refreshSchema), refreshHandler);
|
||||
authRouter.get('/me', requireAuth, meHandler);
|
||||
|
||||
authRouter.post('/2fa/enroll', requireAuth, asyncHandler(twoFactorEnrollHandler));
|
||||
authRouter.post('/2fa/enable', requireAuth, validate(twoFactorEnableSchema), asyncHandler(twoFactorEnableHandler));
|
||||
|
||||
authRouter.get('/oauth/google', googleAuthorizeHandler);
|
||||
authRouter.get('/oauth/google/callback', asyncHandler(googleCallbackHandler));
|
||||
authRouter.get('/oauth/microsoft', microsoftAuthorizeHandler);
|
||||
authRouter.get('/oauth/microsoft/callback', asyncHandler(microsoftCallbackHandler));
|
||||
@@ -0,0 +1,145 @@
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { OAuthProvider } from '@prisma/client';
|
||||
import { prisma } from '../../lib/prisma';
|
||||
import {
|
||||
signAccessToken,
|
||||
signRefreshToken,
|
||||
signTwoFactorChallengeToken,
|
||||
verifyRefreshToken,
|
||||
verifyTwoFactorChallengeToken,
|
||||
} from '../../lib/jwt';
|
||||
import { findMatchingBackupCode, generateBackupCodes, generateTotpSecret, totpKeyUri, verifyTotpToken } from '../../lib/totp';
|
||||
import { loadAuthPerson } from '../../middleware/auth';
|
||||
import { OAuthProfile } from '../../lib/oauth';
|
||||
|
||||
export class InvalidCredentialsError extends Error {
|
||||
constructor() {
|
||||
super('Invalid email or password');
|
||||
this.name = 'InvalidCredentialsError';
|
||||
}
|
||||
}
|
||||
|
||||
export class InvalidTwoFactorCodeError extends Error {
|
||||
constructor() {
|
||||
super('Invalid two-factor code');
|
||||
this.name = 'InvalidTwoFactorCodeError';
|
||||
}
|
||||
}
|
||||
|
||||
type LoginResult =
|
||||
| { requiresTwoFactor: true; twoFactorToken: string }
|
||||
| { requiresTwoFactor: false; accessToken: string; refreshToken: string; person: NonNullable<Awaited<ReturnType<typeof loadAuthPerson>>> };
|
||||
|
||||
async function issueSessionOrChallenge(personId: number): Promise<LoginResult> {
|
||||
const twoFactor = await prisma.twoFactorCredential.findUnique({ where: { personId } });
|
||||
if (twoFactor?.isEnabled) {
|
||||
return { requiresTwoFactor: true, twoFactorToken: signTwoFactorChallengeToken(personId) };
|
||||
}
|
||||
|
||||
const person = await loadAuthPerson(personId);
|
||||
if (!person) throw new InvalidCredentialsError();
|
||||
return {
|
||||
requiresTwoFactor: false,
|
||||
accessToken: signAccessToken(personId),
|
||||
refreshToken: signRefreshToken(personId),
|
||||
person,
|
||||
};
|
||||
}
|
||||
|
||||
export async function login(email: string, password: string): Promise<LoginResult> {
|
||||
const person = await prisma.person.findUnique({ where: { email }, include: { credential: true } });
|
||||
if (!person || !person.isActive || !person.credential) {
|
||||
throw new InvalidCredentialsError();
|
||||
}
|
||||
|
||||
const passwordMatches = await bcrypt.compare(password, person.credential.passwordHash);
|
||||
if (!passwordMatches) {
|
||||
throw new InvalidCredentialsError();
|
||||
}
|
||||
|
||||
return issueSessionOrChallenge(person.id);
|
||||
}
|
||||
|
||||
export async function completeTwoFactorChallenge(twoFactorToken: string, code: string) {
|
||||
let personId: number;
|
||||
try {
|
||||
personId = verifyTwoFactorChallengeToken(twoFactorToken);
|
||||
} catch {
|
||||
throw new InvalidTwoFactorCodeError();
|
||||
}
|
||||
|
||||
const twoFactor = await prisma.twoFactorCredential.findUnique({ where: { personId } });
|
||||
if (!twoFactor?.isEnabled) {
|
||||
throw new InvalidTwoFactorCodeError();
|
||||
}
|
||||
|
||||
if (verifyTotpToken(code, twoFactor.totpSecret)) {
|
||||
return finalizeSession(personId);
|
||||
}
|
||||
|
||||
const backupIndex = await findMatchingBackupCode(code, twoFactor.backupCodes);
|
||||
if (backupIndex === -1) {
|
||||
throw new InvalidTwoFactorCodeError();
|
||||
}
|
||||
|
||||
const remainingCodes = twoFactor.backupCodes.filter((_, index) => index !== backupIndex);
|
||||
await prisma.twoFactorCredential.update({ where: { personId }, data: { backupCodes: remainingCodes } });
|
||||
|
||||
return finalizeSession(personId);
|
||||
}
|
||||
|
||||
async function finalizeSession(personId: number) {
|
||||
const person = await loadAuthPerson(personId);
|
||||
if (!person) throw new InvalidTwoFactorCodeError();
|
||||
return { accessToken: signAccessToken(personId), refreshToken: signRefreshToken(personId), person };
|
||||
}
|
||||
|
||||
export function refreshSessionToken(refreshToken: string): string {
|
||||
const personId = verifyRefreshToken(refreshToken);
|
||||
return signAccessToken(personId);
|
||||
}
|
||||
|
||||
export async function startTwoFactorEnrollment(personId: number, email: string) {
|
||||
const secret = generateTotpSecret();
|
||||
await prisma.twoFactorCredential.upsert({
|
||||
where: { personId },
|
||||
create: { personId, totpSecret: secret, backupCodes: [], isEnabled: false },
|
||||
update: { totpSecret: secret, isEnabled: false, backupCodes: [] },
|
||||
});
|
||||
return { secret, otpauthUrl: totpKeyUri(email, secret) };
|
||||
}
|
||||
|
||||
export async function confirmTwoFactorEnrollment(personId: number, code: string): Promise<string[]> {
|
||||
const twoFactor = await prisma.twoFactorCredential.findUnique({ where: { personId } });
|
||||
if (!twoFactor || !verifyTotpToken(code, twoFactor.totpSecret)) {
|
||||
throw new InvalidTwoFactorCodeError();
|
||||
}
|
||||
const { plainCodes, hashedCodes } = await generateBackupCodes();
|
||||
await prisma.twoFactorCredential.update({
|
||||
where: { personId },
|
||||
data: { isEnabled: true, enabledAt: new Date(), backupCodes: hashedCodes },
|
||||
});
|
||||
return plainCodes;
|
||||
}
|
||||
|
||||
export async function handleOAuthCallback(provider: OAuthProvider, profile: OAuthProfile): Promise<LoginResult> {
|
||||
const existingAccount = await prisma.oAuthAccount.findUnique({
|
||||
where: { provider_providerAccountId: { provider, providerAccountId: profile.providerAccountId } },
|
||||
});
|
||||
|
||||
if (existingAccount) {
|
||||
return issueSessionOrChallenge(existingAccount.personId);
|
||||
}
|
||||
|
||||
const person = await prisma.person.upsert({
|
||||
where: { email: profile.email },
|
||||
create: { email: profile.email, fullName: profile.name },
|
||||
update: {},
|
||||
});
|
||||
|
||||
await prisma.oAuthAccount.create({
|
||||
data: { personId: person.id, provider, providerAccountId: profile.providerAccountId, email: profile.email },
|
||||
});
|
||||
|
||||
return issueSessionOrChallenge(person.id);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Request, Response } from 'express';
|
||||
import * as companiesService from './companies.service';
|
||||
|
||||
export async function listMyCompaniesHandler(req: Request, res: Response): Promise<void> {
|
||||
const memberships = await companiesService.listMyCompanies(req.person!.id);
|
||||
res.json(
|
||||
memberships.map((membership) => ({
|
||||
companyId: membership.company.id,
|
||||
name: membership.company.name,
|
||||
slug: membership.company.slug,
|
||||
status: membership.company.status,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
export async function handoffHandler(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const companyId = Number(req.params.id);
|
||||
const result = await companiesService.issueHandoff(req.person!.id, companyId);
|
||||
res.json(result);
|
||||
} catch (error) {
|
||||
if (error instanceof companiesService.MembershipNotFoundError) {
|
||||
res.status(403).json({ error: error.message });
|
||||
return;
|
||||
}
|
||||
if (error instanceof companiesService.CompanyNotReadyError) {
|
||||
res.status(409).json({ error: error.message });
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Router } from 'express';
|
||||
import { requireAuth } from '../../middleware/auth';
|
||||
import { asyncHandler } from '../../lib/asyncHandler';
|
||||
import { handoffHandler, listMyCompaniesHandler } from './companies.controller';
|
||||
|
||||
export const companiesRouter = Router();
|
||||
|
||||
companiesRouter.use(requireAuth);
|
||||
|
||||
companiesRouter.get('/', asyncHandler(listMyCompaniesHandler));
|
||||
companiesRouter.post('/:id/handoff', asyncHandler(handoffHandler));
|
||||
@@ -0,0 +1,60 @@
|
||||
import { prisma } from '../../lib/prisma';
|
||||
import { signHandoffToken } from '../../lib/handoffToken';
|
||||
|
||||
export class MembershipNotFoundError extends Error {
|
||||
constructor() {
|
||||
super('You do not have access to this company');
|
||||
this.name = 'MembershipNotFoundError';
|
||||
}
|
||||
}
|
||||
|
||||
export class CompanyNotReadyError extends Error {
|
||||
constructor() {
|
||||
super('This company is not currently reachable');
|
||||
this.name = 'CompanyNotReadyError';
|
||||
}
|
||||
}
|
||||
|
||||
export function listMyCompanies(personId: number) {
|
||||
return prisma.personCompanyMembership.findMany({
|
||||
where: { personId, isActive: true },
|
||||
include: { company: true },
|
||||
orderBy: { company: { name: 'asc' } },
|
||||
});
|
||||
}
|
||||
|
||||
export async function issueHandoff(personId: number, companyId: number) {
|
||||
const [person, membership] = await Promise.all([
|
||||
prisma.person.findUniqueOrThrow({ where: { id: personId } }),
|
||||
prisma.personCompanyMembership.findUnique({
|
||||
where: { personId_companyId: { personId, companyId } },
|
||||
include: { company: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!membership || !membership.isActive) {
|
||||
throw new MembershipNotFoundError();
|
||||
}
|
||||
if (!membership.company.publicUrl || membership.company.status !== 'ACTIVE') {
|
||||
throw new CompanyNotReadyError();
|
||||
}
|
||||
|
||||
const resolvedEmail = membership.companyUserEmail ?? person.email;
|
||||
const { token, jti } = signHandoffToken({
|
||||
sub: resolvedEmail,
|
||||
pid: person.id,
|
||||
cid: membership.company.id,
|
||||
companySlug: membership.company.slug,
|
||||
});
|
||||
|
||||
await prisma.provisioningAuditLog.create({
|
||||
data: {
|
||||
companyId: membership.company.id,
|
||||
actorId: person.id,
|
||||
action: 'HANDOFF_ISSUED',
|
||||
detail: { jti, resolvedEmail },
|
||||
},
|
||||
});
|
||||
|
||||
return { token, redirectUrl: membership.company.publicUrl };
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createApp } from './app';
|
||||
import { env } from './config/env';
|
||||
|
||||
const app = createApp();
|
||||
|
||||
app.listen(env.port, () => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`Account Manager API listening on http://localhost:${env.port}`);
|
||||
});
|
||||
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
export interface AuthPerson {
|
||||
id: number;
|
||||
email: string;
|
||||
fullName: string;
|
||||
isOperator: boolean;
|
||||
}
|
||||
|
||||
declare global {
|
||||
namespace Express {
|
||||
interface Request {
|
||||
person?: AuthPerson;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user