Files
sprout2fa/src/worker/index.ts
2026-06-24 22:10:27 +08:00

55 lines
1.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Hono } from 'hono';
import { verifySessionToken } from './middleware/session';
import { registerAuthRoutes } from './routes/auth';
import { registerAccountRoutes } from './routes/accounts';
import { registerImportExportRoutes } from './routes/importExport';
import { registerShareRoutes } from './routes/share';
const app = new Hono<{ Bindings: Env }>();
app.onError((err, c) => {
console.error('[sprout2fa] unhandled', err);
return c.json(
{ error: err instanceof Error ? err.message : '服务器错误' },
500,
);
});
// 必须先注册更具体的前缀 /api/auth避免被 /api 子应用吞掉
const apiAuth = new Hono<{ Bindings: Env }>();
registerAuthRoutes(apiAuth);
app.route('/api/auth', apiAuth);
const apiShare = new Hono<{ Bindings: Env }>();
registerShareRoutes(apiShare);
app.route('/api/share', apiShare);
const authed = new Hono<{ Bindings: Env }>();
authed.use('*', async (c, next) => {
const ok = await verifySessionToken(
c.env.SESSION_SECRET,
c.req.header('Cookie') ?? null,
);
if (!ok) {
return c.json({ error: '未授权' }, 401);
}
await next();
});
registerAccountRoutes(authed);
registerImportExportRoutes(authed);
app.route('/api', authed);
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext,
): Promise<Response> {
const url = new URL(request.url);
if (url.pathname.startsWith('/api')) {
return app.fetch(request, env, ctx);
}
return env.ASSETS.fetch(request);
},
};