@patronage/factory-ci 1.0.0-alpha.4 → 1.0.0-alpha.40
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 +712 -10
- package/dist/.build-fingerprint.json +3 -0
- package/dist/alchemy/index.d.ts +1174 -0
- package/dist/alchemy/index.js +2142 -0
- package/dist/bundle-alchemy-entry-CT5hCphA.js +112 -0
- package/dist/execute-alchemy-entry-B397GSk5.d.ts +134 -0
- package/dist/execute-alchemy-entry-CZ7Knz4q.js +160 -0
- package/dist/index.d.ts +1205 -87
- package/dist/index.js +2752 -317
- package/package.json +28 -10
- package/src/actions.ts +13 -0
- package/src/alchemy/child-diagnostics.ts +148 -0
- package/src/alchemy/credential-preflight.ts +428 -0
- package/src/alchemy/destroy-postcondition.ts +103 -0
- package/src/alchemy/evaluate-stack.ts +153 -0
- package/src/alchemy/first-deploy-authorization.ts +194 -0
- package/src/alchemy/index.ts +144 -0
- package/src/alchemy/lifecycle-failure.ts +174 -0
- package/src/alchemy/lifecycle.ts +1330 -0
- package/src/alchemy/local-emulation.ts +89 -0
- package/src/alchemy/plan-effects.ts +510 -0
- package/src/alchemy/retained-identity.ts +248 -0
- package/src/alchemy/secret-name-policy.ts +96 -0
- package/src/alchemy/stage-policy.ts +269 -0
- package/src/alchemy/state-tree.ts +168 -0
- package/src/alchemy/url-implies-auth.ts +264 -0
- package/src/alchemy-baseline.ts +75 -0
- package/src/bundle-alchemy-entry.ts +5 -0
- package/src/candidate-impact-workflow.ts +110 -0
- package/src/candidate-lifecycle.ts +29 -0
- package/src/cursor-oidc.ts +33 -0
- package/src/execute-alchemy-entry.ts +128 -8
- package/src/factory-workflow.ts +83 -40
- package/src/github-app-token.ts +92 -18
- package/src/github-transport.ts +186 -0
- package/src/impact-demand-condition.ts +67 -0
- package/src/index.ts +174 -0
- package/src/lifecycle-contract-lane.ts +113 -0
- package/src/merge-freeze-job.ts +253 -0
- package/src/pinned-action.ts +30 -0
- package/src/pr-status-hud-workflow.ts +96 -0
- package/src/preview-cleanup-topology.ts +115 -0
- package/src/preview-proof-inventory.ts +1092 -0
- package/src/preview-proof-lifecycle.ts +328 -0
- package/src/preview-receipt-workflow.ts +83 -0
- package/src/production-impact-workflow.ts +181 -0
- package/src/proof-reuse-gate.ts +223 -48
- package/src/proof-reuse-presentation.ts +131 -0
- package/src/push-identity-workflow.ts +463 -0
- package/src/runnable-cli.ts +27 -0
- package/src/verify-runner-policy.ts +290 -0
- package/src/vitest-profile-reader.test.ts +208 -0
- package/src/vitest-profile-reader.ts +225 -0
- package/src/vitest-profile.ts +631 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@patronage/factory-ci",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.40",
|
|
4
4
|
"description": "Deep CI and deploy building blocks for Patronage factory projects: workflow source artifacts, hosted diff classification, Alchemy entry execution, and disposable-stage semantics",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"alchemy",
|
|
@@ -22,16 +22,17 @@
|
|
|
22
22
|
"type": "module",
|
|
23
23
|
"exports": {
|
|
24
24
|
".": {
|
|
25
|
-
"development": {
|
|
26
|
-
"types": "./src/index.ts",
|
|
27
|
-
"default": "./src/index.ts"
|
|
28
|
-
},
|
|
29
25
|
"types": "./dist/index.d.ts",
|
|
30
26
|
"default": "./dist/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./alchemy": {
|
|
29
|
+
"types": "./dist/alchemy/index.d.ts",
|
|
30
|
+
"default": "./dist/alchemy/index.js"
|
|
31
31
|
}
|
|
32
32
|
},
|
|
33
33
|
"publishConfig": {
|
|
34
|
-
"access": "public"
|
|
34
|
+
"access": "public",
|
|
35
|
+
"tag": "next"
|
|
35
36
|
},
|
|
36
37
|
"dependencies": {
|
|
37
38
|
"esbuild": "0.28.1"
|
|
@@ -39,19 +40,36 @@
|
|
|
39
40
|
"devDependencies": {
|
|
40
41
|
"@types/node": "24.13.3",
|
|
41
42
|
"@vitest/coverage-v8": "4.1.10",
|
|
43
|
+
"alchemy": "2.0.0-beta.77",
|
|
44
|
+
"effect": "4.0.0-rc.112",
|
|
45
|
+
"knip": "6.27.0",
|
|
42
46
|
"oxfmt": "0.59.0",
|
|
43
|
-
"oxlint": "1.
|
|
47
|
+
"oxlint": "1.76.0",
|
|
44
48
|
"tsdown": "0.21.10",
|
|
45
49
|
"typescript": "5.9.3",
|
|
46
|
-
"ultracite": "7.
|
|
47
|
-
"vitest": "4.1.10"
|
|
50
|
+
"ultracite": "7.10.5",
|
|
51
|
+
"vitest": "4.1.10",
|
|
52
|
+
"@patronage/alchemy-d1-state": "0.4.0"
|
|
53
|
+
},
|
|
54
|
+
"peerDependencies": {
|
|
55
|
+
"alchemy": ">=2.0.0-beta.63 <3",
|
|
56
|
+
"effect": ">=4.0.0-beta.98 <5"
|
|
57
|
+
},
|
|
58
|
+
"peerDependenciesMeta": {
|
|
59
|
+
"alchemy": {
|
|
60
|
+
"optional": true
|
|
61
|
+
},
|
|
62
|
+
"effect": {
|
|
63
|
+
"optional": true
|
|
64
|
+
}
|
|
48
65
|
},
|
|
49
66
|
"engines": {
|
|
50
67
|
"node": "^24.0.0"
|
|
51
68
|
},
|
|
52
69
|
"scripts": {
|
|
70
|
+
"cleanup:check": "knip --files --dependencies --exports",
|
|
53
71
|
"prebuild": "bash ../scripts/ensure-worktree-bootstrap.sh",
|
|
54
|
-
"build": "tsdown",
|
|
72
|
+
"build": "tsdown && node ../scripts/factory-ci-dist-stamp.mjs write",
|
|
55
73
|
"precheck": "bash ../scripts/ensure-worktree-bootstrap.sh",
|
|
56
74
|
"check": "ultracite check",
|
|
57
75
|
"prefix": "bash ../scripts/ensure-worktree-bootstrap.sh",
|
package/src/actions.ts
CHANGED
|
@@ -52,3 +52,16 @@ export const NODE_PNPM_ACTION_FAMILY_NODE24 = {
|
|
|
52
52
|
uses: "pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271",
|
|
53
53
|
},
|
|
54
54
|
} as const satisfies NodePnpmActionFamily;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The one `actions/upload-artifact` pin every workflow generator shares
|
|
58
|
+
* (#887). Two callers pinned two different commits of the same tag family;
|
|
59
|
+
* naming the pin here makes that drift impossible the same way the Node/pnpm
|
|
60
|
+
* family does. A caller passes this through `factoryWorkflow`'s
|
|
61
|
+
* `additionalActions.uploadArtifact` explicitly — the catalog names the pin,
|
|
62
|
+
* it does not inject the upload step.
|
|
63
|
+
*/
|
|
64
|
+
export const UPLOAD_ARTIFACT = {
|
|
65
|
+
tag: "v4.6.2",
|
|
66
|
+
uses: "actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02",
|
|
67
|
+
} as const satisfies PinnedAction;
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The optional record of what an Alchemy child printed (#1260).
|
|
3
|
+
*
|
|
4
|
+
* `runAlchemyLifecycle` reports a failed child as `CHILD_FAILED` and nothing
|
|
5
|
+
* else: the child's output is parsed and dropped, so no secret in it can
|
|
6
|
+
* reach a job log or an evidence file through the operation. That is the
|
|
7
|
+
* right default and it stays the default. It also leaves an operator with a
|
|
8
|
+
* failure code and no record of what failed, which twice cost a paitronage
|
|
9
|
+
* investigation its evidence.
|
|
10
|
+
*
|
|
11
|
+
* This is the opt-in other half: a consumer that names a file gets every
|
|
12
|
+
* child's streams appended to it, each stream passed whole through the
|
|
13
|
+
* consumer's own redactor, under a header naming the child. The consumer chooses the path
|
|
14
|
+
* and owns the redactor; this module never picks either, and nothing here
|
|
15
|
+
* changes what the lifecycle decides.
|
|
16
|
+
*
|
|
17
|
+
* The file is opened, and the header written, **before** the child starts,
|
|
18
|
+
* so an unwritable path is known before anything runs and a parent that dies
|
|
19
|
+
* mid-child still leaves the marker for the child that was in flight. The
|
|
20
|
+
* streams themselves arrive after the child exits, because the child is
|
|
21
|
+
* captured (`spawnSync`), not streamed.
|
|
22
|
+
*
|
|
23
|
+
* Nothing here throws into the lifecycle's control flow once the handle is
|
|
24
|
+
* open. A write failure is retained and reported by the caller under its own
|
|
25
|
+
* failure code, because a record that could not be written is a different
|
|
26
|
+
* fact from a child that failed, and reporting it as the second one would
|
|
27
|
+
* put a false cause in front of the operator this file exists for. When the
|
|
28
|
+
* caller reports it — up front, or only after the operation has run to the
|
|
29
|
+
* end — is the caller's rule, not this module's; see `runAlchemyLifecycle`.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import { appendFileSync, closeSync, openSync } from "node:fs";
|
|
33
|
+
|
|
34
|
+
export interface ChildDiagnostics {
|
|
35
|
+
/**
|
|
36
|
+
* The file every child's output is appended to. The consumer chooses it,
|
|
37
|
+
* and it belongs outside the repository and outside any uploaded artifact:
|
|
38
|
+
* redaction covers the declared secret names and nothing else, so a value
|
|
39
|
+
* the consumer did not declare reaches this file verbatim.
|
|
40
|
+
*/
|
|
41
|
+
readonly path: string;
|
|
42
|
+
/**
|
|
43
|
+
* Applied to each captured stream **as one piece of text** before it
|
|
44
|
+
* reaches the file. The consumer owns it; `secretNamePolicy({ names,
|
|
45
|
+
* values })` builds the usual one.
|
|
46
|
+
*
|
|
47
|
+
* Whole text, not a line at a time, because a declared value can itself
|
|
48
|
+
* span lines — a PEM private key, a pasted service-account JSON — and a
|
|
49
|
+
* per-line pass would find no line holding the whole value and write every
|
|
50
|
+
* one of them verbatim. A redactor that works line by line is still
|
|
51
|
+
* correct here; one that needs the whole text only works here.
|
|
52
|
+
*/
|
|
53
|
+
readonly redact: (text: string) => string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** One child's open section of the record. */
|
|
57
|
+
export interface ChildDiagnosticsSection {
|
|
58
|
+
/** Append both captured streams. Never throws; see `failure`. */
|
|
59
|
+
readonly append: (captured: {
|
|
60
|
+
readonly stdout: string | null;
|
|
61
|
+
readonly stderr: string | null;
|
|
62
|
+
}) => void;
|
|
63
|
+
/** Close the handle. Never throws; see `failure`. */
|
|
64
|
+
readonly close: () => void;
|
|
65
|
+
/** The first write or close failure, once one happened. */
|
|
66
|
+
readonly failure: () => Error | undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const streamSection = (
|
|
70
|
+
label: string,
|
|
71
|
+
text: string | null,
|
|
72
|
+
redact: (text: string) => string
|
|
73
|
+
): string => {
|
|
74
|
+
if (text === null || text === "") {
|
|
75
|
+
return `--- ${label}: empty ---\n`;
|
|
76
|
+
}
|
|
77
|
+
// One call over the whole stream: a multi-line secret is only ever whole
|
|
78
|
+
// here, and splitting first would hand the redactor fragments of it.
|
|
79
|
+
const body = redact(text);
|
|
80
|
+
return `--- ${label} ---\n${body.endsWith("\n") ? body : `${body}\n`}`;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
export interface OpenChildDiagnosticsOptions {
|
|
84
|
+
readonly diagnostics: ChildDiagnostics;
|
|
85
|
+
/** The child being run: `plan`, `deploy`, or `destroy`. */
|
|
86
|
+
readonly child: string;
|
|
87
|
+
/** The operation the child belongs to. */
|
|
88
|
+
readonly operation: string;
|
|
89
|
+
readonly stack: string;
|
|
90
|
+
readonly stage: string;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Open the record for one child and write its header.
|
|
95
|
+
*
|
|
96
|
+
* Throws when the file cannot be opened or the header cannot be written.
|
|
97
|
+
* That throw happens before the child is launched, so a caller that has not
|
|
98
|
+
* yet mutated anything can refuse the run with the stage still untouched.
|
|
99
|
+
*/
|
|
100
|
+
export const openChildDiagnostics = ({
|
|
101
|
+
child,
|
|
102
|
+
diagnostics,
|
|
103
|
+
operation,
|
|
104
|
+
stack,
|
|
105
|
+
stage,
|
|
106
|
+
}: OpenChildDiagnosticsOptions): ChildDiagnosticsSection => {
|
|
107
|
+
const handle = openSync(diagnostics.path, "a");
|
|
108
|
+
let retained: Error | undefined;
|
|
109
|
+
const guard = (write: () => void): void => {
|
|
110
|
+
try {
|
|
111
|
+
write();
|
|
112
|
+
} catch (error) {
|
|
113
|
+
retained ??= error instanceof Error ? error : new Error(String(error));
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
try {
|
|
117
|
+
// `appendFileSync` on the open handle, not `writeSync`: it writes the
|
|
118
|
+
// whole buffer or throws, where a short `writeSync` would silently
|
|
119
|
+
// truncate a section and leave a record that reads as complete.
|
|
120
|
+
appendFileSync(
|
|
121
|
+
handle,
|
|
122
|
+
`\n===== ${operation} ${child} child — ${stack}/${stage} — ${new Date().toISOString()} =====\n`
|
|
123
|
+
);
|
|
124
|
+
} catch (error) {
|
|
125
|
+
closeSync(handle);
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
return {
|
|
129
|
+
append: ({ stderr, stdout }) => {
|
|
130
|
+
guard(() => {
|
|
131
|
+
appendFileSync(
|
|
132
|
+
handle,
|
|
133
|
+
streamSection("stdout", stdout, diagnostics.redact)
|
|
134
|
+
);
|
|
135
|
+
appendFileSync(
|
|
136
|
+
handle,
|
|
137
|
+
streamSection("stderr", stderr, diagnostics.redact)
|
|
138
|
+
);
|
|
139
|
+
});
|
|
140
|
+
},
|
|
141
|
+
close: () => {
|
|
142
|
+
guard(() => {
|
|
143
|
+
closeSync(handle);
|
|
144
|
+
});
|
|
145
|
+
},
|
|
146
|
+
failure: () => retained,
|
|
147
|
+
};
|
|
148
|
+
};
|
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cloudflare credential preflight for an Alchemy deploy.
|
|
3
|
+
*
|
|
4
|
+
* Two projects built this twice. Paitronage
|
|
5
|
+
* (`scripts/alchemy/credential-preflight.ts` plus
|
|
6
|
+
* `scripts/alchemy/cloudflare-token-policy.ts`) and firedup
|
|
7
|
+
* (`scripts/alchemy/local-credentials.ts`) both resolve a Cloudflare API
|
|
8
|
+
* token, verify it is live, and refuse to deploy unless its permission groups
|
|
9
|
+
* match an exact reviewed list. What repeats is the check. What does not
|
|
10
|
+
* repeat is the account, the permission list, the resource scope, and where
|
|
11
|
+
* the credential comes from, so every one of those is an input.
|
|
12
|
+
*
|
|
13
|
+
* **No credential value is ever printed.** Errors name environment variables and
|
|
14
|
+
* missing groups from the caller-owned permission requirements. Untrusted API
|
|
15
|
+
* status, receipt group names, and resource identifiers are never reflected.
|
|
16
|
+
* The result carries the token id, which Cloudflare's own verification endpoint
|
|
17
|
+
* returns and which is not a secret.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const CLOUDFLARE_API = "https://api.cloudflare.com/client/v4";
|
|
21
|
+
|
|
22
|
+
/** Where the deploy's Cloudflare credential comes from. */
|
|
23
|
+
export type CredentialSource = "hosted" | "trusted-local";
|
|
24
|
+
|
|
25
|
+
/** Ownership of the token, independent of where its value is resolved. */
|
|
26
|
+
export type CloudflareTokenKind = "account" | "user";
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The environment variables a hosted deploy carries and a trusted-local
|
|
30
|
+
* deploy must not. A trusted-local run resolves its credential from the
|
|
31
|
+
* project's own secret manager; an ambient token there means the run is not
|
|
32
|
+
* the run it claims to be.
|
|
33
|
+
*/
|
|
34
|
+
export const HOSTED_CLOUDFLARE_CREDENTIAL_NAMES = [
|
|
35
|
+
"CLOUDFLARE_ACCOUNT_ID",
|
|
36
|
+
"CLOUDFLARE_API_TOKEN",
|
|
37
|
+
] as const;
|
|
38
|
+
|
|
39
|
+
/** The token and the reviewed policy document that describes it. */
|
|
40
|
+
export interface CloudflareCredential {
|
|
41
|
+
/**
|
|
42
|
+
* The reviewed token policy, as JSON. It carries `tokenId` and `policies`;
|
|
43
|
+
* the id must match the live token, and the policies must reduce to the
|
|
44
|
+
* required permission groups.
|
|
45
|
+
*/
|
|
46
|
+
readonly policyJson: string;
|
|
47
|
+
/** The Cloudflare API token. Never logged, never returned. */
|
|
48
|
+
readonly token: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface CredentialPreflightOptions {
|
|
52
|
+
/** The Cloudflare account the deploy is allowed to touch. */
|
|
53
|
+
readonly accountId: string;
|
|
54
|
+
/** The process environment the deploy would run under. */
|
|
55
|
+
readonly environment: Readonly<Record<string, string | undefined>>;
|
|
56
|
+
/** Test and offline seam. Defaults to the global `fetch`. */
|
|
57
|
+
readonly fetchImplementation?: typeof fetch;
|
|
58
|
+
/**
|
|
59
|
+
* The exact permission groups the token must carry — no more, no fewer.
|
|
60
|
+
* The list is the project's, not this package's. An empty list is refused:
|
|
61
|
+
* it would admit any token.
|
|
62
|
+
*/
|
|
63
|
+
readonly requiredPermissionGroups: readonly string[];
|
|
64
|
+
/**
|
|
65
|
+
* Produces the credential for this source. Hosted implementations read the
|
|
66
|
+
* environment; trusted-local implementations read the project's secret
|
|
67
|
+
* manager. The returned value never leaves this function.
|
|
68
|
+
*/
|
|
69
|
+
readonly resolveCredential: (
|
|
70
|
+
environment: Readonly<Record<string, string | undefined>>
|
|
71
|
+
) => CloudflareCredential | Promise<CloudflareCredential>;
|
|
72
|
+
/**
|
|
73
|
+
* The exact resource identifiers a permission group is allowed to be
|
|
74
|
+
* scoped to. Defaults to the account resource alone. A project whose token
|
|
75
|
+
* carries zone-scoped groups returns that group's zone resources here.
|
|
76
|
+
*/
|
|
77
|
+
readonly resourcesFor?: (permissionGroup: string) => readonly string[];
|
|
78
|
+
readonly source: CredentialSource;
|
|
79
|
+
/** Defaults to account-owned token verification. No endpoint fallback is attempted. */
|
|
80
|
+
readonly tokenKind?: CloudflareTokenKind;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface CredentialPreflightResult {
|
|
84
|
+
readonly accountId: string;
|
|
85
|
+
/** The verified permission groups, sorted. Never a secret. */
|
|
86
|
+
readonly permissionGroups: readonly string[];
|
|
87
|
+
readonly source: CredentialSource;
|
|
88
|
+
/** Cloudflare's own id for the verified token. Not the token. */
|
|
89
|
+
readonly tokenId: string;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Cloudflare could not be asked. A caller distinguishes this from a policy
|
|
94
|
+
* mismatch: an unreachable API is a transient condition, and a token whose
|
|
95
|
+
* permissions are wrong is not.
|
|
96
|
+
*/
|
|
97
|
+
export class CloudflareCredentialUnavailableError extends Error {
|
|
98
|
+
constructor(message = "Cloudflare credential inspection is unavailable.") {
|
|
99
|
+
super(message);
|
|
100
|
+
this.name = "CloudflareCredentialUnavailableError";
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
interface CloudflareEnvelope<Result> {
|
|
105
|
+
readonly result?: Result;
|
|
106
|
+
readonly success: boolean;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
interface TokenPolicy {
|
|
110
|
+
readonly effect: "allow" | "deny";
|
|
111
|
+
readonly permission_groups: readonly { readonly name?: string }[];
|
|
112
|
+
readonly resources: Record<string, string>;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
interface ReviewedTokenPolicy {
|
|
116
|
+
readonly policies: readonly TokenPolicy[];
|
|
117
|
+
readonly tokenId: string;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The exact source literals this preflight accepts. */
|
|
121
|
+
const CREDENTIAL_SOURCES: ReadonlySet<string> = new Set([
|
|
122
|
+
"hosted",
|
|
123
|
+
"trusted-local",
|
|
124
|
+
]);
|
|
125
|
+
|
|
126
|
+
const present = (
|
|
127
|
+
environment: Readonly<Record<string, string | undefined>>,
|
|
128
|
+
name: string
|
|
129
|
+
) => Boolean(environment[name]?.trim());
|
|
130
|
+
|
|
131
|
+
const assertCredentialPosture = (
|
|
132
|
+
source: CredentialSource,
|
|
133
|
+
accountId: string,
|
|
134
|
+
environment: Readonly<Record<string, string | undefined>>
|
|
135
|
+
) => {
|
|
136
|
+
if (!CREDENTIAL_SOURCES.has(source)) {
|
|
137
|
+
// A JavaScript caller can pass any string. An unknown source must not
|
|
138
|
+
// fall through to the trusted-local branch and inherit its posture.
|
|
139
|
+
throw new Error("Credential preflight has an unknown credential source.");
|
|
140
|
+
}
|
|
141
|
+
if (source === "hosted") {
|
|
142
|
+
const missing = HOSTED_CLOUDFLARE_CREDENTIAL_NAMES.filter(
|
|
143
|
+
(name) => !present(environment, name)
|
|
144
|
+
);
|
|
145
|
+
if (missing.length > 0) {
|
|
146
|
+
throw new Error(
|
|
147
|
+
`Hosted credential preflight is missing: ${missing.join(", ")}`
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
if (environment.CLOUDFLARE_ACCOUNT_ID?.trim() !== accountId) {
|
|
151
|
+
throw new Error(
|
|
152
|
+
"Hosted credential preflight found a different Cloudflare account than the deploy allows."
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
const ambient = HOSTED_CLOUDFLARE_CREDENTIAL_NAMES.filter((name) =>
|
|
158
|
+
present(environment, name)
|
|
159
|
+
);
|
|
160
|
+
if (ambient.length > 0) {
|
|
161
|
+
throw new Error(
|
|
162
|
+
`Trusted-local credential preflight must not run with hosted credentials in the environment: ${ambient.join(", ")}`
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
const cloudflareJson = async <Result>(
|
|
168
|
+
url: string,
|
|
169
|
+
token: string,
|
|
170
|
+
fetchImplementation: typeof fetch
|
|
171
|
+
) => {
|
|
172
|
+
let response: Response;
|
|
173
|
+
try {
|
|
174
|
+
response = await fetchImplementation(url, {
|
|
175
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
176
|
+
});
|
|
177
|
+
} catch {
|
|
178
|
+
// The thrown fetch error can carry the request, and the request carries
|
|
179
|
+
// the Authorization header. It is dropped, never wrapped as `cause`.
|
|
180
|
+
throw new CloudflareCredentialUnavailableError();
|
|
181
|
+
}
|
|
182
|
+
if (response.status === 429 || response.status >= 500) {
|
|
183
|
+
throw new CloudflareCredentialUnavailableError();
|
|
184
|
+
}
|
|
185
|
+
let envelope: CloudflareEnvelope<Result>;
|
|
186
|
+
try {
|
|
187
|
+
envelope = (await response.json()) as CloudflareEnvelope<Result>;
|
|
188
|
+
} catch {
|
|
189
|
+
throw new CloudflareCredentialUnavailableError();
|
|
190
|
+
}
|
|
191
|
+
if (!(response.ok && envelope.success) || envelope.result === undefined) {
|
|
192
|
+
throw new Error("Cloudflare credential inspection failed.");
|
|
193
|
+
}
|
|
194
|
+
return envelope.result;
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
const parseReviewedTokenPolicy = (policyJson: string): ReviewedTokenPolicy => {
|
|
198
|
+
let parsed: unknown;
|
|
199
|
+
try {
|
|
200
|
+
parsed = JSON.parse(policyJson);
|
|
201
|
+
} catch {
|
|
202
|
+
// The parser's own message quotes the input, which is the policy
|
|
203
|
+
// document. Only the fact of the failure survives.
|
|
204
|
+
throw new Error("Cloudflare token policy metadata is not valid JSON.");
|
|
205
|
+
}
|
|
206
|
+
if (
|
|
207
|
+
typeof parsed !== "object" ||
|
|
208
|
+
parsed === null ||
|
|
209
|
+
!("tokenId" in parsed) ||
|
|
210
|
+
typeof parsed.tokenId !== "string" ||
|
|
211
|
+
!parsed.tokenId ||
|
|
212
|
+
!("policies" in parsed) ||
|
|
213
|
+
!Array.isArray(parsed.policies)
|
|
214
|
+
) {
|
|
215
|
+
throw new Error("Cloudflare token policy metadata has an invalid shape.");
|
|
216
|
+
}
|
|
217
|
+
// SAFETY: `tokenId` is a non-empty string and `policies` is an array. Every
|
|
218
|
+
// element is shape-checked by `permissionGroupsFromPolicies` before any
|
|
219
|
+
// field of it is read, at this function's only call site.
|
|
220
|
+
return parsed as ReviewedTokenPolicy;
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
const isPolicyShaped = (policy: TokenPolicy) =>
|
|
224
|
+
typeof policy === "object" &&
|
|
225
|
+
policy !== null &&
|
|
226
|
+
Array.isArray(policy.permission_groups) &&
|
|
227
|
+
typeof policy.resources === "object" &&
|
|
228
|
+
policy.resources !== null &&
|
|
229
|
+
!Array.isArray(policy.resources);
|
|
230
|
+
|
|
231
|
+
const permissionGroupsFromPolicies = (
|
|
232
|
+
policies: readonly TokenPolicy[],
|
|
233
|
+
resourcesFor: (permissionGroup: string) => readonly string[]
|
|
234
|
+
) => {
|
|
235
|
+
const found: string[] = [];
|
|
236
|
+
for (const policy of policies) {
|
|
237
|
+
if (!isPolicyShaped(policy)) {
|
|
238
|
+
throw new Error("Cloudflare token policy has an invalid shape.");
|
|
239
|
+
}
|
|
240
|
+
if (policy.permission_groups.length === 0) {
|
|
241
|
+
// A group-less policy has no scope to compare through `resourcesFor`.
|
|
242
|
+
// Even when other policies satisfy the exact group list, this policy
|
|
243
|
+
// must not bypass resource validation.
|
|
244
|
+
throw new Error("Cloudflare token policy has no permission groups.");
|
|
245
|
+
}
|
|
246
|
+
if (policy.effect !== "allow") {
|
|
247
|
+
throw new Error("Cloudflare token must carry allow policies only.");
|
|
248
|
+
}
|
|
249
|
+
if (
|
|
250
|
+
Object.values(policy.resources).some((selection) => selection !== "*")
|
|
251
|
+
) {
|
|
252
|
+
throw new Error("Cloudflare token policy has an invalid resource value.");
|
|
253
|
+
}
|
|
254
|
+
const scope = new Set(Object.keys(policy.resources));
|
|
255
|
+
for (const permission of policy.permission_groups) {
|
|
256
|
+
if (!permission?.name) {
|
|
257
|
+
throw new Error("Cloudflare token has an unnamed permission group.");
|
|
258
|
+
}
|
|
259
|
+
found.push(permission.name);
|
|
260
|
+
const expected = new Set(resourcesFor(permission.name));
|
|
261
|
+
if (expected.size === 0) {
|
|
262
|
+
// An empty expectation can only match an empty scope, which no real
|
|
263
|
+
// policy carries. It is a broken `resourcesFor`, and it says so.
|
|
264
|
+
throw new Error(
|
|
265
|
+
"Cloudflare token policy has no expected resource scope."
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
if (
|
|
269
|
+
scope.size !== expected.size ||
|
|
270
|
+
[...scope].some((resource) => !expected.has(resource))
|
|
271
|
+
) {
|
|
272
|
+
throw new Error(
|
|
273
|
+
"Cloudflare token policy has an unexpected resource scope."
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return found;
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
const assertExactPermissionGroups = (
|
|
282
|
+
found: readonly string[],
|
|
283
|
+
required: readonly string[]
|
|
284
|
+
) => {
|
|
285
|
+
const expected = new Set(required);
|
|
286
|
+
const received = new Set(found);
|
|
287
|
+
const missing = [...expected].filter((name) => !received.has(name));
|
|
288
|
+
const extra = [...received].filter((name) => !expected.has(name));
|
|
289
|
+
const duplicates = found.filter(
|
|
290
|
+
(name, index) => found.indexOf(name) !== index
|
|
291
|
+
);
|
|
292
|
+
if (missing.length > 0 || extra.length > 0 || duplicates.length > 0) {
|
|
293
|
+
throw new Error(
|
|
294
|
+
`Cloudflare permission mismatch; missing: ${missing.join(", ") || "none"}; extra count: ${extra.length}; duplicate count: ${duplicates.length}`
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
const assertRequiredPermissionGroups = (required: readonly string[]) => {
|
|
300
|
+
if (required.some((name) => !name.trim())) {
|
|
301
|
+
throw new Error(
|
|
302
|
+
"Credential preflight requires named permission groups; a blank name matches nothing."
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
const duplicates = required.filter(
|
|
306
|
+
(name, index) => required.indexOf(name) !== index
|
|
307
|
+
);
|
|
308
|
+
if (duplicates.length > 0) {
|
|
309
|
+
// The found list is compared as a set, so a repeated requirement would be
|
|
310
|
+
// satisfied by one group and the list would claim more than it proves.
|
|
311
|
+
throw new Error(
|
|
312
|
+
`Credential preflight requires a permission group list with no repeats; repeated: ${[...new Set(duplicates)].join(", ")}`
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Calls the project's resolver and converts any failure into one fixed
|
|
319
|
+
* message.
|
|
320
|
+
*
|
|
321
|
+
* A resolver reads a secret manager. Its error can quote the value it was
|
|
322
|
+
* reading, or carry it on an attached property. Nothing from the original
|
|
323
|
+
* error survives: no message, no `cause`, no copied property.
|
|
324
|
+
*/
|
|
325
|
+
const resolveResolvedCredential = async (
|
|
326
|
+
resolveCredential: CredentialPreflightOptions["resolveCredential"],
|
|
327
|
+
environment: Readonly<Record<string, string | undefined>>
|
|
328
|
+
) => {
|
|
329
|
+
try {
|
|
330
|
+
return await resolveCredential(environment);
|
|
331
|
+
} catch {
|
|
332
|
+
throw new CloudflareCredentialUnavailableError(
|
|
333
|
+
"Cloudflare credential resolution failed."
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Resolves the deploy's Cloudflare credential posture and checks the token
|
|
340
|
+
* against the reviewed policy document.
|
|
341
|
+
*
|
|
342
|
+
* The check is: the environment matches the declared source, the credential
|
|
343
|
+
* resolves, Cloudflare reports the token active, the reviewed policy names
|
|
344
|
+
* that same token, every policy is an allow policy scoped to the resources
|
|
345
|
+
* the project expects, and the permission groups match the required list with
|
|
346
|
+
* no group missing, extra, or repeated.
|
|
347
|
+
*
|
|
348
|
+
* The permission groups come from the reviewed policy document, not from
|
|
349
|
+
* Cloudflare. This function never reads live permissions from the Cloudflare
|
|
350
|
+
* API. A token whose permissions changed after the review still passes, as
|
|
351
|
+
* long as Cloudflare reports it active and the document still matches its id.
|
|
352
|
+
* See issue #1010.
|
|
353
|
+
*
|
|
354
|
+
* Throws on any failure. {@link CloudflareCredentialUnavailableError} means
|
|
355
|
+
* Cloudflare could not be asked; every other error means the credential is
|
|
356
|
+
* wrong. Nothing it throws, and nothing it returns, carries a secret value.
|
|
357
|
+
*/
|
|
358
|
+
export const credentialPreflight = async ({
|
|
359
|
+
accountId,
|
|
360
|
+
environment,
|
|
361
|
+
fetchImplementation = fetch,
|
|
362
|
+
requiredPermissionGroups,
|
|
363
|
+
resolveCredential,
|
|
364
|
+
resourcesFor,
|
|
365
|
+
source,
|
|
366
|
+
tokenKind = "account",
|
|
367
|
+
}: CredentialPreflightOptions): Promise<CredentialPreflightResult> => {
|
|
368
|
+
if (tokenKind !== "account" && tokenKind !== "user") {
|
|
369
|
+
throw new Error("Credential preflight has an unknown token kind.");
|
|
370
|
+
}
|
|
371
|
+
if (!accountId.trim()) {
|
|
372
|
+
throw new Error("Credential preflight requires a Cloudflare account id.");
|
|
373
|
+
}
|
|
374
|
+
if (requiredPermissionGroups.length === 0) {
|
|
375
|
+
throw new Error(
|
|
376
|
+
"Credential preflight requires at least one permission group; an empty list would admit any token."
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
assertRequiredPermissionGroups(requiredPermissionGroups);
|
|
380
|
+
assertCredentialPosture(source, accountId, environment);
|
|
381
|
+
|
|
382
|
+
const accountResource = `com.cloudflare.api.account.${accountId}`;
|
|
383
|
+
const scopeFor = resourcesFor ?? (() => [accountResource]);
|
|
384
|
+
const credential = await resolveResolvedCredential(
|
|
385
|
+
resolveCredential,
|
|
386
|
+
environment
|
|
387
|
+
);
|
|
388
|
+
if (!(credential.token.trim() && credential.policyJson.trim())) {
|
|
389
|
+
throw new Error("Credential preflight resolved an empty credential.");
|
|
390
|
+
}
|
|
391
|
+
if (
|
|
392
|
+
source === "hosted" &&
|
|
393
|
+
credential.token.trim() !== environment.CLOUDFLARE_API_TOKEN?.trim()
|
|
394
|
+
) {
|
|
395
|
+
// Comparison only. A hosted run deploys with the environment token, so a
|
|
396
|
+
// resolver that returns a different one verifies a token the deploy will
|
|
397
|
+
// not use. Neither value is named.
|
|
398
|
+
throw new Error(
|
|
399
|
+
"Hosted credential preflight resolved a token that is not the environment token."
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
const verification = await cloudflareJson<{ id: string; status: string }>(
|
|
404
|
+
tokenKind === "user"
|
|
405
|
+
? `${CLOUDFLARE_API}/user/tokens/verify`
|
|
406
|
+
: `${CLOUDFLARE_API}/accounts/${accountId}/tokens/verify`,
|
|
407
|
+
credential.token,
|
|
408
|
+
fetchImplementation
|
|
409
|
+
);
|
|
410
|
+
if (verification.status !== "active") {
|
|
411
|
+
throw new Error("Cloudflare token is not active.");
|
|
412
|
+
}
|
|
413
|
+
const reviewed = parseReviewedTokenPolicy(credential.policyJson);
|
|
414
|
+
if (reviewed.tokenId !== verification.id) {
|
|
415
|
+
throw new Error(
|
|
416
|
+
"Cloudflare token policy metadata does not describe the live token."
|
|
417
|
+
);
|
|
418
|
+
}
|
|
419
|
+
const found = permissionGroupsFromPolicies(reviewed.policies, scopeFor);
|
|
420
|
+
assertExactPermissionGroups(found, requiredPermissionGroups);
|
|
421
|
+
|
|
422
|
+
return {
|
|
423
|
+
accountId,
|
|
424
|
+
permissionGroups: found.toSorted(),
|
|
425
|
+
source,
|
|
426
|
+
tokenId: verification.id,
|
|
427
|
+
};
|
|
428
|
+
};
|