Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions console-ui/src/i18n/messages.en.admin.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
})
4 changes: 3 additions & 1 deletion console-ui/src/pages/access/iam-request.d.mts
Original file line number Diff line number Diff line change
@@ -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
Expand Down
6 changes: 4 additions & 2 deletions console-ui/src/pages/access/iam-request.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@ 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
this.code = code
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 }
}
}

Expand Down Expand Up @@ -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 })
}
37 changes: 37 additions & 0 deletions console-ui/src/pages/access/token-create-outcome.d.mts
Original file line number Diff line number Diff line change
@@ -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 }
104 changes: 104 additions & 0 deletions console-ui/src/pages/access/token-create-outcome.mjs
Original file line number Diff line number Diff line change
@@ -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]),
}
}
Loading