trylode 0.2.1 → 0.3.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.
- package/PERMISSIONS.md +4 -0
- package/README.md +3 -1
- package/bin/cli.mjs +19 -9
- package/package.json +1 -1
- package/skill/PERMISSIONS.md +2 -0
- package/skill/scripts/failure-hook.mjs +173 -0
- package/skill/scripts/failure-signals.json +988 -0
- package/skill/scripts/gate.mjs +5 -3
- package/skill/scripts/lode.mjs +73 -45
package/PERMISSIONS.md
CHANGED
|
@@ -21,6 +21,10 @@
|
|
|
21
21
|
|
|
22
22
|
If a `gate.mjs` or `gate-packages.json` that differs from this package's copy is already in the project, setup refuses (exit 2) rather than point the hook at it.
|
|
23
23
|
|
|
24
|
+
### Only with `--triage` (the failure hook, Claude Code only, off unless you add it)
|
|
25
|
+
|
|
26
|
+
The same as `--gate`, for a second hook: one `PostToolUseFailure` entry in `.claude/settings.local.json` that runs `.claude/skills/lode-integration-check/scripts/failure-hook.mjs` after a shell command fails, plus that script and `failure-signals.json`. When a command fails with an integration error it recognises, it sends Lode (`POST https://trylode.io/v1/triage`) only the one app and platform named and a failure code, worked out on your machine; never the error text, the command, paths, versions or file contents. `npx trylode remove --triage --yes` takes out only the failure hook.
|
|
27
|
+
|
|
24
28
|
## Reads
|
|
25
29
|
|
|
26
30
|
Only the files above, to see what is already there. It never follows links, never edits a file it can't parse or couldn't write back exactly (a repeated key, or a number JSON can't keep exactly), and refuses files that are links, hard links, larger than 1 MB or not plain UTF-8.
|
package/README.md
CHANGED
|
@@ -15,6 +15,8 @@ It adds:
|
|
|
15
15
|
|
|
16
16
|
Optional (Claude Code only): Lode Gate. Running `npx trylode setup --gate --yes` adds a hook that runs just before the agent installs a package Lode knows (for example, `npm install resend`) and injects Lode's facts into the agent's context: required platform plan, recorded regions, and any SDK deprecation or published security advisory (each with a link and date). It never blocks an install and applies only to you, in this project (`.claude/settings.local.json`, kept out of git). When triggered, it sends only package names and a few codes to Lode—never your full command, source code, or local file paths. See [PERMISSIONS.md](PERMISSIONS.md) for details.
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
Optional (Claude Code only): the Lode failure hook. Running `npx trylode setup --triage --yes` adds a hook that runs after a shell command fails. If the output shows an integration failure Lode recognises (for example a rejected key, a rate limit or a webhook signature error from one app it knows), it adds Lode's facts about that failure to the agent's context. It never blocks and applies only to you, in this project. It reads the error on your machine and sends Lode only the app, the platform and a failure code: never the error text, your command, source code or file paths. See [PERMISSIONS.md](PERMISSIONS.md).
|
|
19
|
+
|
|
20
|
+
Undo it with `npx trylode remove --yes` (or `npx trylode remove --gate --yes` for Gate only, `npx trylode remove --triage --yes` for the failure hook only). Setup itself sends nothing to Lode. See [PERMISSIONS.md](PERMISSIONS.md).
|
|
19
21
|
|
|
20
22
|
Source: [lode-hq/lode-mcp](https://github.com/lode-hq/lode-mcp). MIT licence. Lode's data is free to use with a link per fact; see [trylode.io](https://trylode.io).
|
package/bin/cli.mjs
CHANGED
|
@@ -7,16 +7,19 @@
|
|
|
7
7
|
// No dependencies, no install scripts. See PERMISSIONS.md.
|
|
8
8
|
|
|
9
9
|
const USAGE = `Usage:
|
|
10
|
-
npx trylode setup [--yes] [--client claude|cursor|all] [--no-rules] [--gate]
|
|
10
|
+
npx trylode setup [--yes] [--client claude|cursor|all] [--no-rules] [--gate] [--triage]
|
|
11
11
|
Shows what it would add to this project, and adds it with --yes:
|
|
12
12
|
.mcp.json and .cursor/mcp.json: one "lode" server entry (other entries unchanged)
|
|
13
13
|
CLAUDE.md, AGENTS.md (only if present), .cursor/rules/lode.mdc: the Lode rules line
|
|
14
14
|
.claude/skills/lode-integration-check/: the Lode Integration Check skill
|
|
15
15
|
--gate Also enables Lode Gate for Claude Code in .claude/settings.local.json (user-local, not shared).
|
|
16
16
|
Injects Lode's facts into the agent's context before installing a known package; never blocks.
|
|
17
|
-
|
|
17
|
+
--triage Also enables the Lode failure hook for Claude Code in .claude/settings.local.json (user-local, not shared).
|
|
18
|
+
When a command fails with an integration error it recognises, adds Lode's facts to the agent's context; never blocks.
|
|
19
|
+
npx trylode remove [--yes] [--gate] [--triage]
|
|
18
20
|
Takes out only what setup (or the skill's init) added.
|
|
19
21
|
--gate Removes only Lode Gate (leaves the rest of your Lode setup intact).
|
|
22
|
+
--triage Removes only the Lode failure hook.
|
|
20
23
|
|
|
21
24
|
Setup and remove send nothing to Lode. What Lode Gate sends when it runs: PERMISSIONS.md. More: https://trylode.io/agents/`;
|
|
22
25
|
|
|
@@ -28,11 +31,12 @@ const cmd = argv[0];
|
|
|
28
31
|
// Only these flags are passed on; anything else is ignored. --gate is handled here (warn mode, this person only):
|
|
29
32
|
// --shared and --mode are never passed through, so setup can't put the hook in a committed file (LOD-262).
|
|
30
33
|
const flags = [];
|
|
31
|
-
let gate = false, client = 'all';
|
|
34
|
+
let gate = false, triage = false, client = 'all';
|
|
32
35
|
for (let i = 1; i < argv.length; i++) {
|
|
33
36
|
const a = argv[i];
|
|
34
37
|
if (a === '--yes' || a === '--no-rules') flags.push(a);
|
|
35
38
|
else if (a === '--gate') gate = true;
|
|
39
|
+
else if (a === '--triage') triage = true;
|
|
36
40
|
else if (a === '--client' && ['claude', 'cursor', 'all'].includes(argv[i + 1])) { client = argv[i + 1]; flags.push(a, argv[i + 1]); i++; }
|
|
37
41
|
}
|
|
38
42
|
const yes = flags.includes('--yes') ? ['--yes'] : [];
|
|
@@ -45,18 +49,24 @@ async function steps() {
|
|
|
45
49
|
if (cmd === 'setup') {
|
|
46
50
|
const first = await run(['init', '--src', 'setup', ...flags]);
|
|
47
51
|
if (!OK.test(first)) return { out: [first], ok: false };
|
|
48
|
-
if (client === 'cursor') return { out: [first, ...(gate ? ['Lode Gate
|
|
49
|
-
if (gate
|
|
52
|
+
if (client === 'cursor') return { out: [first, ...(gate || triage ? ['Lode Gate and the failure hook are for Claude Code only, so they were ignored with --client cursor.'] : [])], ok: true };
|
|
53
|
+
if (gate || triage) {
|
|
54
|
+
const out = [first]; let ok = true;
|
|
55
|
+
for (const [on, f] of [[gate, '--gate'], [triage, '--triage']]) if (on) { const g = await run(['init', f, '--src', 'setup', ...yes]); out.push(g); ok = ok && OK.test(g); }
|
|
56
|
+
return { out, ok };
|
|
57
|
+
}
|
|
50
58
|
// Offer Gate only when it isn't on yet (a dry run of the reviewed check; it writes nothing)
|
|
51
59
|
const dry = await run(['init', '--gate', '--src', 'setup']);
|
|
52
60
|
return { out: [first, ...(/already on in this project/.test(dry) ? [] : [GATE_OFFER])], ok: true };
|
|
53
61
|
}
|
|
54
62
|
if (cmd === 'remove') {
|
|
55
|
-
|
|
56
|
-
|
|
63
|
+
// Each hook first (only the ones that are on are reported), then the rest unless only hooks were named
|
|
64
|
+
const hooks = gate || triage ? [gate && '--gate', triage && '--triage'].filter(Boolean) : ['--gate', '--triage'];
|
|
65
|
+
const outs = [];
|
|
66
|
+
for (const f of hooks) { const g = await run(['init', f, '--remove', '--src', 'setup', ...yes]); if (!/Nothing to remove/.test(g) || gate || triage) outs.push(g); }
|
|
67
|
+
if (gate || triage) return { out: outs, ok: outs.every((o) => OK.test(o)) };
|
|
57
68
|
const rest = await run(['init', '--remove', '--src', 'setup', ...yes]);
|
|
58
|
-
|
|
59
|
-
return { out: [...(gateOn ? [g] : []), rest], ok: OK.test(rest) && (!gateOn || OK.test(g)) };
|
|
69
|
+
return { out: [...outs, rest], ok: OK.test(rest) && outs.every((o) => OK.test(o)) };
|
|
60
70
|
}
|
|
61
71
|
return null;
|
|
62
72
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "trylode",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "One command puts Lode in your project: the MCP server, the rules line and the skill, so your coding agent checks integration facts before it adds a third-party service.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": { "trylode": "bin/cli.mjs" },
|
package/skill/PERMISSIONS.md
CHANGED
|
@@ -19,6 +19,8 @@ secrets. Privacy policy: https://trylode.io/privacy/
|
|
|
19
19
|
| `init` | `.mcp.json`, `.cursor/mcp.json`, `.claude/lode-init.json`, `CLAUDE.md`, `AGENTS.md`, `.cursor/rules/lode.mdc` | nothing | only with `--yes`, only inside a project folder and never through links: one `lode` entry in those MCP files, a copy of this skill in `.claude/skills/`, the Lode rules line as one marked block at the end of `CLAUDE.md` (created if missing) and `AGENTS.md` (only if it exists) and as `.cursor/rules/lode.mdc` (left out with `--no-rules`), and a note of what was added in `.claude/lode-init.json`; a file it can't parse is left alone; `init --remove --yes` undoes only what init added (the rules block only when unchanged); with `--src setup` (used by `npx trylode setup`) the entry's address is `https://trylode.io/mcp?src=setup`, and `--remove` recognises either address |
|
|
20
20
|
| `init --gate` (Lode Gate, opt-in) | `.claude/settings.local.json` (or `.claude/settings.json` with `--shared`), `.claude/lode-init.json`, `.claude/.gitignore`, the Gate files already in `.claude/skills/lode-integration-check/` | nothing | only with `--yes`, only inside a project folder and never through links: one PreToolUse hook entry in that settings file (by default only for you: Claude Code keeps `settings.local.json` out of git; `--shared` gives it to everyone who opens the project), a copy of this skill with `gate.mjs` and `gate-packages.json` in `.claude/skills/` (it never overwrites a file, and refuses if Gate files already there differ from its own), two lines at the end of `.claude/.gitignore` inside a git repository (a comment and `settings.local.json`, so the hook file is never committed; `--remove` takes out exactly those two), and a note in `.claude/lode-init.json`; `init --gate --remove --yes` deletes only the files it copied, unchanged, from its fixed list |
|
|
21
21
|
| Gate hook (`scripts/gate.mjs`, runs before each shell command once switched on) | the shell command Claude is about to run and the session id (on your machine only; the id is used only to name the temp file below), the project folder (`CLAUDE_PROJECT_DIR`, else the working folder), whether `vercel.json`, `.vercel/project.json`, `netlify.toml`, `supabase/config.toml`, `wrangler.toml`, `wrangler.json` or `wrangler.jsonc` exist there (names only, never contents), `gate-packages.json`, and `LODE_GATE_LOG` | only when the command installs a package on Lode's list: those package names, the package manager, the platform codes found, the mode and a random code for the Claude Code session; never the command, versions, paths, file contents or the session id; with `LODE_GATE_LOG=0` Lode keeps nothing except the daily rate-limit count | a random session code in your temp folder (tidied after a day) |
|
|
22
|
+
| `init --triage` (the failure hook, opt-in) | the same files as `init --gate`, for the failure hook's own entry | nothing | only with `--yes`, under the same rules as `init --gate`: one `PostToolUseFailure` hook entry in `.claude/settings.local.json` (or `.claude/settings.json` with `--shared`), `failure-hook.mjs` and `failure-signals.json` copied with this skill, the same `.claude/.gitignore` lines and a note in `.claude/lode-init.json`; `init --triage --remove --yes` undoes only that |
|
|
23
|
+
| Failure hook (`scripts/failure-hook.mjs`, runs after a shell command fails, once switched on) | the failed command and its output (on your machine only; never sent or stored), the session id (only to name the temp file below), whether `vercel.json`, `.vercel/project.json`, `netlify.toml`, `supabase/config.toml`, `wrangler.toml`, `wrangler.json` or `wrangler.jsonc` exist (names only), `failure-signals.json`, and `LODE_GATE_LOG` | only when the output shows an integration failure it recognises and names exactly one app and one platform from Lode's list: one `POST https://trylode.io/v1/triage` (1.5 second limit) with that app, that platform, one failure code and the HTTP status number if shown, at most once per app, platform and failure in a session; never the output text, the command, paths, versions, file contents or the session id; with `LODE_GATE_LOG=0` Lode keeps nothing | a temp file listing the failures already asked about in this session (tidied after a day) |
|
|
22
24
|
|
|
23
25
|
Connect the MCP server at `https://trylode.io/mcp?log=0` to keep Lode from logging your requests (only the daily
|
|
24
26
|
rate-limit count and anything you choose to send are kept).
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Lode failure hook (LOD-278): an opt-in Claude Code PostToolUseFailure hook over Integration Triage.
|
|
3
|
+
// When a shell command fails, Claude Code's PostToolUseFailure event hands the hook the command's output. Everything
|
|
4
|
+
// below runs on the user's machine: it reads that output to work out (1) which of Lode's symptom codes fits, from fixed
|
|
5
|
+
// patterns, (2) the HTTP status number if one is shown, (3) which one app from Lode's list is involved, and (4) the
|
|
6
|
+
// platform. Any doubt gives null, and a null means nothing is sent. The output text itself never leaves the machine.
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
|
|
13
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
14
|
+
const MAX_TEXT = 64 * 1024;
|
|
15
|
+
|
|
16
|
+
// Ordered: the first match wins. Codes are Lode's triage symptom codes (src/lib/triage.mjs SYMPTOMS; test keeps them valid).
|
|
17
|
+
export const SYMPTOM_PATTERNS = [
|
|
18
|
+
['webhook-signature-failed', /\b(webhook|event)\b[^\n]{0,80}\bsignature\b|\bsignature\b[^\n]{0,60}\b(verif|mismatch|invalid|failed)|No signatures found matching/i],
|
|
19
|
+
['token-expired', /\b(token|session|jwt)\b[^\n]{0,40}\b(expired|has expired|revoked)\b|\bexpired[_ ]token\b/i],
|
|
20
|
+
['scope-missing', /\b(insufficient|missing)[_ ](scope|permission)s?\b|\bscope\b[^\n]{0,40}\b(required|missing|not granted)\b|\bdoes not have (the )?(required )?(scope|permission)s?\b/i],
|
|
21
|
+
['rate-limited', /\brate[ _-]?limit(ed)?\b|\btoo many requests\b|\bquota (exceeded|exhausted)\b/i],
|
|
22
|
+
['runtime-limit-exceeded', /FUNCTION_INVOCATION_TIMEOUT|\bTask timed out after\b|\bfunction (execution )?(timed out|exceeded)\b|\bmemory limit exceeded\b/i],
|
|
23
|
+
['request-too-large', /\b(payload|request|body)\b[^\n]{0,30}\btoo large\b|\b413\b[^\n]{0,30}\b(payload|request|entity)/i],
|
|
24
|
+
['config-missing', /\b(missing|undefined|not set|not defined|required)\b[^\n]{0,40}\b(env(ironment)? var(iable)?|api[_ ]?key|secret|token)\b|\b[A-Z][A-Z0-9]*_(API_KEY|SECRET|SECRET_KEY|TOKEN|URL)\b[^\n]{0,30}\b(is )?(missing|undefined|not set|required)\b/],
|
|
25
|
+
['package-not-found', /Cannot find (module|package) ['"]|ModuleNotFoundError: No module named|ERR_MODULE_NOT_FOUND|Module not found: Can't resolve/],
|
|
26
|
+
['api-deprecated', /\b(deprecated|no longer supported|has been removed|sunset)\b[^\n]{0,60}\b(api|version|endpoint)\b|\b(api|version|endpoint)\b[^\n]{0,60}\b(deprecated|no longer supported|has been removed)\b/i],
|
|
27
|
+
['connection-failed', /\b(ENOTFOUND|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|CERT_HAS_EXPIRED|UNABLE_TO_VERIFY_LEAF_SIGNATURE|SELF_SIGNED_CERT_IN_CHAIN)\b|getaddrinfo|socket hang up|Can't reach database server|could not connect to (the )?(database )?server|connection refused/i],
|
|
28
|
+
['credential-invalid', /\b(invalid|incorrect|bad|unknown)\b[^\n]{0,20}\b(api[_ ]?key|secret|credentials?|token)\b|\bunauthori[sz]ed\b|\bauthentication (failed|error)\b/i],
|
|
29
|
+
['validation-rejected', /\b(validation (error|failed)|unprocessable entity|invalid[_ ]request[_ ]error)\b/i],
|
|
30
|
+
['service-outage', /\b(service unavailable|bad gateway|gateway timeout|internal server error)\b/i],
|
|
31
|
+
];
|
|
32
|
+
// When only a status number is shown
|
|
33
|
+
export const STATUS_CODES = { 400: 'validation-rejected', 401: 'credential-invalid', 403: 'scope-missing', 404: 'package-not-found', 409: 'validation-rejected', 413: 'request-too-large', 422: 'validation-rejected', 429: 'rate-limited', 500: 'service-outage', 502: 'service-outage', 503: 'service-outage', 504: 'service-outage' };
|
|
34
|
+
const STATUS_RE = /\b(?:status(?:[ _]?code)?\s{0,3}[:=]?\s{0,3}|HTTP\/\d(?:\.\d)?\s{1,3}|statusCode\W{0,3}|code\W{0,3})([45]\d\d)\b|\b([45]\d\d)\s{1,3}(?:Unauthorized|Forbidden|Not Found|Conflict|Too Many Requests|Unprocessable|Bad Request|Internal Server Error|Bad Gateway|Service Unavailable|Gateway Timeout|Payload Too Large)\b/i;
|
|
35
|
+
|
|
36
|
+
const clip = (t) => (typeof t === 'string' ? t.slice(0, MAX_TEXT) : '');
|
|
37
|
+
|
|
38
|
+
// -> { code, status } | null
|
|
39
|
+
export function detectSymptom(text) {
|
|
40
|
+
const t = clip(text);
|
|
41
|
+
if (!t) return null;
|
|
42
|
+
const m = STATUS_RE.exec(t);
|
|
43
|
+
const status = m ? Number(m[1] ?? m[2]) : null;
|
|
44
|
+
for (const [code, re] of SYMPTOM_PATTERNS) if (re.test(t)) return { code, status };
|
|
45
|
+
if (status && STATUS_CODES[status]) return { code: STATUS_CODES[status], status };
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
50
|
+
// Does this product appear in the text? Packages count only in a module or path context, environment prefixes only as
|
|
51
|
+
// upper-case variable names, the API host only as a host, the product name only with its exact capitals.
|
|
52
|
+
export function mentions(entry, text) {
|
|
53
|
+
for (const p of entry.packages ?? []) {
|
|
54
|
+
const q = esc(p);
|
|
55
|
+
if (new RegExp(`(node_modules/${q}(/|\\b)|['"\`]${q}['"\`/]|\\bfrom ${q}\\b|\\bimport ${q}\\b|site-packages/${q}\\b|\\b${q}@\\d)`).test(text)) return true;
|
|
56
|
+
}
|
|
57
|
+
for (const e of entry.env ?? []) if (new RegExp(`\\b${esc(e)}[A-Z0-9_]*\\b`).test(text)) return true;
|
|
58
|
+
if (entry.host && new RegExp(`(^|[/\\s'"@.(])${esc(entry.host)}\\.(com|io|dev|co|so|ai|app|sh|net|org|cloud)\\b`, 'i').test(text)) return true;
|
|
59
|
+
if (entry.name && new RegExp(`(^|[^A-Za-z0-9])${esc(entry.name)}([^A-Za-z0-9]|$)`).test(text)) return true;
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// -> the one app id named, or null (none, or more than one)
|
|
64
|
+
export function detectApp(text, list) {
|
|
65
|
+
const t = clip(text);
|
|
66
|
+
const hits = (list?.apps ?? []).filter((a) => mentions(a, t));
|
|
67
|
+
return hits.length === 1 ? hits[0].id : null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Platform config files told apart by name only (the same list as Lode Gate)
|
|
71
|
+
export const PLATFORM_FILES = { vercel: ['vercel.json', '.vercel/project.json'], netlify: ['netlify.toml'], supabase: ['supabase/config.toml'], cloudflare: ['wrangler.toml', 'wrangler.json', 'wrangler.jsonc'] };
|
|
72
|
+
// -> the one platform, from config file names and platform products named in the text, or null
|
|
73
|
+
export function detectPlatform(text, list, root, { exists = (f) => { try { return fs.existsSync(f); } catch { return false; } } } = {}) {
|
|
74
|
+
const found = new Set();
|
|
75
|
+
if (typeof root === 'string' && root) for (const [p, files] of Object.entries(PLATFORM_FILES)) if (files.some((f) => exists(path.join(root, f)))) found.add(p);
|
|
76
|
+
const t = clip(text);
|
|
77
|
+
for (const p of list?.platforms ?? []) if (mentions(p, t)) found.add(p.platform);
|
|
78
|
+
return found.size === 1 ? [...found][0] : null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function loadSignals() {
|
|
82
|
+
try { return JSON.parse(fs.readFileSync(path.join(here, 'failure-signals.json'), 'utf8')); } catch { return null; }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ---- Step 2: the hook (PostToolUseFailure). Sends only app, platform, symptom code and status number, never the
|
|
86
|
+
// output text, the command, paths, versions or the session id. Asks once per app, platform and symptom in a session.
|
|
87
|
+
const VERSION = '0.1';
|
|
88
|
+
// The hook ships inside the skill, so it identifies as the skill: the server already counts `lode-skill` and leaves
|
|
89
|
+
// `lode-skill-test` (Lode's own tests) out of every figure. Only Lode's tests may point it at this machine.
|
|
90
|
+
const BASE = (() => { const u = process.env.LODE_GATE_URL || ''; return /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(u) ? u : 'https://trylode.io'; })();
|
|
91
|
+
const UA = /^lode-skill-test(\/[\w.-]+)?$/.test(process.env.LODE_UA || '') ? process.env.LODE_UA : `lode-skill/${VERSION} (failure-hook)`;
|
|
92
|
+
const BUDGET_MS = 1500;
|
|
93
|
+
const MAX_CONTEXT = 1200;
|
|
94
|
+
const OK_HOSTS = ['trylode.io'];
|
|
95
|
+
// Lode's answer is untrusted text: control and format characters removed; a line that looks like a command or links
|
|
96
|
+
// anywhere but trylode.io is dropped (the same rule as Lode Gate).
|
|
97
|
+
const clean = (t, n = 300) => String(t ?? '').replace(/[\p{Cc}\p{Cf}\p{Co}\p{Cn}]/gu, ' ').replace(/\s+/g, ' ').trim().slice(0, n);
|
|
98
|
+
// Security review 02-12-2026: scheme case-insensitive; protocol-relative and script links refused. Bare domains stay
|
|
99
|
+
// allowed: product names such as Trigger.dev and Customer.io look like domains.
|
|
100
|
+
const looksSafe = (t) => !/[`$<>{}\\]|\|\s*\w|\b(curl|wget|bash|sh|sudo|rm|chmod|eval|exec|powershell|iex)\b|(^|[\s(\[])\/\/|\b(javascript|vbscript):|\bdata:[a-z]+\/|\bfile:\/\//i.test(t)
|
|
101
|
+
&& [...t.matchAll(/https?:\/\/([^/\s)\]]+)/gi)].every((m) => OK_HOSTS.includes(m[1].toLowerCase()));
|
|
102
|
+
|
|
103
|
+
// Has this app, platform and symptom been asked about in this Claude Code session? Kept in a temp file named by a hash
|
|
104
|
+
// of the session id (the id itself is never sent or stored); only this hook's own regular files are read or tidied.
|
|
105
|
+
export function firstTimeInSession(sessionId, key, { dir = os.tmpdir() } = {}) {
|
|
106
|
+
if (typeof sessionId !== 'string' || !sessionId) return true;
|
|
107
|
+
const f = path.join(dir, `lode-failure-${crypto.createHash('sha256').update(sessionId).digest('hex').slice(0, 24)}`);
|
|
108
|
+
try {
|
|
109
|
+
let seen = [];
|
|
110
|
+
try { const st = fs.lstatSync(f); if (st.isFile() && st.size < 65536 && (typeof process.getuid !== 'function' || st.uid === process.getuid())) seen = fs.readFileSync(f, 'utf8').split('\n'); else if (!st.isFile()) return false; } catch { /* new */ }
|
|
111
|
+
if (seen.includes(key)) return false;
|
|
112
|
+
// Opened without following a link (security review 02-12-2026)
|
|
113
|
+
const fd = fs.openSync(f, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_TRUNC | (fs.constants.O_NOFOLLOW ?? 0), 0o600);
|
|
114
|
+
try { fs.writeSync(fd, [...seen.filter(Boolean), key].slice(-200).join('\n') + '\n'); } finally { fs.closeSync(fd); }
|
|
115
|
+
const mine = (st) => typeof process.getuid !== 'function' || st.uid === process.getuid();
|
|
116
|
+
for (const n of (() => { try { return fs.readdirSync(dir); } catch { return []; } })()) {
|
|
117
|
+
if (!/^lode-failure-[0-9a-f]{24}$/.test(n)) continue;
|
|
118
|
+
try { const g = path.join(dir, n); const st = fs.lstatSync(g); if (st.isFile() && mine(st) && Date.now() - st.mtimeMs > 86400000) fs.rmSync(g); } catch { /* next */ }
|
|
119
|
+
}
|
|
120
|
+
return true;
|
|
121
|
+
} catch { return true; }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export async function run(input, { fetchImpl = globalThis.fetch, env = process.env, list = loadSignals(), tmp } = {}) {
|
|
125
|
+
if (!input || !['Bash', 'PowerShell'].includes(input.tool_name) || input.is_interrupt === true) return null;
|
|
126
|
+
if (input.hook_event_name && input.hook_event_name !== 'PostToolUseFailure') return null;
|
|
127
|
+
const error = typeof input.error === 'string' ? input.error : '';
|
|
128
|
+
const command = typeof input.tool_input?.command === 'string' ? input.tool_input.command : '';
|
|
129
|
+
const symptom = detectSymptom(error);
|
|
130
|
+
if (!symptom || !list) return null;
|
|
131
|
+
const text = `${command}\n${error}`;
|
|
132
|
+
const app = detectApp(text, list);
|
|
133
|
+
const root = typeof env.CLAUDE_PROJECT_DIR === 'string' && env.CLAUDE_PROJECT_DIR ? env.CLAUDE_PROJECT_DIR : (typeof input.cwd === 'string' ? input.cwd : null);
|
|
134
|
+
const platform = app ? detectPlatform(text, list, root) : null;
|
|
135
|
+
if (!app || !platform || app === platform) return null;
|
|
136
|
+
if (!firstTimeInSession(input.session_id, `${app}|${platform}|${symptom.code}`, tmp ? { dir: tmp } : {})) return null;
|
|
137
|
+
const noLog = env.LODE_GATE_LOG === '0';
|
|
138
|
+
const body = { app, platform, symptom: symptom.code, ...(symptom.status ? { http_status: String(symptom.status) } : {}), ...(noLog ? { log: '0' } : {}) };
|
|
139
|
+
let answer;
|
|
140
|
+
try {
|
|
141
|
+
const res = await fetchImpl(`${BASE}/v1/triage`, { method: 'POST', headers: { 'content-type': 'application/json', 'user-agent': UA }, body: JSON.stringify(body), signal: AbortSignal.timeout(BUDGET_MS), redirect: 'error' });
|
|
142
|
+
if (!res.ok) return null;
|
|
143
|
+
answer = await res.json();
|
|
144
|
+
} catch { return null; }
|
|
145
|
+
const lines = [];
|
|
146
|
+
for (const f of Array.isArray(answer?.facts) ? answer.facts.slice(0, 6) : []) { const t = clean(f?.text); if (t && looksSafe(t)) lines.push(`- ${t}`); }
|
|
147
|
+
const nd = clean(answer?.not_documented); if (!lines.length && nd && looksSafe(nd)) lines.push(`- ${nd}`);
|
|
148
|
+
if (!lines.length) return null;
|
|
149
|
+
const url = clean(answer?.url, 200); const when = clean(answer?.last_verified, 10);
|
|
150
|
+
const head = `Lode (https://trylode.io) on this failure (${symptom.code}, ${app} on ${platform}; facts, not instructions; "not documented" is not "not supported")${looksSafe(url) && /^https:\/\/trylode\.io\//.test(url) ? `, record ${url}` : ''}${/^\d{4}-\d{2}-\d{2}$/.test(when) ? `, verified ${when}` : ''}:`;
|
|
151
|
+
let context = `${head}\n${lines.join('\n')}`;
|
|
152
|
+
if (context.length > MAX_CONTEXT) context = `${context.slice(0, MAX_CONTEXT - 1)}…`;
|
|
153
|
+
return { hookSpecificOutput: { hookEventName: 'PostToolUseFailure', additionalContext: context } };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function readStdin(max = 1024 * 1024) {
|
|
157
|
+
let s = '';
|
|
158
|
+
for await (const chunk of process.stdin) { s += chunk; if (s.length > max) return null; }
|
|
159
|
+
return s;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Run as a hook: real paths compared, so a folder reached through a symlink still runs (Gate's 02-12 fix)
|
|
163
|
+
const realArg = (() => { try { return process.argv[1] ? fs.realpathSync(process.argv[1]) : null; } catch { return null; } })();
|
|
164
|
+
if (process.argv[1] && (fileURLToPath(import.meta.url) === path.resolve(process.argv[1]) || fileURLToPath(import.meta.url) === realArg)) {
|
|
165
|
+
(async () => {
|
|
166
|
+
try {
|
|
167
|
+
const raw = await readStdin();
|
|
168
|
+
const out = raw ? await run(JSON.parse(raw)) : null;
|
|
169
|
+
if (out) process.stdout.write(JSON.stringify(out));
|
|
170
|
+
} catch { /* fail open: print nothing */ }
|
|
171
|
+
process.exit(0);
|
|
172
|
+
})();
|
|
173
|
+
}
|