sinatra.dev 0.1.1 → 0.2.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 +31 -12
- package/dist/client.js +16 -1
- package/dist/commands.js +76 -19
- package/dist/config.js +81 -3
- package/dist/index.js +37 -10
- package/dist/oauth.js +274 -0
- package/dist/session.js +77 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -18,19 +18,37 @@ sinatra --version
|
|
|
18
18
|
sinatra login
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
workspace, pick the default one. The
|
|
24
|
-
|
|
21
|
+
`sinatra login` opens your browser on a Sinatra page that asks you to approve the Sinatra CLI. Sign
|
|
22
|
+
in to Sinatra there if you aren't already, click **Approve**, and the CLI is logged in: there's no
|
|
23
|
+
token to create or copy. If you belong to more than one workspace, pick the default one. The CLI
|
|
24
|
+
stops waiting after 5 minutes.
|
|
25
|
+
|
|
26
|
+
The sign-in is saved in `~/.config/sinatra/config.json` (`$XDG_CONFIG_HOME/sinatra` if set,
|
|
27
|
+
`%APPDATA%\sinatra` on Windows), readable only by you. Its access token lasts an hour, and the CLI
|
|
28
|
+
renews it as it goes. It stays signed in for up to 90 days, or until it goes 30 days unused; after
|
|
29
|
+
that, or if you disconnect **Sinatra CLI** under **Connected apps** on the dashboard's Access
|
|
30
|
+
tokens page (<https://app.sinatra.dev/tokens>), the CLI asks you to run `sinatra login` again.
|
|
31
|
+
|
|
32
|
+
If the browser doesn't open, `sinatra login --no-browser` prints the URL to open instead. The
|
|
33
|
+
browser must run on the same computer as the CLI, because Sinatra sends it back to a port the CLI
|
|
34
|
+
listens on there. Logged in to another machine over SSH, or with no browser at all, use a personal
|
|
35
|
+
access token instead:
|
|
25
36
|
|
|
26
|
-
|
|
37
|
+
```sh
|
|
38
|
+
sinatra login --token
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Create a token on the Access tokens page and paste it in; it isn't echoed.
|
|
42
|
+
|
|
43
|
+
In a script, pipe the token in and name the default workspace with `-w`. Piped input always reads a
|
|
44
|
+
token, without `--token`:
|
|
27
45
|
|
|
28
46
|
```sh
|
|
29
47
|
sinatra login -w <workspace-id> < token-file
|
|
30
48
|
```
|
|
31
49
|
|
|
32
50
|
Without `-w`, piped input isn't asked for a workspace: set one later with `sinatra workspace <id>`.
|
|
33
|
-
A `-w` that isn't one of
|
|
51
|
+
A `-w` that isn't one of your workspaces is an error, and nothing is saved.
|
|
34
52
|
|
|
35
53
|
## Commands
|
|
36
54
|
|
|
@@ -41,14 +59,14 @@ sinatra reply <task-id> "also update the docs" # follow up, then follow it
|
|
|
41
59
|
sinatra show <task-id> # a task and its conversation
|
|
42
60
|
sinatra tasks # recent tasks in your workspace
|
|
43
61
|
sinatra stop <task-id> # stop a running turn
|
|
44
|
-
sinatra whoami # who
|
|
62
|
+
sinatra whoami # who you're logged in as, and your workspaces
|
|
45
63
|
sinatra workspace [<id>] # list workspaces, or set the default
|
|
46
|
-
sinatra logout # revoke the token and forget it
|
|
64
|
+
sinatra logout # end the sign-in (or revoke the token) and forget it
|
|
47
65
|
```
|
|
48
66
|
|
|
49
67
|
| Command | Options |
|
|
50
68
|
| --- | --- |
|
|
51
|
-
| `sinatra login` | `--api-url <url>`: another Sinatra API (https; plain http only for localhost); `-w, --workspace <id>`: the default workspace |
|
|
69
|
+
| `sinatra login` | `--no-browser`: print the sign-in URL instead of opening a browser; `--token`: paste a personal access token instead; `--api-url <url>`: another Sinatra API (https; plain http only for localhost); `-w, --workspace <id>`: the default workspace |
|
|
52
70
|
| `sinatra [start] "<what to do>"` | `-r, --repo <owner/name>`, `-f, --file <path>` (repeatable), `-t, --title <title>`, `-w, --workspace <id>`, `--timeout <minutes>`, `--no-wait`, `--json` (with `--no-wait`) |
|
|
53
71
|
| `sinatra reply <task-id> "<message>"` | `-f, --file <path>` (repeatable), `-w`, `--timeout <minutes>`, `--no-wait`, `--json` (with `--no-wait`) |
|
|
54
72
|
| `sinatra show <task-id>` | `-w`, `--json` |
|
|
@@ -85,9 +103,10 @@ An option a command doesn't use is an error, not silently ignored.
|
|
|
85
103
|
`show`, and `start` or `reply` with `--no-wait`.
|
|
86
104
|
- **Prompts vs commands:** a prompt that starts with a command word still starts a task, unless it
|
|
87
105
|
has exactly that command's shape. `sinatra start "..."` always starts one.
|
|
88
|
-
- **Logout:** `sinatra logout`
|
|
89
|
-
can't be reached, the file is still deleted and
|
|
90
|
-
revoke it on the Access
|
|
106
|
+
- **Logout:** `sinatra logout` ends the browser sign-in on Sinatra (or revokes the token you
|
|
107
|
+
pasted), then deletes the local file. If Sinatra can't be reached, the file is still deleted and
|
|
108
|
+
the CLI warns that the sign-in or token may still be active: disconnect or revoke it on the Access
|
|
109
|
+
tokens page.
|
|
91
110
|
- **Retries:** every request that changes something carries an idempotency key, so a retry after a
|
|
92
111
|
dropped connection never starts a second task or sends a message twice.
|
|
93
112
|
|
package/dist/client.js
CHANGED
|
@@ -22,17 +22,21 @@ export function createClient(options) {
|
|
|
22
22
|
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
23
23
|
const base = options.apiUrl.replace(/\/+$/, "");
|
|
24
24
|
const attempts = options.attempts ?? RETRIES;
|
|
25
|
+
const fixed = options.token;
|
|
26
|
+
const credentials = typeof fixed === "string" ? { token: async () => fixed } : fixed;
|
|
25
27
|
async function request(method, path, body) {
|
|
26
28
|
// One key for every attempt of this call: the server answers a retry with the first result.
|
|
27
29
|
// Each call gets its own, so a second call (another repository, say) is a new request.
|
|
28
30
|
const key = method === "GET" ? undefined : randomUUID();
|
|
31
|
+
let bearer = await credentials.token();
|
|
32
|
+
let renewed = false;
|
|
29
33
|
for (let attempt = 1;; attempt++) {
|
|
30
34
|
let response;
|
|
31
35
|
try {
|
|
32
36
|
response = await fetchFn(`${base}${path}`, {
|
|
33
37
|
method,
|
|
34
38
|
headers: {
|
|
35
|
-
authorization: `Bearer ${
|
|
39
|
+
authorization: `Bearer ${bearer}`,
|
|
36
40
|
accept: "application/json",
|
|
37
41
|
...(body !== undefined ? { "content-type": "application/json" } : {}),
|
|
38
42
|
...(key ? { "idempotency-key": key } : {}),
|
|
@@ -51,6 +55,17 @@ export function createClient(options) {
|
|
|
51
55
|
const payload = response.status === 204 ? {} : await response.json().catch(() => ({}));
|
|
52
56
|
if (response.ok)
|
|
53
57
|
return payload;
|
|
58
|
+
// A token refused before it expired (revoked, or the clock is off): renew once and resend.
|
|
59
|
+
// A 401 means the server did nothing, so resending under the same idempotency key is safe.
|
|
60
|
+
if (response.status === 401 && !renewed && credentials.renew) {
|
|
61
|
+
renewed = true;
|
|
62
|
+
const next = await credentials.renew(bearer);
|
|
63
|
+
if (next) {
|
|
64
|
+
bearer = next;
|
|
65
|
+
attempt -= 1;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
54
69
|
if (response.status >= 500 && attempt < attempts) {
|
|
55
70
|
await sleep(RETRY_DELAY_MS * attempt);
|
|
56
71
|
continue;
|
package/dist/commands.js
CHANGED
|
@@ -3,6 +3,7 @@ import { parseArgs } from "node:util";
|
|
|
3
3
|
import { ApiError, createClient } from "./client.js";
|
|
4
4
|
import { ConfigError, DEFAULT_API_URL, DEFAULT_APP_URL } from "./config.js";
|
|
5
5
|
import { DEFAULT_FOLLOW_TIMEOUT_MS } from "./follow.js";
|
|
6
|
+
import { revokeSignIn } from "./oauth.js";
|
|
6
7
|
/** A mistake in how the CLI was called, or anything else to say before exiting with 1. */
|
|
7
8
|
export class UsageError extends Error {
|
|
8
9
|
}
|
|
@@ -39,6 +40,9 @@ export function parseCommand(positionals) {
|
|
|
39
40
|
case "tasks":
|
|
40
41
|
if (rest.length === 0)
|
|
41
42
|
return { name: first };
|
|
43
|
+
if (first === "login" && rest.some((word) => word.startsWith("sntr_"))) {
|
|
44
|
+
return usage("Don't put a token on the command line, where your shell history keeps it. Run `sinatra login --token` and paste it at the prompt.");
|
|
45
|
+
}
|
|
42
46
|
if (!prose)
|
|
43
47
|
return usage(`Usage: sinatra ${first}`);
|
|
44
48
|
break;
|
|
@@ -76,6 +80,8 @@ const OPTIONS = {
|
|
|
76
80
|
status: { type: "string" },
|
|
77
81
|
limit: { type: "string", short: "n" },
|
|
78
82
|
"api-url": { type: "string" },
|
|
83
|
+
token: { type: "boolean" },
|
|
84
|
+
"no-browser": { type: "boolean" },
|
|
79
85
|
version: { type: "boolean", short: "v" },
|
|
80
86
|
help: { type: "boolean", short: "h" },
|
|
81
87
|
};
|
|
@@ -91,7 +97,21 @@ const APPLIES_TO = {
|
|
|
91
97
|
status: ["tasks"],
|
|
92
98
|
limit: ["tasks"],
|
|
93
99
|
"api-url": ["login"],
|
|
100
|
+
token: ["login"],
|
|
101
|
+
"no-browser": ["login"],
|
|
94
102
|
};
|
|
103
|
+
/**
|
|
104
|
+
* How `sinatra login` gets its credential. Asked for explicitly, that way; otherwise the browser
|
|
105
|
+
* at a terminal, and a pasted token when stdin is piped (`sinatra login < token-file`), which
|
|
106
|
+
* holds the token and nothing else.
|
|
107
|
+
*/
|
|
108
|
+
export function loginMode(inv, stdinIsTTY) {
|
|
109
|
+
if (inv.pasteToken)
|
|
110
|
+
return "paste";
|
|
111
|
+
if (inv.noBrowser)
|
|
112
|
+
return "browser";
|
|
113
|
+
return stdinIsTTY ? "browser" : "paste";
|
|
114
|
+
}
|
|
95
115
|
/** The command line, read and checked; anything it can't run is a UsageError. */
|
|
96
116
|
export function parseInvocation(argv) {
|
|
97
117
|
const { values, positionals } = (() => {
|
|
@@ -123,6 +143,9 @@ export function parseInvocation(argv) {
|
|
|
123
143
|
}
|
|
124
144
|
}
|
|
125
145
|
}
|
|
146
|
+
if (values.token && values["no-browser"]) {
|
|
147
|
+
throw new UsageError("--token pastes a token and --no-browser signs in through a browser: pick one.");
|
|
148
|
+
}
|
|
126
149
|
const wait = !values["no-wait"];
|
|
127
150
|
if (values.json && (command.name === "start" || command.name === "reply") && wait) {
|
|
128
151
|
throw new UsageError("--json with start or reply needs --no-wait: following prints the conversation as it comes.");
|
|
@@ -146,6 +169,8 @@ export function parseInvocation(argv) {
|
|
|
146
169
|
wait,
|
|
147
170
|
timeoutMs,
|
|
148
171
|
json: values.json ?? false,
|
|
172
|
+
pasteToken: values.token ?? false,
|
|
173
|
+
noBrowser: values["no-browser"] ?? false,
|
|
149
174
|
...(values.repo !== undefined ? { repo: values.repo } : {}),
|
|
150
175
|
...(values.title !== undefined ? { title: values.title } : {}),
|
|
151
176
|
...(values.workspace !== undefined ? { workspace: values.workspace } : {}),
|
|
@@ -219,23 +244,42 @@ export async function startTask(client, workspaceId, body, repos, notice) {
|
|
|
219
244
|
}
|
|
220
245
|
return { started: await client.startTask(workspaceId, body), repo: null };
|
|
221
246
|
}
|
|
222
|
-
|
|
223
|
-
* `sinatra login`: read a token, check it, pick the default workspace, save. A `--workspace`
|
|
224
|
-
* that isn't one of the token's workspaces is refused before anything is saved, so a script's
|
|
225
|
-
* typo leaves the previous login as it was.
|
|
226
|
-
*/
|
|
227
|
-
export async function login(deps) {
|
|
228
|
-
const { out } = deps;
|
|
247
|
+
async function pastedToken(deps) {
|
|
229
248
|
// The sign-in page sends a signed-in visitor straight on, and a signed-out one there after signing in.
|
|
230
|
-
out(deps.apiUrl === DEFAULT_API_URL
|
|
249
|
+
deps.out(deps.apiUrl === DEFAULT_API_URL
|
|
231
250
|
? `Create a personal access token at ${DEFAULT_APP_URL}/login?returnTo=%2Ftokens, then paste it here.\n`
|
|
232
251
|
: "Create a personal access token on your Sinatra dashboard's Access tokens page, then paste it here.\n");
|
|
233
252
|
const token = await deps.askSecret("Token (hidden): ");
|
|
234
253
|
if (!token)
|
|
235
254
|
throw new UsageError("No token given.");
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
255
|
+
return token;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* `sinatra login`: sign in through the browser or read a pasted token, check it, pick the default
|
|
259
|
+
* workspace, save. A `--workspace` that isn't one of the account's workspaces is refused before
|
|
260
|
+
* anything is saved, so a script's typo leaves the previous login as it was.
|
|
261
|
+
*/
|
|
262
|
+
export async function login(deps) {
|
|
263
|
+
const { out } = deps;
|
|
264
|
+
const signedIn = deps.browser ? await deps.browser.signIn() : { token: await pastedToken(deps) };
|
|
265
|
+
let me;
|
|
266
|
+
let workspaceId;
|
|
267
|
+
try {
|
|
268
|
+
me = await deps.me(signedIn.token);
|
|
269
|
+
workspaceId = await loginWorkspace(me.workspaces, deps);
|
|
270
|
+
}
|
|
271
|
+
catch (error) {
|
|
272
|
+
if (signedIn.oauth)
|
|
273
|
+
await deps.browser?.discard(signedIn.oauth).catch(() => undefined);
|
|
274
|
+
throw error;
|
|
275
|
+
}
|
|
276
|
+
await deps.discardPrevious?.().catch(() => undefined);
|
|
277
|
+
await deps.save({
|
|
278
|
+
apiUrl: deps.apiUrl,
|
|
279
|
+
token: signedIn.token,
|
|
280
|
+
...(signedIn.oauth ? { oauth: signedIn.oauth } : {}),
|
|
281
|
+
...(workspaceId ? { workspaceId } : {}),
|
|
282
|
+
});
|
|
239
283
|
const name = me.user.githubLogin ? `@${me.user.githubLogin}` : me.user.name ?? me.user.id;
|
|
240
284
|
const workspace = me.workspaces.find((w) => w.id === workspaceId)?.name;
|
|
241
285
|
out(printable(`Logged in as ${name}${workspace ? `, workspace ${workspace}` : ""}.\n`));
|
|
@@ -248,7 +292,8 @@ async function loginWorkspace(workspaces, deps) {
|
|
|
248
292
|
if (chosen)
|
|
249
293
|
return chosen.id;
|
|
250
294
|
const yours = workspaces.map((w) => `${w.name} (${w.id})`).join(", ");
|
|
251
|
-
|
|
295
|
+
const whose = deps.browser ? "your" : "this token's";
|
|
296
|
+
throw new UsageError(printable(`${deps.workspace} isn't one of ${whose} workspaces${yours ? ` (${yours})` : ""}. Nothing was saved.`));
|
|
252
297
|
}
|
|
253
298
|
if (workspaces.length === 1)
|
|
254
299
|
return workspaces[0].id;
|
|
@@ -268,20 +313,24 @@ async function loginWorkspace(workspaces, deps) {
|
|
|
268
313
|
out("No default workspace saved; pass -w <id> to commands, or set one with `sinatra workspace <id>`.\n");
|
|
269
314
|
return undefined;
|
|
270
315
|
}
|
|
271
|
-
/** Where to make (or revoke) a token, for the API a config points at. */
|
|
316
|
+
/** Where to make (or revoke) a token, and disconnect a sign-in, for the API a config points at. */
|
|
272
317
|
export function tokensPage(apiUrl) {
|
|
273
318
|
return apiUrl === DEFAULT_API_URL ? `${DEFAULT_APP_URL}/tokens` : "your Sinatra dashboard's Access tokens page";
|
|
274
319
|
}
|
|
275
320
|
/**
|
|
276
|
-
* Revoking the saved
|
|
277
|
-
* up forgetting it here (a retry would only add to the wait).
|
|
321
|
+
* Revoking the saved credential at logout: one attempt, bounded, so an unreachable server can't
|
|
322
|
+
* hold up forgetting it here (a retry would only add to the wait). A browser sign-in revokes its
|
|
323
|
+
* refresh token, which ends the whole grant (its access token may already have expired); a
|
|
324
|
+
* personal access token revokes itself.
|
|
278
325
|
*/
|
|
279
326
|
export function revokeSavedToken(config, fetch) {
|
|
280
|
-
|
|
327
|
+
if (config.oauth)
|
|
328
|
+
return revokeSignIn(config.apiUrl, config.oauth, fetch);
|
|
329
|
+
return createClient({ apiUrl: config.apiUrl, token: config.token, timeoutMs: 10_000, attempts: 1, ...(fetch ? { fetch } : {}) }).revokeToken();
|
|
281
330
|
}
|
|
282
331
|
/**
|
|
283
|
-
* Logging out: revoke the saved
|
|
284
|
-
* token the server already rejects is as good as revoked; any other failure leaves it possibly
|
|
332
|
+
* Logging out: revoke the saved credential on the server, then forget it here whatever happened.
|
|
333
|
+
* A token the server already rejects is as good as revoked; any other failure leaves it possibly
|
|
285
334
|
* still working, which the person is told along with where to revoke it.
|
|
286
335
|
*/
|
|
287
336
|
export async function logout(deps) {
|
|
@@ -295,7 +344,7 @@ export async function logout(deps) {
|
|
|
295
344
|
await deps.forget();
|
|
296
345
|
return {
|
|
297
346
|
message: "Removed the damaged config.",
|
|
298
|
-
warning: `If it held a token, revoke it on ${tokensPage(DEFAULT_API_URL)} (or your dashboard's Access tokens page).`,
|
|
347
|
+
warning: `If it held a token or a sign-in, revoke or disconnect it on ${tokensPage(DEFAULT_API_URL)} (or your dashboard's Access tokens page).`,
|
|
299
348
|
};
|
|
300
349
|
}
|
|
301
350
|
if (!config) {
|
|
@@ -313,6 +362,14 @@ export async function logout(deps) {
|
|
|
313
362
|
}
|
|
314
363
|
}
|
|
315
364
|
await deps.forget();
|
|
365
|
+
if (config.oauth) {
|
|
366
|
+
if (problem === null)
|
|
367
|
+
return { message: "Logged out; the sign-in is revoked." };
|
|
368
|
+
return {
|
|
369
|
+
message: "Logged out on this machine.",
|
|
370
|
+
warning: `Couldn't revoke the sign-in (${problem}), so it may still be active. Disconnect Sinatra CLI under Connected apps on ${tokensPage(config.apiUrl)}.`,
|
|
371
|
+
};
|
|
372
|
+
}
|
|
316
373
|
if (problem === null)
|
|
317
374
|
return { message: "Logged out; the token is revoked." };
|
|
318
375
|
return {
|
package/dist/config.js
CHANGED
|
@@ -1,13 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Where the CLI keeps its
|
|
3
|
-
* directory (`%APPDATA%\sinatra` on Windows).
|
|
2
|
+
* Where the CLI keeps its credentials: one JSON file, readable only by you (0600), in the XDG config
|
|
3
|
+
* directory (`%APPDATA%\sinatra` on Windows). Tokens are never printed back.
|
|
4
4
|
*/
|
|
5
5
|
import { randomBytes } from "node:crypto";
|
|
6
|
-
import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
6
|
+
import { chmod, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
7
7
|
import { homedir } from "node:os";
|
|
8
8
|
import { dirname, join, win32 } from "node:path";
|
|
9
9
|
export const DEFAULT_API_URL = "https://api.sinatra.dev";
|
|
10
10
|
export const DEFAULT_APP_URL = "https://app.sinatra.dev";
|
|
11
|
+
function readOAuthSession(value) {
|
|
12
|
+
if (typeof value !== "object" || value === null)
|
|
13
|
+
return undefined;
|
|
14
|
+
const { refreshToken, expiresAt, clientId } = value;
|
|
15
|
+
if (typeof refreshToken !== "string" || typeof expiresAt !== "string" || typeof clientId !== "string")
|
|
16
|
+
return undefined;
|
|
17
|
+
return { refreshToken, expiresAt, clientId };
|
|
18
|
+
}
|
|
11
19
|
export function configPath(env = process.env, platform = process.platform) {
|
|
12
20
|
if (platform === "win32") {
|
|
13
21
|
return win32.join(env.APPDATA || win32.join(homedir(), "AppData", "Roaming"), "sinatra", "config.json");
|
|
@@ -42,9 +50,11 @@ export async function readConfig(path = configPath()) {
|
|
|
42
50
|
const config = parsed;
|
|
43
51
|
if (typeof config.token !== "string" || typeof config.apiUrl !== "string")
|
|
44
52
|
return null;
|
|
53
|
+
const oauth = readOAuthSession(config.oauth);
|
|
45
54
|
return {
|
|
46
55
|
apiUrl: config.apiUrl,
|
|
47
56
|
token: config.token,
|
|
57
|
+
...(oauth ? { oauth } : {}),
|
|
48
58
|
...(typeof config.workspaceId === "string" ? { workspaceId: config.workspaceId } : {}),
|
|
49
59
|
};
|
|
50
60
|
}
|
|
@@ -67,3 +77,71 @@ export async function writeConfig(config, path = configPath()) {
|
|
|
67
77
|
export async function deleteConfig(path = configPath()) {
|
|
68
78
|
await rm(path, { force: true });
|
|
69
79
|
}
|
|
80
|
+
/**
|
|
81
|
+
* A lock file older than this is a hung or crashed process's. Longer than a renewal can take: the
|
|
82
|
+
* refresh request alone may run for 30 s.
|
|
83
|
+
*/
|
|
84
|
+
export const CONFIG_LOCK_STALE_MS = 60_000;
|
|
85
|
+
/** Whether a process with this id is running (one we may not signal still is). */
|
|
86
|
+
function isRunning(pid) {
|
|
87
|
+
try {
|
|
88
|
+
process.kill(pid, 0);
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
return error.code === "EPERM";
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/** The lock file's contents, `<pid> <nonce>`; null while it is absent or not yet written. */
|
|
96
|
+
async function readLock(lockPath) {
|
|
97
|
+
const text = await readFile(lockPath, "utf8").catch(() => null);
|
|
98
|
+
if (!text)
|
|
99
|
+
return null;
|
|
100
|
+
const pid = Number(text.split(" ")[0]);
|
|
101
|
+
return { text, pid: Number.isInteger(pid) && pid > 0 ? pid : null };
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Runs `fn` holding `<config>.lock`, created exclusively (O_EXCL), so only one `sinatra` process
|
|
105
|
+
* renews the saved sign-in at a time. Another waits for it, retrying every `retryMs`. A lock is
|
|
106
|
+
* taken over at once when the process that wrote it is gone (a Ctrl-C mid-refresh), and otherwise
|
|
107
|
+
* once it is `staleMs` old. It records its holder's pid and a nonce, and is released only while it
|
|
108
|
+
* still holds that nonce, so a holder that was taken over never deletes its successor's lock.
|
|
109
|
+
*/
|
|
110
|
+
export async function withConfigLock(fn, path = configPath(), options = {}) {
|
|
111
|
+
const lockPath = `${path}.lock`;
|
|
112
|
+
const staleMs = options.staleMs ?? CONFIG_LOCK_STALE_MS;
|
|
113
|
+
const retryMs = options.retryMs ?? 50;
|
|
114
|
+
const mine = `${process.pid} ${randomBytes(16).toString("hex")}\n`;
|
|
115
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
116
|
+
for (;;) {
|
|
117
|
+
try {
|
|
118
|
+
const handle = await open(lockPath, "wx", 0o600);
|
|
119
|
+
await handle.writeFile(mine);
|
|
120
|
+
await handle.close();
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
if (error.code !== "EEXIST")
|
|
125
|
+
throw error;
|
|
126
|
+
const [held, info] = await Promise.all([readLock(lockPath), stat(lockPath).catch(() => null)]);
|
|
127
|
+
const abandoned = held?.pid != null && !isRunning(held.pid);
|
|
128
|
+
const stale = info !== null && Date.now() - info.mtimeMs > staleMs;
|
|
129
|
+
if (abandoned || stale) {
|
|
130
|
+
// Removed only if it is still the lock we judged: another waiter may have taken it over.
|
|
131
|
+
const now = await readLock(lockPath);
|
|
132
|
+
if (now?.text === held?.text)
|
|
133
|
+
await rm(lockPath, { force: true });
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
await new Promise((resolve) => setTimeout(resolve, retryMs));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
return await fn();
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
if ((await readLock(lockPath))?.text === mine)
|
|
145
|
+
await rm(lockPath, { force: true });
|
|
146
|
+
}
|
|
147
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -2,21 +2,27 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* `sinatra`: hand coding tasks to Sinatra from your terminal (SIN-1258).
|
|
4
4
|
*
|
|
5
|
-
* sinatra login
|
|
5
|
+
* sinatra login sign in through the browser (--token: paste a token)
|
|
6
6
|
* sinatra "fix the flaky test" start a task and follow it until its turn is done
|
|
7
7
|
* sinatra reply <task> "also docs" follow up on a task
|
|
8
8
|
* sinatra tasks | show <task> | stop <task> | whoami | workspace [id] | logout
|
|
9
9
|
*/
|
|
10
10
|
import { readFileSync } from "node:fs";
|
|
11
11
|
import { ApiError, createClient } from "./client.js";
|
|
12
|
-
import { explain, login, logout, parseInvocation, printable, repoChoices, revokeSavedToken, startTask, UsageError } from "./commands.js";
|
|
13
|
-
import { ConfigError, DEFAULT_API_URL, deleteConfig, readConfig, writeConfig } from "./config.js";
|
|
12
|
+
import { explain, login, loginMode, logout, parseInvocation, printable, repoChoices, revokeSavedToken, startTask, UsageError, } from "./commands.js";
|
|
13
|
+
import { ConfigError, DEFAULT_API_URL, deleteConfig, readConfig, withConfigLock, writeConfig } from "./config.js";
|
|
14
14
|
import { AttachmentError, composePrompt, detectRepos, readAttachments } from "./context.js";
|
|
15
15
|
import { EXIT, followOutcome, followTask } from "./follow.js";
|
|
16
|
+
import { browserSignIn, openBrowser, revokeSignIn, SignInError } from "./oauth.js";
|
|
16
17
|
import { ask, askSecret } from "./prompt.js";
|
|
18
|
+
import { credentialsFor } from "./session.js";
|
|
17
19
|
const USAGE = `Usage:
|
|
18
|
-
sinatra login [--api-url <url>] [-w <id>]
|
|
19
|
-
|
|
20
|
+
sinatra login [--api-url <url>] [-w <id>] [--no-browser | --token]
|
|
21
|
+
Sign in through your browser (-w: the default workspace)
|
|
22
|
+
--no-browser Print the sign-in URL instead of opening it (the browser
|
|
23
|
+
must still be on this computer)
|
|
24
|
+
--token Paste a personal access token instead (also when stdin
|
|
25
|
+
is piped: sinatra login < token-file)
|
|
20
26
|
sinatra [start] "<what to do>" Start a task and follow it
|
|
21
27
|
-r, --repo <owner/name> Repository (default: this checkout's GitHub remote)
|
|
22
28
|
-f, --file <path> Attach a text file (repeatable, 80KB total)
|
|
@@ -30,9 +36,9 @@ const USAGE = `Usage:
|
|
|
30
36
|
sinatra tasks [--status <status>] [-n, --limit <n>] [--json]
|
|
31
37
|
List the workspace's recent tasks (20 unless -n)
|
|
32
38
|
sinatra stop <task-id> Stop a task's running turn
|
|
33
|
-
sinatra whoami [--json] Who
|
|
39
|
+
sinatra whoami [--json] Who you're logged in as, and your workspaces
|
|
34
40
|
sinatra workspace [<id>] List your workspaces, or make one the default
|
|
35
|
-
sinatra logout Revoke the saved token and forget it
|
|
41
|
+
sinatra logout Revoke the saved sign-in or token and forget it
|
|
36
42
|
sinatra -v, --version Print the CLI's version
|
|
37
43
|
|
|
38
44
|
-w, --workspace <id> Workspace for any task command (default: yours from
|
|
@@ -177,13 +183,27 @@ async function main(argv) {
|
|
|
177
183
|
return;
|
|
178
184
|
case "login": {
|
|
179
185
|
const apiUrl = checkApiUrl(inv.apiUrl ?? DEFAULT_API_URL);
|
|
186
|
+
const browser = loginMode(inv, Boolean(process.stdin.isTTY)) === "browser";
|
|
180
187
|
return login({
|
|
181
188
|
apiUrl,
|
|
182
189
|
...(inv.workspace !== undefined ? { workspace: inv.workspace } : {}),
|
|
183
190
|
interactive: Boolean(process.stdin.isTTY),
|
|
191
|
+
...(browser
|
|
192
|
+
? {
|
|
193
|
+
browser: {
|
|
194
|
+
signIn: () => browserSignIn({ apiUrl, openBrowser: inv.noBrowser ? null : (url) => openBrowser(url), out }),
|
|
195
|
+
discard: (session) => revokeSignIn(apiUrl, session),
|
|
196
|
+
},
|
|
197
|
+
}
|
|
198
|
+
: {}),
|
|
184
199
|
askSecret: (question) => askSecret(question),
|
|
185
200
|
ask: (question) => ask(question),
|
|
186
201
|
me: (token) => whoAmI(createClient({ apiUrl, token }), apiUrl, "login"),
|
|
202
|
+
discardPrevious: async () => {
|
|
203
|
+
const previous = await readConfig().catch(() => null);
|
|
204
|
+
if (previous?.oauth)
|
|
205
|
+
await revokeSignIn(previous.apiUrl, previous.oauth);
|
|
206
|
+
},
|
|
187
207
|
save: (config) => writeConfig(config),
|
|
188
208
|
out,
|
|
189
209
|
});
|
|
@@ -201,7 +221,12 @@ async function main(argv) {
|
|
|
201
221
|
}
|
|
202
222
|
}
|
|
203
223
|
const config = await loggedIn();
|
|
204
|
-
const client = createClient(
|
|
224
|
+
const client = createClient({
|
|
225
|
+
apiUrl: config.apiUrl,
|
|
226
|
+
token: credentialsFor(config, {
|
|
227
|
+
store: { read: readConfig, write: (c) => writeConfig(c), forget: deleteConfig, lock: (fn) => withConfigLock(fn) },
|
|
228
|
+
}),
|
|
229
|
+
});
|
|
205
230
|
switch (command.name) {
|
|
206
231
|
case "whoami": {
|
|
207
232
|
const me = await whoAmI(client, config.apiUrl, "me");
|
|
@@ -219,7 +244,9 @@ async function main(argv) {
|
|
|
219
244
|
const chosen = me.workspaces.find((w) => w.id === command.workspaceId);
|
|
220
245
|
if (!chosen)
|
|
221
246
|
throw new UsageError(printable(`${command.workspaceId} isn't one of your workspaces; list them with \`sinatra workspace\`.`));
|
|
222
|
-
|
|
247
|
+
// Read again: checking the account may have refreshed the sign-in, rotating the tokens
|
|
248
|
+
// `config` holds, and writing those back would end it.
|
|
249
|
+
await writeConfig({ ...((await readConfig()) ?? config), workspaceId: chosen.id });
|
|
223
250
|
out(printable(`Default workspace: ${chosen.name} (${chosen.id}).\n`));
|
|
224
251
|
return;
|
|
225
252
|
}
|
|
@@ -305,7 +332,7 @@ process.stdout.on("error", (error) => {
|
|
|
305
332
|
process.exit(process.exitCode ?? 0);
|
|
306
333
|
});
|
|
307
334
|
main(process.argv.slice(2)).catch((error) => {
|
|
308
|
-
if (error instanceof UsageError || error instanceof AttachmentError || error instanceof ConfigError) {
|
|
335
|
+
if (error instanceof UsageError || error instanceof AttachmentError || error instanceof ConfigError || error instanceof SignInError) {
|
|
309
336
|
process.stderr.write(`${error.message}\n`);
|
|
310
337
|
}
|
|
311
338
|
else if (error instanceof ApiError) {
|
package/dist/oauth.js
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Signing in through the browser: the CLI is an OAuth public client of Sinatra's own authorization
|
|
3
|
+
* server (RFC 8252, native apps). It listens on a loopback port, sends the browser to Sinatra's
|
|
4
|
+
* consent page with a PKCE challenge and a random `state`, takes the code back on that port, and
|
|
5
|
+
* exchanges it for an hourly access token and a rotating refresh token, both bound to the REST API.
|
|
6
|
+
*
|
|
7
|
+
* The CLI's client id is a Client ID Metadata Document the API serves itself, so it needs no
|
|
8
|
+
* registration; the consent page says the API's host describes it.
|
|
9
|
+
*/
|
|
10
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
11
|
+
import { spawn } from "node:child_process";
|
|
12
|
+
import { createServer } from "node:http";
|
|
13
|
+
/** A sign-in that can't go on, said for the person: nothing to retry in place. */
|
|
14
|
+
export class SignInError extends Error {
|
|
15
|
+
}
|
|
16
|
+
/** Stops waiting for the browser after this long. */
|
|
17
|
+
export const SIGN_IN_TIMEOUT_MS = 5 * 60_000;
|
|
18
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
19
|
+
const PASTE_INSTEAD = "To paste a personal access token instead, run `sinatra login --token`.";
|
|
20
|
+
/** Where the authorization server is, for an API URL: the API's own origin, which is its issuer. */
|
|
21
|
+
export function oauthEndpoints(apiUrl) {
|
|
22
|
+
const issuer = new URL(apiUrl).origin;
|
|
23
|
+
return {
|
|
24
|
+
issuer,
|
|
25
|
+
metadata: `${issuer}/.well-known/oauth-authorization-server`,
|
|
26
|
+
authorize: `${issuer}/oauth/authorize`,
|
|
27
|
+
token: `${issuer}/oauth/token`,
|
|
28
|
+
revoke: `${issuer}/oauth/revoke`,
|
|
29
|
+
/** The CLI's metadata document, served by the API: its URL is the client id. */
|
|
30
|
+
clientId: `${issuer}/oauth/cli-client.json`,
|
|
31
|
+
/** The REST API (RFC 8707): tokens for it work on `/v1` routes, never on the MCP server. */
|
|
32
|
+
resource: `${issuer}/v1`,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** RFC 7636 S256: a 43-character verifier and its challenge. */
|
|
36
|
+
export function pkcePair() {
|
|
37
|
+
const verifier = randomBytes(32).toString("base64url");
|
|
38
|
+
return { verifier, challenge: createHash("sha256").update(verifier).digest("base64url") };
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Opens a URL in the default browser, without a shell. False when the opener can't be started (no
|
|
42
|
+
* desktop, as over SSH); the URL is printed either way.
|
|
43
|
+
*/
|
|
44
|
+
export function openBrowser(url, platform = process.platform) {
|
|
45
|
+
const [command, args] = platform === "darwin"
|
|
46
|
+
? ["open", [url]]
|
|
47
|
+
: platform === "win32"
|
|
48
|
+
? // Not `cmd /c start`: cmd would read the `&` between query parameters as a command separator.
|
|
49
|
+
["rundll32", ["url.dll,FileProtocolHandler", url]]
|
|
50
|
+
: ["xdg-open", [url]];
|
|
51
|
+
return new Promise((resolve) => {
|
|
52
|
+
try {
|
|
53
|
+
const child = spawn(command, args, { stdio: "ignore", detached: true });
|
|
54
|
+
child.once("error", () => resolve(false));
|
|
55
|
+
child.once("spawn", () => {
|
|
56
|
+
child.unref();
|
|
57
|
+
resolve(true);
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
resolve(false);
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
/** The token endpoint's answer, read as tokens or its error code; nothing else it says is trusted. */
|
|
66
|
+
async function postForm(fetchFn, url, params, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
67
|
+
const response = await fetchFn(url, {
|
|
68
|
+
method: "POST",
|
|
69
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
|
|
70
|
+
body: new URLSearchParams(params).toString(),
|
|
71
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
72
|
+
});
|
|
73
|
+
const body = (await response.json().catch(() => ({})));
|
|
74
|
+
return { status: response.status, body: typeof body === "object" && body !== null ? body : {} };
|
|
75
|
+
}
|
|
76
|
+
/** The callback's `state` against ours, in constant time. */
|
|
77
|
+
function sameState(presented, expected) {
|
|
78
|
+
const a = Buffer.from(presented ?? "");
|
|
79
|
+
const b = Buffer.from(expected);
|
|
80
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
81
|
+
}
|
|
82
|
+
/** An error code from the server or the redirect, safe to print: a short word or nothing. */
|
|
83
|
+
function errorCode(value) {
|
|
84
|
+
return typeof value === "string" && /^[a-z_]{1,64}$/.test(value) ? value : null;
|
|
85
|
+
}
|
|
86
|
+
function signedIn(body, clientId, now) {
|
|
87
|
+
const { access_token: token, refresh_token: refreshToken, expires_in: expiresIn } = body;
|
|
88
|
+
if (typeof token !== "string" || typeof refreshToken !== "string" || typeof expiresIn !== "number")
|
|
89
|
+
return null;
|
|
90
|
+
return { token, oauth: { refreshToken, clientId, expiresAt: new Date(now + expiresIn * 1000).toISOString() } };
|
|
91
|
+
}
|
|
92
|
+
/** The page the browser lands on: fixed text only, so nothing from the request is reflected. */
|
|
93
|
+
function sendPage(res, status, title, text) {
|
|
94
|
+
res.writeHead(status, {
|
|
95
|
+
"content-type": "text/html; charset=utf-8",
|
|
96
|
+
"cache-control": "no-store",
|
|
97
|
+
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'",
|
|
98
|
+
"referrer-policy": "no-referrer",
|
|
99
|
+
// The CLI stops listening once it has its answer; a kept-alive socket would hold the process open.
|
|
100
|
+
connection: "close",
|
|
101
|
+
});
|
|
102
|
+
res.end(`<!doctype html>
|
|
103
|
+
<html lang="en">
|
|
104
|
+
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title} · Sinatra</title>
|
|
105
|
+
<style>body{font:16px/1.5 system-ui,sans-serif;color:#111;background:#f4f5f8;margin:0;display:grid;place-items:center;min-height:100vh}main{max-width:28rem;margin:1rem;padding:2rem;background:#fff;border:1px solid #e3e5ea;border-radius:12px}h1{font-size:1.25rem;margin:0 0 .5rem}p{margin:0;color:#4a4f5c}</style>
|
|
106
|
+
</head>
|
|
107
|
+
<body><main><h1>${title}</h1><p>${text}</p></main></body>
|
|
108
|
+
</html>
|
|
109
|
+
`);
|
|
110
|
+
}
|
|
111
|
+
/** Why the browser came back without a code, said for the person. */
|
|
112
|
+
function refusal(code) {
|
|
113
|
+
if (code === "access_denied")
|
|
114
|
+
return "Sign-in was denied in the browser. Nothing was saved.";
|
|
115
|
+
if (code === "invalid_target")
|
|
116
|
+
return `This Sinatra API doesn't offer CLI sign-in. ${PASTE_INSTEAD}`;
|
|
117
|
+
return `Sign-in failed${code ? ` (${code})` : ""}. Run \`sinatra login\` to try again. ${PASTE_INSTEAD}`;
|
|
118
|
+
}
|
|
119
|
+
/** Checks the server has an authorization server, and that it is the one this API URL names. */
|
|
120
|
+
async function checkAuthorizationServer(fetchFn, endpoints) {
|
|
121
|
+
const response = await fetchFn(endpoints.metadata, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
|
122
|
+
if (response.status === 404)
|
|
123
|
+
throw new SignInError(`This Sinatra API doesn't offer browser sign-in. ${PASTE_INSTEAD}`);
|
|
124
|
+
const metadata = (await response.json().catch(() => null));
|
|
125
|
+
// RFC 8414 §3.3: metadata whose issuer isn't the server we asked is not to be used.
|
|
126
|
+
if (!response.ok || metadata?.issuer !== endpoints.issuer) {
|
|
127
|
+
throw new SignInError(`Couldn't start browser sign-in (HTTP ${response.status}). ${PASTE_INSTEAD}`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* The whole browser sign-in: tokens for the REST API, or a SignInError. Callbacks to the loopback
|
|
132
|
+
* port that don't carry this sign-in's `state` are refused and ignored (another page can reach the
|
|
133
|
+
* port too), and the wait goes on until the real one arrives or `timeoutMs` passes.
|
|
134
|
+
*/
|
|
135
|
+
export async function browserSignIn(deps) {
|
|
136
|
+
const fetchFn = deps.fetch ?? globalThis.fetch;
|
|
137
|
+
const now = deps.now ?? Date.now;
|
|
138
|
+
const timeoutMs = deps.timeoutMs ?? SIGN_IN_TIMEOUT_MS;
|
|
139
|
+
const endpoints = oauthEndpoints(deps.apiUrl);
|
|
140
|
+
await checkAuthorizationServer(fetchFn, endpoints);
|
|
141
|
+
const state = randomBytes(32).toString("base64url");
|
|
142
|
+
const { verifier, challenge } = pkcePair();
|
|
143
|
+
let settle;
|
|
144
|
+
const callback = new Promise((resolve, reject) => {
|
|
145
|
+
settle = { resolve, reject };
|
|
146
|
+
});
|
|
147
|
+
// Handled where it's awaited; this keeps an early refusal (the browser answering before the CLI
|
|
148
|
+
// has finished opening it) from counting as unhandled meanwhile.
|
|
149
|
+
callback.catch(() => undefined);
|
|
150
|
+
let done = false;
|
|
151
|
+
const server = createServer((req, res) => {
|
|
152
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
153
|
+
if (req.method !== "GET" || url.pathname !== "/callback") {
|
|
154
|
+
res.writeHead(404, { "content-type": "text/plain; charset=utf-8", connection: "close" }).end("Not found\n");
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
const params = url.searchParams;
|
|
158
|
+
if (done || !sameState(params.get("state"), state)) {
|
|
159
|
+
sendPage(res, 400, "This sign-in isn't the one the CLI is waiting for", "Go back to your terminal and run sinatra login again if you need to.");
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
// RFC 9207: a response from another authorization server (a mix-up) is refused.
|
|
163
|
+
const iss = params.get("iss");
|
|
164
|
+
const code = params.get("code");
|
|
165
|
+
done = true;
|
|
166
|
+
if (iss !== null && iss !== endpoints.issuer) {
|
|
167
|
+
sendPage(res, 400, "Sign-in failed", "Go back to your terminal.");
|
|
168
|
+
settle.reject(new SignInError(`Sign-in came back from another server. ${PASTE_INSTEAD}`));
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (params.has("error") || !code) {
|
|
172
|
+
const denied = params.get("error") === "access_denied";
|
|
173
|
+
sendPage(res, 400, denied ? "Sign-in denied" : "Sign-in failed", "Go back to your terminal. You can close this tab.");
|
|
174
|
+
settle.reject(new SignInError(refusal(errorCode(params.get("error")))));
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
settle.resolve({ code, res });
|
|
178
|
+
});
|
|
179
|
+
await new Promise((resolve, reject) => {
|
|
180
|
+
server.once("error", reject);
|
|
181
|
+
server.listen(0, "127.0.0.1", () => resolve());
|
|
182
|
+
});
|
|
183
|
+
const redirectUri = `http://127.0.0.1:${server.address().port}/callback`;
|
|
184
|
+
const minutes = Math.max(1, Math.round(timeoutMs / 60_000));
|
|
185
|
+
const timer = setTimeout(() => settle.reject(new SignInError(`Timed out after ${minutes} minute${minutes === 1 ? "" : "s"} waiting for you to sign in in the browser. ` +
|
|
186
|
+
"Run `sinatra login` to try again. If your browser is on another computer (over SSH, say), run " +
|
|
187
|
+
"`sinatra login --token` instead.")), timeoutMs);
|
|
188
|
+
try {
|
|
189
|
+
const authorizeUrl = `${endpoints.authorize}?${new URLSearchParams({
|
|
190
|
+
response_type: "code",
|
|
191
|
+
client_id: endpoints.clientId,
|
|
192
|
+
redirect_uri: redirectUri,
|
|
193
|
+
code_challenge: challenge,
|
|
194
|
+
code_challenge_method: "S256",
|
|
195
|
+
state,
|
|
196
|
+
resource: endpoints.resource,
|
|
197
|
+
})}`;
|
|
198
|
+
if (deps.openBrowser) {
|
|
199
|
+
deps.out("Opening your browser to sign in to Sinatra. If it doesn't open, visit:\n");
|
|
200
|
+
deps.out(` ${authorizeUrl}\n`);
|
|
201
|
+
await deps.openBrowser(authorizeUrl);
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
deps.out("Open this URL in a browser on this computer to sign in to Sinatra:\n");
|
|
205
|
+
deps.out(` ${authorizeUrl}\n`);
|
|
206
|
+
}
|
|
207
|
+
deps.out(`Waiting for you to approve the Sinatra CLI in the browser. On another computer (over SSH), press Ctrl-C and run \`sinatra login --token\` instead.\n`);
|
|
208
|
+
const { code, res } = await callback;
|
|
209
|
+
let result = null;
|
|
210
|
+
try {
|
|
211
|
+
const exchanged = await postForm(fetchFn, endpoints.token, {
|
|
212
|
+
grant_type: "authorization_code",
|
|
213
|
+
code,
|
|
214
|
+
redirect_uri: redirectUri,
|
|
215
|
+
client_id: endpoints.clientId,
|
|
216
|
+
code_verifier: verifier,
|
|
217
|
+
resource: endpoints.resource,
|
|
218
|
+
});
|
|
219
|
+
result = exchanged.status === 200 ? signedIn(exchanged.body, endpoints.clientId, now()) : null;
|
|
220
|
+
if (!result)
|
|
221
|
+
throw new SignInError(refusal(errorCode(exchanged.body.error)));
|
|
222
|
+
return result;
|
|
223
|
+
}
|
|
224
|
+
finally {
|
|
225
|
+
if (result)
|
|
226
|
+
sendPage(res, 200, "Signed in to the Sinatra CLI", "You can close this tab and go back to your terminal.");
|
|
227
|
+
else
|
|
228
|
+
sendPage(res, 400, "Sign-in failed", "Go back to your terminal to see why.");
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
finally {
|
|
232
|
+
clearTimeout(timer);
|
|
233
|
+
server.close();
|
|
234
|
+
server.closeIdleConnections();
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* The `refresh_token` grant, with rotation: the new pair replaces the old, which is dead from now
|
|
239
|
+
* on. `invalid_grant` (expired, disconnected on the dashboard, or rotated by someone else) is a
|
|
240
|
+
* SignInError; any other failure is thrown as it is, and the saved tokens stay.
|
|
241
|
+
*/
|
|
242
|
+
export async function refreshSignIn(apiUrl, session, options = {}) {
|
|
243
|
+
const endpoints = oauthEndpoints(apiUrl);
|
|
244
|
+
const { status, body } = await postForm(options.fetch ?? globalThis.fetch, endpoints.token, {
|
|
245
|
+
grant_type: "refresh_token",
|
|
246
|
+
refresh_token: session.refreshToken,
|
|
247
|
+
client_id: session.clientId,
|
|
248
|
+
resource: endpoints.resource,
|
|
249
|
+
});
|
|
250
|
+
if (status === 200) {
|
|
251
|
+
const result = signedIn(body, session.clientId, (options.now ?? Date.now)());
|
|
252
|
+
if (result)
|
|
253
|
+
return result;
|
|
254
|
+
}
|
|
255
|
+
if (status === 400 && body.error === "invalid_grant")
|
|
256
|
+
throw new SignInEnded();
|
|
257
|
+
throw new Error(`Couldn't refresh the sign-in (HTTP ${status}${errorCode(body.error) ? `, ${errorCode(body.error)}` : ""}).`);
|
|
258
|
+
}
|
|
259
|
+
/** The refresh token is dead: the sign-in expired, or the CLI was disconnected on the dashboard. */
|
|
260
|
+
export class SignInEnded extends SignInError {
|
|
261
|
+
constructor() {
|
|
262
|
+
super("Your sign-in has ended: it expired, or the Sinatra CLI was disconnected on the dashboard. Run `sinatra login` to sign in again.");
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* RFC 7009: revoking the refresh token ends the whole grant, its access tokens included. One
|
|
267
|
+
* bounded attempt, for logout: an unreachable server mustn't hold up forgetting the sign-in.
|
|
268
|
+
*/
|
|
269
|
+
export async function revokeSignIn(apiUrl, session, fetchFn) {
|
|
270
|
+
const params = { token: session.refreshToken, token_type_hint: "refresh_token", client_id: session.clientId };
|
|
271
|
+
const { status } = await postForm(fetchFn ?? globalThis.fetch, oauthEndpoints(apiUrl).revoke, params, 10_000);
|
|
272
|
+
if (status !== 200)
|
|
273
|
+
throw new Error(`HTTP ${status}`);
|
|
274
|
+
}
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The saved login as a client's credentials. A personal access token is sent as it is. A browser
|
|
3
|
+
* sign-in's access token lasts an hour: it is refreshed shortly before it expires or when the API
|
|
4
|
+
* refuses it, and every refresh rotates the refresh token, so the new pair is saved at once.
|
|
5
|
+
*
|
|
6
|
+
* Several `sinatra` processes can share one config file (a `follow` in one terminal, `show` in
|
|
7
|
+
* another). A refresh token presented after another process rotated it would end the sign-in for
|
|
8
|
+
* all of them. So a renewal holds the config's lock file from reading the file to saving the new
|
|
9
|
+
* pair: a second process waits, then reads the file and takes the tokens the first one saved.
|
|
10
|
+
*/
|
|
11
|
+
import { refreshSignIn, SignInEnded } from "./oauth.js";
|
|
12
|
+
/** Refreshed this long before it expires, so a request never goes out with a token about to die. */
|
|
13
|
+
export const REFRESH_BEFORE_EXPIRY_MS = 60_000;
|
|
14
|
+
export function credentialsFor(config, deps) {
|
|
15
|
+
if (!config.oauth)
|
|
16
|
+
return { token: async () => config.token };
|
|
17
|
+
const now = deps.now ?? Date.now;
|
|
18
|
+
const refresh = deps.refresh ?? ((apiUrl, session) => refreshSignIn(apiUrl, session));
|
|
19
|
+
let current = { ...config, oauth: config.oauth };
|
|
20
|
+
let inFlight = null;
|
|
21
|
+
const expiring = (c) => Date.parse(c.oauth.expiresAt) - now() < REFRESH_BEFORE_EXPIRY_MS;
|
|
22
|
+
/** The same login, as another process may have saved it since: newer tokens, same API. */
|
|
23
|
+
async function savedElsewhere() {
|
|
24
|
+
const saved = await deps.store.read().catch(() => null);
|
|
25
|
+
if (!saved?.oauth || saved.apiUrl !== current.apiUrl || saved.oauth.refreshToken === current.oauth.refreshToken)
|
|
26
|
+
return null;
|
|
27
|
+
return { ...saved, oauth: saved.oauth };
|
|
28
|
+
}
|
|
29
|
+
async function renewNow() {
|
|
30
|
+
const newer = await savedElsewhere();
|
|
31
|
+
if (newer) {
|
|
32
|
+
current = newer;
|
|
33
|
+
if (!expiring(newer))
|
|
34
|
+
return newer.token;
|
|
35
|
+
}
|
|
36
|
+
const presented = current.oauth.refreshToken;
|
|
37
|
+
let next;
|
|
38
|
+
try {
|
|
39
|
+
next = await refresh(current.apiUrl, current.oauth);
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
if (!(error instanceof SignInEnded))
|
|
43
|
+
throw error;
|
|
44
|
+
// Refused: a process that ignored a stale lock may have rotated it. If so, its tokens stand.
|
|
45
|
+
const raced = await savedElsewhere();
|
|
46
|
+
if (raced) {
|
|
47
|
+
current = raced;
|
|
48
|
+
return raced.token;
|
|
49
|
+
}
|
|
50
|
+
// The dead sign-in is forgotten; a login saved since by another process is left alone.
|
|
51
|
+
const saved = await deps.store.read().catch(() => null);
|
|
52
|
+
if (saved?.oauth?.refreshToken === presented)
|
|
53
|
+
await deps.store.forget();
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
current = { ...current, token: next.token, oauth: next.oauth };
|
|
57
|
+
// Saved only while the file still holds this sign-in, keeping whatever else it says now (a
|
|
58
|
+
// default workspace set meanwhile). After a logout or another login, it isn't written back.
|
|
59
|
+
const saved = await deps.store.read().catch(() => null);
|
|
60
|
+
if (saved && saved.apiUrl === current.apiUrl && saved.oauth?.refreshToken === presented) {
|
|
61
|
+
current = { ...saved, token: next.token, oauth: next.oauth };
|
|
62
|
+
await deps.store.write(current);
|
|
63
|
+
}
|
|
64
|
+
return current.token;
|
|
65
|
+
}
|
|
66
|
+
function renew() {
|
|
67
|
+
inFlight ??= deps.store.lock(renewNow).finally(() => {
|
|
68
|
+
inFlight = null;
|
|
69
|
+
});
|
|
70
|
+
return inFlight;
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
token: async () => (expiring(current) ? renew() : current.token),
|
|
74
|
+
// A token other than the one refused means this process has already renewed it.
|
|
75
|
+
renew: async (rejected) => (rejected === current.token ? renew() : current.token),
|
|
76
|
+
};
|
|
77
|
+
}
|