@stackmemoryai/stackmemory 0.5.17 → 0.5.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/hooks/auto-background.js +12 -7
- package/dist/hooks/auto-background.js.map +2 -2
- package/dist/hooks/schemas.js +91 -0
- package/dist/hooks/schemas.js.map +7 -0
- package/dist/hooks/secure-fs.js +29 -0
- package/dist/hooks/secure-fs.js.map +7 -0
- package/dist/hooks/sms-action-runner.js +17 -8
- package/dist/hooks/sms-action-runner.js.map +2 -2
- package/dist/hooks/sms-notify.js +14 -10
- package/dist/hooks/sms-notify.js.map +3 -3
- package/dist/hooks/sms-webhook.js +37 -11
- package/dist/hooks/sms-webhook.js.map +2 -2
- package/package.json +1 -1
|
@@ -2,9 +2,11 @@ import { fileURLToPath as __fileURLToPath } from 'url';
|
|
|
2
2
|
import { dirname as __pathDirname } from 'path';
|
|
3
3
|
const __filename = __fileURLToPath(import.meta.url);
|
|
4
4
|
const __dirname = __pathDirname(__filename);
|
|
5
|
-
import { existsSync, readFileSync
|
|
5
|
+
import { existsSync, readFileSync } from "fs";
|
|
6
6
|
import { join } from "path";
|
|
7
7
|
import { homedir } from "os";
|
|
8
|
+
import { writeFileSecure, ensureSecureDir } from "./secure-fs.js";
|
|
9
|
+
import { AutoBackgroundConfigSchema, parseConfigSafe } from "./schemas.js";
|
|
8
10
|
const DEFAULT_CONFIG = {
|
|
9
11
|
enabled: true,
|
|
10
12
|
timeoutMs: 5e3,
|
|
@@ -76,7 +78,13 @@ function loadConfig() {
|
|
|
76
78
|
try {
|
|
77
79
|
if (existsSync(CONFIG_PATH)) {
|
|
78
80
|
const data = readFileSync(CONFIG_PATH, "utf8");
|
|
79
|
-
|
|
81
|
+
const parsed = JSON.parse(data);
|
|
82
|
+
return parseConfigSafe(
|
|
83
|
+
AutoBackgroundConfigSchema,
|
|
84
|
+
{ ...DEFAULT_CONFIG, ...parsed },
|
|
85
|
+
DEFAULT_CONFIG,
|
|
86
|
+
"auto-background"
|
|
87
|
+
);
|
|
80
88
|
}
|
|
81
89
|
} catch {
|
|
82
90
|
}
|
|
@@ -84,11 +92,8 @@ function loadConfig() {
|
|
|
84
92
|
}
|
|
85
93
|
function saveConfig(config) {
|
|
86
94
|
try {
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
mkdirSync(dir, { recursive: true });
|
|
90
|
-
}
|
|
91
|
-
writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));
|
|
95
|
+
ensureSecureDir(join(homedir(), ".stackmemory"));
|
|
96
|
+
writeFileSecure(CONFIG_PATH, JSON.stringify(config, null, 2));
|
|
92
97
|
} catch {
|
|
93
98
|
}
|
|
94
99
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/hooks/auto-background.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Auto-background hook for Claude Code\n * Automatically backgrounds long-running or specific commands\n */\n\nimport { existsSync, readFileSync
|
|
5
|
-
"mappings": ";;;;AAKA,SAAS,YAAY,
|
|
4
|
+
"sourcesContent": ["/**\n * Auto-background hook for Claude Code\n * Automatically backgrounds long-running or specific commands\n */\n\nimport { existsSync, readFileSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { writeFileSecure, ensureSecureDir } from './secure-fs.js';\nimport { AutoBackgroundConfigSchema, parseConfigSafe } from './schemas.js';\n\nexport interface AutoBackgroundConfig {\n enabled: boolean;\n // Time-based: background if command runs longer than this (ms)\n timeoutMs: number;\n // Pattern-based: always background these commands\n alwaysBackground: string[];\n // Never background these (override)\n neverBackground: string[];\n // Log backgrounded commands\n verbose: boolean;\n}\n\nconst DEFAULT_CONFIG: AutoBackgroundConfig = {\n enabled: true,\n timeoutMs: 5000, // 5 seconds\n alwaysBackground: [\n // Package managers\n 'npm install',\n 'npm ci',\n 'yarn install',\n 'pnpm install',\n 'bun install',\n // Builds\n 'npm run build',\n 'yarn build',\n 'pnpm build',\n 'cargo build',\n 'go build',\n 'make',\n 'cmake',\n // Tests\n 'npm test',\n 'npm run test',\n 'yarn test',\n 'pnpm test',\n 'pytest',\n 'jest',\n 'vitest',\n 'cargo test',\n 'go test',\n // Docker\n 'docker build',\n 'docker-compose up',\n 'docker compose up',\n // Git operations that can be slow\n 'git clone',\n 'git fetch --all',\n 'git pull --all',\n // Type checking\n 'npx tsc',\n 'tsc --noEmit',\n // Linting large codebases\n 'eslint .',\n 'npm run lint',\n ],\n neverBackground: [\n // Interactive commands\n 'vim',\n 'nvim',\n 'nano',\n 'less',\n 'more',\n 'top',\n 'htop',\n // Quick commands\n 'echo',\n 'cat',\n 'ls',\n 'pwd',\n 'cd',\n 'which',\n 'git status',\n 'git diff',\n 'git log',\n ],\n verbose: false,\n};\n\nconst CONFIG_PATH = join(homedir(), '.stackmemory', 'auto-background.json');\n\nexport function loadConfig(): AutoBackgroundConfig {\n try {\n if (existsSync(CONFIG_PATH)) {\n const data = readFileSync(CONFIG_PATH, 'utf8');\n const parsed = JSON.parse(data);\n return parseConfigSafe(\n AutoBackgroundConfigSchema,\n { ...DEFAULT_CONFIG, ...parsed },\n DEFAULT_CONFIG,\n 'auto-background'\n );\n }\n } catch {\n // Use defaults\n }\n return DEFAULT_CONFIG;\n}\n\nexport function saveConfig(config: AutoBackgroundConfig): void {\n try {\n ensureSecureDir(join(homedir(), '.stackmemory'));\n writeFileSecure(CONFIG_PATH, JSON.stringify(config, null, 2));\n } catch {\n // Silently fail\n }\n}\n\nexport function shouldAutoBackground(\n command: string,\n config?: AutoBackgroundConfig\n): boolean {\n const cfg = config || loadConfig();\n\n if (!cfg.enabled) return false;\n\n const normalizedCmd = command.trim().toLowerCase();\n\n // Check never-background list first (highest priority)\n for (const pattern of cfg.neverBackground) {\n if (normalizedCmd.startsWith(pattern.toLowerCase())) {\n return false;\n }\n }\n\n // Check always-background list\n for (const pattern of cfg.alwaysBackground) {\n if (normalizedCmd.startsWith(pattern.toLowerCase())) {\n return true;\n }\n }\n\n // Default: don't auto-background (let timeout handle it)\n return false;\n}\n\n/**\n * Hook response format for Claude Code\n * Returns modified tool input if command should be backgrounded\n */\nexport interface HookResponse {\n decision: 'allow' | 'modify' | 'block';\n modifiedInput?: Record<string, unknown>;\n reason?: string;\n}\n\nexport function processToolUse(\n toolName: string,\n toolInput: Record<string, unknown>\n): HookResponse {\n // Only process Bash tool\n if (toolName !== 'Bash') {\n return { decision: 'allow' };\n }\n\n const command = toolInput.command as string;\n if (!command) {\n return { decision: 'allow' };\n }\n\n // Skip if already backgrounded\n if (toolInput.run_in_background === true) {\n return { decision: 'allow' };\n }\n\n const config = loadConfig();\n\n if (shouldAutoBackground(command, config)) {\n if (config.verbose) {\n console.error(\n `[auto-background] Backgrounding: ${command.substring(0, 50)}...`\n );\n }\n\n return {\n decision: 'modify',\n modifiedInput: {\n ...toolInput,\n run_in_background: true,\n },\n reason: `Auto-backgrounded: matches pattern`,\n };\n }\n\n return { decision: 'allow' };\n}\n\n// CLI entry point removed - use stackmemory auto-bg command instead\n"],
|
|
5
|
+
"mappings": ";;;;AAKA,SAAS,YAAY,oBAAoB;AACzC,SAAS,YAAY;AACrB,SAAS,eAAe;AACxB,SAAS,iBAAiB,uBAAuB;AACjD,SAAS,4BAA4B,uBAAuB;AAc5D,MAAM,iBAAuC;AAAA,EAC3C,SAAS;AAAA,EACT,WAAW;AAAA;AAAA,EACX,kBAAkB;AAAA;AAAA,IAEhB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAEA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAEA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAEA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAEA;AAAA,IACA;AAAA,IACA;AAAA;AAA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UACA,WACc;AAEd,MAAI,aAAa,QAAQ;AACvB,WAAO,EAAE,UAAU,QAAQ;AAAA,EAC7B;AAEA,QAAM,UAAU,UAAU;AAC1B,MAAI,CAAC,SAAS;AACZ,WAAO,EAAE,UAAU,QAAQ;AAAA,EAC7B;AAGA,MAAI,UAAU,sBAAsB,MAAM;AACxC,WAAO,EAAE,UAAU,QAAQ;AAAA,EAC7B;AAEA,QAAM,SAAS,WAAW;AAE1B,MAAI,qBAAqB,SAAS,MAAM,GAAG;AACzC,QAAI,OAAO,SAAS;AAClB,cAAQ;AAAA,QACN,oCAAoC,QAAQ,UAAU,GAAG,EAAE,CAAC;AAAA,MAC9D;AAAA,IACF;AAEA,WAAO;AAAA,MACL,UAAU;AAAA,MACV,eAAe;AAAA,QACb,GAAG;AAAA,QACH,mBAAmB;AAAA,MACrB;AAAA,MACA,QAAQ;AAAA,IACV;AAAA,EACF;AAEA,SAAO,EAAE,UAAU,QAAQ;AAC7B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { fileURLToPath as __fileURLToPath } from 'url';
|
|
2
|
+
import { dirname as __pathDirname } from 'path';
|
|
3
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
4
|
+
const __dirname = __pathDirname(__filename);
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
const PromptOptionSchema = z.object({
|
|
7
|
+
key: z.string().max(10),
|
|
8
|
+
label: z.string().max(200),
|
|
9
|
+
action: z.string().max(500).optional()
|
|
10
|
+
});
|
|
11
|
+
const PendingPromptSchema = z.object({
|
|
12
|
+
id: z.string().max(32),
|
|
13
|
+
timestamp: z.string().datetime({ offset: true }).or(z.string().regex(/^\d{4}-\d{2}-\d{2}T/)),
|
|
14
|
+
message: z.string().max(1e3),
|
|
15
|
+
options: z.array(PromptOptionSchema).max(10),
|
|
16
|
+
type: z.enum(["options", "yesno", "freeform"]),
|
|
17
|
+
callback: z.string().max(500).optional(),
|
|
18
|
+
expiresAt: z.string().datetime({ offset: true }).or(z.string().regex(/^\d{4}-\d{2}-\d{2}T/))
|
|
19
|
+
});
|
|
20
|
+
const NotifyOnSchema = z.object({
|
|
21
|
+
taskComplete: z.boolean(),
|
|
22
|
+
reviewReady: z.boolean(),
|
|
23
|
+
error: z.boolean(),
|
|
24
|
+
custom: z.boolean()
|
|
25
|
+
});
|
|
26
|
+
const QuietHoursSchema = z.object({
|
|
27
|
+
enabled: z.boolean(),
|
|
28
|
+
start: z.string().regex(/^\d{2}:\d{2}$/),
|
|
29
|
+
end: z.string().regex(/^\d{2}:\d{2}$/)
|
|
30
|
+
});
|
|
31
|
+
const SMSConfigSchema = z.object({
|
|
32
|
+
enabled: z.boolean(),
|
|
33
|
+
channel: z.enum(["whatsapp", "sms"]),
|
|
34
|
+
accountSid: z.string().max(100).optional(),
|
|
35
|
+
authToken: z.string().max(100).optional(),
|
|
36
|
+
smsFromNumber: z.string().max(20).optional(),
|
|
37
|
+
smsToNumber: z.string().max(20).optional(),
|
|
38
|
+
whatsappFromNumber: z.string().max(30).optional(),
|
|
39
|
+
whatsappToNumber: z.string().max(30).optional(),
|
|
40
|
+
fromNumber: z.string().max(20).optional(),
|
|
41
|
+
toNumber: z.string().max(20).optional(),
|
|
42
|
+
webhookUrl: z.string().url().max(500).optional(),
|
|
43
|
+
notifyOn: NotifyOnSchema,
|
|
44
|
+
quietHours: QuietHoursSchema.optional(),
|
|
45
|
+
responseTimeout: z.number().int().min(30).max(3600),
|
|
46
|
+
pendingPrompts: z.array(PendingPromptSchema).max(100)
|
|
47
|
+
});
|
|
48
|
+
const PendingActionSchema = z.object({
|
|
49
|
+
id: z.string().max(32),
|
|
50
|
+
promptId: z.string().max(32),
|
|
51
|
+
response: z.string().max(1e3),
|
|
52
|
+
action: z.string().max(500),
|
|
53
|
+
timestamp: z.string().datetime({ offset: true }).or(z.string().regex(/^\d{4}-\d{2}-\d{2}T/)),
|
|
54
|
+
status: z.enum(["pending", "running", "completed", "failed"]),
|
|
55
|
+
result: z.string().max(1e4).optional(),
|
|
56
|
+
error: z.string().max(1e3).optional()
|
|
57
|
+
});
|
|
58
|
+
const ActionQueueSchema = z.object({
|
|
59
|
+
actions: z.array(PendingActionSchema).max(1e3),
|
|
60
|
+
lastChecked: z.string().datetime({ offset: true }).or(z.string().regex(/^\d{4}-\d{2}-\d{2}T/))
|
|
61
|
+
});
|
|
62
|
+
const AutoBackgroundConfigSchema = z.object({
|
|
63
|
+
enabled: z.boolean(),
|
|
64
|
+
timeoutMs: z.number().int().min(1e3).max(6e5),
|
|
65
|
+
alwaysBackground: z.array(z.string().max(200)).max(100),
|
|
66
|
+
neverBackground: z.array(z.string().max(200)).max(100),
|
|
67
|
+
verbose: z.boolean().optional()
|
|
68
|
+
});
|
|
69
|
+
function parseConfigSafe(schema, data, defaultValue, configName) {
|
|
70
|
+
const result = schema.safeParse(data);
|
|
71
|
+
if (result.success) {
|
|
72
|
+
return result.data;
|
|
73
|
+
}
|
|
74
|
+
console.error(
|
|
75
|
+
`[hooks] Invalid ${configName} config:`,
|
|
76
|
+
result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join(", ")
|
|
77
|
+
);
|
|
78
|
+
return defaultValue;
|
|
79
|
+
}
|
|
80
|
+
export {
|
|
81
|
+
ActionQueueSchema,
|
|
82
|
+
AutoBackgroundConfigSchema,
|
|
83
|
+
NotifyOnSchema,
|
|
84
|
+
PendingActionSchema,
|
|
85
|
+
PendingPromptSchema,
|
|
86
|
+
PromptOptionSchema,
|
|
87
|
+
QuietHoursSchema,
|
|
88
|
+
SMSConfigSchema,
|
|
89
|
+
parseConfigSafe
|
|
90
|
+
};
|
|
91
|
+
//# sourceMappingURL=schemas.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/hooks/schemas.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Zod schemas for hook configuration validation\n * Prevents malformed or malicious configs from being loaded\n */\n\nimport { z } from 'zod';\n\n// SMS/WhatsApp notification schemas\nexport const PromptOptionSchema = z.object({\n key: z.string().max(10),\n label: z.string().max(200),\n action: z.string().max(500).optional(),\n});\n\nexport const PendingPromptSchema = z.object({\n id: z.string().max(32),\n timestamp: z\n .string()\n .datetime({ offset: true })\n .or(z.string().regex(/^\\d{4}-\\d{2}-\\d{2}T/)),\n message: z.string().max(1000),\n options: z.array(PromptOptionSchema).max(10),\n type: z.enum(['options', 'yesno', 'freeform']),\n callback: z.string().max(500).optional(),\n expiresAt: z\n .string()\n .datetime({ offset: true })\n .or(z.string().regex(/^\\d{4}-\\d{2}-\\d{2}T/)),\n});\n\nexport const NotifyOnSchema = z.object({\n taskComplete: z.boolean(),\n reviewReady: z.boolean(),\n error: z.boolean(),\n custom: z.boolean(),\n});\n\nexport const QuietHoursSchema = z.object({\n enabled: z.boolean(),\n start: z.string().regex(/^\\d{2}:\\d{2}$/),\n end: z.string().regex(/^\\d{2}:\\d{2}$/),\n});\n\nexport const SMSConfigSchema = z.object({\n enabled: z.boolean(),\n channel: z.enum(['whatsapp', 'sms']),\n accountSid: z.string().max(100).optional(),\n authToken: z.string().max(100).optional(),\n smsFromNumber: z.string().max(20).optional(),\n smsToNumber: z.string().max(20).optional(),\n whatsappFromNumber: z.string().max(30).optional(),\n whatsappToNumber: z.string().max(30).optional(),\n fromNumber: z.string().max(20).optional(),\n toNumber: z.string().max(20).optional(),\n webhookUrl: z.string().url().max(500).optional(),\n notifyOn: NotifyOnSchema,\n quietHours: QuietHoursSchema.optional(),\n responseTimeout: z.number().int().min(30).max(3600),\n pendingPrompts: z.array(PendingPromptSchema).max(100),\n});\n\n// Action queue schemas\nexport const PendingActionSchema = z.object({\n id: z.string().max(32),\n promptId: z.string().max(32),\n response: z.string().max(1000),\n action: z.string().max(500),\n timestamp: z\n .string()\n .datetime({ offset: true })\n .or(z.string().regex(/^\\d{4}-\\d{2}-\\d{2}T/)),\n status: z.enum(['pending', 'running', 'completed', 'failed']),\n result: z.string().max(10000).optional(),\n error: z.string().max(1000).optional(),\n});\n\nexport const ActionQueueSchema = z.object({\n actions: z.array(PendingActionSchema).max(1000),\n lastChecked: z\n .string()\n .datetime({ offset: true })\n .or(z.string().regex(/^\\d{4}-\\d{2}-\\d{2}T/)),\n});\n\n// Auto-background config schema\nexport const AutoBackgroundConfigSchema = z.object({\n enabled: z.boolean(),\n timeoutMs: z.number().int().min(1000).max(600000),\n alwaysBackground: z.array(z.string().max(200)).max(100),\n neverBackground: z.array(z.string().max(200)).max(100),\n verbose: z.boolean().optional(),\n});\n\n// Type exports\nexport type SMSConfigValidated = z.infer<typeof SMSConfigSchema>;\nexport type ActionQueueValidated = z.infer<typeof ActionQueueSchema>;\nexport type AutoBackgroundConfigValidated = z.infer<\n typeof AutoBackgroundConfigSchema\n>;\n\n/**\n * Safely parse and validate config, returning default on failure\n */\nexport function parseConfigSafe<T>(\n schema: z.ZodSchema<T>,\n data: unknown,\n defaultValue: T,\n configName: string\n): T {\n const result = schema.safeParse(data);\n if (result.success) {\n return result.data;\n }\n console.error(\n `[hooks] Invalid ${configName} config:`,\n result.error.issues\n .map((i) => `${i.path.join('.')}: ${i.message}`)\n .join(', ')\n );\n return defaultValue;\n}\n"],
|
|
5
|
+
"mappings": ";;;;AAKA,SAAS,SAAS;AAGX,MAAM,qBAAqB,EAAE,OAAO;AAAA,EACzC,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE;AAAA,EACtB,OAAO,EAAE,OAAO,EAAE,IAAI,GAAG;AAAA,EACzB,QAAQ,EAAE,OAAO,EAAE,IAAI,GAAG,EAAE,SAAS;AACvC,CAAC;AAEM,MAAM,sBAAsB,EAAE,OAAO;AAAA,EAC1C,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE;AAAA,EACrB,WAAW,EACR,OAAO,EACP,SAAS,EAAE,QAAQ,KAAK,CAAC,EACzB,GAAG,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAAA,EAC7C,SAA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,IAAI,GAAM;AAAA,EAChD,kBAAkB,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,GAAG,CAAC,EAAE,IAAI,GAAG;AAAA,EACtD,iBAAiB,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,GAAG,CAAC,EAAE,IAAI,GAAG;AAAA,EACrD,SAAS,EAAE,QAAQ,EAAE,SAAS;AAChC,CAAC;AAYM,SAAS,gBACd,QACA,MACA,cACA,YACG;AACH,QAAM,SAAS,OAAO,UAAU,IAAI;AACpC,MAAI,OAAO,SAAS;AAClB,WAAO,OAAO;AAAA,EAChB;AACA,UAAQ;AAAA,IACN,mBAAmB,UAAU;AAAA,IAC7B,OAAO,MAAM,OACV,IAAI,CAAC,MAAM,GAAG,EAAE,KAAK,KAAK,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,EAC9C,KAAK,IAAI;AAAA,EACd;AACA,SAAO;AACT;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { fileURLToPath as __fileURLToPath } from 'url';
|
|
2
|
+
import { dirname as __pathDirname } from 'path';
|
|
3
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
4
|
+
const __dirname = __pathDirname(__filename);
|
|
5
|
+
import { writeFileSync, mkdirSync, chmodSync, existsSync } from "fs";
|
|
6
|
+
import { dirname } from "path";
|
|
7
|
+
function writeFileSecure(filePath, data) {
|
|
8
|
+
const dir = dirname(filePath);
|
|
9
|
+
if (!existsSync(dir)) {
|
|
10
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
11
|
+
}
|
|
12
|
+
writeFileSync(filePath, data);
|
|
13
|
+
chmodSync(filePath, 384);
|
|
14
|
+
}
|
|
15
|
+
function ensureSecureDir(dirPath) {
|
|
16
|
+
if (!existsSync(dirPath)) {
|
|
17
|
+
mkdirSync(dirPath, { recursive: true, mode: 448 });
|
|
18
|
+
} else {
|
|
19
|
+
try {
|
|
20
|
+
chmodSync(dirPath, 448);
|
|
21
|
+
} catch {
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export {
|
|
26
|
+
ensureSecureDir,
|
|
27
|
+
writeFileSecure
|
|
28
|
+
};
|
|
29
|
+
//# sourceMappingURL=secure-fs.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/hooks/secure-fs.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Secure file system utilities for hooks\n * Ensures config files have restricted permissions (0600)\n */\n\nimport { writeFileSync, mkdirSync, chmodSync, existsSync } from 'fs';\nimport { dirname } from 'path';\n\n/**\n * Write file with secure permissions (0600 - user read/write only)\n * Also ensures parent directory has 0700 permissions\n */\nexport function writeFileSecure(filePath: string, data: string): void {\n const dir = dirname(filePath);\n\n // Create directory with secure permissions if needed\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n\n // Write file\n writeFileSync(filePath, data);\n\n // Set secure permissions (user read/write only)\n chmodSync(filePath, 0o600);\n}\n\n/**\n * Ensure directory exists with secure permissions (0700)\n */\nexport function ensureSecureDir(dirPath: string): void {\n if (!existsSync(dirPath)) {\n mkdirSync(dirPath, { recursive: true, mode: 0o700 });\n } else {\n // Set permissions on existing directory\n try {\n chmodSync(dirPath, 0o700);\n } catch {\n // Ignore if we can't change permissions (not owner)\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;AAKA,SAAS,eAAe,WAAW,WAAW,kBAAkB;AAChE,SAAS,eAAe;AAMjB,SAAS,gBAAgB,UAAkB,MAAoB;AACpE,QAAM,MAAM,QAAQ,QAAQ;AAG5B,MAAI,CAAC,WAAW,GAAG,GAAG;AACpB,cAAU,KAAK,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AAAA,EACjD;AAGA,gBAAc,UAAU,IAAI;AAG5B,YAAU,UAAU,GAAK;AAC3B;AAKO,SAAS,gBAAgB,SAAuB;AACrD,MAAI,CAAC,WAAW,OAAO,GAAG;AACxB,cAAU,SAAS,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AAAA,EACrD,OAAO;AAEL,QAAI;AACF,gBAAU,SAAS,GAAK;AAAA,IAC1B,QAAQ;AAAA,IAER;AAAA,EACF;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -2,11 +2,13 @@ import { fileURLToPath as __fileURLToPath } from 'url';
|
|
|
2
2
|
import { dirname as __pathDirname } from 'path';
|
|
3
3
|
const __filename = __fileURLToPath(import.meta.url);
|
|
4
4
|
const __dirname = __pathDirname(__filename);
|
|
5
|
-
import { existsSync, readFileSync
|
|
5
|
+
import { existsSync, readFileSync } from "fs";
|
|
6
6
|
import { join } from "path";
|
|
7
7
|
import { homedir } from "os";
|
|
8
8
|
import { execSync, execFileSync } from "child_process";
|
|
9
9
|
import { randomBytes } from "crypto";
|
|
10
|
+
import { writeFileSecure, ensureSecureDir } from "./secure-fs.js";
|
|
11
|
+
import { ActionQueueSchema, parseConfigSafe } from "./schemas.js";
|
|
10
12
|
const SAFE_ACTION_PATTERNS = [
|
|
11
13
|
// Git/GitHub CLI commands (limited to safe operations)
|
|
12
14
|
{ pattern: /^gh pr (view|list|status|checks) (\d+)$/ },
|
|
@@ -31,22 +33,29 @@ function isActionAllowed(action) {
|
|
|
31
33
|
});
|
|
32
34
|
}
|
|
33
35
|
const QUEUE_PATH = join(homedir(), ".stackmemory", "sms-action-queue.json");
|
|
36
|
+
const DEFAULT_QUEUE = {
|
|
37
|
+
actions: [],
|
|
38
|
+
lastChecked: (/* @__PURE__ */ new Date()).toISOString()
|
|
39
|
+
};
|
|
34
40
|
function loadActionQueue() {
|
|
35
41
|
try {
|
|
36
42
|
if (existsSync(QUEUE_PATH)) {
|
|
37
|
-
|
|
43
|
+
const data = JSON.parse(readFileSync(QUEUE_PATH, "utf8"));
|
|
44
|
+
return parseConfigSafe(
|
|
45
|
+
ActionQueueSchema,
|
|
46
|
+
data,
|
|
47
|
+
DEFAULT_QUEUE,
|
|
48
|
+
"action-queue"
|
|
49
|
+
);
|
|
38
50
|
}
|
|
39
51
|
} catch {
|
|
40
52
|
}
|
|
41
|
-
return {
|
|
53
|
+
return { ...DEFAULT_QUEUE, lastChecked: (/* @__PURE__ */ new Date()).toISOString() };
|
|
42
54
|
}
|
|
43
55
|
function saveActionQueue(queue) {
|
|
44
56
|
try {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
mkdirSync(dir, { recursive: true });
|
|
48
|
-
}
|
|
49
|
-
writeFileSync(QUEUE_PATH, JSON.stringify(queue, null, 2));
|
|
57
|
+
ensureSecureDir(join(homedir(), ".stackmemory"));
|
|
58
|
+
writeFileSecure(QUEUE_PATH, JSON.stringify(queue, null, 2));
|
|
50
59
|
} catch {
|
|
51
60
|
}
|
|
52
61
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/hooks/sms-action-runner.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * SMS Action Runner - Executes actions based on SMS responses\n * Bridges SMS responses to Claude Code actions\n *\n * Security: Uses allowlist-based action execution to prevent command injection\n */\n\nimport { existsSync, readFileSync
|
|
5
|
-
"mappings": ";;;;AAOA,SAAS,YAAY,
|
|
4
|
+
"sourcesContent": ["/**\n * SMS Action Runner - Executes actions based on SMS responses\n * Bridges SMS responses to Claude Code actions\n *\n * Security: Uses allowlist-based action execution to prevent command injection\n */\n\nimport { existsSync, readFileSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { execSync, execFileSync } from 'child_process';\nimport { randomBytes } from 'crypto';\nimport { writeFileSecure, ensureSecureDir } from './secure-fs.js';\nimport { ActionQueueSchema, parseConfigSafe } from './schemas.js';\n\n// Allowlist of safe action patterns\nconst SAFE_ACTION_PATTERNS: Array<{\n pattern: RegExp;\n validate?: (match: RegExpMatchArray) => boolean;\n}> = [\n // Git/GitHub CLI commands (limited to safe operations)\n { pattern: /^gh pr (view|list|status|checks) (\\d+)$/ },\n { pattern: /^gh pr review (\\d+) --approve$/ },\n { pattern: /^gh pr merge (\\d+) --squash$/ },\n { pattern: /^gh issue (view|list) (\\d+)?$/ },\n\n // NPM commands (limited to safe operations)\n { pattern: /^npm run (build|test|lint|lint:fix|test:run)$/ },\n { pattern: /^npm (test|run build)$/ },\n\n // StackMemory commands\n { pattern: /^stackmemory (status|notify check|context list)$/ },\n\n // Simple echo/confirmation (no variables)\n { pattern: /^echo \"?(Done|OK|Confirmed|Acknowledged)\"?$/ },\n];\n\n/**\n * Check if an action is in the allowlist\n */\nfunction isActionAllowed(action: string): boolean {\n const trimmed = action.trim();\n return SAFE_ACTION_PATTERNS.some(({ pattern, validate }) => {\n const match = trimmed.match(pattern);\n if (!match) return false;\n if (validate && !validate(match)) return false;\n return true;\n });\n}\n\nexport interface PendingAction {\n id: string;\n promptId: string;\n response: string;\n action: string;\n timestamp: string;\n status: 'pending' | 'running' | 'completed' | 'failed';\n result?: string;\n error?: string;\n}\n\nexport interface ActionQueue {\n actions: PendingAction[];\n lastChecked: string;\n}\n\nconst QUEUE_PATH = join(homedir(), '.stackmemory', 'sms-action-queue.json');\n\nconst DEFAULT_QUEUE: ActionQueue = {\n actions: [],\n lastChecked: new Date().toISOString(),\n};\n\nexport function loadActionQueue(): ActionQueue {\n try {\n if (existsSync(QUEUE_PATH)) {\n const data = JSON.parse(readFileSync(QUEUE_PATH, 'utf8'));\n return parseConfigSafe(\n ActionQueueSchema,\n data,\n DEFAULT_QUEUE,\n 'action-queue'\n );\n }\n } catch {\n // Use defaults\n }\n return { ...DEFAULT_QUEUE, lastChecked: new Date().toISOString() };\n}\n\nexport function saveActionQueue(queue: ActionQueue): void {\n try {\n ensureSecureDir(join(homedir(), '.stackmemory'));\n writeFileSecure(QUEUE_PATH, JSON.stringify(queue, null, 2));\n } catch {\n // Silently fail\n }\n}\n\nexport function queueAction(\n promptId: string,\n response: string,\n action: string\n): string {\n const queue = loadActionQueue();\n // Use cryptographically secure random ID\n const id = randomBytes(8).toString('hex');\n\n queue.actions.push({\n id,\n promptId,\n response,\n action,\n timestamp: new Date().toISOString(),\n status: 'pending',\n });\n\n saveActionQueue(queue);\n return id;\n}\n\n/**\n * Execute an action safely using allowlist validation\n * This prevents command injection by only allowing pre-approved commands\n */\nexport function executeActionSafe(\n action: string,\n _response: string\n): { success: boolean; output?: string; error?: string } {\n // Check if action is in allowlist\n if (!isActionAllowed(action)) {\n console.error(`[sms-action] Action not in allowlist: ${action}`);\n return {\n success: false,\n error: `Action not allowed. Only pre-approved commands can be executed via SMS.`,\n };\n }\n\n try {\n console.log(`[sms-action] Executing safe action: ${action}`);\n\n // Parse the action into command and args\n const parts = action.split(' ');\n const cmd = parts[0];\n const args = parts.slice(1);\n\n // Use execFileSync for commands without shell interpretation\n // This prevents shell injection even if the allowlist is somehow bypassed\n const output = execFileSync(cmd, args, {\n encoding: 'utf8',\n timeout: 60000,\n stdio: ['pipe', 'pipe', 'pipe'],\n shell: false, // Explicitly disable shell\n });\n\n return { success: true, output };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return { success: false, error };\n }\n}\n\nexport function getPendingActions(): PendingAction[] {\n const queue = loadActionQueue();\n return queue.actions.filter((a) => a.status === 'pending');\n}\n\nexport function markActionRunning(id: string): void {\n const queue = loadActionQueue();\n const action = queue.actions.find((a) => a.id === id);\n if (action) {\n action.status = 'running';\n saveActionQueue(queue);\n }\n}\n\nexport function markActionCompleted(\n id: string,\n result?: string,\n error?: string\n): void {\n const queue = loadActionQueue();\n const action = queue.actions.find((a) => a.id === id);\n if (action) {\n action.status = error ? 'failed' : 'completed';\n action.result = result;\n action.error = error;\n saveActionQueue(queue);\n }\n}\n\nexport function executeAction(action: PendingAction): {\n success: boolean;\n output?: string;\n error?: string;\n} {\n markActionRunning(action.id);\n\n try {\n console.log(`[sms-action] Executing: ${action.action}`);\n\n // Execute the action\n const output = execSync(action.action, {\n encoding: 'utf8',\n timeout: 60000, // 1 minute timeout\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n markActionCompleted(action.id, output);\n return { success: true, output };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n markActionCompleted(action.id, undefined, error);\n return { success: false, error };\n }\n}\n\nexport function processAllPendingActions(): {\n processed: number;\n succeeded: number;\n failed: number;\n} {\n const pending = getPendingActions();\n let succeeded = 0;\n let failed = 0;\n\n for (const action of pending) {\n const result = executeAction(action);\n if (result.success) {\n succeeded++;\n } else {\n failed++;\n }\n }\n\n return { processed: pending.length, succeeded, failed };\n}\n\n// Clean up old completed actions (keep last 50)\nexport function cleanupOldActions(): number {\n const queue = loadActionQueue();\n const completed = queue.actions.filter(\n (a) => a.status === 'completed' || a.status === 'failed'\n );\n\n if (completed.length > 50) {\n const toRemove = completed.slice(0, completed.length - 50);\n queue.actions = queue.actions.filter(\n (a) => !toRemove.find((r) => r.id === a.id)\n );\n saveActionQueue(queue);\n return toRemove.length;\n }\n\n return 0;\n}\n\n/**\n * Action Templates - Common actions for SMS responses\n *\n * SECURITY NOTE: These templates return command strings that must be\n * validated against SAFE_ACTION_PATTERNS before execution.\n * Templates that accept user input are removed to prevent injection.\n */\nexport const ACTION_TEMPLATES = {\n // Git/PR actions (PR numbers must be validated as integers)\n approvePR: (prNumber: string) => {\n // Validate PR number is numeric only\n if (!/^\\d+$/.test(prNumber)) {\n throw new Error('Invalid PR number');\n }\n return `gh pr review ${prNumber} --approve`;\n },\n mergePR: (prNumber: string) => {\n if (!/^\\d+$/.test(prNumber)) {\n throw new Error('Invalid PR number');\n }\n return `gh pr merge ${prNumber} --squash`;\n },\n viewPR: (prNumber: string) => {\n if (!/^\\d+$/.test(prNumber)) {\n throw new Error('Invalid PR number');\n }\n return `gh pr view ${prNumber}`;\n },\n\n // Build actions (no user input)\n rebuild: () => `npm run build`,\n retest: () => `npm run test:run`,\n lint: () => `npm run lint:fix`,\n\n // Status actions (no user input)\n status: () => `stackmemory status`,\n checkNotifications: () => `stackmemory notify check`,\n\n // REMOVED for security - these templates allowed arbitrary user input:\n // - requestChanges (allowed arbitrary message)\n // - closePR (could be used maliciously)\n // - deploy/rollback (too dangerous for SMS)\n // - verifyDeployment (allowed arbitrary URL)\n // - notifySlack (allowed arbitrary message - command injection)\n // - notifyTeam (allowed arbitrary message - command injection)\n};\n\n/**\n * Create action string from template\n */\nexport function createAction(\n template: keyof typeof ACTION_TEMPLATES,\n ...args: string[]\n): string {\n const fn = ACTION_TEMPLATES[template];\n if (typeof fn === 'function') {\n return (fn as (...args: string[]) => string)(...args);\n }\n return fn;\n}\n\n/**\n * Watch for new actions and execute them\n */\nexport function startActionWatcher(intervalMs: number = 5000): NodeJS.Timeout {\n console.log(\n `[sms-action] Starting action watcher (interval: ${intervalMs}ms)`\n );\n\n return setInterval(() => {\n const pending = getPendingActions();\n if (pending.length > 0) {\n console.log(`[sms-action] Found ${pending.length} pending action(s)`);\n processAllPendingActions();\n }\n }, intervalMs);\n}\n\n/**\n * Integration with SMS webhook - queue action when response received\n */\nexport function handleSMSResponse(\n promptId: string,\n response: string,\n action?: string\n): void {\n if (action) {\n const actionId = queueAction(promptId, response, action);\n console.log(`[sms-action] Queued action ${actionId}: ${action}`);\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;AAOA,SAAS,YAAY,oBAAoB;AACzC,SAAS,YAAY;AACrB,SAAS,eAAe;AACxB,SAAS,UAAU,oBAAoB;AACvC,SAAS,mBAAmB;AAC5B,SAAS,iBAAiB,uBAAuB;AACjD,SAAS,mBAAmB,uBAAuB;AAGnD,MAAM,uBAGD;AAAA;AAAA,EAEH,EAAE,SAAS,0CAA0C;AAAA,EACrD,EAAE,SAAS,iCAAiC;AAAA,EAC5C,EAAE,SAAS,+BAA+B;AAAA,EAC1C,EAAE,SAAS,gCAAgC;AAAA;AAAA,EAG3C,EAAE,SAAS,gDAAgD;AAAA,EAC3D,EAAE,SAAS,yBAAyB;AAAA;AAAA,EAGpC,EAAE,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|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/hooks/sms-notify.js
CHANGED
|
@@ -2,10 +2,12 @@ import { fileURLToPath as __fileURLToPath } from 'url';
|
|
|
2
2
|
import { dirname as __pathDirname } from 'path';
|
|
3
3
|
const __filename = __fileURLToPath(import.meta.url);
|
|
4
4
|
const __dirname = __pathDirname(__filename);
|
|
5
|
-
import { existsSync, readFileSync
|
|
5
|
+
import { existsSync, readFileSync } from "fs";
|
|
6
6
|
import { join } from "path";
|
|
7
7
|
import { homedir } from "os";
|
|
8
8
|
import { config as loadDotenv } from "dotenv";
|
|
9
|
+
import { writeFileSecure, ensureSecureDir } from "./secure-fs.js";
|
|
10
|
+
import { SMSConfigSchema, parseConfigSafe } from "./schemas.js";
|
|
9
11
|
const CONFIG_PATH = join(homedir(), ".stackmemory", "sms-notify.json");
|
|
10
12
|
const DEFAULT_CONFIG = {
|
|
11
13
|
enabled: false,
|
|
@@ -34,10 +36,15 @@ function loadSMSConfig() {
|
|
|
34
36
|
try {
|
|
35
37
|
if (existsSync(CONFIG_PATH)) {
|
|
36
38
|
const data = readFileSync(CONFIG_PATH, "utf8");
|
|
37
|
-
const
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
39
|
+
const parsed = JSON.parse(data);
|
|
40
|
+
const validated = parseConfigSafe(
|
|
41
|
+
SMSConfigSchema,
|
|
42
|
+
{ ...DEFAULT_CONFIG, ...parsed },
|
|
43
|
+
DEFAULT_CONFIG,
|
|
44
|
+
"sms-notify"
|
|
45
|
+
);
|
|
46
|
+
applyEnvVars(validated);
|
|
47
|
+
return validated;
|
|
41
48
|
}
|
|
42
49
|
} catch {
|
|
43
50
|
}
|
|
@@ -124,14 +131,11 @@ function applyEnvVars(config) {
|
|
|
124
131
|
}
|
|
125
132
|
function saveSMSConfig(config) {
|
|
126
133
|
try {
|
|
127
|
-
|
|
128
|
-
if (!existsSync(dir)) {
|
|
129
|
-
mkdirSync(dir, { recursive: true });
|
|
130
|
-
}
|
|
134
|
+
ensureSecureDir(join(homedir(), ".stackmemory"));
|
|
131
135
|
const safeConfig = { ...config };
|
|
132
136
|
delete safeConfig.accountSid;
|
|
133
137
|
delete safeConfig.authToken;
|
|
134
|
-
|
|
138
|
+
writeFileSecure(CONFIG_PATH, JSON.stringify(safeConfig, null, 2));
|
|
135
139
|
} catch {
|
|
136
140
|
}
|
|
137
141
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/hooks/sms-notify.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * SMS Notification Hook for StackMemory\n * Sends text messages when tasks are ready for review\n * Supports interactive prompts with numbered options or yes/no\n *\n * Optional feature - requires Twilio setup\n */\n\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { config as loadDotenv } from 'dotenv';\n\nexport type MessageChannel = 'whatsapp' | 'sms';\n\nexport interface SMSConfig {\n enabled: boolean;\n // Preferred channel: whatsapp is cheaper for back-and-forth conversations\n channel: MessageChannel;\n // Twilio credentials (from env or config)\n accountSid?: string;\n authToken?: string;\n // SMS numbers\n smsFromNumber?: string;\n smsToNumber?: string;\n // WhatsApp numbers (Twilio prefixes with 'whatsapp:' automatically)\n whatsappFromNumber?: string;\n whatsappToNumber?: string;\n // Legacy fields (backwards compatibility)\n fromNumber?: string;\n toNumber?: string;\n // Webhook URL for receiving responses\n webhookUrl?: string;\n // Notification preferences\n notifyOn: {\n taskComplete: boolean;\n reviewReady: boolean;\n error: boolean;\n custom: boolean;\n };\n // Quiet hours (don't send during these times)\n quietHours?: {\n enabled: boolean;\n start: string; // \"22:00\"\n end: string; // \"08:00\"\n };\n // Response timeout (seconds)\n responseTimeout: number;\n // Pending prompts awaiting response\n pendingPrompts: PendingPrompt[];\n}\n\nexport interface PendingPrompt {\n id: string;\n timestamp: string;\n message: string;\n options: PromptOption[];\n type: 'options' | 'yesno' | 'freeform';\n callback?: string; // Command to run with response\n expiresAt: string;\n}\n\nexport interface PromptOption {\n key: string; // \"1\", \"2\", \"y\", \"n\", etc.\n label: string;\n action?: string; // Command to execute\n}\n\nexport interface NotificationPayload {\n type: 'task_complete' | 'review_ready' | 'error' | 'custom';\n title: string;\n message: string;\n prompt?: {\n type: 'options' | 'yesno' | 'freeform';\n options?: PromptOption[];\n question?: string;\n };\n metadata?: Record<string, unknown>;\n}\n\nconst CONFIG_PATH = join(homedir(), '.stackmemory', 'sms-notify.json');\n\nconst DEFAULT_CONFIG: SMSConfig = {\n enabled: false,\n channel: 'whatsapp', // WhatsApp is cheaper for conversations\n notifyOn: {\n taskComplete: true,\n reviewReady: true,\n error: true,\n custom: true,\n },\n quietHours: {\n enabled: false,\n start: '22:00',\n end: '08:00',\n },\n responseTimeout: 300, // 5 minutes\n pendingPrompts: [],\n};\n\nexport function loadSMSConfig(): SMSConfig {\n // Load .env files (project, home, global)\n loadDotenv({ path: join(process.cwd(), '.env') });\n loadDotenv({ path: join(process.cwd(), '.env.local') });\n loadDotenv({ path: join(homedir(), '.env') });\n loadDotenv({ path: join(homedir(), '.stackmemory', '.env') });\n\n try {\n if (existsSync(CONFIG_PATH)) {\n const data = readFileSync(CONFIG_PATH, 'utf8');\n const saved = JSON.parse(data);\n // Merge with defaults, then apply env vars\n const config = { ...DEFAULT_CONFIG, ...saved };\n applyEnvVars(config);\n return config;\n }\n } catch {\n // Use defaults\n }\n\n // Check environment variables\n const config = { ...DEFAULT_CONFIG };\n applyEnvVars(config);\n return config;\n}\n\n// Check what's missing for notifications to work\nexport function getMissingConfig(): {\n missing: string[];\n configured: string[];\n ready: boolean;\n} {\n const config = loadSMSConfig();\n const missing: string[] = [];\n const configured: string[] = [];\n\n // Check credentials\n if (config.accountSid) {\n configured.push('TWILIO_ACCOUNT_SID');\n } else {\n missing.push('TWILIO_ACCOUNT_SID');\n }\n\n if (config.authToken) {\n configured.push('TWILIO_AUTH_TOKEN');\n } else {\n missing.push('TWILIO_AUTH_TOKEN');\n }\n\n // Check channel-specific numbers\n const channel = config.channel || 'whatsapp';\n\n if (channel === 'whatsapp') {\n const from = config.whatsappFromNumber || config.fromNumber;\n const to = config.whatsappToNumber || config.toNumber;\n\n if (from) {\n configured.push('TWILIO_WHATSAPP_FROM');\n } else {\n missing.push('TWILIO_WHATSAPP_FROM');\n }\n\n if (to) {\n configured.push('TWILIO_WHATSAPP_TO');\n } else {\n missing.push('TWILIO_WHATSAPP_TO');\n }\n } else {\n const from = config.smsFromNumber || config.fromNumber;\n const to = config.smsToNumber || config.toNumber;\n\n if (from) {\n configured.push('TWILIO_SMS_FROM');\n } else {\n missing.push('TWILIO_SMS_FROM');\n }\n\n if (to) {\n configured.push('TWILIO_SMS_TO');\n } else {\n missing.push('TWILIO_SMS_TO');\n }\n }\n\n return {\n missing,\n configured,\n ready: missing.length === 0,\n };\n}\n\nfunction applyEnvVars(config: SMSConfig): void {\n // Twilio credentials\n if (process.env['TWILIO_ACCOUNT_SID']) {\n config.accountSid = process.env['TWILIO_ACCOUNT_SID'];\n }\n if (process.env['TWILIO_AUTH_TOKEN']) {\n config.authToken = process.env['TWILIO_AUTH_TOKEN'];\n }\n\n // SMS numbers\n if (process.env['TWILIO_SMS_FROM'] || process.env['TWILIO_FROM_NUMBER']) {\n config.smsFromNumber =\n process.env['TWILIO_SMS_FROM'] || process.env['TWILIO_FROM_NUMBER'];\n }\n if (process.env['TWILIO_SMS_TO'] || process.env['TWILIO_TO_NUMBER']) {\n config.smsToNumber =\n process.env['TWILIO_SMS_TO'] || process.env['TWILIO_TO_NUMBER'];\n }\n\n // WhatsApp numbers\n if (process.env['TWILIO_WHATSAPP_FROM']) {\n config.whatsappFromNumber = process.env['TWILIO_WHATSAPP_FROM'];\n }\n if (process.env['TWILIO_WHATSAPP_TO']) {\n config.whatsappToNumber = process.env['TWILIO_WHATSAPP_TO'];\n }\n\n // Legacy support\n if (process.env['TWILIO_FROM_NUMBER']) {\n config.fromNumber = process.env['TWILIO_FROM_NUMBER'];\n }\n if (process.env['TWILIO_TO_NUMBER']) {\n config.toNumber = process.env['TWILIO_TO_NUMBER'];\n }\n\n // Channel preference\n if (process.env['TWILIO_CHANNEL']) {\n config.channel = process.env['TWILIO_CHANNEL'] as MessageChannel;\n }\n}\n\nexport function saveSMSConfig(config: SMSConfig): void {\n try {\n const dir = join(homedir(), '.stackmemory');\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n // Don't save sensitive credentials to file\n const safeConfig = { ...config };\n delete safeConfig.accountSid;\n delete safeConfig.authToken;\n writeFileSync(CONFIG_PATH, JSON.stringify(safeConfig, null, 2));\n } catch {\n // Silently fail\n }\n}\n\nfunction isQuietHours(config: SMSConfig): boolean {\n if (!config.quietHours?.enabled) return false;\n\n const now = new Date();\n const currentTime = now.getHours() * 60 + now.getMinutes();\n\n const [startH, startM] = config.quietHours.start.split(':').map(Number);\n const [endH, endM] = config.quietHours.end.split(':').map(Number);\n\n const startTime = startH * 60 + startM;\n const endTime = endH * 60 + endM;\n\n // Handle overnight quiet hours (e.g., 22:00 - 08:00)\n if (startTime > endTime) {\n return currentTime >= startTime || currentTime < endTime;\n }\n\n return currentTime >= startTime && currentTime < endTime;\n}\n\nfunction generatePromptId(): string {\n return Math.random().toString(36).substring(2, 10);\n}\n\nfunction formatPromptMessage(payload: NotificationPayload): string {\n let message = `${payload.title}\\n\\n${payload.message}`;\n\n if (payload.prompt) {\n message += '\\n\\n';\n\n if (payload.prompt.question) {\n message += `${payload.prompt.question}\\n`;\n }\n\n if (payload.prompt.type === 'yesno') {\n message += 'Reply Y for Yes, N for No';\n } else if (payload.prompt.type === 'options' && payload.prompt.options) {\n payload.prompt.options.forEach((opt) => {\n message += `${opt.key}. ${opt.label}\\n`;\n });\n message += '\\nReply with number to select';\n } else if (payload.prompt.type === 'freeform') {\n message += 'Reply with your response';\n }\n }\n\n return message;\n}\n\nfunction getChannelNumbers(config: SMSConfig): {\n from: string;\n to: string;\n channel: MessageChannel;\n} | null {\n const channel = config.channel || 'whatsapp';\n\n if (channel === 'whatsapp') {\n // Try WhatsApp first\n const from = config.whatsappFromNumber || config.fromNumber;\n const to = config.whatsappToNumber || config.toNumber;\n if (from && to) {\n // Twilio requires 'whatsapp:' prefix for WhatsApp numbers\n return {\n from: from.startsWith('whatsapp:') ? from : `whatsapp:${from}`,\n to: to.startsWith('whatsapp:') ? to : `whatsapp:${to}`,\n channel: 'whatsapp',\n };\n }\n }\n\n // Fall back to SMS\n const from = config.smsFromNumber || config.fromNumber;\n const to = config.smsToNumber || config.toNumber;\n if (from && to) {\n return { from, to, channel: 'sms' };\n }\n\n return null;\n}\n\nexport async function sendNotification(\n payload: NotificationPayload,\n channelOverride?: MessageChannel\n): Promise<{\n success: boolean;\n promptId?: string;\n channel?: MessageChannel;\n error?: string;\n}> {\n const config = loadSMSConfig();\n\n if (!config.enabled) {\n return { success: false, error: 'Notifications disabled' };\n }\n\n // Check notification type is enabled\n const typeMap: Record<string, keyof typeof config.notifyOn> = {\n task_complete: 'taskComplete',\n review_ready: 'reviewReady',\n error: 'error',\n custom: 'custom',\n };\n\n if (!config.notifyOn[typeMap[payload.type]]) {\n return {\n success: false,\n error: `Notifications for ${payload.type} disabled`,\n };\n }\n\n // Check quiet hours\n if (isQuietHours(config)) {\n return { success: false, error: 'Quiet hours active' };\n }\n\n // Validate credentials\n if (!config.accountSid || !config.authToken) {\n return {\n success: false,\n error:\n 'Missing Twilio credentials. Set TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN',\n };\n }\n\n // Get channel numbers (prefer WhatsApp)\n const originalChannel = config.channel;\n if (channelOverride) {\n config.channel = channelOverride;\n }\n\n const numbers = getChannelNumbers(config);\n config.channel = originalChannel; // Restore\n\n if (!numbers) {\n return {\n success: false,\n error:\n config.channel === 'whatsapp'\n ? 'Missing WhatsApp numbers. Set TWILIO_WHATSAPP_FROM and TWILIO_WHATSAPP_TO'\n : 'Missing SMS numbers. Set TWILIO_SMS_FROM and TWILIO_SMS_TO',\n };\n }\n\n const message = formatPromptMessage(payload);\n let promptId: string | undefined;\n\n // Store pending prompt if interactive\n if (payload.prompt) {\n promptId = generatePromptId();\n const expiresAt = new Date(\n Date.now() + config.responseTimeout * 1000\n ).toISOString();\n\n const pendingPrompt: PendingPrompt = {\n id: promptId,\n timestamp: new Date().toISOString(),\n message: payload.message,\n options: payload.prompt.options || [],\n type: payload.prompt.type,\n expiresAt,\n };\n\n config.pendingPrompts.push(pendingPrompt);\n saveSMSConfig(config);\n }\n\n try {\n // Use Twilio API (same endpoint for SMS and WhatsApp)\n const twilioUrl = `https://api.twilio.com/2010-04-01/Accounts/${config.accountSid}/Messages.json`;\n\n const response = await fetch(twilioUrl, {\n method: 'POST',\n headers: {\n Authorization:\n 'Basic ' +\n Buffer.from(`${config.accountSid}:${config.authToken}`).toString(\n 'base64'\n ),\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n From: numbers.from,\n To: numbers.to,\n Body: message,\n }),\n });\n\n if (!response.ok) {\n const errorData = await response.text();\n return {\n success: false,\n channel: numbers.channel,\n error: `Twilio error: ${errorData}`,\n };\n }\n\n return { success: true, promptId, channel: numbers.channel };\n } catch (err) {\n return {\n success: false,\n channel: numbers.channel,\n error: `Failed to send ${numbers.channel}: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n}\n\n// Backwards compatible alias\nexport async function sendSMSNotification(\n payload: NotificationPayload\n): Promise<{ success: boolean; promptId?: string; error?: string }> {\n return sendNotification(payload);\n}\n\nexport function processIncomingResponse(\n from: string,\n body: string\n): {\n matched: boolean;\n prompt?: PendingPrompt;\n response?: string;\n action?: string;\n} {\n const config = loadSMSConfig();\n\n // Normalize response\n const response = body.trim().toLowerCase();\n\n // Find matching pending prompt (most recent first)\n const now = new Date();\n const validPrompts = config.pendingPrompts.filter(\n (p) => new Date(p.expiresAt) > now\n );\n\n if (validPrompts.length === 0) {\n return { matched: false };\n }\n\n // Get most recent prompt\n const prompt = validPrompts[validPrompts.length - 1];\n\n let matchedOption: PromptOption | undefined;\n\n if (prompt.type === 'yesno') {\n if (response === 'y' || response === 'yes') {\n matchedOption = { key: 'y', label: 'Yes' };\n } else if (response === 'n' || response === 'no') {\n matchedOption = { key: 'n', label: 'No' };\n }\n } else if (prompt.type === 'options') {\n matchedOption = prompt.options.find(\n (opt) => opt.key.toLowerCase() === response\n );\n } else if (prompt.type === 'freeform') {\n matchedOption = { key: response, label: response };\n }\n\n // Remove processed prompt\n config.pendingPrompts = config.pendingPrompts.filter(\n (p) => p.id !== prompt.id\n );\n saveSMSConfig(config);\n\n if (matchedOption) {\n return {\n matched: true,\n prompt,\n response: matchedOption.key,\n action: matchedOption.action,\n };\n }\n\n return { matched: false, prompt };\n}\n\n// Convenience functions for common notifications\n\nexport async function notifyReviewReady(\n title: string,\n description: string,\n options?: { label: string; action?: string }[]\n): Promise<{ success: boolean; promptId?: string; error?: string }> {\n const payload: NotificationPayload = {\n type: 'review_ready',\n title: `Review Ready: ${title}`,\n message: description,\n };\n\n if (options && options.length > 0) {\n payload.prompt = {\n type: 'options',\n options: options.map((opt, i) => ({\n key: String(i + 1),\n label: opt.label,\n action: opt.action,\n })),\n question: 'What would you like to do?',\n };\n }\n\n return sendSMSNotification(payload);\n}\n\nexport async function notifyWithYesNo(\n title: string,\n question: string,\n yesAction?: string,\n noAction?: string\n): Promise<{ success: boolean; promptId?: string; error?: string }> {\n return sendSMSNotification({\n type: 'custom',\n title,\n message: question,\n prompt: {\n type: 'yesno',\n options: [\n { key: 'y', label: 'Yes', action: yesAction },\n { key: 'n', label: 'No', action: noAction },\n ],\n },\n });\n}\n\nexport async function notifyTaskComplete(\n taskName: string,\n summary: string\n): Promise<{ success: boolean; error?: string }> {\n return sendSMSNotification({\n type: 'task_complete',\n title: `Task Complete: ${taskName}`,\n message: summary,\n });\n}\n\nexport async function notifyError(\n error: string,\n context?: string\n): Promise<{ success: boolean; error?: string }> {\n return sendSMSNotification({\n type: 'error',\n title: 'Error Alert',\n message: context ? `${error}\\n\\nContext: ${context}` : error,\n });\n}\n\n// Clean up expired prompts\nexport function cleanupExpiredPrompts(): number {\n const config = loadSMSConfig();\n const now = new Date();\n const before = config.pendingPrompts.length;\n\n config.pendingPrompts = config.pendingPrompts.filter(\n (p) => new Date(p.expiresAt) > now\n );\n\n const removed = before - config.pendingPrompts.length;\n if (removed > 0) {\n saveSMSConfig(config);\n }\n\n return removed;\n}\n"],
|
|
5
|
-
"mappings": ";;;;AAQA,SAAS,YAAY,
|
|
6
|
-
"names": ["
|
|
4
|
+
"sourcesContent": ["/**\n * SMS Notification Hook for StackMemory\n * Sends text messages when tasks are ready for review\n * Supports interactive prompts with numbered options or yes/no\n *\n * Optional feature - requires Twilio setup\n */\n\nimport { existsSync, readFileSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { config as loadDotenv } from 'dotenv';\nimport { writeFileSecure, ensureSecureDir } from './secure-fs.js';\nimport { SMSConfigSchema, parseConfigSafe } from './schemas.js';\n\nexport type MessageChannel = 'whatsapp' | 'sms';\n\nexport interface SMSConfig {\n enabled: boolean;\n // Preferred channel: whatsapp is cheaper for back-and-forth conversations\n channel: MessageChannel;\n // Twilio credentials (from env or config)\n accountSid?: string;\n authToken?: string;\n // SMS numbers\n smsFromNumber?: string;\n smsToNumber?: string;\n // WhatsApp numbers (Twilio prefixes with 'whatsapp:' automatically)\n whatsappFromNumber?: string;\n whatsappToNumber?: string;\n // Legacy fields (backwards compatibility)\n fromNumber?: string;\n toNumber?: string;\n // Webhook URL for receiving responses\n webhookUrl?: string;\n // Notification preferences\n notifyOn: {\n taskComplete: boolean;\n reviewReady: boolean;\n error: boolean;\n custom: boolean;\n };\n // Quiet hours (don't send during these times)\n quietHours?: {\n enabled: boolean;\n start: string; // \"22:00\"\n end: string; // \"08:00\"\n };\n // Response timeout (seconds)\n responseTimeout: number;\n // Pending prompts awaiting response\n pendingPrompts: PendingPrompt[];\n}\n\nexport interface PendingPrompt {\n id: string;\n timestamp: string;\n message: string;\n options: PromptOption[];\n type: 'options' | 'yesno' | 'freeform';\n callback?: string; // Command to run with response\n expiresAt: string;\n}\n\nexport interface PromptOption {\n key: string; // \"1\", \"2\", \"y\", \"n\", etc.\n label: string;\n action?: string; // Command to execute\n}\n\nexport interface NotificationPayload {\n type: 'task_complete' | 'review_ready' | 'error' | 'custom';\n title: string;\n message: string;\n prompt?: {\n type: 'options' | 'yesno' | 'freeform';\n options?: PromptOption[];\n question?: string;\n };\n metadata?: Record<string, unknown>;\n}\n\nconst CONFIG_PATH = join(homedir(), '.stackmemory', 'sms-notify.json');\n\nconst DEFAULT_CONFIG: SMSConfig = {\n enabled: false,\n channel: 'whatsapp', // WhatsApp is cheaper for conversations\n notifyOn: {\n taskComplete: true,\n reviewReady: true,\n error: true,\n custom: true,\n },\n quietHours: {\n enabled: false,\n start: '22:00',\n end: '08:00',\n },\n responseTimeout: 300, // 5 minutes\n pendingPrompts: [],\n};\n\nexport function loadSMSConfig(): SMSConfig {\n // Load .env files (project, home, global)\n loadDotenv({ path: join(process.cwd(), '.env') });\n loadDotenv({ path: join(process.cwd(), '.env.local') });\n loadDotenv({ path: join(homedir(), '.env') });\n loadDotenv({ path: join(homedir(), '.stackmemory', '.env') });\n\n try {\n if (existsSync(CONFIG_PATH)) {\n const data = readFileSync(CONFIG_PATH, 'utf8');\n const parsed = JSON.parse(data);\n // Validate with zod schema, fall back to defaults on invalid config\n const validated = parseConfigSafe(\n SMSConfigSchema,\n { ...DEFAULT_CONFIG, ...parsed },\n DEFAULT_CONFIG,\n 'sms-notify'\n );\n applyEnvVars(validated);\n return validated;\n }\n } catch {\n // Use defaults\n }\n\n // Check environment variables\n const config = { ...DEFAULT_CONFIG };\n applyEnvVars(config);\n return config;\n}\n\n// Check what's missing for notifications to work\nexport function getMissingConfig(): {\n missing: string[];\n configured: string[];\n ready: boolean;\n} {\n const config = loadSMSConfig();\n const missing: string[] = [];\n const configured: string[] = [];\n\n // Check credentials\n if (config.accountSid) {\n configured.push('TWILIO_ACCOUNT_SID');\n } else {\n missing.push('TWILIO_ACCOUNT_SID');\n }\n\n if (config.authToken) {\n configured.push('TWILIO_AUTH_TOKEN');\n } else {\n missing.push('TWILIO_AUTH_TOKEN');\n }\n\n // Check channel-specific numbers\n const channel = config.channel || 'whatsapp';\n\n if (channel === 'whatsapp') {\n const from = config.whatsappFromNumber || config.fromNumber;\n const to = config.whatsappToNumber || config.toNumber;\n\n if (from) {\n configured.push('TWILIO_WHATSAPP_FROM');\n } else {\n missing.push('TWILIO_WHATSAPP_FROM');\n }\n\n if (to) {\n configured.push('TWILIO_WHATSAPP_TO');\n } else {\n missing.push('TWILIO_WHATSAPP_TO');\n }\n } else {\n const from = config.smsFromNumber || config.fromNumber;\n const to = config.smsToNumber || config.toNumber;\n\n if (from) {\n configured.push('TWILIO_SMS_FROM');\n } else {\n missing.push('TWILIO_SMS_FROM');\n }\n\n if (to) {\n configured.push('TWILIO_SMS_TO');\n } else {\n missing.push('TWILIO_SMS_TO');\n }\n }\n\n return {\n missing,\n configured,\n ready: missing.length === 0,\n };\n}\n\nfunction applyEnvVars(config: SMSConfig): void {\n // Twilio credentials\n if (process.env['TWILIO_ACCOUNT_SID']) {\n config.accountSid = process.env['TWILIO_ACCOUNT_SID'];\n }\n if (process.env['TWILIO_AUTH_TOKEN']) {\n config.authToken = process.env['TWILIO_AUTH_TOKEN'];\n }\n\n // SMS numbers\n if (process.env['TWILIO_SMS_FROM'] || process.env['TWILIO_FROM_NUMBER']) {\n config.smsFromNumber =\n process.env['TWILIO_SMS_FROM'] || process.env['TWILIO_FROM_NUMBER'];\n }\n if (process.env['TWILIO_SMS_TO'] || process.env['TWILIO_TO_NUMBER']) {\n config.smsToNumber =\n process.env['TWILIO_SMS_TO'] || process.env['TWILIO_TO_NUMBER'];\n }\n\n // WhatsApp numbers\n if (process.env['TWILIO_WHATSAPP_FROM']) {\n config.whatsappFromNumber = process.env['TWILIO_WHATSAPP_FROM'];\n }\n if (process.env['TWILIO_WHATSAPP_TO']) {\n config.whatsappToNumber = process.env['TWILIO_WHATSAPP_TO'];\n }\n\n // Legacy support\n if (process.env['TWILIO_FROM_NUMBER']) {\n config.fromNumber = process.env['TWILIO_FROM_NUMBER'];\n }\n if (process.env['TWILIO_TO_NUMBER']) {\n config.toNumber = process.env['TWILIO_TO_NUMBER'];\n }\n\n // Channel preference\n if (process.env['TWILIO_CHANNEL']) {\n config.channel = process.env['TWILIO_CHANNEL'] as MessageChannel;\n }\n}\n\nexport function saveSMSConfig(config: SMSConfig): void {\n try {\n ensureSecureDir(join(homedir(), '.stackmemory'));\n // Don't save sensitive credentials to file\n const safeConfig = { ...config };\n delete safeConfig.accountSid;\n delete safeConfig.authToken;\n writeFileSecure(CONFIG_PATH, JSON.stringify(safeConfig, null, 2));\n } catch {\n // Silently fail\n }\n}\n\nfunction isQuietHours(config: SMSConfig): boolean {\n if (!config.quietHours?.enabled) return false;\n\n const now = new Date();\n const currentTime = now.getHours() * 60 + now.getMinutes();\n\n const [startH, startM] = config.quietHours.start.split(':').map(Number);\n const [endH, endM] = config.quietHours.end.split(':').map(Number);\n\n const startTime = startH * 60 + startM;\n const endTime = endH * 60 + endM;\n\n // Handle overnight quiet hours (e.g., 22:00 - 08:00)\n if (startTime > endTime) {\n return currentTime >= startTime || currentTime < endTime;\n }\n\n return currentTime >= startTime && currentTime < endTime;\n}\n\nfunction generatePromptId(): string {\n return Math.random().toString(36).substring(2, 10);\n}\n\nfunction formatPromptMessage(payload: NotificationPayload): string {\n let message = `${payload.title}\\n\\n${payload.message}`;\n\n if (payload.prompt) {\n message += '\\n\\n';\n\n if (payload.prompt.question) {\n message += `${payload.prompt.question}\\n`;\n }\n\n if (payload.prompt.type === 'yesno') {\n message += 'Reply Y for Yes, N for No';\n } else if (payload.prompt.type === 'options' && payload.prompt.options) {\n payload.prompt.options.forEach((opt) => {\n message += `${opt.key}. ${opt.label}\\n`;\n });\n message += '\\nReply with number to select';\n } else if (payload.prompt.type === 'freeform') {\n message += 'Reply with your response';\n }\n }\n\n return message;\n}\n\nfunction getChannelNumbers(config: SMSConfig): {\n from: string;\n to: string;\n channel: MessageChannel;\n} | null {\n const channel = config.channel || 'whatsapp';\n\n if (channel === 'whatsapp') {\n // Try WhatsApp first\n const from = config.whatsappFromNumber || config.fromNumber;\n const to = config.whatsappToNumber || config.toNumber;\n if (from && to) {\n // Twilio requires 'whatsapp:' prefix for WhatsApp numbers\n return {\n from: from.startsWith('whatsapp:') ? from : `whatsapp:${from}`,\n to: to.startsWith('whatsapp:') ? to : `whatsapp:${to}`,\n channel: 'whatsapp',\n };\n }\n }\n\n // Fall back to SMS\n const from = config.smsFromNumber || config.fromNumber;\n const to = config.smsToNumber || config.toNumber;\n if (from && to) {\n return { from, to, channel: 'sms' };\n }\n\n return null;\n}\n\nexport async function sendNotification(\n payload: NotificationPayload,\n channelOverride?: MessageChannel\n): Promise<{\n success: boolean;\n promptId?: string;\n channel?: MessageChannel;\n error?: string;\n}> {\n const config = loadSMSConfig();\n\n if (!config.enabled) {\n return { success: false, error: 'Notifications disabled' };\n }\n\n // Check notification type is enabled\n const typeMap: Record<string, keyof typeof config.notifyOn> = {\n task_complete: 'taskComplete',\n review_ready: 'reviewReady',\n error: 'error',\n custom: 'custom',\n };\n\n if (!config.notifyOn[typeMap[payload.type]]) {\n return {\n success: false,\n error: `Notifications for ${payload.type} disabled`,\n };\n }\n\n // Check quiet hours\n if (isQuietHours(config)) {\n return { success: false, error: 'Quiet hours active' };\n }\n\n // Validate credentials\n if (!config.accountSid || !config.authToken) {\n return {\n success: false,\n error:\n 'Missing Twilio credentials. Set TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN',\n };\n }\n\n // Get channel numbers (prefer WhatsApp)\n const originalChannel = config.channel;\n if (channelOverride) {\n config.channel = channelOverride;\n }\n\n const numbers = getChannelNumbers(config);\n config.channel = originalChannel; // Restore\n\n if (!numbers) {\n return {\n success: false,\n error:\n config.channel === 'whatsapp'\n ? 'Missing WhatsApp numbers. Set TWILIO_WHATSAPP_FROM and TWILIO_WHATSAPP_TO'\n : 'Missing SMS numbers. Set TWILIO_SMS_FROM and TWILIO_SMS_TO',\n };\n }\n\n const message = formatPromptMessage(payload);\n let promptId: string | undefined;\n\n // Store pending prompt if interactive\n if (payload.prompt) {\n promptId = generatePromptId();\n const expiresAt = new Date(\n Date.now() + config.responseTimeout * 1000\n ).toISOString();\n\n const pendingPrompt: PendingPrompt = {\n id: promptId,\n timestamp: new Date().toISOString(),\n message: payload.message,\n options: payload.prompt.options || [],\n type: payload.prompt.type,\n expiresAt,\n };\n\n config.pendingPrompts.push(pendingPrompt);\n saveSMSConfig(config);\n }\n\n try {\n // Use Twilio API (same endpoint for SMS and WhatsApp)\n const twilioUrl = `https://api.twilio.com/2010-04-01/Accounts/${config.accountSid}/Messages.json`;\n\n const response = await fetch(twilioUrl, {\n method: 'POST',\n headers: {\n Authorization:\n 'Basic ' +\n Buffer.from(`${config.accountSid}:${config.authToken}`).toString(\n 'base64'\n ),\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n From: numbers.from,\n To: numbers.to,\n Body: message,\n }),\n });\n\n if (!response.ok) {\n const errorData = await response.text();\n return {\n success: false,\n channel: numbers.channel,\n error: `Twilio error: ${errorData}`,\n };\n }\n\n return { success: true, promptId, channel: numbers.channel };\n } catch (err) {\n return {\n success: false,\n channel: numbers.channel,\n error: `Failed to send ${numbers.channel}: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n}\n\n// Backwards compatible alias\nexport async function sendSMSNotification(\n payload: NotificationPayload\n): Promise<{ success: boolean; promptId?: string; error?: string }> {\n return sendNotification(payload);\n}\n\nexport function processIncomingResponse(\n from: string,\n body: string\n): {\n matched: boolean;\n prompt?: PendingPrompt;\n response?: string;\n action?: string;\n} {\n const config = loadSMSConfig();\n\n // Normalize response\n const response = body.trim().toLowerCase();\n\n // Find matching pending prompt (most recent first)\n const now = new Date();\n const validPrompts = config.pendingPrompts.filter(\n (p) => new Date(p.expiresAt) > now\n );\n\n if (validPrompts.length === 0) {\n return { matched: false };\n }\n\n // Get most recent prompt\n const prompt = validPrompts[validPrompts.length - 1];\n\n let matchedOption: PromptOption | undefined;\n\n if (prompt.type === 'yesno') {\n if (response === 'y' || response === 'yes') {\n matchedOption = { key: 'y', label: 'Yes' };\n } else if (response === 'n' || response === 'no') {\n matchedOption = { key: 'n', label: 'No' };\n }\n } else if (prompt.type === 'options') {\n matchedOption = prompt.options.find(\n (opt) => opt.key.toLowerCase() === response\n );\n } else if (prompt.type === 'freeform') {\n matchedOption = { key: response, label: response };\n }\n\n // Remove processed prompt\n config.pendingPrompts = config.pendingPrompts.filter(\n (p) => p.id !== prompt.id\n );\n saveSMSConfig(config);\n\n if (matchedOption) {\n return {\n matched: true,\n prompt,\n response: matchedOption.key,\n action: matchedOption.action,\n };\n }\n\n return { matched: false, prompt };\n}\n\n// Convenience functions for common notifications\n\nexport async function notifyReviewReady(\n title: string,\n description: string,\n options?: { label: string; action?: string }[]\n): Promise<{ success: boolean; promptId?: string; error?: string }> {\n const payload: NotificationPayload = {\n type: 'review_ready',\n title: `Review Ready: ${title}`,\n message: description,\n };\n\n if (options && options.length > 0) {\n payload.prompt = {\n type: 'options',\n options: options.map((opt, i) => ({\n key: String(i + 1),\n label: opt.label,\n action: opt.action,\n })),\n question: 'What would you like to do?',\n };\n }\n\n return sendSMSNotification(payload);\n}\n\nexport async function notifyWithYesNo(\n title: string,\n question: string,\n yesAction?: string,\n noAction?: string\n): Promise<{ success: boolean; promptId?: string; error?: string }> {\n return sendSMSNotification({\n type: 'custom',\n title,\n message: question,\n prompt: {\n type: 'yesno',\n options: [\n { key: 'y', label: 'Yes', action: yesAction },\n { key: 'n', label: 'No', action: noAction },\n ],\n },\n });\n}\n\nexport async function notifyTaskComplete(\n taskName: string,\n summary: string\n): Promise<{ success: boolean; error?: string }> {\n return sendSMSNotification({\n type: 'task_complete',\n title: `Task Complete: ${taskName}`,\n message: summary,\n });\n}\n\nexport async function notifyError(\n error: string,\n context?: string\n): Promise<{ success: boolean; error?: string }> {\n return sendSMSNotification({\n type: 'error',\n title: 'Error Alert',\n message: context ? `${error}\\n\\nContext: ${context}` : error,\n });\n}\n\n// Clean up expired prompts\nexport function cleanupExpiredPrompts(): number {\n const config = loadSMSConfig();\n const now = new Date();\n const before = config.pendingPrompts.length;\n\n config.pendingPrompts = config.pendingPrompts.filter(\n (p) => new Date(p.expiresAt) > now\n );\n\n const removed = before - config.pendingPrompts.length;\n if (removed > 0) {\n saveSMSConfig(config);\n }\n\n return removed;\n}\n"],
|
|
5
|
+
"mappings": ";;;;AAQA,SAAS,YAAY,oBAAoB;AACzC,SAAS,YAAY;AACrB,SAAS,eAAe;AACxB,SAAS,UAAU,kBAAkB;AACrC,SAAS,iBAAiB,uBAAuB;AACjD,SAAS,iBAAiB,uBAAuB;AAqEjD,MAAM,cAAc,KAAK,QAAQ,GAAG,gBAAgB,iBAAiB;AAErE,MAAM,iBAA4B;AAAA,EAChC,SAAS;AAAA,EACT,SAAS;AAAA;AAAA,EACT,UAAU;AAAA,IACR,cAAc;AAAA,IACd,aAAa;AAAA,IACb,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AAAA,EACA,YAAY;AAAA,IACV,SAAS;AAAA,IACT,OAAO;AAAA,IACP,KAAK;AAAA,EACP;AAAA,EACA,iBAAiB;AAAA;AAAA,EACjB,gBAAgB,CAAC;AACnB;AAEO,SAAS,gBAA2B;AAEzC,aAAW,EAAE,MAAM,KAAK,QAAQ,IAAI,GAAG,MAAM,EAAE,CAAC;AAChD,aAAW,EAAE,MAAM,KAAK,QAAQ,IAAI,GAAG,YAAY,EAAE,CAAC;AACtD,aAAW,EAAE,MAAM,KAAK,QAAQ,GAAG,MAAM,EAAE,CAAC;AAC5C,aAAW,EAAE,MAAM,KAAK,QAAQ,GAAG,gBAAgB,MAAM,EAAE,CAAC;AAE5D,MAAI;AACF,QAAI,WAAW,WAAW,GAAG;AA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,oBAAI,KAAK;AACrB,QAAM,SAAS,OAAO,eAAe;AAErC,SAAO,iBAAiB,OAAO,eAAe;AAAA,IAC5C,CAAC,MAAM,IAAI,KAAK,EAAE,SAAS,IAAI;AAAA,EACjC;AAEA,QAAM,UAAU,SAAS,OAAO,eAAe;AAC/C,MAAI,UAAU,GAAG;AACf,kBAAc,MAAM;AAAA,EACtB;AAEA,SAAO;AACT;",
|
|
6
|
+
"names": ["from", "to"]
|
|
7
7
|
}
|
|
@@ -4,13 +4,23 @@ const __filename = __fileURLToPath(import.meta.url);
|
|
|
4
4
|
const __dirname = __pathDirname(__filename);
|
|
5
5
|
import { createServer } from "http";
|
|
6
6
|
import { parse as parseUrl } from "url";
|
|
7
|
-
import { existsSync,
|
|
7
|
+
import { existsSync, readFileSync } from "fs";
|
|
8
8
|
import { join } from "path";
|
|
9
9
|
import { homedir } from "os";
|
|
10
10
|
import { createHmac } from "crypto";
|
|
11
11
|
import { execFileSync } from "child_process";
|
|
12
|
-
import {
|
|
13
|
-
|
|
12
|
+
import {
|
|
13
|
+
processIncomingResponse,
|
|
14
|
+
loadSMSConfig,
|
|
15
|
+
cleanupExpiredPrompts
|
|
16
|
+
} from "./sms-notify.js";
|
|
17
|
+
import {
|
|
18
|
+
queueAction,
|
|
19
|
+
executeActionSafe,
|
|
20
|
+
cleanupOldActions
|
|
21
|
+
} from "./sms-action-runner.js";
|
|
22
|
+
import { writeFileSecure, ensureSecureDir } from "./secure-fs.js";
|
|
23
|
+
const CLEANUP_INTERVAL_MS = 5 * 60 * 1e3;
|
|
14
24
|
const MAX_BODY_SIZE = 50 * 1024;
|
|
15
25
|
const RATE_LIMIT_WINDOW_MS = 60 * 1e3;
|
|
16
26
|
const RATE_LIMIT_MAX_REQUESTS = 30;
|
|
@@ -55,12 +65,13 @@ function parseFormData(body) {
|
|
|
55
65
|
return result;
|
|
56
66
|
}
|
|
57
67
|
function storeLatestResponse(promptId, response, action) {
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
68
|
+
ensureSecureDir(join(homedir(), ".stackmemory"));
|
|
69
|
+
const responsePath = join(
|
|
70
|
+
homedir(),
|
|
71
|
+
".stackmemory",
|
|
72
|
+
"sms-latest-response.json"
|
|
73
|
+
);
|
|
74
|
+
writeFileSecure(
|
|
64
75
|
responsePath,
|
|
65
76
|
JSON.stringify({
|
|
66
77
|
promptId,
|
|
@@ -139,7 +150,7 @@ function triggerResponseNotification(response) {
|
|
|
139
150
|
}
|
|
140
151
|
try {
|
|
141
152
|
const signalPath = join(homedir(), ".stackmemory", "sms-signal.txt");
|
|
142
|
-
|
|
153
|
+
writeFileSecure(
|
|
143
154
|
signalPath,
|
|
144
155
|
JSON.stringify({
|
|
145
156
|
type: "sms_response",
|
|
@@ -248,7 +259,7 @@ function startWebhookServer(port = 3456) {
|
|
|
248
259
|
);
|
|
249
260
|
const statuses = existsSync(statusPath) ? JSON.parse(readFileSync(statusPath, "utf8")) : {};
|
|
250
261
|
statuses[payload["MessageSid"]] = payload["MessageStatus"];
|
|
251
|
-
|
|
262
|
+
writeFileSecure(statusPath, JSON.stringify(statuses, null, 2));
|
|
252
263
|
res.writeHead(200, { "Content-Type": "text/plain" });
|
|
253
264
|
res.end("OK");
|
|
254
265
|
} catch (err) {
|
|
@@ -283,6 +294,21 @@ function startWebhookServer(port = 3456) {
|
|
|
283
294
|
`[sms-webhook] Status callback: http://localhost:${port}/sms/status`
|
|
284
295
|
);
|
|
285
296
|
console.log(`[sms-webhook] Configure these URLs in Twilio console`);
|
|
297
|
+
setInterval(() => {
|
|
298
|
+
try {
|
|
299
|
+
const expiredPrompts = cleanupExpiredPrompts();
|
|
300
|
+
const oldActions = cleanupOldActions();
|
|
301
|
+
if (expiredPrompts > 0 || oldActions > 0) {
|
|
302
|
+
console.log(
|
|
303
|
+
`[sms-webhook] Cleanup: ${expiredPrompts} expired prompts, ${oldActions} old actions`
|
|
304
|
+
);
|
|
305
|
+
}
|
|
306
|
+
} catch {
|
|
307
|
+
}
|
|
308
|
+
}, CLEANUP_INTERVAL_MS);
|
|
309
|
+
console.log(
|
|
310
|
+
`[sms-webhook] Cleanup interval: every ${CLEANUP_INTERVAL_MS / 1e3}s`
|
|
311
|
+
);
|
|
286
312
|
});
|
|
287
313
|
}
|
|
288
314
|
function smsWebhookMiddleware(req, res) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/hooks/sms-webhook.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * SMS Webhook Handler for receiving Twilio responses\n * Can run as standalone server or integrate with existing Express app\n *\n * Security features:\n * - Twilio signature verification\n * - Rate limiting per IP\n * - Body size limits\n * - Content-type validation\n * - Safe action execution (no shell injection)\n */\n\nimport { createServer, IncomingMessage, ServerResponse } from 'http';\nimport { parse as parseUrl } from 'url';\nimport { existsSync, writeFileSync, mkdirSync, readFileSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { createHmac } from 'crypto';\nimport { execFileSync } from 'child_process';\nimport { processIncomingResponse, loadSMSConfig } from './sms-notify.js';\nimport { queueAction, executeActionSafe } from './sms-action-runner.js';\n\n// Security constants\nconst MAX_BODY_SIZE = 50 * 1024; // 50KB max body\nconst RATE_LIMIT_WINDOW_MS = 60 * 1000; // 1 minute\nconst RATE_LIMIT_MAX_REQUESTS = 30; // 30 requests per minute per IP\n\n// Rate limiting store (in production, use Redis)\nconst rateLimitStore = new Map<string, { count: number; resetTime: number }>();\n\nfunction checkRateLimit(ip: string): boolean {\n const now = Date.now();\n const record = rateLimitStore.get(ip);\n\n if (!record || now > record.resetTime) {\n rateLimitStore.set(ip, { count: 1, resetTime: now + RATE_LIMIT_WINDOW_MS });\n return true;\n }\n\n if (record.count >= RATE_LIMIT_MAX_REQUESTS) {\n return false;\n }\n\n record.count++;\n return true;\n}\n\n// Twilio signature verification\nfunction verifyTwilioSignature(\n url: string,\n params: Record<string, string>,\n signature: string\n): boolean {\n const authToken = process.env['TWILIO_AUTH_TOKEN'];\n if (!authToken) {\n console.warn(\n '[sms-webhook] TWILIO_AUTH_TOKEN not set, skipping signature verification'\n );\n return true; // Allow in development, but log warning\n }\n\n // Build the data string (URL + sorted params)\n const sortedKeys = Object.keys(params).sort();\n let data = url;\n for (const key of sortedKeys) {\n data += key + params[key];\n }\n\n // Calculate expected signature\n const hmac = createHmac('sha1', authToken);\n hmac.update(data);\n const expectedSignature = hmac.digest('base64');\n\n return signature === expectedSignature;\n}\n\ninterface TwilioWebhookPayload {\n From: string;\n To: string;\n Body: string;\n MessageSid: string;\n}\n\nfunction parseFormData(body: string): Record<string, string> {\n const params = new URLSearchParams(body);\n const result: Record<string, string> = {};\n params.forEach((value, key) => {\n result[key] = value;\n });\n return result;\n}\n\n// Store response for Claude hook to pick up\nfunction storeLatestResponse(\n promptId: string,\n response: string,\n action?: string\n): void {\n const dir = join(homedir(), '.stackmemory');\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n const responsePath = join(dir, 'sms-latest-response.json');\n writeFileSync(\n responsePath,\n JSON.stringify({\n promptId,\n response,\n action,\n timestamp: new Date().toISOString(),\n })\n );\n}\n\nexport function handleSMSWebhook(payload: TwilioWebhookPayload): {\n response: string;\n action?: string;\n queued?: boolean;\n} {\n const { From, Body } = payload;\n\n console.log(`[sms-webhook] Received from ${From}: ${Body}`);\n\n const result = processIncomingResponse(From, Body);\n\n if (!result.matched) {\n if (result.prompt) {\n return {\n response: `Invalid response. Expected: ${result.prompt.options.map((o) => o.key).join(', ')}`,\n };\n }\n return { response: 'No pending prompt found.' };\n }\n\n // Store response for Claude hook\n storeLatestResponse(\n result.prompt?.id || 'unknown',\n result.response || Body,\n result.action\n );\n\n // Trigger notification to alert user/Claude\n triggerResponseNotification(result.response || Body);\n\n // Execute action safely if present (no shell injection)\n if (result.action) {\n console.log(`[sms-webhook] Executing action: ${result.action}`);\n\n const actionResult = executeActionSafe(\n result.action,\n result.response || Body\n );\n\n if (actionResult.success) {\n console.log(\n `[sms-webhook] Action completed: ${(actionResult.output || '').substring(0, 200)}`\n );\n\n return {\n response: `Done! Action executed successfully.`,\n action: result.action,\n queued: false,\n };\n } else {\n console.log(`[sms-webhook] Action failed: ${actionResult.error}`);\n\n // Queue for retry\n queueAction(\n result.prompt?.id || 'unknown',\n result.response || Body,\n result.action\n );\n\n return {\n response: `Action failed, queued for retry: ${(actionResult.error || '').substring(0, 50)}`,\n action: result.action,\n queued: true,\n };\n }\n }\n\n return {\n response: `Received: ${result.response}. Next action will be triggered.`,\n };\n}\n\n// Escape string for AppleScript (prevent injection)\nfunction escapeAppleScript(str: string): string {\n return str\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .substring(0, 200); // Limit length\n}\n\n// Trigger notification when response received\nfunction triggerResponseNotification(response: string): void {\n const safeMessage = escapeAppleScript(`SMS Response: ${response}`);\n\n // macOS notification using execFile (safer than execSync with shell)\n try {\n execFileSync(\n 'osascript',\n [\n '-e',\n `display notification \"${safeMessage}\" with title \"StackMemory\" sound name \"Glass\"`,\n ],\n { stdio: 'ignore', timeout: 5000 }\n );\n } catch {\n // Ignore if not on macOS\n }\n\n // Write signal file for other processes\n try {\n const signalPath = join(homedir(), '.stackmemory', 'sms-signal.txt');\n writeFileSync(\n signalPath,\n JSON.stringify({\n type: 'sms_response',\n response,\n timestamp: new Date().toISOString(),\n })\n );\n } catch {\n // Ignore\n }\n\n console.log(`\\n*** SMS RESPONSE RECEIVED: \"${response}\" ***`);\n console.log(`*** Run: stackmemory notify run-actions ***\\n`);\n}\n\n// TwiML response helper\nfunction twimlResponse(message: string): string {\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Response>\n <Message>${escapeXml(message)}</Message>\n</Response>`;\n}\n\nfunction escapeXml(str: string): string {\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n// Standalone webhook server\nexport function startWebhookServer(port: number = 3456): void {\n const server = createServer(\n async (req: IncomingMessage, res: ServerResponse) => {\n const url = parseUrl(req.url || '/', true);\n\n // Health check\n if (url.pathname === '/health') {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ status: 'ok' }));\n return;\n }\n\n // SMS webhook endpoint (incoming messages)\n if (\n (url.pathname === '/sms' ||\n url.pathname === '/sms/incoming' ||\n url.pathname === '/webhook') &&\n req.method === 'POST'\n ) {\n // Rate limiting\n const clientIp = req.socket.remoteAddress || 'unknown';\n if (!checkRateLimit(clientIp)) {\n res.writeHead(429, {\n 'Content-Type': 'text/xml',\n 'Retry-After': '60',\n });\n res.end(twimlResponse('Too many requests. Please try again later.'));\n return;\n }\n\n // Content-type validation\n const contentType = req.headers['content-type'] || '';\n if (!contentType.includes('application/x-www-form-urlencoded')) {\n res.writeHead(400, { 'Content-Type': 'text/xml' });\n res.end(twimlResponse('Invalid content type'));\n return;\n }\n\n let body = '';\n let bodyTooLarge = false;\n\n req.on('data', (chunk) => {\n body += chunk;\n // Body size limit\n if (body.length > MAX_BODY_SIZE) {\n bodyTooLarge = true;\n req.destroy();\n }\n });\n\n req.on('end', () => {\n if (bodyTooLarge) {\n res.writeHead(413, { 'Content-Type': 'text/xml' });\n res.end(twimlResponse('Request too large'));\n return;\n }\n\n try {\n const payload = parseFormData(\n body\n ) as unknown as TwilioWebhookPayload;\n\n // Verify Twilio signature\n const twilioSignature = req.headers['x-twilio-signature'] as string;\n const webhookUrl = `${req.headers['x-forwarded-proto'] || 'http'}://${req.headers.host}${req.url}`;\n\n if (\n twilioSignature &&\n !verifyTwilioSignature(\n webhookUrl,\n payload as unknown as Record<string, string>,\n twilioSignature\n )\n ) {\n console.error('[sms-webhook] Invalid Twilio signature');\n res.writeHead(401, { 'Content-Type': 'text/xml' });\n res.end(twimlResponse('Unauthorized'));\n return;\n }\n\n const result = handleSMSWebhook(payload);\n\n res.writeHead(200, { 'Content-Type': 'text/xml' });\n res.end(twimlResponse(result.response));\n } catch (err) {\n console.error('[sms-webhook] Error:', err);\n res.writeHead(500, { 'Content-Type': 'text/xml' });\n res.end(twimlResponse('Error processing message'));\n }\n });\n return;\n }\n\n // Status callback endpoint (delivery status updates)\n if (url.pathname === '/sms/status' && req.method === 'POST') {\n let body = '';\n req.on('data', (chunk) => {\n body += chunk;\n });\n\n req.on('end', () => {\n try {\n const payload = parseFormData(body);\n console.log(\n `[sms-webhook] Status update: ${payload['MessageSid']} -> ${payload['MessageStatus']}`\n );\n\n // Store status for tracking\n const statusPath = join(\n homedir(),\n '.stackmemory',\n 'sms-status.json'\n );\n const statuses: Record<string, string> = existsSync(statusPath)\n ? JSON.parse(readFileSync(statusPath, 'utf8'))\n : {};\n statuses[payload['MessageSid']] = payload['MessageStatus'];\n writeFileSync(statusPath, JSON.stringify(statuses, null, 2));\n\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('OK');\n } catch (err) {\n console.error('[sms-webhook] Status error:', err);\n res.writeHead(500);\n res.end('Error');\n }\n });\n return;\n }\n\n // Server status endpoint\n if (url.pathname === '/status') {\n const config = loadSMSConfig();\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n enabled: config.enabled,\n pendingPrompts: config.pendingPrompts.length,\n })\n );\n return;\n }\n\n res.writeHead(404);\n res.end('Not found');\n }\n );\n\n server.listen(port, () => {\n console.log(`[sms-webhook] Server listening on port ${port}`);\n console.log(\n `[sms-webhook] Incoming messages: http://localhost:${port}/sms/incoming`\n );\n console.log(\n `[sms-webhook] Status callback: http://localhost:${port}/sms/status`\n );\n console.log(`[sms-webhook] Configure these URLs in Twilio console`);\n });\n}\n\n// Express middleware for integration\nexport function smsWebhookMiddleware(\n req: { body: TwilioWebhookPayload },\n res: { type: (t: string) => void; send: (s: string) => void }\n): void {\n const result = handleSMSWebhook(req.body);\n res.type('text/xml');\n res.send(twimlResponse(result.response));\n}\n\n// CLI entry\nif (process.argv[1]?.endsWith('sms-webhook.js')) {\n const port = parseInt(process.env['SMS_WEBHOOK_PORT'] || '3456', 10);\n startWebhookServer(port);\n}\n"],
|
|
5
|
-
"mappings": ";;;;AAYA,SAAS,oBAAqD;AAC9D,SAAS,SAAS,gBAAgB;AAClC,SAAS,YAAY,
|
|
4
|
+
"sourcesContent": ["/**\n * SMS Webhook Handler for receiving Twilio responses\n * Can run as standalone server or integrate with existing Express app\n *\n * Security features:\n * - Twilio signature verification\n * - Rate limiting per IP\n * - Body size limits\n * - Content-type validation\n * - Safe action execution (no shell injection)\n */\n\nimport { createServer, IncomingMessage, ServerResponse } from 'http';\nimport { parse as parseUrl } from 'url';\nimport { existsSync, readFileSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { createHmac } from 'crypto';\nimport { execFileSync } from 'child_process';\nimport {\n processIncomingResponse,\n loadSMSConfig,\n cleanupExpiredPrompts,\n} from './sms-notify.js';\nimport {\n queueAction,\n executeActionSafe,\n cleanupOldActions,\n} from './sms-action-runner.js';\nimport { writeFileSecure, ensureSecureDir } from './secure-fs.js';\n\n// Cleanup interval (5 minutes)\nconst CLEANUP_INTERVAL_MS = 5 * 60 * 1000;\n\n// Security constants\nconst MAX_BODY_SIZE = 50 * 1024; // 50KB max body\nconst RATE_LIMIT_WINDOW_MS = 60 * 1000; // 1 minute\nconst RATE_LIMIT_MAX_REQUESTS = 30; // 30 requests per minute per IP\n\n// Rate limiting store (in production, use Redis)\nconst rateLimitStore = new Map<string, { count: number; resetTime: number }>();\n\nfunction checkRateLimit(ip: string): boolean {\n const now = Date.now();\n const record = rateLimitStore.get(ip);\n\n if (!record || now > record.resetTime) {\n rateLimitStore.set(ip, { count: 1, resetTime: now + RATE_LIMIT_WINDOW_MS });\n return true;\n }\n\n if (record.count >= RATE_LIMIT_MAX_REQUESTS) {\n return false;\n }\n\n record.count++;\n return true;\n}\n\n// Twilio signature verification\nfunction verifyTwilioSignature(\n url: string,\n params: Record<string, string>,\n signature: string\n): boolean {\n const authToken = process.env['TWILIO_AUTH_TOKEN'];\n if (!authToken) {\n console.warn(\n '[sms-webhook] TWILIO_AUTH_TOKEN not set, skipping signature verification'\n );\n return true; // Allow in development, but log warning\n }\n\n // Build the data string (URL + sorted params)\n const sortedKeys = Object.keys(params).sort();\n let data = url;\n for (const key of sortedKeys) {\n data += key + params[key];\n }\n\n // Calculate expected signature\n const hmac = createHmac('sha1', authToken);\n hmac.update(data);\n const expectedSignature = hmac.digest('base64');\n\n return signature === expectedSignature;\n}\n\ninterface TwilioWebhookPayload {\n From: string;\n To: string;\n Body: string;\n MessageSid: string;\n}\n\nfunction parseFormData(body: string): Record<string, string> {\n const params = new URLSearchParams(body);\n const result: Record<string, string> = {};\n params.forEach((value, key) => {\n result[key] = value;\n });\n return result;\n}\n\n// Store response for Claude hook to pick up\nfunction storeLatestResponse(\n promptId: string,\n response: string,\n action?: string\n): void {\n ensureSecureDir(join(homedir(), '.stackmemory'));\n const responsePath = join(\n homedir(),\n '.stackmemory',\n 'sms-latest-response.json'\n );\n writeFileSecure(\n responsePath,\n JSON.stringify({\n promptId,\n response,\n action,\n timestamp: new Date().toISOString(),\n })\n );\n}\n\nexport function handleSMSWebhook(payload: TwilioWebhookPayload): {\n response: string;\n action?: string;\n queued?: boolean;\n} {\n const { From, Body } = payload;\n\n console.log(`[sms-webhook] Received from ${From}: ${Body}`);\n\n const result = processIncomingResponse(From, Body);\n\n if (!result.matched) {\n if (result.prompt) {\n return {\n response: `Invalid response. Expected: ${result.prompt.options.map((o) => o.key).join(', ')}`,\n };\n }\n return { response: 'No pending prompt found.' };\n }\n\n // Store response for Claude hook\n storeLatestResponse(\n result.prompt?.id || 'unknown',\n result.response || Body,\n result.action\n );\n\n // Trigger notification to alert user/Claude\n triggerResponseNotification(result.response || Body);\n\n // Execute action safely if present (no shell injection)\n if (result.action) {\n console.log(`[sms-webhook] Executing action: ${result.action}`);\n\n const actionResult = executeActionSafe(\n result.action,\n result.response || Body\n );\n\n if (actionResult.success) {\n console.log(\n `[sms-webhook] Action completed: ${(actionResult.output || '').substring(0, 200)}`\n );\n\n return {\n response: `Done! Action executed successfully.`,\n action: result.action,\n queued: false,\n };\n } else {\n console.log(`[sms-webhook] Action failed: ${actionResult.error}`);\n\n // Queue for retry\n queueAction(\n result.prompt?.id || 'unknown',\n result.response || Body,\n result.action\n );\n\n return {\n response: `Action failed, queued for retry: ${(actionResult.error || '').substring(0, 50)}`,\n action: result.action,\n queued: true,\n };\n }\n }\n\n return {\n response: `Received: ${result.response}. Next action will be triggered.`,\n };\n}\n\n// Escape string for AppleScript (prevent injection)\nfunction escapeAppleScript(str: string): string {\n return str\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .substring(0, 200); // Limit length\n}\n\n// Trigger notification when response received\nfunction triggerResponseNotification(response: string): void {\n const safeMessage = escapeAppleScript(`SMS Response: ${response}`);\n\n // macOS notification using execFile (safer than execSync with shell)\n try {\n execFileSync(\n 'osascript',\n [\n '-e',\n `display notification \"${safeMessage}\" with title \"StackMemory\" sound name \"Glass\"`,\n ],\n { stdio: 'ignore', timeout: 5000 }\n );\n } catch {\n // Ignore if not on macOS\n }\n\n // Write signal file for other processes\n try {\n const signalPath = join(homedir(), '.stackmemory', 'sms-signal.txt');\n writeFileSecure(\n signalPath,\n JSON.stringify({\n type: 'sms_response',\n response,\n timestamp: new Date().toISOString(),\n })\n );\n } catch {\n // Ignore\n }\n\n console.log(`\\n*** SMS RESPONSE RECEIVED: \"${response}\" ***`);\n console.log(`*** Run: stackmemory notify run-actions ***\\n`);\n}\n\n// TwiML response helper\nfunction twimlResponse(message: string): string {\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Response>\n <Message>${escapeXml(message)}</Message>\n</Response>`;\n}\n\nfunction escapeXml(str: string): string {\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n// Standalone webhook server\nexport function startWebhookServer(port: number = 3456): void {\n const server = createServer(\n async (req: IncomingMessage, res: ServerResponse) => {\n const url = parseUrl(req.url || '/', true);\n\n // Health check\n if (url.pathname === '/health') {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ status: 'ok' }));\n return;\n }\n\n // SMS webhook endpoint (incoming messages)\n if (\n (url.pathname === '/sms' ||\n url.pathname === '/sms/incoming' ||\n url.pathname === '/webhook') &&\n req.method === 'POST'\n ) {\n // Rate limiting\n const clientIp = req.socket.remoteAddress || 'unknown';\n if (!checkRateLimit(clientIp)) {\n res.writeHead(429, {\n 'Content-Type': 'text/xml',\n 'Retry-After': '60',\n });\n res.end(twimlResponse('Too many requests. Please try again later.'));\n return;\n }\n\n // Content-type validation\n const contentType = req.headers['content-type'] || '';\n if (!contentType.includes('application/x-www-form-urlencoded')) {\n res.writeHead(400, { 'Content-Type': 'text/xml' });\n res.end(twimlResponse('Invalid content type'));\n return;\n }\n\n let body = '';\n let bodyTooLarge = false;\n\n req.on('data', (chunk) => {\n body += chunk;\n // Body size limit\n if (body.length > MAX_BODY_SIZE) {\n bodyTooLarge = true;\n req.destroy();\n }\n });\n\n req.on('end', () => {\n if (bodyTooLarge) {\n res.writeHead(413, { 'Content-Type': 'text/xml' });\n res.end(twimlResponse('Request too large'));\n return;\n }\n\n try {\n const payload = parseFormData(\n body\n ) as unknown as TwilioWebhookPayload;\n\n // Verify Twilio signature\n const twilioSignature = req.headers['x-twilio-signature'] as string;\n const webhookUrl = `${req.headers['x-forwarded-proto'] || 'http'}://${req.headers.host}${req.url}`;\n\n if (\n twilioSignature &&\n !verifyTwilioSignature(\n webhookUrl,\n payload as unknown as Record<string, string>,\n twilioSignature\n )\n ) {\n console.error('[sms-webhook] Invalid Twilio signature');\n res.writeHead(401, { 'Content-Type': 'text/xml' });\n res.end(twimlResponse('Unauthorized'));\n return;\n }\n\n const result = handleSMSWebhook(payload);\n\n res.writeHead(200, { 'Content-Type': 'text/xml' });\n res.end(twimlResponse(result.response));\n } catch (err) {\n console.error('[sms-webhook] Error:', err);\n res.writeHead(500, { 'Content-Type': 'text/xml' });\n res.end(twimlResponse('Error processing message'));\n }\n });\n return;\n }\n\n // Status callback endpoint (delivery status updates)\n if (url.pathname === '/sms/status' && req.method === 'POST') {\n let body = '';\n req.on('data', (chunk) => {\n body += chunk;\n });\n\n req.on('end', () => {\n try {\n const payload = parseFormData(body);\n console.log(\n `[sms-webhook] Status update: ${payload['MessageSid']} -> ${payload['MessageStatus']}`\n );\n\n // Store status for tracking\n const statusPath = join(\n homedir(),\n '.stackmemory',\n 'sms-status.json'\n );\n const statuses: Record<string, string> = existsSync(statusPath)\n ? JSON.parse(readFileSync(statusPath, 'utf8'))\n : {};\n statuses[payload['MessageSid']] = payload['MessageStatus'];\n writeFileSecure(statusPath, JSON.stringify(statuses, null, 2));\n\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('OK');\n } catch (err) {\n console.error('[sms-webhook] Status error:', err);\n res.writeHead(500);\n res.end('Error');\n }\n });\n return;\n }\n\n // Server status endpoint\n if (url.pathname === '/status') {\n const config = loadSMSConfig();\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n enabled: config.enabled,\n pendingPrompts: config.pendingPrompts.length,\n })\n );\n return;\n }\n\n res.writeHead(404);\n res.end('Not found');\n }\n );\n\n server.listen(port, () => {\n console.log(`[sms-webhook] Server listening on port ${port}`);\n console.log(\n `[sms-webhook] Incoming messages: http://localhost:${port}/sms/incoming`\n );\n console.log(\n `[sms-webhook] Status callback: http://localhost:${port}/sms/status`\n );\n console.log(`[sms-webhook] Configure these URLs in Twilio console`);\n\n // Start timed cleanup of expired prompts and old actions\n setInterval(() => {\n try {\n const expiredPrompts = cleanupExpiredPrompts();\n const oldActions = cleanupOldActions();\n if (expiredPrompts > 0 || oldActions > 0) {\n console.log(\n `[sms-webhook] Cleanup: ${expiredPrompts} expired prompts, ${oldActions} old actions`\n );\n }\n } catch {\n // Ignore cleanup errors\n }\n }, CLEANUP_INTERVAL_MS);\n console.log(\n `[sms-webhook] Cleanup interval: every ${CLEANUP_INTERVAL_MS / 1000}s`\n );\n });\n}\n\n// Express middleware for integration\nexport function smsWebhookMiddleware(\n req: { body: TwilioWebhookPayload },\n res: { type: (t: string) => void; send: (s: string) => void }\n): void {\n const result = handleSMSWebhook(req.body);\n res.type('text/xml');\n res.send(twimlResponse(result.response));\n}\n\n// CLI entry\nif (process.argv[1]?.endsWith('sms-webhook.js')) {\n const port = parseInt(process.env['SMS_WEBHOOK_PORT'] || '3456', 10);\n startWebhookServer(port);\n}\n"],
|
|
5
|
+
"mappings": ";;;;AAYA,SAAS,oBAAqD;AAC9D,SAAS,SAAS,gBAAgB;AAClC,SAAS,YAAY,oBAAoB;AACzC,SAAS,YAAY;AACrB,SAAS,eAAe;AACxB,SAAS,kBAAkB;AAC3B,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB,uBAAuB;AAGjD,MAAM,sBAAsB,IAAI,KAAK;AAGrC,MAAM,gBAAgB,KAAK;AAC3B,MAAM,uBAAuB,KAAK;AAClC,MAAM,0BAA0B;AAGhC,MAAM,iBAAiB,oBAAI,IAAkD;AAE7E,SAAS,eAAe,IAAqB;AAC3C,QAAM,MAAM,KAAK,IAAI;AACrB,QAAM,SAAS,eAAe,IAAI,EAAE;AAEpC,MAAI,CAAC,UAAU,MAAM,OAAO,WAAW;AACrC,mBAAe,IAAI,IAAI,EAAE,OAAO,GAAG,WAAW,MAAM,qBAAqB,CAAC;AAC1E,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,SAAS,yBAAyB;AAC3C,WAAO;A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AI,0CAA0C,IAAI,EAAE;AAC5D,YAAQ;AAAA,MACN,qDAAqD,IAAI;AAAA,IAC3D;AACA,YAAQ;AAAA,MACN,qDAAqD,IAAI;AAAA,IAC3D;AACA,YAAQ,IAAI,sDAAsD;AAGlE,gBAAY,MAAM;AAChB,UAAI;AACF,cAAM,iBAAiB,sBAAsB;AAC7C,cAAM,aAAa,kBAAkB;AACrC,YAAI,iBAAiB,KAAK,aAAa,GAAG;AACxC,kBAAQ;AAAA,YACN,0BAA0B,cAAc,qBAAqB,UAAU;AAAA,UACzE;AAAA,QACF;AAAA,MACF,QAAQ;AAAA,MAER;AAAA,IACF,GAAG,mBAAmB;AACtB,YAAQ;AAAA,MACN,yCAAyC,sBAAsB,GAAI;AAAA,IACrE;AAAA,EACF,CAAC;AACH;AAGO,SAAS,qBACd,KACA,KACM;AACN,QAAM,SAAS,iBAAiB,IAAI,IAAI;AACxC,MAAI,KAAK,UAAU;AACnB,MAAI,KAAK,cAAc,OAAO,QAAQ,CAAC;AACzC;AAGA,IAAI,QAAQ,KAAK,CAAC,GAAG,SAAS,gBAAgB,GAAG;AAC/C,QAAM,OAAO,SAAS,QAAQ,IAAI,kBAAkB,KAAK,QAAQ,EAAE;AACnE,qBAAmB,IAAI;AACzB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stackmemoryai/stackmemory",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.19",
|
|
4
4
|
"description": "Lossless memory runtime for AI coding tools - organizes context as a call stack instead of linear chat logs, with team collaboration and infinite retention",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=20.0.0",
|