@zapier/zapier-sdk-cli 0.42.2 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/login.cjs CHANGED
@@ -1,12 +1,604 @@
1
1
  'use strict';
2
2
 
3
- var zapierSdkCliLogin = require('@zapier/zapier-sdk-cli-login');
3
+ var Conf = require('conf');
4
+ var fs = require('fs');
5
+ var jwt = require('jsonwebtoken');
6
+ var crossKeychain = require('cross-keychain');
7
+ var crypto = require('crypto');
8
+ var path = require('path');
9
+ var lockfile = require('proper-lockfile');
4
10
 
11
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
5
12
 
13
+ function _interopNamespace(e) {
14
+ if (e && e.__esModule) return e;
15
+ var n = Object.create(null);
16
+ if (e) {
17
+ Object.keys(e).forEach(function (k) {
18
+ if (k !== 'default') {
19
+ var d = Object.getOwnPropertyDescriptor(e, k);
20
+ Object.defineProperty(n, k, d.get ? d : {
21
+ enumerable: true,
22
+ get: function () { return e[k]; }
23
+ });
24
+ }
25
+ });
26
+ }
27
+ n.default = e;
28
+ return Object.freeze(n);
29
+ }
6
30
 
7
- Object.keys(zapierSdkCliLogin).forEach(function (k) {
8
- if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
9
- enumerable: true,
10
- get: function () { return zapierSdkCliLogin[k]; }
11
- });
12
- });
31
+ var Conf__default = /*#__PURE__*/_interopDefault(Conf);
32
+ var jwt__namespace = /*#__PURE__*/_interopNamespace(jwt);
33
+ var lockfile__namespace = /*#__PURE__*/_interopNamespace(lockfile);
34
+
35
+ // src/login/index.ts
36
+ var SERVICE = "zapier-sdk-cli";
37
+ var ACCOUNT = "login";
38
+ var cachedBackendInfo;
39
+ async function getBackendInfo() {
40
+ if (!cachedBackendInfo) {
41
+ const keyring = await crossKeychain.getKeyring();
42
+ cachedBackendInfo = `${keyring.name} (${keyring.id})`;
43
+ }
44
+ return cachedBackendInfo;
45
+ }
46
+ var keychainQueue = Promise.resolve();
47
+ function enqueue(fn) {
48
+ const result = keychainQueue.then(fn, fn);
49
+ keychainQueue = result.then(
50
+ () => {
51
+ },
52
+ () => {
53
+ }
54
+ );
55
+ return result;
56
+ }
57
+ async function getTokensFromKeychain({
58
+ debugLog
59
+ } = {}) {
60
+ return enqueue(async () => {
61
+ const backendInfo = await getBackendInfo();
62
+ debugLog?.(`Keychain read via ${backendInfo}`);
63
+ const startTime = Date.now();
64
+ const raw = await crossKeychain.getPassword(SERVICE, ACCOUNT);
65
+ debugLog?.(`Keychain read completed in ${Date.now() - startTime}ms`);
66
+ if (!raw) {
67
+ debugLog?.("Keychain returned no data");
68
+ return void 0;
69
+ }
70
+ let parsed;
71
+ try {
72
+ parsed = JSON.parse(raw);
73
+ } catch {
74
+ debugLog?.("Keychain data is not valid JSON");
75
+ return void 0;
76
+ }
77
+ if (typeof parsed.login_jwt === "string" && typeof parsed.login_refresh_token === "string") {
78
+ return {
79
+ login_jwt: parsed.login_jwt,
80
+ login_refresh_token: parsed.login_refresh_token
81
+ };
82
+ }
83
+ debugLog?.("Keychain data has invalid shape", parsed);
84
+ return void 0;
85
+ });
86
+ }
87
+ async function setTokensInKeychain({
88
+ data,
89
+ debugLog
90
+ }) {
91
+ return enqueue(async () => {
92
+ const backendInfo = await getBackendInfo();
93
+ debugLog?.(`Keychain write via ${backendInfo}`);
94
+ const startTime = Date.now();
95
+ await crossKeychain.setPassword(SERVICE, ACCOUNT, JSON.stringify(data));
96
+ debugLog?.(`Keychain write completed in ${Date.now() - startTime}ms`);
97
+ });
98
+ }
99
+ async function clearTokensFromKeychain({
100
+ debugLog
101
+ } = {}) {
102
+ return enqueue(async () => {
103
+ try {
104
+ const backendInfo = await getBackendInfo();
105
+ debugLog?.(`Keychain clear via ${backendInfo}`);
106
+ await crossKeychain.deletePassword(SERVICE, ACCOUNT);
107
+ } catch {
108
+ }
109
+ });
110
+ }
111
+ var SERVICE2 = "zapier-sdk-cache";
112
+ var CONFIG_KEY = "cache";
113
+ var LOCK_UPDATE_MS = 5e3;
114
+ var LOCK_STALE_MS = 1e4;
115
+ var LOCK_RETRY_WAIT_MS = 100;
116
+ var LOCK_RETRY_MAX_WAIT_MS = 1e3;
117
+ var LOCK_RETRY_COUNT = 120;
118
+ function keychainAccount(key) {
119
+ return crypto.createHash("sha256").update(key).digest("hex");
120
+ }
121
+ function readConfigMap() {
122
+ const cfg = getConfig();
123
+ const stored = cfg.get(CONFIG_KEY);
124
+ if (stored && typeof stored === "object") {
125
+ return stored;
126
+ }
127
+ return {};
128
+ }
129
+ function writeConfigMap(map) {
130
+ getConfig().set(CONFIG_KEY, map);
131
+ }
132
+ function entryIsExpired(entry) {
133
+ return entry.expires_at !== void 0 && entry.expires_at <= Date.now();
134
+ }
135
+ function createCache() {
136
+ return {
137
+ async get(key) {
138
+ const entry = readConfigMap()[key];
139
+ if (!entry) return void 0;
140
+ if (entryIsExpired(entry)) return void 0;
141
+ if (entry.secret) {
142
+ const stored = await enqueue(async () => {
143
+ await getBackendInfo();
144
+ return crossKeychain.getPassword(SERVICE2, keychainAccount(key));
145
+ });
146
+ if (!stored) {
147
+ return void 0;
148
+ }
149
+ return { value: stored, expiresAt: entry.expires_at };
150
+ }
151
+ if (entry.value === void 0) return void 0;
152
+ return { value: entry.value, expiresAt: entry.expires_at };
153
+ },
154
+ async set(key, value, options) {
155
+ const secret = options?.secret ?? false;
156
+ const expiresAt = options?.ttl ? Date.now() + options.ttl * 1e3 : void 0;
157
+ if (secret) {
158
+ try {
159
+ await enqueue(async () => {
160
+ await getBackendInfo();
161
+ await crossKeychain.setPassword(SERVICE2, keychainAccount(key), value);
162
+ });
163
+ } catch {
164
+ return;
165
+ }
166
+ const map = readConfigMap();
167
+ map[key] = { secret: true, expires_at: expiresAt };
168
+ try {
169
+ writeConfigMap(map);
170
+ } catch {
171
+ }
172
+ } else {
173
+ const map = readConfigMap();
174
+ map[key] = { secret: false, value, expires_at: expiresAt };
175
+ try {
176
+ writeConfigMap(map);
177
+ } catch {
178
+ }
179
+ }
180
+ },
181
+ async delete(key) {
182
+ const map = readConfigMap();
183
+ const entry = map[key];
184
+ if (entry) {
185
+ delete map[key];
186
+ try {
187
+ writeConfigMap(map);
188
+ } catch {
189
+ }
190
+ }
191
+ if (entry?.secret) {
192
+ try {
193
+ await enqueue(async () => {
194
+ await getBackendInfo();
195
+ await crossKeychain.deletePassword(SERVICE2, keychainAccount(key));
196
+ });
197
+ } catch {
198
+ }
199
+ }
200
+ },
201
+ async withLock(_key, fn) {
202
+ const cfg = getConfig();
203
+ const lockTarget = `${cfg.path}.cache-lock`;
204
+ try {
205
+ fs.mkdirSync(path.dirname(lockTarget), { recursive: true });
206
+ if (!fs.existsSync(lockTarget)) {
207
+ fs.writeFileSync(lockTarget, "");
208
+ }
209
+ } catch {
210
+ return fn();
211
+ }
212
+ let release = null;
213
+ try {
214
+ release = await lockfile__namespace.lock(lockTarget, {
215
+ stale: LOCK_STALE_MS,
216
+ update: LOCK_UPDATE_MS,
217
+ retries: {
218
+ retries: LOCK_RETRY_COUNT,
219
+ factor: 1.2,
220
+ minTimeout: LOCK_RETRY_WAIT_MS,
221
+ maxTimeout: LOCK_RETRY_MAX_WAIT_MS
222
+ }
223
+ });
224
+ } catch {
225
+ return fn();
226
+ }
227
+ try {
228
+ return await fn();
229
+ } finally {
230
+ try {
231
+ await release();
232
+ } catch {
233
+ }
234
+ }
235
+ }
236
+ };
237
+ }
238
+
239
+ // src/login/index.ts
240
+ var ZapierAuthenticationError = class extends Error {
241
+ constructor(message) {
242
+ super(message);
243
+ this.name = "ZapierAuthenticationError";
244
+ }
245
+ };
246
+ var config = null;
247
+ var DEFAULT_AUTH_CLIENT_ID = "grwWZD5hUWGvb4V8ODBuOtXer3h0DBEZ2HR8aay6";
248
+ var TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1e3;
249
+ function createDebugLog(enabled) {
250
+ if (!enabled) {
251
+ return () => {
252
+ };
253
+ }
254
+ return (message, data) => {
255
+ if (data === void 0) {
256
+ console.log(`[Zapier SDK CLI Login] ${message}`);
257
+ } else {
258
+ console.log(`[Zapier SDK CLI Login] ${message}`, data);
259
+ }
260
+ };
261
+ }
262
+ function censorHeaderValue(value) {
263
+ if (value.length > 12) {
264
+ return `${value.substring(0, 4)}...${value.substring(value.length - 4)}`;
265
+ }
266
+ return `${value.charAt(0)}...`;
267
+ }
268
+ function getAuthClientId(clientId) {
269
+ return clientId || DEFAULT_AUTH_CLIENT_ID;
270
+ }
271
+ var AUTH_MODE_HEADER = "X-Auth";
272
+ var DEFAULT_AUTH_BASE_URL = "https://zapier.com";
273
+ function getAuthTokenUrl(options) {
274
+ const authBaseUrl = options?.baseUrl || DEFAULT_AUTH_BASE_URL;
275
+ return `${authBaseUrl}/oauth/token/`;
276
+ }
277
+ function getAuthAuthorizeUrl(options) {
278
+ const authBaseUrl = options?.baseUrl || DEFAULT_AUTH_BASE_URL;
279
+ return `${authBaseUrl}/oauth/authorize/`;
280
+ }
281
+ function getPkceLoginConfig(options) {
282
+ return {
283
+ clientId: getAuthClientId(options?.credentials?.clientId),
284
+ tokenUrl: getAuthTokenUrl({ baseUrl: options?.credentials?.baseUrl }),
285
+ authorizeUrl: getAuthAuthorizeUrl({
286
+ baseUrl: options?.credentials?.baseUrl
287
+ })
288
+ };
289
+ }
290
+ var cachedLogin;
291
+ function getConfig() {
292
+ if (!config) {
293
+ config = new Conf__default.default({ projectName: "zapier-sdk-cli" });
294
+ if (!config.has("login_storage_mode")) {
295
+ config.set(
296
+ "login_storage_mode",
297
+ fs.existsSync(config.path) ? "config" : "keychain"
298
+ );
299
+ }
300
+ }
301
+ return config;
302
+ }
303
+ function unloadConfig() {
304
+ config = null;
305
+ cachedLogin = void 0;
306
+ }
307
+ async function updateLogin(loginData, options = {}) {
308
+ const debugLog = createDebugLog(options.debug ?? false);
309
+ const storage = options.storage ?? cachedLogin?.storage ?? "keychain";
310
+ const expiresAt = Date.now() + loginData.expires_in * 1e3;
311
+ const cfg = getConfig();
312
+ cfg.set("login_storage_mode", storage);
313
+ if (storage === "keychain") {
314
+ await setTokensInKeychain({
315
+ data: {
316
+ login_jwt: loginData.access_token,
317
+ login_refresh_token: loginData.refresh_token
318
+ },
319
+ debugLog
320
+ });
321
+ cfg.set("login_expires_at", expiresAt);
322
+ cfg.delete("login_jwt");
323
+ cfg.delete("login_refresh_token");
324
+ } else {
325
+ cfg.set("login_jwt", loginData.access_token);
326
+ cfg.set("login_refresh_token", loginData.refresh_token);
327
+ cfg.set("login_expires_at", expiresAt);
328
+ await clearTokensFromKeychain({ debugLog });
329
+ }
330
+ cachedLogin = {
331
+ jwt: loginData.access_token,
332
+ refreshToken: loginData.refresh_token,
333
+ expiresAt,
334
+ storage
335
+ };
336
+ }
337
+ function decodeJwtOrThrow(token) {
338
+ if (typeof token !== "string") {
339
+ throw new Error("Expected JWT to be a string");
340
+ }
341
+ const decodedJwt = jwt__namespace.decode(token, { complete: true });
342
+ if (!decodedJwt) {
343
+ throw new Error("Could not decode JWT");
344
+ }
345
+ if (typeof decodedJwt.payload === "string") {
346
+ throw new Error("Did not expect JWT payload to be a string");
347
+ }
348
+ return decodedJwt;
349
+ }
350
+ async function refreshJwt(refreshToken, options = {}) {
351
+ const {
352
+ onEvent,
353
+ fetch = globalThis.fetch,
354
+ credentials,
355
+ debug = false
356
+ } = options;
357
+ const debugLog = createDebugLog(debug);
358
+ const tokenUrl = getAuthTokenUrl({ baseUrl: credentials?.baseUrl });
359
+ const clientId = getAuthClientId(credentials?.clientId);
360
+ const startTime = Date.now();
361
+ try {
362
+ onEvent?.({
363
+ type: "auth_refreshing",
364
+ payload: {
365
+ message: "Refreshing your token...",
366
+ operation: "token_refresh"
367
+ },
368
+ timestamp: Date.now()
369
+ });
370
+ debugLog(`\u2192 POST ${tokenUrl}`, {
371
+ headers: {
372
+ "Content-Type": "application/x-www-form-urlencoded",
373
+ [AUTH_MODE_HEADER]: "no"
374
+ },
375
+ body: {
376
+ client_id: clientId,
377
+ refresh_token: censorHeaderValue(refreshToken),
378
+ grant_type: "refresh_token"
379
+ }
380
+ });
381
+ const response = await fetch(tokenUrl, {
382
+ method: "POST",
383
+ headers: {
384
+ "Content-Type": "application/x-www-form-urlencoded",
385
+ [AUTH_MODE_HEADER]: "no"
386
+ },
387
+ body: new URLSearchParams({
388
+ client_id: clientId,
389
+ refresh_token: refreshToken,
390
+ grant_type: "refresh_token"
391
+ })
392
+ });
393
+ const duration = Date.now() - startTime;
394
+ if (!response.ok) {
395
+ debugLog(`\u2190 ${response.status} ${response.statusText} (${duration}ms)`);
396
+ throw new Error(
397
+ `Token refresh failed: ${response.status} ${response.statusText}`
398
+ );
399
+ }
400
+ debugLog(`\u2190 ${response.status} ${response.statusText} (${duration}ms)`);
401
+ const data = await response.json();
402
+ await updateLogin(data, { debug });
403
+ debugLog(
404
+ `Token refreshed and saved to ${cachedLogin?.storage ?? "keychain"}`
405
+ );
406
+ onEvent?.({
407
+ type: "auth_success",
408
+ payload: {
409
+ message: "Token refreshed successfully",
410
+ operation: "token_refresh"
411
+ },
412
+ timestamp: Date.now()
413
+ });
414
+ return data.access_token;
415
+ } catch (error) {
416
+ const duration = Date.now() - startTime;
417
+ debugLog(`\u2716 Token refresh failed (${duration}ms)`, {
418
+ error: error instanceof Error ? error.message : error
419
+ });
420
+ cachedLogin = void 0;
421
+ const errorMessage = `Token refresh failed: ${error instanceof Error ? error.message : "Unknown error"}`;
422
+ onEvent?.({
423
+ type: "auth_error",
424
+ payload: {
425
+ message: errorMessage,
426
+ error: errorMessage,
427
+ operation: "token_refresh"
428
+ },
429
+ timestamp: Date.now()
430
+ });
431
+ throw error;
432
+ }
433
+ }
434
+ var pendingRefresh = null;
435
+ var pendingResolve = null;
436
+ async function resolveStoredLogin(debugLog) {
437
+ if (cachedLogin) {
438
+ debugLog("Using in-memory cached credentials");
439
+ return cachedLogin;
440
+ }
441
+ if (pendingResolve) {
442
+ debugLog("Waiting for existing keychain read to complete");
443
+ return pendingResolve;
444
+ }
445
+ pendingResolve = resolveStoredLoginFromStorage(debugLog).finally(() => {
446
+ pendingResolve = null;
447
+ });
448
+ return pendingResolve;
449
+ }
450
+ async function resolveStoredLoginFromStorage(debugLog) {
451
+ let cfg;
452
+ try {
453
+ cfg = getConfig();
454
+ } catch (error) {
455
+ debugLog("Failed to load config", {
456
+ error: error instanceof Error ? error.message : error
457
+ });
458
+ return void 0;
459
+ }
460
+ const expiresAt = cfg.get("login_expires_at");
461
+ const configJwt = cfg.get("login_jwt");
462
+ const configRefresh = cfg.get("login_refresh_token");
463
+ if (configJwt && configRefresh && typeof expiresAt === "number") {
464
+ debugLog("Loaded credentials from config (legacy format)");
465
+ cachedLogin = {
466
+ jwt: configJwt,
467
+ refreshToken: configRefresh,
468
+ expiresAt,
469
+ storage: "config"
470
+ };
471
+ return cachedLogin;
472
+ }
473
+ if (typeof expiresAt !== "number") {
474
+ debugLog("No stored login credentials found");
475
+ return void 0;
476
+ }
477
+ const keychainData = await getTokensFromKeychain({ debugLog });
478
+ if (!keychainData) {
479
+ debugLog("No tokens found in keychain");
480
+ return void 0;
481
+ }
482
+ debugLog("Loaded credentials from keychain");
483
+ cachedLogin = {
484
+ jwt: keychainData.login_jwt,
485
+ refreshToken: keychainData.login_refresh_token,
486
+ expiresAt,
487
+ storage: "keychain"
488
+ };
489
+ return cachedLogin;
490
+ }
491
+ async function resolveOrRefreshToken(options = {}) {
492
+ const { debug = false } = options;
493
+ const debugLog = createDebugLog(debug);
494
+ const stored = await resolveStoredLogin(debugLog);
495
+ if (!stored) {
496
+ return void 0;
497
+ }
498
+ const { jwt: storedJwt, refreshToken, expiresAt } = stored;
499
+ if (expiresAt > Date.now() + TOKEN_REFRESH_BUFFER_MS) {
500
+ debugLog("Using cached token (still valid)");
501
+ return storedJwt;
502
+ }
503
+ debugLog("Token expired, refreshing...");
504
+ if (pendingRefresh) {
505
+ debugLog("Waiting for existing refresh to complete");
506
+ return pendingRefresh;
507
+ }
508
+ pendingRefresh = refreshJwt(refreshToken, options).finally(() => {
509
+ pendingRefresh = null;
510
+ });
511
+ return await pendingRefresh;
512
+ }
513
+ async function getToken(options = {}) {
514
+ try {
515
+ return await resolveOrRefreshToken(options);
516
+ } catch (error) {
517
+ const message = error instanceof Error ? error.message : "Token refresh failed";
518
+ throw new ZapierAuthenticationError(
519
+ `${message}
520
+ Please run 'login' to authenticate again.`
521
+ );
522
+ }
523
+ }
524
+ async function getLoggedInUser(options = {}) {
525
+ const jwt2 = await getToken(options).catch(() => void 0);
526
+ if (!jwt2) {
527
+ throw new Error(
528
+ "No valid authentication token available. Please login first."
529
+ );
530
+ }
531
+ let decodedJwt = decodeJwtOrThrow(jwt2);
532
+ if (decodedJwt.payload["sub_type"] == "service") {
533
+ decodedJwt = decodeJwtOrThrow(decodedJwt.payload["njwt"]);
534
+ }
535
+ if (typeof decodedJwt.payload["zap:acc"] !== "string") {
536
+ throw new Error("JWT payload does not contain accountId");
537
+ }
538
+ const accountId = parseInt(decodedJwt.payload["zap:acc"], 10);
539
+ if (isNaN(accountId)) {
540
+ throw new Error("JWT accountId is not a number");
541
+ }
542
+ if (decodedJwt.payload["sub_type"] !== "customuser" || typeof decodedJwt.payload["sub"] !== "string") {
543
+ throw new Error("JWT payload does not contain customUserId");
544
+ }
545
+ const customUserId = parseInt(decodedJwt.payload["sub"], 10);
546
+ if (isNaN(customUserId)) {
547
+ throw new Error("JWT customUserId is not a number");
548
+ }
549
+ const email = decodedJwt.payload["zap:uname"];
550
+ if (typeof email !== "string") {
551
+ throw new Error("JWT payload does not contain email");
552
+ }
553
+ return {
554
+ accountId,
555
+ customUserId,
556
+ email
557
+ };
558
+ }
559
+ function getLoginStorageMode() {
560
+ const cfg = getConfig();
561
+ if (typeof cfg.get("login_jwt") === "string") {
562
+ return "config";
563
+ }
564
+ const explicitMode = cfg.get("login_storage_mode");
565
+ if (explicitMode === "keychain" || explicitMode === "config") {
566
+ return explicitMode;
567
+ }
568
+ return "keychain";
569
+ }
570
+ async function logout(options = {}) {
571
+ const { onEvent } = options;
572
+ const mode = getLoginStorageMode();
573
+ cachedLogin = void 0;
574
+ await clearTokensFromKeychain();
575
+ const cfg = getConfig();
576
+ cfg.set("login_storage_mode", mode);
577
+ cfg.delete("login_expires_at");
578
+ cfg.delete("login_jwt");
579
+ cfg.delete("login_refresh_token");
580
+ onEvent?.({
581
+ type: "auth_logout",
582
+ payload: { message: "Logged out successfully", operation: "logout" },
583
+ timestamp: Date.now()
584
+ });
585
+ }
586
+ function getConfigPath() {
587
+ const cfg = getConfig();
588
+ return cfg.path;
589
+ }
590
+
591
+ exports.AUTH_MODE_HEADER = AUTH_MODE_HEADER;
592
+ exports.ZapierAuthenticationError = ZapierAuthenticationError;
593
+ exports.createCache = createCache;
594
+ exports.getAuthAuthorizeUrl = getAuthAuthorizeUrl;
595
+ exports.getAuthTokenUrl = getAuthTokenUrl;
596
+ exports.getConfig = getConfig;
597
+ exports.getConfigPath = getConfigPath;
598
+ exports.getLoggedInUser = getLoggedInUser;
599
+ exports.getLoginStorageMode = getLoginStorageMode;
600
+ exports.getPkceLoginConfig = getPkceLoginConfig;
601
+ exports.getToken = getToken;
602
+ exports.logout = logout;
603
+ exports.unloadConfig = unloadConfig;
604
+ exports.updateLogin = updateLogin;