@recoder.xyz/rithub 0.3.0 → 0.3.2
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/bin/rithub.mjs +0 -0
- package/package.json +1 -1
- package/src/auth.mjs +20 -16
- package/src/branch.mjs +12 -1
- package/src/cli-work.mjs +4 -2
- package/src/cli.mjs +56 -10
- package/src/deviceLogin.mjs +80 -0
- package/src/http.mjs +7 -0
- package/src/issue.mjs +6 -1
- package/src/push-approval.mjs +97 -0
- package/src/repo.mjs +43 -5
package/bin/rithub.mjs
CHANGED
|
File without changes
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@recoder.xyz/rithub",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"description": "A gh-style CLI for Rithub: full gh parity -- issue/change(pr)/release/branch/label/milestone/key/secret/webhook/org/user/search/status/browse/api, plus login/clone/repo/push and `rit init`'s no-human agent signup. One command, zero deps.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
package/src/auth.mjs
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
// `rit login` / `rit logout` / `rit whoami`. Rithub has
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
1
|
+
// `rit login` / `rit logout` / `rit whoami`. 2026-12-01: Rithub now has a
|
|
2
|
+
// real device-authorization sign-in (apps/rithub-device-auth, see that
|
|
3
|
+
// app's README) -- a TTY with no `--token`/`RITHUB_TOKEN` runs the device
|
|
4
|
+
// flow (deviceLogin.mjs) instead of the old "paste a token" fallback.
|
|
5
|
+
// `--token`/`RITHUB_TOKEN` keep working unchanged (still the only path for
|
|
6
|
+
// a non-interactive caller -- an agent/CI session).
|
|
7
7
|
import { CliError, DEFAULT_API_URL } from "./init.mjs";
|
|
8
8
|
import { loadConfig, saveConfig, clearConfig, resolveSession } from "./config.mjs";
|
|
9
9
|
import { openUrl } from "./open-browser.mjs";
|
|
10
|
+
import { runDeviceLogin } from "./deviceLogin.mjs";
|
|
10
11
|
|
|
11
12
|
async function fetchUser(io, apiUrl, token) {
|
|
12
13
|
const res = await io.fetchImpl(`${apiUrl}/api/v1/user`, {
|
|
@@ -43,21 +44,24 @@ export async function runLogin(options, io) {
|
|
|
43
44
|
let token = options.token ?? io.env.RITHUB_TOKEN;
|
|
44
45
|
if (!token) {
|
|
45
46
|
const settingsUrl = `${apiUrl}/user/settings/applications`;
|
|
46
|
-
// write:user is not a typo for write:repository: Rithub's own
|
|
47
|
-
// POST /api/v1/user/repos (used by `rit repo create` and `rit push`'s
|
|
48
|
-
// auto-create) is gated on write:user, not write:repository -- confirmed
|
|
49
|
-
// live, 2026-11-30, from the server's own 403 scope error. A token
|
|
50
|
-
// missing it still works for `rit clone`/`rit push` to an existing repo.
|
|
51
|
-
const howTo = `Open ${settingsUrl}, generate a token (needs "read:user" and "write:repository" to clone/push; add "write:user" too if you want \`rit repo create\`/\`rit push\` to create repos), then paste it below.`;
|
|
52
47
|
if (!io.isTTY) {
|
|
53
48
|
throw new CliError(
|
|
54
|
-
`not an interactive terminal -- pass a token instead of
|
|
49
|
+
`not an interactive terminal -- pass a token instead of signing in: \`rit login --token <token>\` or \`RITHUB_TOKEN=<token> rit login\`. Get one at ${settingsUrl}.`,
|
|
55
50
|
{ code: "no_tty" }
|
|
56
51
|
);
|
|
57
52
|
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
53
|
+
if (options.pasteToken) {
|
|
54
|
+
// Explicit escape hatch (`rit login --paste-token`) back to the old
|
|
55
|
+
// paste-a-PAT flow, kept for a box with no outbound access to the
|
|
56
|
+
// device-flow endpoints or a locked-down headless display.
|
|
57
|
+
const howTo = `Open ${settingsUrl}, generate a token (needs "read:user" and "write:repository" to clone/push; add "write:user" too if you want \`rit repo create\`/\`rit push\` to create repos), then paste it below.`;
|
|
58
|
+
io.out(howTo);
|
|
59
|
+
io.openUrl?.(settingsUrl);
|
|
60
|
+
token = (await io.promptHidden("Token: ")).trim();
|
|
61
|
+
} else {
|
|
62
|
+
const device = await runDeviceLogin(io, apiUrl);
|
|
63
|
+
token = device.token;
|
|
64
|
+
}
|
|
61
65
|
}
|
|
62
66
|
token = token.trim();
|
|
63
67
|
if (!token) throw new CliError("no token given", { code: "invalid_argument" });
|
package/src/branch.mjs
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { CliError } from "./init.mjs";
|
|
4
4
|
import { resolveRepoArg, requireSession } from "./repo-arg.mjs";
|
|
5
5
|
import { apiCall, buildQuery } from "./http.mjs";
|
|
6
|
+
import { stageHeldDelete } from "./push-approval.mjs";
|
|
6
7
|
|
|
7
8
|
function repoPath(r, suffix) {
|
|
8
9
|
return `/api/v1/repos/${encodeURIComponent(r.owner)}/${encodeURIComponent(r.repo)}${suffix}`;
|
|
@@ -15,12 +16,22 @@ export async function runBranchList(options, io) {
|
|
|
15
16
|
return { owner: r.owner, repo: r.repo, branches: (body ?? []).map((b) => ({ name: b.name, protected: !!b.protected })) };
|
|
16
17
|
}
|
|
17
18
|
|
|
19
|
+
/** `rit branch delete`: a human delete behaves exactly as before. An
|
|
20
|
+
* agent-session delete (`RITHUB_AGENT_SESSION_ID` set) is held for a
|
|
21
|
+
* human to approve instead (RIT-ACT) -- see push-approval.mjs. */
|
|
18
22
|
export async function runBranchDelete(options, io) {
|
|
19
23
|
const r = resolveRepoArg(io, options);
|
|
20
24
|
requireSession(r);
|
|
25
|
+
|
|
26
|
+
const sessionId = io.env.RITHUB_AGENT_SESSION_ID || null;
|
|
27
|
+
if (sessionId) {
|
|
28
|
+
const approval = await stageHeldDelete(io, { session: r.session, owner: r.owner, repo: r.repo, branch: options.name, reason: options.reason, sessionId });
|
|
29
|
+
return { owner: r.owner, repo: r.repo, branch: options.name, deleted: false, held: true, approval };
|
|
30
|
+
}
|
|
31
|
+
|
|
21
32
|
const { status, body } = await apiCall(io, r.apiUrl, repoPath(r, `/branches/${encodeURIComponent(options.name)}`), { method: "DELETE" }, r.session.token);
|
|
22
33
|
if (status !== 204 && status !== 200) throw new CliError(`could not delete branch ${options.name} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "delete_failed" });
|
|
23
|
-
return { owner: r.owner, repo: r.repo, branch: options.name, deleted: true };
|
|
34
|
+
return { owner: r.owner, repo: r.repo, branch: options.name, deleted: true, held: false };
|
|
24
35
|
}
|
|
25
36
|
|
|
26
37
|
/** `rit branch protect <name|pattern> [--required-approvals <n>] [--no-force-push] [--no-delete-protected]`:
|
package/src/cli-work.mjs
CHANGED
|
@@ -192,10 +192,12 @@ async function runBranchCommand(rest, io) {
|
|
|
192
192
|
return printResult(io, a, await runBranchList({ ...a, cwd: io.cwd }, io), (r) => r.branches.map((b) => `${b.name}${b.protected ? " (protected)" : ""}`).join("\n"));
|
|
193
193
|
}
|
|
194
194
|
if (sub === "delete") {
|
|
195
|
-
const a = parseFlags(args, withRepoFlags());
|
|
195
|
+
const a = parseFlags(args, withRepoFlags({ valueFlags: ["--reason"] }));
|
|
196
196
|
const name = a._[0];
|
|
197
197
|
if (!name) throw new CliError("`rit branch delete` needs a name: `rit branch delete <name>`", { code: "invalid_argument" });
|
|
198
|
-
return printResult(io, a, await runBranchDelete({ ...a, name, cwd: io.cwd }, io), (r) =>
|
|
198
|
+
return printResult(io, a, await runBranchDelete({ ...a, name, cwd: io.cwd }, io), (r) =>
|
|
199
|
+
r.held ? `Held for human approval: ${r.approval.html_url} (approve with \`rit push approve ${r.approval.id}\`, deny with \`rit push deny ${r.approval.id}\`).` : `Deleted branch ${r.branch}.`
|
|
200
|
+
);
|
|
199
201
|
}
|
|
200
202
|
if (sub === "protect") {
|
|
201
203
|
const a = parseFlags(args, withRepoFlags({ valueFlags: ["--required-approvals"], boolFlags: ["--allow-push", "--allow-force-push"] }));
|
package/src/cli.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { runInit, runClaim, CliError, DEFAULT_API_URL } from "./init.mjs";
|
|
|
2
2
|
import { runLogin, runLogout, runWhoami } from "./auth.mjs";
|
|
3
3
|
import { runClone, runRepoCreate, runPush } from "./repo.mjs";
|
|
4
4
|
import { runWorkCommand, runRepoWorkCommand } from "./cli-work.mjs";
|
|
5
|
+
import { runPushApprove, runPushDeny, runPushStatus, runPushList } from "./push-approval.mjs";
|
|
5
6
|
|
|
6
7
|
const USAGE = `rit <command> [options] (alias: rithub)
|
|
7
8
|
|
|
@@ -10,16 +11,29 @@ const USAGE = `rit <command> [options] (alias: rithub)
|
|
|
10
11
|
this directory's git remote at it
|
|
11
12
|
claim --email <you@example.com> hands a human ownership of the account
|
|
12
13
|
\`init\` created in this directory
|
|
13
|
-
login [--token <token>] sign in: opens a browser
|
|
14
|
-
|
|
14
|
+
login [--token <token>] sign in: opens a browser for a real
|
|
15
|
+
device-code sign-in at ${DEFAULT_API_URL}/device
|
|
15
16
|
(or pass --token / set RITHUB_TOKEN --
|
|
16
|
-
required on a non-interactive session
|
|
17
|
+
required on a non-interactive session;
|
|
18
|
+
--paste-token falls back to pasting a
|
|
19
|
+
token from /user/settings/applications)
|
|
17
20
|
logout forget the saved token
|
|
18
21
|
whoami print the account the saved/env token belongs to
|
|
19
22
|
clone <owner/repo|repo> [dir] clone a repo (bare name = your own account)
|
|
20
23
|
push [--private] [--name <name>] create the repo if missing (needs
|
|
21
|
-
|
|
22
|
-
|
|
24
|
+
[--to <branch>] [--force] "write:user" for that), add a \`rithub\`
|
|
25
|
+
[--reason <text>] remote, push the current branch (or
|
|
26
|
+
\`--to\` another one). With
|
|
27
|
+
RITHUB_AGENT_SESSION_ID set, pushes
|
|
28
|
+
land on agent/<sessionId> automatically
|
|
29
|
+
-- parallel agent sessions never
|
|
30
|
+
collide. A \`--force\` push, or one to a
|
|
31
|
+
protected branch (the repo default, or
|
|
32
|
+
main/master, or RITHUB_PROTECTED_BRANCHES),
|
|
33
|
+
made with a session id set, is held for
|
|
34
|
+
a human to approve instead of landing.
|
|
35
|
+
push approve|deny|status <id> act on a held push/branch-delete
|
|
36
|
+
push list --owner <o> --repo <r> [--status pending|approved|denied]
|
|
23
37
|
|
|
24
38
|
repo <cmd> create|list|view|fork|delete|rename|edit|archive|sync|sync-now|import
|
|
25
39
|
issue <cmd> list|create|view|close|reopen|edit|comment
|
|
@@ -112,8 +126,8 @@ export async function main(argv, io) {
|
|
|
112
126
|
}
|
|
113
127
|
|
|
114
128
|
if (command === "login") {
|
|
115
|
-
const args = parseFlags(rest, { valueFlags: ["--token", "--api-url"], boolFlags: ["--json"] });
|
|
116
|
-
const result = await runLogin({ token: args.token, apiUrl: args.apiUrl }, io);
|
|
129
|
+
const args = parseFlags(rest, { valueFlags: ["--token", "--api-url"], boolFlags: ["--json", "--paste-token"] });
|
|
130
|
+
const result = await runLogin({ token: args.token, apiUrl: args.apiUrl, pasteToken: args.pasteToken }, io);
|
|
117
131
|
io.out(args.json ? JSON.stringify(result) : `Logged in as ${result.username} on ${result.apiUrl}.`);
|
|
118
132
|
return 0;
|
|
119
133
|
}
|
|
@@ -158,14 +172,46 @@ export async function main(argv, io) {
|
|
|
158
172
|
throw new CliError(`unknown \`rit repo\` subcommand "${subcommand}"`, { code: "invalid_argument" });
|
|
159
173
|
}
|
|
160
174
|
|
|
175
|
+
if (command === "push" && ["approve", "deny", "status", "list"].includes(rest[0])) {
|
|
176
|
+
const [subcommand, ...pushRest] = rest;
|
|
177
|
+
if (subcommand === "list") {
|
|
178
|
+
const args = parseFlags(pushRest, { valueFlags: ["--owner", "--repo", "--status", "--api-url"], boolFlags: ["--json"] });
|
|
179
|
+
const approvals = await runPushList({ owner: args.owner, repo: args.repo, status: args.status, apiUrl: args.apiUrl }, io);
|
|
180
|
+
if (args.json) io.out(JSON.stringify(approvals));
|
|
181
|
+
else if (!approvals.length) io.out("No held pushes.");
|
|
182
|
+
else for (const a of approvals) io.out(`${a.id} ${a.status.padEnd(9)} ${a.owner}/${a.repo} ${a.action}${a.forced ? "(force)" : ""} -> ${a.target_ref.replace("refs/heads/", "")} by ${a.requested_by}`);
|
|
183
|
+
return 0;
|
|
184
|
+
}
|
|
185
|
+
const args = parseFlags(pushRest, { valueFlags: ["--api-url"], boolFlags: ["--json"] });
|
|
186
|
+
const [id] = args._;
|
|
187
|
+
if (!id) throw new CliError(`\`rit push ${subcommand}\` needs an id: \`rit push ${subcommand} <id>\``, { code: "invalid_argument" });
|
|
188
|
+
const runner = { approve: runPushApprove, deny: runPushDeny, status: runPushStatus }[subcommand];
|
|
189
|
+
const result = await runner({ id, apiUrl: args.apiUrl }, io);
|
|
190
|
+
if (args.json) {
|
|
191
|
+
io.out(JSON.stringify(result));
|
|
192
|
+
} else if (subcommand === "approve") {
|
|
193
|
+
io.out(`Approved -- landed on ${result.owner}/${result.repo} ${result.target_ref.replace("refs/heads/", "")}.`);
|
|
194
|
+
} else if (subcommand === "deny") {
|
|
195
|
+
io.out(`Denied -- ${result.owner}/${result.repo} ${result.target_ref.replace("refs/heads/", "")} was never touched.`);
|
|
196
|
+
} else {
|
|
197
|
+
io.out(`${result.id} ${result.status} ${result.owner}/${result.repo} ${result.action} -> ${result.target_ref.replace("refs/heads/", "")} requested by ${result.requested_by}${result.decided_by ? ` -- decided by ${result.decided_by}` : ""}`);
|
|
198
|
+
}
|
|
199
|
+
return 0;
|
|
200
|
+
}
|
|
201
|
+
|
|
161
202
|
if (command === "push") {
|
|
162
|
-
const args = parseFlags(rest, { valueFlags: ["--name", "--api-url"], boolFlags: ["--private", "--json"] });
|
|
163
|
-
const result = await runPush({ name: args.name, private: args.private, apiUrl: args.apiUrl, cwd: io.cwd }, io);
|
|
203
|
+
const args = parseFlags(rest, { valueFlags: ["--name", "--to", "--reason", "--api-url"], boolFlags: ["--private", "--force", "--json"] });
|
|
204
|
+
const result = await runPush({ name: args.name, private: args.private, to: args.to, force: args.force, reason: args.reason, apiUrl: args.apiUrl, cwd: io.cwd }, io);
|
|
164
205
|
if (args.json) {
|
|
165
206
|
io.out(JSON.stringify(result));
|
|
166
207
|
} else {
|
|
167
208
|
if (result.created) io.out(`Created ${result.owner}/${result.repo} on Rithub.`);
|
|
168
|
-
|
|
209
|
+
if (result.held) {
|
|
210
|
+
io.out(`Held for human approval: ${result.approval.html_url}`);
|
|
211
|
+
io.out(`Approve with \`rit push approve ${result.approval.id}\`, deny with \`rit push deny ${result.approval.id}\`.`);
|
|
212
|
+
} else {
|
|
213
|
+
io.out(`Pushed ${result.branch} -> ${result.html_url}`);
|
|
214
|
+
}
|
|
169
215
|
}
|
|
170
216
|
return 0;
|
|
171
217
|
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// `rit login`'s real browser sign-in: RFC 8628-shaped device-authorization
|
|
2
|
+
// flow against the new server-side route this pass adds
|
|
3
|
+
// (apps/rithub-device-auth, proxied at https://rithub.dev/api/rit/device/*
|
|
4
|
+
// and https://rithub.dev/device -- see that app's README for the server
|
|
5
|
+
// side). Internally the server wraps Rithub's own OAuth2 "Rit CLI"
|
|
6
|
+
// application (confirmed registered 2026-11-18, client_id unchanged here),
|
|
7
|
+
// so the token this returns is a real Rithub OAuth2 access token, not a
|
|
8
|
+
// classic PAT -- it works identically against `/api/v1/*` either way
|
|
9
|
+
// (same header shape handled by fetchUser in auth.mjs: `Authorization:
|
|
10
|
+
// token <value>` -- Gitea accepts an OAuth2 access token there too).
|
|
11
|
+
import { CliError } from "./init.mjs";
|
|
12
|
+
|
|
13
|
+
const POLL_FLOOR_MS = 2000; // never hammer the server even if the returned interval is 0/missing
|
|
14
|
+
|
|
15
|
+
function sleep(ms) {
|
|
16
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function postJson(io, apiUrl, path, json) {
|
|
20
|
+
const res = await io.fetchImpl(`${apiUrl}${path}`, {
|
|
21
|
+
method: "POST",
|
|
22
|
+
headers: { accept: "application/json", "content-type": "application/json", "user-agent": "rithub-cli" },
|
|
23
|
+
body: JSON.stringify(json ?? {}),
|
|
24
|
+
});
|
|
25
|
+
const text = await res.text();
|
|
26
|
+
let body = null;
|
|
27
|
+
try {
|
|
28
|
+
body = text ? JSON.parse(text) : null;
|
|
29
|
+
} catch {
|
|
30
|
+
body = null;
|
|
31
|
+
}
|
|
32
|
+
return { status: res.status, body };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Starts the device flow: prints the code + URL, best-effort opens the
|
|
36
|
+
* browser, then polls until the human approves (or the code expires / is
|
|
37
|
+
* denied). Returns the access token on success; throws CliError otherwise.
|
|
38
|
+
* `io.sleep` is honored if a caller (tests) supplies one, so this never
|
|
39
|
+
* needs a real wall-clock wait under test. */
|
|
40
|
+
export async function runDeviceLogin(io, apiUrl) {
|
|
41
|
+
const { status, body } = await postJson(io, apiUrl, "/api/rit/device/code", {});
|
|
42
|
+
if (status !== 200 || !body?.device_code || !body?.user_code) {
|
|
43
|
+
throw new CliError(
|
|
44
|
+
`could not start device sign-in against ${apiUrl} (HTTP ${status}): ${body?.message ?? "unknown error"}. Pass a token instead: \`rit login --token <token>\` (get one at ${apiUrl}/user/settings/applications).`,
|
|
45
|
+
{ code: "device_flow_unavailable" }
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const verificationUrl = body.verification_uri_complete ?? body.verification_uri;
|
|
50
|
+
io.out(`First, copy your code: ${body.user_code}`);
|
|
51
|
+
io.out(`Then open this URL in your browser: ${body.verification_uri}`);
|
|
52
|
+
io.openUrl?.(verificationUrl); // best-effort; the code + URL above are already printed either way
|
|
53
|
+
|
|
54
|
+
const intervalMs = Math.max(POLL_FLOOR_MS, (body.interval ?? 5) * 1000);
|
|
55
|
+
const deadline = (io.now?.() ?? Date.now()) + (body.expires_in ?? 600) * 1000;
|
|
56
|
+
let currentIntervalMs = intervalMs;
|
|
57
|
+
|
|
58
|
+
while ((io.now?.() ?? Date.now()) < deadline) {
|
|
59
|
+
await (io.sleep ?? sleep)(currentIntervalMs);
|
|
60
|
+
const poll = await postJson(io, apiUrl, "/api/rit/device/token", { device_code: body.device_code });
|
|
61
|
+
const outcome = poll.body?.error ?? (poll.status === 200 && poll.body?.access_token ? null : "unknown_error");
|
|
62
|
+
|
|
63
|
+
if (poll.status === 200 && poll.body?.access_token) {
|
|
64
|
+
return { token: poll.body.access_token, scope: poll.body.scope ?? null };
|
|
65
|
+
}
|
|
66
|
+
if (outcome === "authorization_pending") continue;
|
|
67
|
+
if (outcome === "slow_down") {
|
|
68
|
+
currentIntervalMs += 5000;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (outcome === "expired_token") {
|
|
72
|
+
throw new CliError("the sign-in code expired before it was approved -- run `rit login` again.", { code: "device_flow_expired" });
|
|
73
|
+
}
|
|
74
|
+
if (outcome === "access_denied") {
|
|
75
|
+
throw new CliError("sign-in was denied in the browser.", { code: "device_flow_denied" });
|
|
76
|
+
}
|
|
77
|
+
throw new CliError(`device sign-in failed (HTTP ${poll.status}): ${poll.body?.message ?? outcome ?? "unknown error"}`, { code: "device_flow_error" });
|
|
78
|
+
}
|
|
79
|
+
throw new CliError("the sign-in code expired before it was approved -- run `rit login` again.", { code: "device_flow_expired" });
|
|
80
|
+
}
|
package/src/http.mjs
CHANGED
|
@@ -33,10 +33,17 @@ export async function apiCall(io, apiUrl, path, init, token) {
|
|
|
33
33
|
* parsing attempt -- for endpoints that answer with a diff/patch, not JSON
|
|
34
34
|
* (`rit change diff`). */
|
|
35
35
|
export async function apiCallRaw(io, apiUrl, path, init, token) {
|
|
36
|
+
// Bug found + fixed 2026-12-01: `init.headers` (e.g. runApi's
|
|
37
|
+
// `content-type: application/json` for a PATCH/POST body) was built by
|
|
38
|
+
// the caller but never actually merged in here, so `rit api` with
|
|
39
|
+
// `--method PATCH`/`--input` sent no Content-Type at all -- confirmed
|
|
40
|
+
// live against rithub.dev: the server answered a 422 "Unsupported
|
|
41
|
+
// Content-Type" instead of applying the PATCH.
|
|
36
42
|
const headers = {
|
|
37
43
|
accept: init?.accept ?? "*/*",
|
|
38
44
|
"user-agent": "rithub-cli",
|
|
39
45
|
...(token ? { authorization: `token ${token}` } : {}),
|
|
46
|
+
...(init?.headers ?? {}),
|
|
40
47
|
};
|
|
41
48
|
const res = await io.fetchImpl(`${apiUrl}${path}`, { ...init, headers });
|
|
42
49
|
const text = await res.text();
|
package/src/issue.mjs
CHANGED
|
@@ -43,7 +43,12 @@ async function setIssueState(options, io, state) {
|
|
|
43
43
|
const r = resolveRepoArg(io, options);
|
|
44
44
|
requireSession(r);
|
|
45
45
|
const { status, body } = await apiCall(io, r.apiUrl, issuesPath(r, `/${options.number}`), { method: "PATCH", body: JSON.stringify({ state }) }, r.session.token);
|
|
46
|
-
|
|
46
|
+
// Confirmed live 2026-12-01 against this engine build: a state-only PATCH
|
|
47
|
+
// on /issues/{number} answers 201, not the 200 every other issue PATCH
|
|
48
|
+
// (e.g. runIssueEdit below) returns -- the state change itself lands
|
|
49
|
+
// correctly either way (re-verified by re-fetching the issue), the status
|
|
50
|
+
// code was just the wrong thing to gate on.
|
|
51
|
+
if (status !== 200 && status !== 201) throw new CliError(`could not ${state === "closed" ? "close" : "reopen"} issue #${options.number} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "update_failed" });
|
|
47
52
|
return { owner: r.owner, repo: r.repo, number: options.number, state: body.state };
|
|
48
53
|
}
|
|
49
54
|
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Agent push approval (RIT-ACT): a push made with an agent-session token
|
|
2
|
+
// (`RITHUB_AGENT_SESSION_ID` set) that would be a force-push, a branch
|
|
3
|
+
// delete, or a push to a protected branch is held by the `rithub-approvals`
|
|
4
|
+
// service (apps/rithub-approvals) instead of landing directly. Human
|
|
5
|
+
// pushes (no session id set) are completely unaffected -- see runPush in
|
|
6
|
+
// src/repo.mjs and runBranchDelete in src/branch.mjs, which only call into
|
|
7
|
+
// this module when a session id is present.
|
|
8
|
+
import { CliError } from "./init.mjs";
|
|
9
|
+
import { apiCall } from "./http.mjs";
|
|
10
|
+
import { gitAuthedArgs } from "./repo.mjs";
|
|
11
|
+
import { resolveSession } from "./config.mjs";
|
|
12
|
+
|
|
13
|
+
/** Default protected-branch set an agent-session push is held against when
|
|
14
|
+
* it isn't an explicit `--force`: the repo's own default branch plus the
|
|
15
|
+
* two common defaults, so a brand-new repo is covered even before a human
|
|
16
|
+
* has configured `rit branch protect` on it. Overridable per-invocation
|
|
17
|
+
* (`RITHUB_PROTECTED_BRANCHES=main,release/*`) for repos with a different
|
|
18
|
+
* convention -- comma-separated exact names (no globbing here; use
|
|
19
|
+
* `rit branch protect` for glob-based protection at the engine level,
|
|
20
|
+
* which is a separate, already-shipped feature this one layers on top of). */
|
|
21
|
+
export function protectedBranches(io, defaultBranch) {
|
|
22
|
+
const configured = io.env.RITHUB_PROTECTED_BRANCHES;
|
|
23
|
+
const set = new Set((configured ? configured.split(",") : ["main", "master"]).map((s) => s.trim()).filter(Boolean));
|
|
24
|
+
if (defaultBranch) set.add(defaultBranch);
|
|
25
|
+
return set;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function approvalsCall(io, apiUrl, path, init, token) {
|
|
29
|
+
const headers = { ...(init?.headers ?? {}), ...(token ? { authorization: `Bearer ${token}` } : {}) };
|
|
30
|
+
const { status, body } = await apiCall(io, apiUrl, `/approvals/api${path}`, { ...init, headers }, undefined);
|
|
31
|
+
return { status, body };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Stages the local HEAD onto `refs/pending/<id>` (an ordinary, always-
|
|
35
|
+
* allowed git push -- never a bespoke transport) and registers + confirms
|
|
36
|
+
* the approval. Returns the created approval record. Throws (and best-
|
|
37
|
+
* effort cancels the half-made record) if the staging push itself fails. */
|
|
38
|
+
export async function stageHeldPush(io, { session, cwd, owner, repo, cloneUrl, branch, forced, reason, sessionId }) {
|
|
39
|
+
const created = await approvalsCall(io, session.apiUrl, "/create", { method: "POST", body: JSON.stringify({ owner, repo, action: "push", branch, forced, reason, session_id: sessionId }) }, session.token);
|
|
40
|
+
if (created.status !== 201) throw new CliError(`could not register the held push (HTTP ${created.status}): ${created.body?.error ?? "unknown error"}`, { code: "approval_failed" });
|
|
41
|
+
const approval = created.body;
|
|
42
|
+
|
|
43
|
+
const pushArgs = gitAuthedArgs(session.token, ["push", cloneUrl, `HEAD:${approval.pending_ref}`]);
|
|
44
|
+
const pushResult = io.run("git", pushArgs, cwd);
|
|
45
|
+
if (!pushResult.ok) {
|
|
46
|
+
await approvalsCall(io, session.apiUrl, `/${approval.id}/cancel`, { method: "POST" }, session.token).catch(() => {});
|
|
47
|
+
throw new CliError(`could not stage the held push: ${pushResult.output.slice(-500)}`, { code: "git_failed" });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const newrev = io.run("git", ["rev-parse", "HEAD"], cwd);
|
|
51
|
+
const confirmed = await approvalsCall(io, session.apiUrl, `/${approval.id}/confirm`, { method: "POST", body: JSON.stringify({ newrev: newrev.ok ? newrev.output.trim() : undefined }) }, session.token);
|
|
52
|
+
if (confirmed.status !== 200) throw new CliError(`staged but could not confirm the held push (HTTP ${confirmed.status}): ${confirmed.body?.error ?? "unknown error"}`, { code: "approval_failed" });
|
|
53
|
+
return confirmed.body;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Registers a held branch delete -- no staging push needed, the delete
|
|
57
|
+
* intent is the whole action. */
|
|
58
|
+
export async function stageHeldDelete(io, { session, owner, repo, branch, reason, sessionId }) {
|
|
59
|
+
const created = await approvalsCall(io, session.apiUrl, "/create", { method: "POST", body: JSON.stringify({ owner, repo, action: "delete", branch, reason, session_id: sessionId }) }, session.token);
|
|
60
|
+
if (created.status !== 201) throw new CliError(`could not register the held delete (HTTP ${created.status}): ${created.body?.error ?? "unknown error"}`, { code: "approval_failed" });
|
|
61
|
+
return created.body;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function runPushApprove(options, io) {
|
|
65
|
+
const session = requireLoggedIn(options, io);
|
|
66
|
+
const { status, body } = await approvalsCall(io, session.apiUrl, `/${options.id}/approve`, { method: "POST" }, session.token);
|
|
67
|
+
if (status !== 200) throw new CliError(`could not approve ${options.id} (HTTP ${status}): ${body?.error ?? "unknown error"}`, { code: "approve_failed" });
|
|
68
|
+
return body;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function runPushDeny(options, io) {
|
|
72
|
+
const session = requireLoggedIn(options, io);
|
|
73
|
+
const { status, body } = await approvalsCall(io, session.apiUrl, `/${options.id}/deny`, { method: "POST" }, session.token);
|
|
74
|
+
if (status !== 200) throw new CliError(`could not deny ${options.id} (HTTP ${status}): ${body?.error ?? "unknown error"}`, { code: "deny_failed" });
|
|
75
|
+
return body;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function runPushStatus(options, io) {
|
|
79
|
+
const session = requireLoggedIn(options, io);
|
|
80
|
+
const { status, body } = await approvalsCall(io, session.apiUrl, `/${options.id}`, { method: "GET" }, session.token);
|
|
81
|
+
if (status !== 200) throw new CliError(`could not look up ${options.id} (HTTP ${status}): ${body?.error ?? "unknown error"}`, { code: "network_error" });
|
|
82
|
+
return body;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function runPushList(options, io) {
|
|
86
|
+
const session = requireLoggedIn(options, io);
|
|
87
|
+
if (!options.owner || !options.repo) throw new CliError("`rit push list` needs --owner and --repo", { code: "invalid_argument" });
|
|
88
|
+
const { status, body } = await approvalsCall(io, session.apiUrl, `/list?owner=${encodeURIComponent(options.owner)}&repo=${encodeURIComponent(options.repo)}${options.status ? `&status=${encodeURIComponent(options.status)}` : ""}`, { method: "GET" }, session.token);
|
|
89
|
+
if (status !== 200) throw new CliError(`could not list held pushes (HTTP ${status}): ${body?.error ?? "unknown error"}`, { code: "network_error" });
|
|
90
|
+
return body.approvals;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function requireLoggedIn(options, io) {
|
|
94
|
+
const session = resolveSession(io, { apiUrl: options.apiUrl });
|
|
95
|
+
if (!session) throw new CliError("not logged in -- run `rit login` first", { code: "not_logged_in" });
|
|
96
|
+
return session;
|
|
97
|
+
}
|
package/src/repo.mjs
CHANGED
|
@@ -4,6 +4,11 @@
|
|
|
4
4
|
// rather than re-implementing them.
|
|
5
5
|
import { CliError, setGitRemote, currentBranch } from "./init.mjs";
|
|
6
6
|
import { resolveSession } from "./config.mjs";
|
|
7
|
+
// push-approval.mjs also imports gitAuthedArgs from this file -- a
|
|
8
|
+
// circular import, but a safe one: both sides only reference the other's
|
|
9
|
+
// export from inside a function body, never at module-evaluation time, so
|
|
10
|
+
// Node's ESM loader resolves it with no ordering issue.
|
|
11
|
+
import { stageHeldPush, protectedBranches } from "./push-approval.mjs";
|
|
7
12
|
|
|
8
13
|
const NAME_RE = /^[A-Za-z0-9._-]{1,100}$/;
|
|
9
14
|
|
|
@@ -123,7 +128,18 @@ export async function runRepoCreate(options, io) {
|
|
|
123
128
|
* the current directory's name), points a `rithub` remote at it (a
|
|
124
129
|
* separate remote from `origin` on purpose -- a checkout that already has
|
|
125
130
|
* a GitHub `origin` must not lose it), and pushes the current branch with
|
|
126
|
-
* `-u`.
|
|
131
|
+
* `-u`.
|
|
132
|
+
*
|
|
133
|
+
* Agent-session isolation + push approval (RIT-ACT, no change for a human
|
|
134
|
+
* push -- i.e. `RITHUB_AGENT_SESSION_ID` unset -- which still does exactly
|
|
135
|
+
* what it always did): when `RITHUB_AGENT_SESSION_ID` is set, the push
|
|
136
|
+
* target is automatically `agent/<sessionId>` instead of the local branch
|
|
137
|
+
* name, so two agent sessions pushing from the same token can never
|
|
138
|
+
* collide on the same ref -- unless `--to <branch>` explicitly overrides
|
|
139
|
+
* it. A push that is `--force`, or whose resolved target is a protected
|
|
140
|
+
* branch (the repo's default branch, or `main`/`master`, or
|
|
141
|
+
* `RITHUB_PROTECTED_BRANCHES`), is held for a human to approve instead of
|
|
142
|
+
* landing directly -- see push-approval.mjs. */
|
|
127
143
|
export async function runPush(options, io) {
|
|
128
144
|
const cwd = options.cwd ?? io.cwd;
|
|
129
145
|
const session = resolveSession(io, { apiUrl: options.apiUrl });
|
|
@@ -152,12 +168,34 @@ export async function runPush(options, io) {
|
|
|
152
168
|
}
|
|
153
169
|
|
|
154
170
|
setGitRemote(io, cwd, repoInfo.clone_url, "rithub");
|
|
155
|
-
const
|
|
156
|
-
if (!
|
|
171
|
+
const localBranch = currentBranch(io, cwd);
|
|
172
|
+
if (!localBranch) throw new CliError("no commits yet -- commit something first", { code: "no_commits" });
|
|
173
|
+
|
|
174
|
+
const sessionId = io.env.RITHUB_AGENT_SESSION_ID || null;
|
|
175
|
+
const targetBranch = options.to || (sessionId ? `agent/${sessionId}` : localBranch);
|
|
176
|
+
const needsApproval = Boolean(sessionId) && (Boolean(options.force) || protectedBranches(io, repoInfo.default_branch).has(targetBranch));
|
|
177
|
+
|
|
178
|
+
if (needsApproval) {
|
|
179
|
+
const approval = await stageHeldPush(io, {
|
|
180
|
+
session,
|
|
181
|
+
cwd,
|
|
182
|
+
owner: session.username,
|
|
183
|
+
repo: name,
|
|
184
|
+
cloneUrl: repoInfo.clone_url,
|
|
185
|
+
branch: targetBranch,
|
|
186
|
+
forced: !!options.force,
|
|
187
|
+
reason: options.reason,
|
|
188
|
+
sessionId,
|
|
189
|
+
});
|
|
190
|
+
return { owner: session.username, repo: name, branch: targetBranch, created: lookup.status === 404, html_url: repoInfo.html_url, held: true, approval };
|
|
191
|
+
}
|
|
157
192
|
|
|
158
|
-
const pushArgs = gitAuthedArgs(
|
|
193
|
+
const pushArgs = gitAuthedArgs(
|
|
194
|
+
session.token,
|
|
195
|
+
["push", ...(options.force ? ["--force"] : []), "-u", "rithub", targetBranch === localBranch ? localBranch : `${localBranch}:${targetBranch}`]
|
|
196
|
+
);
|
|
159
197
|
const result = io.run("git", pushArgs, cwd);
|
|
160
198
|
if (!result.ok) throw new CliError(`git push failed: ${result.output.slice(-500)}`, { code: "git_failed" });
|
|
161
199
|
|
|
162
|
-
return { owner: session.username, repo: name, branch, created: lookup.status === 404, html_url: repoInfo.html_url };
|
|
200
|
+
return { owner: session.username, repo: name, branch: targetBranch, created: lookup.status === 404, html_url: repoInfo.html_url, held: false };
|
|
163
201
|
}
|