@cassiomc1/forgeloop 2.0.0 → 2.2.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/.cursor/rules/project-loop.mdc +1 -1
- package/.github/copilot-instructions.md +1 -1
- package/AGENTS.md +1 -1
- package/CLAUDE.md +1 -1
- package/ENG/design-code-eng.md +7 -5
- package/ENG/dotnet-aspnetcore-development-eng.md +8 -4
- package/ENG/nodejs-backend-development-eng.md +7 -4
- package/ENG/sql-development-eng.md +5 -4
- package/ENG/taste-frontend-eng.md +19 -5
- package/PROTOCOL_INTEGRATION.md +21 -0
- package/README.md +10 -7
- package/THIRD_PARTY_NOTICES.md +1 -0
- package/completions/_forgeloop +6 -1
- package/completions/forgeloop.bash +11 -1
- package/completions/forgeloop.fish +40 -1
- package/docs/AGENT_PROTOCOL_SUMMARY.md +6 -1
- package/docs/CLI_REFERENCE.md +88 -3
- package/docs/CODE_ATTESTATION.md +7 -0
- package/docs/FORGELOOP_AUDIT.md +1 -1
- package/docs/GETTING_STARTED.md +8 -1
- package/docs/PACKAGE_CONTENTS.md +4 -5
- package/docs/RELEASE_CHECKLIST.md +67 -13
- package/docs/STABLE_2_ACCEPTANCE.md +118 -71
- package/docs/TROUBLESHOOTING.md +167 -0
- package/package.json +1 -5
- package/src/cli.js +26 -0
- package/src/commands/assess.js +36 -0
- package/src/commands/evidence-export.js +17 -0
- package/src/commands/evidence-verify.js +36 -0
- package/src/commands/sync-pull.js +46 -0
- package/src/commands/sync-push.js +49 -0
- package/src/core/assessment/facts.js +146 -0
- package/src/core/assessment/plan.js +133 -0
- package/src/core/cli-command-definitions.js +70 -0
- package/src/core/command-executors.js +26 -3
- package/src/core/error-codes.js +232 -2
- package/src/core/evidence/bundle-format.js +72 -0
- package/src/core/evidence/export.js +179 -0
- package/src/core/evidence/markdown.js +40 -0
- package/src/core/evidence/verify.js +179 -0
- package/src/core/integration-invocation-policy.js +4 -2
- package/src/core/next-action-review-phase.js +14 -5
- package/src/core/parsers/dotnet-project.js +221 -0
- package/src/core/parsers/limits.js +9 -0
- package/src/core/parsers/pubspec.js +307 -0
- package/src/core/parsers/shared.js +4 -0
- package/src/core/project-detection.js +6 -527
- package/src/core/sync/remote.js +124 -0
- package/src/core/sync/snapshot.js +129 -0
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { validateAttestationStatement } from "../attestation.js";
|
|
5
|
+
import { assertAttestationStatementBindings, verifyCodeManifestContent } from "../attestation-verifier.js";
|
|
6
|
+
import { validateCodeManifest } from "../code-manifest.js";
|
|
7
|
+
import { E_ATTESTATION_CONTENT_MISMATCH, E_ATTESTATION_COVERAGE_GAP, E_ATTESTATION_UNSIGNED, E_EVIDENCE_BUNDLE_INVALID } from "../error-codes.js";
|
|
8
|
+
import { resolveRevisionProvider } from "../revision/provider.js";
|
|
9
|
+
import { REVISION_PROVIDERS } from "../revision/registry.js";
|
|
10
|
+
import { createSigstoreSigningProvider } from "../signing/sigstore.js";
|
|
11
|
+
import { getPackageRoot } from "../templates.js";
|
|
12
|
+
import { DEFAULT_EVIDENCE_DIRECTORY, parseEvidenceBundle } from "./bundle-format.js";
|
|
13
|
+
|
|
14
|
+
export const EVIDENCE_LEVELS = Object.freeze({ ATTESTED: "ATTESTED", INTEGRITY_ONLY: "INTEGRITY_ONLY", NONE: "NONE" });
|
|
15
|
+
export const UNSIGNED_WARNING = "Unsigned evidence bundles prove internal consistency with the committed code, not that ForgeLoop produced them; require signatures to use this check as a trust gate.";
|
|
16
|
+
|
|
17
|
+
const normalize = (value) => String(value).replaceAll("\\", "/").replace(/^\.\//u, "");
|
|
18
|
+
const entryPaths = (entry) => [entry.path, entry.sourcePath].filter(Boolean).map(normalize);
|
|
19
|
+
|
|
20
|
+
function isExcluded(value, directory, exclusions) {
|
|
21
|
+
if (value === ".forgeloop" || value.startsWith(".forgeloop/")) return true;
|
|
22
|
+
if (value === directory || value.startsWith(`${directory}/`)) return true;
|
|
23
|
+
return exclusions.some((pattern) => {
|
|
24
|
+
const normalized = normalize(pattern);
|
|
25
|
+
if (normalized.endsWith("/**")) return value === normalized.slice(0, -3) || value.startsWith(normalized.slice(0, -2));
|
|
26
|
+
return value === normalized;
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function resolveProvider(target, revisionProvider) {
|
|
31
|
+
return typeof revisionProvider === "string"
|
|
32
|
+
? resolveRevisionProvider({ target, providerName: revisionProvider, registry: REVISION_PROVIDERS })
|
|
33
|
+
: revisionProvider;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function changedBundlePaths(changedEntries, directory) {
|
|
37
|
+
return [...new Set(changedEntries
|
|
38
|
+
.filter((entry) => entry.kind !== "DELETED" && entry.operation !== "DELETED")
|
|
39
|
+
.map((entry) => normalize(entry.path))
|
|
40
|
+
.filter((value) => value.startsWith(`${directory}/`) && value.endsWith(".json")))].sort();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function verifySignature({ statementText, signature, signer, policy }) {
|
|
44
|
+
if (!signature) return { status: "UNSIGNED" };
|
|
45
|
+
const directory = await mkdtemp(path.join(os.tmpdir(), "forgeloop-evidence-signature-"));
|
|
46
|
+
try {
|
|
47
|
+
await writeFile(path.join(directory, "statement.json"), statementText);
|
|
48
|
+
await writeFile(path.join(directory, "statement.sigstore.json"), signature.bundleText);
|
|
49
|
+
const result = await signer.verify({ target: directory, statementPath: "statement.json", bundlePath: "statement.sigstore.json", policy });
|
|
50
|
+
return { status: result.status, ...(result.code ? { code: result.code } : {}), ...(result.message ? { message: result.message } : {}) };
|
|
51
|
+
} finally {
|
|
52
|
+
await rm(directory, { recursive: true, force: true });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function verifyEntries({ target, manifest, provider, headRevision }) {
|
|
57
|
+
const entries = [];
|
|
58
|
+
for (const entry of manifest.entries) {
|
|
59
|
+
try {
|
|
60
|
+
await verifyCodeManifestContent({ target, manifest: { ...manifest, entries: [entry] }, revisionProvider: provider, revision: headRevision });
|
|
61
|
+
entries.push({ paths: entryPaths(entry), digest: entry.sha256 ?? entry.providerContentId ?? entry.kind, matches: true });
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (error.code !== E_ATTESTATION_CONTENT_MISMATCH) throw error;
|
|
64
|
+
entries.push({ paths: entryPaths(entry), digest: entry.sha256 ?? entry.providerContentId ?? entry.kind, matches: false });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return entries;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function loadBundle(context, bundlePath) {
|
|
71
|
+
const { target, provider, headRevision, packageRoot, signer, policy } = context;
|
|
72
|
+
const expectedTaskId = path.posix.basename(bundlePath, ".json");
|
|
73
|
+
const record = { path: bundlePath, taskId: expectedTaskId, integrity: "INVALID", signature: { status: "NOT_CHECKED" }, entries: [] };
|
|
74
|
+
try {
|
|
75
|
+
const bytes = await provider.readContent({ target, revision: headRevision, path: bundlePath });
|
|
76
|
+
const { bundle, statement } = parseEvidenceBundle(Buffer.from(bytes).toString("utf8"), expectedTaskId);
|
|
77
|
+
await validateAttestationStatement(statement, packageRoot);
|
|
78
|
+
const manifest = await validateCodeManifest(bundle.manifest, packageRoot);
|
|
79
|
+
assertAttestationStatementBindings(statement, manifest, bundle.taskId, bundle.manifestFingerprint);
|
|
80
|
+
record.entries = await verifyEntries({ target, manifest, provider, headRevision });
|
|
81
|
+
record.integrity = "VALID";
|
|
82
|
+
record.signature = await verifySignature({ statementText: bundle.statement.text, signature: bundle.signature, signer, policy });
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (error.code?.startsWith("E_REVISION_")) throw error;
|
|
85
|
+
record.error = { code: error.code?.startsWith("E_") ? error.code : E_EVIDENCE_BUNDLE_INVALID, message: error.message };
|
|
86
|
+
}
|
|
87
|
+
return record;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function coverageFor(changedPaths, bundles) {
|
|
91
|
+
const covering = new Map();
|
|
92
|
+
for (const bundle of bundles.filter((item) => item.integrity === "VALID")) {
|
|
93
|
+
for (const entry of bundle.entries.filter((item) => item.matches)) {
|
|
94
|
+
for (const value of entry.paths) covering.set(value, [...(covering.get(value) ?? []), bundle.taskId]);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const errors = [];
|
|
98
|
+
const superseded = [];
|
|
99
|
+
for (const bundle of bundles.filter((item) => item.integrity === "VALID")) {
|
|
100
|
+
for (const entry of bundle.entries.filter((item) => !item.matches)) {
|
|
101
|
+
for (const value of entry.paths) {
|
|
102
|
+
if (covering.has(value)) superseded.push({ path: value, taskId: bundle.taskId, supersededBy: [...new Set(covering.get(value))].sort() });
|
|
103
|
+
else errors.push({ code: E_ATTESTATION_CONTENT_MISMATCH, taskId: bundle.taskId, path: value, message: `Evidence for ${value} does not match the head revision and no other bundle covers it` });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const uncoveredPaths = changedPaths.filter((value) => !covering.has(value));
|
|
108
|
+
return { covering, errors, superseded, uncoveredPaths };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function signerPolicyFrom(signerPolicy) {
|
|
112
|
+
return Object.fromEntries(["identity", "issuer", "trustedRoot"].filter((key) => signerPolicy[key]).map((key) => [key, signerPolicy[key]]));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function signatureErrors(bundles) {
|
|
116
|
+
return bundles.filter((bundle) => bundle.signature.status !== "VALID").map((bundle) => ({
|
|
117
|
+
code: bundle.signature.code ?? E_ATTESTATION_UNSIGNED,
|
|
118
|
+
taskId: bundle.taskId,
|
|
119
|
+
message: bundle.signature.message ?? `Evidence for task ${bundle.taskId} has no valid signature`,
|
|
120
|
+
}));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function overallLevel(status, usedBundles) {
|
|
124
|
+
if (status !== "VALID") return EVIDENCE_LEVELS.NONE;
|
|
125
|
+
return usedBundles.length > 0 && usedBundles.every((bundle) => bundle.signature.status === "VALID") ? EVIDENCE_LEVELS.ATTESTED : EVIDENCE_LEVELS.INTEGRITY_ONLY;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export async function verifyEvidenceRange({
|
|
129
|
+
target,
|
|
130
|
+
packageRoot = getPackageRoot(),
|
|
131
|
+
revisionProvider = "git",
|
|
132
|
+
baseRevision,
|
|
133
|
+
headRevision,
|
|
134
|
+
directory = DEFAULT_EVIDENCE_DIRECTORY,
|
|
135
|
+
requireCompleteCoverage = true,
|
|
136
|
+
requireSignature = false,
|
|
137
|
+
signerPolicy = {},
|
|
138
|
+
signingProvider = null,
|
|
139
|
+
exclusions = [],
|
|
140
|
+
} = {}) {
|
|
141
|
+
const evidenceDirectory = normalize(directory).replace(/\/+$/u, "");
|
|
142
|
+
const provider = await resolveProvider(target, revisionProvider);
|
|
143
|
+
const changedEntries = await provider.getChangedEntries({ target, baseRevision, headRevision });
|
|
144
|
+
const changedPaths = [...new Set(changedEntries.flatMap(entryPaths))].filter((value) => !isExcluded(value, evidenceDirectory, exclusions)).sort();
|
|
145
|
+
const policy = signerPolicyFrom(signerPolicy);
|
|
146
|
+
const context = { target, provider, headRevision, packageRoot, signer: signingProvider ?? createSigstoreSigningProvider(), policy };
|
|
147
|
+
const bundles = [];
|
|
148
|
+
for (const bundlePath of changedBundlePaths(changedEntries, evidenceDirectory)) bundles.push(await loadBundle(context, bundlePath));
|
|
149
|
+
const coverage = coverageFor(changedPaths, bundles);
|
|
150
|
+
const errors = [
|
|
151
|
+
...bundles.filter((bundle) => bundle.error).map((bundle) => ({ ...bundle.error, taskId: bundle.taskId, path: bundle.path })),
|
|
152
|
+
...coverage.errors,
|
|
153
|
+
];
|
|
154
|
+
if (requireCompleteCoverage && coverage.uncoveredPaths.length > 0) {
|
|
155
|
+
errors.push({ code: E_ATTESTATION_COVERAGE_GAP, message: `Changed paths are not covered by evidence: ${coverage.uncoveredPaths.join(", ")}`, paths: coverage.uncoveredPaths });
|
|
156
|
+
}
|
|
157
|
+
const usedBundles = bundles.filter((bundle) => bundle.integrity === "VALID");
|
|
158
|
+
if (requireSignature) errors.push(...signatureErrors(usedBundles));
|
|
159
|
+
const status = errors.length === 0 ? "VALID" : "INVALID";
|
|
160
|
+
const level = overallLevel(status, usedBundles);
|
|
161
|
+
return {
|
|
162
|
+
schemaVersion: 1,
|
|
163
|
+
kind: "forgeloop-evidence-verification",
|
|
164
|
+
status,
|
|
165
|
+
level,
|
|
166
|
+
revisionProvider: provider.name ?? "unknown",
|
|
167
|
+
baseRevision: baseRevision ?? null,
|
|
168
|
+
headRevision: headRevision ?? null,
|
|
169
|
+
evidenceDirectory,
|
|
170
|
+
changedPaths: changedPaths.length,
|
|
171
|
+
coveredPaths: changedPaths.length - coverage.uncoveredPaths.length,
|
|
172
|
+
uncoveredPaths: coverage.uncoveredPaths,
|
|
173
|
+
superseded: coverage.superseded,
|
|
174
|
+
bundles: bundles.map(({ entries, ...bundle }) => ({ ...bundle, entries: entries.length, matchingEntries: entries.filter((entry) => entry.matches).length })),
|
|
175
|
+
signature: { required: requireSignature, ...policy },
|
|
176
|
+
warnings: level === EVIDENCE_LEVELS.INTEGRITY_ONLY ? [UNSIGNED_WARNING] : [],
|
|
177
|
+
errors,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
@@ -26,7 +26,7 @@ export const INTEGRATION_RISK_CLASSES = Object.freeze({
|
|
|
26
26
|
|
|
27
27
|
const READ_ONLY_COMMANDS = Object.freeze(new Set([
|
|
28
28
|
"storage-migration-status",
|
|
29
|
-
"protocol-info", "decision-status", "decision-show", "context-plan", "model-route", "semantic-plan", "test-inventory", "status", "next", "continuity", "reconcile-continuity",
|
|
29
|
+
"protocol-info", "decision-status", "decision-show", "context-plan", "model-route", "semantic-plan", "test-inventory", "assess", "evidence-verify", "status", "next", "continuity", "reconcile-continuity",
|
|
30
30
|
"task-list", "task-show", "task-lock-status", "progress", "audit", "report",
|
|
31
31
|
"inspect", "validate-state", "validate-protocol", "validate-receipt",
|
|
32
32
|
"policy-status", "policy-diff", "rule-verify", "policy",
|
|
@@ -45,7 +45,7 @@ const LOOP_MUTATION_COMMANDS = Object.freeze(new Set([
|
|
|
45
45
|
"record-terminal-result", "complete",
|
|
46
46
|
"record-intervention", "record-hypothesis-disposition",
|
|
47
47
|
"usage-record",
|
|
48
|
-
"workspace-bind", "handoff-create", "handoff-accept", "responsibility-set", "verify-scope", "attestation-create",
|
|
48
|
+
"workspace-bind", "handoff-create", "handoff-accept", "responsibility-set", "verify-scope", "attestation-create", "evidence-export",
|
|
49
49
|
]));
|
|
50
50
|
|
|
51
51
|
const STATIC_RISK_CLASSES = Object.freeze({
|
|
@@ -77,6 +77,8 @@ const STATIC_RISK_CLASSES = Object.freeze({
|
|
|
77
77
|
"storage-migrate": INTEGRATION_RISK_CLASSES.MAINTENANCE,
|
|
78
78
|
"storage-backup": INTEGRATION_RISK_CLASSES.MAINTENANCE,
|
|
79
79
|
"storage-restore": INTEGRATION_RISK_CLASSES.MAINTENANCE,
|
|
80
|
+
"sync-push": INTEGRATION_RISK_CLASSES.MAINTENANCE,
|
|
81
|
+
"sync-pull": INTEGRATION_RISK_CLASSES.MAINTENANCE,
|
|
80
82
|
"storage-restore-resume": INTEGRATION_RISK_CLASSES.MAINTENANCE,
|
|
81
83
|
activate: INTEGRATION_RISK_CLASSES.MAINTENANCE,
|
|
82
84
|
"task-migrate": INTEGRATION_RISK_CLASSES.MAINTENANCE,
|
|
@@ -8,6 +8,19 @@ import { NEXT_ACTIONS, commandFor, decision, recordTerminalResultCommandSpec, re
|
|
|
8
8
|
import { artifactError, checkListReasons, loadArtifact, requirementsAndCoverage } from "./next-action-artifacts.js";
|
|
9
9
|
import { reviewCorrectionAction } from "./next-action-review-correction.js";
|
|
10
10
|
|
|
11
|
+
|
|
12
|
+
// Only an absent receipt is an expected recovery input; corrupt or unreadable
|
|
13
|
+
// storage propagates so the caller fails closed.
|
|
14
|
+
async function readRecoveryReceipt(target, receiptRel, packageRoot) {
|
|
15
|
+
try {
|
|
16
|
+
const receiptArtifact = await readJsonArtifact(target, receiptRel, "execution-receipt", packageRoot);
|
|
17
|
+
return receiptArtifact?.value ?? null;
|
|
18
|
+
} catch (error) {
|
|
19
|
+
if (error?.code !== "ARTIFACT_MISSING") throw error;
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
11
24
|
export async function resolveReviewingPhase(options) {
|
|
12
25
|
const { target, packageRoot, explicitTaskId, state, context, requiredArtifacts } = options;
|
|
13
26
|
const invalidChecks = checkListReasons(state);
|
|
@@ -40,11 +53,7 @@ async function resolveReviewingEvidence({ state, context, requiredArtifacts, tar
|
|
|
40
53
|
if (state.lastCompletionAttempt?.status === "REJECTED") {
|
|
41
54
|
try {
|
|
42
55
|
const ledger = await validateEventLedger(target, packageRoot, { taskId: explicitTaskId, eventsPath: eventsRel });
|
|
43
|
-
|
|
44
|
-
try {
|
|
45
|
-
const receiptArtifact = await readJsonArtifact(target, receiptRel, "execution-receipt", packageRoot);
|
|
46
|
-
currentReceipt = receiptArtifact?.value;
|
|
47
|
-
} catch {}
|
|
56
|
+
const currentReceipt = await readRecoveryReceipt(target, receiptRel, packageRoot);
|
|
48
57
|
const recoveryAuth = validateCompletionRecoveryAuthorization({
|
|
49
58
|
state,
|
|
50
59
|
receipt: currentReceipt,
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
// Bounded parsers for untrusted repository manifest text. They never throw on
|
|
2
|
+
// malformed input: every entry point returns an `invalid` shape instead.
|
|
3
|
+
import { PROJECT_DETECTION_LIMITS } from "./limits.js";
|
|
4
|
+
import { uniqueSorted } from "./shared.js";
|
|
5
|
+
|
|
6
|
+
const MAX_MANIFEST_BYTES = PROJECT_DETECTION_LIMITS.maxManifestBytes;
|
|
7
|
+
const MAX_XML_TEXT_LENGTH = 4096;
|
|
8
|
+
export const DOTNET_SDKS = new Set([
|
|
9
|
+
"Microsoft.NET.Sdk",
|
|
10
|
+
"Microsoft.NET.Sdk.Web",
|
|
11
|
+
"Microsoft.NET.Sdk.Worker",
|
|
12
|
+
"Microsoft.NET.Sdk.Razor",
|
|
13
|
+
"Microsoft.NET.Sdk.BlazorWebAssembly",
|
|
14
|
+
"Aspire.AppHost.Sdk",
|
|
15
|
+
"MSTest.Sdk",
|
|
16
|
+
]);
|
|
17
|
+
const ASPNETCORE_SDKS = new Set([
|
|
18
|
+
"Microsoft.NET.Sdk.Web",
|
|
19
|
+
"Microsoft.NET.Sdk.Razor",
|
|
20
|
+
"Microsoft.NET.Sdk.BlazorWebAssembly",
|
|
21
|
+
]);
|
|
22
|
+
|
|
23
|
+
function invalidDotNetProject() {
|
|
24
|
+
return {
|
|
25
|
+
valid: false,
|
|
26
|
+
sdkStyle: false,
|
|
27
|
+
projectSdks: [],
|
|
28
|
+
targetFrameworks: [],
|
|
29
|
+
frameworkReferences: [],
|
|
30
|
+
packageReferences: [],
|
|
31
|
+
projectReferences: [],
|
|
32
|
+
dotnet: false,
|
|
33
|
+
aspnetcore: false,
|
|
34
|
+
abp: false,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function findXmlTagEnd(text, start) {
|
|
39
|
+
let quote = null;
|
|
40
|
+
for (let index = start; index < text.length; index += 1) {
|
|
41
|
+
const character = text[index];
|
|
42
|
+
if (quote) {
|
|
43
|
+
if (character === quote) quote = null;
|
|
44
|
+
} else if (character === "\"" || character === "'") {
|
|
45
|
+
quote = character;
|
|
46
|
+
} else if (character === ">") {
|
|
47
|
+
return index;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return -1;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function parseXmlAttributes(text) {
|
|
54
|
+
const attributes = {};
|
|
55
|
+
let index = 0;
|
|
56
|
+
while (index < text.length) {
|
|
57
|
+
while (index < text.length && /\s/u.test(text[index])) index += 1;
|
|
58
|
+
if (index >= text.length) break;
|
|
59
|
+
const name = text.slice(index).match(/^[A-Za-z_][A-Za-z0-9_.:-]*/u)?.[0];
|
|
60
|
+
if (!name) return null;
|
|
61
|
+
index += name.length;
|
|
62
|
+
while (index < text.length && /\s/u.test(text[index])) index += 1;
|
|
63
|
+
if (text[index] !== "=") return null;
|
|
64
|
+
index += 1;
|
|
65
|
+
while (index < text.length && /\s/u.test(text[index])) index += 1;
|
|
66
|
+
const quote = text[index];
|
|
67
|
+
if (quote !== "\"" && quote !== "'") return null;
|
|
68
|
+
index += 1;
|
|
69
|
+
const end = text.indexOf(quote, index);
|
|
70
|
+
if (end < 0 || Object.prototype.hasOwnProperty.call(attributes, name)) return null;
|
|
71
|
+
attributes[name] = text.slice(index, end);
|
|
72
|
+
index = end + 1;
|
|
73
|
+
}
|
|
74
|
+
return attributes;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function appendXmlText(stack, value) {
|
|
78
|
+
if (value === "") return true;
|
|
79
|
+
const current = stack[stack.length - 1];
|
|
80
|
+
if (!current) return value.trim() === "";
|
|
81
|
+
current.textParts.push(value);
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function consumeXmlSpecialToken(text, tagStart, stack) {
|
|
86
|
+
if (text.startsWith("<!--", tagStart)) {
|
|
87
|
+
const end = text.indexOf("-->", tagStart + 4);
|
|
88
|
+
return end < 0 ? { valid: false } : { valid: true, nextIndex: end + 3 };
|
|
89
|
+
}
|
|
90
|
+
if (text.startsWith("<![CDATA[", tagStart)) {
|
|
91
|
+
const end = text.indexOf("]]>", tagStart + 9);
|
|
92
|
+
if (end < 0 || stack.length === 0) return { valid: false };
|
|
93
|
+
stack[stack.length - 1].textParts.push(text.slice(tagStart + 9, end));
|
|
94
|
+
return { valid: true, nextIndex: end + 3 };
|
|
95
|
+
}
|
|
96
|
+
if (text.startsWith("<?", tagStart)) {
|
|
97
|
+
const end = text.indexOf("?>", tagStart + 2);
|
|
98
|
+
return end < 0 ? { valid: false } : { valid: true, nextIndex: end + 2 };
|
|
99
|
+
}
|
|
100
|
+
if (text.startsWith("<!", tagStart)) return { valid: false };
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function closeXmlNode(raw, state) {
|
|
105
|
+
const closing = raw.slice(1).trim().match(/^([A-Za-z_][A-Za-z0-9_.:-]*)\s*$/u)?.[1];
|
|
106
|
+
const open = state.stack.pop();
|
|
107
|
+
if (!closing || !open || open.name !== closing) return false;
|
|
108
|
+
open.text = open.textParts.join("");
|
|
109
|
+
if (state.stack.length === 0) {
|
|
110
|
+
if (state.rootClosed || open !== state.root) return false;
|
|
111
|
+
state.rootClosed = true;
|
|
112
|
+
}
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function openXmlNode(raw, state) {
|
|
117
|
+
const selfClosing = /\/\s*$/u.test(raw);
|
|
118
|
+
const body = selfClosing ? raw.replace(/\/\s*$/u, "").trimEnd() : raw;
|
|
119
|
+
const name = body.match(/^([A-Za-z_][A-Za-z0-9_.:-]*)/u)?.[1];
|
|
120
|
+
if (!name) return false;
|
|
121
|
+
if (state.stack.length === 0 && (state.root || state.rootClosed)) return false;
|
|
122
|
+
if (!state.root && state.expectedRoot && name !== state.expectedRoot) return false;
|
|
123
|
+
const attributes = parseXmlAttributes(body.slice(name.length).trim());
|
|
124
|
+
if (!attributes) return false;
|
|
125
|
+
const node = { name, attributes, textParts: [], children: [], text: "" };
|
|
126
|
+
state.nodes.push(node);
|
|
127
|
+
if (state.stack.length > 0) state.stack[state.stack.length - 1].children.push(node);
|
|
128
|
+
if (!state.root) state.root = node;
|
|
129
|
+
if (!selfClosing) state.stack.push(node);
|
|
130
|
+
else if (node === state.root) state.rootClosed = true;
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function consumeXmlTag(text, tagStart, state) {
|
|
135
|
+
const tagEnd = findXmlTagEnd(text, tagStart + 1);
|
|
136
|
+
if (tagEnd < 0) return null;
|
|
137
|
+
const raw = text.slice(tagStart + 1, tagEnd).trim();
|
|
138
|
+
if (raw === "") return null;
|
|
139
|
+
const valid = raw.startsWith("/") ? closeXmlNode(raw, state) : openXmlNode(raw, state);
|
|
140
|
+
return { valid, nextIndex: tagEnd + 1 };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function parseXmlStructure(text, expectedRoot = null) {
|
|
144
|
+
if (typeof text !== "string" || text.length > MAX_MANIFEST_BYTES || /\r(?!\n)/u.test(text)) return null;
|
|
145
|
+
const state = { nodes: [], stack: [], root: null, rootClosed: false, expectedRoot };
|
|
146
|
+
let index = 0;
|
|
147
|
+
while (index < text.length) {
|
|
148
|
+
const tagStart = text.indexOf("<", index);
|
|
149
|
+
if (tagStart < 0) break;
|
|
150
|
+
if (!appendXmlText(state.stack, text.slice(index, tagStart))) return null;
|
|
151
|
+
const special = consumeXmlSpecialToken(text, tagStart, state.stack);
|
|
152
|
+
if (special) {
|
|
153
|
+
if (!special.valid) return null;
|
|
154
|
+
index = special.nextIndex;
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
const tag = consumeXmlTag(text, tagStart, state);
|
|
158
|
+
if (!tag?.valid) return null;
|
|
159
|
+
index = tag.nextIndex;
|
|
160
|
+
}
|
|
161
|
+
if (!appendXmlText(state.stack, text.slice(index))) return null;
|
|
162
|
+
if (!state.root || state.stack.length > 0 || !state.rootClosed) return null;
|
|
163
|
+
return { root: state.root, nodes: state.nodes };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function normalizeSdkName(value) {
|
|
167
|
+
return typeof value === "string" ? value.trim().split("/")[0] : "";
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function xmlValues(nodes, name, attribute = "Include") {
|
|
171
|
+
return uniqueSorted(nodes
|
|
172
|
+
.filter((node) => node.name === name && typeof node.attributes?.[attribute] === "string")
|
|
173
|
+
.map((node) => node.attributes[attribute].trim())
|
|
174
|
+
.filter(Boolean));
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function targetFrameworkValues(nodes) {
|
|
178
|
+
return uniqueSorted(nodes
|
|
179
|
+
.filter((node) => (node.name === "TargetFramework" || node.name === "TargetFrameworks")
|
|
180
|
+
&& node.children.length === 0
|
|
181
|
+
&& node.text.length <= MAX_XML_TEXT_LENGTH)
|
|
182
|
+
.flatMap((node) => node.text.split(";"))
|
|
183
|
+
.map((value) => value.trim())
|
|
184
|
+
.filter(Boolean));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function parseDotNetProject(text) {
|
|
188
|
+
const invalid = invalidDotNetProject();
|
|
189
|
+
if (typeof text !== "string" || text.length > MAX_MANIFEST_BYTES) return invalid;
|
|
190
|
+
const document = parseXmlStructure(text, "Project");
|
|
191
|
+
if (!document) return invalid;
|
|
192
|
+
|
|
193
|
+
const sdkValues = [
|
|
194
|
+
document.root.attributes.Sdk ?? "",
|
|
195
|
+
...document.nodes.filter((node) => node.name === "Sdk").map((node) => node.attributes.Name ?? ""),
|
|
196
|
+
];
|
|
197
|
+
const projectSdks = uniqueSorted(sdkValues
|
|
198
|
+
.flatMap((value) => value.split(";"))
|
|
199
|
+
.map(normalizeSdkName)
|
|
200
|
+
.filter(Boolean));
|
|
201
|
+
const recognizedSdks = projectSdks.filter((sdk) => DOTNET_SDKS.has(sdk));
|
|
202
|
+
const frameworkReferences = xmlValues(document.nodes, "FrameworkReference");
|
|
203
|
+
const packageReferences = xmlValues(document.nodes, "PackageReference");
|
|
204
|
+
const projectReferences = xmlValues(document.nodes, "ProjectReference");
|
|
205
|
+
const dotnet = recognizedSdks.length > 0;
|
|
206
|
+
const aspnetcore = dotnet && (recognizedSdks.some((sdk) => ASPNETCORE_SDKS.has(sdk))
|
|
207
|
+
|| frameworkReferences.some((reference) => reference.toLowerCase() === "microsoft.aspnetcore.app"));
|
|
208
|
+
const abp = dotnet && packageReferences.some((reference) => reference.toLowerCase().startsWith("volo.abp."));
|
|
209
|
+
return {
|
|
210
|
+
valid: true,
|
|
211
|
+
sdkStyle: dotnet,
|
|
212
|
+
projectSdks,
|
|
213
|
+
targetFrameworks: targetFrameworkValues(document.nodes),
|
|
214
|
+
frameworkReferences,
|
|
215
|
+
packageReferences,
|
|
216
|
+
projectReferences,
|
|
217
|
+
dotnet,
|
|
218
|
+
aspnetcore,
|
|
219
|
+
abp,
|
|
220
|
+
};
|
|
221
|
+
}
|