botinabox 0.5.2 → 0.5.3
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/README.md +6 -0
- package/dist/chunk-3X3YKI4T.js +357 -0
- package/dist/chunk-D47AIFOD.js +351 -0
- package/dist/cli.js +93 -2
- package/dist/connectors/google/index.d.ts +37 -17
- package/dist/connectors/google/index.js +33 -13
- package/dist/gmail-connector-MNUBRNFM.js +6 -0
- package/dist/gmail-connector-URRFX6A3.js +6 -0
- package/package.json +10 -2
- package/CHANGELOG.md +0 -76
- package/CONTRIBUTING.md +0 -92
package/README.md
CHANGED
|
@@ -241,6 +241,12 @@ botinabox/
|
|
|
241
241
|
└── tsconfig.json
|
|
242
242
|
```
|
|
243
243
|
|
|
244
|
+
## Staying up to date
|
|
245
|
+
|
|
246
|
+
**CLI users:** The `botinabox` CLI checks for new versions automatically and prints a notice when an update is available. Run `botinabox update` to upgrade in place. Alternatively, use `npx botinabox` to always run the latest version without a global install.
|
|
247
|
+
|
|
248
|
+
**Library consumers:** By default, `npm install botinabox` adds a `^` semver range to your `package.json`, so patch and minor updates are picked up on your next `npm install`. For fully automated dependency updates, set up [Dependabot](https://docs.github.com/en/code-security/dependabot) or [Renovate](https://github.com/renovatebot/renovate) — they'll create PRs in your repo whenever a new version is published.
|
|
249
|
+
|
|
244
250
|
## License
|
|
245
251
|
|
|
246
252
|
MIT
|
|
@@ -0,0 +1,357 @@
|
|
|
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: "metadata",
|
|
303
|
+
metadataHeaders: ["From", "To", "Cc", "Bcc", "Subject", "Date"]
|
|
304
|
+
});
|
|
305
|
+
const msg = res.data;
|
|
306
|
+
const headers = msg.payload?.headers ?? [];
|
|
307
|
+
const getHeader = (name) => headers.find((h) => h.name.toLowerCase() === name.toLowerCase())?.value ?? "";
|
|
308
|
+
return {
|
|
309
|
+
gmailId: msg.id,
|
|
310
|
+
threadId: msg.threadId,
|
|
311
|
+
account: this.config.account,
|
|
312
|
+
subject: getHeader("Subject"),
|
|
313
|
+
from: parseAddress(getHeader("From")),
|
|
314
|
+
to: parseAddressList(getHeader("To")),
|
|
315
|
+
cc: parseAddressList(getHeader("Cc")),
|
|
316
|
+
bcc: parseAddressList(getHeader("Bcc")),
|
|
317
|
+
date: new Date(getHeader("Date")).toISOString(),
|
|
318
|
+
snippet: msg.snippet ?? "",
|
|
319
|
+
labels: msg.labelIds ?? [],
|
|
320
|
+
isRead: !(msg.labelIds ?? []).includes("UNREAD")
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
function parseAddress(raw) {
|
|
325
|
+
const match = raw.match(/^(.+?)\s*<([^>]+)>$/);
|
|
326
|
+
if (match) {
|
|
327
|
+
return { name: match[1].replace(/^["']|["']$/g, "").trim(), email: match[2] };
|
|
328
|
+
}
|
|
329
|
+
return { email: raw.trim() };
|
|
330
|
+
}
|
|
331
|
+
function parseAddressList(raw) {
|
|
332
|
+
if (!raw.trim()) return [];
|
|
333
|
+
const results = [];
|
|
334
|
+
const parts = raw.split(/,(?=(?:[^<]*<[^>]*>)*[^>]*$)/);
|
|
335
|
+
for (const part of parts) {
|
|
336
|
+
const trimmed = part.trim();
|
|
337
|
+
if (trimmed) results.push(parseAddress(trimmed));
|
|
338
|
+
}
|
|
339
|
+
return results;
|
|
340
|
+
}
|
|
341
|
+
function formatAddress(addr) {
|
|
342
|
+
return addr.name ? `${addr.name} <${addr.email}>` : addr.email;
|
|
343
|
+
}
|
|
344
|
+
function errorMessage(err) {
|
|
345
|
+
return err instanceof Error ? err.message : String(err);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export {
|
|
349
|
+
createOAuth2Client,
|
|
350
|
+
getAuthUrl,
|
|
351
|
+
exchangeCode,
|
|
352
|
+
createServiceAccountClient,
|
|
353
|
+
loadTokens,
|
|
354
|
+
saveTokens,
|
|
355
|
+
refreshIfNeeded,
|
|
356
|
+
GoogleGmailConnector
|
|
357
|
+
};
|
|
@@ -0,0 +1,351 @@
|
|
|
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
|
+
const client = await createOAuth2Client(this.config.oauth);
|
|
147
|
+
const scopes = this.config.scopes ?? [
|
|
148
|
+
"https://www.googleapis.com/auth/gmail.readonly",
|
|
149
|
+
"https://www.googleapis.com/auth/gmail.send"
|
|
150
|
+
];
|
|
151
|
+
const authUrl = getAuthUrl(client, scopes);
|
|
152
|
+
const code = await codeProvider(authUrl);
|
|
153
|
+
const tokens = await exchangeCode(client, code);
|
|
154
|
+
await saveTokens(this.tokenSaver, this.config.account, tokens);
|
|
155
|
+
this.tokens = tokens;
|
|
156
|
+
this.client = client;
|
|
157
|
+
this.client.setCredentials(tokens);
|
|
158
|
+
const { google } = await import("googleapis");
|
|
159
|
+
this.gmail = google.gmail({ version: "v1", auth: this.client });
|
|
160
|
+
return { success: true, account: this.config.account };
|
|
161
|
+
} catch (err) {
|
|
162
|
+
return { success: false, error: errorMessage(err) };
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
// ── Sync ───────────────────────────────────────────────────────
|
|
166
|
+
async sync(options) {
|
|
167
|
+
this.ensureConnected();
|
|
168
|
+
if (options?.cursor) {
|
|
169
|
+
return this.syncIncremental(options.cursor, options.limit);
|
|
170
|
+
}
|
|
171
|
+
return this.syncFull(options);
|
|
172
|
+
}
|
|
173
|
+
/** Incremental sync using Gmail history API. */
|
|
174
|
+
async syncIncremental(startHistoryId, limit) {
|
|
175
|
+
const records = [];
|
|
176
|
+
const errors = [];
|
|
177
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
178
|
+
let pageToken;
|
|
179
|
+
let latestHistoryId = startHistoryId;
|
|
180
|
+
do {
|
|
181
|
+
const res = await this.gmail.users.history.list({
|
|
182
|
+
userId: "me",
|
|
183
|
+
startHistoryId,
|
|
184
|
+
historyTypes: ["messageAdded"],
|
|
185
|
+
...pageToken ? { pageToken } : {}
|
|
186
|
+
});
|
|
187
|
+
latestHistoryId = res.data.historyId ?? latestHistoryId;
|
|
188
|
+
const histories = res.data.history ?? [];
|
|
189
|
+
for (const h of histories) {
|
|
190
|
+
for (const added of h.messagesAdded ?? []) {
|
|
191
|
+
const msgId = added.message?.id;
|
|
192
|
+
if (!msgId || seenIds.has(msgId)) continue;
|
|
193
|
+
seenIds.add(msgId);
|
|
194
|
+
try {
|
|
195
|
+
const record = await this.fetchMessage(msgId);
|
|
196
|
+
records.push(record);
|
|
197
|
+
} catch (err) {
|
|
198
|
+
errors.push({ id: msgId, error: errorMessage(err) });
|
|
199
|
+
}
|
|
200
|
+
if (limit && records.length >= limit) {
|
|
201
|
+
return { records, cursor: latestHistoryId, hasMore: true, errors };
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
pageToken = res.data.nextPageToken ?? void 0;
|
|
206
|
+
} while (pageToken);
|
|
207
|
+
return { records, cursor: latestHistoryId, hasMore: false, errors };
|
|
208
|
+
}
|
|
209
|
+
/** Full sync — list messages and fetch each one. */
|
|
210
|
+
async syncFull(options) {
|
|
211
|
+
const records = [];
|
|
212
|
+
const errors = [];
|
|
213
|
+
const maxResults = options?.limit ?? 100;
|
|
214
|
+
let query = "";
|
|
215
|
+
if (options?.since) {
|
|
216
|
+
const epoch = Math.floor(new Date(options.since).getTime() / 1e3);
|
|
217
|
+
query = `after:${epoch}`;
|
|
218
|
+
}
|
|
219
|
+
if (options?.filters?.q) {
|
|
220
|
+
query = query ? `${query} ${options.filters.q}` : String(options.filters.q);
|
|
221
|
+
}
|
|
222
|
+
let pageToken;
|
|
223
|
+
let collected = 0;
|
|
224
|
+
do {
|
|
225
|
+
const res = await this.gmail.users.messages.list({
|
|
226
|
+
userId: "me",
|
|
227
|
+
maxResults: Math.min(maxResults - collected, 100),
|
|
228
|
+
...query ? { q: query } : {},
|
|
229
|
+
...pageToken ? { pageToken } : {}
|
|
230
|
+
});
|
|
231
|
+
const messages = res.data.messages ?? [];
|
|
232
|
+
for (const msg of messages) {
|
|
233
|
+
try {
|
|
234
|
+
const record = await this.fetchMessage(msg.id);
|
|
235
|
+
records.push(record);
|
|
236
|
+
} catch (err) {
|
|
237
|
+
errors.push({ id: msg.id, error: errorMessage(err) });
|
|
238
|
+
}
|
|
239
|
+
collected++;
|
|
240
|
+
if (collected >= maxResults) break;
|
|
241
|
+
}
|
|
242
|
+
pageToken = res.data.nextPageToken ?? void 0;
|
|
243
|
+
} while (pageToken && collected < maxResults);
|
|
244
|
+
const profile = await this.gmail.users.getProfile({ userId: "me" });
|
|
245
|
+
const cursor = profile.data.historyId ?? void 0;
|
|
246
|
+
return {
|
|
247
|
+
records,
|
|
248
|
+
cursor,
|
|
249
|
+
hasMore: !!pageToken,
|
|
250
|
+
errors
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
// ── Push (send email) ─────────────────────────────────────────
|
|
254
|
+
async push(payload) {
|
|
255
|
+
this.ensureConnected();
|
|
256
|
+
try {
|
|
257
|
+
const toHeader = payload.to.map(formatAddress).join(", ");
|
|
258
|
+
const ccHeader = payload.cc.length ? `Cc: ${payload.cc.map(formatAddress).join(", ")}\r
|
|
259
|
+
` : "";
|
|
260
|
+
const bccHeader = payload.bcc.length ? `Bcc: ${payload.bcc.map(formatAddress).join(", ")}\r
|
|
261
|
+
` : "";
|
|
262
|
+
const mime = [
|
|
263
|
+
`To: ${toHeader}\r
|
|
264
|
+
`,
|
|
265
|
+
ccHeader,
|
|
266
|
+
bccHeader,
|
|
267
|
+
`Subject: ${payload.subject}\r
|
|
268
|
+
`,
|
|
269
|
+
`Content-Type: text/plain; charset="UTF-8"\r
|
|
270
|
+
`,
|
|
271
|
+
`\r
|
|
272
|
+
`,
|
|
273
|
+
payload.body ?? ""
|
|
274
|
+
].join("");
|
|
275
|
+
const encoded = Buffer.from(mime).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
276
|
+
const res = await this.gmail.users.messages.send({
|
|
277
|
+
userId: "me",
|
|
278
|
+
requestBody: { raw: encoded }
|
|
279
|
+
});
|
|
280
|
+
return { success: true, externalId: res.data.id };
|
|
281
|
+
} catch (err) {
|
|
282
|
+
return { success: false, error: errorMessage(err) };
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
// ── Internals ─────────────────────────────────────────────────
|
|
286
|
+
ensureConnected() {
|
|
287
|
+
if (!this.gmail || !this.config) {
|
|
288
|
+
throw new Error("GoogleGmailConnector is not connected. Call connect() first.");
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
/** Fetch a single message by ID and parse into an EmailRecord. */
|
|
292
|
+
async fetchMessage(messageId) {
|
|
293
|
+
const res = await this.gmail.users.messages.get({
|
|
294
|
+
userId: "me",
|
|
295
|
+
id: messageId,
|
|
296
|
+
format: "metadata",
|
|
297
|
+
metadataHeaders: ["From", "To", "Cc", "Bcc", "Subject", "Date"]
|
|
298
|
+
});
|
|
299
|
+
const msg = res.data;
|
|
300
|
+
const headers = msg.payload?.headers ?? [];
|
|
301
|
+
const getHeader = (name) => headers.find((h) => h.name.toLowerCase() === name.toLowerCase())?.value ?? "";
|
|
302
|
+
return {
|
|
303
|
+
gmailId: msg.id,
|
|
304
|
+
threadId: msg.threadId,
|
|
305
|
+
account: this.config.account,
|
|
306
|
+
subject: getHeader("Subject"),
|
|
307
|
+
from: parseAddress(getHeader("From")),
|
|
308
|
+
to: parseAddressList(getHeader("To")),
|
|
309
|
+
cc: parseAddressList(getHeader("Cc")),
|
|
310
|
+
bcc: parseAddressList(getHeader("Bcc")),
|
|
311
|
+
date: new Date(getHeader("Date")).toISOString(),
|
|
312
|
+
snippet: msg.snippet ?? "",
|
|
313
|
+
labels: msg.labelIds ?? [],
|
|
314
|
+
isRead: !(msg.labelIds ?? []).includes("UNREAD")
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
function parseAddress(raw) {
|
|
319
|
+
const match = raw.match(/^(.+?)\s*<([^>]+)>$/);
|
|
320
|
+
if (match) {
|
|
321
|
+
return { name: match[1].replace(/^["']|["']$/g, "").trim(), email: match[2] };
|
|
322
|
+
}
|
|
323
|
+
return { email: raw.trim() };
|
|
324
|
+
}
|
|
325
|
+
function parseAddressList(raw) {
|
|
326
|
+
if (!raw.trim()) return [];
|
|
327
|
+
const results = [];
|
|
328
|
+
const parts = raw.split(/,(?=(?:[^<]*<[^>]*>)*[^>]*$)/);
|
|
329
|
+
for (const part of parts) {
|
|
330
|
+
const trimmed = part.trim();
|
|
331
|
+
if (trimmed) results.push(parseAddress(trimmed));
|
|
332
|
+
}
|
|
333
|
+
return results;
|
|
334
|
+
}
|
|
335
|
+
function formatAddress(addr) {
|
|
336
|
+
return addr.name ? `${addr.name} <${addr.email}>` : addr.email;
|
|
337
|
+
}
|
|
338
|
+
function errorMessage(err) {
|
|
339
|
+
return err instanceof Error ? err.message : String(err);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export {
|
|
343
|
+
createOAuth2Client,
|
|
344
|
+
getAuthUrl,
|
|
345
|
+
exchangeCode,
|
|
346
|
+
createServiceAccountClient,
|
|
347
|
+
loadTokens,
|
|
348
|
+
saveTokens,
|
|
349
|
+
refreshIfNeeded,
|
|
350
|
+
GoogleGmailConnector
|
|
351
|
+
};
|
package/dist/cli.js
CHANGED
|
@@ -3,13 +3,88 @@
|
|
|
3
3
|
// src/cli.ts
|
|
4
4
|
import * as readline from "readline";
|
|
5
5
|
import * as fs from "fs";
|
|
6
|
+
import { execSync } from "child_process";
|
|
7
|
+
|
|
8
|
+
// src/update-check.ts
|
|
9
|
+
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
|
|
10
|
+
import { join } from "path";
|
|
11
|
+
import { homedir } from "os";
|
|
12
|
+
var ONE_DAY_MS = 864e5;
|
|
13
|
+
function isNewer(latest, current) {
|
|
14
|
+
const a = latest.split(".").map(Number);
|
|
15
|
+
const b = current.split(".").map(Number);
|
|
16
|
+
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
|
17
|
+
const av = a[i] ?? 0;
|
|
18
|
+
const bv = b[i] ?? 0;
|
|
19
|
+
if (av > bv) return true;
|
|
20
|
+
if (av < bv) return false;
|
|
21
|
+
}
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
async function checkForUpdate(pkgName, currentVersion) {
|
|
25
|
+
const cacheDir = join(homedir(), `.${pkgName}`);
|
|
26
|
+
const cachePath = join(cacheDir, "update-check.json");
|
|
27
|
+
try {
|
|
28
|
+
if (existsSync(cachePath)) {
|
|
29
|
+
const cached = JSON.parse(readFileSync(cachePath, "utf-8"));
|
|
30
|
+
if (Date.now() - cached.checked < ONE_DAY_MS) {
|
|
31
|
+
return isNewer(cached.latest, currentVersion) ? cached.latest : null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
} catch {
|
|
35
|
+
}
|
|
36
|
+
const res = await fetch(`https://registry.npmjs.org/${pkgName}/latest`, {
|
|
37
|
+
headers: { accept: "application/json" },
|
|
38
|
+
signal: AbortSignal.timeout(5e3)
|
|
39
|
+
});
|
|
40
|
+
if (!res.ok) return null;
|
|
41
|
+
const data = await res.json();
|
|
42
|
+
const latest = data.version;
|
|
43
|
+
try {
|
|
44
|
+
if (!existsSync(cacheDir)) mkdirSync(cacheDir, { recursive: true });
|
|
45
|
+
writeFileSync(cachePath, JSON.stringify({ latest, checked: Date.now() }));
|
|
46
|
+
} catch {
|
|
47
|
+
}
|
|
48
|
+
return isNewer(latest, currentVersion) ? latest : null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// src/cli.ts
|
|
52
|
+
function getVersion() {
|
|
53
|
+
try {
|
|
54
|
+
const pkgPath = new URL("../package.json", import.meta.url).pathname;
|
|
55
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
56
|
+
return pkg.version;
|
|
57
|
+
} catch {
|
|
58
|
+
return "unknown";
|
|
59
|
+
}
|
|
60
|
+
}
|
|
6
61
|
async function main(args) {
|
|
7
62
|
const [command, subcommand, ...rest] = args;
|
|
8
|
-
|
|
63
|
+
const version = getVersion();
|
|
64
|
+
if (version !== "unknown") {
|
|
65
|
+
checkForUpdate("botinabox", version).then((latest) => {
|
|
66
|
+
if (latest) {
|
|
67
|
+
process.on("exit", () => {
|
|
68
|
+
console.log(
|
|
69
|
+
`
|
|
70
|
+
Update available: ${version} \u2192 ${latest} \u2014 run "botinabox update" to upgrade`
|
|
71
|
+
);
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}).catch(() => {
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
if (command === "update") {
|
|
78
|
+
await runUpdate(version);
|
|
79
|
+
} else if (command === "--version" || command === "-v") {
|
|
80
|
+
console.log(version);
|
|
81
|
+
} else if (command === "auth" && subcommand === "google") {
|
|
9
82
|
await authGoogle(rest);
|
|
10
83
|
} else {
|
|
11
84
|
console.log("Usage:");
|
|
12
85
|
console.log(" botinabox auth google <account-email> [options]");
|
|
86
|
+
console.log(" botinabox update Upgrade to the latest version");
|
|
87
|
+
console.log(" botinabox --version Print version");
|
|
13
88
|
console.log("");
|
|
14
89
|
console.log("Options:");
|
|
15
90
|
console.log(" --client-id=<id> Google OAuth client ID");
|
|
@@ -20,6 +95,22 @@ async function main(args) {
|
|
|
20
95
|
process.exit(1);
|
|
21
96
|
}
|
|
22
97
|
}
|
|
98
|
+
async function runUpdate(currentVersion) {
|
|
99
|
+
console.log(`Current version: ${currentVersion}`);
|
|
100
|
+
const latest = await checkForUpdate("botinabox", currentVersion);
|
|
101
|
+
if (!latest) {
|
|
102
|
+
console.log("Already up to date.");
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
console.log(`Updating to ${latest}...`);
|
|
106
|
+
try {
|
|
107
|
+
execSync("npm install -g botinabox@latest", { stdio: "inherit" });
|
|
108
|
+
console.log(`Updated botinabox ${currentVersion} \u2192 ${latest}`);
|
|
109
|
+
} catch {
|
|
110
|
+
console.error("Update failed. Try running manually: npm install -g botinabox@latest");
|
|
111
|
+
process.exit(1);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
23
114
|
async function authGoogle(args) {
|
|
24
115
|
const flags = /* @__PURE__ */ new Map();
|
|
25
116
|
let account;
|
|
@@ -87,7 +178,7 @@ async function authGoogle(args) {
|
|
|
87
178
|
});
|
|
88
179
|
}
|
|
89
180
|
};
|
|
90
|
-
const { GoogleGmailConnector } = await import("./gmail-connector-
|
|
181
|
+
const { GoogleGmailConnector } = await import("./gmail-connector-MNUBRNFM.js");
|
|
91
182
|
const connector = new GoogleGmailConnector({ tokenLoader, tokenSaver });
|
|
92
183
|
connector.config = {
|
|
93
184
|
account,
|
|
@@ -13,11 +13,26 @@ interface GoogleTokens {
|
|
|
13
13
|
expiry_date?: number;
|
|
14
14
|
token_type: string;
|
|
15
15
|
}
|
|
16
|
+
interface GoogleServiceAccountConfig {
|
|
17
|
+
/** Path to service account key JSON file */
|
|
18
|
+
keyFile?: string;
|
|
19
|
+
/** Inline service account credentials (alternative to keyFile) */
|
|
20
|
+
credentials?: {
|
|
21
|
+
client_email: string;
|
|
22
|
+
private_key: string;
|
|
23
|
+
project_id?: string;
|
|
24
|
+
};
|
|
25
|
+
/** Email of the user to impersonate via domain-wide delegation */
|
|
26
|
+
subject: string;
|
|
27
|
+
}
|
|
16
28
|
interface GoogleConnectorConfig extends ConnectorConfig {
|
|
17
29
|
/** Google account email */
|
|
18
30
|
account: string;
|
|
19
|
-
|
|
20
|
-
|
|
31
|
+
/** OAuth2 user auth (requires browser flow) */
|
|
32
|
+
oauth?: GoogleOAuthConfig;
|
|
33
|
+
/** Service account auth (headless, for cloud deployments) */
|
|
34
|
+
serviceAccount?: GoogleServiceAccountConfig;
|
|
35
|
+
scopes?: string[];
|
|
21
36
|
}
|
|
22
37
|
interface EmailAddress {
|
|
23
38
|
name?: string;
|
|
@@ -84,6 +99,11 @@ declare function getAuthUrl(client: OAuth2Client, scopes: string[]): string;
|
|
|
84
99
|
* Exchange an authorization code for tokens.
|
|
85
100
|
*/
|
|
86
101
|
declare function exchangeCode(client: OAuth2Client, code: string): Promise<GoogleTokens>;
|
|
102
|
+
/**
|
|
103
|
+
* Create an authenticated client using a service account with
|
|
104
|
+
* domain-wide delegation (impersonation). No browser flow needed.
|
|
105
|
+
*/
|
|
106
|
+
declare function createServiceAccountClient(config: GoogleServiceAccountConfig, scopes: string[]): Promise<OAuth2Client>;
|
|
87
107
|
/**
|
|
88
108
|
* Load persisted tokens via a generic getter callback.
|
|
89
109
|
*
|
|
@@ -115,21 +135,21 @@ declare function refreshIfNeeded(client: OAuth2Client, tokens: GoogleTokens, sav
|
|
|
115
135
|
*/
|
|
116
136
|
|
|
117
137
|
interface GmailConnectorOpts {
|
|
118
|
-
/** Load persisted tokens for a given account key. */
|
|
119
|
-
tokenLoader
|
|
120
|
-
/** Persist tokens for a given account key. */
|
|
121
|
-
tokenSaver
|
|
138
|
+
/** Load persisted tokens for a given account key (OAuth2 flow only). */
|
|
139
|
+
tokenLoader?: (key: string) => Promise<string | null>;
|
|
140
|
+
/** Persist tokens for a given account key (OAuth2 flow only). */
|
|
141
|
+
tokenSaver?: (key: string, value: string) => Promise<void>;
|
|
122
142
|
}
|
|
123
143
|
declare class GoogleGmailConnector implements Connector<EmailRecord> {
|
|
124
144
|
readonly id = "google-gmail";
|
|
125
145
|
readonly meta: ConnectorMeta;
|
|
126
|
-
private tokenLoader
|
|
127
|
-
private tokenSaver
|
|
146
|
+
private tokenLoader?;
|
|
147
|
+
private tokenSaver?;
|
|
128
148
|
private client;
|
|
129
149
|
private config;
|
|
130
150
|
private tokens;
|
|
131
151
|
private gmail;
|
|
132
|
-
constructor(opts
|
|
152
|
+
constructor(opts?: GmailConnectorOpts);
|
|
133
153
|
connect(config: GoogleConnectorConfig): Promise<void>;
|
|
134
154
|
disconnect(): Promise<void>;
|
|
135
155
|
healthCheck(): Promise<{
|
|
@@ -157,21 +177,21 @@ declare class GoogleGmailConnector implements Connector<EmailRecord> {
|
|
|
157
177
|
*/
|
|
158
178
|
|
|
159
179
|
interface CalendarConnectorOpts {
|
|
160
|
-
/** Load persisted tokens for a given account key. */
|
|
161
|
-
tokenLoader
|
|
162
|
-
/** Persist tokens for a given account key. */
|
|
163
|
-
tokenSaver
|
|
180
|
+
/** Load persisted tokens for a given account key (OAuth2 flow only). */
|
|
181
|
+
tokenLoader?: (key: string) => Promise<string | null>;
|
|
182
|
+
/** Persist tokens for a given account key (OAuth2 flow only). */
|
|
183
|
+
tokenSaver?: (key: string, value: string) => Promise<void>;
|
|
164
184
|
}
|
|
165
185
|
declare class GoogleCalendarConnector implements Connector<CalendarEventRecord> {
|
|
166
186
|
readonly id = "google-calendar";
|
|
167
187
|
readonly meta: ConnectorMeta;
|
|
168
|
-
private tokenLoader
|
|
169
|
-
private tokenSaver
|
|
188
|
+
private tokenLoader?;
|
|
189
|
+
private tokenSaver?;
|
|
170
190
|
private client;
|
|
171
191
|
private config;
|
|
172
192
|
private tokens;
|
|
173
193
|
private calendar;
|
|
174
|
-
constructor(opts
|
|
194
|
+
constructor(opts?: CalendarConnectorOpts);
|
|
175
195
|
connect(config: GoogleConnectorConfig): Promise<void>;
|
|
176
196
|
disconnect(): Promise<void>;
|
|
177
197
|
healthCheck(): Promise<{
|
|
@@ -189,4 +209,4 @@ declare class GoogleCalendarConnector implements Connector<CalendarEventRecord>
|
|
|
189
209
|
private mapEvent;
|
|
190
210
|
}
|
|
191
211
|
|
|
192
|
-
export { type CalendarAttendee, type CalendarConnectorOpts, type CalendarEventRecord, type EmailAddress, type EmailRecord, type GmailConnectorOpts, GoogleCalendarConnector, type GoogleConnectorConfig, GoogleGmailConnector, type GoogleOAuthConfig, type GoogleTokens, createOAuth2Client, exchangeCode, getAuthUrl, loadTokens, refreshIfNeeded, saveTokens };
|
|
212
|
+
export { type CalendarAttendee, type CalendarConnectorOpts, type CalendarEventRecord, type EmailAddress, type EmailRecord, type GmailConnectorOpts, GoogleCalendarConnector, type GoogleConnectorConfig, GoogleGmailConnector, type GoogleOAuthConfig, type GoogleServiceAccountConfig, type GoogleTokens, createOAuth2Client, createServiceAccountClient, exchangeCode, getAuthUrl, loadTokens, refreshIfNeeded, saveTokens };
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
2
|
GoogleGmailConnector,
|
|
3
3
|
createOAuth2Client,
|
|
4
|
+
createServiceAccountClient,
|
|
4
5
|
exchangeCode,
|
|
5
6
|
getAuthUrl,
|
|
6
7
|
loadTokens,
|
|
7
8
|
refreshIfNeeded,
|
|
8
9
|
saveTokens
|
|
9
|
-
} from "../../chunk-
|
|
10
|
+
} from "../../chunk-3X3YKI4T.js";
|
|
10
11
|
|
|
11
12
|
// src/connectors/google/calendar-connector.ts
|
|
12
13
|
var GoogleCalendarConnector = class {
|
|
@@ -23,26 +24,38 @@ var GoogleCalendarConnector = class {
|
|
|
23
24
|
tokens = null;
|
|
24
25
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
25
26
|
calendar = null;
|
|
26
|
-
constructor(opts) {
|
|
27
|
+
constructor(opts = {}) {
|
|
27
28
|
this.tokenLoader = opts.tokenLoader;
|
|
28
29
|
this.tokenSaver = opts.tokenSaver;
|
|
29
30
|
}
|
|
30
31
|
// ── Lifecycle ──────────────────────────────────────────────────
|
|
31
32
|
async connect(config) {
|
|
32
33
|
this.config = config;
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
34
|
+
const scopes = config.scopes ?? [
|
|
35
|
+
"https://www.googleapis.com/auth/calendar.readonly"
|
|
36
|
+
];
|
|
37
|
+
if (config.serviceAccount) {
|
|
38
|
+
this.client = await createServiceAccountClient(config.serviceAccount, scopes);
|
|
39
|
+
} else if (config.oauth) {
|
|
40
|
+
this.client = await createOAuth2Client(config.oauth);
|
|
41
|
+
if (!this.tokenLoader) {
|
|
42
|
+
throw new Error("tokenLoader required for OAuth2 flow");
|
|
43
|
+
}
|
|
44
|
+
this.tokens = await loadTokens(this.tokenLoader, config.account);
|
|
45
|
+
if (!this.tokens) {
|
|
46
|
+
throw new Error(
|
|
47
|
+
`No stored tokens for account ${config.account}. Complete the OAuth flow first.`
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
this.tokens = await refreshIfNeeded(
|
|
51
|
+
this.client,
|
|
52
|
+
this.tokens,
|
|
53
|
+
this.tokenSaver ? async (t) => saveTokens(this.tokenSaver, config.account, t) : void 0
|
|
38
54
|
);
|
|
55
|
+
this.client.setCredentials(this.tokens);
|
|
56
|
+
} else {
|
|
57
|
+
throw new Error("Either serviceAccount or oauth config is required");
|
|
39
58
|
}
|
|
40
|
-
this.tokens = await refreshIfNeeded(
|
|
41
|
-
this.client,
|
|
42
|
-
this.tokens,
|
|
43
|
-
async (t) => saveTokens(this.tokenSaver, config.account, t)
|
|
44
|
-
);
|
|
45
|
-
this.client.setCredentials(this.tokens);
|
|
46
59
|
const { google } = await import("googleapis");
|
|
47
60
|
this.calendar = google.calendar({ version: "v3", auth: this.client });
|
|
48
61
|
}
|
|
@@ -71,6 +84,12 @@ var GoogleCalendarConnector = class {
|
|
|
71
84
|
return { success: false, error: "Call connect() first to set config, or pass config and call authenticate() before connect()." };
|
|
72
85
|
}
|
|
73
86
|
try {
|
|
87
|
+
if (!this.config.oauth) {
|
|
88
|
+
return { success: false, error: "OAuth config required for browser-based authenticate(). Use serviceAccount for headless auth." };
|
|
89
|
+
}
|
|
90
|
+
if (!this.tokenSaver) {
|
|
91
|
+
return { success: false, error: "tokenSaver required for authenticate() flow." };
|
|
92
|
+
}
|
|
74
93
|
const client = await createOAuth2Client(this.config.oauth);
|
|
75
94
|
const scopes = this.config.scopes ?? [
|
|
76
95
|
"https://www.googleapis.com/auth/calendar.readonly"
|
|
@@ -219,6 +238,7 @@ export {
|
|
|
219
238
|
GoogleCalendarConnector,
|
|
220
239
|
GoogleGmailConnector,
|
|
221
240
|
createOAuth2Client,
|
|
241
|
+
createServiceAccountClient,
|
|
222
242
|
exchangeCode,
|
|
223
243
|
getAuthUrl,
|
|
224
244
|
loadTokens,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "botinabox",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.3",
|
|
4
4
|
"description": "Bot in a Box — framework for building multi-agent bots",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -42,10 +42,18 @@
|
|
|
42
42
|
"bin": {
|
|
43
43
|
"botinabox": "./bin/botinabox.mjs"
|
|
44
44
|
},
|
|
45
|
+
"files": [
|
|
46
|
+
"dist",
|
|
47
|
+
"bin"
|
|
48
|
+
],
|
|
49
|
+
"engines": {
|
|
50
|
+
"node": ">=18"
|
|
51
|
+
},
|
|
45
52
|
"scripts": {
|
|
46
53
|
"build": "tsup",
|
|
47
54
|
"test": "vitest run",
|
|
48
|
-
"typecheck": "tsc --noEmit"
|
|
55
|
+
"typecheck": "tsc --noEmit",
|
|
56
|
+
"prepublishOnly": "npm run build && npm run typecheck && npm test"
|
|
49
57
|
},
|
|
50
58
|
"dependencies": {
|
|
51
59
|
"@types/uuid": "^10.0.0",
|
package/CHANGELOG.md
DELETED
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
# Changelog
|
|
2
|
-
|
|
3
|
-
All notable changes to `botinabox` are documented here.
|
|
4
|
-
|
|
5
|
-
Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versioning: [SemVer](https://semver.org/).
|
|
6
|
-
|
|
7
|
-
---
|
|
8
|
-
|
|
9
|
-
## [0.5.2] — 2026-04-04
|
|
10
|
-
|
|
11
|
-
### Added
|
|
12
|
-
|
|
13
|
-
- **`authenticate()` method on Connector interface** — optional method for connectors that require OAuth or other auth flows. Accepts a `codeProvider` callback for interactive or programmatic authorization.
|
|
14
|
-
- **Google connectors implement `authenticate()`** — `GoogleGmailConnector` and `GoogleCalendarConnector` now support self-authentication: generate consent URL, exchange code for tokens, persist via tokenSaver callback.
|
|
15
|
-
- **`botinabox auth google` CLI** — native CLI command for Google OAuth setup: `botinabox auth google <account-email> --client-id=... --client-secret=...`. Stores tokens in the secrets table.
|
|
16
|
-
|
|
17
|
-
## [0.5.1] — 2026-04-04
|
|
18
|
-
|
|
19
|
-
### Fixed
|
|
20
|
-
|
|
21
|
-
- **cron-parser ESM import** — cron-parser v4 is CommonJS-only; fixed named import to default import (`import cronParser from "cron-parser"`).
|
|
22
|
-
|
|
23
|
-
## [0.5.0] — 2026-04-04
|
|
24
|
-
|
|
25
|
-
### Added
|
|
26
|
-
|
|
27
|
-
- **Connector interface** — Generic `Connector<T>` abstraction for external service integrations (Gmail, Calendar, Trello, Jira, Salesforce, etc.). Pull-based `sync()` returns typed records; optional `push()` writes back. Connectors produce data — consumers decide where to store it. New `connectors` config key in `BotConfig`.
|
|
28
|
-
- **Google connectors** — `GoogleGmailConnector` and `GoogleCalendarConnector` implementing `Connector<EmailRecord>` and `Connector<CalendarEventRecord>`. Incremental sync (Gmail historyId, Calendar syncToken), full sync with pagination, email sending via `push()`. OAuth2 helpers with callback-based token persistence. Exported from `botinabox/google`. `googleapis` as optional peer dependency.
|
|
29
|
-
- **Scheduler** — Database-backed `Scheduler` class with `schedules` core table. Supports recurring (cron expressions via `cron-parser`) and one-time schedules. Hook-based actions: when a schedule fires, it emits the configured action as a hook event. Methods: `register()`, `update()`, `unregister()`, `list()`, `tick()`.
|
|
30
|
-
- **`schedules` core table** — id, name, type (recurring/one_time), cron, run_at, timezone, enabled, action, action_config, last_fired_at, next_fire_at.
|
|
31
|
-
|
|
32
|
-
### Deprecated
|
|
33
|
-
|
|
34
|
-
- **HeartbeatScheduler** — Replaced by `Scheduler`. HeartbeatScheduler uses in-memory `setInterval` which loses state on restart. Kept for backward compatibility but marked `@deprecated`.
|
|
35
|
-
|
|
36
|
-
### Dependencies
|
|
37
|
-
|
|
38
|
-
- Added `cron-parser` ^4.9.0.
|
|
39
|
-
- Added `googleapis` >=140.0.0 as optional peer dependency.
|
|
40
|
-
|
|
41
|
-
## [0.3.0] — 2026-04-03
|
|
42
|
-
|
|
43
|
-
### Added
|
|
44
|
-
|
|
45
|
-
- **Domain tables** — `defineDomainTables(db, options?)` creates standard multi-agent app tables: org, project, client, invoice, repository, file, channel, rule, event + junction tables. Configurable: disable clients, repos, files, channels, rules, or events.
|
|
46
|
-
- **Domain entity contexts** — `defineDomainEntityContexts(db, options?)` renders per-entity context directories for all domain tables. Projects get REPOS.md + RULES.md. Clients get REPOS.md + AGENTS.md + INVOICES.md.
|
|
47
|
-
- **Claude stream parser** — `parseClaudeStream(stdout)` parses Claude CLI NDJSON output into structured results (session, model, cost, tokens, text, errors). Plus `isMaxTurns()`, `isLoginRequired()`, `deactivateLocalImagePaths()`.
|
|
48
|
-
- **Process env builder** — `buildProcessEnv(allowedKeys?, inject?)` creates a clean subprocess environment with only safe variables. Strips all secrets.
|
|
49
|
-
|
|
50
|
-
## [0.2.0] — 2026-04-03
|
|
51
|
-
|
|
52
|
-
### Added
|
|
53
|
-
|
|
54
|
-
- **Users primitive** — `users` and `user_identities` core tables. Users are protected objects (never auto-rendered into other entities' context). `UserRegistry` class: `register()`, `getById()`, `getByEmail()`, `resolveByIdentity()`, `resolveOrCreate()`, `addIdentity()`.
|
|
55
|
-
- **Secrets primitive** — `secrets` core table for encrypted credential storage. Protected by default. `SecretStore` class: `set()`, `get()`, `getMeta()`, `list()`, `rotate()`, `delete()`.
|
|
56
|
-
- **Message pipeline user resolution** — `MessagePipeline` accepts optional `UserRegistry`. When provided, resolves `InboundMessage.from` to a user ID via `resolveOrCreate()` before task creation. `InboundMessage.userId` field added.
|
|
57
|
-
- **`user_id` on messages table** — Tracks resolved user alongside raw `peer_id`.
|
|
58
|
-
- **Protected/encrypted passthrough** — `EntityContextDef` now supports `protected` and `encrypted` fields, passed through to Lattice's entity context system.
|
|
59
|
-
|
|
60
|
-
### Changed
|
|
61
|
-
|
|
62
|
-
- Core table count: 15 → 18 (added `users`, `user_identities`, `secrets`).
|
|
63
|
-
- `messages` table gains `user_id` column.
|
|
64
|
-
|
|
65
|
-
## [0.1.1] — 2026-03-28
|
|
66
|
-
|
|
67
|
-
### Fixed
|
|
68
|
-
|
|
69
|
-
- Initial release bug fixes and stability improvements.
|
|
70
|
-
|
|
71
|
-
## [0.1.0] — 2026-03-25
|
|
72
|
-
|
|
73
|
-
### Added
|
|
74
|
-
|
|
75
|
-
- Initial release: DataStore, HookBus, AgentRegistry, TaskQueue, RunManager, WakeupQueue, BudgetController, WorkflowEngine, SessionManager, ChannelRegistry, MessagePipeline.
|
|
76
|
-
- 15 core tables, LLM provider routing, channel adapters (Slack, Discord, Webhook).
|
package/CONTRIBUTING.md
DELETED
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
# Contributing
|
|
2
|
-
|
|
3
|
-
Thanks for your interest in contributing to Bot in a Box.
|
|
4
|
-
|
|
5
|
-
## Development Setup
|
|
6
|
-
|
|
7
|
-
```bash
|
|
8
|
-
git clone https://github.com/automated-industries/botinabox.git
|
|
9
|
-
cd botinabox
|
|
10
|
-
pnpm install
|
|
11
|
-
pnpm build
|
|
12
|
-
```
|
|
13
|
-
|
|
14
|
-
## Project Structure
|
|
15
|
-
|
|
16
|
-
This is a pnpm monorepo. Packages are in `packages/`:
|
|
17
|
-
|
|
18
|
-
- `shared/` — Types and constants (zero dependencies)
|
|
19
|
-
- `core/` — Core framework
|
|
20
|
-
- `cli/` — CLI scaffolding tool
|
|
21
|
-
- `providers/` — LLM provider adapters
|
|
22
|
-
- `channels/` — Messaging channel adapters
|
|
23
|
-
|
|
24
|
-
## Running Tests
|
|
25
|
-
|
|
26
|
-
```bash
|
|
27
|
-
# All packages
|
|
28
|
-
pnpm test:run
|
|
29
|
-
|
|
30
|
-
# Single package
|
|
31
|
-
cd packages/core && pnpm test
|
|
32
|
-
```
|
|
33
|
-
|
|
34
|
-
Tests use [Vitest](https://vitest.dev/). Each package has its own `vitest.config.ts`.
|
|
35
|
-
|
|
36
|
-
## Building
|
|
37
|
-
|
|
38
|
-
```bash
|
|
39
|
-
# All packages
|
|
40
|
-
pnpm build
|
|
41
|
-
|
|
42
|
-
# Single package
|
|
43
|
-
cd packages/core && pnpm build
|
|
44
|
-
```
|
|
45
|
-
|
|
46
|
-
Build uses [tsup](https://tsup.egoist.dev/) targeting ESM with declaration files.
|
|
47
|
-
|
|
48
|
-
## Type Checking
|
|
49
|
-
|
|
50
|
-
```bash
|
|
51
|
-
pnpm typecheck
|
|
52
|
-
```
|
|
53
|
-
|
|
54
|
-
## Code Style
|
|
55
|
-
|
|
56
|
-
- TypeScript with strict mode
|
|
57
|
-
- ESM modules (`"type": "module"`)
|
|
58
|
-
- ES2022 target
|
|
59
|
-
- No default exports except for provider/channel factory functions
|
|
60
|
-
|
|
61
|
-
## Making Changes
|
|
62
|
-
|
|
63
|
-
1. Create a branch from `main`
|
|
64
|
-
2. Make your changes
|
|
65
|
-
3. Add or update tests
|
|
66
|
-
4. Run `pnpm test:run` and `pnpm typecheck`
|
|
67
|
-
5. Open a pull request
|
|
68
|
-
|
|
69
|
-
## Adding a Provider
|
|
70
|
-
|
|
71
|
-
1. Create `packages/providers/your-provider/`
|
|
72
|
-
2. Implement the `LLMProvider` interface from `@botinabox/shared`
|
|
73
|
-
3. Export a default factory function
|
|
74
|
-
4. Add `"botinabox": { "type": "provider" }` to `package.json`
|
|
75
|
-
5. Add tests
|
|
76
|
-
|
|
77
|
-
## Adding a Channel Adapter
|
|
78
|
-
|
|
79
|
-
1. Create `packages/channels/your-channel/`
|
|
80
|
-
2. Implement the `ChannelAdapter` interface from `@botinabox/shared`
|
|
81
|
-
3. Export a default factory function
|
|
82
|
-
4. Add `"botinabox": { "type": "channel" }` to `package.json`
|
|
83
|
-
5. Add tests
|
|
84
|
-
|
|
85
|
-
## Reporting Issues
|
|
86
|
-
|
|
87
|
-
Open an issue on GitHub with:
|
|
88
|
-
|
|
89
|
-
- Steps to reproduce
|
|
90
|
-
- Expected behavior
|
|
91
|
-
- Actual behavior
|
|
92
|
-
- Node.js and pnpm versions
|