import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; import { basePath } from '../base-path.ts'; import { safeReturnTo } from '../auth-return.ts'; import type { FeishuBinding } from '../feishu.ts'; import { applicationOrigin, getDatabase } from './database.ts'; import { AuthError, authenticateSession, consumeLoginSourceAttempt, hasAccountPassword, issueIdentitySession, loginWithPassword, revokeSession, type AuthUser } from './auth.ts'; import { feishuJson, feishuLoginConfig } from './feishu-config.ts'; import { PASSWORD_LOGIN_DISABLED } from './password.ts'; const STATE_SECONDS = 600; const STATE_COOKIE = 'demand_feishu_state'; const hash = (value: string) => createHash('sha256').update(value).digest('hex'); type StateRow = { browser_hash: string; account_id: string | null; session_hash: string | null; app_id: string; verifier: string; return_to: string; expires_at: number }; type Identity = { openId: string; tenantKey: string; name: string }; export class FeishuAuthError extends Error { code: string; constructor(code: string) { super(code); this.code = code; } } export function requestCookie(request: Request, name: string): string { return request.headers.get('cookie')?.split(';').map(part => part.trim()).find(part => part.startsWith(name + '='))?.slice(name.length + 1) || ''; } export function feishuStateCookie(token: string): string { return `${STATE_COOKIE}=${token}; Path=${basePath || '/'}; HttpOnly; SameSite=Lax; Max-Age=${token ? STATE_SECONDS : 0}${applicationOrigin().startsWith('https://') ? '; Secure' : ''}`; } export function beginFeishuAuth(request: Request, intent: string, returnTo: unknown) { let config; try { config = feishuLoginConfig(); } catch { throw new FeishuAuthError('unavailable'); } if (!['login', 'bind'].includes(intent)) throw new FeishuAuthError('failed'); const session = requestCookie(request, 'demand_session'); const user = authenticateSession(session); if (intent === 'bind' && (!user || user.mustChangePassword)) throw new FeishuAuthError('session'); consumeLoginSourceAttempt(request); const state = randomBytes(32).toString('base64url'); const browser = randomBytes(32).toString('base64url'); const verifier = randomBytes(32).toString('base64url'); const db = getDatabase(); db.transaction(() => { db.prepare('DELETE FROM feishu_oauth_states WHERE expires_at <= ?').bind(Date.now()).run(); // A new attempt replaces the previous attempt in this browser. const previous = requestCookie(request, STATE_COOKIE); if (previous) db.prepare('DELETE FROM feishu_oauth_states WHERE browser_hash = ?').bind(hash(previous)).run(); db.prepare(`INSERT INTO feishu_oauth_states (state_hash, browser_hash, account_id, session_hash, app_id, verifier, return_to, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).bind(hash(state), hash(browser), intent === 'bind' ? user!.userId : null, intent === 'bind' ? hash(session) : null, config.appId, verifier, safeReturnTo(returnTo), Date.now() + STATE_SECONDS * 1000).run(); }); const url = new URL('https://accounts.feishu.cn/open-apis/authen/v1/authorize'); url.search = new URLSearchParams({ client_id: config.appId, response_type: 'code', redirect_uri: config.callbackUrl, state, code_challenge: createHash('sha256').update(verifier).digest('base64url'), code_challenge_method: 'S256' }).toString(); if (intent === 'bind') url.searchParams.set('prompt', 'consent'); return { url: url.href, cookie: feishuStateCookie(browser) }; } export function consumeFeishuState(request: Request): StateRow { const state = new URL(request.url).searchParams.get('state') || ''; const browser = requestCookie(request, STATE_COOKIE); if (![state, browser].every(value => /^[A-Za-z0-9_-]{43}$/.test(value))) throw new FeishuAuthError('expired'); return getDatabase().transaction(() => { const row = getDatabase().prepare('SELECT * FROM feishu_oauth_states WHERE state_hash = ?').bind(hash(state)).first(); if (!row || row.expires_at <= Date.now() || !timingSafeEqual(Buffer.from(row.browser_hash), Buffer.from(hash(browser)))) throw new FeishuAuthError('expired'); getDatabase().prepare('DELETE FROM feishu_oauth_states WHERE state_hash = ?').bind(hash(state)).run(); return row; }); } async function exchangeIdentity(code: string, verifier: string): Promise { const config = feishuLoginConfig(); // The authorize endpoint's PKCE documentation currently pairs it with v2. // v3 rejected the live app's valid S256 flow with 20049; keep PKCE and use the documented pair. const token = await feishuJson('https://open.feishu.cn/open-apis/authen/v2/oauth/token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ grant_type: 'authorization_code', client_id: config.appId, client_secret: config.secret, code, redirect_uri: config.callbackUrl, code_verifier: verifier }), }); if (token.code !== undefined && token.code !== 0) throw new FeishuAuthError('failed'); if (typeof token.access_token !== 'string' || !token.access_token) { console.error('Feishu identity failure', { stage: 'oauth-token', reason: 'missing-access-token' }); throw new FeishuAuthError('failed'); } const info = await feishuJson('https://open.feishu.cn/open-apis/authen/v1/user_info', { headers: { Authorization: `Bearer ${token.access_token}` } }); const data = info.data as Record | undefined; if (info.code !== 0) throw new FeishuAuthError('failed'); const invalidFields = ['open_id', 'tenant_key', 'name'].filter(field => typeof data?.[field] !== 'string' || (data[field] as string).length > 256 || (field !== 'name' && !data[field])); if (!data || invalidFields.length) { console.error('Feishu identity failure', { stage: 'user-info', invalidFields }); throw new FeishuAuthError('failed'); } if (config.tenantKey && data.tenant_key !== config.tenantKey) throw new FeishuAuthError('tenant'); return { openId: data.open_id as string, tenantKey: data.tenant_key as string, name: data.name as string }; } function bindingUser(request: Request, state: StateRow): AuthUser { const session = requestCookie(request, 'demand_session'); const current = authenticateSession(session); if (!current || current.mustChangePassword || current.userId !== state.account_id || hash(session) !== state.session_hash) throw new FeishuAuthError('session'); return current; } /** Called inside the identity lookup transaction; roles and usernames never come from browser input. */ function registerFeishuAccount(appId: string, identity: Identity): string { const db = getDatabase(); const id = randomBytes(16).toString('hex'); const now = new Date().toISOString(); const displayName = identity.name.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 80) || '飞书成员'; db.prepare(`INSERT INTO accounts (id, username, display_name, password_hash, role, must_change_password, created_at, updated_at) VALUES (?, ?, ?, ?, 'user', 0, ?, ?)`).bind(id, `feishu_${id}`, displayName, PASSWORD_LOGIN_DISABLED, now, now).run(); db.prepare('INSERT INTO feishu_identities (account_id, app_id, tenant_key, open_id, name, bound_at) VALUES (?, ?, ?, ?, ?, ?)') .bind(id, appId, identity.tenantKey, identity.openId, identity.name, now).run(); return id; } export async function completeFeishuAuth(request: Request, state: StateRow) { if (state.app_id !== feishuLoginConfig().appId) throw new FeishuAuthError('expired'); if (state.account_id) bindingUser(request, state); const params = new URL(request.url).searchParams; if (params.has('error')) throw new FeishuAuthError('denied'); const code = params.get('code'); if (!code || code.length > 2048) throw new FeishuAuthError('failed'); const identity = await exchangeIdentity(code, state.verifier); return getDatabase().transaction(() => { const db = getDatabase(); const bound = db.prepare('SELECT account_id FROM feishu_identities WHERE app_id = ? AND tenant_key = ? AND open_id = ?') .bind(state.app_id, identity.tenantKey, identity.openId).first<{ account_id: string }>(); if (state.account_id) { const user = bindingUser(request, state); // Recheck after the network call, including reset/disable/logout. const existing = db.prepare('SELECT account_id FROM feishu_identities WHERE account_id = ?').bind(user.userId).first(); if ((bound && bound.account_id !== user.userId) || (existing && !bound)) throw new FeishuAuthError('conflict'); if (!bound) db.prepare('INSERT INTO feishu_identities (account_id, app_id, tenant_key, open_id, name, bound_at) VALUES (?, ?, ?, ?, ?, ?)') .bind(user.userId, state.app_id, identity.tenantKey, identity.openId, identity.name, new Date().toISOString()).run(); return { bound: true as const, returnTo: '/account/feishu', token: null, user }; } const accountId = bound?.account_id ?? registerFeishuAccount(state.app_id, identity); const result = issueIdentitySession(accountId); revokeSession(requestCookie(request, 'demand_session')); return { bound: false as const, returnTo: result.user.mustChangePassword ? '/account/password' : state.return_to, ...result }; }); } export function getFeishuBinding(accountId: string): FeishuBinding { const row = getDatabase().prepare('SELECT name, bound_at AS boundAt FROM feishu_identities WHERE account_id = ?').bind(accountId).first>(); return row ? { ...row } : null; } export async function unbindFeishu(user: AuthUser, password: unknown, request: Request) { if (!hasAccountPassword(user.userId)) throw new AuthError('请先设置系统密码,再解除飞书绑定。', 409); const verified = await loginWithPassword(user.username, password, request); revokeSession(verified.token); return getDatabase().transaction(() => { if (authenticateSession(requestCookie(request, 'demand_session'))?.userId !== user.userId || verified.user.userId !== user.userId) { throw new AuthError('登录状态已变化,请重新登录。', 401); } getDatabase().prepare('DELETE FROM feishu_identities WHERE account_id = ?').bind(user.userId).run(); getDatabase().prepare('DELETE FROM feishu_oauth_states WHERE account_id = ?').bind(user.userId).run(); getDatabase().prepare('DELETE FROM sessions WHERE account_id = ?').bind(user.userId).run(); return issueIdentitySession(user.userId); }); }