@corsair-dev/cli 0.1.7 → 0.1.9

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.
Files changed (40) hide show
  1. package/dist/auth.d.ts.map +1 -1
  2. package/dist/google/calendar.d.ts +2 -0
  3. package/dist/google/calendar.d.ts.map +1 -0
  4. package/dist/google/drive.d.ts +2 -0
  5. package/dist/google/drive.d.ts.map +1 -0
  6. package/dist/google/gmail.d.ts +2 -0
  7. package/dist/google/gmail.d.ts.map +1 -0
  8. package/dist/google/index.d.ts +5 -0
  9. package/dist/google/index.d.ts.map +1 -0
  10. package/dist/google/shared.d.ts +3 -0
  11. package/dist/google/shared.d.ts.map +1 -0
  12. package/dist/google/sheets.d.ts +2 -0
  13. package/dist/google/sheets.d.ts.map +1 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1724 -67
  16. package/dist/microsoft/credentials.d.ts +15 -0
  17. package/dist/microsoft/credentials.d.ts.map +1 -0
  18. package/dist/microsoft/graph.d.ts +6 -0
  19. package/dist/microsoft/graph.d.ts.map +1 -0
  20. package/dist/microsoft/onedrive.d.ts +4 -0
  21. package/dist/microsoft/onedrive.d.ts.map +1 -0
  22. package/dist/microsoft/outlook.d.ts +4 -0
  23. package/dist/microsoft/outlook.d.ts.map +1 -0
  24. package/dist/microsoft/sharepoint.d.ts +4 -0
  25. package/dist/microsoft/sharepoint.d.ts.map +1 -0
  26. package/dist/microsoft/teams.d.ts +4 -0
  27. package/dist/microsoft/teams.d.ts.map +1 -0
  28. package/dist/subscribe-google.d.ts +2 -0
  29. package/dist/subscribe-google.d.ts.map +1 -0
  30. package/dist/subscribe-microsoft.d.ts +5 -0
  31. package/dist/subscribe-microsoft.d.ts.map +1 -0
  32. package/dist/utils/corsair.d.ts +3 -0
  33. package/dist/utils/corsair.d.ts.map +1 -0
  34. package/dist/utils/load-config.d.ts +6 -0
  35. package/dist/utils/load-config.d.ts.map +1 -0
  36. package/dist/utils/prompts.d.ts +4 -0
  37. package/dist/utils/prompts.d.ts.map +1 -0
  38. package/package.json +2 -2
  39. package/dist/watch-renew.d.ts +0 -4
  40. package/dist/watch-renew.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -26,8 +26,8 @@ function getTsconfigInfo(cwd, flatPath) {
26
26
  tsConfigPath = cwd ? path.join(cwd, "tsconfig.json") : path.join("tsconfig.json");
27
27
  }
28
28
  try {
29
- const text = fs.readFileSync(tsConfigPath, "utf-8");
30
- return JSON.parse(stripJsonComments(text));
29
+ const text6 = fs.readFileSync(tsConfigPath, "utf-8");
30
+ return JSON.parse(stripJsonComments(text6));
31
31
  } catch (error) {
32
32
  throw error;
33
33
  }
@@ -38,6 +38,1482 @@ var init_get_tsconfig_info = __esm({
38
38
  }
39
39
  });
40
40
 
41
+ // utils/corsair.ts
42
+ import { CORSAIR_INTERNAL } from "corsair/core";
43
+ async function extractInternalConfig(cwd) {
44
+ const instance = await getCorsairInstance({ cwd, shouldThrowOnError: true });
45
+ const internal = instance[CORSAIR_INTERNAL];
46
+ if (!internal) {
47
+ throw new Error(
48
+ "Could not read internal config from Corsair instance. Make sure you are using the latest version of corsair."
49
+ );
50
+ }
51
+ return internal;
52
+ }
53
+ var init_corsair = __esm({
54
+ "utils/corsair.ts"() {
55
+ "use strict";
56
+ init_index();
57
+ }
58
+ });
59
+
60
+ // utils/load-config.ts
61
+ import * as p from "@clack/prompts";
62
+ async function loadInternalConfig(cwd, title, pluginId, pluginLabel) {
63
+ p.intro(title);
64
+ const spin = p.spinner();
65
+ spin.start("Loading corsair instance...");
66
+ let internal;
67
+ try {
68
+ internal = await extractInternalConfig(cwd);
69
+ } catch (error) {
70
+ spin.stop("Failed to load.");
71
+ p.log.error(error instanceof Error ? error.message : String(error));
72
+ p.outro("");
73
+ process.exit(1);
74
+ }
75
+ const { plugins, database } = internal;
76
+ if (!database) {
77
+ spin.stop("Failed.");
78
+ p.log.error("No database adapter configured.");
79
+ p.outro("");
80
+ process.exit(1);
81
+ }
82
+ const plugin = plugins.find((pl) => pl.id === pluginId);
83
+ if (!plugin) {
84
+ spin.stop(`${pluginLabel} plugin not found.`);
85
+ p.log.error(`Add the ${pluginId} plugin to your corsair instance first.`);
86
+ p.outro("");
87
+ process.exit(1);
88
+ }
89
+ spin.stop("Loaded.");
90
+ return { internal, plugin };
91
+ }
92
+ var init_load_config = __esm({
93
+ "utils/load-config.ts"() {
94
+ "use strict";
95
+ init_corsair();
96
+ }
97
+ });
98
+
99
+ // utils/prompts.ts
100
+ import * as crypto from "crypto";
101
+ import * as p2 from "@clack/prompts";
102
+ async function promptTenantId() {
103
+ const tenantId = await p2.text({
104
+ message: "Enter tenant ID:",
105
+ defaultValue: "default",
106
+ placeholder: "default"
107
+ });
108
+ if (p2.isCancel(tenantId)) {
109
+ p2.cancel("Operation cancelled.");
110
+ process.exit(0);
111
+ }
112
+ return tenantId;
113
+ }
114
+ async function promptWebhookUrl() {
115
+ const webhookUrl = await p2.text({
116
+ message: "Enter your public webhook URL (ngrok or production):",
117
+ placeholder: "https://abc123.ngrok-free.app/api/webhook",
118
+ validate: (v) => {
119
+ if (!v || v.trim().length === 0) return "Webhook URL is required";
120
+ if (!v.startsWith("https://"))
121
+ return "URL must start with https:// (Microsoft Graph requires HTTPS)";
122
+ }
123
+ });
124
+ if (p2.isCancel(webhookUrl)) {
125
+ p2.cancel("Operation cancelled.");
126
+ process.exit(0);
127
+ }
128
+ return webhookUrl;
129
+ }
130
+ async function promptClientState() {
131
+ const autoSecret = crypto.randomBytes(16).toString("hex");
132
+ const clientState = await p2.text({
133
+ message: "Enter a clientState secret (used to verify webhook payloads):",
134
+ defaultValue: autoSecret,
135
+ placeholder: autoSecret
136
+ });
137
+ if (p2.isCancel(clientState)) {
138
+ p2.cancel("Operation cancelled.");
139
+ process.exit(0);
140
+ }
141
+ return clientState;
142
+ }
143
+ var init_prompts = __esm({
144
+ "utils/prompts.ts"() {
145
+ "use strict";
146
+ }
147
+ });
148
+
149
+ // microsoft/credentials.ts
150
+ import * as p3 from "@clack/prompts";
151
+ import { createAccountKeyManager, createIntegrationKeyManager } from "corsair/core";
152
+ async function refreshMicrosoftToken(clientId, clientSecret, refreshToken) {
153
+ const response = await fetch(MICROSOFT_TOKEN_URL, {
154
+ method: "POST",
155
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
156
+ body: new URLSearchParams({
157
+ client_id: clientId,
158
+ client_secret: clientSecret,
159
+ refresh_token: refreshToken,
160
+ grant_type: "refresh_token"
161
+ })
162
+ });
163
+ if (!response.ok) {
164
+ const error = await response.text();
165
+ throw new Error(`Token refresh failed: ${error}`);
166
+ }
167
+ return response.json();
168
+ }
169
+ async function resolveAccessToken(integrationName, tenantId, internal) {
170
+ const { kek, database } = internal;
171
+ const credSpin = p3.spinner();
172
+ credSpin.start(`Fetching ${integrationName} credentials...`);
173
+ const integrationKm = createIntegrationKeyManager({
174
+ authType: "oauth_2",
175
+ integrationName,
176
+ kek,
177
+ database
178
+ });
179
+ const accountKm = createAccountKeyManager({
180
+ authType: "oauth_2",
181
+ integrationName,
182
+ tenantId,
183
+ kek,
184
+ database
185
+ });
186
+ const [clientId, clientSecret, storedAccessToken, expiresAt, storedRefreshToken] = await Promise.all([
187
+ integrationKm.get_client_id(),
188
+ integrationKm.get_client_secret(),
189
+ accountKm.get_access_token(),
190
+ accountKm.get_expires_at(),
191
+ accountKm.get_refresh_token()
192
+ ]);
193
+ if (!storedRefreshToken) {
194
+ credSpin.stop("Missing credentials.");
195
+ p3.log.error(
196
+ `No refresh token found. Run: pnpm corsair auth --plugin=${integrationName}`
197
+ );
198
+ p3.outro("");
199
+ process.exit(1);
200
+ }
201
+ if (!clientId || !clientSecret) {
202
+ credSpin.stop("Missing credentials.");
203
+ p3.log.error(
204
+ `Client ID/Secret not configured. Run: pnpm corsair setup --${integrationName}`
205
+ );
206
+ p3.outro("");
207
+ process.exit(1);
208
+ }
209
+ let accessToken = storedAccessToken;
210
+ const now = Math.floor(Date.now() / 1e3);
211
+ const needsRefresh = !accessToken || !expiresAt || Number(expiresAt) <= now + 5 * 60;
212
+ if (needsRefresh) {
213
+ credSpin.message("Refreshing access token...");
214
+ try {
215
+ const tokenData = await refreshMicrosoftToken(
216
+ clientId,
217
+ clientSecret,
218
+ storedRefreshToken
219
+ );
220
+ accessToken = tokenData.access_token;
221
+ await accountKm.set_access_token(tokenData.access_token);
222
+ await accountKm.set_expires_at(String(now + tokenData.expires_in));
223
+ if (tokenData.refresh_token) {
224
+ await accountKm.set_refresh_token(tokenData.refresh_token);
225
+ }
226
+ } catch (error) {
227
+ credSpin.stop("Failed.");
228
+ p3.log.error(error instanceof Error ? error.message : String(error));
229
+ p3.outro("");
230
+ process.exit(1);
231
+ }
232
+ }
233
+ if (!accessToken) {
234
+ credSpin.stop("Missing credentials.");
235
+ p3.log.error(
236
+ `Could not obtain a valid access token. Run: pnpm corsair auth --plugin=${integrationName}`
237
+ );
238
+ p3.outro("");
239
+ process.exit(1);
240
+ }
241
+ credSpin.stop("Credentials loaded.");
242
+ return { accessToken, accountKm };
243
+ }
244
+ async function saveWebhookSignature(accountKm, clientState) {
245
+ const saveSpin = p3.spinner();
246
+ saveSpin.start("Saving webhook secret...");
247
+ await accountKm.set_webhook_signature(clientState);
248
+ saveSpin.stop("Webhook secret saved.");
249
+ }
250
+ var MICROSOFT_TOKEN_URL;
251
+ var init_credentials = __esm({
252
+ "microsoft/credentials.ts"() {
253
+ "use strict";
254
+ MICROSOFT_TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
255
+ }
256
+ });
257
+
258
+ // microsoft/graph.ts
259
+ async function createGraphSubscription(accessToken, notificationUrl, resource, changeType, clientState, expiryMinutes) {
260
+ const expirationDateTime = new Date(
261
+ Date.now() + expiryMinutes * 60 * 1e3
262
+ ).toISOString();
263
+ const response = await fetch(`${GRAPH_API_BASE}/subscriptions`, {
264
+ method: "POST",
265
+ headers: {
266
+ Authorization: `Bearer ${accessToken}`,
267
+ "Content-Type": "application/json"
268
+ },
269
+ body: JSON.stringify({
270
+ changeType,
271
+ notificationUrl,
272
+ resource,
273
+ expirationDateTime,
274
+ clientState
275
+ })
276
+ });
277
+ if (!response.ok) {
278
+ const error = await response.text();
279
+ throw new Error(`Graph subscription failed: ${error}`);
280
+ }
281
+ return response.json();
282
+ }
283
+ var GRAPH_API_BASE;
284
+ var init_graph = __esm({
285
+ "microsoft/graph.ts"() {
286
+ "use strict";
287
+ GRAPH_API_BASE = "https://graph.microsoft.com/v1.0";
288
+ }
289
+ });
290
+
291
+ // microsoft/outlook.ts
292
+ import * as p4 from "@clack/prompts";
293
+ async function runOutlookSubscribe({ cwd }) {
294
+ const { internal } = await loadInternalConfig(
295
+ cwd,
296
+ "Corsair \u2014 Outlook Webhook Subscribe",
297
+ "outlook",
298
+ "Outlook"
299
+ );
300
+ const tenantId = await promptTenantId();
301
+ const { accessToken, accountKm } = await resolveAccessToken(
302
+ "outlook",
303
+ tenantId,
304
+ internal
305
+ );
306
+ const webhookUrl = await promptWebhookUrl();
307
+ const selected = await p4.multiselect({
308
+ message: "Select resources to subscribe to:",
309
+ options: Object.entries(OUTLOOK_RESOURCES).map(([value, cfg]) => ({
310
+ value,
311
+ label: cfg.label,
312
+ hint: `${cfg.resource} [${cfg.changeType}]`
313
+ })),
314
+ required: true
315
+ });
316
+ if (p4.isCancel(selected)) {
317
+ p4.cancel("Operation cancelled.");
318
+ process.exit(0);
319
+ }
320
+ const clientState = await promptClientState();
321
+ const results = [];
322
+ let hasError = false;
323
+ for (const value of selected) {
324
+ const cfg = OUTLOOK_RESOURCES[value];
325
+ const subSpin = p4.spinner();
326
+ subSpin.start(`Creating subscription: ${cfg.label}...`);
327
+ try {
328
+ const subscription = await createGraphSubscription(
329
+ accessToken,
330
+ webhookUrl,
331
+ cfg.resource,
332
+ cfg.changeType,
333
+ clientState,
334
+ cfg.expiryMinutes
335
+ );
336
+ subSpin.stop(`Created: ${cfg.label}`);
337
+ results.push(
338
+ `${cfg.label}
339
+ ID: ${subscription.id}
340
+ Expires: ${subscription.expirationDateTime}`
341
+ );
342
+ } catch (error) {
343
+ subSpin.stop(`Failed: ${cfg.label}`);
344
+ p4.log.error(error instanceof Error ? error.message : String(error));
345
+ hasError = true;
346
+ }
347
+ }
348
+ if (results.length > 0) {
349
+ p4.note(results.join("\n\n"), "Subscriptions created");
350
+ }
351
+ await saveWebhookSignature(accountKm, clientState);
352
+ if (!hasError) {
353
+ p4.log.success("Outlook webhook subscriptions set up successfully.");
354
+ } else {
355
+ p4.log.warn("Some subscriptions failed. Check errors above.");
356
+ }
357
+ p4.note(
358
+ `ClientState: ${clientState}
359
+ Webhook URL: ${webhookUrl}
360
+
361
+ Note: Outlook subscriptions expire. Re-run this command to renew.`,
362
+ "Setup complete"
363
+ );
364
+ p4.outro("Done!");
365
+ }
366
+ var OUTLOOK_RESOURCES;
367
+ var init_outlook = __esm({
368
+ "microsoft/outlook.ts"() {
369
+ "use strict";
370
+ init_load_config();
371
+ init_prompts();
372
+ init_credentials();
373
+ init_graph();
374
+ OUTLOOK_RESOURCES = {
375
+ inboxMessages: {
376
+ resource: "me/mailFolders/inbox/messages",
377
+ changeType: "created",
378
+ label: "Inbox Messages \u2014 new messages received",
379
+ expiryMinutes: 4320
380
+ // 3 days (max for mail)
381
+ },
382
+ sentMessages: {
383
+ resource: "me/mailFolders/sentItems/messages",
384
+ changeType: "created",
385
+ label: "Sent Items \u2014 messages sent",
386
+ expiryMinutes: 4320
387
+ },
388
+ newEvents: {
389
+ resource: "me/events",
390
+ changeType: "created",
391
+ label: "Calendar Events \u2014 new events created",
392
+ expiryMinutes: 4230
393
+ // max for calendar
394
+ },
395
+ eventChanges: {
396
+ resource: "me/events",
397
+ changeType: "updated,deleted",
398
+ label: "Calendar Events \u2014 updates & deletions",
399
+ expiryMinutes: 4230
400
+ },
401
+ newContacts: {
402
+ resource: "me/contacts",
403
+ changeType: "created",
404
+ label: "Contacts \u2014 new contacts created",
405
+ expiryMinutes: 4230
406
+ // max for contacts
407
+ }
408
+ };
409
+ }
410
+ });
411
+
412
+ // microsoft/sharepoint.ts
413
+ import * as p5 from "@clack/prompts";
414
+ function buildSiteUrl(siteId, subpath) {
415
+ const isHostnamePath = siteId.includes(":") && !siteId.includes(",");
416
+ return isHostnamePath ? `${GRAPH_API_BASE}/sites/${siteId}:/${subpath}` : `${GRAPH_API_BASE}/sites/${siteId}/${subpath}`;
417
+ }
418
+ async function fetchSiteLists(accessToken, siteId) {
419
+ const response = await fetch(
420
+ `${buildSiteUrl(siteId, "lists")}?$select=id,displayName,webUrl`,
421
+ { headers: { Authorization: `Bearer ${accessToken}` } }
422
+ );
423
+ if (!response.ok) {
424
+ const error = await response.text();
425
+ throw new Error(`Failed to fetch site lists: ${error}`);
426
+ }
427
+ const data = await response.json();
428
+ return data.value ?? [];
429
+ }
430
+ async function createSharepointSubscription(accessToken, siteId, listId, notificationUrl, clientState, expiryDays) {
431
+ const expirationDateTime = new Date(
432
+ Date.now() + expiryDays * 24 * 60 * 60 * 1e3
433
+ ).toISOString();
434
+ const response = await fetch(
435
+ buildSiteUrl(siteId, `lists/${encodeURIComponent(listId)}/subscriptions`),
436
+ {
437
+ method: "POST",
438
+ headers: {
439
+ Authorization: `Bearer ${accessToken}`,
440
+ "Content-Type": "application/json"
441
+ },
442
+ body: JSON.stringify({ notificationUrl, expirationDateTime, clientState })
443
+ }
444
+ );
445
+ if (!response.ok) {
446
+ const error = await response.text();
447
+ throw new Error(`SharePoint subscription failed: ${error}`);
448
+ }
449
+ return response.json();
450
+ }
451
+ async function runSharepointSubscribe({ cwd }) {
452
+ const { internal, plugin: sharepointPlugin } = await loadInternalConfig(
453
+ cwd,
454
+ "Corsair \u2014 SharePoint Webhook Subscribe",
455
+ "sharepoint",
456
+ "SharePoint"
457
+ );
458
+ const tenantId = await promptTenantId();
459
+ const { accessToken, accountKm } = await resolveAccessToken(
460
+ "sharepoint",
461
+ tenantId,
462
+ internal
463
+ );
464
+ const webhookUrl = await promptWebhookUrl();
465
+ const pluginOptions = sharepointPlugin.options;
466
+ const defaultSiteId = pluginOptions?.siteId ?? "";
467
+ const siteId = await p5.text({
468
+ message: "Enter SharePoint site ID:",
469
+ defaultValue: defaultSiteId,
470
+ placeholder: "corsairdev.sharepoint.com:/sites/MySite or tenant.sharepoint.com,siteGuid,webGuid",
471
+ validate: (v) => {
472
+ if (!v || v.trim().length === 0) return "Site ID is required";
473
+ }
474
+ });
475
+ if (p5.isCancel(siteId)) {
476
+ p5.cancel("Operation cancelled.");
477
+ process.exit(0);
478
+ }
479
+ const listSpin = p5.spinner();
480
+ listSpin.start("Fetching lists from site...");
481
+ let siteLists = [];
482
+ try {
483
+ siteLists = await fetchSiteLists(accessToken, siteId);
484
+ listSpin.stop(
485
+ `Found ${siteLists.length} list${siteLists.length === 1 ? "" : "s"}.`
486
+ );
487
+ } catch (error) {
488
+ listSpin.stop("Could not fetch lists.");
489
+ p5.log.warn(error instanceof Error ? error.message : String(error));
490
+ }
491
+ let listId;
492
+ if (siteLists.length > 0) {
493
+ const picked = await p5.select({
494
+ message: "Select a list to subscribe to:",
495
+ options: siteLists.map((l) => ({
496
+ value: l.id,
497
+ label: l.displayName,
498
+ hint: l.id
499
+ }))
500
+ });
501
+ if (p5.isCancel(picked)) {
502
+ p5.cancel("Operation cancelled.");
503
+ process.exit(0);
504
+ }
505
+ listId = picked;
506
+ } else {
507
+ const manualId = await p5.text({
508
+ message: "Enter list ID (GUID) to subscribe to:",
509
+ placeholder: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
510
+ validate: (v) => {
511
+ if (!v || v.trim().length === 0) return "List ID is required";
512
+ }
513
+ });
514
+ if (p5.isCancel(manualId)) {
515
+ p5.cancel("Operation cancelled.");
516
+ process.exit(0);
517
+ }
518
+ listId = manualId;
519
+ }
520
+ const clientState = await promptClientState();
521
+ const expiryDays = SHAREPOINT_MAX_EXPIRY_DAYS;
522
+ const subSpin = p5.spinner();
523
+ subSpin.start("Creating SharePoint webhook subscription...");
524
+ let subscription;
525
+ try {
526
+ subscription = await createSharepointSubscription(
527
+ accessToken,
528
+ siteId,
529
+ listId,
530
+ webhookUrl,
531
+ clientState,
532
+ expiryDays
533
+ );
534
+ } catch (error) {
535
+ subSpin.stop("Failed.");
536
+ p5.log.error(error instanceof Error ? error.message : String(error));
537
+ p5.outro("");
538
+ process.exit(1);
539
+ }
540
+ subSpin.stop("Subscription created.");
541
+ await saveWebhookSignature(accountKm, clientState);
542
+ p5.note(
543
+ `Subscription ID: ${subscription.id}
544
+ Site ID: ${siteId}
545
+ List ID: ${listId}
546
+ Expires: ${subscription.expirationDateTime}
547
+ ClientState: ${clientState}
548
+ Webhook URL: ${webhookUrl}
549
+
550
+ Note: SharePoint subscriptions expire after ${SHAREPOINT_MAX_EXPIRY_DAYS} days max. Re-run this command to renew.`,
551
+ "SharePoint Subscription Created"
552
+ );
553
+ p5.outro("Done!");
554
+ }
555
+ var SHAREPOINT_MAX_EXPIRY_DAYS;
556
+ var init_sharepoint = __esm({
557
+ "microsoft/sharepoint.ts"() {
558
+ "use strict";
559
+ init_load_config();
560
+ init_prompts();
561
+ init_credentials();
562
+ init_graph();
563
+ SHAREPOINT_MAX_EXPIRY_DAYS = 180;
564
+ }
565
+ });
566
+
567
+ // microsoft/teams.ts
568
+ import * as p6 from "@clack/prompts";
569
+ async function fetchJoinedTeams(accessToken) {
570
+ const response = await fetch(`${GRAPH_API_BASE}/me/joinedTeams`, {
571
+ headers: { Authorization: `Bearer ${accessToken}` }
572
+ });
573
+ if (!response.ok) {
574
+ const error = await response.text();
575
+ throw new Error(`Failed to fetch teams: ${error}`);
576
+ }
577
+ const data = await response.json();
578
+ return data.value ?? [];
579
+ }
580
+ async function fetchTeamChannels(accessToken, teamId) {
581
+ const response = await fetch(
582
+ `${GRAPH_API_BASE}/teams/${encodeURIComponent(teamId)}/channels`,
583
+ { headers: { Authorization: `Bearer ${accessToken}` } }
584
+ );
585
+ if (!response.ok) {
586
+ const error = await response.text();
587
+ throw new Error(`Failed to fetch channels: ${error}`);
588
+ }
589
+ const data = await response.json();
590
+ return data.value ?? [];
591
+ }
592
+ async function fetchUserChats(accessToken) {
593
+ const response = await fetch(`${GRAPH_API_BASE}/me/chats`, {
594
+ headers: { Authorization: `Bearer ${accessToken}` }
595
+ });
596
+ if (!response.ok) {
597
+ const error = await response.text();
598
+ throw new Error(`Failed to fetch chats: ${error}`);
599
+ }
600
+ const data = await response.json();
601
+ return data.value ?? [];
602
+ }
603
+ async function pickTeamId(accessToken, label) {
604
+ const teamsSpin = p6.spinner();
605
+ teamsSpin.start("Fetching your teams...");
606
+ let teams = [];
607
+ try {
608
+ teams = await fetchJoinedTeams(accessToken);
609
+ teamsSpin.stop(`Found ${teams.length} team${teams.length === 1 ? "" : "s"}.`);
610
+ } catch (error) {
611
+ teamsSpin.stop("Could not fetch teams.");
612
+ p6.log.warn(error instanceof Error ? error.message : String(error));
613
+ }
614
+ if (teams.length > 0) {
615
+ const picked = await p6.select({
616
+ message: `[${label}] Select a team:`,
617
+ options: teams.map((t) => ({ value: t.id, label: t.displayName, hint: t.id }))
618
+ });
619
+ if (p6.isCancel(picked)) {
620
+ p6.cancel("Operation cancelled.");
621
+ process.exit(0);
622
+ }
623
+ return picked;
624
+ }
625
+ const manual = await p6.text({
626
+ message: `[${label}] Enter team ID:`,
627
+ placeholder: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
628
+ validate: (v) => {
629
+ if (!v || !v.trim()) return "Team ID is required";
630
+ }
631
+ });
632
+ if (p6.isCancel(manual)) {
633
+ p6.cancel("Operation cancelled.");
634
+ process.exit(0);
635
+ }
636
+ return manual;
637
+ }
638
+ async function pickChannelId(accessToken, teamId, label) {
639
+ const chanSpin = p6.spinner();
640
+ chanSpin.start("Fetching channels...");
641
+ let channels = [];
642
+ try {
643
+ channels = await fetchTeamChannels(accessToken, teamId);
644
+ chanSpin.stop(`Found ${channels.length} channel${channels.length === 1 ? "" : "s"}.`);
645
+ } catch (error) {
646
+ chanSpin.stop("Could not fetch channels.");
647
+ p6.log.warn(error instanceof Error ? error.message : String(error));
648
+ }
649
+ if (channels.length > 0) {
650
+ const picked = await p6.select({
651
+ message: `[${label}] Select a channel:`,
652
+ options: channels.map((c) => ({ value: c.id, label: c.displayName, hint: c.id }))
653
+ });
654
+ if (p6.isCancel(picked)) {
655
+ p6.cancel("Operation cancelled.");
656
+ process.exit(0);
657
+ }
658
+ return picked;
659
+ }
660
+ const manual = await p6.text({
661
+ message: `[${label}] Enter channel ID:`,
662
+ placeholder: "19:abc123@thread.skype",
663
+ validate: (v) => {
664
+ if (!v || !v.trim()) return "Channel ID is required";
665
+ }
666
+ });
667
+ if (p6.isCancel(manual)) {
668
+ p6.cancel("Operation cancelled.");
669
+ process.exit(0);
670
+ }
671
+ return manual;
672
+ }
673
+ async function pickChatId(accessToken, label) {
674
+ const chatSpin = p6.spinner();
675
+ chatSpin.start("Fetching your chats...");
676
+ let chats = [];
677
+ try {
678
+ chats = await fetchUserChats(accessToken);
679
+ chatSpin.stop(`Found ${chats.length} chat${chats.length === 1 ? "" : "s"}.`);
680
+ } catch (error) {
681
+ chatSpin.stop("Could not fetch chats.");
682
+ p6.log.warn(error instanceof Error ? error.message : String(error));
683
+ }
684
+ if (chats.length > 0) {
685
+ const picked = await p6.select({
686
+ message: `[${label}] Select a chat:`,
687
+ options: chats.map((c) => ({
688
+ value: c.id,
689
+ label: c.topic ?? `(${c.chatType})`,
690
+ hint: c.id
691
+ }))
692
+ });
693
+ if (p6.isCancel(picked)) {
694
+ p6.cancel("Operation cancelled.");
695
+ process.exit(0);
696
+ }
697
+ return picked;
698
+ }
699
+ const manual = await p6.text({
700
+ message: `[${label}] Enter chat ID:`,
701
+ placeholder: "19:abc123@thread.v2",
702
+ validate: (v) => {
703
+ if (!v || !v.trim()) return "Chat ID is required";
704
+ }
705
+ });
706
+ if (p6.isCancel(manual)) {
707
+ p6.cancel("Operation cancelled.");
708
+ process.exit(0);
709
+ }
710
+ return manual;
711
+ }
712
+ function buildTeamsResource(resourceType, ids) {
713
+ switch (resourceType) {
714
+ case "channelMessage":
715
+ return `teams/${ids.teamId}/channels/${ids.channelId}/messages`;
716
+ case "chatMessage":
717
+ return `chats/${ids.chatId}/messages`;
718
+ case "channelCreated":
719
+ return `teams/${ids.teamId}/channels`;
720
+ case "membershipChanged":
721
+ return `teams/${ids.teamId}/members`;
722
+ }
723
+ }
724
+ async function runTeamsSubscribe({ cwd }) {
725
+ const { internal } = await loadInternalConfig(
726
+ cwd,
727
+ "Corsair \u2014 Microsoft Teams Webhook Subscribe",
728
+ "teams",
729
+ "Teams"
730
+ );
731
+ const tenantId = await promptTenantId();
732
+ const { accessToken, accountKm } = await resolveAccessToken(
733
+ "teams",
734
+ tenantId,
735
+ internal
736
+ );
737
+ const webhookUrl = await promptWebhookUrl();
738
+ const selectedResourceTypes = await p6.multiselect({
739
+ message: "Select resources to subscribe to:",
740
+ options: [
741
+ {
742
+ value: "channelMessage",
743
+ label: "Channel Messages (teams/{id}/channels/{id}/messages)"
744
+ },
745
+ {
746
+ value: "chatMessage",
747
+ label: "Chat Messages (chats/{id}/messages)"
748
+ },
749
+ {
750
+ value: "channelCreated",
751
+ label: "Channel Created (teams/{id}/channels)"
752
+ },
753
+ {
754
+ value: "membershipChanged",
755
+ label: "Membership Changed (teams/{id}/members)"
756
+ }
757
+ ],
758
+ required: true
759
+ });
760
+ if (p6.isCancel(selectedResourceTypes)) {
761
+ p6.cancel("Operation cancelled.");
762
+ process.exit(0);
763
+ }
764
+ const resourceConfigs = [];
765
+ for (const resourceType of selectedResourceTypes) {
766
+ const ids = {};
767
+ if (resourceType === "chatMessage") {
768
+ ids.chatId = await pickChatId(accessToken, resourceType);
769
+ } else {
770
+ ids.teamId = await pickTeamId(accessToken, resourceType);
771
+ if (resourceType === "channelMessage") {
772
+ ids.channelId = await pickChannelId(accessToken, ids.teamId, resourceType);
773
+ }
774
+ }
775
+ resourceConfigs.push({ resourceType, ids });
776
+ }
777
+ const clientState = await promptClientState();
778
+ const results = [];
779
+ let hasError = false;
780
+ for (const { resourceType, ids } of resourceConfigs) {
781
+ const resource = buildTeamsResource(resourceType, ids);
782
+ const expiryMinutes = TEAMS_MAX_EXPIRY_MINUTES[resourceType];
783
+ const subSpin = p6.spinner();
784
+ subSpin.start(`Creating subscription: ${resourceType}...`);
785
+ try {
786
+ const subscription = await createGraphSubscription(
787
+ accessToken,
788
+ webhookUrl,
789
+ resource,
790
+ "created,updated,deleted",
791
+ clientState,
792
+ expiryMinutes
793
+ );
794
+ subSpin.stop(`Created: ${resourceType}`);
795
+ results.push(
796
+ `${resourceType}
797
+ Resource: ${resource}
798
+ ID: ${subscription.id}
799
+ Expires: ${subscription.expirationDateTime}`
800
+ );
801
+ } catch (error) {
802
+ subSpin.stop(`Failed: ${resourceType}`);
803
+ p6.log.error(error instanceof Error ? error.message : String(error));
804
+ hasError = true;
805
+ }
806
+ }
807
+ if (results.length > 0) {
808
+ p6.note(results.join("\n\n"), "Subscriptions created");
809
+ }
810
+ await saveWebhookSignature(accountKm, clientState);
811
+ if (!hasError) {
812
+ p6.log.success("Teams webhook subscriptions set up successfully.");
813
+ } else {
814
+ p6.log.warn("Some subscriptions failed. Check errors above.");
815
+ }
816
+ p6.note(
817
+ `ClientState: ${clientState}
818
+ Webhook URL: ${webhookUrl}
819
+
820
+ Note: Teams subscriptions expire. Re-run this command to renew.`,
821
+ "Setup complete"
822
+ );
823
+ p6.outro("Done!");
824
+ }
825
+ var TEAMS_MAX_EXPIRY_MINUTES;
826
+ var init_teams = __esm({
827
+ "microsoft/teams.ts"() {
828
+ "use strict";
829
+ init_load_config();
830
+ init_prompts();
831
+ init_credentials();
832
+ init_graph();
833
+ TEAMS_MAX_EXPIRY_MINUTES = {
834
+ channelMessage: 60,
835
+ chatMessage: 60,
836
+ channelCreated: 4230,
837
+ membershipChanged: 60
838
+ };
839
+ }
840
+ });
841
+
842
+ // microsoft/onedrive.ts
843
+ import * as p7 from "@clack/prompts";
844
+ function buildOnedriveResource(resourceType, ids) {
845
+ switch (resourceType) {
846
+ case "personalDrive":
847
+ return "me/drive/root";
848
+ case "specificDrive":
849
+ return `drives/${ids.driveId}/root`;
850
+ case "specificFolder":
851
+ return `me/drive/items/${ids.itemId}`;
852
+ }
853
+ }
854
+ async function runOnedriveSubscribe({ cwd }) {
855
+ const { internal } = await loadInternalConfig(
856
+ cwd,
857
+ "Corsair \u2014 OneDrive Webhook Subscribe",
858
+ "onedrive",
859
+ "OneDrive"
860
+ );
861
+ const tenantId = await promptTenantId();
862
+ const { accessToken, accountKm } = await resolveAccessToken(
863
+ "onedrive",
864
+ tenantId,
865
+ internal
866
+ );
867
+ const webhookUrl = await promptWebhookUrl();
868
+ const selectedResourceTypes = await p7.multiselect({
869
+ message: "Select resources to subscribe to:",
870
+ options: ONEDRIVE_RESOURCE_OPTIONS,
871
+ required: true
872
+ });
873
+ if (p7.isCancel(selectedResourceTypes)) {
874
+ p7.cancel("Operation cancelled.");
875
+ process.exit(0);
876
+ }
877
+ const resourceConfigs = [];
878
+ for (const resourceType of selectedResourceTypes) {
879
+ const ids = {};
880
+ if (resourceType === "specificDrive") {
881
+ const driveId = await p7.text({
882
+ message: `[${resourceType}] Enter drive ID:`,
883
+ placeholder: "b!abc123...",
884
+ validate: (v) => {
885
+ if (!v || !v.trim()) return "Drive ID is required";
886
+ }
887
+ });
888
+ if (p7.isCancel(driveId)) {
889
+ p7.cancel("Operation cancelled.");
890
+ process.exit(0);
891
+ }
892
+ ids.driveId = driveId;
893
+ } else if (resourceType === "specificFolder") {
894
+ const itemId = await p7.text({
895
+ message: `[${resourceType}] Enter item/folder ID:`,
896
+ placeholder: "01ABC123...",
897
+ validate: (v) => {
898
+ if (!v || !v.trim()) return "Item ID is required";
899
+ }
900
+ });
901
+ if (p7.isCancel(itemId)) {
902
+ p7.cancel("Operation cancelled.");
903
+ process.exit(0);
904
+ }
905
+ ids.itemId = itemId;
906
+ }
907
+ resourceConfigs.push({ resourceType, ids });
908
+ }
909
+ const clientState = await promptClientState();
910
+ const results = [];
911
+ let hasError = false;
912
+ for (const { resourceType, ids } of resourceConfigs) {
913
+ const resource = buildOnedriveResource(resourceType, ids);
914
+ const subSpin = p7.spinner();
915
+ subSpin.start(`Creating subscription: ${resourceType}...`);
916
+ try {
917
+ const subscription = await createGraphSubscription(
918
+ accessToken,
919
+ webhookUrl,
920
+ resource,
921
+ "updated",
922
+ clientState,
923
+ ONEDRIVE_MAX_EXPIRY_MINUTES
924
+ );
925
+ subSpin.stop(`Created: ${resourceType}`);
926
+ results.push(
927
+ `${resourceType}
928
+ Resource: ${resource}
929
+ ID: ${subscription.id}
930
+ Expires: ${subscription.expirationDateTime}`
931
+ );
932
+ } catch (error) {
933
+ subSpin.stop(`Failed: ${resourceType}`);
934
+ p7.log.error(error instanceof Error ? error.message : String(error));
935
+ hasError = true;
936
+ }
937
+ }
938
+ if (results.length > 0) {
939
+ p7.note(results.join("\n\n"), "Subscriptions created");
940
+ }
941
+ await saveWebhookSignature(accountKm, clientState);
942
+ if (!hasError) {
943
+ p7.log.success("OneDrive webhook subscriptions set up successfully.");
944
+ } else {
945
+ p7.log.warn("Some subscriptions failed. Check errors above.");
946
+ }
947
+ p7.note(
948
+ `ClientState: ${clientState}
949
+ Webhook URL: ${webhookUrl}
950
+
951
+ Note: OneDrive subscriptions expire. Re-run this command to renew.`,
952
+ "Setup complete"
953
+ );
954
+ p7.outro("Done!");
955
+ }
956
+ var ONEDRIVE_MAX_EXPIRY_MINUTES, ONEDRIVE_RESOURCE_OPTIONS;
957
+ var init_onedrive = __esm({
958
+ "microsoft/onedrive.ts"() {
959
+ "use strict";
960
+ init_load_config();
961
+ init_prompts();
962
+ init_credentials();
963
+ init_graph();
964
+ ONEDRIVE_MAX_EXPIRY_MINUTES = 4230;
965
+ ONEDRIVE_RESOURCE_OPTIONS = [
966
+ {
967
+ value: "personalDrive",
968
+ label: "Personal Drive Root \u2014 all changes to the user's drive",
969
+ hint: "me/drive/root"
970
+ },
971
+ {
972
+ value: "specificDrive",
973
+ label: "Specific Drive Root \u2014 all changes to a given drive ID",
974
+ hint: "drives/{driveId}/root"
975
+ },
976
+ {
977
+ value: "specificFolder",
978
+ label: "Specific Folder \u2014 changes within a given item/folder",
979
+ hint: "me/drive/items/{itemId}"
980
+ }
981
+ ];
982
+ }
983
+ });
984
+
985
+ // subscribe-microsoft.ts
986
+ var subscribe_microsoft_exports = {};
987
+ __export(subscribe_microsoft_exports, {
988
+ runOnedriveSubscribe: () => runOnedriveSubscribe,
989
+ runOutlookSubscribe: () => runOutlookSubscribe,
990
+ runSharepointSubscribe: () => runSharepointSubscribe,
991
+ runTeamsSubscribe: () => runTeamsSubscribe
992
+ });
993
+ var init_subscribe_microsoft = __esm({
994
+ "subscribe-microsoft.ts"() {
995
+ "use strict";
996
+ init_outlook();
997
+ init_sharepoint();
998
+ init_teams();
999
+ init_onedrive();
1000
+ }
1001
+ });
1002
+
1003
+ // google/calendar.ts
1004
+ import * as crypto2 from "crypto";
1005
+ import * as p8 from "@clack/prompts";
1006
+ async function setupCalendarWatch(accessToken, webhookUrl, calendarId) {
1007
+ const watchSpin = p8.spinner();
1008
+ watchSpin.start("Starting Calendar watch...");
1009
+ const channelId = crypto2.randomUUID();
1010
+ const watchRes = await fetch(
1011
+ `${CALENDAR_API_BASE}/calendars/${encodeURIComponent(calendarId)}/events/watch`,
1012
+ {
1013
+ method: "POST",
1014
+ headers: {
1015
+ Authorization: `Bearer ${accessToken}`,
1016
+ "Content-Type": "application/json"
1017
+ },
1018
+ body: JSON.stringify({
1019
+ id: channelId,
1020
+ type: "web_hook",
1021
+ address: webhookUrl
1022
+ })
1023
+ }
1024
+ );
1025
+ if (!watchRes.ok) {
1026
+ const error = await watchRes.text();
1027
+ watchSpin.stop("Failed.");
1028
+ p8.log.error(`Calendar watch failed: ${error}`);
1029
+ p8.outro("");
1030
+ process.exit(1);
1031
+ }
1032
+ const data = await watchRes.json();
1033
+ watchSpin.stop("Watch started.");
1034
+ p8.note(
1035
+ `Channel ID: ${channelId}
1036
+ Resource ID: ${data.resourceId}
1037
+ Expiration: ${new Date(Number(data.expiration)).toISOString()}`,
1038
+ "Watch Response"
1039
+ );
1040
+ }
1041
+ var CALENDAR_API_BASE;
1042
+ var init_calendar = __esm({
1043
+ "google/calendar.ts"() {
1044
+ "use strict";
1045
+ CALENDAR_API_BASE = "https://www.googleapis.com/calendar/v3";
1046
+ }
1047
+ });
1048
+
1049
+ // google/drive.ts
1050
+ import * as crypto3 from "crypto";
1051
+ import * as p9 from "@clack/prompts";
1052
+ async function setupDriveWatch(accessToken, webhookUrl) {
1053
+ const watchSpin = p9.spinner();
1054
+ watchSpin.start("Getting start page token...");
1055
+ const startPageTokenRes = await fetch(`${DRIVE_API_BASE}/changes/startPageToken`, {
1056
+ headers: { Authorization: `Bearer ${accessToken}` }
1057
+ });
1058
+ if (!startPageTokenRes.ok) {
1059
+ const error = await startPageTokenRes.text();
1060
+ watchSpin.stop("Failed.");
1061
+ p9.log.error(`Failed to get start page token: ${error}`);
1062
+ p9.outro("");
1063
+ process.exit(1);
1064
+ }
1065
+ const startPageTokenData = await startPageTokenRes.json();
1066
+ watchSpin.message("Starting Drive watch...");
1067
+ const channelId = crypto3.randomUUID();
1068
+ const watchRes = await fetch(
1069
+ `${DRIVE_API_BASE}/changes/watch?pageToken=${startPageTokenData.startPageToken}`,
1070
+ {
1071
+ method: "POST",
1072
+ headers: {
1073
+ Authorization: `Bearer ${accessToken}`,
1074
+ "Content-Type": "application/json"
1075
+ },
1076
+ body: JSON.stringify({
1077
+ id: channelId,
1078
+ type: "web_hook",
1079
+ address: webhookUrl
1080
+ })
1081
+ }
1082
+ );
1083
+ if (!watchRes.ok) {
1084
+ const error = await watchRes.text();
1085
+ watchSpin.stop("Failed.");
1086
+ p9.log.error(`Drive watch failed: ${error}`);
1087
+ p9.outro("");
1088
+ process.exit(1);
1089
+ }
1090
+ const data = await watchRes.json();
1091
+ watchSpin.stop("Watch started.");
1092
+ p9.note(
1093
+ `Channel ID: ${channelId}
1094
+ Resource ID: ${data.resourceId}
1095
+ Start Page Token: ${startPageTokenData.startPageToken}
1096
+ Expiration: ${new Date(Number(data.expiration)).toISOString()}`,
1097
+ "Watch Response"
1098
+ );
1099
+ }
1100
+ var DRIVE_API_BASE;
1101
+ var init_drive = __esm({
1102
+ "google/drive.ts"() {
1103
+ "use strict";
1104
+ DRIVE_API_BASE = "https://www.googleapis.com/drive/v3";
1105
+ }
1106
+ });
1107
+
1108
+ // google/gmail.ts
1109
+ import * as p10 from "@clack/prompts";
1110
+ async function setupGmailWatch(accessToken, topicName) {
1111
+ const watchSpin = p10.spinner();
1112
+ watchSpin.start("Starting Gmail watch...");
1113
+ const response = await fetch(`${GMAIL_API_BASE}/users/me/watch`, {
1114
+ method: "POST",
1115
+ headers: {
1116
+ Authorization: `Bearer ${accessToken}`,
1117
+ "Content-Type": "application/json"
1118
+ },
1119
+ body: JSON.stringify({
1120
+ topicName,
1121
+ labelIds: ["INBOX"]
1122
+ })
1123
+ });
1124
+ if (!response.ok) {
1125
+ const error = await response.text();
1126
+ watchSpin.stop("Failed.");
1127
+ p10.log.error(`Gmail watch failed: ${error}`);
1128
+ p10.outro("");
1129
+ process.exit(1);
1130
+ }
1131
+ const data = await response.json();
1132
+ watchSpin.stop("Watch started.");
1133
+ p10.note(
1134
+ `History ID: ${data.historyId}
1135
+ Expiration: ${new Date(Number(data.expiration)).toISOString()}`,
1136
+ "Watch Response"
1137
+ );
1138
+ }
1139
+ var GMAIL_API_BASE;
1140
+ var init_gmail = __esm({
1141
+ "google/gmail.ts"() {
1142
+ "use strict";
1143
+ GMAIL_API_BASE = "https://gmail.googleapis.com/gmail/v1";
1144
+ }
1145
+ });
1146
+
1147
+ // google/shared.ts
1148
+ import { execSync } from "child_process";
1149
+ async function refreshGoogleAccessToken(clientId, clientSecret, refreshToken) {
1150
+ const response = await fetch("https://oauth2.googleapis.com/token", {
1151
+ method: "POST",
1152
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
1153
+ body: new URLSearchParams({
1154
+ client_id: clientId,
1155
+ client_secret: clientSecret,
1156
+ refresh_token: refreshToken,
1157
+ grant_type: "refresh_token"
1158
+ })
1159
+ });
1160
+ if (!response.ok) {
1161
+ const error = await response.text();
1162
+ throw new Error(`Failed to refresh access token: ${error}`);
1163
+ }
1164
+ const data = await response.json();
1165
+ return data.access_token;
1166
+ }
1167
+ function copyToClipboard(text6) {
1168
+ try {
1169
+ const platform = process.platform;
1170
+ if (platform === "darwin") {
1171
+ execSync("pbcopy", { input: text6 });
1172
+ return true;
1173
+ } else if (platform === "linux") {
1174
+ try {
1175
+ execSync("xclip -selection clipboard", { input: text6 });
1176
+ return true;
1177
+ } catch {
1178
+ try {
1179
+ execSync("xsel --clipboard --input", { input: text6 });
1180
+ return true;
1181
+ } catch {
1182
+ return false;
1183
+ }
1184
+ }
1185
+ } else if (platform === "win32") {
1186
+ execSync("clip", { input: text6 });
1187
+ return true;
1188
+ }
1189
+ return false;
1190
+ } catch {
1191
+ return false;
1192
+ }
1193
+ }
1194
+ var init_shared = __esm({
1195
+ "google/shared.ts"() {
1196
+ "use strict";
1197
+ }
1198
+ });
1199
+
1200
+ // google/sheets.ts
1201
+ import * as p11 from "@clack/prompts";
1202
+ async function setupSheetsWatch(webhookUrl) {
1203
+ const appsScriptCode = APPS_SCRIPT_TEMPLATE(webhookUrl);
1204
+ p11.log.info("Google Sheets does not have a native watch API.");
1205
+ p11.log.info(
1206
+ "Instead, you need to set up Google Apps Script triggers in your spreadsheet."
1207
+ );
1208
+ p11.log.info("");
1209
+ const shouldCopy = await p11.confirm({
1210
+ message: "Copy Apps Script code to clipboard?",
1211
+ initialValue: true
1212
+ });
1213
+ let copied = false;
1214
+ if (shouldCopy) {
1215
+ copied = copyToClipboard(appsScriptCode);
1216
+ if (copied) {
1217
+ p11.log.success("Apps Script code copied to clipboard!");
1218
+ } else {
1219
+ p11.log.warn("Failed to copy to clipboard. Code will be displayed below.");
1220
+ }
1221
+ }
1222
+ p11.log.info("");
1223
+ p11.log.info("Setup Instructions:");
1224
+ p11.log.info("1. Open your Google Sheet");
1225
+ p11.log.info("2. Go to Extensions > Apps Script");
1226
+ p11.log.info("3. Paste the code into the script editor");
1227
+ p11.log.info('4. Run the "createTriggers" function once to install the triggers');
1228
+ p11.log.info("5. Authorize the script when prompted");
1229
+ p11.log.info("");
1230
+ if (!copied) {
1231
+ p11.log.info("Apps Script Code:");
1232
+ p11.log.info("");
1233
+ p11.log.info(appsScriptCode);
1234
+ p11.log.info("");
1235
+ }
1236
+ p11.note(
1237
+ `Webhook URL: ${webhookUrl}
1238
+
1239
+ The Apps Script code ${copied ? "has been copied to your clipboard" : "is displayed above"}. Paste it into your Google Sheet's Apps Script editor.`,
1240
+ "Google Sheets Setup"
1241
+ );
1242
+ }
1243
+ var APPS_SCRIPT_TEMPLATE;
1244
+ var init_sheets = __esm({
1245
+ "google/sheets.ts"() {
1246
+ "use strict";
1247
+ init_shared();
1248
+ APPS_SCRIPT_TEMPLATE = (webhookUrl) => `var WEBHOOK_URL = "${webhookUrl}";
1249
+
1250
+ function onEditTrigger(e) {
1251
+ if (!e || !e.range) return;
1252
+
1253
+ var sheet = e.range.getSheet();
1254
+ var payload = {
1255
+ spreadsheetId: e.source.getId(),
1256
+ sheetName: sheet.getName(),
1257
+ range: e.range.getA1Notation(),
1258
+ values: e.range.getValues(),
1259
+ eventType: "rangeUpdated",
1260
+ timestamp: new Date().toISOString()
1261
+ };
1262
+
1263
+ UrlFetchApp.fetch(WEBHOOK_URL, {
1264
+ method: "post",
1265
+ contentType: "application/json",
1266
+ payload: JSON.stringify(payload)
1267
+ });
1268
+ }
1269
+
1270
+ function onChangeTrigger(e) {
1271
+ if (!e) return;
1272
+
1273
+ var ss = SpreadsheetApp.getActiveSpreadsheet();
1274
+ var sheet = ss.getActiveSheet();
1275
+ var lastRow = sheet.getLastRow();
1276
+ var lastCol = sheet.getLastColumn();
1277
+ if (lastRow === 0 || lastCol === 0) return;
1278
+
1279
+ var values = sheet.getRange(lastRow, 1, 1, lastCol).getValues();
1280
+
1281
+ var payload = {
1282
+ spreadsheetId: ss.getId(),
1283
+ sheetName: sheet.getName(),
1284
+ range: "A" + lastRow + ":" + String.fromCharCode(64 + lastCol) + lastRow,
1285
+ values: values,
1286
+ eventType: "rangeUpdated",
1287
+ timestamp: new Date().toISOString()
1288
+ };
1289
+
1290
+ UrlFetchApp.fetch(WEBHOOK_URL, {
1291
+ method: "post",
1292
+ contentType: "application/json",
1293
+ payload: JSON.stringify(payload)
1294
+ });
1295
+ }
1296
+
1297
+ function createTriggers() {
1298
+ var ss = SpreadsheetApp.getActiveSpreadsheet();
1299
+
1300
+ ScriptApp.newTrigger("onEditTrigger").forSpreadsheet(ss).onEdit().create();
1301
+ ScriptApp.newTrigger("onChangeTrigger").forSpreadsheet(ss).onChange().create();
1302
+
1303
+ Logger.log("Triggers created successfully!");
1304
+ }
1305
+
1306
+ function removeTriggers() {
1307
+ var triggers = ScriptApp.getProjectTriggers();
1308
+ triggers.forEach(function(trigger) {
1309
+ ScriptApp.deleteTrigger(trigger);
1310
+ });
1311
+ Logger.log("All triggers removed.");
1312
+ }`;
1313
+ }
1314
+ });
1315
+
1316
+ // google/index.ts
1317
+ import * as p12 from "@clack/prompts";
1318
+ import { CORSAIR_INTERNAL as CORSAIR_INTERNAL2, createAccountKeyManager as createAccountKeyManager2, createIntegrationKeyManager as createIntegrationKeyManager2 } from "corsair/core";
1319
+ async function extractInternalConfig2(cwd) {
1320
+ const instance = await getCorsairInstance({ cwd, shouldThrowOnError: true });
1321
+ const internal = instance[CORSAIR_INTERNAL2];
1322
+ if (!internal) {
1323
+ throw new Error(
1324
+ "Could not read internal config from Corsair instance. Make sure you are using the latest version of corsair."
1325
+ );
1326
+ }
1327
+ return internal;
1328
+ }
1329
+ async function runGoogleSubscribe({
1330
+ cwd,
1331
+ pluginId: preselectedPluginId
1332
+ }) {
1333
+ p12.intro("Corsair \u2014 Google Webhook Subscribe");
1334
+ const spin = p12.spinner();
1335
+ spin.start("Loading corsair instance...");
1336
+ let internal;
1337
+ try {
1338
+ internal = await extractInternalConfig2(cwd);
1339
+ } catch (error) {
1340
+ spin.stop("Failed to load.");
1341
+ p12.log.error(error instanceof Error ? error.message : String(error));
1342
+ p12.outro("");
1343
+ process.exit(1);
1344
+ }
1345
+ const { plugins, database, kek } = internal;
1346
+ if (!database) {
1347
+ spin.stop("Failed.");
1348
+ p12.log.error("No database adapter configured.");
1349
+ p12.outro("");
1350
+ process.exit(1);
1351
+ }
1352
+ const googlePlugins = plugins.filter((pl) => {
1353
+ const opts = pl.options;
1354
+ return opts?.authType === "oauth_2" && GOOGLE_PLUGINS.includes(pl.id);
1355
+ });
1356
+ if (googlePlugins.length === 0) {
1357
+ spin.stop("No Google OAuth2 plugins found.");
1358
+ p12.outro("");
1359
+ process.exit(1);
1360
+ }
1361
+ spin.stop(
1362
+ `Loaded. Found ${googlePlugins.length} Google plugin${googlePlugins.length === 1 ? "" : "s"}.`
1363
+ );
1364
+ let pluginType;
1365
+ if (preselectedPluginId && GOOGLE_PLUGINS.includes(preselectedPluginId)) {
1366
+ pluginType = preselectedPluginId;
1367
+ } else {
1368
+ const selected = await p12.select({
1369
+ message: "Select a Google integration:",
1370
+ options: googlePlugins.map((pl) => ({ value: pl.id, label: pl.id }))
1371
+ });
1372
+ if (p12.isCancel(selected)) {
1373
+ p12.cancel("Operation cancelled.");
1374
+ process.exit(0);
1375
+ }
1376
+ pluginType = selected;
1377
+ }
1378
+ if (pluginType === "googlesheets") {
1379
+ const webhookUrl = await p12.text({
1380
+ message: "Enter webhook URL:",
1381
+ placeholder: "https://example.com/api/webhook",
1382
+ validate: (v) => {
1383
+ if (!v || v.trim().length === 0) return "Webhook URL is required";
1384
+ if (!v.startsWith("http://") && !v.startsWith("https://"))
1385
+ return "Webhook URL must start with http:// or https://";
1386
+ }
1387
+ });
1388
+ if (p12.isCancel(webhookUrl)) {
1389
+ p12.cancel("Operation cancelled.");
1390
+ process.exit(0);
1391
+ }
1392
+ await setupSheetsWatch(webhookUrl);
1393
+ p12.outro("Done!");
1394
+ return;
1395
+ }
1396
+ const tenantId = await promptTenantId();
1397
+ const credSpin = p12.spinner();
1398
+ credSpin.start("Fetching credentials...");
1399
+ try {
1400
+ const integrationKm = createIntegrationKeyManager2({
1401
+ authType: "oauth_2",
1402
+ integrationName: pluginType,
1403
+ kek,
1404
+ database
1405
+ });
1406
+ const accountKm = createAccountKeyManager2({
1407
+ authType: "oauth_2",
1408
+ integrationName: pluginType,
1409
+ tenantId,
1410
+ kek,
1411
+ database
1412
+ });
1413
+ const clientId = await integrationKm.get_client_id();
1414
+ const clientSecret = await integrationKm.get_client_secret();
1415
+ const refreshToken = await accountKm.get_refresh_token();
1416
+ if (!clientId || !clientSecret || !refreshToken) {
1417
+ credSpin.stop("Missing credentials.");
1418
+ p12.log.error(
1419
+ 'Client ID, Client Secret, and Refresh Token are required. Use "corsair auth" to set them.'
1420
+ );
1421
+ p12.outro("");
1422
+ process.exit(1);
1423
+ }
1424
+ const accessToken = await refreshGoogleAccessToken(clientId, clientSecret, refreshToken);
1425
+ credSpin.stop("Credentials loaded.");
1426
+ if (pluginType === "gmail") {
1427
+ const topicName = await p12.text({
1428
+ message: "Enter Pub/Sub topic name:",
1429
+ placeholder: "projects/my-project/topics/my-topic",
1430
+ validate: (v) => {
1431
+ if (!v || v.trim().length === 0) return "Topic name is required";
1432
+ }
1433
+ });
1434
+ if (p12.isCancel(topicName)) {
1435
+ p12.cancel("Operation cancelled.");
1436
+ process.exit(0);
1437
+ }
1438
+ await setupGmailWatch(accessToken, topicName);
1439
+ } else if (pluginType === "googledrive") {
1440
+ const webhookUrl = await p12.text({
1441
+ message: "Enter webhook URL:",
1442
+ placeholder: "https://example.com/api/webhook",
1443
+ validate: (v) => {
1444
+ if (!v || v.trim().length === 0) return "Webhook URL is required";
1445
+ }
1446
+ });
1447
+ if (p12.isCancel(webhookUrl)) {
1448
+ p12.cancel("Operation cancelled.");
1449
+ process.exit(0);
1450
+ }
1451
+ await setupDriveWatch(accessToken, webhookUrl);
1452
+ } else if (pluginType === "googlecalendar") {
1453
+ const webhookUrl = await p12.text({
1454
+ message: "Enter webhook URL:",
1455
+ placeholder: "https://example.com/api/webhook",
1456
+ validate: (v) => {
1457
+ if (!v || v.trim().length === 0) return "Webhook URL is required";
1458
+ }
1459
+ });
1460
+ if (p12.isCancel(webhookUrl)) {
1461
+ p12.cancel("Operation cancelled.");
1462
+ process.exit(0);
1463
+ }
1464
+ const calendarId = await p12.text({
1465
+ message: "Enter calendar ID:",
1466
+ defaultValue: "primary",
1467
+ placeholder: "primary"
1468
+ });
1469
+ if (p12.isCancel(calendarId)) {
1470
+ p12.cancel("Operation cancelled.");
1471
+ process.exit(0);
1472
+ }
1473
+ await setupCalendarWatch(accessToken, webhookUrl, calendarId);
1474
+ } else {
1475
+ p12.log.error(`Unsupported Google plugin: ${pluginType}`);
1476
+ process.exit(1);
1477
+ }
1478
+ } catch (error) {
1479
+ credSpin.stop("Failed.");
1480
+ p12.log.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
1481
+ process.exit(1);
1482
+ }
1483
+ p12.outro("Done!");
1484
+ }
1485
+ var GOOGLE_PLUGINS;
1486
+ var init_google = __esm({
1487
+ "google/index.ts"() {
1488
+ "use strict";
1489
+ init_index();
1490
+ init_prompts();
1491
+ init_calendar();
1492
+ init_drive();
1493
+ init_gmail();
1494
+ init_shared();
1495
+ init_sheets();
1496
+ GOOGLE_PLUGINS = [
1497
+ "gmail",
1498
+ "googledrive",
1499
+ "googlecalendar",
1500
+ "googlesheets"
1501
+ ];
1502
+ }
1503
+ });
1504
+
1505
+ // subscribe-google.ts
1506
+ var subscribe_google_exports = {};
1507
+ __export(subscribe_google_exports, {
1508
+ runGoogleSubscribe: () => runGoogleSubscribe
1509
+ });
1510
+ var init_subscribe_google = __esm({
1511
+ "subscribe-google.ts"() {
1512
+ "use strict";
1513
+ init_google();
1514
+ }
1515
+ });
1516
+
41
1517
  // auth.ts
42
1518
  var auth_exports = {};
43
1519
  __export(auth_exports, {
@@ -48,9 +1524,9 @@ import * as https from "https";
48
1524
  import * as net from "net";
49
1525
  import * as querystring from "querystring";
50
1526
  import {
51
- CORSAIR_INTERNAL,
52
- createAccountKeyManager,
53
- createIntegrationKeyManager,
1527
+ CORSAIR_INTERNAL as CORSAIR_INTERNAL3,
1528
+ createAccountKeyManager as createAccountKeyManager3,
1529
+ createIntegrationKeyManager as createIntegrationKeyManager3,
54
1530
  encryptDEK,
55
1531
  generateDEK
56
1532
  } from "corsair/core";
@@ -94,19 +1570,25 @@ function waitForOAuthCode(port) {
94
1570
  const error = url.searchParams.get("error");
95
1571
  if (error) {
96
1572
  res.writeHead(400, { "Content-Type": "text/html" });
97
- res.end(`<html><body><h2>Authorization failed: ${error}</h2><p>You can close this tab.</p></body></html>`);
1573
+ res.end(
1574
+ `<html><body><h2>Authorization failed: ${error}</h2><p>You can close this tab.</p></body></html>`
1575
+ );
98
1576
  server.close();
99
1577
  reject(new Error(`OAuth error: ${error}`));
100
1578
  return;
101
1579
  }
102
1580
  if (code) {
103
1581
  res.writeHead(200, { "Content-Type": "text/html" });
104
- res.end("<html><body><h2>Authorization successful!</h2><p>You can close this tab and return to the terminal.</p></body></html>");
1582
+ res.end(
1583
+ "<html><body><h2>Authorization successful!</h2><p>You can close this tab and return to the terminal.</p></body></html>"
1584
+ );
105
1585
  server.close();
106
1586
  resolve(code);
107
1587
  } else {
108
1588
  res.writeHead(400, { "Content-Type": "text/html" });
109
- res.end("<html><body><h2>No code received.</h2><p>You can close this tab.</p></body></html>");
1589
+ res.end(
1590
+ "<html><body><h2>No code received.</h2><p>You can close this tab.</p></body></html>"
1591
+ );
110
1592
  }
111
1593
  });
112
1594
  server.listen(port, "127.0.0.1", () => {
@@ -136,7 +1618,12 @@ function exchangeCodeForTokens(code, clientId, clientSecret, oauthConfig, redire
136
1618
  headers.Authorization = `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`;
137
1619
  }
138
1620
  const req = https.request(
139
- { hostname: tokenUrl.hostname, path: tokenUrl.pathname, method: "POST", headers },
1621
+ {
1622
+ hostname: tokenUrl.hostname,
1623
+ path: tokenUrl.pathname,
1624
+ method: "POST",
1625
+ headers
1626
+ },
140
1627
  (res) => {
141
1628
  let data = "";
142
1629
  res.on("data", (chunk) => {
@@ -151,14 +1638,17 @@ function exchangeCodeForTokens(code, clientId, clientSecret, oauthConfig, redire
151
1638
  });
152
1639
  }
153
1640
  );
154
- req.on("error", (error) => reject(new Error(`Request failed: ${error.message}`)));
1641
+ req.on(
1642
+ "error",
1643
+ (error) => reject(new Error(`Request failed: ${error.message}`))
1644
+ );
155
1645
  req.write(postData);
156
1646
  req.end();
157
1647
  });
158
1648
  }
159
- async function extractInternalConfig(cwd) {
1649
+ async function extractInternalConfig3(cwd) {
160
1650
  const instance = await getCorsairInstance({ cwd, shouldThrowOnError: true });
161
- const internal = instance[CORSAIR_INTERNAL];
1651
+ const internal = instance[CORSAIR_INTERNAL3];
162
1652
  if (!internal) {
163
1653
  throw new Error(
164
1654
  "Could not read internal config from Corsair instance. Make sure you are using the latest version of corsair."
@@ -172,16 +1662,28 @@ async function ensureIntegration(database, pluginId, kek) {
172
1662
  if (existing) return { id: existing.id };
173
1663
  const dek = generateDEK();
174
1664
  const encryptedDek = await encryptDEK(dek, kek);
175
- const row = await orm.integrations.create({ name: pluginId, config: {}, dek: encryptedDek });
1665
+ const row = await orm.integrations.create({
1666
+ name: pluginId,
1667
+ config: {},
1668
+ dek: encryptedDek
1669
+ });
176
1670
  return { id: row.id };
177
1671
  }
178
1672
  async function ensureAccount(database, integrationId, tenantId, kek) {
179
1673
  const orm = createCorsairOrm(database);
180
- const existing = await orm.accounts.findOne({ tenant_id: tenantId, integration_id: integrationId });
1674
+ const existing = await orm.accounts.findOne({
1675
+ tenant_id: tenantId,
1676
+ integration_id: integrationId
1677
+ });
181
1678
  if (existing) return;
182
1679
  const dek = generateDEK();
183
1680
  const encryptedDek = await encryptDEK(dek, kek);
184
- await orm.accounts.create({ tenant_id: tenantId, integration_id: integrationId, config: {}, dek: encryptedDek });
1681
+ await orm.accounts.create({
1682
+ tenant_id: tenantId,
1683
+ integration_id: integrationId,
1684
+ config: {},
1685
+ dek: encryptedDek
1686
+ });
185
1687
  }
186
1688
  async function oauthGetUrl(database, plugin, kek, tenantId) {
187
1689
  const oauthCfg = getOAuthConfigForPlugin(plugin);
@@ -190,7 +1692,7 @@ async function oauthGetUrl(database, plugin, kek, tenantId) {
190
1692
  return;
191
1693
  }
192
1694
  const extraFields = getCustomIntegrationFields(plugin, "oauth_2");
193
- const integrationKm = createIntegrationKeyManager({
1695
+ const integrationKm = createIntegrationKeyManager3({
194
1696
  authType: "oauth_2",
195
1697
  integrationName: plugin.id,
196
1698
  kek,
@@ -199,19 +1701,25 @@ async function oauthGetUrl(database, plugin, kek, tenantId) {
199
1701
  });
200
1702
  const clientId = await integrationKm.get_client_id();
201
1703
  if (!clientId) {
202
- out({ error: `client_id not set for '${plugin.id}'. Run: corsair setup --${plugin.id} client_id=YOUR_CLIENT_ID` });
1704
+ out({
1705
+ error: `client_id not set for '${plugin.id}'. Run: corsair setup --${plugin.id} client_id=YOUR_CLIENT_ID`
1706
+ });
203
1707
  return;
204
1708
  }
205
1709
  const clientSecret = await integrationKm.get_client_secret();
206
1710
  if (!clientSecret) {
207
- out({ error: `client_secret not set for '${plugin.id}'. Run: corsair setup --${plugin.id} client_secret=YOUR_CLIENT_SECRET` });
1711
+ out({
1712
+ error: `client_secret not set for '${plugin.id}'. Run: corsair setup --${plugin.id} client_secret=YOUR_CLIENT_SECRET`
1713
+ });
208
1714
  return;
209
1715
  }
210
1716
  let redirectUri;
211
1717
  if (oauthCfg.requiresRegisteredRedirect) {
212
1718
  const stored = await integrationKm.get_redirect_url();
213
1719
  if (!stored) {
214
- out({ error: `redirect_url required for '${plugin.id}'. Run: corsair setup --${plugin.id} redirect_url=YOUR_REDIRECT_URI` });
1720
+ out({
1721
+ error: `redirect_url required for '${plugin.id}'. Run: corsair setup --${plugin.id} redirect_url=YOUR_REDIRECT_URI`
1722
+ });
215
1723
  return;
216
1724
  }
217
1725
  redirectUri = stored;
@@ -227,38 +1735,74 @@ async function oauthGetUrl(database, plugin, kek, tenantId) {
227
1735
  ...oauthCfg.authParams
228
1736
  };
229
1737
  const authUrl = `${oauthCfg.authUrl}?${querystring.stringify(authParams)}`;
230
- if (!oauthCfg.requiresRegisteredRedirect) {
231
- const portMatch = redirectUri.match(/:(\d+)$/);
232
- const port = portMatch?.[1] ? parseInt(portMatch[1], 10) : null;
233
- if (port) {
234
- out({ status: "pending_oauth", authUrl, redirectUri, plugin: plugin.id, tenant: tenantId, note: "Open authUrl in a browser. Tokens will be saved automatically once authorized." });
235
- let code;
236
- try {
237
- code = await waitForOAuthCode(port);
238
- } catch (err) {
239
- out({ error: `Authorization failed: ${err instanceof Error ? err.message : String(err)}` });
240
- return;
241
- }
242
- await oauthExchangeCode(database, plugin, kek, tenantId, code, redirectUri, clientId, clientSecret, oauthCfg);
1738
+ const localhostPortMatch = redirectUri.match(
1739
+ /^https?:\/\/(?:localhost|127\.0\.0\.1):(\d+)/
1740
+ );
1741
+ const localhostPort = localhostPortMatch?.[1] ? parseInt(localhostPortMatch[1], 10) : null;
1742
+ if (localhostPort) {
1743
+ out({
1744
+ status: "pending_oauth",
1745
+ authUrl,
1746
+ redirectUri,
1747
+ plugin: plugin.id,
1748
+ tenant: tenantId,
1749
+ note: "Open authUrl in a browser. Tokens will be saved automatically once authorized."
1750
+ });
1751
+ let code;
1752
+ try {
1753
+ code = await waitForOAuthCode(localhostPort);
1754
+ } catch (err) {
1755
+ out({
1756
+ error: `Authorization failed: ${err instanceof Error ? err.message : String(err)}`
1757
+ });
243
1758
  return;
244
1759
  }
1760
+ await oauthExchangeCode(
1761
+ database,
1762
+ plugin,
1763
+ kek,
1764
+ tenantId,
1765
+ code,
1766
+ redirectUri,
1767
+ clientId,
1768
+ clientSecret,
1769
+ oauthCfg
1770
+ );
1771
+ return;
245
1772
  }
246
- out({ status: "needs_code", authUrl, redirectUri, plugin: plugin.id, tenant: tenantId, note: "Open authUrl, complete auth, then run: corsair auth --plugin=<id> --code=CODE" });
1773
+ out({
1774
+ status: "needs_code",
1775
+ authUrl,
1776
+ redirectUri,
1777
+ plugin: plugin.id,
1778
+ tenant: tenantId,
1779
+ note: "Open authUrl, complete auth, then run: corsair auth --plugin=<id> --code=CODE"
1780
+ });
247
1781
  }
248
1782
  async function oauthExchangeCode(database, plugin, kek, tenantId, code, redirectUri, clientId, clientSecret, oauthCfg) {
249
1783
  let tokens;
250
1784
  try {
251
- tokens = await exchangeCodeForTokens(code, clientId, clientSecret, oauthCfg, redirectUri);
1785
+ tokens = await exchangeCodeForTokens(
1786
+ code,
1787
+ clientId,
1788
+ clientSecret,
1789
+ oauthCfg,
1790
+ redirectUri
1791
+ );
252
1792
  } catch (err) {
253
- out({ error: `Token exchange failed: ${err instanceof Error ? err.message : String(err)}` });
1793
+ out({
1794
+ error: `Token exchange failed: ${err instanceof Error ? err.message : String(err)}`
1795
+ });
254
1796
  return;
255
1797
  }
256
1798
  if (!tokens.access_token) {
257
- out({ error: `No access_token in response from ${oauthCfg.providerName}.` });
1799
+ out({
1800
+ error: `No access_token in response from ${oauthCfg.providerName}.`
1801
+ });
258
1802
  return;
259
1803
  }
260
1804
  const extraAccountFields = getCustomAccountFields(plugin, "oauth_2");
261
- const accountKm = createAccountKeyManager({
1805
+ const accountKm = createAccountKeyManager3({
262
1806
  authType: "oauth_2",
263
1807
  integrationName: plugin.id,
264
1808
  tenantId,
@@ -267,8 +1811,12 @@ async function oauthExchangeCode(database, plugin, kek, tenantId, code, redirect
267
1811
  extraAccountFields
268
1812
  });
269
1813
  await accountKm.set_access_token(tokens.access_token);
270
- if (tokens.refresh_token) await accountKm.set_refresh_token(tokens.refresh_token);
271
- if (tokens.expires_in) await accountKm.set_expires_at((Math.floor(Date.now() / 1e3) + tokens.expires_in).toString());
1814
+ if (tokens.refresh_token)
1815
+ await accountKm.set_refresh_token(tokens.refresh_token);
1816
+ if (tokens.expires_in)
1817
+ await accountKm.set_expires_at(
1818
+ (Math.floor(Date.now() / 1e3) + tokens.expires_in).toString()
1819
+ );
272
1820
  out({ status: "success", plugin: plugin.id, tenant: tenantId });
273
1821
  }
274
1822
  async function oauthWithCode(database, plugin, kek, tenantId, code) {
@@ -278,7 +1826,7 @@ async function oauthWithCode(database, plugin, kek, tenantId, code) {
278
1826
  return;
279
1827
  }
280
1828
  const extraFields = getCustomIntegrationFields(plugin, "oauth_2");
281
- const integrationKm = createIntegrationKeyManager({
1829
+ const integrationKm = createIntegrationKeyManager3({
282
1830
  authType: "oauth_2",
283
1831
  integrationName: plugin.id,
284
1832
  kek,
@@ -289,17 +1837,29 @@ async function oauthWithCode(database, plugin, kek, tenantId, code) {
289
1837
  const clientSecret = await integrationKm.get_client_secret();
290
1838
  const redirectUri = await integrationKm.get_redirect_url() ?? "";
291
1839
  if (!clientId || !clientSecret) {
292
- out({ error: `client_id and client_secret must be set before exchanging a code.` });
1840
+ out({
1841
+ error: `client_id and client_secret must be set before exchanging a code.`
1842
+ });
293
1843
  return;
294
1844
  }
295
- await oauthExchangeCode(database, plugin, kek, tenantId, code, redirectUri, clientId, clientSecret, oauthCfg);
1845
+ await oauthExchangeCode(
1846
+ database,
1847
+ plugin,
1848
+ kek,
1849
+ tenantId,
1850
+ code,
1851
+ redirectUri,
1852
+ clientId,
1853
+ clientSecret,
1854
+ oauthCfg
1855
+ );
296
1856
  }
297
1857
  async function getCredentials(database, plugin, kek, tenantId) {
298
1858
  const authType = getAuthType(plugin);
299
1859
  const result = {};
300
1860
  if (authType === "oauth_2") {
301
1861
  const extraIntegrationFields = getCustomIntegrationFields(plugin, authType);
302
- const integrationKm = createIntegrationKeyManager({
1862
+ const integrationKm = createIntegrationKeyManager3({
303
1863
  authType,
304
1864
  integrationName: plugin.id,
305
1865
  kek,
@@ -311,10 +1871,11 @@ async function getCredentials(database, plugin, kek, tenantId) {
311
1871
  result.redirect_url = await integrationKm.get_redirect_url();
312
1872
  for (const field of extraIntegrationFields) {
313
1873
  const fn = integrationKm[`get_${field}`];
314
- if (typeof fn === "function") result[field] = await fn();
1874
+ if (typeof fn === "function")
1875
+ result[field] = await fn();
315
1876
  }
316
1877
  const extraAccountFields = getCustomAccountFields(plugin, authType);
317
- const accountKm = createAccountKeyManager({
1878
+ const accountKm = createAccountKeyManager3({
318
1879
  authType,
319
1880
  integrationName: plugin.id,
320
1881
  tenantId,
@@ -328,11 +1889,12 @@ async function getCredentials(database, plugin, kek, tenantId) {
328
1889
  result.webhook_signature = await accountKm.get_webhook_signature();
329
1890
  for (const field of extraAccountFields) {
330
1891
  const fn = accountKm[`get_${field}`];
331
- if (typeof fn === "function") result[field] = await fn();
1892
+ if (typeof fn === "function")
1893
+ result[field] = await fn();
332
1894
  }
333
1895
  } else if (authType === "api_key") {
334
1896
  const extraAccountFields = getCustomAccountFields(plugin, authType);
335
- const accountKm = createAccountKeyManager({
1897
+ const accountKm = createAccountKeyManager3({
336
1898
  authType,
337
1899
  integrationName: plugin.id,
338
1900
  tenantId,
@@ -344,7 +1906,7 @@ async function getCredentials(database, plugin, kek, tenantId) {
344
1906
  result.webhook_signature = await accountKm.get_webhook_signature();
345
1907
  } else if (authType === "bot_token") {
346
1908
  const extraAccountFields = getCustomAccountFields(plugin, authType);
347
- const accountKm = createAccountKeyManager({
1909
+ const accountKm = createAccountKeyManager3({
348
1910
  authType,
349
1911
  integrationName: plugin.id,
350
1912
  tenantId,
@@ -374,7 +1936,7 @@ async function runAuth({
374
1936
  }) {
375
1937
  let internal;
376
1938
  try {
377
- internal = await extractInternalConfig(cwd);
1939
+ internal = await extractInternalConfig3(cwd);
378
1940
  } catch (error) {
379
1941
  out({ error: error instanceof Error ? error.message : String(error) });
380
1942
  process.exit(1);
@@ -387,13 +1949,19 @@ async function runAuth({
387
1949
  if (!pluginIdArg) {
388
1950
  out({
389
1951
  error: "No plugin specified. Use --plugin=<id>.",
390
- available: plugins.map((pl) => ({ id: pl.id, authType: getAuthType(pl) }))
1952
+ available: plugins.map((pl) => ({
1953
+ id: pl.id,
1954
+ authType: getAuthType(pl)
1955
+ }))
391
1956
  });
392
1957
  process.exit(1);
393
1958
  }
394
1959
  const plugin = plugins.find((pl) => pl.id === pluginIdArg);
395
1960
  if (!plugin) {
396
- out({ error: `Plugin '${pluginIdArg}' not found.`, available: plugins.map((pl) => pl.id) });
1961
+ out({
1962
+ error: `Plugin '${pluginIdArg}' not found.`,
1963
+ available: plugins.map((pl) => pl.id)
1964
+ });
397
1965
  process.exit(1);
398
1966
  }
399
1967
  const integration = await ensureIntegration(database, plugin.id, kek);
@@ -405,7 +1973,9 @@ async function runAuth({
405
1973
  }
406
1974
  const authType = getAuthType(plugin);
407
1975
  if (authType !== "oauth_2") {
408
- out({ error: `'corsair auth' is for OAuth flows. Plugin '${plugin.id}' uses '${authType}'. Set credentials via: corsair setup --${plugin.id} <field>=<value>` });
1976
+ out({
1977
+ error: `'corsair auth' is for OAuth flows. Plugin '${plugin.id}' uses '${authType}'. Set credentials via: corsair setup --${plugin.id} <field>=<value>`
1978
+ });
409
1979
  return;
410
1980
  }
411
1981
  if (codeArg) {
@@ -595,9 +2165,13 @@ or reinstall your dependencies:
595
2165
  rm -rf node_modules && npm install`
596
2166
  );
597
2167
  }
598
- console.error(`[#corsair]: Error loading ${possiblePath}: Native module binding not found.`);
2168
+ console.error(
2169
+ `[#corsair]: Error loading ${possiblePath}: Native module binding not found.`
2170
+ );
599
2171
  console.log("");
600
- console.log("[#corsair]: A native Node.js addon (e.g. better-sqlite3) needs to be rebuilt for your current Node.js version.");
2172
+ console.log(
2173
+ "[#corsair]: A native Node.js addon (e.g. better-sqlite3) needs to be rebuilt for your current Node.js version."
2174
+ );
601
2175
  console.log("[#corsair]: Try running:");
602
2176
  console.log(" npm rebuild");
603
2177
  console.log("[#corsair]: Or reinstall your dependencies:");
@@ -651,7 +2225,9 @@ function resolveClient(instance, tenant) {
651
2225
  const obj = instance;
652
2226
  if ("withTenant" in obj && typeof obj.withTenant === "function") {
653
2227
  if (!tenant) {
654
- console.error("[#corsair]: This is a multi-tenant instance. Pass --tenant=<id>.");
2228
+ console.error(
2229
+ "[#corsair]: This is a multi-tenant instance. Pass --tenant=<id>."
2230
+ );
655
2231
  process.exit(1);
656
2232
  }
657
2233
  return obj.withTenant(tenant);
@@ -692,11 +2268,16 @@ function parseAuthArgs(args) {
692
2268
  let tenantId;
693
2269
  let code;
694
2270
  let credentials = false;
2271
+ let webhook = false;
695
2272
  for (const arg of args) {
696
2273
  if (arg === "--credentials") {
697
2274
  credentials = true;
698
2275
  continue;
699
2276
  }
2277
+ if (arg === "--webhook") {
2278
+ webhook = true;
2279
+ continue;
2280
+ }
700
2281
  const eqIdx = arg.indexOf("=");
701
2282
  if (arg.startsWith("--") && eqIdx !== -1) {
702
2283
  const key = arg.slice(2, eqIdx);
@@ -715,7 +2296,7 @@ function parseAuthArgs(args) {
715
2296
  }
716
2297
  }
717
2298
  }
718
- return { pluginId, tenantId, code, credentials };
2299
+ return { pluginId, tenantId, code, credentials, webhook };
719
2300
  }
720
2301
  function parseSetupArgs(args) {
721
2302
  let backfill = false;
@@ -790,6 +2371,8 @@ function printHelp() {
790
2371
  " pnpm corsair auth --plugin=<id> Start OAuth flow",
791
2372
  " pnpm corsair auth --plugin=<id> --code=<code> Exchange OAuth code for tokens",
792
2373
  " pnpm corsair auth --plugin=<id> --credentials Show credential status",
2374
+ " pnpm corsair auth --plugin=<id> --webhook Set up webhook subscription",
2375
+ " Supported plugins: outlook, sharepoint, teams, onedrive, gmail, googledrive, googlecalendar, googlesheets",
793
2376
  " pnpm corsair list [--plugin=<id>] [--type=api|webhooks|db] List endpoint paths (tip: pipe to grep to filter)",
794
2377
  " pnpm corsair schema <path> Show schema for an endpoint/webhook/DB entity",
795
2378
  ' pnpm corsair script --code "<js>" [--tenant=<id>]',
@@ -797,9 +2380,7 @@ function printHelp() {
797
2380
  " IMPORTANT: Always filter results inline \u2014 you are the consumer of the return value, so returning full list responses wastes tokens.",
798
2381
  " Bad: return await corsair.slack.api.users.list({})",
799
2382
  " Good: return (await corsair.slack.api.users.list({})).members.find(u => u.name === 'bob')?.id",
800
- ...SHOW_RUN ? [
801
- " run <path> [input-json] [--tenant=<id>] Call an endpoint directly"
802
- ] : []
2383
+ ...SHOW_RUN ? [" run <path> [input-json] [--tenant=<id>] Call an endpoint directly"] : []
803
2384
  ];
804
2385
  console.log(lines.join("\n"));
805
2386
  }
@@ -819,17 +2400,81 @@ async function main() {
819
2400
  return;
820
2401
  }
821
2402
  if (command === "auth") {
822
- const { runAuth: runAuth2 } = await Promise.resolve().then(() => (init_auth(), auth_exports));
823
2403
  const authArgs = parseAuthArgs(args.slice(1));
2404
+ if (authArgs.webhook) {
2405
+ const pluginId = authArgs.pluginId;
2406
+ if (!pluginId) {
2407
+ console.error("[#corsair]: --webhook requires --plugin=<id>.");
2408
+ process.exit(1);
2409
+ }
2410
+ if (pluginId === "outlook") {
2411
+ const { runOutlookSubscribe: runOutlookSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2412
+ await runOutlookSubscribe2({ cwd });
2413
+ } else if (pluginId === "sharepoint") {
2414
+ const { runSharepointSubscribe: runSharepointSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2415
+ await runSharepointSubscribe2({ cwd });
2416
+ } else if (pluginId === "teams") {
2417
+ const { runTeamsSubscribe: runTeamsSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2418
+ await runTeamsSubscribe2({ cwd });
2419
+ } else if (pluginId === "onedrive") {
2420
+ const { runOnedriveSubscribe: runOnedriveSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2421
+ await runOnedriveSubscribe2({ cwd });
2422
+ } else if (["gmail", "googledrive", "googlecalendar", "googlesheets"].includes(
2423
+ pluginId
2424
+ )) {
2425
+ const { runGoogleSubscribe: runGoogleSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_google(), subscribe_google_exports));
2426
+ await runGoogleSubscribe2({ cwd, pluginId });
2427
+ } else {
2428
+ console.error(
2429
+ `[#corsair]: Webhook subscription not supported for plugin '${pluginId}'.`
2430
+ );
2431
+ console.error(
2432
+ "[#corsair]: Supported: outlook, sharepoint, teams, onedrive, gmail, googledrive, googlecalendar, googlesheets"
2433
+ );
2434
+ process.exit(1);
2435
+ }
2436
+ return;
2437
+ }
2438
+ const { runAuth: runAuth2 } = await Promise.resolve().then(() => (init_auth(), auth_exports));
824
2439
  await runAuth2({ cwd, ...authArgs });
825
2440
  return;
826
2441
  }
2442
+ if (command === "watch-renew") {
2443
+ const { runGoogleSubscribe: runGoogleSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_google(), subscribe_google_exports));
2444
+ await runGoogleSubscribe2({ cwd });
2445
+ return;
2446
+ }
2447
+ if (command === "sharepoint-subscribe") {
2448
+ const { runSharepointSubscribe: runSharepointSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2449
+ await runSharepointSubscribe2({ cwd });
2450
+ return;
2451
+ }
2452
+ if (command === "subscribe") {
2453
+ const pluginArg = args.slice(1).find((a) => a.startsWith("--plugin="));
2454
+ const pluginId = pluginArg ? pluginArg.slice("--plugin=".length) : void 0;
2455
+ if (pluginId === "outlook") {
2456
+ const { runOutlookSubscribe: runOutlookSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2457
+ await runOutlookSubscribe2({ cwd });
2458
+ return;
2459
+ }
2460
+ console.error(
2461
+ `[#corsair]: Unknown plugin for subscribe: '${pluginId ?? "(none)"}'. Supported: outlook`
2462
+ );
2463
+ process.exit(1);
2464
+ }
2465
+ if (command === "teams-subscribe") {
2466
+ const { runTeamsSubscribe: runTeamsSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2467
+ await runTeamsSubscribe2({ cwd });
2468
+ return;
2469
+ }
827
2470
  if (command === "list") {
828
2471
  const { plugin, type } = parseListArgs(args.slice(1));
829
2472
  const instance = await getCorsairInstance({ cwd });
830
2473
  const corsair = instance;
831
2474
  if (typeof corsair.list_operations !== "function") {
832
- console.error("[#corsair]: list_operations not available on this Corsair instance.");
2475
+ console.error(
2476
+ "[#corsair]: list_operations not available on this Corsair instance."
2477
+ );
833
2478
  process.exit(1);
834
2479
  }
835
2480
  const result = corsair.list_operations({ plugin, type });
@@ -848,7 +2493,9 @@ async function main() {
848
2493
  const { path: endpointPath, input, tenant } = parseRunArgs(args.slice(1));
849
2494
  if (!endpointPath) {
850
2495
  console.error("[#corsair]: Usage: corsair run <path> [input-json]");
851
- console.error(`[#corsair]: Example: corsair run slack.api.messages.post '{"channel":"C123","text":"hi"}'`);
2496
+ console.error(
2497
+ `[#corsair]: Example: corsair run slack.api.messages.post '{"channel":"C123","text":"hi"}'`
2498
+ );
852
2499
  process.exit(1);
853
2500
  }
854
2501
  const instance = await getCorsairInstance({ cwd });
@@ -856,7 +2503,9 @@ async function main() {
856
2503
  const fn = navigateToEndpoint(client, endpointPath);
857
2504
  if (!fn) {
858
2505
  console.error(`[#corsair]: Could not find endpoint "${endpointPath}".`);
859
- console.error("[#corsair]: Run `pnpm corsair list` to see available paths.");
2506
+ console.error(
2507
+ "[#corsair]: Run `pnpm corsair list` to see available paths."
2508
+ );
860
2509
  process.exit(1);
861
2510
  }
862
2511
  let parsedInput = {};
@@ -864,7 +2513,9 @@ async function main() {
864
2513
  try {
865
2514
  parsedInput = JSON.parse(input);
866
2515
  } catch {
867
- console.error("[#corsair]: Invalid JSON input. Make sure to quote the JSON string.");
2516
+ console.error(
2517
+ "[#corsair]: Invalid JSON input. Make sure to quote the JSON string."
2518
+ );
868
2519
  process.exit(1);
869
2520
  }
870
2521
  }
@@ -882,7 +2533,9 @@ async function main() {
882
2533
  const { code, tenant } = parseScriptArgs(args.slice(1));
883
2534
  if (!code) {
884
2535
  console.error('[#corsair]: Usage: corsair script --code "<js>"');
885
- console.error(`[#corsair]: Example: corsair script --code "const r = await corsair.slack.channels.list(); return r.channels.find(c => c.name === 'general')?.id"`);
2536
+ console.error(
2537
+ `[#corsair]: Example: corsair script --code "const r = await corsair.slack.channels.list(); return r.channels.find(c => c.name === 'general')?.id"`
2538
+ );
886
2539
  process.exit(1);
887
2540
  }
888
2541
  const instance = await getCorsairInstance({ cwd });
@@ -906,13 +2559,17 @@ async function main() {
906
2559
  const schemaPath = args[1];
907
2560
  if (!schemaPath) {
908
2561
  console.error("[#corsair]: Usage: corsair schema <path>");
909
- console.error("[#corsair]: Example: corsair schema slack.api.messages.post");
2562
+ console.error(
2563
+ "[#corsair]: Example: corsair schema slack.api.messages.post"
2564
+ );
910
2565
  process.exit(1);
911
2566
  }
912
2567
  const instance = await getCorsairInstance({ cwd });
913
2568
  const corsair = instance;
914
2569
  if (typeof corsair.get_schema !== "function") {
915
- console.error("[#corsair]: get_schema not available on this Corsair instance.");
2570
+ console.error(
2571
+ "[#corsair]: get_schema not available on this Corsair instance."
2572
+ );
916
2573
  process.exit(1);
917
2574
  }
918
2575
  const result = corsair.get_schema(schemaPath);