@tirso0882/factory 0.0.0-stage → 0.1.0

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/shared/ci.mts ADDED
@@ -0,0 +1,128 @@
1
+ // Waiting for CI on a commit, and reading what failed.
2
+
3
+ import { setTimeout as sleep } from "node:timers/promises"
4
+ import type { Timeouts } from "./factory.mts"
5
+ import { TicketFailure } from "./failures.mts"
6
+ import { REPO, gh, ghJson, onHost } from "./host.mts"
7
+
8
+ type CheckRun = {
9
+ id: number
10
+ name: string
11
+ status: string
12
+ conclusion: string | null
13
+ html_url: string
14
+ }
15
+
16
+ const FAILED = new Set([
17
+ "failure",
18
+ "timed_out",
19
+ "cancelled",
20
+ "action_required",
21
+ "startup_failure",
22
+ ])
23
+
24
+ /** CI on a commit, once every check finished. */
25
+ export type CiResult = { passed: true } | { passed: false; log: string }
26
+
27
+ const MAX_LOG_CHARS_PER_CHECK = 12_000
28
+ const MAX_LOG_CHARS = 40_000
29
+
30
+ /** The failed steps' output for each failed check, newest lines kept. */
31
+ const failureLog = (failed: CheckRun[]) => {
32
+ const sections = failed.map((check) => {
33
+ let log: string
34
+ try {
35
+ // For GitHub Actions a check run's id is its job's id.
36
+ log = gh(
37
+ "run",
38
+ "view",
39
+ "--repo",
40
+ REPO,
41
+ "--job",
42
+ String(check.id),
43
+ "--log-failed"
44
+ )
45
+ // "<job>\t<step>\t<timestamp> <line>" → "<step> | <line>"
46
+ .replace(/^[^\t\n]*\t([^\t\n]*)\t\S+ /gm, "$1 | ")
47
+ .slice(-MAX_LOG_CHARS_PER_CHECK)
48
+ } catch (error) {
49
+ log = `(couldn't fetch the log: ${String(error).split("\n")[0]})`
50
+ }
51
+ return `## ${check.name}: ${check.conclusion}\n\n${check.html_url}\n\n${log}`
52
+ })
53
+ return sections.join("\n\n").slice(-MAX_LOG_CHARS)
54
+ }
55
+
56
+ /**
57
+ * Wait for every check on `sha` to finish.
58
+ *
59
+ * Asks for the commit's check runs rather than `gh pr checks`: right after a
60
+ * push the pull request can still show the previous commit's results.
61
+ */
62
+ export const waitForChecks = async (
63
+ timeouts: Timeouts,
64
+ sha: string,
65
+ signal: AbortSignal
66
+ ): Promise<CiResult> => {
67
+ const deadline = Date.now() + timeouts.ciMs
68
+ let finishedCount = -1
69
+ for (;;) {
70
+ await sleep(timeouts.ciPollMs, undefined, { signal })
71
+ if (Date.now() > deadline) {
72
+ throw new TicketFailure(
73
+ `CI didn't finish within ${timeouts.ciMs / 60_000} minutes.`
74
+ )
75
+ }
76
+ let runs: CheckRun[]
77
+ try {
78
+ runs = checkRuns(sha)
79
+ } catch (error) {
80
+ console.warn(
81
+ ` Couldn't read the checks: ${String(error).split("\n")[0]}`
82
+ )
83
+ continue
84
+ }
85
+ if (runs.length === 0 || runs.some((r) => r.status !== "completed")) {
86
+ finishedCount = -1
87
+ continue
88
+ }
89
+ // Everything is done. Look once more, so a workflow that registers late
90
+ // isn't missed.
91
+ if (runs.length !== finishedCount) {
92
+ finishedCount = runs.length
93
+ continue
94
+ }
95
+ return verdict(runs)
96
+ }
97
+ }
98
+
99
+ const checkRuns = (sha: string) =>
100
+ ghJson<{ check_runs: CheckRun[] }>(
101
+ "api",
102
+ `repos/${REPO}/commits/${sha}/check-runs?per_page=100`
103
+ ).check_runs
104
+
105
+ /** Every run has finished: whether they passed, and the log if not. */
106
+ const verdict = (runs: CheckRun[]): CiResult => {
107
+ const failed = runs.filter((r) => FAILED.has(r.conclusion ?? ""))
108
+ return failed.length === 0
109
+ ? { passed: true }
110
+ : { passed: false, log: failureLog(failed) }
111
+ }
112
+
113
+ /**
114
+ * CI on `sha`, a commit pushed a while ago: a pull request's head. Waits for
115
+ * checks still running. A commit with no checks counts as passing.
116
+ */
117
+ export const checksOn = async (
118
+ timeouts: Timeouts,
119
+ sha: string,
120
+ signal: AbortSignal
121
+ ): Promise<CiResult> => {
122
+ const runs = onHost("Reading the checks", () => checkRuns(sha))
123
+ if (runs.length === 0) return { passed: true }
124
+ if (runs.some((r) => r.status !== "completed")) {
125
+ return waitForChecks(timeouts, sha, signal)
126
+ }
127
+ return verdict(runs)
128
+ }
@@ -0,0 +1,92 @@
1
+ // Which of a sandbox's variables should never have reached it. Ported from
2
+ // Sandcastle's own `verify/envLeaks.ts`. Pure: no git, gh or file reads
3
+ // here, so the tests can load it (env-leaks.test.mts).
4
+
5
+ export type EnvLeak = { name: string; reason: string }
6
+
7
+ export type EnvContext = {
8
+ /** Keys `.sandcastle/.env` declares: Sandcastle passes these on purpose. */
9
+ declared: ReadonlySet<string>
10
+ /** The host's secrets, name → value. */
11
+ hostSecrets: ReadonlyMap<string, string>
12
+ /** A random value set on the host and declared nowhere. */
13
+ canary: string
14
+ }
15
+
16
+ /** A name that looks like it holds a secret. */
17
+ const SECRET_NAME = /TOKEN|KEY|SECRET|PASSWORD/i
18
+
19
+ /** The secret-looking variables of `env`, name → value. */
20
+ export const secretsIn = (env: NodeJS.ProcessEnv) =>
21
+ new Map(
22
+ Object.entries(env).filter(
23
+ (entry): entry is [string, string] =>
24
+ SECRET_NAME.test(entry[0]) && entry[1] !== undefined
25
+ )
26
+ )
27
+
28
+ /**
29
+ * The name/value pairs of a `.env` file, read the way Sandcastle reads
30
+ * `.sandcastle/.env`: blank lines and comments skipped, quotes stripped.
31
+ */
32
+ export const parseEnvFile = (text: string): [string, string][] =>
33
+ text.split("\n").flatMap((line) => {
34
+ const match = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(line)
35
+ if (!match?.[1]) return []
36
+ const value = (match[2] ?? "").trim().replace(/^(["'])(.*)\1$/, "$2")
37
+ return [[match[1], value]]
38
+ })
39
+
40
+ /** Printed before `env -0`, so output cut down to its tail shows. */
41
+ export const ENV_START = "env-start"
42
+
43
+ /** The command that prints the sandbox's environment for `parseEnvDump`. */
44
+ export const ENV_DUMP_COMMAND = `printf '${ENV_START}\\0' && env -0`
45
+
46
+ /** The sandbox's name/value pairs, or `undefined` if the dump was cut short. */
47
+ export const parseEnvDump = (
48
+ stdout: string
49
+ ): [string, string][] | undefined => {
50
+ const [start, ...entries] = stdout.split("\0")
51
+ if (start !== ENV_START) return undefined
52
+ return entries
53
+ .filter((entry) => entry.includes("="))
54
+ .map((entry) => {
55
+ const at = entry.indexOf("=")
56
+ return [entry.slice(0, at), entry.slice(at + 1)]
57
+ })
58
+ }
59
+
60
+ // A shorter value (an empty key, a port, a flag) would turn up in ordinary
61
+ // variables by chance, so it's matched by its name only.
62
+ const MIN_SECRET_LENGTH = 8
63
+
64
+ /** Every leaked variable in `env`, the sandbox's name/value pairs. */
65
+ export const classifyEnv = (
66
+ env: readonly (readonly [string, string])[],
67
+ ctx: EnvContext
68
+ ): EnvLeak[] => {
69
+ const leaks: EnvLeak[] = []
70
+ for (const [name, value] of env) {
71
+ if (ctx.canary && value.includes(ctx.canary)) {
72
+ leaks.push({ name, reason: "carries the canary, which no .env declares" })
73
+ continue
74
+ }
75
+ if (ctx.declared.has(name)) continue
76
+ if (ctx.hostSecrets.has(name)) {
77
+ leaks.push({ name, reason: "a host secret no .env declares" })
78
+ continue
79
+ }
80
+ for (const [hostName, hostValue] of ctx.hostSecrets) {
81
+ if (ctx.declared.has(hostName) || hostValue.length < MIN_SECRET_LENGTH)
82
+ continue
83
+ if (!value.includes(hostValue)) continue
84
+ leaks.push({
85
+ name,
86
+ reason: `carries the value of host ${hostName}, which no .env declares`,
87
+ })
88
+ break
89
+ }
90
+ }
91
+ return leaks
92
+ }