sinatra.dev 0.1.1 → 0.3.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 +38 -14
- package/dist/client.js +26 -1
- package/dist/commands.js +107 -32
- package/dist/config.js +81 -3
- package/dist/index.js +70 -11
- package/dist/oauth.js +274 -0
- package/dist/session.js +77 -0
- package/package.json +6 -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 **CLI & API**
|
|
30
|
+
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 same **CLI & API** 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,19 +59,23 @@ 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
|
|
62
|
+
sinatra tickets -q "flaky login" # open Linear and GitHub issues you could delegate
|
|
63
|
+
sinatra delegate ENG-123 # hand Sinatra a Linear or GitHub issue (owner/name#12, or its URL) as you
|
|
64
|
+
sinatra whoami # who you're logged in as, and your workspaces
|
|
45
65
|
sinatra workspace [<id>] # list workspaces, or set the default
|
|
46
|
-
sinatra logout # revoke the token and forget it
|
|
66
|
+
sinatra logout # end the sign-in (or revoke the token) and forget it
|
|
47
67
|
```
|
|
48
68
|
|
|
49
69
|
| Command | Options |
|
|
50
70
|
| --- | --- |
|
|
51
|
-
| `sinatra login` | `--api-url <url>`: another Sinatra API (https; plain http only for localhost); `-w, --workspace <id>`: the default workspace |
|
|
71
|
+
| `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
72
|
| `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
73
|
| `sinatra reply <task-id> "<message>"` | `-f, --file <path>` (repeatable), `-w`, `--timeout <minutes>`, `--no-wait`, `--json` (with `--no-wait`) |
|
|
54
74
|
| `sinatra show <task-id>` | `-w`, `--json` |
|
|
55
75
|
| `sinatra tasks` | `--status <status>`, `-n, --limit <n>` (1 to 100, default 20), `-w`, `--json` |
|
|
56
76
|
| `sinatra stop <task-id>` | `-w` |
|
|
77
|
+
| `sinatra tickets` | `-q, --query <text>`, `-r, --repo <owner/name>` (searched first), `-w`, `--json` |
|
|
78
|
+
| `sinatra delegate <ticket>` | `-w` |
|
|
57
79
|
| `sinatra whoami` | `--json` |
|
|
58
80
|
| `sinatra workspace [<id>]` | none |
|
|
59
81
|
| `sinatra logout` | none |
|
|
@@ -72,8 +94,9 @@ An option a command doesn't use is an error, not silently ignored.
|
|
|
72
94
|
- **Attachments:** `-f` attaches text files to a new task or a reply, up to 80KB together. Binary
|
|
73
95
|
files are refused.
|
|
74
96
|
- **Following:** after `start` or `reply`, the CLI prints what Sinatra posts until the turn is
|
|
75
|
-
done: Sinatra replied, or the task finished, failed, was cancelled, or paused.
|
|
76
|
-
|
|
97
|
+
done: Sinatra replied, or the task finished, failed, was cancelled, or paused. If the task is
|
|
98
|
+
queued because your workspace is running as many tasks at a time as its plan allows, the CLI
|
|
99
|
+
says so. It stops waiting after `--timeout` minutes
|
|
77
100
|
(30 by default); the task keeps going. Ctrl-C stops waiting too. After a `reply` to a task that
|
|
78
101
|
had already stopped, if Sinatra hasn't picked the message up within two minutes, the CLI says so
|
|
79
102
|
(exit 3) instead of reporting the previous turn's result.
|
|
@@ -85,9 +108,10 @@ An option a command doesn't use is an error, not silently ignored.
|
|
|
85
108
|
`show`, and `start` or `reply` with `--no-wait`.
|
|
86
109
|
- **Prompts vs commands:** a prompt that starts with a command word still starts a task, unless it
|
|
87
110
|
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
|
|
111
|
+
- **Logout:** `sinatra logout` ends the browser sign-in on Sinatra (or revokes the token you
|
|
112
|
+
pasted), then deletes the local file. If Sinatra can't be reached, the file is still deleted and
|
|
113
|
+
the CLI warns that the sign-in or token may still be active: disconnect or revoke it on the
|
|
114
|
+
**CLI & API** page.
|
|
91
115
|
- **Retries:** every request that changes something carries an idempotency key, so a retry after a
|
|
92
116
|
dropped connection never starts a second task or sends a message twice.
|
|
93
117
|
|
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;
|
|
@@ -77,5 +92,15 @@ export function createClient(options) {
|
|
|
77
92
|
followUp: (workspaceId, taskId, text) => request("POST", `/v1/workspaces/${workspaceId}/tasks/${taskId}/messages`, { text }),
|
|
78
93
|
messages: (workspaceId, taskId, after) => request("GET", `/v1/workspaces/${workspaceId}/tasks/${taskId}/messages${after ? `?after=${encodeURIComponent(after)}` : ""}`),
|
|
79
94
|
stopTask: (workspaceId, taskId) => request("POST", `/v1/workspaces/${workspaceId}/tasks/${taskId}/stop`),
|
|
95
|
+
searchTickets: (workspaceId, query = {}) => {
|
|
96
|
+
const params = new URLSearchParams();
|
|
97
|
+
if (query.q)
|
|
98
|
+
params.set("q", query.q);
|
|
99
|
+
if (query.repo)
|
|
100
|
+
params.set("repo", query.repo);
|
|
101
|
+
const qs = params.toString();
|
|
102
|
+
return request("GET", `/v1/workspaces/${workspaceId}/tickets${qs ? `?${qs}` : ""}`);
|
|
103
|
+
},
|
|
104
|
+
delegateTicket: (workspaceId, ticket) => request("POST", `/v1/workspaces/${workspaceId}/tickets/delegate`, ticket),
|
|
80
105
|
};
|
|
81
106
|
}
|
package/dist/commands.js
CHANGED
|
@@ -3,6 +3,18 @@ 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";
|
|
7
|
+
/**
|
|
8
|
+
* A ticket reference as a person pastes it: `ENG-123`, a Linear issue URL, `owner/name#12` or a
|
|
9
|
+
* GitHub issue URL. Null for anything else.
|
|
10
|
+
*/
|
|
11
|
+
export function parseTicket(ref) {
|
|
12
|
+
const github = ref.match(/^(?:https:\/\/github\.com\/)?([\w.-]+\/[\w.-]+)(?:#|\/issues\/)(\d+)\/?$/i);
|
|
13
|
+
if (github)
|
|
14
|
+
return { source: "github", repo: github[1], number: Number(github[2]) };
|
|
15
|
+
const linear = ref.match(/^(?:https:\/\/linear\.app\/[^/]+\/issue\/)?([a-z][a-z0-9]*-\d+)(?:\/[^/]*)?$/i);
|
|
16
|
+
return linear ? { source: "linear", id: linear[1].toUpperCase() } : null;
|
|
17
|
+
}
|
|
6
18
|
/** A mistake in how the CLI was called, or anything else to say before exiting with 1. */
|
|
7
19
|
export class UsageError extends Error {
|
|
8
20
|
}
|
|
@@ -37,8 +49,12 @@ export function parseCommand(positionals) {
|
|
|
37
49
|
case "logout":
|
|
38
50
|
case "whoami":
|
|
39
51
|
case "tasks":
|
|
52
|
+
case "tickets":
|
|
40
53
|
if (rest.length === 0)
|
|
41
54
|
return { name: first };
|
|
55
|
+
if (first === "login" && rest.some((word) => word.startsWith("sntr_"))) {
|
|
56
|
+
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.");
|
|
57
|
+
}
|
|
42
58
|
if (!prose)
|
|
43
59
|
return usage(`Usage: sinatra ${first}`);
|
|
44
60
|
break;
|
|
@@ -62,11 +78,20 @@ export function parseCommand(positionals) {
|
|
|
62
78
|
if (!prose || TASK_ID.test(rest[0]))
|
|
63
79
|
return usage('Usage: sinatra reply <task-id> "<message>"');
|
|
64
80
|
break;
|
|
81
|
+
case "delegate": {
|
|
82
|
+
const ticket = rest.length === 1 ? parseTicket(rest[0]) : null;
|
|
83
|
+
if (ticket)
|
|
84
|
+
return { name: "delegate", ticket };
|
|
85
|
+
if (!prose)
|
|
86
|
+
return usage("Usage: sinatra delegate <ticket> (ENG-123, owner/name#12, or the issue's URL)");
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
65
89
|
}
|
|
66
90
|
return { name: "start", prompt: positionals.join(" ").trim() };
|
|
67
91
|
}
|
|
68
92
|
const OPTIONS = {
|
|
69
93
|
repo: { type: "string", short: "r" },
|
|
94
|
+
query: { type: "string", short: "q" },
|
|
70
95
|
file: { type: "string", short: "f", multiple: true },
|
|
71
96
|
title: { type: "string", short: "t" },
|
|
72
97
|
workspace: { type: "string", short: "w" },
|
|
@@ -76,22 +101,39 @@ const OPTIONS = {
|
|
|
76
101
|
status: { type: "string" },
|
|
77
102
|
limit: { type: "string", short: "n" },
|
|
78
103
|
"api-url": { type: "string" },
|
|
104
|
+
token: { type: "boolean" },
|
|
105
|
+
"no-browser": { type: "boolean" },
|
|
79
106
|
version: { type: "boolean", short: "v" },
|
|
80
107
|
help: { type: "boolean", short: "h" },
|
|
81
108
|
};
|
|
82
109
|
/** The commands each option means something to; given to any other, it's a mistake. */
|
|
83
110
|
const APPLIES_TO = {
|
|
84
|
-
repo: ["start"],
|
|
111
|
+
repo: ["start", "tickets"],
|
|
112
|
+
query: ["tickets"],
|
|
85
113
|
file: ["start", "reply"],
|
|
86
114
|
title: ["start"],
|
|
87
|
-
workspace: ["start", "reply", "show", "tasks", "stop", "login"],
|
|
115
|
+
workspace: ["start", "reply", "show", "tasks", "stop", "tickets", "delegate", "login"],
|
|
88
116
|
"no-wait": ["start", "reply"],
|
|
89
117
|
timeout: ["start", "reply"],
|
|
90
|
-
json: ["whoami", "tasks", "show", "start", "reply"],
|
|
118
|
+
json: ["whoami", "tasks", "show", "start", "reply", "tickets"],
|
|
91
119
|
status: ["tasks"],
|
|
92
120
|
limit: ["tasks"],
|
|
93
121
|
"api-url": ["login"],
|
|
122
|
+
token: ["login"],
|
|
123
|
+
"no-browser": ["login"],
|
|
94
124
|
};
|
|
125
|
+
/**
|
|
126
|
+
* How `sinatra login` gets its credential. Asked for explicitly, that way; otherwise the browser
|
|
127
|
+
* at a terminal, and a pasted token when stdin is piped (`sinatra login < token-file`), which
|
|
128
|
+
* holds the token and nothing else.
|
|
129
|
+
*/
|
|
130
|
+
export function loginMode(inv, stdinIsTTY) {
|
|
131
|
+
if (inv.pasteToken)
|
|
132
|
+
return "paste";
|
|
133
|
+
if (inv.noBrowser)
|
|
134
|
+
return "browser";
|
|
135
|
+
return stdinIsTTY ? "browser" : "paste";
|
|
136
|
+
}
|
|
95
137
|
/** The command line, read and checked; anything it can't run is a UsageError. */
|
|
96
138
|
export function parseInvocation(argv) {
|
|
97
139
|
const { values, positionals } = (() => {
|
|
@@ -123,6 +165,9 @@ export function parseInvocation(argv) {
|
|
|
123
165
|
}
|
|
124
166
|
}
|
|
125
167
|
}
|
|
168
|
+
if (values.token && values["no-browser"]) {
|
|
169
|
+
throw new UsageError("--token pastes a token and --no-browser signs in through a browser: pick one.");
|
|
170
|
+
}
|
|
126
171
|
const wait = !values["no-wait"];
|
|
127
172
|
if (values.json && (command.name === "start" || command.name === "reply") && wait) {
|
|
128
173
|
throw new UsageError("--json with start or reply needs --no-wait: following prints the conversation as it comes.");
|
|
@@ -146,7 +191,10 @@ export function parseInvocation(argv) {
|
|
|
146
191
|
wait,
|
|
147
192
|
timeoutMs,
|
|
148
193
|
json: values.json ?? false,
|
|
194
|
+
pasteToken: values.token ?? false,
|
|
195
|
+
noBrowser: values["no-browser"] ?? false,
|
|
149
196
|
...(values.repo !== undefined ? { repo: values.repo } : {}),
|
|
197
|
+
...(values.query !== undefined ? { query: values.query } : {}),
|
|
150
198
|
...(values.title !== undefined ? { title: values.title } : {}),
|
|
151
199
|
...(values.workspace !== undefined ? { workspace: values.workspace } : {}),
|
|
152
200
|
...(values.status !== undefined ? { status: values.status } : {}),
|
|
@@ -219,23 +267,42 @@ export async function startTask(client, workspaceId, body, repos, notice) {
|
|
|
219
267
|
}
|
|
220
268
|
return { started: await client.startTask(workspaceId, body), repo: null };
|
|
221
269
|
}
|
|
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;
|
|
270
|
+
async function pastedToken(deps) {
|
|
229
271
|
// 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
|
|
272
|
+
deps.out(deps.apiUrl === DEFAULT_API_URL
|
|
231
273
|
? `Create a personal access token at ${DEFAULT_APP_URL}/login?returnTo=%2Ftokens, then paste it here.\n`
|
|
232
|
-
: "Create a personal access token
|
|
274
|
+
: "Create a personal access token under CLI & API in your Sinatra dashboard, then paste it here.\n");
|
|
233
275
|
const token = await deps.askSecret("Token (hidden): ");
|
|
234
276
|
if (!token)
|
|
235
277
|
throw new UsageError("No token given.");
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
278
|
+
return token;
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* `sinatra login`: sign in through the browser or read a pasted token, check it, pick the default
|
|
282
|
+
* workspace, save. A `--workspace` that isn't one of the account's workspaces is refused before
|
|
283
|
+
* anything is saved, so a script's typo leaves the previous login as it was.
|
|
284
|
+
*/
|
|
285
|
+
export async function login(deps) {
|
|
286
|
+
const { out } = deps;
|
|
287
|
+
const signedIn = deps.browser ? await deps.browser.signIn() : { token: await pastedToken(deps) };
|
|
288
|
+
let me;
|
|
289
|
+
let workspaceId;
|
|
290
|
+
try {
|
|
291
|
+
me = await deps.me(signedIn.token);
|
|
292
|
+
workspaceId = await loginWorkspace(me.workspaces, deps);
|
|
293
|
+
}
|
|
294
|
+
catch (error) {
|
|
295
|
+
if (signedIn.oauth)
|
|
296
|
+
await deps.browser?.discard(signedIn.oauth).catch(() => undefined);
|
|
297
|
+
throw error;
|
|
298
|
+
}
|
|
299
|
+
await deps.discardPrevious?.().catch(() => undefined);
|
|
300
|
+
await deps.save({
|
|
301
|
+
apiUrl: deps.apiUrl,
|
|
302
|
+
token: signedIn.token,
|
|
303
|
+
...(signedIn.oauth ? { oauth: signedIn.oauth } : {}),
|
|
304
|
+
...(workspaceId ? { workspaceId } : {}),
|
|
305
|
+
});
|
|
239
306
|
const name = me.user.githubLogin ? `@${me.user.githubLogin}` : me.user.name ?? me.user.id;
|
|
240
307
|
const workspace = me.workspaces.find((w) => w.id === workspaceId)?.name;
|
|
241
308
|
out(printable(`Logged in as ${name}${workspace ? `, workspace ${workspace}` : ""}.\n`));
|
|
@@ -248,7 +315,8 @@ async function loginWorkspace(workspaces, deps) {
|
|
|
248
315
|
if (chosen)
|
|
249
316
|
return chosen.id;
|
|
250
317
|
const yours = workspaces.map((w) => `${w.name} (${w.id})`).join(", ");
|
|
251
|
-
|
|
318
|
+
const whose = deps.browser ? "your" : "this token's";
|
|
319
|
+
throw new UsageError(printable(`${deps.workspace} isn't one of ${whose} workspaces${yours ? ` (${yours})` : ""}. Nothing was saved.`));
|
|
252
320
|
}
|
|
253
321
|
if (workspaces.length === 1)
|
|
254
322
|
return workspaces[0].id;
|
|
@@ -268,20 +336,24 @@ async function loginWorkspace(workspaces, deps) {
|
|
|
268
336
|
out("No default workspace saved; pass -w <id> to commands, or set one with `sinatra workspace <id>`.\n");
|
|
269
337
|
return undefined;
|
|
270
338
|
}
|
|
271
|
-
/** Where to make (or revoke) a token, for the API a config points at. */
|
|
339
|
+
/** Where to make (or revoke) a token, and disconnect a sign-in, for the API a config points at. */
|
|
272
340
|
export function tokensPage(apiUrl) {
|
|
273
|
-
return apiUrl === DEFAULT_API_URL ? `${DEFAULT_APP_URL}/tokens` : "your Sinatra dashboard's
|
|
341
|
+
return apiUrl === DEFAULT_API_URL ? `${DEFAULT_APP_URL}/tokens` : "your Sinatra dashboard's CLI & API page";
|
|
274
342
|
}
|
|
275
343
|
/**
|
|
276
|
-
* Revoking the saved
|
|
277
|
-
* up forgetting it here (a retry would only add to the wait).
|
|
344
|
+
* Revoking the saved credential at logout: one attempt, bounded, so an unreachable server can't
|
|
345
|
+
* hold up forgetting it here (a retry would only add to the wait). A browser sign-in revokes its
|
|
346
|
+
* refresh token, which ends the whole grant (its access token may already have expired); a
|
|
347
|
+
* personal access token revokes itself.
|
|
278
348
|
*/
|
|
279
349
|
export function revokeSavedToken(config, fetch) {
|
|
280
|
-
|
|
350
|
+
if (config.oauth)
|
|
351
|
+
return revokeSignIn(config.apiUrl, config.oauth, fetch);
|
|
352
|
+
return createClient({ apiUrl: config.apiUrl, token: config.token, timeoutMs: 10_000, attempts: 1, ...(fetch ? { fetch } : {}) }).revokeToken();
|
|
281
353
|
}
|
|
282
354
|
/**
|
|
283
|
-
* Logging out: revoke the saved
|
|
284
|
-
* token the server already rejects is as good as revoked; any other failure leaves it possibly
|
|
355
|
+
* Logging out: revoke the saved credential on the server, then forget it here whatever happened.
|
|
356
|
+
* A token the server already rejects is as good as revoked; any other failure leaves it possibly
|
|
285
357
|
* still working, which the person is told along with where to revoke it.
|
|
286
358
|
*/
|
|
287
359
|
export async function logout(deps) {
|
|
@@ -295,7 +367,7 @@ export async function logout(deps) {
|
|
|
295
367
|
await deps.forget();
|
|
296
368
|
return {
|
|
297
369
|
message: "Removed the damaged config.",
|
|
298
|
-
warning: `If it held a token, revoke it on ${tokensPage(DEFAULT_API_URL)} (or your dashboard's
|
|
370
|
+
warning: `If it held a token or a sign-in, revoke or disconnect it on ${tokensPage(DEFAULT_API_URL)} (or your dashboard's CLI & API page).`,
|
|
299
371
|
};
|
|
300
372
|
}
|
|
301
373
|
if (!config) {
|
|
@@ -313,6 +385,14 @@ export async function logout(deps) {
|
|
|
313
385
|
}
|
|
314
386
|
}
|
|
315
387
|
await deps.forget();
|
|
388
|
+
if (config.oauth) {
|
|
389
|
+
if (problem === null)
|
|
390
|
+
return { message: "Logged out; the sign-in is revoked." };
|
|
391
|
+
return {
|
|
392
|
+
message: "Logged out on this machine.",
|
|
393
|
+
warning: `Couldn't revoke the sign-in (${problem}), so it may still be active. Disconnect Sinatra CLI under Connected apps on ${tokensPage(config.apiUrl)}.`,
|
|
394
|
+
};
|
|
395
|
+
}
|
|
316
396
|
if (problem === null)
|
|
317
397
|
return { message: "Logged out; the token is revoked." };
|
|
318
398
|
return {
|
|
@@ -326,19 +406,12 @@ export function printable(text) {
|
|
|
326
406
|
// and bidirectional overrides, which can make printed text read differently than it is.
|
|
327
407
|
return text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f--]/g, "");
|
|
328
408
|
}
|
|
329
|
-
/** The running-task cap when the server doesn't say. */
|
|
330
|
-
const DEFAULT_RUNNING_CAP = "5";
|
|
331
409
|
export function classifyRefusal(error, context = {}) {
|
|
332
410
|
switch (error.code) {
|
|
333
411
|
case "invalid_token":
|
|
334
412
|
return { kind: context.during === "login" ? "token_rejected_at_login" : "token_invalid" };
|
|
335
413
|
case "not_found":
|
|
336
414
|
return { kind: context.during ? "task_api_off" : "not_found" };
|
|
337
|
-
case "too_many_running": {
|
|
338
|
-
const raw = error.detail.limit;
|
|
339
|
-
const limit = (typeof raw === "string" || typeof raw === "number") && /^\d+$/.test(String(raw)) ? String(raw) : DEFAULT_RUNNING_CAP;
|
|
340
|
-
return { kind: "too_many_running", limit };
|
|
341
|
-
}
|
|
342
415
|
case "unavailable":
|
|
343
416
|
if (typeof error.detail.taskId === "string")
|
|
344
417
|
return { kind: "created_not_started", taskId: error.detail.taskId };
|
|
@@ -359,13 +432,15 @@ export function explain(error, context = {}) {
|
|
|
359
432
|
case "task_api_off":
|
|
360
433
|
return "The task API isn't available for this account. Write to contact@sinatra.dev if you think it should be.";
|
|
361
434
|
case "not_found": return "No such task or workspace, or you're not a member of it.";
|
|
362
|
-
case "too_many_running": return `You already have ${refusal.limit} CLI, MCP or API tasks starting, running or queued in this workspace; wait for one to finish its turn.`;
|
|
363
435
|
case "created_not_started":
|
|
364
436
|
return `Task ${refusal.taskId} was created but Sinatra couldn't start it yet. Run \`sinatra reply ${refusal.taskId} "go"\` to start it (your prompt goes first).`;
|
|
365
437
|
case "message_saved_not_sent":
|
|
366
438
|
return "Sinatra saved your message but couldn't hand it over yet. Don't send it again: it goes out first with your next message to this task.";
|
|
367
439
|
case "unreachable": return "Sinatra couldn't be reached; try again shortly.";
|
|
368
440
|
}
|
|
441
|
+
// A refusal the server explained itself (delegation's are the dashboard's own words).
|
|
442
|
+
if (typeof error.detail.reason === "string")
|
|
443
|
+
return printable(error.detail.reason);
|
|
369
444
|
switch (refusal.code) {
|
|
370
445
|
case "invalid_prompt": return "The message is empty or too long.";
|
|
371
446
|
case "invalid_repo": return "That repository isn't connected to this workspace (see the dashboard's Repositories page).";
|
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,29 @@
|
|
|
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
|
+
* sinatra tickets -q "login" find open Linear and GitHub issues you could delegate
|
|
9
|
+
* sinatra delegate ENG-123 hand Sinatra an existing Linear or GitHub issue
|
|
8
10
|
* sinatra tasks | show <task> | stop <task> | whoami | workspace [id] | logout
|
|
9
11
|
*/
|
|
10
12
|
import { readFileSync } from "node:fs";
|
|
11
13
|
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";
|
|
14
|
+
import { explain, login, loginMode, logout, parseInvocation, printable, repoChoices, revokeSavedToken, startTask, UsageError, } from "./commands.js";
|
|
15
|
+
import { ConfigError, DEFAULT_API_URL, deleteConfig, readConfig, withConfigLock, writeConfig } from "./config.js";
|
|
14
16
|
import { AttachmentError, composePrompt, detectRepos, readAttachments } from "./context.js";
|
|
15
17
|
import { EXIT, followOutcome, followTask } from "./follow.js";
|
|
18
|
+
import { browserSignIn, openBrowser, revokeSignIn, SignInError } from "./oauth.js";
|
|
16
19
|
import { ask, askSecret } from "./prompt.js";
|
|
20
|
+
import { credentialsFor } from "./session.js";
|
|
17
21
|
const USAGE = `Usage:
|
|
18
|
-
sinatra login [--api-url <url>] [-w <id>]
|
|
19
|
-
|
|
22
|
+
sinatra login [--api-url <url>] [-w <id>] [--no-browser | --token]
|
|
23
|
+
Sign in through your browser (-w: the default workspace)
|
|
24
|
+
--no-browser Print the sign-in URL instead of opening it (the browser
|
|
25
|
+
must still be on this computer)
|
|
26
|
+
--token Paste a personal access token instead (also when stdin
|
|
27
|
+
is piped: sinatra login < token-file)
|
|
20
28
|
sinatra [start] "<what to do>" Start a task and follow it
|
|
21
29
|
-r, --repo <owner/name> Repository (default: this checkout's GitHub remote)
|
|
22
30
|
-f, --file <path> Attach a text file (repeatable, 80KB total)
|
|
@@ -30,9 +38,14 @@ const USAGE = `Usage:
|
|
|
30
38
|
sinatra tasks [--status <status>] [-n, --limit <n>] [--json]
|
|
31
39
|
List the workspace's recent tasks (20 unless -n)
|
|
32
40
|
sinatra stop <task-id> Stop a task's running turn
|
|
33
|
-
sinatra
|
|
41
|
+
sinatra tickets [-q <text>] [-r <owner/name>] [--json]
|
|
42
|
+
Open Linear and GitHub issues you could delegate: yours,
|
|
43
|
+
then the team's unassigned (-q: search, -r: repo first)
|
|
44
|
+
sinatra delegate <ticket> Hand Sinatra a Linear or GitHub issue as you: ENG-123,
|
|
45
|
+
owner/name#12, or the issue's URL
|
|
46
|
+
sinatra whoami [--json] Who you're logged in as, and your workspaces
|
|
34
47
|
sinatra workspace [<id>] List your workspaces, or make one the default
|
|
35
|
-
sinatra logout Revoke the saved token and forget it
|
|
48
|
+
sinatra logout Revoke the saved sign-in or token and forget it
|
|
36
49
|
sinatra -v, --version Print the CLI's version
|
|
37
50
|
|
|
38
51
|
-w, --workspace <id> Workspace for any task command (default: yours from
|
|
@@ -113,7 +126,7 @@ async function follow(client, workspaceId, taskId, options) {
|
|
|
113
126
|
taskId,
|
|
114
127
|
...options,
|
|
115
128
|
print,
|
|
116
|
-
onQueued: () => out("Queued:
|
|
129
|
+
onQueued: () => out("Queued: this workspace is running as many tasks at a time as its plan allows.\n"),
|
|
117
130
|
});
|
|
118
131
|
const { task } = result;
|
|
119
132
|
if (task.pullRequest)
|
|
@@ -177,13 +190,27 @@ async function main(argv) {
|
|
|
177
190
|
return;
|
|
178
191
|
case "login": {
|
|
179
192
|
const apiUrl = checkApiUrl(inv.apiUrl ?? DEFAULT_API_URL);
|
|
193
|
+
const browser = loginMode(inv, Boolean(process.stdin.isTTY)) === "browser";
|
|
180
194
|
return login({
|
|
181
195
|
apiUrl,
|
|
182
196
|
...(inv.workspace !== undefined ? { workspace: inv.workspace } : {}),
|
|
183
197
|
interactive: Boolean(process.stdin.isTTY),
|
|
198
|
+
...(browser
|
|
199
|
+
? {
|
|
200
|
+
browser: {
|
|
201
|
+
signIn: () => browserSignIn({ apiUrl, openBrowser: inv.noBrowser ? null : (url) => openBrowser(url), out }),
|
|
202
|
+
discard: (session) => revokeSignIn(apiUrl, session),
|
|
203
|
+
},
|
|
204
|
+
}
|
|
205
|
+
: {}),
|
|
184
206
|
askSecret: (question) => askSecret(question),
|
|
185
207
|
ask: (question) => ask(question),
|
|
186
208
|
me: (token) => whoAmI(createClient({ apiUrl, token }), apiUrl, "login"),
|
|
209
|
+
discardPrevious: async () => {
|
|
210
|
+
const previous = await readConfig().catch(() => null);
|
|
211
|
+
if (previous?.oauth)
|
|
212
|
+
await revokeSignIn(previous.apiUrl, previous.oauth);
|
|
213
|
+
},
|
|
187
214
|
save: (config) => writeConfig(config),
|
|
188
215
|
out,
|
|
189
216
|
});
|
|
@@ -201,7 +228,12 @@ async function main(argv) {
|
|
|
201
228
|
}
|
|
202
229
|
}
|
|
203
230
|
const config = await loggedIn();
|
|
204
|
-
const client = createClient(
|
|
231
|
+
const client = createClient({
|
|
232
|
+
apiUrl: config.apiUrl,
|
|
233
|
+
token: credentialsFor(config, {
|
|
234
|
+
store: { read: readConfig, write: (c) => writeConfig(c), forget: deleteConfig, lock: (fn) => withConfigLock(fn) },
|
|
235
|
+
}),
|
|
236
|
+
});
|
|
205
237
|
switch (command.name) {
|
|
206
238
|
case "whoami": {
|
|
207
239
|
const me = await whoAmI(client, config.apiUrl, "me");
|
|
@@ -219,7 +251,9 @@ async function main(argv) {
|
|
|
219
251
|
const chosen = me.workspaces.find((w) => w.id === command.workspaceId);
|
|
220
252
|
if (!chosen)
|
|
221
253
|
throw new UsageError(printable(`${command.workspaceId} isn't one of your workspaces; list them with \`sinatra workspace\`.`));
|
|
222
|
-
|
|
254
|
+
// Read again: checking the account may have refreshed the sign-in, rotating the tokens
|
|
255
|
+
// `config` holds, and writing those back would end it.
|
|
256
|
+
await writeConfig({ ...((await readConfig()) ?? config), workspaceId: chosen.id });
|
|
223
257
|
out(printable(`Default workspace: ${chosen.name} (${chosen.id}).\n`));
|
|
224
258
|
return;
|
|
225
259
|
}
|
|
@@ -264,6 +298,31 @@ async function main(argv) {
|
|
|
264
298
|
await client.stopTask(workspaceOf(config, inv.workspace), command.taskId);
|
|
265
299
|
out("Stop requested.\n");
|
|
266
300
|
return;
|
|
301
|
+
case "tickets": {
|
|
302
|
+
const result = await client.searchTickets(workspaceOf(config, inv.workspace), {
|
|
303
|
+
...(inv.query ? { q: inv.query } : {}),
|
|
304
|
+
...(inv.repo ? { repo: inv.repo } : {}),
|
|
305
|
+
});
|
|
306
|
+
if (inv.json)
|
|
307
|
+
return printJson(result);
|
|
308
|
+
for (const t of result.tickets) {
|
|
309
|
+
out(printable(`${t.identifier.padEnd(24)} ${t.title}${t.yours ? " (yours)" : ""}\n`));
|
|
310
|
+
}
|
|
311
|
+
if (!result.linear.connected)
|
|
312
|
+
out("Linear isn't connected to this workspace.\n");
|
|
313
|
+
else if (!result.linear.identityLinked)
|
|
314
|
+
out("Link your Linear account in Settings to see Linear issues.\n");
|
|
315
|
+
if (!result.github.connected)
|
|
316
|
+
out("GitHub isn't connected to this workspace.\n");
|
|
317
|
+
out(result.tickets.length === 0
|
|
318
|
+
? (inv.query ? "No open issues match.\n" : "No open issues to delegate.\n")
|
|
319
|
+
: "Delegate one with: sinatra delegate <ticket>\n");
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
case "delegate":
|
|
323
|
+
await client.delegateTicket(workspaceOf(config, inv.workspace), command.ticket);
|
|
324
|
+
out("Delegated. Sinatra answers on the issue; follow it there or with `sinatra tasks`.\n");
|
|
325
|
+
return;
|
|
267
326
|
case "reply": {
|
|
268
327
|
const workspaceId = workspaceOf(config, inv.workspace);
|
|
269
328
|
const text = composePrompt(command.text, await readAttachments(inv.files));
|
|
@@ -305,7 +364,7 @@ process.stdout.on("error", (error) => {
|
|
|
305
364
|
process.exit(process.exitCode ?? 0);
|
|
306
365
|
});
|
|
307
366
|
main(process.argv.slice(2)).catch((error) => {
|
|
308
|
-
if (error instanceof UsageError || error instanceof AttachmentError || error instanceof ConfigError) {
|
|
367
|
+
if (error instanceof UsageError || error instanceof AttachmentError || error instanceof ConfigError || error instanceof SignInError) {
|
|
309
368
|
process.stderr.write(`${error.message}\n`);
|
|
310
369
|
}
|
|
311
370
|
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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,14 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sinatra.dev",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Hand coding tasks to Sinatra from your terminal.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sinatra",
|
|
7
|
+
"sinatra.dev",
|
|
7
8
|
"cli",
|
|
9
|
+
"terminal",
|
|
8
10
|
"coding-agent",
|
|
11
|
+
"background-agent",
|
|
12
|
+
"ai-coding-agent",
|
|
9
13
|
"ai",
|
|
10
14
|
"github",
|
|
11
15
|
"pull-request",
|
|
16
|
+
"developer-tools",
|
|
12
17
|
"automation"
|
|
13
18
|
],
|
|
14
19
|
"homepage": "https://docs.sinatra.dev/docs/cli-and-api",
|