@infaris/calendar-cli 0.9.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/README.md +426 -0
- package/dist/activity.js +165 -0
- package/dist/api.js +409 -0
- package/dist/auth.js +378 -0
- package/dist/browser.js +24 -0
- package/dist/config.js +196 -0
- package/dist/crm-api.js +37 -0
- package/dist/crm-index.js +198 -0
- package/dist/dates.js +164 -0
- package/dist/event-input.js +39 -0
- package/dist/freebusy.js +92 -0
- package/dist/hours-cli.js +335 -0
- package/dist/hours.js +276 -0
- package/dist/index.js +1047 -0
- package/dist/legacy.js +43 -0
- package/dist/selectors.js +49 -0
- package/dist/task-download.js +56 -0
- package/package.json +38 -0
package/dist/auth.js
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import { createInterface } from "node:readline/promises";
|
|
4
|
+
import { openBrowser } from "./browser.js";
|
|
5
|
+
import { CLIENT_ID, ISSUER, LOOPBACK_PORT, PENDING_LOGIN_TTL_MS, canonicalCalendarUrl, clearPendingLogin, loadCredentials, loadPendingLogin, saveCredentials, savePendingLogin, withRefreshLock, } from "./config.js";
|
|
6
|
+
const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
|
|
7
|
+
function html(title, body) {
|
|
8
|
+
return `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title>
|
|
9
|
+
<style>body{font-family:ui-sans-serif,system-ui,sans-serif;background:#09090b;color:#e4e4e7;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0}
|
|
10
|
+
.card{text-align:center;padding:48px 56px;border:1px solid #27272a;border-radius:16px;background:#111113}
|
|
11
|
+
h1{font-size:20px;margin:0 0 8px}p{color:#a1a1aa;margin:0}</style></head>
|
|
12
|
+
<body><div class="card"><h1>${title}</h1><p>${body}</p></div></body></html>`;
|
|
13
|
+
}
|
|
14
|
+
function base64url(buf) {
|
|
15
|
+
return buf
|
|
16
|
+
.toString("base64")
|
|
17
|
+
.replace(/\+/g, "-")
|
|
18
|
+
.replace(/\//g, "_")
|
|
19
|
+
.replace(/=+$/, "");
|
|
20
|
+
}
|
|
21
|
+
function decodeJwtPayload(token) {
|
|
22
|
+
try {
|
|
23
|
+
const payload = token.split(".")[1];
|
|
24
|
+
if (!payload)
|
|
25
|
+
return {};
|
|
26
|
+
return JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return {};
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function toCredentials(baseUrl, tokens) {
|
|
33
|
+
const claims = decodeJwtPayload(tokens.access_token);
|
|
34
|
+
const expClaim = typeof claims.exp === "number" ? claims.exp * 1000 : null;
|
|
35
|
+
const expiresAt = expClaim ?? Date.now() + (tokens.expires_in ?? 900) * 1000;
|
|
36
|
+
return {
|
|
37
|
+
baseUrl: canonicalCalendarUrl(baseUrl),
|
|
38
|
+
issuer: ISSUER,
|
|
39
|
+
accessToken: tokens.access_token,
|
|
40
|
+
refreshToken: tokens.refresh_token,
|
|
41
|
+
expiresAt,
|
|
42
|
+
userId: typeof claims.sub === "string" ? claims.sub : "",
|
|
43
|
+
email: typeof claims.email === "string" ? claims.email : "",
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
async function exchangeToken(params) {
|
|
47
|
+
const res = await fetch(`${ISSUER}/api/oauth/token`, {
|
|
48
|
+
method: "POST",
|
|
49
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
50
|
+
body: new URLSearchParams(params).toString(),
|
|
51
|
+
});
|
|
52
|
+
if (!res.ok) {
|
|
53
|
+
let detail = "";
|
|
54
|
+
try {
|
|
55
|
+
const body = (await res.json());
|
|
56
|
+
detail = `: ${body.error_description || body.error || ""}`;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
/* ignore */
|
|
60
|
+
}
|
|
61
|
+
throw new Error(`Token request failed (${res.status})${detail}`);
|
|
62
|
+
}
|
|
63
|
+
return (await res.json());
|
|
64
|
+
}
|
|
65
|
+
function buildAuthUrl(mode) {
|
|
66
|
+
const verifier = base64url(randomBytes(32));
|
|
67
|
+
const challenge = base64url(createHash("sha256").update(verifier).digest());
|
|
68
|
+
const state = base64url(randomBytes(16));
|
|
69
|
+
const redirectUri = mode === "loopback"
|
|
70
|
+
? `http://127.0.0.1:${LOOPBACK_PORT}/callback`
|
|
71
|
+
: `${ISSUER}/oauth/cli-callback`;
|
|
72
|
+
const authUrl = `${ISSUER}/api/oauth/authorize` +
|
|
73
|
+
`?response_type=code` +
|
|
74
|
+
`&client_id=${encodeURIComponent(CLIENT_ID)}` +
|
|
75
|
+
`&redirect_uri=${encodeURIComponent(redirectUri)}` +
|
|
76
|
+
`&scope=${encodeURIComponent("openid email profile")}` +
|
|
77
|
+
`&state=${state}` +
|
|
78
|
+
`&code_challenge=${challenge}` +
|
|
79
|
+
`&code_challenge_method=S256`;
|
|
80
|
+
return { verifier, state, redirectUri, authUrl };
|
|
81
|
+
}
|
|
82
|
+
/** True when we're likely on a remote/SSH session, where a local loopback
|
|
83
|
+
* redirect can never be reached by the browser that completes the login. */
|
|
84
|
+
export function isLikelySshSession() {
|
|
85
|
+
return Boolean(process.env.SSH_CONNECTION || process.env.SSH_TTY || process.env.SSH_CLIENT);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Pulls the authorization code out of either a pasted full redirect URL or a
|
|
89
|
+
* bare code value, and checks `state` when we have one to compare against
|
|
90
|
+
* (PKCE's `code_verifier` is what actually protects the token exchange, so a
|
|
91
|
+
* bare code with no state alongside it is still safe to accept).
|
|
92
|
+
*/
|
|
93
|
+
function extractCode(pasted, expectedState) {
|
|
94
|
+
const trimmed = pasted.trim();
|
|
95
|
+
let code;
|
|
96
|
+
let returnedState = null;
|
|
97
|
+
try {
|
|
98
|
+
const url = new URL(trimmed);
|
|
99
|
+
code = url.searchParams.get("code");
|
|
100
|
+
returnedState = url.searchParams.get("state");
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
// Not a URL - assume they pasted the bare code value.
|
|
104
|
+
code = trimmed || null;
|
|
105
|
+
}
|
|
106
|
+
if (!code) {
|
|
107
|
+
throw new Error("No authorization code found in what you pasted.");
|
|
108
|
+
}
|
|
109
|
+
if (returnedState !== null && returnedState !== expectedState) {
|
|
110
|
+
throw new Error("State mismatch - please try signing in again.");
|
|
111
|
+
}
|
|
112
|
+
return code;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Manual sign-in: print the authorize URL, but instead of listening on a
|
|
116
|
+
* local port, redirect to an Infaris page that displays the code and ask the
|
|
117
|
+
* user to paste it back. Works from any machine (SSH, a t3code session, a
|
|
118
|
+
* container) because it never depends on the browser reaching the CLI
|
|
119
|
+
* process.
|
|
120
|
+
*/
|
|
121
|
+
async function loginManual(baseUrl) {
|
|
122
|
+
if (!process.stdin.isTTY) {
|
|
123
|
+
// Without a terminal nobody can paste the code; fail fast instead of
|
|
124
|
+
// hanging an agent's tool call until the timeout.
|
|
125
|
+
throw new Error("No interactive terminal to paste the code into. Use `infaris-calendar login link` " +
|
|
126
|
+
"and finish with `infaris-calendar login code <code>`.");
|
|
127
|
+
}
|
|
128
|
+
const { verifier, state, redirectUri, authUrl } = buildAuthUrl("hosted");
|
|
129
|
+
process.stdout.write(`Open this URL on any device to sign in with Infaris:\n\n ${authUrl}\n\n`);
|
|
130
|
+
process.stdout.write("Infaris will show you a code after you sign in - paste it below.\n\n");
|
|
131
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
132
|
+
let pasted;
|
|
133
|
+
try {
|
|
134
|
+
const timeout = new Promise((_, reject) => setTimeout(() => reject(new Error("Login timed out. Please run `infaris-calendar login` again.")), LOGIN_TIMEOUT_MS).unref());
|
|
135
|
+
pasted = await Promise.race([rl.question("Paste the code: "), timeout]);
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
rl.close();
|
|
139
|
+
}
|
|
140
|
+
const code = extractCode(pasted, state);
|
|
141
|
+
const tokens = await exchangeToken({
|
|
142
|
+
grant_type: "authorization_code",
|
|
143
|
+
code,
|
|
144
|
+
redirect_uri: redirectUri,
|
|
145
|
+
client_id: CLIENT_ID,
|
|
146
|
+
code_verifier: verifier,
|
|
147
|
+
});
|
|
148
|
+
const credentials = toCredentials(baseUrl, tokens);
|
|
149
|
+
saveCredentials(credentials);
|
|
150
|
+
return { credentials };
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Step 1 of a two-step sign-in meant to be relayed through a chat agent
|
|
154
|
+
* (Claude Code, Codex, OpenCode, Cursor): print/return the sign-in URL and
|
|
155
|
+
* stash the PKCE state on disk, then return immediately with no open
|
|
156
|
+
* connection - so the agent can paste the URL into the chat and come back
|
|
157
|
+
* later (a new process, from `login code`) once the user replies with a code.
|
|
158
|
+
*/
|
|
159
|
+
/** A pending flow is reused while the user still has this long to finish it. */
|
|
160
|
+
const REUSE_MIN_REMAINING_MS = 5 * 60 * 1000;
|
|
161
|
+
export function beginLogin(baseUrl, opts = {}) {
|
|
162
|
+
const canonical = canonicalCalendarUrl(baseUrl);
|
|
163
|
+
const existing = loadPendingLogin();
|
|
164
|
+
// Re-running `login link` (an agent retrying, a second worktree) must not
|
|
165
|
+
// invalidate a URL the user may already be completing.
|
|
166
|
+
if (!opts.fresh &&
|
|
167
|
+
existing?.authUrl &&
|
|
168
|
+
canonicalCalendarUrl(existing.baseUrl) === canonical &&
|
|
169
|
+
existing.createdAt + PENDING_LOGIN_TTL_MS - Date.now() > REUSE_MIN_REMAINING_MS) {
|
|
170
|
+
return {
|
|
171
|
+
authUrl: existing.authUrl,
|
|
172
|
+
reused: true,
|
|
173
|
+
expiresAt: existing.createdAt + PENDING_LOGIN_TTL_MS,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
const { verifier, state, redirectUri, authUrl } = buildAuthUrl("hosted");
|
|
177
|
+
const createdAt = Date.now();
|
|
178
|
+
savePendingLogin({ baseUrl: canonical, authUrl, verifier, state, redirectUri, createdAt });
|
|
179
|
+
return { authUrl, reused: false, expiresAt: createdAt + PENDING_LOGIN_TTL_MS };
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* The code for `login code`: the argument, or stdin when the argument is `-`
|
|
183
|
+
* or missing. Piping keeps the one-time code out of shell history and `ps`.
|
|
184
|
+
*/
|
|
185
|
+
export async function readLoginCode(value) {
|
|
186
|
+
if (value && value !== "-")
|
|
187
|
+
return value;
|
|
188
|
+
if (process.stdin.isTTY) {
|
|
189
|
+
throw new Error("Pass the code as an argument or pipe it in: `login code -`.");
|
|
190
|
+
}
|
|
191
|
+
let input = "";
|
|
192
|
+
for await (const chunk of process.stdin)
|
|
193
|
+
input += String(chunk);
|
|
194
|
+
if (!input.trim())
|
|
195
|
+
throw new Error("No code received on stdin.");
|
|
196
|
+
return input.trim();
|
|
197
|
+
}
|
|
198
|
+
/** Non-secret description of the pending two-step sign-in, if any. */
|
|
199
|
+
export function pendingLoginStatus() {
|
|
200
|
+
const pending = loadPendingLogin();
|
|
201
|
+
if (!pending)
|
|
202
|
+
return null;
|
|
203
|
+
return {
|
|
204
|
+
baseUrl: pending.baseUrl,
|
|
205
|
+
startedAt: pending.createdAt,
|
|
206
|
+
expiresAt: pending.createdAt + PENDING_LOGIN_TTL_MS,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
/** Step 2: finish a sign-in started with `beginLogin`, given the pasted redirect URL or code. */
|
|
210
|
+
export async function completeLogin(pasted) {
|
|
211
|
+
const pending = loadPendingLogin();
|
|
212
|
+
if (!pending) {
|
|
213
|
+
throw new Error("No pending sign-in (or it expired). Run `infaris-calendar login link` first.");
|
|
214
|
+
}
|
|
215
|
+
const code = extractCode(pasted, pending.state);
|
|
216
|
+
const tokens = await exchangeToken({
|
|
217
|
+
grant_type: "authorization_code",
|
|
218
|
+
code,
|
|
219
|
+
redirect_uri: pending.redirectUri,
|
|
220
|
+
client_id: CLIENT_ID,
|
|
221
|
+
code_verifier: pending.verifier,
|
|
222
|
+
});
|
|
223
|
+
const credentials = toCredentials(pending.baseUrl, tokens);
|
|
224
|
+
saveCredentials(credentials);
|
|
225
|
+
clearPendingLogin();
|
|
226
|
+
return { credentials };
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Infaris OAuth login with loopback PKCE (same pattern as the Env CLI):
|
|
230
|
+
* 1. spin up a one-shot HTTP server on the registered loopback port
|
|
231
|
+
* 2. open the browser to {issuer}/api/oauth/authorize with a PKCE challenge
|
|
232
|
+
* 3. Infaris signs the user in and redirects back with an authorization code
|
|
233
|
+
* 4. exchange the code (plus PKCE verifier) for access/refresh tokens
|
|
234
|
+
*/
|
|
235
|
+
function loginLoopback(baseUrl) {
|
|
236
|
+
const { verifier, state, redirectUri, authUrl } = buildAuthUrl("loopback");
|
|
237
|
+
return new Promise((resolve, reject) => {
|
|
238
|
+
const server = createServer((req, res) => {
|
|
239
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
240
|
+
if (url.pathname !== "/callback") {
|
|
241
|
+
res.statusCode = 404;
|
|
242
|
+
res.end("Not found");
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
const code = url.searchParams.get("code");
|
|
246
|
+
const returnedState = url.searchParams.get("state");
|
|
247
|
+
const errorParam = url.searchParams.get("error");
|
|
248
|
+
if (errorParam) {
|
|
249
|
+
res.statusCode = 400;
|
|
250
|
+
res.setHeader("content-type", "text/html");
|
|
251
|
+
res.end(html("Login failed", errorParam));
|
|
252
|
+
cleanup();
|
|
253
|
+
reject(new Error(`Login failed: ${errorParam}`));
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
if (returnedState !== state || !code) {
|
|
257
|
+
res.statusCode = 400;
|
|
258
|
+
res.setHeader("content-type", "text/html");
|
|
259
|
+
res.end(html("Login failed", "Invalid response. Please try again."));
|
|
260
|
+
cleanup();
|
|
261
|
+
reject(new Error("State mismatch or missing code during login"));
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
exchangeToken({
|
|
265
|
+
grant_type: "authorization_code",
|
|
266
|
+
code,
|
|
267
|
+
redirect_uri: redirectUri,
|
|
268
|
+
client_id: CLIENT_ID,
|
|
269
|
+
code_verifier: verifier,
|
|
270
|
+
})
|
|
271
|
+
.then((tokens) => {
|
|
272
|
+
const credentials = toCredentials(baseUrl, tokens);
|
|
273
|
+
saveCredentials(credentials);
|
|
274
|
+
res.statusCode = 200;
|
|
275
|
+
res.setHeader("content-type", "text/html");
|
|
276
|
+
res.end(html("You're signed in", "You can close this tab and return to your terminal."));
|
|
277
|
+
cleanup();
|
|
278
|
+
resolve({ credentials });
|
|
279
|
+
})
|
|
280
|
+
.catch((err) => {
|
|
281
|
+
res.statusCode = 500;
|
|
282
|
+
res.setHeader("content-type", "text/html");
|
|
283
|
+
res.end(html("Login failed", "Token exchange failed."));
|
|
284
|
+
cleanup();
|
|
285
|
+
reject(err);
|
|
286
|
+
});
|
|
287
|
+
});
|
|
288
|
+
const timer = setTimeout(() => {
|
|
289
|
+
cleanup();
|
|
290
|
+
reject(new Error("Login timed out. Please run `infaris-calendar login` again."));
|
|
291
|
+
}, LOGIN_TIMEOUT_MS);
|
|
292
|
+
function cleanup() {
|
|
293
|
+
clearTimeout(timer);
|
|
294
|
+
server.close();
|
|
295
|
+
}
|
|
296
|
+
server.on("error", (err) => {
|
|
297
|
+
cleanup();
|
|
298
|
+
reject(err);
|
|
299
|
+
});
|
|
300
|
+
server.listen(LOOPBACK_PORT, "127.0.0.1", () => {
|
|
301
|
+
process.stdout.write(`Opening your browser to sign in with Infaris...\n`);
|
|
302
|
+
process.stdout.write(`If it does not open, visit:\n ${authUrl}\n\n`);
|
|
303
|
+
openBrowser(authUrl);
|
|
304
|
+
});
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Signs in with Infaris. Uses the loopback+browser flow by default; falls
|
|
309
|
+
* back to `loginManual` (paste the redirect back) when `manual` is passed
|
|
310
|
+
* explicitly or an SSH session is detected, since the loopback redirect can
|
|
311
|
+
* never reach the CLI process in that case - see `isLikelySshSession`.
|
|
312
|
+
*/
|
|
313
|
+
export function login(baseUrl, opts = {}) {
|
|
314
|
+
if (opts.manual) {
|
|
315
|
+
return loginManual(baseUrl);
|
|
316
|
+
}
|
|
317
|
+
if (isLikelySshSession()) {
|
|
318
|
+
process.stdout.write("Detected an SSH session; using manual sign-in (pass --manual to force this anywhere).\n\n");
|
|
319
|
+
return loginManual(baseUrl);
|
|
320
|
+
}
|
|
321
|
+
return loginLoopback(baseUrl);
|
|
322
|
+
}
|
|
323
|
+
async function refreshAccessToken(stale) {
|
|
324
|
+
return withRefreshLock(async () => {
|
|
325
|
+
// Another process may have rotated the token while we waited for the lock.
|
|
326
|
+
const creds = loadCredentials() ?? stale;
|
|
327
|
+
if (creds.accessToken !== stale.accessToken && Date.now() + 30_000 < creds.expiresAt) {
|
|
328
|
+
return creds;
|
|
329
|
+
}
|
|
330
|
+
return rotate(creds);
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
async function rotate(creds) {
|
|
334
|
+
if (!creds.refreshToken) {
|
|
335
|
+
throw new Error("Your session has expired. Please run `infaris-calendar login` again.");
|
|
336
|
+
}
|
|
337
|
+
let tokens;
|
|
338
|
+
try {
|
|
339
|
+
tokens = await exchangeToken({
|
|
340
|
+
grant_type: "refresh_token",
|
|
341
|
+
refresh_token: creds.refreshToken,
|
|
342
|
+
client_id: CLIENT_ID,
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
catch (err) {
|
|
346
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
347
|
+
// Only a rejected grant means the session is gone; a network or server
|
|
348
|
+
// error is worth retrying without a new sign-in.
|
|
349
|
+
if (!/\((400|401)\)/.test(message))
|
|
350
|
+
throw err;
|
|
351
|
+
throw new Error("Your session has expired. Please run `infaris-calendar login` again " +
|
|
352
|
+
"(or `infaris-calendar login link` from an agent or SSH session).");
|
|
353
|
+
}
|
|
354
|
+
const updated = toCredentials(creds.baseUrl, tokens);
|
|
355
|
+
// Keep the old refresh token if the server did not send a new one.
|
|
356
|
+
updated.refreshToken ??= creds.refreshToken;
|
|
357
|
+
saveCredentials(updated);
|
|
358
|
+
return updated;
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Return valid credentials, transparently refreshing the access token when it
|
|
362
|
+
* expires within the next 30 seconds.
|
|
363
|
+
*/
|
|
364
|
+
let refreshingCredentials = null;
|
|
365
|
+
export async function getValidCredentials() {
|
|
366
|
+
const creds = loadCredentials();
|
|
367
|
+
if (!creds) {
|
|
368
|
+
throw new Error("Not logged in. Run `infaris-calendar login` first.");
|
|
369
|
+
}
|
|
370
|
+
if (Date.now() + 30_000 >= creds.expiresAt) {
|
|
371
|
+
// Parallel dossier reads must not rotate the same refresh token twice.
|
|
372
|
+
refreshingCredentials ??= refreshAccessToken(creds).finally(() => {
|
|
373
|
+
refreshingCredentials = null;
|
|
374
|
+
});
|
|
375
|
+
return refreshingCredentials;
|
|
376
|
+
}
|
|
377
|
+
return creds;
|
|
378
|
+
}
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
/**
|
|
3
|
+
* Open a URL in the user's default browser. Best-effort and cross-platform;
|
|
4
|
+
* if it fails the caller should print the URL so the user can open it manually.
|
|
5
|
+
*/
|
|
6
|
+
export function openBrowser(url) {
|
|
7
|
+
const platform = process.platform;
|
|
8
|
+
try {
|
|
9
|
+
if (platform === "win32") {
|
|
10
|
+
// Use PowerShell Start-Process: cmd's `start` truncates the URL at the
|
|
11
|
+
// first `&`, dropping all query params after response_type.
|
|
12
|
+
spawn("powershell.exe", ["-NoProfile", "-Command", `Start-Process '${url.replace(/'/g, "''")}'`], { detached: true, stdio: "ignore" }).unref();
|
|
13
|
+
}
|
|
14
|
+
else if (platform === "darwin") {
|
|
15
|
+
spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
|
|
16
|
+
}
|
|
17
|
+
else {
|
|
18
|
+
spawn("xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
/* caller prints the fallback URL */
|
|
23
|
+
}
|
|
24
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
4
|
+
import { infarisEnv, migrateLegacyDir } from "./legacy.js";
|
|
5
|
+
import { chmodSync, existsSync, mkdirSync, openSync, closeSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
|
|
6
|
+
/**
|
|
7
|
+
* Canonical Calendar host. `calendar.ipulse.one` 301s to `.infaris.com` and
|
|
8
|
+
* `fetch()` drops `Authorization` on that cross-origin redirect, so the CLI
|
|
9
|
+
* must never call the legacy host with a Bearer token.
|
|
10
|
+
*/
|
|
11
|
+
export function canonicalCalendarUrl(raw) {
|
|
12
|
+
const trimmed = raw.replace(/\/$/, "");
|
|
13
|
+
try {
|
|
14
|
+
const url = new URL(trimmed);
|
|
15
|
+
if (url.hostname === "localhost" || url.hostname === "127.0.0.1") {
|
|
16
|
+
return trimmed;
|
|
17
|
+
}
|
|
18
|
+
if (url.hostname.replace(/^www\./, "") === "calendar.ipulse.one") {
|
|
19
|
+
url.hostname = "calendar.infaris.com";
|
|
20
|
+
return url.origin;
|
|
21
|
+
}
|
|
22
|
+
return `${url.origin}${url.pathname === "/" ? "" : url.pathname.replace(/\/$/, "")}`;
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return trimmed;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export const DEFAULT_BASE_URL = canonicalCalendarUrl(infarisEnv("CALENDAR_URL") || "https://calendar.infaris.com");
|
|
29
|
+
/** Infaris OAuth issuer (same identity provider as the Env CLI). Legacy hosts map to infaris.com. */
|
|
30
|
+
function mapIssuer(raw) {
|
|
31
|
+
try {
|
|
32
|
+
const url = new URL(raw);
|
|
33
|
+
if (url.hostname === "localhost" || url.hostname === "127.0.0.1")
|
|
34
|
+
return raw;
|
|
35
|
+
url.hostname = url.hostname.replace(/ipulse\.one$/i, "infaris.com");
|
|
36
|
+
return url.origin;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return "https://infaris.com";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export const ISSUER = mapIssuer(infarisEnv("CALENDAR_ISSUER")?.replace(/\/$/, "") || "https://infaris.com");
|
|
43
|
+
export const CLIENT_ID =
|
|
44
|
+
// The OAuth client id is a server-side registration and keeps its name.
|
|
45
|
+
infarisEnv("CALENDAR_CLIENT_ID") || "pulsecalendar-cli";
|
|
46
|
+
/** Fixed loopback port registered as redirect URI on the OAuth client. */
|
|
47
|
+
export const LOOPBACK_PORT = Number(infarisEnv("CALENDAR_PORT") || "47655");
|
|
48
|
+
function resolveConfigDir() {
|
|
49
|
+
const override = infarisEnv("CALENDAR_CONFIG_DIR");
|
|
50
|
+
if (override)
|
|
51
|
+
return override;
|
|
52
|
+
const dir = join(homedir(), ".infaris", "calendar");
|
|
53
|
+
migrateLegacyDir(dir, join(homedir(), ".pulse" + "calendar"));
|
|
54
|
+
return dir;
|
|
55
|
+
}
|
|
56
|
+
let configDirCache;
|
|
57
|
+
/** Resolved on first use, so importing this module never moves files. */
|
|
58
|
+
function configDir() {
|
|
59
|
+
configDirCache ??= resolveConfigDir();
|
|
60
|
+
return configDirCache;
|
|
61
|
+
}
|
|
62
|
+
const credentialsFile = () => join(configDir(), "credentials.json");
|
|
63
|
+
export function loadCredentials() {
|
|
64
|
+
try {
|
|
65
|
+
if (!existsSync(credentialsFile()))
|
|
66
|
+
return null;
|
|
67
|
+
const raw = readFileSync(credentialsFile(), "utf8");
|
|
68
|
+
const parsed = JSON.parse(raw);
|
|
69
|
+
if (!parsed.accessToken || !parsed.baseUrl || !parsed.issuer)
|
|
70
|
+
return null;
|
|
71
|
+
const creds = parsed;
|
|
72
|
+
const baseUrl = canonicalCalendarUrl(creds.baseUrl);
|
|
73
|
+
const issuer = mapIssuer(creds.issuer);
|
|
74
|
+
if (baseUrl !== creds.baseUrl || issuer !== creds.issuer) {
|
|
75
|
+
creds.baseUrl = baseUrl;
|
|
76
|
+
creds.issuer = issuer;
|
|
77
|
+
saveCredentials(creds);
|
|
78
|
+
}
|
|
79
|
+
return creds;
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Write a secret file readable only by the current user. The temp file is
|
|
87
|
+
* created with 0600 before any content lands in it and then renamed, so a
|
|
88
|
+
* parallel process never reads a half-written token file.
|
|
89
|
+
*/
|
|
90
|
+
function writePrivateFile(file, content) {
|
|
91
|
+
mkdirSync(configDir(), { recursive: true, mode: 0o700 });
|
|
92
|
+
const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
93
|
+
try {
|
|
94
|
+
writeFileSync(tmp, content, { encoding: "utf8", mode: 0o600 });
|
|
95
|
+
renameSync(tmp, file);
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
rmSync(tmp, { force: true });
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
// Best-effort: also tighten files created by older versions (no-op on Windows).
|
|
102
|
+
chmodSync(file, 0o600);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
/* ignore */
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
export function saveCredentials(creds) {
|
|
109
|
+
writePrivateFile(credentialsFile(), JSON.stringify(creds, null, 2));
|
|
110
|
+
}
|
|
111
|
+
const refreshLockFile = () => join(configDir(), "refresh.lock");
|
|
112
|
+
const LOCK_STALE_MS = 30_000;
|
|
113
|
+
const LOCK_WAIT_MS = 20_000;
|
|
114
|
+
/**
|
|
115
|
+
* Serialize token refreshes across processes. Infaris rotates the refresh
|
|
116
|
+
* token on every use and revokes the whole token family when an old one is
|
|
117
|
+
* replayed, so two agents refreshing the same stored token at once could
|
|
118
|
+
* sign every session of this user out. Callers re-read the credentials
|
|
119
|
+
* inside the lock and only refresh when nobody else already did.
|
|
120
|
+
*/
|
|
121
|
+
export async function withRefreshLock(fn) {
|
|
122
|
+
mkdirSync(configDir(), { recursive: true, mode: 0o700 });
|
|
123
|
+
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
124
|
+
for (;;) {
|
|
125
|
+
try {
|
|
126
|
+
closeSync(openSync(refreshLockFile(), "wx", 0o600));
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
catch (err) {
|
|
130
|
+
if (err.code !== "EEXIST")
|
|
131
|
+
throw err;
|
|
132
|
+
try {
|
|
133
|
+
if (Date.now() - statSync(refreshLockFile()).mtimeMs > LOCK_STALE_MS) {
|
|
134
|
+
rmSync(refreshLockFile(), { force: true });
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (Date.now() > deadline) {
|
|
142
|
+
throw new Error("Another infaris-calendar process is refreshing the session. Try again in a moment.");
|
|
143
|
+
}
|
|
144
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
return await fn();
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
rmSync(refreshLockFile(), { force: true });
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
export function clearCredentials() {
|
|
155
|
+
try {
|
|
156
|
+
rmSync(credentialsFile(), { force: true });
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
/* ignore */
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
export function credentialsPath() {
|
|
163
|
+
return credentialsFile();
|
|
164
|
+
}
|
|
165
|
+
const pendingLoginFile = () => join(configDir(), "pending-login.json");
|
|
166
|
+
export const PENDING_LOGIN_TTL_MS = 15 * 60 * 1000;
|
|
167
|
+
export function savePendingLogin(pending) {
|
|
168
|
+
writePrivateFile(pendingLoginFile(), JSON.stringify(pending));
|
|
169
|
+
}
|
|
170
|
+
export function loadPendingLogin() {
|
|
171
|
+
try {
|
|
172
|
+
if (!existsSync(pendingLoginFile()))
|
|
173
|
+
return null;
|
|
174
|
+
const parsed = JSON.parse(readFileSync(pendingLoginFile(), "utf8"));
|
|
175
|
+
if (!parsed.verifier ||
|
|
176
|
+
!parsed.state ||
|
|
177
|
+
!Number.isFinite(parsed.createdAt) ||
|
|
178
|
+
parsed.createdAt > Date.now() ||
|
|
179
|
+
Date.now() - parsed.createdAt > PENDING_LOGIN_TTL_MS) {
|
|
180
|
+
clearPendingLogin();
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
return parsed;
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
export function clearPendingLogin() {
|
|
190
|
+
try {
|
|
191
|
+
rmSync(pendingLoginFile(), { force: true });
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
/* ignore */
|
|
195
|
+
}
|
|
196
|
+
}
|
package/dist/crm-api.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { getValidCredentials } from "./auth.js";
|
|
2
|
+
import { infarisEnv } from "./legacy.js";
|
|
3
|
+
/** CRM shares Calendar's human PKCE login, not its service-to-service key. */
|
|
4
|
+
export async function crmFetch(path, init = {}) {
|
|
5
|
+
const creds = await getValidCredentials();
|
|
6
|
+
// A development Calendar login must never silently write to production CRM.
|
|
7
|
+
const configured = infarisEnv("CRM_URL");
|
|
8
|
+
if (!configured &&
|
|
9
|
+
new URL(creds.baseUrl).origin !== "https://calendar.infaris.com") {
|
|
10
|
+
throw new Error("Set INFARIS_CRM_URL for this non-production Calendar login");
|
|
11
|
+
}
|
|
12
|
+
const url = new URL(configured || "https://support.infaris.com");
|
|
13
|
+
if (url.hostname === "support.ipulse.one")
|
|
14
|
+
url.hostname = "support.infaris.com";
|
|
15
|
+
if (url.protocol !== "https:" &&
|
|
16
|
+
!(url.protocol === "http:" &&
|
|
17
|
+
["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) {
|
|
18
|
+
throw new Error("INFARIS_CRM_URL must use HTTPS (or local HTTP)");
|
|
19
|
+
}
|
|
20
|
+
if (url.username ||
|
|
21
|
+
url.password ||
|
|
22
|
+
url.pathname !== "/" ||
|
|
23
|
+
url.search ||
|
|
24
|
+
url.hash)
|
|
25
|
+
throw new Error("INFARIS_CRM_URL must be a plain origin");
|
|
26
|
+
const res = await fetch(`${url.origin}/api/crm${path}`, {
|
|
27
|
+
...init,
|
|
28
|
+
redirect: "error",
|
|
29
|
+
signal: AbortSignal.timeout(30_000),
|
|
30
|
+
headers: { ...init.headers, authorization: `Bearer ${creds.accessToken}` },
|
|
31
|
+
});
|
|
32
|
+
if (!res.ok) {
|
|
33
|
+
const body = (await res.json().catch(() => ({})));
|
|
34
|
+
throw new Error(`CRM request failed (${res.status}): ${body.error || res.statusText}${res.status === 401 ? ". Run infaris-crm login with an Infaris admin account." : ""}`);
|
|
35
|
+
}
|
|
36
|
+
return res.json();
|
|
37
|
+
}
|