activitysmith-cli 1.14.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.
- package/README.md +53 -7
- package/package.json +1 -1
- package/src/auth.js +438 -0
- package/src/cli.js +114 -14
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.
|
|
29
|
-
|
|
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
|

|
|
63
107
|
|
|
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.
|
|
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://
|
|
114
|
+
--icon "https://example.com/icons/stripe.png"
|
|
71
115
|
```
|
|
72
116
|
|
|
73
117
|
### Rich Push Notifications with Media
|
|
@@ -585,12 +629,14 @@ String metric values work too.
|
|
|
585
629
|
activitysmith metrics update prod.status healthy
|
|
586
630
|
```
|
|
587
631
|
|
|
588
|
-
## App Icon Badge
|
|
632
|
+
## App Icon Badge
|
|
589
633
|
|
|
590
|
-

|
|
591
635
|
|
|
592
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.
|
|
593
637
|
|
|
638
|
+
App Icon Badge requires Push Notifications enabled. On your iPhone, open Settings > ActivitySmith > Notifications and turn on Allow Notifications.
|
|
639
|
+
|
|
594
640
|
### Set or update the badge value
|
|
595
641
|
|
|
596
642
|
```bash
|
|
@@ -657,7 +703,7 @@ activitysmith activity stream customer-import \
|
|
|
657
703
|
|
|
658
704
|
## Channels
|
|
659
705
|
|
|
660
|
-
Use `--channels` to target specific team members or devices when sending Push Notifications, Live Activities, or App Icon Badge
|
|
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.
|
|
661
707
|
|
|
662
708
|
```bash
|
|
663
709
|
activitysmith push \
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "activitysmith-cli",
|
|
3
|
-
"version": "1.
|
|
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",
|
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
|
-
|
|
271
|
-
|
|
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
|
-
|
|
1240
|
-
|
|
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.
|
|
1260
|
+
"Missing API key. Run activitysmith auth login, provide --api-key, or set ACTIVITYSMITH_API_KEY."
|
|
1244
1261
|
);
|
|
1245
1262
|
}
|
|
1246
1263
|
return apiKey;
|
|
@@ -1296,7 +1313,7 @@ program
|
|
|
1296
1313
|
const globalOptions = program.opts();
|
|
1297
1314
|
|
|
1298
1315
|
try {
|
|
1299
|
-
const apiKey = requireApiKey(globalOptions);
|
|
1316
|
+
const apiKey = await requireApiKey(globalOptions);
|
|
1300
1317
|
const client = createClient(apiKey);
|
|
1301
1318
|
const actions = await loadPushActions(options);
|
|
1302
1319
|
validatePushMediaOptions({
|
|
@@ -1381,7 +1398,7 @@ program
|
|
|
1381
1398
|
const globalOptions = program.opts();
|
|
1382
1399
|
|
|
1383
1400
|
try {
|
|
1384
|
-
const apiKey = requireApiKey(globalOptions);
|
|
1401
|
+
const apiKey = await requireApiKey(globalOptions);
|
|
1385
1402
|
const client = createClient(apiKey);
|
|
1386
1403
|
const response = await client.badgeCount(
|
|
1387
1404
|
value,
|
|
@@ -1418,7 +1435,7 @@ metricsCommand
|
|
|
1418
1435
|
const globalOptions = program.opts();
|
|
1419
1436
|
|
|
1420
1437
|
try {
|
|
1421
|
-
const apiKey = requireApiKey(globalOptions);
|
|
1438
|
+
const apiKey = await requireApiKey(globalOptions);
|
|
1422
1439
|
const client = createClient(apiKey);
|
|
1423
1440
|
const value = parseMetricValueArgument(rawValue);
|
|
1424
1441
|
const response = await client.metrics.update(metricKey, value);
|
|
@@ -1462,7 +1479,7 @@ addLiveActivityActionOptions(addContentStateOptions(
|
|
|
1462
1479
|
if (options.clearTags && options.tags !== undefined) {
|
|
1463
1480
|
throw new Error("Use either --tags or --clear-tags, not both.");
|
|
1464
1481
|
}
|
|
1465
|
-
const apiKey = requireApiKey(globalOptions);
|
|
1482
|
+
const apiKey = await requireApiKey(globalOptions);
|
|
1466
1483
|
const client = createClient(apiKey);
|
|
1467
1484
|
const contentState = await loadContentState(options, "stream");
|
|
1468
1485
|
const action = await loadLiveActivityAction(options);
|
|
@@ -1518,7 +1535,7 @@ addLiveActivityActionOptions(addContentStateOptions(
|
|
|
1518
1535
|
const globalOptions = program.opts();
|
|
1519
1536
|
|
|
1520
1537
|
try {
|
|
1521
|
-
const apiKey = requireApiKey(globalOptions);
|
|
1538
|
+
const apiKey = await requireApiKey(globalOptions);
|
|
1522
1539
|
const client = createClient(apiKey);
|
|
1523
1540
|
const contentState = await loadContentState(options, "start");
|
|
1524
1541
|
const action = await loadLiveActivityAction(options);
|
|
@@ -1566,7 +1583,7 @@ addLiveActivityActionOptions(addContentStateOptions(
|
|
|
1566
1583
|
if (options.clearTags && options.tags !== undefined) {
|
|
1567
1584
|
throw new Error("Use either --tags or --clear-tags, not both.");
|
|
1568
1585
|
}
|
|
1569
|
-
const apiKey = requireApiKey(globalOptions);
|
|
1586
|
+
const apiKey = await requireApiKey(globalOptions);
|
|
1570
1587
|
const client = createClient(apiKey);
|
|
1571
1588
|
const contentState = await loadContentState(options, "update");
|
|
1572
1589
|
const action = await loadLiveActivityAction(options);
|
|
@@ -1607,7 +1624,7 @@ addLiveActivityActionOptions(addContentStateOptions(
|
|
|
1607
1624
|
if (options.clearTags && options.tags !== undefined) {
|
|
1608
1625
|
throw new Error("Use either --tags or --clear-tags, not both.");
|
|
1609
1626
|
}
|
|
1610
|
-
const apiKey = requireApiKey(globalOptions);
|
|
1627
|
+
const apiKey = await requireApiKey(globalOptions);
|
|
1611
1628
|
const client = createClient(apiKey);
|
|
1612
1629
|
const contentState = await loadContentState(options, "end");
|
|
1613
1630
|
const action = await loadLiveActivityAction(options);
|
|
@@ -1649,7 +1666,7 @@ addLiveActivityActionOptions(addContentStateOptions(
|
|
|
1649
1666
|
if (options.clearTags && options.tags !== undefined) throw new Error("Provide either --tags or --clear-tags, not both.");
|
|
1650
1667
|
const tags = options.clearTags ? [] : options.tags;
|
|
1651
1668
|
const metadata = await loadMetadata(options);
|
|
1652
|
-
const apiKey = requireApiKey(globalOptions);
|
|
1669
|
+
const apiKey = await requireApiKey(globalOptions);
|
|
1653
1670
|
const client = createClient(apiKey);
|
|
1654
1671
|
const contentState = await loadOptionalContentState(options, "end");
|
|
1655
1672
|
const action = await loadLiveActivityAction(options);
|
|
@@ -1685,5 +1702,88 @@ addLiveActivityActionOptions(addContentStateOptions(
|
|
|
1685
1702
|
{ includeAutoDismiss: true, includeAutoDismissSeconds: true }
|
|
1686
1703
|
));
|
|
1687
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
|
+
|
|
1688
1788
|
program.showHelpAfterError(true);
|
|
1689
1789
|
program.parseAsync(process.argv);
|