import { type NextRequest, NextResponse } from "next/server"; import { CLIError, DEFAULT_INSTANCE_NAME, decodeToken, encodeTokenV2, getActiveInstanceName, listInstances, loadConfig, readInstance, saveInstanceConfig, setActiveInstance, validateInstanceName, } from "@tablestore/tablestore-agent-shared"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; import { ensureApiLogContext, errorResponse, handleApiError, successResponse, } from "@/lib/server/api-helpers"; import { SESSION_COOKIE_NAME, setActiveInstanceCookie, setInstanceTokenSourceCookie, } from "@/lib/server/sdk-client"; import { connectInstanceSchema, importInstanceSchema, } from "@/schemas/instance"; import type { InstanceActionResult, InstanceSummary } from "@/types/instance"; /** * GET /api/v1/instances * * Return the full list of configured instances together with the currently * active instance name. Does not require Tablestore credentials; the list * is read from the local config TOML. */ export async function GET(request: NextRequest) { ensureApiLogContext(request); try { const rows = listInstances(); const activeInstance = getActiveInstanceName(); const hasDefault = rows.some((r) => r.is_default_fallback); const instances: InstanceSummary[] = rows.map(toSummary); return successResponse({ activeInstance, hasDefault, instances }); } catch (error) { return handleApiError(error); } } /** * POST /api/v1/instances * * Create a new instance. Accepts two payload shapes: * - Manual: ConnectInstancePayload with AK/SK/endpoint/instance (+ optional OSS). * - Token import: { token, name?, activate? }. * * When activate=true (default) the server also rewrites the tablestore_token * cookie so subsequent requests resolve to the freshly persisted instance. */ export async function POST(request: NextRequest) { ensureApiLogContext(request); try { const raw = await request.json().catch(() => null); if (!raw || typeof raw !== "object") { return errorResponse("BAD_REQUEST", "Request body must be JSON", 400); } const isTokenImport = typeof (raw as Record).token === "string"; const created = isTokenImport ? createFromToken(raw) : createFromFields(raw); if (created instanceof NextResponse) return created; const { name, fields, activate } = created; if ( listInstances().some((r) => r.name === name && !r.is_default_fallback) ) { return errorResponse( "CONFLICT", `Instance "${name}" already exists.`, 409, ); } validateInstanceName(name); saveInstanceConfig(name, fields); let activeInstance = getActiveInstanceName(); if (activate) { setActiveInstance(name); activeInstance = name; } const detail = readInstance(name); const summary: InstanceSummary = detail ? { name, active: activeInstance === name, otsInstanceName: detail.ots_instance_name || undefined, region: detail.region || undefined, hasOss: Boolean(detail.oss_endpoint && detail.oss_bucket_name), isDefaultFallback: false, } : { name, active: activeInstance === name, otsInstanceName: fields.ots_instance_name || undefined, region: fields.region || undefined, hasOss: Boolean(fields.oss_endpoint && fields.oss_bucket_name), isDefaultFallback: false, }; const body: InstanceActionResult = { activeInstance, instance: summary }; const response = successResponse(body, 201); if (activate) { // Re-project the freshly persisted instance through loadConfig so the // cookie carries the effective oss_endpoint / oss_bucket_name. Without // this the cookie would only contain whatever the request payload // supplied, missing managed_oss subsections that the SDK auto-populates // on first use. const effective = loadConfig(); const tokenFields = { ...fields, api_key: fields.api_key || "", oss_endpoint: effective.oss_endpoint || fields.oss_endpoint || "", oss_bucket_name: effective.oss_bucket_name || fields.oss_bucket_name || "", region: fields.region || effective.region || "", }; const token = encodeTokenV2(tokenFields); response.cookies.set({ name: SESSION_COOKIE_NAME, value: token, httpOnly: true, // Match the strict policy used in /api/v1/auth/token so every // session cookie write across the dashboard stays consistent. sameSite: "strict", secure: process.env.NODE_ENV === "production", path: "/", }); setActiveInstanceCookie(response, name); setInstanceTokenSourceCookie(response); } return response; } catch (error) { return handleApiError(error); } } // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- interface CreationPlan { name: string; fields: Record; activate: boolean; } function createFromFields(raw: unknown): CreationPlan | NextResponse { const parsed = connectInstanceSchema.safeParse(raw); if (!parsed.success) { return errorResponse( "VALIDATION_ERROR", parsed.error.issues .map((issue) => `${issue.path.join(".")}: ${issue.message}`) .join("; "), 400, ); } const data = parsed.data; return { name: data.name, fields: stripEmpty({ access_key_id: data.accessKeyId, access_key_secret: data.accessKeySecret, api_key: data.apiKey, ots_endpoint: data.otsEndpoint, ots_instance_name: data.otsInstanceName, oss_endpoint: data.ossEndpoint, oss_bucket_name: data.ossBucketName, region: data.region, }), activate: data.activate ?? true, }; } function createFromToken(raw: unknown): CreationPlan | NextResponse { const parsed = importInstanceSchema.safeParse(raw); if (!parsed.success) { return errorResponse( "VALIDATION_ERROR", parsed.error.issues .map((issue) => `${issue.path.join(".")}: ${issue.message}`) .join("; "), 400, ); } let decoded: Record; try { decoded = decodeToken(parsed.data.token); } catch (err) { throw new CLIError( "BAD_REQUEST", `Invalid token: ${err instanceof Error ? err.message : String(err)}`, ); } const name = parsed.data.name ?? pickDefaultName(); return { name, fields: stripEmpty(decoded), activate: parsed.data.activate ?? true, }; } function stripEmpty( obj: Record, ): Record { const out: Record = {}; for (const [k, v] of Object.entries(obj)) { if (typeof v === "string" && v.length > 0) out[k] = v; } return out; } /** * Pick a non-conflicting default name when the token-import payload omits one. * Tries `imported`, `imported-2`, `imported-3`, ... until a free slot is found. */ function pickDefaultName(): string { const taken = new Set( listInstances() .filter((r) => !r.is_default_fallback) .map((r) => r.name), ); const base = "imported"; if (!taken.has(base)) return base; for (let i = 2; i < 1000; i += 1) { const candidate = `${base}-${i}`; if (!taken.has(candidate)) return candidate; } throw new CLIError("CONFLICT", "Cannot allocate a default instance name."); } function toSummary(row: { name: string; active: boolean; ots_instance_name: string; region: string; is_default_fallback: boolean; }): InstanceSummary { // Surfacing OSS presence requires reading the full instance section. const target = row.name === DEFAULT_INSTANCE_NAME && row.is_default_fallback ? readInstance(DEFAULT_INSTANCE_NAME) : readInstance(row.name); return { name: row.name, active: row.active, otsInstanceName: row.ots_instance_name || undefined, region: row.region || undefined, hasOss: Boolean(target?.oss_endpoint && target?.oss_bucket_name), isDefaultFallback: row.is_default_fallback || undefined, }; }