@openthread/claude-code-plugin 0.1.4 → 0.1.8

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "ot",
3
- "version": "0.1.4",
4
- "description": "Share Claude Code conversations to OpenThread",
3
+ "version": "0.1.8",
4
+ "description": "Share Claude Code conversations to OpenThread — the StackOverflow for AI agents. One command to publish any session.",
5
5
  "icon": "icon.svg",
6
6
  "author": {
7
7
  "name": "OpenThread"
package/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # @openthread/claude-code-plugin
2
2
 
3
- Share Claude Code conversations to [OpenThread](https://openthread.me) -- a Reddit-like platform for AI conversation threads.
3
+ Share Claude Code conversations to [OpenThread](https://openthread.me) **the StackOverflow for AI agents**. The community platform for the agentic AI era, where developers share, vote on, and discover the best AI conversation threads from Claude, ChatGPT, Gemini, and more.
4
+
5
+ One command. Zero config. Publish any Claude Code session as a post others can learn from.
4
6
 
5
7
  [![npm version](https://img.shields.io/npm/v/@openthread/claude-code-plugin)](https://www.npmjs.com/package/@openthread/claude-code-plugin)
6
8
  [![license](https://img.shields.io/npm/l/@openthread/claude-code-plugin)](https://opensource.org/licenses/MIT)
@@ -25,7 +27,7 @@ Community: Coding with AI
25
27
  Tags: typescript, authentication, debugging
26
28
 
27
29
  Post shared successfully!
28
- View it at: https://openthread.me/post/abc123
30
+ View it at: https://openthread.me/c/coding-with-ai/post/27512cb1
29
31
  ```
30
32
 
31
33
  ## Examples
@@ -51,7 +53,7 @@ Auto-generates title, picks the best community, adds tags, and posts -- no quest
51
53
  ? Tags: typescript, hono, api
52
54
 
53
55
  Post shared successfully!
54
- View it at: https://openthread.me/post/def456
56
+ View it at: https://openthread.me/c/coding-with-ai/post/27512cb1
55
57
  ```
56
58
 
57
59
  ### Share after a long debugging session
@@ -66,13 +68,20 @@ The plugin reads the full conversation, generates a summary, and shares it as a
66
68
 
67
69
  The plugin auto-detects the current Claude Code session file. Works in any project directory -- just run `/ot:share` and it finds the right conversation.
68
70
 
71
+ ## Why OpenThread?
72
+
73
+ OpenThread is the social platform for the agentic AI world — the place where developers share what their AI agents actually built. Think StackOverflow meets Reddit, designed from the ground up for AI conversations. Every post is a full thread (including code, thinking, and tool use) that the community votes on, comments on, and learns from.
74
+
75
+ **This plugin is the one-command bridge from your Claude Code session to that community.**
76
+
69
77
  ## Features
70
78
 
71
- - **One-command sharing** -- run `/ot:share` inside any Claude Code session to publish the conversation to OpenThread.
72
- - **Quick mode** -- `/ot:share <description>` auto-generates a title, selects a community, and posts immediately.
73
- - **Interactive mode** -- `/ot:share` with no arguments prompts you to choose a title, community, and tags.
74
- - **Secure auth** -- PKCE OAuth flow with automatic token refresh. Credentials are stored locally at `~/.config/openthread/`.
75
- - **CLI management** -- `openthread-claude` binary for install, uninstall, status checks, and updates.
79
+ - **One-command sharing** run `/ot:share` inside any Claude Code session to publish the entire conversation to OpenThread.
80
+ - **Quick mode** `/ot:share <description>` auto-generates a title, picks the best-matching community, adds tags, and posts immediately. Zero questions asked.
81
+ - **Interactive mode** `/ot:share` with no arguments prompts you to choose a title, community, and tags.
82
+ - **Privacy first** strips usernames and local file paths before publishing. Your code, not your filesystem.
83
+ - **Secure auth** PKCE OAuth flow with automatic token refresh. Credentials stored locally at `~/.config/openthread/`.
84
+ - **CLI management** — `openthread-claude` binary for install, uninstall, status checks, and updates.
76
85
 
77
86
  ## Usage
78
87
 
@@ -96,23 +105,108 @@ Run with no arguments to step through each field:
96
105
  2. Community (selectable from list)
97
106
  3. Tags (suggested, accept or modify)
98
107
 
108
+ ## Commands
109
+
110
+ ### `/ot:search <query>`
111
+
112
+ Search OpenThread for threads, comments, communities, or users without
113
+ leaving your Claude Code session.
114
+
115
+ Flags:
116
+
117
+ - `--type posts|comments|communities|users|all` (default `posts`)
118
+ - `--community <name>`
119
+ - `--provider claude|chatgpt|gemini|...`
120
+ - `--time hour|day|week|month|year|all`
121
+ - `--limit 1-25` (default `10`)
122
+
123
+ Works without authentication (narrower visibility). If you're logged in,
124
+ you also see private communities you're a member of. After results are
125
+ shown, pick a number to import the thread via `/ot:import`.
126
+
127
+ ```
128
+ > /ot:search hono auth bug
129
+
130
+ [1] Debugging PKCE token refresh in auth middleware
131
+ c/coding-with-ai · u/alice · 3h ago · ▲ 42 · 💬 7
132
+ Walks through the PKCE refresh flow and the off-by-one in expiresAt...
133
+ ```
134
+
135
+ ### `/ot:import <post-id-or-url> [--read|--context]`
136
+
137
+ Pull a published OpenThread thread into your current workspace.
138
+
139
+ **Imported content is UNTRUSTED third-party data.** It may contain
140
+ prompt injections. The plugin treats every imported byte as data, not
141
+ instructions, and enforces that boundary at multiple layers.
142
+
143
+ - **`--read`** (default) — downloads the thread, sanitizes and masks
144
+ it locally (defense-in-depth on top of server-side masking), and
145
+ saves it to `~/.openthread/imports/<uuid>.md` with mode `0600`
146
+ inside a `0700` directory. Claude does **not** automatically load
147
+ the file into context. If you want it read, ask in a separate
148
+ message after the import completes.
149
+ - **`--context`** — additionally emits an
150
+ `<imported_thread trust="untrusted">` envelope that the skill shows
151
+ to Claude after you explicitly confirm. Even inside the envelope,
152
+ the content is treated as data, never as instructions.
153
+
154
+ Inputs accepted:
155
+
156
+ - Bare UUID: `27512cb1-4e7a-4c3b-9d8e-1f2a3b4c5d6e`
157
+ - Path: `/c/<community>/post/<uuid>` or `/post/<uuid>`
158
+ - Full URL: `https://openthread.me/c/<community>/post/<uuid>`
159
+
160
+ Security properties:
161
+
162
+ - Strict UUID validation on every input form.
163
+ - HTTPS enforced unless `OPENTHREAD_API_URL` points to a loopback host.
164
+ - Response bodies capped at 5 MB, read in bounded chunks.
165
+ - Control characters and ANSI escapes are stripped; paths, usernames,
166
+ secrets, emails, and IPs are masked locally.
167
+ - Writes are atomic via a `.part` rename — a partial fetch never lands
168
+ at the final path. Files land at mode `0600` in a `0700` directory.
169
+ - Every saved file starts with a trust banner reminding Claude that
170
+ the content is data, not instructions.
171
+
172
+ ### `/ot:export <post-id-or-url>`
173
+
174
+ Download a thread from OpenThread as a local file. Unlike `/ot:import`,
175
+ this is for archival / sharing — the file is written with sharable
176
+ permissions and does NOT include the "untrusted data" banner.
177
+
178
+ Flags:
179
+
180
+ - `--format markdown|text|json` (default `markdown`)
181
+ - `--out <path>` (default `./ot-<slug>-<short>.<ext>`)
182
+ - `--stdout`
183
+ - `--no-banner`
184
+
185
+ The file is path-traversal-guarded (relative paths must stay under cwd;
186
+ absolute paths are denied into system dirs). Content is re-masked
187
+ locally on top of the server's masking as defense-in-depth. Writes are
188
+ atomic via a `.part` rename and land at mode `0644` so the file can be
189
+ committed or shared. Exported files are NOT loaded into Claude's
190
+ context — if you want Claude to read one, open it in a follow-up
191
+ message.
192
+
99
193
  ## CLI Commands
100
194
 
101
- | Command | Description |
102
- | --- | --- |
103
- | `openthread-claude install` | Install and register the plugin with Claude Code |
195
+ | Command | Description |
196
+ | ----------------------------- | ------------------------------------------------- |
197
+ | `openthread-claude install` | Install and register the plugin with Claude Code |
104
198
  | `openthread-claude uninstall` | Remove the plugin and deregister from Claude Code |
105
- | `openthread-claude status` | Show plugin installation and registration state |
106
- | `openthread-claude update` | Reinstall plugin (update to current version) |
199
+ | `openthread-claude status` | Show plugin installation and registration state |
200
+ | `openthread-claude update` | Reinstall plugin (update to current version) |
107
201
 
108
202
  ## Configuration
109
203
 
110
204
  Environment variables override the default endpoints. Set them in your shell profile or `.env` file.
111
205
 
112
- | Variable | Default | Description |
113
- | --- | --- | --- |
114
- | `OPENTHREAD_API_URL` | `https://openthread.me/api` | Backend API base URL |
115
- | `OPENTHREAD_WEB_URL` | `https://openthread.me` | Web app base URL (used for post links) |
206
+ | Variable | Default | Description |
207
+ | -------------------- | --------------------------- | -------------------------------------- |
208
+ | `OPENTHREAD_API_URL` | `https://openthread.me/api` | Backend API base URL |
209
+ | `OPENTHREAD_WEB_URL` | `https://openthread.me` | Web app base URL (used for post links) |
116
210
 
117
211
  ## Manual Install
118
212
 
@@ -0,0 +1,122 @@
1
+ #!/usr/bin/env node
2
+ // Unit tests for bin/lib/settings-writer.js
3
+ // Run with: node bin/__tests__/settings-writer.test.js
4
+ // Exit 0 on pass, non-zero on failure.
5
+
6
+ const fs = require("node:fs");
7
+ const os = require("node:os");
8
+ const path = require("node:path");
9
+ const assert = require("node:assert/strict");
10
+
11
+ const { safeUpdateSettings } = require("../lib/settings-writer.js");
12
+
13
+ let failures = 0;
14
+ let passed = 0;
15
+
16
+ function test(name, fn) {
17
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "ot-settings-test-"));
18
+ const tmpFile = path.join(tmpDir, "settings.json");
19
+ try {
20
+ fn(tmpFile);
21
+ console.log(` ok ${name}`);
22
+ passed++;
23
+ } catch (e) {
24
+ console.error(` FAIL ${name}`);
25
+ console.error(" " + (e.stack || e.message));
26
+ failures++;
27
+ } finally {
28
+ try {
29
+ fs.rmSync(tmpDir, { recursive: true, force: true });
30
+ } catch {
31
+ /* ignore */
32
+ }
33
+ }
34
+ }
35
+
36
+ console.log("settings-writer tests:");
37
+
38
+ test("enables ot@openthread on empty file", (file) => {
39
+ const result = safeUpdateSettings(
40
+ { enabledPlugins: { "ot@openthread": true } },
41
+ file,
42
+ );
43
+ assert.equal(result.enabledPlugins["ot@openthread"], true);
44
+ const onDisk = JSON.parse(fs.readFileSync(file, "utf8"));
45
+ assert.equal(onDisk.enabledPlugins["ot@openthread"], true);
46
+ });
47
+
48
+ test("refuses to modify hooks", (file) => {
49
+ assert.throws(
50
+ () =>
51
+ safeUpdateSettings(
52
+ { hooks: { preToolUse: "evil" } },
53
+ file,
54
+ ),
55
+ /refusing to modify top-level key "hooks"/,
56
+ );
57
+ assert.equal(fs.existsSync(file), false);
58
+ });
59
+
60
+ test("refuses to modify permissions", (file) => {
61
+ assert.throws(
62
+ () => safeUpdateSettings({ permissions: { allow: ["*"] } }, file),
63
+ /refusing to modify top-level key "permissions"/,
64
+ );
65
+ });
66
+
67
+ test("refuses unknown plugin keys", (file) => {
68
+ assert.throws(
69
+ () =>
70
+ safeUpdateSettings(
71
+ { enabledPlugins: { "other@thing": true } },
72
+ file,
73
+ ),
74
+ /refusing to modify plugin key "other@thing"/,
75
+ );
76
+ });
77
+
78
+ test("refuses unknown top-level keys", (file) => {
79
+ assert.throws(
80
+ () => safeUpdateSettings({ unknownKey: "x" }, file),
81
+ /refusing to modify top-level key "unknownKey"/,
82
+ );
83
+ });
84
+
85
+ test("preserves unrelated keys on update", (file) => {
86
+ fs.writeFileSync(
87
+ file,
88
+ JSON.stringify({
89
+ permissions: { allow: ["Bash"] },
90
+ hooks: { preToolUse: "existing" },
91
+ enabledPlugins: { "some@other": true },
92
+ }),
93
+ );
94
+ const result = safeUpdateSettings(
95
+ { enabledPlugins: { "ot@openthread": true } },
96
+ file,
97
+ );
98
+ assert.deepEqual(result.permissions, { allow: ["Bash"] });
99
+ assert.deepEqual(result.hooks, { preToolUse: "existing" });
100
+ assert.equal(result.enabledPlugins["some@other"], true);
101
+ assert.equal(result.enabledPlugins["ot@openthread"], true);
102
+ });
103
+
104
+ test("disables ot@openthread", (file) => {
105
+ const result = safeUpdateSettings(
106
+ { enabledPlugins: { "ot@openthread": false } },
107
+ file,
108
+ );
109
+ assert.equal(result.enabledPlugins["ot@openthread"], false);
110
+ });
111
+
112
+ test("replaces non-object enabledPlugins safely", (file) => {
113
+ fs.writeFileSync(file, JSON.stringify({ enabledPlugins: ["bogus"] }));
114
+ const result = safeUpdateSettings(
115
+ { enabledPlugins: { "ot@openthread": true } },
116
+ file,
117
+ );
118
+ assert.equal(result.enabledPlugins["ot@openthread"], true);
119
+ });
120
+
121
+ console.log(`\n${passed} passed, ${failures} failed`);
122
+ process.exit(failures > 0 ? 1 : 0);
package/bin/cli.sh CHANGED
@@ -2,12 +2,13 @@
2
2
  # CLI for managing the OpenThread Claude Code plugin
3
3
  set -euo pipefail
4
4
 
5
- PLUGIN_NAME="openthread-share"
6
5
  PLUGIN_ID="ot"
7
- MARKETPLACE_NAME="local-plugins"
6
+ MARKETPLACE_NAME="openthread"
8
7
  PLUGIN_KEY="${PLUGIN_ID}@${MARKETPLACE_NAME}"
9
8
  PLUGIN_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
10
- DEST_DIR="$HOME/.claude/plugins/$PLUGIN_NAME"
9
+ MARKETPLACE_DIR="$HOME/.claude/plugins/marketplaces/$MARKETPLACE_NAME"
10
+ DEST_DIR="$MARKETPLACE_DIR/plugins/$PLUGIN_ID"
11
+ KNOWN_FILE="$HOME/.claude/plugins/known_marketplaces.json"
11
12
  SETTINGS_FILE="$HOME/.claude/settings.json"
12
13
 
13
14
  usage() {
@@ -20,132 +21,106 @@ usage() {
20
21
  echo " update Reinstall plugin (update to current version)"
21
22
  }
22
23
 
23
- register_plugin() {
24
- python3 -c "
25
- import json, os
26
-
27
- settings_path = '$SETTINGS_FILE'
28
- dest_dir = '$DEST_DIR'
29
- marketplace = '$MARKETPLACE_NAME'
30
- plugin_key = '$PLUGIN_KEY'
31
-
32
- settings = {}
33
- if os.path.exists(settings_path):
34
- try:
35
- with open(settings_path) as f:
36
- settings = json.load(f)
37
- except:
38
- settings = {}
39
-
40
- # Register as local marketplace
41
- if 'extraKnownMarketplaces' not in settings:
42
- settings['extraKnownMarketplaces'] = {}
43
- settings['extraKnownMarketplaces'][marketplace] = {
44
- 'source': {'source': 'directory', 'path': dest_dir}
45
- }
46
-
47
- # Enable the plugin (must be an object, not array)
48
- if not isinstance(settings.get('enabledPlugins'), dict):
49
- settings['enabledPlugins'] = {}
50
- settings['enabledPlugins'][plugin_key] = True
51
-
52
- os.makedirs(os.path.dirname(settings_path), exist_ok=True)
53
- with open(settings_path, 'w') as f:
54
- json.dump(settings, f, indent=2)
55
- f.write('\n')
56
- "
57
- }
58
-
59
- deregister_plugin() {
60
- if [ -f "$SETTINGS_FILE" ]; then
61
- python3 -c "
62
- import json
63
-
64
- settings_path = '$SETTINGS_FILE'
65
- marketplace = '$MARKETPLACE_NAME'
66
- plugin_key = '$PLUGIN_KEY'
67
-
68
- with open(settings_path) as f:
69
- settings = json.load(f)
70
-
71
- # Remove from enabledPlugins
72
- if isinstance(settings.get('enabledPlugins'), dict):
73
- settings['enabledPlugins'].pop(plugin_key, None)
74
-
75
- # Remove marketplace
76
- if isinstance(settings.get('extraKnownMarketplaces'), dict):
77
- settings['extraKnownMarketplaces'].pop(marketplace, None)
78
-
79
- with open(settings_path, 'w') as f:
80
- json.dump(settings, f, indent=2)
81
- f.write('\n')
82
- "
83
- fi
84
- }
85
-
86
24
  install_plugin() {
25
+ # Copy plugin files into marketplace structure
87
26
  mkdir -p "$DEST_DIR"
88
-
89
27
  for dir in .claude-plugin commands skills scripts; do
90
28
  if [ -d "$PLUGIN_DIR/$dir" ]; then
91
29
  cp -r "$PLUGIN_DIR/$dir" "$DEST_DIR/"
92
30
  fi
93
31
  done
32
+ [ -f "$PLUGIN_DIR/icon.svg" ] && cp "$PLUGIN_DIR/icon.svg" "$DEST_DIR/"
33
+ chmod +x "$DEST_DIR/scripts/"*.sh 2>/dev/null || true
94
34
 
95
- if [ -f "$PLUGIN_DIR/icon.svg" ]; then
96
- cp "$PLUGIN_DIR/icon.svg" "$DEST_DIR/"
97
- fi
35
+ # Create marketplace.json
36
+ mkdir -p "$MARKETPLACE_DIR/.claude-plugin"
37
+ python3 -c "
38
+ import json
39
+ mkt = {
40
+ 'name': '$MARKETPLACE_NAME',
41
+ 'description': 'OpenThread plugins for sharing AI conversations',
42
+ 'owner': {'name': 'OpenThread'},
43
+ 'plugins': [{'name': '$PLUGIN_ID', 'description': 'Share Claude Code conversations to OpenThread', 'source': './plugins/$PLUGIN_ID'}]
44
+ }
45
+ with open('$MARKETPLACE_DIR/.claude-plugin/marketplace.json', 'w') as f:
46
+ json.dump(mkt, f, indent=2)
47
+ f.write('\n')
48
+ "
98
49
 
99
- chmod +x "$DEST_DIR/scripts/"*.sh 2>/dev/null || true
50
+ # Register in known_marketplaces.json
51
+ python3 -c "
52
+ import json, os, datetime
53
+ path = '$KNOWN_FILE'
54
+ known = {}
55
+ if os.path.exists(path):
56
+ try:
57
+ with open(path) as f: known = json.load(f)
58
+ except: pass
59
+ known['$MARKETPLACE_NAME'] = {
60
+ 'source': {'source': 'local', 'path': '$MARKETPLACE_DIR'},
61
+ 'installLocation': '$MARKETPLACE_DIR',
62
+ 'lastUpdated': datetime.datetime.utcnow().isoformat() + 'Z'
63
+ }
64
+ with open(path, 'w') as f:
65
+ json.dump(known, f, indent=2)
66
+ f.write('\n')
67
+ "
100
68
 
101
- register_plugin
69
+ # Enable in settings.json via the guarded writer (G16).
70
+ # Only enabledPlugins["ot@openthread"] is permitted to change.
71
+ node "$PLUGIN_DIR/bin/lib/settings-writer.js" enable
102
72
 
103
73
  VERSION=$(python3 -c "import json; print(json.load(open('$DEST_DIR/.claude-plugin/plugin.json'))['version'])")
104
- echo "✓ OpenThread plugin v$VERSION installed to $DEST_DIR"
105
- echo " Registered in $SETTINGS_FILE"
74
+ echo "✓ OpenThread plugin v$VERSION installed"
75
+ echo " Marketplace: $MARKETPLACE_DIR"
106
76
  echo " Restart Claude Code, then use /ot:share to share conversations."
107
77
  }
108
78
 
109
79
  uninstall_plugin() {
110
- if [ -d "$DEST_DIR" ]; then
111
- rm -rf "$DEST_DIR"
112
- deregister_plugin
113
- echo " OpenThread plugin removed and deregistered"
114
- else
115
- echo "Plugin is not installed."
116
- fi
80
+ [ -d "$MARKETPLACE_DIR" ] && rm -rf "$MARKETPLACE_DIR"
81
+
82
+ # Remove from known_marketplaces.json
83
+ [ -f "$KNOWN_FILE" ] && python3 -c "
84
+ import json
85
+ with open('$KNOWN_FILE') as f: known = json.load(f)
86
+ known.pop('$MARKETPLACE_NAME', None)
87
+ with open('$KNOWN_FILE', 'w') as f:
88
+ json.dump(known, f, indent=2)
89
+ f.write('\n')
90
+ " 2>/dev/null || true
91
+
92
+ # Disable in settings.json via the guarded writer (G16).
93
+ [ -f "$SETTINGS_FILE" ] && node "$PLUGIN_DIR/bin/lib/settings-writer.js" disable 2>/dev/null || true
94
+
95
+ echo "✓ OpenThread plugin removed and deregistered"
117
96
  }
118
97
 
119
98
  check_status() {
120
- local installed=false
121
- local registered=false
122
-
123
99
  if [ -d "$DEST_DIR" ] && [ -f "$DEST_DIR/.claude-plugin/plugin.json" ]; then
124
- installed=true
100
+ VERSION=$(python3 -c "import json; print(json.load(open('$DEST_DIR/.claude-plugin/plugin.json'))['version'])")
101
+ echo "✓ Plugin: v$VERSION at $DEST_DIR"
102
+ else
103
+ echo "✗ Plugin: not installed"
125
104
  fi
126
105
 
127
- if [ -f "$SETTINGS_FILE" ]; then
128
- registered=$(python3 -c "
106
+ if [ -f "$KNOWN_FILE" ] && python3 -c "
129
107
  import json
130
- with open('$SETTINGS_FILE') as f:
131
- s = json.load(f)
132
- plugins = s.get('enabledPlugins', {})
133
- print('true' if isinstance(plugins, dict) and plugins.get('$PLUGIN_KEY') else 'false')
134
- " 2>/dev/null || echo "false")
135
- fi
136
-
137
- if [ "$installed" = true ]; then
138
- VERSION=$(python3 -c "import json; print(json.load(open('$DEST_DIR/.claude-plugin/plugin.json'))['version'])")
139
- echo "✓ Plugin files: v$VERSION at $DEST_DIR"
108
+ with open('$KNOWN_FILE') as f: k = json.load(f)
109
+ exit(0 if '$MARKETPLACE_NAME' in k else 1)
110
+ " 2>/dev/null; then
111
+ echo "✓ Marketplace: registered"
140
112
  else
141
- echo "✗ Plugin files: not installed"
113
+ echo "✗ Marketplace: not registered"
142
114
  fi
143
115
 
144
- if [ "$registered" = "true" ]; then
145
- echo "✓ Registered: yes ($PLUGIN_KEY in $SETTINGS_FILE)"
116
+ if [ -f "$SETTINGS_FILE" ] && python3 -c "
117
+ import json
118
+ with open('$SETTINGS_FILE') as f: s = json.load(f)
119
+ exit(0 if isinstance(s.get('enabledPlugins'), dict) and s['enabledPlugins'].get('$PLUGIN_KEY') else 1)
120
+ " 2>/dev/null; then
121
+ echo "✓ Enabled: $PLUGIN_KEY"
146
122
  else
147
- echo "✗ Registered: no (Claude Code won't detect the plugin)"
148
- echo " Run: openthread-claude install"
123
+ echo "✗ Enabled: no"
149
124
  fi
150
125
  }
151
126
 
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env node
2
+ // Guarded writer for ~/.claude/settings.json.
3
+ //
4
+ // Only allows modifications to a strict allowlist of top-level keys. Refuses
5
+ // any diff touching "hooks", "permissions", or unknown keys so that a
6
+ // compromised release cannot inject a preToolUse hook or weaken permissions.
7
+
8
+ const fs = require("node:fs");
9
+ const path = require("node:path");
10
+ const os = require("node:os");
11
+
12
+ const SETTINGS_PATH = path.join(os.homedir(), ".claude", "settings.json");
13
+
14
+ const ALLOWED_TOP_LEVEL_KEYS = new Set(["enabledPlugins"]);
15
+ const ALLOWED_PLUGIN_KEYS = /^ot@openthread$/;
16
+
17
+ function readSettings(settingsPath = SETTINGS_PATH) {
18
+ try {
19
+ return JSON.parse(fs.readFileSync(settingsPath, "utf8"));
20
+ } catch (e) {
21
+ if (e.code === "ENOENT") return {};
22
+ throw e;
23
+ }
24
+ }
25
+
26
+ function writeAtomically(data, settingsPath = SETTINGS_PATH) {
27
+ const tmp = settingsPath + ".part";
28
+ fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
29
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n", { mode: 0o600 });
30
+ fs.renameSync(tmp, settingsPath);
31
+ }
32
+
33
+ function safeUpdateSettings(patch, settingsPath = SETTINGS_PATH) {
34
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) {
35
+ throw new Error("settings-writer: patch must be a plain object");
36
+ }
37
+
38
+ const current = readSettings(settingsPath);
39
+ const next = JSON.parse(JSON.stringify(current));
40
+
41
+ for (const key of Object.keys(patch)) {
42
+ if (!ALLOWED_TOP_LEVEL_KEYS.has(key)) {
43
+ throw new Error(
44
+ `settings-writer: refusing to modify top-level key "${key}"`,
45
+ );
46
+ }
47
+ }
48
+
49
+ // enabledPlugins merge (only ot@openthread keys allowed)
50
+ if (patch.enabledPlugins !== undefined) {
51
+ if (
52
+ !patch.enabledPlugins ||
53
+ typeof patch.enabledPlugins !== "object" ||
54
+ Array.isArray(patch.enabledPlugins)
55
+ ) {
56
+ throw new Error(
57
+ "settings-writer: enabledPlugins patch must be a plain object",
58
+ );
59
+ }
60
+ if (
61
+ !next.enabledPlugins ||
62
+ typeof next.enabledPlugins !== "object" ||
63
+ Array.isArray(next.enabledPlugins)
64
+ ) {
65
+ next.enabledPlugins = {};
66
+ }
67
+ for (const pluginKey of Object.keys(patch.enabledPlugins)) {
68
+ if (!ALLOWED_PLUGIN_KEYS.test(pluginKey)) {
69
+ throw new Error(
70
+ `settings-writer: refusing to modify plugin key "${pluginKey}"`,
71
+ );
72
+ }
73
+ next.enabledPlugins[pluginKey] = patch.enabledPlugins[pluginKey];
74
+ }
75
+ }
76
+
77
+ writeAtomically(next, settingsPath);
78
+ return next;
79
+ }
80
+
81
+ // CLI entry point: node settings-writer.js enable | disable
82
+ if (require.main === module) {
83
+ const cmd = process.argv[2];
84
+ try {
85
+ if (cmd === "enable") {
86
+ safeUpdateSettings({ enabledPlugins: { "ot@openthread": true } });
87
+ console.log("enabled ot@openthread in", SETTINGS_PATH);
88
+ } else if (cmd === "disable") {
89
+ safeUpdateSettings({ enabledPlugins: { "ot@openthread": false } });
90
+ console.log("disabled ot@openthread in", SETTINGS_PATH);
91
+ } else {
92
+ console.error("Usage: settings-writer.js enable|disable");
93
+ process.exit(1);
94
+ }
95
+ } catch (e) {
96
+ console.error(e.message);
97
+ process.exit(1);
98
+ }
99
+ }
100
+
101
+ module.exports = {
102
+ safeUpdateSettings,
103
+ readSettings,
104
+ writeAtomically,
105
+ SETTINGS_PATH,
106
+ ALLOWED_TOP_LEVEL_KEYS,
107
+ ALLOWED_PLUGIN_KEYS,
108
+ };