import { createHash } from "node:crypto"; import { type NextRequest, type NextResponse } from "next/server"; import type { AppConfig, ManagedOssConfig, ManagedOtsConfig, } from "@tablestore/tablestore-agent-shared"; import { CLIError, DEFAULT_REGION, DEFAULT_TIMEOUT, decodeToken, encodeTokenV2, getActiveInstanceName, readInstance, } from "@tablestore/tablestore-agent-shared"; import { KnowledgeBaseClient, MemoryClient, WikiClient, inferRegionFromOtsEndpoint, } from "@tablestore/tablestore-agent-sdk"; const EMPTY_MANAGED_OTS: ManagedOtsConfig = { ots_endpoint: "", ots_instance_name: "", region: "", source: "", created_at: "", }; const EMPTY_MANAGED_OSS: ManagedOssConfig = { oss_endpoint: "", oss_bucket_name: "", region: "", source: "", created_at: "", }; // The legacy single-instance schema let `buildAppConfig` re-read the active // instance from disk to hydrate `managed_*` whenever the cookie carried only // raw credentials. With strict per-instance isolation in shared/sdk that // fallback is no longer correct (it could re-hydrate from the wrong // instance after a CLI-side switch in another terminal). The cookie issued // by `use/route.ts` now projects the per-instance managed_* coordinates // onto the flat `oss_*`/`ots_*` fields directly, so the SDK can be // constructed from cookie alone. // --------------------------------------------------------------------------- // Cookie / token constants // --------------------------------------------------------------------------- export const SESSION_COOKIE_NAME = "tablestore_token"; export const ACTIVE_INSTANCE_COOKIE_NAME = "tablestore_active_instance"; export const TOKEN_SOURCE_COOKIE_NAME = "tablestore_token_source"; const COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30; // 30 days const RAW_TOKEN_SOURCE = "raw"; const INSTANCE_TOKEN_SOURCE = "instance"; const FORCE_ENV_VALUE = "1"; const COOKIE_OPTIONS = { httpOnly: true, sameSite: "strict" as const, secure: process.env.NODE_ENV === "production", path: "/", }; export function setActiveInstanceCookie( response: NextResponse, instanceName: string, ): void { response.cookies.set({ ...COOKIE_OPTIONS, name: ACTIVE_INSTANCE_COOKIE_NAME, value: encodeURIComponent(instanceName), maxAge: COOKIE_MAX_AGE_SECONDS, }); } export function clearActiveInstanceCookie(response: NextResponse): void { response.cookies.set({ ...COOKIE_OPTIONS, name: ACTIVE_INSTANCE_COOKIE_NAME, value: "", maxAge: 0, }); } export function setRawTokenSourceCookie(response: NextResponse): void { response.cookies.set({ ...COOKIE_OPTIONS, name: TOKEN_SOURCE_COOKIE_NAME, value: RAW_TOKEN_SOURCE, maxAge: COOKIE_MAX_AGE_SECONDS, }); } export function setInstanceTokenSourceCookie(response: NextResponse): void { response.cookies.set({ ...COOKIE_OPTIONS, name: TOKEN_SOURCE_COOKIE_NAME, value: INSTANCE_TOKEN_SOURCE, maxAge: COOKIE_MAX_AGE_SECONDS, }); } export function clearTokenSourceCookie(response: NextResponse): void { response.cookies.set({ ...COOKIE_OPTIONS, name: TOKEN_SOURCE_COOKIE_NAME, value: "", maxAge: 0, }); } export function setInstanceSessionCookies( response: NextResponse, instanceName: string, ): boolean { const fields = tokenFieldsForInstance(instanceName); if (!fields) return false; response.cookies.set({ ...COOKIE_OPTIONS, name: SESSION_COOKIE_NAME, value: encodeTokenV2(fields), }); setActiveInstanceCookie(response, instanceName); setInstanceTokenSourceCookie(response); return true; } // --------------------------------------------------------------------------- // Resolved clients // --------------------------------------------------------------------------- export type CredentialSource = "cookie" | "instance" | "env"; export interface ResolvedClients { kb: KnowledgeBaseClient; memory: MemoryClient; wiki: WikiClient; config: AppConfig; source: CredentialSource; /** Trusted active project name for named-instance requests, else null. */ instanceName: string | null; } /** * Resolve credentials from the active named instance in the local config TOML. * * Reads the active instance section directly from disk via `readInstance`, * bypassing `loadConfigWithSources` on purpose: that loader is shared with * the CLI and overlays `TABLESTORE_*` process env vars on top of the section * fields (env wins). For the dashboard that is wrong — `tablestore-agent-cli * dashboard start` ALWAYS injects start-time env vars from whichever * instance was active when the process launched, and they are immutable for * the process lifetime. With the overlay in place, switching projects would * change the active pointer in TOML but every section field (AK, endpoint, * instance name, region) would still be clobbered back to the start-time * values, so requests like `/api/v1/api-keys` reach IMS with the old AK and * the user sees "switch had no effect". * * The reading shape here matches `tokenFieldsForInstance` and the `/use` * route's token-encoding logic so all three places agree on which fields * define an instance. * * Returns null when no named instance is active, the named section is * missing core fields, or disk I/O fails — caller falls back to env vars. */ export function configFromActiveInstance(): { fields: Record; instanceName: string; } | null { const activeName = safeGetActiveInstanceName(); if (!activeName) return null; let detail: ReturnType; try { detail = readInstance(activeName); } catch { return null; } if (!detail) return null; const ots = detail.managed_ots; const oss = detail.managed_oss; const fields = { access_key_id: detail.access_key_id, access_key_secret: detail.access_key_secret, api_key: detail.api_key, ots_endpoint: detail.ots_endpoint || ots.ots_endpoint, ots_instance_name: detail.ots_instance_name || ots.ots_instance_name, oss_endpoint: detail.oss_endpoint || oss.oss_endpoint, oss_bucket_name: detail.oss_bucket_name || oss.oss_bucket_name, region: detail.region || ots.region || oss.region, }; // A usable instance needs an endpoint/instance and at least one data-plane // credential: the AK/SK pair, or an API Key (which takes precedence). const hasAkSk = Boolean(fields.access_key_id && fields.access_key_secret); const hasApiKey = Boolean(fields.api_key); if ( (!hasAkSk && !hasApiKey) || !fields.ots_endpoint || !fields.ots_instance_name ) { return null; } return { fields, instanceName: activeName }; } function buildAppConfig(fields: Record): AppConfig { const otsEndpoint = fields.ots_endpoint ?? ""; const inferredRegion = otsEndpoint ? (inferRegionFromOtsEndpoint(otsEndpoint) ?? "") : ""; // The cookie issued by `use/route.ts` already projects the per-instance // managed_* coordinates onto the flat `oss_*`/`ots_*` fields, so the SDK // can resolve every endpoint from the cookie alone. Passing empty // managed_* placeholders here keeps the AppConfig shape stable for the // few SDK helpers that still touch those fields without re-introducing a // disk-backed fallback that could leak across instances. return { access_key_id: fields.access_key_id ?? "", access_key_secret: fields.access_key_secret ?? "", api_key: fields.api_key ?? "", ots_endpoint: otsEndpoint, ots_instance_name: fields.ots_instance_name ?? "", oss_endpoint: fields.oss_endpoint ?? "", oss_bucket_name: fields.oss_bucket_name ?? "", region: fields.region || inferredRegion || DEFAULT_REGION, memory_store_name: "", memory_app_id: "", memory_tenant_id: "", memory_agent_id: "", memory_run_id: "", timeout: DEFAULT_TIMEOUT, managed_ots: { ...EMPTY_MANAGED_OTS }, managed_oss: { ...EMPTY_MANAGED_OSS }, verbose: false, quiet: false, yes: false, human: false, active_instance: "", instance_source: "env-only", }; } function configFromEnv(): Record | null { const accessKeyId = process.env.TABLESTORE_ACCESS_KEY_ID ?? ""; const accessKeySecret = process.env.TABLESTORE_ACCESS_KEY_SECRET ?? ""; const apiKey = process.env.TABLESTORE_API_KEY ?? ""; const endpoint = process.env.TABLESTORE_ENDPOINT ?? ""; const instanceName = process.env.TABLESTORE_INSTANCE_NAME ?? ""; // Need an endpoint/instance and at least one credential (AK/SK or API Key). const hasAkSk = Boolean(accessKeyId && accessKeySecret); const hasApiKey = Boolean(apiKey); if ((!hasAkSk && !hasApiKey) || !endpoint || !instanceName) { return null; } return { access_key_id: accessKeyId, access_key_secret: accessKeySecret, api_key: apiKey, ots_endpoint: endpoint, ots_instance_name: instanceName, oss_endpoint: process.env.TABLESTORE_OSS_ENDPOINT ?? "", oss_bucket_name: process.env.TABLESTORE_OSS_BUCKET_NAME ?? "", region: process.env.TABLESTORE_REGION ?? "", }; } function shouldForceEnvCredentials(): boolean { return process.env.TABLESTORE_DASHBOARD_FORCE_ENV === FORCE_ENV_VALUE; } function configFromToken(token: string): Record { // decodeToken throws on malformed input; callers translate to 401. return decodeToken(token); } function getCookieActiveInstanceName(request: NextRequest): string | null { const raw = request.cookies.get(ACTIVE_INSTANCE_COOKIE_NAME)?.value; if (!raw) return null; try { const decoded = decodeURIComponent(raw); return decoded ? decoded : null; } catch { return null; } } function tokenFieldsForInstance( instanceName: string, ): Record | null { try { const detail = readInstance(instanceName); if (!detail) return null; const ots = detail.managed_ots; const oss = detail.managed_oss; return { access_key_id: detail.access_key_id, access_key_secret: detail.access_key_secret, api_key: detail.api_key, ots_endpoint: detail.ots_endpoint || ots.ots_endpoint, ots_instance_name: detail.ots_instance_name || ots.ots_instance_name, oss_endpoint: detail.oss_endpoint || oss.oss_endpoint, oss_bucket_name: detail.oss_bucket_name || oss.oss_bucket_name, region: detail.region || ots.region || oss.region, }; } catch { return null; } } function sameCredentialValue( left: Record, right: Record, key: string, ): boolean { return (left[key] ?? "") === (right[key] ?? ""); } function tokenMatchesInstance( fields: Record, instanceName: string, ): boolean { const expected = tokenFieldsForInstance(instanceName); if (!expected) return false; const requiredKeys = [ "access_key_id", "access_key_secret", "api_key", "ots_endpoint", "ots_instance_name", "oss_endpoint", "oss_bucket_name", ]; if ( !requiredKeys.every((key) => sameCredentialValue(fields, expected, key)) ) { return false; } // Region can be inferred by older tokens. Only reject it when both sides // carry a concrete value and those values differ. if (fields.region && expected.region && fields.region !== expected.region) { return false; } return true; } function safeGetActiveInstanceName(): string | null { try { return getActiveInstanceName(); } catch { return null; } } function trustedActiveInstanceFromCookie( request: NextRequest, fields: Record, ): string | null { if (getCookieTokenSource(request) === RAW_TOKEN_SOURCE) return null; const instanceName = getCookieActiveInstanceName(request); const activeInstance = safeGetActiveInstanceName(); if (instanceName) { if (activeInstance !== instanceName) return null; return tokenMatchesInstance(fields, instanceName) ? instanceName : null; } return null; } function getCookieTokenSource(request: NextRequest): string | null { const raw = request.cookies.get(TOKEN_SOURCE_COOKIE_NAME)?.value; return raw === RAW_TOKEN_SOURCE || raw === INSTANCE_TOKEN_SOURCE ? raw : null; } function shouldUseCookieCredentials( request: NextRequest, fields: Record, ): boolean { const tokenSource = getCookieTokenSource(request); if (tokenSource === RAW_TOKEN_SOURCE) return true; const instanceName = getCookieActiveInstanceName(request); if (instanceName) { return trustedActiveInstanceFromCookie(request, fields) === instanceName; } const activeInstance = safeGetActiveInstanceName(); if (!activeInstance) return true; // A cookie with neither explicit raw-token marker nor active-instance // companion is a legacy ambiguous session. In the dashboard project UX the // local TOML active instance is the source of truth, especially after an // external `tablestore-agent-cli configure use`. Prefer TOML here so the // header, runtime context, and resource APIs cannot split across tenants. return false; } // --------------------------------------------------------------------------- // LRU cache for resolved clients // --------------------------------------------------------------------------- // // Repeated Dashboard requests share the same AK/endpoint/instance/bucket // fingerprint; rebuilding the Tablestore SDK client on every request is // wasteful. A tiny in-memory LRU keyed by a salted SHA-256 of those fields // reuses the underlying connection pool without leaking credentials. // // Security note (CR N1): cache values hold the full AppConfig — including // access key id/secret — in process memory. This is equivalent to every // other long-lived credential held by Node.js (env vars, decoded cookies, // etc.) and is acceptable for a single-tenant developer tool. If we ever // need to harden against memory-dump attacks, reintroduce the encryption // layer tracked by CR S1 at the token boundary. const MAX_CLIENT_CACHE_SIZE = 16; // TTL bounds how long a stale credential tuple can linger after an upstream // rotation. 10 min is long enough to amortize cost over a user session yet // short enough that rotating a key takes effect without a process restart // (CR P6). const CLIENT_CACHE_TTL_MS = 10 * 60 * 1000; interface ClientCacheEntry { value: ResolvedClients; expiresAt: number; } const clientCache = new Map(); /** * Drop every cached client. Called from POST /api/v1/instances/[name]/use * after the active instance flips so the next request rebuilds the client * with the new instance's OTS / OSS coordinates instead of waiting for the * 10-minute TTL on the per-key entry. * * Without this eviction the next upload could still hit the previous * tenant's `NodeAgentStorageClient` and fail with * `AccessDeniedError: bucket acl`, because the SDK binds OSS coordinates at * construction time and the cache key fingerprint may not change when only * the active instance flag flips on disk. */ export function clearClientCache(): void { clientCache.clear(); } function computeClientCacheKey( fields: Record, source: CredentialSource, instanceName: string | null, ): string { // The fingerprint includes the secret and named project identity so CLI-side // key rotation or switching between same-tenant named projects takes effect // without waiting for the TTL. const raw = [ source, instanceName ?? "", fields.access_key_id ?? "", fields.access_key_secret ?? "", fields.api_key ?? "", fields.ots_endpoint ?? "", fields.ots_instance_name ?? "", fields.oss_endpoint ?? "", fields.oss_bucket_name ?? "", fields.region ?? "", ].join("|"); return createHash("sha256").update(raw).digest("hex"); } function computeCredentialFingerprint(fields: Record): string { const raw = [ fields.access_key_id ?? "", fields.access_key_secret ?? "", fields.api_key ?? "", fields.ots_endpoint ?? "", fields.ots_instance_name ?? "", fields.oss_endpoint ?? "", fields.oss_bucket_name ?? "", fields.region ?? "", ].join("|"); return createHash("sha256").update(raw).digest("hex").slice(0, 12); } function cacheGet(key: string): ResolvedClients | undefined { const hit = clientCache.get(key); if (!hit) return undefined; if (Date.now() >= hit.expiresAt) { clientCache.delete(key); return undefined; } // Refresh recency by re-inserting. clientCache.delete(key); clientCache.set(key, hit); return hit.value; } function cacheSet(key: string, value: ResolvedClients): void { if (clientCache.has(key)) { clientCache.delete(key); } else if (clientCache.size >= MAX_CLIENT_CACHE_SIZE) { const oldest = clientCache.keys().next().value; if (typeof oldest === "string") { clientCache.delete(oldest); } } clientCache.set(key, { value, expiresAt: Date.now() + CLIENT_CACHE_TTL_MS }); } /** * Resolve the Tablestore credentials for the current request. * * Precedence: * 1. Session cookie (tablestore_token) — set via POST /api/v1/auth/token * or via the instance management endpoints. * 2. Active named instance from the local config TOML. * 3. Process environment variables. * * Throws {@link CLIError} UNAUTHORIZED when no layer yields a valid tuple. */ export function resolveClients(request: NextRequest): ResolvedClients { const token = request.cookies.get(SESSION_COOKIE_NAME)?.value; const forceEnv = shouldForceEnvCredentials(); let fields: Record | null = forceEnv ? configFromEnv() : null; let source: CredentialSource = "env"; let instanceName: string | null = null; if (!forceEnv && token) { try { const tokenFields = configFromToken(token); if (shouldUseCookieCredentials(request, tokenFields)) { fields = tokenFields; source = "cookie"; instanceName = trustedActiveInstanceFromCookie(request, tokenFields); } } catch (err) { throw new CLIError( "UNAUTHORIZED", `Invalid session token: ${err instanceof Error ? err.message : String(err)}`, ); } } if (!forceEnv && !fields) { const fromInstance = configFromActiveInstance(); if (fromInstance) { fields = fromInstance.fields; source = "instance"; instanceName = fromInstance.instanceName; } } if (!fields) { fields = configFromEnv(); } if (!fields) { throw new CLIError( "UNAUTHORIZED", "No valid credentials. Import a token via POST /api/v1/auth/token, configure an instance, or set environment variables.", ); } // The cache key is derived before constructing the AppConfig so a cache hit // avoids rebuilding SDK clients while still reflecting credential rotations. const cacheKey = computeClientCacheKey(fields, source, instanceName); const cached = cacheGet(cacheKey); if (cached) return cached; const appConfig = buildAppConfig(fields); const resolved: ResolvedClients = { kb: new KnowledgeBaseClient(appConfig), memory: new MemoryClient(appConfig), wiki: new WikiClient(appConfig), config: appConfig, source, instanceName, }; cacheSet(cacheKey, resolved); return resolved; } /** * Inspect credentials for auth-status endpoints without throwing. * Returns `null` when no credentials are configured. */ export function inspectCredentials(request: NextRequest): { instanceName: string; region: string; source: CredentialSource; activeInstance: string | null; credentialFingerprint: string; } | null { if (shouldForceEnvCredentials()) { const fields = configFromEnv(); if (!fields) return null; const region = fields.region || inferRegionFromOtsEndpoint(fields.ots_endpoint) || DEFAULT_REGION; return { instanceName: fields.ots_instance_name, region, source: "env", activeInstance: null, credentialFingerprint: computeCredentialFingerprint(fields), }; } const token = request.cookies.get(SESSION_COOKIE_NAME)?.value; if (token) { try { const fields = configFromToken(token); if (!shouldUseCookieCredentials(request, fields)) { // Named-project cookies are snapshots of the TOML-backed active // instance. If the CLI changed or rewrote that project behind the // browser's back, ignore the stale snapshot and inspect the current // file/env layers below. } else { const region = fields.region || inferRegionFromOtsEndpoint(fields.ots_endpoint) || DEFAULT_REGION; return { instanceName: fields.ots_instance_name, region, source: "cookie", activeInstance: trustedActiveInstanceFromCookie(request, fields), credentialFingerprint: computeCredentialFingerprint(fields), }; } } catch { return null; } } const fromInstance = configFromActiveInstance(); if (fromInstance) { const region = fromInstance.fields.region || inferRegionFromOtsEndpoint(fromInstance.fields.ots_endpoint) || DEFAULT_REGION; return { instanceName: fromInstance.fields.ots_instance_name, region, source: "instance", activeInstance: fromInstance.instanceName, credentialFingerprint: computeCredentialFingerprint(fromInstance.fields), }; } const envFields = configFromEnv(); if (!envFields) return null; const region = envFields.region || inferRegionFromOtsEndpoint(envFields.ots_endpoint) || DEFAULT_REGION; return { instanceName: envFields.ots_instance_name, region, source: "env", activeInstance: null, credentialFingerprint: computeCredentialFingerprint(envFields), }; } /** * Lightweight view of the active instance for auth/status consumers that do * not need full client construction. */ export function getActiveInstanceContext(request: NextRequest): { instanceName: string | null; configured: boolean; region?: string; } { const creds = inspectCredentials(request); if (!creds) { return { instanceName: null, configured: false }; } return { instanceName: creds.activeInstance, configured: true, region: creds.region, }; }