@corsair-dev/cli 0.1.8 → 0.1.10

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 (45) hide show
  1. package/dist/auth.d.ts +3 -1
  2. package/dist/auth.d.ts.map +1 -1
  3. package/dist/google/calendar.d.ts +2 -0
  4. package/dist/google/calendar.d.ts.map +1 -0
  5. package/dist/google/drive.d.ts +2 -0
  6. package/dist/google/drive.d.ts.map +1 -0
  7. package/dist/google/gmail.d.ts +2 -0
  8. package/dist/google/gmail.d.ts.map +1 -0
  9. package/dist/google/index.d.ts +5 -0
  10. package/dist/google/index.d.ts.map +1 -0
  11. package/dist/google/shared.d.ts +3 -0
  12. package/dist/google/shared.d.ts.map +1 -0
  13. package/dist/google/sheets.d.ts +2 -0
  14. package/dist/google/sheets.d.ts.map +1 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +1718 -1220
  17. package/dist/microsoft/credentials.d.ts +15 -0
  18. package/dist/microsoft/credentials.d.ts.map +1 -0
  19. package/dist/microsoft/graph.d.ts +6 -0
  20. package/dist/microsoft/graph.d.ts.map +1 -0
  21. package/dist/microsoft/onedrive.d.ts +4 -0
  22. package/dist/microsoft/onedrive.d.ts.map +1 -0
  23. package/dist/microsoft/outlook.d.ts +4 -0
  24. package/dist/microsoft/outlook.d.ts.map +1 -0
  25. package/dist/microsoft/sharepoint.d.ts +4 -0
  26. package/dist/microsoft/sharepoint.d.ts.map +1 -0
  27. package/dist/microsoft/teams.d.ts +4 -0
  28. package/dist/microsoft/teams.d.ts.map +1 -0
  29. package/dist/subscribe-google.d.ts +2 -0
  30. package/dist/subscribe-google.d.ts.map +1 -0
  31. package/dist/subscribe-microsoft.d.ts +5 -0
  32. package/dist/subscribe-microsoft.d.ts.map +1 -0
  33. package/dist/utils/corsair.d.ts +3 -0
  34. package/dist/utils/corsair.d.ts.map +1 -0
  35. package/dist/utils/load-config.d.ts +6 -0
  36. package/dist/utils/load-config.d.ts.map +1 -0
  37. package/dist/utils/prompts.d.ts +4 -0
  38. package/dist/utils/prompts.d.ts.map +1 -0
  39. package/package.json +2 -2
  40. package/dist/sharepoint-subscribe.d.ts +0 -4
  41. package/dist/sharepoint-subscribe.d.ts.map +0 -1
  42. package/dist/subscribe-outlook.d.ts +0 -4
  43. package/dist/subscribe-outlook.d.ts.map +0 -1
  44. package/dist/watch-renew.d.ts +0 -7
  45. 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,287 +50,225 @@ 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 });
271
- }
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;
108
+ if (p2.isCancel(tenantId)) {
109
+ p2.cancel("Operation cancelled.");
110
+ process.exit(0);
277
111
  }
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
112
+ return tenantId;
113
+ }
114
+ async function promptWebhookUrl() {
115
+ const webhookUrl = await p2.text({
116
+ message: "Enter your public webhook URL (ngrok or production):",
117
+ placeholder: "https://abc123.ngrok-free.app/api/webhook",
118
+ validate: (v) => {
119
+ if (!v || v.trim().length === 0) return "Webhook URL is required";
120
+ if (!v.startsWith("https://"))
121
+ return "URL must start with https:// (Microsoft Graph requires HTTPS)";
122
+ }
285
123
  });
286
- const clientId = await integrationKm.get_client_id();
287
- const clientSecret = await integrationKm.get_client_secret();
288
- const redirectUri = await integrationKm.get_redirect_url() ?? "";
289
- if (!clientId || !clientSecret) {
290
- out({ error: `client_id and client_secret must be set before exchanging a code.` });
291
- return;
124
+ if (p2.isCancel(webhookUrl)) {
125
+ p2.cancel("Operation cancelled.");
126
+ process.exit(0);
292
127
  }
293
- await oauthExchangeCode(database, plugin, kek, tenantId, code, redirectUri, clientId, clientSecret, oauthCfg);
128
+ return webhookUrl;
294
129
  }
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
322
- });
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();
330
- }
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();
355
- }
356
- const masked = {};
357
- for (const [k, v] of Object.entries(result)) {
358
- if (!v) {
359
- masked[k] = null;
360
- continue;
361
- }
362
- masked[k] = v.length <= 9 ? "***" : `${v.slice(0, 6)}...${v.slice(-3)}`;
130
+ async function promptClientState() {
131
+ const autoSecret = crypto.randomBytes(16).toString("hex");
132
+ const clientState = await p2.text({
133
+ message: "Enter a clientState secret (used to verify webhook payloads):",
134
+ defaultValue: autoSecret,
135
+ placeholder: autoSecret
136
+ });
137
+ if (p2.isCancel(clientState)) {
138
+ p2.cancel("Operation cancelled.");
139
+ process.exit(0);
363
140
  }
364
- out({ plugin: plugin.id, tenant: tenantId, credentials: masked });
141
+ return clientState;
365
142
  }
366
- async function runAuth({
367
- cwd,
368
- pluginId: pluginIdArg,
369
- tenantId: tenantIdArg,
370
- code: codeArg,
371
- credentials: showCredentials = false
372
- }) {
373
- let internal;
374
- try {
375
- internal = await extractInternalConfig(cwd);
376
- } catch (error) {
377
- out({ error: error instanceof Error ? error.message : String(error) });
378
- process.exit(1);
143
+ var init_prompts = __esm({
144
+ "utils/prompts.ts"() {
145
+ "use strict";
379
146
  }
380
- const { plugins, database, kek } = internal;
381
- if (!database) {
382
- out({ error: "No database adapter configured." });
383
- process.exit(1);
147
+ });
148
+
149
+ // microsoft/credentials.ts
150
+ import * as p3 from "@clack/prompts";
151
+ import {
152
+ createAccountKeyManager,
153
+ createIntegrationKeyManager
154
+ } from "corsair/core";
155
+ async function refreshMicrosoftToken(clientId, clientSecret, refreshToken) {
156
+ const response = await fetch(MICROSOFT_TOKEN_URL, {
157
+ method: "POST",
158
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
159
+ body: new URLSearchParams({
160
+ client_id: clientId,
161
+ client_secret: clientSecret,
162
+ refresh_token: refreshToken,
163
+ grant_type: "refresh_token"
164
+ })
165
+ });
166
+ if (!response.ok) {
167
+ const error = await response.text();
168
+ throw new Error(`Token refresh failed: ${error}`);
384
169
  }
385
- if (!pluginIdArg) {
386
- out({
387
- error: "No plugin specified. Use --plugin=<id>.",
388
- available: plugins.map((pl) => ({ id: pl.id, authType: getAuthType(pl) }))
389
- });
170
+ return response.json();
171
+ }
172
+ async function resolveAccessToken(integrationName, tenantId, internal) {
173
+ const { kek, database } = internal;
174
+ const credSpin = p3.spinner();
175
+ credSpin.start(`Fetching ${integrationName} credentials...`);
176
+ const integrationKm = createIntegrationKeyManager({
177
+ authType: "oauth_2",
178
+ integrationName,
179
+ kek,
180
+ database
181
+ });
182
+ const accountKm = createAccountKeyManager({
183
+ authType: "oauth_2",
184
+ integrationName,
185
+ tenantId,
186
+ kek,
187
+ database
188
+ });
189
+ const [
190
+ clientId,
191
+ clientSecret,
192
+ storedAccessToken,
193
+ expiresAt,
194
+ storedRefreshToken
195
+ ] = await Promise.all([
196
+ integrationKm.get_client_id(),
197
+ integrationKm.get_client_secret(),
198
+ accountKm.get_access_token(),
199
+ accountKm.get_expires_at(),
200
+ accountKm.get_refresh_token()
201
+ ]);
202
+ if (!storedRefreshToken) {
203
+ credSpin.stop("Missing credentials.");
204
+ p3.log.error(
205
+ `No refresh token found. Run: pnpm corsair auth --plugin=${integrationName}`
206
+ );
207
+ p3.outro("");
390
208
  process.exit(1);
391
209
  }
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) });
210
+ if (!clientId || !clientSecret) {
211
+ credSpin.stop("Missing credentials.");
212
+ p3.log.error(
213
+ `Client ID/Secret not configured. Run: pnpm corsair setup --${integrationName}`
214
+ );
215
+ p3.outro("");
395
216
  process.exit(1);
396
217
  }
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;
403
- }
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;
218
+ let accessToken = storedAccessToken;
219
+ const now = Math.floor(Date.now() / 1e3);
220
+ const needsRefresh = !accessToken || !expiresAt || Number(expiresAt) <= now + 5 * 60;
221
+ if (needsRefresh) {
222
+ credSpin.message("Refreshing access token...");
223
+ try {
224
+ const tokenData = await refreshMicrosoftToken(
225
+ clientId,
226
+ clientSecret,
227
+ storedRefreshToken
228
+ );
229
+ accessToken = tokenData.access_token;
230
+ await accountKm.set_access_token(tokenData.access_token);
231
+ await accountKm.set_expires_at(String(now + tokenData.expires_in));
232
+ if (tokenData.refresh_token) {
233
+ await accountKm.set_refresh_token(tokenData.refresh_token);
234
+ }
235
+ } catch (error) {
236
+ credSpin.stop("Failed.");
237
+ p3.log.error(error instanceof Error ? error.message : String(error));
238
+ p3.outro("");
239
+ process.exit(1);
240
+ }
408
241
  }
409
- if (codeArg) {
410
- await oauthWithCode(database, plugin, kek, tenantId, codeArg);
411
- } else {
412
- await oauthGetUrl(database, plugin, kek, tenantId);
242
+ if (!accessToken) {
243
+ credSpin.stop("Missing credentials.");
244
+ p3.log.error(
245
+ `Could not obtain a valid access token. Run: pnpm corsair auth --plugin=${integrationName}`
246
+ );
247
+ p3.outro("");
248
+ process.exit(1);
413
249
  }
250
+ credSpin.stop("Credentials loaded.");
251
+ return { accessToken, accountKm };
414
252
  }
415
- var init_auth = __esm({
416
- "auth.ts"() {
253
+ async function saveWebhookSignature(accountKm, clientState) {
254
+ const saveSpin = p3.spinner();
255
+ saveSpin.start("Saving webhook secret...");
256
+ await accountKm.set_webhook_signature(clientState);
257
+ saveSpin.stop("Webhook secret saved.");
258
+ }
259
+ var MICROSOFT_TOKEN_URL;
260
+ var init_credentials = __esm({
261
+ "microsoft/credentials.ts"() {
417
262
  "use strict";
418
- init_index();
263
+ MICROSOFT_TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
419
264
  }
420
265
  });
421
266
 
422
- // watch-renew.ts
423
- var watch_renew_exports = {};
424
- __export(watch_renew_exports, {
425
- runTeamsSubscribe: () => runTeamsSubscribe,
426
- runWatchRenew: () => runWatchRenew
427
- });
428
- import { execSync } from "child_process";
429
- import * as crypto from "crypto";
430
- import * as p from "@clack/prompts";
431
- import {
432
- CORSAIR_INTERNAL as CORSAIR_INTERNAL2,
433
- createAccountKeyManager as createAccountKeyManager2,
434
- createIntegrationKeyManager as createIntegrationKeyManager2
435
- } from "corsair/core";
436
- function buildTeamsResource(resourceType, ids) {
437
- switch (resourceType) {
438
- case "channelMessage":
439
- return `teams/${ids.teamId}/channels/${ids.channelId}/messages`;
440
- case "chatMessage":
441
- return `chats/${ids.chatId}/messages`;
442
- case "channelCreated":
443
- return `teams/${ids.teamId}/channels`;
444
- case "membershipChanged":
445
- return `teams/${ids.teamId}/members`;
446
- }
447
- }
448
- async function createTeamsSubscription(accessToken, notificationUrl, resource, clientState, expiryMinutes) {
449
- const expirationDateTime = new Date(Date.now() + expiryMinutes * 60 * 1e3).toISOString();
267
+ // microsoft/graph.ts
268
+ async function createGraphSubscription(accessToken, notificationUrl, resource, changeType, clientState, expiryMinutes) {
269
+ const expirationDateTime = new Date(
270
+ Date.now() + expiryMinutes * 60 * 1e3
271
+ ).toISOString();
450
272
  const response = await fetch(`${GRAPH_API_BASE}/subscriptions`, {
451
273
  method: "POST",
452
274
  headers: {
@@ -454,7 +276,7 @@ async function createTeamsSubscription(accessToken, notificationUrl, resource, c
454
276
  "Content-Type": "application/json"
455
277
  },
456
278
  body: JSON.stringify({
457
- changeType: "created,updated,deleted",
279
+ changeType,
458
280
  notificationUrl,
459
281
  resource,
460
282
  expirationDateTime,
@@ -467,252 +289,765 @@ async function createTeamsSubscription(accessToken, notificationUrl, resource, c
467
289
  }
468
290
  return response.json();
469
291
  }
470
- async function runTeamsSubscribe({ cwd }) {
471
- p.intro("Corsair \u2014 Microsoft Teams Webhook Subscribe");
472
- const spin = p.spinner();
473
- spin.start("Loading corsair instance...");
474
- let internal;
475
- try {
476
- internal = await extractInternalConfig2(cwd);
477
- } catch (error) {
478
- spin.stop("Failed to load.");
479
- p.log.error(error instanceof Error ? error.message : String(error));
480
- p.outro("");
481
- process.exit(1);
482
- }
483
- const { plugins, database, kek } = internal;
484
- if (!database) {
485
- spin.stop("Failed.");
486
- p.log.error("No database adapter configured.");
487
- p.outro("");
488
- process.exit(1);
489
- }
490
- const teamsPlugin = plugins.find((pl) => pl.id === "teams");
491
- if (!teamsPlugin) {
492
- spin.stop("Teams plugin not found.");
493
- p.log.error("Add the teams plugin to your corsair instance first.");
494
- p.outro("");
495
- process.exit(1);
292
+ var GRAPH_API_BASE;
293
+ var init_graph = __esm({
294
+ "microsoft/graph.ts"() {
295
+ "use strict";
296
+ GRAPH_API_BASE = "https://graph.microsoft.com/v1.0";
496
297
  }
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);
298
+ });
299
+
300
+ // microsoft/onedrive.ts
301
+ import * as p4 from "@clack/prompts";
302
+ function buildOnedriveResource(resourceType, ids) {
303
+ switch (resourceType) {
304
+ case "personalDrive":
305
+ return "me/drive/root";
306
+ case "specificDrive":
307
+ return `drives/${ids.driveId}/root`;
308
+ case "specificFolder":
309
+ return `me/drive/items/${ids.itemId}`;
506
310
  }
507
- const credSpin = p.spinner();
508
- credSpin.start("Fetching Teams credentials...");
509
- const accountKm = createAccountKeyManager2({
510
- authType: "oauth_2",
511
- integrationName: "teams",
311
+ }
312
+ async function runOnedriveSubscribe({
313
+ cwd
314
+ }) {
315
+ const { internal } = await loadInternalConfig(
316
+ cwd,
317
+ "Corsair \u2014 OneDrive Webhook Subscribe",
318
+ "onedrive",
319
+ "OneDrive"
320
+ );
321
+ const tenantId = await promptTenantId();
322
+ const { accessToken, accountKm } = await resolveAccessToken(
323
+ "onedrive",
512
324
  tenantId,
513
- kek,
514
- database,
515
- extraAccountFields: ["one"]
325
+ internal
326
+ );
327
+ const webhookUrl = await promptWebhookUrl();
328
+ const selectedResourceTypes = await p4.multiselect({
329
+ message: "Select resources to subscribe to:",
330
+ options: ONEDRIVE_RESOURCE_OPTIONS,
331
+ required: true
516
332
  });
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);
333
+ if (p4.isCancel(selectedResourceTypes)) {
334
+ p4.cancel("Operation cancelled.");
335
+ process.exit(0);
523
336
  }
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)";
337
+ const resourceConfigs = [];
338
+ for (const resourceType of selectedResourceTypes) {
339
+ const ids = {};
340
+ if (resourceType === "specificDrive") {
341
+ const driveId = await p4.text({
342
+ message: `[${resourceType}] Enter drive ID:`,
343
+ placeholder: "b!abc123...",
344
+ validate: (v) => {
345
+ if (!v || !v.trim()) return "Drive ID is required";
346
+ }
347
+ });
348
+ if (p4.isCancel(driveId)) {
349
+ p4.cancel("Operation cancelled.");
350
+ process.exit(0);
351
+ }
352
+ ids.driveId = driveId;
353
+ } else if (resourceType === "specificFolder") {
354
+ const itemId = await p4.text({
355
+ message: `[${resourceType}] Enter item/folder ID:`,
356
+ placeholder: "01ABC123...",
357
+ validate: (v) => {
358
+ if (!v || !v.trim()) return "Item ID is required";
359
+ }
360
+ });
361
+ if (p4.isCancel(itemId)) {
362
+ p4.cancel("Operation cancelled.");
363
+ process.exit(0);
364
+ }
365
+ ids.itemId = itemId;
366
+ }
367
+ resourceConfigs.push({ resourceType, ids });
368
+ }
369
+ const clientState = await promptClientState();
370
+ const results = [];
371
+ let hasError = false;
372
+ for (const { resourceType, ids } of resourceConfigs) {
373
+ const resource = buildOnedriveResource(resourceType, ids);
374
+ const subSpin = p4.spinner();
375
+ subSpin.start(`Creating subscription: ${resourceType}...`);
376
+ try {
377
+ const subscription = await createGraphSubscription(
378
+ accessToken,
379
+ webhookUrl,
380
+ resource,
381
+ "updated",
382
+ clientState,
383
+ ONEDRIVE_MAX_EXPIRY_MINUTES
384
+ );
385
+ subSpin.stop(`Created: ${resourceType}`);
386
+ results.push(
387
+ `${resourceType}
388
+ Resource: ${resource}
389
+ ID: ${subscription.id}
390
+ Expires: ${subscription.expirationDateTime}`
391
+ );
392
+ } catch (error) {
393
+ subSpin.stop(`Failed: ${resourceType}`);
394
+ p4.log.error(error instanceof Error ? error.message : String(error));
395
+ hasError = true;
531
396
  }
397
+ }
398
+ if (results.length > 0) {
399
+ p4.note(results.join("\n\n"), "Subscriptions created");
400
+ }
401
+ await saveWebhookSignature(accountKm, clientState);
402
+ if (!hasError) {
403
+ p4.log.success("OneDrive webhook subscriptions set up successfully.");
404
+ } else {
405
+ p4.log.warn("Some subscriptions failed. Check errors above.");
406
+ }
407
+ p4.note(
408
+ `ClientState: ${clientState}
409
+ Webhook URL: ${webhookUrl}
410
+
411
+ Note: OneDrive subscriptions expire. Re-run this command to renew.`,
412
+ "Setup complete"
413
+ );
414
+ p4.outro("Done!");
415
+ }
416
+ var ONEDRIVE_MAX_EXPIRY_MINUTES, ONEDRIVE_RESOURCE_OPTIONS;
417
+ var init_onedrive = __esm({
418
+ "microsoft/onedrive.ts"() {
419
+ "use strict";
420
+ init_load_config();
421
+ init_prompts();
422
+ init_credentials();
423
+ init_graph();
424
+ ONEDRIVE_MAX_EXPIRY_MINUTES = 4230;
425
+ ONEDRIVE_RESOURCE_OPTIONS = [
426
+ {
427
+ value: "personalDrive",
428
+ label: "Personal Drive Root \u2014 all changes to the user's drive",
429
+ hint: "me/drive/root"
430
+ },
431
+ {
432
+ value: "specificDrive",
433
+ label: "Specific Drive Root \u2014 all changes to a given drive ID",
434
+ hint: "drives/{driveId}/root"
435
+ },
436
+ {
437
+ value: "specificFolder",
438
+ label: "Specific Folder \u2014 changes within a given item/folder",
439
+ hint: "me/drive/items/{itemId}"
440
+ }
441
+ ];
442
+ }
443
+ });
444
+
445
+ // microsoft/outlook.ts
446
+ import * as p5 from "@clack/prompts";
447
+ async function runOutlookSubscribe({
448
+ cwd
449
+ }) {
450
+ const { internal } = await loadInternalConfig(
451
+ cwd,
452
+ "Corsair \u2014 Outlook Webhook Subscribe",
453
+ "outlook",
454
+ "Outlook"
455
+ );
456
+ const tenantId = await promptTenantId();
457
+ const { accessToken, accountKm } = await resolveAccessToken(
458
+ "outlook",
459
+ tenantId,
460
+ internal
461
+ );
462
+ const webhookUrl = await promptWebhookUrl();
463
+ const selected = await p5.multiselect({
464
+ message: "Select resources to subscribe to:",
465
+ options: Object.entries(OUTLOOK_RESOURCES).map(([value, cfg]) => ({
466
+ value,
467
+ label: cfg.label,
468
+ hint: `${cfg.resource} [${cfg.changeType}]`
469
+ })),
470
+ required: true
532
471
  });
533
- if (p.isCancel(webhookUrl)) {
534
- p.cancel("Operation cancelled.");
472
+ if (p5.isCancel(selected)) {
473
+ p5.cancel("Operation cancelled.");
535
474
  process.exit(0);
536
475
  }
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
- ]
476
+ const clientState = await promptClientState();
477
+ const results = [];
478
+ let hasError = false;
479
+ for (const value of selected) {
480
+ const cfg = OUTLOOK_RESOURCES[value];
481
+ const subSpin = p5.spinner();
482
+ subSpin.start(`Creating subscription: ${cfg.label}...`);
483
+ try {
484
+ const subscription = await createGraphSubscription(
485
+ accessToken,
486
+ webhookUrl,
487
+ cfg.resource,
488
+ cfg.changeType,
489
+ clientState,
490
+ cfg.expiryMinutes
491
+ );
492
+ subSpin.stop(`Created: ${cfg.label}`);
493
+ results.push(
494
+ `${cfg.label}
495
+ ID: ${subscription.id}
496
+ Expires: ${subscription.expirationDateTime}`
497
+ );
498
+ } catch (error) {
499
+ subSpin.stop(`Failed: ${cfg.label}`);
500
+ p5.log.error(error instanceof Error ? error.message : String(error));
501
+ hasError = true;
502
+ }
503
+ }
504
+ if (results.length > 0) {
505
+ p5.note(results.join("\n\n"), "Subscriptions created");
506
+ }
507
+ await saveWebhookSignature(accountKm, clientState);
508
+ if (!hasError) {
509
+ p5.log.success("Outlook webhook subscriptions set up successfully.");
510
+ } else {
511
+ p5.log.warn("Some subscriptions failed. Check errors above.");
512
+ }
513
+ p5.note(
514
+ `ClientState: ${clientState}
515
+ Webhook URL: ${webhookUrl}
516
+
517
+ Note: Outlook subscriptions expire. Re-run this command to renew.`,
518
+ "Setup complete"
519
+ );
520
+ p5.outro("Done!");
521
+ }
522
+ var OUTLOOK_RESOURCES;
523
+ var init_outlook = __esm({
524
+ "microsoft/outlook.ts"() {
525
+ "use strict";
526
+ init_load_config();
527
+ init_prompts();
528
+ init_credentials();
529
+ init_graph();
530
+ OUTLOOK_RESOURCES = {
531
+ inboxMessages: {
532
+ resource: "me/mailFolders/inbox/messages",
533
+ changeType: "created",
534
+ label: "Inbox Messages \u2014 new messages received",
535
+ expiryMinutes: 4320
536
+ // 3 days (max for mail)
537
+ },
538
+ sentMessages: {
539
+ resource: "me/mailFolders/sentItems/messages",
540
+ changeType: "created",
541
+ label: "Sent Items \u2014 messages sent",
542
+ expiryMinutes: 4320
543
+ },
544
+ newEvents: {
545
+ resource: "me/events",
546
+ changeType: "created",
547
+ label: "Calendar Events \u2014 new events created",
548
+ expiryMinutes: 4230
549
+ // max for calendar
550
+ },
551
+ eventChanges: {
552
+ resource: "me/events",
553
+ changeType: "updated,deleted",
554
+ label: "Calendar Events \u2014 updates & deletions",
555
+ expiryMinutes: 4230
556
+ },
557
+ newContacts: {
558
+ resource: "me/contacts",
559
+ changeType: "created",
560
+ label: "Contacts \u2014 new contacts created",
561
+ expiryMinutes: 4230
562
+ // max for contacts
563
+ }
564
+ };
565
+ }
566
+ });
567
+
568
+ // microsoft/sharepoint.ts
569
+ import * as p6 from "@clack/prompts";
570
+ function buildSiteUrl(siteId, subpath) {
571
+ const isHostnamePath = siteId.includes(":") && !siteId.includes(",");
572
+ return isHostnamePath ? `${GRAPH_API_BASE}/sites/${siteId}:/${subpath}` : `${GRAPH_API_BASE}/sites/${siteId}/${subpath}`;
573
+ }
574
+ async function fetchSiteLists(accessToken, siteId) {
575
+ const response = await fetch(
576
+ `${buildSiteUrl(siteId, "lists")}?$select=id,displayName,webUrl`,
577
+ { headers: { Authorization: `Bearer ${accessToken}` } }
578
+ );
579
+ if (!response.ok) {
580
+ const error = await response.text();
581
+ throw new Error(`Failed to fetch site lists: ${error}`);
582
+ }
583
+ const data = await response.json();
584
+ return data.value ?? [];
585
+ }
586
+ async function createSharepointSubscription(accessToken, siteId, listId, notificationUrl, clientState, expiryDays) {
587
+ const expirationDateTime = new Date(
588
+ Date.now() + expiryDays * 24 * 60 * 60 * 1e3
589
+ ).toISOString();
590
+ const response = await fetch(
591
+ buildSiteUrl(siteId, `lists/${encodeURIComponent(listId)}/subscriptions`),
592
+ {
593
+ method: "POST",
594
+ headers: {
595
+ Authorization: `Bearer ${accessToken}`,
596
+ "Content-Type": "application/json"
597
+ },
598
+ body: JSON.stringify({
599
+ notificationUrl,
600
+ expirationDateTime,
601
+ clientState
602
+ })
603
+ }
604
+ );
605
+ if (!response.ok) {
606
+ const error = await response.text();
607
+ throw new Error(`SharePoint subscription failed: ${error}`);
608
+ }
609
+ return response.json();
610
+ }
611
+ async function runSharepointSubscribe({
612
+ cwd
613
+ }) {
614
+ const { internal, plugin: sharepointPlugin } = await loadInternalConfig(
615
+ cwd,
616
+ "Corsair \u2014 SharePoint Webhook Subscribe",
617
+ "sharepoint",
618
+ "SharePoint"
619
+ );
620
+ const tenantId = await promptTenantId();
621
+ const { accessToken, accountKm } = await resolveAccessToken(
622
+ "sharepoint",
623
+ tenantId,
624
+ internal
625
+ );
626
+ const webhookUrl = await promptWebhookUrl();
627
+ const pluginOptions = sharepointPlugin.options;
628
+ const defaultSiteId = pluginOptions?.siteId ?? "";
629
+ const siteId = await p6.text({
630
+ message: "Enter SharePoint site ID:",
631
+ defaultValue: defaultSiteId,
632
+ placeholder: "corsairdev.sharepoint.com:/sites/MySite or tenant.sharepoint.com,siteGuid,webGuid",
633
+ validate: (v) => {
634
+ if (!v || v.trim().length === 0) return "Site ID is required";
635
+ }
545
636
  });
546
- if (p.isCancel(resourceType)) {
547
- p.cancel("Operation cancelled.");
637
+ if (p6.isCancel(siteId)) {
638
+ p6.cancel("Operation cancelled.");
548
639
  process.exit(0);
549
640
  }
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
- }
641
+ const listSpin = p6.spinner();
642
+ listSpin.start("Fetching lists from site...");
643
+ let siteLists = [];
644
+ try {
645
+ siteLists = await fetchSiteLists(accessToken, siteId);
646
+ listSpin.stop(
647
+ `Found ${siteLists.length} list${siteLists.length === 1 ? "" : "s"}.`
648
+ );
649
+ } catch (error) {
650
+ listSpin.stop("Could not fetch lists.");
651
+ p6.log.warn(error instanceof Error ? error.message : String(error));
652
+ }
653
+ let listId;
654
+ if (siteLists.length > 0) {
655
+ const picked = await p6.select({
656
+ message: "Select a list to subscribe to:",
657
+ options: siteLists.map((l) => ({
658
+ value: l.id,
659
+ label: l.displayName,
660
+ hint: l.id
661
+ }))
558
662
  });
559
- if (p.isCancel(chatId)) {
560
- p.cancel("Operation cancelled.");
663
+ if (p6.isCancel(picked)) {
664
+ p6.cancel("Operation cancelled.");
561
665
  process.exit(0);
562
666
  }
563
- ids.chatId = chatId;
667
+ listId = picked;
564
668
  } else {
565
- const teamId = await p.text({
566
- message: "Enter team ID:",
669
+ const manualId = await p6.text({
670
+ message: "Enter list ID (GUID) to subscribe to:",
567
671
  placeholder: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
568
672
  validate: (v) => {
569
- if (!v || !v.trim()) return "Team ID is required";
673
+ if (!v || v.trim().length === 0) return "List ID is required";
570
674
  }
571
675
  });
572
- if (p.isCancel(teamId)) {
573
- p.cancel("Operation cancelled.");
676
+ if (p6.isCancel(manualId)) {
677
+ p6.cancel("Operation cancelled.");
574
678
  process.exit(0);
575
679
  }
576
- ids.teamId = teamId;
577
- if (resourceType === "channelMessage") {
578
- const channelId = await p.text({
579
- message: "Enter channel ID:",
580
- placeholder: "19:abc123@thread.skype",
581
- validate: (v) => {
582
- if (!v || !v.trim()) return "Channel ID is required";
583
- }
584
- });
585
- if (p.isCancel(channelId)) {
586
- p.cancel("Operation cancelled.");
587
- process.exit(0);
588
- }
589
- ids.channelId = channelId;
590
- }
591
- }
592
- const autoSecret = crypto.randomBytes(16).toString("hex");
593
- const clientState = await p.text({
594
- message: "Enter a clientState secret (used to verify webhook payloads):",
595
- defaultValue: autoSecret,
596
- placeholder: autoSecret
597
- });
598
- if (p.isCancel(clientState)) {
599
- p.cancel("Operation cancelled.");
600
- process.exit(0);
680
+ listId = manualId;
601
681
  }
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...");
682
+ const clientState = await promptClientState();
683
+ const expiryDays = SHAREPOINT_MAX_EXPIRY_DAYS;
684
+ const subSpin = p6.spinner();
685
+ subSpin.start("Creating SharePoint webhook subscription...");
606
686
  let subscription;
607
687
  try {
608
- subscription = await createTeamsSubscription(
688
+ subscription = await createSharepointSubscription(
609
689
  accessToken,
690
+ siteId,
691
+ listId,
610
692
  webhookUrl,
611
- resource,
612
693
  clientState,
613
- expiryMinutes
694
+ expiryDays
614
695
  );
615
696
  } catch (error) {
616
697
  subSpin.stop("Failed.");
617
- p.log.error(error instanceof Error ? error.message : String(error));
618
- p.outro("");
698
+ p6.log.error(error instanceof Error ? error.message : String(error));
699
+ p6.outro("");
619
700
  process.exit(1);
620
701
  }
621
702
  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(
703
+ await saveWebhookSignature(accountKm, clientState);
704
+ p6.note(
627
705
  `Subscription ID: ${subscription.id}
628
- Resource: ${resource}
706
+ Site ID: ${siteId}
707
+ List ID: ${listId}
629
708
  Expires: ${subscription.expirationDateTime}
630
709
  ClientState: ${clientState}
631
710
  Webhook URL: ${webhookUrl}
632
711
 
633
- Note: Teams subscriptions expire. Re-run this command to renew.`,
634
- "Teams Subscription Created"
712
+ Note: SharePoint subscriptions expire after ${SHAREPOINT_MAX_EXPIRY_DAYS} days max. Re-run this command to renew.`,
713
+ "SharePoint Subscription Created"
635
714
  );
636
- p.outro("Done!");
715
+ p6.outro("Done!");
637
716
  }
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
- );
717
+ var SHAREPOINT_MAX_EXPIRY_DAYS;
718
+ var init_sharepoint = __esm({
719
+ "microsoft/sharepoint.ts"() {
720
+ "use strict";
721
+ init_load_config();
722
+ init_prompts();
723
+ init_credentials();
724
+ init_graph();
725
+ SHAREPOINT_MAX_EXPIRY_DAYS = 180;
645
726
  }
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
- })
727
+ });
728
+
729
+ // microsoft/teams.ts
730
+ import * as p7 from "@clack/prompts";
731
+ async function fetchJoinedTeams(accessToken) {
732
+ const response = await fetch(`${GRAPH_API_BASE}/me/joinedTeams`, {
733
+ headers: { Authorization: `Bearer ${accessToken}` }
658
734
  });
659
735
  if (!response.ok) {
660
736
  const error = await response.text();
661
- throw new Error(`Failed to refresh access token: ${error}`);
737
+ throw new Error(`Failed to fetch teams: ${error}`);
662
738
  }
663
739
  const data = await response.json();
664
- return data.access_token;
740
+ return data.value ?? [];
665
741
  }
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
- })
742
+ async function fetchTeamChannels(accessToken, teamId) {
743
+ const response = await fetch(
744
+ `${GRAPH_API_BASE}/teams/${encodeURIComponent(teamId)}/channels`,
745
+ { headers: { Authorization: `Bearer ${accessToken}` } }
746
+ );
747
+ if (!response.ok) {
748
+ const error = await response.text();
749
+ throw new Error(`Failed to fetch channels: ${error}`);
750
+ }
751
+ const data = await response.json();
752
+ return data.value ?? [];
753
+ }
754
+ async function fetchUserChats(accessToken) {
755
+ const response = await fetch(`${GRAPH_API_BASE}/me/chats`, {
756
+ headers: { Authorization: `Bearer ${accessToken}` }
679
757
  });
680
758
  if (!response.ok) {
681
759
  const error = await response.text();
682
- watchSpin.stop("Failed.");
683
- p.log.error(`Gmail watch failed: ${error}`);
684
- p.outro("");
685
- process.exit(1);
760
+ throw new Error(`Failed to fetch chats: ${error}`);
686
761
  }
687
762
  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
- );
763
+ return data.value ?? [];
694
764
  }
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}` }
765
+ async function pickTeamId(accessToken, label) {
766
+ const teamsSpin = p7.spinner();
767
+ teamsSpin.start("Fetching your teams...");
768
+ let teams = [];
769
+ try {
770
+ teams = await fetchJoinedTeams(accessToken);
771
+ teamsSpin.stop(
772
+ `Found ${teams.length} team${teams.length === 1 ? "" : "s"}.`
773
+ );
774
+ } catch (error) {
775
+ teamsSpin.stop("Could not fetch teams.");
776
+ p7.log.warn(error instanceof Error ? error.message : String(error));
777
+ }
778
+ if (teams.length > 0) {
779
+ const picked = await p7.select({
780
+ message: `[${label}] Select a team:`,
781
+ options: teams.map((t) => ({
782
+ value: t.id,
783
+ label: t.displayName,
784
+ hint: t.id
785
+ }))
786
+ });
787
+ if (p7.isCancel(picked)) {
788
+ p7.cancel("Operation cancelled.");
789
+ process.exit(0);
790
+ }
791
+ return picked;
792
+ }
793
+ const manual = await p7.text({
794
+ message: `[${label}] Enter team ID:`,
795
+ placeholder: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
796
+ validate: (v) => {
797
+ if (!v || !v.trim()) return "Team ID is required";
798
+ }
799
+ });
800
+ if (p7.isCancel(manual)) {
801
+ p7.cancel("Operation cancelled.");
802
+ process.exit(0);
803
+ }
804
+ return manual;
805
+ }
806
+ async function pickChannelId(accessToken, teamId, label) {
807
+ const chanSpin = p7.spinner();
808
+ chanSpin.start("Fetching channels...");
809
+ let channels = [];
810
+ try {
811
+ channels = await fetchTeamChannels(accessToken, teamId);
812
+ chanSpin.stop(
813
+ `Found ${channels.length} channel${channels.length === 1 ? "" : "s"}.`
814
+ );
815
+ } catch (error) {
816
+ chanSpin.stop("Could not fetch channels.");
817
+ p7.log.warn(error instanceof Error ? error.message : String(error));
818
+ }
819
+ if (channels.length > 0) {
820
+ const picked = await p7.select({
821
+ message: `[${label}] Select a channel:`,
822
+ options: channels.map((c) => ({
823
+ value: c.id,
824
+ label: c.displayName,
825
+ hint: c.id
826
+ }))
827
+ });
828
+ if (p7.isCancel(picked)) {
829
+ p7.cancel("Operation cancelled.");
830
+ process.exit(0);
831
+ }
832
+ return picked;
833
+ }
834
+ const manual = await p7.text({
835
+ message: `[${label}] Enter channel ID:`,
836
+ placeholder: "19:abc123@thread.skype",
837
+ validate: (v) => {
838
+ if (!v || !v.trim()) return "Channel ID is required";
839
+ }
840
+ });
841
+ if (p7.isCancel(manual)) {
842
+ p7.cancel("Operation cancelled.");
843
+ process.exit(0);
844
+ }
845
+ return manual;
846
+ }
847
+ async function pickChatId(accessToken, label) {
848
+ const chatSpin = p7.spinner();
849
+ chatSpin.start("Fetching your chats...");
850
+ let chats = [];
851
+ try {
852
+ chats = await fetchUserChats(accessToken);
853
+ chatSpin.stop(
854
+ `Found ${chats.length} chat${chats.length === 1 ? "" : "s"}.`
855
+ );
856
+ } catch (error) {
857
+ chatSpin.stop("Could not fetch chats.");
858
+ p7.log.warn(error instanceof Error ? error.message : String(error));
859
+ }
860
+ if (chats.length > 0) {
861
+ const picked = await p7.select({
862
+ message: `[${label}] Select a chat:`,
863
+ options: chats.map((c) => ({
864
+ value: c.id,
865
+ label: c.topic ?? `(${c.chatType})`,
866
+ hint: c.id
867
+ }))
868
+ });
869
+ if (p7.isCancel(picked)) {
870
+ p7.cancel("Operation cancelled.");
871
+ process.exit(0);
872
+ }
873
+ return picked;
874
+ }
875
+ const manual = await p7.text({
876
+ message: `[${label}] Enter chat ID:`,
877
+ placeholder: "19:abc123@thread.v2",
878
+ validate: (v) => {
879
+ if (!v || !v.trim()) return "Chat ID is required";
702
880
  }
881
+ });
882
+ if (p7.isCancel(manual)) {
883
+ p7.cancel("Operation cancelled.");
884
+ process.exit(0);
885
+ }
886
+ return manual;
887
+ }
888
+ function buildTeamsResource(resourceType, ids) {
889
+ switch (resourceType) {
890
+ case "channelMessage":
891
+ return `teams/${ids.teamId}/channels/${ids.channelId}/messages`;
892
+ case "chatMessage":
893
+ return `chats/${ids.chatId}/messages`;
894
+ case "channelCreated":
895
+ return `teams/${ids.teamId}/channels`;
896
+ case "membershipChanged":
897
+ return `teams/${ids.teamId}/members`;
898
+ }
899
+ }
900
+ async function runTeamsSubscribe({
901
+ cwd
902
+ }) {
903
+ const { internal } = await loadInternalConfig(
904
+ cwd,
905
+ "Corsair \u2014 Microsoft Teams Webhook Subscribe",
906
+ "teams",
907
+ "Teams"
703
908
  );
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);
909
+ const tenantId = await promptTenantId();
910
+ const { accessToken, accountKm } = await resolveAccessToken(
911
+ "teams",
912
+ tenantId,
913
+ internal
914
+ );
915
+ const webhookUrl = await promptWebhookUrl();
916
+ const selectedResourceTypes = await p7.multiselect({
917
+ message: "Select resources to subscribe to:",
918
+ options: [
919
+ {
920
+ value: "channelMessage",
921
+ label: "Channel Messages (teams/{id}/channels/{id}/messages)"
922
+ },
923
+ {
924
+ value: "chatMessage",
925
+ label: "Chat Messages (chats/{id}/messages)"
926
+ },
927
+ {
928
+ value: "channelCreated",
929
+ label: "Channel Created (teams/{id}/channels)"
930
+ },
931
+ {
932
+ value: "membershipChanged",
933
+ label: "Membership Changed (teams/{id}/members)"
934
+ }
935
+ ],
936
+ required: true
937
+ });
938
+ if (p7.isCancel(selectedResourceTypes)) {
939
+ p7.cancel("Operation cancelled.");
940
+ process.exit(0);
710
941
  }
711
- const startPageTokenData = await startPageTokenRes.json();
712
- watchSpin.message("Starting Drive watch...");
713
- const channelId = crypto.randomUUID();
942
+ const resourceConfigs = [];
943
+ for (const resourceType of selectedResourceTypes) {
944
+ const ids = {};
945
+ if (resourceType === "chatMessage") {
946
+ ids.chatId = await pickChatId(accessToken, resourceType);
947
+ } else {
948
+ ids.teamId = await pickTeamId(accessToken, resourceType);
949
+ if (resourceType === "channelMessage") {
950
+ ids.channelId = await pickChannelId(
951
+ accessToken,
952
+ ids.teamId,
953
+ resourceType
954
+ );
955
+ }
956
+ }
957
+ resourceConfigs.push({ resourceType, ids });
958
+ }
959
+ const clientState = await promptClientState();
960
+ const results = [];
961
+ let hasError = false;
962
+ for (const { resourceType, ids } of resourceConfigs) {
963
+ const resource = buildTeamsResource(resourceType, ids);
964
+ const expiryMinutes = TEAMS_MAX_EXPIRY_MINUTES[resourceType];
965
+ const subSpin = p7.spinner();
966
+ subSpin.start(`Creating subscription: ${resourceType}...`);
967
+ try {
968
+ const subscription = await createGraphSubscription(
969
+ accessToken,
970
+ webhookUrl,
971
+ resource,
972
+ "created,updated,deleted",
973
+ clientState,
974
+ expiryMinutes
975
+ );
976
+ subSpin.stop(`Created: ${resourceType}`);
977
+ results.push(
978
+ `${resourceType}
979
+ Resource: ${resource}
980
+ ID: ${subscription.id}
981
+ Expires: ${subscription.expirationDateTime}`
982
+ );
983
+ } catch (error) {
984
+ subSpin.stop(`Failed: ${resourceType}`);
985
+ p7.log.error(error instanceof Error ? error.message : String(error));
986
+ hasError = true;
987
+ }
988
+ }
989
+ if (results.length > 0) {
990
+ p7.note(results.join("\n\n"), "Subscriptions created");
991
+ }
992
+ await saveWebhookSignature(accountKm, clientState);
993
+ if (!hasError) {
994
+ p7.log.success("Teams webhook subscriptions set up successfully.");
995
+ } else {
996
+ p7.log.warn("Some subscriptions failed. Check errors above.");
997
+ }
998
+ p7.note(
999
+ `ClientState: ${clientState}
1000
+ Webhook URL: ${webhookUrl}
1001
+
1002
+ Note: Teams subscriptions expire. Re-run this command to renew.`,
1003
+ "Setup complete"
1004
+ );
1005
+ p7.outro("Done!");
1006
+ }
1007
+ var TEAMS_MAX_EXPIRY_MINUTES;
1008
+ var init_teams = __esm({
1009
+ "microsoft/teams.ts"() {
1010
+ "use strict";
1011
+ init_load_config();
1012
+ init_prompts();
1013
+ init_credentials();
1014
+ init_graph();
1015
+ TEAMS_MAX_EXPIRY_MINUTES = {
1016
+ channelMessage: 60,
1017
+ chatMessage: 60,
1018
+ channelCreated: 4230,
1019
+ membershipChanged: 60
1020
+ };
1021
+ }
1022
+ });
1023
+
1024
+ // subscribe-microsoft.ts
1025
+ var subscribe_microsoft_exports = {};
1026
+ __export(subscribe_microsoft_exports, {
1027
+ runOnedriveSubscribe: () => runOnedriveSubscribe,
1028
+ runOutlookSubscribe: () => runOutlookSubscribe,
1029
+ runSharepointSubscribe: () => runSharepointSubscribe,
1030
+ runTeamsSubscribe: () => runTeamsSubscribe
1031
+ });
1032
+ var init_subscribe_microsoft = __esm({
1033
+ "subscribe-microsoft.ts"() {
1034
+ "use strict";
1035
+ init_onedrive();
1036
+ init_outlook();
1037
+ init_sharepoint();
1038
+ init_teams();
1039
+ }
1040
+ });
1041
+
1042
+ // google/calendar.ts
1043
+ import * as crypto2 from "crypto";
1044
+ import * as p8 from "@clack/prompts";
1045
+ async function setupCalendarWatch(accessToken, webhookUrl, calendarId) {
1046
+ const watchSpin = p8.spinner();
1047
+ watchSpin.start("Starting Calendar watch...");
1048
+ const channelId = crypto2.randomUUID();
714
1049
  const watchRes = await fetch(
715
- `${DRIVE_API_BASE}/changes/watch?pageToken=${startPageTokenData.startPageToken}`,
1050
+ `${CALENDAR_API_BASE}/calendars/${encodeURIComponent(calendarId)}/events/watch`,
716
1051
  {
717
1052
  method: "POST",
718
1053
  headers: {
@@ -729,26 +1064,51 @@ async function renewDriveWatch(accessToken, webhookUrl) {
729
1064
  if (!watchRes.ok) {
730
1065
  const error = await watchRes.text();
731
1066
  watchSpin.stop("Failed.");
732
- p.log.error(`Drive watch failed: ${error}`);
733
- p.outro("");
1067
+ p8.log.error(`Calendar watch failed: ${error}`);
1068
+ p8.outro("");
734
1069
  process.exit(1);
735
1070
  }
736
1071
  const data = await watchRes.json();
737
1072
  watchSpin.stop("Watch started.");
738
- p.note(
1073
+ p8.note(
739
1074
  `Channel ID: ${channelId}
740
1075
  Resource ID: ${data.resourceId}
741
- Start Page Token: ${startPageTokenData.startPageToken}
742
1076
  Expiration: ${new Date(Number(data.expiration)).toISOString()}`,
743
1077
  "Watch Response"
744
1078
  );
745
1079
  }
746
- async function renewCalendarWatch(accessToken, webhookUrl, calendarId) {
747
- const watchSpin = p.spinner();
748
- watchSpin.start("Starting Calendar watch...");
749
- const channelId = crypto.randomUUID();
1080
+ var CALENDAR_API_BASE;
1081
+ var init_calendar = __esm({
1082
+ "google/calendar.ts"() {
1083
+ "use strict";
1084
+ CALENDAR_API_BASE = "https://www.googleapis.com/calendar/v3";
1085
+ }
1086
+ });
1087
+
1088
+ // google/drive.ts
1089
+ import * as crypto3 from "crypto";
1090
+ import * as p9 from "@clack/prompts";
1091
+ async function setupDriveWatch(accessToken, webhookUrl) {
1092
+ const watchSpin = p9.spinner();
1093
+ watchSpin.start("Getting start page token...");
1094
+ const startPageTokenRes = await fetch(
1095
+ `${DRIVE_API_BASE}/changes/startPageToken`,
1096
+ {
1097
+ headers: { Authorization: `Bearer ${accessToken}` }
1098
+ }
1099
+ );
1100
+ if (!startPageTokenRes.ok) {
1101
+ const error = await startPageTokenRes.text();
1102
+ watchSpin.stop("Failed.");
1103
+ p9.log.error(`Failed to get start page token: ${error}`);
1104
+ p9.outro("");
1105
+ process.exit(1);
1106
+ }
1107
+ const startPageTokenData = await startPageTokenRes.json();
1108
+ watchSpin.message("Starting Drive watch...");
1109
+ const channelId = crypto3.randomUUID();
750
1110
  const watchRes = await fetch(
751
- `${CALENDAR_API_BASE}/calendars/${encodeURIComponent(calendarId)}/events/watch`,
1111
+ `${DRIVE_API_BASE}/changes/watch?pageToken=${startPageTokenData.startPageToken}`,
752
1112
  {
753
1113
  method: "POST",
754
1114
  headers: {
@@ -765,39 +1125,107 @@ async function renewCalendarWatch(accessToken, webhookUrl, calendarId) {
765
1125
  if (!watchRes.ok) {
766
1126
  const error = await watchRes.text();
767
1127
  watchSpin.stop("Failed.");
768
- p.log.error(`Calendar watch failed: ${error}`);
769
- p.outro("");
1128
+ p9.log.error(`Drive watch failed: ${error}`);
1129
+ p9.outro("");
770
1130
  process.exit(1);
771
1131
  }
772
1132
  const data = await watchRes.json();
773
1133
  watchSpin.stop("Watch started.");
774
- p.note(
1134
+ p9.note(
775
1135
  `Channel ID: ${channelId}
776
1136
  Resource ID: ${data.resourceId}
1137
+ Start Page Token: ${startPageTokenData.startPageToken}
1138
+ Expiration: ${new Date(Number(data.expiration)).toISOString()}`,
1139
+ "Watch Response"
1140
+ );
1141
+ }
1142
+ var DRIVE_API_BASE;
1143
+ var init_drive = __esm({
1144
+ "google/drive.ts"() {
1145
+ "use strict";
1146
+ DRIVE_API_BASE = "https://www.googleapis.com/drive/v3";
1147
+ }
1148
+ });
1149
+
1150
+ // google/gmail.ts
1151
+ import * as p10 from "@clack/prompts";
1152
+ async function setupGmailWatch(accessToken, topicName) {
1153
+ const watchSpin = p10.spinner();
1154
+ watchSpin.start("Starting Gmail watch...");
1155
+ const response = await fetch(`${GMAIL_API_BASE}/users/me/watch`, {
1156
+ method: "POST",
1157
+ headers: {
1158
+ Authorization: `Bearer ${accessToken}`,
1159
+ "Content-Type": "application/json"
1160
+ },
1161
+ body: JSON.stringify({
1162
+ topicName,
1163
+ labelIds: ["INBOX"]
1164
+ })
1165
+ });
1166
+ if (!response.ok) {
1167
+ const error = await response.text();
1168
+ watchSpin.stop("Failed.");
1169
+ p10.log.error(`Gmail watch failed: ${error}`);
1170
+ p10.outro("");
1171
+ process.exit(1);
1172
+ }
1173
+ const data = await response.json();
1174
+ watchSpin.stop("Watch started.");
1175
+ p10.note(
1176
+ `History ID: ${data.historyId}
777
1177
  Expiration: ${new Date(Number(data.expiration)).toISOString()}`,
778
1178
  "Watch Response"
779
1179
  );
780
1180
  }
781
- function copyToClipboard(text4) {
1181
+ var GMAIL_API_BASE;
1182
+ var init_gmail = __esm({
1183
+ "google/gmail.ts"() {
1184
+ "use strict";
1185
+ GMAIL_API_BASE = "https://gmail.googleapis.com/gmail/v1";
1186
+ }
1187
+ });
1188
+
1189
+ // google/shared.ts
1190
+ import { execSync } from "child_process";
1191
+ async function refreshGoogleAccessToken(clientId, clientSecret, refreshToken) {
1192
+ const response = await fetch("https://oauth2.googleapis.com/token", {
1193
+ method: "POST",
1194
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
1195
+ body: new URLSearchParams({
1196
+ client_id: clientId,
1197
+ client_secret: clientSecret,
1198
+ refresh_token: refreshToken,
1199
+ grant_type: "refresh_token"
1200
+ })
1201
+ });
1202
+ if (!response.ok) {
1203
+ const error = await response.text();
1204
+ throw new Error(`Failed to refresh access token: ${error}`);
1205
+ }
1206
+ const data = await response.json();
1207
+ return data.access_token;
1208
+ }
1209
+ function copyToClipboard(text6) {
782
1210
  try {
783
1211
  const platform = process.platform;
784
1212
  if (platform === "darwin") {
785
- execSync("pbcopy", { input: text4 });
1213
+ execSync("pbcopy", { input: text6 });
786
1214
  return true;
787
1215
  } else if (platform === "linux") {
788
1216
  try {
789
- execSync("xclip -selection clipboard", { input: text4 });
1217
+ execSync("xclip -selection clipboard", { input: text6 });
790
1218
  return true;
791
1219
  } catch {
792
1220
  try {
793
- execSync("xsel --clipboard --input", { input: text4 });
1221
+ execSync("xsel --clipboard --input", { input: text6 });
794
1222
  return true;
795
1223
  } catch {
796
1224
  return false;
797
1225
  }
798
1226
  }
799
1227
  } else if (platform === "win32") {
800
- execSync("clip", { input: text4 });
1228
+ execSync("clip", { input: text6 });
801
1229
  return true;
802
1230
  }
803
1231
  return false;
@@ -805,24 +1233,79 @@ function copyToClipboard(text4) {
805
1233
  return false;
806
1234
  }
807
1235
  }
808
- async function renewSheetsWatch(webhookUrl) {
809
- const appsScriptCode = `var WEBHOOK_URL = "${webhookUrl}";
810
-
811
- function onEditTrigger(e) {
812
- if (!e || !e.range) return;
813
-
814
- var sheet = e.range.getSheet();
815
- var payload = {
816
- spreadsheetId: e.source.getId(),
817
- sheetName: sheet.getName(),
818
- range: e.range.getA1Notation(),
819
- values: e.range.getValues(),
820
- eventType: "rangeUpdated",
821
- timestamp: new Date().toISOString()
822
- };
1236
+ var init_shared = __esm({
1237
+ "google/shared.ts"() {
1238
+ "use strict";
1239
+ }
1240
+ });
823
1241
 
824
- UrlFetchApp.fetch(WEBHOOK_URL, {
825
- method: "post",
1242
+ // google/sheets.ts
1243
+ import * as p11 from "@clack/prompts";
1244
+ async function setupSheetsWatch(webhookUrl) {
1245
+ const appsScriptCode = APPS_SCRIPT_TEMPLATE(webhookUrl);
1246
+ p11.log.info("Google Sheets does not have a native watch API.");
1247
+ p11.log.info(
1248
+ "Instead, you need to set up Google Apps Script triggers in your spreadsheet."
1249
+ );
1250
+ p11.log.info("");
1251
+ const shouldCopy = await p11.confirm({
1252
+ message: "Copy Apps Script code to clipboard?",
1253
+ initialValue: true
1254
+ });
1255
+ let copied = false;
1256
+ if (shouldCopy) {
1257
+ copied = copyToClipboard(appsScriptCode);
1258
+ if (copied) {
1259
+ p11.log.success("Apps Script code copied to clipboard!");
1260
+ } else {
1261
+ p11.log.warn("Failed to copy to clipboard. Code will be displayed below.");
1262
+ }
1263
+ }
1264
+ p11.log.info("");
1265
+ p11.log.info("Setup Instructions:");
1266
+ p11.log.info("1. Open your Google Sheet");
1267
+ p11.log.info("2. Go to Extensions > Apps Script");
1268
+ p11.log.info("3. Paste the code into the script editor");
1269
+ p11.log.info(
1270
+ '4. Run the "createTriggers" function once to install the triggers'
1271
+ );
1272
+ p11.log.info("5. Authorize the script when prompted");
1273
+ p11.log.info("");
1274
+ if (!copied) {
1275
+ p11.log.info("Apps Script Code:");
1276
+ p11.log.info("");
1277
+ p11.log.info(appsScriptCode);
1278
+ p11.log.info("");
1279
+ }
1280
+ p11.note(
1281
+ `Webhook URL: ${webhookUrl}
1282
+
1283
+ The Apps Script code ${copied ? "has been copied to your clipboard" : "is displayed above"}. Paste it into your Google Sheet's Apps Script editor.`,
1284
+ "Google Sheets Setup"
1285
+ );
1286
+ }
1287
+ var APPS_SCRIPT_TEMPLATE;
1288
+ var init_sheets = __esm({
1289
+ "google/sheets.ts"() {
1290
+ "use strict";
1291
+ init_shared();
1292
+ APPS_SCRIPT_TEMPLATE = (webhookUrl) => `var WEBHOOK_URL = "${webhookUrl}";
1293
+
1294
+ function onEditTrigger(e) {
1295
+ if (!e || !e.range) return;
1296
+
1297
+ var sheet = e.range.getSheet();
1298
+ var payload = {
1299
+ spreadsheetId: e.source.getId(),
1300
+ sheetName: sheet.getName(),
1301
+ range: e.range.getA1Notation(),
1302
+ values: e.range.getValues(),
1303
+ eventType: "rangeUpdated",
1304
+ timestamp: new Date().toISOString()
1305
+ };
1306
+
1307
+ UrlFetchApp.fetch(WEBHOOK_URL, {
1308
+ method: "post",
826
1309
  contentType: "application/json",
827
1310
  payload: JSON.stringify(payload)
828
1311
  });
@@ -860,7 +1343,7 @@ function createTriggers() {
860
1343
 
861
1344
  ScriptApp.newTrigger("onEditTrigger").forSpreadsheet(ss).onEdit().create();
862
1345
  ScriptApp.newTrigger("onChangeTrigger").forSpreadsheet(ss).onChange().create();
863
-
1346
+
864
1347
  Logger.log("Triggers created successfully!");
865
1348
  }
866
1349
 
@@ -871,65 +1354,47 @@ function removeTriggers() {
871
1354
  });
872
1355
  Logger.log("All triggers removed.");
873
1356
  }`;
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
1357
  }
908
- p.note(
909
- `Webhook URL: ${webhookUrl}
1358
+ });
910
1359
 
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
- );
1360
+ // google/index.ts
1361
+ import * as p12 from "@clack/prompts";
1362
+ import {
1363
+ CORSAIR_INTERNAL as CORSAIR_INTERNAL2,
1364
+ createAccountKeyManager as createAccountKeyManager2,
1365
+ createIntegrationKeyManager as createIntegrationKeyManager2
1366
+ } from "corsair/core";
1367
+ async function extractInternalConfig2(cwd) {
1368
+ const instance = await getCorsairInstance({ cwd, shouldThrowOnError: true });
1369
+ const internal = instance[CORSAIR_INTERNAL2];
1370
+ if (!internal) {
1371
+ throw new Error(
1372
+ "Could not read internal config from Corsair instance. Make sure you are using the latest version of corsair."
1373
+ );
1374
+ }
1375
+ return internal;
914
1376
  }
915
- async function runWatchRenew({ cwd }) {
916
- p.intro("Corsair \u2014 Google Watch Renewal");
917
- const spin = p.spinner();
1377
+ async function runGoogleSubscribe({
1378
+ cwd,
1379
+ pluginId: preselectedPluginId
1380
+ }) {
1381
+ p12.intro("Corsair \u2014 Google Webhook Subscribe");
1382
+ const spin = p12.spinner();
918
1383
  spin.start("Loading corsair instance...");
919
1384
  let internal;
920
1385
  try {
921
1386
  internal = await extractInternalConfig2(cwd);
922
1387
  } catch (error) {
923
1388
  spin.stop("Failed to load.");
924
- p.log.error(error instanceof Error ? error.message : String(error));
925
- p.outro("");
1389
+ p12.log.error(error instanceof Error ? error.message : String(error));
1390
+ p12.outro("");
926
1391
  process.exit(1);
927
1392
  }
928
1393
  const { plugins, database, kek } = internal;
929
1394
  if (!database) {
930
1395
  spin.stop("Failed.");
931
- p.log.error("No database adapter configured.");
932
- p.outro("");
1396
+ p12.log.error("No database adapter configured.");
1397
+ p12.outro("");
933
1398
  process.exit(1);
934
1399
  }
935
1400
  const googlePlugins = plugins.filter((pl) => {
@@ -938,202 +1403,306 @@ async function runWatchRenew({ cwd }) {
938
1403
  });
939
1404
  if (googlePlugins.length === 0) {
940
1405
  spin.stop("No Google OAuth2 plugins found.");
941
- p.outro("");
1406
+ p12.outro("");
942
1407
  process.exit(1);
943
1408
  }
944
1409
  spin.stop(
945
1410
  `Loaded. Found ${googlePlugins.length} Google plugin${googlePlugins.length === 1 ? "" : "s"}.`
946
1411
  );
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);
1412
+ let pluginType;
1413
+ if (preselectedPluginId && GOOGLE_PLUGINS.includes(preselectedPluginId)) {
1414
+ pluginType = preselectedPluginId;
1415
+ } else {
1416
+ const selected = await p12.select({
1417
+ message: "Select a Google integration:",
1418
+ options: googlePlugins.map((pl) => ({ value: pl.id, label: pl.id }))
1419
+ });
1420
+ if (p12.isCancel(selected)) {
1421
+ p12.cancel("Operation cancelled.");
1422
+ process.exit(0);
1423
+ }
1424
+ pluginType = selected;
957
1425
  }
958
- const pluginType = pluginId;
959
1426
  if (pluginType === "googlesheets") {
960
- const webhookUrl = await p.text({
1427
+ const webhookUrl = await p12.text({
961
1428
  message: "Enter webhook URL:",
962
1429
  placeholder: "https://example.com/api/webhook",
963
1430
  validate: (v) => {
964
1431
  if (!v || v.trim().length === 0) return "Webhook URL is required";
965
- if (!v.startsWith("http://") && !v.startsWith("https://")) {
1432
+ if (!v.startsWith("http://") && !v.startsWith("https://"))
966
1433
  return "Webhook URL must start with http:// or https://";
967
- }
968
1434
  }
969
1435
  });
970
- if (p.isCancel(webhookUrl)) {
971
- p.cancel("Operation cancelled.");
1436
+ if (p12.isCancel(webhookUrl)) {
1437
+ p12.cancel("Operation cancelled.");
972
1438
  process.exit(0);
973
1439
  }
974
- await renewSheetsWatch(webhookUrl);
975
- p.outro("Done!");
1440
+ await setupSheetsWatch(webhookUrl);
1441
+ p12.outro("Done!");
976
1442
  return;
977
1443
  }
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();
1444
+ const tenantId = await promptTenantId();
1445
+ const credSpin = p12.spinner();
988
1446
  credSpin.start("Fetching credentials...");
989
1447
  try {
990
1448
  const integrationKm = createIntegrationKeyManager2({
991
1449
  authType: "oauth_2",
992
- integrationName: pluginId,
1450
+ integrationName: pluginType,
993
1451
  kek,
994
1452
  database
995
1453
  });
996
1454
  const accountKm = createAccountKeyManager2({
997
1455
  authType: "oauth_2",
998
- integrationName: pluginId,
1456
+ integrationName: pluginType,
999
1457
  tenantId,
1000
1458
  kek,
1001
1459
  database
1002
1460
  });
1003
1461
  const clientId = await integrationKm.get_client_id();
1004
1462
  const clientSecret = await integrationKm.get_client_secret();
1005
- const refreshToken2 = await accountKm.get_refresh_token();
1006
- if (!clientId || !clientSecret || !refreshToken2) {
1463
+ const refreshToken = await accountKm.get_refresh_token();
1464
+ if (!clientId || !clientSecret || !refreshToken) {
1007
1465
  credSpin.stop("Missing credentials.");
1008
- p.log.error(
1466
+ p12.log.error(
1009
1467
  'Client ID, Client Secret, and Refresh Token are required. Use "corsair auth" to set them.'
1010
1468
  );
1011
- p.outro("");
1469
+ p12.outro("");
1012
1470
  process.exit(1);
1013
1471
  }
1014
- const accessToken = await refreshAccessToken(
1472
+ const accessToken = await refreshGoogleAccessToken(
1015
1473
  clientId,
1016
1474
  clientSecret,
1017
- refreshToken2
1475
+ refreshToken
1018
1476
  );
1019
1477
  credSpin.stop("Credentials loaded.");
1020
1478
  if (pluginType === "gmail") {
1021
- const topicName = await p.text({
1479
+ const topicName = await p12.text({
1022
1480
  message: "Enter Pub/Sub topic name:",
1023
1481
  placeholder: "projects/my-project/topics/my-topic",
1024
1482
  validate: (v) => {
1025
1483
  if (!v || v.trim().length === 0) return "Topic name is required";
1026
1484
  }
1027
1485
  });
1028
- if (p.isCancel(topicName)) {
1029
- p.cancel("Operation cancelled.");
1486
+ if (p12.isCancel(topicName)) {
1487
+ p12.cancel("Operation cancelled.");
1030
1488
  process.exit(0);
1031
1489
  }
1032
- await renewGmailWatch(accessToken, topicName);
1490
+ await setupGmailWatch(accessToken, topicName);
1033
1491
  } else if (pluginType === "googledrive") {
1034
- const webhookUrl = await p.text({
1492
+ const webhookUrl = await p12.text({
1035
1493
  message: "Enter webhook URL:",
1036
1494
  placeholder: "https://example.com/api/webhook",
1037
1495
  validate: (v) => {
1038
1496
  if (!v || v.trim().length === 0) return "Webhook URL is required";
1039
1497
  }
1040
1498
  });
1041
- if (p.isCancel(webhookUrl)) {
1042
- p.cancel("Operation cancelled.");
1499
+ if (p12.isCancel(webhookUrl)) {
1500
+ p12.cancel("Operation cancelled.");
1043
1501
  process.exit(0);
1044
1502
  }
1045
- await renewDriveWatch(accessToken, webhookUrl);
1503
+ await setupDriveWatch(accessToken, webhookUrl);
1046
1504
  } else if (pluginType === "googlecalendar") {
1047
- const webhookUrl = await p.text({
1505
+ const webhookUrl = await p12.text({
1048
1506
  message: "Enter webhook URL:",
1049
1507
  placeholder: "https://example.com/api/webhook",
1050
1508
  validate: (v) => {
1051
1509
  if (!v || v.trim().length === 0) return "Webhook URL is required";
1052
1510
  }
1053
1511
  });
1054
- if (p.isCancel(webhookUrl)) {
1055
- p.cancel("Operation cancelled.");
1512
+ if (p12.isCancel(webhookUrl)) {
1513
+ p12.cancel("Operation cancelled.");
1056
1514
  process.exit(0);
1057
1515
  }
1058
- const calendarId = await p.text({
1516
+ const calendarId = await p12.text({
1059
1517
  message: "Enter calendar ID:",
1060
1518
  defaultValue: "primary",
1061
1519
  placeholder: "primary"
1062
1520
  });
1063
- if (p.isCancel(calendarId)) {
1064
- p.cancel("Operation cancelled.");
1521
+ if (p12.isCancel(calendarId)) {
1522
+ p12.cancel("Operation cancelled.");
1065
1523
  process.exit(0);
1066
1524
  }
1067
- await renewCalendarWatch(
1525
+ await setupCalendarWatch(
1068
1526
  accessToken,
1069
1527
  webhookUrl,
1070
1528
  calendarId
1071
1529
  );
1072
1530
  } else {
1073
- p.log.error(`Unsupported Google plugin: ${pluginType}`);
1531
+ p12.log.error(`Unsupported Google plugin: ${pluginType}`);
1074
1532
  process.exit(1);
1075
1533
  }
1076
1534
  } catch (error) {
1077
1535
  credSpin.stop("Failed.");
1078
- p.log.error(
1536
+ p12.log.error(
1079
1537
  `Error: ${error instanceof Error ? error.message : String(error)}`
1080
1538
  );
1081
1539
  process.exit(1);
1082
1540
  }
1083
- p.outro("Done!");
1541
+ p12.outro("Done!");
1084
1542
  }
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"() {
1543
+ var GOOGLE_PLUGINS;
1544
+ var init_google = __esm({
1545
+ "google/index.ts"() {
1088
1546
  "use strict";
1089
1547
  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";
1548
+ init_prompts();
1549
+ init_calendar();
1550
+ init_drive();
1551
+ init_gmail();
1552
+ init_shared();
1553
+ init_sheets();
1094
1554
  GOOGLE_PLUGINS = [
1095
1555
  "gmail",
1096
1556
  "googledrive",
1097
1557
  "googlecalendar",
1098
1558
  "googlesheets"
1099
1559
  ];
1100
- TEAMS_MAX_EXPIRY_MINUTES = {
1101
- channelMessage: 60,
1102
- chatMessage: 60,
1103
- channelCreated: 4230,
1104
- membershipChanged: 60
1105
- };
1106
1560
  }
1107
1561
  });
1108
1562
 
1109
- // sharepoint-subscribe.ts
1110
- var sharepoint_subscribe_exports = {};
1111
- __export(sharepoint_subscribe_exports, {
1112
- runSharepointSubscribe: () => runSharepointSubscribe
1563
+ // subscribe-google.ts
1564
+ var subscribe_google_exports = {};
1565
+ __export(subscribe_google_exports, {
1566
+ runGoogleSubscribe: () => runGoogleSubscribe
1113
1567
  });
1114
- import * as crypto2 from "crypto";
1115
- import * as p2 from "@clack/prompts";
1568
+ var init_subscribe_google = __esm({
1569
+ "subscribe-google.ts"() {
1570
+ "use strict";
1571
+ init_google();
1572
+ }
1573
+ });
1574
+
1575
+ // auth.ts
1576
+ var auth_exports = {};
1577
+ __export(auth_exports, {
1578
+ runAuth: () => runAuth
1579
+ });
1580
+ import * as http from "http";
1581
+ import * as https from "https";
1582
+ import * as net from "net";
1583
+ import * as querystring from "querystring";
1116
1584
  import {
1117
1585
  CORSAIR_INTERNAL as CORSAIR_INTERNAL3,
1118
1586
  createAccountKeyManager as createAccountKeyManager3,
1119
- createIntegrationKeyManager as createIntegrationKeyManager3
1587
+ createIntegrationKeyManager as createIntegrationKeyManager3,
1588
+ encryptDEK,
1589
+ generateDEK
1120
1590
  } 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
- })
1591
+ import { createCorsairOrm } from "corsair/orm";
1592
+ function out(data) {
1593
+ console.log(JSON.stringify(data));
1594
+ }
1595
+ function getOAuthConfigForPlugin(plugin) {
1596
+ return plugin.oauthConfig ?? null;
1597
+ }
1598
+ function getAuthType(plugin) {
1599
+ return plugin.options?.authType;
1600
+ }
1601
+ function getCustomIntegrationFields(plugin, authType) {
1602
+ const authConfig = plugin.authConfig;
1603
+ return authConfig?.[authType]?.integration ?? [];
1604
+ }
1605
+ function getCustomAccountFields(plugin, authType) {
1606
+ const authConfig = plugin.authConfig;
1607
+ return authConfig?.[authType]?.account ?? [];
1608
+ }
1609
+ function findFreePort() {
1610
+ return new Promise((resolve, reject) => {
1611
+ const server = net.createServer();
1612
+ server.listen(0, "127.0.0.1", () => {
1613
+ const address = server.address();
1614
+ const port = typeof address === "object" && address ? address.port : 0;
1615
+ server.close((err) => {
1616
+ if (err) reject(err);
1617
+ else resolve(port);
1618
+ });
1619
+ });
1620
+ server.on("error", reject);
1621
+ });
1622
+ }
1623
+ function waitForOAuthCode(port) {
1624
+ return new Promise((resolve, reject) => {
1625
+ const server = http.createServer((req, res) => {
1626
+ const url = new URL(req.url ?? "/", `http://localhost:${port}`);
1627
+ const code = url.searchParams.get("code");
1628
+ const error = url.searchParams.get("error");
1629
+ if (error) {
1630
+ res.writeHead(400, { "Content-Type": "text/html" });
1631
+ res.end(
1632
+ `<html><body><h2>Authorization failed: ${error}</h2><p>You can close this tab.</p></body></html>`
1633
+ );
1634
+ server.close();
1635
+ reject(new Error(`OAuth error: ${error}`));
1636
+ return;
1637
+ }
1638
+ if (code) {
1639
+ res.writeHead(200, { "Content-Type": "text/html" });
1640
+ res.end(
1641
+ "<html><body><h2>Authorization successful!</h2><p>You can close this tab and return to the terminal.</p></body></html>"
1642
+ );
1643
+ server.close();
1644
+ resolve(code);
1645
+ } else {
1646
+ res.writeHead(400, { "Content-Type": "text/html" });
1647
+ res.end(
1648
+ "<html><body><h2>No code received.</h2><p>You can close this tab.</p></body></html>"
1649
+ );
1650
+ }
1651
+ });
1652
+ server.listen(port, "127.0.0.1", () => {
1653
+ });
1654
+ server.on("error", reject);
1655
+ });
1656
+ }
1657
+ function exchangeCodeForTokens(code, clientId, clientSecret, oauthConfig, redirectUri) {
1658
+ const tokenUrl = new URL(oauthConfig.tokenUrl);
1659
+ const useBasicAuth = oauthConfig.tokenAuthMethod === "basic";
1660
+ return new Promise((resolve, reject) => {
1661
+ const postDataParams = {
1662
+ code: code.trim(),
1663
+ redirect_uri: redirectUri,
1664
+ grant_type: "authorization_code"
1665
+ };
1666
+ if (!useBasicAuth) {
1667
+ postDataParams.client_id = clientId;
1668
+ postDataParams.client_secret = clientSecret;
1669
+ }
1670
+ const postData = querystring.stringify(postDataParams);
1671
+ const headers = {
1672
+ "Content-Type": "application/x-www-form-urlencoded",
1673
+ "Content-Length": Buffer.byteLength(postData).toString()
1674
+ };
1675
+ if (useBasicAuth) {
1676
+ headers.Authorization = `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`;
1677
+ }
1678
+ const req = https.request(
1679
+ {
1680
+ hostname: tokenUrl.hostname,
1681
+ path: tokenUrl.pathname,
1682
+ method: "POST",
1683
+ headers
1684
+ },
1685
+ (res) => {
1686
+ let data = "";
1687
+ res.on("data", (chunk) => {
1688
+ data += chunk;
1689
+ });
1690
+ res.on("end", () => {
1691
+ if (res.statusCode !== 200) {
1692
+ reject(new Error(`Token exchange failed: ${data}`));
1693
+ return;
1694
+ }
1695
+ resolve(JSON.parse(data));
1696
+ });
1697
+ }
1698
+ );
1699
+ req.on(
1700
+ "error",
1701
+ (error) => reject(new Error(`Request failed: ${error.message}`))
1702
+ );
1703
+ req.write(postData);
1704
+ req.end();
1131
1705
  });
1132
- if (!response.ok) {
1133
- const error = await response.text();
1134
- throw new Error(`Token refresh failed: ${error}`);
1135
- }
1136
- return response.json();
1137
1706
  }
1138
1707
  async function extractInternalConfig3(cwd) {
1139
1708
  const instance = await getCorsairInstance({ cwd, shouldThrowOnError: true });
@@ -1145,505 +1714,357 @@ async function extractInternalConfig3(cwd) {
1145
1714
  }
1146
1715
  return internal;
1147
1716
  }
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}`;
1717
+ async function ensureIntegration(database, pluginId, kek) {
1718
+ const orm = createCorsairOrm(database);
1719
+ const existing = await orm.integrations.findByName(pluginId);
1720
+ if (existing) return { id: existing.id };
1721
+ const dek = generateDEK();
1722
+ const encryptedDek = await encryptDEK(dek, kek);
1723
+ const row = await orm.integrations.create({
1724
+ name: pluginId,
1725
+ config: {},
1726
+ dek: encryptedDek
1727
+ });
1728
+ return { id: row.id };
1151
1729
  }
1152
- async function fetchSiteLists(accessToken, siteId) {
1153
- const response = await fetch(
1154
- `${buildSiteUrl(siteId, "lists")}?$select=id,displayName,webUrl`,
1155
- {
1156
- headers: { Authorization: `Bearer ${accessToken}` }
1157
- }
1158
- );
1159
- if (!response.ok) {
1160
- const error = await response.text();
1161
- throw new Error(`Failed to fetch site lists: ${error}`);
1162
- }
1163
- const data = await response.json();
1164
- return data.value ?? [];
1165
- }
1166
- async function createSharepointSubscription(accessToken, siteId, listId, notificationUrl, clientState, expiryDays) {
1167
- const expirationDateTime = new Date(
1168
- Date.now() + expiryDays * 24 * 60 * 60 * 1e3
1169
- ).toISOString();
1170
- const response = await fetch(
1171
- buildSiteUrl(siteId, `lists/${encodeURIComponent(listId)}/subscriptions`),
1172
- {
1173
- method: "POST",
1174
- headers: {
1175
- Authorization: `Bearer ${accessToken}`,
1176
- "Content-Type": "application/json"
1177
- },
1178
- body: JSON.stringify({
1179
- notificationUrl,
1180
- expirationDateTime,
1181
- clientState
1182
- })
1183
- }
1184
- );
1185
- if (!response.ok) {
1186
- const error = await response.text();
1187
- throw new Error(`SharePoint subscription failed: ${error}`);
1188
- }
1189
- return response.json();
1190
- }
1191
- async function runSharepointSubscribe({ cwd }) {
1192
- p2.intro("Corsair \u2014 SharePoint Webhook Subscribe");
1193
- const spin = p2.spinner();
1194
- spin.start("Loading corsair instance...");
1195
- let internal;
1196
- try {
1197
- internal = await extractInternalConfig3(cwd);
1198
- } catch (error) {
1199
- spin.stop("Failed to load.");
1200
- p2.log.error(error instanceof Error ? error.message : String(error));
1201
- p2.outro("");
1202
- process.exit(1);
1203
- }
1204
- const { plugins, database, kek } = internal;
1205
- if (!database) {
1206
- spin.stop("Failed.");
1207
- p2.log.error("No database adapter configured.");
1208
- p2.outro("");
1209
- process.exit(1);
1210
- }
1211
- const sharepointPlugin = plugins.find((pl) => pl.id === "sharepoint");
1212
- if (!sharepointPlugin) {
1213
- spin.stop("SharePoint plugin not found.");
1214
- p2.log.error("Add the sharepoint plugin to your corsair instance first.");
1215
- p2.outro("");
1216
- process.exit(1);
1217
- }
1218
- spin.stop("Loaded.");
1219
- const tenantId = await p2.text({
1220
- message: "Enter tenant ID:",
1221
- defaultValue: "default",
1222
- placeholder: "default"
1730
+ async function ensureAccount(database, integrationId, tenantId, kek) {
1731
+ const orm = createCorsairOrm(database);
1732
+ const existing = await orm.accounts.findOne({
1733
+ tenant_id: tenantId,
1734
+ integration_id: integrationId
1223
1735
  });
1224
- if (p2.isCancel(tenantId)) {
1225
- p2.cancel("Operation cancelled.");
1226
- process.exit(0);
1736
+ if (existing) return;
1737
+ const dek = generateDEK();
1738
+ const encryptedDek = await encryptDEK(dek, kek);
1739
+ await orm.accounts.create({
1740
+ tenant_id: tenantId,
1741
+ integration_id: integrationId,
1742
+ config: {},
1743
+ dek: encryptedDek
1744
+ });
1745
+ }
1746
+ async function oauthGetUrl(database, plugin, kek, tenantId) {
1747
+ const oauthCfg = getOAuthConfigForPlugin(plugin);
1748
+ if (!oauthCfg) {
1749
+ out({ error: `No oauthConfig defined on plugin '${plugin.id}'.` });
1750
+ return;
1227
1751
  }
1228
- const credSpin = p2.spinner();
1229
- credSpin.start("Fetching SharePoint credentials...");
1752
+ const extraFields = getCustomIntegrationFields(plugin, "oauth_2");
1230
1753
  const integrationKm = createIntegrationKeyManager3({
1231
1754
  authType: "oauth_2",
1232
- integrationName: "sharepoint",
1233
- kek,
1234
- database
1235
- });
1236
- const accountKm = createAccountKeyManager3({
1237
- authType: "oauth_2",
1238
- integrationName: "sharepoint",
1239
- tenantId,
1755
+ integrationName: plugin.id,
1240
1756
  kek,
1241
- database
1757
+ database,
1758
+ extraIntegrationFields: extraFields
1242
1759
  });
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);
1760
+ const clientId = await integrationKm.get_client_id();
1761
+ if (!clientId) {
1762
+ out({
1763
+ error: `client_id not set for '${plugin.id}'. Run: corsair setup --${plugin.id} client_id=YOUR_CLIENT_ID`
1764
+ });
1765
+ return;
1255
1766
  }
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);
1767
+ const clientSecret = await integrationKm.get_client_secret();
1768
+ if (!clientSecret) {
1769
+ out({
1770
+ error: `client_secret not set for '${plugin.id}'. Run: corsair setup --${plugin.id} client_secret=YOUR_CLIENT_SECRET`
1771
+ });
1772
+ return;
1261
1773
  }
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);
1774
+ let redirectUri;
1775
+ if (oauthCfg.requiresRegisteredRedirect) {
1776
+ const stored = await integrationKm.get_redirect_url();
1777
+ if (!stored) {
1778
+ out({
1779
+ error: `redirect_url required for '${plugin.id}'. Run: corsair setup --${plugin.id} redirect_url=YOUR_REDIRECT_URI`
1780
+ });
1781
+ return;
1280
1782
  }
1783
+ redirectUri = stored;
1784
+ } else {
1785
+ const port = await findFreePort();
1786
+ redirectUri = `http://localhost:${port}`;
1281
1787
  }
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";
1788
+ const authParams = {
1789
+ client_id: clientId,
1790
+ redirect_uri: redirectUri,
1791
+ response_type: "code",
1792
+ scope: oauthCfg.scopes.join(" "),
1793
+ ...oauthCfg.authParams
1794
+ };
1795
+ const authUrl = `${oauthCfg.authUrl}?${querystring.stringify(authParams)}`;
1796
+ const localhostPortMatch = redirectUri.match(
1797
+ /^https?:\/\/(?:localhost|127\.0\.0\.1):(\d+)/
1798
+ );
1799
+ const localhostPort = localhostPortMatch?.[1] ? parseInt(localhostPortMatch[1], 10) : null;
1800
+ if (localhostPort) {
1801
+ out({
1802
+ status: "pending_oauth",
1803
+ authUrl,
1804
+ redirectUri,
1805
+ plugin: plugin.id,
1806
+ tenant: tenantId,
1807
+ note: "Open authUrl in a browser. Tokens will be saved automatically once authorized."
1808
+ });
1809
+ let code;
1810
+ try {
1811
+ code = await waitForOAuthCode(localhostPort);
1812
+ } catch (err) {
1813
+ out({
1814
+ error: `Authorization failed: ${err instanceof Error ? err.message : String(err)}`
1815
+ });
1816
+ return;
1297
1817
  }
1298
- });
1299
- if (p2.isCancel(siteId)) {
1300
- p2.cancel("Operation cancelled.");
1301
- process.exit(0);
1818
+ await oauthExchangeCode(
1819
+ database,
1820
+ plugin,
1821
+ kek,
1822
+ tenantId,
1823
+ code,
1824
+ redirectUri,
1825
+ clientId,
1826
+ clientSecret,
1827
+ oauthCfg
1828
+ );
1829
+ return;
1302
1830
  }
1303
- const listSpin = p2.spinner();
1304
- listSpin.start("Fetching lists from site...");
1305
- let siteLists = [];
1831
+ out({
1832
+ status: "needs_code",
1833
+ authUrl,
1834
+ redirectUri,
1835
+ plugin: plugin.id,
1836
+ tenant: tenantId,
1837
+ note: "Open authUrl, complete auth, then run: corsair auth --plugin=<id> --code=CODE"
1838
+ });
1839
+ }
1840
+ async function oauthExchangeCode(database, plugin, kek, tenantId, code, redirectUri, clientId, clientSecret, oauthCfg) {
1841
+ let tokens;
1306
1842
  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
- }
1843
+ tokens = await exchangeCodeForTokens(
1844
+ code,
1845
+ clientId,
1846
+ clientSecret,
1847
+ oauthCfg,
1848
+ redirectUri
1849
+ );
1850
+ } catch (err) {
1851
+ out({
1852
+ error: `Token exchange failed: ${err instanceof Error ? err.message : String(err)}`
1335
1853
  });
1336
- if (p2.isCancel(manualId)) {
1337
- p2.cancel("Operation cancelled.");
1338
- process.exit(0);
1339
- }
1340
- listId = manualId;
1854
+ return;
1341
1855
  }
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);
1856
+ if (!tokens.access_token) {
1857
+ out({
1858
+ error: `No access_token in response from ${oauthCfg.providerName}.`
1859
+ });
1860
+ return;
1353
1861
  }
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
- }
1862
+ const extraAccountFields = getCustomAccountFields(plugin, "oauth_2");
1863
+ const accountKm = createAccountKeyManager3({
1864
+ authType: "oauth_2",
1865
+ integrationName: plugin.id,
1866
+ tenantId,
1867
+ kek,
1868
+ database,
1869
+ extraAccountFields
1363
1870
  });
1364
- if (p2.isCancel(expiryInput)) {
1365
- p2.cancel("Operation cancelled.");
1366
- process.exit(0);
1871
+ await accountKm.set_access_token(tokens.access_token);
1872
+ if (tokens.refresh_token)
1873
+ await accountKm.set_refresh_token(tokens.refresh_token);
1874
+ if (tokens.expires_in)
1875
+ await accountKm.set_expires_at(
1876
+ (Math.floor(Date.now() / 1e3) + tokens.expires_in).toString()
1877
+ );
1878
+ out({ status: "success", plugin: plugin.id, tenant: tenantId });
1879
+ }
1880
+ async function oauthWithCode(database, plugin, kek, tenantId, code) {
1881
+ const oauthCfg = getOAuthConfigForPlugin(plugin);
1882
+ if (!oauthCfg) {
1883
+ out({ error: `No oauthConfig defined on plugin '${plugin.id}'.` });
1884
+ return;
1367
1885
  }
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
1886
+ const extraFields = getCustomIntegrationFields(plugin, "oauth_2");
1887
+ const integrationKm = createIntegrationKeyManager3({
1888
+ authType: "oauth_2",
1889
+ integrationName: plugin.id,
1890
+ kek,
1891
+ database,
1892
+ extraIntegrationFields: extraFields
1373
1893
  });
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);
1894
+ const clientId = await integrationKm.get_client_id();
1895
+ const clientSecret = await integrationKm.get_client_secret();
1896
+ const redirectUri = await integrationKm.get_redirect_url() ?? "";
1897
+ if (!clientId || !clientSecret) {
1898
+ out({
1899
+ error: `client_id and client_secret must be set before exchanging a code.`
1900
+ });
1901
+ return;
1396
1902
  }
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"
1903
+ await oauthExchangeCode(
1904
+ database,
1905
+ plugin,
1906
+ kek,
1907
+ tenantId,
1908
+ code,
1909
+ redirectUri,
1910
+ clientId,
1911
+ clientSecret,
1912
+ oauthCfg
1412
1913
  );
1413
- p2.outro("Done!");
1414
1914
  }
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
- );
1915
+ async function getCredentials(database, plugin, kek, tenantId) {
1916
+ const authType = getAuthType(plugin);
1917
+ const result = {};
1918
+ if (authType === "oauth_2") {
1919
+ const extraIntegrationFields = getCustomIntegrationFields(plugin, authType);
1920
+ const integrationKm = createIntegrationKeyManager3({
1921
+ authType,
1922
+ integrationName: plugin.id,
1923
+ kek,
1924
+ database,
1925
+ extraIntegrationFields
1926
+ });
1927
+ result.client_id = await integrationKm.get_client_id();
1928
+ result.client_secret = await integrationKm.get_client_secret();
1929
+ result.redirect_url = await integrationKm.get_redirect_url();
1930
+ for (const field of extraIntegrationFields) {
1931
+ const fn = integrationKm[`get_${field}`];
1932
+ if (typeof fn === "function")
1933
+ result[field] = await fn();
1934
+ }
1935
+ const extraAccountFields = getCustomAccountFields(plugin, authType);
1936
+ const accountKm = createAccountKeyManager3({
1937
+ authType,
1938
+ integrationName: plugin.id,
1939
+ tenantId,
1940
+ kek,
1941
+ database,
1942
+ extraAccountFields
1943
+ });
1944
+ result.access_token = await accountKm.get_access_token();
1945
+ result.refresh_token = await accountKm.get_refresh_token();
1946
+ result.expires_at = await accountKm.get_expires_at();
1947
+ result.webhook_signature = await accountKm.get_webhook_signature();
1948
+ for (const field of extraAccountFields) {
1949
+ const fn = accountKm[`get_${field}`];
1950
+ if (typeof fn === "function")
1951
+ result[field] = await fn();
1952
+ }
1953
+ } else if (authType === "api_key") {
1954
+ const extraAccountFields = getCustomAccountFields(plugin, authType);
1955
+ const accountKm = createAccountKeyManager3({
1956
+ authType,
1957
+ integrationName: plugin.id,
1958
+ tenantId,
1959
+ kek,
1960
+ database,
1961
+ extraAccountFields
1962
+ });
1963
+ result.api_key = await accountKm.get_api_key();
1964
+ result.webhook_signature = await accountKm.get_webhook_signature();
1965
+ } else if (authType === "bot_token") {
1966
+ const extraAccountFields = getCustomAccountFields(plugin, authType);
1967
+ const accountKm = createAccountKeyManager3({
1968
+ authType,
1969
+ integrationName: plugin.id,
1970
+ tenantId,
1971
+ kek,
1972
+ database,
1973
+ extraAccountFields
1974
+ });
1975
+ result.bot_token = await accountKm.get_bot_token();
1976
+ result.webhook_signature = await accountKm.get_webhook_signature();
1441
1977
  }
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}`);
1978
+ const masked = {};
1979
+ for (const [k, v] of Object.entries(result)) {
1980
+ if (!v) {
1981
+ masked[k] = null;
1982
+ continue;
1983
+ }
1984
+ masked[k] = v.length <= 9 ? "***" : `${v.slice(0, 6)}...${v.slice(-3)}`;
1463
1985
  }
1464
- return response.json();
1986
+ out({ plugin: plugin.id, tenant: tenantId, credentials: masked });
1465
1987
  }
1466
- async function runOutlookSubscribe({ cwd }) {
1467
- p3.intro("Corsair \u2014 Outlook Webhook Subscribe");
1468
- const spin = p3.spinner();
1469
- spin.start("Loading corsair instance...");
1988
+ async function runAuth({
1989
+ cwd,
1990
+ pluginId: pluginIdArg,
1991
+ tenantId: tenantIdArg,
1992
+ code: codeArg,
1993
+ credentials: showCredentials = false,
1994
+ agent: agentMode = false
1995
+ }) {
1470
1996
  let internal;
1471
1997
  try {
1472
- internal = await extractInternalConfig4(cwd);
1998
+ internal = await extractInternalConfig3(cwd);
1473
1999
  } catch (error) {
1474
- spin.stop("Failed to load.");
1475
- p3.log.error(error instanceof Error ? error.message : String(error));
1476
- p3.outro("");
2000
+ out({ error: error instanceof Error ? error.message : String(error) });
1477
2001
  process.exit(1);
1478
2002
  }
1479
2003
  const { plugins, database, kek } = internal;
1480
2004
  if (!database) {
1481
- spin.stop("Failed.");
1482
- p3.log.error("No database adapter configured.");
1483
- p3.outro("");
2005
+ out({ error: "No database adapter configured." });
1484
2006
  process.exit(1);
1485
2007
  }
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("");
2008
+ if (!pluginIdArg) {
2009
+ out({
2010
+ error: "No plugin specified. Use --plugin=<id>.",
2011
+ available: plugins.map((pl) => ({
2012
+ id: pl.id,
2013
+ authType: getAuthType(pl)
2014
+ }))
2015
+ });
1491
2016
  process.exit(1);
1492
2017
  }
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("");
2018
+ const plugin = plugins.find((pl) => pl.id === pluginIdArg);
2019
+ if (!plugin) {
2020
+ out({
2021
+ error: `Plugin '${pluginIdArg}' not found.`,
2022
+ available: plugins.map((pl) => pl.id)
2023
+ });
1518
2024
  process.exit(1);
1519
2025
  }
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);
2026
+ const integration = await ensureIntegration(database, plugin.id, kek);
2027
+ const tenantId = tenantIdArg ?? "default";
2028
+ await ensureAccount(database, integration.id, tenantId, kek);
2029
+ if (showCredentials) {
2030
+ await getCredentials(database, plugin, kek, tenantId);
2031
+ return;
1557
2032
  }
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
- }
2033
+ const authType = getAuthType(plugin);
2034
+ if (authType !== "oauth_2") {
2035
+ out({
2036
+ error: `'corsair auth' is for OAuth flows. Plugin '${plugin.id}' uses '${authType}'. Set credentials via: corsair setup --${plugin.id} <field>=<value>`
2037
+ });
2038
+ return;
1584
2039
  }
1585
- if (results.length > 0) {
1586
- p3.note(results.join("\n\n"), "Subscriptions created");
2040
+ if (agentMode) {
2041
+ const baseCmd = `pnpm corsair auth --plugin=${plugin.id}`;
2042
+ const needsQuoting = tenantIdArg && /[^a-zA-Z0-9_\-.]/.test(tenantIdArg);
2043
+ const tenantFlag = tenantIdArg && tenantIdArg !== "default" ? ` --tenant=${needsQuoting ? `"${tenantIdArg}"` : tenantIdArg}` : "";
2044
+ const cmd = `${baseCmd}${tenantFlag}`;
2045
+ out({
2046
+ status: "agent_instructions",
2047
+ plugin: plugin.id,
2048
+ tenant: tenantId,
2049
+ command: cmd,
2050
+ message: `To authenticate the '${plugin.id}' plugin, run the following command:
2051
+
2052
+ ${cmd}
2053
+
2054
+ This command opens a browser and waits for an OAuth callback \u2014 it is a long-running interactive task. Either ask the user to run it in a separate terminal, or run it as a background process. Do NOT run it inline in the current session.`
2055
+ });
2056
+ return;
1587
2057
  }
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.");
2058
+ if (codeArg) {
2059
+ await oauthWithCode(database, plugin, kek, tenantId, codeArg);
1594
2060
  } else {
1595
- p3.log.warn("Some subscriptions failed. Check errors above.");
2061
+ await oauthGetUrl(database, plugin, kek, tenantId);
1596
2062
  }
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
2063
  }
1606
- var GRAPH_API_BASE3, OUTLOOK_RESOURCES;
1607
- var init_subscribe_outlook = __esm({
1608
- "subscribe-outlook.ts"() {
2064
+ var init_auth = __esm({
2065
+ "auth.ts"() {
1609
2066
  "use strict";
1610
2067
  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
2068
  }
1648
2069
  });
1649
2070
 
@@ -1821,9 +2242,13 @@ or reinstall your dependencies:
1821
2242
  rm -rf node_modules && npm install`
1822
2243
  );
1823
2244
  }
1824
- console.error(`[#corsair]: Error loading ${possiblePath}: Native module binding not found.`);
2245
+ console.error(
2246
+ `[#corsair]: Error loading ${possiblePath}: Native module binding not found.`
2247
+ );
1825
2248
  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.");
2249
+ console.log(
2250
+ "[#corsair]: A native Node.js addon (e.g. better-sqlite3) needs to be rebuilt for your current Node.js version."
2251
+ );
1827
2252
  console.log("[#corsair]: Try running:");
1828
2253
  console.log(" npm rebuild");
1829
2254
  console.log("[#corsair]: Or reinstall your dependencies:");
@@ -1877,7 +2302,9 @@ function resolveClient(instance, tenant) {
1877
2302
  const obj = instance;
1878
2303
  if ("withTenant" in obj && typeof obj.withTenant === "function") {
1879
2304
  if (!tenant) {
1880
- console.error("[#corsair]: This is a multi-tenant instance. Pass --tenant=<id>.");
2305
+ console.error(
2306
+ "[#corsair]: This is a multi-tenant instance. Pass --tenant=<id>."
2307
+ );
1881
2308
  process.exit(1);
1882
2309
  }
1883
2310
  return obj.withTenant(tenant);
@@ -1918,11 +2345,21 @@ function parseAuthArgs(args) {
1918
2345
  let tenantId;
1919
2346
  let code;
1920
2347
  let credentials = false;
2348
+ let webhook = false;
2349
+ let agent = false;
1921
2350
  for (const arg of args) {
1922
2351
  if (arg === "--credentials") {
1923
2352
  credentials = true;
1924
2353
  continue;
1925
2354
  }
2355
+ if (arg === "--agent") {
2356
+ agent = true;
2357
+ continue;
2358
+ }
2359
+ if (arg === "--webhook") {
2360
+ webhook = true;
2361
+ continue;
2362
+ }
1926
2363
  const eqIdx = arg.indexOf("=");
1927
2364
  if (arg.startsWith("--") && eqIdx !== -1) {
1928
2365
  const key = arg.slice(2, eqIdx);
@@ -1941,7 +2378,7 @@ function parseAuthArgs(args) {
1941
2378
  }
1942
2379
  }
1943
2380
  }
1944
- return { pluginId, tenantId, code, credentials };
2381
+ return { pluginId, tenantId, code, credentials, webhook, agent };
1945
2382
  }
1946
2383
  function parseSetupArgs(args) {
1947
2384
  let backfill = false;
@@ -2011,21 +2448,22 @@ function printHelp() {
2011
2448
  const lines = [
2012
2449
  "Corsair CLI",
2013
2450
  "",
2014
- " pnpm corsair setup Init (add -backfill to seed data)",
2015
- " pnpm corsair setup --<plugin> <field>=VALUE Set plugin credentials",
2016
- " pnpm corsair auth --plugin=<id> Start OAuth flow",
2017
- " pnpm corsair auth --plugin=<id> --code=<code> Exchange OAuth code for tokens",
2018
- " pnpm corsair auth --plugin=<id> --credentials Show credential status",
2019
- " pnpm corsair list [--plugin=<id>] [--type=api|webhooks|db] List endpoint paths (tip: pipe to grep to filter)",
2020
- " pnpm corsair schema <path> Show schema for an endpoint/webhook/DB entity",
2021
- ' pnpm corsair script --code "<js>" [--tenant=<id>]',
2022
- " corsair is injected; use return to output a value.",
2023
- " IMPORTANT: Always filter results inline \u2014 you are the consumer of the return value, so returning full list responses wastes tokens.",
2024
- " Bad: return await corsair.slack.api.users.list({})",
2025
- " 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
- ] : []
2451
+ "pnpm corsair setup Init (add -backfill to seed data)",
2452
+ "pnpm corsair setup --<plugin> <field>=VALUE Set plugin credentials",
2453
+ "pnpm corsair auth --plugin=<id> Start OAuth flow",
2454
+ "pnpm corsair auth --plugin=<id> --code=<code> Exchange OAuth code for tokens",
2455
+ "pnpm corsair auth --plugin=<id> --agent Run this if you are an agent (specific instructions to handle pending process)",
2456
+ "pnpm corsair auth --plugin=<id> --credentials Show credential status",
2457
+ "pnpm corsair auth --plugin=<id> --webhook Set up webhook subscription",
2458
+ " `pnpm corsair list --type=webhooks` to see webhook plugins",
2459
+ "pnpm corsair list [--plugin=<id>] [--type=api|webhooks|db] List endpoint paths (tip: pipe to grep to filter)",
2460
+ "pnpm corsair schema <path> Show schema for an endpoint/webhook/DB entity",
2461
+ 'pnpm corsair script --code "<js>" [--tenant=<id>]',
2462
+ " corsair is injected; use return to output a value.",
2463
+ " IMPORTANT: Always filter results inline \u2014 you are the consumer of the return value, so returning full list responses wastes tokens.",
2464
+ " Bad: return await corsair.slack.api.users.list({})",
2465
+ " Good: return (await corsair.slack.api.users.list({})).members.find(u => u.name === 'bob')?.id",
2466
+ ...SHOW_RUN ? [" run <path> [input-json] [--tenant=<id>] Call an endpoint directly"] : []
2029
2467
  ];
2030
2468
  console.log(lines.join("\n"));
2031
2469
  }
@@ -2045,33 +2483,70 @@ async function main() {
2045
2483
  return;
2046
2484
  }
2047
2485
  if (command === "auth") {
2048
- const { runAuth: runAuth2 } = await Promise.resolve().then(() => (init_auth(), auth_exports));
2049
2486
  const authArgs = parseAuthArgs(args.slice(1));
2487
+ if (authArgs.webhook) {
2488
+ const pluginId = authArgs.pluginId;
2489
+ if (!pluginId) {
2490
+ console.error("[#corsair]: --webhook requires --plugin=<id>.");
2491
+ process.exit(1);
2492
+ }
2493
+ if (pluginId === "outlook") {
2494
+ const { runOutlookSubscribe: runOutlookSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2495
+ await runOutlookSubscribe2({ cwd });
2496
+ } else if (pluginId === "sharepoint") {
2497
+ const { runSharepointSubscribe: runSharepointSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2498
+ await runSharepointSubscribe2({ cwd });
2499
+ } else if (pluginId === "teams") {
2500
+ const { runTeamsSubscribe: runTeamsSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2501
+ await runTeamsSubscribe2({ cwd });
2502
+ } else if (pluginId === "onedrive") {
2503
+ const { runOnedriveSubscribe: runOnedriveSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2504
+ await runOnedriveSubscribe2({ cwd });
2505
+ } else if (["gmail", "googledrive", "googlecalendar", "googlesheets"].includes(
2506
+ pluginId
2507
+ )) {
2508
+ const { runGoogleSubscribe: runGoogleSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_google(), subscribe_google_exports));
2509
+ await runGoogleSubscribe2({ cwd, pluginId });
2510
+ } else {
2511
+ console.error(
2512
+ `[#corsair]: Webhook subscription not supported for plugin '${pluginId}'.`
2513
+ );
2514
+ console.error(
2515
+ "[#corsair]: Supported: outlook, sharepoint, teams, onedrive, gmail, googledrive, googlecalendar, googlesheets"
2516
+ );
2517
+ process.exit(1);
2518
+ }
2519
+ return;
2520
+ }
2521
+ const { runAuth: runAuth2 } = await Promise.resolve().then(() => (init_auth(), auth_exports));
2050
2522
  await runAuth2({ cwd, ...authArgs });
2051
2523
  return;
2052
2524
  }
2053
2525
  if (command === "watch-renew") {
2054
- const { runWatchRenew: runWatchRenew2 } = await Promise.resolve().then(() => (init_watch_renew(), watch_renew_exports));
2055
- await runWatchRenew2({ cwd });
2526
+ const { runGoogleSubscribe: runGoogleSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_google(), subscribe_google_exports));
2527
+ await runGoogleSubscribe2({ cwd });
2056
2528
  return;
2057
2529
  }
2058
2530
  if (command === "sharepoint-subscribe") {
2059
- const { runSharepointSubscribe: runSharepointSubscribe2 } = await Promise.resolve().then(() => (init_sharepoint_subscribe(), sharepoint_subscribe_exports));
2531
+ const { runSharepointSubscribe: runSharepointSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2060
2532
  await runSharepointSubscribe2({ cwd });
2533
+ return;
2061
2534
  }
2062
2535
  if (command === "subscribe") {
2063
2536
  const pluginArg = args.slice(1).find((a) => a.startsWith("--plugin="));
2064
2537
  const pluginId = pluginArg ? pluginArg.slice("--plugin=".length) : void 0;
2065
2538
  if (pluginId === "outlook") {
2066
- const { runOutlookSubscribe: runOutlookSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_outlook(), subscribe_outlook_exports));
2539
+ const { runOutlookSubscribe: runOutlookSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2067
2540
  await runOutlookSubscribe2({ cwd });
2068
2541
  return;
2069
2542
  }
2070
- console.error(`[#corsair]: Unknown plugin for subscribe: '${pluginId ?? "(none)"}'. Supported: outlook`);
2543
+ console.error(
2544
+ `[#corsair]: Unknown plugin for subscribe: '${pluginId ?? "(none)"}'. Supported: outlook`
2545
+ );
2071
2546
  process.exit(1);
2072
2547
  }
2073
2548
  if (command === "teams-subscribe") {
2074
- const { runTeamsSubscribe: runTeamsSubscribe2 } = await Promise.resolve().then(() => (init_watch_renew(), watch_renew_exports));
2549
+ const { runTeamsSubscribe: runTeamsSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2075
2550
  await runTeamsSubscribe2({ cwd });
2076
2551
  return;
2077
2552
  }
@@ -2080,10 +2555,18 @@ async function main() {
2080
2555
  const instance = await getCorsairInstance({ cwd });
2081
2556
  const corsair = instance;
2082
2557
  if (typeof corsair.list_operations !== "function") {
2083
- console.error("[#corsair]: list_operations not available on this Corsair instance.");
2558
+ console.error(
2559
+ "[#corsair]: list_operations not available on this Corsair instance."
2560
+ );
2084
2561
  process.exit(1);
2085
2562
  }
2086
2563
  const result = corsair.list_operations({ plugin, type });
2564
+ if (type === "db") {
2565
+ console.log(
2566
+ "[#corsair]: NOTE: Every DB query listed here has both .search() and .list() methods available."
2567
+ );
2568
+ console.log("");
2569
+ }
2087
2570
  if (typeof result === "string") {
2088
2571
  console.log(result);
2089
2572
  } else if (Array.isArray(result)) {
@@ -2099,7 +2582,9 @@ async function main() {
2099
2582
  const { path: endpointPath, input, tenant } = parseRunArgs(args.slice(1));
2100
2583
  if (!endpointPath) {
2101
2584
  console.error("[#corsair]: Usage: corsair run <path> [input-json]");
2102
- console.error(`[#corsair]: Example: corsair run slack.api.messages.post '{"channel":"C123","text":"hi"}'`);
2585
+ console.error(
2586
+ `[#corsair]: Example: corsair run slack.api.messages.post '{"channel":"C123","text":"hi"}'`
2587
+ );
2103
2588
  process.exit(1);
2104
2589
  }
2105
2590
  const instance = await getCorsairInstance({ cwd });
@@ -2107,7 +2592,9 @@ async function main() {
2107
2592
  const fn = navigateToEndpoint(client, endpointPath);
2108
2593
  if (!fn) {
2109
2594
  console.error(`[#corsair]: Could not find endpoint "${endpointPath}".`);
2110
- console.error("[#corsair]: Run `pnpm corsair list` to see available paths.");
2595
+ console.error(
2596
+ "[#corsair]: Run `pnpm corsair list` to see available paths."
2597
+ );
2111
2598
  process.exit(1);
2112
2599
  }
2113
2600
  let parsedInput = {};
@@ -2115,7 +2602,9 @@ async function main() {
2115
2602
  try {
2116
2603
  parsedInput = JSON.parse(input);
2117
2604
  } catch {
2118
- console.error("[#corsair]: Invalid JSON input. Make sure to quote the JSON string.");
2605
+ console.error(
2606
+ "[#corsair]: Invalid JSON input. Make sure to quote the JSON string."
2607
+ );
2119
2608
  process.exit(1);
2120
2609
  }
2121
2610
  }
@@ -2133,7 +2622,9 @@ async function main() {
2133
2622
  const { code, tenant } = parseScriptArgs(args.slice(1));
2134
2623
  if (!code) {
2135
2624
  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"`);
2625
+ console.error(
2626
+ `[#corsair]: Example: corsair script --code "const r = await corsair.slack.channels.list(); return r.channels.find(c => c.name === 'general')?.id"`
2627
+ );
2137
2628
  process.exit(1);
2138
2629
  }
2139
2630
  const instance = await getCorsairInstance({ cwd });
@@ -2157,13 +2648,17 @@ async function main() {
2157
2648
  const schemaPath = args[1];
2158
2649
  if (!schemaPath) {
2159
2650
  console.error("[#corsair]: Usage: corsair schema <path>");
2160
- console.error("[#corsair]: Example: corsair schema slack.api.messages.post");
2651
+ console.error(
2652
+ "[#corsair]: Example: corsair schema slack.api.messages.post"
2653
+ );
2161
2654
  process.exit(1);
2162
2655
  }
2163
2656
  const instance = await getCorsairInstance({ cwd });
2164
2657
  const corsair = instance;
2165
2658
  if (typeof corsair.get_schema !== "function") {
2166
- console.error("[#corsair]: get_schema not available on this Corsair instance.");
2659
+ console.error(
2660
+ "[#corsair]: get_schema not available on this Corsair instance."
2661
+ );
2167
2662
  process.exit(1);
2168
2663
  }
2169
2664
  const result = corsair.get_schema(schemaPath);
@@ -2240,7 +2735,10 @@ var init_index = __esm({
2240
2735
  SHOW_RUN = false;
2241
2736
  isMainModule = import.meta.url === `file://${process.argv[1]?.replace(/\\/g, "/")}` || process.argv[1]?.includes("index.ts") || process.argv[1]?.includes("index.js") || import.meta.url.endsWith("/index.ts") || import.meta.url.endsWith("/index.js");
2242
2737
  if (isMainModule) {
2243
- main();
2738
+ main().then(() => process.exit(0)).catch((e) => {
2739
+ console.error(e);
2740
+ process.exit(1);
2741
+ });
2244
2742
  }
2245
2743
  }
2246
2744
  });