mirror of
https://git.zhongyuan.online/ytke/tap.git
synced 2026-11-24 22:15:18 -08:00
支持自部署需求管理、交付流程与飞书集成
This commit is contained in:
1 parent
4556a5b483
commit
e22b66d9dd
148 files changed
+8300
-6393
No files matched your search
@@ -0,0 +1,295 @@
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { isIP } from 'node:net';
|
||||
import { basePath } from '../base-path.ts';
|
||||
import { applicationOrigin, getDatabase, normalizeDisplayName, normalizeUsername, type AccountRow } from './database.ts';
|
||||
import { hashPassword, hashPasswordSync, hasStoredPassword, validatePassword, verifyPassword } from './password.ts';
|
||||
|
||||
export type AuthUser = {
|
||||
userId: string; username: string; displayName: string;
|
||||
role: 'admin' | 'user'; mustChangePassword: boolean;
|
||||
};
|
||||
export type AdminUser = AuthUser & { disabled: boolean; createdAt: string; lastLoginAt: string | null };
|
||||
export class AuthError extends Error {
|
||||
status: number;
|
||||
constructor(message: string, status = 400) { super(message); this.name = 'AuthError'; this.status = status; }
|
||||
}
|
||||
|
||||
const SESSION_SECONDS = 7 * 24 * 60 * 60;
|
||||
const COOKIE_NAME = 'demand_session';
|
||||
let dummyPasswordHash: string | undefined;
|
||||
|
||||
function publicUser(account: AccountRow): AuthUser {
|
||||
return { userId: account.id, username: account.username, displayName: account.display_name, role: account.role, mustChangePassword: Boolean(account.must_change_password) };
|
||||
}
|
||||
function accountById(id: string): AccountRow | null {
|
||||
return getDatabase().prepare('SELECT * FROM accounts WHERE id = ?').bind(id).first<AccountRow>();
|
||||
}
|
||||
export function hasAccountPassword(userId: string): boolean {
|
||||
return hasStoredPassword(accountById(userId)?.password_hash);
|
||||
}
|
||||
function tokenHash(token: string): string { return createHash('sha256').update(token).digest('hex'); }
|
||||
|
||||
export function isSameOrigin(request: Request): boolean {
|
||||
const origin = request.headers.get('origin');
|
||||
if (!origin || origin === 'null') return false;
|
||||
const fetchSite = request.headers.get('sec-fetch-site');
|
||||
if (fetchSite && !['same-origin', 'none'].includes(fetchSite)) return false;
|
||||
return origin === applicationOrigin(request);
|
||||
}
|
||||
export function assertSameOrigin(request: Request): void {
|
||||
if (!isSameOrigin(request)) throw new AuthError('请求来源无效,请从系统访问地址重新打开页面。', 403);
|
||||
}
|
||||
|
||||
export function sessionCookie(token: string, request?: Request): string {
|
||||
const secure = applicationOrigin(request).startsWith('https://') ? '; Secure' : '';
|
||||
return `${COOKIE_NAME}=${token}; Path=${basePath || '/'}; HttpOnly; SameSite=Lax; Max-Age=${token ? SESSION_SECONDS : 0}${secure}`;
|
||||
}
|
||||
|
||||
function issueSession(account: AccountRow): { user: AuthUser; token: string } {
|
||||
const database = getDatabase();
|
||||
const token = randomBytes(32).toString('base64url');
|
||||
const now = Date.now();
|
||||
database.prepare('DELETE FROM sessions WHERE expires_at <= ?').bind(now).run();
|
||||
database.prepare('INSERT INTO sessions (token_hash, account_id, expires_at, created_at) VALUES (?, ?, ?, ?)')
|
||||
.bind(tokenHash(token), account.id, now + SESSION_SECONDS * 1000, now).run();
|
||||
return { user: publicUser(account), token };
|
||||
}
|
||||
|
||||
/** Called only after a server-side identity provider has authenticated a bound account. */
|
||||
export function issueIdentitySession(accountId: string): { user: AuthUser; token: string } {
|
||||
const account = accountById(accountId);
|
||||
if (!account || account.disabled) throw new AuthError('账号已停用,请联系管理员。', 403);
|
||||
getDatabase().prepare('UPDATE accounts SET last_login_at = ? WHERE id = ?')
|
||||
.bind(new Date().toISOString(), account.id).run();
|
||||
return issueSession(account);
|
||||
}
|
||||
|
||||
export function authenticateSession(token: string | undefined): AuthUser | null {
|
||||
if (!token || !/^[A-Za-z0-9_-]{43}$/.test(token)) return null;
|
||||
const account = getDatabase().prepare(`SELECT accounts.* FROM sessions JOIN accounts ON accounts.id = sessions.account_id
|
||||
WHERE sessions.token_hash = ? AND sessions.expires_at > ? AND accounts.disabled = 0`)
|
||||
.bind(tokenHash(token), Date.now()).first<AccountRow>();
|
||||
return account ? publicUser(account) : null;
|
||||
}
|
||||
|
||||
export async function getCurrentUser(): Promise<AuthUser | null> {
|
||||
const { cookies } = await import('next/headers');
|
||||
return authenticateSession((await cookies()).get(COOKIE_NAME)?.value);
|
||||
}
|
||||
|
||||
export async function requireUser(returnTo = '/'): Promise<AuthUser> {
|
||||
const { redirect } = await import('next/navigation');
|
||||
const user = await getCurrentUser();
|
||||
const safeReturn = returnTo.startsWith('/') && !returnTo.startsWith('//') ? returnTo : '/';
|
||||
if (!user) return redirect(`/login?next=${encodeURIComponent(safeReturn)}`);
|
||||
if (user.mustChangePassword && safeReturn.split('?')[0] !== '/account/password') redirect('/account/password');
|
||||
return user;
|
||||
}
|
||||
|
||||
export async function requireApiUser(options: { admin?: boolean; allowPasswordChange?: boolean } = {}): Promise<AuthUser> {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) throw new AuthError('请先登录。', 401);
|
||||
if (!options.allowPasswordChange && user.mustChangePassword) throw new AuthError('请先修改初始密码后继续。', 403);
|
||||
if (options.admin && user.role !== 'admin') throw new AuthError('仅管理员可以管理账号。', 403);
|
||||
return user;
|
||||
}
|
||||
|
||||
function loginSourceKey(request?: Request): string | undefined {
|
||||
const configuredHeader = process.env.LOGIN_CLIENT_IP_HEADER?.trim().toLowerCase();
|
||||
if (!configuredHeader) return undefined;
|
||||
if (!/^[a-z][a-z0-9-]{0,63}$/.test(configuredHeader)) throw new AuthError('登录来源配置无效,请联系管理员。', 503);
|
||||
|
||||
// Opt-in trust boundary: the reverse proxy must overwrite this single-IP header,
|
||||
// and the application port must not be directly reachable by untrusted clients.
|
||||
// Other forwarded headers are ignored; missing or invalid configured values fail closed.
|
||||
const address = request?.headers.get(configuredHeader)?.trim();
|
||||
const family = address && !address.includes('%') ? isIP(address) : 0;
|
||||
if (!address || !family) throw new AuthError('登录来源信息无效,请联系管理员。', 403);
|
||||
|
||||
let normalized = address;
|
||||
if (family === 6) {
|
||||
normalized = new URL(`http://[${address}]/`).hostname.slice(1, -1);
|
||||
// Equivalent IPv6 spellings and IPv4-mapped addresses share the same bucket.
|
||||
const mapped = /^::ffff:([a-f0-9]{1,4}):([a-f0-9]{1,4})$/.exec(normalized);
|
||||
if (mapped) {
|
||||
const high = Number.parseInt(mapped[1], 16); const low = Number.parseInt(mapped[2], 16);
|
||||
normalized = `${high >>> 8}.${high & 255}.${low >>> 8}.${low & 255}`;
|
||||
}
|
||||
}
|
||||
return `source:${tokenHash(normalized)}`;
|
||||
}
|
||||
|
||||
function consumeLoginAttempt(username: string | undefined, sourceKey?: string): void {
|
||||
const database = getDatabase();
|
||||
const now = Date.now();
|
||||
// Database-backed limits survive restarts and work across local application processes.
|
||||
// There is no shared global bucket: one source cannot spend another source's quota.
|
||||
const buckets = [
|
||||
...(sourceKey ? [{ key: sourceKey, span: 60_000, limit: 60 }] : []),
|
||||
...(username !== undefined ? [{ key: `username:${tokenHash(username)}`, span: 15 * 60_000, limit: 5 }] : []),
|
||||
];
|
||||
if (!buckets.length) return;
|
||||
database.transaction(() => {
|
||||
database.prepare('DELETE FROM login_limits WHERE window_start < ?').bind(now - 15 * 60_000).run();
|
||||
for (const bucket of buckets) {
|
||||
const row = database.prepare('SELECT window_start, attempts FROM login_limits WHERE key = ?').bind(bucket.key).first<{ window_start: number; attempts: number }>();
|
||||
if (row && now - row.window_start < bucket.span && row.attempts >= bucket.limit) {
|
||||
throw new AuthError('登录尝试过于频繁,请稍后再试。', 429);
|
||||
}
|
||||
}
|
||||
for (const bucket of buckets) {
|
||||
database.prepare(`INSERT INTO login_limits (key, window_start, attempts) VALUES (?, ?, 1)
|
||||
ON CONFLICT(key) DO UPDATE SET
|
||||
attempts = CASE WHEN login_limits.window_start <= ? THEN 1 ELSE login_limits.attempts + 1 END,
|
||||
window_start = CASE WHEN login_limits.window_start <= ? THEN excluded.window_start ELSE login_limits.window_start END`)
|
||||
.bind(bucket.key, now, now - bucket.span, now - bucket.span).run();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** OAuth and password login share the same trusted-source quota (when configured). */
|
||||
export function consumeLoginSourceAttempt(request: Request): void {
|
||||
consumeLoginAttempt(undefined, loginSourceKey(request));
|
||||
}
|
||||
|
||||
export async function loginWithPassword(usernameInput: unknown, passwordInput: unknown, request?: Request): Promise<{ user: AuthUser; token: string }> {
|
||||
if (typeof usernameInput !== 'string' || typeof passwordInput !== 'string' || !usernameInput.trim() || usernameInput.length > 128 || !passwordInput || passwordInput.length > 128) {
|
||||
throw new AuthError('账号或密码错误。', 401);
|
||||
}
|
||||
const username = usernameInput.trim().toLowerCase();
|
||||
consumeLoginAttempt(username, loginSourceKey(request));
|
||||
const database = getDatabase();
|
||||
const account = database.prepare('SELECT * FROM accounts WHERE username = ?').bind(username).first<AccountRow>();
|
||||
dummyPasswordHash ??= hashPasswordSync('dummy timing password that never authenticates');
|
||||
const valid = await verifyPassword(passwordInput, hasStoredPassword(account?.password_hash) ? account!.password_hash : dummyPasswordHash);
|
||||
// Feishu-only accounts cannot authenticate using the timing dummy password.
|
||||
if (!account || !hasStoredPassword(account.password_hash) || !valid || account.disabled) throw new AuthError('账号或密码错误。', 401);
|
||||
return database.transaction(() => {
|
||||
const current = accountById(account.id);
|
||||
if (!current || current.disabled || current.password_hash !== account.password_hash) throw new AuthError('账号或密码错误。', 401);
|
||||
database.prepare('DELETE FROM login_limits WHERE key = ?').bind(`username:${tokenHash(username)}`).run();
|
||||
database.prepare('UPDATE accounts SET last_login_at = ? WHERE id = ?').bind(new Date().toISOString(), account.id).run();
|
||||
return issueSession(current);
|
||||
});
|
||||
}
|
||||
|
||||
export function revokeSession(token: string | undefined): void {
|
||||
if (token && /^[A-Za-z0-9_-]{43}$/.test(token)) getDatabase().prepare('DELETE FROM sessions WHERE token_hash = ?').bind(tokenHash(token)).run();
|
||||
}
|
||||
|
||||
export async function logoutCurrentSession(): Promise<void> {
|
||||
const { cookies } = await import('next/headers');
|
||||
revokeSession((await cookies()).get(COOKIE_NAME)?.value);
|
||||
}
|
||||
|
||||
export async function changeAccountPassword(userId: string, currentPassword: unknown, newPassword: unknown): Promise<{ user: AuthUser; token: string }> {
|
||||
try { validatePassword(newPassword); } catch (error) { throw new AuthError((error as Error).message); }
|
||||
const current = accountById(userId);
|
||||
if (!current || current.disabled) throw new AuthError('账号已停用,请联系管理员。', 401);
|
||||
if (hasStoredPassword(current.password_hash)) {
|
||||
if (typeof currentPassword !== 'string' || currentPassword.length > 128 || !await verifyPassword(currentPassword, current.password_hash)) throw new AuthError('当前密码不正确。');
|
||||
if (currentPassword === newPassword) throw new AuthError('新密码不能与当前密码相同。');
|
||||
} else if (!getDatabase().prepare('SELECT account_id FROM feishu_identities WHERE account_id = ?').bind(userId).first()) {
|
||||
throw new AuthError('账号缺少可用的登录方式,请联系管理员。', 403);
|
||||
}
|
||||
const passwordHash = await hashPassword(newPassword);
|
||||
return getDatabase().transaction(() => {
|
||||
const fresh = accountById(userId);
|
||||
if (!fresh || fresh.disabled || fresh.password_hash !== current.password_hash) throw new AuthError('账号状态已变化,请重新登录。', 409);
|
||||
getDatabase().prepare('UPDATE accounts SET password_hash = ?, must_change_password = 0, updated_at = ? WHERE id = ?')
|
||||
.bind(passwordHash, new Date().toISOString(), userId).run();
|
||||
getDatabase().prepare('DELETE FROM sessions WHERE account_id = ?').bind(userId).run();
|
||||
return issueSession({ ...fresh, password_hash: passwordHash, must_change_password: 0 });
|
||||
});
|
||||
}
|
||||
|
||||
function activeAdmin(actorId: string): AccountRow {
|
||||
const actor = accountById(actorId);
|
||||
if (!actor || actor.disabled || actor.role !== 'admin' || actor.must_change_password) throw new AuthError('当前账号无权管理用户,请重新登录。', 403);
|
||||
return actor;
|
||||
}
|
||||
|
||||
export function listAccounts(actorId: string): AdminUser[] {
|
||||
activeAdmin(actorId);
|
||||
return getDatabase().prepare('SELECT * FROM accounts ORDER BY created_at ASC, username ASC').all<AccountRow>().results.map(account => ({
|
||||
...publicUser(account), disabled: Boolean(account.disabled), createdAt: account.created_at, lastLoginAt: account.last_login_at,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function createAccount(actorId: string, input: Record<string, unknown>): Promise<AuthUser> {
|
||||
activeAdmin(actorId);
|
||||
let username: string; let displayName: string;
|
||||
try { username = normalizeUsername(input.username); displayName = normalizeDisplayName(input.displayName); validatePassword(input.password); }
|
||||
catch (error) { throw new AuthError((error as Error).message); }
|
||||
if (!['admin', 'user'].includes(String(input.role))) throw new AuthError('账号角色无效。');
|
||||
const passwordHash = await hashPassword(input.password as string);
|
||||
return getDatabase().transaction(() => {
|
||||
activeAdmin(actorId);
|
||||
if (getDatabase().prepare('SELECT id FROM accounts WHERE username = ?').bind(username).first()) throw new AuthError('该账号已存在。', 409);
|
||||
const now = new Date().toISOString();
|
||||
const userId = randomBytes(16).toString('hex');
|
||||
getDatabase().prepare(`INSERT INTO accounts (id, username, display_name, password_hash, role, must_change_password, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, 1, ?, ?)`).bind(userId, username, displayName, passwordHash, input.role as string, now, now).run();
|
||||
return publicUser(accountById(userId)!);
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateAccount(actorId: string, input: Record<string, unknown>): Promise<AuthUser> {
|
||||
activeAdmin(actorId);
|
||||
if (typeof input.id !== 'string' || input.id.length > 128 || !['disable', 'enable', 'reset-password'].includes(String(input.action))) throw new AuthError('账号操作无效。');
|
||||
if (input.id === actorId && ['disable', 'reset-password'].includes(String(input.action))) throw new AuthError('不能停用或重置自己的账号;请使用“修改密码”。');
|
||||
let passwordHash: string | undefined;
|
||||
if (input.action === 'reset-password') {
|
||||
try { validatePassword(input.password); } catch (error) { throw new AuthError((error as Error).message); }
|
||||
passwordHash = await hashPassword(input.password as string);
|
||||
}
|
||||
return getDatabase().transaction(() => {
|
||||
activeAdmin(actorId);
|
||||
const target = accountById(input.id as string);
|
||||
if (!target) throw new AuthError('找不到该账号。', 404);
|
||||
const database = getDatabase();
|
||||
const now = new Date().toISOString();
|
||||
if (input.action === 'disable') {
|
||||
const admins = database.prepare("SELECT COUNT(*) AS count FROM accounts WHERE role = 'admin' AND disabled = 0").first<{ count: number }>()!;
|
||||
if (target.role === 'admin' && !target.disabled && admins.count <= 1) throw new AuthError('必须至少保留一位启用的管理员。', 409);
|
||||
database.prepare('UPDATE accounts SET disabled = 1, updated_at = ? WHERE id = ?').bind(now, target.id).run();
|
||||
} else if (input.action === 'enable') {
|
||||
database.prepare('UPDATE accounts SET disabled = 0, updated_at = ? WHERE id = ?').bind(now, target.id).run();
|
||||
} else {
|
||||
database.prepare('UPDATE accounts SET password_hash = ?, must_change_password = 1, updated_at = ? WHERE id = ?').bind(passwordHash!, now, target.id).run();
|
||||
database.prepare('DELETE FROM login_limits WHERE key = ?').bind(`username:${tokenHash(target.username)}`).run();
|
||||
}
|
||||
if (input.action !== 'enable') database.prepare('DELETE FROM sessions WHERE account_id = ?').bind(target.id).run();
|
||||
return publicUser(accountById(target.id)!);
|
||||
});
|
||||
}
|
||||
|
||||
export function jsonResponse(value: unknown, status = 200, cookie?: string): Response {
|
||||
const headers = new Headers({ 'Cache-Control': 'no-store' });
|
||||
if (cookie) headers.set('Set-Cookie', cookie);
|
||||
return Response.json(value, { status, headers });
|
||||
}
|
||||
export function authFailure(error: unknown): Response {
|
||||
if (error instanceof AuthError) return jsonResponse({ error: error.message }, error.status);
|
||||
console.error('Account operation failed:', error instanceof Error ? error.message : 'Unknown failure');
|
||||
return jsonResponse({ error: '账号服务暂时不可用,请联系管理员或稍后重试。' }, 503);
|
||||
}
|
||||
|
||||
export async function readJsonObject(request: Request): Promise<Record<string, unknown>> {
|
||||
if (!request.headers.get('content-type')?.toLowerCase().startsWith('application/json')) throw new AuthError('请使用 JSON 格式提交。', 415);
|
||||
const reader = request.body?.getReader();
|
||||
if (!reader) throw new AuthError('提交内容不能为空。');
|
||||
const chunks: Uint8Array[] = []; let length = 0;
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
length += value.length;
|
||||
if (length > 8192) { await reader.cancel(); throw new AuthError('提交内容过长。', 413); }
|
||||
chunks.push(value);
|
||||
}
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('Invalid JSON object');
|
||||
return parsed as Record<string, unknown>;
|
||||
} catch { throw new AuthError('提交内容格式无效。'); }
|
||||
}
|
||||
Reference in new issue
Block a user