@rightkit/ci 0.0.0-stage → 0.2.42

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.
@@ -0,0 +1,161 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { spawnSync } from "node:child_process";
7
+ import { fileURLToPath } from "node:url";
8
+ import { renderTemplate } from "./render.mjs";
9
+ import { buildRenderContext, lockfilePatchStep } from "./manifest.mjs";
10
+
11
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)));
12
+ const templatesDir = path.join(packageRoot, "templates");
13
+
14
+ const TEMPLATES = { node: "ci.yml", rust: "profiles/rust-hybrid/ci.yml" };
15
+ const INSTALL_LINE = " - run: pnpm install --frozen-lockfile";
16
+ const STEP_NAME = " - name: Print pnpm-lock.yaml patch when the lockfile is stale";
17
+
18
+ const NODE_BASE = {
19
+ schemaVersion: 1,
20
+ compile: "github-actions-only",
21
+ lanes: ["ci"],
22
+ matrix: { os: ["ubuntu-latest"], node: ["24"] },
23
+ templateVersion: "1.0.0",
24
+ };
25
+ const RUST_BASE = {
26
+ ...NODE_BASE,
27
+ profile: "rust-hybrid",
28
+ gate: { path: "scripts/gate.sh" },
29
+ matrix: { os: ["xcode-27", "windows-2025"], node: ["26.8.1"] },
30
+ ciAllOs: true,
31
+ };
32
+ const manifestFor = (profile, packageManager) => ({ ...(profile === "rust" ? RUST_BASE : NODE_BASE), packageManager });
33
+
34
+ function render(profile, manifest, override = {}) {
35
+ const context = { ...buildRenderContext(structuredClone(manifest), "/repos/widgets"), ...override };
36
+ return renderTemplate(fs.readFileSync(path.join(templatesDir, TEMPLATES[profile]), "utf8"), context);
37
+ }
38
+
39
+ // The step's run body with the YAML block indent removed, as GitHub Actions runs it.
40
+ function runBody(step) {
41
+ const head = " run: |\n";
42
+ const body = step.slice(step.indexOf(head) + head.length);
43
+ return body.split("\n").map((line) => line.slice(10)).join("\n");
44
+ }
45
+
46
+ test("pnpm: both ci templates print the patch step directly after the frozen install", () => {
47
+ for (const profile of ["node", "rust"]) {
48
+ const out = render(profile, manifestFor(profile, "pnpm@11.24.0"));
49
+ assert.equal(out.split(STEP_NAME).length - 1, 1, `${profile}: exactly one patch step`);
50
+ assert.equal(out.split(INSTALL_LINE).length - 1, 1, `${profile}: exactly one frozen install`);
51
+ assert.ok(out.includes(`${INSTALL_LINE}\n${STEP_NAME}`), `${profile}: step follows the install`);
52
+ assert.match(out, / if: failure\(\)\n/);
53
+ }
54
+ });
55
+
56
+ test("pnpm: the patch step is the only difference from a render without it", () => {
57
+ for (const profile of ["node", "rust"]) {
58
+ const manifest = manifestFor(profile, "pnpm@11.24.0");
59
+ const step = lockfilePatchStep(manifest);
60
+ const withStep = render(profile, manifest);
61
+ const withoutStep = render(profile, manifest, { PNPM_LOCK_PATCH_STEP: "" });
62
+ assert.equal(withoutStep.split(INSTALL_LINE).length - 1, 1, `${profile}: install line is unique`);
63
+ assert.equal(withStep, withoutStep.replace(INSTALL_LINE, INSTALL_LINE + step), `${profile}: only the new step differs`);
64
+ }
65
+ });
66
+
67
+ test("npm and yarn: no patch step and no pnpm lockfile reference in either ci template", () => {
68
+ for (const pm of ["npm@10.9.2", "yarn@4.5.0"]) {
69
+ for (const profile of ["node", "rust"]) {
70
+ const manifest = manifestFor(profile, pm);
71
+ assert.equal(lockfilePatchStep(manifest), "", `${pm} ${profile}: no step generated`);
72
+ const out = render(profile, manifest);
73
+ assert.doesNotMatch(out, /lockfile-only|pnpm-lock\.yaml/, `${pm} ${profile}: no pnpm lockfile text`);
74
+ }
75
+ }
76
+ });
77
+
78
+ test("patch step runs only after a failed install, never masks it, and prints the lockfile diff", () => {
79
+ const step = lockfilePatchStep(manifestFor("node", "pnpm@11.24.0"));
80
+ assert.match(step, /^\n {6}- name: /);
81
+ assert.match(step, /\n {8}if: failure\(\)\n/);
82
+ const body = runBody(step);
83
+ assert.match(body, /pnpm install --lockfile-only/);
84
+ assert.match(body, /git diff -- pnpm-lock\.yaml/);
85
+ assert.doesNotMatch(body, /\bexit\b/, "the step must not choose the job result");
86
+ });
87
+
88
+ test("patch step behaves on a real stale, fresh and failing lockfile", (t) => {
89
+ if (process.platform === "win32") return t.skip("POSIX shell behaviour");
90
+ const git = spawnSync("git", ["--version"], { encoding: "utf8" });
91
+ if (git.error) return t.skip("git not installed");
92
+ const body = runBody(lockfilePatchStep(manifestFor("node", "pnpm@11.24.0")));
93
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "right-git-pnpm-lock-"));
94
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
95
+ const repo = path.join(root, "repo");
96
+ const bin = path.join(root, "bin");
97
+ fs.mkdirSync(repo);
98
+ fs.mkdirSync(bin);
99
+ fs.writeFileSync(path.join(root, "step.sh"), `${body}\n`);
100
+ // Stand-in for pnpm: `install --lockfile-only` rewrites the lockfile to $FAKE_PNPM_LOCK and exits $FAKE_PNPM_STATUS.
101
+ fs.writeFileSync(path.join(bin, "pnpm"), [
102
+ "#!/bin/sh",
103
+ 'if [ "$1" = "install" ] && [ "$2" = "--lockfile-only" ]; then',
104
+ ' printf \'%s\\n\' "$FAKE_PNPM_LOCK" > pnpm-lock.yaml',
105
+ ' exit "${FAKE_PNPM_STATUS:-0}"',
106
+ "fi",
107
+ 'echo "unexpected pnpm arguments: $*" >&2',
108
+ "exit 2",
109
+ "",
110
+ ].join("\n"));
111
+ fs.chmodSync(path.join(bin, "pnpm"), 0o755);
112
+ const gitRun = (args) => spawnSync("git", args, { cwd: repo, encoding: "utf8" });
113
+ gitRun(["init", "-q"]);
114
+ fs.writeFileSync(path.join(repo, "pnpm-lock.yaml"), "lockfileVersion: v1\n");
115
+ gitRun(["add", "pnpm-lock.yaml"]);
116
+ gitRun(["-c", "user.name=test", "-c", "user.email=test@example.invalid", "commit", "-qm", "init"]);
117
+
118
+ const runStep = (env) => spawnSync("bash", ["--noprofile", "--norc", "-eo", "pipefail", path.join(root, "step.sh")], {
119
+ cwd: repo,
120
+ encoding: "utf8",
121
+ env: { ...process.env, PATH: `${bin}${path.delimiter}${process.env.PATH}`, ...env },
122
+ });
123
+
124
+ const stale = runStep({ FAKE_PNPM_LOCK: "lockfileVersion: v2", FAKE_PNPM_STATUS: "0" });
125
+ assert.equal(stale.status, 0, stale.stderr);
126
+ assert.match(stale.stdout, /::group::pnpm-lock\.yaml patch/);
127
+ assert.match(stale.stdout, /^-lockfileVersion: v1$/m);
128
+ assert.match(stale.stdout, /^\+lockfileVersion: v2$/m);
129
+ assert.match(stale.stdout, /::error file=pnpm-lock\.yaml::/);
130
+ assert.doesNotMatch(stale.stdout, /::notice::/);
131
+
132
+ gitRun(["checkout", "--", "pnpm-lock.yaml"]);
133
+ const fresh = runStep({ FAKE_PNPM_LOCK: "lockfileVersion: v1", FAKE_PNPM_STATUS: "0" });
134
+ assert.equal(fresh.status, 0, fresh.stderr);
135
+ assert.match(fresh.stdout, /::notice::pnpm-lock\.yaml already matches package\.json/);
136
+ assert.doesNotMatch(fresh.stdout, /::group::/);
137
+
138
+ const failing = runStep({ FAKE_PNPM_LOCK: "lockfileVersion: v1", FAKE_PNPM_STATUS: "1" });
139
+ assert.equal(failing.status, 0, "the step itself succeeds; the failed install already failed the job");
140
+ assert.match(failing.stdout, /::error::pnpm install --lockfile-only failed/);
141
+ assert.doesNotMatch(failing.stdout, /::group::/);
142
+ });
143
+
144
+ test("rendered pnpm ci workflows pass actionlint with the patch step", (t) => {
145
+ const probe = spawnSync("actionlint", ["-version"], { encoding: "utf8" });
146
+ if (probe.error) return t.skip("actionlint not installed");
147
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "right-git-pnpm-patch-actionlint-"));
148
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
149
+ fs.mkdirSync(path.join(dir, ".github", "workflows"), { recursive: true });
150
+ fs.writeFileSync(path.join(dir, ".github", "actionlint.yaml"), "self-hosted-runner:\n labels:\n - xcode-*\n");
151
+ const files = [
152
+ ["node-pnpm.yml", render("node", manifestFor("node", "pnpm@11.24.0"))],
153
+ ["rust-pnpm.yml", render("rust", manifestFor("rust", "pnpm@11.24.0"))],
154
+ ].map(([name, text]) => {
155
+ const file = path.join(dir, ".github", "workflows", name);
156
+ fs.writeFileSync(file, text);
157
+ return file;
158
+ });
159
+ const result = spawnSync("actionlint", ["-shellcheck=", "-pyflakes=", "-config-file", path.join(dir, ".github", "actionlint.yaml"), ...files], { encoding: "utf8" });
160
+ assert.equal(result.status, 0, result.stdout + result.stderr);
161
+ });
@@ -0,0 +1,168 @@
1
+ // The public-only enforcement (DESIGN.md §5, invariant I1). Install-time
2
+ // layer: resolve a repo's visibility and hard-refuse anything that is not
3
+ // confirmed public. No override flag exists in v1 — that is a deliberate
4
+ // policy change to this file, never a CLI flag.
5
+ //
6
+ // All child-process / network access is injected so tests can run fully
7
+ // offline (never hit gh or the network from a test).
8
+
9
+ import { execFile as execFileCb } from "node:child_process";
10
+ import { promisify } from "node:util";
11
+
12
+ const execFileAsync = promisify(execFileCb);
13
+
14
+ /** @typedef {"public"|"private"|"internal"|"unknown"} Visibility */
15
+
16
+ /**
17
+ * Query `gh repo view --json visibility` in repoPath.
18
+ * Returns { ok, visibility, raw, error }, never throws.
19
+ */
20
+ async function ghVisibility(repoPath, execFile) {
21
+ try {
22
+ const { stdout } = await execFile("gh", ["repo", "view", "--json", "visibility"], { cwd: repoPath });
23
+ const parsed = JSON.parse(stdout);
24
+ const visibility = String(parsed.visibility || "").toLowerCase();
25
+ if (visibility === "public" || visibility === "private" || visibility === "internal") {
26
+ return { ok: true, visibility, raw: parsed, error: null };
27
+ }
28
+ return { ok: false, visibility: "unknown", raw: parsed, error: `unrecognized gh visibility value: ${parsed.visibility}` };
29
+ } catch (error) {
30
+ return { ok: false, visibility: "unknown", raw: null, error: error.message };
31
+ }
32
+ }
33
+
34
+ const GITHUB_HOST = "github.com";
35
+
36
+ /**
37
+ * Normalize a git remote into something the WHATWG `URL` parser accepts.
38
+ * Full URLs (`https://…`, `ssh://…`, `git://…`) pass through unchanged.
39
+ * Git's scp-like shorthand (`[user@]host:path`, no `://`) is rewritten to
40
+ * `ssh://[user@]host/path` so the same parser handles both forms — that
41
+ * parser is what does the real work below, not this rewrite.
42
+ */
43
+ function toParseableUrl(remoteUrl) {
44
+ const trimmed = remoteUrl.trim();
45
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(trimmed)) return trimmed;
46
+ const scpMatch = /^([a-zA-Z0-9_.-]+@)?([a-zA-Z0-9.-]+):(?!\/\/)(.+)$/.exec(trimmed);
47
+ if (!scpMatch) return trimmed;
48
+ const [, userAt = "", host, path] = scpMatch;
49
+ return `ssh://${userAt}${host}/${path}`;
50
+ }
51
+
52
+ /**
53
+ * Parse an owner/repo pair out of a git remote URL (https or ssh form).
54
+ *
55
+ * N1 fix: host matching must be exact, not substring. The prior regex
56
+ * searched the raw string for the text `github.com` anywhere, so
57
+ * `notgithub.com`, `github.com.evil.io`, and `https://github.com@evil.io/…`
58
+ * (github.com as userinfo, real host evil.io) were all misread as GitHub.
59
+ * This parses the remote as a real URL and requires `url.hostname` to equal
60
+ * `github.com` exactly (case-insensitive; WHATWG URL already lowercases
61
+ * hostnames) — the URL parser itself separates userinfo/port from host, so
62
+ * those tricks fall out for free. Enterprise hosts (e.g. github.example.com)
63
+ * and any other non-exact host still fail closed to null.
64
+ *
65
+ * F16 fix (kept): the repo-name group allows internal dots (e.g.
66
+ * `repo.with.dot`) — it only excludes `/` (which ends the segment), not `.`.
67
+ * A trailing `.git` suffix is stripped afterward in code.
68
+ */
69
+ export function parseOwnerRepo(remoteUrl) {
70
+ let url;
71
+ try {
72
+ url = new URL(toParseableUrl(remoteUrl));
73
+ } catch {
74
+ return null;
75
+ }
76
+ if (url.hostname.toLowerCase() !== GITHUB_HOST) return null;
77
+
78
+ const match = /^\/?([^/]+)\/([^/]+?)\/?$/.exec(url.pathname);
79
+ if (!match) return null;
80
+ const owner = match[1];
81
+ const repo = match[2].endsWith(".git") ? match[2].slice(0, -4) : match[2];
82
+ if (!owner || !repo) return null;
83
+ return { owner, repo };
84
+ }
85
+
86
+ /**
87
+ * Fallback: read the origin remote, then ask the public GitHub API for
88
+ * visibility. Unauthenticated API calls can only positively confirm
89
+ * "public" (a 404 is ambiguous: could be private, could be nonexistent) —
90
+ * so this fallback only ever returns "public" or "unknown", never a false
91
+ * "private"/"internal" reading that a hard refusal downstream would relax.
92
+ */
93
+ async function gitRemoteApiVisibility(repoPath, execFile, fetchFn) {
94
+ let remoteUrl;
95
+ try {
96
+ const { stdout } = await execFile("git", ["remote", "get-url", "origin"], { cwd: repoPath });
97
+ remoteUrl = stdout.trim();
98
+ } catch (error) {
99
+ return { ok: false, visibility: "unknown", raw: null, error: `git remote get-url origin failed: ${error.message}` };
100
+ }
101
+
102
+ const ownerRepo = parseOwnerRepo(remoteUrl);
103
+ if (!ownerRepo) {
104
+ return { ok: false, visibility: "unknown", raw: null, error: `could not parse owner/repo from remote: ${remoteUrl}` };
105
+ }
106
+
107
+ try {
108
+ const response = await fetchFn(`https://api.github.com/repos/${ownerRepo.owner}/${ownerRepo.repo}`, {
109
+ headers: { Accept: "application/vnd.github+json", "User-Agent": "right-git" },
110
+ });
111
+ if (!response.ok) {
112
+ return { ok: false, visibility: "unknown", raw: { status: response.status }, error: `github api returned ${response.status}` };
113
+ }
114
+ const body = await response.json();
115
+ if (body.private === false) {
116
+ return { ok: true, visibility: "public", raw: body, error: null };
117
+ }
118
+ // private === true, or field absent: cannot distinguish private/internal
119
+ // over the unauthenticated API — fail closed to "unknown".
120
+ return { ok: false, visibility: "unknown", raw: body, error: "unauthenticated API cannot confirm public visibility" };
121
+ } catch (error) {
122
+ return { ok: false, visibility: "unknown", raw: null, error: error.message };
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Resolve the visibility of the repo at repoPath.
128
+ * deps allows tests to inject fakes for execFile/fetch (never hit the
129
+ * network or spawn a real process from a test).
130
+ * Returns { visibility, source, raw, error } — never throws.
131
+ */
132
+ export async function resolveVisibility(repoPath, deps = {}) {
133
+ const execFile = deps.execFile || execFileAsync;
134
+ const fetchFn = deps.fetch || globalThis.fetch;
135
+
136
+ const gh = await ghVisibility(repoPath, execFile);
137
+ if (gh.ok) {
138
+ return { visibility: gh.visibility, source: "gh", raw: gh.raw, error: null };
139
+ }
140
+
141
+ const fallback = await gitRemoteApiVisibility(repoPath, execFile, fetchFn);
142
+ if (fallback.ok) {
143
+ return { visibility: fallback.visibility, source: "git-remote-api", raw: fallback.raw, error: null };
144
+ }
145
+
146
+ return {
147
+ visibility: "unknown",
148
+ source: "error",
149
+ raw: null,
150
+ error: `gh: ${gh.error}; fallback: ${fallback.error}`,
151
+ };
152
+ }
153
+
154
+ /**
155
+ * I1: hard refusal of anything not confirmed public. No override.
156
+ * Returns a typed result: { allowed, visibility, source, reason }.
157
+ */
158
+ export async function assertPublic(repoPath, deps = {}) {
159
+ const result = await resolveVisibility(repoPath, deps);
160
+ if (result.visibility === "public") {
161
+ return { allowed: true, visibility: result.visibility, source: result.source, reason: null };
162
+ }
163
+ const reason =
164
+ result.visibility === "unknown"
165
+ ? `could not confirm repository visibility (fail closed): ${result.error}`
166
+ : `repository visibility is '${result.visibility}'; right-git installs into public repos only (invariant I1)`;
167
+ return { allowed: false, visibility: result.visibility, source: result.source, reason };
168
+ }
package/render.mjs ADDED
@@ -0,0 +1,69 @@
1
+ // Shared render engine: template text + a flat context map -> rendered YAML.
2
+ // Templates use `${TOKEN}` (single brace, upper-snake-case) placeholders.
3
+ // GitHub Actions expressions use `${{ ... }}` (double brace) and are never
4
+ // touched by this substitution — the two syntaxes cannot collide because our
5
+ // token regex requires an upper-case/underscore character immediately after
6
+ // `${`, and `${{` is followed by another `{`.
7
+
8
+ const TOKEN_RE = /\$\{([A-Z][A-Z0-9_]*)\}/g;
9
+ const LEFTOVER_RE = /\$\{[A-Z][A-Z0-9_]*\}/;
10
+
11
+ // First line of every rendered template (see templates/*.yml). Used to
12
+ // identify right-git-managed files for drift/uninstall without a separate
13
+ // state file — the marker lives in the file itself.
14
+ export const MANAGED_MARKER = "# Managed by right-git";
15
+
16
+ // The step that carries a private Swift package credential (see
17
+ // swiftPrivatePackagesConfigureStep in manifest.mjs). A workflow that renders it
18
+ // must not be triggered by an event that hands secrets to untrusted code.
19
+ const SWIFT_CONFIGURE_STEP_NAME = "- name: Configure private Swift package access";
20
+ const UNSAFE_SECRET_TRIGGER_RE = /\b(pull_request_target|workflow_run)\b/;
21
+
22
+ // The top-level `on:` block: from the `on:` line to the next unindented key.
23
+ function onBlock(text) {
24
+ const lines = text.split("\n");
25
+ const start = lines.findIndex((line) => /^on:/.test(line));
26
+ if (start < 0) return "";
27
+ let end = start + 1;
28
+ while (end < lines.length && (lines[end] === "" || /^[\s#]/.test(lines[end]))) end += 1;
29
+ return lines.slice(start, end).join("\n");
30
+ }
31
+
32
+ /**
33
+ * Refuse a rendered workflow that carries the private Swift package credential
34
+ * steps under a trigger that runs with secrets on untrusted input
35
+ * (pull_request_target, workflow_run). GitHub withholds secrets from fork
36
+ * pull_request runs, so those two are the only triggers that could leak it.
37
+ */
38
+ function assertSwiftCredentialTriggers(rendered) {
39
+ if (!rendered.includes(SWIFT_CONFIGURE_STEP_NAME)) return;
40
+ const trigger = UNSAFE_SECRET_TRIGGER_RE.exec(onBlock(rendered));
41
+ if (trigger) {
42
+ throw new Error(`render: refusing to render the private Swift package credential steps into a workflow triggered by ${trigger[1]}`);
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Render one template against a context map. Deterministic: same template +
48
+ * same context always produces byte-identical output.
49
+ * Throws if a placeholder has no entry in context (mechanical safety net —
50
+ * never silently emits an unresolved token into a workflow file).
51
+ */
52
+ export function renderTemplate(templateText, context) {
53
+ const rendered = templateText.replace(/\r\n?/g, "\n").replace(TOKEN_RE, (full, key) => {
54
+ if (!Object.hasOwn(context, key)) {
55
+ throw new Error(`render: no value provided for placeholder \${${key}}`);
56
+ }
57
+ return String(context[key]);
58
+ });
59
+
60
+ const leftover = LEFTOVER_RE.exec(rendered);
61
+ if (leftover) {
62
+ throw new Error(`render: unresolved placeholder ${leftover[0]} remained after substitution`);
63
+ }
64
+ assertSwiftCredentialTriggers(rendered);
65
+ // Optional final job fragments may expand to an empty string. Normalize
66
+ // template EOF after substitution so managed workflows remain byte-stable
67
+ // with exactly one terminating newline.
68
+ return `${rendered.replace(/(?:\r\n|\r|\n)+$/, "")}\n`;
69
+ }