@recoder.xyz/rithub 0.3.1 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recoder.xyz/rithub",
3
- "version": "0.3.1",
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/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) => `Deleted branch ${r.branch}.`);
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
 
@@ -20,8 +21,19 @@ const USAGE = `rit <command> [options] (alias: rithub)
20
21
  whoami print the account the saved/env token belongs to
21
22
  clone <owner/repo|repo> [dir] clone a repo (bare name = your own account)
22
23
  push [--private] [--name <name>] create the repo if missing (needs
23
- "write:user" for that), add a \`rithub\`
24
- remote, push the current branch
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]
25
37
 
26
38
  repo <cmd> create|list|view|fork|delete|rename|edit|archive|sync|sync-now|import
27
39
  issue <cmd> list|create|view|close|reopen|edit|comment
@@ -160,14 +172,46 @@ export async function main(argv, io) {
160
172
  throw new CliError(`unknown \`rit repo\` subcommand "${subcommand}"`, { code: "invalid_argument" });
161
173
  }
162
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
+
163
202
  if (command === "push") {
164
- const args = parseFlags(rest, { valueFlags: ["--name", "--api-url"], boolFlags: ["--private", "--json"] });
165
- 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);
166
205
  if (args.json) {
167
206
  io.out(JSON.stringify(result));
168
207
  } else {
169
208
  if (result.created) io.out(`Created ${result.owner}/${result.repo} on Rithub.`);
170
- io.out(`Pushed ${result.branch} -> ${result.html_url}`);
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
+ }
171
215
  }
172
216
  return 0;
173
217
  }
@@ -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 branch = currentBranch(io, cwd);
156
- if (!branch) throw new CliError("no commits yet -- commit something first", { code: "no_commits" });
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(session.token, ["push", "-u", "rithub", branch]);
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
  }