@codyn06/cboard 0.0.1 → 0.2.0

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.
Files changed (117) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +71 -3
  3. package/THIRD_PARTY_NOTICES +29 -0
  4. package/bin/cboard-context.js +15 -0
  5. package/bin/cboard.js +5 -0
  6. package/dist/adapters/bash.d.ts +2 -0
  7. package/dist/adapters/bash.js +14 -0
  8. package/dist/adapters/c-family.d.ts +2 -0
  9. package/dist/adapters/c-family.js +81 -0
  10. package/dist/adapters/csharp.d.ts +2 -0
  11. package/dist/adapters/csharp.js +47 -0
  12. package/dist/adapters/extra-languages.d.ts +3 -0
  13. package/dist/adapters/extra-languages.js +15 -0
  14. package/dist/adapters/go.d.ts +2 -0
  15. package/dist/adapters/go.js +42 -0
  16. package/dist/adapters/grammar.d.ts +21 -0
  17. package/dist/adapters/grammar.js +54 -0
  18. package/dist/adapters/index.d.ts +20 -0
  19. package/dist/adapters/index.js +62 -0
  20. package/dist/adapters/java.d.ts +2 -0
  21. package/dist/adapters/java.js +36 -0
  22. package/dist/adapters/kotlin.d.ts +2 -0
  23. package/dist/adapters/kotlin.js +65 -0
  24. package/dist/adapters/lua-family.d.ts +2 -0
  25. package/dist/adapters/lua-family.js +186 -0
  26. package/dist/adapters/php.d.ts +2 -0
  27. package/dist/adapters/php.js +28 -0
  28. package/dist/adapters/python.d.ts +2 -0
  29. package/dist/adapters/python.js +68 -0
  30. package/dist/adapters/ruby.d.ts +2 -0
  31. package/dist/adapters/ruby.js +46 -0
  32. package/dist/adapters/rust.d.ts +2 -0
  33. package/dist/adapters/rust.js +85 -0
  34. package/dist/adapters/swift.d.ts +2 -0
  35. package/dist/adapters/swift.js +38 -0
  36. package/dist/adapters/types.d.ts +61 -0
  37. package/dist/adapters/types.js +1 -0
  38. package/dist/adapters/typescript.d.ts +2 -0
  39. package/dist/adapters/typescript.js +52 -0
  40. package/dist/api.d.ts +56 -0
  41. package/dist/api.js +439 -0
  42. package/dist/cboard.d.ts +2 -0
  43. package/dist/cboard.js +151 -0
  44. package/dist/cli.d.ts +27 -0
  45. package/dist/cli.js +180 -0
  46. package/dist/docs-parse.d.ts +64 -0
  47. package/dist/docs-parse.js +762 -0
  48. package/dist/docs.d.ts +39 -0
  49. package/dist/docs.js +243 -0
  50. package/dist/extract.d.ts +36 -0
  51. package/dist/extract.js +480 -0
  52. package/dist/index.d.ts +5 -0
  53. package/dist/index.js +5 -0
  54. package/dist/issues.d.ts +44 -0
  55. package/dist/issues.js +138 -0
  56. package/dist/languages.d.ts +9 -0
  57. package/dist/languages.js +128 -0
  58. package/dist/model.d.ts +85 -0
  59. package/dist/model.js +1 -0
  60. package/dist/wake.d.ts +13 -0
  61. package/dist/wake.js +33 -0
  62. package/grammars/LICENSES/README.md +3 -0
  63. package/grammars/LICENSES/c.LICENSE +21 -0
  64. package/grammars/LICENSES/kotlin.LICENSE +21 -0
  65. package/grammars/LICENSES/lua.LICENSE +21 -0
  66. package/grammars/LICENSES/luau.LICENSE +21 -0
  67. package/grammars/LICENSES/swift.LICENSE +21 -0
  68. package/grammars/manifest.json +39 -0
  69. package/grammars/tree-sitter-c.wasm +0 -0
  70. package/grammars/tree-sitter-kotlin.wasm +0 -0
  71. package/grammars/tree-sitter-lua.wasm +0 -0
  72. package/grammars/tree-sitter-luau.wasm +0 -0
  73. package/grammars/tree-sitter-swift.wasm +0 -0
  74. package/kit/cboard-connect.js +869 -0
  75. package/kit/cboard-kit/brief.js +512 -0
  76. package/kit/cboard-kit/config.js +250 -0
  77. package/kit/cboard-kit/connect-check.js +95 -0
  78. package/kit/cboard-kit/device.js +192 -0
  79. package/kit/cboard-kit/drift.js +55 -0
  80. package/kit/cboard-kit/headers.js +46 -0
  81. package/kit/cboard-kit/mcp.js +97 -0
  82. package/kit/cboard-kit/references.js +70 -0
  83. package/kit/cboard-kit/skill/SKILL.md +170 -0
  84. package/kit/cboard-kit/wait.js +45 -0
  85. package/package.json +47 -5
  86. package/queries/bash/imports.scm +11 -0
  87. package/queries/bash/symbols.scm +1 -0
  88. package/queries/c/imports.scm +2 -0
  89. package/queries/c/symbols.scm +10 -0
  90. package/queries/cpp/imports.scm +2 -0
  91. package/queries/cpp/symbols.scm +11 -0
  92. package/queries/csharp/imports.scm +2 -0
  93. package/queries/csharp/symbols.scm +10 -0
  94. package/queries/go/imports.scm +2 -0
  95. package/queries/go/symbols.scm +8 -0
  96. package/queries/java/imports.scm +2 -0
  97. package/queries/java/symbols.scm +9 -0
  98. package/queries/javascript/imports.scm +3 -0
  99. package/queries/javascript/symbols.scm +16 -0
  100. package/queries/kotlin/imports.scm +2 -0
  101. package/queries/kotlin/symbols.scm +4 -0
  102. package/queries/lua/imports.scm +5 -0
  103. package/queries/lua/symbols.scm +6 -0
  104. package/queries/luau/imports.scm +5 -0
  105. package/queries/luau/symbols.scm +9 -0
  106. package/queries/php/imports.scm +6 -0
  107. package/queries/php/symbols.scm +7 -0
  108. package/queries/python/imports.scm +3 -0
  109. package/queries/python/symbols.scm +8 -0
  110. package/queries/ruby/imports.scm +2 -0
  111. package/queries/ruby/symbols.scm +4 -0
  112. package/queries/rust/imports.scm +5 -0
  113. package/queries/rust/symbols.scm +11 -0
  114. package/queries/swift/imports.scm +2 -0
  115. package/queries/swift/symbols.scm +5 -0
  116. package/queries/typescript/imports.scm +3 -0
  117. package/queries/typescript/symbols.scm +20 -0
@@ -0,0 +1,250 @@
1
+ /* global URL, process */
2
+ // Shared by the cboard kit scripts: finds `.cboard.json` and resolves which cboard graph,
3
+ // project and token a repository uses. Dependency-free (Node built-ins only).
4
+ //
5
+ // .cboard.json (tracked, never holds a token):
6
+ // { "server": "https://…", "projectId": "<uuid>", "tokenFile": ".cboard/token",
7
+ // "tokenEnv": "CBOARD_PAT" }
8
+ // Optional keys: "references" ([{ "name", "projectId", "tokenFile" }]: other projects read through their
9
+ // own graph:read token, see `connect --reference`), "goalNodeId" (the project goal requirement node, written by `connect --goal`), "releaseBranch" (shows how far that branch lags main), "statusNodeFile" (a file
10
+ // holding the status node id to show) and "syncCommand" (how to run the cboard command).
11
+ // Environment overrides: CBOARD_GRAPH_URL (a 127.0.0.1/localhost URL selects the local dev graph),
12
+ // CBOARD_PROJECT_ID, and the token variable named by "tokenEnv" (default CBOARD_PAT).
13
+ import { existsSync, readFileSync } from "node:fs";
14
+ import { dirname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
15
+ import { fileURLToPath } from "node:url";
16
+
17
+ export const CONFIG_FILE = ".cboard.json";
18
+ // The one place that names the hosted service; everything else reads `.cboard.json`.
19
+ export const DEFAULT_SERVER = "https://cboard-fij7.onrender.com";
20
+ export const DEFAULT_TOKEN_FILE = ".cboard/token";
21
+ export const DEFAULT_TOKEN_ENV = "CBOARD_PAT";
22
+ export const LOCAL_TOKEN_FILE = ".local/cboard.pat";
23
+ export const DEFAULT_SYNC_COMMAND = "npx @codyn06/cboard";
24
+ export const REFERENCE_NAME = /^[a-z0-9][a-z0-9-]{0,30}$/;
25
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
26
+ /** MCP server name and token file a reference name maps to. */
27
+ export const referenceServer = (name) => `cboard-ref-${name}`;
28
+ export const referenceTokenFile = (name) => `.cboard/ref-${name}.token`;
29
+
30
+ /** Old connect versions wrote a checkout path or `cboard-context` here; those no longer work. */
31
+ export const isStaleSyncCommand = (command) =>
32
+ typeof command === "string" && /<cboard-checkout>|cboard-context/.test(command);
33
+
34
+ /** The default command pinned to a kit version, so the printed sync matches the installed kit. */
35
+ export const pinSyncCommand = (command, version) =>
36
+ command === DEFAULT_SYNC_COMMAND && /^\d+\.\d+\.\d+/.test(String(version))
37
+ ? `${DEFAULT_SYNC_COMMAND}@${String(version)}`
38
+ : command;
39
+
40
+ export class ConfigError extends Error {
41
+ constructor(message) {
42
+ super(message);
43
+ this.name = "ConfigError";
44
+ }
45
+ }
46
+
47
+ export const TOKEN_ENV_PATTERN = /^CBOARD_[A-Z0-9_]+$/;
48
+
49
+ export function isLocalHost(url) {
50
+ return url.hostname === "127.0.0.1" || url.hostname === "localhost";
51
+ }
52
+
53
+ /** A local server (http allowed) or an https one; no other scheme may carry a token. */
54
+ export function isLocalOrHttps(url) {
55
+ return isLocalHost(url)
56
+ ? url.protocol === "http:" || url.protocol === "https:"
57
+ : url.protocol === "https:";
58
+ }
59
+
60
+ /** Servers the user trusted outside the repository: the default, CBOARD_TRUSTED_SERVERS, CBOARD_GRAPH_URL. */
61
+ export function isTrustedServer(origin, env) {
62
+ const trusted = [
63
+ DEFAULT_SERVER,
64
+ env.CBOARD_GRAPH_URL ?? "",
65
+ ...(env.CBOARD_TRUSTED_SERVERS ?? "").split(","),
66
+ ];
67
+ return trusted.some((entry) => {
68
+ try {
69
+ return entry.trim() !== "" && new URL(entry.trim()).origin === origin;
70
+ } catch {
71
+ return false;
72
+ }
73
+ });
74
+ }
75
+
76
+ /** Only CBOARD_* variables may be read as a token, so a config cannot name a secret like AWS_*. */
77
+ export function validateTokenEnv(name) {
78
+ if (!TOKEN_ENV_PATTERN.test(name)) {
79
+ throw new ConfigError(
80
+ `${CONFIG_FILE}: tokenEnv must match ${String(TOKEN_ENV_PATTERN)} (got "${name}")`,
81
+ );
82
+ }
83
+ }
84
+
85
+ /**
86
+ * A path from .cboard.json must be relative and stay inside the repository root. The file is
87
+ * shared across machines, so Windows and POSIX absolute forms and `..` segments with either
88
+ * separator are refused on every platform.
89
+ */
90
+ export function validateRepoPath(root, path, key) {
91
+ const rel = relative(root, resolve(root, path));
92
+ if (
93
+ isAbsolute(path) ||
94
+ win32.isAbsolute(path) ||
95
+ posix.isAbsolute(path) ||
96
+ path.split(/[\\/]/).includes("..") ||
97
+ rel === "" ||
98
+ rel === ".." ||
99
+ rel.startsWith(`..${sep}`) ||
100
+ isAbsolute(rel)
101
+ ) {
102
+ throw new ConfigError(
103
+ `${CONFIG_FILE}: ${key} must be a relative path inside the repository (got "${path}")`,
104
+ );
105
+ }
106
+ }
107
+
108
+ /** Nearest directory at or above `start` holding `.cboard.json`, or null. */
109
+ export function findRoot(start) {
110
+ let dir = resolve(start);
111
+ for (;;) {
112
+ if (existsSync(join(dir, CONFIG_FILE))) return dir;
113
+ const parent = dirname(dir);
114
+ if (parent === dir) return null;
115
+ dir = parent;
116
+ }
117
+ }
118
+
119
+ /** Raw parsed `.cboard.json` of a repository root, or null when absent. */
120
+ export function readConfigFile(root) {
121
+ const file = join(root, CONFIG_FILE);
122
+ if (!existsSync(file)) return null;
123
+ let parsed;
124
+ try {
125
+ parsed = JSON.parse(readFileSync(file, "utf8"));
126
+ } catch {
127
+ throw new ConfigError(`${file} is not valid JSON`);
128
+ }
129
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
130
+ throw new ConfigError(`${file} must be a JSON object`);
131
+ }
132
+ return parsed;
133
+ }
134
+
135
+ const str = (value) => (typeof value === "string" && value.trim() ? value.trim() : undefined);
136
+
137
+ /**
138
+ * Resolves the graph target for a repository.
139
+ * @param {Record<string, string | undefined>} env
140
+ * @param {string} root repository root (the directory that holds `.cboard.json`)
141
+ * @param {{ required?: boolean }} [options] `required`: throw when `.cboard.json` is missing
142
+ */
143
+ export function resolveConfig(env, root, options = {}) {
144
+ const file = readConfigFile(root);
145
+ if (!file && options.required) {
146
+ throw new ConfigError(
147
+ `no ${CONFIG_FILE} in ${root}; run \`node <cboard-checkout>/scripts/cboard-connect.js --project <uuid>\` in this repository`,
148
+ );
149
+ }
150
+ // .cboard.json is tracked, so a cloned repository controls it: it must not be able to steer a
151
+ // token to another host or make us read another file. Keep packages/code-context/src/cli.ts
152
+ // (resolveSync) in step with these rules.
153
+ const fromEnv = env.CBOARD_GRAPH_URL?.trim();
154
+ const configured = fromEnv || str(file?.server) || DEFAULT_SERVER;
155
+ let url;
156
+ try {
157
+ url = new URL(configured);
158
+ } catch {
159
+ throw new ConfigError(`server URL is not valid: ${configured}`);
160
+ }
161
+ if (!isLocalOrHttps(url)) throw new ConfigError("the cboard server must use https");
162
+ const local = isLocalHost(url);
163
+ if (!local && !fromEnv && !isTrustedServer(url.origin, env)) {
164
+ throw new ConfigError(
165
+ `${CONFIG_FILE} names the server ${url.origin}, which is not the default cboard server; ` +
166
+ `no token is sent there. If you trust it, set CBOARD_TRUSTED_SERVERS=${url.origin}`,
167
+ );
168
+ }
169
+ const tokenEnv = str(file?.tokenEnv) ?? DEFAULT_TOKEN_ENV;
170
+ validateTokenEnv(tokenEnv);
171
+ const configuredTokenFile = str(file?.tokenFile) ?? DEFAULT_TOKEN_FILE;
172
+ validateRepoPath(root, configuredTokenFile, "tokenFile");
173
+ const tokenFile = local ? LOCAL_TOKEN_FILE : configuredTokenFile;
174
+ const statusNodeFile = str(file?.statusNodeFile);
175
+ const syncCommand = str(file?.syncCommand);
176
+ if (statusNodeFile) validateRepoPath(root, statusNodeFile, "statusNodeFile");
177
+ const abs = (path) => join(root, path);
178
+ // Reference projects: read-only access to other projects, each with its own token file (never the
179
+ // main token, never $CBOARD_PAT).
180
+ const rawRefs = file?.references ?? [];
181
+ if (!Array.isArray(rawRefs)) throw new ConfigError(`${CONFIG_FILE}: references must be an array`);
182
+ const references = rawRefs.map((raw) => {
183
+ const name = str(raw?.name);
184
+ const refProject = str(raw?.projectId);
185
+ if (!name || !REFERENCE_NAME.test(name) || !refProject || !UUID_PATTERN.test(refProject)) {
186
+ throw new ConfigError(
187
+ `${CONFIG_FILE}: each reference needs a name (lowercase letters, digits, hyphens) and a project UUID`,
188
+ );
189
+ }
190
+ const tokenFileRel = str(raw.tokenFile) ?? referenceTokenFile(name);
191
+ validateRepoPath(root, tokenFileRel, `references.${name}.tokenFile`);
192
+ return { name, projectId: refProject, tokenFile: abs(tokenFileRel), tokenFileRel };
193
+ });
194
+ return {
195
+ root,
196
+ configured: file !== null,
197
+ hosted: !local,
198
+ api: local ? `http://127.0.0.1:${env.CBOARD_API_PORT ?? "5394"}` : url.origin,
199
+ projectId: env.CBOARD_PROJECT_ID?.trim() || str(file?.projectId),
200
+ tokenEnv,
201
+ tokenFile: abs(tokenFile),
202
+ tokenFileRel: tokenFile,
203
+ releaseBranch: str(file?.releaseBranch),
204
+ goalNodeId: str(file?.goalNodeId),
205
+ references,
206
+ statusNodeFile: statusNodeFile ? abs(statusNodeFile) : undefined,
207
+ syncCommand:
208
+ syncCommand && !isStaleSyncCommand(syncCommand) ? syncCommand : DEFAULT_SYNC_COMMAND,
209
+ };
210
+ }
211
+
212
+ /**
213
+ * The token, in order: a non-default `tokenEnv` variable, the repo token file (when non-empty),
214
+ * then the global CBOARD_PAT. The repo file beats CBOARD_PAT so a user-wide PAT cannot shadow the
215
+ * token of a connected repo.
216
+ */
217
+ export function readToken(config, env) {
218
+ if (config.tokenEnv !== DEFAULT_TOKEN_ENV) {
219
+ const custom = env[config.tokenEnv]?.trim();
220
+ if (custom) return custom;
221
+ }
222
+ const fromFile = existsSync(config.tokenFile)
223
+ ? readFileSync(config.tokenFile, "utf8").trim()
224
+ : "";
225
+ return fromFile || env.CBOARD_PAT?.trim() || "";
226
+ }
227
+
228
+ /** A reference's token: its own file only, so a reference can never borrow the main (writable) token. */
229
+ export function readReferenceToken(reference) {
230
+ return existsSync(reference.tokenFile) ? readFileSync(reference.tokenFile, "utf8").trim() : "";
231
+ }
232
+
233
+ /** The repo root for a kit script: from the working directory, else from the kit's own location. */
234
+ export function locateRoot(cwd, importMetaUrl) {
235
+ return findRoot(cwd) ?? findRoot(dirname(fileURLToPath(importMetaUrl))) ?? resolve(cwd);
236
+ }
237
+
238
+ /** True when the module is the entry script (not imported). */
239
+ export function isMain(importMetaUrl) {
240
+ return Boolean(process.argv[1]) && resolve(process.argv[1]) === fileURLToPath(importMetaUrl);
241
+ }
242
+
243
+ /** How to get a token, for messages. */
244
+ export function tokenFix(config) {
245
+ return (
246
+ "create one in cboard (Agent tokens button in the project header; members choose graph:read, " +
247
+ `graph:contribute, graph:context; viewers are read-only (graph:read only)) and save it to ${config.tokenFileRel} (it takes precedence over $${DEFAULT_TOKEN_ENV}` +
248
+ (config.tokenEnv === DEFAULT_TOKEN_ENV ? ")" : `; $${config.tokenEnv} overrides the file)`)
249
+ );
250
+ }
@@ -0,0 +1,95 @@
1
+ /* global process, console */
2
+ // SessionStart hook: checks that this repository can reach its cboard graph (token present and
3
+ // accepted, configured project visible). Never starts anything and never prints the token.
4
+ // Prints `cboard graph: CONNECTED …` or a fix hint on stderr; exits 1 when not connected.
5
+ import { McpError, describeWhoami, fetchWhoami, mcpCall } from "./mcp.js";
6
+ import { retryWake } from "./wait.js";
7
+ import { checkReference } from "./references.js";
8
+ import { ConfigError, isMain, locateRoot, readToken, resolveConfig, tokenFix } from "./config.js";
9
+
10
+ // The hosted service may need up to a minute to wake from idle; retry with backoff within this
11
+ // budget (the hook timeout is 120 s).
12
+ const HOSTED_WAKE_MS = 90_000;
13
+
14
+ /** @returns {Promise<{ code: number, message: string }>} */
15
+ export async function connectCheck(env, root, { fetchImpl, timeoutMs, wake } = {}) {
16
+ let config;
17
+ try {
18
+ config = resolveConfig(env, root, { required: true });
19
+ } catch (error) {
20
+ if (error instanceof ConfigError) return { code: 1, message: error.message };
21
+ throw error;
22
+ }
23
+ const main = await checkMain(config, env, { fetchImpl, timeoutMs, wake });
24
+ if (!config.references.length) return main;
25
+ const refs = await Promise.all(
26
+ config.references.map((ref) =>
27
+ checkReference(config, ref, { ...(fetchImpl ? { fetchImpl } : {}), timeoutMs }),
28
+ ),
29
+ );
30
+ return {
31
+ code: main.code || (refs.some((r) => !r.ok) ? 1 : 0),
32
+ message: [main.message, ...refs.map((r) => r.message)].join("\n"),
33
+ };
34
+ }
35
+
36
+ async function checkMain(config, env, { fetchImpl, timeoutMs, wake }) {
37
+ const token = readToken(config, env);
38
+ if (!token) return { code: 1, message: `token missing; ${tokenFix(config)}` };
39
+ let projects;
40
+ const budgetMs = wake?.budgetMs ?? (config.hosted ? HOSTED_WAKE_MS : 0);
41
+ try {
42
+ const listed = await retryWake(
43
+ (attemptMs) =>
44
+ mcpCall({
45
+ api: config.api,
46
+ token,
47
+ name: "list_projects",
48
+ timeoutMs: timeoutMs ?? (budgetMs ? attemptMs : 5000),
49
+ ...(fetchImpl ? { fetchImpl } : {}),
50
+ }),
51
+ { ...wake, budgetMs },
52
+ );
53
+ projects = Array.isArray(listed?.data) ? listed.data : [];
54
+ } catch (error) {
55
+ if (error instanceof McpError && error.kind === "unauthorized") {
56
+ return { code: 1, message: `token rejected; ${tokenFix(config)}` };
57
+ }
58
+ return {
59
+ code: 1,
60
+ message:
61
+ budgetMs > 0
62
+ ? `hosted service did not wake within ${String(Math.round(budgetMs / 1000))} s (${config.api}); retry in a minute, or check the service`
63
+ : `graph unreachable (${config.api}); retry, or check the service`,
64
+ };
65
+ }
66
+ if (config.projectId && !projects.some((p) => p.id === config.projectId)) {
67
+ return {
68
+ code: 1,
69
+ message: `connected to ${config.api}, but project ${config.projectId} is not visible to this token; ${tokenFix(config)}`,
70
+ };
71
+ }
72
+ // Optional: an older server lacks whoami; any failure keeps the plain message. One short try only.
73
+ const me = await fetchWhoami(() =>
74
+ mcpCall({
75
+ api: config.api,
76
+ token,
77
+ name: "whoami",
78
+ timeoutMs: timeoutMs ?? 5000,
79
+ ...(fetchImpl ? { fetchImpl } : {}),
80
+ }),
81
+ );
82
+ const info = me ? describeWhoami(me) : null;
83
+ const head = info?.readOnly
84
+ ? "CONNECTED (read-only): you can query, not contribute"
85
+ : "CONNECTED";
86
+ const tail = info?.warning ? `; ${info.warning}` : "";
87
+ return { code: 0, message: `${head} (${config.api}/mcp)${tail}` };
88
+ }
89
+
90
+ if (isMain(import.meta.url)) {
91
+ const root = locateRoot(process.cwd(), import.meta.url);
92
+ const result = await connectCheck(process.env, root);
93
+ console.error(`cboard graph: ${result.message}`);
94
+ process.exitCode = result.code;
95
+ }
@@ -0,0 +1,192 @@
1
+ /* global fetch, AbortSignal, process, setTimeout, console, Buffer, URL */
2
+ // Browser (device) login for `cboard connect`: the CLI asks the server for a code, the owner
3
+ // approves it in the browser and picks the project, and the token comes back encrypted to a key
4
+ // that never leaves this process ("cboard-device-v1": X25519 + HKDF-SHA256 + AES-256-GCM).
5
+ // Never logs or prints the token.
6
+ import { spawn } from "node:child_process";
7
+ import {
8
+ createDecipheriv,
9
+ createPublicKey,
10
+ diffieHellman,
11
+ generateKeyPairSync,
12
+ hkdfSync,
13
+ } from "node:crypto";
14
+ import { retryWake } from "./wait.js";
15
+
16
+ const SCHEME = "cboard-device-v1";
17
+ const UNSUPPORTED =
18
+ "this server does not support browser login; use --project <id> and a token (see docs/guides/using-cboard.md)";
19
+
20
+ export class DeviceError extends Error {
21
+ /** @param {string} message @param {boolean} [transient] network failure or 5xx: worth retrying */
22
+ constructor(message, transient = false) {
23
+ super(message);
24
+ this.name = "DeviceError";
25
+ this.transient = transient;
26
+ }
27
+ }
28
+
29
+ /** Decrypts `encrypted_token` (base64url of serverPub[32] | iv[12] | ciphertext | tag[16]). */
30
+ export function decryptToken(privateKey, encrypted) {
31
+ const raw = Buffer.from(String(encrypted), "base64url");
32
+ if (raw.length < 32 + 12 + 16 + 1) throw new DeviceError("the server sent a malformed token");
33
+ try {
34
+ const ephemeral = createPublicKey({
35
+ key: { kty: "OKP", crv: "X25519", x: raw.subarray(0, 32).toString("base64url") },
36
+ format: "jwk",
37
+ });
38
+ const shared = diffieHellman({ privateKey, publicKey: ephemeral });
39
+ const key = Buffer.from(hkdfSync("sha256", shared, Buffer.alloc(0), SCHEME, 32));
40
+ const decipher = createDecipheriv("aes-256-gcm", key, raw.subarray(32, 44));
41
+ decipher.setAAD(Buffer.from(SCHEME));
42
+ decipher.setAuthTag(raw.subarray(raw.length - 16));
43
+ return Buffer.concat([
44
+ decipher.update(raw.subarray(44, raw.length - 16)),
45
+ decipher.final(),
46
+ ]).toString("utf8");
47
+ } catch {
48
+ throw new DeviceError("could not decrypt the token the server sent");
49
+ }
50
+ }
51
+
52
+ /** Best effort: open the URL in the default browser without a shell. Never throws. */
53
+ export function openBrowser(url) {
54
+ try {
55
+ const parsed = new URL(url);
56
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return;
57
+ const [command, args] =
58
+ process.platform === "win32"
59
+ ? ["rundll32", ["url.dll,FileProtocolHandler", parsed.href]]
60
+ : process.platform === "darwin"
61
+ ? ["open", [parsed.href]]
62
+ : ["xdg-open", [parsed.href]];
63
+ const child = spawn(command, args, { stdio: "ignore", detached: true, windowsHide: true });
64
+ child.on("error", () => undefined);
65
+ child.unref();
66
+ } catch {
67
+ // Printing the URL is the fallback.
68
+ }
69
+ }
70
+
71
+ async function post(fetchImpl, server, path, body) {
72
+ let res;
73
+ try {
74
+ res = await fetchImpl(`${server}${path}`, {
75
+ method: "POST",
76
+ signal: AbortSignal.timeout(30_000),
77
+ headers: { "content-type": "application/json", accept: "application/json" },
78
+ body: JSON.stringify(body),
79
+ });
80
+ } catch {
81
+ throw new DeviceError(`could not reach ${server}`, true);
82
+ }
83
+ if (res.status >= 500) throw new DeviceError(`${server} answered ${String(res.status)}`, true);
84
+ let json = null;
85
+ try {
86
+ json = await res.json();
87
+ } catch {
88
+ // Handled by status below.
89
+ }
90
+ return { status: res.status, ok: res.ok, json };
91
+ }
92
+
93
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
94
+
95
+ /**
96
+ * Runs the device flow against `server` (an origin) and returns the token and the chosen project.
97
+ * @param {{ server: string, fetchImpl?: typeof fetch, print?: (line: string) => void,
98
+ * open?: ((url: string) => void) | null, sleep?: (ms: number) => Promise<void>,
99
+ * now?: () => number, wakeBudgetMs?: number }} options `open: null` skips the browser.
100
+ * @returns {Promise<{ token: string, projectId: string, scopes: string[], expiresAt: string }>}
101
+ */
102
+ export async function deviceLogin({
103
+ server,
104
+ fetchImpl = fetch,
105
+ print = console.log,
106
+ open = openBrowser,
107
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
108
+ now = Date.now,
109
+ wakeBudgetMs = 0,
110
+ }) {
111
+ const { publicKey, privateKey } = generateKeyPairSync("x25519");
112
+ const clientPublicKey = publicKey.export({ format: "jwk" }).x;
113
+ const started = await retryWake(
114
+ () => post(fetchImpl, server, "/v1/device/code", { client_public_key: clientPublicKey }),
115
+ { budgetMs: wakeBudgetMs, onWake: (message) => print(`cboard: ${message}`), sleep, now },
116
+ );
117
+ if (started.status === 404) throw new DeviceError(UNSUPPORTED);
118
+ if (started.status === 429) {
119
+ throw new DeviceError("the server is rate limiting login requests; wait a minute and retry");
120
+ }
121
+ const grant = started.json;
122
+ if (
123
+ !started.ok ||
124
+ !isObject(grant) ||
125
+ typeof grant.device_code !== "string" ||
126
+ typeof grant.user_code !== "string" ||
127
+ typeof grant.verification_uri !== "string"
128
+ ) {
129
+ throw new DeviceError(`the server did not start a login (status ${String(started.status)})`);
130
+ }
131
+ const deadline = now() + (Number(grant.expires_in) > 0 ? Number(grant.expires_in) : 600) * 1000;
132
+ let interval = Number(grant.interval) >= 0 ? Number(grant.interval) : 5;
133
+ const url =
134
+ typeof grant.verification_uri_complete === "string"
135
+ ? grant.verification_uri_complete
136
+ : grant.verification_uri;
137
+ print(`Open ${url}`);
138
+ print(`and confirm the code ${grant.user_code} to connect this repository.`);
139
+ // Only open a page on the server we are talking to; a mismatched origin is printed, never launched.
140
+ let sameOrigin = false;
141
+ try {
142
+ sameOrigin = new URL(url).origin === new URL(server).origin;
143
+ } catch {
144
+ // an unparsable URL is not opened
145
+ }
146
+ if (open && sameOrigin) open(url);
147
+ print("Waiting for approval in the browser...");
148
+
149
+ for (;;) {
150
+ await sleep(interval * 1000);
151
+ if (now() >= deadline) throw new DeviceError("the login code expired; run connect again");
152
+ let polled;
153
+ try {
154
+ polled = await post(fetchImpl, server, "/v1/device/token", {
155
+ device_code: grant.device_code,
156
+ });
157
+ } catch (error) {
158
+ if (error instanceof DeviceError && error.transient) continue;
159
+ throw error;
160
+ }
161
+ if (polled.status === 429) {
162
+ interval += 5;
163
+ continue;
164
+ }
165
+ const body = polled.json;
166
+ if (polled.ok && isObject(body) && typeof body.encrypted_token === "string") {
167
+ const token = decryptToken(privateKey, body.encrypted_token);
168
+ if (!/^cbp_[A-Za-z0-9_-]+$/.test(token))
169
+ throw new DeviceError("the server returned a token in an unexpected format");
170
+ return {
171
+ token,
172
+ projectId: String(body.project_id),
173
+ scopes: Array.isArray(body.scopes) ? body.scopes : [],
174
+ expiresAt: String(body.expires_at ?? ""),
175
+ };
176
+ }
177
+ const code = isObject(body) ? body.error : undefined;
178
+ if (code === "authorization_pending") {
179
+ if (Number(body.interval) >= 0) interval = Number(body.interval);
180
+ } else if (code === "slow_down") {
181
+ interval = Number(body.interval) >= 0 ? Number(body.interval) : interval + 5;
182
+ } else if (code === "expired_token") {
183
+ throw new DeviceError("the login code expired; run connect again");
184
+ } else if (code === "access_denied") {
185
+ throw new DeviceError("the login was denied in the browser");
186
+ } else {
187
+ throw new DeviceError(
188
+ `the login is no longer valid (${typeof code === "string" ? code : String(polled.status)}); run connect again`,
189
+ );
190
+ }
191
+ }
192
+ }
@@ -0,0 +1,55 @@
1
+ /* global AbortSignal, fetch */
2
+ // Compares the kit version with the npm `latest` of @codyn06/cboard. Cached once a day in the
3
+ // kit directory; silent (returns undefined) on any failure.
4
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+
7
+ export const REGISTRY_URL = "https://registry.npmjs.org/@codyn06%2fcboard/latest";
8
+ export const CACHE_FILE = "latest-version.json";
9
+ const DAY_MS = 24 * 60 * 60 * 1000;
10
+ const FETCH_TIMEOUT_MS = 1500;
11
+
12
+ const parse = (v) => (/^\d+\.\d+\.\d+/.exec(String(v))?.[0] ?? "").split(".").map(Number);
13
+
14
+ /** True when version `a` is older than `b` (plain major.minor.patch comparison). */
15
+ export function isOlder(a, b) {
16
+ const x = parse(a);
17
+ const y = parse(b);
18
+ if (x.length !== 3 || y.length !== 3) return false;
19
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] < y[i];
20
+ return false;
21
+ }
22
+
23
+ /** The npm latest version, from today's cache or the registry; undefined on any failure. */
24
+ export async function latestVersion({ dir, fetchImpl = fetch, now = Date.now() }) {
25
+ const file = join(dir, CACHE_FILE);
26
+ try {
27
+ const cached = JSON.parse(readFileSync(file, "utf8"));
28
+ if (typeof cached.version === "string" && now - cached.checkedAt < DAY_MS)
29
+ return cached.version;
30
+ } catch {
31
+ // No usable cache: ask the registry.
32
+ }
33
+ try {
34
+ const res = await fetchImpl(REGISTRY_URL, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
35
+ if (!res.ok) return undefined;
36
+ const version = (await res.json()).version;
37
+ if (typeof version !== "string") return undefined;
38
+ try {
39
+ mkdirSync(dir, { recursive: true });
40
+ writeFileSync(file, JSON.stringify({ version, checkedAt: now }));
41
+ } catch {
42
+ // Read-only kit directory: just no cache.
43
+ }
44
+ return version;
45
+ } catch {
46
+ return undefined;
47
+ }
48
+ }
49
+
50
+ /** One line when the kit is older than npm latest; empty otherwise. */
51
+ export function driftLine(kit, latest) {
52
+ return kit && latest && isOlder(kit, latest)
53
+ ? `cboard kit ${kit} is behind npm latest ${latest}: run \`npx @codyn06/cboard@latest connect\` to update.`
54
+ : "";
55
+ }
@@ -0,0 +1,46 @@
1
+ /* global process, console */
2
+ // Claude Code `headersHelper` for the cboard MCP server (.mcp.json): prints the auth header JSON.
3
+ // Makes no network call (Claude Code waits on this helper and the hosted service may be asleep).
4
+ // Exits 1 with a fix hint on stderr when there is no token.
5
+ import {
6
+ ConfigError,
7
+ isMain,
8
+ locateRoot,
9
+ readReferenceToken,
10
+ readToken,
11
+ resolveConfig,
12
+ tokenFix,
13
+ } from "./config.js";
14
+
15
+ /** @returns {{ code: number, stdout?: string, stderr?: string }} */
16
+ export function headersResult(env, cwd, importMetaUrl, referenceName) {
17
+ try {
18
+ const config = resolveConfig(env, locateRoot(cwd, importMetaUrl), { required: true });
19
+ if (referenceName) {
20
+ // A reference sends its own token only; it never falls back to the main token or $CBOARD_PAT.
21
+ const reference = config.references.find((r) => r.name === referenceName);
22
+ if (!reference) return { code: 1, stderr: `cboard: no reference named ${referenceName}` };
23
+ const refToken = readReferenceToken(reference);
24
+ if (!refToken) {
25
+ return {
26
+ code: 1,
27
+ stderr: `cboard: no token for reference ${referenceName}; save a graph:read token to ${reference.tokenFileRel}`,
28
+ };
29
+ }
30
+ return { code: 0, stdout: JSON.stringify({ Authorization: `Bearer ${refToken}` }) };
31
+ }
32
+ const token = readToken(config, env);
33
+ if (!token) return { code: 1, stderr: `cboard: no token; ${tokenFix(config)}` };
34
+ return { code: 0, stdout: JSON.stringify({ Authorization: `Bearer ${token}` }) };
35
+ } catch (error) {
36
+ if (error instanceof ConfigError) return { code: 1, stderr: `cboard: ${error.message}` };
37
+ throw error;
38
+ }
39
+ }
40
+
41
+ if (isMain(import.meta.url)) {
42
+ const result = headersResult(process.env, process.cwd(), import.meta.url, process.argv[2]);
43
+ if (result.stdout) console.log(result.stdout);
44
+ if (result.stderr) console.error(result.stderr);
45
+ process.exitCode = result.code;
46
+ }