@corsair-dev/cli 0.1.7 → 0.1.8

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.
@@ -1 +1 @@
1
- {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../auth.ts"],"names":[],"mappings":"AAucA,wBAAsB,OAAO,CAAC,EAC7B,GAAG,EACH,QAAQ,EAAE,WAAW,EACrB,QAAQ,EAAE,WAAW,EACrB,IAAI,EAAE,OAAO,EACb,WAAW,EAAE,eAAuB,GACpC,EAAE;IACF,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,uDAAuD;IACvD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,uEAAuE;IACvE,WAAW,CAAC,EAAE,OAAO,CAAC;CACtB,GAAG,OAAO,CAAC,IAAI,CAAC,CAmDhB"}
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../auth.ts"],"names":[],"mappings":"AAggBA,wBAAsB,OAAO,CAAC,EAC7B,GAAG,EACH,QAAQ,EAAE,WAAW,EACrB,QAAQ,EAAE,WAAW,EACrB,IAAI,EAAE,OAAO,EACb,WAAW,EAAE,eAAuB,GACpC,EAAE;IACF,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,uDAAuD;IACvD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,uEAAuE;IACvE,WAAW,CAAC,EAAE,OAAO,CAAC;CACtB,GAAG,OAAO,CAAC,IAAI,CAAC,CAmDhB"}
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 text4 = fs.readFileSync(tsConfigPath, "utf-8");
30
+ return JSON.parse(stripJsonComments(text4));
31
31
  } catch (error) {
32
32
  throw error;
33
33
  }
@@ -227,21 +227,19 @@ async function oauthGetUrl(database, plugin, kek, tenantId) {
227
227
  ...oauthCfg.authParams
228
228
  };
229
229
  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);
230
+ const localhostPortMatch = redirectUri.match(/^https?:\/\/(?:localhost|127\.0\.0\.1):(\d+)/);
231
+ const localhostPort = localhostPortMatch?.[1] ? parseInt(localhostPortMatch[1], 10) : null;
232
+ if (localhostPort) {
233
+ out({ status: "pending_oauth", authUrl, redirectUri, plugin: plugin.id, tenant: tenantId, note: "Open authUrl in a browser. Tokens will be saved automatically once authorized." });
234
+ let code;
235
+ try {
236
+ code = await waitForOAuthCode(localhostPort);
237
+ } catch (err) {
238
+ out({ error: `Authorization failed: ${err instanceof Error ? err.message : String(err)}` });
243
239
  return;
244
240
  }
241
+ await oauthExchangeCode(database, plugin, kek, tenantId, code, redirectUri, clientId, clientSecret, oauthCfg);
242
+ return;
245
243
  }
246
244
  out({ status: "needs_code", authUrl, redirectUri, plugin: plugin.id, tenant: tenantId, note: "Open authUrl, complete auth, then run: corsair auth --plugin=<id> --code=CODE" });
247
245
  }
@@ -421,6 +419,1234 @@ var init_auth = __esm({
421
419
  }
422
420
  });
423
421
 
422
+ // watch-renew.ts
423
+ var watch_renew_exports = {};
424
+ __export(watch_renew_exports, {
425
+ runTeamsSubscribe: () => runTeamsSubscribe,
426
+ runWatchRenew: () => runWatchRenew
427
+ });
428
+ import { execSync } from "child_process";
429
+ import * as crypto from "crypto";
430
+ import * as p from "@clack/prompts";
431
+ import {
432
+ CORSAIR_INTERNAL as CORSAIR_INTERNAL2,
433
+ createAccountKeyManager as createAccountKeyManager2,
434
+ createIntegrationKeyManager as createIntegrationKeyManager2
435
+ } from "corsair/core";
436
+ function buildTeamsResource(resourceType, ids) {
437
+ switch (resourceType) {
438
+ case "channelMessage":
439
+ return `teams/${ids.teamId}/channels/${ids.channelId}/messages`;
440
+ case "chatMessage":
441
+ return `chats/${ids.chatId}/messages`;
442
+ case "channelCreated":
443
+ return `teams/${ids.teamId}/channels`;
444
+ case "membershipChanged":
445
+ return `teams/${ids.teamId}/members`;
446
+ }
447
+ }
448
+ async function createTeamsSubscription(accessToken, notificationUrl, resource, clientState, expiryMinutes) {
449
+ const expirationDateTime = new Date(Date.now() + expiryMinutes * 60 * 1e3).toISOString();
450
+ const response = await fetch(`${GRAPH_API_BASE}/subscriptions`, {
451
+ method: "POST",
452
+ headers: {
453
+ Authorization: `Bearer ${accessToken}`,
454
+ "Content-Type": "application/json"
455
+ },
456
+ body: JSON.stringify({
457
+ changeType: "created,updated,deleted",
458
+ notificationUrl,
459
+ resource,
460
+ expirationDateTime,
461
+ clientState
462
+ })
463
+ });
464
+ if (!response.ok) {
465
+ const error = await response.text();
466
+ throw new Error(`Graph subscription failed: ${error}`);
467
+ }
468
+ return response.json();
469
+ }
470
+ async function runTeamsSubscribe({ cwd }) {
471
+ p.intro("Corsair \u2014 Microsoft Teams Webhook Subscribe");
472
+ const spin = p.spinner();
473
+ spin.start("Loading corsair instance...");
474
+ let internal;
475
+ try {
476
+ internal = await extractInternalConfig2(cwd);
477
+ } catch (error) {
478
+ spin.stop("Failed to load.");
479
+ p.log.error(error instanceof Error ? error.message : String(error));
480
+ p.outro("");
481
+ process.exit(1);
482
+ }
483
+ const { plugins, database, kek } = internal;
484
+ if (!database) {
485
+ spin.stop("Failed.");
486
+ p.log.error("No database adapter configured.");
487
+ p.outro("");
488
+ process.exit(1);
489
+ }
490
+ const teamsPlugin = plugins.find((pl) => pl.id === "teams");
491
+ if (!teamsPlugin) {
492
+ spin.stop("Teams plugin not found.");
493
+ p.log.error("Add the teams plugin to your corsair instance first.");
494
+ p.outro("");
495
+ process.exit(1);
496
+ }
497
+ spin.stop("Loaded.");
498
+ const tenantId = await p.text({
499
+ message: "Enter tenant ID:",
500
+ defaultValue: "default",
501
+ placeholder: "default"
502
+ });
503
+ if (p.isCancel(tenantId)) {
504
+ p.cancel("Operation cancelled.");
505
+ process.exit(0);
506
+ }
507
+ const credSpin = p.spinner();
508
+ credSpin.start("Fetching Teams credentials...");
509
+ const accountKm = createAccountKeyManager2({
510
+ authType: "oauth_2",
511
+ integrationName: "teams",
512
+ tenantId,
513
+ kek,
514
+ database,
515
+ extraAccountFields: ["one"]
516
+ });
517
+ const accessToken = await accountKm.get_access_token();
518
+ if (!accessToken) {
519
+ credSpin.stop("Missing credentials.");
520
+ p.log.error("Access token not set. Run: pnpm corsair auth --plugin=teams");
521
+ p.outro("");
522
+ process.exit(1);
523
+ }
524
+ credSpin.stop("Credentials loaded.");
525
+ const webhookUrl = await p.text({
526
+ message: "Enter your public webhook URL (ngrok or production):",
527
+ placeholder: "https://abc123.ngrok-free.app/api/webhook",
528
+ validate: (v) => {
529
+ if (!v || v.trim().length === 0) return "Webhook URL is required";
530
+ if (!v.startsWith("https://")) return "URL must start with https:// (Microsoft Graph requires HTTPS)";
531
+ }
532
+ });
533
+ if (p.isCancel(webhookUrl)) {
534
+ p.cancel("Operation cancelled.");
535
+ process.exit(0);
536
+ }
537
+ const resourceType = await p.select({
538
+ message: "Select resource type to subscribe to:",
539
+ options: [
540
+ { value: "channelMessage", label: "Channel Messages (teams/{id}/channels/{id}/messages)" },
541
+ { value: "chatMessage", label: "Chat Messages (chats/{id}/messages)" },
542
+ { value: "channelCreated", label: "Channel Created (teams/{id}/channels)" },
543
+ { value: "membershipChanged", label: "Membership Changed (teams/{id}/members)" }
544
+ ]
545
+ });
546
+ if (p.isCancel(resourceType)) {
547
+ p.cancel("Operation cancelled.");
548
+ process.exit(0);
549
+ }
550
+ const ids = {};
551
+ if (resourceType === "chatMessage") {
552
+ const chatId = await p.text({
553
+ message: "Enter chat ID:",
554
+ placeholder: "19:abc123@thread.v2",
555
+ validate: (v) => {
556
+ if (!v || !v.trim()) return "Chat ID is required";
557
+ }
558
+ });
559
+ if (p.isCancel(chatId)) {
560
+ p.cancel("Operation cancelled.");
561
+ process.exit(0);
562
+ }
563
+ ids.chatId = chatId;
564
+ } else {
565
+ const teamId = await p.text({
566
+ message: "Enter team ID:",
567
+ placeholder: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
568
+ validate: (v) => {
569
+ if (!v || !v.trim()) return "Team ID is required";
570
+ }
571
+ });
572
+ if (p.isCancel(teamId)) {
573
+ p.cancel("Operation cancelled.");
574
+ process.exit(0);
575
+ }
576
+ ids.teamId = teamId;
577
+ if (resourceType === "channelMessage") {
578
+ const channelId = await p.text({
579
+ message: "Enter channel ID:",
580
+ placeholder: "19:abc123@thread.skype",
581
+ validate: (v) => {
582
+ if (!v || !v.trim()) return "Channel ID is required";
583
+ }
584
+ });
585
+ if (p.isCancel(channelId)) {
586
+ p.cancel("Operation cancelled.");
587
+ process.exit(0);
588
+ }
589
+ ids.channelId = channelId;
590
+ }
591
+ }
592
+ const autoSecret = crypto.randomBytes(16).toString("hex");
593
+ const clientState = await p.text({
594
+ message: "Enter a clientState secret (used to verify webhook payloads):",
595
+ defaultValue: autoSecret,
596
+ placeholder: autoSecret
597
+ });
598
+ if (p.isCancel(clientState)) {
599
+ p.cancel("Operation cancelled.");
600
+ process.exit(0);
601
+ }
602
+ const resource = buildTeamsResource(resourceType, ids);
603
+ const expiryMinutes = TEAMS_MAX_EXPIRY_MINUTES[resourceType];
604
+ const subSpin = p.spinner();
605
+ subSpin.start("Creating Microsoft Graph subscription...");
606
+ let subscription;
607
+ try {
608
+ subscription = await createTeamsSubscription(
609
+ accessToken,
610
+ webhookUrl,
611
+ resource,
612
+ clientState,
613
+ expiryMinutes
614
+ );
615
+ } catch (error) {
616
+ subSpin.stop("Failed.");
617
+ p.log.error(error instanceof Error ? error.message : String(error));
618
+ p.outro("");
619
+ process.exit(1);
620
+ }
621
+ subSpin.stop("Subscription created.");
622
+ const saveSpin = p.spinner();
623
+ saveSpin.start("Saving webhook secret...");
624
+ await accountKm.set_webhook_signature(clientState);
625
+ saveSpin.stop("Webhook secret saved.");
626
+ p.note(
627
+ `Subscription ID: ${subscription.id}
628
+ Resource: ${resource}
629
+ Expires: ${subscription.expirationDateTime}
630
+ ClientState: ${clientState}
631
+ Webhook URL: ${webhookUrl}
632
+
633
+ Note: Teams subscriptions expire. Re-run this command to renew.`,
634
+ "Teams Subscription Created"
635
+ );
636
+ p.outro("Done!");
637
+ }
638
+ async function extractInternalConfig2(cwd) {
639
+ const instance = await getCorsairInstance({ cwd, shouldThrowOnError: true });
640
+ const internal = instance[CORSAIR_INTERNAL2];
641
+ if (!internal) {
642
+ throw new Error(
643
+ "Could not read internal config from Corsair instance. Make sure you are using the latest version of corsair."
644
+ );
645
+ }
646
+ return internal;
647
+ }
648
+ async function refreshAccessToken(clientId, clientSecret, refreshToken2) {
649
+ const response = await fetch("https://oauth2.googleapis.com/token", {
650
+ method: "POST",
651
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
652
+ body: new URLSearchParams({
653
+ client_id: clientId,
654
+ client_secret: clientSecret,
655
+ refresh_token: refreshToken2,
656
+ grant_type: "refresh_token"
657
+ })
658
+ });
659
+ if (!response.ok) {
660
+ const error = await response.text();
661
+ throw new Error(`Failed to refresh access token: ${error}`);
662
+ }
663
+ const data = await response.json();
664
+ return data.access_token;
665
+ }
666
+ async function renewGmailWatch(accessToken, topicName) {
667
+ const watchSpin = p.spinner();
668
+ watchSpin.start("Starting Gmail watch...");
669
+ const response = await fetch(`${GMAIL_API_BASE}/users/me/watch`, {
670
+ method: "POST",
671
+ headers: {
672
+ Authorization: `Bearer ${accessToken}`,
673
+ "Content-Type": "application/json"
674
+ },
675
+ body: JSON.stringify({
676
+ topicName,
677
+ labelIds: ["INBOX"]
678
+ })
679
+ });
680
+ if (!response.ok) {
681
+ const error = await response.text();
682
+ watchSpin.stop("Failed.");
683
+ p.log.error(`Gmail watch failed: ${error}`);
684
+ p.outro("");
685
+ process.exit(1);
686
+ }
687
+ const data = await response.json();
688
+ watchSpin.stop("Watch started.");
689
+ p.note(
690
+ `History ID: ${data.historyId}
691
+ Expiration: ${new Date(Number(data.expiration)).toISOString()}`,
692
+ "Watch Response"
693
+ );
694
+ }
695
+ async function renewDriveWatch(accessToken, webhookUrl) {
696
+ const watchSpin = p.spinner();
697
+ watchSpin.start("Getting start page token...");
698
+ const startPageTokenRes = await fetch(
699
+ `${DRIVE_API_BASE}/changes/startPageToken`,
700
+ {
701
+ headers: { Authorization: `Bearer ${accessToken}` }
702
+ }
703
+ );
704
+ if (!startPageTokenRes.ok) {
705
+ const error = await startPageTokenRes.text();
706
+ watchSpin.stop("Failed.");
707
+ p.log.error(`Failed to get start page token: ${error}`);
708
+ p.outro("");
709
+ process.exit(1);
710
+ }
711
+ const startPageTokenData = await startPageTokenRes.json();
712
+ watchSpin.message("Starting Drive watch...");
713
+ const channelId = crypto.randomUUID();
714
+ const watchRes = await fetch(
715
+ `${DRIVE_API_BASE}/changes/watch?pageToken=${startPageTokenData.startPageToken}`,
716
+ {
717
+ method: "POST",
718
+ headers: {
719
+ Authorization: `Bearer ${accessToken}`,
720
+ "Content-Type": "application/json"
721
+ },
722
+ body: JSON.stringify({
723
+ id: channelId,
724
+ type: "web_hook",
725
+ address: webhookUrl
726
+ })
727
+ }
728
+ );
729
+ if (!watchRes.ok) {
730
+ const error = await watchRes.text();
731
+ watchSpin.stop("Failed.");
732
+ p.log.error(`Drive watch failed: ${error}`);
733
+ p.outro("");
734
+ process.exit(1);
735
+ }
736
+ const data = await watchRes.json();
737
+ watchSpin.stop("Watch started.");
738
+ p.note(
739
+ `Channel ID: ${channelId}
740
+ Resource ID: ${data.resourceId}
741
+ Start Page Token: ${startPageTokenData.startPageToken}
742
+ Expiration: ${new Date(Number(data.expiration)).toISOString()}`,
743
+ "Watch Response"
744
+ );
745
+ }
746
+ async function renewCalendarWatch(accessToken, webhookUrl, calendarId) {
747
+ const watchSpin = p.spinner();
748
+ watchSpin.start("Starting Calendar watch...");
749
+ const channelId = crypto.randomUUID();
750
+ const watchRes = await fetch(
751
+ `${CALENDAR_API_BASE}/calendars/${encodeURIComponent(calendarId)}/events/watch`,
752
+ {
753
+ method: "POST",
754
+ headers: {
755
+ Authorization: `Bearer ${accessToken}`,
756
+ "Content-Type": "application/json"
757
+ },
758
+ body: JSON.stringify({
759
+ id: channelId,
760
+ type: "web_hook",
761
+ address: webhookUrl
762
+ })
763
+ }
764
+ );
765
+ if (!watchRes.ok) {
766
+ const error = await watchRes.text();
767
+ watchSpin.stop("Failed.");
768
+ p.log.error(`Calendar watch failed: ${error}`);
769
+ p.outro("");
770
+ process.exit(1);
771
+ }
772
+ const data = await watchRes.json();
773
+ watchSpin.stop("Watch started.");
774
+ p.note(
775
+ `Channel ID: ${channelId}
776
+ Resource ID: ${data.resourceId}
777
+ Expiration: ${new Date(Number(data.expiration)).toISOString()}`,
778
+ "Watch Response"
779
+ );
780
+ }
781
+ function copyToClipboard(text4) {
782
+ try {
783
+ const platform = process.platform;
784
+ if (platform === "darwin") {
785
+ execSync("pbcopy", { input: text4 });
786
+ return true;
787
+ } else if (platform === "linux") {
788
+ try {
789
+ execSync("xclip -selection clipboard", { input: text4 });
790
+ return true;
791
+ } catch {
792
+ try {
793
+ execSync("xsel --clipboard --input", { input: text4 });
794
+ return true;
795
+ } catch {
796
+ return false;
797
+ }
798
+ }
799
+ } else if (platform === "win32") {
800
+ execSync("clip", { input: text4 });
801
+ return true;
802
+ }
803
+ return false;
804
+ } catch {
805
+ return false;
806
+ }
807
+ }
808
+ async function renewSheetsWatch(webhookUrl) {
809
+ const appsScriptCode = `var WEBHOOK_URL = "${webhookUrl}";
810
+
811
+ function onEditTrigger(e) {
812
+ if (!e || !e.range) return;
813
+
814
+ var sheet = e.range.getSheet();
815
+ var payload = {
816
+ spreadsheetId: e.source.getId(),
817
+ sheetName: sheet.getName(),
818
+ range: e.range.getA1Notation(),
819
+ values: e.range.getValues(),
820
+ eventType: "rangeUpdated",
821
+ timestamp: new Date().toISOString()
822
+ };
823
+
824
+ UrlFetchApp.fetch(WEBHOOK_URL, {
825
+ method: "post",
826
+ contentType: "application/json",
827
+ payload: JSON.stringify(payload)
828
+ });
829
+ }
830
+
831
+ function onChangeTrigger(e) {
832
+ if (!e) return;
833
+
834
+ var ss = SpreadsheetApp.getActiveSpreadsheet();
835
+ var sheet = ss.getActiveSheet();
836
+ var lastRow = sheet.getLastRow();
837
+ var lastCol = sheet.getLastColumn();
838
+ if (lastRow === 0 || lastCol === 0) return;
839
+
840
+ var values = sheet.getRange(lastRow, 1, 1, lastCol).getValues();
841
+
842
+ var payload = {
843
+ spreadsheetId: ss.getId(),
844
+ sheetName: sheet.getName(),
845
+ range: "A" + lastRow + ":" + String.fromCharCode(64 + lastCol) + lastRow,
846
+ values: values,
847
+ eventType: "rangeUpdated",
848
+ timestamp: new Date().toISOString()
849
+ };
850
+
851
+ UrlFetchApp.fetch(WEBHOOK_URL, {
852
+ method: "post",
853
+ contentType: "application/json",
854
+ payload: JSON.stringify(payload)
855
+ });
856
+ }
857
+
858
+ function createTriggers() {
859
+ var ss = SpreadsheetApp.getActiveSpreadsheet();
860
+
861
+ ScriptApp.newTrigger("onEditTrigger").forSpreadsheet(ss).onEdit().create();
862
+ ScriptApp.newTrigger("onChangeTrigger").forSpreadsheet(ss).onChange().create();
863
+
864
+ Logger.log("Triggers created successfully!");
865
+ }
866
+
867
+ function removeTriggers() {
868
+ var triggers = ScriptApp.getProjectTriggers();
869
+ triggers.forEach(function(trigger) {
870
+ ScriptApp.deleteTrigger(trigger);
871
+ });
872
+ Logger.log("All triggers removed.");
873
+ }`;
874
+ p.log.info("Google Sheets does not have a native watch API.");
875
+ p.log.info(
876
+ "Instead, you need to set up Google Apps Script triggers in your spreadsheet."
877
+ );
878
+ p.log.info("");
879
+ const shouldCopy = await p.confirm({
880
+ message: "Copy Apps Script code to clipboard?",
881
+ initialValue: true
882
+ });
883
+ let copied = false;
884
+ if (shouldCopy) {
885
+ copied = copyToClipboard(appsScriptCode);
886
+ if (copied) {
887
+ p.log.success("Apps Script code copied to clipboard!");
888
+ } else {
889
+ p.log.warn("Failed to copy to clipboard. Code will be displayed below.");
890
+ }
891
+ }
892
+ p.log.info("");
893
+ p.log.info("Setup Instructions:");
894
+ p.log.info("1. Open your Google Sheet");
895
+ p.log.info("2. Go to Extensions > Apps Script");
896
+ p.log.info("3. Paste the code into the script editor");
897
+ p.log.info(
898
+ '4. Run the "createTriggers" function once to install the triggers'
899
+ );
900
+ p.log.info("5. Authorize the script when prompted");
901
+ p.log.info("");
902
+ if (!copied) {
903
+ p.log.info("Apps Script Code:");
904
+ p.log.info("");
905
+ p.log.info(appsScriptCode);
906
+ p.log.info("");
907
+ }
908
+ p.note(
909
+ `Webhook URL: ${webhookUrl}
910
+
911
+ The Apps Script code ${copied ? "has been copied to your clipboard" : "is displayed above"}. Paste it into your Google Sheet's Apps Script editor.`,
912
+ "Google Sheets Setup"
913
+ );
914
+ }
915
+ async function runWatchRenew({ cwd }) {
916
+ p.intro("Corsair \u2014 Google Watch Renewal");
917
+ const spin = p.spinner();
918
+ spin.start("Loading corsair instance...");
919
+ let internal;
920
+ try {
921
+ internal = await extractInternalConfig2(cwd);
922
+ } catch (error) {
923
+ spin.stop("Failed to load.");
924
+ p.log.error(error instanceof Error ? error.message : String(error));
925
+ p.outro("");
926
+ process.exit(1);
927
+ }
928
+ const { plugins, database, kek } = internal;
929
+ if (!database) {
930
+ spin.stop("Failed.");
931
+ p.log.error("No database adapter configured.");
932
+ p.outro("");
933
+ process.exit(1);
934
+ }
935
+ const googlePlugins = plugins.filter((pl) => {
936
+ const opts = pl.options;
937
+ return opts?.authType === "oauth_2" && GOOGLE_PLUGINS.includes(pl.id);
938
+ });
939
+ if (googlePlugins.length === 0) {
940
+ spin.stop("No Google OAuth2 plugins found.");
941
+ p.outro("");
942
+ process.exit(1);
943
+ }
944
+ spin.stop(
945
+ `Loaded. Found ${googlePlugins.length} Google plugin${googlePlugins.length === 1 ? "" : "s"}.`
946
+ );
947
+ const pluginId = await p.select({
948
+ message: "Select a Google integration:",
949
+ options: googlePlugins.map((pl) => ({
950
+ value: pl.id,
951
+ label: pl.id
952
+ }))
953
+ });
954
+ if (p.isCancel(pluginId)) {
955
+ p.cancel("Operation cancelled.");
956
+ process.exit(0);
957
+ }
958
+ const pluginType = pluginId;
959
+ if (pluginType === "googlesheets") {
960
+ const webhookUrl = await p.text({
961
+ message: "Enter webhook URL:",
962
+ placeholder: "https://example.com/api/webhook",
963
+ validate: (v) => {
964
+ if (!v || v.trim().length === 0) return "Webhook URL is required";
965
+ if (!v.startsWith("http://") && !v.startsWith("https://")) {
966
+ return "Webhook URL must start with http:// or https://";
967
+ }
968
+ }
969
+ });
970
+ if (p.isCancel(webhookUrl)) {
971
+ p.cancel("Operation cancelled.");
972
+ process.exit(0);
973
+ }
974
+ await renewSheetsWatch(webhookUrl);
975
+ p.outro("Done!");
976
+ return;
977
+ }
978
+ const tenantId = await p.text({
979
+ message: "Enter tenant ID:",
980
+ defaultValue: "default",
981
+ placeholder: "default"
982
+ });
983
+ if (p.isCancel(tenantId)) {
984
+ p.cancel("Operation cancelled.");
985
+ process.exit(0);
986
+ }
987
+ const credSpin = p.spinner();
988
+ credSpin.start("Fetching credentials...");
989
+ try {
990
+ const integrationKm = createIntegrationKeyManager2({
991
+ authType: "oauth_2",
992
+ integrationName: pluginId,
993
+ kek,
994
+ database
995
+ });
996
+ const accountKm = createAccountKeyManager2({
997
+ authType: "oauth_2",
998
+ integrationName: pluginId,
999
+ tenantId,
1000
+ kek,
1001
+ database
1002
+ });
1003
+ const clientId = await integrationKm.get_client_id();
1004
+ const clientSecret = await integrationKm.get_client_secret();
1005
+ const refreshToken2 = await accountKm.get_refresh_token();
1006
+ if (!clientId || !clientSecret || !refreshToken2) {
1007
+ credSpin.stop("Missing credentials.");
1008
+ p.log.error(
1009
+ 'Client ID, Client Secret, and Refresh Token are required. Use "corsair auth" to set them.'
1010
+ );
1011
+ p.outro("");
1012
+ process.exit(1);
1013
+ }
1014
+ const accessToken = await refreshAccessToken(
1015
+ clientId,
1016
+ clientSecret,
1017
+ refreshToken2
1018
+ );
1019
+ credSpin.stop("Credentials loaded.");
1020
+ if (pluginType === "gmail") {
1021
+ const topicName = await p.text({
1022
+ message: "Enter Pub/Sub topic name:",
1023
+ placeholder: "projects/my-project/topics/my-topic",
1024
+ validate: (v) => {
1025
+ if (!v || v.trim().length === 0) return "Topic name is required";
1026
+ }
1027
+ });
1028
+ if (p.isCancel(topicName)) {
1029
+ p.cancel("Operation cancelled.");
1030
+ process.exit(0);
1031
+ }
1032
+ await renewGmailWatch(accessToken, topicName);
1033
+ } else if (pluginType === "googledrive") {
1034
+ const webhookUrl = await p.text({
1035
+ message: "Enter webhook URL:",
1036
+ placeholder: "https://example.com/api/webhook",
1037
+ validate: (v) => {
1038
+ if (!v || v.trim().length === 0) return "Webhook URL is required";
1039
+ }
1040
+ });
1041
+ if (p.isCancel(webhookUrl)) {
1042
+ p.cancel("Operation cancelled.");
1043
+ process.exit(0);
1044
+ }
1045
+ await renewDriveWatch(accessToken, webhookUrl);
1046
+ } else if (pluginType === "googlecalendar") {
1047
+ const webhookUrl = await p.text({
1048
+ message: "Enter webhook URL:",
1049
+ placeholder: "https://example.com/api/webhook",
1050
+ validate: (v) => {
1051
+ if (!v || v.trim().length === 0) return "Webhook URL is required";
1052
+ }
1053
+ });
1054
+ if (p.isCancel(webhookUrl)) {
1055
+ p.cancel("Operation cancelled.");
1056
+ process.exit(0);
1057
+ }
1058
+ const calendarId = await p.text({
1059
+ message: "Enter calendar ID:",
1060
+ defaultValue: "primary",
1061
+ placeholder: "primary"
1062
+ });
1063
+ if (p.isCancel(calendarId)) {
1064
+ p.cancel("Operation cancelled.");
1065
+ process.exit(0);
1066
+ }
1067
+ await renewCalendarWatch(
1068
+ accessToken,
1069
+ webhookUrl,
1070
+ calendarId
1071
+ );
1072
+ } else {
1073
+ p.log.error(`Unsupported Google plugin: ${pluginType}`);
1074
+ process.exit(1);
1075
+ }
1076
+ } catch (error) {
1077
+ credSpin.stop("Failed.");
1078
+ p.log.error(
1079
+ `Error: ${error instanceof Error ? error.message : String(error)}`
1080
+ );
1081
+ process.exit(1);
1082
+ }
1083
+ p.outro("Done!");
1084
+ }
1085
+ var GMAIL_API_BASE, DRIVE_API_BASE, CALENDAR_API_BASE, GRAPH_API_BASE, GOOGLE_PLUGINS, TEAMS_MAX_EXPIRY_MINUTES;
1086
+ var init_watch_renew = __esm({
1087
+ "watch-renew.ts"() {
1088
+ "use strict";
1089
+ init_index();
1090
+ GMAIL_API_BASE = "https://gmail.googleapis.com/gmail/v1";
1091
+ DRIVE_API_BASE = "https://www.googleapis.com/drive/v3";
1092
+ CALENDAR_API_BASE = "https://www.googleapis.com/calendar/v3";
1093
+ GRAPH_API_BASE = "https://graph.microsoft.com/v1.0";
1094
+ GOOGLE_PLUGINS = [
1095
+ "gmail",
1096
+ "googledrive",
1097
+ "googlecalendar",
1098
+ "googlesheets"
1099
+ ];
1100
+ TEAMS_MAX_EXPIRY_MINUTES = {
1101
+ channelMessage: 60,
1102
+ chatMessage: 60,
1103
+ channelCreated: 4230,
1104
+ membershipChanged: 60
1105
+ };
1106
+ }
1107
+ });
1108
+
1109
+ // sharepoint-subscribe.ts
1110
+ var sharepoint_subscribe_exports = {};
1111
+ __export(sharepoint_subscribe_exports, {
1112
+ runSharepointSubscribe: () => runSharepointSubscribe
1113
+ });
1114
+ import * as crypto2 from "crypto";
1115
+ import * as p2 from "@clack/prompts";
1116
+ import {
1117
+ CORSAIR_INTERNAL as CORSAIR_INTERNAL3,
1118
+ createAccountKeyManager as createAccountKeyManager3,
1119
+ createIntegrationKeyManager as createIntegrationKeyManager3
1120
+ } from "corsair/core";
1121
+ async function refreshToken(clientId, clientSecret, refreshToken2) {
1122
+ const response = await fetch(MICROSOFT_TOKEN_URL, {
1123
+ method: "POST",
1124
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
1125
+ body: new URLSearchParams({
1126
+ client_id: clientId,
1127
+ client_secret: clientSecret,
1128
+ refresh_token: refreshToken2,
1129
+ grant_type: "refresh_token"
1130
+ })
1131
+ });
1132
+ if (!response.ok) {
1133
+ const error = await response.text();
1134
+ throw new Error(`Token refresh failed: ${error}`);
1135
+ }
1136
+ return response.json();
1137
+ }
1138
+ async function extractInternalConfig3(cwd) {
1139
+ const instance = await getCorsairInstance({ cwd, shouldThrowOnError: true });
1140
+ const internal = instance[CORSAIR_INTERNAL3];
1141
+ if (!internal) {
1142
+ throw new Error(
1143
+ "Could not read internal config from Corsair instance. Make sure you are using the latest version of corsair."
1144
+ );
1145
+ }
1146
+ return internal;
1147
+ }
1148
+ function buildSiteUrl(siteId, subpath) {
1149
+ const isHostnamePath = siteId.includes(":") && !siteId.includes(",");
1150
+ return isHostnamePath ? `${GRAPH_API_BASE2}/sites/${siteId}:/${subpath}` : `${GRAPH_API_BASE2}/sites/${siteId}/${subpath}`;
1151
+ }
1152
+ async function fetchSiteLists(accessToken, siteId) {
1153
+ const response = await fetch(
1154
+ `${buildSiteUrl(siteId, "lists")}?$select=id,displayName,webUrl`,
1155
+ {
1156
+ headers: { Authorization: `Bearer ${accessToken}` }
1157
+ }
1158
+ );
1159
+ if (!response.ok) {
1160
+ const error = await response.text();
1161
+ throw new Error(`Failed to fetch site lists: ${error}`);
1162
+ }
1163
+ const data = await response.json();
1164
+ return data.value ?? [];
1165
+ }
1166
+ async function createSharepointSubscription(accessToken, siteId, listId, notificationUrl, clientState, expiryDays) {
1167
+ const expirationDateTime = new Date(
1168
+ Date.now() + expiryDays * 24 * 60 * 60 * 1e3
1169
+ ).toISOString();
1170
+ const response = await fetch(
1171
+ buildSiteUrl(siteId, `lists/${encodeURIComponent(listId)}/subscriptions`),
1172
+ {
1173
+ method: "POST",
1174
+ headers: {
1175
+ Authorization: `Bearer ${accessToken}`,
1176
+ "Content-Type": "application/json"
1177
+ },
1178
+ body: JSON.stringify({
1179
+ notificationUrl,
1180
+ expirationDateTime,
1181
+ clientState
1182
+ })
1183
+ }
1184
+ );
1185
+ if (!response.ok) {
1186
+ const error = await response.text();
1187
+ throw new Error(`SharePoint subscription failed: ${error}`);
1188
+ }
1189
+ return response.json();
1190
+ }
1191
+ async function runSharepointSubscribe({ cwd }) {
1192
+ p2.intro("Corsair \u2014 SharePoint Webhook Subscribe");
1193
+ const spin = p2.spinner();
1194
+ spin.start("Loading corsair instance...");
1195
+ let internal;
1196
+ try {
1197
+ internal = await extractInternalConfig3(cwd);
1198
+ } catch (error) {
1199
+ spin.stop("Failed to load.");
1200
+ p2.log.error(error instanceof Error ? error.message : String(error));
1201
+ p2.outro("");
1202
+ process.exit(1);
1203
+ }
1204
+ const { plugins, database, kek } = internal;
1205
+ if (!database) {
1206
+ spin.stop("Failed.");
1207
+ p2.log.error("No database adapter configured.");
1208
+ p2.outro("");
1209
+ process.exit(1);
1210
+ }
1211
+ const sharepointPlugin = plugins.find((pl) => pl.id === "sharepoint");
1212
+ if (!sharepointPlugin) {
1213
+ spin.stop("SharePoint plugin not found.");
1214
+ p2.log.error("Add the sharepoint plugin to your corsair instance first.");
1215
+ p2.outro("");
1216
+ process.exit(1);
1217
+ }
1218
+ spin.stop("Loaded.");
1219
+ const tenantId = await p2.text({
1220
+ message: "Enter tenant ID:",
1221
+ defaultValue: "default",
1222
+ placeholder: "default"
1223
+ });
1224
+ if (p2.isCancel(tenantId)) {
1225
+ p2.cancel("Operation cancelled.");
1226
+ process.exit(0);
1227
+ }
1228
+ const credSpin = p2.spinner();
1229
+ credSpin.start("Fetching SharePoint credentials...");
1230
+ const integrationKm = createIntegrationKeyManager3({
1231
+ authType: "oauth_2",
1232
+ integrationName: "sharepoint",
1233
+ kek,
1234
+ database
1235
+ });
1236
+ const accountKm = createAccountKeyManager3({
1237
+ authType: "oauth_2",
1238
+ integrationName: "sharepoint",
1239
+ tenantId,
1240
+ kek,
1241
+ database
1242
+ });
1243
+ const [clientId, clientSecret, storedAccessToken, expiresAt, storedRefreshToken] = await Promise.all([
1244
+ integrationKm.get_client_id(),
1245
+ integrationKm.get_client_secret(),
1246
+ accountKm.get_access_token(),
1247
+ accountKm.get_expires_at(),
1248
+ accountKm.get_refresh_token()
1249
+ ]);
1250
+ if (!storedRefreshToken) {
1251
+ credSpin.stop("Missing credentials.");
1252
+ p2.log.error("No refresh token found. Run: pnpm corsair auth --plugin=sharepoint");
1253
+ p2.outro("");
1254
+ process.exit(1);
1255
+ }
1256
+ if (!clientId || !clientSecret) {
1257
+ credSpin.stop("Missing credentials.");
1258
+ p2.log.error("Client ID/Secret not configured. Run: pnpm corsair setup --sharepoint");
1259
+ p2.outro("");
1260
+ process.exit(1);
1261
+ }
1262
+ let accessToken = storedAccessToken;
1263
+ const now = Math.floor(Date.now() / 1e3);
1264
+ const needsRefresh = !accessToken || !expiresAt || Number(expiresAt) <= now + 5 * 60;
1265
+ if (needsRefresh) {
1266
+ credSpin.message("Refreshing access token...");
1267
+ try {
1268
+ const tokenData = await refreshToken(clientId, clientSecret, storedRefreshToken);
1269
+ accessToken = tokenData.access_token;
1270
+ await accountKm.set_access_token(tokenData.access_token);
1271
+ await accountKm.set_expires_at(String(now + tokenData.expires_in));
1272
+ if (tokenData.refresh_token) {
1273
+ await accountKm.set_refresh_token(tokenData.refresh_token);
1274
+ }
1275
+ } catch (error) {
1276
+ credSpin.stop("Failed.");
1277
+ p2.log.error(error instanceof Error ? error.message : String(error));
1278
+ p2.outro("");
1279
+ process.exit(1);
1280
+ }
1281
+ }
1282
+ if (!accessToken) {
1283
+ credSpin.stop("Missing credentials.");
1284
+ p2.log.error("Could not obtain a valid access token. Run: pnpm corsair auth --plugin=sharepoint");
1285
+ p2.outro("");
1286
+ process.exit(1);
1287
+ }
1288
+ credSpin.stop("Credentials loaded.");
1289
+ const pluginOptions = sharepointPlugin.options;
1290
+ const defaultSiteId = pluginOptions?.siteId ?? "";
1291
+ const siteId = await p2.text({
1292
+ message: "Enter SharePoint site ID:",
1293
+ defaultValue: defaultSiteId,
1294
+ placeholder: "corsairdev.sharepoint.com:/sites/MySite or tenant.sharepoint.com,siteGuid,webGuid",
1295
+ validate: (v) => {
1296
+ if (!v || v.trim().length === 0) return "Site ID is required";
1297
+ }
1298
+ });
1299
+ if (p2.isCancel(siteId)) {
1300
+ p2.cancel("Operation cancelled.");
1301
+ process.exit(0);
1302
+ }
1303
+ const listSpin = p2.spinner();
1304
+ listSpin.start("Fetching lists from site...");
1305
+ let siteLists = [];
1306
+ try {
1307
+ siteLists = await fetchSiteLists(accessToken, siteId);
1308
+ listSpin.stop(`Found ${siteLists.length} list${siteLists.length === 1 ? "" : "s"}.`);
1309
+ } catch (error) {
1310
+ listSpin.stop("Could not fetch lists.");
1311
+ p2.log.warn(error instanceof Error ? error.message : String(error));
1312
+ }
1313
+ let listId;
1314
+ if (siteLists.length > 0) {
1315
+ const picked = await p2.select({
1316
+ message: "Select a list to subscribe to:",
1317
+ options: siteLists.map((l) => ({
1318
+ value: l.id,
1319
+ label: l.displayName,
1320
+ hint: l.id
1321
+ }))
1322
+ });
1323
+ if (p2.isCancel(picked)) {
1324
+ p2.cancel("Operation cancelled.");
1325
+ process.exit(0);
1326
+ }
1327
+ listId = picked;
1328
+ } else {
1329
+ const manualId = await p2.text({
1330
+ message: "Enter list ID (GUID) to subscribe to:",
1331
+ placeholder: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
1332
+ validate: (v) => {
1333
+ if (!v || v.trim().length === 0) return "List ID is required";
1334
+ }
1335
+ });
1336
+ if (p2.isCancel(manualId)) {
1337
+ p2.cancel("Operation cancelled.");
1338
+ process.exit(0);
1339
+ }
1340
+ listId = manualId;
1341
+ }
1342
+ const webhookUrl = await p2.text({
1343
+ message: "Enter your public webhook URL (ngrok or production):",
1344
+ placeholder: "https://abc123.ngrok-free.app/api/webhook",
1345
+ validate: (v) => {
1346
+ if (!v || v.trim().length === 0) return "Webhook URL is required";
1347
+ if (!v.startsWith("https://")) return "URL must start with https:// (SharePoint requires HTTPS)";
1348
+ }
1349
+ });
1350
+ if (p2.isCancel(webhookUrl)) {
1351
+ p2.cancel("Operation cancelled.");
1352
+ process.exit(0);
1353
+ }
1354
+ const expiryInput = await p2.text({
1355
+ message: `Enter subscription expiry in days (max ${SHAREPOINT_MAX_EXPIRY_DAYS}):`,
1356
+ defaultValue: String(SHAREPOINT_MAX_EXPIRY_DAYS),
1357
+ placeholder: String(SHAREPOINT_MAX_EXPIRY_DAYS),
1358
+ validate: (v) => {
1359
+ const n = Number(v);
1360
+ if (isNaN(n) || n < 1) return "Must be a positive number";
1361
+ if (n > SHAREPOINT_MAX_EXPIRY_DAYS) return `Max expiry is ${SHAREPOINT_MAX_EXPIRY_DAYS} days`;
1362
+ }
1363
+ });
1364
+ if (p2.isCancel(expiryInput)) {
1365
+ p2.cancel("Operation cancelled.");
1366
+ process.exit(0);
1367
+ }
1368
+ const autoSecret = crypto2.randomBytes(16).toString("hex");
1369
+ const clientState = await p2.text({
1370
+ message: "Enter a clientState secret (used to verify webhook payloads):",
1371
+ defaultValue: autoSecret,
1372
+ placeholder: autoSecret
1373
+ });
1374
+ if (p2.isCancel(clientState)) {
1375
+ p2.cancel("Operation cancelled.");
1376
+ process.exit(0);
1377
+ }
1378
+ const expiryDays = Number(expiryInput);
1379
+ const subSpin = p2.spinner();
1380
+ subSpin.start("Creating SharePoint webhook subscription...");
1381
+ let subscription;
1382
+ try {
1383
+ subscription = await createSharepointSubscription(
1384
+ accessToken,
1385
+ siteId,
1386
+ listId,
1387
+ webhookUrl,
1388
+ clientState,
1389
+ expiryDays
1390
+ );
1391
+ } catch (error) {
1392
+ subSpin.stop("Failed.");
1393
+ p2.log.error(error instanceof Error ? error.message : String(error));
1394
+ p2.outro("");
1395
+ process.exit(1);
1396
+ }
1397
+ subSpin.stop("Subscription created.");
1398
+ const saveSpin = p2.spinner();
1399
+ saveSpin.start("Saving webhook secret...");
1400
+ await accountKm.set_webhook_signature(clientState);
1401
+ saveSpin.stop("Webhook secret saved.");
1402
+ p2.note(
1403
+ `Subscription ID: ${subscription.id}
1404
+ Site ID: ${siteId}
1405
+ List ID: ${listId}
1406
+ Expires: ${subscription.expirationDateTime}
1407
+ ClientState: ${clientState}
1408
+ Webhook URL: ${webhookUrl}
1409
+
1410
+ Note: SharePoint subscriptions expire after ${SHAREPOINT_MAX_EXPIRY_DAYS} days max. Re-run this command to renew.`,
1411
+ "SharePoint Subscription Created"
1412
+ );
1413
+ p2.outro("Done!");
1414
+ }
1415
+ var GRAPH_API_BASE2, MICROSOFT_TOKEN_URL, SHAREPOINT_MAX_EXPIRY_DAYS;
1416
+ var init_sharepoint_subscribe = __esm({
1417
+ "sharepoint-subscribe.ts"() {
1418
+ "use strict";
1419
+ init_index();
1420
+ GRAPH_API_BASE2 = "https://graph.microsoft.com/v1.0";
1421
+ MICROSOFT_TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
1422
+ SHAREPOINT_MAX_EXPIRY_DAYS = 180;
1423
+ }
1424
+ });
1425
+
1426
+ // subscribe-outlook.ts
1427
+ var subscribe_outlook_exports = {};
1428
+ __export(subscribe_outlook_exports, {
1429
+ runOutlookSubscribe: () => runOutlookSubscribe
1430
+ });
1431
+ import * as crypto3 from "crypto";
1432
+ import * as p3 from "@clack/prompts";
1433
+ import { CORSAIR_INTERNAL as CORSAIR_INTERNAL4, createAccountKeyManager as createAccountKeyManager4 } from "corsair/core";
1434
+ async function extractInternalConfig4(cwd) {
1435
+ const instance = await getCorsairInstance({ cwd, shouldThrowOnError: true });
1436
+ const internal = instance[CORSAIR_INTERNAL4];
1437
+ if (!internal) {
1438
+ throw new Error(
1439
+ "Could not read internal config from Corsair instance. Make sure you are using the latest version of corsair."
1440
+ );
1441
+ }
1442
+ return internal;
1443
+ }
1444
+ async function createGraphSubscription(accessToken, notificationUrl, resource, changeType, clientState, expiryMinutes) {
1445
+ const expirationDateTime = new Date(Date.now() + expiryMinutes * 60 * 1e3).toISOString();
1446
+ const response = await fetch(`${GRAPH_API_BASE3}/subscriptions`, {
1447
+ method: "POST",
1448
+ headers: {
1449
+ Authorization: `Bearer ${accessToken}`,
1450
+ "Content-Type": "application/json"
1451
+ },
1452
+ body: JSON.stringify({
1453
+ changeType,
1454
+ notificationUrl,
1455
+ resource,
1456
+ expirationDateTime,
1457
+ clientState
1458
+ })
1459
+ });
1460
+ if (!response.ok) {
1461
+ const error = await response.text();
1462
+ throw new Error(`Graph subscription failed: ${error}`);
1463
+ }
1464
+ return response.json();
1465
+ }
1466
+ async function runOutlookSubscribe({ cwd }) {
1467
+ p3.intro("Corsair \u2014 Outlook Webhook Subscribe");
1468
+ const spin = p3.spinner();
1469
+ spin.start("Loading corsair instance...");
1470
+ let internal;
1471
+ try {
1472
+ internal = await extractInternalConfig4(cwd);
1473
+ } catch (error) {
1474
+ spin.stop("Failed to load.");
1475
+ p3.log.error(error instanceof Error ? error.message : String(error));
1476
+ p3.outro("");
1477
+ process.exit(1);
1478
+ }
1479
+ const { plugins, database, kek } = internal;
1480
+ if (!database) {
1481
+ spin.stop("Failed.");
1482
+ p3.log.error("No database adapter configured.");
1483
+ p3.outro("");
1484
+ process.exit(1);
1485
+ }
1486
+ const outlookPlugin = plugins.find((pl) => pl.id === "outlook");
1487
+ if (!outlookPlugin) {
1488
+ spin.stop("Outlook plugin not found.");
1489
+ p3.log.error("Add the outlook plugin to your corsair instance first.");
1490
+ p3.outro("");
1491
+ process.exit(1);
1492
+ }
1493
+ spin.stop("Loaded.");
1494
+ const tenantId = await p3.text({
1495
+ message: "Enter tenant ID:",
1496
+ defaultValue: "default",
1497
+ placeholder: "default"
1498
+ });
1499
+ if (p3.isCancel(tenantId)) {
1500
+ p3.cancel("Operation cancelled.");
1501
+ process.exit(0);
1502
+ }
1503
+ const credSpin = p3.spinner();
1504
+ credSpin.start("Fetching Outlook credentials...");
1505
+ const accountKm = createAccountKeyManager4({
1506
+ authType: "oauth_2",
1507
+ integrationName: "outlook",
1508
+ tenantId,
1509
+ kek,
1510
+ database,
1511
+ extraAccountFields: ["one"]
1512
+ });
1513
+ const accessToken = await accountKm.get_access_token();
1514
+ if (!accessToken) {
1515
+ credSpin.stop("Missing credentials.");
1516
+ p3.log.error("Access token not set. Run: corsair auth --plugin=outlook");
1517
+ p3.outro("");
1518
+ process.exit(1);
1519
+ }
1520
+ credSpin.stop("Credentials loaded.");
1521
+ const webhookUrl = await p3.text({
1522
+ message: "Enter your public webhook URL (ngrok or production):",
1523
+ placeholder: "https://abc123.ngrok-free.app/api/webhook",
1524
+ validate: (v) => {
1525
+ if (!v || v.trim().length === 0) return "Webhook URL is required";
1526
+ if (!v.startsWith("https://")) return "URL must start with https:// (Microsoft Graph requires HTTPS)";
1527
+ }
1528
+ });
1529
+ if (p3.isCancel(webhookUrl)) {
1530
+ p3.cancel("Operation cancelled.");
1531
+ process.exit(0);
1532
+ }
1533
+ const selected = await p3.multiselect({
1534
+ message: "Select resources to subscribe to:",
1535
+ options: Object.entries(OUTLOOK_RESOURCES).map(
1536
+ ([value, cfg]) => ({
1537
+ value,
1538
+ label: cfg.label,
1539
+ hint: `${cfg.resource} [${cfg.changeType}]`
1540
+ })
1541
+ ),
1542
+ required: true
1543
+ });
1544
+ if (p3.isCancel(selected)) {
1545
+ p3.cancel("Operation cancelled.");
1546
+ process.exit(0);
1547
+ }
1548
+ const autoSecret = crypto3.randomBytes(16).toString("hex");
1549
+ const clientState = await p3.text({
1550
+ message: "Enter a clientState secret (used to verify webhook payloads):",
1551
+ defaultValue: autoSecret,
1552
+ placeholder: autoSecret
1553
+ });
1554
+ if (p3.isCancel(clientState)) {
1555
+ p3.cancel("Operation cancelled.");
1556
+ process.exit(0);
1557
+ }
1558
+ const results = [];
1559
+ let hasError = false;
1560
+ for (const value of selected) {
1561
+ const cfg = OUTLOOK_RESOURCES[value];
1562
+ const subSpin = p3.spinner();
1563
+ subSpin.start(`Creating subscription: ${cfg.label}...`);
1564
+ try {
1565
+ const subscription = await createGraphSubscription(
1566
+ accessToken,
1567
+ webhookUrl,
1568
+ cfg.resource,
1569
+ cfg.changeType,
1570
+ clientState,
1571
+ cfg.expiryMinutes
1572
+ );
1573
+ subSpin.stop(`Created: ${cfg.label}`);
1574
+ results.push(
1575
+ `${cfg.label}
1576
+ ID: ${subscription.id}
1577
+ Expires: ${subscription.expirationDateTime}`
1578
+ );
1579
+ } catch (error) {
1580
+ subSpin.stop(`Failed: ${cfg.label}`);
1581
+ p3.log.error(error instanceof Error ? error.message : String(error));
1582
+ hasError = true;
1583
+ }
1584
+ }
1585
+ if (results.length > 0) {
1586
+ p3.note(results.join("\n\n"), "Subscriptions created");
1587
+ }
1588
+ const saveSpin = p3.spinner();
1589
+ saveSpin.start("Saving webhook secret...");
1590
+ await accountKm.set_webhook_signature(clientState);
1591
+ saveSpin.stop("Webhook secret saved.");
1592
+ if (!hasError) {
1593
+ p3.log.success("Outlook webhook subscriptions set up successfully.");
1594
+ } else {
1595
+ p3.log.warn("Some subscriptions failed. Check errors above.");
1596
+ }
1597
+ p3.note(
1598
+ `ClientState: ${clientState}
1599
+ Webhook URL: ${webhookUrl}
1600
+
1601
+ Note: Outlook subscriptions expire. Re-run this command to renew.`,
1602
+ "Setup complete"
1603
+ );
1604
+ p3.outro("Done!");
1605
+ }
1606
+ var GRAPH_API_BASE3, OUTLOOK_RESOURCES;
1607
+ var init_subscribe_outlook = __esm({
1608
+ "subscribe-outlook.ts"() {
1609
+ "use strict";
1610
+ init_index();
1611
+ GRAPH_API_BASE3 = "https://graph.microsoft.com/v1.0";
1612
+ OUTLOOK_RESOURCES = {
1613
+ inboxMessages: {
1614
+ resource: "me/mailFolders/inbox/messages",
1615
+ changeType: "created",
1616
+ label: "Inbox Messages \u2014 new messages received",
1617
+ expiryMinutes: 4320
1618
+ // 3 days (max for mail)
1619
+ },
1620
+ sentMessages: {
1621
+ resource: "me/mailFolders/sentItems/messages",
1622
+ changeType: "created",
1623
+ label: "Sent Items \u2014 messages sent",
1624
+ expiryMinutes: 4320
1625
+ },
1626
+ newEvents: {
1627
+ resource: "me/events",
1628
+ changeType: "created",
1629
+ label: "Calendar Events \u2014 new events created",
1630
+ expiryMinutes: 4230
1631
+ // max for calendar
1632
+ },
1633
+ eventChanges: {
1634
+ resource: "me/events",
1635
+ changeType: "created,updated,deleted",
1636
+ label: "Calendar Events \u2014 updates & deletions",
1637
+ expiryMinutes: 4230
1638
+ },
1639
+ newContacts: {
1640
+ resource: "me/contacts",
1641
+ changeType: "created",
1642
+ label: "Contacts \u2014 new contacts created",
1643
+ expiryMinutes: 4230
1644
+ // max for contacts
1645
+ }
1646
+ };
1647
+ }
1648
+ });
1649
+
424
1650
  // index.ts
425
1651
  import fs2, { existsSync } from "fs";
426
1652
  import path2 from "path";
@@ -824,6 +2050,31 @@ async function main() {
824
2050
  await runAuth2({ cwd, ...authArgs });
825
2051
  return;
826
2052
  }
2053
+ if (command === "watch-renew") {
2054
+ const { runWatchRenew: runWatchRenew2 } = await Promise.resolve().then(() => (init_watch_renew(), watch_renew_exports));
2055
+ await runWatchRenew2({ cwd });
2056
+ return;
2057
+ }
2058
+ if (command === "sharepoint-subscribe") {
2059
+ const { runSharepointSubscribe: runSharepointSubscribe2 } = await Promise.resolve().then(() => (init_sharepoint_subscribe(), sharepoint_subscribe_exports));
2060
+ await runSharepointSubscribe2({ cwd });
2061
+ }
2062
+ if (command === "subscribe") {
2063
+ const pluginArg = args.slice(1).find((a) => a.startsWith("--plugin="));
2064
+ const pluginId = pluginArg ? pluginArg.slice("--plugin=".length) : void 0;
2065
+ if (pluginId === "outlook") {
2066
+ const { runOutlookSubscribe: runOutlookSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_outlook(), subscribe_outlook_exports));
2067
+ await runOutlookSubscribe2({ cwd });
2068
+ return;
2069
+ }
2070
+ console.error(`[#corsair]: Unknown plugin for subscribe: '${pluginId ?? "(none)"}'. Supported: outlook`);
2071
+ process.exit(1);
2072
+ }
2073
+ if (command === "teams-subscribe") {
2074
+ const { runTeamsSubscribe: runTeamsSubscribe2 } = await Promise.resolve().then(() => (init_watch_renew(), watch_renew_exports));
2075
+ await runTeamsSubscribe2({ cwd });
2076
+ return;
2077
+ }
827
2078
  if (command === "list") {
828
2079
  const { plugin, type } = parseListArgs(args.slice(1));
829
2080
  const instance = await getCorsairInstance({ cwd });
@@ -0,0 +1,4 @@
1
+ export declare function runSharepointSubscribe({ cwd }: {
2
+ cwd: string;
3
+ }): Promise<void>;
4
+ //# sourceMappingURL=sharepoint-subscribe.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sharepoint-subscribe.d.ts","sourceRoot":"","sources":["../sharepoint-subscribe.ts"],"names":[],"mappings":"AAyJA,wBAAsB,sBAAsB,CAAC,EAAE,GAAG,EAAE,EAAE;IAAE,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CA6OpF"}
@@ -0,0 +1,4 @@
1
+ export declare function runOutlookSubscribe({ cwd }: {
2
+ cwd: string;
3
+ }): Promise<void>;
4
+ //# sourceMappingURL=subscribe-outlook.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subscribe-outlook.d.ts","sourceRoot":"","sources":["../subscribe-outlook.ts"],"names":[],"mappings":"AA6GA,wBAAsB,mBAAmB,CAAC,EAAE,GAAG,EAAE,EAAE;IAAE,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAqJjF"}
@@ -1,3 +1,6 @@
1
+ export declare function runTeamsSubscribe({ cwd }: {
2
+ cwd: string;
3
+ }): Promise<void>;
1
4
  export declare function runWatchRenew({ cwd }: {
2
5
  cwd: string;
3
6
  }): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"watch-renew.d.ts","sourceRoot":"","sources":["../watch-renew.ts"],"names":[],"mappings":"AA0WA,wBAAsB,aAAa,CAAC,EAAE,GAAG,EAAE,EAAE;IAAE,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CA4M3E"}
1
+ {"version":3,"file":"watch-renew.d.ts","sourceRoot":"","sources":["../watch-renew.ts"],"names":[],"mappings":"AAmFA,wBAAsB,iBAAiB,CAAC,EAAE,GAAG,EAAE,EAAE;IAAE,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAmK/E;AAqVD,wBAAsB,aAAa,CAAC,EAAE,GAAG,EAAE,EAAE;IAAE,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CA4M3E"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@corsair-dev/cli",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -23,7 +23,7 @@
23
23
  "@clack/prompts": "^1.0.0",
24
24
  "c12": "^3.3.3",
25
25
  "zod": "^3.25.76",
26
- "corsair": "0.1.50"
26
+ "corsair": "0.1.53"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@types/jest": "^29.5.14",