Skip to content

Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.

style: format all files with new prettier config

auroracapital318dab18c6ef
diff --git a/claude-ops/agents/monitor-agent.md b/claude-ops/agents/monitor-agent.md
new file mode 100644
index 00000000..c6754999
--- /dev/null
+++ b/claude-ops/agents/monitor-agent.md
@@ -0,0 +1,170 @@
+---
+name: monitor-agent
+description: Lightweight APM and metrics probe agent. Queries Datadog, New Relic, and OpenTelemetry backends for active alerts, error traces, and entity health. Returns structured JSON. Read-only — used by ops-monitor skill.
+model: claude-haiku-4-5
+effort: low
+maxTurns: 15
+tools:
+ - Bash
+ - Read
+disallowedTools:
+ - Write
+ - Edit
+ - Agent
+memory: project
+initialPrompt: "Probe all configured monitoring backends (Datadog, New Relic, OTEL). Return structured JSON with per-service health, open alerts, error traces. Read-only only."
+---
+
+# MONITOR AGENT
+
+Probe all configured APM and monitoring backends and return structured health data. Read-only only. Never write files or call any mutating API verb.
+
+## Preflight
+
+Read credentials from preferences.json:
+
+```bash
+PREFS="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json"
+
+DD_API_KEY=$(jq -r '.datadog_api_key // empty' "$PREFS" 2>/dev/null)
+DD_APP_KEY=$(jq -r '.datadog_app_key // empty' "$PREFS" 2>/dev/null)
+NR_API_KEY=$(jq -r '.newrelic_api_key // empty' "$PREFS" 2>/dev/null)
+NR_ACCOUNT=$(jq -r '.newrelic_account_id // empty' "$PREFS" 2>/dev/null)
+OTEL_ENDPOINT=$(jq -r '.otel_endpoint // empty' "$PREFS" 2>/dev/null)
+```
+
+## Datadog checks
+
+Run only when `DD_API_KEY` is non-empty:
+
+```bash
+if [ -n "$DD_API_KEY" ] && [ -n "$DD_APP_KEY" ]; then
+ # Active monitors in Alert or Warn state
+ DD_ALERTS=$(curl -sf \
+ -H "DD-API-KEY: ${DD_API_KEY}" \
+ -H "DD-APPLICATION-KEY: ${DD_APP_KEY}" \
+ "https://api.datadoghq.com/api/v1/monitor?monitor_tags=*&with_downtimes=false" \
+ 2>/dev/null | jq '[.[] | select(.overall_state == "Alert" or .overall_state == "Warn") | {id:.id, name:.name, state:.overall_state, tags:.tags}]') || DD_ALERTS='[]'
+
+ # Top 5 APM error traces (last 1 hour)
+ DD_ERRORS=$(curl -sf \
+ -H "DD-API-KEY: ${DD_API_KEY}" \
+ -H "DD-APPLICATION-KEY: ${DD_APP_KEY}" \
+ "https://api.datadoghq.com/api/v2/apm/traces?filter[status]=error&page[limit]=5" \
+ 2>/dev/null | jq '[.data[]? | {service:.attributes.service, resource:.attributes.resource_name, error:.attributes.error_message}]') || DD_ERRORS='[]'
+
+ DD_CONFIGURED=true
+else
+ DD_ALERTS='[]'
+ DD_ERRORS='[]'
+ DD_CONFIGURED=false
+fi
+```
+
+## New Relic checks
+
+Run only when `NR_API_KEY` is non-empty:
+
+```bash
+if [ -n "$NR_API_KEY" ]; then
+ NR_HEALTH=$(curl -sf \
+ -H "Api-Key: ${NR_API_KEY}" \
+ -H "Content-Type: application/json" \
+ -d '{"query":"{ actor { entitySearch(queryBuilder: {alertSeverity: CRITICAL}) { results { entities { name alertSeverity entityType } } } } }"}' \
+ "https://api.newrelic.com/graphql" \
+ 2>/dev/null | jq '.data.actor.entitySearch.results.entities[:10]') || NR_HEALTH='[]'
+
+ NR_CONFIGURED=true
+else
+ NR_HEALTH='[]'
+ NR_CONFIGURED=false
+fi
+```
+
+## OTEL check
+
+Run only when `OTEL_ENDPOINT` is non-empty:
+
+```bash
+if [ -n "$OTEL_ENDPOINT" ]; then
+ OTEL_STATUS=$(curl -sf "${OTEL_ENDPOINT}/healthz" 2>/dev/null | jq -r '.status // "unknown"') || OTEL_STATUS="unreachable"
+ OTEL_CONFIGURED=true
+else
+ OTEL_STATUS="not_configured"
+ OTEL_CONFIGURED=false
+fi
+```
+
+## Output
+
+Emit structured JSON to stdout. No other output.
+
+```json
+{
+ "datadog": {
+ "configured": "<bool>",
+ "alerts": "<array from DD_ALERTS>",
+ "top_errors": "<array from DD_ERRORS>",
+ "alert_count": "<length of alerts array>"
+ },
+ "newrelic": {
+ "configured": "<bool>",
+ "critical_entities": "<array from NR_HEALTH>",
+ "open_violations": "<length of NR_HEALTH>"
+ },
+ "otel": {
+ "configured": "<bool>",
+ "endpoint": "<OTEL_ENDPOINT or empty>",
+ "status": "<healthy|unhealthy|unreachable|not_configured>"
+ },
+ "summary": {
+ "total_alerts": "<dd alert_count + nr open_violations>",
+ "severity": "<critical if any critical, warning if any warn, healthy if all clear>",
+ "backends_configured": "<array of configured backend names>"
+ }
+}
+```
+
+Construct and print via `jq -n`:
+
+```bash
+jq -n \
+ --argjson dd_alerts "${DD_ALERTS}" \
+ --argjson dd_errors "${DD_ERRORS}" \
+ --argjson nr_health "${NR_HEALTH}" \
+ --arg otel_status "${OTEL_STATUS}" \
+ --arg otel_endpoint "${OTEL_ENDPOINT}" \
+ --argjson dd_configured "${DD_CONFIGURED}" \
+ --argjson nr_configured "${NR_CONFIGURED}" \
+ --argjson otel_configured "${OTEL_CONFIGURED}" \
+ '{
+ datadog: {
+ configured: $dd_configured,
+ alerts: $dd_alerts,
+ top_errors: $dd_errors,
+ alert_count: ($dd_alerts | length)
+ },
+ newrelic: {
+ configured: $nr_configured,
+ critical_entities: $nr_health,
+ open_violations: ($nr_health | length)
+ },
+ otel: {
+ configured: $otel_configured,
+ endpoint: $otel_endpoint,
+ status: $otel_status
+ },
+ summary: {
+ total_alerts: (($dd_alerts | length) + ($nr_health | length)),
+ severity: (if (($dd_alerts | map(select(.state == "Alert")) | length) > 0) or ($nr_health | length) > 0 then "critical" elif ($dd_alerts | length) > 0 then "warning" else "healthy" end),
+ backends_configured: ([if $dd_configured then "datadog" else empty end, if $nr_configured then "newrelic" else empty end, if $otel_configured then "otel" else empty end])
+ }
+ }'
+```
+
+## Rules
+
+- Read-only — never run any mutating API call.
+- Keys passed as `-H` headers only — never embed in URLs or log to stdout beyond what JSON requires.
+- Graceful degradation — a backend that fails or returns an error contributes empty arrays; it never crashes the scan.
+- Print only the JSON to stdout.
diff --git a/claude-ops/bin/ops-slack-autolink.mjs b/claude-ops/bin/ops-slack-autolink.mjs
index 04915fef..bdd1a89d 100755
--- a/claude-ops/bin/ops-slack-autolink.mjs
+++ b/claude-ops/bin/ops-slack-autolink.mjs
@@ -28,48 +28,42 @@
* {"xoxc_token": "xoxc-...", "xoxd_token": "xoxd-...", "team_id": "T...", "source": "scout|playwright"}
*/
-import { existsSync, readFileSync, mkdirSync } from "node:fs";
-import { homedir, userInfo } from "node:os";
-import { join, basename } from "node:path";
-import { parseArgs } from "node:util";
-import { execSync } from "node:child_process";
-import { osId, isWsl, browserProfileDirs } from "../lib/os-detect.mjs";
-import {
- setCredential,
- getCredential,
- deleteCredential,
- backendsAvailable,
-} from "../lib/credential-store.mjs";
+import { existsSync, readFileSync, mkdirSync } from 'node:fs';
+import { homedir, userInfo } from 'node:os';
+import { join, basename } from 'node:path';
+import { parseArgs } from 'node:util';
+import { execSync } from 'node:child_process';
+import { osId, isWsl, browserProfileDirs } from '../lib/os-detect.mjs';
+import { setCredential, getCredential, deleteCredential, backendsAvailable } from '../lib/credential-store.mjs';
const OS_ID = osId();
const IS_WSL = isWsl();
-const USER_ACCOUNT =
- userInfo().username || process.env.USER || process.env.USERNAME || "default";
+const USER_ACCOUNT = userInfo().username || process.env.USER || process.env.USERNAME || 'default';
const { values } = parseArgs({
options: {
- workspace: { type: "string", default: "https://app.slack.com/client/" },
- headless: { type: "boolean", default: false },
- "profile-dir": {
- type: "string",
- default: join(homedir(), ".claude-ops", "slack-profile"),
+ workspace: { type: 'string', default: 'https://app.slack.com/client/' },
+ headless: { type: 'boolean', default: false },
+ 'profile-dir': {
+ type: 'string',
+ default: join(homedir(), '.claude-ops', 'slack-profile'),
},
- "ready-file": { type: "string", default: "/tmp/slack-login-done" },
- "scout-only": { type: "boolean", default: false },
+ 'ready-file': { type: 'string', default: '/tmp/slack-login-done' },
+ 'scout-only': { type: 'boolean', default: false },
},
});
const WORKSPACE = values.workspace;
const HEADLESS = values.headless;
-const PROFILE_DIR = values["profile-dir"];
-const READY_FILE = values["ready-file"];
-const SCOUT_ONLY = values["scout-only"];
+const PROFILE_DIR = values['profile-dir'];
+const READY_FILE = values['ready-file'];
+const SCOUT_ONLY = values['scout-only'];
function emit(event) {
- process.stderr.write(JSON.stringify(event) + "\n");
+ process.stderr.write(JSON.stringify(event) + '\n');
}
function die(msg, extra = {}) {
- emit({ type: "error", message: msg, ...extra });
+ emit({ type: 'error', message: msg, ...extra });
process.exit(1);
}
@@ -83,14 +77,10 @@ function validateWorkspaceURL(raw) {
} catch (e) {
die(`--workspace is not a valid URL: ${e.message}`, { raw });
}
- if (u.protocol !== "https:")
- die(`--workspace must use https:// (got ${u.protocol})`, { raw });
+ if (u.protocol !== 'https:') die(`--workspace must use https:// (got ${u.protocol})`, { raw });
const host = u.hostname.toLowerCase();
- if (host !== "slack.com" && !host.endsWith(".slack.com")) {
- die(
- `--workspace hostname must be slack.com or a *.slack.com subdomain (got ${host})`,
- { raw },
- );
+ if (host !== 'slack.com' && !host.endsWith('.slack.com')) {
+ die(`--workspace hostname must be slack.com or a *.slack.com subdomain (got ${host})`, { raw });
}
return u.toString();
}
@@ -98,31 +88,26 @@ const WORKSPACE_VALIDATED = validateWorkspaceURL(WORKSPACE);
// --- Phase 1: scout existing locations for already-extracted tokens ---
emit({
- type: "phase",
+ type: 'phase',
phase: 1,
- message: "Scouting for existing Slack tokens",
+ message: 'Scouting for existing Slack tokens',
});
async function scoutSources() {
const sources = [];
// 1. ~/.claude.json mcpServers.slack.env — where Claude Code stores them
- const claudeJson = join(homedir(), ".claude.json");
+ const claudeJson = join(homedir(), '.claude.json');
if (existsSync(claudeJson)) {
try {
- const parsed = JSON.parse(readFileSync(claudeJson, "utf8"));
+ const parsed = JSON.parse(readFileSync(claudeJson, 'utf8'));
const env = parsed?.mcpServers?.slack?.env;
if (env) {
const xoxc = env.SLACK_MCP_XOXC_TOKEN || env.SLACK_BOT_TOKEN;
const xoxd = env.SLACK_MCP_XOXD_TOKEN;
- if (
- xoxc &&
- xoxc.startsWith("xoxc-") &&
- xoxd &&
- xoxd.startsWith("xoxd-")
- ) {
+ if (xoxc && xoxc.startsWith('xoxc-') && xoxd && xoxd.startsWith('xoxd-')) {
sources.push({
- source: "claude.json:mcpServers.slack",
+ source: 'claude.json:mcpServers.slack',
xoxc_token: xoxc,
xoxd_token: xoxd,
});
@@ -132,12 +117,11 @@ async function scoutSources() {
}
// 2. Shell env (live process)
- const envXoxc =
- process.env.SLACK_MCP_XOXC_TOKEN || process.env.SLACK_BOT_TOKEN;
+ const envXoxc = process.env.SLACK_MCP_XOXC_TOKEN || process.env.SLACK_BOT_TOKEN;
const envXoxd = process.env.SLACK_MCP_XOXD_TOKEN;
- if (envXoxc?.startsWith("xoxc-") && envXoxd?.startsWith("xoxd-")) {
+ if (envXoxc?.startsWith('xoxc-') && envXoxd?.startsWith('xoxd-')) {
sources.push({
- source: "process.env",
+ source: 'process.env',
xoxc_token: envXoxc,
xoxd_token: envXoxd,
});
@@ -147,11 +131,11 @@ async function scoutSources() {
// credential manager — cmdkey on Windows can't read, so it's skipped).
// Items are stored under service=slack-xoxc / slack-xoxd, account=$USER.
try {
- const xoxcHit = await getCredential("slack-xoxc", USER_ACCOUNT);
- const xoxdHit = await getCredential("slack-xoxd", USER_ACCOUNT);
+ const xoxcHit = await getCredential('slack-xoxc', USER_ACCOUNT);
+ const xoxdHit = await getCredential('slack-xoxd', USER_ACCOUNT);
const xoxc = xoxcHit?.secret;
const xoxd = xoxdHit?.secret;
- if (xoxc?.startsWith("xoxc-") && xoxd?.startsWith("xoxd-")) {
+ if (xoxc?.startsWith('xoxc-') && xoxd?.startsWith('xoxd-')) {
sources.push({
source: `credential-store:${xoxcHit.backend}`,
xoxc_token: xoxc,
@@ -162,38 +146,24 @@ async function scoutSources() {
// 4. Shell profile files (OS-aware)
const profiles = [];
- if (OS_ID !== "windows") {
+ if (OS_ID !== 'windows') {
// Unix-style shell profiles (macOS, Linux, WSL)
- profiles.push(
- ...[".zshrc", ".bashrc", ".zprofile", ".envrc"].map((f) =>
- join(homedir(), f),
- ),
- );
+ profiles.push(...['.zshrc', '.bashrc', '.zprofile', '.envrc'].map((f) => join(homedir(), f)));
}
- if (OS_ID === "windows" || IS_WSL) {
+ if (OS_ID === 'windows' || IS_WSL) {
// PowerShell profiles — check common canonical locations.
// $PROFILE on Windows typically resolves to:
// %USERPROFILE%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
// PowerShell 7+ uses the "PowerShell" folder instead of "WindowsPowerShell".
- if (OS_ID === "windows") {
+ if (OS_ID === 'windows') {
const userProfile = process.env.USERPROFILE || homedir();
profiles.push(
- join(
- userProfile,
- "Documents",
- "WindowsPowerShell",
- "Microsoft.PowerShell_profile.ps1",
- ),
- join(
- userProfile,
- "Documents",
- "PowerShell",
- "Microsoft.PowerShell_profile.ps1",
- ),
+ join(userProfile, 'Documents', 'WindowsPowerShell', 'Microsoft.PowerShell_profile.ps1'),
+ join(userProfile, 'Documents', 'PowerShell', 'Microsoft.PowerShell_profile.ps1'),
);
} else if (IS_WSL) {
// Best-effort: check the Windows-side PowerShell profile from /mnt/c.
- const winUser = process.env.USER || process.env.USERNAME || "";
+ const winUser = process.env.USER || process.env.USERNAME || '';
if (winUser) {
profiles.push(
`/mnt/c/Users/${winUser}/Documents/WindowsPowerShell/Microsoft.PowerShell_profile.ps1`,
@@ -205,13 +175,9 @@ async function scoutSources() {
for (const path of profiles) {
if (!existsSync(path)) continue;
try {
- const text = readFileSync(path, "utf8");
- const xoxcMatch = text.match(
- /SLACK(?:_MCP)?_XOXC_TOKEN=["']?(xoxc-[^"'\s]+)/,
- );
- const xoxdMatch = text.match(
- /SLACK(?:_MCP)?_XOXD_TOKEN=["']?(xoxd-[^"'\s]+)/,
- );
+ const text = readFileSync(path, 'utf8');
+ const xoxcMatch = text.match(/SLACK(?:_MCP)?_XOXC_TOKEN=["']?(xoxc-[^"'\s]+)/);
+ const xoxdMatch = text.match(/SLACK(?:_MCP)?_XOXD_TOKEN=["']?(xoxd-[^"'\s]+)/);
if (xoxcMatch && xoxdMatch) {
sources.push({
source: path,
@@ -225,14 +191,13 @@ async function scoutSources() {
// 5. Doppler (if configured; cheap probe)
try {
const dopRaw = execSync(`doppler secrets --json 2>/dev/null`, {
- encoding: "utf8",
+ encoding: 'utf8',
});
const dop = JSON.parse(dopRaw);
- const xoxc =
- dop?.SLACK_MCP_XOXC_TOKEN?.computed || dop?.SLACK_BOT_TOKEN?.computed;
+ const xoxc = dop?.SLACK_MCP_XOXC_TOKEN?.computed || dop?.SLACK_BOT_TOKEN?.computed;
const xoxd = dop?.SLACK_MCP_XOXD_TOKEN?.computed;
- if (xoxc?.startsWith("xoxc-") && xoxd?.startsWith("xoxd-")) {
- sources.push({ source: "doppler", xoxc_token: xoxc, xoxd_token: xoxd });
+ if (xoxc?.startsWith('xoxc-') && xoxd?.startsWith('xoxd-')) {
+ sources.push({ source: 'doppler', xoxc_token: xoxc, xoxd_token: xoxd });
}
} catch {}
@@ -242,10 +207,10 @@ async function scoutSources() {
const scouted = await scoutSources();
for (const s of scouted) {
emit({
- type: "found",
+ type: 'found',
source: s.source,
- xoxc_preview: s.xoxc_token.slice(0, 10) + "..." + s.xoxc_token.slice(-4),
- xoxd_preview: s.xoxd_token.slice(0, 10) + "..." + s.xoxd_token.slice(-4),
+ xoxc_preview: s.xoxc_token.slice(0, 10) + '...' + s.xoxc_token.slice(-4),
+ xoxd_preview: s.xoxd_token.slice(0, 10) + '...' + s.xoxd_token.slice(-4),
});
}
@@ -254,10 +219,10 @@ if (scouted.length > 0) {
const first = scouted[0];
// Try to get team_id from ~/.claude.json too, if available
let teamId = null;
- const claudeJson = join(homedir(), ".claude.json");
+ const claudeJson = join(homedir(), '.claude.json');
if (existsSync(claudeJson)) {
try {
- const parsed = JSON.parse(readFileSync(claudeJson, "utf8"));
+ const parsed = JSON.parse(readFileSync(claudeJson, 'utf8'));
teamId = parsed?.mcpServers?.slack?.env?.SLACK_MCP_TEAM_ID || null;
} catch {}
}
@@ -267,26 +232,26 @@ if (scouted.length > 0) {
xoxd_token: first.xoxd_token,
team_id: teamId,
source: `scout:${first.source}`,
- }) + "\n",
+ }) + '\n',
);
process.exit(0);
}
if (SCOUT_ONLY) {
- die("no existing Slack tokens found in any scouted location (--scout-only)");
+ die('no existing Slack tokens found in any scouted location (--scout-only)');
}
// --- Phase 2: Playwright-based extraction ---
// Scan installed browsers for an existing Slack session cookie, then launch
// Playwright with those cookies pre-injected so no manual login is needed.
emit({
- type: "phase",
+ type: 'phase',
phase: 2,
- message: "No scouted tokens — scanning browsers for Slack session",
+ message: 'No scouted tokens — scanning browsers for Slack session',
});
-import { tmpdir } from "node:os";
-import { cpSync, readdirSync } from "node:fs";
+import { tmpdir } from 'node:os';
+import { cpSync, readdirSync } from 'node:fs';
/**
* Map an absolute browser-profile directory to a friendly name. Uses path
@@ -294,21 +259,17 @@ import { cpSync, readdirSync } from "node:fs";
* (e.g. "Google/Chrome", "google-chrome", "Chrome\\User Data").
*/
function browserNameForDir(dir) {
- const d = dir.replace(/\\/g, "/").toLowerCase();
- if (d.includes("/google/chrome beta") || d.includes("chrome-beta"))
- return "Google Chrome Beta";
- if (d.includes("/google/chrome") || d.includes("google-chrome"))
- return "Google Chrome";
- if (d.includes("bravesoftware")) return "Brave";
- if (d.includes("/arc/")) return "Arc";
- if (d.includes("/chromium")) return "Chromium";
- if (d.includes("microsoft edge") || d.includes("edge/user data"))
- return "Microsoft Edge";
- if (d.includes("com.operasoftware.opera") || d.includes("/opera"))
- return "Opera";
- if (d.includes("/comet")) return "Comet";
- if (d.includes("/vivaldi")) return "Vivaldi";
- if (d.includes("/orion")) return "Orion";
+ const d = dir.replace(/\\/g, '/').toLowerCase();
+ if (d.includes('/google/chrome beta') || d.includes('chrome-beta')) return 'Google Chrome Beta';
+ if (d.includes('/google/chrome') || d.includes('google-chrome')) return 'Google Chrome';
+ if (d.includes('bravesoftware')) return 'Brave';
+ if (d.includes('/arc/')) return 'Arc';
+ if (d.includes('/chromium')) return 'Chromium';
+ if (d.includes('microsoft edge') || d.includes('edge/user data')) return 'Microsoft Edge';
+ if (d.includes('com.operasoftware.opera') || d.includes('/opera')) return 'Opera';
+ if (d.includes('/comet')) return 'Comet';
+ if (d.includes('/vivaldi')) return 'Vivaldi';
+ if (d.includes('/orion')) return 'Orion';
return basename(dir);
}
@@ -336,18 +297,18 @@ async function detectBrowserProfiles() {
// On macOS, also probe browsers that browserProfileDirs() doesn't cover
// (Edge/Opera/Vivaldi/Orion/Comet/Chrome Beta). Keeps parity with the
// pre-refactor behavior.
- if (OS_ID === "macos") {
- const appSupport = join(home, "Library", "Application Support");
+ if (OS_ID === 'macos') {
+ const appSupport = join(home, 'Library', 'Application Support');
const extras = [
{
- name: "Google Chrome Beta",
- dir: join(appSupport, "Google", "Chrome Beta"),
+ name: 'Google Chrome Beta',
+ dir: join(appSupport, 'Google', 'Chrome Beta'),
},
- { name: "Microsoft Edge", dir: join(appSupport, "Microsoft Edge") },
- { name: "Opera", dir: join(appSupport, "com.operasoftware.Opera") },
- { name: "Comet", dir: join(appSupport, "Comet") },
- { name: "Vivaldi", dir: join(appSupport, "Vivaldi") },
- { name: "Orion", dir: join(appSupport, "Orion") },
+ { name: 'Microsoft Edge', dir: join(appSupport, 'Microsoft Edge') },
+ { name: 'Opera', dir: join(appSupport, 'com.operasoftware.Opera') },
+ { name: 'Comet', dir: join(appSupport, 'Comet') },
+ { name: 'Vivaldi', dir: join(appSupport, 'Vivaldi') },
+ { name: 'Orion', dir: join(appSupport, 'Orion') },
];
for (const e of extras) {
if (existsSync(e.dir) && !chromiumDirs.some((c) => c.dir === e.dir)) {
@@ -357,7 +318,7 @@ async function detectBrowserProfiles() {
}
for (const { name, dir } of chromiumDirs) {
- const profiles = ["Default"];
+ const profiles = ['Default'];
try {
const entries = readdirSync(dir);
for (const e of entries) {
@@ -368,15 +329,11 @@ async function detectBrowserProfiles() {
}
for (const profile of profiles) {
- const cookieDb = join(dir, profile, "Cookies");
- const localStorageDir = join(dir, profile, "Local Storage", "leveldb");
+ const cookieDb = join(dir, profile, 'Cookies');
+ const localStorageDir = join(dir, profile, 'Local Storage', 'leveldb');
// Chrome/Chromium on some platforms store cookies under Network/Cookies
- const netCookieDb = join(dir, profile, "Network", "Cookies");
- const cookieDbFinal = existsSync(cookieDb)
- ? cookieDb
- : existsSync(netCookieDb)
- ? netCookieDb
- : null;
+ const netCookieDb = join(dir, profile, 'Network', 'Cookies');
+ const cookieDbFinal = existsSync(cookieDb) ? cookieDb : existsSync(netCookieDb) ? netCookieDb : null;
if (cookieDbFinal) {
found.push({
name: `${name}/${profile}`,
@@ -390,33 +347,33 @@ async function detectBrowserProfiles() {
}
// --- Slack desktop app (macOS-only container layout) --------------------
- if (OS_ID === "macos") {
- const appSupport = join(home, "Library", "Application Support");
+ if (OS_ID === 'macos') {
+ const appSupport = join(home, 'Library', 'Application Support');
const slackDesktopPaths = [
// Mac App Store version (sandboxed)
join(
home,
- "Library",
- "Containers",
- "com.tinyspeck.slackmacgap",
- "Data",
- "Library",
- "Application Support",
- "Slack",
+ 'Library',
+ 'Containers',
+ 'com.tinyspeck.slackmacgap',
+ 'Data',
+ 'Library',
+ 'Application Support',
+ 'Slack',
),
// Direct download version (non-sandboxed)
- join(appSupport, "Slack"),
+ join(appSupport, 'Slack'),
];
for (const slackDir of slackDesktopPaths) {
- const cookieDb = join(slackDir, "Cookies");
- const localStorageDir = join(slackDir, "Local Storage", "leveldb");
+ const cookieDb = join(slackDir, 'Cookies');
+ const localStorageDir = join(slackDir, 'Local Storage', 'leveldb');
if (existsSync(cookieDb)) {
found.unshift({
- name: "Slack Desktop",
+ name: 'Slack Desktop',
cookieDb,
localStorageDir,
userDataDir: slackDir,
- profile: ".",
+ profile: '.',
});
}
}
@@ -424,35 +381,28 @@ async function detectBrowserProfiles() {
// --- Firefox (SQLite cookies.sqlite, unencrypted) -----------------------
const firefoxDirs = [];
- if (OS_ID === "macos") {
- firefoxDirs.push(
- join(home, "Library", "Application Support", "Firefox", "Profiles"),
- );
- } else if (process.platform === "linux") {
- firefoxDirs.push(join(home, ".mozilla", "firefox"));
+ if (OS_ID === 'macos') {
+ firefoxDirs.push(join(home, 'Library', 'Application Support', 'Firefox', 'Profiles'));
+ } else if (process.platform === 'linux') {
+ firefoxDirs.push(join(home, '.mozilla', 'firefox'));
if (IS_WSL) {
- const winUser = process.env.USER || process.env.USERNAME || "";
+ const winUser = process.env.USER || process.env.USERNAME || '';
if (winUser) {
- firefoxDirs.push(
- `/mnt/c/Users/${winUser}/AppData/Roaming/Mozilla/Firefox/Profiles`,
- );
+ firefoxDirs.push(`/mnt/c/Users/${winUser}/AppData/Roaming/Mozilla/Firefox/Profiles`);
}
}
- } else if (OS_ID === "windows") {
+ } else if (OS_ID === 'windows') {
const appData =
- process.env.APPDATA ||
- (process.env.USERPROFILE
- ? join(process.env.USERPROFILE, "AppData", "Roaming")
- : null);
+ process.env.APPDATA || (process.env.USERPROFILE ? join(process.env.USERPROFILE, 'AppData', 'Roaming') : null);
if (appData) {
- firefoxDirs.push(join(appData, "Mozilla", "Firefox", "Profiles"));
+ firefoxDirs.push(join(appData, 'Mozilla', 'Firefox', 'Profiles'));
}
}
for (const firefoxDir of firefoxDirs) {
try {
const profiles = readdirSync(firefoxDir);
for (const p of profiles) {
- const cookieDb = join(firefoxDir, p, "cookies.sqlite");
+ const cookieDb = join(firefoxDir, p, 'cookies.sqlite');
if (existsSync(cookieDb)) {
found.push({
name: `Firefox/${p}`,
@@ -468,20 +418,15 @@ async function detectBrowserProfiles() {
}
// --- Safari (macOS-only binary cookie file) -----------------------------
- if (OS_ID === "macos") {
- const safariCookies = join(
- home,
- "Library",
- "Cookies",
- "Cookies.binarycookies",
- );
+ if (OS_ID === 'macos') {
+ const safariCookies = join(home, 'Library', 'Cookies', 'Cookies.binarycookies');
if (existsSync(safariCookies)) {
found.push({
- name: "Safari",
+ name: 'Safari',
cookieDb: safariCookies,
localStorageDir: null,
userDataDir: null,
- profile: ".",
+ profile: '.',
isSafari: true,
});
}
@@ -501,10 +446,10 @@ function querySlackCookieFromDb(cookieDb, browserName, opts = {}) {
try {
if (opts.isSafari) {
// Safari uses Cookies.binarycookies — binary format. Check with strings.
- const result = execSync(
- `strings "${cookieDb}" 2>/dev/null | grep -c "slack.com"`,
- { encoding: "utf8", timeout: 5000 },
- ).trim();
+ const result = execSync(`strings "${cookieDb}" 2>/dev/null | grep -c "slack.com"`, {
+ encoding: 'utf8',
+ timeout: 5000,
+ }).trim();
return parseInt(result, 10) > 0 ? browserName : null;
}
@@ -512,7 +457,7 @@ function querySlackCookieFromDb(cookieDb, browserName, opts = {}) {
// Firefox uses moz_cookies table with plaintext values
const checkResult = execSync(
`sqlite3 "${cookieDb}" "SELECT length(value) FROM moz_cookies WHERE host LIKE '%.slack.com' AND name = 'd' LIMIT 1;" 2>/dev/null`,
- { encoding: "utf8", timeout: 5000 },
+ { encoding: 'utf8', timeout: 5000 },
).trim();
return checkResult && parseInt(checkResult, 10) > 0 ? browserName : null;
}
@@ -520,7 +465,7 @@ function querySlackCookieFromDb(cookieDb, browserName, opts = {}) {
// Chromium / Electron — encrypted_value in 'cookies' table
const checkResult = execSync(
`sqlite3 "${cookieDb}" "SELECT length(encrypted_value) FROM cookies WHERE host_key LIKE '%.slack.com' AND name = 'd' LIMIT 1;" 2>/dev/null`,
- { encoding: "utf8", timeout: 5000 },
+ { encoding: 'utf8', timeout: 5000 },
).trim();
return checkResult && parseInt(checkResult, 10) > 0 ? browserName : null;
} catch {
@@ -530,7 +475,7 @@ function querySlackCookieFromDb(cookieDb, browserName, opts = {}) {
const browserProfiles = await detectBrowserProfiles();
emit({
- type: "step",
+ type: 'step',
message: `Found ${browserProfiles.length} browser profile(s) to scan`,
});
@@ -541,16 +486,16 @@ for (const bp of browserProfiles) {
isSafari: bp.isSafari,
});
if (hasSlack) {
- emit({ type: "step", message: `✓ ${bp.name} has Slack cookies` });
+ emit({ type: 'step', message: `✓ ${bp.name} has Slack cookies` });
selectedBrowser = bp;
break;
} else {
- emit({ type: "step", message: `○ ${bp.name} — no Slack cookies` });
+ emit({ type: 'step', message: `○ ${bp.name} — no Slack cookies` });
}
}
// --- Direct cookie decryption (no Playwright needed for extraction) ---
-import { createHash, pbkdf2Sync, createDecipheriv } from "node:crypto";
+import { createHash, pbkdf2Sync, createDecipheriv } from 'node:crypto';
/**
* Decrypt a Chromium encrypted cookie value on macOS.
@@ -560,23 +505,22 @@ import { createHash, pbkdf2Sync, createDecipheriv } from "node:crypto";
*/
function decryptChromiumCookie(encryptedHex, keychainService) {
try {
- const masterKey = execSync(
- `security find-generic-password -w -s "${keychainService}" 2>/dev/null`,
- { encoding: "utf8" },
- ).trim();
+ const masterKey = execSync(`security find-generic-password -w -s "${keychainService}" 2>/dev/null`, {
+ encoding: 'utf8',
+ }).trim();
if (!masterKey) return null;
- const derivedKey = pbkdf2Sync(masterKey, "saltysalt", 1003, 16, "sha1");
- const encrypted = Buffer.from(encryptedHex, "hex");
+ const derivedKey = pbkdf2Sync(masterKey, 'saltysalt', 1003, 16, 'sha1');
+ const encrypted = Buffer.from(encryptedHex, 'hex');
// Strip "v10" prefix (3 bytes)
if (encrypted.length < 4) return null;
- const prefix = encrypted.slice(0, 3).toString("ascii");
- if (prefix !== "v10") return null;
+ const prefix = encrypted.slice(0, 3).toString('ascii');
+ if (prefix !== 'v10') return null;
const ciphertext = encrypted.slice(3);
- const iv = Buffer.alloc(16, " ");
- const decipher = createDecipheriv("aes-128-cbc", derivedKey, iv);
+ const iv = Buffer.alloc(16, ' ');
+ const decipher = createDecipheriv('aes-128-cbc', derivedKey, iv);
decipher.setAutoPadding(false);
let decrypted = decipher.update(ciphertext);
decrypted = Buffer.concat([decrypted, decipher.final()]);
@@ -589,7 +533,7 @@ function decryptChromiumCookie(encryptedHex, keychainService) {
// Chrome v130+ prepends a 32-byte SHA256 domain hash before the value.
// The real cookie value is URL-encoded ASCII text.
- const raw = decrypted.toString("latin1");
+ const raw = decrypted.toString('latin1');
// The 'd' cookie value is URL-encoded (contains %2B, %2F, %3D etc.)
// Find the longest URL-encoded chunk — that's the real value.
const allMatches = [...raw.matchAll(/[A-Za-z0-9%+/=_-]{30,}/g)];
@@ -607,19 +551,19 @@ function decryptChromiumCookie(encryptedHex, keychainService) {
* Map browser name to its keychain Safe Storage service name.
*/
function keychainServiceFor(browserName) {
- const name = browserName.split("/")[0]; // strip "/Default" etc.
+ const name = browserName.split('/')[0]; // strip "/Default" etc.
const map = {
- "Google Chrome": "Chrome Safe Storage",
- "Google Chrome Beta": "Chrome Beta Safe Storage",
- Comet: "Comet Safe Storage",
- Arc: "Arc Safe Storage",
- Brave: "Brave Safe Storage",
- "Microsoft Edge": "Microsoft Edge Safe Storage",
- Chromium: "Chromium Safe Storage",
- Opera: "Opera Safe Storage",
- Vivaldi: "Vivaldi Safe Storage",
- Orion: "Orion Safe Storage",
- "Slack Desktop": "Slack Safe Storage",
+ 'Google Chrome': 'Chrome Safe Storage',
+ 'Google Chrome Beta': 'Chrome Beta Safe Storage',
+ Comet: 'Comet Safe Storage',
+ Arc: 'Arc Safe Storage',
+ Brave: 'Brave Safe Storage',
+ 'Microsoft Edge': 'Microsoft Edge Safe Storage',
+ Chromium: 'Chromium Safe Storage',
+ Opera: 'Opera Safe Storage',
+ Vivaldi: 'Vivaldi Safe Storage',
+ Orion: 'Orion Safe Storage',
+ 'Slack Desktop': 'Slack Safe Storage',
};
return map[name] || `${name} Safe Storage`;
}
@@ -635,25 +579,25 @@ async function extractXoxcFromLocalStorage(localStorageDir) {
// Try proper LevelDB reading first
try {
- const { ClassicLevel } = await import("classic-level");
+ const { ClassicLevel } = await import('classic-level');
// Copy to temp to avoid lock conflicts with running browser
const tmpCopy = join(tmpdir(), `ops-slack-ls-${Date.now()}`);
cpSync(localStorageDir, tmpCopy, { recursive: true });
// Remove LOCK file so we can open read-only
try {
- unlinkSync(join(tmpCopy, "LOCK"));
+ unlinkSync(join(tmpCopy, 'LOCK'));
} catch {}
const db = new ClassicLevel(tmpCopy, {
createIfMissing: false,
- valueEncoding: "utf8",
- keyEncoding: "utf8",
+ valueEncoding: 'utf8',
+ keyEncoding: 'utf8',
});
await db.open({ readOnly: true });
let token = null;
for await (const [, value] of db.iterator()) {
- if (value && value.includes("xoxc-")) {
+ if (value && value.includes('xoxc-')) {
const m = value.match(/xoxc-[0-9a-zA-Z._-]+/);
if (m && m[0].length > 20) {
token = m[0];
@@ -671,13 +615,11 @@ async function extractXoxcFromLocalStorage(localStorageDir) {
// Fallback: raw file scanning (less reliable due to LevelDB binary framing)
try {
- const files = readdirSync(localStorageDir).filter(
- (f) => f.endsWith(".ldb") || f.endsWith(".log"),
- );
+ const files = readdirSync(localStorageDir).filter((f) => f.endsWith('.ldb') || f.endsWith('.log'));
for (const f of files) {
try {
const data = readFileSync(join(localStorageDir, f));
- const text = data.toString("latin1");
+ const text = data.toString('latin1');
const match = text.match(/xoxc-[0-9A-Za-z._-]+/);
if (match && match[0].length > 20) return match[0];
} catch {}
@@ -689,7 +631,7 @@ async function extractXoxcFromLocalStorage(localStorageDir) {
// --- Try direct extraction if we found a browser with cookies ---
if (selectedBrowser && !selectedBrowser.isSafari) {
emit({
- type: "step",
+ type: 'step',
message: `Attempting direct cookie decryption from ${selectedBrowser.name}`,
});
@@ -702,7 +644,7 @@ if (selectedBrowser && !selectedBrowser.isSafari) {
try {
xoxdToken = execSync(
`sqlite3 "${selectedBrowser.cookieDb}" "SELECT value FROM moz_cookies WHERE host LIKE '%.slack.com' AND name = 'd' LIMIT 1;" 2>/dev/null`,
- { encoding: "utf8", timeout: 5000 },
+ { encoding: 'utf8', timeout: 5000 },
).trim();
} catch {}
} else {
@@ -710,7 +652,7 @@ if (selectedBrowser && !selectedBrowser.isSafari) {
try {
const hexValue = execSync(
`sqlite3 "${selectedBrowser.cookieDb}" "SELECT hex(encrypted_value) FROM cookies WHERE host_key LIKE '%.slack.com' AND name = 'd' LIMIT 1;" 2>/dev/null`,
- { encoding: "utf8", timeout: 5000 },
+ { encoding: 'utf8', timeout: 5000 },
).trim();
if (hexValue) {
xoxdToken = decryptChromiumCookie(hexValue, keychainSvc);
@@ -720,24 +662,22 @@ if (selectedBrowser && !selectedBrowser.isSafari) {
if (xoxdToken) {
// Clean up: if decrypted value contains an embedded xoxd-, extract from there
- const xoxdIdx = xoxdToken.lastIndexOf("xoxd-");
+ const xoxdIdx = xoxdToken.lastIndexOf('xoxd-');
if (xoxdIdx > 0) {
xoxdToken = xoxdToken.slice(xoxdIdx);
- } else if (!xoxdToken.startsWith("xoxd-")) {
+ } else if (!xoxdToken.startsWith('xoxd-')) {
xoxdToken = `xoxd-${xoxdToken}`;
}
emit({
- type: "step",
+ type: 'step',
message: `✓ Decrypted 'd' cookie (${xoxdToken.slice(0, 10)}...${xoxdToken.slice(-4)})`,
});
// Extract xoxc from localStorage
- const xoxcToken = await extractXoxcFromLocalStorage(
- selectedBrowser.localStorageDir,
- );
+ const xoxcToken = await extractXoxcFromLocalStorage(selectedBrowser.localStorageDir);
if (xoxcToken) {
emit({
- type: "step",
+ type: 'step',
message: `✓ Found xoxc token from localStorage (${xoxcToken.slice(0, 10)}...${xoxcToken.slice(-4)})`,
});
@@ -746,14 +686,11 @@ if (selectedBrowser && !selectedBrowser.isSafari) {
if (selectedBrowser.localStorageDir) {
try {
const files = readdirSync(selectedBrowser.localStorageDir).filter(
- (f) => f.endsWith(".ldb") || f.endsWith(".log"),
+ (f) => f.endsWith('.ldb') || f.endsWith('.log'),
);
for (const f of files) {
try {
- const data = readFileSync(
- join(selectedBrowser.localStorageDir, f),
- "latin1",
- );
+ const data = readFileSync(join(selectedBrowser.localStorageDir, f), 'latin1');
const m = data.match(/"team_id"\s*:\s*"(T[A-Z0-9]+)"/);
if (m) {
teamId = m[1];
@@ -765,10 +702,10 @@ if (selectedBrowser && !selectedBrowser.isSafari) {
}
// Validate tokens against Slack API
- emit({ type: "step", message: "Validating tokens against Slack API..." });
+ emit({ type: 'step', message: 'Validating tokens against Slack API...' });
let authResult = null;
try {
- const res = await fetch("https://slack.com/api/auth.test", {
+ const res = await fetch('https://slack.com/api/auth.test', {
headers: {
Authorization: `Bearer ${xoxcToken}`,
Cookie: `d=${xoxdToken}`,
@@ -780,43 +717,35 @@ if (selectedBrowser && !selectedBrowser.isSafari) {
if (authResult?.ok) {
teamId = authResult.team_id || teamId;
emit({
- type: "step",
+ type: 'step',
message: `✓ Validated — ${authResult.url} (${authResult.team_id})`,
});
} else {
emit({
- type: "step",
- message: `⚠ Validation failed: ${authResult?.error || "unknown"} — tokens may be stale`,
+ type: 'step',
+ message: `⚠ Validation failed: ${authResult?.error || 'unknown'} — tokens may be stale`,
});
}
// Persist via cascading credential store (macOS Keychain → libsecret →
// Windows Credential Manager → keytar → encrypted JSON → plaintext).
try {
- const xoxcRes = await setCredential(
- "slack-xoxc",
- USER_ACCOUNT,
- xoxcToken,
- );
- const xoxdRes = await setCredential(
- "slack-xoxd",
- USER_ACCOUNT,
- xoxdToken,
- );
+ const xoxcRes = await setCredential('slack-xoxc', USER_ACCOUNT, xoxcToken);
+ const xoxdRes = await setCredential('slack-xoxd', USER_ACCOUNT, xoxdToken);
if (xoxcRes.ok && xoxdRes.ok) {
emit({
- type: "step",
+ type: 'step',
message: `✓ Saved tokens via credential-store (${xoxcRes.backend})`,
});
} else {
emit({
- type: "step",
+ type: 'step',
message: `○ Credential-store save partial: xoxc=${xoxcRes.backend}/${xoxcRes.ok} xoxd=${xoxdRes.backend}/${xoxdRes.ok}`,
});
}
} catch (e) {
emit({
- type: "step",
+ type: 'step',
message: `○ Credential-store save failed: ${e.message}`,
});
}
@@ -827,16 +756,16 @@ if (selectedBrowser && !selectedBrowser.isSafari) {
`claude mcp add slack -s user -e SLACK_XOXC_TOKEN='${xoxcToken.replace(/'/g, "'\\''")}'` +
` -e SLACK_XOXD_TOKEN='${xoxdToken.replace(/'/g, "'\\''")}'` +
` -- npx -y @anthropic-ai/slack-mcp@latest`,
- { timeout: 15000, stdio: "pipe" },
+ { timeout: 15000, stdio: 'pipe' },
);
emit({
- type: "step",
- message: "✓ Registered Slack MCP server in Claude Code",
+ type: 'step',
+ message: '✓ Registered Slack MCP server in Claude Code',
});
} catch {
emit({
- type: "step",
- message: "○ Could not auto-register MCP — run: claude mcp add slack",
+ type: 'step',
+ message: '○ Could not auto-register MCP — run: claude mcp add slack',
});
}
@@ -847,18 +776,18 @@ if (selectedBrowser && !selectedBrowser.isSafari) {
xoxd_token: xoxdToken,
team_id: teamId,
source: `direct:${selectedBrowser.name}`,
- }) + "\n",
+ }) + '\n',
);
process.exit(0);
} else {
emit({
- type: "step",
+ type: 'step',
message: `○ Could not find xoxc in localStorage — falling back to Playwright`,
});
}
} else {
emit({
- type: "step",
+ type: 'step',
message: `○ Could not decrypt cookie from ${selectedBrowser.name} — falling back to Playwright`,
});
}
@@ -867,10 +796,10 @@ if (selectedBrowser && !selectedBrowser.isSafari) {
// --- Playwright fallback (only if direct extraction failed) ---
let chromium;
try {
- ({ chromium } = await import("playwright"));
+ ({ chromium } = await import('playwright'));
} catch {
die(
- "playwright is not installed and direct cookie extraction failed. Run `npm install playwright` in the plugin root and `npx playwright install chromium`.",
+ 'playwright is not installed and direct cookie extraction failed. Run `npm install playwright` in the plugin root and `npx playwright install chromium`.',
);
}
@@ -882,28 +811,27 @@ try {
// $XDG_DATA_HOME (or ~/.local/share on Linux/macOS, or the default elsewhere).
async function resolvePlaywrightProfileDir() {
// --profile-dir was explicitly provided and differs from the library default?
- const libDefault = join(homedir(), ".claude-ops", "slack-profile");
+ const libDefault = join(homedir(), '.claude-ops', 'slack-profile');
if (PROFILE_DIR && PROFILE_DIR !== libDefault) return PROFILE_DIR;
try {
const dirs = await browserProfileDirs();
const chromeDir = dirs.find((d) => {
- const low = d.replace(/\\/g, "/").toLowerCase();
- return low.includes("chrome") || low.includes("chromium");
+ const low = d.replace(/\\/g, '/').toLowerCase();
+ return low.includes('chrome') || low.includes('chromium');
});
if (chromeDir) return chromeDir;
} catch {}
// Nothing pre-existing — use an XDG-compliant fresh profile.
- const xdgData =
- process.env.XDG_DATA_HOME || join(homedir(), ".local", "share");
- return join(xdgData, "claude-ops", "chromium-profile");
+ const xdgData = process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share');
+ return join(xdgData, 'claude-ops', 'chromium-profile');
}
const LAUNCH_PROFILE_DIR = await resolvePlaywrightProfileDir();
mkdirSync(LAUNCH_PROFILE_DIR, { recursive: true });
emit({
- type: "step",
+ type: 'step',
message: `Launching Chromium (headless=${HEADLESS}, profile=${LAUNCH_PROFILE_DIR})`,
});
@@ -911,11 +839,7 @@ let context;
try {
context = await chromium.launchPersistentContext(LAUNCH_PROFILE_DIR, {
headless: HEADLESS,
- args: [
- "--disable-blink-features=AutomationControlled",
- "--no-first-run",
- "--no-default-browser-check",
- ],
+ args: ['--disable-blink-features=AutomationControlled', '--no-first-run', '--no-default-browser-check'],
viewport: { width: 1280, height: 800 },
});
} catch (err) {
@@ -928,9 +852,8 @@ try {
);
if (looksHeadlessy || !HEADLESS) {
emit({
- type: "error",
- message:
- "no display available — run ops:setup slack on a machine with a desktop environment",
+ type: 'error',
+ message: 'no display available — run ops:setup slack on a machine with a desktop environment',
os: OS_ID,
headless_available: false,
detail: msg,
@@ -943,23 +866,22 @@ try {
const page = context.pages()[0] || (await context.newPage());
try {
- emit({ type: "step", message: `Navigating to ${WORKSPACE_VALIDATED}` });
+ emit({ type: 'step', message: `Navigating to ${WORKSPACE_VALIDATED}` });
await page.goto(WORKSPACE_VALIDATED);
try {
- await page.waitForLoadState("networkidle", { timeout: 30_000 });
+ await page.waitForLoadState('networkidle', { timeout: 30_000 });
} catch {}
const currentUrl = page.url();
if (/signin|sign_in|ssb\/signin/i.test(currentUrl)) {
if (HEADLESS) {
die(
- "Not logged in and running headless. Run without --headless first to establish a session in the profile dir.",
+ 'Not logged in and running headless. Run without --headless first to establish a session in the profile dir.',
);
}
emit({
- type: "need_login",
- message:
- "Log in to Slack in the open Chromium window, then touch the ready-file to continue",
+ type: 'need_login',
+ message: 'Log in to Slack in the open Chromium window, then touch the ready-file to continue',
ready_file: READY_FILE,
});
// Wait for the caller to touch READY_FILE once the user finishes login
@@ -968,12 +890,12 @@ try {
if (existsSync(READY_FILE)) break;
await new Promise((r) => setTimeout(r, 2000));
}
- if (!existsSync(READY_FILE)) die("timeout waiting for login completion");
+ if (!existsSync(READY_FILE)) die('timeout waiting for login completion');
try {
await page.waitForURL(/\/client\//, { timeout: 15_000 });
} catch {}
try {
- await page.waitForLoadState("networkidle", { timeout: 30_000 });
+ await page.waitForLoadState('networkidle', { timeout: 30_000 });
} catch {}
}
@@ -984,26 +906,23 @@ try {
if (!teamId) {
teamId = await page.evaluate(() => {
try {
- const cfg = JSON.parse(localStorage.localConfig_v2 || "{}");
+ const cfg = JSON.parse(localStorage.localConfig_v2 || '{}');
return Object.keys(cfg.teams || {})[0] || null;
} catch {
return null;
}
});
}
- if (!teamId)
- die(
- "Could not determine Slack team ID — make sure you're viewing a workspace",
- );
- emit({ type: "step", message: `Found team_id=${teamId}` });
+ if (!teamId) die("Could not determine Slack team ID — make sure you're viewing a workspace");
+ emit({ type: 'step', message: `Found team_id=${teamId}` });
// Extract XOXC from localStorage
let xoxcToken = await page.evaluate((tid) => {
try {
- const cfg = JSON.parse(localStorage.localConfig_v2 || "{}");
+ const cfg = JSON.parse(localStorage.localConfig_v2 || '{}');
if (cfg.teams?.[tid]?.token) return cfg.teams[tid].token;
for (const [, data] of Object.entries(cfg.teams || {})) {
- if (data?.token?.startsWith("xoxc-")) return data.token;
+ if (data?.token?.startsWith('xoxc-')) return data.token;
}
return null;
} catch {
@@ -1017,18 +936,13 @@ try {
return m ? m[1] : null;
});
}
- if (!xoxcToken)
- die("Could not find XOXC token — ensure the workspace is fully loaded");
+ if (!xoxcToken) die('Could not find XOXC token — ensure the workspace is fully loaded');
// Extract XOXD ('d' cookie) from the context cookie jar
const cookies = await context.cookies();
- const dCookie = cookies.find(
- (c) => c.name === "d" && /slack\.com/.test(c.domain),
- );
+ const dCookie = cookies.find((c) => c.name === 'd' && /slack\.com/.test(c.domain));
if (!dCookie) die("Could not find 'd' cookie (XOXD token)");
- const xoxdToken = dCookie.value.startsWith("xoxd-")
- ? dCookie.value
- : `xoxd-${dCookie.value}`;
+ const xoxdToken = dCookie.value.startsWith('xoxd-') ? dCookie.value : `xoxd-${dCookie.value}`;
await context.close();
@@ -1037,8 +951,8 @@ try {
xoxc_token: xoxcToken,
xoxd_token: xoxdToken,
team_id: teamId,
- source: "playwright",
- }) + "\n",
+ source: 'playwright',
+ }) + '\n',
);
process.exit(0);
} catch (err) {
diff --git a/claude-ops/bin/ops-telegram-autolink.mjs b/claude-ops/bin/ops-telegram-autolink.mjs
index c0f5ed75..07c74908 100755
--- a/claude-ops/bin/ops-telegram-autolink.mjs
+++ b/claude-ops/bin/ops-telegram-autolink.mjs
@@ -35,46 +35,42 @@
* simple regex to keep the dep footprint minimal.
*/
-import { readFileSync, existsSync, unlinkSync } from "node:fs";
-import { execSync } from "node:child_process";
-import { parseArgs } from "node:util";
-import os from "node:os";
-import { TelegramClient } from "telegram";
-import { StringSession } from "telegram/sessions/index.js";
-import {
- setCredential,
- getCredential,
- deleteCredential,
-} from "../lib/credential-store.mjs";
-import { osId, keyringBackend } from "../lib/os-detect.mjs";
+import { readFileSync, existsSync, unlinkSync } from 'node:fs';
+import { execSync } from 'node:child_process';
+import { parseArgs } from 'node:util';
+import os from 'node:os';
+import { TelegramClient } from 'telegram';
+import { StringSession } from 'telegram/sessions/index.js';
+import { setCredential, getCredential, deleteCredential } from '../lib/credential-store.mjs';
+import { osId, keyringBackend } from '../lib/os-detect.mjs';
const { values } = parseArgs({
options: {
- phone: { type: "string" },
- "app-title": { type: "string", default: "claude-ops" },
- "app-short": { type: "string", default: "claude_ops" },
- "skip-session": { type: "boolean", default: false },
- "code-file": { type: "string", default: "/tmp/telegram-code.txt" },
+ phone: { type: 'string' },
+ 'app-title': { type: 'string', default: 'claude-ops' },
+ 'app-short': { type: 'string', default: 'claude_ops' },
+ 'skip-session': { type: 'boolean', default: false },
+ 'code-file': { type: 'string', default: '/tmp/telegram-code.txt' },
},
});
const PHONE = values.phone;
-const APP_TITLE = values["app-title"];
-const APP_SHORT = values["app-short"];
-const SKIP_SESSION = values["skip-session"];
-const CODE_FILE = values["code-file"];
+const APP_TITLE = values['app-title'];
+const APP_SHORT = values['app-short'];
+const SKIP_SESSION = values['skip-session'];
+const CODE_FILE = values['code-file'];
function emit(event) {
- process.stderr.write(JSON.stringify(event) + "\n");
+ process.stderr.write(JSON.stringify(event) + '\n');
}
function die(message, extra = {}) {
- emit({ type: "error", message, ...extra });
+ emit({ type: 'error', message, ...extra });
process.exit(1);
}
if (!PHONE || !/^\+\d{7,15}$/.test(PHONE)) {
- die("missing or invalid --phone (E.164 required, e.g. +15551234567)");
+ die('missing or invalid --phone (E.164 required, e.g. +15551234567)');
}
if (existsSync(CODE_FILE)) unlinkSync(CODE_FILE);
@@ -87,7 +83,7 @@ async function waitForCode(maxSec = 300) {
let lastLog = 0;
while (Date.now() - start < maxSec * 1000) {
if (existsSync(CODE_FILE)) {
- const raw = readFileSync(CODE_FILE, "utf8").trim();
+ const raw = readFileSync(CODE_FILE, 'utf8').trim();
if (/^[\w\-]{3,20}$/.test(raw)) {
try {
unlinkSync(CODE_FILE);
@@ -97,7 +93,7 @@ async function waitForCode(maxSec = 300) {
}
if (Date.now() - lastLog > 15000) {
emit({
- type: "heartbeat",
+ type: 'heartbeat',
waited_s: Math.floor((Date.now() - start) / 1000),
});
lastLog = Date.now();
@@ -117,48 +113,47 @@ class CookieJar {
update(response) {
const raw = response.headers.getSetCookie
? response.headers.getSetCookie()
- : [response.headers.get("set-cookie")].filter(Boolean);
+ : [response.headers.get('set-cookie')].filter(Boolean);
for (const c of raw || []) {
- const [kv] = c.split(";");
- const eq = kv.indexOf("=");
- if (eq > 0)
- this.cookies.set(kv.slice(0, eq).trim(), kv.slice(eq + 1).trim());
+ const [kv] = c.split(';');
+ const eq = kv.indexOf('=');
+ if (eq > 0) this.cookies.set(kv.slice(0, eq).trim(), kv.slice(eq + 1).trim());
}
}
header() {
return Array.from(this.cookies.entries())
.map(([k, v]) => `${k}=${v}`)
- .join("; ");
+ .join('; ');
}
}
// --- Phase 1: my.telegram.org HTTP flow ---
emit({
- type: "phase",
+ type: 'phase',
phase: 1,
- message: "Extracting api_id / api_hash from my.telegram.org",
+ message: 'Extracting api_id / api_hash from my.telegram.org',
});
const jar = new CookieJar();
const COMMON_HEADERS = {
- "User-Agent":
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
- "Accept-Language": "en-US,en;q=0.9",
+ 'User-Agent':
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36',
+ 'Accept-Language': 'en-US,en;q=0.9',
};
async function httpPost(url, body) {
const res = await fetch(url, {
- method: "POST",
+ method: 'POST',
headers: {
...COMMON_HEADERS,
- "Content-Type": "application/x-www-form-urlencoded",
- "X-Requested-With": "XMLHttpRequest",
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ 'X-Requested-With': 'XMLHttpRequest',
Cookie: jar.header(),
- Referer: "https://my.telegram.org/auth",
- Origin: "https://my.telegram.org",
+ Referer: 'https://my.telegram.org/auth',
+ Origin: 'https://my.telegram.org',
},
body: new URLSearchParams(body).toString(),
- redirect: "manual",
+ redirect: 'manual',
});
jar.update(res);
return res;
@@ -167,48 +162,48 @@ async function httpPost(url, body) {
async function httpGet(url) {
const res = await fetch(url, {
headers: { ...COMMON_HEADERS, Cookie: jar.header() },
- redirect: "manual",
+ redirect: 'manual',
});
jar.update(res);
return res;
}
// Step 1.1: request a login code for PHONE
-emit({ type: "step", message: `POST /auth/send_password for ${PHONE}` });
-const sendRes = await httpPost("https://my.telegram.org/auth/send_password", {
+emit({ type: 'step', message: `POST /auth/send_password for ${PHONE}` });
+const sendRes = await httpPost('https://my.telegram.org/auth/send_password', {
phone: PHONE,
});
const sendText = await sendRes.text();
-if (sendText.includes("Sorry, too many tries")) {
- die("my.telegram.org rate-limited your account. Wait ~8 hours and retry.");
+if (sendText.includes('Sorry, too many tries')) {
+ die('my.telegram.org rate-limited your account. Wait ~8 hours and retry.');
}
let randomHash;
try {
const parsed = JSON.parse(sendText);
randomHash = parsed.random_hash;
- if (!randomHash) throw new Error("no random_hash in response");
+ if (!randomHash) throw new Error('no random_hash in response');
} catch (e) {
- die("send_password response was not valid JSON", {
+ die('send_password response was not valid JSON', {
body: sendText.slice(0, 200),
});
}
emit({
- type: "step",
- message: "Telegram has sent a code to your Telegram account",
+ type: 'step',
+ message: 'Telegram has sent a code to your Telegram account',
});
// Step 1.2: wait for code from the bridge
emit({
- type: "need_code",
- channel: "web_login",
+ type: 'need_code',
+ channel: 'web_login',
message: `Enter the code from Telegram → write it to ${CODE_FILE}`,
code_file: CODE_FILE,
});
const webCode = await waitForCode(300);
// Step 1.3: POST login with phone + random_hash + password=code
-emit({ type: "step", message: "POST /auth/login" });
-const loginRes = await httpPost("https://my.telegram.org/auth/login", {
+emit({ type: 'step', message: 'POST /auth/login' });
+const loginRes = await httpPost('https://my.telegram.org/auth/login', {
phone: PHONE,
random_hash: randomHash,
password: webCode,
@@ -219,8 +214,8 @@ if (loginBody && /error|invalid|wrong/i.test(loginBody)) {
}
// Step 1.4: GET /apps to see if an app already exists
-emit({ type: "step", message: "GET /apps" });
-let appsRes = await httpGet("https://my.telegram.org/apps");
+emit({ type: 'step', message: 'GET /apps' });
+let appsRes = await httpGet('https://my.telegram.org/apps');
let appsHtml = await appsRes.text();
/**
@@ -237,12 +232,8 @@ function extract(html) {
let apiHash = null;
// Strategy 1: label + nearby span (original layout)
- const idS1 = html.match(
- /api_id[^<]*<\/label>[\s\S]*?<span[^>]*>\s*(\d{5,12})\s*<\/span>/i,
- );
- const hashS1 = html.match(
- /api_hash[^<]*<\/label>[\s\S]*?<span[^>]*>\s*([a-f0-9]{32})\s*<\/span>/i,
- );
+ const idS1 = html.match(/api_id[^<]*<\/label>[\s\S]*?<span[^>]*>\s*(\d{5,12})\s*<\/span>/i);
+ const hashS1 = html.match(/api_hash[^<]*<\/label>[\s\S]*?<span[^>]*>\s*([a-f0-9]{32})\s*<\/span>/i);
if (idS1) apiId = idS1[1];
if (hashS1) apiHash = hashS1[1];
@@ -268,22 +259,18 @@ function extract(html) {
// Strategy 4: input/hidden fields with api_id/api_hash as name or id
if (!apiId) {
- const idS4 = html.match(
- /(?:name|id)=['"]?api_id['"]?[^>]*value=['"]?(\d{5,12})['"]?/i,
- );
+ const idS4 = html.match(/(?:name|id)=['"]?api_id['"]?[^>]*value=['"]?(\d{5,12})['"]?/i);
if (idS4) apiId = idS4[1];
}
if (!apiHash) {
- const hashS4 = html.match(
- /(?:name|id)=['"]?api_hash['"]?[^>]*value=['"]?([a-f0-9]{32})['"]?/i,
- );
+ const hashS4 = html.match(/(?:name|id)=['"]?api_hash['"]?[^>]*value=['"]?([a-f0-9]{32})['"]?/i);
if (hashS4) apiHash = hashS4[1];
}
// Strategy 5: brute-force — strip all HTML tags and look for the
// characteristic patterns near their keywords in plain text
if (!apiId || !apiHash) {
- const text = html.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ");
+ const text = html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ');
if (!apiId) {
const idS5 = text.match(/api_id\s*:?\s*(\d{5,12})/i);
if (idS5) apiId = idS5[1];
@@ -308,23 +295,18 @@ let { apiId, apiHash } = extract(appsHtml);
if (!apiId || !apiHash) {
// Step 1.5: no app exists → create one
- emit({ type: "step", message: "No existing app — creating one" });
+ emit({ type: 'step', message: 'No existing app — creating one' });
// Extract CSRF token / hash value from the create-app form if present
- const hashInput = appsHtml.match(
- /name=['"]hash['"]\s+value=['"]([a-z0-9]+)['"]/i,
- );
+ const hashInput = appsHtml.match(/name=['"]hash['"]\s+value=['"]([a-z0-9]+)['"]/i);
const createParams = {
- hash: hashInput ? hashInput[1] : "",
+ hash: hashInput ? hashInput[1] : '',
app_title: APP_TITLE,
app_shortname: APP_SHORT,
- app_url: "https://github.com/claude-ops-marketplace/claude-ops",
- app_platform: "desktop",
- app_desc: "claude-ops — automated operations for Claude Code",
+ app_url: 'https://github.com/claude-ops-marketplace/claude-ops',
+ app_platform: 'desktop',
+ app_desc: 'claude-ops — automated operations for Claude Code',
};
- const createRes = await httpPost(
- "https://my.telegram.org/apps/create",
- createParams,
- );
+ const createRes = await httpPost('https://my.telegram.org/apps/create', createParams);
const createBody = await createRes.text();
if (createRes.status >= 400 || /error/i.test(createBody.slice(0, 200))) {
die(`/apps/create failed (HTTP ${createRes.status})`, {
@@ -332,7 +314,7 @@ if (!apiId || !apiHash) {
});
}
// Re-fetch the apps page now that an app exists
- appsRes = await httpGet("https://my.telegram.org/apps");
+ appsRes = await httpGet('https://my.telegram.org/apps');
appsHtml = await appsRes.text();
({ apiId, apiHash } = extract(appsHtml));
}
@@ -340,22 +322,22 @@ if (!apiId || !apiHash) {
if (!apiId || !apiHash) {
// Dump a snippet of the HTML so the caller can diagnose what changed
const snippet = appsHtml
- .replace(/<script[\s\S]*?<\/script>/gi, "")
- .replace(/<style[\s\S]*?<\/style>/gi, "")
- .replace(/<[^>]+>/g, " ")
- .replace(/\s+/g, " ")
+ .replace(/<script[\s\S]*?<\/script>/gi, '')
+ .replace(/<style[\s\S]*?<\/style>/gi, '')
+ .replace(/<[^>]+>/g, ' ')
+ .replace(/\s+/g, ' ')
.trim()
.slice(0, 500);
die(
- `could not extract ${!apiId ? "api_id" : ""}${!apiId && !apiHash ? " or " : ""}${!apiHash ? "api_hash" : ""} from /apps HTML after 6 extraction strategies`,
+ `could not extract ${!apiId ? 'api_id' : ''}${!apiId && !apiHash ? ' or ' : ''}${!apiHash ? 'api_hash' : ''} from /apps HTML after 6 extraction strategies`,
{ html_snippet: snippet },
);
}
emit({
- type: "phase",
+ type: 'phase',
phase: 1,
- message: "Extracted credentials",
+ message: 'Extracted credentials',
api_id: apiId,
});
@@ -367,20 +349,20 @@ if (SKIP_SESSION) {
api_hash: apiHash,
phone: PHONE,
session: null,
- }) + "\n",
+ }) + '\n',
);
process.exit(0);
}
-emit({ type: "phase", phase: 2, message: "Generating gram.js session string" });
+emit({ type: 'phase', phase: 2, message: 'Generating gram.js session string' });
-const stringSession = new StringSession("");
+const stringSession = new StringSession('');
const client = new TelegramClient(stringSession, parseInt(apiId, 10), apiHash, {
connectionRetries: 3,
baseLogger: {
log: () => {},
warn: () => {},
- error: (...a) => emit({ type: "gram_error", message: a.join(" ") }),
+ error: (...a) => emit({ type: 'gram_error', message: a.join(' ') }),
info: () => {},
debug: () => {},
},
@@ -401,34 +383,34 @@ try {
// enabled, we'd need another bridge file. For MVP, default to empty
// and let gram.js error loudly if 2FA is required.
emit({
- type: "need_password",
+ type: 'need_password',
message:
- "Telegram 2FA password required. Write to /tmp/telegram-password.txt or leave unset for no-2FA accounts",
- password_file: "/tmp/telegram-password.txt",
+ 'Telegram 2FA password required. Write to /tmp/telegram-password.txt or leave unset for no-2FA accounts',
+ password_file: '/tmp/telegram-password.txt',
});
const start = Date.now();
while (Date.now() - start < 60_000) {
- if (existsSync("/tmp/telegram-password.txt")) {
- const pw = readFileSync("/tmp/telegram-password.txt", "utf8").trim();
+ if (existsSync('/tmp/telegram-password.txt')) {
+ const pw = readFileSync('/tmp/telegram-password.txt', 'utf8').trim();
try {
- unlinkSync("/tmp/telegram-password.txt");
+ unlinkSync('/tmp/telegram-password.txt');
} catch {}
return pw;
}
await new Promise((r) => setTimeout(r, 2000));
}
- return "";
+ return '';
},
phoneCode: async () => {
emit({
- type: "need_code",
- channel: "gram_auth",
+ type: 'need_code',
+ channel: 'gram_auth',
message: `Telegram sent a SECOND code for gram.js auth. Write digits-only to ${CODE_FILE}`,
code_file: CODE_FILE,
});
return await waitForCode(300);
},
- onError: (err) => emit({ type: "gram_error", message: err.message }),
+ onError: (err) => emit({ type: 'gram_error', message: err.message }),
});
} catch (err) {
die(`gram.js auth failed: ${err.message}`);
@@ -437,17 +419,17 @@ try {
const sessionStr = client.session.save();
// Step 2.1: Validate session
-emit({ type: "step", message: "Validating session..." });
+emit({ type: 'step', message: 'Validating session...' });
try {
await client.connect();
const me = await client.getMe();
emit({
- type: "step",
- message: `✓ Validated — ${me.firstName} (@${me.username || "no-username"})`,
+ type: 'step',
+ message: `✓ Validated — ${me.firstName} (@${me.username || 'no-username'})`,
});
await client.disconnect();
} catch (e) {
- emit({ type: "step", message: `⚠ Session validation failed: ${e.message}` });
+ emit({ type: 'step', message: `⚠ Session validation failed: ${e.message}` });
await client.disconnect().catch(() => {});
}
@@ -458,33 +440,30 @@ try {
// installations keep working because the service/account names (and the
// underlying `security add-generic-password` invocation on darwin) are
// unchanged. See lib/credential-store.mjs for cascade details.
-const CRED_ACCOUNT =
- process.env.USER || process.env.USERNAME || os.userInfo().username || "user";
+const CRED_ACCOUNT = process.env.USER || process.env.USERNAME || os.userInfo().username || 'user';
try {
const backends = new Set();
for (const [svc, val] of [
- ["telegram-api-id", apiId],
- ["telegram-api-hash", apiHash],
- ["telegram-phone", PHONE],
- ["telegram-session", sessionStr],
+ ['telegram-api-id', apiId],
+ ['telegram-api-hash', apiHash],
+ ['telegram-phone', PHONE],
+ ['telegram-session', sessionStr],
]) {
const r = await setCredential(svc, CRED_ACCOUNT, val);
if (!r || !r.ok) {
- throw new Error(
- `setCredential(${svc}) failed (backend=${r ? r.backend : "none"})`,
- );
+ throw new Error(`setCredential(${svc}) failed (backend=${r ? r.backend : 'none'})`);
}
if (r.backend) backends.add(r.backend);
}
- const backendList = Array.from(backends).join(", ") || "unknown";
+ const backendList = Array.from(backends).join(', ') || 'unknown';
emit({
- type: "step",
- message: `✓ Saved credentials to credential store (backend=${backendList}, host=${osId()}, native=${keyringBackend() || "none"})`,
+ type: 'step',
+ message: `✓ Saved credentials to credential store (backend=${backendList}, host=${osId()}, native=${keyringBackend() || 'none'})`,
backend: backendList,
});
} catch (e) {
emit({
- type: "step",
+ type: 'step',
message: `○ Credential store save failed: ${e.message}`,
});
}
@@ -492,11 +471,8 @@ try {
// Step 2.3: Register MCP server
try {
const pluginRoot =
- process.env.CLAUDE_PLUGIN_ROOT ||
- execSync("echo $CLAUDE_PLUGIN_ROOT", { encoding: "utf8" }).trim();
- const telegramServerPath = pluginRoot
- ? `${pluginRoot}/telegram-server/index.js`
- : null;
+ process.env.CLAUDE_PLUGIN_ROOT || execSync('echo $CLAUDE_PLUGIN_ROOT', { encoding: 'utf8' }).trim();
+ const telegramServerPath = pluginRoot ? `${pluginRoot}/telegram-server/index.js` : null;
if (telegramServerPath) {
execSync(
`claude mcp add telegram -s user` +
@@ -505,17 +481,17 @@ try {
` -e TELEGRAM_PHONE='${PHONE}'` +
` -e TELEGRAM_SESSION='${sessionStr.replace(/'/g, "'\\''")}'` +
` -- node "${telegramServerPath}"`,
- { timeout: 15000, stdio: "pipe" },
+ { timeout: 15000, stdio: 'pipe' },
);
emit({
- type: "step",
- message: "✓ Registered Telegram MCP server in Claude Code",
+ type: 'step',
+ message: '✓ Registered Telegram MCP server in Claude Code',
});
}
} catch {
emit({
- type: "step",
- message: "○ Could not auto-register MCP — run: claude mcp add telegram",
+ type: 'step',
+ message: '○ Could not auto-register MCP — run: claude mcp add telegram',
});
}
@@ -525,5 +501,5 @@ const result = {
phone: PHONE,
session: sessionStr,
};
-process.stdout.write(JSON.stringify(result) + "\n");
+process.stdout.write(JSON.stringify(result) + '\n');
process.exit(0);
diff --git a/claude-ops/lib/credential-store.mjs b/claude-ops/lib/credential-store.mjs
index a3c03660..c54b7e09 100644
--- a/claude-ops/lib/credential-store.mjs
+++ b/claude-ops/lib/credential-store.mjs
@@ -14,26 +14,26 @@
// Override the cascade in tests:
// CLAUDE_OPS_CRED_BACKEND=plaintext-json node ...
-import { spawnSync, spawn } from "node:child_process";
-import { promises as fs, constants as fsConst } from "node:fs";
-import path from "node:path";
-import os from "node:os";
-import crypto from "node:crypto";
-import { fileURLToPath } from "node:url";
+import { spawnSync, spawn } from 'node:child_process';
+import { promises as fs, constants as fsConst } from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import crypto from 'node:crypto';
+import { fileURLToPath } from 'node:url';
-import { osId, keyringBackend } from "./os-detect.mjs";
+import { osId, keyringBackend } from './os-detect.mjs';
// ─── Paths ───────────────────────────────────────────────────────────────────
const DATA_DIR = process.env.XDG_DATA_HOME
- ? path.join(process.env.XDG_DATA_HOME, "claude-ops")
- : path.join(os.homedir(), ".local", "share", "claude-ops");
-const ENC_FILE = path.join(DATA_DIR, "secrets.enc.json");
-const PLAIN_FILE = path.join(DATA_DIR, "secrets.plain.json");
-const MASTERKEY_FILE = path.join(DATA_DIR, ".masterkey");
+ ? path.join(process.env.XDG_DATA_HOME, 'claude-ops')
+ : path.join(os.homedir(), '.local', 'share', 'claude-ops');
+const ENC_FILE = path.join(DATA_DIR, 'secrets.enc.json');
+const PLAIN_FILE = path.join(DATA_DIR, 'secrets.plain.json');
+const MASTERKEY_FILE = path.join(DATA_DIR, '.masterkey');
let __plaintextWarned = false;
-const log = (...args) => console.error("credential-store:", ...args);
+const log = (...args) => console.error('credential-store:', ...args);
async function ensureDataDir() {
await fs.mkdir(DATA_DIR, { recursive: true, mode: 0o700 });
@@ -42,114 +42,69 @@ async function ensureDataDir() {
// ─── 1. OS-native backends ───────────────────────────────────────────────────
function runSync(cmd, args, opts = {}) {
- return spawnSync(cmd, args, { encoding: "utf8", ...opts });
+ return spawnSync(cmd, args, { encoding: 'utf8', ...opts });
}
// --- macOS Keychain (security) ---
function macSet(service, account, secret) {
- const r = runSync("security", [
- "add-generic-password",
- "-U",
- "-s",
- service,
- "-a",
- account,
- "-w",
- secret,
- ]);
+ const r = runSync('security', ['add-generic-password', '-U', '-s', service, '-a', account, '-w', secret]);
return r.status === 0;
}
function macGet(service, account) {
- const r = runSync("security", [
- "find-generic-password",
- "-s",
- service,
- "-a",
- account,
- "-w",
- ]);
- if (r.status === 0) return (r.stdout || "").replace(/\n$/, "");
+ const r = runSync('security', ['find-generic-password', '-s', service, '-a', account, '-w']);
+ if (r.status === 0) return (r.stdout || '').replace(/\n$/, '');
// exit 44 means "not found" — treat as normal
return null;
}
function macDelete(service, account) {
- runSync("security", [
- "delete-generic-password",
- "-s",
- service,
- "-a",
- account,
- ]);
+ runSync('security', ['delete-generic-password', '-s', service, '-a', account]);
return true;
}
// --- Linux libsecret (secret-tool) ---
function hasSecretTool() {
- return runSync("sh", ["-c", "command -v secret-tool"]).status === 0;
+ return runSync('sh', ['-c', 'command -v secret-tool']).status === 0;
}
function stSet(service, account, secret) {
if (!hasSecretTool()) return false;
const r = spawnSync(
- "secret-tool",
- [
- "store",
- "--label=" + service + "/" + account,
- "service",
- service,
- "account",
- account,
- ],
- { input: secret, encoding: "utf8" },
+ 'secret-tool',
+ ['store', '--label=' + service + '/' + account, 'service', service, 'account', account],
+ { input: secret, encoding: 'utf8' },
);
return r.status === 0;
}
function stGet(service, account) {
if (!hasSecretTool()) return null;
- const r = runSync("secret-tool", [
- "lookup",
- "service",
- service,
- "account",
- account,
- ]);
- if (r.status === 0 && r.stdout) return r.stdout.replace(/\n$/, "");
+ const r = runSync('secret-tool', ['lookup', 'service', service, 'account', account]);
+ if (r.status === 0 && r.stdout) return r.stdout.replace(/\n$/, '');
return null;
}
function stDelete(service, account) {
if (!hasSecretTool()) return true;
- runSync("secret-tool", ["clear", "service", service, "account", account]);
+ runSync('secret-tool', ['clear', 'service', service, 'account', account]);
return true;
}
// --- Windows Credential Manager (cmdkey — write-only from CLI) ---
function hasCmd() {
- return (
- runSync("sh", ["-c", "command -v cmd.exe || which cmd.exe"]).status === 0 ||
- process.platform === "win32"
- );
+ return runSync('sh', ['-c', 'command -v cmd.exe || which cmd.exe']).status === 0 || process.platform === 'win32';
}
function wincredSet(service, account, secret) {
if (!hasCmd()) return false;
// Windows: direct invocation; elsewhere: through cmd.exe //c
- if (process.platform === "win32") {
- const r = runSync("cmdkey", [
- "/generic:claude-ops:" + service + ":" + account,
- "/user:" + account,
- "/pass:" + secret,
+ if (process.platform === 'win32') {
+ const r = runSync('cmdkey', [
+ '/generic:claude-ops:' + service + ':' + account,
+ '/user:' + account,
+ '/pass:' + secret,
]);
return r.status === 0;
}
// MSYS/WSL path — shell through cmd.exe
- const r = runSync("cmd.exe", [
- "/c",
- "cmdkey /generic:claude-ops:" +
- service +
- ":" +
- account +
- " /user:" +
- account +
- " /pass:" +
- secret,
+ const r = runSync('cmd.exe', [
+ '/c',
+ 'cmdkey /generic:claude-ops:' + service + ':' + account + ' /user:' + account + ' /pass:' + secret,
]);
return r.status === 0;
}
@@ -159,13 +114,10 @@ function wincredGet(_service, _account) {
}
function wincredDelete(service, account) {
if (!hasCmd()) return true;
- if (process.platform === "win32") {
- runSync("cmdkey", ["/delete:claude-ops:" + service + ":" + account]);
+ if (process.platform === 'win32') {
+ runSync('cmdkey', ['/delete:claude-ops:' + service + ':' + account]);
} else {
- runSync("cmd.exe", [
- "/c",
- "cmdkey /delete:claude-ops:" + service + ":" + account,
- ]);
+ runSync('cmd.exe', ['/c', 'cmdkey /delete:claude-ops:' + service + ':' + account]);
}
return true;
}
@@ -174,9 +126,9 @@ function nativeBackend() {
// Prefer os-detect's answer but fall back to process.platform heuristics
const b = keyringBackend();
if (b) return b;
- if (process.platform === "darwin") return "security";
- if (process.platform === "linux" && hasSecretTool()) return "secret-tool";
- if (process.platform === "win32") return "wincred";
+ if (process.platform === 'darwin') return 'security';
+ if (process.platform === 'linux' && hasSecretTool()) return 'secret-tool';
+ if (process.platform === 'win32') return 'wincred';
return null;
}
@@ -185,7 +137,7 @@ let __keytarCache;
async function loadKeytar() {
if (__keytarCache !== undefined) return __keytarCache;
try {
- const mod = await import("keytar");
+ const mod = await import('keytar');
__keytarCache = mod.default || mod;
} catch {
__keytarCache = null;
@@ -224,13 +176,12 @@ async function keytarDelete(service, account) {
// ─── 3. Encrypted JSON (AES-256-GCM) ─────────────────────────────────────────
async function masterKey() {
- if (process.env.CLAUDE_OPS_MASTER_KEY)
- return process.env.CLAUDE_OPS_MASTER_KEY;
+ if (process.env.CLAUDE_OPS_MASTER_KEY) return process.env.CLAUDE_OPS_MASTER_KEY;
await ensureDataDir();
try {
- return (await fs.readFile(MASTERKEY_FILE, "utf8")).trim();
+ return (await fs.readFile(MASTERKEY_FILE, 'utf8')).trim();
} catch {
- const key = crypto.randomBytes(32).toString("base64");
+ const key = crypto.randomBytes(32).toString('base64');
await fs.writeFile(MASTERKEY_FILE, key, { mode: 0o600 });
return key;
}
@@ -238,17 +189,17 @@ async function masterKey() {
async function readJson(file) {
try {
- const raw = await fs.readFile(file, "utf8");
+ const raw = await fs.readFile(file, 'utf8');
return JSON.parse(raw);
} catch (e) {
- if (e.code === "ENOENT") return {};
+ if (e.code === 'ENOENT') return {};
throw e;
}
}
async function writeJson(file, obj) {
await ensureDataDir();
- const tmp = file + ".tmp." + process.pid;
+ const tmp = file + '.tmp.' + process.pid;
await fs.writeFile(tmp, JSON.stringify(obj, null, 2), { mode: 0o600 });
await fs.rename(tmp, file);
await fs.chmod(file, 0o600);
@@ -258,28 +209,28 @@ function encrypt(plaintext, keyB64) {
const salt = crypto.randomBytes(16);
const iv = crypto.randomBytes(12);
const key = crypto.scryptSync(keyB64, salt, 32);
- const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
- const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
+ const ct = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return {
- iv: iv.toString("base64"),
- salt: salt.toString("base64"),
- tag: tag.toString("base64"),
- ct: ct.toString("base64"),
+ iv: iv.toString('base64'),
+ salt: salt.toString('base64'),
+ tag: tag.toString('base64'),
+ ct: ct.toString('base64'),
};
}
function decrypt(entry, keyB64) {
try {
- const salt = Buffer.from(entry.salt, "base64");
- const iv = Buffer.from(entry.iv, "base64");
- const tag = Buffer.from(entry.tag, "base64");
- const ct = Buffer.from(entry.ct, "base64");
+ const salt = Buffer.from(entry.salt, 'base64');
+ const iv = Buffer.from(entry.iv, 'base64');
+ const tag = Buffer.from(entry.tag, 'base64');
+ const ct = Buffer.from(entry.ct, 'base64');
const key = crypto.scryptSync(keyB64, salt, 32);
- const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(tag);
const pt = Buffer.concat([decipher.update(ct), decipher.final()]);
- return pt.toString("utf8");
+ return pt.toString('utf8');
} catch {
return null;
}
@@ -291,21 +242,21 @@ async function encJsonSet(service, account, secret) {
entry.service = service;
entry.account = account;
const store = await readJson(ENC_FILE);
- store[service + "/" + account] = entry;
+ store[service + '/' + account] = entry;
await writeJson(ENC_FILE, store);
return true;
}
async function encJsonGet(service, account) {
- const key = service + "/" + account;
+ const key = service + '/' + account;
const store = await readJson(ENC_FILE);
if (!store[key]) return null;
const k = await masterKey();
const pt = decrypt(store[key], k);
- if (pt === null) log("decrypt failed for enc-json/" + key);
+ if (pt === null) log('decrypt failed for enc-json/' + key);
return pt;
}
async function encJsonDelete(service, account) {
- const key = service + "/" + account;
+ const key = service + '/' + account;
const store = await readJson(ENC_FILE);
if (store[key]) {
delete store[key];
@@ -318,24 +269,22 @@ async function encJsonDelete(service, account) {
function plaintextWarnOnce() {
if (__plaintextWarned) return;
__plaintextWarned = true;
- log(
- "⚠ using plaintext JSON fallback — install secret-tool (linux) or cmdkey (windows) for better security",
- );
+ log('⚠ using plaintext JSON fallback — install secret-tool (linux) or cmdkey (windows) for better security');
}
async function plainSet(service, account, secret) {
plaintextWarnOnce();
const store = await readJson(PLAIN_FILE);
- store[service + "/" + account] = secret;
+ store[service + '/' + account] = secret;
await writeJson(PLAIN_FILE, store);
return true;
}
async function plainGet(service, account) {
const store = await readJson(PLAIN_FILE);
- return store[service + "/" + account] ?? null;
+ return store[service + '/' + account] ?? null;
}
async function plainDelete(service, account) {
const store = await readJson(PLAIN_FILE);
- const key = service + "/" + account;
+ const key = service + '/' + account;
if (store[key]) {
delete store[key];
await writeJson(PLAIN_FILE, store);
@@ -353,9 +302,9 @@ export async function backendsAvailable() {
const backends = [];
const nb = nativeBackend();
if (nb) backends.push(nb);
- if (await loadKeytar()) backends.push("keytar");
- backends.push("enc-json");
- backends.push("plaintext-json");
+ if (await loadKeytar()) backends.push('keytar');
+ backends.push('enc-json');
+ backends.push('plaintext-json');
return backends;
}
@@ -368,43 +317,43 @@ export async function setCredential(service, account, secret) {
const tryBackend = async (name) => {
let ok = false;
switch (name) {
- case "security":
+ case 'security':
ok = macSet(service, account, secret);
break;
- case "secret-tool":
+ case 'secret-tool':
ok = stSet(service, account, secret);
break;
- case "wincred":
+ case 'wincred':
ok = wincredSet(service, account, secret);
break;
- case "keytar":
+ case 'keytar':
ok = await keytarSet(service, account, secret);
break;
- case "enc-json":
+ case 'enc-json':
ok = await encJsonSet(service, account, secret);
break;
- case "plaintext-json":
+ case 'plaintext-json':
ok = await plainSet(service, account, secret);
break;
}
- if (ok) log("stored via=" + name);
+ if (ok) log('stored via=' + name);
return ok;
};
if (forced) {
const ok = await tryBackend(forced);
- if (!ok) log("forced backend=" + forced + " failed");
+ if (!ok) log('forced backend=' + forced + ' failed');
return { backend: forced, ok };
}
const cascade = [];
const nb = nativeBackend();
if (nb) cascade.push(nb);
- cascade.push("keytar", "enc-json", "plaintext-json");
+ cascade.push('keytar', 'enc-json', 'plaintext-json');
for (const name of cascade) {
if (await tryBackend(name)) return { backend: name, ok: true };
}
- log("all backends failed");
+ log('all backends failed');
return { backend: null, ok: false };
}
@@ -417,22 +366,22 @@ export async function getCredential(service, account) {
const tryBackend = async (name) => {
let v = null;
switch (name) {
- case "security":
+ case 'security':
v = macGet(service, account);
break;
- case "secret-tool":
+ case 'secret-tool':
v = stGet(service, account);
break;
- case "wincred":
+ case 'wincred':
v = wincredGet(service, account);
break;
- case "keytar":
+ case 'keytar':
v = await keytarGet(service, account);
break;
- case "enc-json":
+ case 'enc-json':
v = await encJsonGet(service, account);
break;
- case "plaintext-json":
+ case 'plaintext-json':
v = await plainGet(service, account);
break;
}
@@ -444,7 +393,7 @@ export async function getCredential(service, account) {
const cascade = [];
const nb = nativeBackend();
if (nb) cascade.push(nb);
- cascade.push("keytar", "enc-json", "plaintext-json");
+ cascade.push('keytar', 'enc-json', 'plaintext-json');
for (const name of cascade) {
const hit = await tryBackend(name);
if (hit) return hit;
@@ -460,36 +409,36 @@ export async function deleteCredential(service, account) {
const deletedFrom = [];
const nb = nativeBackend();
try {
- if (nb === "security") {
+ if (nb === 'security') {
macDelete(service, account);
- deletedFrom.push("security");
+ deletedFrom.push('security');
}
- if (nb === "secret-tool") {
+ if (nb === 'secret-tool') {
stDelete(service, account);
- deletedFrom.push("secret-tool");
+ deletedFrom.push('secret-tool');
}
- if (nb === "wincred") {
+ if (nb === 'wincred') {
wincredDelete(service, account);
- deletedFrom.push("wincred");
+ deletedFrom.push('wincred');
}
} catch {
/* ignore */
}
try {
await keytarDelete(service, account);
- deletedFrom.push("keytar");
+ deletedFrom.push('keytar');
} catch {
/* ignore */
}
try {
await encJsonDelete(service, account);
- deletedFrom.push("enc-json");
+ deletedFrom.push('enc-json');
} catch {
/* ignore */
}
try {
await plainDelete(service, account);
- deletedFrom.push("plaintext-json");
+ deletedFrom.push('plaintext-json');
} catch {
/* ignore */
}
@@ -511,63 +460,63 @@ if (isCli) {
const [, , sub, ...rest] = process.argv;
const dispatch = async () => {
switch (sub) {
- case "set": {
+ case 'set': {
const [service, account, secret] = rest;
const r = await setCredential(service, account, secret);
process.exit(r.ok ? 0 : 1);
}
- case "get": {
+ case 'get': {
const [service, account] = rest;
const r = await getCredential(service, account);
if (!r) process.exit(1);
process.stdout.write(r.secret);
process.exit(0);
}
- case "delete": {
+ case 'delete': {
const [service, account] = rest;
await deleteCredential(service, account);
process.exit(0);
}
- case "backends": {
+ case 'backends': {
const r = await backendsAvailable();
- process.stdout.write(r.join(" ") + "\n");
+ process.stdout.write(r.join(' ') + '\n');
process.exit(0);
}
- case "backend-for": {
+ case 'backend-for': {
const [service, account] = rest;
const r = await backendFor(service, account);
if (!r) process.exit(1);
- process.stdout.write(r + "\n");
+ process.stdout.write(r + '\n');
process.exit(0);
}
// Helpers called by lib/credential-store.sh
- case "set-keytar": {
+ case 'set-keytar': {
const [service, account, secret] = rest;
const ok = await keytarSet(service, account, secret);
process.exit(ok ? 0 : 1);
}
- case "get-keytar": {
+ case 'get-keytar': {
const [service, account] = rest;
const v = await keytarGet(service, account);
if (v == null) process.exit(1);
process.stdout.write(v);
process.exit(0);
}
- case "delete-keytar": {
+ case 'delete-keytar': {
const [service, account] = rest;
await keytarDelete(service, account);
process.exit(0);
}
default: {
process.stderr.write(
- "usage: credential-store.mjs {set|get|delete|backends|backend-for|set-keytar|get-keytar|delete-keytar} ...\n",
+ 'usage: credential-store.mjs {set|get|delete|backends|backend-for|set-keytar|get-keytar|delete-keytar} ...\n',
);
process.exit(2);
}
}
};
dispatch().catch((e) => {
- log("fatal:", e.message);
+ log('fatal:', e.message);
process.exit(1);
});
}
diff --git a/claude-ops/lib/opener.mjs b/claude-ops/lib/opener.mjs
index 155ca0ea..4fe9923b 100644
--- a/claude-ops/lib/opener.mjs
+++ b/claude-ops/lib/opener.mjs
@@ -22,10 +22,10 @@
// string is `start`'s title placeholder; without it, a path/URL
// containing spaces gets eaten as the window title.
-import { spawn, spawnSync } from "node:child_process";
-import { promises as fsp } from "node:fs";
-import process from "node:process";
-import { osId, opener } from "./os-detect.mjs";
+import { spawn, spawnSync } from 'node:child_process';
+import { promises as fsp } from 'node:fs';
+import process from 'node:process';
+import { osId, opener } from './os-detect.mjs';
// ---------------------------------------------------------------------------
// Internal helpers
@@ -39,12 +39,12 @@ import { osId, opener } from "./os-detect.mjs";
*/
function hasBin(name) {
try {
- if (process.platform === "win32") {
- return spawnSync("where.exe", [name], { stdio: "ignore" }).status === 0;
+ if (process.platform === 'win32') {
+ return spawnSync('where.exe', [name], { stdio: 'ignore' }).status === 0;
}
return (
- spawnSync("/bin/sh", ["-c", `command -v ${name}`], {
- stdio: "ignore",
+ spawnSync('/bin/sh', ['-c', `command -v ${name}`], {
+ stdio: 'ignore',
}).status === 0
);
} catch {
@@ -61,10 +61,10 @@ function resolveOpener() {
const detected = opener();
if (detected) return detected;
- if (hasBin("open")) return "open";
- if (hasBin("wslview")) return "wslview";
- if (hasBin("xdg-open")) return "xdg-open";
- if (hasBin("cmd.exe")) return "cmd.exe /c start";
+ if (hasBin('open')) return 'open';
+ if (hasBin('wslview')) return 'wslview';
+ if (hasBin('xdg-open')) return 'xdg-open';
+ if (hasBin('cmd.exe')) return 'cmd.exe /c start';
return null;
}
@@ -101,13 +101,13 @@ function logOpen(cmd, target) {
*/
export async function openTarget(target) {
if (!target) {
- process.stderr.write("opener: missing target\n");
- return { ok: false, command: null, target: "" };
+ process.stderr.write('opener: missing target\n');
+ return { ok: false, command: null, target: '' };
}
const cmd = resolveOpener();
if (!cmd) {
- process.stderr.write("opener: no URL opener available on this host\n");
+ process.stderr.write('opener: no URL opener available on this host\n');
return { ok: false, command: null, target };
}
@@ -115,15 +115,12 @@ export async function openTarget(target) {
try {
// Windows: always use `cmd.exe /c start "" <target>` with the empty title.
- const isWindowsStart =
- cmd === "cmd.exe /c start" ||
- osId() === "windows" ||
- process.platform === "win32";
+ const isWindowsStart = cmd === 'cmd.exe /c start' || osId() === 'windows' || process.platform === 'win32';
- if (isWindowsStart && cmd.includes("start")) {
- const child = spawn("cmd.exe", ["/c", "start", "", target], {
+ if (isWindowsStart && cmd.includes('start')) {
+ const child = spawn('cmd.exe', ['/c', 'start', '', target], {
detached: true,
- stdio: "ignore",
+ stdio: 'ignore',
windowsVerbatimArguments: false,
});
child.unref();
@@ -137,7 +134,7 @@ export async function openTarget(target) {
const [program, extraArgs] = split;
const child = spawn(program, [...extraArgs, target], {
detached: true,
- stdio: "ignore",
+ stdio: 'ignore',
});
child.unref();
return { ok: true, command: cmd, target };
@@ -154,8 +151,8 @@ export async function openTarget(target) {
*/
export async function openUrl(url) {
if (!url) {
- process.stderr.write("opener: missing url\n");
- return { ok: false, command: null, target: "" };
+ process.stderr.write('opener: missing url\n');
+ return { ok: false, command: null, target: '' };
}
if (!/^https?:\/\/|^mailto:|^tel:/.test(url)) {
process.stderr.write(`opener: refusing to open non-URL scheme: ${url}\n`);
@@ -171,8 +168,8 @@ export async function openUrl(url) {
*/
export async function openDir(pathStr) {
if (!pathStr) {
- process.stderr.write("opener: missing directory path\n");
- return { ok: false, command: null, target: "" };
+ process.stderr.write('opener: missing directory path\n');
+ return { ok: false, command: null, target: '' };
}
try {
const st = await fsp.stat(pathStr);
@@ -191,25 +188,24 @@ export async function openDir(pathStr) {
// CLI entry
// ---------------------------------------------------------------------------
-const invokedDirectly =
- process.argv[1] && import.meta.url === `file://${process.argv[1]}`;
+const invokedDirectly = process.argv[1] && import.meta.url === `file://${process.argv[1]}`;
if (invokedDirectly) {
const [, , sub, ...rest] = process.argv;
- const target = rest[0] || "";
+ const target = rest[0] || '';
let result;
switch (sub) {
- case "open":
+ case 'open':
result = await openTarget(target);
break;
- case "url":
+ case 'url':
result = await openUrl(target);
break;
- case "dir":
+ case 'dir':
result = await openDir(target);
break;
default:
- process.stderr.write("usage: opener.mjs {open|url|dir} <target>\n");
+ process.stderr.write('usage: opener.mjs {open|url|dir} <target>\n');
process.exit(2);
}
process.exit(result.ok ? 0 : 1);
diff --git a/claude-ops/lib/os-detect.mjs b/claude-ops/lib/os-detect.mjs
index 96bb9366..52e0f06d 100644
--- a/claude-ops/lib/os-detect.mjs
+++ b/claude-ops/lib/os-detect.mjs
@@ -13,12 +13,12 @@
// - Never throw on missing files — degrade to null/false/[]
// - Runnable directly (`node lib/os-detect.mjs`) for debugging
-import { readFileSync, promises as fsp } from "node:fs";
-import { spawnSync } from "node:child_process";
-import { homedir } from "node:os";
-import path from "node:path";
-import process from "node:process";
-import { fileURLToPath } from "node:url";
+import { readFileSync, promises as fsp } from 'node:fs';
+import { spawnSync } from 'node:child_process';
+import { homedir } from 'node:os';
+import path from 'node:path';
+import process from 'node:process';
+import { fileURLToPath } from 'node:url';
// ---------------------------------------------------------------------------
// Internal helpers
@@ -32,9 +32,9 @@ import { fileURLToPath } from "node:url";
*/
function safeRead(p) {
try {
- return readFileSync(p, "utf8");
+ return readFileSync(p, 'utf8');
} catch {
- return "";
+ return '';
}
}
@@ -47,17 +47,14 @@ function safeRead(p) {
function parseEnvFile(contents) {
/** @type {Record<string, string>} */
const out = {};
- for (const rawLine of contents.split("\n")) {
+ for (const rawLine of contents.split('\n')) {
const line = rawLine.trim();
- if (!line || line.startsWith("#")) continue;
- const eq = line.indexOf("=");
+ if (!line || line.startsWith('#')) continue;
+ const eq = line.indexOf('=');
if (eq < 0) continue;
const key = line.slice(0, eq).trim();
let value = line.slice(eq + 1).trim();
- if (
- (value.startsWith('"') && value.endsWith('"')) ||
- (value.startsWith("'") && value.endsWith("'"))
- ) {
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
out[key] = value;
@@ -74,12 +71,12 @@ function parseEnvFile(contents) {
*/
function hasBin(name) {
try {
- if (process.platform === "win32") {
- const r = spawnSync("where.exe", [name], { stdio: "ignore" });
+ if (process.platform === 'win32') {
+ const r = spawnSync('where.exe', [name], { stdio: 'ignore' });
return r.status === 0;
}
- const r = spawnSync("/bin/sh", ["-c", `command -v ${name}`], {
- stdio: "ignore",
+ const r = spawnSync('/bin/sh', ['-c', `command -v ${name}`], {
+ stdio: 'ignore',
});
return r.status === 0;
} catch {
@@ -97,9 +94,9 @@ function hasBin(name) {
* @returns {boolean}
*/
export function isWsl() {
- if (process.platform !== "linux") return false;
- const procVersion = safeRead("/proc/version").toLowerCase();
- return procVersion.includes("microsoft");
+ if (process.platform !== 'linux') return false;
+ const procVersion = safeRead('/proc/version').toLowerCase();
+ return procVersion.includes('microsoft');
}
/**
@@ -107,33 +104,27 @@ export function isWsl() {
* @returns {"macos"|"debian"|"fedora"|"arch"|"suse"|"alpine"|"linux"|"wsl"|"windows"|"unknown"}
*/
export function osId() {
- if (process.platform === "darwin") return "macos";
- if (process.platform === "win32") return "windows";
- if (process.platform !== "linux") return "unknown";
+ if (process.platform === 'darwin') return 'macos';
+ if (process.platform === 'win32') return 'windows';
+ if (process.platform !== 'linux') return 'unknown';
- if (isWsl()) return "wsl";
+ if (isWsl()) return 'wsl';
- const release = parseEnvFile(safeRead("/etc/os-release"));
- const candidates = [release.ID, ...(release.ID_LIKE || "").split(/\s+/)]
- .map((s) => (s || "").toLowerCase())
+ const release = parseEnvFile(safeRead('/etc/os-release'));
+ const candidates = [release.ID, ...(release.ID_LIKE || '').split(/\s+/)]
+ .map((s) => (s || '').toLowerCase())
.filter(Boolean);
for (const id of candidates) {
- if (id === "debian" || id === "ubuntu") return "debian";
- if (
- id === "fedora" ||
- id === "rhel" ||
- id === "centos" ||
- id === "rocky" ||
- id === "almalinux"
- ) {
- return "fedora";
+ if (id === 'debian' || id === 'ubuntu') return 'debian';
+ if (id === 'fedora' || id === 'rhel' || id === 'centos' || id === 'rocky' || id === 'almalinux') {
+ return 'fedora';
}
- if (id === "arch" || id === "manjaro") return "arch";
- if (id.startsWith("opensuse") || id === "sles") return "suse";
- if (id === "alpine") return "alpine";
+ if (id === 'arch' || id === 'manjaro') return 'arch';
+ if (id.startsWith('opensuse') || id === 'sles') return 'suse';
+ if (id === 'alpine') return 'alpine';
}
- return "linux";
+ return 'linux';
}
/**
@@ -142,16 +133,16 @@ export function osId() {
*/
export function arch() {
switch (process.arch) {
- case "x64":
- return "x86_64";
- case "arm64":
- return "arm64";
- case "arm":
- return "armv7";
- case "ia32":
- return "i686";
+ case 'x64':
+ return 'x86_64';
+ case 'arm64':
+ return 'arm64';
+ case 'arm':
+ return 'armv7';
+ case 'ia32':
+ return 'i686';
default:
- return "unknown";
+ return 'unknown';
}
}
@@ -163,16 +154,16 @@ export function arch() {
*/
export function pkgMgr() {
// Homebrew wins everywhere it's installed (macOS and Linuxbrew).
- if (hasBin("brew")) return "brew";
+ if (hasBin('brew')) return 'brew';
- if (process.platform === "linux") {
- for (const m of ["apt-get", "dnf", "pacman", "zypper", "apk"]) {
+ if (process.platform === 'linux') {
+ for (const m of ['apt-get', 'dnf', 'pacman', 'zypper', 'apk']) {
if (hasBin(m)) return m;
}
}
- if (process.platform === "win32") {
- for (const m of ["winget", "scoop", "choco"]) {
+ if (process.platform === 'win32') {
+ for (const m of ['winget', 'scoop', 'choco']) {
if (hasBin(m)) return m;
}
}
@@ -189,23 +180,23 @@ export function pkgMgr() {
export function pkgInstallCmd(pkg) {
const mgr = pkgMgr();
switch (mgr) {
- case "brew":
+ case 'brew':
return `brew install ${pkg}`;
- case "apt-get":
+ case 'apt-get':
return `sudo apt-get install -y ${pkg}`;
- case "dnf":
+ case 'dnf':
return `sudo dnf install -y ${pkg}`;
- case "pacman":
+ case 'pacman':
return `sudo pacman -S --noconfirm ${pkg}`;
- case "zypper":
+ case 'zypper':
return `sudo zypper install -y ${pkg}`;
- case "apk":
+ case 'apk':
return `sudo apk add ${pkg}`;
- case "winget":
+ case 'winget':
return `winget install -e --id ${pkg}`;
- case "scoop":
+ case 'scoop':
return `scoop install ${pkg}`;
- case "choco":
+ case 'choco':
return `choco install -y ${pkg}`;
default:
return null;
@@ -220,11 +211,10 @@ export function pkgInstallCmd(pkg) {
* @returns {"security"|"secret-tool"|"wincred"|null}
*/
export function keyringBackend() {
- if (process.platform === "darwin") return "security";
- if (process.platform === "win32") return "wincred";
- if (isWsl() && hasBin("cmd.exe")) return "wincred";
- if (process.platform === "linux" && hasBin("secret-tool"))
- return "secret-tool";
+ if (process.platform === 'darwin') return 'security';
+ if (process.platform === 'win32') return 'wincred';
+ if (isWsl() && hasBin('cmd.exe')) return 'wincred';
+ if (process.platform === 'linux' && hasBin('secret-tool')) return 'secret-tool';
return null;
}
@@ -233,13 +223,13 @@ export function keyringBackend() {
* @returns {"open"|"xdg-open"|"wslview"|"cmd.exe /c start"|null}
*/
export function opener() {
- if (process.platform === "darwin") return "open";
- if (process.platform === "win32") return "cmd.exe /c start";
+ if (process.platform === 'darwin') return 'open';
+ if (process.platform === 'win32') return 'cmd.exe /c start';
if (isWsl()) {
- if (hasBin("wslview")) return "wslview";
- if (hasBin("cmd.exe")) return "cmd.exe /c start";
+ if (hasBin('wslview')) return 'wslview';
+ if (hasBin('cmd.exe')) return 'cmd.exe /c start';
}
- if (hasBin("xdg-open")) return "xdg-open";
+ if (hasBin('xdg-open')) return 'xdg-open';
return null;
}
@@ -250,8 +240,8 @@ export function opener() {
export function shell() {
const s = process.env.SHELL;
if (s) return path.basename(s);
- if (process.platform === "win32") return "pwsh";
- return "bash";
+ if (process.platform === 'win32') return 'pwsh';
+ return 'bash';
}
// ---------------------------------------------------------------------------
@@ -268,44 +258,42 @@ export async function browserProfileDirs() {
/** @type {string[]} */
const candidates = [];
- if (process.platform === "darwin") {
- const sup = path.join(home, "Library", "Application Support");
+ if (process.platform === 'darwin') {
+ const sup = path.join(home, 'Library', 'Application Support');
candidates.push(
- path.join(sup, "Google", "Chrome"),
- path.join(sup, "Chromium"),
- path.join(sup, "BraveSoftware", "Brave-Browser"),
- path.join(sup, "Arc", "User Data"),
+ path.join(sup, 'Google', 'Chrome'),
+ path.join(sup, 'Chromium'),
+ path.join(sup, 'BraveSoftware', 'Brave-Browser'),
+ path.join(sup, 'Arc', 'User Data'),
);
- } else if (process.platform === "linux") {
- const config = path.join(home, ".config");
+ } else if (process.platform === 'linux') {
+ const config = path.join(home, '.config');
candidates.push(
- path.join(config, "google-chrome"),
- path.join(config, "chromium"),
- path.join(config, "BraveSoftware", "Brave-Browser"),
+ path.join(config, 'google-chrome'),
+ path.join(config, 'chromium'),
+ path.join(config, 'BraveSoftware', 'Brave-Browser'),
);
// On WSL, also probe the Windows-side profile under /mnt/c.
if (isWsl()) {
- const winUser = process.env.USER || process.env.USERNAME || "";
+ const winUser = process.env.USER || process.env.USERNAME || '';
if (winUser) {
const winLocal = `/mnt/c/Users/${winUser}/AppData/Local`;
candidates.push(
- path.join(winLocal, "Google", "Chrome", "User Data"),
- path.join(winLocal, "Chromium", "User Data"),
- path.join(winLocal, "BraveSoftware", "Brave-Browser", "User Data"),
+ path.join(winLocal, 'Google', 'Chrome', 'User Data'),
+ path.join(winLocal, 'Chromium', 'User Data'),
+ path.join(winLocal, 'BraveSoftware', 'Brave-Browser', 'User Data'),
);
}
}
- } else if (process.platform === "win32") {
+ } else if (process.platform === 'win32') {
const localAppData =
process.env.LOCALAPPDATA ||
- (process.env.USERPROFILE
- ? path.join(process.env.USERPROFILE, "AppData", "Local")
- : "");
+ (process.env.USERPROFILE ? path.join(process.env.USERPROFILE, 'AppData', 'Local') : '');
if (localAppData) {
candidates.push(
- path.join(localAppData, "Google", "Chrome", "User Data"),
- path.join(localAppData, "Chromium", "User Data"),
- path.join(localAppData, "BraveSoftware", "Brave-Browser", "User Data"),
+ path.join(localAppData, 'Google', 'Chrome', 'User Data'),
+ path.join(localAppData, 'Chromium', 'User Data'),
+ path.join(localAppData, 'BraveSoftware', 'Brave-Browser', 'User Data'),
);
}
}
@@ -338,10 +326,10 @@ export async function browserProfileDirs() {
* }>}
*/
export async function osJson() {
- const release = parseEnvFile(safeRead("/etc/os-release"));
+ const release = parseEnvFile(safeRead('/etc/os-release'));
return {
os: osId(),
- distro_id: release.ID || "",
+ distro_id: release.ID || '',
arch: arch(),
pkg_mgr: pkgMgr(),
keyring_backend: keyringBackend(),
@@ -356,19 +344,14 @@ export async function osJson() {
// CLI entrypoint: `node lib/os-detect.mjs` prints the full JSON report.
// ---------------------------------------------------------------------------
-const invokedDirectly =
- process.argv[1] && import.meta.url === `file://${process.argv[1]}`;
+const invokedDirectly = process.argv[1] && import.meta.url === `file://${process.argv[1]}`;
// Also handle symlinks and realpath differences that can trip the naive check.
const invokedViaRealpath =
process.argv[1] &&
- import.meta.url ===
- `file://${fileURLToPath(import.meta.url)}`.replace(
- /^file:\/\//,
- "file://",
- ) &&
- process.argv[1].endsWith("os-detect.mjs");
+ import.meta.url === `file://${fileURLToPath(import.meta.url)}`.replace(/^file:\/\//, 'file://') &&
+ process.argv[1].endsWith('os-detect.mjs');
if (invokedDirectly || invokedViaRealpath) {
const obj = await osJson();
- process.stdout.write(JSON.stringify(obj, null, 2) + "\n");
+ process.stdout.write(JSON.stringify(obj, null, 2) + '\n');
}
diff --git a/claude-ops/scripts/registry.example.json b/claude-ops/scripts/registry.example.json
index a12efef5..19d0f43f 100644
--- a/claude-ops/scripts/registry.example.json
+++ b/claude-ops/scripts/registry.example.json
@@ -21,16 +21,8 @@
},
{
"alias": "example-multi-repo",
- "paths": [
- "~/Projects/example-api",
- "~/Projects/example-web",
- "~/Projects/example-mobile"
- ],
- "repos": [
- "your-github-org/example-api",
- "your-github-org/example-web",
- "your-github-org/example-mobile"
- ],
+ "paths": ["~/Projects/example-api", "~/Projects/example-web", "~/Projects/example-mobile"],
+ "repos": ["your-github-org/example-api", "your-github-org/example-web", "your-github-org/example-mobile"],
"org": "your-github-org",
"type": "multi-repo",
"infra": {
diff --git a/claude-ops/telegram-server/auth-with-chat-db.mjs b/claude-ops/telegram-server/auth-with-chat-db.mjs
index 633dec61..8e4a28af 100644
--- a/claude-ops/telegram-server/auth-with-chat-db.mjs
+++ b/claude-ops/telegram-server/auth-with-chat-db.mjs
@@ -1,24 +1,24 @@
#!/usr/bin/env node
// Auto-auth: read Telegram code from /tmp/telegram-code.txt (file-based input).
-import { TelegramClient } from "telegram";
-import { StringSession } from "telegram/sessions/index.js";
-import { readFileSync, writeFileSync, existsSync, unlinkSync } from "node:fs";
+import { TelegramClient } from 'telegram';
+import { StringSession } from 'telegram/sessions/index.js';
+import { readFileSync, writeFileSync, existsSync, unlinkSync } from 'node:fs';
const API_ID = parseInt(process.env.TELEGRAM_API_ID, 10);
const API_HASH = process.env.TELEGRAM_API_HASH;
const PHONE = process.env.TELEGRAM_PHONE;
-const CODE_FILE = "/tmp/telegram-code.txt";
+const CODE_FILE = '/tmp/telegram-code.txt';
if (existsSync(CODE_FILE)) unlinkSync(CODE_FILE);
if (!API_ID || !API_HASH || !PHONE) {
- console.error("missing env");
+ console.error('missing env');
process.exit(1);
}
function readFileCode() {
if (existsSync(CODE_FILE)) {
- const c = readFileSync(CODE_FILE, "utf8").trim();
+ const c = readFileSync(CODE_FILE, 'utf8').trim();
if (/^\d{4,8}$/.test(c)) return c;
}
return null;
@@ -34,17 +34,15 @@ async function waitForCode(maxSec = 180) {
return code;
}
if (Date.now() - lastLog > 10000) {
- console.error(
- `waiting for code — write to ${CODE_FILE} (${Math.floor((Date.now() - start) / 1000)}s)`,
- );
+ console.error(`waiting for code — write to ${CODE_FILE} (${Math.floor((Date.now() - start) / 1000)}s)`);
lastLog = Date.now();
}
await new Promise((r) => setTimeout(r, 2000));
}
- throw new Error("timeout");
+ throw new Error('timeout');
}
-const stringSession = new StringSession("");
+const stringSession = new StringSession('');
const client = new TelegramClient(stringSession, API_ID, API_HASH, {
connectionRetries: 5,
baseLogger: {
@@ -59,29 +57,29 @@ const client = new TelegramClient(stringSession, API_ID, API_HASH, {
await client.start({
phoneNumber: async () => PHONE,
password: async () => {
- console.error("2FA: empty");
- return "";
+ console.error('2FA: empty');
+ return '';
},
phoneCode: async () => {
- console.error("Telegram sent code; waiting for /tmp/telegram-code.txt");
+ console.error('Telegram sent code; waiting for /tmp/telegram-code.txt');
return await waitForCode(180);
},
- onError: (err) => console.error("auth err:", err.message),
+ onError: (err) => console.error('auth err:', err.message),
});
const saved = client.session.save();
-console.log("=== SESSION STRING ===");
+console.log('=== SESSION STRING ===');
console.log(saved);
-console.log("=== END ===");
+console.log('=== END ===');
// 0o600: /tmp is world-readable on macOS (drwxrwxrwt). Without this mode
// any local process could read the session string during the window between
// write and whoever reads it next.
-writeFileSync("/tmp/telegram-session.txt", saved, { mode: 0o600 });
+writeFileSync('/tmp/telegram-session.txt', saved, { mode: 0o600 });
// writeFileSync mode only applies to NEW files; if it already existed,
// chmod explicitly.
try {
- (await import("node:fs")).chmodSync("/tmp/telegram-session.txt", 0o600);
+ (await import('node:fs')).chmodSync('/tmp/telegram-session.txt', 0o600);
} catch {}
-console.error("session saved to /tmp/telegram-session.txt (0600)");
+console.error('session saved to /tmp/telegram-session.txt (0600)');
await client.disconnect();
process.exit(0);
diff --git a/claude-ops/telegram-server/index.js b/claude-ops/telegram-server/index.js
index 5c403196..8e4d5517 100644
--- a/claude-ops/telegram-server/index.js
+++ b/claude-ops/telegram-server/index.js
@@ -22,56 +22,51 @@
* search_messages — full-text search across all chats
*/
-import { Server } from "@modelcontextprotocol/sdk/server/index.js";
-import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
-import {
- CallToolRequestSchema,
- ListToolsRequestSchema,
-} from "@modelcontextprotocol/sdk/types.js";
-import { TelegramClient } from "telegram";
-import { StringSession } from "telegram/sessions/index.js";
-import readline from "node:readline/promises";
-import { stdin as input, stdout as output } from "node:process";
+import { Server } from '@modelcontextprotocol/sdk/server/index.js';
+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
+import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
+import { TelegramClient } from 'telegram';
+import { StringSession } from 'telegram/sessions/index.js';
+import readline from 'node:readline/promises';
+import { stdin as input, stdout as output } from 'node:process';
-const API_ID = parseInt(process.env.TELEGRAM_API_ID || "0", 10);
-const API_HASH = process.env.TELEGRAM_API_HASH || "";
-const SESSION_STRING = process.env.TELEGRAM_SESSION || "";
-const PHONE = process.env.TELEGRAM_PHONE || "";
+const API_ID = parseInt(process.env.TELEGRAM_API_ID || '0', 10);
+const API_HASH = process.env.TELEGRAM_API_HASH || '';
+const SESSION_STRING = process.env.TELEGRAM_SESSION || '';
+const PHONE = process.env.TELEGRAM_PHONE || '';
// Detect whether credentials are present — server always starts regardless
const CONFIGURED = !!(API_ID && API_HASH && SESSION_STRING);
-const NOT_CONFIGURED_MSG =
- "Telegram not configured. Run /ops:setup telegram to set up your credentials.";
+const NOT_CONFIGURED_MSG = 'Telegram not configured. Run /ops:setup telegram to set up your credentials.';
let client = null;
if (CONFIGURED) {
// First-run interactive auth mode (only when creds are available)
- if (process.argv.includes("--auth")) {
+ if (process.argv.includes('--auth')) {
const stringSession = new StringSession(SESSION_STRING);
const authClient = new TelegramClient(stringSession, API_ID, API_HASH, {
connectionRetries: 5,
baseLogger: {
log: () => {},
warn: () => {},
- error: (...args) => process.stderr.write(args.join(" ") + "\n"),
+ error: (...args) => process.stderr.write(args.join(' ') + '\n'),
info: () => {},
debug: () => {},
},
});
const rl = readline.createInterface({ input, output });
await authClient.start({
- phoneNumber: async () =>
- PHONE || (await rl.question("Phone number (E.164): ")),
- password: async () => await rl.question("2FA password (blank if none): "),
- phoneCode: async () => await rl.question("SMS code: "),
+ phoneNumber: async () => PHONE || (await rl.question('Phone number (E.164): ')),
+ password: async () => await rl.question('2FA password (blank if none): '),
+ phoneCode: async () => await rl.question('SMS code: '),
onError: (err) => process.stderr.write(`Auth error: ${err.message}\n`),
});
rl.close();
const saved = authClient.session.save();
- process.stdout.write("\n=== AUTH SUCCESSFUL ===\n");
- process.stdout.write("Save this to TELEGRAM_SESSION env var:\n\n");
- process.stdout.write(saved + "\n");
+ process.stdout.write('\n=== AUTH SUCCESSFUL ===\n');
+ process.stdout.write('Save this to TELEGRAM_SESSION env var:\n\n');
+ process.stdout.write(saved + '\n');
await authClient.disconnect();
process.exit(0);
}
@@ -83,7 +78,7 @@ if (CONFIGURED) {
baseLogger: {
log: () => {},
warn: () => {},
- error: (...args) => process.stderr.write(args.join(" ") + "\n"),
+ error: (...args) => process.stderr.write(args.join(' ') + '\n'),
info: () => {},
debug: () => {},
},
@@ -92,124 +87,114 @@ if (CONFIGURED) {
try {
await client.connect();
if (!(await client.checkAuthorization())) {
- process.stderr.write(
- "Warning: Telegram session is no longer valid. Re-run `node index.js --auth`.\n",
- );
+ process.stderr.write('Warning: Telegram session is no longer valid. Re-run `node index.js --auth`.\n');
client = null;
}
} catch (err) {
- process.stderr.write(
- `Warning: Failed to connect to Telegram: ${err.message}\n`,
- );
+ process.stderr.write(`Warning: Failed to connect to Telegram: ${err.message}\n`);
client = null;
}
} else {
- process.stderr.write(
- "Telegram credentials not set — server starting in unconfigured mode.\n",
- );
+ process.stderr.write('Telegram credentials not set — server starting in unconfigured mode.\n');
}
// ── MCP server setup ──
-const server = new Server(
- { name: "claude-ops-telegram", version: "0.2.0" },
- { capabilities: { tools: {} } },
-);
+const server = new Server({ name: 'claude-ops-telegram', version: '0.2.0' }, { capabilities: { tools: {} } });
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [
{
- name: "list_dialogs",
+ name: 'list_dialogs',
description:
- "List recent Telegram conversations (DMs, groups, channels). Returns last-message preview, sender, timestamp, and unread count.",
+ 'List recent Telegram conversations (DMs, groups, channels). Returns last-message preview, sender, timestamp, and unread count.',
inputSchema: {
- type: "object",
+ type: 'object',
properties: {
limit: {
- type: "number",
- description: "Max dialogs to return (default 30, max 100)",
+ type: 'number',
+ description: 'Max dialogs to return (default 30, max 100)',
},
archived: {
- type: "boolean",
- description: "Include archived dialogs (default false)",
+ type: 'boolean',
+ description: 'Include archived dialogs (default false)',
},
},
required: [],
},
},
{
- name: "get_messages",
+ name: 'get_messages',
description:
- "Fetch recent messages from a specific chat. Use chat_id from list_dialogs or a username like @example.",
+ 'Fetch recent messages from a specific chat. Use chat_id from list_dialogs or a username like @example.',
inputSchema: {
- type: "object",
+ type: 'object',
properties: {
chat: {
- type: "string",
- description: "Chat ID (numeric) or @username",
+ type: 'string',
+ description: 'Chat ID (numeric) or @username',
},
limit: {
- type: "number",
- description: "Number of messages to fetch (default 20, max 100)",
+ type: 'number',
+ description: 'Number of messages to fetch (default 20, max 100)',
},
},
- required: ["chat"],
+ required: ['chat'],
},
},
{
- name: "send_message",
- description:
- "Send a message to a Telegram chat or user (personal account, not bot).",
+ name: 'send_message',
+ description: 'Send a message to a Telegram chat or user (personal account, not bot).',
inputSchema: {
- type: "object",
+ type: 'object',
properties: {
chat: {
- type: "string",
- description: "Chat ID (numeric) or @username",
+ type: 'string',
+ description: 'Chat ID (numeric) or @username',
},
text: {
- type: "string",
- description: "Message text (supports Markdown)",
+ type: 'string',
+ description: 'Message text (supports Markdown)',
},
},
- required: ["chat", "text"],
+ required: ['chat', 'text'],
},
},
{
- name: "search_messages",
- description: "Full-text search across all Telegram conversations.",
+ name: 'search_messages',
+ description: 'Full-text search across all Telegram conversations.',
inputSchema: {
- type: "object",
+ type: 'object',
properties: {
query: {
- type: "string",
- description: "Search query text",
+ type: 'string',
+ description: 'Search query text',
},
limit: {
- type: "number",
- description: "Max results (default 20)",
+ type: 'number',
+ description: 'Max results (default 20)',
},
},
- required: ["query"],
+ required: ['query'],
},
},
],
}));
function formatPeer(entity) {
- if (!entity) return "Unknown";
+ if (!entity) return 'Unknown';
if (entity.title) return entity.title;
- const first = entity.firstName || "";
- const last = entity.lastName || "";
+ const first = entity.firstName || '';
+ const last = entity.lastName || '';
const name = `${first} ${last}`.trim();
if (name) return name;
if (entity.username) return `@${entity.username}`;
- return String(entity.id || "Unknown");
+ return String(entity.id || 'Unknown');
}
function resolveChatArg(chat) {
// Accept numeric ID or @username
if (/^-?\d+$/.test(chat)) return parseInt(chat, 10);
- return chat.startsWith("@") ? chat : `@${chat}`;
+ return chat.startsWith('@') ? chat : `@${chat}`;
}
server.setRequestHandler(CallToolRequestSchema, async (request) => {
@@ -217,13 +202,13 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (!client) {
return {
- content: [{ type: "text", text: NOT_CONFIGURED_MSG }],
+ content: [{ type: 'text', text: NOT_CONFIGURED_MSG }],
isError: true,
};
}
try {
- if (name === "list_dialogs") {
+ if (name === 'list_dialogs') {
const limit = Math.min(args?.limit || 30, 100);
const includeArchived = args?.archived || false;
@@ -236,14 +221,12 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
const peer = formatPeer(d.entity);
const lastMsg = d.message;
const fromMe = lastMsg?.out || false;
- const text = lastMsg?.message || "[non-text message]";
- const ts = lastMsg?.date
- ? new Date(lastMsg.date * 1000).toISOString()
- : "";
+ const text = lastMsg?.message || '[non-text message]';
+ const ts = lastMsg?.date ? new Date(lastMsg.date * 1000).toISOString() : '';
return {
chat_id: String(d.id),
name: peer,
- type: d.isChannel ? "channel" : d.isGroup ? "group" : "dm",
+ type: d.isChannel ? 'channel' : d.isGroup ? 'group' : 'dm',
unread: d.unreadCount || 0,
last_message: {
from_me: fromMe,
@@ -256,18 +239,14 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
return {
content: [
{
- type: "text",
- text: JSON.stringify(
- { dialogs: formatted, count: formatted.length },
- null,
- 2,
- ),
+ type: 'text',
+ text: JSON.stringify({ dialogs: formatted, count: formatted.length }, null, 2),
},
],
};
}
- if (name === "get_messages") {
+ if (name === 'get_messages') {
const chat = resolveChatArg(args.chat);
const limit = Math.min(args?.limit || 20, 100);
@@ -277,42 +256,38 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
id: m.id,
from_me: m.out,
sender: formatPeer(m.sender),
- text: m.message || "[non-text message]",
- timestamp: m.date ? new Date(m.date * 1000).toISOString() : "",
+ text: m.message || '[non-text message]',
+ timestamp: m.date ? new Date(m.date * 1000).toISOString() : '',
}));
return {
content: [
{
- type: "text",
- text: JSON.stringify(
- { messages: formatted, count: formatted.length },
- null,
- 2,
- ),
+ type: 'text',
+ text: JSON.stringify({ messages: formatted, count: formatted.length }, null, 2),
},
],
};
}
- if (name === "send_message") {
+ if (name === 'send_message') {
const chat = resolveChatArg(args.chat);
const result = await client.sendMessage(chat, { message: args.text });
return {
content: [
{
- type: "text",
+ type: 'text',
text: `Message sent. ID: ${result.id}, to: ${chat}`,
},
],
};
}
- if (name === "search_messages") {
+ if (name === 'search_messages') {
const limit = Math.min(args?.limit || 20, 100);
// gram.js messages.search on global scope
- const { Api } = await import("telegram");
+ const { Api } = await import('telegram');
const results = await client.invoke(
new Api.messages.SearchGlobal({
q: args.query,
@@ -328,20 +303,16 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
const msgs = (results.messages || []).map((m) => ({
id: m.id,
- text: m.message || "[non-text]",
- timestamp: m.date ? new Date(m.date * 1000).toISOString() : "",
+ text: m.message || '[non-text]',
+ timestamp: m.date ? new Date(m.date * 1000).toISOString() : '',
from_me: m.out || false,
}));
return {
content: [
{
- type: "text",
- text: JSON.stringify(
- { results: msgs, count: msgs.length },
- null,
- 2,
- ),
+ type: 'text',
+ text: JSON.stringify({ results: msgs, count: msgs.length }, null, 2),
},
],
};
@@ -350,7 +321,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
throw new Error(`Unknown tool: ${name}`);
} catch (error) {
return {
- content: [{ type: "text", text: `Error: ${error.message}` }],
+ content: [{ type: 'text', text: `Error: ${error.message}` }],
isError: true,
};
}
@@ -358,14 +329,14 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
const transport = new StdioServerTransport();
await server.connect(transport);
-process.stderr.write("Telegram MCP server running (user-auth mode)\n");
+process.stderr.write('Telegram MCP server running (user-auth mode)\n');
// Graceful shutdown
-process.on("SIGINT", async () => {
+process.on('SIGINT', async () => {
if (client) await client.disconnect();
process.exit(0);
});
-process.on("SIGTERM", async () => {
+process.on('SIGTERM', async () => {
if (client) await client.disconnect();
process.exit(0);
});
diff --git a/claude-ops/templates/nestjs-api/nest-cli.json b/claude-ops/templates/nestjs-api/nest-cli.json
new file mode 100644
index 00000000..d50e6ab4
--- /dev/null
+++ b/claude-ops/templates/nestjs-api/nest-cli.json
@@ -0,0 +1,6 @@
+{
+ "$schema": "https://json.schemastore.org/nest-cli",
+ "collection": "@nestjs/schematics",
+ "sourceRoot": "src",
+ "compilerOptions": { "deleteOutDir": true }
+}
diff --git a/claude-ops/templates/nestjs-api/package.json b/claude-ops/templates/nestjs-api/package.json
new file mode 100644
index 00000000..3290f353
--- /dev/null
+++ b/claude-ops/templates/nestjs-api/package.json
@@ -0,0 +1,43 @@
+{
+ "name": "nestjs-api",
+ "version": "0.1.0",
+ "private": true,
+ "scripts": {
+ "build": "nest build",
+ "start": "nest start",
+ "start:dev": "nest start --watch",
+ "start:prod": "node dist/main",
+ "test": "jest",
+ "test:e2e": "jest --config ./test/jest-e2e.json",
+ "lint": "eslint \"{src,apps,libs,test}/**/*.ts\""
+ },
+ "dependencies": {
+ "@nestjs/common": "^10.0.0",
+ "@nestjs/core": "^10.0.0",
+ "@nestjs/jwt": "^10.0.0",
+ "@nestjs/passport": "^10.0.0",
+ "@nestjs/platform-fastify": "^10.0.0",
+ "@nestjs/bull": "^10.0.0",
+ "@nestjs/terminus": "^10.0.0",
+ "@nestjs/config": "^3.0.0",
+ "@prisma/client": "^5.0.0",
+ "bcryptjs": "^2.4.3",
+ "bullmq": "^4.0.0",
+ "ioredis": "^5.0.0",
+ "passport": "^0.6.0",
+ "passport-jwt": "^4.0.0",
+ "reflect-metadata": "^0.1.13",
+ "rxjs": "^7.8.0"
+ },
+ "devDependencies": {
+ "@nestjs/cli": "^10.0.0",
+ "@nestjs/schematics": "^10.0.0",
+ "@types/bcryptjs": "^2.4.0",
+ "@types/jest": "^29.0.0",
+ "@types/node": "^20.0.0",
+ "@types/passport-jwt": "^3.0.0",
+ "prisma": "^5.0.0",
+ "ts-jest": "^29.0.0",
+ "typescript": "^5.0.0"
+ }
+}
diff --git a/claude-ops/templates/nestjs-api/src/app.module.ts b/claude-ops/templates/nestjs-api/src/app.module.ts
new file mode 100644
index 00000000..128a0d94
--- /dev/null
+++ b/claude-ops/templates/nestjs-api/src/app.module.ts
@@ -0,0 +1,24 @@
+import { Module } from '@nestjs/common';
+import { ConfigModule, ConfigService } from '@nestjs/config';
+import { BullModule } from '@nestjs/bull';
+import { AuthModule } from './auth/auth.module';
+import { HealthModule } from './health/health.module';
+import { QueueModule } from './queue/queue.module';
+import { PrismaModule } from './prisma/prisma.module';
+
+@Module({
+ imports: [
+ ConfigModule.forRoot({ isGlobal: true }),
+ BullModule.forRootAsync({
+ inject: [ConfigService],
+ useFactory: (config: ConfigService) => ({
+ redis: { host: config.get('REDIS_HOST', 'localhost'), port: 6379 },
+ }),
+ }),
+ AuthModule,
+ HealthModule,
+ QueueModule,
+ PrismaModule,
+ ],
+})
+export class AppModule {}
diff --git a/claude-ops/templates/nestjs-api/src/auth/auth.controller.ts b/claude-ops/templates/nestjs-api/src/auth/auth.controller.ts
new file mode 100644
index 00000000..8ce2c2be
--- /dev/null
+++ b/claude-ops/templates/nestjs-api/src/auth/auth.controller.ts
@@ -0,0 +1,17 @@
+import { Body, Controller, Post } from '@nestjs/common';
+import { AuthService } from './auth.service';
+
+@Controller('auth')
+export class AuthController {
+ constructor(private auth: AuthService) {}
+
+ @Post('register')
+ register(@Body() body: { email: string; password: string }) {
+ return this.auth.register(body.email, body.password);
+ }
+
+ @Post('login')
+ login(@Body() body: { email: string; password: string }) {
+ return this.auth.login(body.email, body.password);
+ }
+}
diff --git a/claude-ops/templates/nestjs-api/src/auth/auth.module.ts b/claude-ops/templates/nestjs-api/src/auth/auth.module.ts
new file mode 100644
index 00000000..947ee8fd
--- /dev/null
+++ b/claude-ops/templates/nestjs-api/src/auth/auth.module.ts
@@ -0,0 +1,26 @@
+import { Module } from '@nestjs/common';
+import { JwtModule } from '@nestjs/jwt';
+import { PassportModule } from '@nestjs/passport';
+import { ConfigService } from '@nestjs/config';
+import { AuthService } from './auth.service';
+import { AuthController } from './auth.controller';
+import { JwtStrategy } from './jwt.strategy';
+import { PrismaModule } from '../prisma/prisma.module';
+
+@Module({
+ imports: [
+ PassportModule,
+ PrismaModule,
+ JwtModule.registerAsync({
+ inject: [ConfigService],
+ useFactory: (config: ConfigService) => ({
+ secret: config.get<string>('JWT_SECRET'),
+ signOptions: { expiresIn: '15m' },
+ }),
+ }),
+ ],
+ providers: [AuthService, JwtStrategy],
+ controllers: [AuthController],
+ exports: [AuthService],
+})
+export class AuthModule {}
diff --git a/claude-ops/templates/nestjs-api/src/auth/auth.service.ts b/claude-ops/templates/nestjs-api/src/auth/auth.service.ts
new file mode 100644
index 00000000..e11f01d0
--- /dev/null
+++ b/claude-ops/templates/nestjs-api/src/auth/auth.service.ts
@@ -0,0 +1,35 @@
+import { Injectable, UnauthorizedException } from '@nestjs/common';
+import { JwtService } from '@nestjs/jwt';
+import * as bcrypt from 'bcryptjs';
+import { PrismaService } from '../prisma/prisma.service';
+
+@Injectable()
+export class AuthService {
+ constructor(
+ private prisma: PrismaService,
+ private jwt: JwtService,
+ ) {}
+
+ async register(email: string, password: string) {
+ const hash = await bcrypt.hash(password, 10);
+ const user = await this.prisma.user.create({
+ data: { email, password: hash },
+ });
+ return this.signTokens(user.id, user.email);
+ }
+
+ async login(email: string, password: string) {
+ const user = await this.prisma.user.findUnique({ where: { email } });
+ if (!user || !(await bcrypt.compare(password, user.password))) {
+ throw new UnauthorizedException('Invalid credentials');
+ }
+ return this.signTokens(user.id, user.email);
+ }
+
+ private async signTokens(userId: string, email: string) {
+ const payload = { sub: userId, email };
+ return {
+ access_token: await this.jwt.signAsync(payload),
+ };
+ }
+}
diff --git a/claude-ops/templates/nestjs-api/src/auth/jwt.strategy.ts b/claude-ops/templates/nestjs-api/src/auth/jwt.strategy.ts
new file mode 100644
index 00000000..4c10ebd3
--- /dev/null
+++ b/claude-ops/templates/nestjs-api/src/auth/jwt.strategy.ts
@@ -0,0 +1,18 @@
+import { Injectable } from '@nestjs/common';
+import { ConfigService } from '@nestjs/config';
+import { PassportStrategy } from '@nestjs/passport';
+import { ExtractJwt, Strategy } from 'passport-jwt';
+
+@Injectable()
+export class JwtStrategy extends PassportStrategy(Strategy) {
+ constructor(config: ConfigService) {
+ super({
+ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
+ secretOrKey: config.get<string>('JWT_SECRET'),
+ });
+ }
+
+ validate(payload: { sub: string; email: string }) {
+ return { userId: payload.sub, email: payload.email };
+ }
+}
diff --git a/claude-ops/templates/nestjs-api/src/health/health.controller.ts b/claude-ops/templates/nestjs-api/src/health/health.controller.ts
new file mode 100644
index 00000000..b4cdfb2a
--- /dev/null
+++ b/claude-ops/templates/nestjs-api/src/health/health.controller.ts
@@ -0,0 +1,20 @@
+import { Controller, Get } from '@nestjs/common';
+import { HealthCheck, HealthCheckService, PrismaHealthIndicator } from '@nestjs/terminus';
+import { PrismaService } from '../prisma/prisma.service';
+
+@Controller('health')
+export class HealthController {
+ constructor(
+ private health: HealthCheckService,
+ private prismaHealth: PrismaHealthIndicator,
+ private prisma: PrismaService,
+ ) {}
+
+ @Get()
+ @HealthCheck()
+ check() {
+ return this.health.check([
+ () => this.prismaHealth.pingCheck('database', this.prisma),
+ ]);
+ }
+}
diff --git a/claude-ops/templates/nestjs-api/src/health/health.module.ts b/claude-ops/templates/nestjs-api/src/health/health.module.ts
new file mode 100644
index 00000000..ffe8b4c6
--- /dev/null
+++ b/claude-ops/templates/nestjs-api/src/health/health.module.ts
@@ -0,0 +1,10 @@
+import { Module } from '@nestjs/common';
+import { TerminusModule } from '@nestjs/terminus';
+import { HealthController } from './health.controller';
+import { PrismaModule } from '../prisma/prisma.module';
+
+@Module({
+ imports: [TerminusModule, PrismaModule],
+ controllers: [HealthController],
+})
+export class HealthModule {}
diff --git a/claude-ops/templates/nestjs-api/src/main.ts b/claude-ops/templates/nestjs-api/src/main.ts
new file mode 100644
index 00000000..5958b880
--- /dev/null
+++ b/claude-ops/templates/nestjs-api/src/main.ts
@@ -0,0 +1,16 @@
+import { NestFactory } from '@nestjs/core';
+import {
+ FastifyAdapter,
+ NestFastifyApplication,
+} from '@nestjs/platform-fastify';
+import { AppModule } from './app.module';
+
+async function bootstrap() {
+ const app = await NestFactory.create<NestFastifyApplication>(
+ AppModule,
+ new FastifyAdapter({ logger: true }),
+ );
+ app.enableCors();
+ await app.listen(process.env.PORT ?? 3000, '0.0.0.0');
+}
+bootstrap();
diff --git a/claude-ops/templates/nestjs-api/src/prisma/prisma.module.ts b/claude-ops/templates/nestjs-api/src/prisma/prisma.module.ts
new file mode 100644
index 00000000..dd4abed2
--- /dev/null
+++ b/claude-ops/templates/nestjs-api/src/prisma/prisma.module.ts
@@ -0,0 +1,6 @@
+import { Module, Global } from '@nestjs/common';
+import { PrismaService } from './prisma.service';
+
+@Global()
+@Module({ providers: [PrismaService], exports: [PrismaService] })
+export class PrismaModule {}
diff --git a/claude-ops/templates/nestjs-api/src/prisma/prisma.service.ts b/claude-ops/templates/nestjs-api/src/prisma/prisma.service.ts
new file mode 100644
index 00000000..359f950b
--- /dev/null
+++ b/claude-ops/templates/nestjs-api/src/prisma/prisma.service.ts
@@ -0,0 +1,9 @@
+import { Injectable, OnModuleInit } from '@nestjs/common';
+import { PrismaClient } from '@prisma/client';
+
+@Injectable()
+export class PrismaService extends PrismaClient implements OnModuleInit {
+ async onModuleInit() {
+ await this.$connect();
+ }
+}
diff --git a/claude-ops/templates/nestjs-api/src/queue/queue.module.ts b/claude-ops/templates/nestjs-api/src/queue/queue.module.ts
new file mode 100644
index 00000000..fc2fb86b
--- /dev/null
+++ b/claude-ops/templates/nestjs-api/src/queue/queue.module.ts
@@ -0,0 +1,9 @@
+import { Module } from '@nestjs/common';
+import { BullModule } from '@nestjs/bull';
+import { ExampleProcessor } from './processors/example.processor';
+
+@Module({
+ imports: [BullModule.registerQueue({ name: 'example' })],
+ providers: [ExampleProcessor],
+})
+export class QueueModule {}
diff --git a/claude-ops/templates/nestjs-api/tsconfig.json b/claude-ops/templates/nestjs-api/tsconfig.json
new file mode 100644
index 00000000..926366e3
--- /dev/null
+++ b/claude-ops/templates/nestjs-api/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "module": "commonjs",
+ "declaration": true,
+ "removeComments": true,
+ "emitDecoratorMetadata": true,
+ "experimentalDecorators": true,
+ "allowSyntheticDefaultImports": true,
+ "target": "ES2021",
+ "sourceMap": true,
+ "outDir": "./dist",
+ "baseUrl": "./",
+ "strict": false,
+ "skipLibCheck": true
+ }
+}