update project
This commit is contained in:
@@ -2,11 +2,11 @@ import express from 'express';
|
||||
import helmet from 'helmet';
|
||||
import cors from 'cors';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import swaggerUi from 'swagger-ui-express';
|
||||
import { env } from './config/env';
|
||||
import { swaggerSpec } from './config/swagger';
|
||||
import { errorHandler } from './middleware/error-handler';
|
||||
import walletSetupRoutes from './routes/wallet-setup.routes';
|
||||
import walletRoutes from './routes/wallet.routes';
|
||||
import vaultRoutes from './routes/vault.routes';
|
||||
import relayProxyRoutes from './routes/relay-proxy.routes';
|
||||
import tronProxyRoutes from './routes/tron-proxy.routes';
|
||||
import solSwapProxyRoutes from './routes/sol-swap-proxy.routes';
|
||||
@@ -25,12 +25,9 @@ app.get('/api/health', (_req, res) => {
|
||||
res.json({ success: true, data: { status: 'ok' } });
|
||||
});
|
||||
|
||||
app.use('/api/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
|
||||
app.get('/api/docs/swagger.json', (_req, res) => {
|
||||
res.json(swaggerSpec);
|
||||
});
|
||||
|
||||
app.use('/api/wallet', walletSetupRoutes);
|
||||
app.use('/api/wallets', walletRoutes);
|
||||
app.use('/api/vault', vaultRoutes);
|
||||
app.use('/api/relay', relayProxyRoutes);
|
||||
app.use('/api/tron', tronProxyRoutes);
|
||||
app.use('/api/sol/swap', solSwapProxyRoutes);
|
||||
|
||||
@@ -1,22 +1,16 @@
|
||||
import dotenv from 'dotenv';
|
||||
import path from 'path';
|
||||
import { fetchVaultSecrets } from './vault';
|
||||
|
||||
dotenv.config({ path: path.resolve(__dirname, '../../../../.env') });
|
||||
|
||||
export const env = {
|
||||
export let env = {
|
||||
db: {
|
||||
host: process.env.DB_HOST || 'localhost',
|
||||
port: parseInt(process.env.DB_PORT || '5432'),
|
||||
user: process.env.DB_USER || 'postgres',
|
||||
password: process.env.DB_PASSWORD || 'postgres',
|
||||
name: process.env.DB_NAME || 'cryptowallet_v2',
|
||||
},
|
||||
jwt: {
|
||||
jwksUrl: process.env.JWT_JWKS_URL || '',
|
||||
publicKey: process.env.JWT_PUBLIC_KEY || '',
|
||||
algorithm: process.env.JWT_ALGORITHM || 'RS256',
|
||||
issuer: process.env.JWT_ISSUER || '',
|
||||
audience: process.env.JWT_AUDIENCE || '',
|
||||
name: process.env.DB_NAME || 'cryptowallet',
|
||||
},
|
||||
port: parseInt(process.env.API_PORT || '3001'),
|
||||
frontendUrl: process.env.FRONTEND_URL || 'http://localhost:3000',
|
||||
@@ -24,5 +18,38 @@ export const env = {
|
||||
tronApiKey: process.env.TRON_API_KEY || null,
|
||||
jupiterApiKey: process.env.JUPITER_API_KEY || null,
|
||||
jupiterReferralAccount: process.env.JUPITER_REFERRAL_ACCOUNT || null,
|
||||
jupiterFeeBps: parseInt(process.env.JUPITER_FEE_BPS || '70'),
|
||||
jupiterFeeBps: parseInt(process.env.JUPITER_FEE_BPS || '70'), // 0.7%
|
||||
|
||||
// BITOK auth service
|
||||
bitokJwksUrl: process.env.BITOK_JWKS_URL || 'http://localhost:8000/.well-known/jwks.json',
|
||||
bitokIssuer: process.env.BITOK_ISSUER || 'auth-service',
|
||||
bitokAudience: process.env.BITOK_AUDIENCE || 'wallet-service',
|
||||
|
||||
// RabbitMQ
|
||||
rabbitmqUrl: process.env.RABBITMQ_URL || 'amqp://guest:guest@localhost:5672/',
|
||||
rabbitmqExchange: process.env.RABBITMQ_EXCHANGE || 'bitok.events',
|
||||
rabbitmqWalletQueue: process.env.RABBITMQ_WALLET_QUEUE || 'wallet.user_events',
|
||||
};
|
||||
|
||||
export async function initEnv(): Promise<void> {
|
||||
const secrets = await fetchVaultSecrets();
|
||||
|
||||
if (secrets) {
|
||||
console.log('[ENV] Loaded secrets from Vault');
|
||||
env = {
|
||||
...env,
|
||||
db: {
|
||||
host: secrets.db_host,
|
||||
port: parseInt(secrets.db_port),
|
||||
user: secrets.db_user,
|
||||
password: secrets.db_password,
|
||||
name: secrets.db_name,
|
||||
},
|
||||
relayApiKey: secrets.relay_api_key || null,
|
||||
tronApiKey: secrets.tron_api_key || env.tronApiKey,
|
||||
jupiterApiKey: secrets.jupiter_api_key || env.jupiterApiKey,
|
||||
};
|
||||
} else {
|
||||
console.log('[ENV] Vault not available, using env vars');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const swaggerPath = path.resolve(__dirname, '../../swagger.json');
|
||||
export const swaggerSpec = JSON.parse(fs.readFileSync(swaggerPath, 'utf-8'));
|
||||
30
apps/api/src/config/vault.ts
Normal file
30
apps/api/src/config/vault.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
interface VaultSecrets {
|
||||
db_host: string;
|
||||
db_port: string;
|
||||
db_user: string;
|
||||
db_password: string;
|
||||
db_name: string;
|
||||
relay_api_key: string;
|
||||
tron_api_key: string;
|
||||
jupiter_api_key: string;
|
||||
}
|
||||
|
||||
export async function fetchVaultSecrets(): Promise<VaultSecrets | null> {
|
||||
const vaultAddr = process.env.VAULT_ADDR;
|
||||
const vaultToken = process.env.VAULT_TOKEN;
|
||||
|
||||
if (!vaultAddr || !vaultToken) return null;
|
||||
|
||||
try {
|
||||
const res = await fetch(`${vaultAddr}/v1/kv/data/cryptowallet`, {
|
||||
headers: { 'X-Vault-Token': vaultToken },
|
||||
});
|
||||
|
||||
if (!res.ok) return null;
|
||||
|
||||
const body = (await res.json()) as { data: { data: VaultSecrets } };
|
||||
return body.data.data;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
23
apps/api/src/controllers/vault.controller.ts
Normal file
23
apps/api/src/controllers/vault.controller.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { UserModel } from '../models/user.model';
|
||||
|
||||
export const VaultController = {
|
||||
async getVault(req: Request, res: Response) {
|
||||
try {
|
||||
const user = await UserModel.findByBitokUserId(req.user!.bitokUserId);
|
||||
if (!user) {
|
||||
res.status(404).json({ success: false, error: 'User not found' });
|
||||
return;
|
||||
}
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
encryptedVault: user.encrypted_vault,
|
||||
vaultSalt: user.vault_salt,
|
||||
},
|
||||
});
|
||||
} catch (err: any) {
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
},
|
||||
};
|
||||
118
apps/api/src/controllers/wallet-setup.controller.ts
Normal file
118
apps/api/src/controllers/wallet-setup.controller.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { UserModel } from '../models/user.model';
|
||||
import { WalletModel } from '../models/wallet.model';
|
||||
import { db } from '../config/database';
|
||||
import { generateUlid } from '../utils/ulid';
|
||||
|
||||
export const WalletSetupController = {
|
||||
async setup(req: Request, res: Response) {
|
||||
try {
|
||||
const { bitokUserId, email } = req.user!;
|
||||
const { encryptedVault, vaultSalt, wallets } = req.body;
|
||||
|
||||
// Check if user already exists
|
||||
const existing = await UserModel.findByBitokUserId(bitokUserId);
|
||||
if (existing) {
|
||||
res.status(409).json({ success: false, error: 'Wallet already set up for this user' });
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await db.transaction(async (trx) => {
|
||||
const [user] = await trx('users')
|
||||
.insert({
|
||||
id: generateUlid(),
|
||||
bitok_user_id: bitokUserId,
|
||||
email: email || null,
|
||||
encrypted_vault: encryptedVault,
|
||||
vault_salt: vaultSalt,
|
||||
})
|
||||
.returning('*');
|
||||
|
||||
const walletRows = await trx('wallets')
|
||||
.insert(
|
||||
wallets.map((w: { chain: string; address: string; derivationPath: string }) => ({
|
||||
id: generateUlid(),
|
||||
user_id: user.id,
|
||||
chain: w.chain,
|
||||
address: w.address,
|
||||
derivation_path: w.derivationPath,
|
||||
}))
|
||||
)
|
||||
.returning('*');
|
||||
|
||||
return { user, wallets: walletRows };
|
||||
});
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
data: {
|
||||
user: {
|
||||
id: result.user.id,
|
||||
bitokUserId: result.user.bitok_user_id,
|
||||
email: result.user.email,
|
||||
},
|
||||
wallets: result.wallets.map((w: any) => ({
|
||||
chain: w.chain,
|
||||
address: w.address,
|
||||
derivationPath: w.derivation_path,
|
||||
})),
|
||||
},
|
||||
});
|
||||
} catch (err: any) {
|
||||
console.error('[WalletSetup] Error:', err.message);
|
||||
res.status(500).json({ success: false, error: 'Failed to set up wallet' });
|
||||
}
|
||||
},
|
||||
|
||||
async confirmMnemonic(req: Request, res: Response) {
|
||||
try {
|
||||
const { bitokUserId } = req.user!;
|
||||
const user = await UserModel.findByBitokUserId(bitokUserId);
|
||||
if (!user) {
|
||||
res.status(404).json({ success: false, error: 'Wallet not found' });
|
||||
return;
|
||||
}
|
||||
await UserModel.setMnemonicShown(user.id);
|
||||
res.json({ success: true, data: { mnemonicShown: true } });
|
||||
} catch (err: any) {
|
||||
console.error('[ConfirmMnemonic] Error:', err.message);
|
||||
res.status(500).json({ success: false, error: 'Failed to confirm mnemonic' });
|
||||
}
|
||||
},
|
||||
|
||||
async unlock(req: Request, res: Response) {
|
||||
try {
|
||||
const { bitokUserId } = req.user!;
|
||||
|
||||
const user = await UserModel.findByBitokUserId(bitokUserId);
|
||||
if (!user) {
|
||||
res.status(404).json({ success: false, error: 'Wallet not found' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (user.deleted) {
|
||||
res.status(403).json({ success: false, error: 'Account has been deleted' });
|
||||
return;
|
||||
}
|
||||
|
||||
const wallets = await WalletModel.findByUserId(user.id);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
encryptedVault: user.encrypted_vault,
|
||||
vaultSalt: user.vault_salt,
|
||||
wallets: wallets.map((w) => ({
|
||||
chain: w.chain,
|
||||
address: w.address,
|
||||
derivationPath: w.derivation_path,
|
||||
})),
|
||||
mnemonicShown: user.mnemonic_shown,
|
||||
},
|
||||
});
|
||||
} catch (err: any) {
|
||||
console.error('[WalletUnlock] Error:', err.message);
|
||||
res.status(500).json({ success: false, error: 'Failed to unlock wallet' });
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -1,10 +1,17 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { UserModel } from '../models/user.model';
|
||||
import { WalletModel } from '../models/wallet.model';
|
||||
|
||||
export const WalletController = {
|
||||
async getWallets(req: Request, res: Response) {
|
||||
try {
|
||||
const wallets = await WalletModel.findByUserId(req.auth!.userId);
|
||||
const user = await UserModel.findByBitokUserId(req.user!.bitokUserId);
|
||||
if (!user) {
|
||||
res.status(404).json({ success: false, error: 'User not found' });
|
||||
return;
|
||||
}
|
||||
|
||||
const wallets = await WalletModel.findByUserId(user.id);
|
||||
res.json({
|
||||
success: true,
|
||||
data: wallets.map((w) => ({
|
||||
|
||||
@@ -12,7 +12,7 @@ const config: Knex.Config = {
|
||||
port: parseInt(process.env.DB_PORT || '5432'),
|
||||
user: process.env.DB_USER || 'postgres',
|
||||
password: process.env.DB_PASSWORD || 'postgres',
|
||||
database: process.env.DB_NAME || 'cryptowallet_v2',
|
||||
database: process.env.DB_NAME || 'cryptowallet',
|
||||
},
|
||||
migrations: {
|
||||
directory: path.resolve(__dirname, 'migrations'),
|
||||
|
||||
@@ -3,21 +3,12 @@ import type { Knex } from 'knex';
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
await knex.schema.createTable('users', (t) => {
|
||||
t.string('id', 26).primary();
|
||||
t.string('email', 255).notNullable().unique();
|
||||
t.string('password_hash', 255).notNullable();
|
||||
t.string('last_name', 128).nullable();
|
||||
t.string('first_name', 128).nullable();
|
||||
t.string('middle_name', 128).nullable();
|
||||
t.date('birth_date').nullable();
|
||||
t.string('crypto_wallet', 255).nullable();
|
||||
t.string('phone', 16).nullable();
|
||||
t.string('bik', 9).nullable();
|
||||
t.string('account_number', 20).nullable();
|
||||
t.string('card_number', 19).nullable();
|
||||
t.string('inn', 12).nullable();
|
||||
t.boolean('kyc_verified').notNullable().defaultTo(false);
|
||||
t.timestamp('kyc_verified_at', { useTz: true }).nullable();
|
||||
t.boolean('is_deleted').notNullable().defaultTo(false);
|
||||
t.string('username', 64).notNullable().unique();
|
||||
t.text('password_hash').notNullable();
|
||||
t.text('pin_hash').notNullable();
|
||||
t.text('encrypted_vault').notNullable();
|
||||
t.string('vault_salt', 128).notNullable();
|
||||
t.boolean('mnemonic_shown').notNullable().defaultTo(false);
|
||||
t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(knex.fn.now());
|
||||
t.timestamp('updated_at', { useTz: true }).notNullable().defaultTo(knex.fn.now());
|
||||
});
|
||||
|
||||
@@ -3,22 +3,16 @@ import type { Knex } from 'knex';
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
await knex.schema.createTable('sessions', (t) => {
|
||||
t.string('id', 26).primary();
|
||||
t.string('sid', 26).notNullable().unique();
|
||||
t.string('user_id', 26).notNullable().references('id').inTable('users').onDelete('CASCADE');
|
||||
t.string('device_id', 26).nullable();
|
||||
t.string('user_agent', 500).nullable();
|
||||
t.string('first_ip', 64).nullable();
|
||||
t.string('last_ip', 64).nullable();
|
||||
t.timestamp('last_seen_at', { useTz: true }).nullable();
|
||||
t.timestamp('revoked_at', { useTz: true }).nullable();
|
||||
t.string('refresh_jti_hash', 255).nullable();
|
||||
t.timestamp('refresh_expires_at', { useTz: true }).nullable();
|
||||
t.text('refresh_token_hash').notNullable();
|
||||
t.string('user_agent').nullable();
|
||||
t.specificType('ip_address', 'inet').nullable();
|
||||
t.timestamp('expires_at', { useTz: true }).notNullable();
|
||||
t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(knex.fn.now());
|
||||
t.timestamp('updated_at', { useTz: true }).notNullable().defaultTo(knex.fn.now());
|
||||
});
|
||||
|
||||
await knex.schema.raw('CREATE INDEX idx_sessions_user_id ON sessions(user_id)');
|
||||
await knex.schema.raw('CREATE INDEX idx_sessions_sid ON sessions(sid)');
|
||||
await knex.schema.raw('CREATE INDEX idx_sessions_expires ON sessions(expires_at)');
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
|
||||
18
apps/api/src/db/migrations/004_create_login_attempts.ts
Normal file
18
apps/api/src/db/migrations/004_create_login_attempts.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import type { Knex } from 'knex';
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
await knex.schema.createTable('login_attempts', (t) => {
|
||||
t.string('id', 26).primary();
|
||||
t.string('username', 64).notNullable();
|
||||
t.specificType('ip_address', 'inet').notNullable();
|
||||
t.boolean('success').notNullable().defaultTo(false);
|
||||
t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(knex.fn.now());
|
||||
});
|
||||
|
||||
await knex.schema.raw('CREATE INDEX idx_login_attempts_username_created ON login_attempts(username, created_at)');
|
||||
await knex.schema.raw('CREATE INDEX idx_login_attempts_ip_created ON login_attempts(ip_address, created_at)');
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
await knex.schema.dropTableIfExists('login_attempts');
|
||||
}
|
||||
33
apps/api/src/db/migrations/005_simplify_users_for_bitok.ts
Normal file
33
apps/api/src/db/migrations/005_simplify_users_for_bitok.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import type { Knex } from 'knex';
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
await knex.schema.alterTable('users', (t) => {
|
||||
t.dropColumn('username');
|
||||
t.dropColumn('password_hash');
|
||||
t.dropColumn('pin_hash');
|
||||
|
||||
t.string('bitok_user_id', 26).notNullable().unique();
|
||||
t.string('email', 255).nullable();
|
||||
t.boolean('kyc_verified').notNullable().defaultTo(false);
|
||||
t.string('kyc_level', 20).nullable();
|
||||
t.boolean('deleted').notNullable().defaultTo(false);
|
||||
|
||||
t.index(['bitok_user_id'], 'idx_users_bitok_user_id');
|
||||
});
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
await knex.schema.alterTable('users', (t) => {
|
||||
t.dropIndex(['bitok_user_id'], 'idx_users_bitok_user_id');
|
||||
|
||||
t.dropColumn('bitok_user_id');
|
||||
t.dropColumn('email');
|
||||
t.dropColumn('kyc_verified');
|
||||
t.dropColumn('kyc_level');
|
||||
t.dropColumn('deleted');
|
||||
|
||||
t.string('username', 64).notNullable().unique();
|
||||
t.text('password_hash').notNullable();
|
||||
t.text('pin_hash').notNullable();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { Knex } from 'knex';
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
await knex.schema.dropTableIfExists('sessions');
|
||||
await knex.schema.dropTableIfExists('login_attempts');
|
||||
|
||||
await knex.schema.createTable('processed_events', (t) => {
|
||||
t.string('event_id', 26).primary();
|
||||
t.string('event_type', 64).notNullable();
|
||||
t.string('payload_hash', 64).notNullable();
|
||||
t.timestamp('processed_at', { useTz: true }).notNullable().defaultTo(knex.fn.now());
|
||||
});
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
await knex.schema.dropTableIfExists('processed_events');
|
||||
|
||||
await knex.schema.createTable('sessions', (t) => {
|
||||
t.string('id', 26).primary();
|
||||
t.string('user_id', 26).notNullable().references('id').inTable('users').onDelete('CASCADE');
|
||||
t.text('refresh_token_hash').notNullable();
|
||||
t.string('user_agent').nullable();
|
||||
t.specificType('ip_address', 'inet').nullable();
|
||||
t.timestamp('expires_at', { useTz: true }).notNullable();
|
||||
t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(knex.fn.now());
|
||||
});
|
||||
|
||||
await knex.schema.createTable('login_attempts', (t) => {
|
||||
t.string('id', 26).primary();
|
||||
t.string('username', 64).notNullable();
|
||||
t.specificType('ip_address', 'inet').notNullable();
|
||||
t.boolean('success').notNullable().defaultTo(false);
|
||||
t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(knex.fn.now());
|
||||
});
|
||||
}
|
||||
49
apps/api/src/db/reset-db.ts
Normal file
49
apps/api/src/db/reset-db.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import dotenv from 'dotenv';
|
||||
import path from 'path';
|
||||
import knex from 'knex';
|
||||
|
||||
// Load .env from repo root (works when running from apps/api)
|
||||
dotenv.config({ path: path.resolve(__dirname, '../../../../.env') });
|
||||
dotenv.config({ path: path.resolve(process.cwd(), '.env') });
|
||||
|
||||
const dbName = process.env.DB_NAME || 'cryptowallet_devphase3';
|
||||
if (!/^[a-zA-Z0-9_]+$/.test(dbName)) {
|
||||
console.error('[DB Reset] Invalid DB_NAME');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const baseConnection = {
|
||||
host: process.env.DB_HOST || 'localhost',
|
||||
port: parseInt(process.env.DB_PORT || '5432'),
|
||||
user: process.env.DB_USER || 'postgres',
|
||||
password: process.env.DB_PASSWORD || 'postgres',
|
||||
};
|
||||
|
||||
async function reset() {
|
||||
const admin = knex({
|
||||
client: 'pg',
|
||||
connection: { ...baseConnection, database: 'postgres' },
|
||||
});
|
||||
|
||||
try {
|
||||
await admin.raw(
|
||||
`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = ? AND pid <> pg_backend_pid()`,
|
||||
[dbName]
|
||||
);
|
||||
} catch {
|
||||
// Ignore if no connections
|
||||
}
|
||||
|
||||
const safeName = dbName.replace(/"/g, '""');
|
||||
await admin.raw(`DROP DATABASE IF EXISTS "${safeName}"`);
|
||||
await admin.raw(`CREATE DATABASE "${safeName}"`);
|
||||
|
||||
await admin.destroy();
|
||||
console.log('[DB Reset] Database dropped and recreated:', dbName);
|
||||
}
|
||||
|
||||
reset().catch((err: unknown) => {
|
||||
console.error('[DB Reset] Failed:', err instanceof Error ? err.message : String(err));
|
||||
if (err instanceof Error && err.stack) console.error(err.stack);
|
||||
process.exit(1);
|
||||
});
|
||||
59
apps/api/src/events/connection.ts
Normal file
59
apps/api/src/events/connection.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import amqplib, { type Channel, type ChannelModel } from 'amqplib';
|
||||
import { env } from '../config/env';
|
||||
|
||||
let connectionModel: ChannelModel | null = null;
|
||||
let channel: Channel | null = null;
|
||||
|
||||
const DLX_EXCHANGE = `${env.rabbitmqExchange}.dlx`;
|
||||
const DLQ_NAME = `${env.rabbitmqWalletQueue}.dlq`;
|
||||
|
||||
export async function createRabbitConnection(): Promise<Channel> {
|
||||
connectionModel = await amqplib.connect(env.rabbitmqUrl);
|
||||
|
||||
connectionModel.on('error', (err) => {
|
||||
console.error('[RabbitMQ] Connection error:', err.message);
|
||||
});
|
||||
|
||||
connectionModel.on('close', () => {
|
||||
console.warn('[RabbitMQ] Connection closed. Reconnecting in 5s...');
|
||||
setTimeout(() => createRabbitConnection().catch(console.error), 5000);
|
||||
});
|
||||
|
||||
channel = await connectionModel.createChannel();
|
||||
await channel.prefetch(1);
|
||||
|
||||
// Declare main exchange
|
||||
await channel.assertExchange(env.rabbitmqExchange, 'topic', { durable: true });
|
||||
|
||||
// Declare DLX and DLQ
|
||||
await channel.assertExchange(DLX_EXCHANGE, 'topic', { durable: true });
|
||||
await channel.assertQueue(DLQ_NAME, { durable: true });
|
||||
await channel.bindQueue(DLQ_NAME, DLX_EXCHANGE, '#');
|
||||
|
||||
// Declare main queue with DLX
|
||||
await channel.assertQueue(env.rabbitmqWalletQueue, {
|
||||
durable: true,
|
||||
arguments: {
|
||||
'x-dead-letter-exchange': DLX_EXCHANGE,
|
||||
},
|
||||
});
|
||||
|
||||
// Bind routing keys
|
||||
await channel.bindQueue(env.rabbitmqWalletQueue, env.rabbitmqExchange, 'user.kyc_verified');
|
||||
await channel.bindQueue(env.rabbitmqWalletQueue, env.rabbitmqExchange, 'user.deleted');
|
||||
|
||||
console.log('[RabbitMQ] Connected and queues declared');
|
||||
|
||||
return channel;
|
||||
}
|
||||
|
||||
export async function closeRabbitConnection(): Promise<void> {
|
||||
try {
|
||||
if (channel) await channel.close();
|
||||
if (connectionModel) await connectionModel.close();
|
||||
} catch {
|
||||
// ignore close errors
|
||||
}
|
||||
channel = null;
|
||||
connectionModel = null;
|
||||
}
|
||||
121
apps/api/src/events/consumer.ts
Normal file
121
apps/api/src/events/consumer.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
import type { Channel, ConsumeMessage } from 'amqplib';
|
||||
import crypto from 'crypto';
|
||||
import { db } from '../config/database';
|
||||
import { env } from '../config/env';
|
||||
import { handleKycVerified } from './handlers/kyc-verified.handler';
|
||||
import { handleUserDeleted } from './handlers/deleted.handler';
|
||||
|
||||
const MAX_RETRIES = 3;
|
||||
|
||||
interface BitokEvent {
|
||||
event_id: string;
|
||||
event_type: string;
|
||||
payload: Record<string, unknown>;
|
||||
occurred_at: string;
|
||||
schema_version: number;
|
||||
}
|
||||
|
||||
function isValidEvent(msg: unknown): msg is BitokEvent {
|
||||
if (!msg || typeof msg !== 'object') return false;
|
||||
const e = msg as Record<string, unknown>;
|
||||
return (
|
||||
typeof e.event_id === 'string' &&
|
||||
typeof e.event_type === 'string' &&
|
||||
typeof e.payload === 'object' &&
|
||||
e.payload !== null &&
|
||||
typeof e.occurred_at === 'string'
|
||||
);
|
||||
}
|
||||
|
||||
function getRetryCount(msg: ConsumeMessage): number {
|
||||
const xDeath = msg.properties.headers?.['x-death'] as Array<{ count: number }> | undefined;
|
||||
if (!xDeath || xDeath.length === 0) return 0;
|
||||
return xDeath[0].count ?? 0;
|
||||
}
|
||||
|
||||
function hashPayload(payload: Record<string, unknown>): string {
|
||||
return crypto.createHash('sha256').update(JSON.stringify(payload)).digest('hex');
|
||||
}
|
||||
|
||||
async function isAlreadyProcessed(eventId: string): Promise<boolean> {
|
||||
const row = await db('processed_events').where({ event_id: eventId }).first();
|
||||
return !!row;
|
||||
}
|
||||
|
||||
async function markProcessed(eventId: string, eventType: string, payloadHash: string): Promise<void> {
|
||||
await db('processed_events').insert({
|
||||
event_id: eventId,
|
||||
event_type: eventType,
|
||||
payload_hash: payloadHash,
|
||||
});
|
||||
}
|
||||
|
||||
export async function startConsumer(channel: Channel): Promise<void> {
|
||||
console.log('[Consumer] Listening on queue:', env.rabbitmqWalletQueue);
|
||||
|
||||
await channel.consume(env.rabbitmqWalletQueue, async (msg) => {
|
||||
if (!msg) return;
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(msg.content.toString());
|
||||
} catch {
|
||||
console.error('[Consumer] Invalid JSON, nacking without requeue');
|
||||
channel.nack(msg, false, false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isValidEvent(parsed)) {
|
||||
console.error('[Consumer] Schema validation failed, nacking without requeue');
|
||||
channel.nack(msg, false, false);
|
||||
return;
|
||||
}
|
||||
|
||||
const event = parsed;
|
||||
|
||||
// Idempotency check
|
||||
try {
|
||||
if (await isAlreadyProcessed(event.event_id)) {
|
||||
console.log(`[Consumer] Event ${event.event_id} already processed, acking`);
|
||||
channel.ack(msg);
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[Consumer] DB error checking idempotency, nacking with requeue');
|
||||
channel.nack(msg, false, true);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check retry count
|
||||
const retries = getRetryCount(msg);
|
||||
if (retries >= MAX_RETRIES) {
|
||||
console.error(`[Consumer] Event ${event.event_id} exceeded max retries (${MAX_RETRIES}), sending to DLQ`);
|
||||
channel.nack(msg, false, false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
switch (event.event_type) {
|
||||
case 'user.kyc_verified':
|
||||
await handleKycVerified(event.payload);
|
||||
break;
|
||||
case 'user.deleted':
|
||||
await handleUserDeleted(event.payload);
|
||||
break;
|
||||
default:
|
||||
console.warn(`[Consumer] Unknown event type: ${event.event_type}, acking`);
|
||||
channel.ack(msg);
|
||||
return;
|
||||
}
|
||||
|
||||
const payloadHash = hashPayload(event.payload);
|
||||
await markProcessed(event.event_id, event.event_type, payloadHash);
|
||||
channel.ack(msg);
|
||||
console.log(`[Consumer] Processed event: ${event.event_id} (${event.event_type})`);
|
||||
} catch (err: any) {
|
||||
console.error(`[Consumer] Handler error for ${event.event_id}:`, err.message);
|
||||
// DB/handler error -- requeue for retry
|
||||
channel.nack(msg, false, true);
|
||||
}
|
||||
});
|
||||
}
|
||||
17
apps/api/src/events/handlers/deleted.handler.ts
Normal file
17
apps/api/src/events/handlers/deleted.handler.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { UserModel } from '../../models/user.model';
|
||||
|
||||
interface UserDeletedPayload {
|
||||
bitok_user_id: string;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export async function handleUserDeleted(payload: Record<string, unknown>): Promise<void> {
|
||||
const data = payload as unknown as UserDeletedPayload;
|
||||
|
||||
if (!data.bitok_user_id) {
|
||||
throw new Error('Invalid user.deleted payload: missing bitok_user_id');
|
||||
}
|
||||
|
||||
await UserModel.softDelete(data.bitok_user_id);
|
||||
console.log(`[UserDeleted] Soft-deleted user ${data.bitok_user_id} reason=${data.reason}`);
|
||||
}
|
||||
18
apps/api/src/events/handlers/kyc-verified.handler.ts
Normal file
18
apps/api/src/events/handlers/kyc-verified.handler.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { UserModel } from '../../models/user.model';
|
||||
|
||||
interface KycVerifiedPayload {
|
||||
bitok_user_id: string;
|
||||
kyc_verified: boolean;
|
||||
kyc_level: string;
|
||||
}
|
||||
|
||||
export async function handleKycVerified(payload: Record<string, unknown>): Promise<void> {
|
||||
const data = payload as unknown as KycVerifiedPayload;
|
||||
|
||||
if (!data.bitok_user_id || typeof data.kyc_verified !== 'boolean') {
|
||||
throw new Error('Invalid kyc_verified payload');
|
||||
}
|
||||
|
||||
await UserModel.updateKyc(data.bitok_user_id, data.kyc_verified, data.kyc_level || null);
|
||||
console.log(`[KYC] Updated KYC for user ${data.bitok_user_id}: verified=${data.kyc_verified}, level=${data.kyc_level}`);
|
||||
}
|
||||
@@ -1,23 +1,23 @@
|
||||
import knex from 'knex';
|
||||
import knexConfig from './db/knexfile';
|
||||
import app from './app';
|
||||
import { env } from './config/env';
|
||||
import { env, initEnv } from './config/env';
|
||||
import { createRabbitConnection } from './events/connection';
|
||||
import { startConsumer } from './events/consumer';
|
||||
|
||||
async function main() {
|
||||
const db = knex(knexConfig);
|
||||
await initEnv();
|
||||
|
||||
console.log('[API] Running migrations...');
|
||||
await db.migrate.latest();
|
||||
console.log('[API] Migrations complete.');
|
||||
|
||||
await db.destroy();
|
||||
// Start RabbitMQ consumer
|
||||
try {
|
||||
const channel = await createRabbitConnection();
|
||||
await startConsumer(channel);
|
||||
console.log('[API] RabbitMQ consumer started');
|
||||
} catch (err: any) {
|
||||
console.warn('[API] RabbitMQ not available, events will not be consumed:', err.message);
|
||||
}
|
||||
|
||||
app.listen(env.port, () => {
|
||||
console.log(`[API] Server running on port ${env.port}`);
|
||||
});
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[API] Failed to start:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
main().catch(console.error);
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { verifyAccessToken, AuthContext } from '../services/jwt.service';
|
||||
|
||||
declare global {
|
||||
namespace Express {
|
||||
interface Request {
|
||||
auth?: AuthContext;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function extractToken(req: Request): string | null {
|
||||
const cookie = req.cookies?.access_token;
|
||||
if (cookie) return cookie;
|
||||
|
||||
const auth = req.headers.authorization;
|
||||
if (auth) {
|
||||
const [scheme, token] = auth.split(' ');
|
||||
if (scheme?.toLowerCase() === 'bearer' && token) return token;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function authMiddleware(req: Request, res: Response, next: NextFunction): Promise<void> {
|
||||
const token = extractToken(req);
|
||||
|
||||
if (!token) {
|
||||
res.status(401).json({ success: false, error: 'Not authenticated' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
req.auth = await verifyAccessToken(token);
|
||||
next();
|
||||
} catch (err: any) {
|
||||
res.status(err.status || 401).json({ success: false, error: err.message || 'Invalid token' });
|
||||
}
|
||||
}
|
||||
60
apps/api/src/middleware/bitok-auth.ts
Normal file
60
apps/api/src/middleware/bitok-auth.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { jwtVerify, decodeProtectedHeader } from 'jose';
|
||||
import { getSigningKey } from '../services/jwks.service';
|
||||
import { env } from '../config/env';
|
||||
|
||||
declare global {
|
||||
namespace Express {
|
||||
interface Request {
|
||||
user?: { bitokUserId: string; email?: string };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function bitokAuth(req: Request, res: Response, next: NextFunction): Promise<void> {
|
||||
const header = req.headers.authorization;
|
||||
if (!header?.startsWith('Bearer ')) {
|
||||
res.status(401).json({ success: false, error: 'No token provided' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const token = header.slice(7);
|
||||
|
||||
// Decode header to get kid
|
||||
const protectedHeader = decodeProtectedHeader(token);
|
||||
if (protectedHeader.alg !== 'RS256') {
|
||||
res.status(401).json({ success: false, error: 'Invalid token algorithm' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!protectedHeader.kid) {
|
||||
res.status(401).json({ success: false, error: 'Token missing kid' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the signing key for this kid
|
||||
const key = await getSigningKey(protectedHeader.kid);
|
||||
|
||||
// Verify the token
|
||||
const { payload } = await jwtVerify(token, key, {
|
||||
issuer: env.bitokIssuer,
|
||||
audience: env.bitokAudience,
|
||||
algorithms: ['RS256'],
|
||||
});
|
||||
|
||||
if (!payload.sub) {
|
||||
res.status(401).json({ success: false, error: 'Token missing subject' });
|
||||
return;
|
||||
}
|
||||
|
||||
req.user = {
|
||||
bitokUserId: payload.sub,
|
||||
email: payload.email as string | undefined,
|
||||
};
|
||||
|
||||
next();
|
||||
} catch {
|
||||
res.status(401).json({ success: false, error: 'Invalid or expired token' });
|
||||
}
|
||||
}
|
||||
25
apps/api/src/middleware/rate-limit.ts
Normal file
25
apps/api/src/middleware/rate-limit.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import rateLimit from 'express-rate-limit';
|
||||
|
||||
export const loginLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000,
|
||||
max: 20,
|
||||
message: { success: false, error: 'Too many login attempts, try again later' },
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
});
|
||||
|
||||
export const registerLimiter = rateLimit({
|
||||
windowMs: 60 * 60 * 1000,
|
||||
max: 3,
|
||||
message: { success: false, error: 'Too many registration attempts, try again later' },
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
});
|
||||
|
||||
export const seedPhraseLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000,
|
||||
max: 3,
|
||||
message: { success: false, error: 'Too many attempts. Try again in 15 minutes.' },
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
});
|
||||
@@ -1,66 +0,0 @@
|
||||
import { db } from '../config/database';
|
||||
import { generateUlid } from '../utils/ulid';
|
||||
|
||||
export interface SessionRow {
|
||||
id: string;
|
||||
sid: string;
|
||||
user_id: string;
|
||||
device_id: string | null;
|
||||
user_agent: string | null;
|
||||
first_ip: string | null;
|
||||
last_ip: string | null;
|
||||
last_seen_at: Date | null;
|
||||
revoked_at: Date | null;
|
||||
refresh_jti_hash: string | null;
|
||||
refresh_expires_at: Date | null;
|
||||
created_at: Date;
|
||||
updated_at: Date;
|
||||
}
|
||||
|
||||
export const SessionModel = {
|
||||
async findBySid(sid: string): Promise<SessionRow | undefined> {
|
||||
return db('sessions').where({ sid }).whereNull('revoked_at').first();
|
||||
},
|
||||
|
||||
async findByUserId(userId: string): Promise<SessionRow[]> {
|
||||
return db('sessions').where({ user_id: userId }).whereNull('revoked_at');
|
||||
},
|
||||
|
||||
async create(data: {
|
||||
sid: string;
|
||||
user_id: string;
|
||||
device_id?: string;
|
||||
user_agent?: string;
|
||||
first_ip?: string;
|
||||
refresh_jti_hash?: string;
|
||||
refresh_expires_at?: Date;
|
||||
}): Promise<SessionRow> {
|
||||
const [session] = await db('sessions')
|
||||
.insert({
|
||||
id: generateUlid(),
|
||||
...data,
|
||||
last_ip: data.first_ip || null,
|
||||
})
|
||||
.returning('*');
|
||||
return session;
|
||||
},
|
||||
|
||||
async revoke(sid: string): Promise<void> {
|
||||
await db('sessions')
|
||||
.where({ sid })
|
||||
.update({ revoked_at: db.fn.now(), updated_at: db.fn.now() });
|
||||
},
|
||||
|
||||
async revokeAllForUser(userId: string): Promise<void> {
|
||||
await db('sessions')
|
||||
.where({ user_id: userId })
|
||||
.whereNull('revoked_at')
|
||||
.update({ revoked_at: db.fn.now(), updated_at: db.fn.now() });
|
||||
},
|
||||
|
||||
async updateLastSeen(sid: string, ip: string): Promise<void> {
|
||||
await db('sessions')
|
||||
.where({ sid })
|
||||
.update({ last_seen_at: db.fn.now(), last_ip: ip, updated_at: db.fn.now() });
|
||||
},
|
||||
};
|
||||
@@ -3,47 +3,71 @@ import { generateUlid } from '../utils/ulid';
|
||||
|
||||
export interface UserRow {
|
||||
id: string;
|
||||
email: string;
|
||||
password_hash: string;
|
||||
last_name: string | null;
|
||||
first_name: string | null;
|
||||
middle_name: string | null;
|
||||
birth_date: string | null;
|
||||
crypto_wallet: string | null;
|
||||
phone: string | null;
|
||||
bik: string | null;
|
||||
account_number: string | null;
|
||||
card_number: string | null;
|
||||
inn: string | null;
|
||||
bitok_user_id: string;
|
||||
email: string | null;
|
||||
encrypted_vault: string;
|
||||
vault_salt: string;
|
||||
mnemonic_shown: boolean;
|
||||
kyc_verified: boolean;
|
||||
kyc_verified_at: Date | null;
|
||||
is_deleted: boolean;
|
||||
kyc_level: string | null;
|
||||
deleted: boolean;
|
||||
created_at: Date;
|
||||
updated_at: Date;
|
||||
}
|
||||
|
||||
export const UserModel = {
|
||||
async findByEmail(email: string): Promise<UserRow | undefined> {
|
||||
return db('users').where({ email, is_deleted: false }).first();
|
||||
},
|
||||
|
||||
async findById(id: string): Promise<UserRow | undefined> {
|
||||
return db('users').where({ id, is_deleted: false }).first();
|
||||
return db('users').where({ id }).first();
|
||||
},
|
||||
|
||||
async create(data: {
|
||||
email: string;
|
||||
password_hash: string;
|
||||
async findByBitokUserId(bitokUserId: string): Promise<UserRow | undefined> {
|
||||
return db('users').where({ bitok_user_id: bitokUserId }).first();
|
||||
},
|
||||
|
||||
async createFromBitok(data: {
|
||||
bitokUserId: string;
|
||||
email?: string | null;
|
||||
encryptedVault: string;
|
||||
vaultSalt: string;
|
||||
}): Promise<UserRow> {
|
||||
const [user] = await db('users').insert({ id: generateUlid(), ...data }).returning('*');
|
||||
return user;
|
||||
},
|
||||
|
||||
async update(id: string, data: Partial<Omit<UserRow, 'id' | 'created_at'>>): Promise<UserRow | undefined> {
|
||||
const [user] = await db('users')
|
||||
.where({ id })
|
||||
.update({ ...data, updated_at: db.fn.now() })
|
||||
.insert({
|
||||
id: generateUlid(),
|
||||
bitok_user_id: data.bitokUserId,
|
||||
email: data.email || null,
|
||||
encrypted_vault: data.encryptedVault,
|
||||
vault_salt: data.vaultSalt,
|
||||
})
|
||||
.returning('*');
|
||||
return user;
|
||||
},
|
||||
|
||||
async setMnemonicShown(id: string): Promise<void> {
|
||||
await db('users').where({ id }).update({ mnemonic_shown: true, updated_at: db.fn.now() });
|
||||
},
|
||||
|
||||
async updateVault(id: string, encrypted_vault: string, vault_salt: string): Promise<void> {
|
||||
await db('users')
|
||||
.where({ id })
|
||||
.update({ encrypted_vault, vault_salt, updated_at: db.fn.now() });
|
||||
},
|
||||
|
||||
async updateKyc(bitokUserId: string, kycVerified: boolean, kycLevel: string | null): Promise<void> {
|
||||
await db('users')
|
||||
.where({ bitok_user_id: bitokUserId })
|
||||
.update({
|
||||
kyc_verified: kycVerified,
|
||||
kyc_level: kycLevel,
|
||||
updated_at: db.fn.now(),
|
||||
});
|
||||
},
|
||||
|
||||
async softDelete(bitokUserId: string): Promise<void> {
|
||||
await db('users')
|
||||
.where({ bitok_user_id: bitokUserId })
|
||||
.update({
|
||||
deleted: true,
|
||||
updated_at: db.fn.now(),
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
9
apps/api/src/routes/vault.routes.ts
Normal file
9
apps/api/src/routes/vault.routes.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Router } from 'express';
|
||||
import { VaultController } from '../controllers/vault.controller';
|
||||
import { bitokAuth } from '../middleware/bitok-auth';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.get('/', bitokAuth, VaultController.getVault);
|
||||
|
||||
export default router;
|
||||
25
apps/api/src/routes/wallet-setup.routes.ts
Normal file
25
apps/api/src/routes/wallet-setup.routes.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { Router } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { WalletSetupController } from '../controllers/wallet-setup.controller';
|
||||
import { validate } from '../middleware/validate';
|
||||
import { bitokAuth } from '../middleware/bitok-auth';
|
||||
|
||||
const setupSchema = z.object({
|
||||
encryptedVault: z.string().min(1),
|
||||
vaultSalt: z.string().min(1),
|
||||
wallets: z.array(
|
||||
z.object({
|
||||
chain: z.enum(['ETH', 'BTC', 'SOL', 'TRX', 'BSC']),
|
||||
address: z.string().min(1),
|
||||
derivationPath: z.string().min(1),
|
||||
})
|
||||
).min(4).max(5),
|
||||
});
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.post('/setup', bitokAuth, validate(setupSchema), WalletSetupController.setup);
|
||||
router.get('/unlock', bitokAuth, WalletSetupController.unlock);
|
||||
router.post('/confirm-mnemonic', bitokAuth, WalletSetupController.confirmMnemonic);
|
||||
|
||||
export default router;
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Router } from 'express';
|
||||
import { WalletController } from '../controllers/wallet.controller';
|
||||
import { authMiddleware } from '../middleware/auth';
|
||||
import { bitokAuth } from '../middleware/bitok-auth';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.get('/', authMiddleware, WalletController.getWallets);
|
||||
router.get('/', bitokAuth, WalletController.getWallets);
|
||||
|
||||
export default router;
|
||||
|
||||
46
apps/api/src/services/jwks.service.ts
Normal file
46
apps/api/src/services/jwks.service.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { importJWK, type JWK, type CryptoKey } from 'jose';
|
||||
import { env } from '../config/env';
|
||||
|
||||
interface CachedKey {
|
||||
key: CryptoKey | Uint8Array;
|
||||
fetchedAt: number;
|
||||
}
|
||||
|
||||
const KEY_TTL_MS = 60 * 60 * 1000; // 1 hour
|
||||
const keyCache = new Map<string, CachedKey>();
|
||||
|
||||
async function fetchJwks(): Promise<{ keys: JWK[] }> {
|
||||
const res = await fetch(env.bitokJwksUrl);
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to fetch JWKS: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
return res.json() as Promise<{ keys: JWK[] }>;
|
||||
}
|
||||
|
||||
async function refreshKeys(): Promise<void> {
|
||||
const jwks = await fetchJwks();
|
||||
|
||||
for (const jwk of jwks.keys) {
|
||||
if (!jwk.kid) continue;
|
||||
const key = await importJWK(jwk, 'RS256');
|
||||
keyCache.set(jwk.kid, { key, fetchedAt: Date.now() });
|
||||
}
|
||||
}
|
||||
|
||||
export async function getSigningKey(kid: string): Promise<CryptoKey | Uint8Array> {
|
||||
const cached = keyCache.get(kid);
|
||||
|
||||
if (cached && Date.now() - cached.fetchedAt < KEY_TTL_MS) {
|
||||
return cached.key;
|
||||
}
|
||||
|
||||
// Unknown kid or expired -- force refresh
|
||||
await refreshKeys();
|
||||
|
||||
const refreshed = keyCache.get(kid);
|
||||
if (!refreshed) {
|
||||
throw new Error(`No key found for kid: ${kid}`);
|
||||
}
|
||||
|
||||
return refreshed.key;
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
import * as jose from 'jose';
|
||||
import { env } from '../config/env';
|
||||
|
||||
export interface AccessTokenPayload {
|
||||
sub: string;
|
||||
type: string;
|
||||
sid: string;
|
||||
iat: number;
|
||||
nbf: number;
|
||||
exp: number;
|
||||
iss?: string;
|
||||
aud?: string;
|
||||
}
|
||||
|
||||
export interface AuthContext {
|
||||
userId: string;
|
||||
sid: string;
|
||||
token: AccessTokenPayload;
|
||||
}
|
||||
|
||||
let jwks: ReturnType<typeof jose.createRemoteJWKSet> | null = null;
|
||||
let localKey: Awaited<ReturnType<typeof jose.importSPKI>> | null = null;
|
||||
|
||||
function getJWKS(): ReturnType<typeof jose.createRemoteJWKSet> {
|
||||
if (!jwks && env.jwt.jwksUrl) {
|
||||
jwks = jose.createRemoteJWKSet(new URL(env.jwt.jwksUrl));
|
||||
}
|
||||
if (!jwks) {
|
||||
throw new Error('JWT_JWKS_URL is not configured');
|
||||
}
|
||||
return jwks;
|
||||
}
|
||||
|
||||
async function getLocalKey(): Promise<Awaited<ReturnType<typeof jose.importSPKI>>> {
|
||||
if (!localKey && env.jwt.publicKey) {
|
||||
localKey = await jose.importSPKI(env.jwt.publicKey, env.jwt.algorithm);
|
||||
}
|
||||
if (!localKey) {
|
||||
throw new Error('No JWT public key available');
|
||||
}
|
||||
return localKey;
|
||||
}
|
||||
|
||||
export async function verifyAccessToken(token: string): Promise<AuthContext> {
|
||||
let payload: jose.JWTPayload;
|
||||
|
||||
try {
|
||||
const verifyOptions: jose.JWTVerifyOptions = {
|
||||
algorithms: [env.jwt.algorithm],
|
||||
clockTolerance: 10,
|
||||
};
|
||||
if (env.jwt.issuer) verifyOptions.issuer = env.jwt.issuer;
|
||||
if (env.jwt.audience) verifyOptions.audience = env.jwt.audience;
|
||||
|
||||
if (env.jwt.jwksUrl) {
|
||||
const result = await jose.jwtVerify(token, getJWKS(), verifyOptions);
|
||||
payload = result.payload;
|
||||
} else {
|
||||
const key = await getLocalKey();
|
||||
const result = await jose.jwtVerify(token, key, verifyOptions);
|
||||
payload = result.payload;
|
||||
}
|
||||
} catch (err: any) {
|
||||
if (err.code === 'ERR_JWT_EXPIRED') {
|
||||
throw Object.assign(new Error('Token expired'), { status: 401 });
|
||||
}
|
||||
throw Object.assign(new Error('Invalid token'), { status: 401 });
|
||||
}
|
||||
|
||||
if (payload.type !== 'access') {
|
||||
throw Object.assign(new Error('Invalid token type'), { status: 401 });
|
||||
}
|
||||
|
||||
if (!payload.sub || !payload.sid) {
|
||||
throw Object.assign(new Error('Missing token claims'), { status: 401 });
|
||||
}
|
||||
|
||||
return {
|
||||
userId: payload.sub,
|
||||
sid: payload.sid as string,
|
||||
token: {
|
||||
sub: payload.sub,
|
||||
type: payload.type as string,
|
||||
sid: payload.sid as string,
|
||||
iat: payload.iat!,
|
||||
nbf: payload.nbf!,
|
||||
exp: payload.exp!,
|
||||
iss: payload.iss,
|
||||
aud: typeof payload.aud === 'string' ? payload.aud : undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user