@recoder.xyz/rithub 0.3.2 → 0.3.4

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 CHANGED
@@ -16,7 +16,7 @@ directly. The package stays scoped, but it installs **two** bin names:
16
16
  `rit` and `rithub` — same binary, either one works.)
17
17
 
18
18
  ```
19
- rit login # paste a token from Settings -> Applications
19
+ rit login # opens a browser for a real device-code sign-in
20
20
  rit whoami
21
21
  rit clone homeplan # bare name = your own account
22
22
  rit clone caelum0x/homeplan # or owner/repo, for any repo you can see
@@ -25,17 +25,31 @@ rit push # creates the repo on Rithub if missing, then pus
25
25
  rit logout
26
26
  ```
27
27
 
28
- Rithub has no OAuth2 device-code flow to log in with (confirmed live:
29
- `https://rithub.dev/login/device/code` is a plain 404 -- a real device
30
- flow needs a server-side route that doesn't exist yet; see "Server change
31
- this would need" below). `rit login` with no `--token` falls back to
32
- opening `https://rithub.dev/user/settings/applications` in the real
33
- browser (best-effort -- still prints the URL either way) and reading a
34
- pasted personal access token back, hidden input, never echoed. The token
35
- is validated against the real account (`GET /api/v1/user`) before
36
- anything is saved to `~/.config/rithub/config.json` (written `0600`).
37
-
38
- That prompt only happens at a real TTY. Run `rit login` with no
28
+ `rit login` with no `--token` runs a real RFC-8628-shaped device-code sign-in
29
+ (`https://rithub.dev/device`): it prints a short code, opens the browser
30
+ (best-effort -- still prints the URL either way), and polls until you
31
+ confirm there. The token is validated against the real account
32
+ (`GET /api/v1/user`) before anything is saved to
33
+ `~/.config/rithub/config.json` (written `0600`). `--paste-token` falls
34
+ back to the older "copy a token from Settings -> Applications" flow for a
35
+ box with no outbound access to the sign-in endpoints.
36
+
37
+ **Agent identity, enforced at sign-in, not opt-in (2026-12-01):** every
38
+ device sign-in defaults to an **agent** credential -- a force-push, a
39
+ branch delete, or a push to a protected branch made with it is held for a
40
+ human to approve at `https://rithub.dev/approvals`, even with plain `git`,
41
+ even if that token never runs through `rit` at all. A human signing in
42
+ for themselves unticks "this is me" on the `/device` page to get the
43
+ old, unmarked, behaves-exactly-like-before personal token. `rit login
44
+ --agent` removes that choice entirely for a scripted/CI caller where no
45
+ human will be looking at the page. A one-click **"New agent token"**
46
+ button at `https://rithub.dev/user/settings/applications` ("Agent tokens"
47
+ panel) mints one without any device flow at all, and the same panel lists
48
+ every agent-identity token for one-click revoke (which stops that
49
+ credential from pushing anything through Rithub's git-smart-HTTP gateway
50
+ from then on).
51
+
52
+ That device-flow prompt only happens at a real TTY. Run `rit login` with no
39
53
  `--token`/`RITHUB_TOKEN` from a non-interactive session -- an agent, CI,
40
54
  anything with stdin open but nobody there to answer it -- and it fails
41
55
  immediately with a clear message instead of hanging forever (confirmed
@@ -125,7 +139,7 @@ The original surface (unchanged):
125
139
  ```
126
140
  rit init [--repo <name>] [--api-url <url>] [--json]
127
141
  rit claim --email <you@example.com> [--json]
128
- rit login [--token <token>] [--api-url <url>] [--json]
142
+ rit login [--token <token>] [--agent] [--paste-token] [--api-url <url>] [--json]
129
143
  rit logout [--json]
130
144
  rit whoami [--json]
131
145
  rit clone <owner/repo|repo> [dir] [--json]
@@ -196,13 +210,16 @@ pretending to search and silently returning nothing.
196
210
 
197
211
  ## Server change this would need
198
212
 
199
- A real browser/device sign-in (poll until approved, no pasted token) --
200
- what `rit login` falls back from -- needs a device-authorization-grant
201
- route added server-side (e.g. the standard `POST /login/oauth/device` +
202
- `POST /login/oauth/token` pair with `device_code`/`user_code` polling).
203
- That route doesn't exist on rithub.dev today; `rit login`'s browser +
204
- paste flow is the closest equivalent until it does. Out of scope for
205
- this package (server/API code is a different agent's lane).
213
+ Done, 2026-12-01: a real RFC-8628-shaped device-authorization flow now
214
+ exists server-side (`apps/rithub-device-auth`, `POST /api/rit/device/code`
215
+ + `GET /device` + `POST /api/rit/device/token`), wrapping the engine's own
216
+ OAuth2 "Rit CLI" application via PKCE -- `rit login`'s browser + poll flow
217
+ above, not the old paste-a-token fallback (`--paste-token` keeps that path
218
+ for a box with no outbound access to the device-flow endpoints). Every
219
+ token it hands out is marked agent-identity server-side at the moment
220
+ it's minted, unless the human opts out on the `/device` page -- see
221
+ `apps/rithub-approvals/src/agentSessionTokens.mjs` for the full
222
+ "enforced, not opt-in" design.
206
223
 
207
224
  ## Design notes
208
225
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recoder.xyz/rithub",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
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
@@ -39,6 +39,14 @@ async function fetchUser(io, apiUrl, token) {
39
39
  * of hanging on a prompt nobody is there to answer -- confirmed live,
40
40
  * 2026-11-30, that the old code could hang indefinitely on stdin that is
41
41
  * open but never sends data or EOF. */
42
+ // `options.agent` (`rit login --agent`, 2026-12-01): tells the server this
43
+ // device sign-in is for an agent, before any token exists -- the server
44
+ // marks the resulting token agent-identity at the moment it is minted
45
+ // (apps/rithub-device-auth's handleCallback), not only if/when `rit`
46
+ // later happens to run with RITHUB_AGENT_SESSION_ID set. Every device
47
+ // sign-in defaults to agent anyway (the human opts OUT on the /device
48
+ // page) -- this flag just removes that opt-out for a scripted/CI caller
49
+ // where no human will be looking at the page at all.
42
50
  export async function runLogin(options, io) {
43
51
  const apiUrl = (options.apiUrl ?? io.env.RITHUB_API_URL ?? DEFAULT_API_URL).replace(/\/+$/, "");
44
52
  let token = options.token ?? io.env.RITHUB_TOKEN;
@@ -59,7 +67,7 @@ export async function runLogin(options, io) {
59
67
  io.openUrl?.(settingsUrl);
60
68
  token = (await io.promptHidden("Token: ")).trim();
61
69
  } else {
62
- const device = await runDeviceLogin(io, apiUrl);
70
+ const device = await runDeviceLogin(io, apiUrl, { agent: Boolean(options.agent) });
63
71
  token = device.token;
64
72
  }
65
73
  }
package/src/cli.mjs CHANGED
@@ -2,7 +2,8 @@ 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
+ import { runPushApprove, runPushDeny, runPushStatus, runPushList, markAgentSessionIfNeeded } from "./push-approval.mjs";
6
+ import { runExport } from "./export.mjs";
6
7
 
7
8
  const USAGE = `rit <command> [options] (alias: rithub)
8
9
 
@@ -11,8 +12,13 @@ const USAGE = `rit <command> [options] (alias: rithub)
11
12
  this directory's git remote at it
12
13
  claim --email <you@example.com> hands a human ownership of the account
13
14
  \`init\` created in this directory
14
- login [--token <token>] sign in: opens a browser for a real
15
+ login [--token <token>] [--agent] sign in: opens a browser for a real
15
16
  device-code sign-in at ${DEFAULT_API_URL}/device
17
+ (defaults to an agent-identity token --
18
+ a held push for --force/protected/
19
+ delete -- unless the human ticks "this
20
+ is me" on that page; --agent removes
21
+ that choice, for a scripted/CI caller)
16
22
  (or pass --token / set RITHUB_TOKEN --
17
23
  required on a non-interactive session;
18
24
  --paste-token falls back to pasting a
@@ -34,6 +40,12 @@ const USAGE = `rit <command> [options] (alias: rithub)
34
40
  a human to approve instead of landing.
35
41
  push approve|deny|status <id> act on a held push/branch-delete
36
42
  push list --owner <o> --repo <r> [--status pending|approved|denied]
43
+ export [--output <path>] one archive: every repo you own as a
44
+ real git bundle (+ wiki), issues/
45
+ pulls/releases+assets as documented
46
+ JSON. \`export --nightly on|off\`
47
+ toggles a 7-day-retained nightly copy
48
+ kept server-side instead of exporting.
37
49
 
38
50
  repo <cmd> create|list|view|fork|delete|rename|edit|archive|sync|sync-now|import
39
51
  issue <cmd> list|create|view|close|reopen|edit|comment
@@ -93,6 +105,15 @@ export function parseFlags(argv, { valueFlags = [], boolFlags = [], repeatableFl
93
105
 
94
106
  export async function main(argv, io) {
95
107
  const [command, ...rest] = argv;
108
+ // RIT-ACT gap 1 (server-side enforcement, 2026-12-01): mark this
109
+ // session's token as agent-attributed before running ANY command, not
110
+ // just `push`/`branch delete` -- so even a session's first action marks
111
+ // the token before a later raw `git push` with the same credential
112
+ // could reach the server unheld. No-op (not even a network call) unless
113
+ // RITHUB_AGENT_SESSION_ID is set. See push-approval.mjs's header comment.
114
+ if (command !== "--version" && command !== "-v" && command !== "help" && command !== "--help" && command !== "-h") {
115
+ await markAgentSessionIfNeeded(io);
116
+ }
96
117
  try {
97
118
  if (command === "--version" || command === "-v") {
98
119
  io.out(io.version ?? "unknown");
@@ -126,8 +147,8 @@ export async function main(argv, io) {
126
147
  }
127
148
 
128
149
  if (command === "login") {
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);
150
+ const args = parseFlags(rest, { valueFlags: ["--token", "--api-url"], boolFlags: ["--json", "--paste-token", "--agent"] });
151
+ const result = await runLogin({ token: args.token, apiUrl: args.apiUrl, pasteToken: args.pasteToken, agent: args.agent }, io);
131
152
  io.out(args.json ? JSON.stringify(result) : `Logged in as ${result.username} on ${result.apiUrl}.`);
132
153
  return 0;
133
154
  }
@@ -146,6 +167,19 @@ export async function main(argv, io) {
146
167
  return 0;
147
168
  }
148
169
 
170
+ if (command === "export") {
171
+ const args = parseFlags(rest, { valueFlags: ["--output", "--nightly", "--api-url"], boolFlags: ["--json"] });
172
+ const result = await runExport({ output: args.output, nightly: args.nightly, apiUrl: args.apiUrl }, io);
173
+ if (args.json) {
174
+ io.out(JSON.stringify(result));
175
+ } else if ("nightly" in result) {
176
+ io.out(`Nightly export copy ${result.nightly ? "enabled" : "disabled"}.`);
177
+ } else {
178
+ io.out(`Exported to ${result.output} (${result.size_bytes} bytes): ${result.totals?.repos ?? "?"} repo(s), ${result.totals?.issues ?? "?"} issue(s), ${result.totals?.pulls ?? "?"} pull(s), ${result.totals?.releases ?? "?"} release(s).`);
179
+ }
180
+ return 0;
181
+ }
182
+
149
183
  if (command === "clone") {
150
184
  const args = parseFlags(rest, { valueFlags: ["--api-url"], boolFlags: ["--json"] });
151
185
  const [target, dir] = args._;
@@ -37,8 +37,13 @@ async function postJson(io, apiUrl, path, json) {
37
37
  * denied). Returns the access token on success; throws CliError otherwise.
38
38
  * `io.sleep` is honored if a caller (tests) supplies one, so this never
39
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", {});
40
+ export async function runDeviceLogin(io, apiUrl, { agent = false } = {}) {
41
+ // RIT-ACT "enforced, not opt-in" (2026-12-01): `--agent` tells the
42
+ // server up front this device code is for an agent, so the /device
43
+ // page locks to that (no "this is me" checkbox to override it) --
44
+ // the server still defaults every OTHER device code to agent too
45
+ // (safe default), this flag only removes the human's opt-out.
46
+ const { status, body } = await postJson(io, apiUrl, "/api/rit/device/code", agent ? { kind: "agent" } : {});
42
47
  if (status !== 200 || !body?.device_code || !body?.user_code) {
43
48
  throw new CliError(
44
49
  `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).`,
package/src/export.mjs ADDED
@@ -0,0 +1,78 @@
1
+ // `rit export` -- RIT-RET (2026-12-01): the CLI half of the full account
2
+ // export (the other half is the one-click "Export your account" page at
3
+ // https://rithub.dev/export). Same job, same server
4
+ // (apps/rithub-export): this just saves a browser round trip for a
5
+ // caller that already has its own token. Polls until the archive is
6
+ // ready, then downloads it straight to disk.
7
+ import { writeFileSync } from "node:fs";
8
+ import { CliError, DEFAULT_API_URL } from "./init.mjs";
9
+ import { resolveSession } from "./config.mjs";
10
+
11
+ const POLL_INTERVAL_MS = 2000;
12
+ const MAX_WAIT_MS = 20 * 60_000; // a real multi-repo export can take a while; this is a ceiling, not a target
13
+
14
+ async function jsonCall(io, apiUrl, path, init, token) {
15
+ const res = await io.fetchImpl(`${apiUrl}${path}`, {
16
+ ...init,
17
+ headers: { accept: "application/json", "user-agent": "rithub-cli", "content-type": "application/json", authorization: `token ${token}`, ...(init?.headers ?? {}) },
18
+ });
19
+ const text = await res.text();
20
+ let body = null;
21
+ try {
22
+ body = text ? JSON.parse(text) : null;
23
+ } catch {
24
+ body = { message: text.slice(0, 300) };
25
+ }
26
+ return { status: res.status, body };
27
+ }
28
+
29
+ function sleep(ms) {
30
+ return new Promise((resolve) => setTimeout(resolve, ms));
31
+ }
32
+
33
+ /** `rit export [--output <path>] [--nightly on|off]`. With `--nightly`,
34
+ * just toggles the opt-in server-side nightly copy and returns -- no
35
+ * export runs. Otherwise starts one, polls `GET /export/api/jobs/:id`
36
+ * until `done`/`failed`, then downloads the finished archive. */
37
+ export async function runExport(options, io) {
38
+ const apiUrl = (options.apiUrl ?? io.env.RITHUB_API_URL ?? DEFAULT_API_URL).replace(/\/+$/, "");
39
+ const session = resolveSession(io, { apiUrl });
40
+ if (!session) throw new CliError("not logged in -- run `rit login`", { code: "not_logged_in" });
41
+
42
+ if (options.nightly) {
43
+ const enabled = options.nightly === "on";
44
+ const { status, body } = await jsonCall(io, apiUrl, "/export/api/nightly", { method: "POST", body: JSON.stringify({ enabled }) }, session.token);
45
+ if (status !== 200) throw new CliError(`could not set the nightly export preference (HTTP ${status}): ${body?.error ?? "unknown error"}`, { code: "export_failed" });
46
+ return { nightly: body.enabled };
47
+ }
48
+
49
+ const started = await jsonCall(io, apiUrl, "/export/api/start", { method: "POST" }, session.token);
50
+ if (started.status !== 202) {
51
+ throw new CliError(`could not start the export (HTTP ${started.status}): ${started.body?.error ?? "unknown error"}`, { code: "export_failed" });
52
+ }
53
+ const jobId = started.body.id;
54
+ io.out(`Export started (${jobId}), waiting...`);
55
+
56
+ const deadline = (io.now?.() ?? Date.now()) + MAX_WAIT_MS;
57
+ let job = null;
58
+ while ((io.now?.() ?? Date.now()) < deadline) {
59
+ await (io.sleep ?? sleep)(POLL_INTERVAL_MS);
60
+ const polled = await jsonCall(io, apiUrl, `/export/api/jobs/${jobId}`, { method: "GET" }, session.token);
61
+ if (polled.status !== 200) throw new CliError(`lost track of the export job (HTTP ${polled.status})`, { code: "export_failed" });
62
+ job = polled.body;
63
+ if (job.status === "done" || job.status === "failed") break;
64
+ }
65
+ if (!job || (job.status !== "done" && job.status !== "failed")) {
66
+ throw new CliError(`the export is still running after ${Math.round(MAX_WAIT_MS / 60000)} minutes -- check https://rithub.dev/export for status`, { code: "export_timeout" });
67
+ }
68
+ if (job.status === "failed") {
69
+ throw new CliError(`the export failed: ${job.error ?? "unknown error"}`, { code: "export_failed" });
70
+ }
71
+
72
+ const outputPath = options.output ?? `rithub-export-${session.username ?? "account"}-${jobId}.tar.gz`;
73
+ const res = await io.fetchImpl(`${apiUrl}/export/download/${jobId}`, { headers: { authorization: `token ${session.token}`, "user-agent": "rithub-cli" } });
74
+ if (res.status !== 200) throw new CliError(`could not download the finished archive (HTTP ${res.status})`, { code: "export_failed" });
75
+ const buf = Buffer.from(await res.arrayBuffer());
76
+ writeFileSync(outputPath, buf);
77
+ return { id: jobId, output: outputPath, size_bytes: buf.length, totals: job.totals };
78
+ }
@@ -82,6 +82,32 @@ export async function runPushStatus(options, io) {
82
82
  return body;
83
83
  }
84
84
 
85
+ /** RIT-ACT gap 1 (server-side enforcement, 2026-12-01): a raw `git push`
86
+ * made outside `rit` entirely (bypassing stageHeldPush above completely)
87
+ * is only ever held server-side if the server already knows this exact
88
+ * bearer token belongs to an agent session -- it has no other way to tell
89
+ * an agent-session token apart from a human's own PAT, since both are
90
+ * ordinary Rithub access tokens. So every `rit` command, when
91
+ * `RITHUB_AGENT_SESSION_ID` is set, marks its own token here (idempotent,
92
+ * cheap, best-effort -- see apps/rithub-approvals/src/agentSessionTokens.mjs
93
+ * and apps/rithub-agent-gateway, which reads the mark this writes). Called
94
+ * from cli.mjs's `main()` before any subcommand runs, so even a session's
95
+ * very first action (e.g. `rit clone`) marks the token before any later
96
+ * raw `git push` with the same credential could land unheld. Never throws
97
+ * -- a network hiccup here must not block the command the human/agent
98
+ * actually asked for. */
99
+ export async function markAgentSessionIfNeeded(io, options = {}) {
100
+ const sessionId = io.env.RITHUB_AGENT_SESSION_ID;
101
+ if (!sessionId) return;
102
+ const session = resolveSession(io, { apiUrl: options.apiUrl });
103
+ if (!session) return;
104
+ try {
105
+ await approvalsCall(io, session.apiUrl, "/agent-session/mark", { method: "POST", body: JSON.stringify({ session_id: sessionId }), signal: AbortSignal.timeout(5000) }, session.token);
106
+ } catch {
107
+ // best-effort -- see header comment
108
+ }
109
+ }
110
+
85
111
  export async function runPushList(options, io) {
86
112
  const session = requireLoggedIn(options, io);
87
113
  if (!options.owner || !options.repo) throw new CliError("`rit push list` needs --owner and --repo", { code: "invalid_argument" });