Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): middleware adapted for D1/Better Auth

Gener66a033b9c8c8
diff --git a/src/web/src/lib/middleware/auth.ts b/src/web/src/lib/middleware/auth.ts
new file mode 100644
index 000000000..2be589818
--- /dev/null
+++ b/src/web/src/lib/middleware/auth.ts
@@ -0,0 +1,76 @@
+import { NextRequest, NextResponse } from "next/server"
+import { getCloudflareContext } from "@opennextjs/cloudflare"
+import { createDb, queries } from "@alook/shared"
+import { createAuth } from "@/lib/auth"
+import { createHash } from "crypto"
+
+export interface AuthContext {
+ userId: string
+ email: string
+ workspaceId?: string
+}
+
+export type AuthenticatedHandler = (
+ req: NextRequest,
+ ctx: AuthContext & { params?: Record<string, string> }
+) => Promise<NextResponse | Response>
+
+function hashToken(raw: string): string {
+ return createHash("sha256").update(raw).digest("hex")
+}
+
+export function withAuth(handler: AuthenticatedHandler) {
+ return async (
+ req: NextRequest,
+ context?: { params?: Promise<Record<string, string>> | Record<string, string> }
+ ) => {
+ const resolvedParams = context?.params
+ ? context.params instanceof Promise
+ ? await context.params
+ : context.params
+ : undefined
+
+ const { env } = await getCloudflareContext({ async: true })
+ const cloudflareEnv = env as Env
+
+ const authHeader = req.headers.get("Authorization")
+ if (authHeader?.startsWith("Bearer ")) {
+ const token = authHeader.slice(7)
+ if (token.startsWith("al_")) {
+ try {
+ const db = createDb(cloudflareEnv.DB)
+ const hashed = hashToken(token)
+ const mt = await queries.machineToken.getMachineTokenByHash(db, hashed)
+ if (!mt) {
+ return NextResponse.json({ error: "invalid token" }, { status: 401 })
+ }
+ queries.machineToken.updateMachineTokenLastUsed(db, mt.id).catch(() => {})
+ const authCtx: AuthContext = {
+ userId: mt.userId,
+ email: mt.userEmail,
+ workspaceId: mt.workspaceId ?? undefined,
+ }
+ return handler(req, { ...authCtx, params: resolvedParams })
+ } catch {
+ return NextResponse.json({ error: "invalid token" }, { status: 401 })
+ }
+ }
+ }
+
+ // Fall back to Better Auth session
+ try {
+ const auth = createAuth(cloudflareEnv)
+ const session = await auth.api.getSession({ headers: req.headers })
+ if (!session) {
+ return NextResponse.json({ error: "unauthorized" }, { status: 401 })
+ }
+ const authCtx: AuthContext = {
+ userId: session.user.id,
+ email: session.user.email,
+ }
+ return handler(req, { ...authCtx, params: resolvedParams })
+ } catch {
+ return NextResponse.json({ error: "unauthorized" }, { status: 401 })
+ }
+ }
+}
diff --git a/src/web/src/lib/middleware/helpers.ts b/src/web/src/lib/middleware/helpers.ts
new file mode 100644
index 000000000..ecb398955
--- /dev/null
+++ b/src/web/src/lib/middleware/helpers.ts
@@ -0,0 +1,57 @@
+import { NextResponse } from "next/server";
+
+export function writeJSON(data: unknown, status = 200): NextResponse {
+ return NextResponse.json(data, { status });
+}
+
+export function writeError(message: string, status: number): NextResponse {
+ return NextResponse.json({ error: message }, { status });
+}
+
+/** Format a Date or ISO string as RFC 3339 without sub-second precision (matching Go output). */
+export function formatTimestamp(date: Date | string | null): string {
+ if (!date) return "";
+ const d = typeof date === "string" ? new Date(date) : date;
+ return d.toISOString().replace(/\.\d{3}Z$/, "Z");
+}
+
+/**
+ * Parse and validate a JSON request body against a Zod schema.
+ * Returns [data, null] on success or [null, 400 response] on failure.
+ */
+export async function parseBody<T>(
+ req: Request,
+ schema: { parse(data: unknown): T },
+): Promise<[T, null] | [null, NextResponse]> {
+ let raw: unknown;
+ try {
+ raw = await req.json();
+ } catch {
+ return [null, writeError("invalid request body", 400)];
+ }
+ try {
+ const data = schema.parse(raw);
+ return [data, null];
+ } catch (err: unknown) {
+ const e = err as Record<string, unknown>;
+ const issues: { path: (string | number)[]; message: string }[] =
+ (e.issues ?? e.errors ?? []) as { path: (string | number)[]; message: string }[];
+ const fields = issues.map(
+ (e) => `${e.path.join(".")}: ${e.message}`,
+ );
+ return [
+ null,
+ NextResponse.json(
+ { error: "validation error", details: fields },
+ { status: 400 },
+ ),
+ ];
+ }
+}
+
+/** Same as formatTimestamp but returns null instead of empty string. */
+export function formatTimestampNullable(date: Date | string | null): string | null {
+ if (!date) return null;
+ const d = typeof date === "string" ? new Date(date) : date;
+ return d.toISOString().replace(/\.\d{3}Z$/, "Z");
+}
diff --git a/src/web/src/lib/middleware/request-id.ts b/src/web/src/lib/middleware/request-id.ts
new file mode 100644
index 000000000..299afb44c
--- /dev/null
+++ b/src/web/src/lib/middleware/request-id.ts
@@ -0,0 +1,14 @@
+import { NextResponse } from "next/server";
+import { randomUUID } from "crypto";
+
+export function getRequestId(req: Request): string {
+ return req.headers.get("X-Request-ID") || randomUUID();
+}
+
+export function setRequestIdHeader(
+ response: NextResponse,
+ requestId: string
+): NextResponse {
+ response.headers.set("X-Request-ID", requestId);
+ return response;
+}
diff --git a/src/web/src/lib/middleware/request-logger.ts b/src/web/src/lib/middleware/request-logger.ts
new file mode 100644
index 000000000..b3ac648ba
--- /dev/null
+++ b/src/web/src/lib/middleware/request-logger.ts
@@ -0,0 +1,25 @@
+import { log } from "../logger";
+
+export function logRequest(
+ method: string,
+ path: string,
+ status: number,
+ durationMs: number,
+ requestId?: string,
+ userId?: string
+): void {
+ if (path === "/health" || path === "/api/health") return;
+
+ const ctx: Record<string, unknown> = {
+ method,
+ path,
+ status,
+ duration: `${durationMs}ms`,
+ };
+ if (requestId) ctx.request_id = requestId;
+ if (userId) ctx.user_id = userId;
+
+ if (status >= 500) log.error("http request", ctx);
+ else if (status >= 400) log.warn("http request", ctx);
+ else log.info("http request", ctx);
+}
diff --git a/src/web/src/lib/middleware/workspace.ts b/src/web/src/lib/middleware/workspace.ts
new file mode 100644
index 000000000..43b12151a
--- /dev/null
+++ b/src/web/src/lib/middleware/workspace.ts
@@ -0,0 +1,49 @@
+import { NextRequest, NextResponse } from "next/server"
+import { getCloudflareContext } from "@opennextjs/cloudflare"
+import { createDb, queries } from "@alook/shared"
+import type { AuthContext } from "./auth"
+
+export interface WorkspaceContext extends AuthContext {
+ workspaceId: string
+}
+
+export async function withWorkspaceMember(
+ req: NextRequest,
+ auth: AuthContext
+): Promise<{ workspaceId: string } | NextResponse> {
+ const workspaceId =
+ req.nextUrl.searchParams.get("workspace_id") ||
+ req.headers.get("X-Workspace-ID") ||
+ auth.workspaceId
+
+ if (!workspaceId) {
+ return NextResponse.json(
+ { error: "workspace_id is required" },
+ { status: 400 }
+ )
+ }
+
+ if (!auth.userId) {
+ return NextResponse.json(
+ { error: "user not authenticated" },
+ { status: 401 }
+ )
+ }
+
+ const { env } = await getCloudflareContext({ async: true })
+ const db = createDb((env as Env).DB)
+
+ const membership = await queries.member.getMemberByUserAndWorkspace(
+ db,
+ auth.userId,
+ workspaceId
+ )
+ if (!membership) {
+ return NextResponse.json(
+ { error: "workspace not found" },
+ { status: 404 }
+ )
+ }
+
+ return { workspaceId }
+}