clankoff-bridge 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,30 +4,43 @@ Play games on a Clankoff site with the AI command-line tools installed on your o
4
4
  Copilot, Gemini), using your own subscriptions. The site sends your machine a game position; your CLI answers; the
5
5
  bridge sends the answer back. That is all it does.
6
6
 
7
- No dependencies: everything that runs is the five files in `src/`, about 580 lines. Read them before you run them.
7
+ No dependencies: everything that runs is the seven files in `src/`, about 750 lines. Read them before you run them.
8
8
 
9
9
  ## Use
10
10
 
11
11
  You need Node.js 24 or newer, and at least one AI CLI installed and logged in (for example, `claude` works in your
12
12
  terminal).
13
13
 
14
- 1. On the Clankoff site, open **Account → Bridge** and click **Make a bridge token**. It shows two lines, once.
15
- 2. Put them in a file called `.env` in an empty folder (or set them as environment variables):
16
- ```
17
- CLANKOFF_SERVER=https://the-clankoff-site
18
- CLANKOFF_BRIDGE_TOKEN=clk_bridge_…
19
- ```
20
- 3. In that folder, run:
14
+ 1. Run it, in any folder:
21
15
  ```
22
16
  npx clankoff-bridge
23
17
  ```
24
- Options: `--agents claude,codex` offers only those CLIs, `--max 2` sets how many turns run at once, and `--server`
25
- overrides `CLANKOFF_SERVER`. Leave it running; Ctrl-C stops it.
26
- 4. On the site, choose **Claude via bridge** (or Codex, Copilot, Gemini) as your player. Only you see them, and only
27
- while your bridge is running.
18
+ (For a Clankoff site other than `https://clankoff.com`, add `--server https://that-site`.)
19
+ 2. It prints a link to the site's Account page, and opens it if this machine has a browser. Sign in there, check that
20
+ the page shows the same code as your terminal, and click **Connect**. Any device you are signed in on will do.
21
+ 3. The terminal says `ready`. Leave it running; Ctrl-C stops it. On the site, choose **Claude via bridge** (or Codex,
22
+ Copilot, Gemini) as your player. Only you see them, and only while your bridge is running.
23
+
24
+ You do that once. The bridge remembers the site and its token in `~/.config/clankoff-bridge/config.json`
25
+ (`%APPDATA%\clankoff-bridge` on Windows), a file only your user can read, so from then on `npx clankoff-bridge` starts
26
+ straight away. If the site later refuses the token (you revoked it), the bridge forgets it and prints a new link.
27
+
28
+ Options: `--server` is the site (default `https://clankoff.com`, or the one remembered), `--agents claude,codex` offers
29
+ only those CLIs, `--max 2` sets how many turns run at once, and `--forget` deletes the remembered site and token.
30
+
31
+ On a machine with no terminal (a service, a container): on the site, open **Account → Bridge**, make a token by hand,
32
+ and set `CLANKOFF_SERVER` and `CLANKOFF_BRIDGE_TOKEN` in the environment, or in a `.env` file in the folder the bridge
33
+ runs from. They come first when set, and nothing is saved. A site too old to connect from the browser gets the same
34
+ kind of token pasted into the terminal instead (it isn't shown as you paste).
28
35
 
29
36
  ## What it does
30
37
 
38
+ 0. **Connects to your account**, the first time (`src/pair.js`). It makes a random token on your machine and sends
39
+ the site only the token's SHA-256 (`POST <server>/api/bridge/pair`), getting a short code back. It prints
40
+ `<server>/account#pair=<code>` and opens it with your system's opener (`open`, `xdg-open`; not over ssh).
41
+ When you click Connect there, the site starts accepting that token; the bridge finds out by asking
42
+ `GET <server>/api/bridge/whoami` every few seconds, for at most ten minutes. Only connect a code you see in your
43
+ own terminal: whoever holds the bridge behind a code plays your turns.
31
44
  1. **Checks the token** with `GET <server>/api/bridge/whoami` and prints whose account it belongs to. The server
32
45
  must be an `https://` address (plain `http://` only for `localhost`), so the token never travels unencrypted.
33
46
  2. **Connects out** to `<server>/api/bridge/connect` over a WebSocket. Nothing listens on your machine. The token
@@ -63,7 +76,8 @@ or the bridge token: `ANTHROPIC_API_KEY`, `ANTHROPIC_BASE_URL`, `OPENAI_API_KEY`
63
76
  ### What leaves your machine
64
77
 
65
78
  The names of your CLIs and their models, and for each turn the CLI's final answer text, or which kind of failure it
66
- was (never the CLI's own error output). No files, no environment, no keys.
79
+ was (never the CLI's own error output). When connecting: the SHA-256 of the bridge's token, then the token itself in a
80
+ header, as on every later run. No files, no environment, no keys, not your machine's name.
67
81
 
68
82
  ## Good to know
69
83
 
@@ -90,10 +104,19 @@ JSON over a WebSocket (plus text `ping` / `pong`):
90
104
 
91
105
  Close code 4001 means the token was revoked; 4000 means another bridge took over.
92
106
 
107
+ Connecting from the browser, before any of that (plain HTTPS):
108
+
109
+ | Request | Answer |
110
+ |---|---|
111
+ | `POST /api/bridge/pair` `{tokenHash}` (hex SHA-256 of a token the bridge made) | `{code, expiresIn}` |
112
+ | `GET /api/bridge/whoami` with the token, while waiting | `401 {pairing: "pending"}`, then `200 {name}` once connected; a plain `401` if it was declined or ran out |
113
+
93
114
  ## Files
94
115
 
95
116
  ```
96
- src/cli.js the npx command: reads options and the token, starts the bridge
117
+ src/cli.js the npx command: reads options, finds the token (environment, remembered, or a new one), starts the bridge
118
+ src/pair.js connects to your account with a link and a click in the browser
119
+ src/saved.js the file the site and token are remembered in; pasting a token, for a site that can't do the above
97
120
  src/client.js connection, hello, running and cancelling turns, reconnecting
98
121
  src/agents.js how each CLI is run (arguments, empty folder, withheld variables, timeouts)
99
122
  src/reap.js finds and kills processes a CLI left behind
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clankoff-bridge",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Play Clankoff games with the AI CLIs on your own machine (Claude Code, Codex, Copilot, Gemini), tools off. No dependencies; read src/ to see everything it does.",
5
5
  "license": "MIT",
6
6
  "author": "jaysencpp",
@@ -20,6 +20,7 @@
20
20
  ".": "./src/client.js",
21
21
  "./agents": "./src/agents.js",
22
22
  "./meta": "./src/meta.js",
23
+ "./pair": "./src/pair.js",
23
24
  "./reap": "./src/reap.js"
24
25
  },
25
26
  "files": [
package/src/cli.js CHANGED
@@ -1,15 +1,22 @@
1
1
  #!/usr/bin/env node
2
2
  // clankoff-bridge: play turns for a Clankoff site with the AI CLIs installed on this machine. See README.md.
3
3
  //
4
- // npx clankoff-bridge [--server https://…] [--agents claude,codex] [--max 2]
4
+ // npx clankoff-bridge [--server https://…] [--agents claude,codex] [--max 2] [--forget]
5
5
  //
6
- // The token comes from CLANKOFF_BRIDGE_TOKEN (environment, or a .env file in the current folder), never the command
7
- // line, where other users of this machine could see it. --server can also be CLANKOFF_SERVER.
6
+ // The first run prints a link to the site's Account page (and opens it): sign in there and click Connect (src/pair.js).
7
+ // The bridge then remembers its token with the site's address (src/saved.js), so later runs ask nothing.
8
+ // A site that can't do that gets a token pasted in the terminal instead. CLANKOFF_BRIDGE_TOKEN and CLANKOFF_SERVER
9
+ // (environment, or a .env file in the current folder) come first if set. The token is never taken from the command
10
+ // line, where other users of this machine could see it.
8
11
  // Each turn runs a CLI with its tools off, in a fresh empty folder, without API keys or this token (src/agents.js).
9
12
  import { parseArgs } from 'node:util';
10
13
  import { readFileSync } from 'node:fs';
11
14
  import { cliAgents } from './agents.js';
12
- import { startBridge } from './client.js';
15
+ import { serverBase, startBridge } from './client.js';
16
+ import { openBrowser, startPairing, waitForApproval } from './pair.js';
17
+ import { askToken, forget, looksLikeToken, readSaved, save, savedPath } from './saved.js';
18
+
19
+ const DEFAULT_SERVER = 'https://clankoff.com';
13
20
 
14
21
  // .env in the current folder, if there is one (variables already set win)
15
22
  try { process.loadEnvFile(); } catch { /* none */ }
@@ -20,20 +27,65 @@ const { values } = parseArgs({
20
27
  server: { type: 'string' },
21
28
  agents: { type: 'string' },
22
29
  max: { type: 'string' },
30
+ forget: { type: 'boolean' },
23
31
  help: { type: 'boolean', short: 'h' },
24
32
  version: { type: 'boolean', short: 'v' },
25
33
  },
26
34
  });
27
35
  const usage = `clankoff-bridge ${version}
28
36
  usage: npx clankoff-bridge [--server https://your-clankoff.example] [--agents claude,codex] [--max 2]
29
- The token is read from CLANKOFF_BRIDGE_TOKEN (environment or ./.env); make one on the site's Account page.`;
37
+ The first run prints a link: open it, sign in to the site and click Connect. The bridge then remembers its token in
38
+ ${savedPath()}
39
+ --server the site to play on (default ${DEFAULT_SERVER}, or the one remembered)
40
+ --forget delete the remembered site and token, and stop
41
+ Without a terminal (a service, a container), make a token on the site's Account page and set CLANKOFF_BRIDGE_TOKEN
42
+ (and CLANKOFF_SERVER) in the environment or ./.env.`;
30
43
  if (values.help) { console.log(usage); process.exit(0); }
31
44
  if (values.version) { console.log(version); process.exit(0); }
32
- const server = values.server || process.env.CLANKOFF_SERVER;
33
- const token = process.env.CLANKOFF_BRIDGE_TOKEN;
34
- if (!server || !token) {
35
- console.error(`${!server ? 'No server given. ' : ''}${!token ? 'CLANKOFF_BRIDGE_TOKEN is not set (make one on the Account page). ' : ''}\n${usage}`);
36
- process.exit(2);
45
+ if (values.forget) { forget(); console.log(`Forgot the site and token in ${savedPath()}. To switch the token off for good, revoke it on the site's Account page.`); process.exit(0); }
46
+
47
+ const saved = readSaved();
48
+ const server = serverBase(values.server || process.env.CLANKOFF_SERVER || saved?.server || DEFAULT_SERVER);
49
+ if (server instanceof Error) { console.error(`${server.message}\n${usage}`); process.exit(2); }
50
+ const canShow = process.stdout.isTTY; // someone is there to read a link
51
+ const canAsk = canShow && process.stdin.isTTY;
52
+ const stop = (line, code = 1) => { console.error(line); process.exit(code); };
53
+
54
+ /** A token for this machine: connected with a click in the browser, or pasted if the site can't do that. */
55
+ async function connect() {
56
+ console.log(`Site: ${server}`);
57
+ let pairing;
58
+ try { pairing = await startPairing(server); } catch (e) {
59
+ if (!e.status) stop(`Can't reach ${server}: ${e.cause?.message || e.message}`);
60
+ if (!canAsk) stop(`${server} can't connect a bridge from the browser (${e.message}).\n${usage}`, 2);
61
+ console.log(`This site can't connect a bridge from the browser right now (${e.message}).`);
62
+ return ask();
63
+ }
64
+ console.log(`\nOpen this link, sign in, and click Connect (it works for ${Math.round(pairing.expiresIn / 60)} minutes):\n\n ${pairing.url}\n\nThe page must show the code ${pairing.code}. Waiting for the click…`);
65
+ openBrowser(pairing.url);
66
+ try { await waitForApproval(server, pairing); } catch (e) { stop(`Not connected: ${e.message}. Run it again for a new link.`); }
67
+ return pairing.token;
68
+ }
69
+
70
+ /** Ask until something that looks like a token is pasted. */
71
+ async function ask() {
72
+ console.log('Make a bridge token there (Account → Bridge) and paste it here. It won\'t show as you paste.');
73
+ for (;;) {
74
+ const answer = await askToken('Bridge token: ');
75
+ if (looksLikeToken(answer)) return answer;
76
+ if (!answer) { console.error('No token entered.'); process.exit(2); }
77
+ console.log('That isn\'t a bridge token: they start with clk_bridge_. Try again, or Ctrl-C to stop.');
78
+ }
79
+ }
80
+
81
+ // the token: the environment's, else the one remembered for this site, else a new one connected now
82
+ let token = process.env.CLANKOFF_BRIDGE_TOKEN;
83
+ let from = 'the environment';
84
+ if (!token && saved && serverBase(saved.server) === server) { token = saved.token; from = 'saved'; }
85
+ if (!token) {
86
+ if (!canShow) stop(`CLANKOFF_BRIDGE_TOKEN is not set, and there is no terminal to show a link in.\n${usage}`, 2);
87
+ token = await connect();
88
+ from = 'connected';
37
89
  }
38
90
 
39
91
  let agents = cliAgents();
@@ -42,7 +94,22 @@ if (values.agents) {
42
94
  agents = Object.fromEntries(Object.entries(agents).filter(([id]) => wanted.has(id)));
43
95
  }
44
96
  const stamp = () => new Date().toLocaleTimeString();
45
- const bridge = startBridge({ server, token, agents, client: `clankoff-bridge@${version}`, maxConcurrent: Math.max(1, Number(values.max) || 2), log: (line) => console.log(`${stamp()} ${line}`) });
46
- bridge.ready.then((name) => console.log(`${stamp()} ready: games on ${server} can now use your CLIs as ${name}. Ctrl-C to stop.`))
47
- .catch((e) => { console.error(`${stamp()} bridge stopped: ${e.message}`); process.exit(1); });
48
- for (const sig of ['SIGINT', 'SIGTERM']) process.once(sig, () => { bridge.close(); process.exit(0); });
97
+ let bridge;
98
+ for (const sig of ['SIGINT', 'SIGTERM']) process.once(sig, () => { bridge?.close(); process.exit(0); });
99
+ for (;;) {
100
+ bridge = startBridge({ server, token, agents, client: `clankoff-bridge@${version}`, maxConcurrent: Math.max(1, Number(values.max) || 2), log: (line) => console.log(`${stamp()} ${line}`) });
101
+ try {
102
+ const name = await bridge.ready;
103
+ if (from === 'connected') { save({ server, token }); console.log(`${stamp()} remembered in ${savedPath()}: next time, just run npx clankoff-bridge (--forget deletes it)`); }
104
+ console.log(`${stamp()} ready: games on ${server} can now use your CLIs as ${name}. Ctrl-C to stop.`);
105
+ break;
106
+ } catch (e) {
107
+ console.error(`${stamp()} bridge stopped: ${e.message}`);
108
+ // a token the site refuses: drop it if it was the remembered one, and connect again
109
+ if (e.code !== 'bad-token' || from === 'the environment') process.exit(1);
110
+ if (from === 'saved') forget();
111
+ if (!canShow) process.exit(1);
112
+ token = await connect();
113
+ from = 'connected';
114
+ }
115
+ }
package/src/client.js CHANGED
@@ -144,7 +144,7 @@ export function startBridge({ server, token, agents, log = (line) => console.log
144
144
  // Check the token over plain HTTP first: a refused WebSocket gives no reason.
145
145
  fetch(`${base}/api/bridge/whoami`, { headers: { Authorization: `Bearer ${token}` } })
146
146
  .then(async (r) => {
147
- if (r.status === 401) throw new Error('the server doesn\'t know this bridge token (revoked, or for another site?)');
147
+ if (r.status === 401) throw Object.assign(new Error('the server doesn\'t know this bridge token (revoked, or for another site?)'), { code: 'bad-token' });
148
148
  if (!r.ok) throw new Error(`the server answered ${r.status}`);
149
149
  log(`bridge token belongs to ${(await r.json()).name}`);
150
150
  connect();
package/src/pair.js ADDED
@@ -0,0 +1,53 @@
1
+ // Connecting to your account with a click in the browser, instead of a copied token.
2
+ // The bridge makes a token here and sends the site only its SHA-256, getting a short code back. You open the site's
3
+ // Account page with that code, signed in, and click Connect: the site then accepts the token this machine is holding.
4
+ // The token itself is not sent until the site says the link was approved.
5
+ import { createHash, randomBytes } from 'node:crypto';
6
+ import { spawn } from 'node:child_process';
7
+
8
+ const CODE_RE = /^[A-Z2-9]{4}-[A-Z2-9]{4}$/;
9
+ const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
10
+
11
+ /**
12
+ * Ask the site for a code. Resolves with {token, code, url, expiresIn (seconds)}. An Error with `.status` means the
13
+ * site answered but can't do this (an older site, or too many waiting); without, it couldn't be reached.
14
+ * @param {string} base the site's address, from serverBase()
15
+ */
16
+ export async function startPairing(base) {
17
+ const token = `clk_bridge_${randomBytes(24).toString('base64url')}`;
18
+ const tokenHash = createHash('sha256').update(token).digest('hex');
19
+ const r = await fetch(`${base}/api/bridge/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ tokenHash }) });
20
+ const j = await r.json().catch(() => ({}));
21
+ if (!r.ok) throw Object.assign(new Error(typeof j.error === 'string' ? j.error : `the site answered ${r.status}`), { status: r.status });
22
+ // the code goes into a link that is opened in a browser: only a code, nothing else the site might send
23
+ if (!CODE_RE.test(j.code)) throw Object.assign(new Error('the site sent a code this bridge doesn\'t understand'), { status: r.status });
24
+ return { token, code: j.code, url: `${base}/account#pair=${j.code}`, expiresIn: Math.max(30, Math.min(Number(j.expiresIn) || 600, 3600)) };
25
+ }
26
+
27
+ /** Wait for the click. Resolves with the account's name; rejects when it was declined or the link ran out. */
28
+ export async function waitForApproval(base, { token, expiresIn }, { every = 2000 } = {}) {
29
+ const until = Date.now() + expiresIn * 1000;
30
+ for (let n = 0; Date.now() < until; n++) {
31
+ await sleep(n < 60 ? every : every * 2.5); // every 2 s for two minutes, then every 5 s
32
+ let r;
33
+ try { r = await fetch(`${base}/api/bridge/whoami`, { headers: { Authorization: `Bearer ${token}` } }); } catch { continue; } // offline for a moment
34
+ const j = await r.json().catch(() => ({}));
35
+ if (r.ok) return String(j.name || '');
36
+ if (r.status === 401 && j.pairing !== 'pending') throw new Error('it was declined on the site, or the link ran out');
37
+ }
38
+ throw new Error('the link ran out before anyone clicked Connect');
39
+ }
40
+
41
+ /** Open the link in this machine's browser, if it has one. Fails silently: the link is printed too. */
42
+ export function openBrowser(url, { platform = process.platform, env = process.env } = {}) {
43
+ if (platform !== 'darwin' && platform !== 'win32' && !env.DISPLAY && !env.WAYLAND_DISPLAY) return false; // no desktop (ssh, a server)
44
+ const [cmd, args] = platform === 'darwin' ? ['open', [url]]
45
+ : platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
46
+ : ['xdg-open', [url]];
47
+ try {
48
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true }); // no shell: the link is one argument
49
+ child.on('error', () => {});
50
+ child.unref();
51
+ return true;
52
+ } catch { return false; }
53
+ }
package/src/saved.js ADDED
@@ -0,0 +1,50 @@
1
+ // The site and token the bridge was given, remembered between runs so it asks only once: one small JSON file in your
2
+ // config folder that only your user can read. Also the question itself, asked in the terminal the first time.
3
+ import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join } from 'node:path';
6
+ import { createInterface } from 'node:readline';
7
+ import { Writable } from 'node:stream';
8
+
9
+ /** Where it is kept: ~/.config/clankoff-bridge/config.json (XDG_CONFIG_HOME if set; %APPDATA% on Windows). */
10
+ export function savedPath(env = process.env) {
11
+ const dir = env.XDG_CONFIG_HOME || (process.platform === 'win32' && env.APPDATA) || join(homedir(), '.config');
12
+ return join(dir, 'clankoff-bridge', 'config.json');
13
+ }
14
+
15
+ /** What was saved, or null (no file, or not one of ours). */
16
+ export function readSaved(path = savedPath()) {
17
+ try {
18
+ const { server, token } = JSON.parse(readFileSync(path, 'utf8'));
19
+ return typeof server === 'string' && typeof token === 'string' ? { server, token } : null;
20
+ } catch { return null; }
21
+ }
22
+
23
+ export function save({ server, token }, path = savedPath()) {
24
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
25
+ writeFileSync(path, `${JSON.stringify({ server, token }, null, 2)}\n`, { mode: 0o600 });
26
+ chmodSync(path, 0o600); // the mode above only counts for a new file
27
+ }
28
+
29
+ export function forget(path = savedPath()) {
30
+ rmSync(path, { force: true });
31
+ }
32
+
33
+ /** A pasted token, tidied: spaces and quotes off, and the `CLANKOFF_BRIDGE_TOKEN=` in front if a whole .env line was pasted. */
34
+ export function cleanToken(text) {
35
+ return String(text || '').trim().replace(/^CLANKOFF_BRIDGE_TOKEN\s*=\s*/, '').replace(/^["']|["']$/g, '').trim();
36
+ }
37
+ export const looksLikeToken = (token) => /^clk_bridge_[\w-]+$/.test(token);
38
+
39
+ /** Ask for the token in the terminal. What is typed or pasted isn't shown, so it stays out of the scrollback. */
40
+ export function askToken(question) {
41
+ return new Promise((resolve) => {
42
+ let hide = false;
43
+ const output = new Writable({ write(chunk, enc, done) { if (!hide) process.stdout.write(chunk, enc); done(); } });
44
+ const rl = createInterface({ input: process.stdin, output, terminal: true });
45
+ rl.on('SIGINT', () => { process.stdout.write('\n'); process.exit(130); });
46
+ rl.on('close', () => resolve('')); // Ctrl-D; after an answer this does nothing
47
+ rl.question(question, (answer) => { process.stdout.write('\n'); resolve(cleanToken(answer)); rl.close(); });
48
+ hide = true; // the question is written; nothing after it is
49
+ });
50
+ }