From 088d7557d30298f539f934331d7013afde30bf95 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 08:28:50 +0000 Subject: [PATCH 1/2] =?UTF-8?q?=E7=AD=BE=E5=8F=91=20API=20=E4=BB=A4?= =?UTF-8?q?=E7=89=8C=E7=BB=93=E6=9E=9C=E6=9C=AA=E7=9F=A5=E6=97=B6=E9=94=81?= =?UTF-8?q?=E4=BD=8F=E3=80=8C=E7=AD=BE=E5=8F=91=E3=80=8D=EF=BC=8C=E5=8F=AA?= =?UTF-8?q?=E7=BB=99=E3=80=8C=E6=A0=B8=E5=AF=B9=E3=80=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 管理员「为用户签发」和个人设置「新建令牌」遇到结果未知(504 instance_timeout + requestOutcome unknown、断网、代理返回的裸 502/504)时,原来只显示错误, 「签发」「创建」仍可点,再点会多签一个令牌,而第一个令牌的明文已经拿不到。 - 新增 token-create-outcome.mjs:判断结果是否未知;「核对」按名称、用户和 创建时间在令牌列表里找刚才的令牌,找到就提示吊销后重签;没找到且距发出 不足 30 秒时只说「暂未找到」,不解锁;回复里没有令牌列表时不下结论。 - 锁定状态保存在页面上(个人设置弹窗常驻),关掉弹窗再打开仍锁住。 - IamRequestError 和 /auth 失败结果保留 Host 给的 requestOutcome。 - 个人设置弹窗请求进行中不能关闭。 关联 #64 token-create-unknown-outcome Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SLUGBDtJbRzDTQgkyE1mGh --- console-ui/src/i18n/messages.en.admin.mjs | 8 ++ console-ui/src/pages/access/iam-request.d.mts | 4 +- console-ui/src/pages/access/iam-request.mjs | 6 +- .../pages/access/token-create-outcome.d.mts | 34 ++++++ .../src/pages/access/token-create-outcome.mjs | 97 +++++++++++++++ console-ui/src/pages/access/tokens.tsx | 45 +++++-- console-ui/src/pages/account/index.tsx | 50 ++++++-- console-ui/src/utils/console-auth-api.ts | 5 + console-ui/src/utils/console-auth-model.d.mts | 2 + console-ui/src/utils/console-auth-model.mjs | 2 + tests/token-create-unknown-outcome.test.mjs | 110 ++++++++++++++++++ 11 files changed, 346 insertions(+), 17 deletions(-) create mode 100644 console-ui/src/pages/access/token-create-outcome.d.mts create mode 100644 console-ui/src/pages/access/token-create-outcome.mjs create mode 100644 tests/token-create-unknown-outcome.test.mjs diff --git a/console-ui/src/i18n/messages.en.admin.mjs b/console-ui/src/i18n/messages.en.admin.mjs index b4acedd1..47a20a4e 100644 --- a/console-ui/src/i18n/messages.en.admin.mjs +++ b/console-ui/src/i18n/messages.en.admin.mjs @@ -121,4 +121,12 @@ export const adminMessages = Object.freeze({ "账号与令牌由管理网关验证:机器人实例停止时也能登录,查看实例日志并重新启动。": "The management gateway checks accounts and tokens, so you can sign in while the bot instance is stopped, read its logs and start it again.", "已从上次的进度继续:数据库已经选定,接下来创建所有者。": "Continuing where you left off: the database is chosen; now create the owner.", "Host 没有执行这次修改,内容保持原样。查看技术详情后可以重新准备。": "The Host did not apply this change; nothing was modified. Check the technical details, then prepare it again.", + "签发请求已发出,但没有收到可信的答复,令牌可能已经签发。令牌只显示一次,请先核对,不要直接重新签发。": "The issue request was sent but no reliable answer came back, so the token may have been issued. A token is shown only once: check first instead of issuing again.", + "创建请求已发出,但没有收到可信的答复,令牌可能已经创建。令牌只显示一次,请先核对,不要直接重新创建。": "The create request was sent but no reliable answer came back, so the token may have been created. A token is shown only once: check first instead of creating it again.", + "核对结果:没有找到名为「{0}」的新令牌,签发没有生效,可以重新签发。": "Check result: no new token named \"{0}\" was found. Nothing was issued; you can issue it again.", + "核对结果:已有名为「{0}」的令牌,刚才的签发可能已经生效。令牌只显示一次,无法再次查看;请在列表里吊销它,再重新签发。": "Check result: a token named \"{0}\" exists, so the last attempt may have issued it. A token is shown only once and cannot be viewed again: revoke it in the list, then issue a new one.", + "核对失败:没有读到令牌列表,请稍后再核对。": "Check failed: the token list could not be read. Check again later.", + "核对结果:已有名为「{0}」的令牌,刚才的创建可能已经生效。令牌只显示一次,无法再次查看;请在列表里吊销它,再重新创建。": "Check result: a token named \"{0}\" exists, so the last attempt may have created it. A token is shown only once and cannot be viewed again: revoke it in the list, then create a new one.", + "核对结果:没有找到名为「{0}」的新令牌,创建没有生效,可以重新创建。": "Check result: no new token named \"{0}\" was found. Nothing was created; you can create it again.", + "核对结果:暂未找到名为「{0}」的令牌,但实例可能仍在处理。请 {1} 秒后再核对。": "Check result: no token named \"{0}\" yet, but the instance may still be working on it. Check again in {1} seconds.", }) diff --git a/console-ui/src/pages/access/iam-request.d.mts b/console-ui/src/pages/access/iam-request.d.mts index 19e9e9ff..1890897e 100644 --- a/console-ui/src/pages/access/iam-request.d.mts +++ b/console-ui/src/pages/access/iam-request.d.mts @@ -1,9 +1,11 @@ export declare class IamRequestError extends Error { - constructor(message: string, options?: { status?: number; code?: string; hostMessage?: string; retryAfter?: number }) + constructor(message: string, options?: { status?: number; code?: string; hostMessage?: string; retryAfter?: number; requestOutcome?: unknown }) readonly status: number readonly code: string readonly hostMessage: string readonly retryAfter?: number + /** Present when the Host said whether an instance-backed write ran. */ + readonly details?: { readonly requestOutcome: 'unknown' | 'not-dispatched' } } export type IamErrorKind = 'unsupported' | 'last_owner' | 'forbidden' | 'database_busy' | 'unavailable' | 'failed' export function iamErrorKind(error: unknown): IamErrorKind diff --git a/console-ui/src/pages/access/iam-request.mjs b/console-ui/src/pages/access/iam-request.mjs index 817ad986..d9df2c0a 100644 --- a/console-ui/src/pages/access/iam-request.mjs +++ b/console-ui/src/pages/access/iam-request.mjs @@ -5,7 +5,7 @@ import { parseRetryAfterSeconds } from '../../utils/retry-after.mjs' */ export class IamRequestError extends Error { - constructor(message, { status = 0, code = 'failed', hostMessage = '', retryAfter } = {}) { + constructor(message, { status = 0, code = 'failed', hostMessage = '', retryAfter, requestOutcome } = {}) { super(message) this.name = 'IamRequestError' this.status = status @@ -13,6 +13,8 @@ export class IamRequestError extends Error { this.hostMessage = hostMessage // Seconds from the gateway's Retry-After (`database_busy`); read by `statusFromError`. if (typeof retryAfter === 'number' && retryAfter > 0) this.retryAfter = retryAfter + // Whether an instance-backed write ran (`unknown`: it may have); read by `statusFromError`. + if (requestOutcome === 'unknown' || requestOutcome === 'not-dispatched') this.details = { requestOutcome } } } @@ -52,5 +54,5 @@ export function readIamReply(status, json, t, retryAfterHeader) { throw new IamRequestError(retryAfter ? t('网关的数据库正忙,请在 {0} 秒后重试。', [retryAfter]) : t('网关的数据库正忙,请稍后重试。'), { status, code, hostMessage, retryAfter }) } const message = hostMessage || t('请求失败(HTTP {0})', [status]) - throw new IamRequestError(message, { status, code: code || 'failed', hostMessage, retryAfter }) + throw new IamRequestError(message, { status, code: code || 'failed', hostMessage, retryAfter, requestOutcome: body.requestOutcome }) } diff --git a/console-ui/src/pages/access/token-create-outcome.d.mts b/console-ui/src/pages/access/token-create-outcome.d.mts new file mode 100644 index 00000000..425e98b1 --- /dev/null +++ b/console-ui/src/pages/access/token-create-outcome.d.mts @@ -0,0 +1,34 @@ +export declare const TOKEN_CREATE_CLOCK_SKEW_MS: number +export declare const TOKEN_CREATE_SETTLE_MS: number + +export interface TokenCreateAuthFailure { + readonly status: number + readonly code: string + readonly message?: string + readonly requestOutcome?: 'unknown' | 'not-dispatched' +} + +export declare function authFailureAsError(failure: TokenCreateAuthFailure | null | undefined): { + message: string + details: { transport?: string; serverCode?: string; httpStatus?: number; requestOutcome?: 'unknown' | 'not-dispatched' } +} + +export declare function tokenCreateUnknown(error: unknown): boolean + +export declare function tokenListOf(payload: unknown): unknown[] | null + +export interface TokenCreatePlan { + readonly name: string + readonly userId?: string + /** When the request was sent (ms). */ + readonly since?: number + /** Wording: `issue` 签发 (default) or `create` 创建. */ + readonly action?: 'issue' | 'create' +} + +export declare function tokenCreateCheck( + tokens: unknown, + plan: TokenCreatePlan, + locale?: string, + now?: number, +): { issued: boolean; settled: boolean; ids: string[]; text: string } diff --git a/console-ui/src/pages/access/token-create-outcome.mjs b/console-ui/src/pages/access/token-create-outcome.mjs new file mode 100644 index 00000000..4e0f0d7a --- /dev/null +++ b/console-ui/src/pages/access/token-create-outcome.mjs @@ -0,0 +1,97 @@ +import { translate } from '../../i18n/locale.mjs' +import { outcomeUnknown, serverCodeOf, statusFromError } from '../../components/status-state-model.mjs' + +/** + * Issuing an API token whose outcome is unknown (#64 `token-create-unknown-outcome`): the Host may + * have created the token, and its secret is shown only once. Re-issuing would leave a live token + * nobody has; so the dialog locks 「签发」 and offers only 「核对」 (a read of the token list). + */ + +/** How long before the attempt a listed token may have been created and still be this one (clock skew). */ +export const TOKEN_CREATE_CLOCK_SKEW_MS = 10 * 60 * 1000 +/** + * After a timeout the instance may still be writing the token: a 「核对」 sooner than this after the + * attempt that finds nothing does not unlock yet. + */ +export const TOKEN_CREATE_SETTLE_MS = 30 * 1000 + +/** + * A failed `/auth/tokens` call (an `AuthFailure`: `{ status, code, message, requestOutcome? }`) as an + * error `statusFromError` reads. `unreachable` means fetch rejected, which includes a request that + * was sent and then timed out, so it counts as a lost connection (outcome unknown). + */ +export function authFailureAsError(failure) { + const message = typeof failure?.message === 'string' && failure.message ? failure.message : String(failure?.code ?? 'failed') + if (!failure || failure.code === 'unreachable' || failure.status === 0) { + return { message, details: { transport: 'network' } } + } + return { + message, + details: { + serverCode: failure.code, + httpStatus: failure.status, + ...(failure.requestOutcome === 'unknown' || failure.requestOutcome === 'not-dispatched' ? { requestOutcome: failure.requestOutcome } : {}), + }, + } +} + +const isRecord = value => value !== null && typeof value === 'object' && !Array.isArray(value) + +/** + * A bare 502 / 504 from a proxy in front of the gateway (no Host code): the request may have reached + * the instance, so the outcome is unknown too. + */ +function gatewayTimeout(error) { + if (!isRecord(error)) return false + const details = isRecord(error.details) ? error.details : {} + const status = Number(details.httpStatus ?? error.status) + const code = serverCodeOf(error) + return (status === 502 || status === 504) && (!code || code === 'failed') +} + +/** Whether a failed token creation may have issued the token anyway (then 「签发」 must not be replayed). */ +export function tokenCreateUnknown(error) { + return outcomeUnknown(statusFromError(error)) || gatewayTimeout(error) +} + +/** The token array of a list reply (`{ tokens: [...] }`), or `null` when the reply has none. */ +export function tokenListOf(payload) { + if (Array.isArray(payload)) return payload + return isRecord(payload) && Array.isArray(payload.tokens) ? payload.tokens : null +} + +/** + * 「核对」 after an unknown outcome, from a fresh token list. `plan` is `{ name, userId?, since, action? }` + * (`since`: when the request was sent; `action`: `issue` 签发 or `create` 创建, for the wording). + * A token with that name (for that user) created around or after the attempt means the token was + * probably issued: its secret is lost, so the user should revoke it and issue a new one + * (`issued: true`). None found means nothing was issued, but only once `TOKEN_CREATE_SETTLE_MS` have + * passed since the attempt (`settled`); sooner, the instance may still be writing it. The caller + * unlocks only on `settled && !issued`. A reply without a list decides nothing: it throws. + */ +export function tokenCreateCheck(tokens, plan, locale = 'zh-CN', now = Date.now()) { + if (!Array.isArray(tokens)) throw new TypeError('The token list is not readable') + const create = plan?.action === 'create' + const attempted = Number.isFinite(plan?.since) ? plan.since : -Infinity + const found = tokens.filter(token => isRecord(token) && token.name === plan.name + && (!plan.userId || token.userId === plan.userId) + && !(typeof token.createdAt === 'number' && token.createdAt < attempted - TOKEN_CREATE_CLOCK_SKEW_MS)) + if (found.length) { + return { + issued: true, settled: true, ids: found.map(token => token.id), + text: create + ? translate(locale, '核对结果:已有名为「{0}」的令牌,刚才的创建可能已经生效。令牌只显示一次,无法再次查看;请在列表里吊销它,再重新创建。', [plan.name]) + : translate(locale, '核对结果:已有名为「{0}」的令牌,刚才的签发可能已经生效。令牌只显示一次,无法再次查看;请在列表里吊销它,再重新签发。', [plan.name]), + } + } + const wait = Math.ceil((attempted + TOKEN_CREATE_SETTLE_MS - now) / 1000) + if (wait > 0) { + return { issued: false, settled: false, ids: [], text: translate(locale, '核对结果:暂未找到名为「{0}」的令牌,但实例可能仍在处理。请 {1} 秒后再核对。', [plan.name, wait]) } + } + return { + issued: false, settled: true, ids: [], + text: create + ? translate(locale, '核对结果:没有找到名为「{0}」的新令牌,创建没有生效,可以重新创建。', [plan.name]) + : translate(locale, '核对结果:没有找到名为「{0}」的新令牌,签发没有生效,可以重新签发。', [plan.name]), + } +} diff --git a/console-ui/src/pages/access/tokens.tsx b/console-ui/src/pages/access/tokens.tsx index d3f41683..5d75f1bd 100644 --- a/console-ui/src/pages/access/tokens.tsx +++ b/console-ui/src/pages/access/tokens.tsx @@ -13,6 +13,7 @@ import { useToast } from '../../components/toast' import { TOKEN_EXPIRY_DAYS, tokenExpiresAt, tokenNameProblem } from '../../utils/console-auth-model.mjs' import { copyText } from '../clipboard-copy.mjs' import { IAM_RPC, readTokens, tokenExpired, type IamToken, type IamUser } from './access-model.mjs' +import { tokenCreateCheck, tokenCreateUnknown, tokenListOf } from './token-create-outcome.mjs' import { FormField, IamLoadError, ReadOnlyNotice } from './access-components' import { iamRequest, useCanManageIam, useIamRead, useIamUsers } from './use-iam' import '../admin-pages.css' @@ -20,6 +21,9 @@ import '../admin-pages.css' const EMPTY_TOKENS: IamToken[] = [] const ALL = '*' +/** An issue with an unknown outcome, not yet 核对-ed: kept by the page so reopening the dialog stays locked. */ +interface IssueHold { readonly name: string; readonly userId: string; readonly since: number; readonly error: unknown; readonly text?: string } + export default function AccessTokensPage() { const i18n = useI18n() const canManage = useCanManageIam() @@ -30,6 +34,7 @@ export default function AccessTokensPage() { const usersById = useMemo(() => new Map(users.data.map(user => [user.id, user])), [users.data]) const [issuing, setIssuing] = useState(false) const [issued, setIssued] = useState<{ name: string; token: string; user: string } | null>(null) + const [issueHold, setIssueHold] = useState(null) const now = Date.now() const when = (value: number | null) => (value ? i18n.date(value, { dateStyle: 'medium', timeStyle: 'short' }) : '—') @@ -142,7 +147,8 @@ export default function AccessTokensPage() { )} {issuing ? ( - setIssuing(false)} + { setIssuing(false); if (issueHold) tokens.refresh() }} onIssued={value => { setIssuing(false); setIssued(value); tokens.refresh() // The secret is shown once in the dialog; the read-back only checks the token is listed. @@ -159,13 +165,17 @@ export default function AccessTokensPage() { } /** `iam.tokens.create { userId, name, expiresAt? }`: a token carrying all of that user's permissions. */ -function IssueTokenDialog({ users, initialUser, onClose, onIssued }: { +function IssueTokenDialog({ users, initialUser, held, onHeld, onClose, onIssued }: { users: readonly IamUser[] initialUser: string + /** A token may have been issued (no trustworthy answer): 「签发」 stays locked until 「核对」 finds none. */ + held: IssueHold | null + onHeld: (hold: IssueHold | null) => void onClose: () => void onIssued: (value: { name: string; token: string; user: string; userId: string; id?: string }) => void }) { const i18n = useI18n() + const toast = useToast() const id = useId() const enabled = users.filter(user => !user.disabled) const [userId, setUserId] = useState(() => enabled.some(user => user.id === initialUser) ? initialUser : enabled[0]?.id ?? '') @@ -174,13 +184,15 @@ function IssueTokenDialog({ users, initialUser, onClose, onIssued }: { const [touched, setTouched] = useState(false) const [saving, setSaving] = useState(false) const [error, setError] = useState(null) + const [checking, setChecking] = useState(false) const problem = tokenNameProblem(name) const nameError = problem === 'empty' ? i18n.t('请输入令牌名称。') : problem === 'long' ? i18n.t('名称最多 128 个字符。') : null const submit = async () => { setTouched(true) - if (nameError || !userId) return + if (nameError || !userId || held) return setSaving(true) setError(null) + const since = Date.now() try { const expiresAt = tokenExpiresAt(Number(days)) const reply = await iamRequest<{ token?: unknown; record?: { name?: unknown; id?: unknown } }>(IAM_RPC.TOKENS_CREATE, { userId, name: name.trim(), ...(expiresAt ? { expiresAt } : {}) }, i18n.t) @@ -188,11 +200,27 @@ function IssueTokenDialog({ users, initialUser, onClose, onIssued }: { onIssued({ name: typeof reply.record?.name === 'string' ? reply.record.name : name.trim(), token: reply.token, user: users.find(user => user.id === userId)?.username ?? userId, userId, ...(typeof reply.record?.id === 'string' ? { id: reply.record.id } : {}) }) } catch (caught) { - setError(caught) + if (tokenCreateUnknown(caught)) onHeld({ name: name.trim(), userId, since, error: caught }) + else setError(caught) } finally { setSaving(false) } } + // Read-only: lists the user's tokens; never issues again. + const check = async () => { + if (!held || checking) return + setChecking(true) + try { + // A reply without a token list decides nothing (readTokens would read it as empty). + const result = tokenCreateCheck(tokenListOf(await iamRequest(IAM_RPC.TOKENS_LIST, { userId: held.userId }, i18n.t)), held, i18n.locale) + if (result.issued || !result.settled) onHeld({ ...held, text: result.text }) + else { onHeld(null); toast.info(result.text) } + } catch { + onHeld({ ...held, text: i18n.t('核对失败:没有读到令牌列表,请稍后再核对。') }) + } finally { + setChecking(false) + } + } return ( { if (!open && !saving) onClose() }}> @@ -212,10 +240,13 @@ function IssueTokenDialog({ users, initialUser, onClose, onIssued }: { ({ value: String(value), label: value > 0 ? i18n.t('{0} 天', [value]) : i18n.t('永不过期') }))} /> - {error ? : null} + {held ? ( + void check()} + description={held.text ?? i18n.t('签发请求已发出,但没有收到可信的答复,令牌可能已经签发。令牌只显示一次,请先核对,不要直接重新签发。')} /> + ) : error ? : null} - - + + diff --git a/console-ui/src/pages/account/index.tsx b/console-ui/src/pages/account/index.tsx index d2e0cd19..e13d1ba6 100644 --- a/console-ui/src/pages/account/index.tsx +++ b/console-ui/src/pages/account/index.tsx @@ -14,7 +14,7 @@ import { useConsoleSession } from '../../hooks/use-console-session' import { useConsoleAccess } from '../../hooks/use-console-access' import { hasConsolePermission } from '../../utils/console-access.mjs' import { requestSetup } from '../../utils/console-session.mjs' -import { changeOwnPassword, createOwnToken, fetchMe, listOwnTokens, revokeOwnToken } from '../../utils/console-auth-api' +import { changeOwnPassword, createOwnToken, fetchMe, listOwnTokens, readOwnTokenList, revokeOwnToken } from '../../utils/console-auth-api' import { MIN_PASSWORD_LENGTH, TOKEN_EXPIRY_DAYS, authErrorMessage, newPasswordProblem, principalLabel, tokenExpiresAt, tokenNameProblem, tokenState, type AuthFailure, @@ -22,6 +22,8 @@ import { import { CONSOLE_PATHS as P } from '../../console-routes.mjs' import { builtinRoleLabel, scopeLabel } from '../access/access-model.mjs' import { IssuedTokenDialog } from '../access/tokens' +import { authFailureAsError, tokenCreateCheck, tokenCreateUnknown, tokenListOf } from '../access/token-create-outcome.mjs' +import { useToast } from '../../components/toast' import type { ConsoleApiTokenView, ConsoleMe } from '../../contracts/console-auth' import { MyChatIdentitySection } from '../../scope/ChatIdentityPanels' import '../admin-pages.css' @@ -215,7 +217,7 @@ function TokensSection() { : null} {savedToken.element} - { + void load()} onCreated={(name, token) => { setCreated({ name, token }); void load() // The token is shown once in the dialog; the read-back only checks that it is listed. void savedToken.report(i18n.t('已新建令牌 {0}', [name]), outcomeFromAccessWrite({ secret: true }), async () => { @@ -228,12 +230,19 @@ function TokensSection() { } -function CreateTokenDialog({ open, onOpenChange, onCreated }: { +function CreateTokenDialog({ open, onOpenChange, onCreated, onUncertain }: { open: boolean onOpenChange: (open: boolean) => void onCreated: (name: string, token: string) => void + /** Closed after a creation with an unknown outcome: the list may hold a new token. */ + onUncertain: () => void }) { const i18n = useI18n() + const toast = useToast() + // A token may have been created (no trustworthy answer): 「创建」 stays locked until 「核对」 finds none. + // Kept while the dialog is closed (it stays mounted), so reopening it stays locked. + const [held, setHeld] = useState<{ name: string; since: number; error: unknown; action: 'create'; text?: string } | null>(null) + const [checking, setChecking] = useState(false) const [name, setName] = useState('') const [days, setDays] = useState(String(TOKEN_EXPIRY_DAYS[1])) const [error, setError] = useState('') @@ -244,15 +253,40 @@ function CreateTokenDialog({ open, onOpenChange, onCreated }: { const submit = async () => { const problem = tokenNameProblem(name) if (problem) { setError(problem === 'empty' ? i18n.t('请输入令牌名称。') : i18n.t('名称最多 128 个字符。')); return } + if (held) return setBusy(true) + const since = Date.now() const result = await createOwnToken({ name: name.trim(), expiresAt: tokenExpiresAt(Number(days)) }) setBusy(false) - if (!result.ok) { setError(authErrorMessage(result, i18n.t, 'tokens')); return } + if (!result.ok) { + const failure = authFailureAsError(result) + if (tokenCreateUnknown(failure)) { setError(''); setHeld({ name: name.trim(), since, error: failure, action: 'create' }); return } + setError(authErrorMessage(result, i18n.t, 'tokens')); return + } onOpenChange(false) onCreated(result.data.record?.name ?? name.trim(), result.data.token) } - return + // Read-only: lists the own tokens; never creates again. + const check = async () => { + if (!held || checking) return + setChecking(true) + // The raw reply: a reply without a token list decides nothing (listOwnTokens would read it as empty). + const list = await readOwnTokenList() + setChecking(false) + const tokens = list.ok ? tokenListOf(list.data) : null + if (!tokens) { setHeld({ ...held, text: i18n.t('核对失败:没有读到令牌列表,请稍后再核对。') }); return } + const result = tokenCreateCheck(tokens, held, i18n.locale) + if (result.issued || !result.settled) setHeld({ ...held, text: result.text }) + else { setHeld(null); toast.info(result.text) } + } + const changeOpen = (next: boolean) => { + if (!next && busy) return + if (!next && held) onUncertain() + onOpenChange(next) + } + + return
{ event.preventDefault(); void submit() }} className="grid gap-4"> @@ -270,9 +304,11 @@ function CreateTokenDialog({ open, onOpenChange, onCreated }: { options={TOKEN_EXPIRY_DAYS.map(value => ({ value: String(value), label: value > 0 ? i18n.t('{0} 天', [value]) : i18n.t('永不过期') }))} /> {error &&

{error}

} + {held ? void check()} + description={held.text ?? i18n.t('创建请求已发出,但没有收到可信的答复,令牌可能已经创建。令牌只显示一次,请先核对,不要直接重新创建。')} /> : null} - - + +
diff --git a/console-ui/src/utils/console-auth-api.ts b/console-ui/src/utils/console-auth-api.ts index 2ce70819..b78e7f0e 100644 --- a/console-ui/src/utils/console-auth-api.ts +++ b/console-ui/src/utils/console-auth-api.ts @@ -160,6 +160,11 @@ export async function listOwnTokens(): Promise> { + return sessionCall(R.TOKENS) +} + export function createOwnToken(input: { name: string; expiresAt: number | null }): Promise> { return sessionCall(R.TOKENS, { method: 'POST', body: { name: input.name, ...(input.expiresAt ? { expiresAt: input.expiresAt } : {}) }, diff --git a/console-ui/src/utils/console-auth-model.d.mts b/console-ui/src/utils/console-auth-model.d.mts index 408a1b12..2efbe5b8 100644 --- a/console-ui/src/utils/console-auth-model.d.mts +++ b/console-ui/src/utils/console-auth-model.d.mts @@ -30,6 +30,8 @@ export interface AuthFailure { readonly message: string /** 429 only; `null` when the Host's Retry-After is not readable. */ readonly retryAfterSec?: number | null + /** Instance-backed writes: whether the request reached the instance (`unknown`: it may have run). */ + readonly requestOutcome?: 'unknown' | 'not-dispatched' } export interface AuthSuccess { readonly ok: true; readonly status: number; readonly data: T } export type AuthResult = AuthSuccess | AuthFailure diff --git a/console-ui/src/utils/console-auth-model.mjs b/console-ui/src/utils/console-auth-model.mjs index 4c2e8eee..2e77e826 100644 --- a/console-ui/src/utils/console-auth-model.mjs +++ b/console-ui/src/utils/console-auth-model.mjs @@ -48,6 +48,8 @@ export function readAuthResponse({ status, body, retryAfter, now }) { const message = envelope && typeof body.error === 'string' ? body.error.slice(0, 500) : '' return { ok: false, status, code, message, + // Whether an instance-backed write ran (`instance_timeout` etc.): `unknown` means it may have. + ...(envelope && (body.requestOutcome === 'unknown' || body.requestOutcome === 'not-dispatched') ? { requestOutcome: body.requestOutcome } : {}), ...(status === 429 || status === 503 ? { retryAfterSec: retryAfterSeconds(retryAfter, body, now) } : {}), } } diff --git a/tests/token-create-unknown-outcome.test.mjs b/tests/token-create-unknown-outcome.test.mjs new file mode 100644 index 00000000..aabdec9b --- /dev/null +++ b/tests/token-create-unknown-outcome.test.mjs @@ -0,0 +1,110 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { readFileSync } from 'node:fs' +import { authFailureAsError, tokenCreateCheck, tokenCreateUnknown, tokenListOf, TOKEN_CREATE_CLOCK_SKEW_MS, TOKEN_CREATE_SETTLE_MS } from '../console-ui/src/pages/access/token-create-outcome.mjs' +import { readAuthResponse, unreachableResult } from '../console-ui/src/utils/console-auth-model.mjs' +import { readIamReply } from '../console-ui/src/pages/access/iam-request.mjs' + +// #64 `token-create-unknown-outcome`: issuing an API token that ran into an unknown outcome +// (504 instance_timeout, requestOutcome 'unknown') showed 「实例不可用……建议 5 秒后重试」 and left +// 「签发」 clickable; a second click issued a second token, while the first one's secret (shown only +// once) was lost. The dialogs must lock 「签发」/「创建」 and offer only 「核对」. +const CJK = /[一-鿿]/u +const read = path => readFileSync(new URL(`../console-ui/src/${path}`, import.meta.url), 'utf8') +const timeout = () => Object.assign(new Error('The instance did not answer in time'), { code: 'instance_timeout', status: 504, requestOutcome: 'unknown' }) + +test('an IAM token creation without a trustworthy answer may have issued the token', () => { + assert.equal(tokenCreateUnknown(timeout()), true) + assert.equal(tokenCreateUnknown({ message: 'timeout', details: { serverCode: 'instance_timeout', httpStatus: 504, requestOutcome: 'unknown' } }), true) + assert.equal(tokenCreateUnknown({ message: 'Failed to fetch', details: { transport: 'network' } }), true) + // The request never reached the instance, or the Host refused it: issuing again is safe. + assert.equal(tokenCreateUnknown({ message: 'down', details: { serverCode: 'instance_unavailable', httpStatus: 503, requestOutcome: 'not-dispatched' } }), false) + assert.equal(tokenCreateUnknown(Object.assign(new Error('Forbidden'), { code: 'forbidden', status: 403 })), false) + assert.equal(tokenCreateUnknown({ message: 'bad name', details: { serverCode: 'invalid_input', httpStatus: 400 } }), false) +}) + +test('an iam.tokens.create reply keeps the Host requestOutcome', () => { + const t = text => text + const replied = body => { try { readIamReply(body.status, body.json, t) } catch (error) { return error } } + assert.equal(tokenCreateUnknown(replied({ status: 504, json: { success: false, code: 'instance_timeout', error: 'timeout', requestOutcome: 'unknown' } })), true) + // instance_unavailable usually means not sent; the Host saying `unknown` overrides that. + assert.equal(tokenCreateUnknown(replied({ status: 503, json: { success: false, code: 'instance_unavailable', error: 'down', requestOutcome: 'unknown' } })), true) + assert.equal(tokenCreateUnknown(replied({ status: 503, json: { success: false, code: 'instance_unavailable', error: 'down', requestOutcome: 'not-dispatched' } })), false) + assert.equal(tokenCreateUnknown(new TypeError('Failed to fetch')), true) + // A bare 502 / 504 from a proxy (no Host body) may have reached the instance too. + assert.equal(tokenCreateUnknown(replied({ status: 504, json: null })), true) + assert.equal(tokenCreateUnknown(authFailureAsError(readAuthResponse({ status: 502, body: 'Bad Gateway' }))), true) + assert.equal(tokenCreateUnknown(replied({ status: 500, json: null })), false) +}) + +test('a failed /auth/tokens call keeps the Host code and requestOutcome for that decision', () => { + const answer = readAuthResponse({ status: 504, body: { success: false, code: 'instance_timeout', error: 'The instance did not answer in time', requestOutcome: 'unknown' } }) + assert.equal(answer.requestOutcome, 'unknown') + assert.equal(tokenCreateUnknown(authFailureAsError(answer)), true) + const notSent = readAuthResponse({ status: 503, body: { success: false, code: 'instance_unavailable', error: 'down', requestOutcome: 'not-dispatched' } }) + assert.equal(tokenCreateUnknown(authFailureAsError(notSent)), false) + // fetch rejected (also a request that timed out after being sent): the token may exist. + assert.equal(tokenCreateUnknown(authFailureAsError(unreachableResult())), true) + assert.equal(tokenCreateUnknown(authFailureAsError(readAuthResponse({ status: 400, body: { success: false, code: 'invalid_input', error: 'name too long' } }))), false) + assert.equal(tokenCreateUnknown(authFailureAsError(readAuthResponse({ status: 403, body: { success: false, code: 'forbidden', error: 'no' } }))), false) +}) + +test('「核对」 finds a token of that name created around the attempt; an older namesake does not count', () => { + const since = Date.UTC(2026, 11, 1, 8) + const later = since + TOKEN_CREATE_SETTLE_MS + const plan = { name: 'deploy', userId: 'u1', since } + const fresh = tokenCreateCheck([{ id: 't1', name: 'deploy', userId: 'u1', createdAt: since + 1000 }], plan, 'zh-CN', since + 1000) + assert.equal(fresh.issued, true) + assert.deepEqual(fresh.ids, ['t1']) + assert.match(fresh.text, /吊销/) + assert.match(fresh.text, /只显示一次/) + assert.doesNotMatch(tokenCreateCheck([{ id: 't1', name: 'deploy', userId: 'u1', createdAt: since }], plan, 'en').text, CJK) + // A small clock difference between the browser and the Host still counts. + assert.equal(tokenCreateCheck([{ id: 't1', name: 'deploy', userId: 'u1', createdAt: since - 60_000 }], plan).issued, true) + const none = tokenCreateCheck([ + { id: 'old', name: 'deploy', userId: 'u1', createdAt: since - TOKEN_CREATE_CLOCK_SKEW_MS - 1 }, + { id: 'other', name: 'deploy', userId: 'u2', createdAt: since + 1000 }, + { id: 'x', name: 'ci', userId: 'u1', createdAt: since + 1000 }, + ], plan, 'zh-CN', later) + assert.equal(none.issued, false) + assert.equal(none.settled, true) + assert.match(none.text, /可以重新签发/) + assert.doesNotMatch(tokenCreateCheck([], plan, 'en', later).text, CJK) + // Right after a timeout the instance may still be writing it: nothing found yet does not unlock. + const early = tokenCreateCheck([], plan, 'zh-CN', since + 5000) + assert.equal(early.settled, false) + assert.match(early.text, /暂未找到[\s\S]*25 秒后再核对/) + assert.doesNotMatch(tokenCreateCheck([], plan, 'en', since + 5000).text, CJK) + // 个人设置 says 创建. + assert.match(tokenCreateCheck([], { ...plan, action: 'create' }, 'zh-CN', later).text, /可以重新创建/) + assert.match(tokenCreateCheck([{ id: 't1', name: 'deploy', userId: 'u1', createdAt: since }], { ...plan, action: 'create' }).text, /再重新创建/) + assert.doesNotMatch(tokenCreateCheck([{ id: 't1', name: 'deploy', userId: 'u1', createdAt: since }], { ...plan, action: 'create' }, 'en').text, CJK) + // A list reply without a token array is not an empty list. + assert.equal(tokenListOf({}), null) + assert.equal(tokenListOf({ tokens: 'x' }), null) + assert.deepEqual(tokenListOf({ tokens: [] }), []) + // Own tokens carry no user filter; an unreadable reply decides nothing. + assert.equal(tokenCreateCheck([{ id: 't1', name: 'deploy', userId: 'me', createdAt: since }], { name: 'deploy', since }).issued, true) + assert.throws(() => tokenCreateCheck(null, plan)) +}) + +test('both dialogs lock 「签发」/「创建」 on an unknown outcome and offer a read-only 「核对」', () => { + const admin = read('pages/access/tokens.tsx') + assert.match(admin, /if \(tokenCreateUnknown\(caught\)\) onHeld\(/) + // The page keeps the hold, so closing and reopening the dialog stays locked. + assert.match(admin, /const \[issueHold, setIssueHold\] = useState/) + assert.match(admin, /held=\{issueHold\} onHeld=\{setIssueHold\}/) + assert.match(admin, /disabled=\{saving \|\| !userId \|\| held !== null\}>\{saving \? i18n\.t\("处理中\.\.\."\) : i18n\.t\("签发"\)\}/) + assert.match(admin, /kind="unknown"[^>]*onVerify=/) + assert.match(admin, /const check = async \(\) => \{[\s\S]*?tokenCreateCheck\(tokenListOf\(await iamRequest\(IAM_RPC\.TOKENS_LIST/) + assert.match(admin, /if \(result\.issued \|\| !result\.settled\) onHeld/) + assert.doesNotMatch(admin.slice(admin.indexOf('const check = async'), admin.indexOf('return (\n ]*onVerify=/) + assert.doesNotMatch(own.slice(own.indexOf('const check = async'), own.indexOf('const changeOpen')), /createOwnToken/, '「核对」 never creates again') +}) From de9f278f74652355bff87a2aad71ca2bb4777389 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 08:38:09 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=E4=BB=A4=E7=89=8C=E6=A0=B8=E5=AF=B9?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E6=AF=94=E8=BE=83=20Host=20=E4=B8=8E?= =?UTF-8?q?=E6=B5=8F=E8=A7=88=E5=99=A8=E7=9A=84=E6=97=B6=E9=92=9F=EF=BC=8C?= =?UTF-8?q?=E5=B9=B6=E5=A4=84=E7=90=86=E8=BF=87=E6=9C=9F=E6=A0=B8=E5=AF=B9?= =?UTF-8?q?=E4=B8=8E=E6=97=A0=E4=BB=A4=E7=89=8C=E7=9A=84=E6=88=90=E5=8A=9F?= =?UTF-8?q?=E5=9B=9E=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 「核对」改为对照签发前页面已列出的令牌 id:不在其中的同名令牌才算刚签出 的那个;页面没有该用户的列表时,任何同名令牌都算(不再用 createdAt 和浏览器时间比较,避免时钟偏差把新令牌当成旧的而解锁)。 - 核对结果只作用于它开始时的锁定状态,过期的核对不会清掉更新的锁定。 - 2xx 但没有令牌(回复丢失或读不出)也按结果未知处理,锁住「签发」「创建」。 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SLUGBDtJbRzDTQgkyE1mGh --- .../pages/access/token-create-outcome.d.mts | 5 ++- .../src/pages/access/token-create-outcome.mjs | 23 ++++++++----- console-ui/src/pages/access/tokens.tsx | 33 +++++++++++++------ console-ui/src/pages/account/index.tsx | 27 ++++++++++----- tests/token-create-unknown-outcome.test.mjs | 21 +++++++++--- 5 files changed, 77 insertions(+), 32 deletions(-) diff --git a/console-ui/src/pages/access/token-create-outcome.d.mts b/console-ui/src/pages/access/token-create-outcome.d.mts index 425e98b1..5bed6903 100644 --- a/console-ui/src/pages/access/token-create-outcome.d.mts +++ b/console-ui/src/pages/access/token-create-outcome.d.mts @@ -1,4 +1,3 @@ -export declare const TOKEN_CREATE_CLOCK_SKEW_MS: number export declare const TOKEN_CREATE_SETTLE_MS: number export interface TokenCreateAuthFailure { @@ -15,6 +14,8 @@ export declare function authFailureAsError(failure: TokenCreateAuthFailure | nul export declare function tokenCreateUnknown(error: unknown): boolean +export declare function tokenCreateMissingSecret(message: string): Error & { details: { transport: 'invalid-response' } } + export declare function tokenListOf(payload: unknown): unknown[] | null export interface TokenCreatePlan { @@ -24,6 +25,8 @@ export interface TokenCreatePlan { readonly since?: number /** Wording: `issue` 签发 (default) or `create` 创建. */ readonly action?: 'issue' | 'create' + /** Ids of that user's tokens listed before the attempt (a namesake among them is not this one). */ + readonly knownIds?: readonly string[] | null } export declare function tokenCreateCheck( diff --git a/console-ui/src/pages/access/token-create-outcome.mjs b/console-ui/src/pages/access/token-create-outcome.mjs index 4e0f0d7a..d0db54b5 100644 --- a/console-ui/src/pages/access/token-create-outcome.mjs +++ b/console-ui/src/pages/access/token-create-outcome.mjs @@ -7,8 +7,6 @@ import { outcomeUnknown, serverCodeOf, statusFromError } from '../../components/ * nobody has; so the dialog locks 「签发」 and offers only 「核对」 (a read of the token list). */ -/** How long before the attempt a listed token may have been created and still be this one (clock skew). */ -export const TOKEN_CREATE_CLOCK_SKEW_MS = 10 * 60 * 1000 /** * After a timeout the instance may still be writing the token: a 「核对」 sooner than this after the * attempt that finds nothing does not unlock yet. @@ -60,12 +58,20 @@ export function tokenListOf(payload) { return isRecord(payload) && Array.isArray(payload.tokens) ? payload.tokens : null } +/** A reply to a create that succeeded but carried no token (lost or unreadable body): it may have been issued. */ +export function tokenCreateMissingSecret(message) { + return Object.assign(new Error(message), { details: { transport: 'invalid-response' } }) +} + /** - * 「核对」 after an unknown outcome, from a fresh token list. `plan` is `{ name, userId?, since, action? }` - * (`since`: when the request was sent; `action`: `issue` 签发 or `create` 创建, for the wording). - * A token with that name (for that user) created around or after the attempt means the token was - * probably issued: its secret is lost, so the user should revoke it and issue a new one - * (`issued: true`). None found means nothing was issued, but only once `TOKEN_CREATE_SETTLE_MS` have + * 「核对」 after an unknown outcome, from a fresh token list. `plan` is + * `{ name, userId?, since, action?, knownIds? }` (`since`: when the request was sent, by the browser's + * clock; `action`: `issue` 签发 or `create` 创建, for the wording; `knownIds`: the ids of that user's + * tokens listed before the attempt, when the page had them). + * A token with that name (for that user) that was not listed before means the token was probably + * issued: its secret is lost, so the user should revoke it and issue a new one (`issued: true`). + * Without `knownIds` any token of that name counts (the Host's `createdAt` is not compared with the + * browser's clock, which may be off). None found means nothing was issued, but only once `TOKEN_CREATE_SETTLE_MS` have * passed since the attempt (`settled`); sooner, the instance may still be writing it. The caller * unlocks only on `settled && !issued`. A reply without a list decides nothing: it throws. */ @@ -73,9 +79,10 @@ export function tokenCreateCheck(tokens, plan, locale = 'zh-CN', now = Date.now( if (!Array.isArray(tokens)) throw new TypeError('The token list is not readable') const create = plan?.action === 'create' const attempted = Number.isFinite(plan?.since) ? plan.since : -Infinity + const known = new Set(Array.isArray(plan?.knownIds) ? plan.knownIds : []) const found = tokens.filter(token => isRecord(token) && token.name === plan.name && (!plan.userId || token.userId === plan.userId) - && !(typeof token.createdAt === 'number' && token.createdAt < attempted - TOKEN_CREATE_CLOCK_SKEW_MS)) + && !known.has(token.id)) if (found.length) { return { issued: true, settled: true, ids: found.map(token => token.id), diff --git a/console-ui/src/pages/access/tokens.tsx b/console-ui/src/pages/access/tokens.tsx index 5d75f1bd..ddc228a7 100644 --- a/console-ui/src/pages/access/tokens.tsx +++ b/console-ui/src/pages/access/tokens.tsx @@ -1,4 +1,4 @@ -import { useEffect, useId, useMemo, useRef, useState } from 'react' +import { useEffect, useId, useMemo, useRef, useState, type Dispatch, type SetStateAction } from 'react' import { Copy, KeyRound, Plus, RefreshCw, Trash2 } from 'lucide-react' import { Link } from 'react-router-dom' import { CONSOLE_PATHS } from '../../console-routes.mjs' @@ -13,7 +13,7 @@ import { useToast } from '../../components/toast' import { TOKEN_EXPIRY_DAYS, tokenExpiresAt, tokenNameProblem } from '../../utils/console-auth-model.mjs' import { copyText } from '../clipboard-copy.mjs' import { IAM_RPC, readTokens, tokenExpired, type IamToken, type IamUser } from './access-model.mjs' -import { tokenCreateCheck, tokenCreateUnknown, tokenListOf } from './token-create-outcome.mjs' +import { tokenCreateCheck, tokenCreateMissingSecret, tokenCreateUnknown, tokenListOf } from './token-create-outcome.mjs' import { FormField, IamLoadError, ReadOnlyNotice } from './access-components' import { iamRequest, useCanManageIam, useIamRead, useIamUsers } from './use-iam' import '../admin-pages.css' @@ -22,7 +22,11 @@ const EMPTY_TOKENS: IamToken[] = [] const ALL = '*' /** An issue with an unknown outcome, not yet 核对-ed: kept by the page so reopening the dialog stays locked. */ -interface IssueHold { readonly name: string; readonly userId: string; readonly since: number; readonly error: unknown; readonly text?: string } +interface IssueHold { + readonly name: string; readonly userId: string; readonly since: number; readonly error: unknown; readonly text?: string + /** That user's token ids listed before the attempt, when the page had them (a namesake among them is not this one). */ + readonly knownIds: readonly string[] | null +} export default function AccessTokensPage() { const i18n = useI18n() @@ -148,6 +152,7 @@ export default function AccessTokensPage() { )} {issuing ? ( tokens.loaded && (userFilter === ALL || userFilter === owner) ? tokens.data.filter(token => token.userId === owner).map(token => token.id) : null} onClose={() => { setIssuing(false); if (issueHold) tokens.refresh() }} onIssued={value => { setIssuing(false); setIssued(value); tokens.refresh() @@ -165,12 +170,14 @@ export default function AccessTokensPage() { } /** `iam.tokens.create { userId, name, expiresAt? }`: a token carrying all of that user's permissions. */ -function IssueTokenDialog({ users, initialUser, held, onHeld, onClose, onIssued }: { +function IssueTokenDialog({ users, initialUser, held, onHeld, knownIds, onClose, onIssued }: { users: readonly IamUser[] initialUser: string /** A token may have been issued (no trustworthy answer): 「签发」 stays locked until 「核对」 finds none. */ held: IssueHold | null - onHeld: (hold: IssueHold | null) => void + onHeld: Dispatch> + /** Ids of the user's tokens the page has listed, or `null` when its list does not cover that user. */ + knownIds: (userId: string) => readonly string[] | null onClose: () => void onIssued: (value: { name: string; token: string; user: string; userId: string; id?: string }) => void }) { @@ -193,14 +200,16 @@ function IssueTokenDialog({ users, initialUser, held, onHeld, onClose, onIssued setSaving(true) setError(null) const since = Date.now() + const before = knownIds(userId) try { const expiresAt = tokenExpiresAt(Number(days)) const reply = await iamRequest<{ token?: unknown; record?: { name?: unknown; id?: unknown } }>(IAM_RPC.TOKENS_CREATE, { userId, name: name.trim(), ...(expiresAt ? { expiresAt } : {}) }, i18n.t) - if (typeof reply?.token !== 'string' || !reply.token) throw new Error(i18n.t('Host 没有返回令牌。请在列表里确认后重新签发。')) + // A success without a token (lost or unreadable body): it may have been issued. + if (typeof reply?.token !== 'string' || !reply.token) throw tokenCreateMissingSecret(i18n.t('Host 没有返回令牌。请在列表里确认后重新签发。')) onIssued({ name: typeof reply.record?.name === 'string' ? reply.record.name : name.trim(), token: reply.token, user: users.find(user => user.id === userId)?.username ?? userId, userId, ...(typeof reply.record?.id === 'string' ? { id: reply.record.id } : {}) }) } catch (caught) { - if (tokenCreateUnknown(caught)) onHeld({ name: name.trim(), userId, since, error: caught }) + if (tokenCreateUnknown(caught)) onHeld({ name: name.trim(), userId, since, error: caught, knownIds: before }) else setError(caught) } finally { setSaving(false) @@ -213,10 +222,14 @@ function IssueTokenDialog({ users, initialUser, held, onHeld, onClose, onIssued try { // A reply without a token list decides nothing (readTokens would read it as empty). const result = tokenCreateCheck(tokenListOf(await iamRequest(IAM_RPC.TOKENS_LIST, { userId: held.userId }, i18n.t)), held, i18n.locale) - if (result.issued || !result.settled) onHeld({ ...held, text: result.text }) - else { onHeld(null); toast.info(result.text) } + // Applies only to the hold this check started from (a newer one is left alone). + if (result.issued || !result.settled) onHeld(current => current === held ? { ...held, text: result.text } : current) + else { + onHeld(current => current === held ? null : current) + toast.info(result.text) + } } catch { - onHeld({ ...held, text: i18n.t('核对失败:没有读到令牌列表,请稍后再核对。') }) + onHeld(current => current === held ? { ...held, text: i18n.t('核对失败:没有读到令牌列表,请稍后再核对。') } : current) } finally { setChecking(false) } diff --git a/console-ui/src/pages/account/index.tsx b/console-ui/src/pages/account/index.tsx index e13d1ba6..501309e5 100644 --- a/console-ui/src/pages/account/index.tsx +++ b/console-ui/src/pages/account/index.tsx @@ -22,7 +22,7 @@ import { import { CONSOLE_PATHS as P } from '../../console-routes.mjs' import { builtinRoleLabel, scopeLabel } from '../access/access-model.mjs' import { IssuedTokenDialog } from '../access/tokens' -import { authFailureAsError, tokenCreateCheck, tokenCreateUnknown, tokenListOf } from '../access/token-create-outcome.mjs' +import { authFailureAsError, tokenCreateCheck, tokenCreateMissingSecret, tokenCreateUnknown, tokenListOf } from '../access/token-create-outcome.mjs' import { useToast } from '../../components/toast' import type { ConsoleApiTokenView, ConsoleMe } from '../../contracts/console-auth' import { MyChatIdentitySection } from '../../scope/ChatIdentityPanels' @@ -217,7 +217,7 @@ function TokensSection() { : null} {savedToken.element} - void load()} onCreated={(name, token) => { + void load()} knownIds={tokens ? tokens.map(token => token.id) : null} onCreated={(name, token) => { setCreated({ name, token }); void load() // The token is shown once in the dialog; the read-back only checks that it is listed. void savedToken.report(i18n.t('已新建令牌 {0}', [name]), outcomeFromAccessWrite({ secret: true }), async () => { @@ -230,18 +230,20 @@ function TokensSection() { } -function CreateTokenDialog({ open, onOpenChange, onCreated, onUncertain }: { +function CreateTokenDialog({ open, onOpenChange, onCreated, onUncertain, knownIds }: { open: boolean onOpenChange: (open: boolean) => void onCreated: (name: string, token: string) => void /** Closed after a creation with an unknown outcome: the list may hold a new token. */ onUncertain: () => void + /** Ids of the own tokens listed before (a namesake among them is not the new one); `null` when not loaded. */ + knownIds: readonly string[] | null }) { const i18n = useI18n() const toast = useToast() // A token may have been created (no trustworthy answer): 「创建」 stays locked until 「核对」 finds none. // Kept while the dialog is closed (it stays mounted), so reopening it stays locked. - const [held, setHeld] = useState<{ name: string; since: number; error: unknown; action: 'create'; text?: string } | null>(null) + const [held, setHeld] = useState<{ name: string; since: number; error: unknown; action: 'create'; knownIds: readonly string[] | null; text?: string } | null>(null) const [checking, setChecking] = useState(false) const [name, setName] = useState('') const [days, setDays] = useState(String(TOKEN_EXPIRY_DAYS[1])) @@ -256,13 +258,18 @@ function CreateTokenDialog({ open, onOpenChange, onCreated, onUncertain }: { if (held) return setBusy(true) const since = Date.now() + const before = knownIds const result = await createOwnToken({ name: name.trim(), expiresAt: tokenExpiresAt(Number(days)) }) setBusy(false) if (!result.ok) { const failure = authFailureAsError(result) - if (tokenCreateUnknown(failure)) { setError(''); setHeld({ name: name.trim(), since, error: failure, action: 'create' }); return } + if (tokenCreateUnknown(failure)) { setError(''); setHeld({ name: name.trim(), since, error: failure, action: 'create', knownIds: before }); return } setError(authErrorMessage(result, i18n.t, 'tokens')); return } + // A success without a token (lost or unreadable body): it may have been created. + if (typeof result.data?.token !== 'string' || !result.data.token) { + setError(''); setHeld({ name: name.trim(), since, error: tokenCreateMissingSecret(i18n.t('Host 没有返回令牌。请在列表里确认后重新签发。')), action: 'create', knownIds: before }); return + } onOpenChange(false) onCreated(result.data.record?.name ?? name.trim(), result.data.token) } @@ -275,10 +282,14 @@ function CreateTokenDialog({ open, onOpenChange, onCreated, onUncertain }: { const list = await readOwnTokenList() setChecking(false) const tokens = list.ok ? tokenListOf(list.data) : null - if (!tokens) { setHeld({ ...held, text: i18n.t('核对失败:没有读到令牌列表,请稍后再核对。') }); return } + // Applies only to the hold this check started from (a newer one is left alone). + if (!tokens) { setHeld(current => current === held ? { ...held, text: i18n.t('核对失败:没有读到令牌列表,请稍后再核对。') } : current); return } const result = tokenCreateCheck(tokens, held, i18n.locale) - if (result.issued || !result.settled) setHeld({ ...held, text: result.text }) - else { setHeld(null); toast.info(result.text) } + if (result.issued || !result.settled) setHeld(current => current === held ? { ...held, text: result.text } : current) + else { + setHeld(current => current === held ? null : current) + toast.info(result.text) + } } const changeOpen = (next: boolean) => { if (!next && busy) return diff --git a/tests/token-create-unknown-outcome.test.mjs b/tests/token-create-unknown-outcome.test.mjs index aabdec9b..19e4aaaf 100644 --- a/tests/token-create-unknown-outcome.test.mjs +++ b/tests/token-create-unknown-outcome.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict' import test from 'node:test' import { readFileSync } from 'node:fs' -import { authFailureAsError, tokenCreateCheck, tokenCreateUnknown, tokenListOf, TOKEN_CREATE_CLOCK_SKEW_MS, TOKEN_CREATE_SETTLE_MS } from '../console-ui/src/pages/access/token-create-outcome.mjs' +import { authFailureAsError, tokenCreateCheck, tokenCreateMissingSecret, tokenCreateUnknown, tokenListOf, TOKEN_CREATE_SETTLE_MS } from '../console-ui/src/pages/access/token-create-outcome.mjs' import { readAuthResponse, unreachableResult } from '../console-ui/src/utils/console-auth-model.mjs' import { readIamReply } from '../console-ui/src/pages/access/iam-request.mjs' @@ -35,6 +35,9 @@ test('an iam.tokens.create reply keeps the Host requestOutcome', () => { assert.equal(tokenCreateUnknown(replied({ status: 504, json: null })), true) assert.equal(tokenCreateUnknown(authFailureAsError(readAuthResponse({ status: 502, body: 'Bad Gateway' }))), true) assert.equal(tokenCreateUnknown(replied({ status: 500, json: null })), false) + // A 2xx whose body was lost or unreadable carries no token: it may have been issued. + assert.equal(replied({ status: 200, json: null }), undefined, 'the reader reports success') + assert.equal(tokenCreateUnknown(tokenCreateMissingSecret('no token')), true) }) test('a failed /auth/tokens call keeps the Host code and requestOutcome for that decision', () => { @@ -59,10 +62,13 @@ test('「核对」 finds a token of that name created around the attempt; an old assert.match(fresh.text, /吊销/) assert.match(fresh.text, /只显示一次/) assert.doesNotMatch(tokenCreateCheck([{ id: 't1', name: 'deploy', userId: 'u1', createdAt: since }], plan, 'en').text, CJK) - // A small clock difference between the browser and the Host still counts. - assert.equal(tokenCreateCheck([{ id: 't1', name: 'deploy', userId: 'u1', createdAt: since - 60_000 }], plan).issued, true) + // The Host's createdAt is not compared with the browser's clock: a browser 15 minutes fast still finds it. + assert.equal(tokenCreateCheck([{ id: 't1', name: 'deploy', userId: 'u1', createdAt: since - 15 * 60_000 }], plan, 'zh-CN', later).issued, true) + // A namesake the page listed before the attempt is not the new token. + const knownPlan = { ...plan, knownIds: ['old'] } + assert.equal(tokenCreateCheck([{ id: 'old', name: 'deploy', userId: 'u1', createdAt: since - 86_400_000 }], knownPlan, 'zh-CN', later).issued, false) + assert.equal(tokenCreateCheck([{ id: 'old', name: 'deploy', userId: 'u1' }, { id: 'new', name: 'deploy', userId: 'u1' }], knownPlan, 'zh-CN', later).issued, true) const none = tokenCreateCheck([ - { id: 'old', name: 'deploy', userId: 'u1', createdAt: since - TOKEN_CREATE_CLOCK_SKEW_MS - 1 }, { id: 'other', name: 'deploy', userId: 'u2', createdAt: since + 1000 }, { id: 'x', name: 'ci', userId: 'u1', createdAt: since + 1000 }, ], plan, 'zh-CN', later) @@ -97,7 +103,10 @@ test('both dialogs lock 「签发」/「创建」 on an unknown outcome and offe assert.match(admin, /disabled=\{saving \|\| !userId \|\| held !== null\}>\{saving \? i18n\.t\("处理中\.\.\."\) : i18n\.t\("签发"\)\}/) assert.match(admin, /kind="unknown"[^>]*onVerify=/) assert.match(admin, /const check = async \(\) => \{[\s\S]*?tokenCreateCheck\(tokenListOf\(await iamRequest\(IAM_RPC\.TOKENS_LIST/) - assert.match(admin, /if \(result\.issued \|\| !result\.settled\) onHeld/) + assert.match(admin, /if \(result\.issued \|\| !result\.settled\) onHeld\(current => current === held/) + assert.match(admin, /onHeld\(current => current === held \? null : current\)/, 'a stale check never clears a newer hold') + assert.match(admin, /throw tokenCreateMissingSecret\(/) + assert.match(admin, /knownIds: before/) assert.doesNotMatch(admin.slice(admin.indexOf('const check = async'), admin.indexOf('return (\n current === held \? null : current\)/) + assert.match(own, /typeof result\.data\?\.token !== 'string'[\s\S]*?tokenCreateMissingSecret/) assert.match(own, /kind="unknown"[^>]*onVerify=/) assert.doesNotMatch(own.slice(own.indexOf('const check = async'), own.indexOf('const changeOpen')), /createOwnToken/, '「核对」 never creates again') })