activitysmith-cli 1.14.0 → 1.16.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 +94 -7
  2. package/package.json +1 -1
  3. package/src/auth.js +444 -0
  4. package/src/cli.js +249 -14
package/README.md CHANGED
@@ -24,10 +24,57 @@ For example, a Codex agent can work on your computer, send a Push Notification w
24
24
 
25
25
  ## Quickstart
26
26
 
27
- 1. [Create an API key](https://activitysmith.com/app/keys)
28
- 2. Authenticate with `ACTIVITYSMITH_API_KEY` or pass `--api-key` per command.
27
+ 1. Run `activitysmith auth login` and approve access in your browser.
28
+ 2. Run `activitysmith devices list` to check that your iPhone is paired.
29
29
  3. Run `activitysmith --help` to inspect available commands.
30
30
 
31
+ ```bash
32
+ activitysmith auth login
33
+
34
+ activitysmith devices list
35
+
36
+ activitysmith push --title "Hello"
37
+ ```
38
+
39
+ ## Authentication
40
+
41
+ ### Sign in with your browser
42
+
43
+ `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.
44
+
45
+ ```bash
46
+ activitysmith auth login
47
+ ```
48
+
49
+ 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.
50
+
51
+ ```bash
52
+ activitysmith auth login --no-browser
53
+ ```
54
+
55
+ The CLI appears under AI Agents in the ActivitySmith web app. Select **Disconnect** there to stop it immediately on every machine.
56
+
57
+ Check how the CLI authenticates. Secrets are never printed:
58
+
59
+ ```bash
60
+ activitysmith auth status
61
+ ```
62
+
63
+ Sign out to disconnect the CLI and remove the saved sign-in from this machine:
64
+
65
+ ```bash
66
+ activitysmith auth logout
67
+ ```
68
+
69
+ Set `ACTIVITYSMITH_CONFIG_DIR` to save the sign-in in a different directory.
70
+
71
+ ### Use an API key
72
+
73
+ 1. [Create an API key](https://activitysmith.com/app/keys)
74
+ 2. Set `ACTIVITYSMITH_API_KEY` or pass `--api-key` per command.
75
+
76
+ 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`.
77
+
31
78
  Use the environment variable when you want the cleanest shell scripts:
32
79
 
33
80
  ```bash
@@ -42,6 +89,44 @@ Or pass the key directly:
42
89
  activitysmith --api-key "YOUR-API-KEY" push --title "Hello"
43
90
  ```
44
91
 
92
+ ### Create an API key from the CLI
93
+
94
+ Create an API key for CI, servers, and scripts without opening the web app. The command uses the browser sign-in. The first time, it opens your browser so you can approve API key access.
95
+
96
+ ```bash
97
+ activitysmith keys create --name "GitHub Actions"
98
+ ```
99
+
100
+ The key is shown only once. Add `--raw` to print only the key, then pipe it straight into a secret store. The key never appears in your terminal:
101
+
102
+ ```bash
103
+ activitysmith keys create --name "GitHub Actions" --raw | gh secret set ACTIVITYSMITH_API_KEY
104
+ ```
105
+
106
+ Add `--channels` to limit the key to some Channels:
107
+
108
+ ```bash
109
+ activitysmith keys create --name "Ops alerts" --channels ops,alerts
110
+ ```
111
+
112
+ An API key cannot create another key. This command always uses the browser sign-in, even when `ACTIVITYSMITH_API_KEY` is set.
113
+
114
+ ## Paired Devices
115
+
116
+ List the iPhones and iPads paired to your account. Active devices come first:
117
+
118
+ ```bash
119
+ activitysmith devices list
120
+ ```
121
+
122
+ If no device is paired, the command prints the App Store link. Install ActivitySmith on your iPhone, sign in with the same account, and allow notifications.
123
+
124
+ Add `--include-inactive` to also list devices that can no longer receive deliveries:
125
+
126
+ ```bash
127
+ activitysmith devices list --include-inactive
128
+ ```
129
+
45
130
  ## Push Notifications
46
131
 
47
132
  ### Send a Push Notification
@@ -61,13 +146,13 @@ activitysmith push \
61
146
 
62
147
  ![Push Notifications with custom icons](https://cdn.activitysmith.com/features/push-notifications-with-custom-icons.png)
63
148
 
64
- Set `--icon` to a publicly accessible HTTPS image URL to show a logo or avatar alongside a smaller ActivitySmith app icon. With a custom icon, iOS may omit the subtitle from the notification.
149
+ 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
150
 
66
151
  ```bash
67
152
  activitysmith push \
68
153
  --title 'MRR just crossed $10,000 🎉' \
69
154
  --message "Up 18% this month from 31 new subscriptions." \
70
- --icon "https://cdn.activitysmith.com/integrations/icons/stripe.png"
155
+ --icon "https://example.com/icons/stripe.png"
71
156
  ```
72
157
 
73
158
  ### Rich Push Notifications with Media
@@ -585,12 +670,14 @@ String metric values work too.
585
670
  activitysmith metrics update prod.status healthy
586
671
  ```
587
672
 
588
- ## App Icon Badge Count
673
+ ## App Icon Badge
589
674
 
590
- ![ActivitySmith app icon with an App Icon Badge Count](https://cdn.activitysmith.com/features/badge-count.png)
675
+ ![ActivitySmith app icon with an App Icon Badge](https://cdn.activitysmith.com/features/badge-count.png)
591
676
 
592
677
  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.
593
678
 
679
+ App Icon Badge requires Push Notifications enabled. On your iPhone, open Settings > ActivitySmith > Notifications and turn on Allow Notifications.
680
+
594
681
  ### Set or update the badge value
595
682
 
596
683
  ```bash
@@ -657,7 +744,7 @@ activitysmith activity stream customer-import \
657
744
 
658
745
  ## Channels
659
746
 
660
- 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.
747
+ 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.
661
748
 
662
749
  ```bash
663
750
  activitysmith push \
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "activitysmith-cli",
3
- "version": "1.14.0",
3
+ "version": "1.16.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",
package/src/auth.js ADDED
@@ -0,0 +1,444 @@
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
+ // Asked for only by `activitysmith keys create`, which signs in again so the user approves it in the browser.
20
+ export const API_KEYS_SCOPE = "api_keys:write";
21
+
22
+ export const hasScope = (credentials, scope) => String(credentials?.scope ?? "").split(/\s+/).includes(scope);
23
+ const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
24
+ // Refresh a little early so a token does not expire mid-request.
25
+ const ACCESS_TOKEN_REFRESH_MARGIN_MS = 60 * 1000;
26
+ const LOCK_WAIT_MS = 15 * 1000;
27
+ const LOCK_STALE_MS = 30 * 1000;
28
+ const LOCK_POLL_MS = 50;
29
+
30
+ export const credentialsPath = (env = process.env) => {
31
+ if (env.ACTIVITYSMITH_CONFIG_DIR) return join(env.ACTIVITYSMITH_CONFIG_DIR, "credentials.json");
32
+ const configHome = env.XDG_CONFIG_HOME || join(homedir(), ".config");
33
+ return join(configHome, "activitysmith", "credentials.json");
34
+ };
35
+
36
+ export const readCredentials = (path = credentialsPath()) => {
37
+ let raw;
38
+ try {
39
+ raw = readFileSync(path, "utf8");
40
+ } catch (error) {
41
+ if (error.code === "ENOENT") return null;
42
+ throw error;
43
+ }
44
+ try {
45
+ const parsed = JSON.parse(raw);
46
+ return parsed && typeof parsed.refresh_token === "string" && parsed.refresh_token ? parsed : null;
47
+ } catch {
48
+ throw new Error(`Stored credentials at ${path} are not valid JSON. Run activitysmith auth logout, then sign in again.`);
49
+ }
50
+ };
51
+
52
+ // Written to a temporary file and renamed into place, so a parallel command never reads half a file.
53
+ export const writeCredentials = (credentials, path = credentialsPath()) => {
54
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
55
+ const temporary = `${path}.${process.pid}.tmp`;
56
+ writeFileSync(temporary, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 0o600 });
57
+ chmodSync(temporary, 0o600);
58
+ renameSync(temporary, path);
59
+ };
60
+
61
+ export const deleteCredentials = (path = credentialsPath()) => {
62
+ rmSync(path, { force: true });
63
+ };
64
+
65
+ const base64Url = (buffer) => buffer.toString("base64url");
66
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
67
+
68
+ export const createPkcePair = () => {
69
+ const verifier = base64Url(randomBytes(32));
70
+ const challenge = base64Url(createHash("sha256").update(verifier).digest());
71
+ return { verifier, challenge };
72
+ };
73
+
74
+ const readJsonResponse = async (response, label) => {
75
+ const text = await response.text();
76
+ let body = null;
77
+ try {
78
+ body = text ? JSON.parse(text) : null;
79
+ } catch {
80
+ // Fall through with the raw text for the error message.
81
+ }
82
+ if (!response.ok) {
83
+ const detail = body?.error_description || body?.error || text || response.statusText;
84
+ const error = new Error(`${label} failed (${response.status}): ${detail}`);
85
+ error.oauthError = body?.error;
86
+ throw error;
87
+ }
88
+ return body;
89
+ };
90
+
91
+ export const discoverOAuthServer = async ({ issuer, fetchImpl }) => {
92
+ const response = await fetchImpl(`${issuer}/.well-known/oauth-authorization-server`);
93
+ const metadata = await readJsonResponse(response, "OAuth discovery");
94
+ for (const field of ["authorization_endpoint", "token_endpoint"]) {
95
+ if (typeof metadata?.[field] !== "string") {
96
+ throw new Error(`OAuth discovery response is missing ${field}`);
97
+ }
98
+ }
99
+ return metadata;
100
+ };
101
+
102
+ export const buildAuthorizeUrl = ({ authorizationEndpoint, redirectUri, challenge, state, resource, scope = LOGIN_SCOPES }) => {
103
+ const url = new URL(authorizationEndpoint);
104
+ url.search = new URLSearchParams({
105
+ response_type: "code",
106
+ client_id: CLIENT_ID,
107
+ redirect_uri: redirectUri,
108
+ scope,
109
+ state,
110
+ code_challenge: challenge,
111
+ code_challenge_method: "S256",
112
+ resource,
113
+ }).toString();
114
+ return url.toString();
115
+ };
116
+
117
+ const requestToken = async ({ tokenEndpoint, fetchImpl, params }) => {
118
+ const response = await fetchImpl(tokenEndpoint, {
119
+ method: "POST",
120
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
121
+ body: new URLSearchParams(params).toString(),
122
+ });
123
+ const token = await readJsonResponse(response, "Token request");
124
+ if (typeof token?.access_token !== "string" || typeof token?.refresh_token !== "string") {
125
+ throw new Error("Token response did not include an access token and a refresh token");
126
+ }
127
+ return token;
128
+ };
129
+
130
+ // RFC 7009. Best effort: if the server cannot be reached, the token expires on its own.
131
+ const revokeRefreshToken = async ({ revocationEndpoint, fetchImpl, clientId, refreshToken }) => {
132
+ if (!revocationEndpoint || !refreshToken || !clientId) return false;
133
+ try {
134
+ const response = await fetchImpl(revocationEndpoint, {
135
+ method: "POST",
136
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
137
+ body: new URLSearchParams({ token: refreshToken, token_type_hint: "refresh_token", client_id: clientId }).toString(),
138
+ });
139
+ return response.ok;
140
+ } catch {
141
+ return false;
142
+ }
143
+ };
144
+
145
+ const tokenCredentials = (token, now) => ({
146
+ access_token: token.access_token,
147
+ access_token_expires_at: new Date(now + Number(token.expires_in || 3600) * 1000).toISOString(),
148
+ refresh_token: token.refresh_token,
149
+ scope: token.scope ?? LOGIN_SCOPES,
150
+ });
151
+
152
+ const callbackPage = (title, message) => `<!doctype html>
153
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
154
+ <title>${title}</title>
155
+ <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>
156
+ </head><body><main><h1>${title}</h1><p>${message}</p></main></body></html>`;
157
+
158
+ const parseCallback = (url, expectedState) => {
159
+ const params = url.searchParams;
160
+ if (params.get("state") !== expectedState) {
161
+ return { error: new Error("The sign-in response did not match this login attempt. Run activitysmith auth login again.") };
162
+ }
163
+ const oauthError = params.get("error");
164
+ if (oauthError) {
165
+ const message = oauthError === "access_denied"
166
+ ? "Sign-in was cancelled in the browser."
167
+ : `Sign-in failed: ${params.get("error_description") || oauthError}`;
168
+ return { error: new Error(message) };
169
+ }
170
+ const code = params.get("code");
171
+ if (!code) return { error: new Error("The sign-in response did not include an authorization code.") };
172
+ return { code };
173
+ };
174
+
175
+ // Listens on 127.0.0.1 for the OAuth redirect. Where the browser runs on another machine,
176
+ // the user can paste the address it ends up on instead (see promptForPastedCallback).
177
+ const startCallbackServer = async ({ state }) => {
178
+ let settle;
179
+ const result = new Promise((resolve) => {
180
+ settle = resolve;
181
+ });
182
+ const server = createServer((req, res) => {
183
+ const url = new URL(req.url, "http://127.0.0.1");
184
+ if (url.pathname !== "/callback") {
185
+ res.writeHead(404, { "Content-Type": "text/plain" }).end("Not found");
186
+ return;
187
+ }
188
+ const outcome = parseCallback(url, state);
189
+ const [title, message] = outcome.error
190
+ ? ["Sign-in failed", `${outcome.error.message} You can close this tab.`]
191
+ : ["You're signed in", "The ActivitySmith CLI is ready. You can close this tab and return to your terminal."];
192
+ res.writeHead(outcome.error ? 400 : 200, { "Content-Type": "text/html; charset=utf-8" }).end(callbackPage(title, message));
193
+ settle(outcome);
194
+ });
195
+ await new Promise((resolve, reject) => {
196
+ server.once("error", reject);
197
+ server.listen(0, "127.0.0.1", resolve);
198
+ });
199
+ return {
200
+ redirectUri: `http://127.0.0.1:${server.address().port}/callback`,
201
+ result,
202
+ settle,
203
+ close: () => server.close(),
204
+ };
205
+ };
206
+
207
+ const promptForPastedCallback = ({ input, state, settle }) => {
208
+ const rl = createInterface({ input, terminal: false });
209
+ rl.on("line", (line) => {
210
+ const trimmed = line.trim();
211
+ if (!trimmed) return;
212
+ let url;
213
+ try {
214
+ url = new URL(trimmed);
215
+ } catch {
216
+ return;
217
+ }
218
+ if (url.searchParams.has("code") || url.searchParams.has("error")) settle(parseCallback(url, state));
219
+ });
220
+ return () => rl.close();
221
+ };
222
+
223
+ export const openBrowser = (url) =>
224
+ new Promise((resolve) => {
225
+ const [command, args] =
226
+ process.platform === "darwin"
227
+ ? ["open", [url]]
228
+ : process.platform === "win32"
229
+ ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
230
+ : ["xdg-open", [url]];
231
+ if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
232
+ resolve(false);
233
+ return;
234
+ }
235
+ try {
236
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
237
+ child.once("error", () => resolve(false));
238
+ child.once("spawn", () => {
239
+ child.unref();
240
+ resolve(true);
241
+ });
242
+ } catch {
243
+ resolve(false);
244
+ }
245
+ });
246
+
247
+ /**
248
+ * Signs in through the browser and saves the OAuth tokens. A previous sign-in on this machine is
249
+ * revoked once the new one is saved, so repeated logins do not pile up connections.
250
+ */
251
+ export const login = async ({
252
+ issuer = DEFAULT_ISSUER,
253
+ resource = DEFAULT_API_RESOURCE,
254
+ path = credentialsPath(),
255
+ fetchImpl = globalThis.fetch,
256
+ launchBrowser = openBrowser,
257
+ noBrowser = false,
258
+ input = process.stdin,
259
+ log = (line) => console.error(line),
260
+ now = Date.now,
261
+ timeoutMs = LOGIN_TIMEOUT_MS,
262
+ scope = LOGIN_SCOPES,
263
+ } = {}) => {
264
+ let previous = null;
265
+ try {
266
+ previous = readCredentials(path);
267
+ } catch {
268
+ // An unreadable file is replaced by this login.
269
+ }
270
+ const metadata = await discoverOAuthServer({ issuer, fetchImpl });
271
+ const { verifier, challenge } = createPkcePair();
272
+ const state = base64Url(randomBytes(16));
273
+ const callback = await startCallbackServer({ state });
274
+ const stopPrompt = input?.isTTY ? promptForPastedCallback({ input, state, settle: callback.settle }) : () => {};
275
+ let timer;
276
+ try {
277
+ const authorizeUrl = buildAuthorizeUrl({
278
+ authorizationEndpoint: metadata.authorization_endpoint,
279
+ redirectUri: callback.redirectUri,
280
+ challenge,
281
+ state,
282
+ resource,
283
+ scope,
284
+ });
285
+ const opened = noBrowser ? false : await launchBrowser(authorizeUrl);
286
+ log(opened ? "Opened your browser to sign in to ActivitySmith." : "Open this URL in a browser to sign in to ActivitySmith:");
287
+ log(opened ? `If it did not open, visit: ${authorizeUrl}` : authorizeUrl);
288
+ if (input?.isTTY) {
289
+ log("If the browser is on another machine, paste the address it lands on after you approve.");
290
+ }
291
+ log("Waiting for approval...");
292
+
293
+ const outcome = await Promise.race([
294
+ callback.result,
295
+ new Promise((_, reject) => {
296
+ timer = setTimeout(() => reject(new Error("Timed out waiting for browser sign-in. Run activitysmith auth login again.")), timeoutMs);
297
+ }),
298
+ ]);
299
+ if (outcome.error) throw outcome.error;
300
+
301
+ const token = await requestToken({
302
+ tokenEndpoint: metadata.token_endpoint,
303
+ fetchImpl,
304
+ params: {
305
+ grant_type: "authorization_code",
306
+ code: outcome.code,
307
+ client_id: CLIENT_ID,
308
+ redirect_uri: callback.redirectUri,
309
+ code_verifier: verifier,
310
+ resource,
311
+ },
312
+ });
313
+
314
+ const credentials = {
315
+ client_id: CLIENT_ID,
316
+ issuer,
317
+ resource,
318
+ token_endpoint: metadata.token_endpoint,
319
+ revocation_endpoint: metadata.revocation_endpoint ?? null,
320
+ ...tokenCredentials(token, now()),
321
+ signed_in_at: new Date(now()).toISOString(),
322
+ };
323
+ writeCredentials(credentials, path);
324
+
325
+ if (previous?.refresh_token && previous.refresh_token !== credentials.refresh_token) {
326
+ await revokeRefreshToken({
327
+ revocationEndpoint: previous.revocation_endpoint ?? metadata.revocation_endpoint,
328
+ fetchImpl,
329
+ clientId: previous.client_id,
330
+ refreshToken: previous.refresh_token,
331
+ });
332
+ }
333
+
334
+ return { credentials };
335
+ } finally {
336
+ clearTimeout(timer);
337
+ stopPrompt();
338
+ callback.close();
339
+ }
340
+ };
341
+
342
+ // Several CLI commands can run at once, for example from a coding agent. Refreshing rotates the
343
+ // refresh token, so only one process may refresh at a time; the others wait and reuse its result.
344
+ const acquireLock = async (lockPath) => {
345
+ mkdirSync(dirname(lockPath), { recursive: true, mode: 0o700 });
346
+ const deadline = Date.now() + LOCK_WAIT_MS;
347
+ for (;;) {
348
+ try {
349
+ closeSync(openSync(lockPath, "wx", 0o600));
350
+ return () => rmSync(lockPath, { force: true });
351
+ } catch (error) {
352
+ if (error.code !== "EEXIST") throw error;
353
+ }
354
+ try {
355
+ if (Date.now() - statSync(lockPath).mtimeMs > LOCK_STALE_MS) {
356
+ rmSync(lockPath, { force: true });
357
+ continue;
358
+ }
359
+ } catch {
360
+ continue;
361
+ }
362
+ if (Date.now() > deadline) {
363
+ throw new Error(`Timed out waiting for another ActivitySmith command to refresh the sign-in. Delete ${lockPath} if no other command is running.`);
364
+ }
365
+ await sleep(LOCK_POLL_MS);
366
+ }
367
+ };
368
+
369
+ const isFresh = (credentials, now) =>
370
+ typeof credentials?.access_token === "string" &&
371
+ Date.parse(credentials.access_token_expires_at) - ACCESS_TOKEN_REFRESH_MARGIN_MS > now;
372
+
373
+ /**
374
+ * Returns a valid access token from the saved sign-in, refreshing it when it is about to expire.
375
+ * Returns null when this machine is not signed in.
376
+ */
377
+ export const getAccessToken = async ({ path = credentialsPath(), fetchImpl = globalThis.fetch, now = Date.now } = {}) => {
378
+ const current = readCredentials(path);
379
+ if (!current) return null;
380
+ if (isFresh(current, now())) return current.access_token;
381
+
382
+ const release = await acquireLock(`${path}.lock`);
383
+ try {
384
+ // Another command may have refreshed while this one waited for the lock.
385
+ const latest = readCredentials(path);
386
+ if (!latest) return null;
387
+ if (isFresh(latest, now())) return latest.access_token;
388
+
389
+ let token;
390
+ try {
391
+ token = await requestToken({
392
+ tokenEndpoint: latest.token_endpoint,
393
+ fetchImpl,
394
+ params: {
395
+ grant_type: "refresh_token",
396
+ refresh_token: latest.refresh_token,
397
+ client_id: latest.client_id,
398
+ resource: latest.resource,
399
+ },
400
+ });
401
+ } catch (error) {
402
+ if (error.oauthError === "invalid_grant") {
403
+ throw new Error("Your ActivitySmith sign-in expired or was disconnected. Run activitysmith auth login to sign in again.");
404
+ }
405
+ throw error;
406
+ }
407
+ writeCredentials({ ...latest, ...tokenCredentials(token, now()) }, path);
408
+ return token.access_token;
409
+ } finally {
410
+ release();
411
+ }
412
+ };
413
+
414
+ /**
415
+ * Revokes the saved sign-in so the CLI leaves the account's AI Agents list, then removes the local
416
+ * credentials either way.
417
+ */
418
+ export const logout = async ({ path = credentialsPath(), fetchImpl = globalThis.fetch } = {}) => {
419
+ let credentials = null;
420
+ try {
421
+ credentials = readCredentials(path);
422
+ } catch {
423
+ deleteCredentials(path);
424
+ return { signedIn: true, revoked: false };
425
+ }
426
+ if (!credentials) return { signedIn: false, revoked: false };
427
+
428
+ let revocationEndpoint = credentials.revocation_endpoint;
429
+ if (!revocationEndpoint) {
430
+ try {
431
+ revocationEndpoint = (await discoverOAuthServer({ issuer: credentials.issuer || DEFAULT_ISSUER, fetchImpl })).revocation_endpoint;
432
+ } catch {
433
+ revocationEndpoint = null;
434
+ }
435
+ }
436
+ const revoked = await revokeRefreshToken({
437
+ revocationEndpoint,
438
+ fetchImpl,
439
+ clientId: credentials.client_id,
440
+ refreshToken: credentials.refresh_token,
441
+ });
442
+ deleteCredentials(path);
443
+ return { signedIn: true, revoked };
444
+ };
package/src/cli.js CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  import { Command, InvalidArgumentError, Option } from "commander";
4
4
  import { loadMetadata } from "./metadata.js";
5
+ import {
6
+ API_KEYS_SCOPE,
7
+ DEFAULT_API_RESOURCE,
8
+ LOGIN_SCOPES,
9
+ credentialsPath,
10
+ getAccessToken,
11
+ hasScope,
12
+ login,
13
+ logout,
14
+ readCredentials,
15
+ } from "./auth.js";
5
16
  import ActivitySmith from "activitysmith";
6
17
  import { createRequire } from "module";
7
18
  import { readFile } from "fs/promises";
@@ -18,7 +29,7 @@ program
18
29
  .version(version)
19
30
  .option(
20
31
  "--api-key <key>",
21
- "ActivitySmith API key (defaults to ACTIVITYSMITH_API_KEY)"
32
+ "ActivitySmith API key (defaults to ACTIVITYSMITH_API_KEY, then the sign-in from auth login)"
22
33
  )
23
34
  .option("--json", "Output JSON");
24
35
 
@@ -267,8 +278,12 @@ const addLiveActivityActionOptions = (command) =>
267
278
  "Secondary Live Activity action JSON file path"
268
279
  );
269
280
 
270
- const getApiKey = (options) =>
271
- options.apiKey || process.env.ACTIVITYSMITH_API_KEY;
281
+ // Precedence: --api-key, then ACTIVITYSMITH_API_KEY, then the sign-in saved by `auth login`.
282
+ const credentialSource = (options) => {
283
+ if (options.apiKey) return "--api-key";
284
+ if (process.env.ACTIVITYSMITH_API_KEY) return "ACTIVITYSMITH_API_KEY";
285
+ return readCredentials() ? "auth login" : null;
286
+ };
272
287
 
273
288
  const createClient = (apiKey) =>
274
289
  new ActivitySmith({
@@ -1203,8 +1218,16 @@ const buildErrorDetails = async (error) => {
1203
1218
  return details;
1204
1219
  };
1205
1220
 
1221
+ // Set when a command authenticates with the browser sign-in rather than an API key.
1222
+ let usingSignIn = false;
1223
+
1206
1224
  const handleError = async (error, options) => {
1207
1225
  const details = await buildErrorDetails(error);
1226
+ // Disconnecting the CLI in the web app rejects its token at once, before it expires.
1227
+ if (usingSignIn && details.status === 401) {
1228
+ details.message =
1229
+ "Your ActivitySmith sign-in was disconnected or expired. Run activitysmith auth login to sign in again.";
1230
+ }
1208
1231
 
1209
1232
  if (options?.json) {
1210
1233
  console.log(JSON.stringify({ error: details }, null, 2));
@@ -1236,11 +1259,15 @@ const handleError = async (error, options) => {
1236
1259
  process.exit(1);
1237
1260
  };
1238
1261
 
1239
- const requireApiKey = (options) => {
1240
- const apiKey = getApiKey(options);
1262
+ // Returns the API key, or a current access token from the saved sign-in. The REST API accepts
1263
+ // either as a Bearer token.
1264
+ const requireApiKey = async (options) => {
1265
+ const configuredKey = options.apiKey || process.env.ACTIVITYSMITH_API_KEY;
1266
+ const apiKey = configuredKey || (await getAccessToken());
1267
+ usingSignIn = !configuredKey && Boolean(apiKey);
1241
1268
  if (!apiKey) {
1242
1269
  throw new Error(
1243
- "Missing API key. Provide --api-key or set ACTIVITYSMITH_API_KEY."
1270
+ "Missing API key. Run activitysmith auth login, provide --api-key, or set ACTIVITYSMITH_API_KEY."
1244
1271
  );
1245
1272
  }
1246
1273
  return apiKey;
@@ -1296,7 +1323,7 @@ program
1296
1323
  const globalOptions = program.opts();
1297
1324
 
1298
1325
  try {
1299
- const apiKey = requireApiKey(globalOptions);
1326
+ const apiKey = await requireApiKey(globalOptions);
1300
1327
  const client = createClient(apiKey);
1301
1328
  const actions = await loadPushActions(options);
1302
1329
  validatePushMediaOptions({
@@ -1381,7 +1408,7 @@ program
1381
1408
  const globalOptions = program.opts();
1382
1409
 
1383
1410
  try {
1384
- const apiKey = requireApiKey(globalOptions);
1411
+ const apiKey = await requireApiKey(globalOptions);
1385
1412
  const client = createClient(apiKey);
1386
1413
  const response = await client.badgeCount(
1387
1414
  value,
@@ -1418,7 +1445,7 @@ metricsCommand
1418
1445
  const globalOptions = program.opts();
1419
1446
 
1420
1447
  try {
1421
- const apiKey = requireApiKey(globalOptions);
1448
+ const apiKey = await requireApiKey(globalOptions);
1422
1449
  const client = createClient(apiKey);
1423
1450
  const value = parseMetricValueArgument(rawValue);
1424
1451
  const response = await client.metrics.update(metricKey, value);
@@ -1462,7 +1489,7 @@ addLiveActivityActionOptions(addContentStateOptions(
1462
1489
  if (options.clearTags && options.tags !== undefined) {
1463
1490
  throw new Error("Use either --tags or --clear-tags, not both.");
1464
1491
  }
1465
- const apiKey = requireApiKey(globalOptions);
1492
+ const apiKey = await requireApiKey(globalOptions);
1466
1493
  const client = createClient(apiKey);
1467
1494
  const contentState = await loadContentState(options, "stream");
1468
1495
  const action = await loadLiveActivityAction(options);
@@ -1518,7 +1545,7 @@ addLiveActivityActionOptions(addContentStateOptions(
1518
1545
  const globalOptions = program.opts();
1519
1546
 
1520
1547
  try {
1521
- const apiKey = requireApiKey(globalOptions);
1548
+ const apiKey = await requireApiKey(globalOptions);
1522
1549
  const client = createClient(apiKey);
1523
1550
  const contentState = await loadContentState(options, "start");
1524
1551
  const action = await loadLiveActivityAction(options);
@@ -1566,7 +1593,7 @@ addLiveActivityActionOptions(addContentStateOptions(
1566
1593
  if (options.clearTags && options.tags !== undefined) {
1567
1594
  throw new Error("Use either --tags or --clear-tags, not both.");
1568
1595
  }
1569
- const apiKey = requireApiKey(globalOptions);
1596
+ const apiKey = await requireApiKey(globalOptions);
1570
1597
  const client = createClient(apiKey);
1571
1598
  const contentState = await loadContentState(options, "update");
1572
1599
  const action = await loadLiveActivityAction(options);
@@ -1607,7 +1634,7 @@ addLiveActivityActionOptions(addContentStateOptions(
1607
1634
  if (options.clearTags && options.tags !== undefined) {
1608
1635
  throw new Error("Use either --tags or --clear-tags, not both.");
1609
1636
  }
1610
- const apiKey = requireApiKey(globalOptions);
1637
+ const apiKey = await requireApiKey(globalOptions);
1611
1638
  const client = createClient(apiKey);
1612
1639
  const contentState = await loadContentState(options, "end");
1613
1640
  const action = await loadLiveActivityAction(options);
@@ -1649,7 +1676,7 @@ addLiveActivityActionOptions(addContentStateOptions(
1649
1676
  if (options.clearTags && options.tags !== undefined) throw new Error("Provide either --tags or --clear-tags, not both.");
1650
1677
  const tags = options.clearTags ? [] : options.tags;
1651
1678
  const metadata = await loadMetadata(options);
1652
- const apiKey = requireApiKey(globalOptions);
1679
+ const apiKey = await requireApiKey(globalOptions);
1653
1680
  const client = createClient(apiKey);
1654
1681
  const contentState = await loadOptionalContentState(options, "end");
1655
1682
  const action = await loadLiveActivityAction(options);
@@ -1685,5 +1712,213 @@ addLiveActivityActionOptions(addContentStateOptions(
1685
1712
  { includeAutoDismiss: true, includeAutoDismissSeconds: true }
1686
1713
  ));
1687
1714
 
1715
+ const APP_STORE_URL = "https://apps.apple.com/us/app/activitysmith/id6752254835";
1716
+
1717
+ // Account endpoints the generated SDK does not cover. Same API and SDK header as the SDK client, so
1718
+ // errors print the same way and usage shows the CLI version.
1719
+ const apiRequest = async (path, { token, method = "GET", body } = {}) => {
1720
+ const response = await fetch(`${DEFAULT_API_RESOURCE}${path}`, {
1721
+ method,
1722
+ headers: {
1723
+ Authorization: `Bearer ${token}`,
1724
+ Accept: "application/json",
1725
+ "X-ActivitySmith-SDK": `cli-v${version}`,
1726
+ ...(body ? { "Content-Type": "application/json" } : {}),
1727
+ },
1728
+ ...(body ? { body: JSON.stringify(body) } : {}),
1729
+ });
1730
+ if (!response.ok) {
1731
+ const error = new Error(`Request failed with status ${response.status}`);
1732
+ error.response = response;
1733
+ throw error;
1734
+ }
1735
+ return response.json();
1736
+ };
1737
+
1738
+ const describeDevice = (device) => {
1739
+ const name = device.device_name || device.device_type || "Device";
1740
+ const system = [device.system_name, device.system_version].filter(Boolean).join(" ");
1741
+ const details = [system, device.is_active ? "active" : "inactive", device.user_email].filter(Boolean);
1742
+ return `- ${name} (${details.join(", ")}) ID: ${device.device_id}`;
1743
+ };
1744
+
1745
+ const devicesCommand = program
1746
+ .command("devices")
1747
+ .description("List the iPhones and iPads paired to your account");
1748
+
1749
+ devicesCommand
1750
+ .command("list", { isDefault: true })
1751
+ .description("List paired devices, active ones first")
1752
+ .option("--include-inactive", "Also list devices that can no longer receive deliveries")
1753
+ .action(async (options) => {
1754
+ const globalOptions = program.opts();
1755
+
1756
+ try {
1757
+ const token = await requireApiKey(globalOptions);
1758
+ const query = options.includeInactive ? "?include_inactive=true" : "";
1759
+ const result = await apiRequest(`/account/devices${query}`, { token });
1760
+ const devices = Array.isArray(result.devices) ? result.devices : [];
1761
+ const active = devices.filter((device) => device.is_active).length;
1762
+ outputResult(
1763
+ result,
1764
+ globalOptions,
1765
+ devices.length === 0
1766
+ ? [
1767
+ "No paired devices.",
1768
+ "Install ActivitySmith from the App Store, sign in with this account, and allow notifications:",
1769
+ APP_STORE_URL,
1770
+ ]
1771
+ : [
1772
+ `${devices.length} ${devices.length === 1 ? "device" : "devices"}, ${active} active:`,
1773
+ ...devices.map(describeDevice),
1774
+ result.meta?.has_more ? "More devices exist. Use --json to see the meta.next_offset value." : null,
1775
+ ]
1776
+ );
1777
+ } catch (error) {
1778
+ await handleError(error, globalOptions);
1779
+ }
1780
+ });
1781
+
1782
+ const keysCommand = program
1783
+ .command("keys")
1784
+ .description("Create API keys for CI, servers, and scripts");
1785
+
1786
+ keysCommand
1787
+ .command("create")
1788
+ .description(
1789
+ "Create an API key with the browser sign-in. The first time, approve API key access in the browser"
1790
+ )
1791
+ .requiredOption("--name <name>", 'Key name, such as "GitHub Actions"')
1792
+ .option("--channels <slugs>", "Comma-separated channel slugs. The key reaches only these Channels")
1793
+ .option("--raw", "Print only the key on standard output, for piping it into a secret store")
1794
+ .action(async (options) => {
1795
+ const globalOptions = program.opts();
1796
+
1797
+ try {
1798
+ // API keys cannot create keys, so this always uses the browser sign-in, even when an API key is set.
1799
+ let stored = null;
1800
+ try {
1801
+ stored = readCredentials();
1802
+ } catch {
1803
+ // An unreadable sign-in is replaced by the login below.
1804
+ }
1805
+ if (!hasScope(stored, API_KEYS_SCOPE)) {
1806
+ console.error("Approve API key access in the browser so the CLI can create API keys.");
1807
+ await login({ scope: `${LOGIN_SCOPES} ${API_KEYS_SCOPE}` });
1808
+ }
1809
+ const token = await getAccessToken();
1810
+ usingSignIn = true;
1811
+ const channels = String(options.channels ?? "")
1812
+ .split(",")
1813
+ .map((slug) => slug.trim())
1814
+ .filter(Boolean);
1815
+ const result = await apiRequest("/account/api-keys", {
1816
+ token,
1817
+ method: "POST",
1818
+ body: { name: options.name, ...(channels.length > 0 ? { channels } : {}) },
1819
+ });
1820
+ const key = result.api_key?.key;
1821
+ if (!key) {
1822
+ throw new Error("The API did not return a key. Run the command again.");
1823
+ }
1824
+
1825
+ if (options.raw) {
1826
+ process.stdout.write(`${key}\n`);
1827
+ console.error(`Created API key "${result.api_key.name}". Store it as a secret and never commit it.`);
1828
+ return;
1829
+ }
1830
+ outputResult(result, globalOptions, [
1831
+ `Created API key "${result.api_key.name}".`,
1832
+ `Key: ${key}`,
1833
+ "This is the only time the key is shown. Store it as a secret named ACTIVITYSMITH_API_KEY and never commit it.",
1834
+ ]);
1835
+ } catch (error) {
1836
+ await handleError(error, globalOptions);
1837
+ }
1838
+ });
1839
+
1840
+ const authCommand = program
1841
+ .command("auth")
1842
+ .description("Sign in through the browser and manage the saved sign-in");
1843
+
1844
+ authCommand
1845
+ .command("login")
1846
+ .description("Sign in through the browser so commands work without an API key")
1847
+ .option("--no-browser", "Print the sign-in URL instead of opening a browser")
1848
+ .action(async (options) => {
1849
+ const globalOptions = program.opts();
1850
+
1851
+ try {
1852
+ await login({ noBrowser: options.browser === false });
1853
+ outputResult(
1854
+ { signed_in: true, credentials_path: credentialsPath() },
1855
+ globalOptions,
1856
+ [
1857
+ "Signed in to ActivitySmith.",
1858
+ `Saved to: ${credentialsPath()}`,
1859
+ process.env.ACTIVITYSMITH_API_KEY
1860
+ ? "Note: ACTIVITYSMITH_API_KEY is set and takes precedence over the sign-in."
1861
+ : null,
1862
+ ]
1863
+ );
1864
+ } catch (error) {
1865
+ await handleError(error, globalOptions);
1866
+ }
1867
+ });
1868
+
1869
+ authCommand
1870
+ .command("logout")
1871
+ .description("Sign out and disconnect the CLI from your account")
1872
+ .action(async () => {
1873
+ const globalOptions = program.opts();
1874
+
1875
+ try {
1876
+ const result = await logout();
1877
+ const lines = !result.signedIn
1878
+ ? ["Not signed in."]
1879
+ : result.revoked
1880
+ ? ["Signed out. The CLI is disconnected from your ActivitySmith account."]
1881
+ : [
1882
+ "Signed out on this machine.",
1883
+ 'If "ActivitySmith CLI" is still listed under AI Agents at https://activitysmith.com/app/ai-agents, select Disconnect there.',
1884
+ ];
1885
+ outputResult({ signed_out: result.signedIn, disconnected: result.revoked }, globalOptions, lines);
1886
+ } catch (error) {
1887
+ await handleError(error, globalOptions);
1888
+ }
1889
+ });
1890
+
1891
+ authCommand
1892
+ .command("status")
1893
+ .description("Show how the CLI authenticates, without printing secrets")
1894
+ .action(async () => {
1895
+ const globalOptions = program.opts();
1896
+
1897
+ try {
1898
+ const source = credentialSource(globalOptions);
1899
+ const stored = readCredentials();
1900
+ const payload = {
1901
+ signed_in: Boolean(stored),
1902
+ auth_source: source,
1903
+ signed_in_at: stored?.signed_in_at ?? null,
1904
+ credentials_path: credentialsPath(),
1905
+ };
1906
+ const sourceLine =
1907
+ source === "auth login"
1908
+ ? "Using the browser sign-in from activitysmith auth login."
1909
+ : source
1910
+ ? `Using the API key from ${source}.`
1911
+ : "Not signed in. Run activitysmith auth login.";
1912
+ outputResult(payload, globalOptions, [
1913
+ sourceLine,
1914
+ stored && source !== "auth login" ? "A browser sign-in is also saved, but the API key takes precedence." : null,
1915
+ stored ? `Signed in: ${stored.signed_in_at}` : null,
1916
+ stored ? `Saved to: ${credentialsPath()}` : null,
1917
+ ]);
1918
+ } catch (error) {
1919
+ await handleError(error, globalOptions);
1920
+ }
1921
+ });
1922
+
1688
1923
  program.showHelpAfterError(true);
1689
1924
  program.parseAsync(process.argv);