feat: add NocoBase browser OAuth login

This commit is contained in:
nac
2026-08-18 04:08:27 +00:00
parent 5c2cbac5b1
commit 4c53f90947
16 changed files with 1138 additions and 143 deletions
+3 -3
View File
@@ -9,7 +9,7 @@ import { VERSION } from "../src/version.js";
test("package, manifest, and runtime versions agree with no runtime npm dependencies", () => {
const packageJson = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
const manifest = JSON.parse(readFileSync(new URL("../install-manifest.json", import.meta.url), "utf8"));
assert.equal(VERSION, "0.3.1");
assert.equal(VERSION, "0.4.0");
assert.equal(packageJson.version, VERSION);
assert.equal(manifest.version, VERSION);
assert.deepEqual(packageJson.dependencies, undefined);
@@ -24,14 +24,14 @@ test("generated MCP config contains no Key, token, or environment secret", () =>
assert.doesNotMatch(serialized, /authorize|token|secret|password/i);
});
test("setup refuses a non-TTY before creating credential files", async () => {
test("manual Key fallback refuses a non-TTY before creating credential files", async () => {
if (process.stdin.isTTY || process.stderr.isTTY) return;
const directory = mkdtempSync(join(tmpdir(), "nocobase-mcp-nontty-"));
const path = join(directory, "credentials.json");
const previous = process.env.NOCOBASE_MCP_CREDENTIALS;
process.env.NOCOBASE_MCP_CREDENTIALS = path;
try {
await assert.rejects(runCli(["setup", "--json"]), /local terminal/);
await assert.rejects(runCli(["setup", "--manual-key", "--json"]), /local terminal/);
assert.equal(existsSync(path), false);
assert.equal(existsSync(join(directory, "config.json")), false);
} finally {
+91 -2
View File
@@ -1,10 +1,17 @@
import assert from "node:assert/strict";
import { chmodSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { chmodSync, mkdtempSync, readFileSync, statSync, 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, NOCOBASE_API_BASE_URL, saveCredentials } from "../src/credentials.js";
import {
createCredentialProvider,
loadCredentials,
loadStoredCredentials,
NOCOBASE_API_BASE_URL,
saveCredentials,
saveOAuthCredentials,
} from "../src/credentials.js";
test("stores only the Key and always loads the fixed NocoBase endpoint", () => {
const directory = mkdtempSync(join(tmpdir(), "nocobase-mcp-credentials-"));
@@ -24,6 +31,84 @@ test("stores only the Key and always loads the fixed NocoBase endpoint", () => {
}
});
test("stores OAuth credentials privately and refreshes them once for concurrent requests", async () => {
const directory = mkdtempSync(join(tmpdir(), "nocobase-mcp-oauth-"));
const path = join(directory, "private", "credentials.json");
saveOAuthCredentials(
{
type: "oauth",
issuer: "https://justconn.top/api",
clientId: "desktop-client",
accessToken: "old-access",
refreshToken: "old-refresh",
tokenType: "Bearer",
scope: "api offline_access",
expiresAt: 900,
},
path,
);
assert.equal(loadCredentials(path).authorizeKey, "old-access");
let refreshes = 0;
const provider = createCredentialProvider({
path,
now: () => 1_000,
refresh: async (credentials) => {
refreshes += 1;
await Promise.resolve();
return { ...credentials, accessToken: "new-access", refreshToken: "new-refresh", expiresAt: 100_000 };
},
});
const results = await Promise.all([provider(), provider(), provider()]);
assert.equal(refreshes, 1);
assert.deepEqual(
results.map((result) => result.authorizeKey),
["new-access", "new-access", "new-access"],
);
const stored = loadStoredCredentials(path);
assert.equal(stored.type, "oauth");
if (stored.type === "oauth") {
assert.equal(stored.accessToken, "new-access");
assert.equal(stored.refreshToken, "new-refresh");
}
if (process.platform !== "win32") assert.equal(statMode(path), 0o600);
});
test("backs off after a refresh failure while the current access token remains valid", async () => {
const directory = mkdtempSync(join(tmpdir(), "nocobase-mcp-oauth-backoff-"));
const path = join(directory, "private", "credentials.json");
saveOAuthCredentials(
{
type: "oauth",
issuer: "https://justconn.top/api",
clientId: "desktop-client",
accessToken: "still-valid-access",
refreshToken: "refresh-token",
tokenType: "Bearer",
scope: "api offline_access",
expiresAt: 50_000,
},
path,
);
let currentTime = 10_000;
let refreshes = 0;
const provider = createCredentialProvider({
path,
now: () => currentTime,
refresh: async () => {
refreshes += 1;
throw new Error("temporary network failure");
},
});
assert.equal((await provider()).authorizeKey, "still-valid-access");
assert.equal((await provider()).authorizeKey, "still-valid-access");
assert.equal(refreshes, 1);
currentTime += 30_000;
assert.equal((await provider()).authorizeKey, "still-valid-access");
assert.equal(refreshes, 2);
});
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");
@@ -50,3 +135,7 @@ test("rejects malformed config types before any NocoBase request", () => {
writeFileSync(path, JSON.stringify({ collections: { customers: { fields: "id,name" } } }));
assert.throws(() => loadConfig(path), /array of strings/);
});
function statMode(path: string): number {
return statSync(path).mode & 0o777;
}
+150
View File
@@ -0,0 +1,150 @@
import assert from "node:assert/strict";
import test from "node:test";
import { type AuthorizationPrompt, loginWithBrowser, refreshOAuthCredentials } from "../src/oauth.js";
const discovery = {
issuer: "https://justconn.top/api",
device_authorization_endpoint: "https://justconn.top/api/idpOAuth/device/auth",
registration_endpoint: "https://justconn.top/api/idpOAuth/register",
token_endpoint: "https://justconn.top/api/idpOAuth/token",
grant_types_supported: [
"authorization_code",
"refresh_token",
"urn:ietf:params:oauth:grant-type:device_code",
],
scopes_supported: ["openid", "offline_access", "api", "mcp"],
token_endpoint_auth_methods_supported: ["none", "client_secret_basic"],
};
test("uses NocoBase dynamic registration and browser device authorization without exposing tokens", async () => {
const calls: Array<{ body: string; method: string; url: string }> = [];
let tokenPolls = 0;
const fetchMock = (async (input: string | URL | Request, init: RequestInit = {}) => {
const url = String(input);
const method = init.method ?? "GET";
const body =
typeof init.body === "string" || init.body instanceof URLSearchParams ? String(init.body) : "";
calls.push({ body, method, url });
if (url.endsWith("/.well-known/openid-configuration")) return jsonResponse(discovery);
if (url.endsWith("/idpOAuth/register")) {
return jsonResponse(
{
client_id: "desktop-client",
registration_access_token: "must-not-be-stored",
token_endpoint_auth_method: "none",
},
201,
);
}
if (url.endsWith("/idpOAuth/device/auth")) {
return jsonResponse({
device_code: "private-device-code",
user_code: "ABCD-EFGH",
verification_uri: "https://justconn.top/idpOAuth/device",
verification_uri_complete: "https://justconn.top/idpOAuth/device?user_code=ABCD-EFGH",
expires_in: 600,
interval: 5,
});
}
if (url.endsWith("/idpOAuth/token")) {
tokenPolls += 1;
if (tokenPolls === 1) return jsonResponse({ error: "authorization_pending" }, 400);
return jsonResponse({
access_token: "oauth-access-token",
refresh_token: "oauth-refresh-token",
token_type: "Bearer",
scope: "api offline_access",
expires_in: 900,
});
}
throw new Error(`Unexpected request: ${method} ${url}`);
}) as typeof fetch;
let prompt: AuthorizationPrompt | undefined;
const sleeps: number[] = [];
const credentials = await loginWithBrowser({
fetch: fetchMock,
now: () => 1_000,
openBrowser: async () => true,
onAuthorization: (value) => {
prompt = value;
},
sleep: async (milliseconds) => {
sleeps.push(milliseconds);
},
});
assert.equal(credentials.clientId, "desktop-client");
assert.equal(credentials.accessToken, "oauth-access-token");
assert.equal(credentials.refreshToken, "oauth-refresh-token");
assert.equal(credentials.expiresAt, 901_000);
assert.doesNotMatch(JSON.stringify(credentials), /must-not-be-stored/);
assert.deepEqual(prompt, {
opened: true,
url: "https://justconn.top/idpOAuth/device?user_code=ABCD-EFGH",
userCode: "ABCD-EFGH",
expiresIn: 600,
});
assert.deepEqual(sleeps, [5_000, 5_000]);
const registration = JSON.parse(calls.find((call) => call.url.endsWith("/register"))?.body ?? "{}");
assert.equal(registration.application_type, "native");
assert.equal(registration.token_endpoint_auth_method, "none");
assert.deepEqual(registration.response_types, []);
assert.deepEqual(registration.redirect_uris, []);
assert.equal(registration.client_secret, undefined);
const deviceForm = new URLSearchParams(calls.find((call) => call.url.endsWith("/device/auth"))?.body);
assert.equal(deviceForm.get("scope"), "api offline_access");
assert.equal(deviceForm.get("resource"), "https://justconn.top/api/");
});
test("rejects OAuth discovery that points tokens at another origin", async () => {
const fetchMock = (async () =>
jsonResponse({ ...discovery, token_endpoint: "https://evil.example/token" })) as typeof fetch;
await assert.rejects(
loginWithBrowser({ fetch: fetchMock, openBrowser: async () => true }),
/untrusted endpoint/,
);
});
test("refreshes a public-client OAuth session and keeps a rotated refresh token optional", async () => {
const bodies: string[] = [];
const fetchMock = (async (input: string | URL | Request, init: RequestInit = {}) => {
const url = String(input);
if (url.endsWith("/.well-known/openid-configuration")) return jsonResponse(discovery);
bodies.push(String(init.body));
return jsonResponse({
access_token: "new-access",
token_type: "Bearer",
scope: "api offline_access",
expires_in: 600,
});
}) as typeof fetch;
const refreshed = await refreshOAuthCredentials(
{
type: "oauth",
issuer: "https://justconn.top/api",
clientId: "desktop-client",
accessToken: "old-access",
refreshToken: "old-refresh",
tokenType: "Bearer",
scope: "api offline_access",
expiresAt: 10,
},
{ fetch: fetchMock, now: () => 2_000 },
);
assert.equal(refreshed.accessToken, "new-access");
assert.equal(refreshed.refreshToken, "old-refresh");
assert.equal(refreshed.expiresAt, 602_000);
const form = new URLSearchParams(bodies[0]);
assert.equal(form.get("grant_type"), "refresh_token");
assert.equal(form.get("client_id"), "desktop-client");
assert.equal(form.get("refresh_token"), "old-refresh");
});
function jsonResponse(value: unknown, status = 200): Response {
return new Response(JSON.stringify(value), {
status,
headers: { "content-type": "application/json" },
});
}