@astrofoundry/astrogate 0.0.0-stage → 0.1.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.
Files changed (101) hide show
  1. package/README.md +13 -2
  2. package/agents/foreman.md +27 -0
  3. package/cli/astro-install.sh +242 -0
  4. package/cli/astro.sh +449 -0
  5. package/cli/astro.test.ts +65 -0
  6. package/cli/astrogate.sh +309 -0
  7. package/cli/astrogate.test.ts +113 -0
  8. package/cli/verify-release.sh +77 -0
  9. package/cli/verify-release.test.ts +140 -0
  10. package/dist/bridge.js +9950 -0
  11. package/dist/claude.js +7899 -0
  12. package/dist/extensions/bridge/index.js +9937 -0
  13. package/dist/extensions/gate/index.js +286 -0
  14. package/dist/extensions/guard/index.js +364 -0
  15. package/dist/extensions/subagents/index.js +8458 -0
  16. package/extensions/bridge/admin.ts +86 -0
  17. package/extensions/bridge/approvals.ts +147 -0
  18. package/extensions/bridge/attachments.ts +65 -0
  19. package/extensions/bridge/chunk.ts +50 -0
  20. package/extensions/bridge/claude-run.test.ts +62 -0
  21. package/extensions/bridge/claude-run.ts +301 -0
  22. package/extensions/bridge/commands.ts +89 -0
  23. package/extensions/bridge/config.ts +263 -0
  24. package/extensions/bridge/conversations.ts +144 -0
  25. package/extensions/bridge/daemon.ts +60 -0
  26. package/extensions/bridge/discord.test.ts +547 -0
  27. package/extensions/bridge/gateway.ts +222 -0
  28. package/extensions/bridge/index.ts +951 -0
  29. package/extensions/bridge/launcher.ts +36 -0
  30. package/extensions/bridge/lifecycle.test.ts +78 -0
  31. package/extensions/bridge/open-work.ts +74 -0
  32. package/extensions/bridge/plugin.ts +172 -0
  33. package/extensions/bridge/quote.ts +39 -0
  34. package/extensions/bridge/reports.ts +65 -0
  35. package/extensions/bridge/rest.ts +217 -0
  36. package/extensions/bridge/setup.ts +218 -0
  37. package/extensions/gate/approvals.test.ts +40 -0
  38. package/extensions/gate/config.ts +110 -0
  39. package/extensions/gate/core.ts +114 -0
  40. package/extensions/gate/index.test.ts +202 -0
  41. package/extensions/gate/index.ts +114 -0
  42. package/extensions/gate/risky.ts +14 -0
  43. package/extensions/gate/types.ts +19 -0
  44. package/extensions/guard/config.test.ts +107 -0
  45. package/extensions/guard/config.ts +120 -0
  46. package/extensions/guard/defaults.ts +40 -0
  47. package/extensions/guard/index.test.ts +313 -0
  48. package/extensions/guard/index.ts +183 -0
  49. package/extensions/guard/rules.test.ts +118 -0
  50. package/extensions/guard/rules.ts +101 -0
  51. package/extensions/guard/types.ts +12 -0
  52. package/extensions/subagents/agents.test.ts +137 -0
  53. package/extensions/subagents/agents.ts +207 -0
  54. package/extensions/subagents/bundled.test.ts +29 -0
  55. package/extensions/subagents/child.test.ts +202 -0
  56. package/extensions/subagents/child.ts +367 -0
  57. package/extensions/subagents/index.test.ts +123 -0
  58. package/extensions/subagents/index.ts +352 -0
  59. package/extensions/subagents/pi-paths.test.ts +39 -0
  60. package/extensions/subagents/pi-paths.ts +58 -0
  61. package/extensions/subagents/render.ts +221 -0
  62. package/extensions/subagents/sessions.test.ts +32 -0
  63. package/extensions/subagents/sessions.ts +34 -0
  64. package/extensions/subagents/ticker.test.ts +40 -0
  65. package/extensions/subagents/ticker.ts +36 -0
  66. package/harness/claude/agents.ts +93 -0
  67. package/harness/claude/claude.test.ts +171 -0
  68. package/harness/claude/hook.ts +77 -0
  69. package/harness/claude/main.ts +122 -0
  70. package/harness/claude/mcp.ts +174 -0
  71. package/harness/claude/settings.ts +63 -0
  72. package/package.json +71 -4
  73. package/release.sha256 +99 -0
  74. package/release.sha256.sig +6 -0
  75. package/specialists/AGENTS.md +67 -0
  76. package/specialists/README.md +81 -0
  77. package/specialists/entry/specialist-cli.sh +22 -0
  78. package/specialists/entry/specialist-install.sh +861 -0
  79. package/specialists/entry/specialist-install.test.ts +305 -0
  80. package/specialists/lib/argv.ts +19 -0
  81. package/specialists/lib/audit.ts +20 -0
  82. package/specialists/lib/config.ts +27 -0
  83. package/specialists/lib/errors.ts +8 -0
  84. package/specialists/lib/flush.test.ts +21 -0
  85. package/specialists/lib/lib.test.ts +87 -0
  86. package/specialists/lib/lock.test.ts +42 -0
  87. package/specialists/lib/lock.ts +67 -0
  88. package/specialists/lib/main.ts +40 -0
  89. package/specialists/lib/output.ts +11 -0
  90. package/specialists/lib/paths.ts +22 -0
  91. package/specialists/lib/pinned.test.ts +55 -0
  92. package/specialists/lib/pinned.ts +67 -0
  93. package/specialists/lib/proc.ts +49 -0
  94. package/specialists/lib/repo.ts +198 -0
  95. package/specialists/lib/runtime.test.ts +81 -0
  96. package/specialists/lib/sanitize.ts +43 -0
  97. package/specialists/lib/secrets.ts +28 -0
  98. package/specialists/lib/ssh.ts +38 -0
  99. package/specialists/lib/tunnel.test.ts +44 -0
  100. package/specialists/lib/tunnel.ts +76 -0
  101. package/specialists/provision/provision.sh +96 -0
@@ -0,0 +1,309 @@
1
+ #!/bin/sh
2
+ # astrogate: the host command for the Astrogate core. Tools and workspaces follow.
3
+ #
4
+ # astrogate core [status] the current core, the kept previous one, and the newest on npm
5
+ # sudo astrogate core update [<x.y.z>] the newest core on npm, or that version; the running core's
6
+ # verify-release.sh checks its signature and every file first
7
+ # sudo astrogate core rollback swaps the current core and the previous one
8
+ # astrogate doctor read-only checks; exits 1 when one fails
9
+ #
10
+ # The first install runs this script from a tarball the owner checked with the repo's
11
+ # verify-release.sh, and adds `--signers <the repo's allowed_signers>`; root keeps that file
12
+ # in /usr/local/etc/astrogate. Root runs only system programs and files in root-owned folders.
13
+ # macOS only for now.
14
+ set -eu
15
+ PATH=/usr/bin:/bin:/usr/sbin:/sbin
16
+ export PATH
17
+ umask 022
18
+
19
+ BASE=/usr/local/libexec/astrogate
20
+ SIGNERS_DIR=/usr/local/etc/astrogate
21
+ SIGNERS=$SIGNERS_DIR/allowed_signers
22
+ COMMAND=/usr/local/bin/astrogate
23
+ REGISTRY=https://registry.npmjs.org
24
+
25
+ usage() {
26
+ echo "usage: astrogate core [status] | core update [<x.y.z>] [--signers <allowed_signers>] | core rollback | doctor" >&2
27
+ exit 2
28
+ }
29
+
30
+ fail() {
31
+ echo "astrogate: $*" >&2
32
+ exit 1
33
+ }
34
+
35
+ # x.y.z with plain decimal parts; the character check also rules out newlines.
36
+ valid_version() {
37
+ case "$1" in '' | *[!0-9.]*) return 1 ;; esac
38
+ printf '%s\n' "$1" | /usr/bin/grep -Eq '^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$'
39
+ }
40
+
41
+ # True when version $1 is older than version $2.
42
+ version_lt() {
43
+ old_ifs=$IFS
44
+ IFS=.
45
+ set -- $1 $2
46
+ IFS=$old_ifs
47
+ [ "$1" -lt "$4" ] && return 0
48
+ [ "$1" -gt "$4" ] && return 1
49
+ [ "$2" -lt "$5" ] && return 0
50
+ [ "$2" -gt "$5" ] && return 1
51
+ [ "$3" -lt "$6" ]
52
+ }
53
+
54
+ action=""
55
+ version=""
56
+ signers_arg=""
57
+ case "${1:-}" in
58
+ core)
59
+ action=${2:-status}
60
+ case "$action" in
61
+ status) [ $# -le 2 ] || usage ;;
62
+ update)
63
+ shift 2
64
+ while [ $# -gt 0 ]; do
65
+ case "$1" in
66
+ --signers)
67
+ [ $# -ge 2 ] && [ -z "$signers_arg" ] && [ -n "$2" ] || usage
68
+ signers_arg=$2
69
+ shift 2
70
+ ;;
71
+ *)
72
+ [ -z "$version" ] && valid_version "$1" || usage
73
+ version=$1
74
+ shift
75
+ ;;
76
+ esac
77
+ done
78
+ ;;
79
+ rollback) [ $# -eq 2 ] || usage ;;
80
+ *) usage ;;
81
+ esac
82
+ ;;
83
+ doctor)
84
+ [ $# -eq 1 ] || usage
85
+ action=doctor
86
+ ;;
87
+ *) usage ;;
88
+ esac
89
+
90
+ [ "$(/usr/bin/uname -s)" = Darwin ] || fail "only macOS is supported yet"
91
+
92
+ # This script's folder, after the /usr/local/bin/astrogate link.
93
+ self=$0
94
+ while [ -L "$self" ]; do
95
+ target=$(/usr/bin/readlink "$self")
96
+ case "$target" in /*) self=$target ;; *) self=$(/usr/bin/dirname "$self")/$target ;; esac
97
+ done
98
+ HERE=$(cd "$(/usr/bin/dirname "$self")" && /bin/pwd -P)
99
+
100
+ # The version a link in $BASE names (current or previous), or nothing.
101
+ link_version() {
102
+ link_target=$(/usr/bin/readlink "$BASE/$1" 2>/dev/null || true)
103
+ case "$link_target" in
104
+ versions/*) valid_version "${link_target#versions/}" && printf '%s' "${link_target#versions/}" || true ;;
105
+ esac
106
+ }
107
+
108
+ # The newest version from npm's dist-tags answer on stdin, or nothing.
109
+ parse_latest() {
110
+ /usr/bin/sed -n 's/.*"latest":"\([0-9][0-9.]*\)".*/\1/p' | /usr/bin/head -n 1
111
+ }
112
+
113
+ latest_version() {
114
+ latest=$(/usr/bin/curl --proto '=https' --tlsv1.2 -fsS --max-time 20 "$REGISTRY/-/package/@astrofoundry%2fastrogate/dist-tags" 2>/dev/null | parse_latest || true)
115
+ valid_version "$latest" && printf '%s' "$latest" || true
116
+ }
117
+
118
+ fetch() {
119
+ /usr/bin/curl --proto '=https' --proto-redir '=https' --tlsv1.2 -fsSL --retry 2 --max-time 300 -o "$2" "$1" || fail "download failed: $1"
120
+ }
121
+
122
+ # A directory only root can change: owned by uid 0, not a link, writable by nobody else.
123
+ root_dir_problem() {
124
+ [ -d "$1" ] && [ ! -L "$1" ] || {
125
+ echo "$1 is not a directory"
126
+ return
127
+ }
128
+ set -- "$1" $(/usr/bin/stat -f '%u %Lp' "$1")
129
+ [ "$2" = 0 ] || {
130
+ echo "$1 is not owned by root"
131
+ return
132
+ }
133
+ case "$3" in *[2367] | *[2367]?) echo "$1 is writable by group or others" ;; esac
134
+ }
135
+
136
+ check_root_dir() {
137
+ problem=$(root_dir_problem "$1")
138
+ [ -z "$problem" ] || fail "$problem"
139
+ }
140
+
141
+ ensure_root_dir() {
142
+ [ -e "$1" ] || { /bin/mkdir -m 0755 "$1" && /usr/sbin/chown root:wheel "$1"; }
143
+ check_root_dir "$1"
144
+ }
145
+
146
+ # Points current at versions/$1, and previous at the version current named before.
147
+ switch_to() {
148
+ before=$(link_version current)
149
+ if [ -n "$before" ]; then
150
+ /bin/rm -f "$BASE/previous.new"
151
+ /bin/ln -s "versions/$before" "$BASE/previous.new"
152
+ /bin/mv -h "$BASE/previous.new" "$BASE/previous"
153
+ fi
154
+ /bin/rm -f "$BASE/current.new"
155
+ /bin/ln -s "versions/$1" "$BASE/current.new"
156
+ /bin/mv -h "$BASE/current.new" "$BASE/current"
157
+ }
158
+
159
+ # Removes every version that neither current nor previous names.
160
+ prune() {
161
+ keep_current=$(link_version current)
162
+ keep_previous=$(link_version previous)
163
+ for dir in "$BASE"/versions/*; do
164
+ [ -e "$dir" ] || continue
165
+ name=${dir##*/}
166
+ [ "$name" = "$keep_current" ] || [ "$name" = "$keep_previous" ] || /bin/rm -rf "$dir"
167
+ done
168
+ }
169
+
170
+ require_root() {
171
+ [ "$(/usr/bin/id -u)" = 0 ] || fail "run it as root: sudo astrogate core $action"
172
+ }
173
+
174
+ core_status() {
175
+ current=$(link_version current)
176
+ previous=$(link_version previous)
177
+ latest=$(latest_version)
178
+ echo "core ${current:-not installed}${previous:+, previous $previous}, newest on npm ${latest:-unknown}"
179
+ }
180
+
181
+ core_update() {
182
+ require_root
183
+ check_root_dir /
184
+ check_root_dir /usr
185
+ check_root_dir /usr/local
186
+ ensure_root_dir /usr/local/libexec
187
+ ensure_root_dir "$BASE"
188
+ ensure_root_dir "$BASE/versions"
189
+ if [ -f "$SIGNERS" ]; then
190
+ [ -z "$signers_arg" ] || /usr/bin/cmp -s "$signers_arg" "$SIGNERS" || fail "$SIGNERS exists and differs from $signers_arg; replace it by hand when the signing key changes"
191
+ signers=$SIGNERS
192
+ else
193
+ [ -n "$signers_arg" ] && [ -f "$signers_arg" ] || fail "no $SIGNERS yet: the first install needs --signers <the repo's allowed_signers>"
194
+ signers=$signers_arg
195
+ fi
196
+ current=$(link_version current)
197
+ if [ -z "$version" ]; then
198
+ version=$(latest_version)
199
+ [ -n "$version" ] || fail "cannot read the newest version from $REGISTRY"
200
+ if [ -n "$current" ] && version_lt "$version" "$current"; then
201
+ fail "npm names $version as newest, older than the installed $current; name a version to go back"
202
+ fi
203
+ fi
204
+ if [ "$version" = "$current" ]; then
205
+ echo "core $current is installed"
206
+ return 0
207
+ fi
208
+ # The installed core checks a new one; only the first install uses the copy next to this script.
209
+ if [ -n "$current" ]; then verifier=$BASE/current/cli/verify-release.sh; else verifier=$HERE/verify-release.sh; fi
210
+ [ -f "$verifier" ] || fail "$verifier is missing"
211
+
212
+ work=$(/usr/bin/mktemp -d /private/var/tmp/astrogate.XXXXXX)
213
+ trap '/bin/rm -rf "$work"' EXIT
214
+ trap 'exit 1' HUP INT TERM
215
+ fetch "$REGISTRY/@astrofoundry/astrogate/-/astrogate-$version.tgz" "$work/core.tgz"
216
+ /bin/mkdir "$work/check"
217
+ /bin/sh "$verifier" "$work/core.tgz" "$signers" "$version" "$work/check" >/dev/null
218
+
219
+ target=$BASE/versions/$version
220
+ /bin/rm -rf "$target.new"
221
+ /bin/mv "$work/check/package" "$target.new"
222
+ /usr/sbin/chown -R root:wheel "$target.new"
223
+ /bin/chmod -R u+rwX,go+rX,go-w "$target.new"
224
+ /bin/chmod 0755 "$target.new/cli/astrogate.sh" "$target.new/cli/verify-release.sh"
225
+ /bin/rm -rf "$target"
226
+ /bin/mv "$target.new" "$target"
227
+ switch_to "$version"
228
+ prune
229
+
230
+ if [ ! -f "$SIGNERS" ]; then
231
+ ensure_root_dir /usr/local/etc
232
+ ensure_root_dir "$SIGNERS_DIR"
233
+ /usr/bin/install -m 0644 -o root -g wheel "$signers" "$SIGNERS"
234
+ echo "installed $SIGNERS"
235
+ fi
236
+ ensure_root_dir /usr/local/bin
237
+ if [ "$(/usr/bin/readlink "$COMMAND" 2>/dev/null || true)" != "$BASE/current/cli/astrogate.sh" ]; then
238
+ /bin/ln -shf "$BASE/current/cli/astrogate.sh" "$COMMAND"
239
+ echo "linked $COMMAND"
240
+ fi
241
+ echo "core ${current:-none} -> $version${current:+; astrogate core rollback goes back to $current}"
242
+ }
243
+
244
+ core_rollback() {
245
+ require_root
246
+ current=$(link_version current)
247
+ previous=$(link_version previous)
248
+ [ -n "$previous" ] && [ -d "$BASE/versions/$previous" ] || fail "no previous core to roll back to"
249
+ switch_to "$previous"
250
+ echo "core $current -> $previous; astrogate core rollback again goes forward"
251
+ }
252
+
253
+ # --- doctor ---------------------------------------------------------------
254
+
255
+ failed=0
256
+ ok() { printf 'ok %s\n' "$*"; }
257
+ warn() { printf 'warn %s\n' "$*"; }
258
+ bad() {
259
+ printf 'FAIL %s\n' "$*"
260
+ failed=1
261
+ }
262
+
263
+ doctor() {
264
+ printf 'astrogate doctor on %s, macOS %s on %s\n' "$(/bin/hostname -s)" "$(/usr/bin/sw_vers -productVersion)" "$(/usr/bin/uname -m)"
265
+ current=$(link_version current)
266
+ if [ -z "$current" ] || [ ! -d "$BASE/versions/$current" ]; then
267
+ bad "no core in $BASE/current: install it (README, First install)"
268
+ [ "$failed" = 0 ] || exit 1
269
+ fi
270
+ problems=""
271
+ for dir in / /usr /usr/local /usr/local/libexec "$BASE" "$BASE/versions" "$BASE/versions/$current"; do
272
+ problem=$(root_dir_problem "$dir")
273
+ [ -z "$problem" ] || problems="$problems; $problem"
274
+ done
275
+ unsafe=$(/usr/bin/find "$BASE/versions/$current" \( ! -user root -o -perm -0002 -o -perm -0020 \) -print 2>/dev/null | /usr/bin/head -n 3)
276
+ [ -z "$unsafe" ] || problems="$problems; not root-only: $(printf '%s' "$unsafe" | /usr/bin/tr '\n' ' ')"
277
+ if [ -z "$problems" ]; then ok "core folders are root-only"; else bad "core folders${problems}"; fi
278
+
279
+ if [ -f "$SIGNERS" ] && [ "$(/usr/bin/stat -f '%u %Lp' "$SIGNERS")" = "0 644" ]; then
280
+ ok "$SIGNERS"
281
+ if result=$(/bin/sh "$BASE/current/cli/verify-release.sh" --tree "$BASE/versions/$current" "$SIGNERS" "$current" 2>&1); then
282
+ ok "core $current matches its signed release.sha256"
283
+ else
284
+ bad "core $current: $result"
285
+ fi
286
+ else
287
+ bad "$SIGNERS is missing or not root with mode 644"
288
+ fi
289
+
290
+ latest=$(latest_version)
291
+ if [ -z "$latest" ]; then
292
+ warn "cannot read the newest core from $REGISTRY"
293
+ elif version_lt "$current" "$latest"; then
294
+ warn "core $current; $latest is published (sudo astrogate core update)"
295
+ else
296
+ ok "core $current is the newest"
297
+ fi
298
+ previous=$(link_version previous)
299
+ if [ -n "$previous" ] && [ -d "$BASE/versions/$previous" ]; then ok "previous core $previous kept for rollback"; else warn "no previous core to roll back to"; fi
300
+ if [ "$(/usr/bin/readlink "$COMMAND" 2>/dev/null || true)" = "$BASE/current/cli/astrogate.sh" ]; then ok "$COMMAND"; else bad "$COMMAND does not link to $BASE/current/cli/astrogate.sh"; fi
301
+ [ "$failed" = 0 ] || exit 1
302
+ }
303
+
304
+ case "$action" in
305
+ status) core_status ;;
306
+ update) core_update ;;
307
+ rollback) core_rollback ;;
308
+ doctor) doctor ;;
309
+ esac
@@ -0,0 +1,113 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { describe, expect, it } from "vitest";
6
+
7
+ const SCRIPT = join(import.meta.dirname, "astrogate.sh");
8
+ const isRoot = process.getuid?.() === 0;
9
+ const isMac = process.platform === "darwin";
10
+
11
+ function astrogate(...args: string[]) {
12
+ return spawnSync("/bin/sh", [SCRIPT, ...args], { encoding: "utf-8" });
13
+ }
14
+
15
+ /** Runs the named shell functions of the script on their own, followed by `call`. */
16
+ function shellFunctions(names: string[], call: string) {
17
+ const source = readFileSync(SCRIPT, "utf-8");
18
+ const bodies = names.map((name) => {
19
+ const match = new RegExp(`^${name}\\(\\) \\{\\n[\\s\\S]*?^\\}`, "m").exec(source);
20
+ if (!match) throw new Error(`${name} not found in the script`);
21
+ return match[0];
22
+ });
23
+ return spawnSync("/bin/sh", ["-c", `set -eu\n${bodies.join("\n")}\n${call}`], { encoding: "utf-8" });
24
+ }
25
+
26
+ describe("astrogate", () => {
27
+ it("parses as POSIX sh", () => {
28
+ expect(spawnSync("/bin/sh", ["-n", SCRIPT]).status).toBe(0);
29
+ });
30
+
31
+ it.each([
32
+ [[]],
33
+ [["core", "status", "now"]],
34
+ [["core", "bogus"]],
35
+ [["core", "update", "1.2"]],
36
+ [["core", "update", "v1.2.3"]],
37
+ [["core", "update", "01.2.3"]],
38
+ [["core", "update", "1.2.3\nrm"]],
39
+ [["core", "update", "1.2.3", "1.2.4"]],
40
+ [["core", "update", "--signers"]],
41
+ [["core", "update", "--signers", ""]],
42
+ [["core", "update", "--signers", "a", "--signers", "b"]],
43
+ [["core", "rollback", "1.2.3"]],
44
+ [["doctor", "now"]],
45
+ [["update"]],
46
+ ])("refuses %j with a usage error before anything else", (args) => {
47
+ const result = astrogate(...args);
48
+ expect(result.status).toBe(2);
49
+ expect(result.stderr).toMatch(/^usage: astrogate/);
50
+ });
51
+
52
+ it.runIf(isMac && !isRoot).each([["update"], ["update", "1.2.3", "--signers", "x"], ["rollback"]])("refuses core %s without root", (...args) => {
53
+ const result = astrogate("core", ...args);
54
+ expect(result.status).toBe(1);
55
+ expect(result.stderr).toContain("run it as root: sudo astrogate core");
56
+ });
57
+
58
+ it.each([
59
+ ["0.1.9", "0.1.10", 0],
60
+ ["0.1.10", "0.1.10", 1],
61
+ ["0.2.0", "0.1.10", 1],
62
+ ["0.9.200", "0.10.0", 0],
63
+ ["1.0.0", "0.99.99", 1],
64
+ ])("version_lt %s %s exits %i", (a, b, code) => {
65
+ expect(shellFunctions(["version_lt"], `version_lt ${a} ${b}`).status).toBe(code);
66
+ });
67
+
68
+ it.each([
69
+ ['{"legacy-node20":"0.74.2","latest":"1.8.0"}', "1.8.0"],
70
+ ['{"latest":"0.1.1"}', "0.1.1"],
71
+ ['{"next":"2.0.0"}', ""],
72
+ ["<html>error</html>", ""],
73
+ ])("parse_latest reads %s", (answer, expected) => {
74
+ const result = shellFunctions(["parse_latest"], `printf '%s' '${answer}' | parse_latest`);
75
+ expect(result.status).toBe(0);
76
+ expect(result.stdout.trim()).toBe(expected);
77
+ });
78
+
79
+ it.runIf(isMac)("switches current and previous, prunes the rest, and rolls back by swapping", () => {
80
+ const base = mkdtempSync(join(tmpdir(), "astrogate-core-"));
81
+ try {
82
+ for (const v of ["1.0.0", "1.1.0", "1.2.0"]) mkdirSync(join(base, "versions", v), { recursive: true });
83
+ const run = (call: string) => shellFunctions(["valid_version", "link_version", "switch_to", "prune"], `BASE='${base}'\n${call}`);
84
+ const links = () => ({ current: readlinkSync(join(base, "current")), previous: readlinkSync(join(base, "previous")) });
85
+
86
+ expect(run("switch_to 1.0.0").status).toBe(0);
87
+ expect(readlinkSync(join(base, "current"))).toBe("versions/1.0.0");
88
+ expect(run("switch_to 1.1.0 && switch_to 1.2.0 && prune").status).toBe(0);
89
+ expect(links()).toEqual({ current: "versions/1.2.0", previous: "versions/1.1.0" });
90
+ expect(readdirSync(join(base, "versions")).sort()).toEqual(["1.1.0", "1.2.0"]);
91
+
92
+ expect(run('switch_to "$(link_version previous)"').status).toBe(0);
93
+ expect(links()).toEqual({ current: "versions/1.1.0", previous: "versions/1.2.0" });
94
+ expect(run("link_version current").stdout).toBe("1.1.0");
95
+ expect(readdirSync(base).sort()).toEqual(["current", "previous", "versions"]);
96
+ } finally {
97
+ rmSync(base, { recursive: true, force: true });
98
+ }
99
+ });
100
+
101
+ it("link_version ignores a link outside versions/ or with a bad version", () => {
102
+ const base = mkdtempSync(join(tmpdir(), "astrogate-core-"));
103
+ try {
104
+ const read = (target: string) => shellFunctions(["valid_version", "link_version"], `BASE='${base}'\nrm -f '${base}/current'\nln -s '${target}' '${base}/current'\nlink_version current`).stdout;
105
+ expect(read("versions/1.2.3")).toBe("1.2.3");
106
+ expect(read("/etc")).toBe("");
107
+ expect(read("versions/1.2")).toBe("");
108
+ expect(shellFunctions(["valid_version", "link_version"], `BASE='${base}'\nlink_version previous`).stdout).toBe("");
109
+ } finally {
110
+ rmSync(base, { recursive: true, force: true });
111
+ }
112
+ });
113
+ });
@@ -0,0 +1,77 @@
1
+ #!/bin/sh
2
+ # Checks a core release before anything from it runs: a valid astrogate-core
3
+ # signature on release.sha256, every file listed with its hash, nothing unlisted,
4
+ # no links, and the expected version. CI runs it on the tarball it publishes; a
5
+ # host runs the installed core's copy on a downloaded tarball, and `astrogate
6
+ # doctor` runs it on the installed tree. It uses only system programs, so root
7
+ # can run it.
8
+ #
9
+ # verify-release.sh <tarball> <allowed_signers> <version> <empty folder>
10
+ # also refuses a tarball with anything but regular files under package/;
11
+ # the package lands in <folder>/package
12
+ # verify-release.sh --tree <package folder> <allowed_signers> <version>
13
+ set -eu
14
+ PATH=/usr/bin:/bin:/usr/sbin:/sbin
15
+ export PATH
16
+
17
+ usage() {
18
+ echo "usage: verify-release.sh <tarball> <allowed_signers> <version> <empty folder> | --tree <package folder> <allowed_signers> <version>" >&2
19
+ exit 2
20
+ }
21
+ fail() {
22
+ echo "verify-release: $*" >&2
23
+ exit 1
24
+ }
25
+
26
+ # x.y.z with plain decimal parts; the character check also rules out newlines.
27
+ valid_version() {
28
+ case "$1" in '' | *[!0-9.]*) return 1 ;; esac
29
+ printf '%s\n' "$1" | grep -Eq '^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$'
30
+ }
31
+
32
+ # Signature, hashes, listing, and version of an unpacked package folder.
33
+ check_tree() {
34
+ pkg=$1
35
+ [ -z "$(cd "$pkg" && find . ! -type f ! -type d)" ] || fail "$pkg holds links or other entries that are not files"
36
+ [ -f "$pkg/release.sha256" ] && [ -f "$pkg/release.sha256.sig" ] || fail "the package has no release.sha256 and signature"
37
+ ssh-keygen -Y verify -f "$signers" -I astrogate -n astrogate-core -s "$pkg/release.sha256.sig" <"$pkg/release.sha256" >/dev/null 2>&1 ||
38
+ fail "the signature on release.sha256 does not verify against $signers"
39
+ (cd "$pkg" && shasum -a 256 -c --quiet release.sha256 >/dev/null 2>&1) || fail "a file differs from release.sha256"
40
+ listed=$(cut -c67- "$pkg/release.sha256" | sort)
41
+ actual=$(cd "$pkg" && find . -type f ! -path ./release.sha256 ! -path ./release.sha256.sig | sed 's|^\./||' | sort)
42
+ [ "$listed" = "$actual" ] || fail "the package holds files release.sha256 does not list, or misses listed ones"
43
+ # The signed package.json keeps npm's two-space layout, so its one top-level version line is exact.
44
+ found=$(sed -n 's/^ "version": "\([0-9][0-9.]*\)",\{0,1\}$/\1/p' "$pkg/package.json")
45
+ [ "$found" = "$version" ] || fail "the package is version ${found:-unknown}, not $version"
46
+ }
47
+
48
+ if [ "${1:-}" = --tree ]; then
49
+ [ $# -eq 4 ] || usage
50
+ pkg=$2 signers=$3 version=$4
51
+ valid_version "$version" || fail "$version is not a version like 1.2.3"
52
+ [ -d "$pkg" ] || fail "$pkg is not a folder"
53
+ [ -f "$signers" ] || fail "$signers is missing"
54
+ check_tree "$pkg"
55
+ echo "verify-release: @astrofoundry/astrogate $version in $pkg is signed and complete"
56
+ exit 0
57
+ fi
58
+
59
+ [ $# -eq 4 ] || usage
60
+ tarball=$1 signers=$2 version=$3 out=$4
61
+ valid_version "$version" || fail "$version is not a version like 1.2.3"
62
+ [ -f "$tarball" ] || fail "$tarball is missing"
63
+ [ -f "$signers" ] || fail "$signers is missing"
64
+ [ -d "$out" ] && [ -z "$(ls -A "$out")" ] || fail "$out must be an empty folder"
65
+
66
+ types=$(tar -tvzf "$tarball" | cut -c1 | sort -u)
67
+ [ "$types" = "-" ] || fail "$tarball holds entries other than regular files"
68
+ tar -tzf "$tarball" | while IFS= read -r name; do
69
+ case "$name" in
70
+ package/*) ;;
71
+ *) fail "$tarball has $name outside package/" ;;
72
+ esac
73
+ case "/$name/" in */../*) fail "$tarball has $name with .." ;; esac
74
+ done
75
+ tar -xzf "$tarball" --no-same-owner -C "$out"
76
+ check_tree "$out/package"
77
+ echo "verify-release: @astrofoundry/astrogate $version is signed and complete"
@@ -0,0 +1,140 @@
1
+ import { execFileSync, spawnSync } from "node:child_process";
2
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
6
+ import { MANIFEST, manifestText, NAMESPACE, SIGNATURE } from "../scripts/manifest.ts";
7
+
8
+ const VERIFY = join(import.meta.dirname, "verify-release.sh");
9
+ let home: string;
10
+ let signers: string;
11
+ let n = 0;
12
+
13
+ function keygen(name: string): string {
14
+ const key = join(home, name);
15
+ execFileSync("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", name, "-f", key]);
16
+ return key;
17
+ }
18
+
19
+ interface Options {
20
+ version?: string;
21
+ key?: string;
22
+ namespace?: string;
23
+ afterSigning?: (pkg: string) => void;
24
+ extraEntries?: string[];
25
+ }
26
+
27
+ /** A package/ tarball like `npm pack` makes, signed with the trusted key unless told otherwise. */
28
+ function tarball(options: Options = {}): string {
29
+ const pkg = signedPackage(options);
30
+ const dir = join(pkg, "..");
31
+ const entries = [...FILES, MANIFEST, SIGNATURE, ...(options.extraEntries ?? [])].map((f) => `package/${f}`);
32
+ const out = join(dir, "pkg.tgz");
33
+ execFileSync("tar", ["-czf", out, "-C", dir, ...entries], { env: { ...process.env, COPYFILE_DISABLE: "1" } });
34
+ return out;
35
+ }
36
+
37
+ const FILES = ["dist/bridge.js", "package.json"];
38
+
39
+ /** An unpacked package folder, signed with the trusted key unless told otherwise. */
40
+ function signedPackage(options: Options = {}): string {
41
+ const pkg = join(home, `pkg-${n++}`, "package");
42
+ mkdirSync(join(pkg, "dist"), { recursive: true });
43
+ writeFileSync(join(pkg, "package.json"), `${JSON.stringify({ name: "@astrofoundry/astrogate", version: "1.2.3" }, null, 2)}\n`);
44
+ writeFileSync(join(pkg, "dist", "bridge.js"), "console.log('bridge');\n");
45
+ writeFileSync(join(pkg, MANIFEST), manifestText(pkg, FILES));
46
+ execFileSync("ssh-keygen", ["-Y", "sign", "-q", "-f", options.key ?? join(home, "trusted"), "-n", options.namespace ?? NAMESPACE, join(pkg, MANIFEST)]);
47
+ options.afterSigning?.(pkg);
48
+ return pkg;
49
+ }
50
+
51
+ function verify(file: string, version = "1.2.3") {
52
+ const out = join(home, `out-${n++}`);
53
+ mkdirSync(out);
54
+ return spawnSync("sh", [VERIFY, file, signers, version, out], { encoding: "utf-8" });
55
+ }
56
+
57
+ function verifyTree(pkg: string, version = "1.2.3") {
58
+ return spawnSync("sh", [VERIFY, "--tree", pkg, signers, version], { encoding: "utf-8" });
59
+ }
60
+
61
+ beforeAll(() => {
62
+ home = mkdtempSync(join(tmpdir(), "astrogate-verify-"));
63
+ const trusted = keygen("trusted");
64
+ keygen("stranger");
65
+ signers = join(home, "allowed_signers");
66
+ writeFileSync(signers, `astrogate namespaces="${NAMESPACE}" ${readFileSync(`${trusted}.pub`, "utf-8").split(" ").slice(0, 2).join(" ")}\n`);
67
+ });
68
+
69
+ afterAll(() => rmSync(home, { recursive: true, force: true }));
70
+
71
+ describe("verify-release.sh", () => {
72
+ it("accepts a signed, complete package of the expected version", () => {
73
+ const result = verify(tarball());
74
+ expect(result.stderr).toBe("");
75
+ expect(result.status).toBe(0);
76
+ expect(result.stdout).toContain("1.2.3 is signed and complete");
77
+ });
78
+
79
+ it("refuses a file changed after signing", () => {
80
+ const result = verify(tarball({ afterSigning: (pkg) => writeFileSync(join(pkg, "dist", "bridge.js"), "evil();\n") }));
81
+ expect(result.status).toBe(1);
82
+ expect(result.stderr).toContain("a file differs");
83
+ });
84
+
85
+ it("refuses a file the manifest does not list", () => {
86
+ const result = verify(tarball({ afterSigning: (pkg) => writeFileSync(join(pkg, "dist", "extra.js"), "evil();\n"), extraEntries: ["dist/extra.js"] }));
87
+ expect(result.status).toBe(1);
88
+ expect(result.stderr).toContain("does not list");
89
+ });
90
+
91
+ it("refuses another version", () => {
92
+ const result = verify(tarball(), "1.2.4");
93
+ expect(result.status).toBe(1);
94
+ expect(result.stderr).toContain("version 1.2.3, not 1.2.4");
95
+ });
96
+
97
+ it("refuses a signature from another key or for another namespace", () => {
98
+ expect(verify(tarball({ key: join(home, "stranger") })).stderr).toContain("does not verify");
99
+ expect(verify(tarball({ namespace: "astro-pack" })).stderr).toContain("does not verify");
100
+ });
101
+
102
+ it("refuses a link inside the tarball", () => {
103
+ const result = verify(tarball({ afterSigning: (pkg) => symlinkSync("/etc/hosts", join(pkg, "dist", "link")), extraEntries: ["dist/link"] }));
104
+ expect(result.status).toBe(1);
105
+ expect(result.stderr).toContain("other than regular files");
106
+ });
107
+ });
108
+
109
+ describe("verify-release.sh --tree", () => {
110
+ it("accepts an unpacked, signed, complete package", () => {
111
+ const result = verifyTree(signedPackage());
112
+ expect(result.stderr).toBe("");
113
+ expect(result.status).toBe(0);
114
+ expect(result.stdout).toContain("1.2.3 in");
115
+ });
116
+
117
+ it("refuses a file changed after install", () => {
118
+ const result = verifyTree(signedPackage({ afterSigning: (pkg) => writeFileSync(join(pkg, "dist", "bridge.js"), "evil();\n") }));
119
+ expect(result.status).toBe(1);
120
+ expect(result.stderr).toContain("a file differs");
121
+ });
122
+
123
+ it("refuses a file added after install", () => {
124
+ const result = verifyTree(signedPackage({ afterSigning: (pkg) => writeFileSync(join(pkg, "dist", "extra.js"), "evil();\n") }));
125
+ expect(result.status).toBe(1);
126
+ expect(result.stderr).toContain("does not list");
127
+ });
128
+
129
+ it("refuses a link, even to a listed file", () => {
130
+ const result = verifyTree(signedPackage({ afterSigning: (pkg) => symlinkSync("bridge.js", join(pkg, "dist", "link.js")) }));
131
+ expect(result.status).toBe(1);
132
+ expect(result.stderr).toContain("not files");
133
+ });
134
+
135
+ it("refuses another version and bad arguments", () => {
136
+ expect(verifyTree(signedPackage(), "1.2.4").stderr).toContain("version 1.2.3, not 1.2.4");
137
+ expect(verifyTree(signedPackage(), "1.2.3\nx").stderr).toContain("not a version");
138
+ expect(spawnSync("sh", [VERIFY, "--tree", "x"], { encoding: "utf-8" }).status).toBe(2);
139
+ });
140
+ });