botinabox 1.3.1 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/channels/slack/index.js +3 -3
- package/dist/channels/webhook/index.js +2 -1
- package/dist/chunk-J6S6QMUY.js +144 -0
- package/dist/chunk-NNPCKR6G.js +144 -0
- package/dist/chunk-XYF5PSB2.js +389 -0
- package/dist/cli.js +3 -3
- package/dist/connectors/google/index.js +1 -1
- package/dist/gmail-connector-ULSMN6X2.js +6 -0
- package/dist/inbound-MCOLRH6U.js +10 -0
- package/dist/inbound-ZJHAYVMF.js +10 -0
- package/dist/index.d.ts +9 -1
- package/dist/index.js +73 -14
- package/package.json +3 -3
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
extractVoiceTranscript,
|
|
5
5
|
parseSlackEvent,
|
|
6
6
|
transcribeAudio
|
|
7
|
-
} from "../../chunk-
|
|
7
|
+
} from "../../chunk-NNPCKR6G.js";
|
|
8
8
|
|
|
9
9
|
// src/channels/slack/outbound.ts
|
|
10
10
|
function formatForSlack(text) {
|
|
@@ -67,8 +67,8 @@ var SlackAdapter = class {
|
|
|
67
67
|
/** Simulate receiving an inbound message (for testing/webhooks). */
|
|
68
68
|
async receive(event) {
|
|
69
69
|
if (this.onMessage) {
|
|
70
|
-
const { parseSlackEvent: parseSlackEvent2 } = await import("../../inbound-
|
|
71
|
-
const { enrichVoiceMessage: enrichVoiceMessage2 } = await import("../../inbound-
|
|
70
|
+
const { parseSlackEvent: parseSlackEvent2 } = await import("../../inbound-ZJHAYVMF.js");
|
|
71
|
+
const { enrichVoiceMessage: enrichVoiceMessage2 } = await import("../../inbound-ZJHAYVMF.js");
|
|
72
72
|
let msg = parseSlackEvent2(event);
|
|
73
73
|
if (msg.body.includes("[Voice message") && this.config?.botToken) {
|
|
74
74
|
msg = await enrichVoiceMessage2(msg, this.config.botToken);
|
|
@@ -87,8 +87,9 @@ var WebhookServer = class {
|
|
|
87
87
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
88
88
|
res.end(JSON.stringify({ ok: true }));
|
|
89
89
|
} catch (err) {
|
|
90
|
+
console.error("[webhook] Error:", err);
|
|
90
91
|
res.writeHead(500, { "Content-Type": "application/json" });
|
|
91
|
-
res.end(JSON.stringify({ error:
|
|
92
|
+
res.end(JSON.stringify({ error: "Internal server error" }));
|
|
92
93
|
}
|
|
93
94
|
}
|
|
94
95
|
};
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// src/channels/slack/transcribe.ts
|
|
2
|
+
import { execFileSync } from "child_process";
|
|
3
|
+
import { writeFileSync, unlinkSync, mkdirSync } from "fs";
|
|
4
|
+
import { join } from "path";
|
|
5
|
+
import { randomUUID } from "crypto";
|
|
6
|
+
import os from "os";
|
|
7
|
+
import { createRequire } from "module";
|
|
8
|
+
var TEMP_DIR = join(os.tmpdir(), "botinabox-audio");
|
|
9
|
+
async function transcribeAudio(audioBuffer, filename, opts) {
|
|
10
|
+
let whisper;
|
|
11
|
+
try {
|
|
12
|
+
const require2 = createRequire(import.meta.url);
|
|
13
|
+
const mod = require2("whisper-node");
|
|
14
|
+
whisper = mod.whisper ?? mod.default ?? mod;
|
|
15
|
+
} catch {
|
|
16
|
+
console.warn("[botinabox] whisper-node not installed \u2014 voice transcription unavailable. Run: npm install whisper-node && npx whisper-node download");
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
try {
|
|
20
|
+
execSync("ffmpeg -version", { stdio: "ignore" });
|
|
21
|
+
} catch {
|
|
22
|
+
console.warn("[botinabox] ffmpeg not found \u2014 required for audio conversion. Install: brew install ffmpeg");
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
const id = randomUUID().slice(0, 8);
|
|
26
|
+
const ext = filename.split(".").pop() ?? "aac";
|
|
27
|
+
mkdirSync(TEMP_DIR, { recursive: true });
|
|
28
|
+
const inputPath = join(TEMP_DIR, `${id}.${ext}`);
|
|
29
|
+
const wavPath = join(TEMP_DIR, `${id}.wav`);
|
|
30
|
+
try {
|
|
31
|
+
writeFileSync(inputPath, audioBuffer);
|
|
32
|
+
execFileSync("ffmpeg", ["-y", "-i", inputPath, "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", wavPath], {
|
|
33
|
+
stdio: "ignore",
|
|
34
|
+
timeout: 3e4
|
|
35
|
+
});
|
|
36
|
+
const segments = await whisper(wavPath, {
|
|
37
|
+
modelName: opts?.modelName ?? "base.en",
|
|
38
|
+
whisperOptions: {
|
|
39
|
+
language: opts?.language ?? "auto"
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
if (!segments || segments.length === 0) return null;
|
|
43
|
+
return segments.map((s) => s.speech).join(" ").trim();
|
|
44
|
+
} catch (err) {
|
|
45
|
+
console.error("[botinabox] Transcription failed:", err);
|
|
46
|
+
return null;
|
|
47
|
+
} finally {
|
|
48
|
+
try {
|
|
49
|
+
unlinkSync(inputPath);
|
|
50
|
+
} catch {
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
unlinkSync(wavPath);
|
|
54
|
+
} catch {
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
async function downloadAudio(url, token) {
|
|
59
|
+
try {
|
|
60
|
+
const resp = await fetch(url, {
|
|
61
|
+
headers: { Authorization: `Bearer ${token}` }
|
|
62
|
+
});
|
|
63
|
+
if (!resp.ok) {
|
|
64
|
+
console.error(`[botinabox] Audio download failed: ${resp.status} ${resp.statusText}`);
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
return Buffer.from(await resp.arrayBuffer());
|
|
68
|
+
} catch (err) {
|
|
69
|
+
console.error("[botinabox] Audio download error:", err);
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/channels/slack/inbound.ts
|
|
75
|
+
var AUDIO_TYPES = /* @__PURE__ */ new Set(["aac", "mp4", "m4a", "ogg", "webm", "mp3", "wav"]);
|
|
76
|
+
function extractVoiceTranscript(file) {
|
|
77
|
+
const isAudio = file.subtype === "slack_audio" || AUDIO_TYPES.has(file.filetype ?? "");
|
|
78
|
+
if (!isAudio) return null;
|
|
79
|
+
const transcript = file.transcription?.preview?.content ?? (typeof file.preview === "string" ? file.preview : null);
|
|
80
|
+
return transcript ?? null;
|
|
81
|
+
}
|
|
82
|
+
function parseSlackEvent(event) {
|
|
83
|
+
const id = event.client_msg_id ?? event.ts ?? event.event_ts ?? `slack-${Date.now()}`;
|
|
84
|
+
const channel = event.channel ?? "unknown";
|
|
85
|
+
const from = event.user ?? "unknown";
|
|
86
|
+
const threadId = event.thread_ts !== void 0 ? event.thread_ts : void 0;
|
|
87
|
+
const receivedAt = event.ts ? new Date(parseFloat(event.ts) * 1e3).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
|
|
88
|
+
let body = event.text ?? "";
|
|
89
|
+
if (event.subtype === "file_share" && event.files?.length) {
|
|
90
|
+
for (const file of event.files) {
|
|
91
|
+
const transcript = extractVoiceTranscript(file);
|
|
92
|
+
if (transcript) {
|
|
93
|
+
body = body ? `${body}
|
|
94
|
+
|
|
95
|
+
[Voice message] ${transcript}` : `[Voice message] ${transcript}`;
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (event.subtype === "file_share" && event.files?.length && !body) {
|
|
101
|
+
const hasAudio = event.files.some(
|
|
102
|
+
(f) => f.subtype === "slack_audio" || AUDIO_TYPES.has(f.filetype ?? "")
|
|
103
|
+
);
|
|
104
|
+
if (hasAudio) {
|
|
105
|
+
body = "[Voice message \u2014 no transcript available]";
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return {
|
|
109
|
+
id,
|
|
110
|
+
channel,
|
|
111
|
+
from,
|
|
112
|
+
body,
|
|
113
|
+
threadId,
|
|
114
|
+
receivedAt,
|
|
115
|
+
raw: event
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
async function enrichVoiceMessage(msg, botToken) {
|
|
119
|
+
if (!msg.body.includes("[Voice message \u2014 no transcript available]")) return msg;
|
|
120
|
+
const raw = msg.raw;
|
|
121
|
+
const files = raw?.files;
|
|
122
|
+
if (!files?.length) return msg;
|
|
123
|
+
const audioFile = files.find(
|
|
124
|
+
(f) => f.subtype === "slack_audio" || AUDIO_TYPES.has(f.filetype ?? "")
|
|
125
|
+
);
|
|
126
|
+
if (!audioFile?.url_private) return msg;
|
|
127
|
+
const buffer = await downloadAudio(audioFile.url_private, botToken);
|
|
128
|
+
if (!buffer) return msg;
|
|
129
|
+
const filename = audioFile.name ?? `voice.${audioFile.filetype ?? "aac"}`;
|
|
130
|
+
const transcript = await transcribeAudio(buffer, filename);
|
|
131
|
+
if (!transcript) return msg;
|
|
132
|
+
return {
|
|
133
|
+
...msg,
|
|
134
|
+
body: `[Voice message] ${transcript}`
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export {
|
|
139
|
+
transcribeAudio,
|
|
140
|
+
downloadAudio,
|
|
141
|
+
extractVoiceTranscript,
|
|
142
|
+
parseSlackEvent,
|
|
143
|
+
enrichVoiceMessage
|
|
144
|
+
};
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// src/channels/slack/transcribe.ts
|
|
2
|
+
import { execFileSync } from "child_process";
|
|
3
|
+
import { writeFileSync, unlinkSync, mkdirSync } from "fs";
|
|
4
|
+
import { join } from "path";
|
|
5
|
+
import { randomUUID } from "crypto";
|
|
6
|
+
import os from "os";
|
|
7
|
+
import { createRequire } from "module";
|
|
8
|
+
var TEMP_DIR = join(os.tmpdir(), "botinabox-audio");
|
|
9
|
+
async function transcribeAudio(audioBuffer, filename, opts) {
|
|
10
|
+
let whisper;
|
|
11
|
+
try {
|
|
12
|
+
const require2 = createRequire(import.meta.url);
|
|
13
|
+
const mod = require2("whisper-node");
|
|
14
|
+
whisper = mod.whisper ?? mod.default ?? mod;
|
|
15
|
+
} catch {
|
|
16
|
+
console.warn("[botinabox] whisper-node not installed \u2014 voice transcription unavailable. Run: npm install whisper-node && npx whisper-node download");
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
try {
|
|
20
|
+
execFileSync("ffmpeg", ["-version"], { stdio: "ignore" });
|
|
21
|
+
} catch {
|
|
22
|
+
console.warn("[botinabox] ffmpeg not found \u2014 required for audio conversion. Install: brew install ffmpeg");
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
const id = randomUUID().slice(0, 8);
|
|
26
|
+
const ext = filename.split(".").pop() ?? "aac";
|
|
27
|
+
mkdirSync(TEMP_DIR, { recursive: true });
|
|
28
|
+
const inputPath = join(TEMP_DIR, `${id}.${ext}`);
|
|
29
|
+
const wavPath = join(TEMP_DIR, `${id}.wav`);
|
|
30
|
+
try {
|
|
31
|
+
writeFileSync(inputPath, audioBuffer);
|
|
32
|
+
execFileSync("ffmpeg", ["-y", "-i", inputPath, "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", wavPath], {
|
|
33
|
+
stdio: "ignore",
|
|
34
|
+
timeout: 3e4
|
|
35
|
+
});
|
|
36
|
+
const segments = await whisper(wavPath, {
|
|
37
|
+
modelName: opts?.modelName ?? "base.en",
|
|
38
|
+
whisperOptions: {
|
|
39
|
+
language: opts?.language ?? "auto"
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
if (!segments || segments.length === 0) return null;
|
|
43
|
+
return segments.map((s) => s.speech).join(" ").trim();
|
|
44
|
+
} catch (err) {
|
|
45
|
+
console.error("[botinabox] Transcription failed:", err);
|
|
46
|
+
return null;
|
|
47
|
+
} finally {
|
|
48
|
+
try {
|
|
49
|
+
unlinkSync(inputPath);
|
|
50
|
+
} catch {
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
unlinkSync(wavPath);
|
|
54
|
+
} catch {
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
async function downloadAudio(url, token) {
|
|
59
|
+
try {
|
|
60
|
+
const resp = await fetch(url, {
|
|
61
|
+
headers: { Authorization: `Bearer ${token}` }
|
|
62
|
+
});
|
|
63
|
+
if (!resp.ok) {
|
|
64
|
+
console.error(`[botinabox] Audio download failed: ${resp.status} ${resp.statusText}`);
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
return Buffer.from(await resp.arrayBuffer());
|
|
68
|
+
} catch (err) {
|
|
69
|
+
console.error("[botinabox] Audio download error:", err);
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/channels/slack/inbound.ts
|
|
75
|
+
var AUDIO_TYPES = /* @__PURE__ */ new Set(["aac", "mp4", "m4a", "ogg", "webm", "mp3", "wav"]);
|
|
76
|
+
function extractVoiceTranscript(file) {
|
|
77
|
+
const isAudio = file.subtype === "slack_audio" || AUDIO_TYPES.has(file.filetype ?? "");
|
|
78
|
+
if (!isAudio) return null;
|
|
79
|
+
const transcript = file.transcription?.preview?.content ?? (typeof file.preview === "string" ? file.preview : null);
|
|
80
|
+
return transcript ?? null;
|
|
81
|
+
}
|
|
82
|
+
function parseSlackEvent(event) {
|
|
83
|
+
const id = event.client_msg_id ?? event.ts ?? event.event_ts ?? `slack-${Date.now()}`;
|
|
84
|
+
const channel = event.channel ?? "unknown";
|
|
85
|
+
const from = event.user ?? "unknown";
|
|
86
|
+
const threadId = event.thread_ts !== void 0 ? event.thread_ts : void 0;
|
|
87
|
+
const receivedAt = event.ts ? new Date(parseFloat(event.ts) * 1e3).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
|
|
88
|
+
let body = event.text ?? "";
|
|
89
|
+
if (event.subtype === "file_share" && event.files?.length) {
|
|
90
|
+
for (const file of event.files) {
|
|
91
|
+
const transcript = extractVoiceTranscript(file);
|
|
92
|
+
if (transcript) {
|
|
93
|
+
body = body ? `${body}
|
|
94
|
+
|
|
95
|
+
[Voice message] ${transcript}` : `[Voice message] ${transcript}`;
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (event.subtype === "file_share" && event.files?.length && !body) {
|
|
101
|
+
const hasAudio = event.files.some(
|
|
102
|
+
(f) => f.subtype === "slack_audio" || AUDIO_TYPES.has(f.filetype ?? "")
|
|
103
|
+
);
|
|
104
|
+
if (hasAudio) {
|
|
105
|
+
body = "[Voice message \u2014 no transcript available]";
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return {
|
|
109
|
+
id,
|
|
110
|
+
channel,
|
|
111
|
+
from,
|
|
112
|
+
body,
|
|
113
|
+
threadId,
|
|
114
|
+
receivedAt,
|
|
115
|
+
raw: event
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
async function enrichVoiceMessage(msg, botToken) {
|
|
119
|
+
if (!msg.body.includes("[Voice message \u2014 no transcript available]")) return msg;
|
|
120
|
+
const raw = msg.raw;
|
|
121
|
+
const files = raw?.files;
|
|
122
|
+
if (!files?.length) return msg;
|
|
123
|
+
const audioFile = files.find(
|
|
124
|
+
(f) => f.subtype === "slack_audio" || AUDIO_TYPES.has(f.filetype ?? "")
|
|
125
|
+
);
|
|
126
|
+
if (!audioFile?.url_private) return msg;
|
|
127
|
+
const buffer = await downloadAudio(audioFile.url_private, botToken);
|
|
128
|
+
if (!buffer) return msg;
|
|
129
|
+
const filename = audioFile.name ?? `voice.${audioFile.filetype ?? "aac"}`;
|
|
130
|
+
const transcript = await transcribeAudio(buffer, filename);
|
|
131
|
+
if (!transcript) return msg;
|
|
132
|
+
return {
|
|
133
|
+
...msg,
|
|
134
|
+
body: `[Voice message] ${transcript}`
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export {
|
|
139
|
+
transcribeAudio,
|
|
140
|
+
downloadAudio,
|
|
141
|
+
extractVoiceTranscript,
|
|
142
|
+
parseSlackEvent,
|
|
143
|
+
enrichVoiceMessage
|
|
144
|
+
};
|
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
// src/connectors/google/oauth.ts
|
|
2
|
+
var _google;
|
|
3
|
+
async function getGoogle() {
|
|
4
|
+
if (!_google) {
|
|
5
|
+
try {
|
|
6
|
+
const mod = await import("googleapis");
|
|
7
|
+
_google = mod.google;
|
|
8
|
+
} catch {
|
|
9
|
+
throw new Error(
|
|
10
|
+
"googleapis is required for Google connectors. Install it: npm install googleapis"
|
|
11
|
+
);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
return _google;
|
|
15
|
+
}
|
|
16
|
+
async function createOAuth2Client(config) {
|
|
17
|
+
const google = await getGoogle();
|
|
18
|
+
return new google.auth.OAuth2(
|
|
19
|
+
config.clientId,
|
|
20
|
+
config.clientSecret,
|
|
21
|
+
config.redirectUri
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
function getAuthUrl(client, scopes) {
|
|
25
|
+
return client.generateAuthUrl({
|
|
26
|
+
access_type: "offline",
|
|
27
|
+
prompt: "consent",
|
|
28
|
+
scope: scopes
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
async function exchangeCode(client, code) {
|
|
32
|
+
const { tokens } = await client.getToken(code);
|
|
33
|
+
return tokens;
|
|
34
|
+
}
|
|
35
|
+
async function createServiceAccountClient(config, scopes) {
|
|
36
|
+
const google = await getGoogle();
|
|
37
|
+
const auth = new google.auth.GoogleAuth({
|
|
38
|
+
...config.keyFile ? { keyFile: config.keyFile } : {},
|
|
39
|
+
...config.credentials ? { credentials: config.credentials } : {},
|
|
40
|
+
scopes,
|
|
41
|
+
clientOptions: { subject: config.subject }
|
|
42
|
+
});
|
|
43
|
+
return auth.getClient();
|
|
44
|
+
}
|
|
45
|
+
async function loadTokens(getter, accountKey) {
|
|
46
|
+
const raw = await getter(`google_tokens:${accountKey}`);
|
|
47
|
+
if (!raw) return null;
|
|
48
|
+
try {
|
|
49
|
+
return JSON.parse(raw);
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async function saveTokens(setter, accountKey, tokens) {
|
|
55
|
+
await setter(`google_tokens:${accountKey}`, JSON.stringify(tokens));
|
|
56
|
+
}
|
|
57
|
+
async function refreshIfNeeded(client, tokens, saver) {
|
|
58
|
+
const buffer = 6e4;
|
|
59
|
+
const isExpired = tokens.expiry_date != null && Date.now() >= tokens.expiry_date - buffer;
|
|
60
|
+
if (!isExpired) return tokens;
|
|
61
|
+
client.setCredentials(tokens);
|
|
62
|
+
const { credentials } = await client.refreshAccessToken();
|
|
63
|
+
const refreshed = {
|
|
64
|
+
access_token: credentials.access_token,
|
|
65
|
+
refresh_token: credentials.refresh_token ?? tokens.refresh_token,
|
|
66
|
+
expiry_date: credentials.expiry_date ?? void 0,
|
|
67
|
+
token_type: credentials.token_type ?? "Bearer"
|
|
68
|
+
};
|
|
69
|
+
if (saver) {
|
|
70
|
+
await saver(refreshed);
|
|
71
|
+
}
|
|
72
|
+
return refreshed;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// src/connectors/google/gmail-connector.ts
|
|
76
|
+
var GoogleGmailConnector = class {
|
|
77
|
+
id = "google-gmail";
|
|
78
|
+
meta = {
|
|
79
|
+
displayName: "Google Gmail",
|
|
80
|
+
provider: "google",
|
|
81
|
+
dataType: "email"
|
|
82
|
+
};
|
|
83
|
+
tokenLoader;
|
|
84
|
+
tokenSaver;
|
|
85
|
+
client = null;
|
|
86
|
+
config = null;
|
|
87
|
+
tokens = null;
|
|
88
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
89
|
+
gmail = null;
|
|
90
|
+
constructor(opts = {}) {
|
|
91
|
+
this.tokenLoader = opts.tokenLoader;
|
|
92
|
+
this.tokenSaver = opts.tokenSaver;
|
|
93
|
+
}
|
|
94
|
+
// ── Lifecycle ──────────────────────────────────────────────────
|
|
95
|
+
async connect(config) {
|
|
96
|
+
this.config = config;
|
|
97
|
+
const scopes = config.scopes ?? [
|
|
98
|
+
"https://www.googleapis.com/auth/gmail.readonly"
|
|
99
|
+
];
|
|
100
|
+
if (config.serviceAccount) {
|
|
101
|
+
this.client = await createServiceAccountClient(config.serviceAccount, scopes);
|
|
102
|
+
} else if (config.oauth) {
|
|
103
|
+
this.client = await createOAuth2Client(config.oauth);
|
|
104
|
+
if (!this.tokenLoader) {
|
|
105
|
+
throw new Error("tokenLoader required for OAuth2 flow");
|
|
106
|
+
}
|
|
107
|
+
this.tokens = await loadTokens(this.tokenLoader, config.account);
|
|
108
|
+
if (!this.tokens) {
|
|
109
|
+
throw new Error(
|
|
110
|
+
`No stored tokens for account ${config.account}. Complete the OAuth flow first.`
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
this.tokens = await refreshIfNeeded(
|
|
114
|
+
this.client,
|
|
115
|
+
this.tokens,
|
|
116
|
+
this.tokenSaver ? async (t) => saveTokens(this.tokenSaver, config.account, t) : void 0
|
|
117
|
+
);
|
|
118
|
+
this.client.setCredentials(this.tokens);
|
|
119
|
+
} else {
|
|
120
|
+
throw new Error("Either serviceAccount or oauth config is required");
|
|
121
|
+
}
|
|
122
|
+
const { google } = await import("googleapis");
|
|
123
|
+
this.gmail = google.gmail({ version: "v1", auth: this.client });
|
|
124
|
+
}
|
|
125
|
+
async disconnect() {
|
|
126
|
+
this.client = null;
|
|
127
|
+
this.gmail = null;
|
|
128
|
+
this.tokens = null;
|
|
129
|
+
this.config = null;
|
|
130
|
+
}
|
|
131
|
+
async healthCheck() {
|
|
132
|
+
try {
|
|
133
|
+
this.ensureConnected();
|
|
134
|
+
const res = await this.gmail.users.getProfile({ userId: "me" });
|
|
135
|
+
return { ok: true, account: res.data.emailAddress };
|
|
136
|
+
} catch (err) {
|
|
137
|
+
return { ok: false, error: errorMessage(err) };
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
// ── Auth ───────────────────────────────────────────────────────
|
|
141
|
+
async authenticate(codeProvider) {
|
|
142
|
+
if (!this.config) {
|
|
143
|
+
return { success: false, error: "Call connect() first to set config, or pass config and call authenticate() before connect()." };
|
|
144
|
+
}
|
|
145
|
+
try {
|
|
146
|
+
if (!this.config.oauth) {
|
|
147
|
+
return { success: false, error: "OAuth config required for browser-based authenticate(). Use serviceAccount for headless auth." };
|
|
148
|
+
}
|
|
149
|
+
if (!this.tokenSaver) {
|
|
150
|
+
return { success: false, error: "tokenSaver required for authenticate() flow." };
|
|
151
|
+
}
|
|
152
|
+
const client = await createOAuth2Client(this.config.oauth);
|
|
153
|
+
const scopes = this.config.scopes ?? [
|
|
154
|
+
"https://www.googleapis.com/auth/gmail.readonly",
|
|
155
|
+
"https://www.googleapis.com/auth/gmail.send"
|
|
156
|
+
];
|
|
157
|
+
const authUrl = getAuthUrl(client, scopes);
|
|
158
|
+
const code = await codeProvider(authUrl);
|
|
159
|
+
const tokens = await exchangeCode(client, code);
|
|
160
|
+
await saveTokens(this.tokenSaver, this.config.account, tokens);
|
|
161
|
+
this.tokens = tokens;
|
|
162
|
+
this.client = client;
|
|
163
|
+
this.client.setCredentials(tokens);
|
|
164
|
+
const { google } = await import("googleapis");
|
|
165
|
+
this.gmail = google.gmail({ version: "v1", auth: this.client });
|
|
166
|
+
return { success: true, account: this.config.account };
|
|
167
|
+
} catch (err) {
|
|
168
|
+
return { success: false, error: errorMessage(err) };
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
// ── Sync ───────────────────────────────────────────────────────
|
|
172
|
+
async sync(options) {
|
|
173
|
+
this.ensureConnected();
|
|
174
|
+
if (options?.cursor) {
|
|
175
|
+
return this.syncIncremental(options.cursor, options.limit);
|
|
176
|
+
}
|
|
177
|
+
return this.syncFull(options);
|
|
178
|
+
}
|
|
179
|
+
/** Incremental sync using Gmail history API. */
|
|
180
|
+
async syncIncremental(startHistoryId, limit) {
|
|
181
|
+
const records = [];
|
|
182
|
+
const errors = [];
|
|
183
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
184
|
+
let pageToken;
|
|
185
|
+
let latestHistoryId = startHistoryId;
|
|
186
|
+
do {
|
|
187
|
+
const res = await this.gmail.users.history.list({
|
|
188
|
+
userId: "me",
|
|
189
|
+
startHistoryId,
|
|
190
|
+
historyTypes: ["messageAdded"],
|
|
191
|
+
...pageToken ? { pageToken } : {}
|
|
192
|
+
});
|
|
193
|
+
latestHistoryId = res.data.historyId ?? latestHistoryId;
|
|
194
|
+
const histories = res.data.history ?? [];
|
|
195
|
+
for (const h of histories) {
|
|
196
|
+
for (const added of h.messagesAdded ?? []) {
|
|
197
|
+
const msgId = added.message?.id;
|
|
198
|
+
if (!msgId || seenIds.has(msgId)) continue;
|
|
199
|
+
seenIds.add(msgId);
|
|
200
|
+
try {
|
|
201
|
+
const record = await this.fetchMessage(msgId);
|
|
202
|
+
records.push(record);
|
|
203
|
+
} catch (err) {
|
|
204
|
+
errors.push({ id: msgId, error: errorMessage(err) });
|
|
205
|
+
}
|
|
206
|
+
if (limit && records.length >= limit) {
|
|
207
|
+
return { records, cursor: latestHistoryId, hasMore: true, errors };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
pageToken = res.data.nextPageToken ?? void 0;
|
|
212
|
+
} while (pageToken);
|
|
213
|
+
return { records, cursor: latestHistoryId, hasMore: false, errors };
|
|
214
|
+
}
|
|
215
|
+
/** Full sync — list messages and fetch each one. */
|
|
216
|
+
async syncFull(options) {
|
|
217
|
+
const records = [];
|
|
218
|
+
const errors = [];
|
|
219
|
+
const maxResults = options?.limit ?? 100;
|
|
220
|
+
let query = "";
|
|
221
|
+
if (options?.since) {
|
|
222
|
+
const epoch = Math.floor(new Date(options.since).getTime() / 1e3);
|
|
223
|
+
query = `after:${epoch}`;
|
|
224
|
+
}
|
|
225
|
+
if (options?.filters?.q) {
|
|
226
|
+
query = query ? `${query} ${options.filters.q}` : String(options.filters.q);
|
|
227
|
+
}
|
|
228
|
+
let pageToken;
|
|
229
|
+
let collected = 0;
|
|
230
|
+
do {
|
|
231
|
+
const res = await this.gmail.users.messages.list({
|
|
232
|
+
userId: "me",
|
|
233
|
+
maxResults: Math.min(maxResults - collected, 100),
|
|
234
|
+
...query ? { q: query } : {},
|
|
235
|
+
...pageToken ? { pageToken } : {}
|
|
236
|
+
});
|
|
237
|
+
const messages = res.data.messages ?? [];
|
|
238
|
+
for (const msg of messages) {
|
|
239
|
+
try {
|
|
240
|
+
const record = await this.fetchMessage(msg.id);
|
|
241
|
+
records.push(record);
|
|
242
|
+
} catch (err) {
|
|
243
|
+
errors.push({ id: msg.id, error: errorMessage(err) });
|
|
244
|
+
}
|
|
245
|
+
collected++;
|
|
246
|
+
if (collected >= maxResults) break;
|
|
247
|
+
}
|
|
248
|
+
pageToken = res.data.nextPageToken ?? void 0;
|
|
249
|
+
} while (pageToken && collected < maxResults);
|
|
250
|
+
const profile = await this.gmail.users.getProfile({ userId: "me" });
|
|
251
|
+
const cursor = profile.data.historyId ?? void 0;
|
|
252
|
+
return {
|
|
253
|
+
records,
|
|
254
|
+
cursor,
|
|
255
|
+
hasMore: !!pageToken,
|
|
256
|
+
errors
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
// ── Push (send email) ─────────────────────────────────────────
|
|
260
|
+
async push(payload) {
|
|
261
|
+
this.ensureConnected();
|
|
262
|
+
try {
|
|
263
|
+
const toHeader = payload.to.map(formatAddress).join(", ");
|
|
264
|
+
const ccHeader = payload.cc.length ? `Cc: ${payload.cc.map(formatAddress).join(", ")}\r
|
|
265
|
+
` : "";
|
|
266
|
+
const bccHeader = payload.bcc.length ? `Bcc: ${payload.bcc.map(formatAddress).join(", ")}\r
|
|
267
|
+
` : "";
|
|
268
|
+
const mime = [
|
|
269
|
+
`To: ${toHeader}\r
|
|
270
|
+
`,
|
|
271
|
+
ccHeader,
|
|
272
|
+
bccHeader,
|
|
273
|
+
`Subject: ${payload.subject}\r
|
|
274
|
+
`,
|
|
275
|
+
`Content-Type: text/plain; charset="UTF-8"\r
|
|
276
|
+
`,
|
|
277
|
+
`\r
|
|
278
|
+
`,
|
|
279
|
+
payload.body ?? ""
|
|
280
|
+
].join("");
|
|
281
|
+
const encoded = Buffer.from(mime).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
282
|
+
const res = await this.gmail.users.messages.send({
|
|
283
|
+
userId: "me",
|
|
284
|
+
requestBody: { raw: encoded }
|
|
285
|
+
});
|
|
286
|
+
return { success: true, externalId: res.data.id };
|
|
287
|
+
} catch (err) {
|
|
288
|
+
return { success: false, error: errorMessage(err) };
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
// ── Internals ─────────────────────────────────────────────────
|
|
292
|
+
ensureConnected() {
|
|
293
|
+
if (!this.gmail || !this.config) {
|
|
294
|
+
throw new Error("GoogleGmailConnector is not connected. Call connect() first.");
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
/** Fetch a single message by ID and parse into an EmailRecord. */
|
|
298
|
+
async fetchMessage(messageId) {
|
|
299
|
+
const res = await this.gmail.users.messages.get({
|
|
300
|
+
userId: "me",
|
|
301
|
+
id: messageId,
|
|
302
|
+
format: "full"
|
|
303
|
+
});
|
|
304
|
+
const msg = res.data;
|
|
305
|
+
const headers = msg.payload?.headers ?? [];
|
|
306
|
+
const getHeader = (name) => headers.find((h) => h.name.toLowerCase() === name.toLowerCase())?.value ?? "";
|
|
307
|
+
return {
|
|
308
|
+
gmailId: msg.id,
|
|
309
|
+
threadId: msg.threadId,
|
|
310
|
+
account: this.config.account,
|
|
311
|
+
subject: getHeader("Subject"),
|
|
312
|
+
from: parseAddress(getHeader("From")),
|
|
313
|
+
to: parseAddressList(getHeader("To")),
|
|
314
|
+
cc: parseAddressList(getHeader("Cc")),
|
|
315
|
+
bcc: parseAddressList(getHeader("Bcc")),
|
|
316
|
+
date: new Date(getHeader("Date")).toISOString(),
|
|
317
|
+
snippet: msg.snippet ?? "",
|
|
318
|
+
body: extractPlainTextBody(msg.payload),
|
|
319
|
+
labels: msg.labelIds ?? [],
|
|
320
|
+
isRead: !(msg.labelIds ?? []).includes("UNREAD")
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
function extractPlainTextBody(payload) {
|
|
325
|
+
if (!payload) return void 0;
|
|
326
|
+
if (payload.mimeType === "text/plain" && payload.body?.data) {
|
|
327
|
+
return decodeBase64Url(payload.body.data);
|
|
328
|
+
}
|
|
329
|
+
if (payload.parts) {
|
|
330
|
+
for (const part of payload.parts) {
|
|
331
|
+
if (part.mimeType === "text/plain" && part.body?.data) {
|
|
332
|
+
return decodeBase64Url(part.body.data);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
for (const part of payload.parts) {
|
|
336
|
+
if (part.mimeType?.startsWith("multipart/")) {
|
|
337
|
+
const result = extractPlainTextBody(part);
|
|
338
|
+
if (result) return result;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
return void 0;
|
|
343
|
+
}
|
|
344
|
+
function decodeBase64Url(data) {
|
|
345
|
+
const base64 = data.replace(/-/g, "+").replace(/_/g, "/");
|
|
346
|
+
return Buffer.from(base64, "base64").toString("utf-8");
|
|
347
|
+
}
|
|
348
|
+
function parseAddress(raw) {
|
|
349
|
+
const match = raw.match(/^(.+?)\s*<([^>]+)>$/);
|
|
350
|
+
if (match) {
|
|
351
|
+
return { name: match[1].replace(/^["']|["']$/g, "").trim(), email: match[2] };
|
|
352
|
+
}
|
|
353
|
+
return { email: raw.trim() };
|
|
354
|
+
}
|
|
355
|
+
function parseAddressList(raw) {
|
|
356
|
+
if (!raw.trim()) return [];
|
|
357
|
+
const results = [];
|
|
358
|
+
let current = "";
|
|
359
|
+
let depth = 0;
|
|
360
|
+
for (const ch of raw) {
|
|
361
|
+
if (ch === "<") depth++;
|
|
362
|
+
else if (ch === ">") depth--;
|
|
363
|
+
else if (ch === "," && depth === 0) {
|
|
364
|
+
if (current.trim()) results.push(parseAddress(current.trim()));
|
|
365
|
+
current = "";
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
current += ch;
|
|
369
|
+
}
|
|
370
|
+
if (current.trim()) results.push(parseAddress(current.trim()));
|
|
371
|
+
return results;
|
|
372
|
+
}
|
|
373
|
+
function formatAddress(addr) {
|
|
374
|
+
return addr.name ? `${addr.name} <${addr.email}>` : addr.email;
|
|
375
|
+
}
|
|
376
|
+
function errorMessage(err) {
|
|
377
|
+
return err instanceof Error ? err.message : String(err);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
export {
|
|
381
|
+
createOAuth2Client,
|
|
382
|
+
getAuthUrl,
|
|
383
|
+
exchangeCode,
|
|
384
|
+
createServiceAccountClient,
|
|
385
|
+
loadTokens,
|
|
386
|
+
saveTokens,
|
|
387
|
+
refreshIfNeeded,
|
|
388
|
+
GoogleGmailConnector
|
|
389
|
+
};
|
package/dist/cli.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// src/cli.ts
|
|
4
4
|
import * as readline from "readline";
|
|
5
5
|
import * as fs from "fs";
|
|
6
|
-
import {
|
|
6
|
+
import { execFileSync } from "child_process";
|
|
7
7
|
|
|
8
8
|
// src/update-check.ts
|
|
9
9
|
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
|
|
@@ -104,7 +104,7 @@ async function runUpdate(currentVersion) {
|
|
|
104
104
|
}
|
|
105
105
|
console.log(`Updating to ${latest}...`);
|
|
106
106
|
try {
|
|
107
|
-
|
|
107
|
+
execFileSync("npm", ["install", "-g", "botinabox@latest"], { stdio: "inherit" });
|
|
108
108
|
console.log(`Updated botinabox ${currentVersion} \u2192 ${latest}`);
|
|
109
109
|
} catch {
|
|
110
110
|
console.error("Update failed. Try running manually: npm install -g botinabox@latest");
|
|
@@ -178,7 +178,7 @@ async function authGoogle(args) {
|
|
|
178
178
|
});
|
|
179
179
|
}
|
|
180
180
|
};
|
|
181
|
-
const { GoogleGmailConnector } = await import("./gmail-connector-
|
|
181
|
+
const { GoogleGmailConnector } = await import("./gmail-connector-ULSMN6X2.js");
|
|
182
182
|
const connector = new GoogleGmailConnector({ tokenLoader, tokenSaver });
|
|
183
183
|
connector.config = {
|
|
184
184
|
account,
|
package/dist/index.d.ts
CHANGED
|
@@ -1537,7 +1537,15 @@ interface SecretMeta {
|
|
|
1537
1537
|
declare class SecretStore {
|
|
1538
1538
|
private readonly db;
|
|
1539
1539
|
private readonly hooks;
|
|
1540
|
-
|
|
1540
|
+
private readonly encKey;
|
|
1541
|
+
/**
|
|
1542
|
+
* @param db - DataStore instance
|
|
1543
|
+
* @param hooks - HookBus instance
|
|
1544
|
+
* @param encryptionKey - Optional master key for encrypting secrets at rest.
|
|
1545
|
+
* When provided, all new secrets are encrypted with AES-256-GCM.
|
|
1546
|
+
* Existing plaintext secrets are read transparently (passthrough on decrypt).
|
|
1547
|
+
*/
|
|
1548
|
+
constructor(db: DataStore, hooks: HookBus, encryptionKey?: string);
|
|
1541
1549
|
set(input: SecretInput): Promise<SecretMeta>;
|
|
1542
1550
|
get(name: string, environment?: string): Promise<string | null>;
|
|
1543
1551
|
getMeta(name: string, environment?: string): Promise<SecretMeta | null>;
|
package/dist/index.js
CHANGED
|
@@ -1124,6 +1124,9 @@ var DataStore = class {
|
|
|
1124
1124
|
for (const stmt of def.tableConstraints ?? []) {
|
|
1125
1125
|
const upper = stmt.trimStart().toUpperCase();
|
|
1126
1126
|
if (upper.startsWith("CREATE ") || upper.startsWith("DROP ") || upper.startsWith("ALTER ")) {
|
|
1127
|
+
if (stmt.includes(";")) {
|
|
1128
|
+
throw new DataStoreError(`Deferred DDL statement must not contain semicolons: ${stmt}`);
|
|
1129
|
+
}
|
|
1127
1130
|
this.deferredStatements.push(stmt);
|
|
1128
1131
|
} else {
|
|
1129
1132
|
inlineConstraints.push(stmt);
|
|
@@ -1146,8 +1149,11 @@ var DataStore = class {
|
|
|
1146
1149
|
this.lattice.defineEntityContext(name, {
|
|
1147
1150
|
slug: (row) => {
|
|
1148
1151
|
const val = row[def.slugColumn];
|
|
1149
|
-
|
|
1150
|
-
|
|
1152
|
+
const raw = val == null ? String(row.id ?? row.name ?? "unknown") : String(val);
|
|
1153
|
+
if (raw.includes("/") || raw.includes("\\") || raw.includes("..")) {
|
|
1154
|
+
throw new Error(`Invalid slug "${raw}": contains path traversal characters`);
|
|
1155
|
+
}
|
|
1156
|
+
return raw;
|
|
1151
1157
|
},
|
|
1152
1158
|
directoryRoot: def.directory,
|
|
1153
1159
|
files: def.files,
|
|
@@ -2728,9 +2734,10 @@ async function runPackageMigrations(db, migrations) {
|
|
|
2728
2734
|
}
|
|
2729
2735
|
|
|
2730
2736
|
// src/core/update/auto-update.ts
|
|
2731
|
-
import {
|
|
2737
|
+
import { execFileSync } from "child_process";
|
|
2732
2738
|
import { readFileSync as readFileSync3 } from "fs";
|
|
2733
2739
|
import { join as join5 } from "path";
|
|
2740
|
+
var SEMVER_RE = /^\d+\.\d+\.\d+(-[\w.]+)?$/;
|
|
2734
2741
|
function getInstalledVersion(pkgName) {
|
|
2735
2742
|
try {
|
|
2736
2743
|
const pkgPath = join5(process.cwd(), "node_modules", pkgName, "package.json");
|
|
@@ -2773,6 +2780,10 @@ async function autoUpdate(packages = ["botinabox", "latticesql"], opts) {
|
|
|
2773
2780
|
const latest = await getLatestVersion(pkg);
|
|
2774
2781
|
if (!latest) continue;
|
|
2775
2782
|
if (isNewer(latest, installed)) {
|
|
2783
|
+
if (!SEMVER_RE.test(latest)) {
|
|
2784
|
+
console.error(`[autoUpdate] Rejecting invalid version "${latest}" for ${pkg}`);
|
|
2785
|
+
continue;
|
|
2786
|
+
}
|
|
2776
2787
|
toInstall.push(`${pkg}@${latest}`);
|
|
2777
2788
|
result.packages.push({ name: pkg, from: installed, to: latest });
|
|
2778
2789
|
}
|
|
@@ -2780,7 +2791,7 @@ async function autoUpdate(packages = ["botinabox", "latticesql"], opts) {
|
|
|
2780
2791
|
if (toInstall.length === 0) return result;
|
|
2781
2792
|
log(`[autoUpdate] Updating: ${toInstall.join(", ")}`);
|
|
2782
2793
|
try {
|
|
2783
|
-
|
|
2794
|
+
execFileSync("npm", ["install", ...toInstall], {
|
|
2784
2795
|
cwd: process.cwd(),
|
|
2785
2796
|
stdio: opts?.quiet ? "ignore" : "inherit",
|
|
2786
2797
|
timeout: 6e4
|
|
@@ -3613,10 +3624,14 @@ var Scheduler = class {
|
|
|
3613
3624
|
for (const schedule of schedules) {
|
|
3614
3625
|
try {
|
|
3615
3626
|
const config = JSON.parse(schedule.action_config || "{}");
|
|
3627
|
+
const safeConfig = {};
|
|
3628
|
+
for (const [k, v] of Object.entries(config)) {
|
|
3629
|
+
if (!k.startsWith("__")) safeConfig[k] = v;
|
|
3630
|
+
}
|
|
3616
3631
|
await this.hooks.emit(schedule.action, {
|
|
3617
3632
|
schedule_id: schedule.id,
|
|
3618
3633
|
schedule_name: schedule.name,
|
|
3619
|
-
...
|
|
3634
|
+
...safeConfig
|
|
3620
3635
|
});
|
|
3621
3636
|
await this.hooks.emit("schedule.fired", {
|
|
3622
3637
|
schedule_id: schedule.id,
|
|
@@ -4136,19 +4151,57 @@ var UserRegistry = class {
|
|
|
4136
4151
|
|
|
4137
4152
|
// src/core/orchestrator/secret-store.ts
|
|
4138
4153
|
import { v4 as uuidv42 } from "uuid";
|
|
4154
|
+
import { scryptSync, createCipheriv, createDecipheriv, randomBytes } from "crypto";
|
|
4155
|
+
var ENC_PREFIX = "enc:";
|
|
4156
|
+
var ALGORITHM = "aes-256-gcm";
|
|
4157
|
+
var IV_LEN = 12;
|
|
4158
|
+
var TAG_LEN = 16;
|
|
4159
|
+
function deriveEncKey(masterKey) {
|
|
4160
|
+
return scryptSync(masterKey, "botinabox-secrets-v1", 32);
|
|
4161
|
+
}
|
|
4162
|
+
function encryptValue(plaintext, key) {
|
|
4163
|
+
const iv = randomBytes(IV_LEN);
|
|
4164
|
+
const cipher = createCipheriv(ALGORITHM, key, iv);
|
|
4165
|
+
const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
|
4166
|
+
const tag = cipher.getAuthTag();
|
|
4167
|
+
return ENC_PREFIX + Buffer.concat([iv, tag, encrypted]).toString("base64");
|
|
4168
|
+
}
|
|
4169
|
+
function decryptValue(ciphertext, key) {
|
|
4170
|
+
if (!ciphertext.startsWith(ENC_PREFIX)) return ciphertext;
|
|
4171
|
+
const buf = Buffer.from(ciphertext.slice(ENC_PREFIX.length), "base64");
|
|
4172
|
+
const iv = buf.subarray(0, IV_LEN);
|
|
4173
|
+
const tag = buf.subarray(IV_LEN, IV_LEN + TAG_LEN);
|
|
4174
|
+
const data = buf.subarray(IV_LEN + TAG_LEN);
|
|
4175
|
+
const decipher = createDecipheriv(ALGORITHM, key, iv);
|
|
4176
|
+
decipher.setAuthTag(tag);
|
|
4177
|
+
return decipher.update(data).toString("utf8") + decipher.final("utf8");
|
|
4178
|
+
}
|
|
4139
4179
|
var SecretStore = class {
|
|
4140
4180
|
db;
|
|
4141
4181
|
hooks;
|
|
4142
|
-
|
|
4182
|
+
encKey;
|
|
4183
|
+
/**
|
|
4184
|
+
* @param db - DataStore instance
|
|
4185
|
+
* @param hooks - HookBus instance
|
|
4186
|
+
* @param encryptionKey - Optional master key for encrypting secrets at rest.
|
|
4187
|
+
* When provided, all new secrets are encrypted with AES-256-GCM.
|
|
4188
|
+
* Existing plaintext secrets are read transparently (passthrough on decrypt).
|
|
4189
|
+
*/
|
|
4190
|
+
constructor(db, hooks, encryptionKey) {
|
|
4143
4191
|
this.db = db;
|
|
4144
4192
|
this.hooks = hooks;
|
|
4193
|
+
this.encKey = encryptionKey ? deriveEncKey(encryptionKey) : null;
|
|
4145
4194
|
}
|
|
4146
4195
|
async set(input) {
|
|
4147
4196
|
const id = uuidv42();
|
|
4148
|
-
|
|
4197
|
+
const data = { ...input, id };
|
|
4198
|
+
if (this.encKey && data.value) {
|
|
4199
|
+
data.value = encryptValue(data.value, this.encKey);
|
|
4200
|
+
}
|
|
4201
|
+
await this.db.insert("secrets", data);
|
|
4149
4202
|
await this.hooks.emit("secret.created", { name: input.name });
|
|
4150
|
-
const
|
|
4151
|
-
return this._toMeta(
|
|
4203
|
+
const inserted = await this.db.get("secrets", id);
|
|
4204
|
+
return this._toMeta(inserted);
|
|
4152
4205
|
}
|
|
4153
4206
|
async get(name, environment = "production") {
|
|
4154
4207
|
const rows = await this.db.query("secrets", {
|
|
@@ -4158,7 +4211,9 @@ var SecretStore = class {
|
|
|
4158
4211
|
});
|
|
4159
4212
|
if (rows.length === 0) return null;
|
|
4160
4213
|
await this.hooks.emit("secret.accessed", { name, environment });
|
|
4161
|
-
|
|
4214
|
+
const raw = rows[0].value ?? null;
|
|
4215
|
+
if (raw && this.encKey) return decryptValue(raw, this.encKey);
|
|
4216
|
+
return raw;
|
|
4162
4217
|
}
|
|
4163
4218
|
async getMeta(name, environment = "production") {
|
|
4164
4219
|
const rows = await this.db.query("secrets", {
|
|
@@ -4182,8 +4237,9 @@ var SecretStore = class {
|
|
|
4182
4237
|
limit: 1
|
|
4183
4238
|
});
|
|
4184
4239
|
if (rows.length === 0) throw new Error(`Secret "${name}" not found`);
|
|
4240
|
+
const storedValue = this.encKey ? encryptValue(newValue, this.encKey) : newValue;
|
|
4185
4241
|
await this.db.update("secrets", rows[0].id, {
|
|
4186
|
-
value:
|
|
4242
|
+
value: storedValue,
|
|
4187
4243
|
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
4188
4244
|
});
|
|
4189
4245
|
await this.hooks.emit("secret.rotated", { name, environment });
|
|
@@ -4212,13 +4268,16 @@ var SecretStore = class {
|
|
|
4212
4268
|
filters: [{ col: "deleted_at", op: "isNull" }],
|
|
4213
4269
|
limit: 1
|
|
4214
4270
|
});
|
|
4215
|
-
|
|
4271
|
+
const raw = rows[0]?.value ?? void 0;
|
|
4272
|
+
if (raw && this.encKey) return decryptValue(raw, this.encKey);
|
|
4273
|
+
return raw;
|
|
4216
4274
|
}
|
|
4217
4275
|
/**
|
|
4218
4276
|
* Persist a sync cursor by key. Creates or updates the secret.
|
|
4219
4277
|
*/
|
|
4220
4278
|
async saveCursor(key, value) {
|
|
4221
4279
|
const name = `sync-cursor:${key}`;
|
|
4280
|
+
const storedValue = this.encKey ? encryptValue(value, this.encKey) : value;
|
|
4222
4281
|
const rows = await this.db.query("secrets", {
|
|
4223
4282
|
where: { name },
|
|
4224
4283
|
filters: [{ col: "deleted_at", op: "isNull" }],
|
|
@@ -4226,7 +4285,7 @@ var SecretStore = class {
|
|
|
4226
4285
|
});
|
|
4227
4286
|
if (rows.length > 0) {
|
|
4228
4287
|
await this.db.update("secrets", rows[0].id, {
|
|
4229
|
-
value,
|
|
4288
|
+
value: storedValue,
|
|
4230
4289
|
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
4231
4290
|
});
|
|
4232
4291
|
} else {
|
|
@@ -4234,7 +4293,7 @@ var SecretStore = class {
|
|
|
4234
4293
|
id: uuidv42(),
|
|
4235
4294
|
name,
|
|
4236
4295
|
type: "sync_cursor",
|
|
4237
|
-
value
|
|
4296
|
+
value: storedValue
|
|
4238
4297
|
});
|
|
4239
4298
|
}
|
|
4240
4299
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "botinabox",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "Bot in a Box — framework for building multi-agent bots",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -59,7 +59,7 @@
|
|
|
59
59
|
"@types/uuid": "^10.0.0",
|
|
60
60
|
"ajv": "^8.17.1",
|
|
61
61
|
"cron-parser": "^4.9.0",
|
|
62
|
-
"latticesql": "^1.
|
|
62
|
+
"latticesql": "^1.2.0",
|
|
63
63
|
"uuid": "^13.0.0",
|
|
64
64
|
"yaml": "^2.7.0"
|
|
65
65
|
},
|
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
},
|
|
69
69
|
"peerDependencies": {
|
|
70
70
|
"@anthropic-ai/sdk": "^0.52.0",
|
|
71
|
-
"googleapis": ">=140.0.0",
|
|
71
|
+
"googleapis": ">=140.0.0 <200.0.0",
|
|
72
72
|
"openai": "^4.104.0"
|
|
73
73
|
},
|
|
74
74
|
"peerDependenciesMeta": {
|