Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(server,web): a rejected sign-in link lands on the login page, not on raw JSON (#690)

Yaowei Zheng086a3401ab54
diff --git a/changelog/unreleased/2026-09-11-claim-link-failure.md b/changelog/unreleased/2026-09-11-claim-link-failure.md
new file mode 100644
index 00000000..386ca442
--- /dev/null
+++ b/changelog/unreleased/2026-09-11-claim-link-failure.md
@@ -0,0 +1,25 @@
+# A used-up sign-in link lands on the login page instead of a JSON error
+
+- **Date:** 2026-09-11
+- **Type:** fix
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#690](https://github.com/Prism-Shadow/penguin-harness/pull/690)
+
+[中文版](2026-09-11-claim-link-failure.zh.md)
+
+Opening a one-time sign-in link that had already been used, or had expired, answered the
+browser with `{"error":{"code":"unauthorized",…}}` and left the visitor on a page of raw JSON
+with nothing to act on. `GET /api/auth/claim` now redirects such a claim to `/login`, where
+the Web App raises a dialog over the ordinary sign-in form explaining what happened and how to
+get a working link.
+
+## Details
+
+- The redirect carries `?claimFailed=desktop` or `?claimFailed=server`, decided by whether the
+ server was started by the desktop shell. The desktop copy says to restart the app, which
+ issues a fresh link and signs the window in; the server copy points at the password form and
+ at whoever runs the server. Both token kinds — the shell's one-shot token and the first-login
+ link — still produce byte-identical refusals on a given server.
+- The login page clears the parameter with a history replace once the dialog is up, so a reload
+ does not raise it again and a copied address does not carry it.
+- `server-api` documents the failure redirect alongside the success one.
diff --git a/changelog/unreleased/2026-09-11-claim-link-failure.zh.md b/changelog/unreleased/2026-09-11-claim-link-failure.zh.md
new file mode 100644
index 00000000..475a0c4a
--- /dev/null
+++ b/changelog/unreleased/2026-09-11-claim-link-failure.zh.md
@@ -0,0 +1,20 @@
+# 用过的一次性登录链接回到登录页,不再甩出 JSON 报错
+
+- **Date:** 2026-09-11
+- **Type:** fix
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#690](https://github.com/Prism-Shadow/penguin-harness/pull/690)
+
+[English](2026-09-11-claim-link-failure.md)
+
+打开一条已被使用或已失效的一次性登录链接时,浏览器收到的是 `{"error":{"code":"unauthorized",…}}`,
+用户停在一页原始 JSON 上,无从下手。`GET /api/auth/claim` 现在把这类兑换重定向到 `/login`,Web App
+在常规登录表单之上弹出对话框,说明发生了什么、以及如何拿到可用的链接。
+
+## 细节
+
+- 重定向带上 `?claimFailed=desktop` 或 `?claimFailed=server`,取值由服务端是否由桌面壳拉起决定。桌面
+ 文案让用户重启应用——重启即生成新链接并自动登录;服务端文案指向下方的账号密码表单与服务器管理员。
+ 两种 token(壳的一次性 token 与首次登录链接)在同一服务端上的拒绝答复仍然逐字节相同。
+- 登录页在弹出对话框后以一次 history replace 清掉该参数:刷新不会再次弹出,复制出去的地址也不带它。
+- `server-api` 文档在成功路径之外补记了失败重定向。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 2e5f1e27..97e6ddee 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -68,7 +68,7 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
| --- | --- | --- |
| POST | /api/auth/login | Log in: `{userId, password}` → `{user}` |
| POST | /api/auth/logout | Log out, returns 204 |
-| GET | /api/auth/claim?token=… | Redeem a sign-in link (first-login, or the desktop shell's one-shot token): sets the cookie, redirects to `/` |
+| GET | /api/auth/claim?token=… | Redeem a sign-in link (first-login, or the desktop shell's one-shot token): sets the cookie, redirects to `/`. An invalid or already-used link redirects to `/login?claimFailed=…` instead, where the Web App says how to get a working one |
| GET | /api/install | Public: `{installId}` — an opaque id identifying the data root being served (`<root>/install-id`), minted the first time the root is used. The Web App compares it against the one it stored and clears the browser-side UI state that references server entities when it differs, so replacing the data root no longer leaves the old Workspace, drafts and pins in place. `null` means the server could not establish one; clients must then change nothing. |
| GET | /api/me | Current user info |
| PUT | /api/me/password | Change password: `{oldPassword, newPassword}`; a desktop or first-login session may omit `oldPassword` — its current password is random and was never shown |
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index bae307d3..8f281949 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -68,7 +68,7 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
| --- | --- | --- |
| POST | /api/auth/login | 登录:`{userId, password}` → `{user}` |
| POST | /api/auth/logout | 退出登录,返回 204 |
-| GET | /api/auth/claim?token=… | 兑换登录链接(首次登录链接,或桌面 shell 的一次性 token):种下 Cookie 并跳转到 `/` |
+| GET | /api/auth/claim?token=… | 兑换登录链接(首次登录链接,或桌面 shell 的一次性 token):种下 Cookie 并跳转到 `/`;链接无效或已被使用时改为跳转 `/login?claimFailed=…`,由 Web App 说明如何获取新链接 |
| GET | /api/install | 公开:`{installId}`——标识当前所服务数据根的不透明 id(`<root>/install-id`),在该根首次被使用时铸造。Web App 将其与自己存下的值比较,不一致时清除浏览器侧那些引用服务端实体的 UI 状态,因此更换数据根后不会再留下旧的 Workspace、草稿与置顶。`null` 表示服务端无法确定该 id,此时客户端不应改动任何内容。 |
| GET | /api/me | 当前用户信息 |
| PUT | /api/me/password | 修改密码:`{oldPassword, newPassword}`;桌面会话与首次登录会话可省略 `oldPassword`——其当前密码是随机生成且从未展示过的 |
diff --git a/packages/server/src/http/routes/auth.ts b/packages/server/src/http/routes/auth.ts
index 289dd834..121e4b36 100644
--- a/packages/server/src/http/routes/auth.ts
+++ b/packages/server/src/http/routes/auth.ts
@@ -9,7 +9,6 @@
import { Hono } from "hono";
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
import type { AuthResponse } from "../../api/types.js";
-import { HttpError } from "../errors.js";
import { SESSION_COOKIE, cookieOptions } from "../../auth/middleware.js";
import type { AppEnv } from "../../auth/middleware.js";
import { readJson, requireString } from "../validate.js";
@@ -43,7 +42,7 @@ export function authRoutes(deps: AppDeps): Hono<AppEnv> {
* Two proofs, expiring differently: the desktop shell's token is spent on first use, while
* the first-login link keeps working until a password exists — a link a mail client may
* prefetch cannot afford to be one-shot, and until then the account protects nothing.
- * Both fail with the same 401, so a caller learns nothing about which it got wrong.
+ * Both fail with the same redirect, so a caller learns nothing about which it got wrong.
*/
app.get("/claim", (c) => {
const token = c.req.query("token") ?? "";
@@ -53,9 +52,17 @@ export function authRoutes(deps: AppDeps): Hono<AppEnv> {
token !== "" && deps.desktop?.redeemLoginToken(token) === true
? deps.authService.loginDesktop().token
: deps.authService.redeemFirstLogin(token);
- if (session === null) {
- throw new HttpError(401, "unauthorized", "Invalid or already-used sign-in link.");
- }
+ // A browser is at the other end of this navigation, so the refusal answers a browser
+ // too: an error body would leave the visitor staring at raw JSON with nothing to act
+ // on. The login page takes it from here, form included. The advice it reads out of
+ // `claimFailed` describes the DEPLOYMENT, never the token: a desktop shell mints a fresh
+ // link on every start, so restarting the app is the way back in, while anywhere else the
+ // link has to come from whoever runs the server and restarting helps nobody. Every token
+ // a given server rejects yields the same value, so the refusal still says nothing about
+ // which kind was presented — only that a shell is attached, which is a property of how
+ // the server was started rather than of the credential.
+ if (session === null)
+ return c.redirect(`/login?claimFailed=${deps.desktop !== null ? "desktop" : "server"}`, 302);
setCookie(
c,
SESSION_COOKIE,
diff --git a/packages/server/test/desktop.test.ts b/packages/server/test/desktop.test.ts
index a3281e03..101e8547 100644
--- a/packages/server/test/desktop.test.ts
+++ b/packages/server/test/desktop.test.ts
@@ -15,7 +15,14 @@ import {
import type { ErrorBody, MeResponse } from "../src/api/types.js";
describe("desktop claim", () => {
- it("redeems the token once: cookie session, redirect to /, second attempt 401", async () => {
+ /** What a browser gets for a token this server will not honour: the login page, plus the advice it can give there. */
+ function expectRefusal(res: Response, advice: "desktop" | "server"): void {
+ expect(res.status).toBe(302);
+ expect(res.headers.get("location")).toBe(`/login?claimFailed=${advice}`);
+ expect(res.headers.get("set-cookie")).toBeNull();
+ }
+
+ it("redeems the token once: cookie session, redirect to /, a replay back to the login page", async () => {
const t = await createDesktopApp();
try {
const res = await t.app.request(`/api/auth/claim?token=${TEST_DESKTOP_TOKEN}`);
@@ -33,7 +40,7 @@ describe("desktop claim", () => {
expect(body.desktopMode).toBe(true);
const replay = await t.app.request(`/api/auth/claim?token=${TEST_DESKTOP_TOKEN}`);
- expect(replay.status).toBe(401);
+ expectRefusal(replay, "desktop");
} finally {
await t.cleanup();
}
@@ -42,8 +49,8 @@ describe("desktop claim", () => {
it("rejects a wrong or missing token without consuming the real one", async () => {
const t = await createDesktopApp();
try {
- expect((await t.app.request("/api/auth/claim?token=wrong")).status).toBe(401);
- expect((await t.app.request("/api/auth/claim")).status).toBe(401);
+ expectRefusal(await t.app.request("/api/auth/claim?token=wrong"), "desktop");
+ expectRefusal(await t.app.request("/api/auth/claim"), "desktop");
// The real token still works after failed attempts.
expect((await t.app.request(`/api/auth/claim?token=${TEST_DESKTOP_TOKEN}`)).status).toBe(302);
} finally {
@@ -54,10 +61,11 @@ describe("desktop claim", () => {
it("refuses a desktop token outside desktop mode, and /api/me reports desktopMode false", async () => {
const t = await createTestApp();
try {
- // The claim route serves the first-login link too, so it exists in every mode. A
- // server with no shell has no shell token to honour, and says so as 401 — the same
- // answer any wrong value gets, so the reply does not report which modes are enabled.
- expect((await t.app.request("/api/auth/claim?token=x")).status).toBe(401);
+ // The claim route serves the first-login link too, so it exists in every mode. A server
+ // with no shell has no shell token to honour, and refuses this one the way it refuses
+ // every other wrong value here — pointing at the only advice it can give, since no
+ // restart of anything on this machine would produce a link.
+ expectRefusal(await t.app.request("/api/auth/claim?token=x"), "server");
const admin = await loginAdmin(t.app);
const me = await apiClient(t.app, admin.cookie).get("/api/me");
expect(((await me.json()) as MeResponse).desktopMode).toBe(false);
diff --git a/packages/server/test/first-login.test.ts b/packages/server/test/first-login.test.ts
index 23cb021d..3f18c5a9 100644
--- a/packages/server/test/first-login.test.ts
+++ b/packages/server/test/first-login.test.ts
@@ -33,6 +33,17 @@ describe("the first-login link", () => {
redirect: "manual",
});
+ /**
+ * What a browser gets for a link that no longer works: back to the login page, carrying the
+ * advice this deployment can give (no shell here, so a new link comes from whoever runs the
+ * server), and no session.
+ */
+ function expectRefusal(res: Response): void {
+ expect(res.status).toBe(302);
+ expect(res.headers.get("location")).toBe("/login?claimFailed=server");
+ expect(res.headers.get("set-cookie")).toBeNull();
+ }
+
it("claims an unclaimed server, with a session that may set a password but is not desktop", async () => {
const res = await redeem(link);
expect(res.status).toBe(302);
@@ -57,7 +68,7 @@ describe("the first-login link", () => {
expect(t.deps.authService.adminPasswordIsInitial()).toBe(false);
// Claimed: a console scrollback is not a way in.
- expect((await redeem(link)).status).toBe(401);
+ expectRefusal(await redeem(link));
});
it("refuses any token but the printed one, and says nothing about which it got", async () => {
@@ -67,8 +78,9 @@ describe("the first-login link", () => {
const someoneElse = (await loginAdmin(t.app)).cookie.split("=").slice(1).join("=");
const other = await redeem(someoneElse);
const wrong = await redeem("not-the-token");
- expect([other.status, wrong.status]).toEqual([401, 401]);
- expect(await other.text()).toBe(await wrong.text());
+ expectRefusal(other);
+ expectRefusal(wrong);
+ expect(other.headers.get("location")).toBe(wrong.headers.get("location"));
});
/**
@@ -279,7 +291,7 @@ describe("the first-login link", () => {
const res = await second.app.request("/api/auth/claim?token=anything", {
redirect: "manual",
});
- expect(res.status).toBe(401);
+ expectRefusal(res);
} finally {
await second.cleanup();
}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index bb72b7fe..a6dc00ae 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -348,6 +348,8 @@ export const en: Strings = {
edit: "Edit",
settings: "Settings",
confirm: "Confirm",
+ /** Sole button of a dialog that only informs: it has nothing to confirm or cancel, so the label acknowledges rather than agrees (and does not repeat the header X's "close"). */
+ gotIt: "Got it",
loading: "Loading…",
saved: "Saved",
saving: "Saving…",
@@ -390,6 +392,14 @@ export const en: Strings = {
/** Login footer line 2: the offline rescue for a forgotten admin password (other users ask the admin instead). */
forgotAdminNote:
"Forgot the admin password? Stop the server and run penguin server reset-admin-password to issue a fresh initial one",
+ /** Dialog raised over the login form when the server refused a sign-in link (spent, expired, or never valid). */
+ claimFailedTitle: "Sign-in link no longer works",
+ /** Desktop deployment: the shell mints a fresh link every time it starts, so restarting it is the way back in. */
+ claimFailedDesktop:
+ "This one-time sign-in link has already been used or has expired. Restart the PenguinHarness desktop app to get a fresh link and be signed in automatically, or sign in with your username and password below.",
+ /** Everywhere else: nobody at this browser can mint a link, so the way in is the form below or whoever runs the server. */
+ claimFailedServer:
+ "The first-login link stops working once the server has a password, and a restart replaces it with a new one. Sign in with your username and password below, or ask your administrator for a new sign-in link.",
},
account: {
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 69bc05ff..8f189319 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -355,6 +355,8 @@ export const zh = {
edit: "编辑",
settings: "设置",
confirm: "确认",
+ /** Sole button of a dialog that only informs: it has nothing to confirm or cancel, so the label acknowledges rather than agrees (and does not repeat the header X's "close"). */
+ gotIt: "知道了",
loading: "加载中…",
saved: "已保存",
saving: "保存中…",
@@ -395,6 +397,14 @@ export const zh = {
/** Login footer line 2: the offline rescue for a forgotten admin password (other users ask the admin instead). */
forgotAdminNote:
"忘记管理员密码时,停止服务后执行 penguin server reset-admin-password 重置为新的初始密码",
+ /** Dialog raised over the login form when the server refused a sign-in link (spent, expired, or never valid). */
+ claimFailedTitle: "登录链接已失效",
+ /** Desktop deployment: the shell mints a fresh link every time it starts, so restarting it is the way back in. */
+ claimFailedDesktop:
+ "这个一次性登录链接已被使用或已失效。重启 PenguinHarness 桌面应用即可生成新的登录链接并自动登录;也可以在下方用账号密码登录。",
+ /** Everywhere else: nobody at this browser can mint a link, so the way in is the form below or whoever runs the server. */
+ claimFailedServer:
+ "首次登录链接在服务端设置密码后即失效,重启服务端也会换发新的链接。请在下方用账号密码登录,或向管理员索取新的登录链接。",
},
account: {
diff --git a/packages/web/src/pages/login.tsx b/packages/web/src/pages/login.tsx
index 64e61da9..0173e8da 100644
--- a/packages/web/src/pages/login.tsx
+++ b/packages/web/src/pages/login.tsx
@@ -4,9 +4,12 @@
* the form area, not the background graphics); top-right corner has language and theme settings (reuses
* global preferences, defaults to following the device). No open registration: accounts are created by
* admins in the user backend; first use logs in with the built-in admin account (hinted in the footer).
+ *
+ * It is also where a rejected sign-in link lands: the server redirects a spent or invalid claim here
+ * with `?claimFailed=`, and the page raises a dialog over the form saying how to get a working link.
*/
-import { useState } from "react";
-import { useNavigate } from "react-router";
+import { useEffect, useState } from "react";
+import { useNavigate, useSearchParams } from "react-router";
import { S } from "../lib/strings";
import { apiErrorText } from "../lib/api-error";
import { useDocumentTitle } from "../lib/use-document-title";
@@ -18,10 +21,19 @@ import type { ThemeMode } from "../state/theme";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { PasswordInput } from "../components/ui/password-input";
+import { Modal } from "../components/ui/modal";
import { PenguinLogo } from "../components/ui/penguin-logo";
import { Segmented } from "../components/ui/segmented";
import { LoginCircuit } from "./login-circuit";
+/** Which advice a failed claim asks for; the server decides it from the deployment, not from the token. */
+type ClaimFailure = "desktop" | "server";
+
+/** Reads `?claimFailed=`; anything the server did not write is ignored rather than shown. */
+function parseClaimFailure(value: string | null): ClaimFailure | null {
+ return value === "desktop" || value === "server" ? value : null;
+}
+
export function LoginPage() {
useDocumentTitle(S.auth.login);
const { login } = useAuth();
@@ -35,6 +47,18 @@ export function LoginPage() {
const [busy, setBusy] = useState(false);
const clearErrors = () => setErrors((p) => (p.userId || p.password || p.form ? {} : p));
+ // Read once from the landing address, which the effect below then strips: the dialog answers
+ // the navigation that arrived here, so a reload must not raise it again and an address copied
+ // out of the bar must not raise it for someone who never followed a link.
+ const [searchParams] = useSearchParams();
+ const [claimFailure] = useState<ClaimFailure | null>(() =>
+ parseClaimFailure(searchParams.get("claimFailed")),
+ );
+ const [noticeOpen, setNoticeOpen] = useState(claimFailure !== null);
+ useEffect(() => {
+ if (claimFailure !== null) navigate("/login", { replace: true });
+ }, [claimFailure, navigate]);
+
const submit = async () => {
const next: { userId?: string; password?: string } = {};
if (!userId.trim()) next.userId = S.common.requiredField;
@@ -145,6 +169,22 @@ export function LoginPage() {
</p>
</div>
</div>
+ {/* Over the form, never instead of it: the link is one way in and the password form is the
+ other, so the dialog explains and steps aside. */}
+ <Modal
+ open={noticeOpen}
+ title={S.auth.claimFailedTitle}
+ onClose={() => setNoticeOpen(false)}
+ footer={
+ <Button variant="primary" onClick={() => setNoticeOpen(false)}>
+ {S.common.gotIt}
+ </Button>
+ }
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {claimFailure === "desktop" ? S.auth.claimFailedDesktop : S.auth.claimFailedServer}
+ </p>
+ </Modal>
</div>
);
}