@corsair-dev/cli 0.1.8 → 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 (42) 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 +1644 -1238
  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/{subscribe-outlook.d.ts → microsoft/outlook.d.ts} +1 -1
  23. package/dist/microsoft/outlook.d.ts.map +1 -0
  24. package/dist/{sharepoint-subscribe.d.ts → microsoft/sharepoint.d.ts} +1 -1
  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/sharepoint-subscribe.d.ts.map +0 -1
  40. package/dist/subscribe-outlook.d.ts.map +0 -1
  41. package/dist/watch-renew.d.ts +0 -7
  42. 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 text4 = fs.readFileSync(tsConfigPath, "utf-8");
30
- return JSON.parse(stripJsonComments(text4));
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,124 +38,8 @@ var init_get_tsconfig_info = __esm({
38
38
  }
39
39
  });
40
40
 
41
- // auth.ts
42
- var auth_exports = {};
43
- __export(auth_exports, {
44
- runAuth: () => runAuth
45
- });
46
- import * as http from "http";
47
- import * as https from "https";
48
- import * as net from "net";
49
- import * as querystring from "querystring";
50
- import {
51
- CORSAIR_INTERNAL,
52
- createAccountKeyManager,
53
- createIntegrationKeyManager,
54
- encryptDEK,
55
- generateDEK
56
- } from "corsair/core";
57
- import { createCorsairOrm } from "corsair/orm";
58
- function out(data) {
59
- console.log(JSON.stringify(data));
60
- }
61
- function getOAuthConfigForPlugin(plugin) {
62
- return plugin.oauthConfig ?? null;
63
- }
64
- function getAuthType(plugin) {
65
- return plugin.options?.authType;
66
- }
67
- function getCustomIntegrationFields(plugin, authType) {
68
- const authConfig = plugin.authConfig;
69
- return authConfig?.[authType]?.integration ?? [];
70
- }
71
- function getCustomAccountFields(plugin, authType) {
72
- const authConfig = plugin.authConfig;
73
- return authConfig?.[authType]?.account ?? [];
74
- }
75
- function findFreePort() {
76
- return new Promise((resolve, reject) => {
77
- const server = net.createServer();
78
- server.listen(0, "127.0.0.1", () => {
79
- const address = server.address();
80
- const port = typeof address === "object" && address ? address.port : 0;
81
- server.close((err) => {
82
- if (err) reject(err);
83
- else resolve(port);
84
- });
85
- });
86
- server.on("error", reject);
87
- });
88
- }
89
- function waitForOAuthCode(port) {
90
- return new Promise((resolve, reject) => {
91
- const server = http.createServer((req, res) => {
92
- const url = new URL(req.url ?? "/", `http://localhost:${port}`);
93
- const code = url.searchParams.get("code");
94
- const error = url.searchParams.get("error");
95
- if (error) {
96
- 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>`);
98
- server.close();
99
- reject(new Error(`OAuth error: ${error}`));
100
- return;
101
- }
102
- if (code) {
103
- 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>");
105
- server.close();
106
- resolve(code);
107
- } else {
108
- 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>");
110
- }
111
- });
112
- server.listen(port, "127.0.0.1", () => {
113
- });
114
- server.on("error", reject);
115
- });
116
- }
117
- function exchangeCodeForTokens(code, clientId, clientSecret, oauthConfig, redirectUri) {
118
- const tokenUrl = new URL(oauthConfig.tokenUrl);
119
- const useBasicAuth = oauthConfig.tokenAuthMethod === "basic";
120
- return new Promise((resolve, reject) => {
121
- const postDataParams = {
122
- code: code.trim(),
123
- redirect_uri: redirectUri,
124
- grant_type: "authorization_code"
125
- };
126
- if (!useBasicAuth) {
127
- postDataParams.client_id = clientId;
128
- postDataParams.client_secret = clientSecret;
129
- }
130
- const postData = querystring.stringify(postDataParams);
131
- const headers = {
132
- "Content-Type": "application/x-www-form-urlencoded",
133
- "Content-Length": Buffer.byteLength(postData).toString()
134
- };
135
- if (useBasicAuth) {
136
- headers.Authorization = `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`;
137
- }
138
- const req = https.request(
139
- { hostname: tokenUrl.hostname, path: tokenUrl.pathname, method: "POST", headers },
140
- (res) => {
141
- let data = "";
142
- res.on("data", (chunk) => {
143
- data += chunk;
144
- });
145
- res.on("end", () => {
146
- if (res.statusCode !== 200) {
147
- reject(new Error(`Token exchange failed: ${data}`));
148
- return;
149
- }
150
- resolve(JSON.parse(data));
151
- });
152
- }
153
- );
154
- req.on("error", (error) => reject(new Error(`Request failed: ${error.message}`)));
155
- req.write(postData);
156
- req.end();
157
- });
158
- }
41
+ // utils/corsair.ts
42
+ import { CORSAIR_INTERNAL } from "corsair/core";
159
43
  async function extractInternalConfig(cwd) {
160
44
  const instance = await getCorsairInstance({ cwd, shouldThrowOnError: true });
161
45
  const internal = instance[CORSAIR_INTERNAL];
@@ -166,273 +50,665 @@ async function extractInternalConfig(cwd) {
166
50
  }
167
51
  return internal;
168
52
  }
169
- async function ensureIntegration(database, pluginId, kek) {
170
- const orm = createCorsairOrm(database);
171
- const existing = await orm.integrations.findByName(pluginId);
172
- if (existing) return { id: existing.id };
173
- const dek = generateDEK();
174
- const encryptedDek = await encryptDEK(dek, kek);
175
- const row = await orm.integrations.create({ name: pluginId, config: {}, dek: encryptedDek });
176
- return { id: row.id };
177
- }
178
- async function ensureAccount(database, integrationId, tenantId, kek) {
179
- const orm = createCorsairOrm(database);
180
- const existing = await orm.accounts.findOne({ tenant_id: tenantId, integration_id: integrationId });
181
- if (existing) return;
182
- const dek = generateDEK();
183
- const encryptedDek = await encryptDEK(dek, kek);
184
- await orm.accounts.create({ tenant_id: tenantId, integration_id: integrationId, config: {}, dek: encryptedDek });
185
- }
186
- async function oauthGetUrl(database, plugin, kek, tenantId) {
187
- const oauthCfg = getOAuthConfigForPlugin(plugin);
188
- if (!oauthCfg) {
189
- out({ error: `No oauthConfig defined on plugin '${plugin.id}'.` });
190
- return;
191
- }
192
- const extraFields = getCustomIntegrationFields(plugin, "oauth_2");
193
- const integrationKm = createIntegrationKeyManager({
194
- authType: "oauth_2",
195
- integrationName: plugin.id,
196
- kek,
197
- database,
198
- extraIntegrationFields: extraFields
199
- });
200
- const clientId = await integrationKm.get_client_id();
201
- if (!clientId) {
202
- out({ error: `client_id not set for '${plugin.id}'. Run: corsair setup --${plugin.id} client_id=YOUR_CLIENT_ID` });
203
- return;
53
+ var init_corsair = __esm({
54
+ "utils/corsair.ts"() {
55
+ "use strict";
56
+ init_index();
204
57
  }
205
- const clientSecret = await integrationKm.get_client_secret();
206
- if (!clientSecret) {
207
- out({ error: `client_secret not set for '${plugin.id}'. Run: corsair setup --${plugin.id} client_secret=YOUR_CLIENT_SECRET` });
208
- return;
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);
209
74
  }
210
- let redirectUri;
211
- if (oauthCfg.requiresRegisteredRedirect) {
212
- const stored = await integrationKm.get_redirect_url();
213
- if (!stored) {
214
- out({ error: `redirect_url required for '${plugin.id}'. Run: corsair setup --${plugin.id} redirect_url=YOUR_REDIRECT_URI` });
215
- return;
216
- }
217
- redirectUri = stored;
218
- } else {
219
- const port = await findFreePort();
220
- redirectUri = `http://localhost:${port}`;
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);
221
81
  }
222
- const authParams = {
223
- client_id: clientId,
224
- redirect_uri: redirectUri,
225
- response_type: "code",
226
- scope: oauthCfg.scopes.join(" "),
227
- ...oauthCfg.authParams
228
- };
229
- const authUrl = `${oauthCfg.authUrl}?${querystring.stringify(authParams)}`;
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)}` });
239
- return;
240
- }
241
- await oauthExchangeCode(database, plugin, kek, tenantId, code, redirectUri, clientId, clientSecret, oauthCfg);
242
- return;
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);
243
88
  }
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" });
89
+ spin.stop("Loaded.");
90
+ return { internal, plugin };
245
91
  }
246
- async function oauthExchangeCode(database, plugin, kek, tenantId, code, redirectUri, clientId, clientSecret, oauthCfg) {
247
- let tokens;
248
- try {
249
- tokens = await exchangeCodeForTokens(code, clientId, clientSecret, oauthCfg, redirectUri);
250
- } catch (err) {
251
- out({ error: `Token exchange failed: ${err instanceof Error ? err.message : String(err)}` });
252
- return;
253
- }
254
- if (!tokens.access_token) {
255
- out({ error: `No access_token in response from ${oauthCfg.providerName}.` });
256
- return;
92
+ var init_load_config = __esm({
93
+ "utils/load-config.ts"() {
94
+ "use strict";
95
+ init_corsair();
257
96
  }
258
- const extraAccountFields = getCustomAccountFields(plugin, "oauth_2");
259
- const accountKm = createAccountKeyManager({
260
- authType: "oauth_2",
261
- integrationName: plugin.id,
262
- tenantId,
263
- kek,
264
- database,
265
- extraAccountFields
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"
266
107
  });
267
- await accountKm.set_access_token(tokens.access_token);
268
- if (tokens.refresh_token) await accountKm.set_refresh_token(tokens.refresh_token);
269
- if (tokens.expires_in) await accountKm.set_expires_at((Math.floor(Date.now() / 1e3) + tokens.expires_in).toString());
270
- out({ status: "success", plugin: plugin.id, tenant: tenantId });
108
+ if (p2.isCancel(tenantId)) {
109
+ p2.cancel("Operation cancelled.");
110
+ process.exit(0);
111
+ }
112
+ return tenantId;
271
113
  }
272
- async function oauthWithCode(database, plugin, kek, tenantId, code) {
273
- const oauthCfg = getOAuthConfigForPlugin(plugin);
274
- if (!oauthCfg) {
275
- out({ error: `No oauthConfig defined on plugin '${plugin.id}'.` });
276
- return;
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);
277
127
  }
278
- const extraFields = getCustomIntegrationFields(plugin, "oauth_2");
279
- const integrationKm = createIntegrationKeyManager({
280
- authType: "oauth_2",
281
- integrationName: plugin.id,
282
- kek,
283
- database,
284
- extraIntegrationFields: extraFields
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
285
136
  });
286
- const clientId = await integrationKm.get_client_id();
287
- const clientSecret = await integrationKm.get_client_secret();
288
- const redirectUri = await integrationKm.get_redirect_url() ?? "";
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
+ }
289
201
  if (!clientId || !clientSecret) {
290
- out({ error: `client_id and client_secret must be set before exchanging a code.` });
291
- return;
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}`);
292
599
  }
293
- await oauthExchangeCode(database, plugin, kek, tenantId, code, redirectUri, clientId, clientSecret, oauthCfg);
600
+ const data = await response.json();
601
+ return data.value ?? [];
294
602
  }
295
- async function getCredentials(database, plugin, kek, tenantId) {
296
- const authType = getAuthType(plugin);
297
- const result = {};
298
- if (authType === "oauth_2") {
299
- const extraIntegrationFields = getCustomIntegrationFields(plugin, authType);
300
- const integrationKm = createIntegrationKeyManager({
301
- authType,
302
- integrationName: plugin.id,
303
- kek,
304
- database,
305
- extraIntegrationFields
306
- });
307
- result.client_id = await integrationKm.get_client_id();
308
- result.client_secret = await integrationKm.get_client_secret();
309
- result.redirect_url = await integrationKm.get_redirect_url();
310
- for (const field of extraIntegrationFields) {
311
- const fn = integrationKm[`get_${field}`];
312
- if (typeof fn === "function") result[field] = await fn();
313
- }
314
- const extraAccountFields = getCustomAccountFields(plugin, authType);
315
- const accountKm = createAccountKeyManager({
316
- authType,
317
- integrationName: plugin.id,
318
- tenantId,
319
- kek,
320
- database,
321
- extraAccountFields
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 }))
322
618
  });
323
- result.access_token = await accountKm.get_access_token();
324
- result.refresh_token = await accountKm.get_refresh_token();
325
- result.expires_at = await accountKm.get_expires_at();
326
- result.webhook_signature = await accountKm.get_webhook_signature();
327
- for (const field of extraAccountFields) {
328
- const fn = accountKm[`get_${field}`];
329
- if (typeof fn === "function") result[field] = await fn();
619
+ if (p6.isCancel(picked)) {
620
+ p6.cancel("Operation cancelled.");
621
+ process.exit(0);
330
622
  }
331
- } else if (authType === "api_key") {
332
- const extraAccountFields = getCustomAccountFields(plugin, authType);
333
- const accountKm = createAccountKeyManager({
334
- authType,
335
- integrationName: plugin.id,
336
- tenantId,
337
- kek,
338
- database,
339
- extraAccountFields
340
- });
341
- result.api_key = await accountKm.get_api_key();
342
- result.webhook_signature = await accountKm.get_webhook_signature();
343
- } else if (authType === "bot_token") {
344
- const extraAccountFields = getCustomAccountFields(plugin, authType);
345
- const accountKm = createAccountKeyManager({
346
- authType,
347
- integrationName: plugin.id,
348
- tenantId,
349
- kek,
350
- database,
351
- extraAccountFields
352
- });
353
- result.bot_token = await accountKm.get_bot_token();
354
- result.webhook_signature = await accountKm.get_webhook_signature();
623
+ return picked;
355
624
  }
356
- const masked = {};
357
- for (const [k, v] of Object.entries(result)) {
358
- if (!v) {
359
- masked[k] = null;
360
- continue;
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";
361
630
  }
362
- masked[k] = v.length <= 9 ? "***" : `${v.slice(0, 6)}...${v.slice(-3)}`;
631
+ });
632
+ if (p6.isCancel(manual)) {
633
+ p6.cancel("Operation cancelled.");
634
+ process.exit(0);
363
635
  }
364
- out({ plugin: plugin.id, tenant: tenantId, credentials: masked });
636
+ return manual;
365
637
  }
366
- async function runAuth({
367
- cwd,
368
- pluginId: pluginIdArg,
369
- tenantId: tenantIdArg,
370
- code: codeArg,
371
- credentials: showCredentials = false
372
- }) {
373
- let internal;
638
+ async function pickChannelId(accessToken, teamId, label) {
639
+ const chanSpin = p6.spinner();
640
+ chanSpin.start("Fetching channels...");
641
+ let channels = [];
374
642
  try {
375
- internal = await extractInternalConfig(cwd);
643
+ channels = await fetchTeamChannels(accessToken, teamId);
644
+ chanSpin.stop(`Found ${channels.length} channel${channels.length === 1 ? "" : "s"}.`);
376
645
  } catch (error) {
377
- out({ error: error instanceof Error ? error.message : String(error) });
378
- process.exit(1);
379
- }
380
- const { plugins, database, kek } = internal;
381
- if (!database) {
382
- out({ error: "No database adapter configured." });
383
- process.exit(1);
646
+ chanSpin.stop("Could not fetch channels.");
647
+ p6.log.warn(error instanceof Error ? error.message : String(error));
384
648
  }
385
- if (!pluginIdArg) {
386
- out({
387
- error: "No plugin specified. Use --plugin=<id>.",
388
- available: plugins.map((pl) => ({ id: pl.id, authType: getAuthType(pl) }))
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 }))
389
653
  });
390
- process.exit(1);
391
- }
392
- const plugin = plugins.find((pl) => pl.id === pluginIdArg);
393
- if (!plugin) {
394
- out({ error: `Plugin '${pluginIdArg}' not found.`, available: plugins.map((pl) => pl.id) });
395
- process.exit(1);
654
+ if (p6.isCancel(picked)) {
655
+ p6.cancel("Operation cancelled.");
656
+ process.exit(0);
657
+ }
658
+ return picked;
396
659
  }
397
- const integration = await ensureIntegration(database, plugin.id, kek);
398
- const tenantId = tenantIdArg ?? "default";
399
- await ensureAccount(database, integration.id, tenantId, kek);
400
- if (showCredentials) {
401
- await getCredentials(database, plugin, kek, tenantId);
402
- return;
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);
403
670
  }
404
- const authType = getAuthType(plugin);
405
- if (authType !== "oauth_2") {
406
- out({ error: `'corsair auth' is for OAuth flows. Plugin '${plugin.id}' uses '${authType}'. Set credentials via: corsair setup --${plugin.id} <field>=<value>` });
407
- return;
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;
408
698
  }
409
- if (codeArg) {
410
- await oauthWithCode(database, plugin, kek, tenantId, codeArg);
411
- } else {
412
- await oauthGetUrl(database, plugin, kek, tenantId);
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);
413
709
  }
710
+ return manual;
414
711
  }
415
- var init_auth = __esm({
416
- "auth.ts"() {
417
- "use strict";
418
- init_index();
419
- }
420
- });
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
712
  function buildTeamsResource(resourceType, ids) {
437
713
  switch (resourceType) {
438
714
  case "channelMessage":
@@ -445,274 +721,294 @@ function buildTeamsResource(resourceType, ids) {
445
721
  return `teams/${ids.teamId}/members`;
446
722
  }
447
723
  }
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
- })
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
463
759
  });
464
- if (!response.ok) {
465
- const error = await response.text();
466
- throw new Error(`Graph subscription failed: ${error}`);
760
+ if (p6.isCancel(selectedResourceTypes)) {
761
+ p6.cancel("Operation cancelled.");
762
+ process.exit(0);
467
763
  }
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);
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 });
482
776
  }
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);
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
+ }
489
806
  }
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);
807
+ if (results.length > 0) {
808
+ p6.note(results.join("\n\n"), "Subscriptions created");
496
809
  }
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);
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.");
506
815
  }
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);
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
+ };
523
839
  }
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);
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}`;
536
852
  }
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
- ]
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
545
872
  });
546
- if (p.isCancel(resourceType)) {
547
- p.cancel("Operation cancelled.");
873
+ if (p7.isCancel(selectedResourceTypes)) {
874
+ p7.cancel("Operation cancelled.");
548
875
  process.exit(0);
549
876
  }
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";
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);
570
891
  }
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",
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...",
581
897
  validate: (v) => {
582
- if (!v || !v.trim()) return "Channel ID is required";
898
+ if (!v || !v.trim()) return "Item ID is required";
583
899
  }
584
900
  });
585
- if (p.isCancel(channelId)) {
586
- p.cancel("Operation cancelled.");
901
+ if (p7.isCancel(itemId)) {
902
+ p7.cancel("Operation cancelled.");
587
903
  process.exit(0);
588
904
  }
589
- ids.channelId = channelId;
905
+ ids.itemId = itemId;
590
906
  }
907
+ resourceConfigs.push({ resourceType, ids });
591
908
  }
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);
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
+ }
601
937
  }
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);
938
+ if (results.length > 0) {
939
+ p7.note(results.join("\n\n"), "Subscriptions created");
620
940
  }
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}
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}
632
950
 
633
- Note: Teams subscriptions expire. Re-run this command to renew.`,
634
- "Teams Subscription Created"
951
+ Note: OneDrive subscriptions expire. Re-run this command to renew.`,
952
+ "Setup complete"
635
953
  );
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;
954
+ p7.outro("Done!");
665
955
  }
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);
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
+ ];
686
982
  }
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);
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();
710
1000
  }
711
- const startPageTokenData = await startPageTokenRes.json();
712
- watchSpin.message("Starting Drive watch...");
713
- const channelId = crypto.randomUUID();
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();
714
1010
  const watchRes = await fetch(
715
- `${DRIVE_API_BASE}/changes/watch?pageToken=${startPageTokenData.startPageToken}`,
1011
+ `${CALENDAR_API_BASE}/calendars/${encodeURIComponent(calendarId)}/events/watch`,
716
1012
  {
717
1013
  method: "POST",
718
1014
  headers: {
@@ -729,26 +1025,48 @@ async function renewDriveWatch(accessToken, webhookUrl) {
729
1025
  if (!watchRes.ok) {
730
1026
  const error = await watchRes.text();
731
1027
  watchSpin.stop("Failed.");
732
- p.log.error(`Drive watch failed: ${error}`);
733
- p.outro("");
1028
+ p8.log.error(`Calendar watch failed: ${error}`);
1029
+ p8.outro("");
734
1030
  process.exit(1);
735
1031
  }
736
1032
  const data = await watchRes.json();
737
1033
  watchSpin.stop("Watch started.");
738
- p.note(
1034
+ p8.note(
739
1035
  `Channel ID: ${channelId}
740
1036
  Resource ID: ${data.resourceId}
741
- Start Page Token: ${startPageTokenData.startPageToken}
742
1037
  Expiration: ${new Date(Number(data.expiration)).toISOString()}`,
743
1038
  "Watch Response"
744
1039
  );
745
1040
  }
746
- async function renewCalendarWatch(accessToken, webhookUrl, calendarId) {
747
- const watchSpin = p.spinner();
748
- watchSpin.start("Starting Calendar watch...");
749
- const channelId = crypto.randomUUID();
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();
750
1068
  const watchRes = await fetch(
751
- `${CALENDAR_API_BASE}/calendars/${encodeURIComponent(calendarId)}/events/watch`,
1069
+ `${DRIVE_API_BASE}/changes/watch?pageToken=${startPageTokenData.startPageToken}`,
752
1070
  {
753
1071
  method: "POST",
754
1072
  headers: {
@@ -765,39 +1083,107 @@ async function renewCalendarWatch(accessToken, webhookUrl, calendarId) {
765
1083
  if (!watchRes.ok) {
766
1084
  const error = await watchRes.text();
767
1085
  watchSpin.stop("Failed.");
768
- p.log.error(`Calendar watch failed: ${error}`);
769
- p.outro("");
1086
+ p9.log.error(`Drive watch failed: ${error}`);
1087
+ p9.outro("");
770
1088
  process.exit(1);
771
1089
  }
772
1090
  const data = await watchRes.json();
773
1091
  watchSpin.stop("Watch started.");
774
- p.note(
1092
+ p9.note(
775
1093
  `Channel ID: ${channelId}
776
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}
777
1135
  Expiration: ${new Date(Number(data.expiration)).toISOString()}`,
778
1136
  "Watch Response"
779
1137
  );
780
1138
  }
781
- function copyToClipboard(text4) {
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) {
782
1168
  try {
783
1169
  const platform = process.platform;
784
1170
  if (platform === "darwin") {
785
- execSync("pbcopy", { input: text4 });
1171
+ execSync("pbcopy", { input: text6 });
786
1172
  return true;
787
1173
  } else if (platform === "linux") {
788
1174
  try {
789
- execSync("xclip -selection clipboard", { input: text4 });
1175
+ execSync("xclip -selection clipboard", { input: text6 });
790
1176
  return true;
791
1177
  } catch {
792
1178
  try {
793
- execSync("xsel --clipboard --input", { input: text4 });
1179
+ execSync("xsel --clipboard --input", { input: text6 });
794
1180
  return true;
795
1181
  } catch {
796
1182
  return false;
797
1183
  }
798
1184
  }
799
1185
  } else if (platform === "win32") {
800
- execSync("clip", { input: text4 });
1186
+ execSync("clip", { input: text6 });
801
1187
  return true;
802
1188
  }
803
1189
  return false;
@@ -805,8 +1191,61 @@ function copyToClipboard(text4) {
805
1191
  return false;
806
1192
  }
807
1193
  }
808
- async function renewSheetsWatch(webhookUrl) {
809
- const appsScriptCode = `var WEBHOOK_URL = "${webhookUrl}";
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}";
810
1249
 
811
1250
  function onEditTrigger(e) {
812
1251
  if (!e || !e.range) return;
@@ -860,7 +1299,7 @@ function createTriggers() {
860
1299
 
861
1300
  ScriptApp.newTrigger("onEditTrigger").forSpreadsheet(ss).onEdit().create();
862
1301
  ScriptApp.newTrigger("onChangeTrigger").forSpreadsheet(ss).onChange().create();
863
-
1302
+
864
1303
  Logger.log("Triggers created successfully!");
865
1304
  }
866
1305
 
@@ -871,65 +1310,43 @@ function removeTriggers() {
871
1310
  });
872
1311
  Logger.log("All triggers removed.");
873
1312
  }`;
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
1313
  }
908
- p.note(
909
- `Webhook URL: ${webhookUrl}
1314
+ });
910
1315
 
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
- );
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;
914
1328
  }
915
- async function runWatchRenew({ cwd }) {
916
- p.intro("Corsair \u2014 Google Watch Renewal");
917
- const spin = p.spinner();
1329
+ async function runGoogleSubscribe({
1330
+ cwd,
1331
+ pluginId: preselectedPluginId
1332
+ }) {
1333
+ p12.intro("Corsair \u2014 Google Webhook Subscribe");
1334
+ const spin = p12.spinner();
918
1335
  spin.start("Loading corsair instance...");
919
1336
  let internal;
920
1337
  try {
921
1338
  internal = await extractInternalConfig2(cwd);
922
1339
  } catch (error) {
923
1340
  spin.stop("Failed to load.");
924
- p.log.error(error instanceof Error ? error.message : String(error));
925
- p.outro("");
1341
+ p12.log.error(error instanceof Error ? error.message : String(error));
1342
+ p12.outro("");
926
1343
  process.exit(1);
927
1344
  }
928
1345
  const { plugins, database, kek } = internal;
929
1346
  if (!database) {
930
1347
  spin.stop("Failed.");
931
- p.log.error("No database adapter configured.");
932
- p.outro("");
1348
+ p12.log.error("No database adapter configured.");
1349
+ p12.outro("");
933
1350
  process.exit(1);
934
1351
  }
935
1352
  const googlePlugins = plugins.filter((pl) => {
@@ -938,202 +1355,296 @@ async function runWatchRenew({ cwd }) {
938
1355
  });
939
1356
  if (googlePlugins.length === 0) {
940
1357
  spin.stop("No Google OAuth2 plugins found.");
941
- p.outro("");
1358
+ p12.outro("");
942
1359
  process.exit(1);
943
1360
  }
944
1361
  spin.stop(
945
1362
  `Loaded. Found ${googlePlugins.length} Google plugin${googlePlugins.length === 1 ? "" : "s"}.`
946
1363
  );
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);
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;
957
1377
  }
958
- const pluginType = pluginId;
959
1378
  if (pluginType === "googlesheets") {
960
- const webhookUrl = await p.text({
1379
+ const webhookUrl = await p12.text({
961
1380
  message: "Enter webhook URL:",
962
1381
  placeholder: "https://example.com/api/webhook",
963
1382
  validate: (v) => {
964
1383
  if (!v || v.trim().length === 0) return "Webhook URL is required";
965
- if (!v.startsWith("http://") && !v.startsWith("https://")) {
1384
+ if (!v.startsWith("http://") && !v.startsWith("https://"))
966
1385
  return "Webhook URL must start with http:// or https://";
967
- }
968
1386
  }
969
1387
  });
970
- if (p.isCancel(webhookUrl)) {
971
- p.cancel("Operation cancelled.");
1388
+ if (p12.isCancel(webhookUrl)) {
1389
+ p12.cancel("Operation cancelled.");
972
1390
  process.exit(0);
973
1391
  }
974
- await renewSheetsWatch(webhookUrl);
975
- p.outro("Done!");
1392
+ await setupSheetsWatch(webhookUrl);
1393
+ p12.outro("Done!");
976
1394
  return;
977
1395
  }
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();
1396
+ const tenantId = await promptTenantId();
1397
+ const credSpin = p12.spinner();
988
1398
  credSpin.start("Fetching credentials...");
989
1399
  try {
990
1400
  const integrationKm = createIntegrationKeyManager2({
991
1401
  authType: "oauth_2",
992
- integrationName: pluginId,
1402
+ integrationName: pluginType,
993
1403
  kek,
994
1404
  database
995
1405
  });
996
1406
  const accountKm = createAccountKeyManager2({
997
1407
  authType: "oauth_2",
998
- integrationName: pluginId,
1408
+ integrationName: pluginType,
999
1409
  tenantId,
1000
1410
  kek,
1001
1411
  database
1002
1412
  });
1003
1413
  const clientId = await integrationKm.get_client_id();
1004
1414
  const clientSecret = await integrationKm.get_client_secret();
1005
- const refreshToken2 = await accountKm.get_refresh_token();
1006
- if (!clientId || !clientSecret || !refreshToken2) {
1415
+ const refreshToken = await accountKm.get_refresh_token();
1416
+ if (!clientId || !clientSecret || !refreshToken) {
1007
1417
  credSpin.stop("Missing credentials.");
1008
- p.log.error(
1418
+ p12.log.error(
1009
1419
  'Client ID, Client Secret, and Refresh Token are required. Use "corsair auth" to set them.'
1010
1420
  );
1011
- p.outro("");
1421
+ p12.outro("");
1012
1422
  process.exit(1);
1013
1423
  }
1014
- const accessToken = await refreshAccessToken(
1015
- clientId,
1016
- clientSecret,
1017
- refreshToken2
1018
- );
1424
+ const accessToken = await refreshGoogleAccessToken(clientId, clientSecret, refreshToken);
1019
1425
  credSpin.stop("Credentials loaded.");
1020
1426
  if (pluginType === "gmail") {
1021
- const topicName = await p.text({
1427
+ const topicName = await p12.text({
1022
1428
  message: "Enter Pub/Sub topic name:",
1023
1429
  placeholder: "projects/my-project/topics/my-topic",
1024
1430
  validate: (v) => {
1025
1431
  if (!v || v.trim().length === 0) return "Topic name is required";
1026
1432
  }
1027
1433
  });
1028
- if (p.isCancel(topicName)) {
1029
- p.cancel("Operation cancelled.");
1434
+ if (p12.isCancel(topicName)) {
1435
+ p12.cancel("Operation cancelled.");
1030
1436
  process.exit(0);
1031
1437
  }
1032
- await renewGmailWatch(accessToken, topicName);
1438
+ await setupGmailWatch(accessToken, topicName);
1033
1439
  } else if (pluginType === "googledrive") {
1034
- const webhookUrl = await p.text({
1440
+ const webhookUrl = await p12.text({
1035
1441
  message: "Enter webhook URL:",
1036
1442
  placeholder: "https://example.com/api/webhook",
1037
1443
  validate: (v) => {
1038
1444
  if (!v || v.trim().length === 0) return "Webhook URL is required";
1039
1445
  }
1040
1446
  });
1041
- if (p.isCancel(webhookUrl)) {
1042
- p.cancel("Operation cancelled.");
1447
+ if (p12.isCancel(webhookUrl)) {
1448
+ p12.cancel("Operation cancelled.");
1043
1449
  process.exit(0);
1044
1450
  }
1045
- await renewDriveWatch(accessToken, webhookUrl);
1451
+ await setupDriveWatch(accessToken, webhookUrl);
1046
1452
  } else if (pluginType === "googlecalendar") {
1047
- const webhookUrl = await p.text({
1453
+ const webhookUrl = await p12.text({
1048
1454
  message: "Enter webhook URL:",
1049
1455
  placeholder: "https://example.com/api/webhook",
1050
1456
  validate: (v) => {
1051
1457
  if (!v || v.trim().length === 0) return "Webhook URL is required";
1052
1458
  }
1053
1459
  });
1054
- if (p.isCancel(webhookUrl)) {
1055
- p.cancel("Operation cancelled.");
1460
+ if (p12.isCancel(webhookUrl)) {
1461
+ p12.cancel("Operation cancelled.");
1056
1462
  process.exit(0);
1057
1463
  }
1058
- const calendarId = await p.text({
1464
+ const calendarId = await p12.text({
1059
1465
  message: "Enter calendar ID:",
1060
1466
  defaultValue: "primary",
1061
1467
  placeholder: "primary"
1062
1468
  });
1063
- if (p.isCancel(calendarId)) {
1064
- p.cancel("Operation cancelled.");
1469
+ if (p12.isCancel(calendarId)) {
1470
+ p12.cancel("Operation cancelled.");
1065
1471
  process.exit(0);
1066
1472
  }
1067
- await renewCalendarWatch(
1068
- accessToken,
1069
- webhookUrl,
1070
- calendarId
1071
- );
1473
+ await setupCalendarWatch(accessToken, webhookUrl, calendarId);
1072
1474
  } else {
1073
- p.log.error(`Unsupported Google plugin: ${pluginType}`);
1475
+ p12.log.error(`Unsupported Google plugin: ${pluginType}`);
1074
1476
  process.exit(1);
1075
1477
  }
1076
1478
  } catch (error) {
1077
1479
  credSpin.stop("Failed.");
1078
- p.log.error(
1079
- `Error: ${error instanceof Error ? error.message : String(error)}`
1080
- );
1480
+ p12.log.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
1081
1481
  process.exit(1);
1082
1482
  }
1083
- p.outro("Done!");
1483
+ p12.outro("Done!");
1084
1484
  }
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"() {
1485
+ var GOOGLE_PLUGINS;
1486
+ var init_google = __esm({
1487
+ "google/index.ts"() {
1088
1488
  "use strict";
1089
1489
  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";
1490
+ init_prompts();
1491
+ init_calendar();
1492
+ init_drive();
1493
+ init_gmail();
1494
+ init_shared();
1495
+ init_sheets();
1094
1496
  GOOGLE_PLUGINS = [
1095
1497
  "gmail",
1096
1498
  "googledrive",
1097
1499
  "googlecalendar",
1098
1500
  "googlesheets"
1099
1501
  ];
1100
- TEAMS_MAX_EXPIRY_MINUTES = {
1101
- channelMessage: 60,
1102
- chatMessage: 60,
1103
- channelCreated: 4230,
1104
- membershipChanged: 60
1105
- };
1106
1502
  }
1107
1503
  });
1108
1504
 
1109
- // sharepoint-subscribe.ts
1110
- var sharepoint_subscribe_exports = {};
1111
- __export(sharepoint_subscribe_exports, {
1112
- runSharepointSubscribe: () => runSharepointSubscribe
1505
+ // subscribe-google.ts
1506
+ var subscribe_google_exports = {};
1507
+ __export(subscribe_google_exports, {
1508
+ runGoogleSubscribe: () => runGoogleSubscribe
1113
1509
  });
1114
- import * as crypto2 from "crypto";
1115
- import * as p2 from "@clack/prompts";
1510
+ var init_subscribe_google = __esm({
1511
+ "subscribe-google.ts"() {
1512
+ "use strict";
1513
+ init_google();
1514
+ }
1515
+ });
1516
+
1517
+ // auth.ts
1518
+ var auth_exports = {};
1519
+ __export(auth_exports, {
1520
+ runAuth: () => runAuth
1521
+ });
1522
+ import * as http from "http";
1523
+ import * as https from "https";
1524
+ import * as net from "net";
1525
+ import * as querystring from "querystring";
1116
1526
  import {
1117
1527
  CORSAIR_INTERNAL as CORSAIR_INTERNAL3,
1118
1528
  createAccountKeyManager as createAccountKeyManager3,
1119
- createIntegrationKeyManager as createIntegrationKeyManager3
1529
+ createIntegrationKeyManager as createIntegrationKeyManager3,
1530
+ encryptDEK,
1531
+ generateDEK
1120
1532
  } 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
- })
1533
+ import { createCorsairOrm } from "corsair/orm";
1534
+ function out(data) {
1535
+ console.log(JSON.stringify(data));
1536
+ }
1537
+ function getOAuthConfigForPlugin(plugin) {
1538
+ return plugin.oauthConfig ?? null;
1539
+ }
1540
+ function getAuthType(plugin) {
1541
+ return plugin.options?.authType;
1542
+ }
1543
+ function getCustomIntegrationFields(plugin, authType) {
1544
+ const authConfig = plugin.authConfig;
1545
+ return authConfig?.[authType]?.integration ?? [];
1546
+ }
1547
+ function getCustomAccountFields(plugin, authType) {
1548
+ const authConfig = plugin.authConfig;
1549
+ return authConfig?.[authType]?.account ?? [];
1550
+ }
1551
+ function findFreePort() {
1552
+ return new Promise((resolve, reject) => {
1553
+ const server = net.createServer();
1554
+ server.listen(0, "127.0.0.1", () => {
1555
+ const address = server.address();
1556
+ const port = typeof address === "object" && address ? address.port : 0;
1557
+ server.close((err) => {
1558
+ if (err) reject(err);
1559
+ else resolve(port);
1560
+ });
1561
+ });
1562
+ server.on("error", reject);
1563
+ });
1564
+ }
1565
+ function waitForOAuthCode(port) {
1566
+ return new Promise((resolve, reject) => {
1567
+ const server = http.createServer((req, res) => {
1568
+ const url = new URL(req.url ?? "/", `http://localhost:${port}`);
1569
+ const code = url.searchParams.get("code");
1570
+ const error = url.searchParams.get("error");
1571
+ if (error) {
1572
+ res.writeHead(400, { "Content-Type": "text/html" });
1573
+ res.end(
1574
+ `<html><body><h2>Authorization failed: ${error}</h2><p>You can close this tab.</p></body></html>`
1575
+ );
1576
+ server.close();
1577
+ reject(new Error(`OAuth error: ${error}`));
1578
+ return;
1579
+ }
1580
+ if (code) {
1581
+ res.writeHead(200, { "Content-Type": "text/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
+ );
1585
+ server.close();
1586
+ resolve(code);
1587
+ } else {
1588
+ res.writeHead(400, { "Content-Type": "text/html" });
1589
+ res.end(
1590
+ "<html><body><h2>No code received.</h2><p>You can close this tab.</p></body></html>"
1591
+ );
1592
+ }
1593
+ });
1594
+ server.listen(port, "127.0.0.1", () => {
1595
+ });
1596
+ server.on("error", reject);
1597
+ });
1598
+ }
1599
+ function exchangeCodeForTokens(code, clientId, clientSecret, oauthConfig, redirectUri) {
1600
+ const tokenUrl = new URL(oauthConfig.tokenUrl);
1601
+ const useBasicAuth = oauthConfig.tokenAuthMethod === "basic";
1602
+ return new Promise((resolve, reject) => {
1603
+ const postDataParams = {
1604
+ code: code.trim(),
1605
+ redirect_uri: redirectUri,
1606
+ grant_type: "authorization_code"
1607
+ };
1608
+ if (!useBasicAuth) {
1609
+ postDataParams.client_id = clientId;
1610
+ postDataParams.client_secret = clientSecret;
1611
+ }
1612
+ const postData = querystring.stringify(postDataParams);
1613
+ const headers = {
1614
+ "Content-Type": "application/x-www-form-urlencoded",
1615
+ "Content-Length": Buffer.byteLength(postData).toString()
1616
+ };
1617
+ if (useBasicAuth) {
1618
+ headers.Authorization = `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`;
1619
+ }
1620
+ const req = https.request(
1621
+ {
1622
+ hostname: tokenUrl.hostname,
1623
+ path: tokenUrl.pathname,
1624
+ method: "POST",
1625
+ headers
1626
+ },
1627
+ (res) => {
1628
+ let data = "";
1629
+ res.on("data", (chunk) => {
1630
+ data += chunk;
1631
+ });
1632
+ res.on("end", () => {
1633
+ if (res.statusCode !== 200) {
1634
+ reject(new Error(`Token exchange failed: ${data}`));
1635
+ return;
1636
+ }
1637
+ resolve(JSON.parse(data));
1638
+ });
1639
+ }
1640
+ );
1641
+ req.on(
1642
+ "error",
1643
+ (error) => reject(new Error(`Request failed: ${error.message}`))
1644
+ );
1645
+ req.write(postData);
1646
+ req.end();
1131
1647
  });
1132
- if (!response.ok) {
1133
- const error = await response.text();
1134
- throw new Error(`Token refresh failed: ${error}`);
1135
- }
1136
- return response.json();
1137
1648
  }
1138
1649
  async function extractInternalConfig3(cwd) {
1139
1650
  const instance = await getCorsairInstance({ cwd, shouldThrowOnError: true });
@@ -1145,505 +1656,338 @@ async function extractInternalConfig3(cwd) {
1145
1656
  }
1146
1657
  return internal;
1147
1658
  }
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();
1659
+ async function ensureIntegration(database, pluginId, kek) {
1660
+ const orm = createCorsairOrm(database);
1661
+ const existing = await orm.integrations.findByName(pluginId);
1662
+ if (existing) return { id: existing.id };
1663
+ const dek = generateDEK();
1664
+ const encryptedDek = await encryptDEK(dek, kek);
1665
+ const row = await orm.integrations.create({
1666
+ name: pluginId,
1667
+ config: {},
1668
+ dek: encryptedDek
1669
+ });
1670
+ return { id: row.id };
1190
1671
  }
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"
1672
+ async function ensureAccount(database, integrationId, tenantId, kek) {
1673
+ const orm = createCorsairOrm(database);
1674
+ const existing = await orm.accounts.findOne({
1675
+ tenant_id: tenantId,
1676
+ integration_id: integrationId
1223
1677
  });
1224
- if (p2.isCancel(tenantId)) {
1225
- p2.cancel("Operation cancelled.");
1226
- process.exit(0);
1678
+ if (existing) return;
1679
+ const dek = generateDEK();
1680
+ const encryptedDek = await encryptDEK(dek, kek);
1681
+ await orm.accounts.create({
1682
+ tenant_id: tenantId,
1683
+ integration_id: integrationId,
1684
+ config: {},
1685
+ dek: encryptedDek
1686
+ });
1687
+ }
1688
+ async function oauthGetUrl(database, plugin, kek, tenantId) {
1689
+ const oauthCfg = getOAuthConfigForPlugin(plugin);
1690
+ if (!oauthCfg) {
1691
+ out({ error: `No oauthConfig defined on plugin '${plugin.id}'.` });
1692
+ return;
1227
1693
  }
1228
- const credSpin = p2.spinner();
1229
- credSpin.start("Fetching SharePoint credentials...");
1694
+ const extraFields = getCustomIntegrationFields(plugin, "oauth_2");
1230
1695
  const integrationKm = createIntegrationKeyManager3({
1231
1696
  authType: "oauth_2",
1232
- integrationName: "sharepoint",
1233
- kek,
1234
- database
1235
- });
1236
- const accountKm = createAccountKeyManager3({
1237
- authType: "oauth_2",
1238
- integrationName: "sharepoint",
1239
- tenantId,
1697
+ integrationName: plugin.id,
1240
1698
  kek,
1241
- database
1699
+ database,
1700
+ extraIntegrationFields: extraFields
1242
1701
  });
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);
1702
+ const clientId = await integrationKm.get_client_id();
1703
+ if (!clientId) {
1704
+ out({
1705
+ error: `client_id not set for '${plugin.id}'. Run: corsair setup --${plugin.id} client_id=YOUR_CLIENT_ID`
1706
+ });
1707
+ return;
1255
1708
  }
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);
1709
+ const clientSecret = await integrationKm.get_client_secret();
1710
+ if (!clientSecret) {
1711
+ out({
1712
+ error: `client_secret not set for '${plugin.id}'. Run: corsair setup --${plugin.id} client_secret=YOUR_CLIENT_SECRET`
1713
+ });
1714
+ return;
1261
1715
  }
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);
1716
+ let redirectUri;
1717
+ if (oauthCfg.requiresRegisteredRedirect) {
1718
+ const stored = await integrationKm.get_redirect_url();
1719
+ if (!stored) {
1720
+ out({
1721
+ error: `redirect_url required for '${plugin.id}'. Run: corsair setup --${plugin.id} redirect_url=YOUR_REDIRECT_URI`
1722
+ });
1723
+ return;
1280
1724
  }
1725
+ redirectUri = stored;
1726
+ } else {
1727
+ const port = await findFreePort();
1728
+ redirectUri = `http://localhost:${port}`;
1281
1729
  }
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";
1730
+ const authParams = {
1731
+ client_id: clientId,
1732
+ redirect_uri: redirectUri,
1733
+ response_type: "code",
1734
+ scope: oauthCfg.scopes.join(" "),
1735
+ ...oauthCfg.authParams
1736
+ };
1737
+ const authUrl = `${oauthCfg.authUrl}?${querystring.stringify(authParams)}`;
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
+ });
1758
+ return;
1297
1759
  }
1298
- });
1299
- if (p2.isCancel(siteId)) {
1300
- p2.cancel("Operation cancelled.");
1301
- process.exit(0);
1760
+ await oauthExchangeCode(
1761
+ database,
1762
+ plugin,
1763
+ kek,
1764
+ tenantId,
1765
+ code,
1766
+ redirectUri,
1767
+ clientId,
1768
+ clientSecret,
1769
+ oauthCfg
1770
+ );
1771
+ return;
1302
1772
  }
1303
- const listSpin = p2.spinner();
1304
- listSpin.start("Fetching lists from site...");
1305
- let siteLists = [];
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
+ });
1781
+ }
1782
+ async function oauthExchangeCode(database, plugin, kek, tenantId, code, redirectUri, clientId, clientSecret, oauthCfg) {
1783
+ let tokens;
1306
1784
  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
- }
1785
+ tokens = await exchangeCodeForTokens(
1786
+ code,
1787
+ clientId,
1788
+ clientSecret,
1789
+ oauthCfg,
1790
+ redirectUri
1791
+ );
1792
+ } catch (err) {
1793
+ out({
1794
+ error: `Token exchange failed: ${err instanceof Error ? err.message : String(err)}`
1335
1795
  });
1336
- if (p2.isCancel(manualId)) {
1337
- p2.cancel("Operation cancelled.");
1338
- process.exit(0);
1339
- }
1340
- listId = manualId;
1796
+ return;
1341
1797
  }
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);
1798
+ if (!tokens.access_token) {
1799
+ out({
1800
+ error: `No access_token in response from ${oauthCfg.providerName}.`
1801
+ });
1802
+ return;
1353
1803
  }
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
- }
1804
+ const extraAccountFields = getCustomAccountFields(plugin, "oauth_2");
1805
+ const accountKm = createAccountKeyManager3({
1806
+ authType: "oauth_2",
1807
+ integrationName: plugin.id,
1808
+ tenantId,
1809
+ kek,
1810
+ database,
1811
+ extraAccountFields
1363
1812
  });
1364
- if (p2.isCancel(expiryInput)) {
1365
- p2.cancel("Operation cancelled.");
1366
- process.exit(0);
1813
+ await accountKm.set_access_token(tokens.access_token);
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
+ );
1820
+ out({ status: "success", plugin: plugin.id, tenant: tenantId });
1821
+ }
1822
+ async function oauthWithCode(database, plugin, kek, tenantId, code) {
1823
+ const oauthCfg = getOAuthConfigForPlugin(plugin);
1824
+ if (!oauthCfg) {
1825
+ out({ error: `No oauthConfig defined on plugin '${plugin.id}'.` });
1826
+ return;
1367
1827
  }
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
1828
+ const extraFields = getCustomIntegrationFields(plugin, "oauth_2");
1829
+ const integrationKm = createIntegrationKeyManager3({
1830
+ authType: "oauth_2",
1831
+ integrationName: plugin.id,
1832
+ kek,
1833
+ database,
1834
+ extraIntegrationFields: extraFields
1373
1835
  });
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);
1836
+ const clientId = await integrationKm.get_client_id();
1837
+ const clientSecret = await integrationKm.get_client_secret();
1838
+ const redirectUri = await integrationKm.get_redirect_url() ?? "";
1839
+ if (!clientId || !clientSecret) {
1840
+ out({
1841
+ error: `client_id and client_secret must be set before exchanging a code.`
1842
+ });
1843
+ return;
1396
1844
  }
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"
1845
+ await oauthExchangeCode(
1846
+ database,
1847
+ plugin,
1848
+ kek,
1849
+ tenantId,
1850
+ code,
1851
+ redirectUri,
1852
+ clientId,
1853
+ clientSecret,
1854
+ oauthCfg
1412
1855
  );
1413
- p2.outro("Done!");
1414
1856
  }
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
- );
1857
+ async function getCredentials(database, plugin, kek, tenantId) {
1858
+ const authType = getAuthType(plugin);
1859
+ const result = {};
1860
+ if (authType === "oauth_2") {
1861
+ const extraIntegrationFields = getCustomIntegrationFields(plugin, authType);
1862
+ const integrationKm = createIntegrationKeyManager3({
1863
+ authType,
1864
+ integrationName: plugin.id,
1865
+ kek,
1866
+ database,
1867
+ extraIntegrationFields
1868
+ });
1869
+ result.client_id = await integrationKm.get_client_id();
1870
+ result.client_secret = await integrationKm.get_client_secret();
1871
+ result.redirect_url = await integrationKm.get_redirect_url();
1872
+ for (const field of extraIntegrationFields) {
1873
+ const fn = integrationKm[`get_${field}`];
1874
+ if (typeof fn === "function")
1875
+ result[field] = await fn();
1876
+ }
1877
+ const extraAccountFields = getCustomAccountFields(plugin, authType);
1878
+ const accountKm = createAccountKeyManager3({
1879
+ authType,
1880
+ integrationName: plugin.id,
1881
+ tenantId,
1882
+ kek,
1883
+ database,
1884
+ extraAccountFields
1885
+ });
1886
+ result.access_token = await accountKm.get_access_token();
1887
+ result.refresh_token = await accountKm.get_refresh_token();
1888
+ result.expires_at = await accountKm.get_expires_at();
1889
+ result.webhook_signature = await accountKm.get_webhook_signature();
1890
+ for (const field of extraAccountFields) {
1891
+ const fn = accountKm[`get_${field}`];
1892
+ if (typeof fn === "function")
1893
+ result[field] = await fn();
1894
+ }
1895
+ } else if (authType === "api_key") {
1896
+ const extraAccountFields = getCustomAccountFields(plugin, authType);
1897
+ const accountKm = createAccountKeyManager3({
1898
+ authType,
1899
+ integrationName: plugin.id,
1900
+ tenantId,
1901
+ kek,
1902
+ database,
1903
+ extraAccountFields
1904
+ });
1905
+ result.api_key = await accountKm.get_api_key();
1906
+ result.webhook_signature = await accountKm.get_webhook_signature();
1907
+ } else if (authType === "bot_token") {
1908
+ const extraAccountFields = getCustomAccountFields(plugin, authType);
1909
+ const accountKm = createAccountKeyManager3({
1910
+ authType,
1911
+ integrationName: plugin.id,
1912
+ tenantId,
1913
+ kek,
1914
+ database,
1915
+ extraAccountFields
1916
+ });
1917
+ result.bot_token = await accountKm.get_bot_token();
1918
+ result.webhook_signature = await accountKm.get_webhook_signature();
1441
1919
  }
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}`);
1920
+ const masked = {};
1921
+ for (const [k, v] of Object.entries(result)) {
1922
+ if (!v) {
1923
+ masked[k] = null;
1924
+ continue;
1925
+ }
1926
+ masked[k] = v.length <= 9 ? "***" : `${v.slice(0, 6)}...${v.slice(-3)}`;
1463
1927
  }
1464
- return response.json();
1928
+ out({ plugin: plugin.id, tenant: tenantId, credentials: masked });
1465
1929
  }
1466
- async function runOutlookSubscribe({ cwd }) {
1467
- p3.intro("Corsair \u2014 Outlook Webhook Subscribe");
1468
- const spin = p3.spinner();
1469
- spin.start("Loading corsair instance...");
1930
+ async function runAuth({
1931
+ cwd,
1932
+ pluginId: pluginIdArg,
1933
+ tenantId: tenantIdArg,
1934
+ code: codeArg,
1935
+ credentials: showCredentials = false
1936
+ }) {
1470
1937
  let internal;
1471
1938
  try {
1472
- internal = await extractInternalConfig4(cwd);
1939
+ internal = await extractInternalConfig3(cwd);
1473
1940
  } catch (error) {
1474
- spin.stop("Failed to load.");
1475
- p3.log.error(error instanceof Error ? error.message : String(error));
1476
- p3.outro("");
1941
+ out({ error: error instanceof Error ? error.message : String(error) });
1477
1942
  process.exit(1);
1478
1943
  }
1479
1944
  const { plugins, database, kek } = internal;
1480
1945
  if (!database) {
1481
- spin.stop("Failed.");
1482
- p3.log.error("No database adapter configured.");
1483
- p3.outro("");
1946
+ out({ error: "No database adapter configured." });
1484
1947
  process.exit(1);
1485
1948
  }
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("");
1949
+ if (!pluginIdArg) {
1950
+ out({
1951
+ error: "No plugin specified. Use --plugin=<id>.",
1952
+ available: plugins.map((pl) => ({
1953
+ id: pl.id,
1954
+ authType: getAuthType(pl)
1955
+ }))
1956
+ });
1491
1957
  process.exit(1);
1492
1958
  }
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("");
1959
+ const plugin = plugins.find((pl) => pl.id === pluginIdArg);
1960
+ if (!plugin) {
1961
+ out({
1962
+ error: `Plugin '${pluginIdArg}' not found.`,
1963
+ available: plugins.map((pl) => pl.id)
1964
+ });
1518
1965
  process.exit(1);
1519
1966
  }
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
- }
1967
+ const integration = await ensureIntegration(database, plugin.id, kek);
1968
+ const tenantId = tenantIdArg ?? "default";
1969
+ await ensureAccount(database, integration.id, tenantId, kek);
1970
+ if (showCredentials) {
1971
+ await getCredentials(database, plugin, kek, tenantId);
1972
+ return;
1584
1973
  }
1585
- if (results.length > 0) {
1586
- p3.note(results.join("\n\n"), "Subscriptions created");
1974
+ const authType = getAuthType(plugin);
1975
+ if (authType !== "oauth_2") {
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
+ });
1979
+ return;
1587
1980
  }
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.");
1981
+ if (codeArg) {
1982
+ await oauthWithCode(database, plugin, kek, tenantId, codeArg);
1594
1983
  } else {
1595
- p3.log.warn("Some subscriptions failed. Check errors above.");
1984
+ await oauthGetUrl(database, plugin, kek, tenantId);
1596
1985
  }
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
1986
  }
1606
- var GRAPH_API_BASE3, OUTLOOK_RESOURCES;
1607
- var init_subscribe_outlook = __esm({
1608
- "subscribe-outlook.ts"() {
1987
+ var init_auth = __esm({
1988
+ "auth.ts"() {
1609
1989
  "use strict";
1610
1990
  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
1991
  }
1648
1992
  });
1649
1993
 
@@ -1821,9 +2165,13 @@ or reinstall your dependencies:
1821
2165
  rm -rf node_modules && npm install`
1822
2166
  );
1823
2167
  }
1824
- 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
+ );
1825
2171
  console.log("");
1826
- 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
+ );
1827
2175
  console.log("[#corsair]: Try running:");
1828
2176
  console.log(" npm rebuild");
1829
2177
  console.log("[#corsair]: Or reinstall your dependencies:");
@@ -1877,7 +2225,9 @@ function resolveClient(instance, tenant) {
1877
2225
  const obj = instance;
1878
2226
  if ("withTenant" in obj && typeof obj.withTenant === "function") {
1879
2227
  if (!tenant) {
1880
- 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
+ );
1881
2231
  process.exit(1);
1882
2232
  }
1883
2233
  return obj.withTenant(tenant);
@@ -1918,11 +2268,16 @@ function parseAuthArgs(args) {
1918
2268
  let tenantId;
1919
2269
  let code;
1920
2270
  let credentials = false;
2271
+ let webhook = false;
1921
2272
  for (const arg of args) {
1922
2273
  if (arg === "--credentials") {
1923
2274
  credentials = true;
1924
2275
  continue;
1925
2276
  }
2277
+ if (arg === "--webhook") {
2278
+ webhook = true;
2279
+ continue;
2280
+ }
1926
2281
  const eqIdx = arg.indexOf("=");
1927
2282
  if (arg.startsWith("--") && eqIdx !== -1) {
1928
2283
  const key = arg.slice(2, eqIdx);
@@ -1941,7 +2296,7 @@ function parseAuthArgs(args) {
1941
2296
  }
1942
2297
  }
1943
2298
  }
1944
- return { pluginId, tenantId, code, credentials };
2299
+ return { pluginId, tenantId, code, credentials, webhook };
1945
2300
  }
1946
2301
  function parseSetupArgs(args) {
1947
2302
  let backfill = false;
@@ -2016,6 +2371,8 @@ function printHelp() {
2016
2371
  " pnpm corsair auth --plugin=<id> Start OAuth flow",
2017
2372
  " pnpm corsair auth --plugin=<id> --code=<code> Exchange OAuth code for tokens",
2018
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",
2019
2376
  " pnpm corsair list [--plugin=<id>] [--type=api|webhooks|db] List endpoint paths (tip: pipe to grep to filter)",
2020
2377
  " pnpm corsair schema <path> Show schema for an endpoint/webhook/DB entity",
2021
2378
  ' pnpm corsair script --code "<js>" [--tenant=<id>]',
@@ -2023,9 +2380,7 @@ function printHelp() {
2023
2380
  " IMPORTANT: Always filter results inline \u2014 you are the consumer of the return value, so returning full list responses wastes tokens.",
2024
2381
  " Bad: return await corsair.slack.api.users.list({})",
2025
2382
  " Good: return (await corsair.slack.api.users.list({})).members.find(u => u.name === 'bob')?.id",
2026
- ...SHOW_RUN ? [
2027
- " run <path> [input-json] [--tenant=<id>] Call an endpoint directly"
2028
- ] : []
2383
+ ...SHOW_RUN ? [" run <path> [input-json] [--tenant=<id>] Call an endpoint directly"] : []
2029
2384
  ];
2030
2385
  console.log(lines.join("\n"));
2031
2386
  }
@@ -2045,33 +2400,70 @@ async function main() {
2045
2400
  return;
2046
2401
  }
2047
2402
  if (command === "auth") {
2048
- const { runAuth: runAuth2 } = await Promise.resolve().then(() => (init_auth(), auth_exports));
2049
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));
2050
2439
  await runAuth2({ cwd, ...authArgs });
2051
2440
  return;
2052
2441
  }
2053
2442
  if (command === "watch-renew") {
2054
- const { runWatchRenew: runWatchRenew2 } = await Promise.resolve().then(() => (init_watch_renew(), watch_renew_exports));
2055
- await runWatchRenew2({ cwd });
2443
+ const { runGoogleSubscribe: runGoogleSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_google(), subscribe_google_exports));
2444
+ await runGoogleSubscribe2({ cwd });
2056
2445
  return;
2057
2446
  }
2058
2447
  if (command === "sharepoint-subscribe") {
2059
- const { runSharepointSubscribe: runSharepointSubscribe2 } = await Promise.resolve().then(() => (init_sharepoint_subscribe(), sharepoint_subscribe_exports));
2448
+ const { runSharepointSubscribe: runSharepointSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2060
2449
  await runSharepointSubscribe2({ cwd });
2450
+ return;
2061
2451
  }
2062
2452
  if (command === "subscribe") {
2063
2453
  const pluginArg = args.slice(1).find((a) => a.startsWith("--plugin="));
2064
2454
  const pluginId = pluginArg ? pluginArg.slice("--plugin=".length) : void 0;
2065
2455
  if (pluginId === "outlook") {
2066
- const { runOutlookSubscribe: runOutlookSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_outlook(), subscribe_outlook_exports));
2456
+ const { runOutlookSubscribe: runOutlookSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2067
2457
  await runOutlookSubscribe2({ cwd });
2068
2458
  return;
2069
2459
  }
2070
- console.error(`[#corsair]: Unknown plugin for subscribe: '${pluginId ?? "(none)"}'. Supported: outlook`);
2460
+ console.error(
2461
+ `[#corsair]: Unknown plugin for subscribe: '${pluginId ?? "(none)"}'. Supported: outlook`
2462
+ );
2071
2463
  process.exit(1);
2072
2464
  }
2073
2465
  if (command === "teams-subscribe") {
2074
- const { runTeamsSubscribe: runTeamsSubscribe2 } = await Promise.resolve().then(() => (init_watch_renew(), watch_renew_exports));
2466
+ const { runTeamsSubscribe: runTeamsSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2075
2467
  await runTeamsSubscribe2({ cwd });
2076
2468
  return;
2077
2469
  }
@@ -2080,7 +2472,9 @@ async function main() {
2080
2472
  const instance = await getCorsairInstance({ cwd });
2081
2473
  const corsair = instance;
2082
2474
  if (typeof corsair.list_operations !== "function") {
2083
- 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
+ );
2084
2478
  process.exit(1);
2085
2479
  }
2086
2480
  const result = corsair.list_operations({ plugin, type });
@@ -2099,7 +2493,9 @@ async function main() {
2099
2493
  const { path: endpointPath, input, tenant } = parseRunArgs(args.slice(1));
2100
2494
  if (!endpointPath) {
2101
2495
  console.error("[#corsair]: Usage: corsair run <path> [input-json]");
2102
- 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
+ );
2103
2499
  process.exit(1);
2104
2500
  }
2105
2501
  const instance = await getCorsairInstance({ cwd });
@@ -2107,7 +2503,9 @@ async function main() {
2107
2503
  const fn = navigateToEndpoint(client, endpointPath);
2108
2504
  if (!fn) {
2109
2505
  console.error(`[#corsair]: Could not find endpoint "${endpointPath}".`);
2110
- 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
+ );
2111
2509
  process.exit(1);
2112
2510
  }
2113
2511
  let parsedInput = {};
@@ -2115,7 +2513,9 @@ async function main() {
2115
2513
  try {
2116
2514
  parsedInput = JSON.parse(input);
2117
2515
  } catch {
2118
- 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
+ );
2119
2519
  process.exit(1);
2120
2520
  }
2121
2521
  }
@@ -2133,7 +2533,9 @@ async function main() {
2133
2533
  const { code, tenant } = parseScriptArgs(args.slice(1));
2134
2534
  if (!code) {
2135
2535
  console.error('[#corsair]: Usage: corsair script --code "<js>"');
2136
- 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
+ );
2137
2539
  process.exit(1);
2138
2540
  }
2139
2541
  const instance = await getCorsairInstance({ cwd });
@@ -2157,13 +2559,17 @@ async function main() {
2157
2559
  const schemaPath = args[1];
2158
2560
  if (!schemaPath) {
2159
2561
  console.error("[#corsair]: Usage: corsair schema <path>");
2160
- console.error("[#corsair]: Example: corsair schema slack.api.messages.post");
2562
+ console.error(
2563
+ "[#corsair]: Example: corsair schema slack.api.messages.post"
2564
+ );
2161
2565
  process.exit(1);
2162
2566
  }
2163
2567
  const instance = await getCorsairInstance({ cwd });
2164
2568
  const corsair = instance;
2165
2569
  if (typeof corsair.get_schema !== "function") {
2166
- 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
+ );
2167
2573
  process.exit(1);
2168
2574
  }
2169
2575
  const result = corsair.get_schema(schemaPath);