skillhub/cli/src/shared/output.ts
gale-popai d977ea9dc4
fix(api): tell callers why a request was forbidden (#610)
* fix(api): tell callers why a request was forbidden

The scope filter already computes an exact reason ("Missing API token
scope: skill:delete", "API token cannot access endpoint: /x") and the
access-denied handler discarded it, returning a bare "Forbidden" for
every case: missing scope, endpoint closed to API tokens, and paths
that simply don't exist. Clients cannot tell those apart, so they
guess — the published CLI reports every 403 as "token may lack
required scope", which sent us debugging token scopes for an hour when
the real causes were a revoked token and a mistyped namespace path.

The reason now rides in the response via a new error.forbidden.detail
message (en + zh), and is logged alongside the exception type.

Signed-off-by: Gal Eyal <gal.e@popai.health>

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(api): safely expose API token denial reasons

Signed-off-by: XiaoSeS <87064762+XiaoSeS@users.noreply.github.com>

---------

Signed-off-by: XiaoSeS <87064762+XiaoSeS@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: XiaoSeS <87064762+XiaoSeS@users.noreply.github.com>
2026-07-28 17:42:20 +08:00

47 lines
1.4 KiB
TypeScript

import { CliError } from './errors'
export type JsonObject = Record<string, unknown>
export function printResult(result: string | JsonObject, json: boolean): string {
if (json) {
return JSON.stringify(typeof result === 'string' ? { ok: true, message: result } : result)
}
return typeof result === 'string' ? result : humanize(result)
}
export function renderError(error: unknown, json: boolean): string {
const cliError = error instanceof CliError
? error
: new CliError('unexpected failure', 1)
if (json) {
return JSON.stringify({
ok: false,
message: cliError.message,
exitCode: cliError.exitCode,
...(Object.keys(cliError.details).length > 0 ? { details: cliError.details } : {})
})
}
const lines = [`Error: ${cliError.message}`]
if (typeof cliError.details.registry === 'string') {
lines.push(`Context: registry ${cliError.details.registry}`)
}
if (typeof cliError.details.path === 'string') {
lines.push(`Context: path ${cliError.details.path}`)
}
if (typeof cliError.details.requestId === 'string') {
lines.push(`Request ID: ${cliError.details.requestId}`)
}
if (typeof cliError.details.next === 'string') {
lines.push(`Next: ${cliError.details.next}`)
}
return lines.join('\n')
}
function humanize(value: JsonObject): string {
return Object.entries(value)
.filter(([key]) => key !== 'ok')
.map(([key, item]) => `${key}: ${String(item)}`)
.join('\n')
}