package-registry-manager 0.25.0 → 0.26.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/README.md +5 -0
- package/package.json +3 -3
- package/src/audit-config.mjs +96 -0
- package/src/bootstrap-recovery.mjs +163 -0
- package/src/cpp-distribution.mjs +164 -0
- package/src/credential-cycle.mjs +8 -3
- package/src/credential-requirements.mjs +105 -0
- package/src/default-browser.mjs +1 -1
- package/src/default-scope.mjs +1 -1
- package/src/discovery.mjs +289 -24
- package/src/distribution-channel.mjs +87 -0
- package/src/exec.mjs +20 -0
- package/src/extra-flows.mjs +122 -2
- package/src/flows.mjs +19 -3
- package/src/generated-artifact.mjs +48 -0
- package/src/github.mjs +4 -0
- package/src/identity-conflicts.mjs +130 -0
- package/src/manifest-proposal.mjs +1 -1
- package/src/model.mjs +6 -0
- package/src/npm-release.mjs +68 -0
- package/src/nuget-ci.mjs +238 -0
- package/src/nuget-migration.mjs +275 -0
- package/src/nuget-page.mjs +100 -0
- package/src/nuget-policy.mjs +198 -0
- package/src/nuget-publish.py +145 -0
- package/src/nuget-setup.mjs +169 -0
- package/src/nuget-workflow.mjs +54 -0
- package/src/organization-scan.mjs +41 -2
- package/src/pack-review.mjs +122 -0
- package/src/package-coverage.mjs +33 -9
- package/src/plan.mjs +35 -9
- package/src/prerequisites.mjs +1 -1
- package/src/profile.mjs +1 -1
- package/src/publication-state.mjs +299 -0
- package/src/publishers.mjs +78 -12
- package/src/publishing-policy.mjs +7 -1
- package/src/publishing-state.mjs +74 -1
- package/src/python.mjs +1 -1
- package/src/registry-state.mjs +118 -3
- package/src/release-runs.mjs +3 -4
- package/src/setup-batch.mjs +48 -2
- package/src/setup.mjs +82 -120
- package/src/sign-in-import.mjs +132 -40
- package/src/skips.mjs +9 -1
- package/src/source-code.mjs +1 -1
- package/src/tokens.mjs +32 -4
- package/src/workflow-migration.mjs +15 -2
- package/src/workflow-proposal.mjs +6 -2
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/** Identity fields are independent: NuGet profile, package owner and GitHub subject. */
|
|
2
|
+
export function validateNugetPolicy(policy) {
|
|
3
|
+
const required = [
|
|
4
|
+
"username",
|
|
5
|
+
"package_owner",
|
|
6
|
+
"organization",
|
|
7
|
+
"repository",
|
|
8
|
+
"workflow",
|
|
9
|
+
"owner_id",
|
|
10
|
+
"repository_id",
|
|
11
|
+
];
|
|
12
|
+
for (const field of required) {
|
|
13
|
+
if (
|
|
14
|
+
!String(policy[field] ?? "").trim() ||
|
|
15
|
+
/^(?:MyPackage|Your[ -]?Name|your[-_].*|OWNER|REPO|example|placeholder)$/i.test(
|
|
16
|
+
String(policy[field]),
|
|
17
|
+
)
|
|
18
|
+
) {
|
|
19
|
+
throw new Error(`NuGet policy requires an actual ${field}`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
if (
|
|
23
|
+
!["owner_id", "repository_id"].every((field) =>
|
|
24
|
+
/^\d+$/.test(String(policy[field])),
|
|
25
|
+
)
|
|
26
|
+
) {
|
|
27
|
+
throw new Error("NuGet policy requires immutable numeric GitHub IDs");
|
|
28
|
+
}
|
|
29
|
+
if (!/^[\w.-]+\.ya?ml$/.test(policy.workflow)) {
|
|
30
|
+
throw new Error("NuGet policy requires a workflow filename");
|
|
31
|
+
}
|
|
32
|
+
if (
|
|
33
|
+
!Array.isArray(policy.package_ids) ||
|
|
34
|
+
!policy.package_ids.length ||
|
|
35
|
+
policy.package_ids.some(
|
|
36
|
+
(id) =>
|
|
37
|
+
!/^[a-z0-9_.-]+$/i.test(id) ||
|
|
38
|
+
/^(MyPackage|PackageName|example)$/i.test(id),
|
|
39
|
+
)
|
|
40
|
+
) {
|
|
41
|
+
throw new Error("NuGet policy requires exact, non-template package IDs");
|
|
42
|
+
}
|
|
43
|
+
if (
|
|
44
|
+
!Array.isArray(policy.operations) ||
|
|
45
|
+
policy.operations.length !== 1 ||
|
|
46
|
+
policy.operations.some(
|
|
47
|
+
(operation) =>
|
|
48
|
+
!["package:push", "package:pushversion"].includes(operation),
|
|
49
|
+
)
|
|
50
|
+
) {
|
|
51
|
+
throw new Error("NuGet policy requires one explicit publish operation");
|
|
52
|
+
}
|
|
53
|
+
return policy;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Discover an equivalent policy before any creation; activation is fresh evidence. */
|
|
57
|
+
export function nugetPolicyState(policies, expected, actualUsername) {
|
|
58
|
+
validateNugetPolicy(expected);
|
|
59
|
+
if (actualUsername?.toLowerCase() !== expected.username.toLowerCase()) {
|
|
60
|
+
return { status: "wrong-account", verified: false };
|
|
61
|
+
}
|
|
62
|
+
const fields = ["package_owner", "organization", "repository"];
|
|
63
|
+
const matches = policies.filter(
|
|
64
|
+
(policy) =>
|
|
65
|
+
fields.every(
|
|
66
|
+
(field) =>
|
|
67
|
+
String(policy[field] ?? "").toLowerCase() ===
|
|
68
|
+
String(expected[field] ?? "").toLowerCase(),
|
|
69
|
+
) &&
|
|
70
|
+
["workflow", "environment"].every(
|
|
71
|
+
(field) =>
|
|
72
|
+
String(policy[field] ?? "") === String(expected[field] ?? ""),
|
|
73
|
+
) &&
|
|
74
|
+
["package_ids", "operations"].every(
|
|
75
|
+
(field) =>
|
|
76
|
+
JSON.stringify(
|
|
77
|
+
[...(policy[field] ?? [])].map((s) => s.toLowerCase()).sort(),
|
|
78
|
+
) ===
|
|
79
|
+
JSON.stringify(
|
|
80
|
+
[...expected[field]].map((s) => s.toLowerCase()).sort(),
|
|
81
|
+
),
|
|
82
|
+
),
|
|
83
|
+
);
|
|
84
|
+
if (matches.length > 1) {
|
|
85
|
+
return { status: "duplicate", verified: false };
|
|
86
|
+
}
|
|
87
|
+
if (!matches.length) {
|
|
88
|
+
return { status: "missing-or-mismatched", verified: false };
|
|
89
|
+
}
|
|
90
|
+
const policy = matches[0];
|
|
91
|
+
const bound = ["owner_id", "repository_id"].every(
|
|
92
|
+
(field) => String(policy[field] ?? "") === String(expected[field]),
|
|
93
|
+
);
|
|
94
|
+
return {
|
|
95
|
+
status: bound
|
|
96
|
+
? (policy.activation ?? "unknown")
|
|
97
|
+
: "immutable-identity-unverified",
|
|
98
|
+
verified: bound && policy.activation === "active",
|
|
99
|
+
policy_id: policy.id,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** PackageVerify does not establish push authorization, especially for OIDC push-only keys. */
|
|
104
|
+
export function nugetVerificationEvidence(status, body, options = {}) {
|
|
105
|
+
const secrets = options.secrets ?? [];
|
|
106
|
+
let diagnostic = String(body ?? "");
|
|
107
|
+
for (const secret of secrets.filter(Boolean)) {
|
|
108
|
+
diagnostic = diagnostic.replaceAll(secret, "[REDACTED]");
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
http_status: status,
|
|
112
|
+
diagnostic: diagnostic.slice(0, 4000),
|
|
113
|
+
authentication: [401, 403].includes(status)
|
|
114
|
+
? "rejected-by-verification-endpoint"
|
|
115
|
+
: status >= 200 && status < 300
|
|
116
|
+
? "accepted-by-verification-endpoint"
|
|
117
|
+
: "unknown",
|
|
118
|
+
authorization: "unknown",
|
|
119
|
+
publication: "unverified",
|
|
120
|
+
reason: options.derivedKey
|
|
121
|
+
? "derived verification key changes the subject; original policy package scope is unproven"
|
|
122
|
+
: status === 400
|
|
123
|
+
? "PackageVerify may require package:verify; a push-only key is not proven invalid"
|
|
124
|
+
: "verification endpoint evidence is separate from actual push acceptance",
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** OIDC always wins; never validate or rotate a fallback when OIDC succeeded. */
|
|
129
|
+
export async function publishNugetArtifact(artifact, adapter) {
|
|
130
|
+
const attempts = [];
|
|
131
|
+
const oidc = adapter.username
|
|
132
|
+
? await adapter
|
|
133
|
+
.login()
|
|
134
|
+
.catch(() => ({ status: "failed", reason: "OIDC exchange failed" }))
|
|
135
|
+
: { status: "unavailable", reason: "NuGet profile username is missing" };
|
|
136
|
+
attempts.push({
|
|
137
|
+
method: "trusted-publishing",
|
|
138
|
+
status: oidc.status,
|
|
139
|
+
reason: oidc.reason,
|
|
140
|
+
});
|
|
141
|
+
const candidates = [
|
|
142
|
+
{ method: "trusted-publishing", value: oidc.key },
|
|
143
|
+
{ method: "token-fallback", value: adapter.fallback },
|
|
144
|
+
].filter((c) => c.value);
|
|
145
|
+
const fingerprint = await adapter.fingerprint(artifact);
|
|
146
|
+
for (const candidate of candidates) {
|
|
147
|
+
if ((await adapter.fingerprint(artifact)) !== fingerprint) {
|
|
148
|
+
throw new Error("validated NuGet artifact changed before retry");
|
|
149
|
+
}
|
|
150
|
+
const result = await adapter.push(artifact, candidate.value);
|
|
151
|
+
attempts.push({
|
|
152
|
+
method: candidate.method,
|
|
153
|
+
status: result.status,
|
|
154
|
+
reason: result.reason,
|
|
155
|
+
});
|
|
156
|
+
if (result.status === "accepted") {
|
|
157
|
+
return {
|
|
158
|
+
selected_method: candidate.method,
|
|
159
|
+
attempts,
|
|
160
|
+
publication: "accepted",
|
|
161
|
+
trust_repaired: candidate.method === "trusted-publishing",
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
if (
|
|
165
|
+
!["authentication-failed", "authorization-failed"].includes(result.status)
|
|
166
|
+
) {
|
|
167
|
+
return {
|
|
168
|
+
selected_method: candidate.method,
|
|
169
|
+
attempts,
|
|
170
|
+
publication: "unverified",
|
|
171
|
+
trust_repaired: false,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
const accepted = await adapter.exactVersionExists(artifact);
|
|
175
|
+
if (accepted === true) {
|
|
176
|
+
return {
|
|
177
|
+
selected_method: candidate.method,
|
|
178
|
+
attempts,
|
|
179
|
+
publication: "already-present",
|
|
180
|
+
trust_repaired: false,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
if (accepted !== false) {
|
|
184
|
+
return {
|
|
185
|
+
selected_method: candidate.method,
|
|
186
|
+
attempts,
|
|
187
|
+
publication: "unknown",
|
|
188
|
+
trust_repaired: false,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return {
|
|
193
|
+
selected_method: "none",
|
|
194
|
+
attempts,
|
|
195
|
+
publication: "unverified",
|
|
196
|
+
trust_repaired: false,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Publish one validated artifact with job-local OIDC, then a provided fallback.
|
|
2
|
+
|
|
3
|
+
Never use PackageVerify as a push gate. Never create or persist an API key.
|
|
4
|
+
HTTP uncertainty and non-authentication push failures stop the retry sequence.
|
|
5
|
+
"""
|
|
6
|
+
import glob
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import re
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
import tempfile
|
|
16
|
+
from urllib.error import HTTPError
|
|
17
|
+
from urllib.request import urlopen
|
|
18
|
+
import xml.etree.ElementTree as ET
|
|
19
|
+
import zipfile
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def normalized_version(version):
|
|
23
|
+
"""NuGet's flat-container URLs omit build metadata and a zero revision."""
|
|
24
|
+
if not re.fullmatch(r"[0-9]+(?:\.[0-9]+){0,3}(?:-[0-9a-z-]+(?:\.[0-9a-z-]+)*)?(?:\+[0-9a-z-]+(?:\.[0-9a-z-]+)*)?", version, re.I):
|
|
25
|
+
raise ValueError("invalid NuGet version")
|
|
26
|
+
public = version.split("+", 1)[0].lower()
|
|
27
|
+
release, separator, prerelease = public.partition("-")
|
|
28
|
+
if not re.fullmatch(r"[0-9]+(?:\.[0-9]+){0,3}", release):
|
|
29
|
+
raise ValueError("invalid NuGet release version")
|
|
30
|
+
parts = [str(int(part)) for part in release.split(".")]
|
|
31
|
+
while len(parts) < 3:
|
|
32
|
+
parts.append("0")
|
|
33
|
+
if len(parts) == 4 and parts[3] == "0":
|
|
34
|
+
parts.pop()
|
|
35
|
+
return ".".join(parts) + (separator + prerelease if separator else "")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def exact_version_exists(package_id, version):
|
|
39
|
+
version = normalized_version(version)
|
|
40
|
+
url = ("https://api.nuget.org/v3-flatcontainer/"
|
|
41
|
+
f"{package_id.lower()}/{version.lower()}/"
|
|
42
|
+
f"{package_id.lower()}.{version.lower()}.nupkg")
|
|
43
|
+
try:
|
|
44
|
+
with urlopen(url, timeout=30) as response:
|
|
45
|
+
data = response.read()
|
|
46
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
47
|
+
file = Path(directory) / "public.nupkg"
|
|
48
|
+
file.write_bytes(data)
|
|
49
|
+
return True if identity(file) == (package_id.lower(), version) else None
|
|
50
|
+
except HTTPError as error:
|
|
51
|
+
return False if error.code == 404 else None
|
|
52
|
+
except Exception:
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def identity(artifact):
|
|
57
|
+
with zipfile.ZipFile(artifact) as archive:
|
|
58
|
+
specs = [name for name in archive.namelist() if name.endswith(".nuspec")]
|
|
59
|
+
if len(specs) != 1:
|
|
60
|
+
raise ValueError("artifact must contain exactly one nuspec")
|
|
61
|
+
root = ET.fromstring(archive.read(specs[0]))
|
|
62
|
+
fields = {node.tag.rsplit("}", 1)[-1]: node.text for node in root.iter()}
|
|
63
|
+
package_id, version = fields.get("id", ""), fields.get("version", "")
|
|
64
|
+
if not re.fullmatch(r"[A-Za-z0-9_.-]+", package_id) or not re.fullmatch(r"[A-Za-z0-9.+-]+", version):
|
|
65
|
+
raise ValueError("invalid artifact identity")
|
|
66
|
+
return package_id.lower(), normalized_version(version)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def publish(artifact, oidc, fallback, push, probe=exact_version_exists):
|
|
70
|
+
package_id, version = identity(artifact)
|
|
71
|
+
fingerprint = hashlib.sha256(artifact.read_bytes()).digest()
|
|
72
|
+
attempts = [{"method": "trusted-publishing", "status": "available" if oidc else "unavailable"}]
|
|
73
|
+
existing = probe(package_id, version)
|
|
74
|
+
if existing is not False:
|
|
75
|
+
return {"selected_method": "none", "publication": "already-present" if existing else "unknown", "trust_repaired": False, "attempts": attempts}
|
|
76
|
+
for method, key in [("trusted-publishing", oidc), ("token-fallback", fallback)]:
|
|
77
|
+
if not key:
|
|
78
|
+
continue
|
|
79
|
+
if hashlib.sha256(artifact.read_bytes()).digest() != fingerprint:
|
|
80
|
+
raise ValueError("validated artifact changed before retry")
|
|
81
|
+
status = push(artifact, key)
|
|
82
|
+
attempts.append({"method": method, "status": status})
|
|
83
|
+
if status == "accepted":
|
|
84
|
+
return {"selected_method": method, "publication": "accepted", "trust_repaired": method == "trusted-publishing", "attempts": attempts}
|
|
85
|
+
if status not in ("authentication-failed", "authorization-failed"):
|
|
86
|
+
return {"selected_method": method, "publication": "unverified", "trust_repaired": False, "attempts": attempts}
|
|
87
|
+
exists = probe(package_id, version)
|
|
88
|
+
if exists is not False:
|
|
89
|
+
return {"selected_method": method, "publication": "already-present" if exists else "unknown", "trust_repaired": False, "attempts": attempts}
|
|
90
|
+
return {"selected_method": "none", "publication": "unverified", "trust_repaired": False, "attempts": attempts}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def push_artifact(artifact, key):
|
|
94
|
+
result = subprocess.run(["dotnet", "nuget", "push", str(artifact), "--source", "https://api.nuget.org/v3/index.json", "--api-key", key], capture_output=True, text=True, check=False)
|
|
95
|
+
# Captured output can contain credentials. Report only a fixed classification.
|
|
96
|
+
if result.returncode == 0:
|
|
97
|
+
return "accepted"
|
|
98
|
+
output = result.stdout + result.stderr
|
|
99
|
+
if re.search(r"\b403\b.*Forbidden|Forbidden.*\b403\b", output, re.I):
|
|
100
|
+
return "authorization-failed"
|
|
101
|
+
if re.search(r"\b401\b.*Unauthorized|Unauthorized.*\b401\b|API key.*(?:invalid|expired)", output, re.I):
|
|
102
|
+
return "authentication-failed"
|
|
103
|
+
return "push-failed"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def main():
|
|
107
|
+
expected = os.environ["PRM_PACKAGE_ID"].lower()
|
|
108
|
+
if expected in ("mypackage", "packagename", "example"):
|
|
109
|
+
raise ValueError("resolve template package identity before publication")
|
|
110
|
+
candidates = [Path(file) for file in glob.glob(os.path.expandvars(os.environ.get("PRM_ARTIFACT_GLOB", ".prm-nuget/*.nupkg")))]
|
|
111
|
+
if any(identity(file)[0] != expected for file in candidates):
|
|
112
|
+
raise ValueError("artifact glob includes another package; choose an exact package-specific glob")
|
|
113
|
+
artifacts = candidates
|
|
114
|
+
if len(artifacts) != 1:
|
|
115
|
+
raise ValueError("expected exactly one validated artifact for selected package ID")
|
|
116
|
+
artifact = artifacts[0]
|
|
117
|
+
result = publish(artifact, os.environ.get("PRM_NUGET_OIDC"), os.environ.get("PRM_NUGET_FALLBACK"), push_artifact)
|
|
118
|
+
result["package_id"], result["version"] = identity(artifact)
|
|
119
|
+
result["attempts"][0]["reason"] = ("temporary OIDC key available" if os.environ.get("PRM_NUGET_OIDC") else "NuGet username is missing" if not os.environ.get("PRM_NUGET_USER") else "OIDC exchange failed or returned no key")
|
|
120
|
+
print(json.dumps(result))
|
|
121
|
+
if result["publication"] not in ("accepted", "already-present"):
|
|
122
|
+
raise SystemExit("NuGet publication remains unverified; see classified outcomes above")
|
|
123
|
+
package_id, version = identity(artifact)
|
|
124
|
+
verify_public(package_id, version)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def verify_public(package_id, version):
|
|
128
|
+
for attempt in range(12):
|
|
129
|
+
if exact_version_exists(package_id, version) is True:
|
|
130
|
+
break
|
|
131
|
+
if attempt == 11:
|
|
132
|
+
raise SystemExit("exact public package download is not verified")
|
|
133
|
+
time.sleep(5)
|
|
134
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
135
|
+
for command in (["dotnet", "new", "classlib", "--output", directory], ["dotnet", "add", directory, "package", package_id, "--version", version, "--source", "https://api.nuget.org/v3/index.json"], ["dotnet", "build", directory, "--no-restore"]):
|
|
136
|
+
subprocess.run(command, check=True)
|
|
137
|
+
print(json.dumps({"package_id": package_id, "version": version, "public_download": "verified", "consumer": "passed"}))
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
if __name__ == "__main__":
|
|
142
|
+
if len(sys.argv) == 4 and sys.argv[1] == "--verify-public":
|
|
143
|
+
verify_public(sys.argv[2], sys.argv[3])
|
|
144
|
+
else:
|
|
145
|
+
main()
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import nugetPage from "./nuget-page.mjs";
|
|
4
|
+
import { validateNugetPolicy, nugetPolicyState } from "./nuget-policy.mjs";
|
|
5
|
+
import { githubServices } from "./github.mjs";
|
|
6
|
+
import { offerSignInImport, signInDomains } from "./sign-in-import.mjs";
|
|
7
|
+
|
|
8
|
+
const URL = "https://www.nuget.org/account/TrustedPublishing";
|
|
9
|
+
|
|
10
|
+
/** Account names are explicit configuration; GitHub immutable IDs are read fresh. */
|
|
11
|
+
export async function nugetSetupPolicy(session, github) {
|
|
12
|
+
const config = JSON.parse(
|
|
13
|
+
await readFile(
|
|
14
|
+
path.join(session.options.repository, ".package-registry-manager.json"),
|
|
15
|
+
"utf8",
|
|
16
|
+
).catch((error) => {
|
|
17
|
+
if (error.code === "ENOENT") {
|
|
18
|
+
return "{}";
|
|
19
|
+
}
|
|
20
|
+
throw error;
|
|
21
|
+
}),
|
|
22
|
+
);
|
|
23
|
+
const publisher = session.plan.trusted_publisher;
|
|
24
|
+
const settings = config.nuget ?? {};
|
|
25
|
+
if (!publisher) {
|
|
26
|
+
throw new Error(
|
|
27
|
+
"NuGet requires an explicit GitHub repository and workflow",
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
const repository = await github.rest.request(
|
|
31
|
+
`/repos/${publisher.organization}/${publisher.repository}`,
|
|
32
|
+
);
|
|
33
|
+
const expected = validateNugetPolicy({
|
|
34
|
+
...settings,
|
|
35
|
+
...publisher,
|
|
36
|
+
username: settings.username,
|
|
37
|
+
package_owner: settings.package_owner,
|
|
38
|
+
package_ids: settings.package_ids ?? [session.plan.package.name],
|
|
39
|
+
operations: settings.operations,
|
|
40
|
+
owner_id: String(repository.owner.id),
|
|
41
|
+
repository_id: String(repository.id),
|
|
42
|
+
});
|
|
43
|
+
if (
|
|
44
|
+
!expected.package_ids.some(
|
|
45
|
+
(id) => id.toLowerCase() === session.plan.package.name.toLowerCase(),
|
|
46
|
+
)
|
|
47
|
+
) {
|
|
48
|
+
throw new Error("selected package is outside configured NuGet policy IDs");
|
|
49
|
+
}
|
|
50
|
+
return { expected, route: settings.sign_in_route ?? "work" };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Discover before creation, verify signed-in identity, and read server state again. */
|
|
54
|
+
export async function configureNuget(session) {
|
|
55
|
+
const github = session.options.github ?? githubServices(session.options);
|
|
56
|
+
const { expected, route } = await nugetSetupPolicy(session, github);
|
|
57
|
+
session.options.domains = signInDomains("nuget", route);
|
|
58
|
+
const script = (create = false) =>
|
|
59
|
+
`(${nugetPage.toString()})(${JSON.stringify(expected)},${create})`;
|
|
60
|
+
const inspect = async () => {
|
|
61
|
+
const page = await session.visiblePage();
|
|
62
|
+
await page.goto(URL);
|
|
63
|
+
const deadline = Date.now() + (session.options.waitTimeoutMs ?? 600000);
|
|
64
|
+
for (;;) {
|
|
65
|
+
const snapshot = await page.evaluate(script());
|
|
66
|
+
if (snapshot.ready || !snapshot.username || snapshot.error) {
|
|
67
|
+
return snapshot;
|
|
68
|
+
}
|
|
69
|
+
if (Date.now() >= deadline) {
|
|
70
|
+
throw new Error("NuGet policy page did not become ready");
|
|
71
|
+
}
|
|
72
|
+
await new Promise((resolve) =>
|
|
73
|
+
setTimeout(resolve, session.options.pollIntervalMs ?? 500),
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
let snapshot = await inspect();
|
|
78
|
+
if (snapshot.username?.toLowerCase() !== expected.username.toLowerCase()) {
|
|
79
|
+
await offerSignInImport(session, session.options.domains, async () => {
|
|
80
|
+
snapshot = await inspect();
|
|
81
|
+
return (
|
|
82
|
+
snapshot.username?.toLowerCase() === expected.username.toLowerCase()
|
|
83
|
+
);
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
const deadline = Date.now() + (session.options.waitTimeoutMs ?? 600000);
|
|
87
|
+
while (
|
|
88
|
+
!snapshot.ready ||
|
|
89
|
+
snapshot.username?.toLowerCase() !== expected.username.toLowerCase()
|
|
90
|
+
) {
|
|
91
|
+
if (snapshot.username) {
|
|
92
|
+
throw new Error(
|
|
93
|
+
"signed-in NuGet profile differs from the configured identity; policy was not changed",
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
if (session.options.yes) {
|
|
97
|
+
throw new Error(
|
|
98
|
+
"NuGet sign-in requires interaction; local session reuse did not verify the configured identity",
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
await session.prompt(
|
|
102
|
+
`Sign in with the configured NuGet profile using ${route}; complete password, 2FA or platform passkey authentication, then press Enter...`,
|
|
103
|
+
);
|
|
104
|
+
if (Date.now() >= deadline) {
|
|
105
|
+
throw new Error("NuGet authentication remains unverified");
|
|
106
|
+
}
|
|
107
|
+
snapshot = await inspect();
|
|
108
|
+
}
|
|
109
|
+
let policyChanged = false;
|
|
110
|
+
let state = nugetPolicyState(snapshot.policies, expected, snapshot.username);
|
|
111
|
+
if (state.status === "missing-or-mismatched") {
|
|
112
|
+
const submitted = await session.automation.evaluate(script(true));
|
|
113
|
+
if (!submitted.submitted || submitted.error) {
|
|
114
|
+
throw new Error(
|
|
115
|
+
`NuGet policy was not created: ${submitted.error ?? "unsupported page"}`,
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
while (true) {
|
|
119
|
+
await new Promise((resolve) =>
|
|
120
|
+
setTimeout(resolve, session.options.pollIntervalMs ?? 500),
|
|
121
|
+
);
|
|
122
|
+
const pending = await session.automation.evaluate(script());
|
|
123
|
+
if (pending.error) {
|
|
124
|
+
throw new Error(`NuGet policy creation failed: ${pending.error}`);
|
|
125
|
+
}
|
|
126
|
+
if (!pending.pending) {
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
if (Date.now() >= deadline) {
|
|
130
|
+
throw new Error("NuGet policy creation remains pending");
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
snapshot = await inspect();
|
|
134
|
+
policyChanged = true;
|
|
135
|
+
state = nugetPolicyState(snapshot.policies, expected, snapshot.username);
|
|
136
|
+
}
|
|
137
|
+
console.log(JSON.stringify({ nuget_policy: state }));
|
|
138
|
+
if (!state.verified) {
|
|
139
|
+
throw new Error(
|
|
140
|
+
`NuGet policy is ${state.status}; publication remains unverified`,
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
const scope = {
|
|
144
|
+
repo: `${expected.organization}/${expected.repository}`,
|
|
145
|
+
...(expected.environment ? { environment: expected.environment } : {}),
|
|
146
|
+
};
|
|
147
|
+
const variable = await github
|
|
148
|
+
.variables(scope)
|
|
149
|
+
.ensure("NUGET_USER", expected.username);
|
|
150
|
+
if (
|
|
151
|
+
!variable.verified ||
|
|
152
|
+
!variable.effective?.length ||
|
|
153
|
+
variable.effective.some((value) => value.value !== expected.username)
|
|
154
|
+
) {
|
|
155
|
+
throw new Error("effective NUGET_USER readback did not verify the profile");
|
|
156
|
+
}
|
|
157
|
+
session.nugetEvidence = {
|
|
158
|
+
policy: state,
|
|
159
|
+
variable,
|
|
160
|
+
policy_changed: policyChanged,
|
|
161
|
+
};
|
|
162
|
+
if (policyChanged || variable.changed) {
|
|
163
|
+
session.recordRecoveryChange();
|
|
164
|
+
}
|
|
165
|
+
session.conditions.delete("trust-missing");
|
|
166
|
+
console.log(
|
|
167
|
+
"NuGet policy and effective NUGET_USER verified; authentication exchange, actual push and public consumer validation remain separate CI gates. Existing fallback secrets are retained.",
|
|
168
|
+
);
|
|
169
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
|
|
3
|
+
/** Build once; NuGet/login creates a temporary key used only inside this job. */
|
|
4
|
+
export function nugetWorkflowSteps(item, options = {}) {
|
|
5
|
+
if (
|
|
6
|
+
!/^[a-z0-9_.-]+$/i.test(item.name) ||
|
|
7
|
+
/^(MyPackage|PackageName|example)$/i.test(item.name)
|
|
8
|
+
) {
|
|
9
|
+
throw new Error(
|
|
10
|
+
"resolve exact NuGet package identity before proposing publication",
|
|
11
|
+
);
|
|
12
|
+
}
|
|
13
|
+
const secrets = [
|
|
14
|
+
...new Set([...(item.token_secrets ?? []), "NUGET_API_KEY", "NUGET_TOKEN"]),
|
|
15
|
+
];
|
|
16
|
+
if (secrets.some((name) => !/^[A-Z_][A-Z0-9_]*$/i.test(name))) {
|
|
17
|
+
throw new Error("invalid NuGet fallback secret name");
|
|
18
|
+
}
|
|
19
|
+
const project = `'${item.manifest.split("/").at(-1).replaceAll("'", "''")}'`;
|
|
20
|
+
const controller = readFileSync(
|
|
21
|
+
new URL("./nuget-publish.py", import.meta.url),
|
|
22
|
+
"utf8",
|
|
23
|
+
).trimEnd();
|
|
24
|
+
const result = [
|
|
25
|
+
" - uses: actions/setup-dotnet@v6",
|
|
26
|
+
" with:",
|
|
27
|
+
" dotnet-version: '10.0.x'",
|
|
28
|
+
` - run: dotnet test ${project} --configuration Release`,
|
|
29
|
+
` - run: dotnet pack ${project} --configuration Release --no-build --output .prm-nuget`,
|
|
30
|
+
" - uses: NuGet/login@8d196754b4036150537f80ac539e15c2f1028841 # v1",
|
|
31
|
+
" id: prm_nuget_login",
|
|
32
|
+
" if: vars.NUGET_USER != ''",
|
|
33
|
+
" continue-on-error: true",
|
|
34
|
+
" with:",
|
|
35
|
+
" user: ${{ vars.NUGET_USER }}",
|
|
36
|
+
" - name: Publish validated NuGet artifact and verify public consumer",
|
|
37
|
+
" shell: bash",
|
|
38
|
+
" env:",
|
|
39
|
+
` PRM_PACKAGE_ID: '${item.name}'`,
|
|
40
|
+
...(options.artifactGlob
|
|
41
|
+
? [
|
|
42
|
+
` PRM_ARTIFACT_GLOB: '${options.artifactGlob.replaceAll("'", "''")}'`,
|
|
43
|
+
]
|
|
44
|
+
: []),
|
|
45
|
+
" PRM_NUGET_USER: ${{ vars.NUGET_USER }}",
|
|
46
|
+
" PRM_NUGET_OIDC: ${{ steps.prm_nuget_login.outputs.NUGET_API_KEY }}",
|
|
47
|
+
` PRM_NUGET_FALLBACK: \${{ ${secrets.map((name) => `secrets.${name}`).join(" || ")} }}`,
|
|
48
|
+
" run: |",
|
|
49
|
+
" python3 - <<'PRM_NUGET_PY'",
|
|
50
|
+
...controller.split("\n").map((line) => ` ${line}`),
|
|
51
|
+
" PRM_NUGET_PY",
|
|
52
|
+
];
|
|
53
|
+
return options.build === false ? result.slice(5) : result;
|
|
54
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { markIdentityConflicts } from "./identity-conflicts.mjs";
|
|
1
2
|
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
2
3
|
import os from "node:os";
|
|
3
4
|
import path from "node:path";
|
|
@@ -13,6 +14,9 @@ import { scriptReferences } from "./publishers.mjs";
|
|
|
13
14
|
/** Only files used by existing discovery; no full repository clones for scans. */
|
|
14
15
|
export const SCAN_MATCHES = [
|
|
15
16
|
...[
|
|
17
|
+
"CMakeLists.txt",
|
|
18
|
+
"conanfile.py",
|
|
19
|
+
"vcpkg.json",
|
|
16
20
|
"package.json",
|
|
17
21
|
"Cargo.toml",
|
|
18
22
|
"pyproject.toml",
|
|
@@ -52,11 +56,30 @@ export function packageFindings(inspection) {
|
|
|
52
56
|
manifest: item.manifest,
|
|
53
57
|
};
|
|
54
58
|
const findings = [];
|
|
55
|
-
if (
|
|
59
|
+
if (
|
|
60
|
+
item.exists_on_registry === undefined &&
|
|
61
|
+
(item.registry_http_status || item.registry_state_reason)
|
|
62
|
+
) {
|
|
56
63
|
findings.push({
|
|
57
64
|
...common,
|
|
58
65
|
type: "registry-state-unknown",
|
|
59
|
-
evidence: {
|
|
66
|
+
evidence: {
|
|
67
|
+
http_status: item.registry_http_status,
|
|
68
|
+
reason:
|
|
69
|
+
item.registry_state_reason ??
|
|
70
|
+
"registry state could not be determined",
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
if (item.manifest_version_exists === false || item.version_state) {
|
|
75
|
+
findings.push({
|
|
76
|
+
...common,
|
|
77
|
+
type: item.version_state ?? "manifest-version-absent",
|
|
78
|
+
evidence: {
|
|
79
|
+
expected_version: item.version,
|
|
80
|
+
latest_version: item.latest_version,
|
|
81
|
+
url: item.version_evidence_url ?? item.registry_evidence_url,
|
|
82
|
+
},
|
|
60
83
|
});
|
|
61
84
|
}
|
|
62
85
|
if (item.exists_on_registry === false) {
|
|
@@ -248,6 +271,22 @@ export async function withAccountScan(options, callback) {
|
|
|
248
271
|
repositories.length,
|
|
249
272
|
);
|
|
250
273
|
}
|
|
274
|
+
const conflicts = markIdentityConflicts(
|
|
275
|
+
scan.repositories.flatMap((item) =>
|
|
276
|
+
item.inspection ? [item.inspection] : [],
|
|
277
|
+
),
|
|
278
|
+
);
|
|
279
|
+
for (const conflict of conflicts) {
|
|
280
|
+
scan.findings.push({
|
|
281
|
+
type: "package-identity-conflict",
|
|
282
|
+
repository: conflict.sources
|
|
283
|
+
.map((source) => source.repository)
|
|
284
|
+
.join(", "),
|
|
285
|
+
registry: conflict.identity.split(":")[0],
|
|
286
|
+
package: conflict.identity.slice(conflict.identity.indexOf(":") + 1),
|
|
287
|
+
evidence: conflict,
|
|
288
|
+
});
|
|
289
|
+
}
|
|
251
290
|
return await callback(scan, github);
|
|
252
291
|
} finally {
|
|
253
292
|
await rm(directory, { recursive: true, force: true });
|