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..5bed6903 --- /dev/null +++ b/console-ui/src/pages/access/token-create-outcome.d.mts @@ -0,0 +1,37 @@ +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 tokenCreateMissingSecret(message: string): Error & { details: { transport: 'invalid-response' } } + +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' + /** 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( + 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..d0db54b5 --- /dev/null +++ b/console-ui/src/pages/access/token-create-outcome.mjs @@ -0,0 +1,104 @@ +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). + */ + +/** + * 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 +} + +/** 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?, 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. + */ +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) + && !known.has(token.id)) + 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..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,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, 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' @@ -20,6 +21,13 @@ 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 + /** 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() const canManage = useCanManageIam() @@ -30,6 +38,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 +151,9 @@ export default function AccessTokensPage() { )} {issuing ? ( - setIssuing(false)} + 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() // The secret is shown once in the dialog; the read-back only checks the token is listed. @@ -159,13 +170,19 @@ 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, 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: 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 }) { 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,25 +191,49 @@ 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() + 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) { - setError(caught) + if (tokenCreateUnknown(caught)) onHeld({ name: name.trim(), userId, since, error: caught, knownIds: before }) + 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) + // 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(current => current === held ? { ...held, text: i18n.t('核对失败:没有读到令牌列表,请稍后再核对。') } : current) + } finally { + setChecking(false) + } + } return ( { if (!open && !saving) onClose() }}> @@ -212,10 +253,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..501309e5 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, 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' import '../admin-pages.css' @@ -215,7 +217,7 @@ function TokensSection() { : null} {savedToken.element} - { + 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 () => { @@ -228,12 +230,21 @@ function TokensSection() { } -function CreateTokenDialog({ open, onOpenChange, onCreated }: { +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'; 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])) const [error, setError] = useState('') @@ -244,15 +255,49 @@ 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 before = knownIds 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', 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) } - 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 + // 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(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 + if (!next && held) onUncertain() + onOpenChange(next) + } + + return
{ event.preventDefault(); void submit() }} className="grid gap-4"> @@ -270,9 +315,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..19e4aaaf --- /dev/null +++ b/tests/token-create-unknown-outcome.test.mjs @@ -0,0 +1,121 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { readFileSync } from 'node:fs' +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' + +// #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) + // 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', () => { + 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) + // 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: '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\(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') +})