activitysmith-cli 1.13.0 → 1.15.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.
Files changed (4) hide show
  1. package/README.md +72 -11
  2. package/package.json +2 -2
  3. package/src/auth.js +438 -0
  4. package/src/cli.js +146 -22
package/README.md CHANGED
@@ -24,9 +24,53 @@ For example, a Codex agent can work on your computer, send a Push Notification w
24
24
 
25
25
  ## Quickstart
26
26
 
27
+ 1. Run `activitysmith auth login` and approve access in your browser.
28
+ 2. Run `activitysmith --help` to inspect available commands.
29
+
30
+ ```bash
31
+ activitysmith auth login
32
+
33
+ activitysmith push --title "Hello"
34
+ ```
35
+
36
+ ## Authentication
37
+
38
+ ### Sign in with your browser
39
+
40
+ `activitysmith auth login` opens your browser to the ActivitySmith approval screen. Select **Approve**. The CLI saves the sign-in to `~/.config/activitysmith/credentials.json` with owner-only file permissions, and every command then uses it. No API key is created.
41
+
42
+ ```bash
43
+ activitysmith auth login
44
+ ```
45
+
46
+ If no browser can open, for example over SSH, the CLI prints the sign-in URL. Open it in any browser. After you approve, paste the address the browser lands on back into the terminal.
47
+
48
+ ```bash
49
+ activitysmith auth login --no-browser
50
+ ```
51
+
52
+ The CLI appears under AI Agents in the ActivitySmith web app. Select **Disconnect** there to stop it immediately on every machine.
53
+
54
+ Check how the CLI authenticates. Secrets are never printed:
55
+
56
+ ```bash
57
+ activitysmith auth status
58
+ ```
59
+
60
+ Sign out to disconnect the CLI and remove the saved sign-in from this machine:
61
+
62
+ ```bash
63
+ activitysmith auth logout
64
+ ```
65
+
66
+ Set `ACTIVITYSMITH_CONFIG_DIR` to save the sign-in in a different directory.
67
+
68
+ ### Use an API key
69
+
27
70
  1. [Create an API key](https://activitysmith.com/app/keys)
28
- 2. Authenticate with `ACTIVITYSMITH_API_KEY` or pass `--api-key` per command.
29
- 3. Run `activitysmith --help` to inspect available commands.
71
+ 2. Set `ACTIVITYSMITH_API_KEY` or pass `--api-key` per command.
72
+
73
+ Use an API key for CI pipelines, servers, and other machines where nobody can approve a browser sign-in. The CLI uses `--api-key` first, then `ACTIVITYSMITH_API_KEY`, then the sign-in from `activitysmith auth login`.
30
74
 
31
75
  Use the environment variable when you want the cleanest shell scripts:
32
76
 
@@ -61,13 +105,13 @@ activitysmith push \
61
105
 
62
106
  ![Push Notifications with custom icons](https://cdn.activitysmith.com/features/push-notifications-with-custom-icons.png)
63
107
 
64
- Set `--icon` to a publicly accessible HTTPS image URL to show an avatar or service logo alongside a smaller ActivitySmith app icon. With a custom icon, iOS may omit the subtitle from the notification.
108
+ Set `--icon` to a publicly accessible HTTPS image URL to show a logo or avatar alongside a smaller ActivitySmith app icon. Host the image anywhere, such as on your own website or CDN. With a custom icon, iOS may omit the subtitle from the notification.
65
109
 
66
110
  ```bash
67
111
  activitysmith push \
68
112
  --title 'MRR just crossed $10,000 🎉' \
69
113
  --message "Up 18% this month from 31 new subscriptions." \
70
- --icon "https://cdn.activitysmith.com/integrations/icons/stripe.png"
114
+ --icon "https://example.com/icons/stripe.png"
71
115
  ```
72
116
 
73
117
  ### Rich Push Notifications with Media
@@ -210,6 +254,22 @@ activitysmith push \
210
254
  --interruption-level "time-sensitive"
211
255
  ```
212
256
 
257
+ ### Replace a Push Notification
258
+
259
+ Every `push` prints a `Notification ID`. Pass it to `--replace` to update a Push Notification you already sent, for example when an incident you alerted on is resolved. The replacement takes the old notification's place on the Lock Screen and in history instead of stacking a second one. It arrives silently, without sound or waking the screen, and goes to the same recipients as the original, so `--channels` and `--interruption-level` don't apply.
260
+
261
+ ```bash
262
+ activitysmith push \
263
+ --title "🚨 checkout-api is down" \
264
+ --message "500 errors on 62% of requests."
265
+ # Notification ID: Xk3pQ8mV2nR7tL9wB4yZ
266
+
267
+ activitysmith push \
268
+ --replace "Xk3pQ8mV2nR7tL9wB4yZ" \
269
+ --title "✅ checkout-api recovered" \
270
+ --message "Error rate is back to normal. Incident resolved."
271
+ ```
272
+
213
273
  ## Live Activities
214
274
 
215
275
  Choose the Live Activity type that matches what you want to show:
@@ -246,6 +306,9 @@ Choose the Live Activity type that matches what you want to show:
246
306
 
247
307
  Use a stable `stream_key` to identify the metric, job, deployment, or system you want to keep visible. The first `activity stream` command starts the Live Activity. Later commands with the same `stream_key` update it.
248
308
 
309
+ > [!WARNING]
310
+ > iOS limits how often a Live Activity can update. Short bursts that end, like deployment steps, are fine. If one Live Activity keeps updating more often than every couple of minutes, iOS throttles it until the budget refills, roughly an hour, even though the API still returns `200`. [Learn more](https://activitysmith.com/docs/live-activity-stream#update-frequency-and-ios-limits)
311
+
249
312
  #### Value
250
313
 
251
314
  ![Value Live Activity stream example](https://cdn.activitysmith.com/features/value-live-activity.png)
@@ -566,12 +629,14 @@ String metric values work too.
566
629
  activitysmith metrics update prod.status healthy
567
630
  ```
568
631
 
569
- ## App Icon Badge Count
632
+ ## App Icon Badge
570
633
 
571
- ![ActivitySmith app icon with an App Icon Badge Count](https://cdn.activitysmith.com/features/badge-count.png)
634
+ ![ActivitySmith app icon with an App Icon Badge](https://cdn.activitysmith.com/features/badge-count.png)
572
635
 
573
636
  Show the number you care about on your ActivitySmith app icon. Track MRR, a customer count, a stock price, or any other value you want to keep in view.
574
637
 
638
+ App Icon Badge requires Push Notifications enabled. On your iPhone, open Settings > ActivitySmith > Notifications and turn on Allow Notifications.
639
+
575
640
  ### Set or update the badge value
576
641
 
577
642
  ```bash
@@ -638,7 +703,7 @@ activitysmith activity stream customer-import \
638
703
 
639
704
  ## Channels
640
705
 
641
- Use `--channels` to target specific team members or devices when sending Push Notifications, Live Activities, or App Icon Badge Count updates. Omit it for account-wide delivery.
706
+ Use `--channels` to target specific team members or devices when sending Push Notifications, Live Activities, or App Icon Badge updates. Omit it for account-wide delivery.
642
707
 
643
708
  ```bash
644
709
  activitysmith push \
@@ -679,7 +744,3 @@ The CLI exits non-zero on non-2xx responses and prints the API error body. That
679
744
  ### [NPM Package](https://www.npmjs.com/package/activitysmith-cli)
680
745
 
681
746
  Install the ActivitySmith CLI from npm
682
-
683
- ### [Source Code](https://github.com/ActivitySmithHQ/activitysmith-cli)
684
-
685
- View the CLI source on GitHub
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "activitysmith-cli",
3
- "version": "1.13.0",
3
+ "version": "1.15.0",
4
4
  "description": "Command-line interface for ActivitySmith. Send Push Notifications, start, update, and end Live Activities, and set App Icon Badge Counts from your terminal.",
5
5
  "keywords": [
6
6
  "activitysmith",
@@ -42,7 +42,7 @@
42
42
  "test": "node --test"
43
43
  },
44
44
  "dependencies": {
45
- "activitysmith": "^1.13.0",
45
+ "activitysmith": "^1.14.0",
46
46
  "commander": "^12.1.0"
47
47
  }
48
48
  }
package/src/auth.js ADDED
@@ -0,0 +1,438 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { chmodSync, closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
+ import { createServer } from "node:http";
5
+ import { homedir } from "node:os";
6
+ import { dirname, join } from "node:path";
7
+ import { createInterface } from "node:readline";
8
+
9
+ export const DEFAULT_ISSUER = "https://activitysmith.com";
10
+ // OAuth resource indicator for the REST API the CLI calls. Tokens issued for it work only there.
11
+ export const DEFAULT_API_RESOURCE = "https://activitysmith.com/api";
12
+ export const CLIENT_NAME = "ActivitySmith CLI";
13
+ // OAuth Client ID Metadata Document hosted on activitysmith.com. It registers the portless
14
+ // loopback callback http://127.0.0.1/callback, so any free port works per login, and the
15
+ // approval screen recognizes this exact client_id as the ActivitySmith CLI.
16
+ export const CLIENT_ID = "https://activitysmith.com/.well-known/oauth-client/activitysmith-cli.json";
17
+ // Sending Push Notifications, Live Activities, badges, and widget values. Nothing else.
18
+ export const LOGIN_SCOPES = "mcp:write";
19
+ const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
20
+ // Refresh a little early so a token does not expire mid-request.
21
+ const ACCESS_TOKEN_REFRESH_MARGIN_MS = 60 * 1000;
22
+ const LOCK_WAIT_MS = 15 * 1000;
23
+ const LOCK_STALE_MS = 30 * 1000;
24
+ const LOCK_POLL_MS = 50;
25
+
26
+ export const credentialsPath = (env = process.env) => {
27
+ if (env.ACTIVITYSMITH_CONFIG_DIR) return join(env.ACTIVITYSMITH_CONFIG_DIR, "credentials.json");
28
+ const configHome = env.XDG_CONFIG_HOME || join(homedir(), ".config");
29
+ return join(configHome, "activitysmith", "credentials.json");
30
+ };
31
+
32
+ export const readCredentials = (path = credentialsPath()) => {
33
+ let raw;
34
+ try {
35
+ raw = readFileSync(path, "utf8");
36
+ } catch (error) {
37
+ if (error.code === "ENOENT") return null;
38
+ throw error;
39
+ }
40
+ try {
41
+ const parsed = JSON.parse(raw);
42
+ return parsed && typeof parsed.refresh_token === "string" && parsed.refresh_token ? parsed : null;
43
+ } catch {
44
+ throw new Error(`Stored credentials at ${path} are not valid JSON. Run activitysmith auth logout, then sign in again.`);
45
+ }
46
+ };
47
+
48
+ // Written to a temporary file and renamed into place, so a parallel command never reads half a file.
49
+ export const writeCredentials = (credentials, path = credentialsPath()) => {
50
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
51
+ const temporary = `${path}.${process.pid}.tmp`;
52
+ writeFileSync(temporary, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 0o600 });
53
+ chmodSync(temporary, 0o600);
54
+ renameSync(temporary, path);
55
+ };
56
+
57
+ export const deleteCredentials = (path = credentialsPath()) => {
58
+ rmSync(path, { force: true });
59
+ };
60
+
61
+ const base64Url = (buffer) => buffer.toString("base64url");
62
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
63
+
64
+ export const createPkcePair = () => {
65
+ const verifier = base64Url(randomBytes(32));
66
+ const challenge = base64Url(createHash("sha256").update(verifier).digest());
67
+ return { verifier, challenge };
68
+ };
69
+
70
+ const readJsonResponse = async (response, label) => {
71
+ const text = await response.text();
72
+ let body = null;
73
+ try {
74
+ body = text ? JSON.parse(text) : null;
75
+ } catch {
76
+ // Fall through with the raw text for the error message.
77
+ }
78
+ if (!response.ok) {
79
+ const detail = body?.error_description || body?.error || text || response.statusText;
80
+ const error = new Error(`${label} failed (${response.status}): ${detail}`);
81
+ error.oauthError = body?.error;
82
+ throw error;
83
+ }
84
+ return body;
85
+ };
86
+
87
+ export const discoverOAuthServer = async ({ issuer, fetchImpl }) => {
88
+ const response = await fetchImpl(`${issuer}/.well-known/oauth-authorization-server`);
89
+ const metadata = await readJsonResponse(response, "OAuth discovery");
90
+ for (const field of ["authorization_endpoint", "token_endpoint"]) {
91
+ if (typeof metadata?.[field] !== "string") {
92
+ throw new Error(`OAuth discovery response is missing ${field}`);
93
+ }
94
+ }
95
+ return metadata;
96
+ };
97
+
98
+ export const buildAuthorizeUrl = ({ authorizationEndpoint, redirectUri, challenge, state, resource }) => {
99
+ const url = new URL(authorizationEndpoint);
100
+ url.search = new URLSearchParams({
101
+ response_type: "code",
102
+ client_id: CLIENT_ID,
103
+ redirect_uri: redirectUri,
104
+ scope: LOGIN_SCOPES,
105
+ state,
106
+ code_challenge: challenge,
107
+ code_challenge_method: "S256",
108
+ resource,
109
+ }).toString();
110
+ return url.toString();
111
+ };
112
+
113
+ const requestToken = async ({ tokenEndpoint, fetchImpl, params }) => {
114
+ const response = await fetchImpl(tokenEndpoint, {
115
+ method: "POST",
116
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
117
+ body: new URLSearchParams(params).toString(),
118
+ });
119
+ const token = await readJsonResponse(response, "Token request");
120
+ if (typeof token?.access_token !== "string" || typeof token?.refresh_token !== "string") {
121
+ throw new Error("Token response did not include an access token and a refresh token");
122
+ }
123
+ return token;
124
+ };
125
+
126
+ // RFC 7009. Best effort: if the server cannot be reached, the token expires on its own.
127
+ const revokeRefreshToken = async ({ revocationEndpoint, fetchImpl, clientId, refreshToken }) => {
128
+ if (!revocationEndpoint || !refreshToken || !clientId) return false;
129
+ try {
130
+ const response = await fetchImpl(revocationEndpoint, {
131
+ method: "POST",
132
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
133
+ body: new URLSearchParams({ token: refreshToken, token_type_hint: "refresh_token", client_id: clientId }).toString(),
134
+ });
135
+ return response.ok;
136
+ } catch {
137
+ return false;
138
+ }
139
+ };
140
+
141
+ const tokenCredentials = (token, now) => ({
142
+ access_token: token.access_token,
143
+ access_token_expires_at: new Date(now + Number(token.expires_in || 3600) * 1000).toISOString(),
144
+ refresh_token: token.refresh_token,
145
+ scope: token.scope ?? LOGIN_SCOPES,
146
+ });
147
+
148
+ const callbackPage = (title, message) => `<!doctype html>
149
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
150
+ <title>${title}</title>
151
+ <style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#000;color:#fff;font:16px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}main{max-width:28rem;padding:1.5rem;text-align:center}p{color:#a1a1aa}</style>
152
+ </head><body><main><h1>${title}</h1><p>${message}</p></main></body></html>`;
153
+
154
+ const parseCallback = (url, expectedState) => {
155
+ const params = url.searchParams;
156
+ if (params.get("state") !== expectedState) {
157
+ return { error: new Error("The sign-in response did not match this login attempt. Run activitysmith auth login again.") };
158
+ }
159
+ const oauthError = params.get("error");
160
+ if (oauthError) {
161
+ const message = oauthError === "access_denied"
162
+ ? "Sign-in was cancelled in the browser."
163
+ : `Sign-in failed: ${params.get("error_description") || oauthError}`;
164
+ return { error: new Error(message) };
165
+ }
166
+ const code = params.get("code");
167
+ if (!code) return { error: new Error("The sign-in response did not include an authorization code.") };
168
+ return { code };
169
+ };
170
+
171
+ // Listens on 127.0.0.1 for the OAuth redirect. Where the browser runs on another machine,
172
+ // the user can paste the address it ends up on instead (see promptForPastedCallback).
173
+ const startCallbackServer = async ({ state }) => {
174
+ let settle;
175
+ const result = new Promise((resolve) => {
176
+ settle = resolve;
177
+ });
178
+ const server = createServer((req, res) => {
179
+ const url = new URL(req.url, "http://127.0.0.1");
180
+ if (url.pathname !== "/callback") {
181
+ res.writeHead(404, { "Content-Type": "text/plain" }).end("Not found");
182
+ return;
183
+ }
184
+ const outcome = parseCallback(url, state);
185
+ const [title, message] = outcome.error
186
+ ? ["Sign-in failed", `${outcome.error.message} You can close this tab.`]
187
+ : ["You're signed in", "The ActivitySmith CLI is ready. You can close this tab and return to your terminal."];
188
+ res.writeHead(outcome.error ? 400 : 200, { "Content-Type": "text/html; charset=utf-8" }).end(callbackPage(title, message));
189
+ settle(outcome);
190
+ });
191
+ await new Promise((resolve, reject) => {
192
+ server.once("error", reject);
193
+ server.listen(0, "127.0.0.1", resolve);
194
+ });
195
+ return {
196
+ redirectUri: `http://127.0.0.1:${server.address().port}/callback`,
197
+ result,
198
+ settle,
199
+ close: () => server.close(),
200
+ };
201
+ };
202
+
203
+ const promptForPastedCallback = ({ input, state, settle }) => {
204
+ const rl = createInterface({ input, terminal: false });
205
+ rl.on("line", (line) => {
206
+ const trimmed = line.trim();
207
+ if (!trimmed) return;
208
+ let url;
209
+ try {
210
+ url = new URL(trimmed);
211
+ } catch {
212
+ return;
213
+ }
214
+ if (url.searchParams.has("code") || url.searchParams.has("error")) settle(parseCallback(url, state));
215
+ });
216
+ return () => rl.close();
217
+ };
218
+
219
+ export const openBrowser = (url) =>
220
+ new Promise((resolve) => {
221
+ const [command, args] =
222
+ process.platform === "darwin"
223
+ ? ["open", [url]]
224
+ : process.platform === "win32"
225
+ ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
226
+ : ["xdg-open", [url]];
227
+ if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
228
+ resolve(false);
229
+ return;
230
+ }
231
+ try {
232
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
233
+ child.once("error", () => resolve(false));
234
+ child.once("spawn", () => {
235
+ child.unref();
236
+ resolve(true);
237
+ });
238
+ } catch {
239
+ resolve(false);
240
+ }
241
+ });
242
+
243
+ /**
244
+ * Signs in through the browser and saves the OAuth tokens. A previous sign-in on this machine is
245
+ * revoked once the new one is saved, so repeated logins do not pile up connections.
246
+ */
247
+ export const login = async ({
248
+ issuer = DEFAULT_ISSUER,
249
+ resource = DEFAULT_API_RESOURCE,
250
+ path = credentialsPath(),
251
+ fetchImpl = globalThis.fetch,
252
+ launchBrowser = openBrowser,
253
+ noBrowser = false,
254
+ input = process.stdin,
255
+ log = (line) => console.error(line),
256
+ now = Date.now,
257
+ timeoutMs = LOGIN_TIMEOUT_MS,
258
+ } = {}) => {
259
+ let previous = null;
260
+ try {
261
+ previous = readCredentials(path);
262
+ } catch {
263
+ // An unreadable file is replaced by this login.
264
+ }
265
+ const metadata = await discoverOAuthServer({ issuer, fetchImpl });
266
+ const { verifier, challenge } = createPkcePair();
267
+ const state = base64Url(randomBytes(16));
268
+ const callback = await startCallbackServer({ state });
269
+ const stopPrompt = input?.isTTY ? promptForPastedCallback({ input, state, settle: callback.settle }) : () => {};
270
+ let timer;
271
+ try {
272
+ const authorizeUrl = buildAuthorizeUrl({
273
+ authorizationEndpoint: metadata.authorization_endpoint,
274
+ redirectUri: callback.redirectUri,
275
+ challenge,
276
+ state,
277
+ resource,
278
+ });
279
+ const opened = noBrowser ? false : await launchBrowser(authorizeUrl);
280
+ log(opened ? "Opened your browser to sign in to ActivitySmith." : "Open this URL in a browser to sign in to ActivitySmith:");
281
+ log(opened ? `If it did not open, visit: ${authorizeUrl}` : authorizeUrl);
282
+ if (input?.isTTY) {
283
+ log("If the browser is on another machine, paste the address it lands on after you approve.");
284
+ }
285
+ log("Waiting for approval...");
286
+
287
+ const outcome = await Promise.race([
288
+ callback.result,
289
+ new Promise((_, reject) => {
290
+ timer = setTimeout(() => reject(new Error("Timed out waiting for browser sign-in. Run activitysmith auth login again.")), timeoutMs);
291
+ }),
292
+ ]);
293
+ if (outcome.error) throw outcome.error;
294
+
295
+ const token = await requestToken({
296
+ tokenEndpoint: metadata.token_endpoint,
297
+ fetchImpl,
298
+ params: {
299
+ grant_type: "authorization_code",
300
+ code: outcome.code,
301
+ client_id: CLIENT_ID,
302
+ redirect_uri: callback.redirectUri,
303
+ code_verifier: verifier,
304
+ resource,
305
+ },
306
+ });
307
+
308
+ const credentials = {
309
+ client_id: CLIENT_ID,
310
+ issuer,
311
+ resource,
312
+ token_endpoint: metadata.token_endpoint,
313
+ revocation_endpoint: metadata.revocation_endpoint ?? null,
314
+ ...tokenCredentials(token, now()),
315
+ signed_in_at: new Date(now()).toISOString(),
316
+ };
317
+ writeCredentials(credentials, path);
318
+
319
+ if (previous?.refresh_token && previous.refresh_token !== credentials.refresh_token) {
320
+ await revokeRefreshToken({
321
+ revocationEndpoint: previous.revocation_endpoint ?? metadata.revocation_endpoint,
322
+ fetchImpl,
323
+ clientId: previous.client_id,
324
+ refreshToken: previous.refresh_token,
325
+ });
326
+ }
327
+
328
+ return { credentials };
329
+ } finally {
330
+ clearTimeout(timer);
331
+ stopPrompt();
332
+ callback.close();
333
+ }
334
+ };
335
+
336
+ // Several CLI commands can run at once, for example from a coding agent. Refreshing rotates the
337
+ // refresh token, so only one process may refresh at a time; the others wait and reuse its result.
338
+ const acquireLock = async (lockPath) => {
339
+ mkdirSync(dirname(lockPath), { recursive: true, mode: 0o700 });
340
+ const deadline = Date.now() + LOCK_WAIT_MS;
341
+ for (;;) {
342
+ try {
343
+ closeSync(openSync(lockPath, "wx", 0o600));
344
+ return () => rmSync(lockPath, { force: true });
345
+ } catch (error) {
346
+ if (error.code !== "EEXIST") throw error;
347
+ }
348
+ try {
349
+ if (Date.now() - statSync(lockPath).mtimeMs > LOCK_STALE_MS) {
350
+ rmSync(lockPath, { force: true });
351
+ continue;
352
+ }
353
+ } catch {
354
+ continue;
355
+ }
356
+ if (Date.now() > deadline) {
357
+ throw new Error(`Timed out waiting for another ActivitySmith command to refresh the sign-in. Delete ${lockPath} if no other command is running.`);
358
+ }
359
+ await sleep(LOCK_POLL_MS);
360
+ }
361
+ };
362
+
363
+ const isFresh = (credentials, now) =>
364
+ typeof credentials?.access_token === "string" &&
365
+ Date.parse(credentials.access_token_expires_at) - ACCESS_TOKEN_REFRESH_MARGIN_MS > now;
366
+
367
+ /**
368
+ * Returns a valid access token from the saved sign-in, refreshing it when it is about to expire.
369
+ * Returns null when this machine is not signed in.
370
+ */
371
+ export const getAccessToken = async ({ path = credentialsPath(), fetchImpl = globalThis.fetch, now = Date.now } = {}) => {
372
+ const current = readCredentials(path);
373
+ if (!current) return null;
374
+ if (isFresh(current, now())) return current.access_token;
375
+
376
+ const release = await acquireLock(`${path}.lock`);
377
+ try {
378
+ // Another command may have refreshed while this one waited for the lock.
379
+ const latest = readCredentials(path);
380
+ if (!latest) return null;
381
+ if (isFresh(latest, now())) return latest.access_token;
382
+
383
+ let token;
384
+ try {
385
+ token = await requestToken({
386
+ tokenEndpoint: latest.token_endpoint,
387
+ fetchImpl,
388
+ params: {
389
+ grant_type: "refresh_token",
390
+ refresh_token: latest.refresh_token,
391
+ client_id: latest.client_id,
392
+ resource: latest.resource,
393
+ },
394
+ });
395
+ } catch (error) {
396
+ if (error.oauthError === "invalid_grant") {
397
+ throw new Error("Your ActivitySmith sign-in expired or was disconnected. Run activitysmith auth login to sign in again.");
398
+ }
399
+ throw error;
400
+ }
401
+ writeCredentials({ ...latest, ...tokenCredentials(token, now()) }, path);
402
+ return token.access_token;
403
+ } finally {
404
+ release();
405
+ }
406
+ };
407
+
408
+ /**
409
+ * Revokes the saved sign-in so the CLI leaves the account's AI Agents list, then removes the local
410
+ * credentials either way.
411
+ */
412
+ export const logout = async ({ path = credentialsPath(), fetchImpl = globalThis.fetch } = {}) => {
413
+ let credentials = null;
414
+ try {
415
+ credentials = readCredentials(path);
416
+ } catch {
417
+ deleteCredentials(path);
418
+ return { signedIn: true, revoked: false };
419
+ }
420
+ if (!credentials) return { signedIn: false, revoked: false };
421
+
422
+ let revocationEndpoint = credentials.revocation_endpoint;
423
+ if (!revocationEndpoint) {
424
+ try {
425
+ revocationEndpoint = (await discoverOAuthServer({ issuer: credentials.issuer || DEFAULT_ISSUER, fetchImpl })).revocation_endpoint;
426
+ } catch {
427
+ revocationEndpoint = null;
428
+ }
429
+ }
430
+ const revoked = await revokeRefreshToken({
431
+ revocationEndpoint,
432
+ fetchImpl,
433
+ clientId: credentials.client_id,
434
+ refreshToken: credentials.refresh_token,
435
+ });
436
+ deleteCredentials(path);
437
+ return { signedIn: true, revoked };
438
+ };
package/src/cli.js CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  import { Command, InvalidArgumentError, Option } from "commander";
4
4
  import { loadMetadata } from "./metadata.js";
5
+ import { credentialsPath, getAccessToken, login, logout, readCredentials } from "./auth.js";
5
6
  import ActivitySmith from "activitysmith";
6
7
  import { createRequire } from "module";
7
8
  import { readFile } from "fs/promises";
@@ -18,7 +19,7 @@ program
18
19
  .version(version)
19
20
  .option(
20
21
  "--api-key <key>",
21
- "ActivitySmith API key (defaults to ACTIVITYSMITH_API_KEY)"
22
+ "ActivitySmith API key (defaults to ACTIVITYSMITH_API_KEY, then the sign-in from auth login)"
22
23
  )
23
24
  .option("--json", "Output JSON");
24
25
 
@@ -267,8 +268,12 @@ const addLiveActivityActionOptions = (command) =>
267
268
  "Secondary Live Activity action JSON file path"
268
269
  );
269
270
 
270
- const getApiKey = (options) =>
271
- options.apiKey || process.env.ACTIVITYSMITH_API_KEY;
271
+ // Precedence: --api-key, then ACTIVITYSMITH_API_KEY, then the sign-in saved by `auth login`.
272
+ const credentialSource = (options) => {
273
+ if (options.apiKey) return "--api-key";
274
+ if (process.env.ACTIVITYSMITH_API_KEY) return "ACTIVITYSMITH_API_KEY";
275
+ return readCredentials() ? "auth login" : null;
276
+ };
272
277
 
273
278
  const createClient = (apiKey) =>
274
279
  new ActivitySmith({
@@ -1203,8 +1208,16 @@ const buildErrorDetails = async (error) => {
1203
1208
  return details;
1204
1209
  };
1205
1210
 
1211
+ // Set when a command authenticates with the browser sign-in rather than an API key.
1212
+ let usingSignIn = false;
1213
+
1206
1214
  const handleError = async (error, options) => {
1207
1215
  const details = await buildErrorDetails(error);
1216
+ // Disconnecting the CLI in the web app rejects its token at once, before it expires.
1217
+ if (usingSignIn && details.status === 401) {
1218
+ details.message =
1219
+ "Your ActivitySmith sign-in was disconnected or expired. Run activitysmith auth login to sign in again.";
1220
+ }
1208
1221
 
1209
1222
  if (options?.json) {
1210
1223
  console.log(JSON.stringify({ error: details }, null, 2));
@@ -1236,11 +1249,15 @@ const handleError = async (error, options) => {
1236
1249
  process.exit(1);
1237
1250
  };
1238
1251
 
1239
- const requireApiKey = (options) => {
1240
- const apiKey = getApiKey(options);
1252
+ // Returns the API key, or a current access token from the saved sign-in. The REST API accepts
1253
+ // either as a Bearer token.
1254
+ const requireApiKey = async (options) => {
1255
+ const configuredKey = options.apiKey || process.env.ACTIVITYSMITH_API_KEY;
1256
+ const apiKey = configuredKey || (await getAccessToken());
1257
+ usingSignIn = !configuredKey && Boolean(apiKey);
1241
1258
  if (!apiKey) {
1242
1259
  throw new Error(
1243
- "Missing API key. Provide --api-key or set ACTIVITYSMITH_API_KEY."
1260
+ "Missing API key. Run activitysmith auth login, provide --api-key, or set ACTIVITYSMITH_API_KEY."
1244
1261
  );
1245
1262
  }
1246
1263
  return apiKey;
@@ -1257,15 +1274,19 @@ const outputResult = (payload, options, lines) => {
1257
1274
 
1258
1275
  program
1259
1276
  .command("push")
1260
- .description("Send a push notification")
1277
+ .description("Send a push notification, or replace one you already sent")
1261
1278
  .requiredOption("--title <title>", "Push title")
1279
+ .option(
1280
+ "--replace <notification-id>",
1281
+ "Silently replace a sent push notification, using the notification ID from its send output"
1282
+ )
1262
1283
  .option("--message <message>", "Push message")
1263
1284
  .option("--subtitle <subtitle>", "Push subtitle")
1264
1285
  .option(
1265
1286
  "--media <url>",
1266
1287
  "HTTPS URL for image, audio, or video shown when the notification is expanded"
1267
1288
  )
1268
- .option("--icon <url>", "HTTPS image URL for the notification icon, such as an avatar or service logo")
1289
+ .option("--icon <url>", "HTTPS image URL for the notification icon, such as a logo or avatar")
1269
1290
  .addOption(
1270
1291
  new Option("--interruption-level <level>", "Notification interruption level").choices([
1271
1292
  "passive",
@@ -1292,13 +1313,23 @@ program
1292
1313
  const globalOptions = program.opts();
1293
1314
 
1294
1315
  try {
1295
- const apiKey = requireApiKey(globalOptions);
1316
+ const apiKey = await requireApiKey(globalOptions);
1296
1317
  const client = createClient(apiKey);
1297
1318
  const actions = await loadPushActions(options);
1298
1319
  validatePushMediaOptions({
1299
1320
  media: options.media,
1300
1321
  actions,
1301
1322
  });
1323
+ if (options.replace !== undefined) {
1324
+ if (options.channels !== undefined || options.interruptionLevel !== undefined) {
1325
+ throw new Error(
1326
+ "--channels and --interruption-level cannot be combined with --replace. Replacements go to the original recipients and arrive silently."
1327
+ );
1328
+ }
1329
+ if (options.replace.trim() === "") {
1330
+ throw new Error("--replace requires the notification ID from the original push output.");
1331
+ }
1332
+ }
1302
1333
 
1303
1334
  const pushNotificationRequest = withTargetChannels(
1304
1335
  {
@@ -1325,18 +1356,24 @@ program
1325
1356
  options.channels
1326
1357
  );
1327
1358
 
1328
- const response = await client.notifications.sendPushNotification({
1329
- pushNotificationRequest,
1330
- });
1359
+ const isReplacement = options.replace !== undefined;
1360
+ const response = isReplacement
1361
+ ? await client.notifications.replace(options.replace.trim(), pushNotificationRequest)
1362
+ : await client.notifications.sendPushNotification({
1363
+ pushNotificationRequest,
1364
+ });
1365
+ const devicesNotified = response?.devices_notified ?? response?.devicesNotified;
1366
+ const notificationId = response?.notification_id ?? response?.notificationId;
1331
1367
 
1332
1368
  outputResult(response, globalOptions, [
1333
- "Push sent.",
1369
+ isReplacement ? "Push replaced." : "Push sent.",
1334
1370
  response?.success !== undefined
1335
1371
  ? `Success: ${response.success}`
1336
1372
  : null,
1337
- response?.devicesNotified !== undefined
1338
- ? `Devices notified: ${response.devicesNotified}`
1373
+ devicesNotified !== undefined
1374
+ ? `Devices notified: ${devicesNotified}`
1339
1375
  : null,
1376
+ notificationId ? `Notification ID: ${notificationId}` : null,
1340
1377
  ]);
1341
1378
  } catch (error) {
1342
1379
  await handleError(error, globalOptions);
@@ -1361,7 +1398,7 @@ program
1361
1398
  const globalOptions = program.opts();
1362
1399
 
1363
1400
  try {
1364
- const apiKey = requireApiKey(globalOptions);
1401
+ const apiKey = await requireApiKey(globalOptions);
1365
1402
  const client = createClient(apiKey);
1366
1403
  const response = await client.badgeCount(
1367
1404
  value,
@@ -1398,7 +1435,7 @@ metricsCommand
1398
1435
  const globalOptions = program.opts();
1399
1436
 
1400
1437
  try {
1401
- const apiKey = requireApiKey(globalOptions);
1438
+ const apiKey = await requireApiKey(globalOptions);
1402
1439
  const client = createClient(apiKey);
1403
1440
  const value = parseMetricValueArgument(rawValue);
1404
1441
  const response = await client.metrics.update(metricKey, value);
@@ -1417,6 +1454,10 @@ addLiveActivityActionOptions(addContentStateOptions(
1417
1454
  activityCommand
1418
1455
  .command("stream")
1419
1456
  .description("Send a stateless Live Activity stream update")
1457
+ .addHelpText(
1458
+ "after",
1459
+ "\niOS limits how often a Live Activity can update. Short bursts are fine, but avoid updating the same Live Activity more often than every couple of minutes for long periods.\n"
1460
+ )
1420
1461
  .argument("<stream-key>", "Stable stream key")
1421
1462
  .option(
1422
1463
  "--channels <channels>",
@@ -1438,7 +1479,7 @@ addLiveActivityActionOptions(addContentStateOptions(
1438
1479
  if (options.clearTags && options.tags !== undefined) {
1439
1480
  throw new Error("Use either --tags or --clear-tags, not both.");
1440
1481
  }
1441
- const apiKey = requireApiKey(globalOptions);
1482
+ const apiKey = await requireApiKey(globalOptions);
1442
1483
  const client = createClient(apiKey);
1443
1484
  const contentState = await loadContentState(options, "stream");
1444
1485
  const action = await loadLiveActivityAction(options);
@@ -1494,7 +1535,7 @@ addLiveActivityActionOptions(addContentStateOptions(
1494
1535
  const globalOptions = program.opts();
1495
1536
 
1496
1537
  try {
1497
- const apiKey = requireApiKey(globalOptions);
1538
+ const apiKey = await requireApiKey(globalOptions);
1498
1539
  const client = createClient(apiKey);
1499
1540
  const contentState = await loadContentState(options, "start");
1500
1541
  const action = await loadLiveActivityAction(options);
@@ -1542,7 +1583,7 @@ addLiveActivityActionOptions(addContentStateOptions(
1542
1583
  if (options.clearTags && options.tags !== undefined) {
1543
1584
  throw new Error("Use either --tags or --clear-tags, not both.");
1544
1585
  }
1545
- const apiKey = requireApiKey(globalOptions);
1586
+ const apiKey = await requireApiKey(globalOptions);
1546
1587
  const client = createClient(apiKey);
1547
1588
  const contentState = await loadContentState(options, "update");
1548
1589
  const action = await loadLiveActivityAction(options);
@@ -1583,7 +1624,7 @@ addLiveActivityActionOptions(addContentStateOptions(
1583
1624
  if (options.clearTags && options.tags !== undefined) {
1584
1625
  throw new Error("Use either --tags or --clear-tags, not both.");
1585
1626
  }
1586
- const apiKey = requireApiKey(globalOptions);
1627
+ const apiKey = await requireApiKey(globalOptions);
1587
1628
  const client = createClient(apiKey);
1588
1629
  const contentState = await loadContentState(options, "end");
1589
1630
  const action = await loadLiveActivityAction(options);
@@ -1625,7 +1666,7 @@ addLiveActivityActionOptions(addContentStateOptions(
1625
1666
  if (options.clearTags && options.tags !== undefined) throw new Error("Provide either --tags or --clear-tags, not both.");
1626
1667
  const tags = options.clearTags ? [] : options.tags;
1627
1668
  const metadata = await loadMetadata(options);
1628
- const apiKey = requireApiKey(globalOptions);
1669
+ const apiKey = await requireApiKey(globalOptions);
1629
1670
  const client = createClient(apiKey);
1630
1671
  const contentState = await loadOptionalContentState(options, "end");
1631
1672
  const action = await loadLiveActivityAction(options);
@@ -1661,5 +1702,88 @@ addLiveActivityActionOptions(addContentStateOptions(
1661
1702
  { includeAutoDismiss: true, includeAutoDismissSeconds: true }
1662
1703
  ));
1663
1704
 
1705
+ const authCommand = program
1706
+ .command("auth")
1707
+ .description("Sign in through the browser and manage the saved sign-in");
1708
+
1709
+ authCommand
1710
+ .command("login")
1711
+ .description("Sign in through the browser so commands work without an API key")
1712
+ .option("--no-browser", "Print the sign-in URL instead of opening a browser")
1713
+ .action(async (options) => {
1714
+ const globalOptions = program.opts();
1715
+
1716
+ try {
1717
+ await login({ noBrowser: options.browser === false });
1718
+ outputResult(
1719
+ { signed_in: true, credentials_path: credentialsPath() },
1720
+ globalOptions,
1721
+ [
1722
+ "Signed in to ActivitySmith.",
1723
+ `Saved to: ${credentialsPath()}`,
1724
+ process.env.ACTIVITYSMITH_API_KEY
1725
+ ? "Note: ACTIVITYSMITH_API_KEY is set and takes precedence over the sign-in."
1726
+ : null,
1727
+ ]
1728
+ );
1729
+ } catch (error) {
1730
+ await handleError(error, globalOptions);
1731
+ }
1732
+ });
1733
+
1734
+ authCommand
1735
+ .command("logout")
1736
+ .description("Sign out and disconnect the CLI from your account")
1737
+ .action(async () => {
1738
+ const globalOptions = program.opts();
1739
+
1740
+ try {
1741
+ const result = await logout();
1742
+ const lines = !result.signedIn
1743
+ ? ["Not signed in."]
1744
+ : result.revoked
1745
+ ? ["Signed out. The CLI is disconnected from your ActivitySmith account."]
1746
+ : [
1747
+ "Signed out on this machine.",
1748
+ 'If "ActivitySmith CLI" is still listed under AI Agents at https://activitysmith.com/app/ai-agents, select Disconnect there.',
1749
+ ];
1750
+ outputResult({ signed_out: result.signedIn, disconnected: result.revoked }, globalOptions, lines);
1751
+ } catch (error) {
1752
+ await handleError(error, globalOptions);
1753
+ }
1754
+ });
1755
+
1756
+ authCommand
1757
+ .command("status")
1758
+ .description("Show how the CLI authenticates, without printing secrets")
1759
+ .action(async () => {
1760
+ const globalOptions = program.opts();
1761
+
1762
+ try {
1763
+ const source = credentialSource(globalOptions);
1764
+ const stored = readCredentials();
1765
+ const payload = {
1766
+ signed_in: Boolean(stored),
1767
+ auth_source: source,
1768
+ signed_in_at: stored?.signed_in_at ?? null,
1769
+ credentials_path: credentialsPath(),
1770
+ };
1771
+ const sourceLine =
1772
+ source === "auth login"
1773
+ ? "Using the browser sign-in from activitysmith auth login."
1774
+ : source
1775
+ ? `Using the API key from ${source}.`
1776
+ : "Not signed in. Run activitysmith auth login.";
1777
+ outputResult(payload, globalOptions, [
1778
+ sourceLine,
1779
+ stored && source !== "auth login" ? "A browser sign-in is also saved, but the API key takes precedence." : null,
1780
+ stored ? `Signed in: ${stored.signed_in_at}` : null,
1781
+ stored ? `Saved to: ${credentialsPath()}` : null,
1782
+ ]);
1783
+ } catch (error) {
1784
+ await handleError(error, globalOptions);
1785
+ }
1786
+ });
1787
+
1664
1788
  program.showHelpAfterError(true);
1665
1789
  program.parseAsync(process.argv);