import assert from "node:assert/strict"; import { chmodSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; import { DEFAULT_CONFIG, loadConfig } from "../src/config.js"; import { loadCredentials, normalizeApiBaseUrl, saveCredentials } from "../src/credentials.js"; test("normalizes application URLs to the NocoBase API base", () => { assert.equal(normalizeApiBaseUrl("https://nb.example/app/"), "https://nb.example/app/api"); assert.equal(normalizeApiBaseUrl("http://127.0.0.1:13000/api"), "http://127.0.0.1:13000/api"); assert.throws(() => normalizeApiBaseUrl("http://nb.example"), /HTTPS/i); assert.throws(() => normalizeApiBaseUrl("https://user:pass@nb.example"), /credentials/i); }); test("stores and reads credentials from a private file", () => { const directory = mkdtempSync(join(tmpdir(), "nocobase-mcp-credentials-")); const path = join(directory, "private", "credentials.json"); saveCredentials({ apiBaseUrl: "https://nb.example", authorizeKey: "secret" }, path); assert.deepEqual(loadCredentials(path), { apiBaseUrl: "https://nb.example/api", authorizeKey: "secret", }); assert.match(readFileSync(path, "utf8"), /secret/); if (process.platform !== "win32") { chmodSync(path, 0o644); assert.throws(() => loadCredentials(path), /0600/); } }); test("loads camelCase and snake_case config aliases without mutating defaults", () => { const directory = mkdtempSync(join(tmpdir(), "nocobase-mcp-config-")); const path = join(directory, "config.json"); writeFileSync( path, JSON.stringify({ data_source: "secondary", timezone: "UTC", collections: { customers: { resource: "crm_customers", owner_field: "assignee" } }, projects: { nameField: "project_title" }, }), ); const loaded = loadConfig(path); assert.equal(loaded.dataSource, "secondary"); assert.equal(loaded.customer.resource, "crm_customers"); assert.equal(loaded.customer.ownerField, "assignee"); assert.equal(loaded.project.nameField, "project_title"); assert.equal(DEFAULT_CONFIG.customer.resource, "customers"); }); test("rejects malformed config types before any NocoBase request", () => { const directory = mkdtempSync(join(tmpdir(), "nocobase-mcp-invalid-config-")); const path = join(directory, "config.json"); writeFileSync(path, JSON.stringify({ collections: { customers: { fields: "id,name" } } })); assert.throws(() => loadConfig(path), /array of strings/); });