feat: add admin user management and disable public registration
This commit is contained in:
1 parent
cfbba73791
commit
312a5ccb86
32 files changed
+1120
-69
No files matched your search
@@ -6,6 +6,11 @@
|
||||
# 未明确设置的网络开关会按环境采用默认值;本示例明确设置的开关优先。
|
||||
NODE_ENV=development
|
||||
|
||||
# 仅在数据库没有管理员时初始化;不覆盖同名已有用户、不重置已有管理员密码。
|
||||
# 初次登录必须更换密码;新密码至少 10 个字符、最多 72 字节。
|
||||
ADMIN_USERNAME=admin
|
||||
ADMIN_PASSWORD=admin
|
||||
|
||||
# MySQL 连接字符串:替换用户名、密码、主机、端口及数据库名。
|
||||
# 密码中的特殊字符需要进行 URL 编码。
|
||||
DATABASE_URL="mysql://USER:PASSWORD@HOST:3306/worthpath"
|
||||
@@ -80,7 +85,7 @@ COOKIE_SAME_SITE=strict
|
||||
NETWORK_RATE_LIMIT_ENABLED=true
|
||||
# 同一来源累计请求的时间窗口,单位毫秒;900000 为 15 分钟。
|
||||
NETWORK_RATE_LIMIT_WINDOW_MS=900000
|
||||
# 每个来源在窗口内可尝试的登录、注册或安全操作次数;上线可按需收紧。
|
||||
# 每个来源在窗口内可尝试的登录或安全操作次数;上线可按需收紧。
|
||||
NETWORK_AUTH_RATE_LIMIT_MAX=30
|
||||
# 每个来源在窗口内访问单个 OAuth 授权、令牌、撤销或注册端点的次数。
|
||||
MCP_AUTH_RATE_LIMIT_MAX=100
|
||||
@@ -10,6 +10,7 @@
|
||||
"db:migrate": "node scripts/database.cjs deploy",
|
||||
"db:status": "node scripts/database.cjs status",
|
||||
"test:integration": "tsx --test --test-concurrency=1 test/integration.test.ts test/privacy.test.ts test/icons.test.ts test/transfers.test.ts test/queries.test.ts test/debts.test.ts test/update-integration.test.ts test/record-edit.test.ts test/security-backup.test.ts test/credit-balance.test.ts test/group-order.test.ts test/settings-plans.test.ts test/inclusion-metals.test.ts test/account-deletion-integration.test.ts test/quick-entry-integration.test.ts",
|
||||
"test:isolated": "node scripts/test-isolated.cjs",
|
||||
"test:performance": "tsx scripts/performance.ts after",
|
||||
"test:mcp": "tsx --test --test-concurrency=1 test/mcp.test.ts test/oauth-duration.test.ts",
|
||||
"mcp:probe": "tsx scripts/mcp-probe.ts",
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
ALTER TABLE `User`
|
||||
ADD COLUMN `role` VARCHAR(16) NOT NULL DEFAULT 'user' COMMENT '系统权限:admin、user 或 readonly;管理员不能查看其他用户财务数据',
|
||||
ADD COLUMN `banned` BOOLEAN NOT NULL DEFAULT false COMMENT '封禁后禁止登录和使用已有会话、MCP 授权',
|
||||
ADD COLUMN `mustChangePassword` BOOLEAN NOT NULL DEFAULT false COMMENT '首次登录必须设置新的强密码';
|
||||
@@ -13,6 +13,12 @@ model User {
|
||||
username String @unique @db.VarChar(64)
|
||||
/// 登录密码的 bcrypt 哈希,不存储明文
|
||||
passwordHash String @db.VarChar(255)
|
||||
/// 系统权限:admin、user 或 readonly;管理员不能查看其他用户财务数据
|
||||
role String @default("user") @db.VarChar(16)
|
||||
/// 封禁后禁止登录和使用已有会话、MCP 授权
|
||||
banned Boolean @default(false)
|
||||
/// 首次登录必须设置新的强密码
|
||||
mustChangePassword Boolean @default(false)
|
||||
/// 本位币代码
|
||||
baseCurrency String @default("CNY") @db.Char(3)
|
||||
/// 隐藏菜单标识列表
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
// Run HTTP integration tests against a disposable MySQL database and API process.
|
||||
require('dotenv').config({ quiet: true });
|
||||
const mysql = require('mysql2/promise');
|
||||
const { spawn, spawnSync } = require('node:child_process');
|
||||
const { randomBytes } = require('node:crypto');
|
||||
const net = require('node:net');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const pkg = require('../package.json');
|
||||
async function main() {
|
||||
const url = new URL(process.env.DATABASE_URL);
|
||||
const name = 'wp_test_' + randomBytes(8).toString('hex');
|
||||
const connection = await mysql.createConnection({
|
||||
host: url.hostname,
|
||||
port: Number(url.port || 3306),
|
||||
user: decodeURIComponent(url.username),
|
||||
password: decodeURIComponent(url.password),
|
||||
});
|
||||
let api;
|
||||
try {
|
||||
await connection.query('CREATE DATABASE `' + name + '`');
|
||||
url.pathname = '/' + name;
|
||||
const port = await new Promise((resolve, reject) => {
|
||||
const server = net.createServer();
|
||||
server.on('error', reject);
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
const port = server.address().port;
|
||||
server.close(() => resolve(port));
|
||||
});
|
||||
});
|
||||
const env = {
|
||||
...process.env,
|
||||
DATABASE_URL: url.toString(),
|
||||
ADMIN_USERNAME: 'admin',
|
||||
ADMIN_PASSWORD: 'admin',
|
||||
PORT: String(port),
|
||||
API_HOST: '127.0.0.1',
|
||||
API_ALLOWED_HOSTS: '*',
|
||||
WEB_ORIGIN: 'http://localhost:5173',
|
||||
NETWORK_RATE_LIMIT_ENABLED: 'false',
|
||||
MCP_PUBLIC_URL: 'http://127.0.0.1:' + port + '/mcp',
|
||||
MCP_WEB_URL: 'http://localhost:5173',
|
||||
NETWORK_ALLOW_HTTP: 'true',
|
||||
TEST_API_URL: 'http://127.0.0.1:' + port + '/api',
|
||||
};
|
||||
const run = (args) => spawnSync(process.execPath, args, { env, encoding: 'utf8' });
|
||||
// Historical 005-007 directories sort before the initial migration. Use the
|
||||
// current schema only in this disposable database, then exercise our SQL.
|
||||
const migration = run([
|
||||
require.resolve('prisma/build/index.js'),
|
||||
'db',
|
||||
'push',
|
||||
'--skip-generate',
|
||||
]);
|
||||
if (migration.status !== 0) {
|
||||
const safe = (migration.stdout + migration.stderr)
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => !/Datasource|mysql:\/\/|DATABASE_URL|Environment variables/.test(line))
|
||||
.join('\n');
|
||||
console.error(safe);
|
||||
throw Error('Disposable database migration failed');
|
||||
}
|
||||
await connection.query('USE `' + name + '`');
|
||||
// db push omits the historical column comments asserted by integration tests.
|
||||
await connection.query(
|
||||
"ALTER TABLE `User` MODIFY COLUMN `accountGroupOrder` JSON NULL COMMENT '账户分组显示顺序;空值表示沿用默认顺序'",
|
||||
);
|
||||
await connection.query(
|
||||
'ALTER TABLE `User` DROP COLUMN `role`, DROP COLUMN `banned`, DROP COLUMN `mustChangePassword`',
|
||||
);
|
||||
await connection.query(
|
||||
fs.readFileSync(
|
||||
path.join(__dirname, '../prisma/migrations/20261005130000_admin_accounts/migration.sql'),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
const build = run([require.resolve('typescript/bin/tsc')]);
|
||||
if (build.status !== 0) {
|
||||
console.log(build.stdout);
|
||||
throw Error('API build failed');
|
||||
}
|
||||
api = spawn(process.execPath, ['dist/main.js'], { env, stdio: 'ignore' });
|
||||
let ready = false;
|
||||
for (let i = 0; i < 80; i++) {
|
||||
try {
|
||||
ready = (await fetch(env.TEST_API_URL + '/health')).ok;
|
||||
} catch {}
|
||||
if (ready) break;
|
||||
if (api.exitCode !== null) throw Error('Disposable API startup failed');
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
}
|
||||
if (!ready) throw Error('Disposable API startup timed out');
|
||||
env.TEST_ISOLATED = 'true';
|
||||
const requested = process.argv.slice(2);
|
||||
const tests = requested.length
|
||||
? requested
|
||||
: [
|
||||
...pkg.scripts['test:integration'].split(' ').filter((s) => s.endsWith('.test.ts')),
|
||||
'test/admin-integration.test.ts',
|
||||
'test/mcp.test.ts',
|
||||
'test/oauth-duration.test.ts',
|
||||
];
|
||||
const result = spawnSync(
|
||||
process.execPath,
|
||||
[require.resolve('tsx/cli'), '--test', '--test-concurrency=1', ...tests],
|
||||
{ env, stdio: 'inherit' },
|
||||
);
|
||||
process.exitCode = result.status || 0;
|
||||
} finally {
|
||||
if (api && api.exitCode === null) {
|
||||
const exited = new Promise((resolve) => api.once('exit', resolve));
|
||||
api.kill();
|
||||
await exited;
|
||||
}
|
||||
await connection.query('DROP DATABASE `' + name + '`');
|
||||
await connection.end();
|
||||
console.log('Disposable test database and API cleaned up.');
|
||||
}
|
||||
}
|
||||
main().catch((e) => {
|
||||
console.error(
|
||||
'Isolated test run failed: ' +
|
||||
(/Disposable|API build/.test(e.message)
|
||||
? e.message
|
||||
: 'check test configuration or database access'),
|
||||
);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import {
|
||||
Injectable,
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Patch,
|
||||
Req,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
ForbiddenException,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { hash } from 'bcryptjs';
|
||||
import { z } from 'zod';
|
||||
import { Database } from './database';
|
||||
import { UserRequest } from './auth';
|
||||
import { adminCreateInput, adminUpdateInput } from './user-access';
|
||||
|
||||
const summary = {
|
||||
id: true,
|
||||
username: true,
|
||||
role: true,
|
||||
banned: true,
|
||||
mustChangePassword: true,
|
||||
createdAt: true,
|
||||
} as const;
|
||||
@Injectable()
|
||||
export class AdminService {
|
||||
constructor(private db: Database) {}
|
||||
private async requireAdmin(userId: string) {
|
||||
const u = await this.db.user.findUnique({ where: { id: userId } });
|
||||
if (!u || u.role !== 'admin' || u.banned || u.mustChangePassword)
|
||||
throw new ForbiddenException('需要已完成改密的管理员账号');
|
||||
}
|
||||
async list(r: UserRequest, query: unknown) {
|
||||
await this.requireAdmin(r.userId);
|
||||
const p = z
|
||||
.object({
|
||||
offset: z.coerce.number().int().min(0).default(0),
|
||||
limit: z.coerce.number().int().min(1).max(100).default(50),
|
||||
})
|
||||
.parse(query);
|
||||
const [items, total] = await Promise.all([
|
||||
this.db.user.findMany({
|
||||
select: summary,
|
||||
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||
skip: p.offset,
|
||||
take: p.limit,
|
||||
}),
|
||||
this.db.user.count(),
|
||||
]);
|
||||
return { items, total, offset: p.offset, limit: p.limit };
|
||||
}
|
||||
async create(r: UserRequest, body: unknown) {
|
||||
await this.requireAdmin(r.userId);
|
||||
const v = adminCreateInput.parse(body);
|
||||
const passwordHash = await hash(v.password, 12);
|
||||
return this.db.serial(async (tx) => {
|
||||
await tx.$queryRaw(Prisma.sql`SELECT id FROM User WHERE id=${r.userId} FOR UPDATE`);
|
||||
const actor = await tx.user.findUniqueOrThrow({ where: { id: r.userId } });
|
||||
if (actor.role !== 'admin' || actor.banned || actor.mustChangePassword)
|
||||
throw new ForbiddenException('管理员权限已变更');
|
||||
return tx.user.create({
|
||||
data: { username: v.username, passwordHash, role: v.role, mustChangePassword: true },
|
||||
select: summary,
|
||||
});
|
||||
});
|
||||
}
|
||||
async update(r: UserRequest, id: string, body: unknown) {
|
||||
z.string().uuid().parse(id);
|
||||
const v = adminUpdateInput.parse(body);
|
||||
await this.requireAdmin(r.userId);
|
||||
if (id === r.userId) throw new ForbiddenException('不能修改自己的系统权限或封禁自己');
|
||||
return this.db.serial(async (tx) => {
|
||||
// Serialize administrator changes, including two administrators changing each other.
|
||||
await tx.$queryRaw(Prisma.sql`SELECT id FROM User WHERE role='admin' ORDER BY id FOR UPDATE`);
|
||||
const actor = await tx.user.findUniqueOrThrow({ where: { id: r.userId } });
|
||||
if (actor.role !== 'admin' || actor.banned || actor.mustChangePassword)
|
||||
throw new ForbiddenException('管理员权限已变更');
|
||||
const target = await tx.user.findUnique({ where: { id } });
|
||||
if (!target) throw new NotFoundException('账号不存在');
|
||||
if (
|
||||
target.role === 'admin' &&
|
||||
!target.banned &&
|
||||
(v.banned || (v.role && v.role !== 'admin')) &&
|
||||
(await tx.user.count({ where: { role: 'admin', banned: false } })) <= 1
|
||||
)
|
||||
throw new ForbiddenException('必须保留至少一个可用管理员');
|
||||
const result = await tx.user.update({ where: { id }, data: v, select: summary });
|
||||
if (result.role !== target.role || result.banned !== target.banned) {
|
||||
await tx.session.deleteMany({ where: { userId: id } });
|
||||
await tx.agentGrant.updateMany({
|
||||
where: { userId: id, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
await tx.agentAuthorization.updateMany({
|
||||
where: { userId: id, status: { in: ['pending', 'approved'] } },
|
||||
data: { status: 'cancelled' },
|
||||
});
|
||||
await tx.agentOperation.updateMany({
|
||||
where: { userId: id, status: 'pending' },
|
||||
data: { status: 'cancelled', completedAt: new Date() },
|
||||
});
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
}
|
||||
@Controller('api/admin/users')
|
||||
export class AdminController {
|
||||
constructor(private service: AdminService) {}
|
||||
@Get() list(@Req() r: UserRequest, @Query() q: unknown) {
|
||||
return this.service.list(r, q);
|
||||
}
|
||||
@Post() create(@Req() r: UserRequest, @Body() b: unknown) {
|
||||
return this.service.create(r, b);
|
||||
}
|
||||
@Patch(':id') update(@Req() r: UserRequest, @Param('id') id: string, @Body() b: unknown) {
|
||||
return this.service.update(r, id, b);
|
||||
}
|
||||
}
|
||||
+78
-13
@@ -15,6 +15,7 @@ import {
|
||||
ForbiddenException,
|
||||
HttpException,
|
||||
SetMetadata,
|
||||
OnModuleInit,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { Request, Response } from 'express';
|
||||
@@ -23,6 +24,7 @@ import { hash, compare } from 'bcryptjs';
|
||||
import { Database } from './database';
|
||||
import { credentials, credentialChange, defaultOverviewCards } from './validation';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { loginInput } from './user-access';
|
||||
export type UserRequest = Request & {
|
||||
userId: string;
|
||||
sessionId: string;
|
||||
@@ -40,9 +42,26 @@ export function allowedOrigin(
|
||||
return isNetworkOriginAllowed(origin, configured, !production);
|
||||
}
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
export class AuthService implements OnModuleInit {
|
||||
private attempts = new Map<string, { count: number; until: number }>();
|
||||
constructor(private db: Database) {}
|
||||
async onModuleInit() {
|
||||
// Never reset or promote an existing account based on environment defaults.
|
||||
const username = credentials.shape.username.parse(process.env.ADMIN_USERNAME ?? 'admin');
|
||||
const password = loginInput.shape.password.parse(process.env.ADMIN_PASSWORD ?? 'admin');
|
||||
if (await this.db.user.count({ where: { role: 'admin' } })) return;
|
||||
const passwordHash = await hash(password, 12);
|
||||
await this.db.serial(async (tx) => {
|
||||
if (await tx.user.count({ where: { role: 'admin' } })) return;
|
||||
if (await tx.user.findUnique({ where: { username } }))
|
||||
throw new Error(
|
||||
'Default administrator username already exists; configure a different ADMIN_USERNAME',
|
||||
);
|
||||
await tx.user.create({
|
||||
data: { username, passwordHash, role: 'admin', mustChangePassword: true },
|
||||
});
|
||||
});
|
||||
}
|
||||
limit(req: Request) {
|
||||
const network = networkConfig();
|
||||
if (!network.rateLimitEnabled) return;
|
||||
@@ -84,8 +103,9 @@ export class AuthService {
|
||||
if (!s || s.expiresAt <= new Date()) return null;
|
||||
const u = await this.db.user.findUniqueOrThrow({
|
||||
where: { id: s.userId },
|
||||
select: { idleMinutes: true },
|
||||
select: { idleMinutes: true, banned: true },
|
||||
});
|
||||
if (u.banned) throw new UnauthorizedException('账号已被封禁');
|
||||
if (u.idleMinutes && Date.now() - +s.lastActivity >= u.idleMinutes * 60000) {
|
||||
await this.db.session.deleteMany({ where: { id: s.id } });
|
||||
throw new UnauthorizedException('长时间无操作,已自动退出登录');
|
||||
@@ -102,6 +122,29 @@ export class AuthService {
|
||||
httpOnly: true,
|
||||
});
|
||||
}
|
||||
async access(req: UserRequest) {
|
||||
const u = await this.db.user.findUniqueOrThrow({ where: { id: req.userId } });
|
||||
if (u.banned) throw new UnauthorizedException('账号已被封禁');
|
||||
const path = req.path.replace(/\/$/, '');
|
||||
const passwordAllowed = [
|
||||
'/api/auth/me',
|
||||
'/api/auth/credentials',
|
||||
'/api/auth/logout',
|
||||
'/api/auth/activity',
|
||||
];
|
||||
if (u.mustChangePassword && !passwordAllowed.includes(path))
|
||||
throw new ForbiddenException('首次登录必须修改密码');
|
||||
const connectionManagement =
|
||||
path === '/api/agent/tokens' ||
|
||||
/^\/api\/agent\/(authorizations|connections)\/[a-f0-9-]{36}$/.test(path);
|
||||
if (
|
||||
u.role === 'readonly' &&
|
||||
!['GET', 'HEAD', 'OPTIONS'].includes(req.method) &&
|
||||
!path.startsWith('/api/auth/') &&
|
||||
!connectionManagement
|
||||
)
|
||||
throw new ForbiddenException('只读账号不能修改数据');
|
||||
}
|
||||
}
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
@@ -126,6 +169,7 @@ export class AuthGuard implements CanActivate {
|
||||
req.userId = id.userId;
|
||||
req.sessionId = id.id;
|
||||
req.revealed = !!id.revealUntil && +id.revealUntil > Date.now();
|
||||
await this.auth.access(req);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -140,30 +184,34 @@ export class AuthBusinessService {
|
||||
return { status: 'ok' };
|
||||
}
|
||||
async register(body: unknown, req: Request, res: Response) {
|
||||
this.auth.limit(req);
|
||||
const v = credentials.parse(body),
|
||||
user = await this.db.user.create({
|
||||
data: { username: v.username, passwordHash: await hash(v.password, 12) },
|
||||
});
|
||||
await this.auth.issue(user.id, res);
|
||||
return { username: user.username, baseCurrency: user.baseCurrency };
|
||||
throw new ForbiddenException('公开注册已关闭,请联系管理员创建账号');
|
||||
}
|
||||
async login(body: unknown, req: Request, res: Response) {
|
||||
this.auth.limit(req);
|
||||
const v = credentials.parse(body),
|
||||
const v = loginInput.parse(body),
|
||||
user = await this.db.user.findUnique({ where: { username: v.username } });
|
||||
const ok = await compare(
|
||||
v.password,
|
||||
user?.passwordHash || '$2b$12$JZKvzAzfqM3obKxMQTFBjOzqIIKG97kn96/xUMbgTuWUnlMAT2bSi',
|
||||
);
|
||||
if (!user || !ok) throw new UnauthorizedException('账号或密码错误');
|
||||
if (user.banned) throw new ForbiddenException('账号已被封禁');
|
||||
await this.auth.issue(user.id, res);
|
||||
return { username: user.username, baseCurrency: user.baseCurrency };
|
||||
return {
|
||||
username: user.username,
|
||||
baseCurrency: user.baseCurrency,
|
||||
role: user.role,
|
||||
mustChangePassword: user.mustChangePassword,
|
||||
hiddenMenus: [],
|
||||
};
|
||||
}
|
||||
async me(req: UserRequest) {
|
||||
const user = await this.db.user.findUniqueOrThrow({
|
||||
where: { id: req.userId },
|
||||
select: {
|
||||
id: true,
|
||||
role: true,
|
||||
mustChangePassword: true,
|
||||
username: true,
|
||||
baseCurrency: true,
|
||||
hiddenMenus: true,
|
||||
@@ -195,6 +243,11 @@ export class AuthBusinessService {
|
||||
const user = await this.db.user.findUniqueOrThrow({ where: { id: r.userId } });
|
||||
if (!(await compare(v.currentPassword, user.passwordHash)))
|
||||
throw new ForbiddenException('当前密码错误');
|
||||
if (
|
||||
user.mustChangePassword &&
|
||||
(!v.newPassword || (await compare(v.newPassword, user.passwordHash)))
|
||||
)
|
||||
throw new BadRequestException('请设置与初始密码不同的新密码(至少 10 个字符)');
|
||||
if ((!v.username || v.username === user.username) && !v.newPassword)
|
||||
throw new BadRequestException('请填写新的账号或密码');
|
||||
const passwordHash = v.newPassword ? await hash(v.newPassword, 12) : user.passwordHash;
|
||||
@@ -203,11 +256,23 @@ export class AuthBusinessService {
|
||||
await this.db.serial(async (tx) => {
|
||||
await tx.$queryRaw(Prisma.sql`SELECT id FROM User WHERE id = ${r.userId} FOR UPDATE`);
|
||||
const current = await tx.user.findUniqueOrThrow({ where: { id: r.userId } });
|
||||
if (current.passwordHash !== user.passwordHash || current.username !== user.username)
|
||||
if (
|
||||
current.banned ||
|
||||
current.passwordHash !== user.passwordHash ||
|
||||
current.username !== user.username
|
||||
)
|
||||
throw new ForbiddenException('账号已变更,请重新登录后操作');
|
||||
await tx.user.update({
|
||||
where: { id: r.userId },
|
||||
data: { username: v.username, passwordHash },
|
||||
data: {
|
||||
username: v.username,
|
||||
passwordHash,
|
||||
...(v.newPassword ? { mustChangePassword: false } : {}),
|
||||
},
|
||||
});
|
||||
await tx.agentGrant.updateMany({
|
||||
where: { userId: r.userId, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
await tx.session.deleteMany({ where: { userId: r.userId } });
|
||||
await tx.session.create({ data: { id: digest(token), userId: r.userId, expiresAt } });
|
||||
|
||||
@@ -8,6 +8,7 @@ import cookieParser from 'cookie-parser';
|
||||
import helmet from 'helmet';
|
||||
import { json } from 'express';
|
||||
import { AuthController, AuthBusinessService, AuthGuard, AuthService } from './auth';
|
||||
import { AdminController, AdminService } from './admin';
|
||||
import { CalendarController, CalendarBusinessService } from './calendar';
|
||||
import { SchedulesController, SchedulesBusinessService } from './schedules';
|
||||
import { TransfersController, TransfersBusinessService } from './transfers';
|
||||
@@ -57,6 +58,7 @@ class SafeErrors implements ExceptionFilter {
|
||||
providers: [
|
||||
Database,
|
||||
AuthService,
|
||||
AdminService,
|
||||
RatesService,
|
||||
MetalsService,
|
||||
IconsService,
|
||||
@@ -82,6 +84,7 @@ class SafeErrors implements ExceptionFilter {
|
||||
CalendarController,
|
||||
IconsController,
|
||||
AuthController,
|
||||
AdminController,
|
||||
PortfolioController,
|
||||
MetalsController,
|
||||
SettingsController,
|
||||
|
||||
@@ -178,6 +178,15 @@ export class AgentOAuth implements OAuthServerProvider {
|
||||
const authorizationDays = oauthDays.parse(days);
|
||||
const allowed = selected || ['read'];
|
||||
scopeInput.parse(allowed);
|
||||
const user = await this.db.user.findUnique({ where: { id: userId } });
|
||||
if (!user || user.banned || user.mustChangePassword)
|
||||
throw new ForbiddenException('账号不可用');
|
||||
if (
|
||||
approved &&
|
||||
user.role === 'readonly' &&
|
||||
allowed.some((s: string) => ['draft', 'write', 'hidden_write'].includes(s))
|
||||
)
|
||||
throw new ForbiddenException('只读账号只能授予查询权限');
|
||||
if (allowed.some((scope: string) => !parameters.scopes.includes(scope)))
|
||||
throw new BadRequestException('不能授予客户端未请求的权限');
|
||||
const code = secret();
|
||||
@@ -220,6 +229,14 @@ export class AgentOAuth implements OAuthServerProvider {
|
||||
authorizationDays: number | null = 30,
|
||||
) {
|
||||
if (clientId && days === null) throw new BadRequestException('OAuth 连接必须有期限');
|
||||
const user = await this.db.user.findUnique({ where: { id: userId } });
|
||||
if (!user || user.banned || user.mustChangePassword)
|
||||
throw new ForbiddenException('账号已封禁或需要首次改密');
|
||||
if (
|
||||
user.role === 'readonly' &&
|
||||
selected.some((s) => ['draft', 'write', 'hidden_write'].includes(s))
|
||||
)
|
||||
throw new ForbiddenException('只读账号只能授予查询权限');
|
||||
const access = secret(),
|
||||
refresh = clientId ? secret() : undefined,
|
||||
sessionId = digest(secret());
|
||||
@@ -315,6 +332,9 @@ export class AgentOAuth implements OAuthServerProvider {
|
||||
(row.refreshExpiresAt && row.refreshExpiresAt <= new Date())
|
||||
)
|
||||
throw new InvalidGrantError('Invalid refresh token');
|
||||
const user = await this.db.user.findUnique({ where: { id: row.userId } });
|
||||
if (!user || user.banned || user.mustChangePassword)
|
||||
throw new InvalidGrantError('Account unavailable');
|
||||
const current = row.scopes as string[];
|
||||
if (
|
||||
selected &&
|
||||
@@ -368,6 +388,9 @@ export class AgentOAuth implements OAuthServerProvider {
|
||||
row.resource !== urls().resource.toString()
|
||||
)
|
||||
throw new InvalidTokenError('Expired, revoked or invalid resource token');
|
||||
const user = await this.db.user.findUnique({ where: { id: row.userId } });
|
||||
if (!user || user.banned || user.mustChangePassword)
|
||||
throw new InvalidTokenError('Account unavailable');
|
||||
return {
|
||||
token,
|
||||
clientId: row.clientId || row.id,
|
||||
@@ -407,6 +430,9 @@ export class AgentOAuth implements OAuthServerProvider {
|
||||
},
|
||||
});
|
||||
if (!row) throw new ForbiddenException('Agent 连接已过期或撤销');
|
||||
const user = await this.db.user.findUnique({ where: { id: row.userId } });
|
||||
if (!user || user.banned || user.mustChangePassword)
|
||||
throw new ForbiddenException('账号已封禁或需要首次改密');
|
||||
return row;
|
||||
}
|
||||
}
|
||||
@@ -134,6 +134,10 @@ export class AgentOperations {
|
||||
return digest(stable(plain(data)));
|
||||
}
|
||||
private async permission(grant: AgentGrant, t: ToolDefinition, p: any) {
|
||||
const user = await this.db.user.findUniqueOrThrow({ where: { id: grant.userId } });
|
||||
if (user.banned || user.mustChangePassword) throw new ForbiddenException('账号不可用');
|
||||
if (user.role === 'readonly' && t.scope !== 'read')
|
||||
throw new ForbiddenException('只读账号不能提交写入或草稿');
|
||||
const selected = grant.scopes as string[];
|
||||
if (!selected.includes('read')) throw new ForbiddenException('缺少 read 权限');
|
||||
const mode = selected.includes('write')
|
||||
|
||||
@@ -3,6 +3,7 @@ import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import { metalConfig, metalHoldingInput } from './metals';
|
||||
import { scheduleInput } from './schedules';
|
||||
import { z } from 'zod';
|
||||
import { loginInput, adminCreateInput, adminUpdateInput } from './user-access';
|
||||
import {
|
||||
credentials,
|
||||
credentialChange,
|
||||
@@ -32,8 +33,9 @@ export function setupOpenApi(app: INestApplication) {
|
||||
.build(),
|
||||
);
|
||||
const bodies: Record<string, z.ZodType> = {
|
||||
'POST /api/auth/register': credentials,
|
||||
'POST /api/auth/login': credentials,
|
||||
'POST /api/auth/login': loginInput,
|
||||
'POST /api/admin/users': adminCreateInput,
|
||||
'PATCH /api/admin/users/{id}': adminUpdateInput,
|
||||
'PATCH /api/auth/credentials': credentialChange,
|
||||
'POST /api/auth/reveal': z.object({ password: credentials.shape.password.optional() }).strict(),
|
||||
'POST /api/positions': positionInput,
|
||||
|
||||
@@ -183,6 +183,9 @@ export class SettingsBusinessService {
|
||||
where: { id: r.userId },
|
||||
select: {
|
||||
username: true,
|
||||
id: true,
|
||||
role: true,
|
||||
mustChangePassword: true,
|
||||
baseCurrency: true,
|
||||
hiddenMenus: true,
|
||||
showNotes: true,
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { z } from 'zod';
|
||||
import { credentials } from './validation';
|
||||
|
||||
export const roles = z.enum(['admin', 'user', 'readonly']);
|
||||
export const loginInput = credentials.extend({
|
||||
password: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(72)
|
||||
.refine((s) => Buffer.byteLength(s, 'utf8') <= 72, '密码最多 72 字节'),
|
||||
});
|
||||
export const adminCreateInput = credentials.extend({ role: roles.default('user') }).strict();
|
||||
export const adminUpdateInput = z
|
||||
.object({ role: roles.optional(), banned: z.boolean().optional() })
|
||||
.strict()
|
||||
.refine((v) => v.role !== undefined || v.banned !== undefined, '请选择权限或封禁状态');
|
||||
@@ -177,7 +177,11 @@ export const pairedReasons = [
|
||||
|
||||
export const credentialChange = z
|
||||
.object({
|
||||
currentPassword: credentials.shape.password,
|
||||
currentPassword: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(72)
|
||||
.refine((s) => Buffer.byteLength(s, 'utf8') <= 72, '密码最多 72 字节'),
|
||||
username: credentials.shape.username.optional(),
|
||||
newPassword: credentials.shape.password.optional(),
|
||||
})
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
import 'dotenv/config';
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { AuthService } from '../src/auth';
|
||||
import { Database } from '../src/database';
|
||||
import { AgentOAuth } from '../src/mcp/oauth';
|
||||
|
||||
test(
|
||||
'admin bootstrap, closed registration, mandatory password change, roles and ban revoke sessions and MCP',
|
||||
{ skip: process.env.TEST_ISOLATED !== 'true' },
|
||||
async () => {
|
||||
const db = new PrismaClient();
|
||||
const base = process.env.TEST_API_URL!;
|
||||
const origin = process.env.WEB_ORIGIN!;
|
||||
async function call(path: string, method = 'GET', body?: unknown, cookie = '') {
|
||||
const r = await fetch(base + path, {
|
||||
method,
|
||||
headers: {
|
||||
Origin: origin,
|
||||
Cookie: cookie,
|
||||
...(body ? { 'Content-Type': 'application/json' } : {}),
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
return {
|
||||
status: r.status,
|
||||
data: await r.json(),
|
||||
cookie: r.headers.get('set-cookie')?.split(';')[0] || cookie,
|
||||
};
|
||||
}
|
||||
try {
|
||||
assert.equal(
|
||||
(await call('/auth/register', 'POST', { username: 'blocked', password: 'long-password' }))
|
||||
.status,
|
||||
403,
|
||||
);
|
||||
assert.equal(await db.user.count({ where: { username: 'blocked' } }), 0);
|
||||
const initial = await db.user.findUniqueOrThrow({ where: { username: 'admin' } });
|
||||
assert.equal(initial.role, 'admin');
|
||||
assert.equal(initial.mustChangePassword, true);
|
||||
const login = await call('/auth/login', 'POST', { username: 'admin', password: 'admin' });
|
||||
assert.equal(login.status, 201);
|
||||
assert.equal(login.data.mustChangePassword, true);
|
||||
assert.equal((await call('/overview', 'GET', undefined, login.cookie)).status, 403);
|
||||
assert.equal((await call('/admin/users', 'GET', undefined, login.cookie)).status, 403);
|
||||
assert.equal(
|
||||
(
|
||||
await call(
|
||||
'/agent/tokens',
|
||||
'POST',
|
||||
{ name: 'blocked', scopes: ['read'], days: 1, password: 'admin' },
|
||||
login.cookie,
|
||||
)
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await call(
|
||||
'/auth/credentials',
|
||||
'PATCH',
|
||||
{ currentPassword: 'admin', username: 'renamed' },
|
||||
login.cookie,
|
||||
)
|
||||
).status,
|
||||
400,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await call(
|
||||
'/auth/credentials',
|
||||
'PATCH',
|
||||
{ currentPassword: 'admin', newPassword: 'short' },
|
||||
login.cookie,
|
||||
)
|
||||
).status,
|
||||
400,
|
||||
);
|
||||
const password = 'Admin-new-' + randomUUID();
|
||||
const changed = await call(
|
||||
'/auth/credentials',
|
||||
'PATCH',
|
||||
{ currentPassword: 'admin', newPassword: password },
|
||||
login.cookie,
|
||||
);
|
||||
assert.equal(changed.status, 200);
|
||||
const cookie = changed.cookie;
|
||||
assert.equal(
|
||||
(await call('/auth/me', 'GET', undefined, cookie)).data.mustChangePassword,
|
||||
false,
|
||||
);
|
||||
assert.equal((await call('/auth/me', 'GET', undefined, login.cookie)).status, 401);
|
||||
const savedHash = (await db.user.findUniqueOrThrow({ where: { id: initial.id } }))
|
||||
.passwordHash;
|
||||
await new AuthService(db as Database).onModuleInit();
|
||||
assert.equal(
|
||||
(await db.user.findUniqueOrThrow({ where: { id: initial.id } })).passwordHash,
|
||||
savedHash,
|
||||
);
|
||||
assert.equal(
|
||||
(await call('/auth/login', 'POST', { username: 'admin', password: 'admin' })).status,
|
||||
401,
|
||||
);
|
||||
assert.equal(
|
||||
(await call('/admin/users/' + initial.id, 'PATCH', { banned: true }, cookie)).status,
|
||||
403,
|
||||
);
|
||||
const username = 'admin_test_' + randomUUID().slice(0, 10),
|
||||
first = 'Initial-' + randomUUID();
|
||||
const created = await call(
|
||||
'/admin/users',
|
||||
'POST',
|
||||
{ username, password: first, role: 'user' },
|
||||
cookie,
|
||||
);
|
||||
assert.equal(created.status, 201);
|
||||
assert.equal(created.data.mustChangePassword, true);
|
||||
assert.equal('passwordHash' in created.data, false);
|
||||
const id = created.data.id;
|
||||
assert.equal(
|
||||
(await call('/admin/users', 'POST', { username, password: first }, cookie)).status,
|
||||
409,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await call(
|
||||
'/admin/users',
|
||||
'POST',
|
||||
{ username: username + '_bad', password: first, role: 'superuser' },
|
||||
cookie,
|
||||
)
|
||||
).status,
|
||||
400,
|
||||
);
|
||||
const fresh = await call('/auth/login', 'POST', { username, password: first });
|
||||
assert.equal((await call('/positions', 'GET', undefined, fresh.cookie)).status, 403);
|
||||
assert.equal(
|
||||
(
|
||||
await call(
|
||||
'/auth/credentials',
|
||||
'PATCH',
|
||||
{ currentPassword: first, newPassword: first },
|
||||
fresh.cookie,
|
||||
)
|
||||
).status,
|
||||
400,
|
||||
);
|
||||
const regularPassword = 'Changed-' + randomUUID();
|
||||
const updated = await call(
|
||||
'/auth/credentials',
|
||||
'PATCH',
|
||||
{ currentPassword: first, newPassword: regularPassword },
|
||||
fresh.cookie,
|
||||
);
|
||||
assert.equal(updated.status, 200);
|
||||
const regular = updated.cookie;
|
||||
assert.equal((await call('/admin/users', 'GET', undefined, regular)).status, 403);
|
||||
assert.equal(
|
||||
(
|
||||
await call(
|
||||
'/admin/users',
|
||||
'POST',
|
||||
{ username: 'escalate', password: first, role: 'admin' },
|
||||
regular,
|
||||
)
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
const token = await call(
|
||||
'/agent/tokens',
|
||||
'POST',
|
||||
{ name: 'ban-test', scopes: ['read', 'write'], days: 1, password: regularPassword },
|
||||
regular,
|
||||
);
|
||||
assert.equal(token.status, 201);
|
||||
const oauth = new AgentOAuth(db as Database);
|
||||
await oauth.verifyAccessToken(token.data.token);
|
||||
assert.equal(
|
||||
(await call('/admin/users/' + id, 'PATCH', { role: 'readonly' }, cookie)).status,
|
||||
200,
|
||||
);
|
||||
assert.equal((await call('/auth/me', 'GET', undefined, regular)).status, 401);
|
||||
await assert.rejects(oauth.verifyAccessToken(token.data.token));
|
||||
const readonly = await call('/auth/login', 'POST', { username, password: regularPassword });
|
||||
assert.equal((await call('/positions', 'GET', undefined, readonly.cookie)).status, 200);
|
||||
assert.equal((await call('/positions', 'POST', {}, readonly.cookie)).status, 403);
|
||||
assert.equal((await call('/schedules/run', 'POST', {}, readonly.cookie)).status, 403);
|
||||
assert.equal(
|
||||
(
|
||||
await call(
|
||||
'/agent/tokens',
|
||||
'POST',
|
||||
{ name: 'escalate', scopes: ['read', 'draft'], days: 1, password: regularPassword },
|
||||
readonly.cookie,
|
||||
)
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
const readToken = await call(
|
||||
'/agent/tokens',
|
||||
'POST',
|
||||
{ name: 'readonly', scopes: ['read'], days: 1, password: regularPassword },
|
||||
readonly.cookie,
|
||||
);
|
||||
assert.equal(readToken.status, 201);
|
||||
const readInfo = await oauth.verifyAccessToken(readToken.data.token);
|
||||
assert.deepEqual(readInfo.scopes, ['read']);
|
||||
const list = await call('/admin/users?limit=1&offset=1', 'GET', undefined, cookie);
|
||||
assert.equal(list.data.items.length, 1);
|
||||
assert.ok(list.data.total >= 2);
|
||||
assert.equal(
|
||||
(await call('/admin/users/' + id, 'PATCH', { banned: true }, cookie)).status,
|
||||
200,
|
||||
);
|
||||
assert.equal(
|
||||
(await call('/auth/login', 'POST', { username, password: regularPassword })).status,
|
||||
403,
|
||||
);
|
||||
assert.equal((await call('/auth/me', 'GET', undefined, readonly.cookie)).status, 401);
|
||||
await assert.rejects(oauth.verifyAccessToken(readToken.data.token));
|
||||
assert.equal(await db.session.count({ where: { userId: id } }), 0);
|
||||
assert.equal(
|
||||
(await call('/admin/users/' + id, 'PATCH', { banned: false, role: 'user' }, cookie)).status,
|
||||
200,
|
||||
);
|
||||
const unbanned = await call('/auth/login', 'POST', { username, password: regularPassword });
|
||||
assert.equal(unbanned.status, 201);
|
||||
assert.equal((await call('/overview', 'GET', undefined, unbanned.cookie)).status, 200);
|
||||
} finally {
|
||||
await db.$disconnect();
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -1,3 +1,4 @@
|
||||
import { provisionTestUser } from './user-fixture';
|
||||
import 'dotenv/config';
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
@@ -62,7 +63,8 @@ for (const useDefaultScopes of [false, true])
|
||||
}
|
||||
}
|
||||
try {
|
||||
const fixture = await web('/auth/register', { username, password });
|
||||
await provisionTestUser({ username, password });
|
||||
const fixture = await web('/auth/login', { username, password });
|
||||
userId = (await db.user.findUniqueOrThrow({ where: { username } })).id;
|
||||
await writeFile(
|
||||
join(home, 'config.toml'),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { provisionTestUser } from './user-fixture';
|
||||
import { fixtureFetch } from './backup-fixture';
|
||||
import 'dotenv/config';
|
||||
import { test } from 'node:test';
|
||||
@@ -32,11 +33,13 @@ test('private and shared icons, account reuse and complete ZIP restoration prese
|
||||
};
|
||||
}
|
||||
async function account() {
|
||||
const username = 'wp_icons_' + randomUUID();
|
||||
const username = 'wp_icons_' + randomUUID(),
|
||||
password = randomBytes(18).toString('hex');
|
||||
names.push(username);
|
||||
const r = await call('/auth/register', '', 'POST', {
|
||||
await provisionTestUser({ username, password });
|
||||
const r = await call('/auth/login', '', 'POST', {
|
||||
username,
|
||||
password: randomBytes(18).toString('hex'),
|
||||
password,
|
||||
});
|
||||
assert.equal(r.status, 201);
|
||||
return { ...r, id: (await db.user.findUniqueOrThrow({ where: { username } })).id };
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { provisionTestUser } from './user-fixture';
|
||||
import { fixtureFetch } from './backup-fixture';
|
||||
import 'dotenv/config';
|
||||
import { test } from 'node:test';
|
||||
@@ -32,7 +33,8 @@ test('real MySQL: authentication, isolation, history, backup and atomic failures
|
||||
async function account() {
|
||||
const username = 'wp_test_' + randomUUID().slice(0, 12),
|
||||
password = randomBytes(18).toString('hex');
|
||||
const r = await call('/auth/register', 'POST', { username, password });
|
||||
await provisionTestUser({ username, password });
|
||||
const r = await call('/auth/login', 'POST', { username, password });
|
||||
assert.equal(r.status, 201);
|
||||
assert.ok(r.cookie);
|
||||
const u = await db.user.findUniqueOrThrow({ where: { username } });
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { provisionTestUser } from './user-fixture';
|
||||
import { networkConfig, isNetworkOriginAllowed } from '../src/network';
|
||||
import 'dotenv/config';
|
||||
import { test } from 'node:test';
|
||||
@@ -44,7 +45,8 @@ test('official SDK Streamable HTTP: real MySQL full business paths, drafts, isol
|
||||
) {
|
||||
const username = 'mcp_test_' + randomUUID().slice(0, 12),
|
||||
password = randomBytes(20).toString('hex');
|
||||
const registered = await web('', '/auth/register', 'POST', { username, password });
|
||||
await provisionTestUser({ username, password });
|
||||
const registered = await web('', '/auth/login', 'POST', { username, password });
|
||||
assert.equal(registered.status, 201);
|
||||
const user = await db.user.findUniqueOrThrow({ where: { username } });
|
||||
users.push(user.id);
|
||||
@@ -705,7 +707,8 @@ test('real concurrent MCP idempotency, stale writes, icon workflow, nested rollb
|
||||
});
|
||||
}
|
||||
try {
|
||||
assert.equal((await web('/auth/register', 'POST', { username, password })).status, 201);
|
||||
await provisionTestUser({ username, password });
|
||||
assert.equal((await web('/auth/login', 'POST', { username, password })).status, 201);
|
||||
userId = (await db.user.findUniqueOrThrow({ where: { username } })).id;
|
||||
const grant = (
|
||||
await web('/agent/tokens', 'POST', {
|
||||
@@ -902,7 +905,8 @@ test('official SDK OAuth discovery, DCR, PKCE, consent, one-use codes, rotation
|
||||
};
|
||||
}
|
||||
try {
|
||||
const registered = await post('/api/auth/register', { username, password });
|
||||
await provisionTestUser({ username, password });
|
||||
const registered = await post('/api/auth/login', { username, password });
|
||||
assert.equal(registered.status, 201);
|
||||
userId = (await db.user.findUniqueOrThrow({ where: { username } })).id;
|
||||
assert.equal(await auth(provider, { serverUrl: resource, scope: 'read write' }), 'REDIRECT');
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { provisionTestUser } from './user-fixture';
|
||||
import { fixtureFetch } from './backup-fixture';
|
||||
import 'dotenv/config';
|
||||
import { test } from 'node:test';
|
||||
@@ -31,7 +32,8 @@ test('privacy, minute history, backup-gated clear and idle sessions remain user
|
||||
const username = 'wp_privacy_' + randomUUID(),
|
||||
password = randomBytes(18).toString('hex');
|
||||
names.push(username);
|
||||
const r = await call('/auth/register', 'POST', { username, password });
|
||||
await provisionTestUser({ username, password });
|
||||
const r = await call('/auth/login', 'POST', { username, password });
|
||||
assert.equal(r.status, 201);
|
||||
const u = await db.user.findUniqueOrThrow({ where: { username } });
|
||||
return { ...r, username, password, id: u.id };
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { provisionTestUser } from './user-fixture';
|
||||
import { fixtureFetch } from './backup-fixture';
|
||||
import 'dotenv/config';
|
||||
import { test } from 'node:test';
|
||||
@@ -33,7 +34,8 @@ test('transfers are atomic, scoped, retry-safe, decimal exact and included in ba
|
||||
const username = 'wp_transfer_' + randomUUID(),
|
||||
password = randomBytes(18).toString('hex');
|
||||
names.push(username);
|
||||
const r = await call('/auth/register', '', 'POST', { username, password });
|
||||
await provisionTestUser({ username, password });
|
||||
const r = await call('/auth/login', '', 'POST', { username, password });
|
||||
assert.equal(r.status, 201);
|
||||
return { ...r, id: (await db.user.findUniqueOrThrow({ where: { username } })).id, password };
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { provisionTestUser } from './user-fixture';
|
||||
import { fixtureFetch } from './backup-fixture';
|
||||
import 'dotenv/config';
|
||||
import { test } from 'node:test';
|
||||
@@ -34,7 +35,8 @@ test('real MySQL: groups, scheduled atomic execution, calendar, privacy and ZIP
|
||||
const username = 'wp_update_' + randomUUID(),
|
||||
password = randomBytes(18).toString('hex');
|
||||
names.push(username);
|
||||
const result = await call('/auth/register', '', 'POST', { username, password });
|
||||
await provisionTestUser({ username, password });
|
||||
const result = await call('/auth/login', '', 'POST', { username, password });
|
||||
assert.equal(result.status, 201);
|
||||
return {
|
||||
cookie: result.cookie,
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { hash } from 'bcryptjs';
|
||||
|
||||
// Provision test data directly; production registration remains disabled.
|
||||
export async function provisionTestUser(input: { username: string; password: string }) {
|
||||
const db = new PrismaClient();
|
||||
try {
|
||||
return await db.user.create({
|
||||
data: { username: input.username, passwordHash: await hash(input.password, 12) },
|
||||
});
|
||||
} finally {
|
||||
await db.$disconnect();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user