A local-first multi-agent app development platform, built on PenguinHarness
fix(server): a route group's auth flag means the same wherever the group lands (#793)
lmlihengb9c8d2e063c8
diff --git a/changelog/unreleased/2026-10-12-route-group-auth-per-group.md b/changelog/unreleased/2026-10-12-route-group-auth-per-group.mdnew file mode 100644index 00000000..4de8a5b4--- /dev/null+++ b/changelog/unreleased/2026-10-12-route-group-auth-per-group.md@@ -0,0 +1,24 @@+# A route group's auth flag holds wherever the group is mounted++- **Date:** 2026-10-12+- **Type:** fix+- **Scope:** `server`++[中文版](2026-10-12-route-group-auth-per-group.zh.md)++Ported from upstream PenguinHarness (#793, commit `24abe4ef`).++The platform's HTTP surface mounted its sign-in gate once, on `/api/*`, ahead of the first+protected route group. The gate is now mounted on each protected group's own prefix, so a group's+`auth` flag no longer depends on its `order`.++## Details++- A group contributed with `auth: "none"` under `/api` stays public when it is ordered after a+ protected group. Before, it answered 401 to a request without a session.+- A protected group is gated on its own prefix, the bare prefix included, whether or not the prefix+ is under `/api`. A request whose path passes several protected prefixes is authenticated once.+- A path that no route group serves is declined by the platform and answers 404. Before, such a+ path under `/api` answered 401 to a request without a session.+- In the `GET /api/contributions` response, a contribution's `id` and `from` are always the+ server's own. Before, a contribution whose data carried a field of either name replaced it.diff --git a/changelog/unreleased/2026-10-12-route-group-auth-per-group.zh.md b/changelog/unreleased/2026-10-12-route-group-auth-per-group.zh.mdnew file mode 100644index 00000000..a9891fbe--- /dev/null+++ b/changelog/unreleased/2026-10-12-route-group-auth-per-group.zh.md@@ -0,0 +1,22 @@+# 路由组的 auth 标记不再随挂载位置而变++- **Date:** 2026-10-12+- **Type:** fix+- **Scope:** `server`++[English](2026-10-12-route-group-auth-per-group.md)++移植自上游 PenguinHarness(#793,提交 `24abe4ef`)。++平台的 HTTP 面原先只在第一个受保护路由组之前、于 `/api/*` 上挂一次登录门。现在登录门挂在每个受保护路由组+自己的前缀上,路由组的 `auth` 标记不再取决于它的 `order`。++## 细节++- 以 `auth: "none"` 贡献、位于 `/api` 下的路由组,即使排在受保护路由组之后也保持公开。此前,未登录的请求+ 会得到 401。+- 受保护的路由组在自己的前缀上设门(含前缀本身),无论该前缀是否位于 `/api` 之下。路径经过多个受保护前缀的+ 请求只鉴权一次。+- 没有任何路由组服务的路径由平台拒绝,返回 404。此前,`/api` 下的这类路径对未登录的请求返回 401。+- `GET /api/contributions` 的响应中,每条贡献的 `id` 与 `from` 恒为服务端自己的归属信息。此前,贡献数据中+ 的同名字段会将其覆盖。diff --git a/packages/server/src/http/app.ts b/packages/server/src/http/app.tsindex 39863790..436484c3 100644--- a/packages/server/src/http/app.ts+++ b/packages/server/src/http/app.ts@@ -99,24 +99,21 @@ export class HttpModule {app: c.code as Hono<AppEnv>,})).sort((a, b) => a.order - b.order || a.id.localeCompare(b.id));- let gated = false;+ // Protected routes: cookie -> auth_session -> user. Built once, mounted per group, and+ // run once per request: prefixes nest (/api/projects, /api/projects/:projectId/members),+ // so a request can pass several mounts, and the first is the one that authenticates.+ const authenticate = authMiddleware(this.auth, this.config.trustProxy);+ const gate: MiddlewareHandler<AppEnv> = (c, next) =>+ (c.var.user as AppEnv["Variables"]["user"] | undefined) === undefined+ ? authenticate(c, next)+ : next();for (const r of routes) {- if (r.auth === "user") {- // Protected routes: cookie -> auth_session -> user. /api/* is gated once, ahead of- // the first protected group. A protected group under another prefix — the machine- // proxy at /server/ — is gated on its own prefix: the gate is what puts the user on- // the context, and a handler reading it behind an ungated prefix would throw.- if (!gated) {- app.use("/api/*", authMiddleware(this.auth, this.config.trustProxy));- gated = true;- }- if (!r.prefix.startsWith("/api")) {- app.use(- `${r.prefix.replace(/\/$/, "")}/*`,- authMiddleware(this.auth, this.config.trustProxy),- );- }- }+ // The gate sits on each group that asked for it, not once on `/api/*` ahead of the+ // first such group: a contributor picks its own prefix and order, and `auth` has to+ // mean the same thing wherever the group lands — a public group ordered after a+ // protected one stays public, and a protected group outside /api (the machine proxy+ // at /server/) is still protected. The gate is also what puts the user on the context.+ if (r.auth === "user") app.use(`${r.prefix.replace(/\/$/, "")}/*`, gate);app.route(r.prefix, r.app);}this.http = { fetch: (request: Request) => Promise.resolve(app.fetch(request)) };diff --git a/packages/server/src/http/routes/contributions.ts b/packages/server/src/http/routes/contributions.tsindex a617886d..1f4e0f4a 100644--- a/packages/server/src/http/routes/contributions.ts+++ b/packages/server/src/http/routes/contributions.ts@@ -68,7 +68,9 @@ export class WebModule {setup({ contributions }: ClassCtx) {const collect = (slot: string): WebContribution[] =>(contributions[slot] ?? []).map(- (c) => ({ id: c.id, from: c.from, ...c.data }) as WebContribution,+ // The contribution's own fields first: `id` and `from` are the server's attribution,+ // and a data field of the same name must not replace them.+ (c) => ({ ...c.data, id: c.id, from: c.from }) as WebContribution,);const response: ContributionsResponse = {pages: collect("pages"),diff --git a/packages/server/test/http-route-groups.test.ts b/packages/server/test/http-route-groups.test.tsnew file mode 100644index 00000000..608daf65--- /dev/null+++ b/packages/server/test/http-route-groups.test.ts@@ -0,0 +1,147 @@+/**+ * What a route group's `auth` flag means, wherever the group lands (http/app.ts), and what a+ * web contribution's data may not overwrite (http/routes/contributions.ts). Both modules are+ * wired by hand: the point is the assembly, not the tree around it.+ */+import { describe, expect, it } from "vitest";+import { Hono } from "hono";+import { wire } from "@lmliheng/penguin-core/kernel";+import type { ClassCtx, Contributed } from "@lmliheng/penguin-core/kernel";+import type { AppEnv } from "../src/auth/middleware.js";+import type { UserRow } from "../src/db/repos/users.js";+import { HttpModule } from "../src/http/app.js";+import { WebModule } from "../src/http/routes/contributions.js";+import {+ DEFAULT_ATTACHMENT_MAX_MB,+ DEFAULT_ATTACHMENT_TOTAL_MB,+} from "../src/services/attachment-limits.js";++const TOKEN = "good-token";+const USER = { userId: "u1", isAdmin: false };++interface Group {+ id: string;+ prefix: string;+ auth: "user" | "none";+ order: number;+ /** The one path this group serves; every path under its prefix when omitted. */+ only?: string;+}++/** A group that answers with the user the gate put on the context, or "anonymous". */+function group({ only, ...g }: Group): Contributed {+ const app = new Hono<AppEnv>();+ app.all(only ?? "*", (c) =>+ c.json({ group: g.id, user: (c.var.user as UserRow | undefined)?.userId ?? "anonymous" }),+ );+ const { id, ...data } = g;+ return { id, from: "test", data, code: app };+}++function assemble(groups: Group[]): {+ fetch(path: string, token?: string): Promise<Response>;+ authentications(): number;+} {+ let authentications = 0;+ const http = wire(HttpModule, {+ config: { trustProxy: false },+ log: { line: () => {} },+ auth: {+ sessionTtlMs: 1000,+ authenticateApiToken: (token: string) => {+ authentications += 1;+ return token === TOKEN ? { user: USER, via: "api-token" } : null;+ },+ authenticateWithMeta: () => null,+ },+ errors: { record: () => {} },+ settings: {+ getAttachmentLimitsMb: () => ({+ attachmentMaxMb: DEFAULT_ATTACHMENT_MAX_MB,+ attachmentTotalMb: DEFAULT_ATTACHMENT_TOTAL_MB,+ }),+ },+ access: {},+ });+ http.setup({ contributions: { routes: groups.map(group) } } as unknown as ClassCtx);+ return {+ fetch: (path, token) =>+ http.http.fetch(+ new Request(`http://localhost${path}`, {+ headers: token === undefined ? {} : { authorization: `Bearer ${token}` },+ }),+ ),+ authentications: () => authentications,+ };+}++describe("a route group's auth flag", () => {+ it("leaves a public /api group public when it is ordered after a protected one", async () => {+ const app = assemble([+ { id: "members", prefix: "/api/members", auth: "user", order: 10 },+ { id: "webhook", prefix: "/api/webhook", auth: "none", order: 500 },+ ]);++ const res = await app.fetch("/api/webhook/incoming");+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ group: "webhook", user: "anonymous" });+ });++ it("protects a group on its own prefix, the bare prefix included", async () => {+ const app = assemble([{ id: "members", prefix: "/api/members", auth: "user", order: 10 }]);++ expect((await app.fetch("/api/members")).status).toBe(401);+ expect((await app.fetch("/api/members/u2")).status).toBe(401);+ expect((await app.fetch("/api/members/u2", "wrong")).status).toBe(401);+ const res = await app.fetch("/api/members/u2", TOKEN);+ expect(await res.json()).toEqual({ group: "members", user: "u1" });+ });++ it("protects a group outside /api", async () => {+ const app = assemble([{ id: "proxy", prefix: "/server/", auth: "user", order: 51 }]);++ expect((await app.fetch("/server/m1/api/me")).status).toBe(401);+ expect((await app.fetch("/server/m1/api/me", TOKEN)).status).toBe(200);+ });++ it("authenticates once per request however many protected prefixes the path passes", async () => {+ const app = assemble([+ // The outer group serves its root alone, so the nested path passes its gate and goes on.+ { id: "projects", prefix: "/api/projects", auth: "user", order: 80, only: "/" },+ { id: "members", prefix: "/api/projects/:projectId/members", auth: "user", order: 90 },+ ]);++ const res = await app.fetch("/api/projects/p1/members", TOKEN);+ expect(await res.json()).toEqual({ group: "members", user: "u1" });+ expect(app.authentications()).toBe(1);+ });++ it("declines a path no group serves, instead of answering for it", async () => {+ const app = assemble([{ id: "members", prefix: "/api/members", auth: "user", order: 10 }]);++ const res = await app.fetch("/api/nothing-here");+ expect(res.status).toBe(404);+ expect(res.headers.get("x-penguin-platform-decline")).not.toBeNull();+ });+});++describe("a web contribution", () => {+ it("keeps the server's id and from over data fields of the same name", () => {+ const web = wire(WebModule, {});+ web.setup({+ contributions: {+ pages: [+ {+ id: "plugin.page",+ from: "PluginModule",+ data: { id: "forged", from: "HttpModule", key: "p", path: "/p" },+ },+ ],+ },+ } as unknown as ClassCtx);++ expect(web.web.contributions().pages).toEqual([+ { id: "plugin.page", from: "PluginModule", key: "p", path: "/p" },+ ]);+ });+});