Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"chat": "node dist/cli.js",
"openai-agent": "node dist/adapters/openai-agent.js",
"dev:broker": "tsx src/broker/main.ts",
"test": "tsc -p tsconfig.json && node scripts/copy-data.mjs && node --test --test-concurrency=1 --test-timeout=120000 \"dist/test/*.test.js\" src/adapters/codex-channel.test.mjs src/adapters/agy-channel.test.mjs src/adapters/core/files.test.mjs src/adapters/core/broker.test.mjs src/adapters/core/instructions.test.mjs",
"test": "tsc -p tsconfig.json && node scripts/copy-data.mjs && node --test --test-concurrency=1 --test-timeout=120000 \"dist/test/*.test.js\" src/adapters/codex-channel.test.mjs src/adapters/agy-channel.test.mjs src/adapters/core/files.test.mjs src/adapters/core/broker.test.mjs src/adapters/core/instructions.test.mjs src/adapters/core/serviceTokens.test.mjs",
"build:web": "tsc -p web/tsconfig.json && vite build --config web/vite.config.ts",
"dev:web": "vite --config web/vite.config.ts",
"test:web": "vitest run --config web/vite.config.ts",
Expand Down
22 changes: 22 additions & 0 deletions src/adapters/core/serviceTokens.d.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Types of serviceTokens.mjs for the TypeScript adapters (the module itself stays plain JS: see its header).
export declare const SERVICE_ID_RE: RegExp;
export declare const MAX_SERVICE_TOKEN_LENGTH: number;
export declare const SERVICE_TOKEN_HEADER_PREFIX: string;
export declare const LEGACY_GITHUB_KEY: string;
export type ServiceLog = (line: string) => void;
export type ServiceTokenOptions = { dir?: string; log?: ServiceLog };
export declare function serviceTokenHeader(id: string): string;
export declare function serviceTokenFiles(
config: Record<string, unknown> | null | undefined,
options?: ServiceTokenOptions,
): Map<string, string>;
export declare function readServiceToken(file: string): string | null;
export declare function serviceTokens(
config: Record<string, unknown> | null | undefined,
options?: ServiceTokenOptions,
): Map<string, string>;
export declare function serviceTokenHeaders(
config: Record<string, unknown> | null | undefined,
options?: ServiceTokenOptions,
): Record<string, string>;
export declare function redactServiceTokens(text: string, tokens: Iterable<string>): string;
116 changes: 116 additions & 0 deletions src/adapters/core/serviceTokens.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// The adapters' shared core: tokens for other services (ТЗ-5, AIChat 6276-6312). One rule for how an agent's
// aichat.config.json names a token and how that token reaches an HTTP request, so the four adapters cannot drift apart.
// The token is read from a file the manager writes, goes into one header and nowhere else: not into the model's
// context, not into a log, not into a message. Nothing here judges whether the token is good - the broker does that,
// and answers "no token for <id>" when the header is absent (fail closed).
// Plain JS with node:* imports only, like files.mjs: the .mjs adapters and their tests import it as it is, the TS ones
// through serviceTokens.d.mts, and scripts/bundle.mjs puts it into each adapter's single file.
import fs from "node:fs";
import { expandPath } from "./files.mjs";

/** A service id is a config key and part of a header name: lowercase letters, digits and dashes. */
export const SERVICE_ID_RE = /^[a-z0-9-]+$/;
/** A token file holds one line; anything longer than this is the wrong file, not a token. */
export const MAX_SERVICE_TOKEN_LENGTH = 1024;
/** The header a service's token travels in: `X-Service-Token-<id>`. */
export const SERVICE_TOKEN_HEADER_PREFIX = "X-Service-Token-";
/** `ghTokenFile` is read as `serviceTokens.github` for one release (opencode 6306, alexey 6309). */
export const LEGACY_GITHUB_KEY = "ghTokenFile";

/** The header one service's token goes in. */
export function serviceTokenHeader(id) {
return SERVICE_TOKEN_HEADER_PREFIX + id;
}

/** Whether a config's `serviceTokens` names `id` itself, however good or bad that entry is. */
function namedHas(named, id) {
return Boolean(named) && typeof named === "object" && !Array.isArray(named) && Object.prototype.hasOwnProperty.call(named, id);
}

/**
* The services an agent's config names and the files their tokens are in: `[[id, file], …]`.
* `serviceTokens` is read as written; `ghTokenFile` counts as `github` only when `serviceTokens` does not name it.
* Relative paths are resolved against `dir` (the folder of the config), `~` is expanded.
* A malformed id or an empty path is left out and named in the log, without any value.
*/
export function serviceTokenFiles(config, { dir = ".", log } = {}) {
const files = new Map();
const named = config?.serviceTokens;
if (named && typeof named === "object" && !Array.isArray(named)) {
for (const [id, file] of Object.entries(named)) {
if (!SERVICE_ID_RE.test(id)) {
log?.(`aichat: service token skipped, bad id ${JSON.stringify(String(id))}`);
continue;
}
if (typeof file !== "string" || !file.trim()) {
log?.(`aichat: service token ${id} skipped, no file`);
continue;
}
files.set(id, expandPath(file.trim(), dir));
}
}
// The alias serves only a config that has no github entry at all: an empty or broken `serviceTokens.github` is a
// mistake to report, not a reason to fall back to the old PAT (codex 6317 - that would silently revive a token the
// owner meant to replace).
const legacy = config?.[LEGACY_GITHUB_KEY];
if (!namedHas(named, "github") && typeof legacy === "string" && legacy.trim()) {
files.set("github", expandPath(legacy.trim(), dir));
}
return files;
}

/**
* The token in a file as a header value: trimmed, one line, a sane length. Null when the file is missing or holds
* something that cannot be a header value (empty, a control character, too long). Never throws.
*/
export function readServiceToken(file) {
let text;
try {
text = fs.readFileSync(file, "utf8");
} catch {
return null;
}
const token = text.trim();
// A header value is printable ASCII on one line: a newline means the wrong file, a non-ASCII character (an
// accidental UTF-8 file) would make fetch throw on the header and take /mcp down with it (agy 6318).
if (!token || token.length > MAX_SERVICE_TOKEN_LENGTH || /[^\x21-\x7e]/.test(token)) return null;
return token;
}

/**
* `Map(id → token)` for an agent config. A service whose file is missing or unusable is left out with a line in the
* log that names the service and the file, never the value.
*/
export function serviceTokens(config, { dir = ".", log } = {}) {
const tokens = new Map();
for (const [id, file] of serviceTokenFiles(config, { dir, log })) {
const token = readServiceToken(file);
if (token === null) {
log?.(`aichat: service token ${id} is unusable (${file})`);
continue;
}
tokens.set(id, token);
}
return tokens;
}

/**
* `text` with every service token of `tokens` replaced by `[REDACTED]`, longest first so one token never cuts
* another in half: for an adapter's log and error lines (agy 6318). Pass `serviceTokens(config).values()`.
*/
export function redactServiceTokens(text, tokens) {
let out = String(text);
const values = [...new Set(tokens)].filter((t) => typeof t === "string" && t.length > 0).sort((a, b) => b.length - a.length);
for (const token of values) out = out.split(token).join("[REDACTED]");
return out;
}

/**
* `{ "X-Service-Token-github": "…" }` for an agent config: the headers to add to the `/mcp` request and to nothing
* else. Empty when no service has a usable token - the adapter then simply has no rights on any service.
*/
export function serviceTokenHeaders(config, { dir = ".", log } = {}) {
const headers = {};
for (const [id, token] of serviceTokens(config, { dir, log })) headers[serviceTokenHeader(id)] = token;
return headers;
}
131 changes: 131 additions & 0 deletions src/adapters/core/serviceTokens.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// Tests of the adapters' shared service-token rules (core/serviceTokens.mjs): one set for every adapter, so the
// four cannot read one config in four ways. The token itself is checked to stay out of everything but the header.
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import {
MAX_SERVICE_TOKEN_LENGTH,
readServiceToken,
redactServiceTokens,
serviceTokenFiles,
serviceTokenHeader,
serviceTokenHeaders,
serviceTokens,
} from "./serviceTokens.mjs";

/** A throwaway agent folder with token files; `log` collects what an adapter would print. */
function sandbox(t) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "aichat-core-tokens-"));
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const write = (name, text) => {
const file = path.join(dir, name);
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, text);
return file;
};
const lines = [];
const log = (line) => lines.push(line);
return { dir, write, lines, log };
}

test("serviceTokenHeader: the name comes from the id alone", () => {
assert.equal(serviceTokenHeader("github"), "X-Service-Token-github");
assert.equal(serviceTokenHeader("jira-cloud"), "X-Service-Token-jira-cloud");
});

test("serviceTokenFiles: serviceTokens as written, paths resolved against the config folder", (t) => {
const s = sandbox(t);
s.write("github.token", "ghp_one\n");
const files = serviceTokenFiles({ serviceTokens: { github: "github.token" } }, { dir: s.dir });
assert.deepEqual([...files], [["github", path.join(s.dir, "github.token")]]);
});

test("serviceTokenFiles: ghTokenFile counts as github, and only when serviceTokens does not name it", (t) => {
const s = sandbox(t);
s.write("legacy.token", "ghp_legacy\n");
s.write("new.token", "ghp_new\n");
const legacy = serviceTokenFiles({ ghTokenFile: "legacy.token" }, { dir: s.dir });
assert.deepEqual([...legacy], [["github", path.join(s.dir, "legacy.token")]]);
const both = serviceTokenFiles({ serviceTokens: { github: "new.token" }, ghTokenFile: "legacy.token" }, { dir: s.dir });
assert.deepEqual([...both], [["github", path.join(s.dir, "new.token")]]);
});

test("serviceTokenFiles: an explicit but bad github entry never falls back to ghTokenFile (codex 6317)", (t) => {
const s = sandbox(t);
s.write("legacy.token", "ghp_legacy\n");
for (const bad of ["", " ", null, 42]) {
const files = serviceTokenFiles({ serviceTokens: { github: bad }, ghTokenFile: "legacy.token" }, { dir: s.dir, log: s.log });
assert.equal(files.size, 0, `an entry ${JSON.stringify(bad)} is a mistake to report, not a reason to revive the old PAT`);
}
assert.ok(s.lines.length >= 4);
assert.ok(s.lines.every((line) => !line.includes("ghp_")));
});

test("serviceTokenFiles: a bad id or an empty path is skipped and named, without any value", (t) => {
const s = sandbox(t);
s.write("good.token", "ghp_good\n");
const files = serviceTokenFiles(
{ serviceTokens: { Good: "good.token", "with space": "x.token", github: " ", jira: "good.token" } },
{ dir: s.dir, log: s.log },
);
assert.deepEqual([...files.keys()], ["jira"]);
assert.equal(s.lines.length, 3);
assert.ok(s.lines.every((line) => !line.includes("ghp_")), "a log line never carries a value");
});

test("readServiceToken: trimmed, one line, printable ASCII only; anything else is null and never throws", (t) => {
const s = sandbox(t);
assert.equal(readServiceToken(s.write("ok.token", " ghp_ok\n")), "ghp_ok");
assert.equal(readServiceToken(s.write("empty.token", " \n")), null);
assert.equal(readServiceToken(s.write("two.token", "ghp_a\nghp_b\n")), null);
assert.equal(readServiceToken(s.write("nul.token", "ghp_a\u0000b")), null);
assert.equal(readServiceToken(s.write("space.token", "ghp_a b")), null, "a space would not survive a header check anyway");
assert.equal(readServiceToken(s.write("tab.token", "ghp_a\tb")), null);
assert.equal(readServiceToken(s.write("utf8.token", "ghp_кирилиця")), null, "fetch throws on a non-ASCII header value");
assert.equal(readServiceToken(s.write("long.token", "x".repeat(MAX_SERVICE_TOKEN_LENGTH + 1))), null);
assert.equal(readServiceToken(path.join(s.dir, "missing.token")), null);
assert.equal(readServiceToken(s.dir), null, "a folder is not a token file");
});

test("redactServiceTokens: every value goes, longest first, and the rest stays", () => {
const short = "ghp_ab";
const long = "ghp_abcdef";
assert.equal(redactServiceTokens(`${long} then ${short}`, [short, long]), "[REDACTED] then [REDACTED]");
assert.equal(redactServiceTokens("nothing here", new Map().values()), "nothing here");
});

test("serviceTokens: every named service with a usable file, the rest left out with a log line", (t) => {
const s = sandbox(t);
s.write("gh.token", "ghp_gh\n");
s.write("broken.token", "ghp_a\nghp_b\n");
const tokens = serviceTokens(
{ serviceTokens: { github: "gh.token", jira: "broken.token", gitlab: "missing.token" } },
{ dir: s.dir, log: s.log },
);
assert.deepEqual([...tokens], [["github", "ghp_gh"]]);
assert.equal(s.lines.length, 2);
assert.ok(s.lines.every((line) => !line.includes("ghp_")), "a log line never carries a value");
});

test("serviceTokenHeaders: the one shape an adapter adds to a request, and nothing when there is no token", (t) => {
const s = sandbox(t);
s.write("gh.token", "ghp_gh\n");
assert.deepEqual(serviceTokenHeaders({ serviceTokens: { github: "gh.token" } }, { dir: s.dir }), {
"X-Service-Token-github": "ghp_gh",
});
assert.deepEqual(serviceTokenHeaders({}, { dir: s.dir, log: s.log }), {});
assert.deepEqual(serviceTokenHeaders({ ghTokenFile: "missing.token" }, { dir: s.dir, log: s.log }), {});
assert.equal(s.lines.length, 1, "the missing legacy token is reported once");
assert.ok(!s.lines[0].includes("ghp_"));
});

test("a token value never leaks into the returned files, only into the header", (t) => {
const s = sandbox(t);
s.write("gh.token", "ghp_secret_value\n");
const config = { serviceTokens: { github: "gh.token" } };
assert.ok(!JSON.stringify([...serviceTokenFiles(config, { dir: s.dir })]).includes("ghp_secret_value"));
assert.ok(JSON.stringify([...serviceTokens(config, { dir: s.dir })]).includes("ghp_secret_value"), "the caller may build a header");
assert.ok(!JSON.stringify(s.lines).includes("ghp_secret_value"));
});