Skip to content

Commit 56b4181

Browse files
authored
Merge pull request #873 from mincia1110/agent/admin-token-password-manager
Enable password manager autofill for admin tokens
2 parents 3e56207 + 2411b18 commit 56b4181

17 files changed

Lines changed: 421 additions & 7 deletions

File tree

‎docs-site/src/content/docs/guides/web-dashboard.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,11 @@ they expire or the proxy restarts. Only a dashboard bound to a non-loopback host
2929
the admin token (`OPENCODEX_ADMIN_AUTH_TOKEN`, or the auto-generated
3030
`~/.opencodex/admin-api-token` file).
3131

32+
When a remote dashboard needs that credential, it presents a standard password form so a browser
33+
password manager can offer to save and autofill it. The dashboard itself still keeps the token only
34+
in memory and does not write it to `localStorage` or `sessionStorage`; whether it is saved is entirely
35+
the browser or password manager's decision.
36+
3237
## What you can do
3338

3439
| Area | What it does |

‎docs-site/src/content/docs/ja/guides/web-dashboard.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@ ocx start
2121
bun run dev:gui
2222
```
2323

24+
## サインイン
25+
26+
`localhost` や `127.0.0.1` などのループバックアドレスで開いたダッシュボードは、短時間有効な GUI セッションを自動的に受け取るため、通常はトークン入力が不要です。ループバック以外のホストで公開する場合は、`OPENCODEX_ADMIN_AUTH_TOKEN`、または自動生成される `~/.opencodex/admin-api-token` ファイルの管理トークンが必要です。
27+
28+
リモートダッシュボードでは標準のパスワードフォームが表示され、ブラウザのパスワードマネージャーで保存・自動入力できます。ダッシュボード自体はトークンをメモリ内だけに保持し、`localStorage` や `sessionStorage` には書き込みません。保存するかどうかはブラウザまたはパスワードマネージャーだけが決定します。
29+
2430
## できること
2531

2632
| 領域 | 機能 |

‎docs-site/src/content/docs/ko/guides/web-dashboard.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@ ocx start
2121
bun run dev:gui
2222
```
2323

24+
## 로그인
25+
26+
`localhost`나 `127.0.0.1` 같은 loopback 주소에서 연 대시보드는 짧게 유지되는 GUI 세션을 자동으로 받으므로 보통 토큰을 입력할 필요가 없습니다. loopback이 아닌 호스트로 공개한 대시보드에는 `OPENCODEX_ADMIN_AUTH_TOKEN` 또는 자동 생성되는 `~/.opencodex/admin-api-token` 파일의 관리자 토큰이 필요합니다.
27+
28+
원격 대시보드는 표준 비밀번호 폼을 표시하므로 브라우저 비밀번호 관리자가 토큰 저장과 자동 완성을 제안할 수 있습니다. 대시보드 자체는 토큰을 메모리에만 보관하며 `localStorage`나 `sessionStorage`에 쓰지 않습니다. 저장 여부는 전적으로 브라우저 또는 비밀번호 관리자가 결정합니다.
29+
2430
## 할 수 있는 일
2531

2632
| 영역 | 기능 |

‎docs-site/src/content/docs/ru/guides/web-dashboard.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@ ocx start
2121
bun run dev:gui
2222
```
2323

24+
## Вход
25+
26+
При открытии дашборда через loopback-адрес, например `localhost` или `127.0.0.1`, он автоматически получает краткоживущую GUI-сессию, поэтому ввод токена обычно не требуется. Для дашборда на любом другом хосте нужен административный токен из `OPENCODEX_ADMIN_AUTH_TOKEN` или автоматически созданного файла `~/.opencodex/admin-api-token`.
27+
28+
Удалённый дашборд показывает стандартную форму пароля, поэтому менеджер паролей браузера может предложить сохранить и автозаполнять токен. Сам дашборд хранит токен только в памяти и не записывает его в `localStorage` или `sessionStorage`; решение о сохранении полностью остаётся за браузером или менеджером паролей.
29+
2430
## Возможности
2531

2632
| Раздел | Что делает |

‎docs-site/src/content/docs/zh-cn/guides/web-dashboard.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@ ocx start
2020
bun run dev:gui
2121
```
2222

23+
## 登录
24+
25+
通过 `localhost`、`127.0.0.1` 等 loopback 地址打开仪表盘时,它会自动获得一个短期 GUI session,因此通常无需输入 token。在非 loopback 主机上公开仪表盘时,必须使用 `OPENCODEX_ADMIN_AUTH_TOKEN` 或自动生成的 `~/.opencodex/admin-api-token` 文件中的管理员 token。
26+
27+
远程仪表盘会显示标准密码表单,浏览器密码管理器可以提示保存并自动填充 token。仪表盘本身只在内存中保存 token,不会写入 `localStorage` 或 `sessionStorage`;是否持久保存完全由浏览器或密码管理器决定。
28+
2329
## 可以完成哪些操作
2430

2531
| 区域 | 作用 |

‎gui/src/admin-token-dialog.ts‎

Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
import { DICTS, getActiveLocale, type Locale } from "./i18n/shared";
2+
3+
const ADMIN_TOKEN_DIALOG_ID = "opencodex-admin-token-dialog";
4+
const ADMIN_TOKEN_USERNAME = "OpenCodex";
5+
6+
export type AdminTokenValidation = "accepted" | "rejected" | "unavailable";
7+
export type AdminTokenVerifier = (token: string) => Promise<AdminTokenValidation>;
8+
9+
/**
10+
* Ask for the management credential with a real sign-in form so browsers and
11+
* password managers can offer save/autofill. OpenCodex itself still keeps the
12+
* submitted token in memory only; persistence remains entirely browser-owned.
13+
*/
14+
export function promptForAdminToken(
15+
verifyToken: AdminTokenVerifier,
16+
locale: Locale = getActiveLocale(),
17+
): Promise<string | null> {
18+
const messages = DICTS[locale];
19+
const titleText = messages["auth.adminTokenTitle"];
20+
21+
return new Promise((resolve) => {
22+
const previouslyFocused = document.activeElement instanceof HTMLElement
23+
? document.activeElement
24+
: null;
25+
let settled = false;
26+
27+
const dialog = document.createElement("dialog");
28+
dialog.id = ADMIN_TOKEN_DIALOG_ID;
29+
dialog.className = "modal-overlay";
30+
dialog.setAttribute("aria-labelledby", `${ADMIN_TOKEN_DIALOG_ID}-title`);
31+
32+
const form = document.createElement("form");
33+
form.className = "modal-card";
34+
form.method = "post";
35+
form.action = window.location.href;
36+
form.autocomplete = "on";
37+
38+
const heading = document.createElement("div");
39+
heading.className = "modal-head";
40+
const title = document.createElement("h3");
41+
title.id = `${ADMIN_TOKEN_DIALOG_ID}-title`;
42+
title.textContent = titleText;
43+
heading.append(title);
44+
45+
const accountField = document.createElement("div");
46+
const accountLabel = document.createElement("label");
47+
accountLabel.className = "field-label";
48+
accountLabel.htmlFor = `${ADMIN_TOKEN_DIALOG_ID}-username`;
49+
accountLabel.textContent = messages["auth.adminAccountLabel"];
50+
const username = document.createElement("input");
51+
username.id = accountLabel.htmlFor;
52+
username.className = "input";
53+
username.type = "text";
54+
username.name = "username";
55+
username.autocomplete = "username";
56+
username.value = ADMIN_TOKEN_USERNAME;
57+
username.readOnly = true;
58+
accountField.append(accountLabel, username);
59+
60+
const tokenField = document.createElement("div");
61+
tokenField.style.marginTop = "var(--space-4)";
62+
const tokenLabel = document.createElement("label");
63+
tokenLabel.className = "field-label";
64+
tokenLabel.htmlFor = `${ADMIN_TOKEN_DIALOG_ID}-password`;
65+
tokenLabel.textContent = messages["auth.adminTokenFieldLabel"];
66+
const password = document.createElement("input");
67+
password.id = tokenLabel.htmlFor;
68+
password.className = "input";
69+
password.type = "password";
70+
password.name = "password";
71+
password.autocomplete = "current-password";
72+
password.required = true;
73+
password.spellcheck = false;
74+
password.autocapitalize = "none";
75+
tokenField.append(tokenLabel, password);
76+
77+
const validationError = document.createElement("div");
78+
validationError.className = "notice notice-err";
79+
validationError.setAttribute("role", "alert");
80+
validationError.hidden = true;
81+
82+
const actions = document.createElement("div");
83+
actions.className = "modal-actions";
84+
const cancel = document.createElement("button");
85+
cancel.type = "button";
86+
cancel.className = "btn btn-ghost";
87+
cancel.textContent = messages["common.cancel"];
88+
const submit = document.createElement("button");
89+
submit.type = "submit";
90+
submit.className = "btn btn-primary";
91+
submit.textContent = messages["common.ok"];
92+
actions.append(cancel, submit);
93+
94+
form.append(heading, accountField, tokenField, validationError, actions);
95+
dialog.append(form);
96+
97+
const finish = (value: string | null): void => {
98+
if (settled) return;
99+
settled = true;
100+
if (dialog.open) dialog.close();
101+
dialog.remove();
102+
previouslyFocused?.focus();
103+
resolve(value);
104+
};
105+
106+
form.addEventListener("submit", (event) => {
107+
event.preventDefault();
108+
const token = password.value.trim();
109+
if (!token) {
110+
password.value = "";
111+
password.reportValidity();
112+
return;
113+
}
114+
password.disabled = true;
115+
submit.disabled = true;
116+
validationError.hidden = true;
117+
118+
void verifyToken(token).then((result) => {
119+
if (settled) return;
120+
if (result === "accepted") {
121+
finish(token);
122+
return;
123+
}
124+
password.value = "";
125+
password.disabled = false;
126+
submit.disabled = false;
127+
validationError.textContent = result === "rejected"
128+
? messages["auth.adminTokenRejected"]
129+
: messages["auth.adminTokenUnavailable"];
130+
validationError.hidden = false;
131+
password.focus();
132+
}).catch(() => {
133+
if (settled) return;
134+
password.value = "";
135+
password.disabled = false;
136+
submit.disabled = false;
137+
validationError.textContent = messages["auth.adminTokenUnavailable"];
138+
validationError.hidden = false;
139+
password.focus();
140+
});
141+
});
142+
cancel.addEventListener("click", () => finish(null));
143+
dialog.addEventListener("cancel", (event) => {
144+
event.preventDefault();
145+
finish(null);
146+
});
147+
148+
document.body.append(dialog);
149+
if (typeof dialog.showModal === "function") dialog.showModal();
150+
else dialog.setAttribute("open", "");
151+
queueMicrotask(() => password.focus());
152+
});
153+
}

‎gui/src/api.ts‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { promptForAdminToken, type AdminTokenVerifier } from "./admin-token-dialog";
2+
13
let installed = false;
24
/** Shared 401 refresh gate — concurrent waiters join one prompt / token resolution. */
35
let resolutionInFlight: Promise<string | null> | null = null;
@@ -11,8 +13,13 @@ let rawFetch: typeof fetch | null = null;
1113
*/
1214
let promptCancelled = false;
1315

16+
type AdminTokenPrompt = (verifyToken: AdminTokenVerifier) => Promise<string | null>;
17+
let requestAdminToken: AdminTokenPrompt = promptForAdminToken;
18+
1419
/** Document path re-fetched to mint a fresh loopback GUI session (server injects meta tags). */
1520
const SESSION_REBOOTSTRAP_PATH = "/";
21+
/** Safe authenticated read used to validate a raw admin token before closing the sign-in form. */
22+
const ADMIN_TOKEN_VALIDATION_PATH = "/api/settings";
1623

1724
function needsApiAuth(input: RequestInfo | URL): boolean {
1825
try {
@@ -111,6 +118,18 @@ async function reBootstrapSessionToken(): Promise<string | null> {
111118
}
112119
}
113120

121+
async function verifyAdminToken(token: string): ReturnType<AdminTokenVerifier> {
122+
if (!rawFetch) return "unavailable";
123+
try {
124+
const [input, init] = withToken(ADMIN_TOKEN_VALIDATION_PATH, { cache: "no-store" }, token);
125+
const response = await rawFetch(input, init);
126+
if (response.status === 401) return "rejected";
127+
return response.ok ? "accepted" : "unavailable";
128+
} catch {
129+
return "unavailable";
130+
}
131+
}
132+
114133
function clearLegacySessionToken(): void {
115134
try {
116135
sessionStorage.removeItem(LEGACY_TOKEN_KEY);
@@ -135,8 +154,9 @@ function withToken(input: RequestInfo | URL, init: RequestInit | undefined, toke
135154

136155
/**
137156
* Resolve a token after a 401. Concurrent callers share one in-flight resolution so a dashboard
138-
* fan-out does not open one window.prompt per /api request (#647). Re-reads memoryToken before
139-
* prompting so waiters that wake after another request already stored a token do not re-prompt.
157+
* fan-out opens at most one credential dialog per /api request wave (#647). Re-reads
158+
* memoryToken before prompting so waiters that wake after another request already stored a token
159+
* do not re-prompt.
140160
*/
141161
async function resolveTokenAfter401(failedToken: string | null): Promise<string | null> {
142162
if (promptCancelled) return null;
@@ -150,7 +170,7 @@ async function resolveTokenAfter401(failedToken: string | null): Promise<string
150170
const renewed = await reBootstrapSessionToken();
151171
if (renewed) return renewed;
152172

153-
const prompted = window.prompt("OpenCodex admin token (OPENCODEX_ADMIN_AUTH_TOKEN)")?.trim() || null;
173+
const prompted = await requestAdminToken(verifyAdminToken);
154174
if (prompted) {
155175
storeToken(prompted);
156176
return prompted;
@@ -202,12 +222,13 @@ export function installApiAuthFetch(): void {
202222
}
203223

204224
/** Test-only: allow a fresh `installApiAuthFetch()` in the same module instance. */
205-
export function resetApiAuthFetchForTests(): void {
225+
export function resetApiAuthFetchForTests(adminTokenPrompt: AdminTokenPrompt = promptForAdminToken): void {
206226
installed = false;
207227
memoryToken = null;
208228
memoryCsrfToken = null;
209229
memorySessionOrigin = null;
210230
resolutionInFlight = null;
211231
rawFetch = null;
212232
promptCancelled = false;
233+
requestAdminToken = adminTokenPrompt;
213234
}

‎gui/src/i18n/de.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ export const de: Record<TKey, string> = {
2424
"common.remove": "Entfernen",
2525
"common.loading": "Lädt…",
2626
"common.retry": "Wiederholen",
27+
"auth.adminTokenTitle": "OpenCodex-Admin-Token (OPENCODEX_ADMIN_AUTH_TOKEN)",
28+
"auth.adminAccountLabel": "Konto",
29+
"auth.adminTokenFieldLabel": "Admin-Token",
30+
"auth.adminTokenRejected": "Der Admin-Token wurde abgelehnt. Prüfen Sie ihn und versuchen Sie es erneut.",
31+
"auth.adminTokenUnavailable": "Der Admin-Token konnte nicht überprüft werden. Versuchen Sie es erneut.",
2732
"theme.label": "Design",
2833
"theme.light": "Hell",
2934
"theme.dark": "Dunkel",

‎gui/src/i18n/en.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ export const en = {
2626
"common.remove": "Remove",
2727
"common.loading": "Loading…",
2828
"common.retry": "Retry",
29+
"auth.adminTokenTitle": "OpenCodex admin token (OPENCODEX_ADMIN_AUTH_TOKEN)",
30+
"auth.adminAccountLabel": "Account",
31+
"auth.adminTokenFieldLabel": "Admin token",
32+
"auth.adminTokenRejected": "That admin token was rejected. Check it and try again.",
33+
"auth.adminTokenUnavailable": "The admin token could not be verified. Try again.",
2934
"app.logoAria": "opencodex logo",
3035
"app.claudeOn": "Claude ON",
3136
"app.claudeOff": "Claude OFF",

‎gui/src/i18n/ja.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ export const ja: Record<TKey, string> = {
2626
"common.remove": "削除",
2727
"common.loading": "読み込み中…",
2828
"common.retry": "再試行",
29+
"auth.adminTokenTitle": "OpenCodex 管理者トークン (OPENCODEX_ADMIN_AUTH_TOKEN)",
30+
"auth.adminAccountLabel": "アカウント",
31+
"auth.adminTokenFieldLabel": "管理者トークン",
32+
"auth.adminTokenRejected": "管理者トークンが拒否されました。確認してもう一度お試しください。",
33+
"auth.adminTokenUnavailable": "管理者トークンを確認できませんでした。もう一度お試しください。",
2934
"app.logoAria": "opencodex ロゴ",
3035
"app.claudeOn": "Claude オン",
3136
"app.claudeOff": "Claude オフ",

0 commit comments

Comments
 (0)