/** * 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) { 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) { 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) { // `getSetCookie` exists on undici/Node 18.14+ but is not in every Headers type. const withCookies = headers; 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 ''; } /** * 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, what) { if (value === null || typeof value !== 'object' || Array.isArray(value)) { throw new Error(`${what} must be a JSON object`); } return value; } function requireResponseArray(body, key) { const value = body[key]; if (!Array.isArray(value)) throw new Error(`${key} must be an array`); return value; } function requireResponseString(body, key, allowEmpty = false) { 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, key) { const value = body[key]; if (value !== undefined && typeof value !== 'string') throw new Error(`${key} must be a string`); } function optionalNullableString(body, key) { 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, key) { const value = body[key]; if (value !== undefined && (typeof value !== 'number' || !Number.isFinite(value))) { throw new Error(`${key} must be a number`); } } function optionalResponseBoolean(body, key) { const value = body[key]; if (value !== undefined && typeof value !== 'boolean') throw new Error(`${key} must be a boolean`); } function optionalResponseStringArray(body, key) { 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, key) { 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) { const body = requireResponseObject(value, 'activity turn response'); optionalResponseBoolean(body, 'recorded'); optionalResponseBoolean(body, 'duplicate'); return body; } function validateSummaryAck(value) { const body = requireResponseObject(value, 'activity summary response'); optionalResponseNumber(body, 'staged'); optionalResponseNumber(body, 'skipped'); optionalResponseBoolean(body, 'full'); return body; } function validateMemoryHitItem(value, what) { 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; } function validateMemoryRead(value) { const body = requireResponseObject(value, 'memory response'); requireResponseString(body, 'id'); return validateMemoryHitItem(body, 'memory response'); } function validateSearchResponse(value) { 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; } function validateListResponse(value) { 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; } function validateProjectsResponse(value) { 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; } function validateAddResponse(value) { 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; } function validateStorageStatus(value) { return requireResponseObject(value, 'storage status response'); } function validateSkillSummary(value, what) { 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; } function validateSkillListing(value) { 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; } function validateSkillBundle(value) { 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; } function validateSkillWriteResult(value) { 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; } /** Map one HTTP error body onto a {@link CloudError}. */ function errorFromBody(status, raw, retryAfterHeader) { let code = `http_${status}`; let message = raw.slice(0, 300); try { const parsed = JSON.parse(raw); if (parsed !== null && typeof parsed === 'object') { const body = parsed; if (typeof body.error === 'string') code = body.error; else if (body.error !== null && typeof body.error === 'object') { const nested = body.error; 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 = { 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 { options; constructor(options) { this.options = options; } async request(method, path, body, tokenOverride, validate) { const token = tokenOverride ?? this.options.token(); const base = this.options.baseUrl(); const url = `${base}${path}`; const headers = { Accept: 'application/json' }; if (token !== '') headers.Authorization = `Bearer ${token}`; const init = { method, headers, signal: AbortSignal.timeout(this.options.timeoutMs()) }; if (body !== undefined) { headers['Content-Type'] = 'application/json'; init.body = JSON.stringify(body); } let 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; 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 = {}; 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 }; } /** Report one conversation turn (activity:write token). */ reportTurn(payload, token) { return this.request('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() { 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, token) { return this.request('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) { const result = await this.request('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) { const result = await this.request('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, k, project) { const body = { query, k }; if (project !== undefined && project !== '') body.filters = { project_id: project }; return this.request('POST', '/memory/query', body, undefined, validateSearchResponse); } /** Read one memory by id (memory token). */ read(id) { return this.request('GET', `/memory/${encodeURIComponent(id)}`, undefined, undefined, validateMemoryRead); } /** List memories with optional paging filters (memory token). */ list(options = {}) { 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('GET', `/memory/all${suffix}`, undefined, undefined, validateListResponse); } /** Store one memory; `operationId` makes the write idempotent (memory token). */ add(input) { const body = { 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('POST', '/memory/add', body, undefined, validateAddResponse); } /** List the account's projects (memory token). */ projects() { return this.request('GET', '/dashboard/projects', undefined, undefined, validateProjectsResponse); } /** Storage configuration state (memory token). */ storageStatus() { return this.request('GET', '/storage/status', undefined, undefined, validateStorageStatus); } /** List the cloud skill center inventory (memory token). */ listSkills() { return this.request('GET', '/skills', undefined, undefined, validateSkillListing); } /** Fetch one skill bundle with hashed, base64-carried files (memory token). */ skillBundle(name) { return this.request('GET', `/skills/${encodeURIComponent(name)}/bundle`, undefined, undefined, validateSkillBundle); } /** Create one skill in the center; `expected_revision` must be 0 (memory token). */ createSkill(body) { return this.request('POST', '/skills', body, undefined, validateSkillWriteResult); } /** Replace one skill's files/description at an expected revision (memory token). */ updateSkill(name, body) { return this.request('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. */ async authFetch(method, path, body, cookie, target) { // 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 = { 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 = { method, headers, signal: AbortSignal.timeout(timeoutMs) }; if (body !== undefined) { headers['Content-Type'] = 'application/json'; init.body = JSON.stringify(body); } let 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; 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 = {}; 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, password, target) { 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; 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 ?? {}); return { ok: true, status: sent.status, data: { user, sessionCookie: cookie } }; } /** Mint one scoped API token using a live session cookie. */ async mintToken(sessionCookie, scope, label, target) { 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 }; } 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) { if (error.status === 0) return `网络不可用:${error.message}`; return `HTTP ${error.status} ${error.code}:${error.message}`; }