dsh-brain/src/api.ts

801 lines
31 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Thin client for the LongMemory cloud API (`/api/longmemory`).
*
* - Every call carries `Authorization: Bearer <token>`; the owner is injected
* server-side, so no request ever names a user.
* - Errors normalize to `{ status, code, message }`; a network failure is
* status 0 with code `network_error`, so callers can retry safely.
* - Only metadata ever leaves this process: turn ids, timestamps, statuses, and
* the memory content the user explicitly asked to save.
*/
import type { TurnStatus } from './reporter.ts'
/** Normalized non-2xx outcome. */
export interface CloudError {
/** HTTP status, or 0 for a transport failure. */
status: number
/** Machine-readable code from the service, or a local fallback. */
code: string
/** Human-readable message (already safe to show: never contains secrets). */
message: string
/** Milliseconds the service asked us to wait (429 handling). */
retryAfterMs?: number
}
/** One request outcome. */
export type CloudResult<T> = { ok: true; status: number; data: T } | { ok: false; error: CloudError }
/** Activity turn payload — exactly the six fields the service accepts. */
export interface TurnPayload {
client_id: string
conversation_id: string
turn_id: string
status: TurnStatus
started_at: number
completed_at: number
}
/** Activity turn outcome. */
export interface TurnAck {
recorded?: boolean
duplicate?: boolean
}
/** One transcript message sent for turn summarization (text only). */
export interface SummaryMessage {
role: 'user' | 'assistant'
text: string
}
/** `POST /activity/summary` request body. */
export interface SummaryPayload {
conversation_id: string
turn_id: string
messages: SummaryMessage[]
}
/** Staging outcome: how many proposals were queued for confirmation. */
export interface SummaryAck {
staged?: number
skipped?: number
full?: boolean
}
/** One search hit as the service indexes it. */
export interface MemoryHit {
id?: string
content?: string
tags?: string[]
project_id?: string | null
primary_sector?: string
revision?: number
created_at?: number
updated_at?: number
[key: string]: unknown
}
/** `POST /memory/query` response. */
export interface SearchResponse {
matches?: MemoryHit[]
total?: number
search_mode?: string
[key: string]: unknown
}
/** `GET /memory/all` response. */
export interface ListResponse {
items?: MemoryHit[]
total?: number
[key: string]: unknown
}
/** `GET /dashboard/projects` response. */
export interface ProjectsResponse {
projects?: { id?: string; name?: string; [key: string]: unknown }[]
[key: string]: unknown
}
/** `POST /memory/add` response. */
export interface AddResponse {
id?: string
revision?: number
deleted?: boolean
state?: string
remote_saved?: boolean
memory?: MemoryHit | null
[key: string]: unknown
}
/** One skill as the cloud skill center lists it (`GET /skills` item). */
export interface SkillSummary {
name: string
description?: string
category?: string | null
execution_mode?: string
enabled?: boolean
revision?: number
manifest_sha256?: string
files?: number
bytes?: number
script_changed?: boolean
/** Center creation time (ISO string; older servers may send epoch seconds). */
created_at?: string | number
/** Center last-change time — the timestamp the sync engine compares against local mtimes. */
updated_at?: string | number
[key: string]: unknown
}
/** `GET /skills` response. */
export interface SkillListing {
items?: SkillSummary[]
total?: number
trash_total?: number
[key: string]: unknown
}
/** One file inside a skill bundle (`GET /skills/:name/bundle`). */
export interface SkillBundleFile {
path: string
sha256: string
size?: number
encoding?: string
/** Base64 payload; present on every bundle file. */
data: string
}
/** `GET /skills/:name/bundle` response. */
export interface SkillBundle {
name: string
revision: number
manifest_sha256: string
script_changed?: boolean
script_changes?: string[]
files: SkillBundleFile[]
[key: string]: unknown
}
/** One file in a skill write payload: text inline, or base64 for binaries. */
export type SkillUploadFile = { path: string; content: string } | { path: string; base64: string }
/** `POST /skills` / `PATCH /skills/:name` outcome. */
export interface SkillWriteResult {
skill?: SkillSummary
revision?: number
manifest_sha256?: string
[key: string]: unknown
}
/** One dashboard account as the login endpoint returns it. */
export interface AccountInfo {
id?: string
username?: string
role?: string
[key: string]: unknown
}
/** Outcome of a password login: the account plus the session cookie to spend. */
export interface LoginOutcome {
user: AccountInfo
/** `name=value` pair ready for a Cookie header; never leaves this process. */
sessionCookie: string
}
/** One freshly minted API token. */
export interface IssuedToken {
id?: string
token?: string
scope?: string
label?: string
}
/**
* Derive the dashboard auth root (`/api/auth`) from the memory base URL
* (`.../api/longmemory`): login and token minting live one segment over.
*/
function authBase(baseUrl: string): string {
try {
const url = new URL(baseUrl)
const prefix = url.pathname.replace(/\/longmemory\/?$/i, '')
return `${url.origin}${prefix}/auth`
} catch {
return ''
}
}
/** True when sending a password to this URL is safe (TLS, or loopback). */
export function isSecureLoginTarget(baseUrl: string): boolean {
try {
const url = new URL(baseUrl)
if (url.protocol === 'https:') return true
return url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)
} catch {
return false
}
}
/** Pull the first cookie pair out of one or more Set-Cookie headers. */
function sessionCookieOf(headers: Headers): string {
// `getSetCookie` exists on undici/Node 18.14+ but is not in every Headers type.
const withCookies = headers as Headers & { getSetCookie?: () => string[] }
const list = typeof withCookies.getSetCookie === 'function' ? withCookies.getSetCookie() : [headers.get('set-cookie') ?? '']
for (const entry of list) {
if (entry === '') continue
const pair = entry.split(';', 1)[0]
if (pair !== undefined && pair.includes('=') && !pair.startsWith('=')) return pair.trim()
}
return ''
}
/** Options for one {@link CloudClient}. */
export interface CloudClientOptions {
/** Effective base URL (no trailing slash). */
baseUrl: () => string
/** Bearer token for the call's scope. */
token: () => string
/** Request timeout in milliseconds. */
timeoutMs: () => number
}
/**
* Optional frozen connection target for a multi-step auth flow.
*
* Login and minting happen in separate calls; without an override each call
* re-reads the live settings, so a settings edit between them would send the
* password and the session cookie to different services. Passing one target
* keeps the whole flow pinned to the connection snapshotted at its start.
*/
export interface CloudAuthTarget {
/** Base URL for this auth call (defaults to the client's live setting). */
baseUrl?: string
/** Timeout for this auth call (defaults to the client's live setting). */
timeoutMs?: number
}
/**
* Runtime response-shape guards.
*
* A 2xx with syntactically valid JSON but the wrong shape is still a failed
* call: without these checks `null` becomes `data: null` and every downstream
* `data.items ?? []` silently turns a contract violation into "empty". The
* helpers throw; request() normalizes the throw to `invalid_response`.
*/
function requireResponseObject(value: unknown, what: string): Record<string, unknown> {
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
throw new Error(`${what} must be a JSON object`)
}
return value as Record<string, unknown>
}
function requireResponseArray(body: Record<string, unknown>, key: string): unknown[] {
const value = body[key]
if (!Array.isArray(value)) throw new Error(`${key} must be an array`)
return value
}
function requireResponseString(body: Record<string, unknown>, key: string, allowEmpty = false): string {
const value = body[key]
if (typeof value !== 'string' || (!allowEmpty && value === '')) {
throw new Error(`${key} must be a non-empty string`)
}
return value
}
function optionalResponseString(body: Record<string, unknown>, key: string): void {
const value = body[key]
if (value !== undefined && typeof value !== 'string') throw new Error(`${key} must be a string`)
}
function optionalNullableString(body: Record<string, unknown>, key: string): void {
const value = body[key]
if (value !== undefined && value !== null && typeof value !== 'string') {
throw new Error(`${key} must be a string or null`)
}
}
function optionalResponseNumber(body: Record<string, unknown>, key: string): void {
const value = body[key]
if (value !== undefined && (typeof value !== 'number' || !Number.isFinite(value))) {
throw new Error(`${key} must be a number`)
}
}
function optionalResponseBoolean(body: Record<string, unknown>, key: string): void {
const value = body[key]
if (value !== undefined && typeof value !== 'boolean') throw new Error(`${key} must be a boolean`)
}
function optionalResponseStringArray(body: Record<string, unknown>, key: string): void {
const value = body[key]
if (value === undefined) return
if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string')) {
throw new Error(`${key} must be an array of strings`)
}
}
function optionalStringOrNumber(body: Record<string, unknown>, key: string): void {
const value = body[key]
if (value !== undefined && typeof value !== 'string' && typeof value !== 'number') {
throw new Error(`${key} must be a string or number`)
}
}
function validateTurnAck(value: unknown): TurnAck {
const body = requireResponseObject(value, 'activity turn response')
optionalResponseBoolean(body, 'recorded')
optionalResponseBoolean(body, 'duplicate')
return body as unknown as TurnAck
}
function validateSummaryAck(value: unknown): SummaryAck {
const body = requireResponseObject(value, 'activity summary response')
optionalResponseNumber(body, 'staged')
optionalResponseNumber(body, 'skipped')
optionalResponseBoolean(body, 'full')
return body as unknown as SummaryAck
}
function validateMemoryHitItem(value: unknown, what: string): MemoryHit {
const body = requireResponseObject(value, what)
optionalResponseString(body, 'id')
optionalResponseString(body, 'content')
optionalResponseStringArray(body, 'tags')
optionalResponseString(body, 'primary_sector')
if (body.project_id !== undefined && body.project_id !== null && typeof body.project_id !== 'string') {
throw new Error(`${what}.project_id must be a string or null`)
}
optionalResponseNumber(body, 'revision')
optionalResponseNumber(body, 'created_at')
optionalResponseNumber(body, 'updated_at')
return body as unknown as MemoryHit
}
function validateMemoryRead(value: unknown): MemoryHit {
const body = requireResponseObject(value, 'memory response')
requireResponseString(body, 'id')
return validateMemoryHitItem(body, 'memory response')
}
function validateSearchResponse(value: unknown): SearchResponse {
const body = requireResponseObject(value, 'memory search response')
const matches = requireResponseArray(body, 'matches')
matches.forEach((entry, index) => validateMemoryHitItem(entry, `matches[${index}]`))
optionalResponseNumber(body, 'total')
optionalResponseString(body, 'search_mode')
return body as unknown as SearchResponse
}
function validateListResponse(value: unknown): ListResponse {
const body = requireResponseObject(value, 'memory list response')
const items = requireResponseArray(body, 'items')
items.forEach((entry, index) => validateMemoryHitItem(entry, `items[${index}]`))
optionalResponseNumber(body, 'total')
return body as unknown as ListResponse
}
function validateProjectsResponse(value: unknown): ProjectsResponse {
const body = requireResponseObject(value, 'projects response')
const projects = requireResponseArray(body, 'projects')
projects.forEach((entry, index) => {
const project = requireResponseObject(entry, `projects[${index}]`)
optionalResponseString(project, 'id')
optionalResponseString(project, 'name')
})
return body as unknown as ProjectsResponse
}
function validateAddResponse(value: unknown): AddResponse {
const body = requireResponseObject(value, 'memory add response')
optionalResponseString(body, 'id')
optionalResponseNumber(body, 'revision')
optionalResponseBoolean(body, 'deleted')
optionalResponseString(body, 'state')
optionalResponseBoolean(body, 'remote_saved')
if (body.memory !== undefined && body.memory !== null) {
validateMemoryHitItem(body.memory, 'memory')
}
return body as unknown as AddResponse
}
function validateStorageStatus(value: unknown): Record<string, unknown> {
return requireResponseObject(value, 'storage status response')
}
function validateSkillSummary(value: unknown, what: string): SkillSummary {
const body = requireResponseObject(value, what)
requireResponseString(body, 'name')
optionalResponseString(body, 'description')
optionalNullableString(body, 'category')
optionalResponseString(body, 'execution_mode')
optionalResponseBoolean(body, 'enabled')
optionalResponseNumber(body, 'revision')
optionalResponseString(body, 'manifest_sha256')
optionalResponseNumber(body, 'files')
optionalResponseNumber(body, 'bytes')
optionalResponseBoolean(body, 'script_changed')
optionalStringOrNumber(body, 'created_at')
optionalStringOrNumber(body, 'updated_at')
return body as unknown as SkillSummary
}
function validateSkillListing(value: unknown): SkillListing {
const body = requireResponseObject(value, 'skills response')
const items = requireResponseArray(body, 'items')
items.forEach((entry, index) => validateSkillSummary(entry, `items[${index}]`))
optionalResponseNumber(body, 'total')
optionalResponseNumber(body, 'trash_total')
return body as unknown as SkillListing
}
function validateSkillBundle(value: unknown): SkillBundle {
const body = requireResponseObject(value, 'skill bundle response')
requireResponseString(body, 'name')
optionalResponseNumber(body, 'revision')
if (typeof body.revision !== 'number' || !Number.isFinite(body.revision)) {
throw new Error('revision must be a number')
}
requireResponseString(body, 'manifest_sha256')
optionalResponseBoolean(body, 'script_changed')
optionalResponseStringArray(body, 'script_changes')
const files = requireResponseArray(body, 'files')
files.forEach((entry, index) => {
const file = requireResponseObject(entry, `files[${index}]`)
requireResponseString(file, 'path')
requireResponseString(file, 'sha256')
requireResponseString(file, 'data', true)
optionalResponseNumber(file, 'size')
optionalResponseString(file, 'encoding')
})
return body as unknown as SkillBundle
}
function validateSkillWriteResult(value: unknown): SkillWriteResult {
const body = requireResponseObject(value, 'skill write response')
if (body.skill !== undefined && body.skill !== null) {
validateSkillSummary(body.skill, 'skill')
}
optionalResponseNumber(body, 'revision')
optionalResponseString(body, 'manifest_sha256')
return body as unknown as SkillWriteResult
}
/** Map one HTTP error body onto a {@link CloudError}. */
function errorFromBody(status: number, raw: string, retryAfterHeader: string | null): CloudError {
let code = `http_${status}`
let message = raw.slice(0, 300)
try {
const parsed: unknown = JSON.parse(raw)
if (parsed !== null && typeof parsed === 'object') {
const body = parsed as Record<string, unknown>
if (typeof body.error === 'string') code = body.error
else if (body.error !== null && typeof body.error === 'object') {
const nested = body.error as Record<string, unknown>
if (typeof nested.code === 'string') code = nested.code
if (typeof nested.message === 'string') message = nested.message
}
if (typeof body.message === 'string') message = body.message
}
} catch {
// Non-JSON error (proxy HTML page, empty body): keep the text snippet.
}
const error: CloudError = { status, code, message: message === '' ? code : message }
if (status === 429) {
const header = retryAfterHeader === null ? Number.NaN : Number(retryAfterHeader)
error.retryAfterMs = Number.isFinite(header) && header > 0 ? header * 1000 : 900_000
}
return error
}
/**
* One cloud endpoint handle. Instances are cheap: construct per call site and
* keep the live settings behind closures so a settings edit applies at once.
*/
export class CloudClient {
constructor(private readonly options: CloudClientOptions) {}
private async request<T>(
method: string,
path: string,
body?: unknown,
tokenOverride?: string,
validate?: (value: unknown) => T,
): Promise<CloudResult<T>> {
const token = tokenOverride ?? this.options.token()
const base = this.options.baseUrl()
const url = `${base}${path}`
const headers: Record<string, string> = { Accept: 'application/json' }
if (token !== '') headers.Authorization = `Bearer ${token}`
const init: RequestInit = { method, headers, signal: AbortSignal.timeout(this.options.timeoutMs()) }
if (body !== undefined) {
headers['Content-Type'] = 'application/json'
init.body = JSON.stringify(body)
}
let response: Response
try {
response = await fetch(url, init)
} catch (error) {
const reason = error instanceof Error ? error.message : String(error)
return { ok: false, error: { status: 0, code: 'network_error', message: `${method} ${path}: ${reason}` } }
}
// A failed body read (connection torn mid-response) is NOT an empty
// success: a 200 whose payload cannot be read must surface as an error,
// not as `{ ok: true, data: {} }`.
let text: string
try {
text = await response.text()
} catch (error) {
const reason = error instanceof Error ? error.message : String(error)
if (!response.ok) {
return { ok: false, error: errorFromBody(response.status, `body read failed: ${reason}`, response.headers.get('retry-after')) }
}
return { ok: false, error: { status: response.status, code: 'body_read_error', message: `${method} ${path}: body read failed: ${reason}` } }
}
if (!response.ok) {
return { ok: false, error: errorFromBody(response.status, text, response.headers.get('retry-after')) }
}
// Empty bodies are endpoint-specific: the validator decides whether `{}`
// is an acceptable 2xx payload (add/turn acknowledgements) or a missing
// required field (list/search/projects/skills/bundle). Probes pass no
// validator on purpose: any 2xx already proves the credential, and a 400
// remains their "authenticated but bad body" signal.
let parsed: unknown = {}
if (text.trim() !== '') {
try {
parsed = JSON.parse(text)
} catch {
return { ok: false, error: { status: response.status, code: 'invalid_json', message: `${method} ${path}: response was not JSON` } }
}
}
if (validate !== undefined) {
try {
validate(parsed)
} catch (error) {
const reason = error instanceof Error ? error.message : String(error)
return { ok: false, error: { status: response.status, code: 'invalid_response', message: `${method} ${path}: ${reason}` } }
}
}
return { ok: true, status: response.status, data: parsed as T }
}
/** Report one conversation turn (activity:write token). */
reportTurn(payload: TurnPayload, token: string): Promise<CloudResult<TurnAck>> {
return this.request<TurnAck>('POST', '/activity/turn', payload, token, validateTurnAck)
}
/**
* Read-only reachability probe: any HTTP answer (even 401 or 404) proves the
* host is up. This is what separates "服务不可达" from "令牌无效" in the card,
* and it never sends a credential.
*/
async reach(): Promise<{ ok: boolean; status: number; message: string }> {
try {
const response = await fetch(`${this.options.baseUrl()}/status`, {
method: 'GET',
headers: { Accept: 'application/json' },
signal: AbortSignal.timeout(this.options.timeoutMs()),
})
return { ok: true, status: response.status, message: `服务可达(HTTP ${response.status})` }
} catch (error) {
const reason = error instanceof Error ? error.message : String(error)
return { ok: false, status: 0, message: `服务不可达:${reason}` }
}
}
/** Stage one turn summary as pending proposals (summary:write token). */
submitSummary(payload: SummaryPayload, token: string): Promise<CloudResult<SummaryAck>> {
return this.request<SummaryAck>('POST', '/activity/summary', payload, token, validateSummaryAck)
}
/**
* Verify a summary token without staging anything.
*
* The endpoint authenticates before it validates the body, so an empty
* object coming back `400 invalid_input` proves the scope is right.
*/
async probeSummary(token: string): Promise<CloudResult<{ authenticated: true }>> {
const result = await this.request<unknown>('POST', '/activity/summary', {}, token)
if (result.ok) return { ok: true, status: result.status, data: { authenticated: true } }
if (result.error.status === 400) return { ok: true, status: 400, data: { authenticated: true } }
return { ok: false, error: result.error }
}
/**
* Verify an activity token without recording anything.
*
* `/activity/turn` validates auth before the payload, so an empty body that
* comes back `400 invalid_event` proves the token carries `activity:write`.
* A 401/403 is a token problem; anything else is reported verbatim.
*/
async probeActivity(token: string): Promise<CloudResult<{ authenticated: true }>> {
const result = await this.request<unknown>('POST', '/activity/turn', {}, token)
if (result.ok) return { ok: true, status: result.status, data: { authenticated: true } }
// 400 means the credentials were accepted and only the body was rejected.
if (result.error.status === 400) {
return { ok: true, status: 400, data: { authenticated: true } }
}
return { ok: false, error: result.error }
}
/** Keyword search over stored memories (memory token). */
async search(query: string, k: number, project?: string): Promise<CloudResult<SearchResponse>> {
const body: Record<string, unknown> = { query, k }
if (project !== undefined && project !== '') body.filters = { project_id: project }
return this.request<SearchResponse>('POST', '/memory/query', body, undefined, validateSearchResponse)
}
/** Read one memory by id (memory token). */
read(id: string): Promise<CloudResult<MemoryHit>> {
return this.request<MemoryHit>('GET', `/memory/${encodeURIComponent(id)}`, undefined, undefined, validateMemoryRead)
}
/** List memories with optional paging filters (memory token). */
list(options: { limit?: number; offset?: number; project?: string } = {}): Promise<CloudResult<ListResponse>> {
const params = new URLSearchParams()
if (options.limit !== undefined) params.set('limit', String(options.limit))
if (options.offset !== undefined) params.set('offset', String(options.offset))
if (options.project !== undefined && options.project !== '') params.set('project_id', options.project)
const suffix = params.toString() === '' ? '' : `?${params.toString()}`
return this.request<ListResponse>('GET', `/memory/all${suffix}`, undefined, undefined, validateListResponse)
}
/** Store one memory; `operationId` makes the write idempotent (memory token). */
add(input: { content: string; tags?: string[]; project?: string; sector?: string; operationId: string }): Promise<CloudResult<AddResponse>> {
const body: Record<string, unknown> = {
operation_id: input.operationId,
content: input.content,
}
if (input.tags !== undefined && input.tags.length > 0) body.tags = input.tags
if (input.project !== undefined && input.project !== '') body.project_id = input.project
if (input.sector !== undefined && input.sector !== '') body.metadata = { primary_sector: input.sector }
return this.request<AddResponse>('POST', '/memory/add', body, undefined, validateAddResponse)
}
/** List the account's projects (memory token). */
projects(): Promise<CloudResult<ProjectsResponse>> {
return this.request<ProjectsResponse>('GET', '/dashboard/projects', undefined, undefined, validateProjectsResponse)
}
/** Storage configuration state (memory token). */
storageStatus(): Promise<CloudResult<Record<string, unknown>>> {
return this.request<Record<string, unknown>>('GET', '/storage/status', undefined, undefined, validateStorageStatus)
}
/** List the cloud skill center inventory (memory token). */
listSkills(): Promise<CloudResult<SkillListing>> {
return this.request<SkillListing>('GET', '/skills', undefined, undefined, validateSkillListing)
}
/** Fetch one skill bundle with hashed, base64-carried files (memory token). */
skillBundle(name: string): Promise<CloudResult<SkillBundle>> {
return this.request<SkillBundle>('GET', `/skills/${encodeURIComponent(name)}/bundle`, undefined, undefined, validateSkillBundle)
}
/** Create one skill in the center; `expected_revision` must be 0 (memory token). */
createSkill(body: Record<string, unknown>): Promise<CloudResult<SkillWriteResult>> {
return this.request<SkillWriteResult>('POST', '/skills', body, undefined, validateSkillWriteResult)
}
/** Replace one skill's files/description at an expected revision (memory token). */
updateSkill(name: string, body: Record<string, unknown>): Promise<CloudResult<SkillWriteResult>> {
return this.request<SkillWriteResult>('PATCH', `/skills/${encodeURIComponent(name)}`, body, undefined, validateSkillWriteResult)
}
/**
* One call against the dashboard auth surface (`/api/auth/*`).
*
* These endpoints authorize by session cookie, not by Bearer token, and they
* reject any non-GET without a matching `Origin` (the server's CSRF gate), so
* the origin of the configured base URL is sent explicitly — that is a header
* only a non-browser client can set, which is exactly what this is.
*/
private async authFetch(
method: string,
path: string,
body?: unknown,
cookie?: string,
target?: CloudAuthTarget,
): Promise<{ ok: true; status: number; body: unknown; headers: Headers } | { ok: false; error: CloudError }> {
// The target is frozen by the caller at the start of the login flow; every
// auth request in that flow must hit the same service, even if settings
// change while a request is in flight.
const baseUrl = target?.baseUrl ?? this.options.baseUrl()
const timeoutMs = target?.timeoutMs ?? this.options.timeoutMs()
const base = authBase(baseUrl)
if (base === '') return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } }
const headers: Record<string, string> = { Accept: 'application/json' }
try {
headers.Origin = new URL(baseUrl).origin
} catch {
return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } }
}
if (cookie !== undefined && cookie !== '') headers.Cookie = cookie
const init: RequestInit = { method, headers, signal: AbortSignal.timeout(timeoutMs) }
if (body !== undefined) {
headers['Content-Type'] = 'application/json'
init.body = JSON.stringify(body)
}
let response: Response
try {
response = await fetch(`${base}${path}`, init)
} catch (error) {
const reason = error instanceof Error ? error.message : String(error)
return { ok: false, error: { status: 0, code: 'network_error', message: `${method} /auth${path}: ${reason}` } }
}
let text: string
try {
text = await response.text()
} catch (error) {
const reason = error instanceof Error ? error.message : String(error)
if (!response.ok) {
return { ok: false, error: errorFromBody(response.status, `body read failed: ${reason}`, response.headers.get('retry-after')) }
}
return { ok: false, error: { status: response.status, code: 'body_read_error', message: `${method} /auth${path}: body read failed: ${reason}` } }
}
if (!response.ok) {
return { ok: false, error: errorFromBody(response.status, text, response.headers.get('retry-after')) }
}
let parsed: unknown = {}
if (text.trim() !== '') {
try {
parsed = JSON.parse(text)
} catch {
// Swallowing a malformed login/token body would make the caller treat
// garbage as an empty success; surface it as a normalized failure.
return { ok: false, error: { status: response.status, code: 'invalid_json', message: `${method} /auth${path}: response was not JSON` } }
}
}
return { ok: true, status: response.status, body: parsed, headers: response.headers }
}
/**
* Password login against the dashboard.
*
* The password is used once, in this call, and never stored: what comes back
* is a short-lived session cookie that the caller immediately spends on
* {@link CloudClient.mintToken} and then drops.
*/
async login(username: string, password: string, target?: CloudAuthTarget): Promise<CloudResult<LoginOutcome>> {
const sent = await this.authFetch('POST', '/login', { username, password }, undefined, target)
if (!sent.ok) return sent
const cookie = sessionCookieOf(sent.headers)
if (cookie === '') {
return { ok: false, error: { status: sent.status, code: 'no_session', message: '登录成功,但服务端没有下发会话' } }
}
let body: Record<string, unknown>
try {
body = requireResponseObject(sent.body, 'login response')
if (body.user !== undefined && body.user !== null) requireResponseObject(body.user, 'login response user')
} catch (error) {
const reason = error instanceof Error ? error.message : String(error)
return { ok: false, error: { status: sent.status, code: 'invalid_response', message: `POST /auth/login: ${reason}` } }
}
const user = (body.user ?? {}) as AccountInfo
return { ok: true, status: sent.status, data: { user, sessionCookie: cookie } }
}
/** Mint one scoped API token using a live session cookie. */
async mintToken(sessionCookie: string, scope: string, label: string, target?: CloudAuthTarget): Promise<CloudResult<IssuedToken>> {
const sent = await this.authFetch('POST', '/tokens', { scope, label }, sessionCookie, target)
if (!sent.ok) return sent
try {
const body = requireResponseObject(sent.body, 'token response')
const issued = requireResponseObject(body.token, 'token response token')
requireResponseString(issued, 'token')
optionalResponseString(issued, 'id')
optionalResponseString(issued, 'scope')
optionalResponseString(issued, 'label')
return { ok: true, status: sent.status, data: issued as unknown as IssuedToken }
} catch (error) {
const reason = error instanceof Error ? error.message : String(error)
return { ok: false, error: { status: sent.status, code: 'invalid_response', message: `POST /auth/tokens: ${reason}` } }
}
}
}
/** Render a {@link CloudError} as one display line. */
export function describeError(error: CloudError): string {
if (error.status === 0) return `网络不可用:${error.message}`
return `HTTP ${error.status} ${error.code}:${error.message}`
}