Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 | 54x 54x 1x 53x 53x 53x 53x 5x 48x 48x 54x 6x 42x 42x 42x 41x 245x 245x 245x 5x 240x 206x 2x 34x 1x 33x 33x 33x 32x 32x 224x 224x 224x 221x 2x 219x 27x 58x 54x 54x 27x 189x 189x 27x 701x 176x 2x 25x 25x 25x 1x 24x 1x 23x 23x 23x 58x 23x 1x 22x 154x 154x 1x 153x 154x 154x 1x 152x 2x 18x 18x 18x 1x 1x 1x 1x 1x 1x 6x 1x 1x 1x 1x 16x 16x 16x 112x 112x 112x 16x 16x 16x 4x 4x 4x 3x 1x 12x 12x 12x 12x 1x 11x 11x 12x 12x 12x 5x 5x 3x 2x 7x 7x 9x 9x 63x 684x 48x 1168x 84x 84x 583x 582x 83x 448x 448x 447x 447x 447x 445x 445x 445x 2x 893x 893x 591x 18x 126x 104x 104x 104x 1x 103x 17x | /**
* Publish orchestrator for the V1 Core CSS gitcore drop.
*
* Takes the evidence packet produced by `audit-v1-gitcore-drift` and publishes
* the seven V1 CSS artifacts to a gitcore release branch + PR: it validates and
* re-verifies the packet, uploads the unique LFS objects, atomically commits the
* six pointers plus the one plain file, creates the branch ref last, opens the
* PR, and posts the byte-level validation comment. It never rebuilds the CSS —
* it ships exactly the audited bytes — and it writes nothing until every safety
* check has passed.
*/
import { createHash } from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import type { CoreCssArtifactManifest } from '../services/core-css-preparation-service.js';
import type { GitcoreFileBuffer } from '../services/gitcore-service.js';
import { parseLfsPointer } from '../services/git-lfs-service.js';
import type { Logger } from '../utils/logger.js';
// CLI inputs: the packet path, the GUS work item, and the two mode flags.
export type PublishV1GitcoreCssArgs = {
result: string;
wi: string;
dryRun: boolean;
publishVersionOnly: boolean;
};
type Verdict = 'no-change' | 'version-only' | 'content-change';
// One artifact's bytes + recorded hashes/sizes, loaded and verified from the packet.
type ArtifactBytes = {
id: string;
path: string;
storage: 'git' | 'lfs';
baseline: Buffer;
candidate: Buffer;
baselineSha256: string;
candidateSha256: string;
baselineSize: number;
candidateSize: number;
rawEqual: boolean;
stampNormalizedEqual: boolean;
};
// The validated, in-memory form of the audit evidence packet this command publishes.
type LoadedPacket = {
version: string;
verdict: Verdict;
repo: string;
target: string;
baseSha: string;
artifacts: ArtifactBytes[];
};
// The design-system classifier, loaded from the repo so publish can re-derive
// the verdict from the on-disk bytes rather than trust the packet's recorded one.
type Classification = {
verdict: Verdict;
artifacts: Array<{ id: string; rawEqual: boolean; stampNormalizedEqual: boolean }>;
};
type Classifier = {
manifest: CoreCssArtifactManifest[];
classifyCoreCssArtifacts(
baseline: Array<{ id: string; path: string; content: Buffer }>,
candidate: Array<{ id: string; path: string; content: Buffer }>,
): Classification;
};
// The gitcore operations publish needs: reads, the Git Data API write primitives, and PR ops.
type Gitcore = {
getAuthenticatedLogin(): Promise<string>;
getRefSha(repo: string, target: string): Promise<string>;
getFileBuffer(repo: string, path: string, ref: string): Promise<GitcoreFileBuffer>;
getCommitTreeSha(repo: string, sha: string): Promise<string>;
getCommitParents(repo: string, sha: string): Promise<string[]>;
createBlobBase64(repo: string, content: Buffer): Promise<string>;
createTree(
repo: string,
baseTreeSha: string,
entries: Array<{ path: string; sha: string }>,
): Promise<string>;
createCommit(repo: string, message: string, treeSha: string, parentSha: string): Promise<string>;
getBranchHeadSha(repo: string, branch: string): Promise<string | null>;
createRef(repo: string, branch: string, commitSha: string): Promise<void>;
findOpenPullRequest(
repo: string,
base: string,
head: string,
): Promise<{ url: string; title: string; assignees: string[]; labels: string[] } | null>;
createPullRequest(input: {
repo: string;
base: string;
head: string;
title: string;
body: string;
assignees: string[];
labels: string[];
}): Promise<string>;
};
// Injected dependencies: gitcore + LFS services, the packet loader and classifier
// loader (both injectable so tests stay hermetic), and the logger.
export type PublishV1GitcoreCssDeps = {
gitcore: Gitcore;
lfs: {
hydrate(pointerBytes: Buffer): Promise<Buffer>;
queryObjects(
objects: Array<{ oid: string; size: number; content: Buffer }>,
): Promise<{ uploadRequired: string[]; alreadyPresent: string[] }>;
uploadObjects(
objects: Array<{ oid: string; size: number; content: Buffer }>,
): Promise<{ uploaded: string[]; alreadyPresent: string[] }>;
};
loadPacket(resultPath: string, manifest: CoreCssArtifactManifest[]): Promise<LoadedPacket>;
loadClassifier(): Promise<Classifier>;
logger: Logger;
};
// Structured result: published (with branch/commit/PR + per-artifact summary for
// the validation comment), skipped (no-change / version-only without opt-in), or dry-run.
export type PublishOutcome = {
status: 'published' | 'skipped' | 'dry-run';
version: string;
verdict: Verdict;
repo: string;
target: string;
baseSha: string;
branch?: string;
commitSha?: string;
prUrl?: string;
prCreated?: boolean;
uploaded?: string[];
alreadyPresent?: string[];
reason?: string;
artifacts: Array<{
id: string;
gitcorePath: string;
storage: 'git' | 'lfs';
rawEqual: boolean;
stampNormalizedEqual: boolean;
baselineSize: number;
candidateSize: number;
}>;
};
/**
* Load and fully validate the audit evidence packet into memory.
*
* Everything here runs before any gitcore write. It rejects a packet that is
* malformed, points at an unexpected repo/target/base, references the wrong
* artifact set, escapes the report directory via symlink/traversal, or whose
* on-disk bytes do not match their recorded sizes and SHA-256s. The returned
* bytes — not the packet's JSON — are what the rest of the flow trusts.
*/
export async function loadAuditPacket(
resultPath: string,
manifest: CoreCssArtifactManifest[],
): Promise<LoadedPacket> {
let value: unknown;
try {
value = JSON.parse(await fs.readFile(resultPath, 'utf8'));
} catch {
throw new Error('Invalid evidence packet');
}
Iif (!isRecord(value)) throw new Error('Invalid evidence packet');
const packet = value;
// Strict SemVer so the version can be interpolated into a branch name / PR title safely.
const versionPattern =
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
if (
packet.schemaVersion !== 1 ||
typeof packet.version !== 'string' ||
!versionPattern.test(packet.version) ||
typeof packet.sourceSha !== 'string' ||
packet.sourceSha.length === 0 ||
typeof packet.parserVersion !== 'string' ||
packet.parserVersion.length === 0 ||
typeof packet.reportDir !== 'string' ||
packet.reportDir.length === 0 ||
!isVerdict(packet.verdict) ||
!isRecord(packet.baseline) ||
!Array.isArray(packet.artifacts)
) {
throw new Error('Invalid evidence packet');
}
// Constrain the publication target: repo must be a core-2206 public release repo,
// target its matching main/patch branch, baseSha a real object id. This stops a
// crafted packet from redirecting writes to an unintended repo or branch.
const baseline = packet.baseline;
const repoMatch =
typeof baseline.repo === 'string' ? /^core-2206\/core-(\d+)-public$/.exec(baseline.repo) : null;
if (
!repoMatch ||
(baseline.target !== `p4/${repoMatch[1]}-main` && baseline.target !== `p4/${repoMatch[1]}-patch`) ||
typeof baseline.baseSha !== 'string' ||
!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(baseline.baseSha) ||
!Array.isArray(baseline.artifacts) ||
baseline.artifacts.length !== manifest.length ||
packet.artifacts.length !== manifest.length ||
manifest.length !== 7
) {
throw new Error('Invalid evidence packet');
}
// Every manifest artifact must have well-formed provenance + recorded result
// metadata, matched by id; LFS entries carry an oid/size, git entries must not.
const provenanceById = uniqueRecordsById(baseline.artifacts);
const resultById = uniqueRecordsById(packet.artifacts);
if (!provenanceById || !resultById) throw new Error('Invalid evidence packet');
for (const artifact of manifest) {
const provenance = provenanceById.get(artifact.id);
const recorded = resultById.get(artifact.id);
if (
!provenance ||
!recorded ||
provenance.path !== artifact.gitcorePath ||
provenance.storage !== artifact.storage ||
recorded.path !== artifact.gitcorePath ||
typeof provenance.gitBlobSha !== 'string' ||
provenance.gitBlobSha.length === 0 ||
!isSize(provenance.gitBlobSize) ||
!isSize(provenance.apiSize) ||
recorded.storage !== artifact.storage ||
!isSize(recorded.baselineSize) ||
!isSize(recorded.candidateSize) ||
typeof recorded.baselineSha256 !== 'string' ||
!/^[0-9a-f]{64}$/.test(recorded.baselineSha256) ||
typeof recorded.candidateSha256 !== 'string' ||
!/^[0-9a-f]{64}$/.test(recorded.candidateSha256) ||
typeof recorded.rawEqual !== 'boolean' ||
typeof recorded.stampNormalizedEqual !== 'boolean'
) {
throw new Error('Invalid evidence packet');
}
if (artifact.storage === 'lfs') {
if (
typeof provenance.lfsOid !== 'string' ||
!/^[0-9a-f]{64}$/.test(provenance.lfsOid) ||
!isSize(provenance.lfsSize)
) {
throw new Error('Invalid evidence packet');
}
} else if (provenance.lfsOid !== undefined || provenance.lfsSize !== undefined) {
throw new Error('Invalid evidence packet');
}
}
// The report dir named in the packet must be the directory the packet file
// actually lives in (realpath compare) — guards against a packet pointing its
// baseline/candidate reads at some other location.
let resultDirectory: string;
let reportDirectory: string;
try {
[resultDirectory, reportDirectory] = await Promise.all([
fs.realpath(path.dirname(resultPath)),
fs.realpath(packet.reportDir),
]);
} catch {
throw new Error('Evidence packet reportDir mismatch');
}
if (resultDirectory !== reportDirectory) throw new Error('Evidence packet reportDir mismatch');
// Read each artifact's baseline + candidate bytes from the packet and confirm
// they match the recorded sizes and SHA-256s. A tampered byte fails here.
const [baselineRoot, candidateRoot] = await Promise.all([
fs.realpath(path.join(reportDirectory, 'baseline')),
fs.realpath(path.join(reportDirectory, 'candidate')),
]);
const artifacts = await Promise.all(
manifest.map(async (artifact): Promise<ArtifactBytes> => {
const provenance = provenanceById.get(artifact.id)!;
const recorded = resultById.get(artifact.id)!;
const [baselineBytes, candidateBytes] = await Promise.all([
readSafeFile(baselineRoot, artifact.gitcorePath),
readSafeFile(candidateRoot, artifact.candidatePath),
]);
if (
baselineBytes.length !== recorded.baselineSize ||
hash(baselineBytes) !== recorded.baselineSha256 ||
candidateBytes.length !== recorded.candidateSize ||
hash(candidateBytes) !== recorded.candidateSha256
) {
throw new Error(`Evidence packet hash mismatch for ${artifact.id}`);
}
return {
id: artifact.id,
path: artifact.gitcorePath,
storage: artifact.storage,
baseline: baselineBytes,
candidate: candidateBytes,
baselineSha256: recorded.baselineSha256 as string,
candidateSha256: recorded.candidateSha256 as string,
baselineSize: recorded.baselineSize as number,
candidateSize: recorded.candidateSize as number,
rawEqual: recorded.rawEqual as boolean,
stampNormalizedEqual: recorded.stampNormalizedEqual as boolean,
};
}),
);
return {
version: packet.version,
verdict: packet.verdict,
repo: baseline.repo as string,
target: baseline.target as string,
baseSha: baseline.baseSha as string,
artifacts,
};
}
/**
* Publish the audited V1 CSS packet to gitcore.
*
* Ordering is the safety contract: validate the packet, re-derive the verdict,
* gate on it, confirm the target has not moved, anchor the baseline to gitcore,
* then (real runs only) upload LFS objects, build the commit, and create the
* branch ref LAST so any earlier failure leaves only unreferenced objects.
*/
export async function runPublishV1GitcoreCss(
args: PublishV1GitcoreCssArgs,
deps: PublishV1GitcoreCssDeps,
): Promise<PublishOutcome> {
// WI format is validated up front; it becomes part of the branch name and PR title.
if (!/^W-\d+$/.test(args.wi)) throw new Error(`Invalid work item: ${args.wi}`);
const classifier = await deps.loadClassifier();
const packet = await deps.loadPacket(args.result, classifier.manifest);
// Re-derive the verdict from the on-disk bytes. If a hand-edited result.json
// claims a different verdict or per-artifact equality than the bytes produce,
// refuse — the packet's recorded verdict is never trusted on its own.
const classification = classifier.classifyCoreCssArtifacts(
packet.artifacts.map(({ id, path: artifactPath, baseline }) => ({
id,
path: artifactPath,
content: baseline,
})),
packet.artifacts.map(({ id, path: artifactPath, candidate }) => ({
id,
path: artifactPath,
content: candidate,
})),
);
if (
classification.verdict !== packet.verdict ||
classification.artifacts.length !== packet.artifacts.length ||
packet.artifacts.some((recorded) => {
const derived = classification.artifacts.find(({ id }) => id === recorded.id);
return (
!derived ||
derived.rawEqual !== recorded.rawEqual ||
derived.stampNormalizedEqual !== recorded.stampNormalizedEqual
);
})
) {
throw new Error('Evidence packet verdict mismatch');
}
const verdict = classification.verdict;
const outcomeBase = {
version: packet.version,
verdict,
repo: packet.repo,
target: packet.target,
baseSha: packet.baseSha,
};
// Verdict gate. Touched CSS *content* is the criterion for a gitcore PR:
// no-change never ships; version-only is a stamp-only re-stamp that ships only
// on explicit opt-in; content-change publishes. This single decision point is
// also where an App-era human throttle would later hook in.
if (verdict === 'no-change') {
return { status: 'skipped', ...outcomeBase, reason: 'no-change', artifacts: [] };
}
if (verdict === 'version-only' && !args.publishVersionOnly) {
return {
status: 'skipped',
...outcomeBase,
reason: 'version-only requires --publish-version-only',
artifacts: [],
};
}
const branch = `t/design-systems-engineering/${args.wi.toLowerCase()}/slds-${packet.version}`;
const title = `@${args.wi}: Release SLDS v${packet.version}`;
const body = `Release SLDS ${packet.version} CSS artifacts.${
verdict === 'version-only' ? '\n\nThis is a version-only re-stamp.' : ''
}`;
// Base-drift check #1: the target must still be at the audited base before we
// touch anything. If it moved, the audit is stale — stop and re-audit.
const current = await deps.gitcore.getRefSha(packet.repo, packet.target);
if (current !== packet.baseSha) {
throw new Error(
`Target ${packet.target} moved from audited base ${packet.baseSha} to ${current}; re-audit`,
);
}
// Anchor the baseline to gitcore: re-fetch each of the seven files at baseSha
// (hydrating LFS) and require them to equal the packet's baseline bytes. This
// proves the packet describes what is actually vended right now, closing the
// gap where a crafted packet could otherwise misrepresent the baseline.
await Promise.all(
packet.artifacts.map(async (artifact) => {
const file = await deps.gitcore.getFileBuffer(packet.repo, `core/${artifact.path}`, packet.baseSha);
if (
artifact.storage === 'git' &&
(file.content.length !== file.apiSize || file.content.length !== file.blobSize)
) {
throw new Error(`Core CSS size mismatch for ${artifact.path}`);
}
const pointer = artifact.storage === 'lfs' ? parseLfsPointer(file.content) : undefined;
const content = pointer ? await deps.lfs.hydrate(file.content) : file.content;
if (pointer && (content.length !== pointer.size || content.length !== file.apiSize)) {
throw new Error(`Core CSS size mismatch for ${artifact.path}`);
}
if (
hash(content) !== artifact.baselineSha256 ||
content.length !== artifact.baselineSize ||
!content.equals(artifact.baseline)
) {
throw new Error(
`Evidence packet baseline does not match gitcore at ${packet.baseSha} for ${artifact.path}`,
);
}
}),
);
deps.logger.step(`Anchored ${packet.artifacts.length} baseline files to gitcore @ ${packet.baseSha}`);
// The six LFS files dedupe by content to a handful of unique objects to upload.
const lfsObjects = uniqueLfsObjects(packet.artifacts);
// Dry-run: do the real reads (incl. a read-only LFS presence query) and report
// the intended branch/commit/PR, but perform no uploads or writes.
if (args.dryRun) {
const query = await deps.lfs.queryObjects(lfsObjects);
deps.logger.dryRun(`Branch: ${branch}`);
deps.logger.dryRun(`Commit message / PR title: ${title}`);
deps.logger.dryRun(`PR body: ${body}`);
deps.logger.dryRun('Assignee: @me');
deps.logger.dryRun('Label: Team: Design Systems Engineering');
for (const object of lfsObjects) deps.logger.dryRun(`LFS object: ${object.oid} (${object.size} bytes)`);
deps.logger.dryRun(`LFS upload required: ${query.uploadRequired.length}`);
deps.logger.dryRun(`LFS already present: ${query.alreadyPresent.length}`);
deps.logger.dryRun('A real run will upload, commit, create the branch, and open the PR.');
return { status: 'dry-run', ...outcomeBase, branch, artifacts: [] };
}
const head = await deps.gitcore.getBranchHeadSha(packet.repo, branch);
// Build the committable tree: LFS files become canonical pointer blobs, the one
// plain file is its raw candidate bytes; all created byte-exact via base64.
// (base_tree lookup runs alongside blob creation since it is independent.)
const createIntendedTree = async (): Promise<string> => {
const [entries, baseTreeSha] = await Promise.all([
Promise.all(
packet.artifacts.map(async (artifact) => {
const content =
artifact.storage === 'lfs'
? Buffer.from(
`version https://git-lfs.github.com/spec/v1\noid sha256:${artifact.candidateSha256}\nsize ${artifact.candidateSize}\n`,
)
: artifact.candidate;
const sha = await deps.gitcore.createBlobBase64(packet.repo, content);
return { path: `core/${artifact.path}`, sha };
}),
),
deps.gitcore.getCommitTreeSha(packet.repo, packet.baseSha),
]);
return deps.gitcore.createTree(packet.repo, baseTreeSha, entries);
};
let commitSha: string;
let upload = { uploaded: [] as string[], alreadyPresent: [] as string[] };
if (head !== null) {
// Branch already exists (likely a prior interrupted run). Resume only if it
// matches exactly: same tree and a sole parent of baseSha. We key on the tree
// SHA, not the commit SHA, because commit SHAs vary by timestamp. Any
// mismatch is left untouched for a human — never force-updated or deleted.
const treeSha = await createIntendedTree();
const [headTree, parents] = await Promise.all([
deps.gitcore.getCommitTreeSha(packet.repo, head),
deps.gitcore.getCommitParents(packet.repo, head),
]);
if (headTree !== treeSha || parents.length !== 1 || parents[0] !== packet.baseSha) {
throw new Error(`Branch ${branch} exists with different content; inspect and coordinate`);
}
commitSha = head;
} else {
// Fresh publish: upload LFS objects, build the commit, then re-check the base
// (drift check #2) immediately before creating the ref so the branch only
// appears once everything behind it is in place.
upload = await deps.lfs.uploadObjects(lfsObjects);
const treeSha = await createIntendedTree();
const createdCommitSha = await deps.gitcore.createCommit(packet.repo, title, treeSha, packet.baseSha);
if ((await deps.gitcore.getRefSha(packet.repo, packet.target)) !== packet.baseSha) {
throw new Error('Target moved during publish; re-audit');
}
await deps.gitcore.createRef(packet.repo, branch, createdCommitSha);
commitSha = createdCommitSha;
}
// Reuse an already-open PR for this branch (validating its metadata) or open a
// new one. prCreated distinguishes the two so the caller posts the validation
// comment only on a freshly created PR, keeping reruns from duplicating it.
const existing = await deps.gitcore.findOpenPullRequest(packet.repo, packet.target, branch);
let prUrl: string;
let prCreated = false;
if (existing) {
// @me resolves to a login in the returned assignee list, so compare against
// the authenticated login rather than the literal "@me" alias.
const self = await deps.gitcore.getAuthenticatedLogin();
if (
existing.title !== title ||
!existing.assignees.includes(self) ||
!existing.labels.includes('Team: Design Systems Engineering')
) {
throw new Error(`Existing PR ${existing.url} missing required metadata`);
}
prUrl = existing.url;
} else {
prUrl = await deps.gitcore.createPullRequest({
repo: packet.repo,
base: packet.target,
head: branch,
title,
body,
assignees: ['@me'],
labels: ['Team: Design Systems Engineering'],
});
prCreated = true;
}
deps.logger.success(`Published ${commitSha} on ${branch}: ${prUrl}`);
return {
status: 'published',
...outcomeBase,
branch,
commitSha,
prUrl,
prCreated,
uploaded: upload.uploaded,
alreadyPresent: upload.alreadyPresent,
artifacts: packet.artifacts.map((artifact) => ({
id: artifact.id,
gitcorePath: artifact.path,
storage: artifact.storage,
rawEqual: artifact.rawEqual,
stampNormalizedEqual: artifact.stampNormalizedEqual,
baselineSize: artifact.baselineSize,
candidateSize: artifact.candidateSize,
})),
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isVerdict(value: unknown): value is Verdict {
return value === 'no-change' || value === 'version-only' || value === 'content-change';
}
function isSize(value: unknown): value is number {
return Number.isSafeInteger(value) && (value as number) >= 0;
}
function uniqueRecordsById(values: unknown[]): Map<string, Record<string, unknown>> | null {
const records = new Map<string, Record<string, unknown>>();
for (const value of values) {
if (!isRecord(value) || typeof value.id !== 'string' || records.has(value.id)) return null;
records.set(value.id, value);
}
return records;
}
// Read a packet file while refusing anything that escapes the report dir: no
// traversal, no symlinks, and the realpath must still resolve under the root.
async function readSafeFile(root: string, relativePath: string): Promise<Buffer> {
const intended = path.resolve(root, relativePath);
if (!isUnder(root, intended)) throw new Error('Unsafe evidence packet path');
try {
const stat = await fs.lstat(intended);
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('Unsafe evidence packet path');
const resolved = await fs.realpath(intended);
Iif (!isUnder(root, resolved)) throw new Error('Unsafe evidence packet path');
return await fs.readFile(resolved);
} catch (error) {
Eif (error instanceof Error && error.message === 'Unsafe evidence packet path') throw error;
throw new Error('Unsafe evidence packet path');
}
}
function isUnder(root: string, candidate: string): boolean {
const relative = path.relative(root, candidate);
return (
relative.length > 0 &&
!relative.startsWith(`..${path.sep}`) &&
relative !== '..' &&
!path.isAbsolute(relative)
);
}
function hash(content: Buffer): string {
return createHash('sha256').update(content).digest('hex');
}
// Collapse the LFS artifacts to their unique objects (by oid); a repeated oid
// with mismatched size/content is a corrupt packet and aborts.
function uniqueLfsObjects(artifacts: ArtifactBytes[]): Array<{ oid: string; size: number; content: Buffer }> {
const objects = new Map<string, { oid: string; size: number; content: Buffer }>();
for (const artifact of artifacts.filter(({ storage }) => storage === 'lfs')) {
const object = {
oid: artifact.candidateSha256,
size: artifact.candidateSize,
content: artifact.candidate,
};
const existing = objects.get(object.oid);
if (existing && (existing.size !== object.size || !existing.content.equals(object.content))) {
throw new Error(`Git LFS object conflict for ${object.oid}`);
}
if (!existing) objects.set(object.oid, object);
}
return [...objects.values()];
}
|