fix: chunk OAuth credentials for platform keyrings

This commit is contained in:
cneicy committed 2026-08-20 17:27:29 +08:00
1 parent ac4480bb09
commit af7f184f45
7 files changed
+269 -26

No files matched your search

Vendored
+86 -11
View File
@@ -737,7 +737,7 @@ async function serveBridge(options, tokenStore, discoveryStore, serviceToken = p
}
}
function createProxyServer(upstream) {
const server = new Server({ name: "crafttable-mcp-stdio-bridge", version: "0.1.1" }, {
const server = new Server({ name: "crafttable-mcp-stdio-bridge", version: "0.1.2" }, {
capabilities: {
tools: {},
resources: {}
@@ -752,44 +752,119 @@ function createProxyServer(upstream) {
}
// src/credentials.ts
import { randomUUID as randomUUID2 } from "node:crypto";
var KEYRING_SERVICE = "CraftTable MCP";
var KEYRING_CHUNK_SIZE = 1e3;
var KeyringTokenStore = class {
constructor(entryFactory = keyringEntry) {
this.entryFactory = entryFactory;
}
entryFactory;
async get(account) {
let serialized;
try {
const entry = await keyringEntry(account);
serialized = await entry.getPassword();
serialized = await this.readPassword(account);
} catch (error) {
throw keyringError(error);
}
if (!serialized) return void 0;
const manifest = parseChunkManifest(serialized);
if (manifest) {
try {
const chunks = await Promise.all(Array.from({ length: manifest.chunks }, (_, index) => this.readPassword(chunkAccount(account, manifest.generation, index))));
if (chunks.some((chunk) => chunk === void 0)) throw new Error("missing credential chunk");
serialized = Buffer.from(chunks.join(""), "base64").toString("utf8");
} catch (error) {
if (error instanceof Error && error.message === "missing credential chunk") throw invalidCredentialError();
throw keyringError(error);
}
}
try {
const value = JSON.parse(serialized);
if (!value.access_token || !value.token_type) throw new Error("missing token fields");
return value;
} catch {
throw new Error("The saved CraftTable MCP credential is invalid; run `crafttable-mcp logout --local-only` and log in again");
throw invalidCredentialError();
}
}
async set(account, tokens) {
const encoded = Buffer.from(JSON.stringify(tokens), "utf8").toString("base64");
const chunks = splitCredential(encoded);
const generation = randomUUID2().replaceAll("-", "");
const manifest = { version: 2, generation, chunks: chunks.length };
let previous;
const writtenAccounts = [];
try {
const entry = await keyringEntry(account);
await entry.setPassword(JSON.stringify(tokens));
previous = await this.readPassword(account);
for (const [index, chunk] of chunks.entries()) {
const partAccount = chunkAccount(account, generation, index);
await (await this.entryFactory(partAccount)).setPassword(chunk);
writtenAccounts.push(partAccount);
}
await (await this.entryFactory(account)).setPassword(JSON.stringify(manifest));
} catch (error) {
await Promise.allSettled(writtenAccounts.map((partAccount) => this.deletePassword(partAccount)));
throw keyringError(error);
}
const previousManifest = previous && parseChunkManifest(previous);
if (previousManifest) {
await Promise.allSettled(Array.from({ length: previousManifest.chunks }, (_, index) => this.deletePassword(chunkAccount(account, previousManifest.generation, index))));
}
}
async delete(account) {
try {
const entry = await keyringEntry(account);
await entry.deleteCredential();
const serialized = await this.readPassword(account);
const manifest = serialized ? parseChunkManifest(serialized) : void 0;
await this.deletePassword(account);
if (manifest) {
await Promise.all(Array.from({ length: manifest.chunks }, (_, index) => this.deletePassword(chunkAccount(account, manifest.generation, index))));
}
} catch (error) {
const message = String(error?.message ?? error).toLowerCase();
if (message.includes("no entry") || message.includes("not found")) return;
throw keyringError(error);
}
}
async readPassword(account) {
try {
return await (await this.entryFactory(account)).getPassword();
} catch (error) {
if (isMissingCredential(error)) return void 0;
throw error;
}
}
async deletePassword(account) {
try {
await (await this.entryFactory(account)).deleteCredential();
} catch (error) {
if (!isMissingCredential(error)) throw error;
}
}
};
function splitCredential(value) {
const chunks = [];
for (let offset = 0; offset < value.length; offset += KEYRING_CHUNK_SIZE) {
chunks.push(value.slice(offset, offset + KEYRING_CHUNK_SIZE));
}
return chunks.length ? chunks : [""];
}
function chunkAccount(account, generation, index) {
return `${account}:v2:${generation}:${index}`;
}
function parseChunkManifest(value) {
try {
const parsed = JSON.parse(value);
if (parsed.version !== 2 || typeof parsed.generation !== "string" || !/^[0-9a-f]{32}$/.test(parsed.generation) || !Number.isInteger(parsed.chunks) || (parsed.chunks ?? 0) < 1 || (parsed.chunks ?? 0) > 100) return void 0;
return parsed;
} catch {
return void 0;
}
}
function isMissingCredential(error) {
const message = String(error?.message ?? error).toLowerCase();
return message.includes("no entry") || message.includes("not found");
}
function invalidCredentialError() {
return new Error("The saved CraftTable MCP credential is invalid; run `crafttable-mcp logout --local-only` and log in again");
}
async function keyringEntry(account) {
try {
const { AsyncEntry } = await import("@napi-rs/keyring");
@@ -805,7 +880,7 @@ function keyringError(error) {
}
// src/cli.ts
var program = new Command().name("crafttable-mcp").description("OAuth client and stdio bridge for CraftTable MCP").version("0.1.1");
var program = new Command().name("crafttable-mcp").description("OAuth client and stdio bridge for CraftTable MCP").version("0.1.2");
withConnection(program.command("login").description("Log in through the system browser")).option("--no-browser", "print the authorization URL instead of opening it").option("--timeout <milliseconds>", "OAuth callback timeout", "600000").action(async (flags) => {
const options = connectionOptions(flags);
const timeoutMs = positiveInteger(flags.timeout, "OAuth callback timeout");
+3 -3
View File
@@ -1,7 +1,7 @@
{
"version": 3,
"sources": ["../src/cli.ts", "../src/agents.ts", "../src/config.ts", "../src/bridge.ts", "../src/remote.ts", "../src/callbackServer.ts", "../src/oauthProvider.ts", "../src/credentials.ts"],
"sourcesContent": ["#!/usr/bin/env node\n\nimport { fileURLToPath } from \"node:url\";\nimport { Command } from \"commander\";\nimport { configureAgents, type AgentTarget, unconfigureAgents } from \"./agents.js\";\nimport { serveBridge } from \"./bridge.js\";\nimport { type ClientOptions, credentialAccount, DiscoveryStore, resolveClientOptions } from \"./config.js\";\nimport { KeyringTokenStore } from \"./credentials.js\";\nimport { connectRemote, loginRemote, logoutRemote } from \"./remote.js\";\n\ntype ConnectionFlags = { url?: string; clientId?: string; callbackPort?: string };\n\nconst program = new Command()\n .name(\"crafttable-mcp\")\n .description(\"OAuth client and stdio bridge for CraftTable MCP\")\n .version(\"0.1.1\");\n\nwithConnection(program.command(\"login\").description(\"Log in through the system browser\"))\n .option(\"--no-browser\", \"print the authorization URL instead of opening it\")\n .option(\"--timeout <milliseconds>\", \"OAuth callback timeout\", \"600000\")\n .action(async (flags: ConnectionFlags & { browser: boolean; timeout: string }) => {\n const options = connectionOptions(flags);\n const timeoutMs = positiveInteger(flags.timeout, \"OAuth callback timeout\");\n const result = await loginRemote(options, new KeyringTokenStore(), new DiscoveryStore(), { browser: flags.browser, timeoutMs });\n printJson({ loggedIn: true, alreadyAuthenticated: result.alreadyAuthenticated, server: options.url.toString(), tools: result.toolCount });\n });\n\nwithConnection(program.command(\"status\").description(\"Check saved login state and remote MCP connectivity\"))\n .action(async (flags: ConnectionFlags) => {\n const options = connectionOptions(flags);\n const tokens = await new KeyringTokenStore().get(credentialAccount(options));\n const connection = await connectRemote(options, new KeyringTokenStore(), new DiscoveryStore());\n try {\n const tools = await connection.client.listTools();\n printJson({\n loggedIn: Boolean(tokens),\n authentication: connection.authentication,\n connected: true,\n server: options.url.toString(),\n tools: tools.tools.length,\n });\n } finally {\n await connection.close();\n }\n });\n\nwithConnection(program.command(\"logout\").description(\"Revoke OAuth tokens and remove the local credential\"))\n .option(\"--local-only\", \"remove local credentials without contacting the authorization server\")\n .action(async (flags: ConnectionFlags & { localOnly?: boolean }) => {\n const options = connectionOptions(flags);\n const result = await logoutRemote(options, new KeyringTokenStore(), new DiscoveryStore(), Boolean(flags.localOnly));\n printJson({ loggedIn: false, credentialRemoved: result.hadCredential, revoked: result.revoked, localOnly: Boolean(flags.localOnly) });\n });\n\nwithConnection(program.command(\"tools\").description(\"List remote MCP tools\"))\n .action(async (flags: ConnectionFlags) => withClient(connectionOptions(flags), async (client) => printJson(await client.listTools())));\n\nwithConnection(program.command(\"resources\").description(\"List remote MCP resources and resource templates\"))\n .action(async (flags: ConnectionFlags) => withClient(connectionOptions(flags), async (client) => printJson({\n resources: (await client.listResources()).resources,\n resourceTemplates: (await client.listResourceTemplates()).resourceTemplates,\n })));\n\nwithConnection(program.command(\"read <uri>\").description(\"Read an MCP resource\"))\n .action(async (uri: string, flags: ConnectionFlags) => withClient(connectionOptions(flags), async (client) => printJson(await client.readResource({ uri }))));\n\nwithConnection(program.command(\"call <tool> [json]\").description(\"Call an MCP tool\"))\n .action(async (tool: string, json: string | undefined, flags: ConnectionFlags) => withClient(connectionOptions(flags), async (client) => {\n printJson(await client.callTool({ name: tool, arguments: parseObject(json ?? \"{}\") }));\n }));\n\nwithConnection(program.command(\"serve\").description(\"Run the local stdio bridge\"))\n .action(async (flags: ConnectionFlags) => {\n await serveBridge(connectionOptions(flags), new KeyringTokenStore(), new DiscoveryStore());\n });\n\nfor (const operation of [\"configure\", \"unconfigure\"] as const) {\n withConnection(program.command(`${operation} <agent>`).description(`${operation === \"configure\" ? \"Add\" : \"Remove\"} the stdio bridge and CraftTable Skill in Codex, Claude Code, or OpenCode`))\n .option(\"--dry-run\", \"show the planned changes without writing\")\n .option(\"--force\", \"replace a conflicting entry without prompting\")\n .action(async (agent: AgentTarget, flags: ConnectionFlags & { dryRun?: boolean; force?: boolean }) => {\n const cliEntry = fileURLToPath(import.meta.url);\n if (!cliEntry.endsWith(\".js\")) throw new Error(\"Agent configuration requires the built CLI; run `npm --Line truncated
"mappings": ";;;AAEA,SAAS,qBAAqB;AAC9B,SAAS,eAAe;;;ACHxB,SAAS,aAAa;AACtB,SAAS,kBAAkB;AAC3B,SAAS,iBAAiB;AAC1B,SAAS,UAAU,IAAI,SAAAA,QAAO,YAAAC,WAAU,SAAS,UAAAC,SAAQ,IAAI,MAAM,aAAAC,kBAAiB;AACpF,OAAOC,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,uBAAuB;AAChC,SAAS,YAAY,QAAQ,aAAa;;;ACP1C,SAAS,kBAAkB;AAC3B,SAAS,OAAO,UAAU,QAAQ,iBAAiB;AACnD,OAAO,QAAQ;AACf,OAAO,UAAU;AAGV,IAAM,kBAAkB;AACxB,IAAM,oBAAoB;AAC1B,IAAM,wBAAwB;AAC9B,IAAM,eAAe;AAQrB,SAAS,qBAAqB,QAKjC,CAAC,GAAkB;AACrB,QAAM,MAAM,MAAM,OAAO,QAAQ;AACjC,QAAM,MAAM,eAAe,MAAM,OAAO,IAAI,sBAAsB,eAAe;AACjF,QAAM,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,YAAY;AAC1F,QAAM,aAAa,UAAU,UAAU,UAAU;AACjD,MAAI,SAAS,QAAQ;AACnB,UAAM,aAAa,UAAU,UACzB,CAAC,OAAO,UAAU,WAAW,IAC7B,CAAC,OAAO,UAAU,WAAW,QAAQ,WAAW;AACpD,UAAM,eAAe,OAAO,IAAI,YAAY,UAAU,GAAG,GAAG,KAAK,0BAA0B;AAAA,EAC7F;AACA,QAAM,UAAU,UAAU,UACtB,CAAC,OAAO,OAAO,aAAa,MAAM,GAAG,OAAO,IAC5C,CAAC,OAAO,OAAO,WAAW,QAAQ,aAAa,MAAM,GAAG,OAAO;AACnE,QLine truncated
"names": ["mkdir", "readFile", "rename", "writeFile", "os", "path", "path", "os", "readFile", "mkdir", "rename", "writeFile"]
"sourcesContent": ["#!/usr/bin/env node\n\nimport { fileURLToPath } from \"node:url\";\nimport { Command } from \"commander\";\nimport { configureAgents, type AgentTarget, unconfigureAgents } from \"./agents.js\";\nimport { serveBridge } from \"./bridge.js\";\nimport { type ClientOptions, credentialAccount, DiscoveryStore, resolveClientOptions } from \"./config.js\";\nimport { KeyringTokenStore } from \"./credentials.js\";\nimport { connectRemote, loginRemote, logoutRemote } from \"./remote.js\";\n\ntype ConnectionFlags = { url?: string; clientId?: string; callbackPort?: string };\n\nconst program = new Command()\n .name(\"crafttable-mcp\")\n .description(\"OAuth client and stdio bridge for CraftTable MCP\")\n .version(\"0.1.2\");\n\nwithConnection(program.command(\"login\").description(\"Log in through the system browser\"))\n .option(\"--no-browser\", \"print the authorization URL instead of opening it\")\n .option(\"--timeout <milliseconds>\", \"OAuth callback timeout\", \"600000\")\n .action(async (flags: ConnectionFlags & { browser: boolean; timeout: string }) => {\n const options = connectionOptions(flags);\n const timeoutMs = positiveInteger(flags.timeout, \"OAuth callback timeout\");\n const result = await loginRemote(options, new KeyringTokenStore(), new DiscoveryStore(), { browser: flags.browser, timeoutMs });\n printJson({ loggedIn: true, alreadyAuthenticated: result.alreadyAuthenticated, server: options.url.toString(), tools: result.toolCount });\n });\n\nwithConnection(program.command(\"status\").description(\"Check saved login state and remote MCP connectivity\"))\n .action(async (flags: ConnectionFlags) => {\n const options = connectionOptions(flags);\n const tokens = await new KeyringTokenStore().get(credentialAccount(options));\n const connection = await connectRemote(options, new KeyringTokenStore(), new DiscoveryStore());\n try {\n const tools = await connection.client.listTools();\n printJson({\n loggedIn: Boolean(tokens),\n authentication: connection.authentication,\n connected: true,\n server: options.url.toString(),\n tools: tools.tools.length,\n });\n } finally {\n await connection.close();\n }\n });\n\nwithConnection(program.command(\"logout\").description(\"Revoke OAuth tokens and remove the local credential\"))\n .option(\"--local-only\", \"remove local credentials without contacting the authorization server\")\n .action(async (flags: ConnectionFlags & { localOnly?: boolean }) => {\n const options = connectionOptions(flags);\n const result = await logoutRemote(options, new KeyringTokenStore(), new DiscoveryStore(), Boolean(flags.localOnly));\n printJson({ loggedIn: false, credentialRemoved: result.hadCredential, revoked: result.revoked, localOnly: Boolean(flags.localOnly) });\n });\n\nwithConnection(program.command(\"tools\").description(\"List remote MCP tools\"))\n .action(async (flags: ConnectionFlags) => withClient(connectionOptions(flags), async (client) => printJson(await client.listTools())));\n\nwithConnection(program.command(\"resources\").description(\"List remote MCP resources and resource templates\"))\n .action(async (flags: ConnectionFlags) => withClient(connectionOptions(flags), async (client) => printJson({\n resources: (await client.listResources()).resources,\n resourceTemplates: (await client.listResourceTemplates()).resourceTemplates,\n })));\n\nwithConnection(program.command(\"read <uri>\").description(\"Read an MCP resource\"))\n .action(async (uri: string, flags: ConnectionFlags) => withClient(connectionOptions(flags), async (client) => printJson(await client.readResource({ uri }))));\n\nwithConnection(program.command(\"call <tool> [json]\").description(\"Call an MCP tool\"))\n .action(async (tool: string, json: string | undefined, flags: ConnectionFlags) => withClient(connectionOptions(flags), async (client) => {\n printJson(await client.callTool({ name: tool, arguments: parseObject(json ?? \"{}\") }));\n }));\n\nwithConnection(program.command(\"serve\").description(\"Run the local stdio bridge\"))\n .action(async (flags: ConnectionFlags) => {\n await serveBridge(connectionOptions(flags), new KeyringTokenStore(), new DiscoveryStore());\n });\n\nfor (const operation of [\"configure\", \"unconfigure\"] as const) {\n withConnection(program.command(`${operation} <agent>`).description(`${operation === \"configure\" ? \"Add\" : \"Remove\"} the stdio bridge and CraftTable Skill in Codex, Claude Code, or OpenCode`))\n .option(\"--dry-run\", \"show the planned changes without writing\")\n .option(\"--force\", \"replace a conflicting entry without prompting\")\n .action(async (agent: AgentTarget, flags: ConnectionFlags & { dryRun?: boolean; force?: boolean }) => {\n const cliEntry = fileURLToPath(import.meta.url);\n if (!cliEntry.endsWith(\".js\")) throw new Error(\"Agent configuration requires the built CLI; run `npm --Line truncated
"mappings": ";;;AAEA,SAAS,qBAAqB;AAC9B,SAAS,eAAe;;;ACHxB,SAAS,aAAa;AACtB,SAAS,kBAAkB;AAC3B,SAAS,iBAAiB;AAC1B,SAAS,UAAU,IAAI,SAAAA,QAAO,YAAAC,WAAU,SAAS,UAAAC,SAAQ,IAAI,MAAM,aAAAC,kBAAiB;AACpF,OAAOC,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,uBAAuB;AAChC,SAAS,YAAY,QAAQ,aAAa;;;ACP1C,SAAS,kBAAkB;AAC3B,SAAS,OAAO,UAAU,QAAQ,iBAAiB;AACnD,OAAO,QAAQ;AACf,OAAO,UAAU;AAGV,IAAM,kBAAkB;AACxB,IAAM,oBAAoB;AAC1B,IAAM,wBAAwB;AAC9B,IAAM,eAAe;AAQrB,SAAS,qBAAqB,QAKjC,CAAC,GAAkB;AACrB,QAAM,MAAM,MAAM,OAAO,QAAQ;AACjC,QAAM,MAAM,eAAe,MAAM,OAAO,IAAI,sBAAsB,eAAe;AACjF,QAAM,YAAY,MAAM,YAAY,IAAI,kCAAkC,mBAAmB,KAAK;AAClG,MAAI,CAAC,SAAU,OAAM,IAAI,MAAM,mCAAmC;AAClE,QAAM,eAAe,OAAO,MAAM,gBAAgB,IAAI,sCAAsC,qBAAqB;AACjH,MAAI,CAAC,OAA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eAAe,OAAO,IAAI,YAAY,UAAU,GAAG,GAAG,KAAK,0BAA0B;AAAA,EAC7F;AACA,QAAM,UAAU,UAAU,UACtB,CAAC,OAAO,OAAO,aAAa,MAAM,GAAG,OAAO,IAC5C,CAAC,OAAO,OAAO,WAAW,QAAQ,aAAa,MAAM,GAAG,OAAO;AACnE,QLine truncated
"names": ["mkdir", "readFile", "rename", "writeFile", "os", "path", "path", "os", "readFile", "mkdir", "rename", "writeFile", "randomUUID"]
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@game-crafttable/mcp-client",
"version": "0.1.1",
"version": "0.1.2",
"description": "OAuth CLI and stdio bridge for the CraftTable MCP server",
"repository": {
"type": "git",
+1 -1
View File
@@ -45,7 +45,7 @@ export function createProxyServer(upstream: {
listResourceTemplates: (params?: { cursor?: string }) => Promise<unknown>;
readResource: (params: { uri: string }) => Promise<unknown>;
}): Server {
const server = new Server({ name: "crafttable-mcp-stdio-bridge", version: "0.1.1" }, {
const server = new Server({ name: "crafttable-mcp-stdio-bridge", version: "0.1.2" }, {
capabilities: {
tools: {},
resources: {},
+1 -1
View File
@@ -13,7 +13,7 @@ type ConnectionFlags = { url?: string; clientId?: string; callbackPort?: string
const program = new Command()
.name("crafttable-mcp")
.description("OAuth client and stdio bridge for CraftTable MCP")
.version("0.1.1");
.version("0.1.2");
withConnection(program.command("login").description("Log in through the system browser"))
.option("--no-browser", "print the authorization URL instead of opening it")
+111 -9
View File
@@ -1,6 +1,22 @@
import { randomUUID } from "node:crypto";
import type { OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js";
export const KEYRING_SERVICE = "CraftTable MCP";
const KEYRING_CHUNK_SIZE = 1000;
type CredentialEntry = {
getPassword(): Promise<string | undefined>;
setPassword(password: string): Promise<void>;
deleteCredential(): Promise<boolean>;
};
type CredentialEntryFactory = (account: string) => Promise<CredentialEntry>;
type ChunkManifest = {
version: 2;
generation: string;
chunks: number;
};
export interface TokenStore {
get(account: string): Promise<OAuthTokens | undefined>;
@@ -9,43 +25,129 @@ export interface TokenStore {
}
export class KeyringTokenStore implements TokenStore {
constructor(private readonly entryFactory: CredentialEntryFactory = keyringEntry) {}
async get(account: string): Promise<OAuthTokens | undefined> {
let serialized: string | undefined;
try {
const entry = await keyringEntry(account);
serialized = await entry.getPassword();
serialized = await this.readPassword(account);
} catch (error) {
throw keyringError(error);
}
if (!serialized) return undefined;
const manifest = parseChunkManifest(serialized);
if (manifest) {
try {
const chunks = await Promise.all(Array.from({ length: manifest.chunks }, (_, index) =>
this.readPassword(chunkAccount(account, manifest.generation, index))));
if (chunks.some((chunk) => chunk === undefined)) throw new Error("missing credential chunk");
serialized = Buffer.from(chunks.join(""), "base64").toString("utf8");
} catch (error) {
if (error instanceof Error && error.message === "missing credential chunk") throw invalidCredentialError();
throw keyringError(error);
}
}
try {
const value = JSON.parse(serialized) as OAuthTokens;
if (!value.access_token || !value.token_type) throw new Error("missing token fields");
return value;
} catch {
throw new Error("The saved CraftTable MCP credential is invalid; run `crafttable-mcp logout --local-only` and log in again");
throw invalidCredentialError();
}
}
async set(account: string, tokens: OAuthTokens): Promise<void> {
const encoded = Buffer.from(JSON.stringify(tokens), "utf8").toString("base64");
const chunks = splitCredential(encoded);
const generation = randomUUID().replaceAll("-", "");
const manifest: ChunkManifest = { version: 2, generation, chunks: chunks.length };
let previous: string | undefined;
const writtenAccounts: string[] = [];
try {
const entry = await keyringEntry(account);
await entry.setPassword(JSON.stringify(tokens));
previous = await this.readPassword(account);
for (const [index, chunk] of chunks.entries()) {
const partAccount = chunkAccount(account, generation, index);
await (await this.entryFactory(partAccount)).setPassword(chunk);
writtenAccounts.push(partAccount);
}
await (await this.entryFactory(account)).setPassword(JSON.stringify(manifest));
} catch (error) {
await Promise.allSettled(writtenAccounts.map((partAccount) => this.deletePassword(partAccount)));
throw keyringError(error);
}
const previousManifest = previous && parseChunkManifest(previous);
if (previousManifest) {
await Promise.allSettled(Array.from({ length: previousManifest.chunks }, (_, index) =>
this.deletePassword(chunkAccount(account, previousManifest.generation, index))));
}
}
async delete(account: string): Promise<void> {
try {
const entry = await keyringEntry(account);
await entry.deleteCredential();
const serialized = await this.readPassword(account);
const manifest = serialized ? parseChunkManifest(serialized) : undefined;
await this.deletePassword(account);
if (manifest) {
await Promise.all(Array.from({ length: manifest.chunks }, (_, index) =>
this.deletePassword(chunkAccount(account, manifest.generation, index))));
}
} catch (error) {
const message = String((error as Error)?.message ?? error).toLowerCase();
if (message.includes("no entry") || message.includes("not found")) return;
throw keyringError(error);
}
}
private async readPassword(account: string): Promise<string | undefined> {
try {
return await (await this.entryFactory(account)).getPassword();
} catch (error) {
if (isMissingCredential(error)) return undefined;
throw error;
}
}
private async deletePassword(account: string): Promise<void> {
try {
await (await this.entryFactory(account)).deleteCredential();
} catch (error) {
if (!isMissingCredential(error)) throw error;
}
}
}
function splitCredential(value: string): string[] {
const chunks: string[] = [];
for (let offset = 0; offset < value.length; offset += KEYRING_CHUNK_SIZE) {
chunks.push(value.slice(offset, offset + KEYRING_CHUNK_SIZE));
}
return chunks.length ? chunks : [""];
}
function chunkAccount(account: string, generation: string, index: number): string {
return `${account}:v2:${generation}:${index}`;
}
function parseChunkManifest(value: string): ChunkManifest | undefined {
try {
const parsed = JSON.parse(value) as Partial<ChunkManifest>;
if (parsed.version !== 2 || typeof parsed.generation !== "string" || !/^[0-9a-f]{32}$/.test(parsed.generation)
|| !Number.isInteger(parsed.chunks) || (parsed.chunks ?? 0) < 1 || (parsed.chunks ?? 0) > 100) return undefined;
return parsed as ChunkManifest;
} catch {
return undefined;
}
}
function isMissingCredential(error: unknown): boolean {
const message = String((error as Error)?.message ?? error).toLowerCase();
return message.includes("no entry") || message.includes("not found");
}
function invalidCredentialError(): Error {
return new Error("The saved CraftTable MCP credential is invalid; run `crafttable-mcp logout --local-only` and log in again");
}
async function keyringEntry(account: string): Promise<import("@napi-rs/keyring").AsyncEntry> {
+66
View File
@@ -0,0 +1,66 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js";
import { KeyringTokenStore } from "../src/credentials.js";
class MemoryEntry {
constructor(private readonly values: Map<string, string>, private readonly account: string) {}
async getPassword(): Promise<string | undefined> {
return this.values.get(this.account);
}
async setPassword(password: string): Promise<void> {
if (password.length > 1000) throw new Error("credential too large");
this.values.set(this.account, password);
}
async deleteCredential(): Promise<boolean> {
return this.values.delete(this.account);
}
}
function memoryStore(values = new Map<string, string>()): KeyringTokenStore {
return new KeyringTokenStore(async (account) => new MemoryEntry(values, account));
}
test("keyring token store chunks large OAuth credentials and removes every chunk", async () => {
const values = new Map<string, string>();
const store = memoryStore(values);
const tokens: OAuthTokens = {
access_token: "a".repeat(3400),
refresh_token: "r".repeat(2400),
token_type: "Bearer",
};
await store.set("account", tokens);
assert.ok(values.size > 2);
assert.deepEqual(await store.get("account"), tokens);
assert.ok([...values.values()].every((value) => value.length <= 1000));
await store.delete("account");
assert.equal(values.size, 0);
});
test("keyring token store replaces rotated credentials and cleans old chunks", async () => {
const values = new Map<string, string>();
const store = memoryStore(values);
await store.set("account", { access_token: "a".repeat(3000), refresh_token: "old", token_type: "Bearer" });
const oldAccounts = [...values.keys()].filter((account) => account !== "account");
await store.set("account", { access_token: "b".repeat(3000), refresh_token: "new", token_type: "Bearer" });
assert.equal((await store.get("account"))?.refresh_token, "new");
assert.ok(oldAccounts.every((account) => !values.has(account)));
});
test("keyring token store still reads and removes legacy single-entry credentials", async () => {
const tokens: OAuthTokens = { access_token: "legacy", token_type: "Bearer" };
const values = new Map([["account", JSON.stringify(tokens)]]);
const store = memoryStore(values);
assert.deepEqual(await store.get("account"), tokens);
await store.delete("account");
assert.equal(values.size, 0);
});