From 7f8119f4accf192e787c988e768604ca161183d6 Mon Sep 17 00:00:00 2001 From: Krrish Mittal Date: Tue, 24 Nov 2026 18:02:55 -0800 Subject: [PATCH 1/2] chore(ci): simplify ADO npm publish pipeline for E2E test Collapse .azure-pipelines/npm-publish.yml to a single Publish stage and simplify scripts/ado-npm-publisher.cjs to build from the release tag, skip packages already in the feed, and run npm publish without extra verification or post-publish readbacks. Temporarily omit the Build.SourceBranch filter on this test branch for E2E validation. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .azure-pipelines/npm-publish.yml | 382 +--- .azure-pipelines/npm-verify-release.steps.yml | 169 -- scripts/ado-npm-publisher-artifact.cjs | 398 ---- scripts/ado-npm-publisher-lib.cjs | 402 ---- scripts/ado-npm-publisher-test-feed.cjs | 332 --- scripts/ado-npm-publisher.cjs | 493 ++--- scripts/ado-npm-publisher.test.cjs | 1927 +++-------------- 7 files changed, 613 insertions(+), 3490 deletions(-) delete mode 100644 .azure-pipelines/npm-verify-release.steps.yml delete mode 100644 scripts/ado-npm-publisher-artifact.cjs delete mode 100644 scripts/ado-npm-publisher-lib.cjs delete mode 100644 scripts/ado-npm-publisher-test-feed.cjs diff --git a/.azure-pipelines/npm-publish.yml b/.azure-pipelines/npm-publish.yml index 46234059bde..7a8730fad34 100644 --- a/.azure-pipelines/npm-publish.yml +++ b/.azure-pipelines/npm-publish.yml @@ -1,33 +1,23 @@ -# Manual npm release build for LogicAppsUX, driven by one canonical stable version (X.Y.Z). +# Manual npm release publish pipeline for LogicAppsUX. # -# Versioning and release publication stay in GitHub (version-release.yml). This pipeline takes the -# canonical stable version, resolves refs/tags/vX.Y.Z^{commit} from the local checked-out repository, -# and builds that exact commit with the recipe (scripts/ado-npm-publisher*.cjs and this YAML) from -# the reviewed pipeline ref. Released tags never need to carry this pipeline. -# Select a release that is already complete and stable; the pipeline does not look up release status. -# The product build scripts (pnpm build:lib, scripts/update-versions.js) come from the released tree. -# Release assets (VSIX, iframe ZIP) are never read or treated as npm packages. -# -# This pipeline warns about absent literal CSS export files; all other archive checks still fail closed. -# Released manifests and tarballs are not patched. -# Component Governance scans the agent build directory, including the retained release worktree. -# Actual detection of the tagged dependency inputs must be verified in ADO. -# -# Publish follows successful Release validation automatically, subject to the WIF service connection checks. +# Versioning and GitHub Release creation stay in .github/workflows/version-release.yml. +# Given a release version (e.g. 5.1024.0), this pipeline checks out the existing v +# tag into a clean detached worktree, builds and packs the 9 publishable packages, and +# publishes any missing packages to the Azure Artifacts npm feed. trigger: none pr: none schedules: [] parameters: - name: releaseVersion - displayName: Stable release version (e.g. 5.1024.0) + displayName: Release version (e.g. 5.1024.0) type: string default: '' variables: - ArtifactName: logicappsux-npm-release-cohort - PackageOutput: '$(Build.ArtifactStagingDirectory)/logicappsux-npm-release-cohort' NpmRegistry: 'https://pkgs.dev.azure.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/' + TarballDir: '$(Agent.TempDirectory)/npm-tarballs' + PublishNpmrc: '$(Agent.TempDirectory)/npm-publish/.npmrc' resources: repositories: @@ -51,20 +41,16 @@ extends: image: windows-latest os: windows stages: - - stage: Release - displayName: Build and verify npm packages for one stable release version + - stage: Publish + displayName: Build and publish npm packages + lockBehavior: sequential + condition: succeeded() jobs: - - job: BuildRelease - displayName: Resolve local tag, build exact source, pack and validate + - job: BuildAndPublish + displayName: Build release tag and publish to npm feed workspace: clean: all - templateContext: - outputs: - - output: pipelineArtifact - targetPath: '$(PackageOutput)' - artifactName: '$(ArtifactName)' steps: - # This checkout provides both the recipe and tag objects; scripts do not fetch source again. - checkout: self clean: true fetchTags: true @@ -74,339 +60,27 @@ extends: displayName: Use Node 24 inputs: version: '24.x' - - bash: node scripts/ado-npm-publisher.cjs build-release-artifact - displayName: Resolve version tag, build its exact commit and validate nine tarballs + - bash: node scripts/ado-npm-publisher.cjs build + displayName: Build and pack release packages workingDirectory: '$(Build.Repository.LocalPath)' env: - BASH_ENV: /dev/null RELEASE_VERSION: ${{ parameters.releaseVersion }} - BUILD_REASON: '$(Build.Reason)' - BUILD_ID: '$(Build.BuildId)' - RECIPE_SHA: '$(Build.SourceVersion)' - SOURCE_REPOSITORY: '$(Build.Repository.Name)' AGENT_TMP: '$(Agent.TempDirectory)' RELEASE_SCAN_ROOT: '$(Agent.BuildDirectory)' - ARTIFACT_ROOT: '$(PackageOutput)' - # Publish the manifest digest as a job output so the verifier pins the exact uploaded manifest. - - bash: | - set -euo pipefail - python3 -I - <<'PY' - import hashlib, json, os, re, stat - path = os.path.join(os.environ['PACKAGE_OUTPUT'], 'publisher-artifact.json') - fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) - with os.fdopen(fd, 'rb') as handle: - if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode): - raise SystemExit('Manifest is not a regular file.') - data = handle.read(128 * 1024 + 1) - if len(data) > 128 * 1024: - raise SystemExit('Manifest is too large.') - sha = json.loads(data)['source']['verifiedSha'] - if not isinstance(sha, str) or not re.fullmatch(r'[0-9a-f]{40}', sha): - raise SystemExit('Manifest source SHA is invalid.') - print('##vso[task.setvariable variable=ManifestSha256;isOutput=true]' + hashlib.sha256(data).hexdigest()) - print('##vso[task.setvariable variable=SourceSha;isOutput=true]' + sha) - PY - name: manifest - displayName: Record manifest digest and source SHA - env: - BASH_ENV: /dev/null - PACKAGE_OUTPUT: '$(PackageOutput)' - - # Artifact-only consumer: no repository checkout, no tool from the artifact is executed, and every - # byte is checked against this run's manifest digest, release version tag, build ID and recipe commit. - - job: VerifyRelease - displayName: Verify the same-run artifact without a checkout - dependsOn: BuildRelease - variables: - ExpectedManifestSha256: $[ dependencies.BuildRelease.outputs['manifest.ManifestSha256'] ] - ExpectedSourceSha: $[ dependencies.BuildRelease.outputs['manifest.SourceSha'] ] - ArtifactDir: '$(Pipeline.Workspace)/release-artifact' - templateContext: - inputs: - - input: pipelineArtifact - buildType: current - artifactName: '$(ArtifactName)' - targetPath: '$(ArtifactDir)' - steps: - - checkout: none - - template: /.azure-pipelines/npm-verify-release.steps.yml@self - parameters: - releaseVersion: ${{ parameters.releaseVersion }} - - # Release never writes to the feed; Publish requires the protected service connection. - - job: ProductionPublishNotActivated - displayName: Release stage remains validation-only - dependsOn: VerifyRelease - steps: - - checkout: none - - bash: | - set -euo pipefail - echo '##vso[task.logissue type=warning]Release stage validated artifacts only. Feed writes require the protected Publish stage.' - displayName: Report that Release stage did not write to npm - env: - BASH_ENV: /dev/null - - - stage: Publish - displayName: Publish verified npm release cohort - dependsOn: Release - # Serialize this pipeline's Publish stages, not writers outside this pipeline. - lockBehavior: sequential - # Stage conditions use dependencies; job variables below use stageDependencies. - condition: and( - not(canceled()), - eq(dependencies.Release.result, 'Succeeded'), - eq(dependencies.Release.outputs['VerifyRelease.verification.ArtifactVerified'], 'true'), - eq(variables['Build.Reason'], 'Manual'), - eq(variables['Build.SourceBranch'], 'refs/heads/hotfix/v1.23123') - ) - jobs: - - job: PublishRelease - displayName: Publish release cohort with reconciled readback - workspace: - clean: all - variables: - ArtifactDir: '$(Pipeline.Workspace)/release-artifact' - NpmWriter: '$(Agent.TempDirectory)/npm-writer-private' - ExpectedManifestSha256: $[ stageDependencies.Release.BuildRelease.outputs['manifest.ManifestSha256'] ] - ExpectedSourceSha: $[ stageDependencies.Release.BuildRelease.outputs['manifest.SourceSha'] ] - templateContext: - inputs: - - input: pipelineArtifact - buildType: current - artifactName: '$(ArtifactName)' - targetPath: '$(ArtifactDir)' - steps: - - checkout: none - - template: /.azure-pipelines/npm-verify-release.steps.yml@self - parameters: - releaseVersion: ${{ parameters.releaseVersion }} - prepareWriter: true - - task: UseNode@1 - displayName: Use Node 24 - inputs: - version: '24.x' + TARBALL_DIR: '$(TarballDir)' + NPM_REGISTRY: '$(NpmRegistry)' + PUBLISH_NPMRC: '$(PublishNpmrc)' - task: npmAuthenticate@0 - displayName: Authenticate npm writer via protected WIF + displayName: Authenticate npm feed via WIF inputs: - workingFile: '$(NpmWriter)/.npmrc' + workingFile: '$(PublishNpmrc)' workloadIdentityServiceConnection: 21d5a1d8-11d3-425c-8d3a-e7f088725481 feedUrl: 'https://pkgs.dev.azure.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/' - - bash: | - set -euo pipefail - python3 -I - <<'PY' - import hashlib - import json - import os - import re - import subprocess - import tempfile - from pathlib import Path - - os.umask(0o077) - root = Path(os.environ['DIR']).resolve() - registry = os.environ['REGISTRY'] - version = os.environ['RELEASE_VERSION'] - auth_line = re.compile(r'//pkgs\.dev\.azure\.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/:_authToken=\S+') - if registry != 'https://pkgs.dev.azure.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/': - raise SystemExit('Publish registry endpoint is not approved.') - npmrc = root / '.npmrc' - if not npmrc.is_file(): - raise SystemExit('Writer .npmrc is missing.') - if not any(auth_line.fullmatch(line.strip()) for line in npmrc.read_text(encoding='utf-8').splitlines()): - raise SystemExit('Scoped npm _authToken line is missing after npmAuthenticate.') - cohort = json.loads((root / 'cohort.json').read_text(encoding='utf-8')) - rows = cohort.get('packages') - if not isinstance(rows, list) or len(rows) != 9: - raise SystemExit('cohort.json must contain exactly nine validated package rows.') - - numeric_semver = r'(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)' - inventory_version = re.compile(numeric_semver + r'(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?') - - def parse_numeric_semver(value): - if not re.fullmatch(numeric_semver, value): - raise SystemExit('Encountered non-numeric semver; failing closed.') - parts = value.split('.') - return int(parts[0]), int(parts[1]), int(parts[2]) - - target_key = parse_numeric_semver(version) - base_env = {'PATH': os.environ['PATH'], 'HOME': str(root)} - write_root = root / 'write-cache' - write_root.mkdir(exist_ok=True) - - def run_npm(args, cache_dir, timeout_seconds): - command = [ - 'npm', - *args, - '--registry', - registry, - '--userconfig', - str(npmrc), - '--globalconfig', - '/dev/null', - '--strict-ssl', - 'true', - '--ignore-scripts', - '--fetch-retries', - '0', - '--fetch-timeout', - '60000', - '--logs-max', - '0', - '--cache', - str(cache_dir), - ] - return subprocess.run( - command, - cwd=root, - env=base_env, - stdin=subprocess.DEVNULL, - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - text=True, - timeout=timeout_seconds, - check=False, - ) - - def read_npm(args, timeout_seconds): - # A fresh cache prevents a retry or readback from proving state using local bytes. - with tempfile.TemporaryDirectory(dir=root, prefix='read-cache-') as cache: - return run_npm([*args, '--prefer-online'], cache, timeout_seconds) - - def read_json(args, spec): - try: - result = read_npm([*args, '--json'], 90) - if result.returncode == 0: - return json.loads(result.stdout) - except (subprocess.TimeoutExpired, ValueError): - pass - raise SystemExit(f'Registry metadata is inconclusive for {spec}.') - - def inventory(name): - payload = read_json(['view', name, 'name', 'version', 'versions', 'dist-tags'], name) - if not isinstance(payload, dict) or sorted(payload.keys()) != ['dist-tags', 'name', 'version', 'versions']: - raise SystemExit(f'Inventory shape is invalid for {name}.') - if payload['name'] != name: - raise SystemExit(f'Inventory package identity mismatch for {name}.') - versions = payload['versions'] - if not isinstance(versions, list) or not all(isinstance(v, str) and inventory_version.fullmatch(v) for v in versions): - raise SystemExit(f'Inventory versions list is invalid for {name}.') - if any(v.startswith(version + '+') for v in versions): - raise SystemExit(f'An existing version has the same SemVer precedence as {name}@{version}.') - tags = payload['dist-tags'] - if not isinstance(tags, dict) or 'latest' not in tags or not isinstance(tags['latest'], str): - raise SystemExit(f'Inventory dist-tags are invalid for {name}.') - if payload['version'] != tags['latest']: - raise SystemExit(f'Inventory latest tag is unstable for {name}.') - if any(tagged not in versions for tagged in tags.values()): - raise SystemExit(f'Inventory contains an unlisted tagged version for {name}.') - latest_key = parse_numeric_semver(tags['latest']) - if latest_key > target_key: - raise SystemExit(f'Latest published version for {name} is newer than target {version}.') - return payload - - def verify_exact_present(row): - name, file_name = row['name'], row['file'] - spec = f'{name}@{version}' - payload = read_json(['view', spec, 'name', 'version', 'dist.integrity', 'dist.tarball'], spec) - if not isinstance(payload, dict) or sorted(payload.keys()) != ['dist.integrity', 'dist.tarball', 'name', 'version']: - raise SystemExit(f'Exact version payload shape is invalid for {spec}.') - if payload['name'] != name or payload['version'] != version or payload['dist.integrity'] != row['integrity']: - raise SystemExit(f'Exact version metadata mismatch for {spec}.') - package = name.split('/', 1)[1] - attachment = f'{package}/-/{package}-{version}.tgz' - legacy_registry = 'https://msazure.pkgs.visualstudio.com/One/_packaging/microsoft-logic-apps/npm/registry/' - allowed_roots = f'(?:{re.escape(registry)}|{re.escape(legacy_registry)})' - # Accept only the exact attachment route, optionally with the npm scope/slash escaped. - route = allowed_roots + r'(?:@|%40)microsoft(?:/|%2[fF])' + re.escape(attachment) - tarball = payload['dist.tarball'] - if not isinstance(tarball, str) or not re.fullmatch(route, tarball): - raise SystemExit(f'Unapproved registry attachment for {spec}.') - # Fetch that attachment directly using the authenticated alias. npm handles service redirects. - with tempfile.TemporaryDirectory(dir=root, prefix='readback-') as readback: - try: - pack = read_npm(['pack', f'{registry}@microsoft/{attachment}', '--pack-destination', readback], 120) - except subprocess.TimeoutExpired: - raise SystemExit(f'Exact readback timed out for {spec}.') - packed_path = Path(readback) / file_name - if pack.returncode != 0 or not packed_path.is_file(): - raise SystemExit(f'Exact readback failed for {spec}.') - if packed_path.stat().st_size != row['bytes'] or hashlib.sha256(packed_path.read_bytes()).hexdigest() != row['sha256']: - raise SystemExit(f'Exact readback bytes mismatch for {spec}.') - - states = [] - for row in rows: - name = row['name'] - file_name = row['file'] - if not isinstance(name, str) or not re.fullmatch(r'@microsoft/[a-z0-9-]+', name): - raise SystemExit('cohort.json contains invalid package name.') - if row.get('version') != version: - raise SystemExit(f'cohort.json version mismatch for {name}.') - if not isinstance(file_name, str) or '/' in file_name: - raise SystemExit(f'cohort.json file is invalid for {name}.') - local_file = root / file_name - if (not local_file.is_file() or local_file.stat().st_size != row['bytes'] - or hashlib.sha256(local_file.read_bytes()).hexdigest() != row['sha256']): - raise SystemExit(f'Private writer tarball does not match the verified artifact for {name}.') - inv = inventory(name) - latest = inv['dist-tags']['latest'] - target_present = version in inv['versions'] - if target_present: - if latest != version: - raise SystemExit(f'Target version already exists but latest is {latest} for {name}.') - verify_exact_present(row) - states.append({'row': row, 'present': True}) - else: - states.append({'row': row, 'present': False}) - - for state in states: - row = state['row'] - name = row['name'] - file_name = row['file'] - spec = f'{name}@{version}' - if state['present']: - print(f'Exact latest version already present for {spec}; no publish needed.') - continue - - inv = inventory(name) - latest = inv['dist-tags']['latest'] - if version in inv['versions']: - if latest != version: - raise SystemExit(f'Recheck found existing {spec} but latest is {latest}; refusing write.') - verify_exact_present(row) - print(f'Recheck found exact latest version already present for {spec}; no publish needed.') - continue - - publish_result = None - publish_timeout = False - try: - publish_result = run_npm(['publish', f'./{file_name}', '--tag', 'latest'], write_root, 180) - except subprocess.TimeoutExpired: - publish_timeout = True - - post_inv = inventory(name) - if version not in post_inv['versions'] or post_inv['dist-tags']['latest'] != version: - state_desc = 'timeout' if publish_timeout else f'exit {publish_result.returncode}' - raise SystemExit(f'Publish lacked exact evidence for {spec} after {state_desc}.') - verify_exact_present(row) - if publish_timeout: - print(f'Publish timed out but exact latest evidence is confirmed for {spec}.') - elif publish_result.returncode == 0: - print(f'Published and verified exact latest {spec}.') - else: - print(f'Publish returned nonzero but exact latest evidence is confirmed for {spec}.') - - # Check the whole cohort's latest tags after writing. Exact versions are immutable, - # and the bytes were freshly read from this same feed above. - for row in rows: - name = row['name'] - if inventory(name)['dist-tags']['latest'] != version: - raise SystemExit(f'Final registry latest is not {version} for {name}.') - print(f'Azure Artifacts npm base feed confirmed all nine exact versions, artifact digests, and latest={version}.') - PY - displayName: Preflight, publish, and reconcile npm release cohort - workingDirectory: '$(NpmWriter)' + - bash: node scripts/ado-npm-publisher.cjs publish + displayName: Publish packages to Azure Artifacts npm feed + workingDirectory: '$(Build.Repository.LocalPath)' env: - BASH_ENV: /dev/null - DIR: '$(NpmWriter)' - REGISTRY: '$(NpmRegistry)' - RELEASE_VERSION: ${{ parameters.releaseVersion }} \ No newline at end of file + RELEASE_VERSION: ${{ parameters.releaseVersion }} + TARBALL_DIR: '$(TarballDir)' + NPM_REGISTRY: '$(NpmRegistry)' + PUBLISH_NPMRC: '$(PublishNpmrc)' \ No newline at end of file diff --git a/.azure-pipelines/npm-verify-release.steps.yml b/.azure-pipelines/npm-verify-release.steps.yml deleted file mode 100644 index 2817b45b2b5..00000000000 --- a/.azure-pipelines/npm-verify-release.steps.yml +++ /dev/null @@ -1,169 +0,0 @@ -parameters: - - name: releaseVersion - type: string - default: '' - - name: prepareWriter - type: boolean - default: false - -steps: - - bash: | - set -euo pipefail - python3 -I - <<'PY' - import base64 - import hashlib - import json - import os - import re - import stat - from pathlib import Path - - version = os.environ['RELEASE_VERSION'] - if len(version) > 40 or not re.fullmatch(r'(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)', version): - raise SystemExit('Invalid releaseVersion. Enter a stable version such as 5.1024.0 (without the v prefix).') - - hex40 = re.compile(r'[0-9a-f]{40}') - build_id = os.environ['BUILD_ID'] - recipe_sha = os.environ['RECIPE_SHA'].lower() - source_sha = os.environ['SOURCE_SHA'] - manifest_sha256 = os.environ['EXPECTED_MANIFEST_SHA256'] - if not re.fullmatch(r'[1-9]\d{0,14}', build_id) or not hex40.fullmatch(recipe_sha) or not hex40.fullmatch(source_sha): - raise SystemExit('Run identity is invalid.') - if not re.fullmatch(r'[0-9a-f]{64}', manifest_sha256): - raise SystemExit('Expected manifest digest is missing.') - - packages = [ - 'logic-apps-shared', - 'designer-ui', - 'designer-ui-v2', - 'logic-apps-chatbot', - 'logic-apps-designer', - 'logic-apps-designer-v2', - 'logic-apps-data-mapper', - 'logic-apps-data-mapper-v2', - 'vscode-extension-logic-apps', - ] - files = ['microsoft-%s-%s.tgz' % (name, version) for name in packages] - root = os.environ['ARTIFACT_DIR'] - if not stat.S_ISDIR(os.lstat(root).st_mode) or os.path.realpath(root) != os.path.abspath(root): - raise SystemExit('Artifact directory is not confined.') - - entries = os.listdir(root) - if '_manifest' in entries: - if not stat.S_ISDIR(os.lstat(os.path.join(root, '_manifest')).st_mode): - raise SystemExit('Reserved _manifest entry is not a directory.') - entries.remove('_manifest') - if sorted(entries) != sorted(files + ['publisher-artifact.json']): - raise SystemExit('Artifact must contain exactly the nine tarballs and the manifest.') - - nofollow = getattr(os, 'O_NOFOLLOW', 0) - nonblock = getattr(os, 'O_NONBLOCK', 0) - - def read_regular(name, limit): - path = os.path.join(root, name) - try: - fd = os.open(path, os.O_RDONLY | nofollow | nonblock) - except OSError: - raise SystemExit('Artifact entry is not a regular file: ' + name) - with os.fdopen(fd, 'rb') as handle: - if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode): - raise SystemExit('Artifact entry is not a regular file: ' + name) - data = handle.read(limit + 1) - if len(data) > limit: - raise SystemExit('Artifact entry is too large: ' + name) - return data - - manifest = read_regular('publisher-artifact.json', 128 * 1024) - if hashlib.sha256(manifest).hexdigest() != manifest_sha256: - raise SystemExit('Manifest digest does not match the producing job.') - - record = json.loads(manifest) - if not isinstance(record, dict) or sorted(record) != ['destination', 'packages', 'source']: - raise SystemExit('Manifest shape is invalid.') - - source = record['source'] - if not isinstance(source, dict): - raise SystemExit('Manifest shape is invalid.') - - expected_source = { - 'repository': 'Azure/LogicAppsUX', - 'releaseRef': 'refs/tags/v' + version, - 'verifiedSha': source_sha, - 'version': version, - 'buildId': build_id, - 'recipeSha': recipe_sha, - } - if source != expected_source: - raise SystemExit('Manifest provenance does not match this run, release tag, source SHA or recipe commit.') - - expected_destination = { - 'registry': 'https://msazure.pkgs.visualstudio.com/One/_packaging/microsoft-logic-apps/npm/registry/', - 'feedId': '44fc6edc-394a-403a-86cd-700a15978af1', - 'distTag': 'latest', - } - if record['destination'] != expected_destination: - raise SystemExit('Manifest destination is invalid.') - - writer_path = None - if os.environ['PREPARE_WRITER'] == 'true': - writer_dir = os.environ['WRITER_DIR'] - registry = os.environ['REGISTRY'] - if registry != 'https://pkgs.dev.azure.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/': - raise SystemExit('Writer registry must use the approved modern endpoint.') - if not os.path.isabs(writer_dir) or os.path.realpath(writer_dir) != os.path.abspath(writer_dir): - raise SystemExit('Writer directory is not confined.') - writer_path = Path(writer_dir) - writer_path.mkdir(mode=0o700, exist_ok=False) - - expected_packages = [] - for name, file in zip(packages, files): - data = read_regular(file, 64 * 1024 * 1024) - expected_packages.append( - { - 'name': '@microsoft/' + name, - 'version': version, - 'file': file, - 'integrity': 'sha512-' + base64.b64encode(hashlib.sha512(data).digest()).decode(), - 'sha256': hashlib.sha256(data).hexdigest(), - 'bytes': len(data), - } - ) - # Copy the same bytes just hashed; never reopen the downloaded file for publishing. - if writer_path is not None: - fd = os.open(writer_path / file, os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow, 0o400) - with os.fdopen(fd, 'wb') as handle: - handle.write(data) - - if record['packages'] != expected_packages: - raise SystemExit('Package identity or integrity mismatch.') - - if writer_path is not None: - cohort_path = writer_path / 'cohort.json' - fd = os.open(str(cohort_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow, 0o600) - with os.fdopen(fd, 'w', encoding='utf-8') as handle: - json.dump({'packages': expected_packages}, handle, separators=(',', ':')) - - npmrc_path = writer_path / '.npmrc' - fd = os.open(str(npmrc_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow, 0o600) - with os.fdopen(fd, 'w', encoding='utf-8') as handle: - handle.write('registry=' + registry + '\n') - - print('Verified nine packages for v%s at %s from build %s.' % (version, source_sha, build_id)) - print('##vso[task.setvariable variable=ArtifactVerified;isOutput=true]true') - PY - name: verification - displayName: Verify manifest digest, provenance and nine tarballs - env: - BASH_ENV: /dev/null - ARTIFACT_DIR: '$(ArtifactDir)' - RELEASE_VERSION: ${{ parameters.releaseVersion }} - BUILD_ID: '$(Build.BuildId)' - RECIPE_SHA: '$(Build.SourceVersion)' - SOURCE_SHA: '$(ExpectedSourceSha)' - EXPECTED_MANIFEST_SHA256: '$(ExpectedManifestSha256)' - ${{ if eq(parameters.prepareWriter, true) }}: - PREPARE_WRITER: 'true' - WRITER_DIR: '$(NpmWriter)' - REGISTRY: '$(NpmRegistry)' - ${{ if ne(parameters.prepareWriter, true) }}: - PREPARE_WRITER: 'false' diff --git a/scripts/ado-npm-publisher-artifact.cjs b/scripts/ado-npm-publisher-artifact.cjs deleted file mode 100644 index aff4ebe31a1..00000000000 --- a/scripts/ado-npm-publisher-artifact.cjs +++ /dev/null @@ -1,398 +0,0 @@ -const assert = require('node:assert/strict'); -const crypto = require('node:crypto'); -const fs = require('node:fs'); -const path = require('node:path'); -const { spawnSync } = require('node:child_process'); -const { gunzipSync } = require('node:zlib'); -const { - COHORT, DEPENDENCY_FIELDS, DESTINATION_FEED_ID, DESTINATION_REGISTRY, DIST_TAG, ENTRY_FIELDS, - MANIFEST_FILE_NAME, SOURCE_REPOSITORY, TEST_VERSION_PATTERN, assertNoRegistryOverride, assertSafeManifest, dependencyMap, fetchJson, isObject, normalizeSha, -} = require('./ado-npm-publisher-lib.cjs'); - -const FEED_URL = `https://feeds.dev.azure.com/msazure/One/_apis/packaging/feeds/${DESTINATION_FEED_ID}?api-version=7.1`; - -function resolveNpmRoot(execPath = process.execPath) { - const nodeDirectory = path.dirname(execPath); - const launcher = path.join(nodeDirectory, 'npm'); - const candidates = [ - ...(fs.existsSync(launcher) ? [path.dirname(path.dirname(fs.realpathSync(launcher)))] : []), - path.join(nodeDirectory, 'node_modules/npm'), - path.resolve(nodeDirectory, '../lib/node_modules/npm'), - ]; - // Resolve only the Node installation's npm, never PATH or the source checkout. - for (const root of candidates) { - if (!fs.existsSync(path.join(root, 'bin/npm-cli.js'))) continue; - try { - for (const dependency of ['tar', 'ini']) require.resolve(path.join(root, 'node_modules', dependency)); - return root; - } catch (error) { - if (error.code !== 'MODULE_NOT_FOUND') throw error; - } - } - throw new Error('Node installation is missing a supported npm CLI with bundled tar and ini modules.'); -} - -function isPackagePath(value) { - return typeof value === 'string' && !/[:\\\u0000-\u001f\u007f*]/.test(value) && - value.split('/').every(part => part && part !== '.' && part !== '..'); -} - -function readRegularFile(filename, limit) { - const fd = fs.openSync(filename, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK); - try { - const stat = fs.fstatSync(fd); - if (!stat.isFile() || stat.nlink !== 1 || stat.size > limit) throw new Error(`Not a bounded regular file: ${path.basename(filename)}.`); - return fs.readFileSync(fd); - } finally { - fs.closeSync(fd); - } -} - -function isPackageContent(name, directory) { - if (name.startsWith('package/build/lib/')) return !/(?:^|\/)(?:\.npmrc|node_modules)(?:\/|$)/i.test(name); - if (directory) return ['package', 'package/build', 'package/build/lib'].includes(name); - return /^package\/(?:package\.json|(?:readme|licen[cs]e|copying|notice|changelog|history)(?:\.[\w.-]+)?)$/i.test(name); -} - -function readTarball(buffer) { - // Use the trusted Node distribution's npm tar parser (same format as npm publish), never code from the artifact. - const tar = require(path.join(resolveNpmRoot(), 'node_modules/tar')); - const Parser = tar.Parser ?? tar.Parse; - const archive = gunzipSync(buffer, { maxOutputLength: 256 * 1024 * 1024 }); - const entries = new Map(); - const foldedFiles = new Set(); - const foldedDirectories = new Set(); - let ended = false; - const parser = new Parser({ - strict: true, - ondone() { ended = true; }, - }); - // The entry event is supported across npm's bundled tar versions, unlike the onentry option. - parser.on('entry', entry => { - const directory = entry.type === 'Directory'; - const name = directory ? entry.path.replace(/\/$/, '') : entry.path; - const foldedName = name.toLowerCase().normalize('NFC'); - if (foldedName === 'package/package.json' && name !== 'package/package.json') { - throw new Error('Noncanonical package manifest path.'); - } - if (!isPackagePath(name) || (name !== 'package' && !name.startsWith('package/')) || - foldedFiles.has(foldedName) || foldedDirectories.has(foldedName)) throw new Error('Invalid or duplicate tar entry path.'); - if (!directory && !['File', 'OldFile'].includes(entry.type)) throw new Error('Unexpected tar entry type.'); - if (!isPackageContent(name, directory)) throw new Error('Unexpected path outside the library package content.'); - // Case-insensitive consumers must not see files overwrite entries or become directories. - const parts = foldedName.split('/'); - if (parts.some((_, index) => foldedFiles.has(parts.slice(0, index).join('/'))) || - (!directory && [...foldedFiles, ...foldedDirectories].some(existing => existing.startsWith(`${foldedName}/`)))) { - throw new Error('Tar file conflicts with a directory ancestor.'); - } - if (directory) { - foldedDirectories.add(foldedName); - entries.set(name, null); - } else { - foldedFiles.add(foldedName); - entries.set(name, entry.size); - } - if (name === 'package/package.json') { - if (!entries.has(name) || entry.size > 256 * 1024) throw new Error('Invalid packed package.json.'); - const chunks = []; - entry.on('data', chunk => chunks.push(chunk)); - entry.on('end', () => entries.set(name, Buffer.concat(chunks))); - } - entry.resume(); - }); - parser.on('ignoredEntry', entry => { - if (!['ExtendedHeader', 'NextFileHasLongPath', 'OldExtendedHeader'].includes(entry.type)) { - throw new Error('Unsupported or ambiguous tar metadata entry.'); - } - }); - parser.end(archive); - if (!ended || archive.length % 512 !== 0 || !archive.subarray(-1024).every(byte => byte === 0) || - !Buffer.isBuffer(entries.get('package/package.json'))) throw new Error('Incomplete tar archive or missing package.json.'); - return entries; -} - -function requiredPaths(value, requireDot = false) { - if (typeof value === 'string') { - const entry = value.replace(/^\.\//, ''); - if (!isPackagePath(entry) || (requireDot && !value.startsWith('./'))) throw new Error('Invalid packed entrypoint path.'); - return [`package/${entry}`]; - } - if (requireDot && (isObject(value) || Array.isArray(value))) return Object.values(value).flatMap(item => requiredPaths(item, true)); - if (requireDot && value === null) return []; - throw new Error('Invalid packed entrypoint type.'); -} - -function validateEntrypoints(manifest, contract, entries, warnMissingCss) { - for (const field of ENTRY_FIELDS) { - assert.deepEqual(manifest[field], contract.entrypoints[field], `${manifest.name}: packed ${field} differs from source.`); - if (Object.hasOwn(manifest.publishConfig ?? {}, field)) { - assert.deepEqual(manifest.publishConfig[field], manifest[field], `${manifest.name}: publishConfig override mismatch.`); - } - if (manifest[field] !== undefined) { - for (const file of requiredPaths(manifest[field], field === 'exports')) { - if (entries.get(file)) continue; - const message = `${manifest.name} is missing required packed entry '${file}'.`; - // A valid CSS export may point to no file in a released archive. An empty file or directory is not absent. - if (warnMissingCss && field === 'exports' && file.endsWith('.css') && isPackageContent(file, false) && - !entries.has(file) && ![...entries.keys()].some(name => name.startsWith(`${file}/`))) { - warnMissingCss(message); - } else { - throw new Error(message); - } - } - } - } - if (!manifest.main || !manifest.types || !manifest.exports || - (manifest.name === '@microsoft/designer-ui-v2' && !Object.hasOwn(manifest.exports, './metrics')) || - (manifest.name === '@microsoft/logic-apps-designer-v2' && !entries.get('package/build/lib/_graph-layout/index.d.ts'))) { - throw new Error(`${manifest.name}: missing library entrypoints or graph declarations.`); - } -} - -function digest(buffer) { - return { - integrity: `sha512-${crypto.createHash('sha512').update(buffer).digest('base64')}`, - sha256: crypto.createHash('sha256').update(buffer).digest('hex'), - bytes: buffer.length, - }; -} - -function validateTarballArtifact(buffer, definition, version, contract, warnMissingCss) { - const entries = readTarball(buffer); - const manifest = JSON.parse(entries.get('package/package.json').toString('utf8')); - assertSafeManifest(manifest, definition.name); - if (TEST_VERSION_PATTERN.test(version)) { - assertNoRegistryOverride(manifest, definition.name); - } - assert.equal(manifest.version, version, `${definition.name}: packed version mismatch.`); - for (const field of DEPENDENCY_FIELDS) { - assert.deepEqual(dependencyMap(manifest, field), contract[field], `${definition.name}: packed ${field} differs from source.`); - } - validateEntrypoints(manifest, contract, entries, warnMissingCss); - return { name: definition.name, version, file: tarballName(definition, version), ...digest(buffer) }; -} - -function tarballName(definition, version) { - return `${definition.name.slice(1).replace('/', '-')}-${version}.tgz`; -} - -function expectedProvenance(verified) { - if (verified.kind === 'branch-e2e') { - return { - source: { - kind: verified.kind, repository: SOURCE_REPOSITORY, branchRef: verified.branchRef, - verifiedSha: verified.commitSha, buildId: verified.buildId, version: verified.version, - }, - destination: null, - }; - } - return { - source: { - repository: SOURCE_REPOSITORY, releaseRef: `refs/tags/${verified.releaseTag}`, - // Only the legacy REST-backed commands have a GitHub Release record to attest. - ...(verified.kind === 'release-tag' ? {} : { releaseId: verified.releaseId }), - verifiedSha: verified.commitSha, version: verified.version, - ...(verified.buildId === undefined ? {} : { buildId: verified.buildId, recipeSha: verified.recipeSha }), - }, - destination: { registry: DESTINATION_REGISTRY, feedId: DESTINATION_FEED_ID, distTag: DIST_TAG }, - }; -} - -function checkDirectory(dir, fileNames) { - if (!fs.lstatSync(dir).isDirectory() || path.resolve(dir) !== fs.realpathSync(dir)) throw new Error('Artifact directory is not confined.'); - assert.deepEqual(fs.readdirSync(dir).sort(), [...fileNames].sort(), 'Artifact must contain exactly the expected filenames.'); -} - -function validateArtifactFiles(dir, verified, contracts, { prepare = false, warnMissingCss } = {}) { - const version = verified.version; - const names = COHORT.map(item => tarballName(item, version)); - checkDirectory(dir, prepare ? names : [MANIFEST_FILE_NAME, ...names]); - const provenance = expectedProvenance(verified); - const record = prepare ? null : JSON.parse(readRegularFile(path.join(dir, MANIFEST_FILE_NAME), 128 * 1024).toString('utf8')); - if (!prepare) { - assert.deepEqual(record.source, provenance.source, 'Artifact source provenance mismatch.'); - assert.deepEqual(record.destination, provenance.destination, 'Artifact destination mismatch.'); - assert(Array.isArray(record.packages) && record.packages.length === COHORT.length, 'Artifact cohort size mismatch.'); - } - const packages = COHORT.map((definition, index) => { - // Never derive a filesystem path from the uploaded manifest. - const file = names[index]; - const buffer = readRegularFile(path.join(dir, file), 64 * 1024 * 1024); - const identity = { name: definition.name, version, file, ...digest(buffer) }; - if (!prepare) assert.deepEqual(record.packages[index], identity, 'Artifact identity or integrity mismatch.'); - return validateTarballArtifact(buffer, definition, version, contracts[definition.name], - prepare && verified.kind === 'release-tag' ? warnMissingCss : undefined); - }); - const artifact = { ...provenance, packages }; - if (prepare) fs.writeFileSync(path.join(dir, MANIFEST_FILE_NAME), `${JSON.stringify(artifact, null, 2)}\n`, { flag: 'wx' }); - return artifact; -} - -function readNpmAuthorization(npmrcPath) { - const scope = DESTINATION_REGISTRY.slice('https:'.length); - const parentScope = scope.replace(/registry\/$/, ''); - const ini = require(path.join(resolveNpmRoot(), 'node_modules/ini')); - const credentials = new Map(); - for (const line of readRegularFile(npmrcPath, 16 * 1024).toString('utf8').split(/\r?\n/).map(line => line.trim())) { - if (!line || /^[;#]/.test(line)) continue; - const values = Object.entries(ini.parse(line)); - if (values.length === 1 && ((values[0][0] === 'registry' && values[0][1] === DESTINATION_REGISTRY) || - (values[0][0] === 'always-auth' && values[0][1] === true))) continue; - const [key, value] = values[0] ?? []; - const match = /^(.*\/):(_authToken|_password|username|email)$/.exec(key ?? ''); - if (values.length !== 1 || !match || ![scope, parentScope].includes(match[1]) || credentials.has(key) || - typeof value !== 'string' || !value || /[\s$]/.test(value)) { - throw new Error('Unexpected or duplicate entry in dedicated npmrc.'); - } - credentials.set(key, value); - } - const authorizations = [scope, parentScope].map(prefix => { - const [token, password, username] = ['_authToken', '_password', 'username'].map(key => credentials.get(`${prefix}:${key}`)); - if (!token && !password && !username) return undefined; - if (token && !password && !username) return `Bearer ${token}`; - if (!token && username && !username.includes(':') && password && Buffer.from(password, 'base64').toString('base64') === password) { - return `Basic ${Buffer.concat([Buffer.from(`${username}:`), Buffer.from(password, 'base64')]).toString('base64')}`; - } - // npm selects complete credentials at one scope; never synthesize a split-scope pair. - throw new Error('Missing or ambiguous credentials for the exact registry scope.'); - }).filter(Boolean); - if (!authorizations.length) throw new Error('Missing credentials for the exact registry scope.'); - if (new Set(authorizations).size !== 1) throw new Error('Conflicting npm credential scopes.'); - return authorizations[0]; -} - -function npmRunner(npmrcPath, cwd, run = spawnSync) { - checkDirectory(cwd, []); - // With no project/user/global fallback and no inherited npm_config_* or NODE_OPTIONS. - const environment = { HOME: cwd, PATH: path.dirname(process.execPath) + ':/usr/bin:/bin' }; - const invoke = args => run(process.execPath, [path.join(resolveNpmRoot(), 'bin/npm-cli.js'), ...args, - '--prefix', cwd, '--userconfig', npmrcPath, '--globalconfig', '/dev/null', '--cache', path.join(cwd, 'cache'), - '--strict-ssl=true', '--fetch-retries=0', '--ignore-scripts', '--logs-max=0'], - { cwd, env: environment, encoding: 'utf8', timeout: 120_000 }); - // Deliberately omit --registry from this probe so it checks the actual configuration. - const registry = invoke(['config', 'get', 'registry']); - if (registry.status !== 0 || registry.stdout?.trim() !== DESTINATION_REGISTRY) throw new Error('Effective npm registry does not match the fixed feed.'); - return (tarball, distTag, dryRun = false) => invoke([ - 'publish', tarball, '--registry', DESTINATION_REGISTRY, '--tag', distTag, ...(dryRun ? ['--dry-run'] : []), - ]); -} - -async function authenticateFeed(token, fetchImpl) { - if (!token || !/^[A-Za-z0-9._~+/-]+=*$/.test(token)) throw new Error('Missing valid ADO job token for exact feed read.'); - const feed = await fetchJson(FEED_URL, fetchImpl, { authorization: `Bearer ${token}` }, 'Exact feed access check'); - if (feed?.id !== DESTINATION_FEED_ID || feed.name !== 'microsoft-logic-apps') throw new Error('ADO feed identity mismatch.'); -} - -function createRegistry(authorization, fetchImpl) { - return name => { - return fetchJson(`${DESTINATION_REGISTRY}${encodeURIComponent(name)}`, fetchImpl, - { authorization, 'cache-control': 'no-cache' }, 'Exact registry metadata'); - }; -} - -function isVersion(value) { - return typeof value === 'string' && /^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.+-]+)?$/.test(value) && value === value.trim(); -} - -async function readTagsAndVersions(registry, name) { - const doc = await registry(name); - if (doc?.name !== name || !isObject(doc.versions) || !isObject(doc['dist-tags']) || !Object.hasOwn(doc['dist-tags'], 'latest') || - Object.keys(doc.versions).length === 0 || Object.entries(doc.versions).some(([version, item]) => - !isVersion(version) || item?.name !== name || item?.version !== version) || - Object.values(doc['dist-tags']).some(version => !isVersion(version) || !Object.hasOwn(doc.versions, version))) { - throw new Error('Package metadata identity, version map or dist-tags are invalid.'); - } - return { tags: doc['dist-tags'], versions: doc.versions }; -} - -function compareStableVersions(left, right) { - const parse = value => { - if (typeof value !== 'string' || value.length > 100 || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value)) { - throw new Error('Cannot safely compare non-stable latest or release version.'); - } - return value.split('.').map(part => BigInt(part)); - }; - const a = parse(left); - const b = parse(right); - for (let i = 0; i < a.length; i++) { - if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; - } - return 0; -} - -function reconcileVersion(versions, entry) { - const metadata = versions[entry.version]; - const integrity = metadata?.dist?.integrity; - if (metadata?.name !== entry.name || metadata.version !== entry.version || - typeof integrity !== 'string' || !/^sha512-[A-Za-z0-9+/]{85}[AQgw]==$/.test(integrity)) { - return { status: 'unknown', reason: 'Missing exact identity or canonical SHA-512 registry integrity.' }; - } - if (integrity !== entry.integrity) return { status: 'conflict', reason: 'Existing integrity differs from the artifact.' }; - return { status: 'already-identical', reason: 'Exact identity and SHA-512 match.' }; -} - -function classifyPackageSnapshot(tags, versions, entry) { - if (compareStableVersions(tags.latest, entry.version) > 0) { - return { status: 'conflict', reason: 'Release is older than latest; backfill requires reconciliation.' }; - } - let newerStable; - for (const published of Object.keys(versions)) { - const stable = /^((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(published); - if (!stable || published === entry.version) continue; - const comparison = compareStableVersions(stable[1], entry.version); - if (comparison === 0) { - return { status: 'conflict', reason: `Existing stable version ${published} has ambiguous release precedence.` }; - } - if (comparison > 0) newerStable ??= published; - } - // Only a successful authenticated packument can supply absence evidence. Every HTTP 404 is unknown. - const state = Object.hasOwn(versions, entry.version) - ? reconcileVersion(versions, entry) - : { status: 'absent', reason: 'Version missing from successful package metadata.' }; - if (state.status === 'already-identical' && tags.latest !== entry.version) { - return { status: 'conflict', reason: 'Existing identical version is not latest; reconciliation is required.' }; - } - const warning = newerStable - ? `Newer stable version ${newerStable} exists outside latest; release order is unverified.` - : undefined; - return { ...state, latest: tags.latest, warning }; -} - -async function classifyPackageState(registry, entry) { - try { - const { tags, versions } = await readTagsAndVersions(registry, entry.name); - return classifyPackageSnapshot(tags, versions, entry); - } catch (error) { - return { status: 'unknown', reason: error.message }; - } -} - -async function publishPackage({ entry, registry, write }) { - let result; - try { - result = write(); - } catch { - // Spawn exceptions and timeouts are just as ambiguous as a server error. - } - const failed = reason => ({ status: 'failed', reason }); - try { - // Even a zero exit is not evidence that this feed retained the expected immutable bytes. - // Integrity and tags must describe the same observed registry state. - const { tags, versions } = await readTagsAndVersions(registry, entry.name); - if (tags.latest !== entry.version) return failed('Publication outcome unknown: latest does not point to the release version.'); - const state = classifyPackageSnapshot(tags, versions, entry); - if (state.status === 'conflict') return failed(`Publication conflict: ${state.reason}`); - if (state.status !== 'already-identical') return failed(`Publication outcome unknown: ${state.reason}`); - const outcome = result?.status === 0 - ? { status: 'published', reason: 'Publish completed and tags verified.' } - : { status: 'already-identical', reason: 'Exact version reconciled after a nonzero write result.' }; - return state.warning ? { ...outcome, warning: state.warning } : outcome; - } catch (error) { - return failed(`Publication outcome unknown: ${error.message}`); - } -} - -module.exports = { - authenticateFeed, classifyPackageState, createRegistry, digest, npmRunner, publishPackage, - readNpmAuthorization, readRegularFile, resolveNpmRoot, validateArtifactFiles, validateTarballArtifact, -}; diff --git a/scripts/ado-npm-publisher-lib.cjs b/scripts/ado-npm-publisher-lib.cjs deleted file mode 100644 index 832347c61df..00000000000 --- a/scripts/ado-npm-publisher-lib.cjs +++ /dev/null @@ -1,402 +0,0 @@ -const assert = require('node:assert/strict'); -const fs = require('node:fs'); -const { spawnSync } = require('node:child_process'); - -const SOURCE_REPOSITORY = 'Azure/LogicAppsUX'; -const SOURCE_API_BASE = `https://api.github.com/repos/${SOURCE_REPOSITORY}`; -const DESTINATION_REGISTRY = 'https://msazure.pkgs.visualstudio.com/One/_packaging/microsoft-logic-apps/npm/registry/'; -const DESTINATION_FEED_ID = '44fc6edc-394a-403a-86cd-700a15978af1'; -const DIST_TAG = 'latest'; -const MANIFEST_FILE_NAME = 'publisher-artifact.json'; -const PNPM_PIN = 'pnpm@9.1.3+sha512.7c2ea089e1a6af306409c4fc8c4f0897bdac32b772016196c469d9428f1fe2d5a21daf8ad6512762654ac645b5d9136bb210ec9a00afa8dbc4677843ba362ecd'; - -const COHORT = [ - { directory: 'libs/logic-apps-shared', name: '@microsoft/logic-apps-shared', runtimeDependencies: [] }, - { directory: 'libs/designer-ui', name: '@microsoft/designer-ui', runtimeDependencies: ['@microsoft/logic-apps-shared'] }, - { directory: 'libs/designer-ui-v2', name: '@microsoft/designer-ui-v2', runtimeDependencies: [] }, - { directory: 'libs/chatbot', name: '@microsoft/logic-apps-chatbot', runtimeDependencies: ['@microsoft/designer-ui', '@microsoft/logic-apps-shared'] }, - { directory: 'libs/designer', name: '@microsoft/logic-apps-designer', runtimeDependencies: ['@microsoft/designer-ui', '@microsoft/logic-apps-chatbot', '@microsoft/logic-apps-shared'] }, - { - directory: 'libs/designer-v2', - name: '@microsoft/logic-apps-designer-v2', - runtimeDependencies: ['@microsoft/designer-ui', '@microsoft/designer-ui-v2', '@microsoft/logic-apps-chatbot', '@microsoft/logic-apps-shared'], - }, - { - directory: 'libs/data-mapper', - name: '@microsoft/logic-apps-data-mapper', - runtimeDependencies: ['@microsoft/designer-ui', '@microsoft/logic-apps-designer', '@microsoft/logic-apps-shared'], - }, - { - directory: 'libs/data-mapper-v2', - name: '@microsoft/logic-apps-data-mapper-v2', - runtimeDependencies: ['@microsoft/designer-ui', '@microsoft/logic-apps-shared'], - }, - { - directory: 'libs/vscode-extension', - name: '@microsoft/vscode-extension-logic-apps', - runtimeDependencies: ['@microsoft/logic-apps-shared'], - }, -]; - -const COHORT_BY_NAME = new Map(COHORT.map(definition => [definition.name, definition])); -const EXCLUDED_PACKAGES = new Set(['@microsoft/logic-apps-chat', '@microsoft/logic-apps-graph-layout', 'btm-data-mapper']); -const ENTRY_FIELDS = ['main', 'module', 'types', 'typings', 'style', 'exports']; -const DEPENDENCY_FIELDS = ['dependencies', 'peerDependencies', 'optionalDependencies', 'peerDependenciesMeta']; -const TEST_BRANCH = 'refs/heads/krmitta/ado-npm-publish-pipeline'; -const TEST_VERSION_PATTERN = /^0\.0\.0-ado\.[1-9]\d{0,14}\.g[0-9a-f]{40}$/; - -function branchProvenance(env) { - assert.equal(env.SOURCE_REPOSITORY, SOURCE_REPOSITORY, 'Expected the LogicAppsUX GitHub repository.'); - assert.equal(env.SOURCE_BRANCH, TEST_BRANCH, 'Branch validation is limited to the designated test branch.'); - const commitSha = normalizeSha(env.EXPECTED_SHA); - assert.equal(normalizeSha(env.SOURCE_VERSION), commitSha, 'Azure Pipelines source version does not match the reviewed SHA.'); - const buildId = env.BUILD_ID; - assert(typeof buildId === 'string' && /^[1-9]\d{0,14}$/.test(buildId), 'Expected a positive Azure Pipelines build ID.'); - return { kind: 'branch-e2e', branchRef: TEST_BRANCH, commitSha, buildId, version: `0.0.0-ado.${buildId}.g${commitSha}` }; -} - -function parseReleaseRef(releaseRef) { - const match = /^refs\/tags\/v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(releaseRef ?? ''); - if (!match || match[0] !== releaseRef || match[0].length > 100) { - throw new Error('Invalid releaseRef. Expected refs/tags/v...'); - } - return { tag: `v${match[1]}.${match[2]}.${match[3]}`, version: `${match[1]}.${match[2]}.${match[3]}` }; -} - -function parseReleaseVersion(releaseVersion) { - const expected = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/; - if (typeof releaseVersion !== 'string' || releaseVersion.length > 40 || expected.exec(releaseVersion)?.[0] !== releaseVersion) { - throw new Error('Invalid releaseVersion. Enter a stable version such as 5.1024.0 (without the v prefix).'); - } - return releaseVersion; -} - -// The pipeline runs from a reviewed recipe ref; source is resolved from local tags in the checked-out repository. -function releaseRunSource(env) { - assert.equal(env.BUILD_REASON, 'Manual', 'Release builds must be queued manually.'); - assert.equal(env.SOURCE_REPOSITORY, SOURCE_REPOSITORY, 'Expected the LogicAppsUX GitHub repository.'); - const version = parseReleaseVersion(env.RELEASE_VERSION); - const releaseTag = `v${version}`; - const buildId = env.BUILD_ID; - assert(typeof buildId === 'string' && /^[1-9]\d{0,14}$/.test(buildId), 'Expected a positive Azure Pipelines build ID.'); - return { version, releaseTag, releaseRef: `refs/tags/${releaseTag}`, buildId, recipeSha: normalizeSha(env.RECIPE_SHA) }; -} - -function normalizeSha(input) { - const normalized = String(input ?? '').toLowerCase(); - if (normalized.length !== 40 || !/^[0-9a-f]{40}$/.test(normalized)) { - throw new Error('expectedSha must be a full 40-character hexadecimal commit SHA.'); - } - return normalized; -} - -async function fetchJson(url, fetchImpl = fetch, headers = {}, label = 'GitHub source read') { - let response; - try { - response = await fetchImpl(url, { - headers: { accept: 'application/json', 'user-agent': 'ado-additive-npm-publisher', ...headers }, - redirect: 'error', - signal: AbortSignal.timeout(30_000), - }); - } catch { - throw new Error(`${label}: network, redirect or timeout failure.`); - } - if (response.status !== 200 || response.redirected) { - throw new Error(`${label}: unexpected HTTP ${response.status}.`); - } - try { - return JSON.parse(await response.text()); - } catch { - throw new Error(`${label}: invalid JSON.`); - } -} - -async function verifyReleaseMetadata({ releaseRef, expectedSha, fetchImpl = fetch }) { - const normalizedExpectedSha = normalizeSha(expectedSha); - const verified = await resolveReleaseMetadata({ releaseRef, fetchImpl }); - if (verified.commitSha !== normalizedExpectedSha) { - throw new Error(`Tag commit SHA '${verified.commitSha}' does not match expectedSha '${normalizedExpectedSha}'.`); - } - return verified; -} - -// Only standard platform codes are reported; raw messages can carry URLs or headers. -const TRANSPORT_CODE = /^(?:E[A-Z]{2,15}|UND_ERR_[A-Z_]{2,30}|CERT_[A-Z_]{2,40}|ERR_TLS_[A-Z_]{2,40}|(?:UNABLE|SELF|DEPTH)_[A-Z_]{2,40})$/; - -function describeFetchFailure(error) { - if (error?.name === 'TimeoutError' || error?.name === 'AbortError') return 'timeout'; - const code = error?.cause?.code ?? error?.code; - return typeof code === 'string' && TRANSPORT_CODE.test(code) ? `transport failure (${code})` : 'transport failure'; -} - -// Uncredentialed GitHub release/tag/commit reads only (the feed keeps fetchJson). Each read is single-use: -// `connection: close` stops reuse of a pooled socket left idle across the long build, redirects are refused -// by numeric status, and failures never retry. -async function fetchReleaseJson(url, fetchImpl, accept = 'application/json', label = 'GitHub source read') { - let response; - try { - response = await fetchImpl(url, { - headers: { accept, 'user-agent': 'ado-additive-npm-publisher', connection: 'close' }, - redirect: 'manual', - signal: AbortSignal.timeout(30_000), - }); - } catch (error) { - throw new Error(`${label}: ${describeFetchFailure(error)}.`); - } - const status = Number.isInteger(response?.status) ? response.status : 0; - if (status === 0 || (status >= 300 && status < 400) || response.redirected) { - throw new Error(`${label}: refused redirect (HTTP ${status}).`); - } - if (status !== 200) throw new Error(`${label}: unexpected HTTP ${status}.`); - let body; - try { - body = await response.text(); - } catch (error) { - throw new Error(`${label}: ${describeFetchFailure(error)}.`); - } - try { - return JSON.parse(body); - } catch { - throw new Error(`${label}: invalid JSON.`); - } -} - -// Resolves an exact stable tag to its published GitHub Release and peeled commit. Release assets are never read. -async function resolveReleaseMetadata({ releaseRef, fetchImpl = fetch }) { - const { tag, version } = parseReleaseRef(releaseRef); - const release = await fetchReleaseJson(`${SOURCE_API_BASE}/releases/tags/${encodeURIComponent(tag)}`, fetchImpl, - 'application/vnd.github+json', 'GitHub release lookup'); - if (release?.tag_name !== tag || release.draft !== false || release.prerelease !== false || - !Number.isSafeInteger(release.id) || release.id <= 0 || !Number.isFinite(Date.parse(release.published_at))) { - throw new Error(`Release '${tag}' is not a verified published stable release.`); - } - - const tagRef = await fetchReleaseJson(`${SOURCE_API_BASE}/git/ref/tags/${encodeURIComponent(tag)}`, fetchImpl); - if (tagRef?.ref !== `refs/tags/${tag}`) { - throw new Error(`Release tag reference mismatch. Expected refs/tags/${tag}.`); - } - - let peeledCommitSha; - if (tagRef?.object?.type === 'commit') { - peeledCommitSha = normalizeSha(tagRef.object.sha); - } else if (tagRef?.object?.type === 'tag') { - const tagSha = normalizeSha(tagRef.object.sha); - const tagObject = await fetchReleaseJson(`${SOURCE_API_BASE}/git/tags/${tagSha}`, fetchImpl); - if (tagObject?.sha !== tagSha || tagObject?.tag !== tag || tagObject?.object?.type !== 'commit') { - throw new Error(`Annotated tag '${tag}' does not point to a commit.`); - } - peeledCommitSha = normalizeSha(tagObject.object.sha); - } else { - throw new Error(`Unsupported tag object type '${tagRef?.object?.type ?? 'unknown'}' for ${tag}.`); - } - - const commit = await fetchReleaseJson(`${SOURCE_API_BASE}/git/commits/${peeledCommitSha}`, fetchImpl); - if (commit?.sha !== peeledCommitSha) throw new Error('GitHub commit response does not match the peeled tag.'); - - return { - sourceRepository: SOURCE_REPOSITORY, - releaseTag: tag, - version, - commitSha: peeledCommitSha, - releaseId: release?.id, - releaseUrl: release?.html_url, - }; -} - -function runGit(args, cwd) { - const result = spawnSync('git', ['-c', 'core.hooksPath=/dev/null', ...args], { - encoding: 'utf8', - cwd, - timeout: 180_000, - env: { - PATH: process.env.PATH, - GIT_CONFIG_NOSYSTEM: '1', - GIT_CONFIG_GLOBAL: '/dev/null', - GIT_TERMINAL_PROMPT: '0', - // Source objects must already be present from the native checkout. - GIT_ALLOW_PROTOCOL: '', - GIT_NO_LAZY_FETCH: '1', - GIT_NO_REPLACE_OBJECTS: '1', - GIT_LFS_SKIP_SMUDGE: '1', - }, - }); - if (result.status !== 0) { - // Report the git subcommand, not leading `-c key=value` options. - const command = args.find((arg, index) => !arg.startsWith('-') && args[index - 1] !== '-c'); - throw new Error(`Git ${command} failed (exit ${result.status ?? 'unavailable'}).`); - } - return result.stdout; -} - -function resolveLocalReleaseTag(recipeRoot, releaseRef) { - const { tag } = parseReleaseRef(releaseRef); - let tagSha; - try { - // Match the ref by full name, without Git's revision-name fallback to branches. - tagSha = runGit(['show-ref', '--verify', '--hash', '--', releaseRef], recipeRoot).trim(); - } catch { - throw new Error(`Release tag '${tag}' is missing from the local checkout.`); - } - try { - return normalizeSha(runGit(['rev-parse', '--verify', `${normalizeSha(tagSha)}^{commit}`], recipeRoot).trim()); - } catch { - throw new Error(`Release tag '${tag}' must peel to a commit.`); - } -} - -function materializeDetachedSourceWorktree(recipeRoot, sourceRoot, commitSha) { - const sha = normalizeSha(commitSha); - fs.mkdirSync(sourceRoot); - // An owned, empty directory keeps the recipe checkout untouched. Snapshotting checks HEAD and cleanliness. - runGit(['-c', 'submodule.recurse=false', 'worktree', 'add', '--quiet', '--detach', sourceRoot, sha], recipeRoot); - return () => runGit(['worktree', 'remove', '--force', sourceRoot], recipeRoot); -} - -function restoreTrackedReleaseSource(sourceRoot, commitSha) { - // Restore the committed scanner inputs without removing dependencies and other untracked build outputs. - runGit(['restore', '--source', normalizeSha(commitSha), '--staged', '--worktree', '--no-recurse-submodules', '--', '.'], sourceRoot); - runGit(['diff', '--quiet', 'HEAD', '--', '.'], sourceRoot); -} - -function verifyCheckoutHead(sourceRoot, expectedSha) { - const head = runGit(['rev-parse', 'HEAD'], sourceRoot).trim().toLowerCase(); - if (head !== normalizeSha(expectedSha)) { - throw new Error(`Checked out commit '${head}' does not match expectedSha '${expectedSha}'.`); - } - return head; -} - -function verifyCleanCheckout(sourceRoot) { - if (runGit(['status', '--porcelain=v1', '--untracked-files=all'], sourceRoot)) { - throw new Error('Source checkout contains modified or untracked files.'); - } -} - -function isObject(value) { - return value !== null && typeof value === 'object' && !Array.isArray(value); -} - -function assertSafeManifest(manifest, packageName) { - if (!isObject(manifest) || manifest.name !== packageName || (manifest.private !== undefined && manifest.private !== false)) { - throw new Error(`Invalid identity or private package: ${packageName}.`); - } - const config = manifest.publishConfig === undefined ? {} : manifest.publishConfig; - if (!isObject(config) || Object.entries(config).some(([key, value]) => - !ENTRY_FIELDS.includes(key) && !(key === 'registry' && value === DESTINATION_REGISTRY))) { - throw new Error(`${packageName}: unexpected publishConfig.`); - } - if (!isObject(manifest.scripts ?? {}) || - Object.keys(manifest.scripts ?? {}).some(key => /^(?:(?:pre|post)?(?:install|pack|publish)|prepare|prepublishOnly|preprepare|postprepare)$/i.test(key))) { - throw new Error(`${packageName}: unexpected lifecycle hook.`); - } - if (Object.hasOwn(manifest, 'bundleDependencies') || Object.hasOwn(manifest, 'bundledDependencies')) { - throw new Error(`${packageName}: bundled dependencies are not supported.`); - } -} - -function assertNoRegistryOverride(manifest, name) { - assert(!Object.hasOwn(manifest.publishConfig ?? {}, 'registry'), `${name}: branch test artifacts cannot override the registry.`); -} - -function dependencyMap(manifest, field) { - const value = manifest[field]; - if (value === undefined) return {}; - if (!isObject(value)) throw new Error(`${manifest.name}: invalid ${field}.`); - return value; -} - -function assertExternalDependency(name, spec, owner) { - if (COHORT_BY_NAME.has(name) || EXCLUDED_PACKAGES.has(name) || - typeof spec !== 'string' || !spec || spec !== spec.trim() || - /^(?:workspace:|file:|link:|portal:|patch:|npm:|[.~][/\\]|[/\\]|[a-z]:[/\\])/i.test(spec)) { - throw new Error(`${owner}: unexpected external or local dependency '${name}'.`); - } -} - -function buildManifestContract(definition, manifest, version) { - assertSafeManifest(manifest, definition.name); - if (TEST_VERSION_PATTERN.test(version)) { - assertNoRegistryOverride(manifest, definition.name); - } - const dependencies = dependencyMap(manifest, 'dependencies'); - for (const name of definition.runtimeDependencies) { - assert.equal(dependencies[name], 'workspace:*', `${definition.name}: expected workspace:* for ${name}.`); - } - const contract = { - dependencies: { ...dependencies }, - optionalDependencies: dependencyMap(manifest, 'optionalDependencies'), - peerDependencies: dependencyMap(manifest, 'peerDependencies'), - peerDependenciesMeta: dependencyMap(manifest, 'peerDependenciesMeta'), - entrypoints: Object.fromEntries(ENTRY_FIELDS.map(field => [field, manifest.publishConfig?.[field] ?? manifest[field]]) - .filter(([, value]) => value !== undefined)), - }; - for (const field of DEPENDENCY_FIELDS.slice(0, 3)) { - for (const [name, spec] of Object.entries(contract[field])) { - if (field === 'dependencies' && definition.runtimeDependencies.includes(name)) contract[field][name] = version; - else assertExternalDependency(name, spec, definition.name); - } - } - return contract; -} - -function verifyBuildPrerequisites(turbo) { - // Turbo declares these dependencies on Designer v2's task, not the global build task. - const dependsOn = (turbo.tasks ?? turbo.pipeline)?.['@microsoft/logic-apps-designer-v2#build:lib']?.dependsOn; - for (const job of ['@microsoft/designer-ui-v2#build:lib', '@microsoft/logic-apps-graph-layout#build:lib']) { - assert(Array.isArray(dependsOn) && dependsOn.includes(job), `Missing Turbo prerequisite ${job}.`); - } -} - -function snapshotCheckout(sourceRoot, verified) { - const head = verifyCheckoutHead(sourceRoot, verified.commitSha); - verifyCleanCheckout(sourceRoot); - const read = file => JSON.parse(runGit(['show', `${head}:${file}`], sourceRoot)); - assert.equal(read('package.json').packageManager, PNPM_PIN, 'Source packageManager pin changed.'); - verifyBuildPrerequisites(read('turbo.json')); - return Object.fromEntries(COHORT.map(item => [ - item.name, buildManifestContract(item, read(`${item.directory}/package.json`), verified.version), - ])); -} - -async function readVerifiedContracts(verified, fetchImpl = fetch) { - const base = `https://raw.githubusercontent.com/${SOURCE_REPOSITORY}/${normalizeSha(verified.commitSha)}`; - const contracts = await Promise.all(COHORT.map(async item => { - const manifest = await fetchJson(`${base}/${item.directory}/package.json`, fetchImpl); - return [item.name, buildManifestContract(item, manifest, verified.version)]; - })); - return Object.fromEntries(contracts); -} - -module.exports = { - COHORT, - DEPENDENCY_FIELDS, - DESTINATION_FEED_ID, - DESTINATION_REGISTRY, - DIST_TAG, - ENTRY_FIELDS, - MANIFEST_FILE_NAME, - SOURCE_REPOSITORY, - TEST_VERSION_PATTERN, - assertNoRegistryOverride, - assertSafeManifest, - branchProvenance, - buildManifestContract, - dependencyMap, - fetchJson, - fetchReleaseJson, - isObject, - materializeDetachedSourceWorktree, - normalizeSha, - parseReleaseRef, - parseReleaseVersion, - readVerifiedContracts, - releaseRunSource, - resolveLocalReleaseTag, - resolveReleaseMetadata, - restoreTrackedReleaseSource, - snapshotCheckout, - verifyBuildPrerequisites, - verifyCheckoutHead, - verifyCleanCheckout, - verifyReleaseMetadata, -}; diff --git a/scripts/ado-npm-publisher-test-feed.cjs b/scripts/ado-npm-publisher-test-feed.cjs deleted file mode 100644 index 8f72bb53858..00000000000 --- a/scripts/ado-npm-publisher-test-feed.cjs +++ /dev/null @@ -1,332 +0,0 @@ -const path = require('node:path'); -const { isDeepStrictEqual } = require('node:util'); -const { COHORT, DESTINATION_FEED_ID, DESTINATION_REGISTRY, TEST_VERSION_PATTERN } = require('./ado-npm-publisher-lib.cjs'); -const { digest, readRegularFile, validateArtifactFiles } = require('./ado-npm-publisher-artifact.cjs'); - -const FIXTURE_PROTOCOL = 'logicappsux-isolated-test-feed/v1'; -const VERSION_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/; -const SHA512_PATTERN = /^sha512-[A-Za-z0-9+/]{85}[AQgw]==$/; -const MAX_INVENTORY_PAGES = 32; -const MAX_INVENTORY_EVENTS = 10_000; - -function normalizeRegistry(registry) { - let url; - try { - url = new URL(registry); - } catch { - throw new Error('Pinned registry must be a valid absolute URL.'); - } - if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) { - throw new Error('Pinned registry must be a clean https URL.'); - } - if (!url.pathname.endsWith('/')) { - throw new Error('Pinned registry must end with a trailing slash.'); - } - return url.toString(); -} - -function assertPinnedIsolatedIdentity(input) { - if (typeof input?.id !== 'string' || !input.id || typeof input?.name !== 'string' || !input.name) { - throw new Error('Pinned feed identity must include id and name.'); - } - const registry = normalizeRegistry(input.registry); - const host = new URL(registry).hostname.toLowerCase(); - if (!host.endsWith('.invalid')) { - throw new Error('Pinned feed registry must target a local-only .invalid host.'); - } - if (registry === DESTINATION_REGISTRY || input.id === DESTINATION_FEED_ID || input.name === 'microsoft-logic-apps') { - throw new Error('Pinned feed identity cannot target production.'); - } - return Object.freeze({ id: input.id, name: input.name, registry }); -} - -function assertIdentityMatch(expected, actual, source) { - const normalized = assertPinnedIsolatedIdentity(actual); - for (const field of ['id', 'name', 'registry']) { - if (normalized[field] !== expected[field]) { - throw new Error(`${source} identity mismatch for ${field}.`); - } - } -} - -function parseVersion(version, label, branch) { - if (typeof version !== 'string' || version.length > 256 || !(branch ? TEST_VERSION_PATTERN : VERSION_PATTERN).test(version)) { - throw new Error(`${label} must be a ${branch ? 'reserved branch test' : 'stable semver'} version.`); - } - if (branch) return [BigInt(version.split('.')[3])]; - const [major, minor, patch] = version.split(/[.+]/); - return [BigInt(major), BigInt(minor), BigInt(patch)]; -} - -function compareVersions(left, right, branch) { - const a = parseVersion(left, 'left version', branch); - const b = parseVersion(right, 'right version', branch); - for (let i = 0; i < a.length; i++) { - if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; - } - return 0; -} - -function normalizeInventoryEvent(event, branch) { - if (!event || typeof event !== 'object') throw new Error('Inventory event must be an object.'); - const { type, version } = event; - if (!['version', 'deleted', 'upstream'].includes(type)) throw new Error('Inventory event type is not supported.'); - parseVersion(version, 'Inventory event version', branch); - const normalized = { type, version }; - if (type === 'version') { - if (typeof event.integrity !== 'string' || !SHA512_PATTERN.test(event.integrity)) { - throw new Error('Inventory version event must include sha512 integrity.'); - } - normalized.integrity = event.integrity; - } - return normalized; -} - -async function readBoundedInventory(readPage, packageName, { maxInventoryPages: maxPages, maxInventoryEvents: maxEvents, branch }) { - const visited = new Set(); - const versions = new Map(); - const deleted = new Set(); - const upstream = new Set(); - let cursor = null; - let pageCount = 0; - let eventCount = 0; - let complete = false; - while (true) { - if (++pageCount > maxPages) throw new Error(`Inventory exceeded ${maxPages} pages for ${packageName}.`); - if (visited.has(cursor)) throw new Error(`Inventory cursor loop detected for ${packageName}.`); - visited.add(cursor); - const page = await readPage(packageName, cursor); - if (page?.protocol !== FIXTURE_PROTOCOL || page?.packageName !== packageName || !Array.isArray(page?.events)) { - throw new Error(`Inventory page does not match fixture protocol for ${packageName}.`); - } - for (const raw of page.events) { - if (++eventCount > maxEvents) throw new Error(`Inventory exceeded ${maxEvents} events for ${packageName}.`); - const event = normalizeInventoryEvent(raw, branch); - if (versions.has(event.version) || deleted.has(event.version) || upstream.has(event.version)) { - throw new Error(`Ambiguous inventory: duplicate version for ${packageName}.`); - } - if (event.type === 'version') versions.set(event.version, event.integrity); - if (event.type === 'deleted') deleted.add(event.version); - if (event.type === 'upstream') upstream.add(event.version); - } - const next = page.nextCursor; - if (next !== null && (typeof next !== 'string' || next.length === 0 || page.complete !== false)) { - throw new Error(`Inventory continuation is invalid for ${packageName}.`); - } - if (next === null) { - complete = page.complete === true; - break; - } - cursor = next; - } - if (!complete) throw new Error(`Inventory did not provide a complete terminal page for ${packageName}.`); - return { versions, deleted, upstream }; -} - -function normalizeMetadata(packageName, metadata, { maxInventoryEvents: maxVersions, branch, tagField }) { - if (metadata?.protocol !== FIXTURE_PROTOCOL || metadata?.packageName !== packageName || typeof metadata?.status !== 'number') { - throw new Error(`Package metadata does not match fixture protocol for ${packageName}.`); - } - if (metadata.status === 404 && metadata.versions === undefined && metadata.latest === undefined && metadata.testTag === undefined) { - return { status: 'not-found' }; - } - const taggedVersion = metadata[tagField]; - if (metadata.status !== 200 || !Array.isArray(metadata.versions) || metadata.versions.length > maxVersions || typeof taggedVersion !== 'string') { - return { status: 'unknown', reason: `Package metadata read failed with status ${metadata.status}.` }; - } - parseVersion(taggedVersion, 'Dist-tag version', branch); - const versions = new Map(); - for (const item of metadata.versions) { - if (!item || item.name !== packageName || typeof item.version !== 'string' || - typeof item.integrity !== 'string' || !SHA512_PATTERN.test(item.integrity) || versions.has(item.version)) { - return { status: 'unknown', reason: 'Package metadata contains invalid version entries.' }; - } - parseVersion(item.version, 'Package version', branch); - versions.set(item.version, item.integrity); - } - if (!versions.has(taggedVersion)) { - return { status: 'unknown', reason: 'Tagged version is missing from version entries.' }; - } - return { status: 'ok', taggedVersion, versions }; -} - -function classifyPackage(entry, metadata, inventory, branch) { - if (metadata.status === 'unknown') return metadata; - const compareToEntry = v => compareVersions(v, entry.version, branch); - const sameRelease = v => compareToEntry(v) === 0; - if ([...inventory.deleted, ...inventory.upstream].some(sameRelease)) { - return { status: 'conflict', reason: 'Release precedence collides with deleted or upstream inventory.' }; - } - // A brand-new name can return 404. Only the complete authenticated empty inventory makes it safe to proceed. - if (metadata.status === 'not-found') { - return inventory.versions.size === 0 && inventory.deleted.size === 0 && inventory.upstream.size === 0 - ? { status: 'absent', reason: 'Package is absent from complete authenticated inventory.' } - : { status: 'unknown', reason: 'npm 404 disagrees with authenticated package inventory.' }; - } - if ([...metadata.versions.keys(), ...inventory.versions.keys()].some(v => v !== entry.version && compareToEntry(v) >= 0)) { - return { status: 'conflict', reason: 'Inventory or metadata contains a newer or same-precedence release.' }; - } - // For fixture evidence, omission from one view isn't proof: both views must agree on every live record. - if (!isDeepStrictEqual(metadata.versions, inventory.versions)) { - return { status: 'unknown', reason: 'Metadata and inventory disagree on live versions or integrity.' }; - } - const metadataIntegrity = metadata.versions.get(entry.version); - if (!metadataIntegrity) { - return { status: 'absent', reason: 'Release version is absent from metadata and complete inventory.' }; - } - if (metadataIntegrity !== entry.integrity) { - return { status: 'conflict', reason: 'Existing release integrity differs from artifact bytes.' }; - } - if (metadata.taggedVersion !== entry.version) { - return { status: 'conflict', reason: 'Existing identical release does not match the selected dist-tag.' }; - } - return { status: 'already-identical', reason: 'Release identity and integrity match.' }; -} - -function assertResolvedUrl(entry, url, pinned) { - // Fixture protocol uses an exact canonical URL for each package. A prefix does not confine URL dot segments. - const expected = new URL(`${encodeURIComponent(entry.name)}/-/${entry.file}`, pinned.registry).href; - if (url !== expected) { - throw new Error(`Resolved URL does not match the pinned registry tarball for ${entry.name}@${entry.version}.`); - } -} - -function assertDownloadMatches(entry, download, pinned) { - if (download?.protocol !== FIXTURE_PROTOCOL || download?.status !== 200 || !Buffer.isBuffer(download?.bytes) || - typeof download?.resolvedUrl !== 'string' || typeof download?.integrity !== 'string') { - throw new Error(`Download payload is invalid for ${entry.name}@${entry.version}.`); - } - assertResolvedUrl(entry, download.resolvedUrl, pinned); - const actual = digest(download.bytes); - if (download.integrity !== entry.integrity || actual.integrity !== entry.integrity || actual.bytes !== entry.bytes || actual.sha256 !== entry.sha256) { - throw new Error(`Download bytes do not match artifact for ${entry.name}@${entry.version}.`); - } -} - -function assertConsumerResult(consumer, artifact, pinned) { - if (consumer?.protocol !== FIXTURE_PROTOCOL || consumer?.scriptsDisabled !== true || !Array.isArray(consumer?.entries)) { - throw new Error('Consumer verification did not use the fixture protocol with scripts disabled.'); - } - const byName = new Map(consumer.entries.map(entry => [entry?.name, entry])); - if (byName.size !== artifact.packages.length || consumer.entries.length !== byName.size) { - throw new Error('Consumer verification must return exactly one entry per cohort package.'); - } - for (const pkg of artifact.packages) { - const actual = byName.get(pkg.name); - if (!actual || actual.version !== pkg.version || actual.integrity !== pkg.integrity || typeof actual.resolvedUrl !== 'string') { - throw new Error(`Consumer entry mismatch for ${pkg.name}@${pkg.version}.`); - } - assertResolvedUrl(pkg, actual.resolvedUrl, pinned); - } -} - -async function classifyWithOperations(entry, operations, limits) { - const metadata = normalizeMetadata(entry.name, await operations.readPackageMetadata(entry.name), limits); - const inventory = await readBoundedInventory( - (name, cursor) => operations.readPackageInventoryPage(name, cursor), entry.name, limits - ); - return classifyPackage(entry, metadata, inventory, limits.branch); -} - -function readRetainedBytes(artifactRoot, entry) { - const buffer = readRegularFile(path.join(artifactRoot, entry.file), entry.bytes); - const actual = digest(buffer); - if (actual.bytes !== entry.bytes || actual.sha256 !== entry.sha256 || actual.integrity !== entry.integrity) { - throw new Error(`Retained bytes changed before simulated publication for ${entry.name}@${entry.version}.`); - } - return buffer; -} - -async function writeAndVerify(entry, artifactRoot, operations, limits, verifyDownload) { - const before = await classifyWithOperations(entry, operations, limits); - if (before.status !== 'absent') { - throw new Error(`Pre-publication recheck failed for ${entry.name}@${entry.version}: ${before.reason}`); - } - // Never retry an interrupted write in the same run. A replay rechecks the same artifact before writing. - await operations.writePackage(Object.freeze({ ...entry }), readRetainedBytes(artifactRoot, entry), limits.distTag); - const after = await classifyWithOperations(entry, operations, limits); - if (after.status !== 'already-identical') { - throw new Error(`Publication outcome unresolved for ${entry.name}@${entry.version}: ${after.reason}`); - } - await verifyDownload(entry); - return after; -} - -async function runIsolatedTestFeedPath(options) { - const { - artifactRoot, verified, contracts, pinnedFeed, readFeedIdentity, openFeedOperations, - mode = 'preflight', maxInventoryPages = MAX_INVENTORY_PAGES, maxInventoryEvents = MAX_INVENTORY_EVENTS, - } = options ?? {}; - if (!['preflight', 'publish', 'replay'].includes(mode)) throw new Error('Isolated test-feed mode must be preflight, publish or replay.'); - if (typeof readFeedIdentity !== 'function' || typeof openFeedOperations !== 'function') { - throw new Error('Isolated test-feed path requires injected feed adapter callbacks.'); - } - if (!Number.isInteger(maxInventoryPages) || maxInventoryPages < 1 || maxInventoryPages > MAX_INVENTORY_PAGES || - !Number.isInteger(maxInventoryEvents) || maxInventoryEvents < 1 || maxInventoryEvents > MAX_INVENTORY_EVENTS) { - throw new Error('Invalid fixture inventory limits.'); - } - - const pinned = assertPinnedIsolatedIdentity(pinnedFeed); - const branch = verified?.kind === 'branch-e2e'; - parseVersion(verified?.version, 'Artifact version', branch); - const artifact = validateArtifactFiles(artifactRoot, verified, contracts); - if (artifact.packages.length !== COHORT.length) throw new Error(`Expected ${COHORT.length} packages in artifact cohort.`); - assertIdentityMatch(pinned, await readFeedIdentity(pinned), 'Unauthenticated'); - const operations = await openFeedOperations(pinned); - const requiredOperations = ['readAuthenticatedFeedIdentity', 'readPackageMetadata', 'readPackageInventoryPage', 'downloadPackage', 'verifyConsumerInstall']; - if (mode === 'publish') requiredOperations.push('writePackage'); - if (requiredOperations.some(method => typeof operations?.[method] !== 'function')) { - throw new Error('Isolated test-feed fixture adapter is missing required operations.'); - } - assertIdentityMatch(pinned, await operations.readAuthenticatedFeedIdentity(pinned), 'Authenticated'); - - // Branch fixtures use only the reserved versions and never use the production "latest" tag. - const limits = { maxInventoryPages, maxInventoryEvents, branch, tagField: branch ? 'testTag' : 'latest', distTag: branch ? 'ado-e2e' : 'latest' }; - - const states = new Map(); - for (const entry of artifact.packages) { - const state = await classifyWithOperations(entry, operations, limits); - if (!['absent', 'already-identical'].includes(state.status)) { - throw new Error(`Preflight blocked for ${entry.name}@${entry.version}: ${state.reason}`); - } - states.set(entry.name, state); - } - if (mode === 'replay' && [...states.values()].some(state => state.status !== 'already-identical')) { - throw new Error('Read-only replay requires all nine versions to be present; zero writes.'); - } - - let writes = 0; - const verifyDownload = async entry => assertDownloadMatches(entry, await operations.downloadPackage(entry.name, entry.version), pinned); - for (const entry of artifact.packages) { - // Verify retained versions before a single missing version is written. - if (states.get(entry.name).status === 'already-identical') await verifyDownload(entry); - } - if (mode === 'publish') { - for (const entry of artifact.packages) { - if (states.get(entry.name).status !== 'absent') continue; - states.set(entry.name, await writeAndVerify(entry, artifactRoot, operations, limits, verifyDownload)); - writes++; - } - } - - if ([...states.values()].every(state => state.status === 'already-identical')) { - assertConsumerResult(await operations.verifyConsumerInstall({ - protocol: FIXTURE_PROTOCOL, - registry: pinned.registry, - scriptsDisabled: true, - packages: artifact.packages.map(item => ({ name: item.name, version: item.version })), - }), artifact, pinned); - } - - const summary = [...states.values()].reduce((counts, state) => { - counts[state.status] = (counts[state.status] ?? 0) + 1; - return counts; - }, { writes }); - return { summary, states: Object.fromEntries(states), protocol: FIXTURE_PROTOCOL }; -} - -module.exports = { - FIXTURE_PROTOCOL, - assertPinnedIsolatedIdentity, - runIsolatedTestFeedPath, -}; diff --git a/scripts/ado-npm-publisher.cjs b/scripts/ado-npm-publisher.cjs index 6c31611d31a..0e99cadb198 100644 --- a/scripts/ado-npm-publisher.cjs +++ b/scripts/ado-npm-publisher.cjs @@ -1,287 +1,270 @@ -const assert = require('node:assert/strict'); const { spawnSync } = require('node:child_process'); const { createHash } = require('node:crypto'); const fs = require('node:fs'); +const os = require('node:os'); const path = require('node:path'); -const { - COHORT, - branchProvenance, - buildManifestContract, - materializeDetachedSourceWorktree, - parseReleaseRef, - readVerifiedContracts, - releaseRunSource, - resolveLocalReleaseTag, - restoreTrackedReleaseSource, - snapshotCheckout, - verifyCheckoutHead, - verifyCleanCheckout, - verifyReleaseMetadata, -} = - require('./ado-npm-publisher-lib.cjs'); -const { authenticateFeed, classifyPackageState, createRegistry, npmRunner, publishPackage, readNpmAuthorization, validateArtifactFiles } = - require('./ado-npm-publisher-artifact.cjs'); - -function sanitizeAgentOutput(value) { - return String(value).replace(/#/g, '# '); -} -async function prepareArtifact(env, log) { - const snapshot = JSON.parse(fs.readFileSync(env.CONTRACT_FILE, 'utf8')); - verifyCheckoutHead(env.SOURCE_ROOT, snapshot.verified.commitSha); - const artifact = validateArtifactFiles(env.ARTIFACT_ROOT, snapshot.verified, snapshot.contracts, { prepare: true }); - log(`Validated ${artifact.packages.length} tarballs; feed authentication and publication were not attempted.`); -} +const DEFAULT_REGISTRY = 'https://pkgs.dev.azure.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/'; +const PNPM_MIRROR_BASE = 'https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry'; -function bootstrapBranchPnpm(sourceRoot, home, exec) { - // snapshotCheckout already checked this pin against the committed, reviewed manifest. - const { packageManager } = JSON.parse(fs.readFileSync(path.join(sourceRoot, 'package.json'), 'utf8')); - const pin = /^pnpm@(\d+\.\d+\.\d+)\+sha512\.([a-f0-9]{128})$/.exec(packageManager); - assert(pin, 'Expected pnpm with an exact version and SHA-512 pin.'); - const [, version, sha512] = pin; - const archive = path.join(home, 'pnpm.tgz'); - - // The lockfile mirror serves the tarball but not Corepack's version metadata endpoint. - const mirror = 'https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry'; - exec('curl', [ - '--disable', '--fail', '--silent', '--show-error', '--location', '--max-redirs', '1', - '--proto', '=https', '--proto-redir', '=https', '--max-time', '120', '--max-filesize', '10000000', - '--output', archive, `${mirror}/pnpm/-/pnpm-${version}.tgz`, - ]); - assert( - createHash('sha512').update(fs.readFileSync(archive)).digest('hex') === sha512, - 'Downloaded pnpm archive does not match the pinned SHA-512.' - ); - exec('tar', ['-xzf', archive, '-C', home]); - // Nested build scripts also invoke pnpm by name. - const pnpm = path.join(home, 'bin', 'pnpm'); - fs.symlinkSync(path.join(home, 'package', 'bin', 'pnpm.cjs'), pnpm); - return pnpm; +// Publishable workspace libraries in dependency order (matches scripts/update-versions.js). +const PACKAGES = [ + { directory: 'libs/logic-apps-shared', name: '@microsoft/logic-apps-shared' }, + { directory: 'libs/designer-ui', name: '@microsoft/designer-ui' }, + { directory: 'libs/designer-ui-v2', name: '@microsoft/designer-ui-v2' }, + { directory: 'libs/chatbot', name: '@microsoft/logic-apps-chatbot' }, + { directory: 'libs/designer', name: '@microsoft/logic-apps-designer' }, + { directory: 'libs/designer-v2', name: '@microsoft/logic-apps-designer-v2' }, + { directory: 'libs/data-mapper', name: '@microsoft/logic-apps-data-mapper' }, + { directory: 'libs/data-mapper-v2', name: '@microsoft/logic-apps-data-mapper-v2' }, + { directory: 'libs/vscode-extension', name: '@microsoft/vscode-extension-logic-apps' }, +]; + +function parseReleaseVersion(raw) { + const value = typeof raw === 'string' ? raw.trim() : ''; + if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value)) { + throw new Error(`Invalid releaseVersion '${value}'. Expected a version like 5.1024.0 (without the 'v' prefix).`); + } + return value; } -function buildCohort(env, snapshot, run = spawnSync, writeOutput = text => process.stdout.write(text), childEnv) { - const { verified } = snapshot; - if (verified.kind === 'branch-e2e') { - assert.deepEqual(verified, branchProvenance(env), 'Verified branch provenance mismatch.'); - } else { - assert.equal(verified.version, parseReleaseRef(`refs/tags/${verified.releaseTag}`).version, 'Verified release version mismatch.'); - } - const { version } = verified; - fs.mkdirSync(env.ARTIFACT_ROOT); - const exec = (command, args) => { - const result = run(command, args, { - cwd: env.SOURCE_ROOT, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', - timeout: 1_800_000, maxBuffer: 64 * 1024 * 1024, env: childEnv, - }); - // Source and dependency output must not become Azure Pipelines logging commands. - for (const output of [result.stdout, result.stderr]) { - if (output) writeOutput(sanitizeAgentOutput(output)); - } - if (result.error || result.status !== 0) { - throw new Error(`${command} failed: ${result.error?.message ?? `exit ${result.status ?? 'unavailable'}`}.`); - } - }; - const pnpmBin = childEnv && bootstrapBranchPnpm(env.SOURCE_ROOT, childEnv.HOME, exec); - const pnpm = args => (pnpmBin ? exec(pnpmBin, args) : exec('corepack', ['pnpm', ...args])); - pnpm(['install', '--recursive', '--frozen-lockfile', '--strict-peer-dependencies']); - exec(process.execPath, ['scripts/update-versions.js', version]); - // The source rewrite logs individual file failures, so verify all nine before building. - for (const item of COHORT) { - const manifest = JSON.parse(fs.readFileSync(path.join(env.SOURCE_ROOT, item.directory, 'package.json'), 'utf8')); - assert.equal(manifest.version, version, `${item.name}: version rewrite failed.`); - assert.deepEqual(buildManifestContract(item, manifest, version), snapshot.contracts[item.name], `${item.name}: source contract changed.`); - } - pnpm(['run', 'build:lib']); - for (const item of COHORT) { - pnpm(['--dir', path.join(env.SOURCE_ROOT, item.directory), 'pack', '--pack-destination', env.ARTIFACT_ROOT]); - } +function tarballName(packageName, version) { + return `${packageName.replace(/^@/, '').replace('/', '-')}-${version}.tgz`; } -function withSandboxedBuild(env, prefix, build) { - const home = fs.mkdtempSync(path.join(env.AGENT_TMP, prefix)); - try { - const bin = path.join(home, 'bin'); - fs.mkdirSync(bin); - // This limits credential inheritance, but is not an agent/job isolation boundary. - return build({ - PATH: `${bin}${path.delimiter}${env.PATH}`, - HOME: home, - CI: 'true', - HUSKY: '0', - GIT_CONFIG_NOSYSTEM: '1', - GIT_CONFIG_GLOBAL: '/dev/null', - GIT_TERMINAL_PROMPT: '0', - NPM_CONFIG_USERCONFIG: '/dev/null', - NPM_CONFIG_GLOBALCONFIG: path.join(home, 'global.npmrc'), - }); - } finally { - fs.rmSync(home, { force: true, recursive: true }); - } +function runCommand(command, args, options, run = spawnSync) { + const result = run(command, args, options); + if (result.error || result.status !== 0) { + const detail = result.error?.message ?? `exit ${result.status ?? 'unknown'}`; + const stderr = typeof result.stderr === 'string' && result.stderr.trim() ? `\n${result.stderr.trim()}` : ''; + throw new Error(`${command} ${args[0] ?? ''} failed (${detail}).${stderr}`.trim()); + } + return result; } -function buildBranchArtifact(env, log, run = spawnSync) { - const verified = branchProvenance(env); - const contracts = snapshotCheckout(env.SOURCE_ROOT, verified); - withSandboxedBuild(env, 'npm-branch-home-', childEnv => buildCohort(env, { verified, contracts }, run, undefined, childEnv)); - verifyCheckoutHead(env.SOURCE_ROOT, verified.commitSha); - const artifact = validateArtifactFiles(env.ARTIFACT_ROOT, verified, contracts, { prepare: true }); - log(`Validated ${artifact.packages.length} test tarballs at ${verified.version}; publication was not attempted.`); +function resolveReleaseTag(repoRoot, version, run = spawnSync) { + const tag = `v${version}`; + const ref = `refs/tags/${tag}`; + const gitOptions = { cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }; + + const showRef = run('git', ['show-ref', '--verify', '--hash', '--', ref], gitOptions); + if (showRef.error || showRef.status !== 0) { + throw new Error(`Release tag '${tag}' was not found in the local repository.`); + } + const tagSha = showRef.stdout.trim(); + + const revParse = run('git', ['rev-parse', '--verify', `${tagSha}^{commit}`], gitOptions); + if (revParse.error || revParse.status !== 0) { + throw new Error(`Release tag '${tag}' does not resolve to a commit.`); + } + return { tag, ref, commitSha: revParse.stdout.trim() }; } -// Release build from a local checked-out stable tag. The reviewed pipeline recipe remains on the pipeline ref, -// while the source tree is materialized in a detached worktree pinned to refs/tags/vX.Y.Z^{commit}. -// The options are code-level seams for local fixtures only; none is read from the environment. -async function buildReleaseArtifact(env, log, { run = spawnSync, sandbox = withSandboxedBuild, recipeRoot } = {}) { - const source = releaseRunSource(env); - const root = fs.realpathSync(recipeRoot ?? process.cwd()); - verifyCheckoutHead(root, source.recipeSha); - const commitSha = resolveLocalReleaseTag(root, source.releaseRef); - const verified = { ...source, kind: 'release-tag', commitSha }; - log(`Resolved ${source.releaseRef} to ${commitSha}; packing has not started.`); - const scanRoot = env.RELEASE_SCAN_ROOT; - assert(scanRoot === undefined || path.isAbsolute(scanRoot), 'Expected an absolute release scan root.'); - const sourceRoot = path.join(scanRoot === undefined ? env.AGENT_TMP : fs.realpathSync(scanRoot), 'release-source'); - const removeSource = materializeDetachedSourceWorktree(root, sourceRoot, verified.commitSha); - let retainForScan = false; - try { - const contracts = snapshotCheckout(sourceRoot, verified); - const buildEnv = { ...env, SOURCE_ROOT: sourceRoot }; - sandbox(env, 'npm-release-home-', childEnv => buildCohort(buildEnv, { verified, contracts }, run, undefined, childEnv)); - verifyCheckoutHead(sourceRoot, verified.commitSha); - const artifact = validateArtifactFiles(env.ARTIFACT_ROOT, verified, contracts, { - prepare: true, - warnMissingCss: warning => log(`Warning: ${sanitizeAgentOutput(warning)}`), - }); - log(`Packed and validated ${artifact.packages.length} release tarballs for ${verified.releaseTag} at ${verified.commitSha} (run ${verified.buildId}, recipe ${verified.recipeSha}); publication was not attempted.`); - if (scanRoot !== undefined) { - restoreTrackedReleaseSource(sourceRoot, verified.commitSha); - log(`Retaining tagged source ${verified.commitSha} for Component Governance at ${sanitizeAgentOutput(sourceRoot)}.`); - retainForScan = true; // The injected task runs after this step; workspace cleanup owns the tree. - } - return artifact; - } finally { - if (!retainForScan) { - removeSource(); - } +// 1ES Linux network isolation blocks Corepack from reaching registry.npmjs.org, +// so download the exact pnpm version declared in package.json from the 1ES mirror. +function bootstrapPnpm(sourceRoot, pnpmHome, run = spawnSync) { + const { packageManager } = JSON.parse(fs.readFileSync(path.join(sourceRoot, 'package.json'), 'utf8')); + const match = /^pnpm@(\d+\.\d+\.\d+)(?:\+sha512\.([a-f0-9]{128}))?$/.exec(packageManager ?? ''); + if (!match) { + throw new Error(`Unsupported packageManager '${packageManager ?? ''}' in package.json.`); + } + const [, pnpmVersion, expectedSha512] = match; + const archive = path.join(pnpmHome, `pnpm-${pnpmVersion}.tgz`); + const url = `${PNPM_MIRROR_BASE}/pnpm/-/pnpm-${pnpmVersion}.tgz`; + + runCommand( + 'curl', + ['--fail', '--silent', '--show-error', '--location', '--output', archive, url], + { cwd: pnpmHome, stdio: 'inherit', timeout: 120_000 }, + run + ); + + if (expectedSha512) { + const actualSha512 = createHash('sha512').update(fs.readFileSync(archive)).digest('hex'); + if (actualSha512 !== expectedSha512) { + throw new Error(`Downloaded pnpm@${pnpmVersion} archive SHA-512 does not match packageManager pin.`); } -} + } -async function verifyArtifact(env, fetchImpl) { - // Neither provenance nor the contract used by the privileged job comes from the tarballs. - const verified = await verifyReleaseMetadata({ releaseRef: env.RELEASE_REF, expectedSha: env.EXPECTED_SHA, fetchImpl }); - const contracts = await readVerifiedContracts(verified, fetchImpl); - return validateArtifactFiles(env.ARTIFACT_ROOT, verified, contracts); + runCommand('tar', ['-xzf', archive, '-C', pnpmHome], { cwd: pnpmHome, stdio: 'inherit', timeout: 60_000 }, run); + + const binDir = path.join(pnpmHome, 'bin'); + fs.mkdirSync(binDir, { recursive: true }); + const pnpmBin = path.join(binDir, 'pnpm'); + fs.symlinkSync(path.join(pnpmHome, 'package', 'bin', 'pnpm.cjs'), pnpmBin); + return { pnpmBin, binDir }; } -async function processCohort(artifact, registry, write, log) { - const distTag = artifact.destination.distTag; - if (distTag !== 'latest') throw new Error('Invalid publication tag; expected latest.'); - const results = []; - for (const entry of artifact.packages) { - results.push({ ...entry, ...await classifyPackageState(registry, entry) }); +function buildRelease(env, { run = spawnSync, log = console.log, repoRoot = process.cwd() } = {}) { + const version = parseReleaseVersion(env.RELEASE_VERSION); + const agentTmp = env.AGENT_TMP || os.tmpdir(); + const tarballDir = env.TARBALL_DIR || path.join(agentTmp, 'npm-tarballs'); + const registry = env.NPM_REGISTRY || DEFAULT_REGISTRY; + const npmrcPath = env.PUBLISH_NPMRC; + + const { tag, commitSha } = resolveReleaseTag(repoRoot, version, run); + log(`Resolved ${tag} to ${commitSha}.`); + + // Retain the release worktree under RELEASE_SCAN_ROOT (Agent.BuildDirectory) when set + // so 1ES Component Governance scans the released tag's lockfile and node_modules. + const scanRoot = env.RELEASE_SCAN_ROOT; + const sourceRoot = path.join(scanRoot || agentTmp, 'release-source'); + fs.rmSync(sourceRoot, { recursive: true, force: true }); + run('git', ['worktree', 'prune'], { cwd: repoRoot, stdio: 'ignore' }); + runCommand('git', ['worktree', 'add', '--quiet', '--detach', sourceRoot, commitSha], { cwd: repoRoot, stdio: 'inherit' }, run); + + const pnpmHome = fs.mkdtempSync(path.join(agentTmp, 'pnpm-bootstrap-')); + let retainForScan = false; + + try { + const { pnpmBin, binDir } = bootstrapPnpm(sourceRoot, pnpmHome, run); + const buildEnv = { + ...env, + PATH: `${binDir}${path.delimiter}${env.PATH ?? process.env.PATH ?? ''}`, + HOME: pnpmHome, + CI: 'true', + HUSKY: '0', + NPM_CONFIG_USERCONFIG: '/dev/null', + }; + const execOptions = { cwd: sourceRoot, env: buildEnv, stdio: 'inherit', timeout: 1_800_000 }; + + runCommand(pnpmBin, ['install', '--recursive', '--frozen-lockfile', '--strict-peer-dependencies'], execOptions, run); + runCommand(process.execPath, ['scripts/update-versions.js', version], execOptions, run); + runCommand(pnpmBin, ['run', 'build:lib'], execOptions, run); + + fs.rmSync(tarballDir, { recursive: true, force: true }); + fs.mkdirSync(tarballDir, { recursive: true }); + + // Pack via pnpm so workspace:* references and publishConfig fields are rewritten into each tarball. + for (const pkg of PACKAGES) { + runCommand(pnpmBin, ['--dir', path.join(sourceRoot, pkg.directory), 'pack', '--pack-destination', tarballDir], execOptions, run); + const expectedTarball = path.join(tarballDir, tarballName(pkg.name, version)); + if (!fs.existsSync(expectedTarball)) { + throw new Error(`Expected packed tarball was not created: ${expectedTarball}`); + } } - const report = () => results.forEach(result => log(`${result.name}@${result.version} ${result.integrity}: ${result.status} (${result.reason})${result.warning ? ` Warning: ${result.warning}` : ''}`)); - if (results.some(result => ['unknown', 'conflict'].includes(result.status))) { - report(); - throw new Error('Preflight blocked; zero package writes.'); + + if (npmrcPath) { + fs.mkdirSync(path.dirname(npmrcPath), { recursive: true, mode: 0o700 }); + fs.writeFileSync(npmrcPath, `registry=${registry}\n`, { mode: 0o600 }); } - let stopped = false; - if (write) { - for (const result of results.filter(item => item.status === 'absent')) { - let outcome = { status: 'not-attempted', reason: 'Blocked by earlier unresolved write.' }; - if (!stopped) { - // This narrows the race window but cannot serialize independent writers. - const current = await classifyPackageState(registry, result); - if (current.warning) result.warning = current.warning; - if (current.status === 'absent') { - outcome = await publishPackage({ entry: result, registry, write: () => write(result.file, distTag) }); - } else if (current.status === 'already-identical') { - outcome = current; - } else { - outcome = { status: 'failed', reason: `Pre-publication check blocked: ${current.reason}` }; - } - } - Object.assign(result, outcome); - stopped ||= result.status === 'failed'; - } + + log(`Built and packed ${PACKAGES.length} packages for v${version} into ${tarballDir}.`); + + if (scanRoot) { + runCommand('git', ['restore', '--source', commitSha, '--staged', '--worktree', '--', '.'], { cwd: sourceRoot, stdio: 'inherit' }, run); + retainForScan = true; } - report(); - if (stopped) throw new Error('Publication stopped. Retain and reconcile this exact pipeline artifact before retrying.'); -} -function dryRunCohort(artifact, artifactRoot, npm, log) { - for (const entry of artifact.packages) { - const result = npm(path.join(artifactRoot, entry.file), 'latest', true); - if (result.error || result.status !== 0) { - throw new Error(`npm dry run failed for ${entry.name}@${entry.version}: ${result.error?.message ?? `exit ${result.status ?? 'unavailable'}`}.`); - } - log(`npm dry run succeeded for ${entry.name}@${entry.version}; no package was published.`); + return { version, tag, commitSha, tarballDir }; + } finally { + fs.rmSync(pnpmHome, { recursive: true, force: true }); + if (!retainForScan) { + run('git', ['worktree', 'remove', '--force', sourceRoot], { cwd: repoRoot, stdio: 'ignore' }); + fs.rmSync(sourceRoot, { recursive: true, force: true }); } + } } -async function main([command, ...args] = process.argv.slice(2), env = process.env, fetchImpl = fetch, log = console.log) { - const writeLog = log; - log = message => writeLog(sanitizeAgentOutput(message)); - if (args.length) throw new Error('Publisher commands only accept inputs from their environment.'); - if (command === 'isolated-test-feed') { - throw new Error('Isolated test-feed attempts are fixture-only and are rejected before environment, provenance, or network reads.'); - } - if (command === 'build-branch-artifact') return buildBranchArtifact(env, log); - if (command === 'build-release-artifact') { - await buildReleaseArtifact(env, log); - return; - } - if (command === 'prepare-artifact') return prepareArtifact(env, log); - if (command === 'build-cohort') { - const snapshot = JSON.parse(fs.readFileSync(env.CONTRACT_FILE, 'utf8')); - verifyCheckoutHead(env.SOURCE_ROOT, snapshot.verified.commitSha); - verifyCleanCheckout(env.SOURCE_ROOT); - buildCohort(env, snapshot); - return; - } - if (command === 'verify-source') { - const verified = await verifyReleaseMetadata({ releaseRef: env.RELEASE_REF, expectedSha: env.EXPECTED_SHA, fetchImpl }); - fs.writeFileSync(env.PROVENANCE_FILE, JSON.stringify(verified), { flag: 'wx', mode: 0o600 }); - log(`Verified ${verified.releaseTag} at ${verified.commitSha} before checkout.`); - return; - } - if (command === 'snapshot-source') { - const previous = JSON.parse(fs.readFileSync(env.PROVENANCE_FILE, 'utf8')); - const verified = await verifyReleaseMetadata({ releaseRef: env.RELEASE_REF, expectedSha: env.EXPECTED_SHA, fetchImpl }); - for (const field of ['releaseTag', 'version', 'commitSha', 'releaseId']) { - assert.equal(previous[field], verified[field], 'Release metadata changed during checkout.'); - } - const contracts = snapshotCheckout(env.SOURCE_ROOT, verified); - fs.writeFileSync(env.CONTRACT_FILE, JSON.stringify({ verified, contracts }), { flag: 'wx', mode: 0o600 }); - log(`Verified ${verified.releaseTag} at ${verified.commitSha}; snapshotted ${COHORT.length} source manifests before lifecycle execution.`); - return; +function isVersionInFeed(packageName, version, { registry, npmrc, cwd, run = spawnSync }) { + const spec = `${packageName}@${version}`; + const result = run( + 'npm', + ['view', spec, 'version', '--registry', registry, '--userconfig', npmrc, '--prefer-online'], + { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 60_000 } + ); + + if (result.error) { + throw new Error(`Failed to check ${spec} in feed: ${result.error.message}`); + } + if (result.status === 0) { + // When the package exists in the feed but the requested version does not, npm view exits 0 with empty stdout. + return (result.stdout ?? '').trim() === version; + } + + const combined = `${result.stdout ?? ''}\n${result.stderr ?? ''}`; + if (/\bE404\b|404 Not Found|is not in this registry/i.test(combined)) { + return false; + } + throw new Error(`Failed to check ${spec} in feed (exit ${result.status}): ${combined.trim()}`); +} + +function publishRelease(env, { run = spawnSync, log = console.log } = {}) { + const version = parseReleaseVersion(env.RELEASE_VERSION); + const tarballDir = env.TARBALL_DIR; + const npmrc = env.PUBLISH_NPMRC; + const registry = env.NPM_REGISTRY || DEFAULT_REGISTRY; + + if (!tarballDir || !fs.existsSync(tarballDir)) { + throw new Error(`Tarball directory does not exist: ${tarballDir ?? '(unset)'}`); + } + if (!npmrc || !fs.existsSync(npmrc)) { + throw new Error(`Authenticated .npmrc file does not exist: ${npmrc ?? '(unset)'}`); + } + + let published = 0; + let skipped = 0; + + for (const pkg of PACKAGES) { + const spec = `${pkg.name}@${version}`; + const tarball = path.join(tarballDir, tarballName(pkg.name, version)); + if (!fs.existsSync(tarball)) { + throw new Error(`Missing tarball for ${spec}: ${tarball}`); } - if (command === 'validate-artifact') { - const artifact = await verifyArtifact(env, fetchImpl); - log(`Validated artifact provenance and ${artifact.packages.length} tarballs.`); - return; + + if (isVersionInFeed(pkg.name, version, { registry, npmrc, cwd: tarballDir, run })) { + log(`Skipping ${spec} (already exists in feed).`); + skipped += 1; + continue; } - if (command !== 'feed') throw new Error('Unknown publisher command.'); - - const mode = env.PUBLISHER_MODE; - if (!['publish', 'preflight', 'dry-run'].includes(mode)) throw new Error('Invalid publisher mode.'); - // Independent writers can race between preflight and publish; keep this stop until their coordination is verified. - if (mode === 'publish') throw new Error('Publication blocked: public-source controls and Azure Artifacts publication behavior have not been verified.'); - const artifact = await verifyArtifact(env, fetchImpl); - const authorization = readNpmAuthorization(env.PUBLISH_NPMRC); - const npm = npmRunner(env.PUBLISH_NPMRC, env.NPM_CWD); - log(`${mode} ${artifact.source.releaseRef} ${artifact.source.verifiedSha} ${artifact.destination.registry} tag=${artifact.destination.distTag}`); - await authenticateFeed(env.ADO_FEED_TOKEN, fetchImpl); - const registry = createRegistry(authorization, fetchImpl); - await processCohort(artifact, registry, undefined, log); - if (mode === 'dry-run') dryRunCohort(artifact, env.ARTIFACT_ROOT, npm, log); + + log(`Publishing ${spec}...`); + runCommand( + 'npm', + ['publish', tarball, '--tag', 'latest', '--registry', registry, '--userconfig', npmrc], + { cwd: tarballDir, stdio: 'inherit', timeout: 180_000 }, + run + ); + log(`Published ${spec}.`); + published += 1; + } + + log(`Publish complete for ${version}: ${published} published, ${skipped} skipped.`); + return { version, published, skipped }; +} + +function main([command, ...rest] = process.argv.slice(2), env = process.env, options = {}) { + if (rest.length > 0) { + throw new Error('Unexpected arguments. Usage: node scripts/ado-npm-publisher.cjs '); + } + if (command === 'build') { + return buildRelease(env, options); + } + if (command === 'publish') { + return publishRelease(env, options); + } + throw new Error(`Unknown command '${command ?? ''}'. Expected 'build' or 'publish'.`); } if (require.main === module) { - main().catch(error => { - console.error(sanitizeAgentOutput(error.message)); - process.exitCode = 1; - }); + try { + main(); + } catch (error) { + console.error(error.message); + process.exitCode = 1; + } } -module.exports = { buildBranchArtifact, buildCohort, buildReleaseArtifact, dryRunCohort, main, prepareArtifact, processCohort, sanitizeAgentOutput }; +module.exports = { + DEFAULT_REGISTRY, + PACKAGES, + PNPM_MIRROR_BASE, + bootstrapPnpm, + buildRelease, + isVersionInFeed, + main, + parseReleaseVersion, + publishRelease, + resolveReleaseTag, + tarballName, +}; diff --git a/scripts/ado-npm-publisher.test.cjs b/scripts/ado-npm-publisher.test.cjs index 432874e9dbc..f7b5421d5e6 100644 --- a/scripts/ado-npm-publisher.test.cjs +++ b/scripts/ado-npm-publisher.test.cjs @@ -1,1612 +1,379 @@ const assert = require('node:assert/strict'); -const fs = require('node:fs'); -const path = require('node:path'); const { spawnSync } = require('node:child_process'); -const crypto = require('node:crypto'); +const { createHash, randomUUID } = require('node:crypto'); +const fs = require('node:fs'); const os = require('node:os'); -const { randomUUID } = crypto; -const { gzipSync } = require('node:zlib'); +const path = require('node:path'); const { afterEach, test } = require('node:test'); const { - COHORT, - DESTINATION_FEED_ID, - DESTINATION_REGISTRY, - MANIFEST_FILE_NAME, - branchProvenance, - buildManifestContract, - fetchReleaseJson, - parseReleaseRef, - parseReleaseVersion, - releaseRunSource, - resolveReleaseMetadata, - verifyBuildPrerequisites, - verifyCleanCheckout, - verifyReleaseMetadata, -} = require('./ado-npm-publisher-lib.cjs'); -const { authenticateFeed, classifyPackageState, createRegistry, digest, npmRunner, publishPackage, readNpmAuthorization, resolveNpmRoot, validateArtifactFiles, validateTarballArtifact } = - require('./ado-npm-publisher-artifact.cjs'); -const { buildCohort, buildReleaseArtifact, dryRunCohort, main, prepareArtifact, processCohort, sanitizeAgentOutput } = require('./ado-npm-publisher.cjs'); -const { FIXTURE_PROTOCOL, assertPinnedIsolatedIdentity, runIsolatedTestFeedPath } = require('./ado-npm-publisher-test-feed.cjs'); - -const releaseRef = 'refs/tags/v5.1022.0'; -const commitSha = '6b2a7a7344e1165cda3d5db490c748446051b45f'; -const version = '5.1022.0'; -const previousVersion = '5.1021.0'; -const distTag = 'latest'; -const verified = { releaseTag: 'v5.1022.0', releaseId: 7, commitSha, version }; -const branchEnv = { - SOURCE_REPOSITORY: 'Azure/LogicAppsUX', - SOURCE_BRANCH: 'refs/heads/krmitta/ado-npm-publish-pipeline', - SOURCE_VERSION: commitSha, - EXPECTED_SHA: commitSha, - BUILD_ID: '192333967', -}; -const roots = []; -const workspace = () => { - const root = path.join(fs.realpathSync('scripts'), `.publisher-test-${randomUUID()}`); - fs.mkdirSync(root); - roots.push(root); - return root; -}; -afterEach(() => roots.splice(0).forEach(root => fs.rmSync(root, { force: true, recursive: true }))); - -function tar(entries) { - const chunks = []; - for (const [file, text, { type = '0', prefix = '', corrupt = false } = {}] of entries) { - const content = Buffer.from(text); - const header = Buffer.alloc(512); - header.write(file, 0, 100); - header.write('0000644\0', 100); - header.write(`${content.length.toString(8).padStart(11, '0')}\0`, 124); - header.fill(' ', 148, 156); - header.write(type, 156); - if (type === '2') header.write('target', 157); - header.write('ustar\0' + '00', 257); - header.write(prefix, 345, 155); - const checksum = header.reduce((sum, byte) => sum + byte, 0); - header.write(`${(checksum + Number(corrupt)).toString(8).padStart(6, '0')}\0 `, 148); - chunks.push(header, content, Buffer.alloc((512 - (content.length % 512)) % 512)); - } - return gzipSync(Buffer.concat([...chunks, Buffer.alloc(1024)])); -} - -function fixture(definition, artifactVersion = version) { - const source = { name: definition.name, - dependencies: { react: '^18.2.0', ...Object.fromEntries(definition.runtimeDependencies.map(name => [name, 'workspace:*'])) }, - peerDependencies: { '@fluentui/react': '^8.0.0' }, - publishConfig: { main: 'build/lib/index.js', module: 'build/lib/index.js', types: 'build/lib/index.d.ts', - exports: { '.': './build/lib/index.js', './index.css': './build/lib/index.css' } } }; - if (definition.directory === 'libs/designer-ui-v2') source.publishConfig.exports['./metrics'] = './build/lib/metrics.js'; - const contract = buildManifestContract(definition, source, artifactVersion); - const packed = { name: definition.name, version: artifactVersion, ...source.publishConfig, dependencies: contract.dependencies, peerDependencies: contract.peerDependencies }; - const content = [ - ['index.js', 'export {};', { prefix: 'package/build/lib' }], - ['package/build/lib/index.d.ts', 'export {};'], - ['package/build/lib/index.css', 'div {}'], - ['package/build/lib/metrics.js', 'export {};'], - ['package/build/lib/_graph-layout/index.d.ts', 'export {};'], - ]; - const pack = (manifest = packed, files = content) => tar([['package/package.json', JSON.stringify(manifest)], ...files]); - return { source, contract, packed, content, pack }; -} - -function artifactFixture(provenance = verified) { - const dir = workspace(); - const contracts = Object.fromEntries(COHORT.map(item => { - const { pack, contract } = fixture(item, provenance.version); - const filename = `${item.name.slice(1).replace('/', '-')}-${provenance.version}.tgz`; - fs.writeFileSync(path.join(dir, filename), pack()); - return [item.name, contract]; - })); - return { dir, contracts, record: validateArtifactFiles(dir, provenance, contracts, { prepare: true }) }; -} - -function isolatedFeedFixture({ missing = new Set(), empty = false, upstream = new Set(), provenance = verified } = {}) { - const pinnedFeed = { id: 'logicappsux-npm-e2e.invalid', name: 'logicappsux-npm-e2e', registry: 'https://logicappsux-feed.invalid/npm/registry/' }; - const state = new Map(); - const writes = []; - const stored = new Map(); - const { dir, contracts, record } = artifactFixture(provenance); - const branch = provenance.kind === 'branch-e2e'; - const tagField = branch ? 'testTag' : 'latest'; - for (const pkg of record.packages) { - if (empty) continue; - if (missing.has(pkg.name)) { - const previousIntegrity = digest(Buffer.from(`${pkg.name}@${previousVersion}`)).integrity; - state.set(pkg.name, { latest: previousVersion, versions: new Map([[previousVersion, previousIntegrity]]) }); - } else { - state.set(pkg.name, { latest: pkg.version, versions: new Map([[pkg.version, pkg.integrity]]) }); - stored.set(pkg.name, fs.readFileSync(path.join(dir, pkg.file))); - } - } - const metadata = name => { - if (!state.has(name)) { - return { - protocol: FIXTURE_PROTOCOL, - packageName: name, - status: 404, - }; - } - const snapshot = state.get(name); - return { - protocol: FIXTURE_PROTOCOL, - packageName: name, - status: 200, - [tagField]: snapshot.latest, - versions: [...snapshot.versions.entries()].map(([pkgVersion, integrity]) => ({ name, version: pkgVersion, integrity })), - }; - }; - const inventory = name => { - const snapshot = state.get(name); - const events = []; - if (snapshot) { - for (const [pkgVersion, integrity] of snapshot.versions.entries()) { - events.push({ type: 'version', version: pkgVersion, integrity }); - } - } - if (upstream.has(name)) events.push({ type: 'upstream', version: provenance.version }); - return [ - { protocol: FIXTURE_PROTOCOL, packageName: name, events: events.slice(0, 1), nextCursor: events.length > 1 ? 'next' : null, complete: events.length <= 1 }, - { protocol: FIXTURE_PROTOCOL, packageName: name, events: events.slice(1), nextCursor: null, complete: true }, - ]; - }; - const operations = { - async readAuthenticatedFeedIdentity() { - return pinnedFeed; - }, - async readPackageMetadata(name) { - return metadata(name); - }, - async readPackageInventoryPage(name, cursor) { - const pages = inventory(name); - return cursor === 'next' ? pages[1] : pages[0]; - }, - async writePackage(entry, bytes, tag = distTag) { - assert.equal(tag, branch ? 'ado-e2e' : distTag); - assert.deepEqual(digest(bytes), { integrity: entry.integrity, bytes: entry.bytes, sha256: entry.sha256 }); - writes.push(entry.name); - const versions = state.get(entry.name)?.versions ?? new Map(); - versions.set(entry.version, entry.integrity); - state.set(entry.name, { latest: entry.version, versions }); - stored.set(entry.name, Buffer.from(bytes)); - }, - async downloadPackage(name, pkgVersion) { - const pkg = record.packages.find(item => item.name === name && item.version === pkgVersion); - const bytes = stored.get(name); - return { - protocol: FIXTURE_PROTOCOL, - status: 200, - bytes, - integrity: digest(bytes).integrity, - resolvedUrl: `${pinnedFeed.registry}${encodeURIComponent(name)}/-/${pkg.file}`, - }; - }, - async verifyConsumerInstall(request) { - assert.equal(request.scriptsDisabled, true); - assert.equal(request.registry, pinnedFeed.registry); - assert.deepEqual(request.packages, record.packages.map(({ name, version: pkgVersion }) => ({ name, version: pkgVersion }))); - return { - protocol: FIXTURE_PROTOCOL, - scriptsDisabled: true, - entries: record.packages.map(pkg => ({ - name: pkg.name, - version: pkg.version, - integrity: pkg.integrity, - resolvedUrl: `${pinnedFeed.registry}${encodeURIComponent(pkg.name)}/-/${pkg.file}`, - })), - }; - }, - }; - return { - dir, - contracts, - pinnedFeed, - record, - operations, - stored, - writes, - options: { - artifactRoot: dir, - verified: provenance, - contracts, - pinnedFeed, - readFeedIdentity: async () => pinnedFeed, - openFeedOperations: async () => operations, - }, - }; -} - -const json = (body, status = 200, redirected = false) => ({ status, redirected, text: async () => JSON.stringify(body) }); - -const releaseUrl = 'https://github.com/Azure/LogicAppsUX/releases/tag/v5.1022.0'; -const releaseVersion = '5.1022.0'; -const recipeSha = 'c0ffee0000000000000000000000000000000001'; -const releaseEnv = { BUILD_REASON: 'Manual', SOURCE_REPOSITORY: 'Azure/LogicAppsUX', RELEASE_VERSION: releaseVersion, BUILD_ID: '192333967', RECIPE_SHA: recipeSha }; -const releaseProvenance = { ...verified, kind: 'release-tag', buildId: releaseEnv.BUILD_ID, recipeSha }; - -// GitHub API mock for one release. Unknown paths return 404, so any asset or "latest" lookup fails loudly. -function releaseApi(sha = commitSha) { - const tagObject = '773772347897c57b58c9bf51ec7cc7bb27d24581'; - const release = { id: 7, tag_name: 'v5.1022.0', html_url: releaseUrl, draft: false, prerelease: false, published_at: '2026-11-18T16:55:54Z', - assets: [{ name: 'vscode-azurelogicapps-5.1022.0.vsix', browser_download_url: `${releaseUrl}/x.vsix` }] }; - const responses = new Map([ - ['releases/tags/v5.1022.0', release], - ['git/ref/tags/v5.1022.0', { ref: releaseRef, object: { type: 'tag', sha: tagObject } }], - [`git/tags/${tagObject}`, { sha: tagObject, tag: 'v5.1022.0', object: { type: 'commit', sha } }], - [`git/commits/${sha}`, { sha }], - ]); - const calls = []; - const fetchImpl = async url => { - const key = url.split('/LogicAppsUX/')[1]; - calls.push(key); - return responses.has(key) ? json(responses.get(key)) : json({ message: 'Not Found' }, 404); - }; - return { release, responses, calls, fetchImpl, tagObject }; + DEFAULT_REGISTRY, + PACKAGES, + PNPM_MIRROR_BASE, + bootstrapPnpm, + buildRelease, + isVersionInFeed, + main, + parseReleaseVersion, + publishRelease, + resolveReleaseTag, + tarballName, +} = require('./ado-npm-publisher.cjs'); + +const tempDirs = []; + +function createTempDir(prefix = 'ado-npm-publisher-test-') { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), `${prefix}${randomUUID()}-`)); + tempDirs.push(dir); + return dir; } -function gitFixture(cwd, ...args) { - const result = spawnSync('git', ['-c', 'user.name=fixture', '-c', 'user.email=fixture@example.invalid', '-c', 'commit.gpgsign=false', ...args], { - cwd, encoding: 'utf8', env: { PATH: process.env.PATH, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' }, - }); - assert.equal(result.status, 0, result.stderr); - return result.stdout.trim(); +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +function git(args, cwd) { + const result = spawnSync('git', args, { + cwd, + encoding: 'utf8', + env: { + ...process.env, + GIT_AUTHOR_NAME: 'Test', + GIT_AUTHOR_EMAIL: 'test@example.com', + GIT_COMMITTER_NAME: 'Test', + GIT_COMMITTER_EMAIL: 'test@example.com', + }, + }); + assert.equal(result.status, 0, `git ${args.join(' ')} failed: ${result.stderr}`); + return result.stdout.trim(); } -// A local release repository with the root pins and the nine package manifests snapshotCheckout reads. -function releaseRepoFixture({ tagType = 'annotated' } = {}) { - const repo = path.join(workspace(), 'release-repo'); - fs.mkdirSync(repo); - const { packageManager } = require('../package.json'); - fs.writeFileSync(path.join(repo, 'package.json'), JSON.stringify({ packageManager })); - const prerequisites = ['@microsoft/designer-ui-v2#build:lib', '@microsoft/logic-apps-graph-layout#build:lib']; - fs.writeFileSync(path.join(repo, 'turbo.json'), JSON.stringify({ tasks: { '@microsoft/logic-apps-designer-v2#build:lib': { dependsOn: prerequisites } } })); - for (const item of COHORT) { - fs.mkdirSync(path.join(repo, item.directory), { recursive: true }); - fs.writeFileSync(path.join(repo, item.directory, 'package.json'), JSON.stringify({ ...fixture(item).source, version: '5.110.0' })); +function createSampleRepo({ tag, annotated = false, packageManager } = {}) { + const repoRoot = createTempDir('repo-'); + git(['init'], repoRoot); + fs.writeFileSync( + path.join(repoRoot, 'package.json'), + `${JSON.stringify({ name: '@microsoft/logicappsux', version: '0.0.0', packageManager }, null, 2)}\n` + ); + for (const pkg of PACKAGES) { + const pkgDir = path.join(repoRoot, pkg.directory); + fs.mkdirSync(pkgDir, { recursive: true }); + fs.writeFileSync(path.join(pkgDir, 'package.json'), `${JSON.stringify({ name: pkg.name, version: '0.0.0' }, null, 2)}\n`); + } + git(['add', '.'], repoRoot); + git(['commit', '-m', 'Initial commit'], repoRoot); + const commitSha = git(['rev-parse', 'HEAD'], repoRoot); + if (tag) { + if (annotated) { + git(['tag', '-a', tag, '-m', `Release ${tag}`], repoRoot); + } else { + git(['tag', tag], repoRoot); } - fs.writeFileSync(path.join(repo, 'release-source.txt'), 'tagged bytes\n'); - gitFixture(repo, 'init', '--quiet'); - gitFixture(repo, 'add', '.'); - gitFixture(repo, 'commit', '--quiet', '-m', 'release'); - const sha = gitFixture(repo, 'rev-parse', 'HEAD'); - if (tagType === 'annotated') { - gitFixture(repo, 'tag', '-a', `v${releaseVersion}`, '-m', 'release', sha); - } else if (tagType === 'lightweight') { - gitFixture(repo, 'tag', `v${releaseVersion}`, sha); - } else if (tagType === 'noncommit') { - const blob = spawnSync('git', ['hash-object', '-w', '--stdin'], { - cwd: repo, - encoding: 'utf8', - env: { PATH: process.env.PATH, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' }, - input: 'not-a-commit', - }); - assert.equal(blob.status, 0, blob.stderr); - gitFixture(repo, 'update-ref', `refs/tags/v${releaseVersion}`, blob.stdout.trim()); - } else if (tagType !== 'none') { - throw new Error(`Unknown tagType: ${tagType}`); - } - return { repo, sha }; + } + return { repoRoot, commitSha }; } -// Run the exact inline pipeline code without loading any hosted services. -const pipelineFile = path.join(__dirname, '..', '.azure-pipelines', 'npm-publish.yml'); -const verifierFile = path.join(path.dirname(pipelineFile), 'npm-verify-release.steps.yml'); -function pipelinePython(file, index = 0) { - const yaml = fs.readFileSync(file, 'utf8'); - const block = [...yaml.matchAll(/python3 -I - <<'PY'\n([\s\S]*?)\n *PY\n/g)][index][1].split('\n'); - const indent = Math.min(...block.filter(line => line.trim()).map(line => /^ */.exec(line)[0].length)); - return block.map(line => line.slice(indent)).join('\n'); -} -const runPython = (file, env, options = {}) => spawnSync(options.executable ?? 'python3', ['-I', '-'], { - input: pipelinePython(file, options.index), encoding: 'utf8', env: { PATH: process.env.PATH, ...env }, cwd: options.cwd, timeout: 30_000, +test('parseReleaseVersion accepts valid semver and rejects invalid inputs', () => { + assert.equal(parseReleaseVersion('5.1024.0'), '5.1024.0'); + assert.equal(parseReleaseVersion(' 5.1024.1 '), '5.1024.1'); + for (const bad of ['', 'v5.1024.0', '5.1024', '5.1024.0-beta.1', '01.2.3', null, undefined]) { + assert.throws(() => parseReleaseVersion(bad), /Invalid releaseVersion/); + } }); -test('rejects whitespace, non-stable refs and queue macro text before any request', async () => { - assert.deepEqual(parseReleaseRef(releaseRef), { version, tag: 'v5.1022.0' }); - for (const ref of [`${releaseRef}\n`, 'refs/heads/main', 'refs/tags/v05.1022.0', 'refs/tags/v5.1022.0-beta.1', '$(System.AccessToken)']) { - assert.throws(() => parseReleaseRef(ref), /Invalid releaseRef/); - } - await assert.rejects(verifyReleaseMetadata({ releaseRef, expectedSha: `${commitSha} `, fetchImpl: assert.fail }), /full 40-character/); - await assert.rejects(main(['snapshot-source', '--release-ref'], {}, assert.fail), /only accept inputs from their environment/); +test('tarballName formats scoped package names as pnpm pack filenames', () => { + assert.equal(tarballName('@microsoft/logic-apps-shared', '5.1024.0'), 'microsoft-logic-apps-shared-5.1024.0.tgz'); + assert.equal(tarballName('@microsoft/designer-ui-v2', '5.1024.0'), 'microsoft-designer-ui-v2-5.1024.0.tgz'); }); -test('requires a published release and an annotated tag peeled to the expected commit', async () => { - const tagObject = '773772347897c57b58c9bf51ec7cc7bb27d24581'; - const responses = new Map([ - ['releases/tags/v5.1022.0', { id: 7, tag_name: 'v5.1022.0', draft: false, prerelease: false, published_at: '2026-11-18T16:55:54Z' }], - ['git/ref/tags/v5.1022.0', { ref: releaseRef, object: { type: 'tag', sha: tagObject } }], - [`git/tags/${tagObject}`, { sha: tagObject, tag: 'v5.1022.0', object: { type: 'commit', sha: commitSha } }], - [`git/commits/${commitSha}`, { sha: commitSha }], - ]); - const fetchImpl = async url => json(responses.get(url.split('/LogicAppsUX/')[1])); - assert.equal((await verifyReleaseMetadata({ releaseRef, expectedSha: commitSha.toUpperCase(), fetchImpl })).commitSha, commitSha); - await assert.rejects(verifyReleaseMetadata({ releaseRef, expectedSha: 'a'.repeat(40), fetchImpl }), /does not match expectedSha/); - delete responses.get('releases/tags/v5.1022.0').published_at; - await assert.rejects(verifyReleaseMetadata({ releaseRef, expectedSha: commitSha, fetchImpl }), /not a verified published/); -}); +test('resolveReleaseTag resolves lightweight and annotated tags and fails clearly when missing', () => { + const lightweight = createSampleRepo({ tag: 'v5.1024.0', annotated: false }); + assert.deepEqual(resolveReleaseTag(lightweight.repoRoot, '5.1024.0'), { + tag: 'v5.1024.0', + ref: 'refs/tags/v5.1024.0', + commitSha: lightweight.commitSha, + }); -test('verifies release metadata before checkout and rejects a different checked-out HEAD', async () => { - const root = workspace(); - const provenance = path.join(root, 'provenance.json'); - const contract = path.join(root, 'contract.json'); - const fetchImpl = async url => { - const key = url.split('/LogicAppsUX/')[1]; - if (key === 'releases/tags/v5.1022.0') { - return json({ id: 7, tag_name: 'v5.1022.0', draft: false, prerelease: false, published_at: '2026-11-18T16:55:54Z' }); - } - if (key === 'git/ref/tags/v5.1022.0') return json({ ref: releaseRef, object: { type: 'commit', sha: commitSha } }); - if (key === `git/commits/${commitSha}`) return json({ sha: commitSha }); - throw new Error(`Unexpected source lookup: ${key}`); - }; - const env = { - RELEASE_REF: releaseRef, EXPECTED_SHA: commitSha, PROVENANCE_FILE: provenance, - SOURCE_ROOT: process.cwd(), CONTRACT_FILE: contract, - }; - await main(['verify-source'], env, fetchImpl, () => {}); - assert.equal(JSON.parse(fs.readFileSync(provenance, 'utf8')).commitSha, commitSha); - await assert.rejects(main(['snapshot-source'], env, fetchImpl, () => {}), /Checked out commit.*does not match/); - assert.equal(fs.existsSync(contract), false); - fs.writeFileSync(provenance, JSON.stringify({ ...JSON.parse(fs.readFileSync(provenance, 'utf8')), releaseId: 8 })); - await assert.rejects(main(['snapshot-source'], env, fetchImpl, () => {}), /Release metadata changed/); -}); + const annotated = createSampleRepo({ tag: 'v5.1025.0', annotated: true }); + assert.deepEqual(resolveReleaseTag(annotated.repoRoot, '5.1025.0'), { + tag: 'v5.1025.0', + ref: 'refs/tags/v5.1025.0', + commitSha: annotated.commitSha, + }); -test('artifact preparation stops on HEAD mismatch before consuming tarballs', async () => { - const saved = path.join(workspace(), 'source.json'); - fs.writeFileSync(saved, JSON.stringify({ verified })); - await assert.rejects(prepareArtifact({ CONTRACT_FILE: saved, SOURCE_ROOT: process.cwd() }, assert.fail), /Checked out commit.*does not match/); + assert.throws(() => resolveReleaseTag(lightweight.repoRoot, '5.9999.0'), /Release tag 'v5\.9999\.0' was not found/); }); -test('requires a clean source checkout before snapshot and build', () => { - const root = workspace(); - const result = spawnSync('git', ['init', '--quiet', root], { encoding: 'utf8' }); - assert.equal(result.status, 0, result.stderr); - assert.doesNotThrow(() => verifyCleanCheckout(root)); - fs.writeFileSync(path.join(root, 'untracked.js'), 'fixture'); - assert.throws(() => verifyCleanCheckout(root), /modified or untracked/); -}); +test('bootstrapPnpm downloads pnpm from the 1ES mirror and verifies optional SHA-512 pin', () => { + const archivePayload = Buffer.from('fake-pnpm-tarball'); + const sha512 = createHash('sha512').update(archivePayload).digest('hex'); -test('source contract requires all cohort workspace edges and rejects excluded packages', () => { - const definition = COHORT[4]; - const { source } = fixture(definition); - const [dependency] = definition.runtimeDependencies; - assert.equal(buildManifestContract(definition, source, version).dependencies[dependency], version); - assert.throws(() => buildManifestContract(definition, { ...source, dependencies: { ...source.dependencies, [dependency]: 'workspace:^' } }, version), /expected workspace:\*/); - assert.throws(() => buildManifestContract(definition, { ...source, optionalDependencies: { '@microsoft/logic-apps-chat': '^0.1.0' } }, version), /unexpected external/); -}); - -test('sanitizes source-derived validation errors before they reach the agent log', () => { - const definition = COHORT[0]; - const { source } = fixture(definition); - const untrustedName = '##vso[task.setvariable variable=example]value'; - source.dependencies[untrustedName] = 'workspace:*'; - assert.throws(() => buildManifestContract(definition, source, version), error => { - assert(error.message.includes(untrustedName)); - assert(!sanitizeAgentOutput(error.message).includes('##')); - return true; - }); -}); - -test('sanitizes the CLI error path before writing to stderr', () => { - const root = workspace(); - const result = spawnSync(process.execPath, [path.join('scripts', 'ado-npm-publisher.cjs'), 'prepare-artifact'], { - env: { ...process.env, CONTRACT_FILE: path.join(root, '##vso[task.setvariable variable=example]value') }, - encoding: 'utf8', - }); - assert.equal(result.status, 1); - assert.match(result.stderr, /vso\[task\.setvariable/); - assert(!result.stderr.includes('##')); -}); - -test('requires Designer v2 build prerequisites on its specific Turbo task', () => { - const designerTask = '@microsoft/logic-apps-designer-v2#build:lib'; - const prerequisites = ['@microsoft/designer-ui-v2#build:lib', '@microsoft/logic-apps-graph-layout#build:lib']; - const config = { tasks: { 'build:lib': {}, [designerTask]: { dependsOn: prerequisites } } }; - assert.doesNotThrow(() => verifyBuildPrerequisites(config)); - assert.throws(() => verifyBuildPrerequisites({ tasks: { 'build:lib': { dependsOn: prerequisites } } }), /Missing Turbo prerequisite/); - assert.throws(() => verifyBuildPrerequisites({ tasks: { [designerTask]: { dependsOn: [prerequisites[0]] } } }), /graph-layout/); -}); + const sourceRoot = createTempDir('src-'); + const pnpmHome = createTempDir('pnpm-'); + fs.writeFileSync(path.join(sourceRoot, 'package.json'), JSON.stringify({ packageManager: `pnpm@9.1.3+sha512.${sha512}` })); -test('builds and packs only the verified cohort after checking each version rewrite', () => { - const root = workspace(); - const source = path.join(root, 'source'); - const output = path.join(root, 'output'); - const contracts = {}; - for (const item of COHORT) { - const { contract, source: manifest } = fixture(item); - const dir = path.join(source, item.directory); - fs.mkdirSync(dir, { recursive: true }); - fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ ...manifest, version: '5.110.0' })); - contracts[item.name] = contract; + const calls = []; + const run = (cmd, args) => { + calls.push([cmd, args]); + if (cmd === 'curl') { + const outputIndex = args.indexOf('--output'); + fs.writeFileSync(args[outputIndex + 1], archivePayload); } - const calls = []; - const logs = []; - const run = (command, args, options) => { - calls.push({ command, args, cwd: options.cwd }); - assert.deepEqual(options.stdio, ['ignore', 'pipe', 'pipe']); - if (command === process.execPath) { - for (const item of COHORT) { - const file = path.join(source, item.directory, 'package.json'); - fs.writeFileSync(file, JSON.stringify({ ...JSON.parse(fs.readFileSync(file, 'utf8')), version })); - } - } - return { status: 0, stdout: '##vso[task.prependpath]/tmp/untrusted\n', stderr: '##[error]untrusted\n' }; - }; - const env = { SOURCE_ROOT: source, ARTIFACT_ROOT: output }; - const snapshot = JSON.parse(JSON.stringify({ verified, contracts })); - buildCohort(env, snapshot, run, text => logs.push(text)); - assert(logs.some(text => text.includes('vso[task.prependpath]'))); - assert(logs.every(text => !text.includes('##'))); - assert.deepEqual(calls.slice(0, 3).map(call => call.args), [ - ['pnpm', 'install', '--recursive', '--frozen-lockfile', '--strict-peer-dependencies'], - ['scripts/update-versions.js', version], - ['pnpm', 'run', 'build:lib'], - ]); - assert.deepEqual(calls.slice(3).map(call => call.args), COHORT.map(item => - ['pnpm', '--dir', path.join(source, item.directory), 'pack', '--pack-destination', output])); - assert(calls.every(call => call.cwd === source)); - - fs.rmSync(output, { recursive: true }); - const failingRewrite = (command, args) => ({ status: command === process.execPath ? 1 : 0 }); - assert.throws(() => buildCohort(env, snapshot, failingRewrite), /failed: exit 1/); - - fs.rmSync(output, { recursive: true }); - const first = path.join(source, COHORT[0].directory, 'package.json'); - fs.writeFileSync(first, JSON.stringify({ ...JSON.parse(fs.readFileSync(first, 'utf8')), version: '5.110.0' })); - const attempted = []; - assert.throws(() => buildCohort(env, snapshot, (command, args) => { - attempted.push(args); - return { status: 0 }; - }), /version rewrite failed/); - assert.equal(attempted.length, 2); -}); - -test('branch bootstrap rejects a mismatched pnpm download before extracting or running it', () => { - const root = workspace(); - const { packageManager } = require('../package.json'); - fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify({ packageManager })); - const output = path.join(root, 'output'); - const requested = []; - const download = (command, args) => { - requested.push(command); - assert.equal(command, 'curl'); - assert.equal(new URL(args.at(-1)).hostname, 'ms-feed-25.pkgs.visualstudio.com'); - fs.writeFileSync(args[args.indexOf('--output') + 1], 'not the pinned pnpm archive'); - return { status: 0 }; - }; - assert.throws( - () => buildCohort({ ...branchEnv, SOURCE_ROOT: root, ARTIFACT_ROOT: output }, - { verified: branchProvenance(branchEnv) }, download, assert.fail, { HOME: root }), - /pnpm archive does not match the pinned SHA-512/ - ); - assert.deepEqual(requested, ['curl']); -}); - -test('validates ustar prefix, entry types, checksums and entrypoint files without a leading ./', () => { - const item = COHORT[0]; - const { contract, pack, content, packed } = fixture(item); - const validate = buffer => validateTarballArtifact(buffer, item, version, contract); - assert.equal(validate(pack()).name, item.name); - assert.throws(() => validate(pack(packed, content.slice(1))), /missing required packed entry.*index.js/); - assert.throws(() => validate(pack(packed, [...content, ['package/../escape', 'x']])), /tar entry path/); - assert.throws(() => validate(pack(packed, [...content, ['package/link', '', { type: '2' }]])), /tar entry type/); - assert.throws(() => validate(pack(packed, [...content, ['package/bad', 'x', { corrupt: true }]])), /checksum failure/); - assert.throws(() => validate(pack(packed, [...content, ['package/build/lib/.npmrc', 'x']])), /outside the library package/); -}); - -test('an absent CSS export can be advisory without relaxing other archive checks', () => { - const item = COHORT[0]; - const { contract, pack, packed, content } = fixture(item); - const css = 'package/build/lib/index.css'; - const withoutCss = content.filter(([file]) => file !== css); - const warnings = []; - const validate = (buffer, expected = contract) => validateTarballArtifact(buffer, item, version, expected, warning => warnings.push(warning)); - const archive = pack(packed, withoutCss); - - assert.deepEqual(validate(archive), { name: item.name, version, file: `microsoft-logic-apps-shared-${version}.tgz`, ...digest(archive) }); - assert.deepEqual(warnings, [`${item.name} is missing required packed entry '${css}'.`]); - assert.throws(() => validateTarballArtifact(archive, item, version, contract), /missing required packed entry.*index.css/); - - assert.throws(() => validate(pack(packed, withoutCss.slice(1))), /missing required packed entry.*index.js/); - assert.throws(() => validate(pack(packed, [...withoutCss, [css, '']])), /missing required packed entry.*index.css/); - assert.throws(() => validate(pack(packed, [...withoutCss, [css, '', { type: '5' }]])), /missing required packed entry.*index.css/); - assert.throws(() => validate(pack(packed, [...withoutCss, [css, '', { type: '2' }]])), /Unexpected tar entry type/); - assert.throws(() => validate(pack({ ...packed, exports: { ...packed.exports, './index.css': './other.css' } }, withoutCss)), /packed exports differs/); - const cssMain = { ...packed, main: 'build/lib/index.css' }; - const cssMainContract = { ...contract, entrypoints: { ...contract.entrypoints, main: cssMain.main } }; - assert.throws(() => validate(pack(cssMain, withoutCss), cssMainContract), /missing required packed entry.*index.css/); -}); - -test('validates a real npm pack archive against the bundled parser and preserves its integrity', () => { - const item = COHORT[0]; - const { contract, packed } = fixture(item); - const root = workspace(); - const config = path.join(root, 'empty.npmrc'); - fs.writeFileSync(config, ''); - fs.mkdirSync(path.join(root, 'build/lib'), { recursive: true }); - for (const file of ['index.js', 'index.d.ts', 'index.css']) fs.writeFileSync(path.join(root, 'build/lib', file), 'fixture'); - fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify({ ...packed, files: ['build/lib/**/*'] })); - const npm = path.join(resolveNpmRoot(), 'bin/npm-cli.js'); - const result = spawnSync(process.execPath, [npm, 'pack', '--offline', '--ignore-scripts', '--json', '--prefix', root, '--userconfig', config, - '--globalconfig', '/dev/null', '--cache', path.join(root, 'cache')], { cwd: root, env: { HOME: root, PATH: process.env.PATH }, encoding: 'utf8' }); - assert.equal(result.status, 0, 'npm pack fixture failed'); - const [{ filename, integrity, size }] = JSON.parse(result.stdout); - const artifact = validateTarballArtifact(fs.readFileSync(path.join(root, filename)), item, version, contract); - assert.deepEqual({ file: artifact.file, integrity: artifact.integrity, bytes: artifact.bytes }, { file: filename, integrity, bytes: size }); -}); - -test('rejects file ancestors in either tar order and noncanonical root manifests', () => { - const item = COHORT[0]; - const { contract, pack, packed, content } = fixture(item); - const validate = files => validateTarballArtifact(pack(packed, files), item, version, contract); - const collision = [['package/build/lib/parent', 'file'], ['package/build/lib/parent/child.js', 'child']]; - for (const files of [collision, [...collision].reverse()]) { - assert.throws(() => validate([...content, ...files]), /directory ancestor/); - } - assert.throws(() => validate([...content, ['package/PACKAGE.JSON', '{}']]), /Noncanonical package manifest/); - assert.equal(validate([['package/build/lib', '', { type: '5' }], ...content]).name, item.name); -}); - -test('rejects case-insensitive file and ancestor collisions in either tar order', () => { - const item = COHORT[0]; - const { contract, pack, packed, content } = fixture(item); - const validate = files => validateTarballArtifact(pack(packed, files), item, version, contract); - const collisions = [ - [['package/build/lib/Component.js', 'a'], ['package/build/lib/component.js', 'b']], - [['package/build/lib/Parent', 'file'], ['package/build/lib/parent/child.js', 'child']], - [['package/build/lib/Folder/file.js', 'a'], ['package/build/lib/folder/FILE.js', 'b']], - [['package/build/lib/Caf\u00e9.js', 'a'], ['package/build/lib/CAFE\u0301.js', 'b']], - ]; - for (const pair of collisions) { - for (const files of [pair, [...pair].reverse()]) { - assert.throws(() => validate([...content, ...files]), /duplicate tar entry path|directory ancestor/); - } + return { status: 0 }; + }; + + const { pnpmBin, binDir } = bootstrapPnpm(sourceRoot, pnpmHome, run); + assert.equal(calls[0][0], 'curl'); + assert.equal(calls[0][1].at(-1), `${PNPM_MIRROR_BASE}/pnpm/-/pnpm-9.1.3.tgz`); + assert.equal(calls[1][0], 'tar'); + assert.equal(pnpmBin, path.join(binDir, 'pnpm')); + assert.equal(fs.readlinkSync(pnpmBin), path.join(pnpmHome, 'package', 'bin', 'pnpm.cjs')); + + // Reject mismatched SHA-512 pin + const badHome = createTempDir('pnpm-bad-'); + fs.writeFileSync(path.join(sourceRoot, 'package.json'), JSON.stringify({ packageManager: `pnpm@9.1.3+sha512.${'0'.repeat(128)}` })); + assert.throws(() => bootstrapPnpm(sourceRoot, badHome, run), /SHA-512 does not match/); + + // Accept version-only packageManager without a hash suffix + const noHashHome = createTempDir('pnpm-nohash-'); + fs.writeFileSync(path.join(sourceRoot, 'package.json'), JSON.stringify({ packageManager: 'pnpm@9.15.0' })); + const result = bootstrapPnpm(sourceRoot, noHashHome, run); + assert.equal(fs.readlinkSync(result.pnpmBin), path.join(noHashHome, 'package', 'bin', 'pnpm.cjs')); +}); + +test('buildRelease checks out release tag, builds, packs all 9 packages, and writes .npmrc', () => { + const archivePayload = Buffer.from('fake-pnpm-archive'); + const sha512 = createHash('sha512').update(archivePayload).digest('hex'); + const { repoRoot, commitSha } = createSampleRepo({ + tag: 'v5.1024.0', + annotated: true, + packageManager: `pnpm@9.1.3+sha512.${sha512}`, + }); + + const agentTmp = createTempDir('tmp-'); + const scanRoot = createTempDir('scan-'); + const tarballDir = path.join(agentTmp, 'tarballs'); + const publishNpmrc = path.join(agentTmp, 'npm-publish', '.npmrc'); + const commands = []; + const logs = []; + + const run = (cmd, args, options) => { + commands.push({ cmd, args, cwd: options?.cwd }); + if (cmd === 'git') { + return spawnSync(cmd, args, options); } -}); - -test('rejects private packages, publish overrides, hooks and changed external requirements', () => { - const item = COHORT[0]; - const { contract, pack, packed } = fixture(item); - const validate = changes => validateTarballArtifact(pack({ ...packed, ...changes }), item, version, contract); - assert.throws(() => validate({ private: true }), /private package/); - assert.throws(() => validate({ publishConfig: { tag: 'latest' } }), /unexpected publishConfig/); - assert.throws(() => validate({ publishConfig: { registry: 'https://other.invalid/' } }), /unexpected publishConfig/); - assert.throws(() => validate({ scripts: { prepublishOnly: 'false' } }), /lifecycle hook/); - assert.throws(() => validate({ dependencies: { react: '^17' } }), /packed dependencies differs/); -}); - -test('revalidates every tarball against the same source contract even when uploaded digests match', () => { - const { dir, contracts, record } = artifactFixture(); - const manifestFile = path.join(dir, MANIFEST_FILE_NAME); - assert.deepEqual(validateArtifactFiles(dir, verified, contracts), record); - const { pack, packed } = fixture(COHORT[0]); - const forged = pack({ ...packed, peerDependencies: { '@fluentui/react': '^7' } }); - fs.writeFileSync(path.join(dir, record.packages[0].file), forged); - assert.throws(() => validateArtifactFiles(dir, verified, contracts), /identity or integrity mismatch/); - Object.assign(record.packages[0], digest(forged)); - fs.writeFileSync(manifestFile, JSON.stringify(record)); - assert.throws(() => validateArtifactFiles(dir, verified, contracts), /packed peerDependencies differs/); -}); - -test('rejects provenance changes, artifact path traversal and symlink tarballs', () => { - const { dir, contracts, record } = artifactFixture(); - const file = path.join(dir, MANIFEST_FILE_NAME); - const validate = () => validateArtifactFiles(dir, verified, contracts); - fs.writeFileSync(file, JSON.stringify({ ...record, source: { ...record.source, verifiedSha: 'a'.repeat(40) } })); - assert.throws(validate, /source provenance mismatch/); - const first = record.packages[0]; - fs.writeFileSync(file, JSON.stringify({ ...record, packages: [{ ...first, file: `../${first.file}` }, ...record.packages.slice(1)] })); - assert.throws(validate, /identity or integrity mismatch/); - fs.writeFileSync(file, JSON.stringify(record)); - const target = path.join(dir, first.file); - fs.renameSync(target, path.join(workspace(), first.file)); - fs.symlinkSync('anything', target); - assert.throws(validate, /ELOOP/); -}); - -test('uses only exact-scope npm credentials and asserts npm registry from an empty cwd', () => { - const root = workspace(); - const cwd = path.join(root, 'empty'); - fs.mkdirSync(cwd); - const config = path.join(root, 'config.npmrc'); - fs.writeFileSync(config, `registry=${DESTINATION_REGISTRY}\n${DESTINATION_REGISTRY.slice(6)}:_authToken=fake-token\n`); - assert.equal(readNpmAuthorization(config), 'Bearer fake-token'); - // Real local npm config resolution (no network) and a separate fake subprocess to inspect write arguments. - npmRunner(config, cwd); - fs.rmSync(path.join(cwd, 'cache'), { force: true, recursive: true }); - const calls = []; - const write = npmRunner(config, cwd, (_, args, options) => { - calls.push(args); - assert.equal(options.cwd, cwd); - assert.deepEqual(Object.keys(options.env).sort(), ['HOME', 'PATH']); - return { status: 0, stdout: DESTINATION_REGISTRY }; - }); - write(path.join(root, 'package.tgz'), distTag); - write(path.join(root, 'package.tgz'), 'latest', true); - assert(!calls[0].includes('--registry')); - assert(calls[1].includes('--ignore-scripts') && calls[1].includes(distTag)); - assert(calls[2].includes('--ignore-scripts') && calls[2].includes('--dry-run') && calls[2].includes('latest')); - fs.appendFileSync(config, '@microsoft:registry=https://other.invalid/\n'); - assert.throws(() => readNpmAuthorization(config), /Unexpected or duplicate/); -}); - -const entry = { name: COHORT[0].name, version, integrity: digest(Buffer.from('same')).integrity }; -const old = previousVersion; -const packument = (name = entry.name, tags = { latest: old }, versions = [old]) => ({ - name, 'dist-tags': tags, versions: Object.fromEntries(versions.map(value => [value, { name, version: value }])), -}); -const exact = { name: entry.name, version, dist: { integrity: entry.integrity } }; - -test('npm dry run uses latest without writes and stops on the first failure', () => { - const packages = [ - { ...entry, file: 'one.tgz' }, - { ...entry, name: COHORT[1].name, file: 'two.tgz' }, - { ...entry, name: COHORT[2].name, file: 'three.tgz' }, - ]; - const calls = []; - const run = (file, tag, isDryRun) => { - calls.push({ file, tag, isDryRun }); - return { status: calls.length === 2 ? 1 : 0 }; - }; - assert.throws(() => dryRunCohort({ packages }, '/artifact', run, () => {}), /dry run failed/); - assert.deepEqual(calls, [ - { file: '/artifact/one.tgz', tag: 'latest', isDryRun: true }, - { file: '/artifact/two.tgz', tag: 'latest', isDryRun: true }, - ]); -}); - -test('requires authenticated HTTP 200 on the exact feed ID and rejects redirects', async () => { - const fake = async (url, opts) => { - assert(url.includes(`/${DESTINATION_FEED_ID}?`)); - assert.equal(opts.redirect, 'error'); - assert.equal(opts.headers.authorization, 'Bearer fake-token'); - return json({ id: DESTINATION_FEED_ID, name: 'microsoft-logic-apps' }); - }; - await authenticateFeed('fake-token', fake); - await assert.rejects(authenticateFeed('fake-token', async () => json({ id: 'another-feed' })), /identity mismatch/); - await assert.rejects(authenticateFeed('fake-token', async () => json({}, 200, true)), /unexpected HTTP/); -}); - -test('only authenticated successful package metadata supplies absence evidence', async () => { - for (const status of [401, 403, 404, 429, 500]) { - const registry = createRegistry('Bearer fake-token', async (url, options) => { - assert.equal(url, `${DESTINATION_REGISTRY}${encodeURIComponent(entry.name)}`); - assert.equal(options.headers.authorization, 'Bearer fake-token'); - return json({ code: 'E404' }, status); - }); - assert.equal((await classifyPackageState(registry, entry, distTag)).status, 'unknown'); + if (cmd === 'curl') { + fs.writeFileSync(args[args.indexOf('--output') + 1], archivePayload); + return { status: 0 }; } - assert.equal((await classifyPackageState(async () => packument(), entry, distTag)).status, 'absent'); - assert.equal((await classifyPackageState(async () => ({ name: entry.name, 'dist-tags': {}, versions: [] }), entry, distTag)).status, 'unknown'); -}); - -test('rejects backfills and requires existing identical versions to already be latest', async () => { - const newer = '5.1023.0'; - const pre = name => packument(name, { latest: newer }, [old, newer]); - assert.equal((await classifyPackageState(pre, entry, distTag)).status, 'conflict'); - const existing = name => { - const doc = packument(name, { latest: old }, [old, version]); - doc.versions[version] = exact; - return doc; - }; - assert.equal((await classifyPackageState(existing, entry, distTag)).status, 'conflict'); - const prerelease = name => packument(name, { latest: '5.1021.0-beta.1' }, ['5.1021.0-beta.1']); - assert.equal((await classifyPackageState(prerelease, entry, distTag)).status, 'unknown'); - const numeric = latest => name => packument(name, { latest }, [latest]); - assert.equal((await classifyPackageState(numeric('5.99.0'), entry)).status, 'absent'); - assert.equal((await classifyPackageState(numeric('5.10210.0'), entry)).status, 'conflict'); -}); - -test('reports newer stable versions outside latest without assuming their release order', async () => { - for (const newer of ['5.1023.0', '5.1023.0+build.1']) { - const registry = name => packument(name, { latest: old }, [old, newer]); - const state = await classifyPackageState(registry, entry); - assert.equal(state.status, 'absent'); - assert.match(state.warning, /newer stable version.*release order is unverified/i); + if (cmd === 'tar') { + return { status: 0 }; } - const prerelease = name => packument(name, { latest: old }, [old, '5.1023.0-beta.1']); - assert.equal((await classifyPackageState(prerelease, entry)).status, 'absent'); - const sameVersion = name => packument(name, { latest: old }, [old, '5.1022.0+build.1']); - assert.equal((await classifyPackageState(sameVersion, entry)).status, 'conflict'); -}); - -test('requires exact name/version and matching canonical SHA-512 to skip a version', async () => { - const lookup = metadata => name => { - const doc = packument(name, { latest: version }, [old, version]); - doc.versions[version] = metadata; - return doc; - }; - assert.equal((await classifyPackageState(lookup(exact), entry, distTag)).status, 'already-identical'); - assert.equal((await classifyPackageState(lookup({ ...exact, version: old }), entry, distTag)).status, 'unknown'); - assert.equal((await classifyPackageState(lookup({ ...exact, dist: {} }), entry, distTag)).status, 'unknown'); - const changed = { integrity: digest(Buffer.from('different')).integrity }; - assert.equal((await classifyPackageState(lookup({ ...exact, dist: changed }), entry, distTag)).status, 'conflict'); -}); - -test('reconciles all nonzero write results without retry, even timeout and spawn exception', async () => { - for (const writeResult of [{ status: 1 }, { status: 128 }, { status: null, error: 'ETIMEDOUT' }, undefined]) { - let writes = 0; - const lookups = []; - const registry = name => { - lookups.push(name); - const doc = packument(name, { latest: version }, [old, version]); - doc.versions[version] = exact; - return doc; - }; - const write = () => { - writes++; - if (!writeResult) throw new Error('spawn failure'); - return writeResult; - }; - assert.equal((await publishPackage({ entry, registry, write })).status, 'already-identical'); - assert.equal(writes, 1); - assert.deepEqual(lookups, [entry.name]); + if (cmd === process.execPath && args[0] === 'scripts/update-versions.js') { + // Simulate version update in the detached worktree + const pkgPath = path.join(options.cwd, 'package.json'); + const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')); + pkg.version = args[1]; + fs.writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`); + return { status: 0 }; } -}); - -test('stops dependents for an unknown write or latest drift; no tag repair', async () => { - const second = { ...entry, name: COHORT[1].name }; - const artifact = { destination: { distTag }, packages: [entry, second] }; - for (const drift of [false, true]) { - const results = []; - let writes = 0; - const registry = name => { - if (writes && !drift) throw new Error('read timed out'); - const doc = writes ? packument(name, { latest: old }, [old, version]) : packument(name); - if (writes) doc.versions[version] = { ...exact, name }; - return doc; - }; - const write = () => { writes++; return { status: drift ? 0 : 1 }; }; - await assert.rejects(processCohort(artifact, registry, write, line => results.push(line)), /Publication stopped/); - assert.equal(writes, 1); - assert.match(results[0], drift ? /latest does not point/ : /Publication outcome unknown/); - assert.match(results[1], /not-attempted/); + if (cmd.endsWith(`${path.sep}pnpm`) && args[2] === 'pack') { + const pkgDir = args[1]; + const pkgJson = JSON.parse(fs.readFileSync(path.join(pkgDir, 'package.json'), 'utf8')); + const dest = args[args.indexOf('--pack-destination') + 1]; + fs.writeFileSync(path.join(dest, tarballName(pkgJson.name, '5.1024.0')), 'tgz-bytes'); + return { status: 0 }; } -}); - -test('rechecks latest immediately before each write and stops when a newer version appears', async () => { - const second = { ...entry, name: COHORT[1].name }; - const artifact = { destination: { distTag }, packages: [entry, second] }; - let firstReads = 0; - const registry = name => { - const latest = name === entry.name && ++firstReads > 1 ? '5.1023.0' : old; - return packument(name, { latest }, [latest]); - }; - const report = []; - let writes = 0; - await assert.rejects(processCohort(artifact, registry, () => { writes++; }, line => report.push(line)), /Publication stopped/); - assert.equal(writes, 0); - assert.match(report[0], /older than latest/); - assert.match(report[1], /not-attempted/); -}); - -test('npmAuthenticate parent credentials, quoted values and always-auth do not mask conflicting scopes', () => { - const config = path.join(workspace(), 'npmrc'); - const parent = DESTINATION_REGISTRY.slice(6).replace(/registry\/$/, ''); - fs.writeFileSync(config, `registry=${DESTINATION_REGISTRY}\nalways-auth=true\n${parent}:_authToken="fake-token"\n`); - assert.equal(readNpmAuthorization(config), 'Bearer fake-token'); - fs.appendFileSync(config, `${DESTINATION_REGISTRY.slice(6)}:_authToken=different-token\n`); - assert.throws(() => readNpmAuthorization(config), /Conflicting npm credential scopes/); -}); - -test('auth agrees with npm parsing without borrowing fields across credential scopes', () => { - const config = path.join(workspace(), 'npmrc'); - const scope = DESTINATION_REGISTRY.slice(6); - const parent = scope.replace(/registry\/$/, ''); - const npmRoot = resolveNpmRoot(); - const ini = require(path.join(npmRoot, 'node_modules/ini')); - const getAuth = require(path.join(npmRoot, 'node_modules/npm-registry-fetch/lib/auth.js')); - const password = Buffer.from('fake-password').toString('base64'); - const check = text => { - fs.writeFileSync(config, `registry=${DESTINATION_REGISTRY}\n${text}`); - const auth = getAuth(DESTINATION_REGISTRY, ini.parse(fs.readFileSync(config, 'utf8'))); - assert.equal(readNpmAuthorization(config), auth.token ? `Bearer ${auth.token}` : `Basic ${auth.auth}`); - }; - for (const prefix of [scope, parent]) { - check(`${prefix}:username=fake-user\n${prefix}:_password=${password}\n`); - check(`${prefix}:_authToken=fake-token ; inline comment\n`); - check(`${prefix}:_authToken="fake-token" # inline comment\n`); - check(`${prefix}:_authToken='fake-token'\n`); + return { status: 0 }; + }; + + const result = buildRelease( + { + RELEASE_VERSION: '5.1024.0', + AGENT_TMP: agentTmp, + RELEASE_SCAN_ROOT: scanRoot, + TARBALL_DIR: tarballDir, + NPM_REGISTRY: DEFAULT_REGISTRY, + PUBLISH_NPMRC: publishNpmrc, + }, + { run, log: msg => logs.push(msg), repoRoot } + ); + + assert.equal(result.version, '5.1024.0'); + assert.equal(result.commitSha, commitSha); + + // Verify build steps ran in order + const pnpmCalls = commands.filter(c => c.cmd.endsWith(`${path.sep}pnpm`)).map(c => c.args); + assert.deepEqual(pnpmCalls[0], ['install', '--recursive', '--frozen-lockfile', '--strict-peer-dependencies']); + assert.deepEqual(pnpmCalls[1], ['run', 'build:lib']); + assert.equal(pnpmCalls.filter(a => a[2] === 'pack').length, PACKAGES.length); + + assert.ok(commands.some(c => c.cmd === process.execPath && c.args[0] === 'scripts/update-versions.js' && c.args[1] === '5.1024.0')); + + // All 9 tarballs exist and .npmrc was prepared for npmAuthenticate + for (const pkg of PACKAGES) { + assert.ok(fs.existsSync(path.join(tarballDir, tarballName(pkg.name, '5.1024.0')))); + } + assert.equal(fs.readFileSync(publishNpmrc, 'utf8'), `registry=${DEFAULT_REGISTRY}\n`); + + // Retained release-source worktree for Component Governance has tracked files restored + const retainedRoot = path.join(scanRoot, 'release-source'); + assert.ok(fs.existsSync(retainedRoot)); + assert.equal(JSON.parse(fs.readFileSync(path.join(retainedRoot, 'package.json'), 'utf8')).version, '0.0.0'); +}); + +test('isVersionInFeed handles present, empty-stdout absent, 404 absent, and unexpected errors', () => { + const baseOpts = { registry: DEFAULT_REGISTRY, npmrc: '/tmp/.npmrc', cwd: '/tmp' }; + + assert.equal( + isVersionInFeed('@microsoft/logic-apps-shared', '5.1024.0', { + ...baseOpts, + run: () => ({ status: 0, stdout: '5.1024.0\n', stderr: '' }), + }), + true + ); + + // Package exists in feed, target version does not -> npm view exits 0 with empty stdout + assert.equal( + isVersionInFeed('@microsoft/logic-apps-shared', '5.1024.0', { + ...baseOpts, + run: () => ({ status: 0, stdout: '', stderr: '' }), + }), + false + ); + + // Brand-new package not in feed -> npm view exits 1 with E404 + assert.equal( + isVersionInFeed('@microsoft/logic-apps-shared', '5.1024.0', { + ...baseOpts, + run: () => ({ status: 1, stdout: '', stderr: 'npm error code E404\nnpm error 404 Not Found' }), + }), + false + ); + + // Auth failure must throw instead of falsely treating package as absent + assert.throws( + () => + isVersionInFeed('@microsoft/logic-apps-shared', '5.1024.0', { + ...baseOpts, + run: () => ({ status: 1, stdout: '', stderr: 'npm error code E401\nnpm error Unable to authenticate' }), + }), + /Failed to check @microsoft\/logic-apps-shared@5\.1024\.0 in feed/ + ); +}); + +test('publishRelease skips packages already in feed and publishes missing packages without post-publish readback', () => { + const version = '5.1024.0'; + const tarballDir = createTempDir('tarballs-'); + const npmrc = path.join(createTempDir('npmrc-'), '.npmrc'); + fs.writeFileSync(npmrc, `registry=${DEFAULT_REGISTRY}\n`); + + for (const pkg of PACKAGES) { + fs.writeFileSync(path.join(tarballDir, tarballName(pkg.name, version)), 'tgz-bytes'); + } + + const alreadyInFeed = new Set([ + '@microsoft/logic-apps-shared', + '@microsoft/designer-ui', + '@microsoft/designer-ui-v2', + ]); + const calls = []; + const logs = []; + + const run = (cmd, args, options) => { + calls.push({ cmd, args, stdio: options?.stdio }); + if (cmd === 'npm' && args[0] === 'view') { + const pkgName = args[1].slice(0, args[1].lastIndexOf('@')); + return alreadyInFeed.has(pkgName) + ? { status: 0, stdout: `${version}\n`, stderr: '' } + : { status: 0, stdout: '', stderr: '' }; } - fs.writeFileSync(config, `${scope}:username=fake-user\n${parent}:_password=${password}\n`); - assert.throws(() => readNpmAuthorization(config), /Missing or ambiguous credentials/); -}); - -test('resolves trusted npm lazily for symlink and regular launchers, failing closed when missing', () => { - const root = workspace(); - const bin = path.join(root, 'bin'); - fs.mkdirSync(bin); - const execPath = path.join(bin, 'node'); - const actualRoot = resolveNpmRoot(); - fs.symlinkSync(path.join(actualRoot, 'bin/npm-cli.js'), path.join(bin, 'npm')); - assert.equal(resolveNpmRoot(execPath), actualRoot); - fs.unlinkSync(path.join(bin, 'npm')); - fs.writeFileSync(path.join(bin, 'npm'), '# regular launcher fixture\n'); - fs.mkdirSync(path.join(bin, 'node_modules')); - fs.symlinkSync(actualRoot, path.join(bin, 'node_modules/npm'), 'dir'); - assert.equal(resolveNpmRoot(execPath), path.join(bin, 'node_modules/npm')); - fs.unlinkSync(path.join(bin, 'node_modules/npm')); - assert.throws(() => resolveNpmRoot(execPath), /missing a supported npm CLI/); - fs.unlinkSync(path.join(bin, 'npm')); - assert.throws(() => resolveNpmRoot(execPath), /missing a supported npm CLI/); -}); - -test('uses one coherent packument for preflight and each zero or nonzero write reconciliation', async () => { - const complete = () => { - const doc = packument(entry.name, { latest: version }, [old, version]); - doc.versions[version] = structuredClone(exact); - return doc; - }; - let reads = 0; - const initial = complete(); - delete initial.versions[version].dist; - // The following response must not be used to fill holes in the first response. - const preflight = await classifyPackageState(async () => ++reads === 1 ? initial : complete(), entry, distTag); - assert.equal(preflight.status, 'unknown'); - assert.equal(reads, 1); - for (const status of [0, 1]) { - reads = 0; - const wrongLatest = complete(); - wrongLatest['dist-tags'].latest = old; - const result = await publishPackage({ entry, write: () => ({ status }), - registry: async () => ++reads === 1 ? wrongLatest : complete() }); - assert.equal(result.status, 'failed'); - assert.match(result.reason, /latest does not point/); - assert.equal(reads, 1); + if (cmd === 'npm' && args[0] === 'publish') { + return { status: 0 }; } -}); - -test('zero-exit publish still requires exact retained integrity and latest', async () => { - const registry = metadata => async () => { - const doc = packument(entry.name, { latest: version }, [old, version]); - doc.versions[version] = metadata; - return doc; - }; - const write = () => ({ status: 0 }); - const call = metadata => publishPackage({ entry, registry: registry(metadata), write }); - assert.equal((await call(exact)).status, 'published'); - assert.match((await call({ ...exact, dist: { integrity: digest(Buffer.from('other')).integrity } })).reason, /conflict/); - const missingTag = async () => { - const doc = packument(entry.name, { latest: old }, [old, version]); - doc.versions[version] = exact; - return doc; - }; - assert.match((await publishPackage({ entry, registry: missingTag, write: () => ({ status: 1 }) })).reason, /latest does not point/); - assert.equal((await classifyPackageState(async () => packument(entry.name, {}, [old]), entry, distTag)).status, 'unknown'); -}); - -test('stops later writes when a same-precedence variant appears during reconciliation', async () => { - const second = { ...entry, name: COHORT[1].name }; - const artifact = { destination: { distTag }, packages: [entry, second] }; - let writes = 0; - const registry = name => { - if (!writes) return packument(name); - const doc = packument(name, { latest: version }, [old, version, `${version}+build.1`]); - doc.versions[version] = { ...exact, name }; - return doc; - }; - const report = []; - await assert.rejects(processCohort(artifact, registry, () => { writes++; return { status: 0 }; }, line => report.push(line)), - /Publication stopped/); - assert.equal(writes, 1); - assert.match(report[0], /ambiguous release precedence/); - assert.match(report[1], /not-attempted/); -}); - -test('blocks every write if any preflight fails, and keeps the production command disabled', async () => { - const second = { ...entry, name: COHORT[1].name }; - const artifact = { destination: { distTag }, packages: [entry, second] }; - const registry = name => name === entry.name ? packument(name) : {}; - await assert.rejects(processCohort(artifact, registry, assert.fail, () => {}), /zero package writes/); - await assert.rejects(main(['feed'], { PUBLISHER_MODE: 'publish' }, assert.fail, assert.fail), /Publication blocked/); -}); - -test('blocks isolated test-feed CLI path before reading environment or network state', async () => { - await assert.rejects( - main(['isolated-test-feed'], new Proxy({}, { get: () => { throw new Error('env should not be read'); } }), assert.fail, assert.fail), - /fixture-only.*rejected before environment/i, - ); -}); - -test('isolated feed path rejects production identities and non-.invalid registries', () => { - assert.throws(() => assertPinnedIsolatedIdentity({ - id: DESTINATION_FEED_ID, - name: 'microsoft-logic-apps', - registry: 'https://logicappsux-feed.invalid/npm/registry/', - }), /cannot target production/); - assert.throws(() => assertPinnedIsolatedIdentity({ - id: 'test', - name: 'test', - registry: 'https://feeds.dev.azure.com/msazure/One/_packaging/test/npm/registry/', - }), /\.invalid host/); -}); - -test('isolated preflight validates all 9 retained packages with zero writes', async () => { - const fixtureState = isolatedFeedFixture(); - const result = await runIsolatedTestFeedPath(fixtureState.options); - assert.equal(result.summary['already-identical'], COHORT.length); - assert.equal(result.summary.writes, 0); - assert.equal(fixtureState.writes.length, 0); -}); - -test('isolated publish writes only missing packages and replays same artifact with zero writes', async () => { - const missing = new Set(COHORT.slice(0, 3).map(item => item.name)); - const fixtureState = isolatedFeedFixture({ missing }); - const first = await runIsolatedTestFeedPath({ ...fixtureState.options, mode: 'publish' }); - assert.equal(first.summary.writes, 3); - assert.equal(fixtureState.writes.length, 3); - const second = await runIsolatedTestFeedPath({ ...fixtureState.options, mode: 'publish' }); - assert.equal(second.summary.writes, 0); - assert.equal(fixtureState.writes.length, 3); -}); - -test('isolated publish writes all nine to an empty fixture and replays without writes', async () => { - const { options, writes } = isolatedFeedFixture({ empty: true }); - const preflight = await runIsolatedTestFeedPath(options); - assert.deepEqual(preflight.summary, { writes: 0, absent: COHORT.length }); - const publish = { ...options, mode: 'publish' }; - assert.deepEqual((await runIsolatedTestFeedPath(publish)).summary, { writes: COHORT.length, 'already-identical': COHORT.length }); - assert.deepEqual((await runIsolatedTestFeedPath(publish)).summary, { writes: 0, 'already-identical': COHORT.length }); - assert.deepEqual(writes, COHORT.map(({ name }) => name)); -}); - -test('isolated publish blocks uncorroborated 404, permission failures, and ambiguous inventory before any writes', async t => { - const name = COHORT[0].name; - for (const [label, empty, overrides, error] of [ - ['404 with a retained version', false, { readPackageMetadata: packageName => ({ protocol: FIXTURE_PROTOCOL, packageName, status: 404 }) }, /404 disagrees/], - ['permission denied despite empty inventory', true, { readPackageMetadata: packageName => ({ protocol: FIXTURE_PROTOCOL, packageName, status: 403 }) }, /status 403/], - ['partial inventory', true, { readPackageInventoryPage: packageName => ({ protocol: FIXTURE_PROTOCOL, packageName, events: [], nextCursor: null, complete: false }) }, /complete terminal/], - ['deleted release variant', true, { readPackageInventoryPage: packageName => ({ protocol: FIXTURE_PROTOCOL, packageName, events: [{ type: 'deleted', version: `${version}+other` }], nextCursor: null, complete: true }) }, /deleted or upstream/], - ['duplicate inventory across pages', true, { readPackageInventoryPage: (packageName, cursor) => ({ protocol: FIXTURE_PROTOCOL, packageName, events: [{ type: 'deleted', version: previousVersion }], nextCursor: cursor ? null : 'next', complete: Boolean(cursor) }) }, /duplicate version/], - ['mismatched authenticated identity', true, { readAuthenticatedFeedIdentity: pinned => ({ ...pinned, id: 'other-feed' }) }, /Authenticated identity mismatch/], - ]) { - await t.test(label, async () => { - const { options, operations, writes } = isolatedFeedFixture({ empty, missing: new Set([COHORT[1].name]) }); - const overridden = { ...operations }; - for (const [method, override] of Object.entries(overrides)) { - overridden[method] = (...args) => method === 'readAuthenticatedFeedIdentity' || args[0] === name ? override(...args) : operations[method](...args); - } - await assert.rejects(runIsolatedTestFeedPath({ ...options, mode: 'publish', openFeedOperations: async () => overridden }), error); - assert.deepEqual(writes, []); - }); - } -}); - -test('isolated publish rejects conflicting metadata and retained bytes before writing missing packages', async t => { - const missing = new Set([COHORT[0].name]); - for (const [label, modifyMetadata, corrupt, error] of [ - ['duplicate metadata', metadata => ({ ...metadata, versions: [...metadata.versions, metadata.versions[0]] }), false, /invalid version entries/], - ['same-precedence metadata', metadata => ({ ...metadata, versions: [...metadata.versions, { ...metadata.versions[0], version: `${version}+other` }] }), false, /same-precedence/], - ['status or integrity disagreement', metadata => ({ ...metadata, versions: [{ ...metadata.versions[0], integrity: digest(Buffer.from('different')).integrity }] }), false, /disagree/], - ['wrong retained tarball', metadata => metadata, true, /Download bytes do not match/], - ]) { - await t.test(label, async () => { - const { options, operations, stored, writes } = isolatedFeedFixture({ missing }); - const name = COHORT[1].name; - if (corrupt) stored.set(name, Buffer.from('not the retained tarball')); - const readPackageMetadata = async packageName => { - const metadata = await operations.readPackageMetadata(packageName); - return packageName === name ? modifyMetadata(metadata) : metadata; - }; - await assert.rejects(runIsolatedTestFeedPath({ ...options, mode: 'publish', openFeedOperations: async () => ({ ...operations, readPackageMetadata }) }), error); - assert.deepEqual(writes, []); - }); - } -}); - -test('isolated publish stops on a bad download before the next simulated write', async () => { - const { options, operations, pinnedFeed, writes } = isolatedFeedFixture({ empty: true }); - const downloadPackage = async (...args) => ({ - ...await operations.downloadPackage(...args), - resolvedUrl: `${pinnedFeed.registry}../other-registry/fake.tgz`, - }); - await assert.rejects(runIsolatedTestFeedPath({ ...options, mode: 'publish', openFeedOperations: async () => ({ ...operations, downloadPackage }) }), /does not match the pinned registry/); - assert.deepEqual(writes, [COHORT[0].name]); -}); - -test('isolated publish rechecks bytes on rerun after an acknowledged or unacknowledged simulated write', async t => { - for (const landed of [true, false]) { - await t.test(landed ? 'write landed before failure' : 'write did not land', async () => { - const { options, operations, writes } = isolatedFeedFixture({ empty: true }); - const writePackage = async (entry, bytes) => { - if (landed) await operations.writePackage(entry, bytes); - throw new Error('simulated interruption'); - }; - const publish = { ...options, mode: 'publish' }; - await assert.rejects(runIsolatedTestFeedPath({ ...publish, openFeedOperations: async () => ({ ...operations, writePackage }) }), /simulated interruption/); - assert.equal(writes.length, Number(landed)); - assert.equal((await runIsolatedTestFeedPath(publish)).summary.writes, COHORT.length - Number(landed)); - assert.equal((await runIsolatedTestFeedPath(publish)).summary.writes, 0); - assert.deepEqual(writes, COHORT.map(({ name }) => name)); - }); - } -}); - -test('isolated consumer rejects duplicate records and an unexpected tarball URL', async t => { - for (const [label, modify, error] of [ - ['duplicate records', entries => [...entries, entries[0]], /exactly one entry/], - ['unexpected URL', entries => [{ ...entries[0], resolvedUrl: `${entries[0].resolvedUrl}?other=1` }, ...entries.slice(1)], /does not match the pinned registry/], - ]) { - await t.test(label, async () => { - const { options, operations, writes } = isolatedFeedFixture(); - const verifyConsumerInstall = async request => { - const consumer = await operations.verifyConsumerInstall(request); - return { ...consumer, entries: modify(consumer.entries) }; - }; - await assert.rejects(runIsolatedTestFeedPath({ ...options, openFeedOperations: async () => ({ ...operations, verifyConsumerInstall }) }), error); - assert.deepEqual(writes, []); - }); - } -}); - -test('branch provenance rejects unreviewed sources and requires the pipeline SHA to match', () => { - assert.throws(() => branchProvenance({ ...branchEnv, SOURCE_REPOSITORY: 'fork/LogicAppsUX' }), /GitHub repository/); - assert.throws(() => branchProvenance({ ...branchEnv, SOURCE_BRANCH: 'refs/heads/main' }), /designated test branch/); - assert.throws(() => branchProvenance({ ...branchEnv, SOURCE_VERSION: 'a'.repeat(40) }), /does not match the reviewed SHA/); - assert.throws(() => branchProvenance({ ...branchEnv, BUILD_ID: '001' }), /positive Azure Pipelines build ID/); -}); - -test('branch tarballs pin all intra-cohort dependencies to the test version and cannot override the registry', () => { - const provenance = branchProvenance(branchEnv); - const definition = COHORT[1]; - const { source, contract, pack, packed } = fixture(definition, provenance.version); - const override = { registry: DESTINATION_REGISTRY }; - assert.equal(contract.dependencies[COHORT[0].name], provenance.version); - assert.throws(() => buildManifestContract(definition, { ...source, publishConfig: override }, provenance.version), /cannot override the registry/); - assert.throws(() => validateTarballArtifact(pack({ ...packed, publishConfig: override }), definition, provenance.version, contract), /cannot override the registry/); -}); - -test('branch artifact cannot be reclassified as a release, even at the same commit', () => { - const provenance = branchProvenance(branchEnv); - const { dir, contracts, record } = artifactFixture(provenance); - assert.equal(record.destination, null); - assert.equal(record.source.version, `0.0.0-ado.${branchEnv.BUILD_ID}.g${commitSha}`); - assert.throws(() => validateArtifactFiles(dir, { ...verified, version: provenance.version }, contracts), /source provenance mismatch/); -}); - -test('branch fixture writes nine test-tagged tarballs, then verifies them in a read-only replay', async () => { - const provenance = branchProvenance(branchEnv); - const { options, operations, writes } = isolatedFeedFixture({ empty: true, provenance }); - const { writePackage, ...reader } = operations; - const replay = { ...options, mode: 'replay', openFeedOperations: async () => reader }; - await assert.rejects(runIsolatedTestFeedPath(replay), /requires all nine versions/); - assert.deepEqual(writes, []); - assert.deepEqual((await runIsolatedTestFeedPath({ ...options, mode: 'publish' })).summary, { writes: 9, 'already-identical': 9 }); - assert.deepEqual((await runIsolatedTestFeedPath(replay)).summary, { writes: 0, 'already-identical': 9 }); - assert.deepEqual(writes, COHORT.map(({ name }) => name)); -}); - -test('branch fixture rejects a reserved test version already in upstream inventory', async () => { - const provenance = branchProvenance(branchEnv); - const { options, writes } = isolatedFeedFixture({ empty: true, provenance, upstream: new Set([COHORT[1].name]) }); - await assert.rejects(runIsolatedTestFeedPath({ ...options, mode: 'publish' }), /deleted or upstream/); - assert.deepEqual(writes, []); -}); - - -test('only the separate protected Publish stage can authenticate after verifying the current run', () => { - const yaml = fs.readFileSync(pipelineFile, 'utf8'); - const [release, publish] = yaml.split(/(?= {6}- stage: Publish\n)/); - const verifier = fs.readFileSync(verifierFile, 'utf8'); - assert.match(yaml, /^trigger: none\npr: none\nschedules: \[\]$/m); - assert.deepEqual([...yaml.matchAll(/^ {2}- name: (\w+)/gm)].map(match => match[1]), ['releaseVersion']); - assert.doesNotMatch(release, /npmAuthenticate|System\.AccessToken|serviceConnection|workloadIdentity|type: boolean/i); - assert.match(yaml, /name: Azure-Pipelines-1ESPT-ExDShared\s+image: ubuntu-latest\s+os: linux/); - assert.match(yaml, /fetchTags: true/); - assert.match(yaml, /fetchDepth: 0/); - assert.match(yaml, /persistCredentials: false/); - assert.match(release, /componentgovernance:\s+useAgentBuildDirectory: true/); - assert.match(release, /RELEASE_SCAN_ROOT: '\$\(Agent\.BuildDirectory\)'/); - const verify = release.slice(release.indexOf('- job: VerifyRelease'), release.indexOf('- job: ProductionPublishNotActivated')); - assert.match(verify, /buildType: current/); - assert.match(verify, /steps:\s+- checkout: none/); - assert.equal((yaml.match(/- checkout: self/g) ?? []).length, 1); - assert.match(release.slice(release.indexOf('- job: ProductionPublishNotActivated')), /checkout: none/); - assert.doesNotMatch(publish, /trigger: manual/); - assert.match(publish, /dependsOn: Release/); - assert.match(publish, /^ {8}lockBehavior: sequential$/m); - assert.match(publish, /eq\(dependencies\.Release\.result, 'Succeeded'\)/); - assert.match(publish, /eq\(dependencies\.Release\.outputs\['VerifyRelease\.verification\.ArtifactVerified'\], 'true'\)/); - assert.match(publish, /eq\(variables\['Build\.Reason'\], 'Manual'\)/); - assert.match(publish, /eq\(variables\['Build\.SourceBranch'\], 'refs\/heads\/hotfix\/v1\.23123'\)/); - assert.match(publish, /stageDependencies\.Release\.BuildRelease\.outputs\['manifest\.ManifestSha256'\]/); - assert.match(publish, /stageDependencies\.Release\.BuildRelease\.outputs\['manifest\.SourceSha'\]/); - assert.match(publish, /buildType: current/); - assert.match(publish, /steps:\s+- checkout: none\s+- template: .*npm-verify-release\.steps\.yml[\s\S]+npmAuthenticate@0/); - assert.match(publish, /workloadIdentityServiceConnection: 21d5a1d8-11d3-425c-8d3a-e7f088725481/); - assert.doesNotMatch(publish, /build-release-artifact|npm (?:install|ci)|System\.AccessToken/); - // The verifier restates the cohort independently of the producer; it must still name the same nine packages in order. - const listed = /packages = \[([^\]]+)\]/.exec(verifier)[1].match(/'[^']+'/g).map(name => `@microsoft/${name.slice(1, -1)}`); - assert.deepEqual(listed, COHORT.map(item => item.name)); -}); - -test('inline verifiers accept the same-run artifact and reject changed bytes, wrong runs and unexpected entries', () => { - const { dir } = artifactFixture(releaseProvenance); - const recorded = runPython(pipelineFile, { PACKAGE_OUTPUT: dir }); - assert.equal(recorded.status, 0, recorded.stderr); - const outputs = Object.fromEntries([...recorded.stdout.matchAll(/variable=(\w+);isOutput=true\](\S+)/g)].map(match => match.slice(1))); - const manifestBytes = fs.readFileSync(path.join(dir, 'publisher-artifact.json')); - assert.deepEqual(outputs, { ManifestSha256: crypto.createHash('sha256').update(manifestBytes).digest('hex'), SourceSha: commitSha }); - - const env = { ARTIFACT_DIR: dir, RELEASE_VERSION: releaseVersion, BUILD_ID: releaseEnv.BUILD_ID, RECIPE_SHA: recipeSha, - SOURCE_SHA: outputs.SourceSha, EXPECTED_MANIFEST_SHA256: outputs.ManifestSha256 }; - const verify = (overrides = {}) => runPython(verifierFile, { ...env, PREPARE_WRITER: 'false', ...overrides }); - const good = verify(); - assert.equal(good.status, 0, good.stderr); - assert.match(good.stdout, /Verified nine packages for v5\.1022\.0/); - - // 1ES stages a reserved _manifest/ SBOM directory beside the payload; only a real directory is tolerated. - fs.mkdirSync(path.join(dir, '_manifest')); - fs.writeFileSync(path.join(dir, '_manifest', 'manifest.json'), '{}'); - assert.equal(verify().status, 0); - - const rejects = (overrides, message) => { - const result = verify(overrides); - assert.notEqual(result.status, 0); - assert.match(result.stderr, message); - }; - rejects({ BUILD_ID: '192333968' }, /does not match this run/); - rejects({ RECIPE_SHA: commitSha }, /does not match this run/); - rejects({ SOURCE_SHA: recipeSha }, /does not match this run/); - rejects({ RELEASE_VERSION: '5.1023.0' }, /exactly the nine tarballs/); - rejects({ RELEASE_VERSION: 'v5.1022.0' }, /Invalid releaseVersion/); - rejects({ EXPECTED_MANIFEST_SHA256: '0'.repeat(64) }, /digest does not match/); - rejects({ EXPECTED_MANIFEST_SHA256: '' }, /digest is missing/); - const manifestPath = path.join(dir, 'publisher-artifact.json'); - const wrongRef = JSON.parse(manifestBytes); - wrongRef.source.releaseRef = 'refs/tags/v5.1023.0'; - const wrongRefBytes = JSON.stringify(wrongRef); - fs.writeFileSync(manifestPath, wrongRefBytes); - rejects({ EXPECTED_MANIFEST_SHA256: crypto.createHash('sha256').update(wrongRefBytes).digest('hex') }, /Manifest provenance/); - fs.writeFileSync(manifestPath, manifestBytes); - - const tarball = path.join(dir, `microsoft-designer-ui-v2-${version}.tgz`); - const original = fs.readFileSync(tarball); - fs.writeFileSync(tarball, Buffer.concat([original, Buffer.from([0])])); - rejects({}, /identity or integrity mismatch/); - fs.writeFileSync(tarball, original); - assert.equal(verify().status, 0); - - fs.writeFileSync(path.join(dir, 'extra.tgz'), ''); - rejects({}, /exactly the nine tarballs/); - fs.rmSync(path.join(dir, 'extra.tgz')); - - fs.rmSync(path.join(dir, '_manifest'), { recursive: true }); - fs.writeFileSync(path.join(dir, '_manifest'), ''); - rejects({}, /Reserved _manifest entry is not a directory/); - fs.rmSync(path.join(dir, '_manifest')); - fs.symlinkSync(os.tmpdir(), path.join(dir, '_manifest')); - rejects({}, /Reserved _manifest entry is not a directory/); - fs.rmSync(path.join(dir, '_manifest')); - - // A symlinked payload is refused even when it points at identical bytes. - const outside = path.join(workspace(), 'outside.tgz'); - fs.writeFileSync(outside, original); - fs.rmSync(tarball); - fs.symlinkSync(outside, tarball); - rejects({}, /not a regular file/); -}); - -const writerRegistry = 'https://pkgs.dev.azure.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/'; -const legacyWriterRegistry = 'https://msazure.pkgs.visualstudio.com/One/_packaging/microsoft-logic-apps/npm/registry/'; -const testTokenLine = `//${new URL(writerRegistry).host}${new URL(writerRegistry).pathname}:_authToken=fixture-only`; - -function writerAttachment(name, registry = writerRegistry) { - return `${registry}${name}/-/${name.split('/')[1]}-${version}.tgz`; -} - -function writerFixture() { - const { dir, record } = artifactFixture(releaseProvenance); - const scratch = workspace(); - const cwd = path.join(scratch, 'writer'); - const manifest = fs.readFileSync(path.join(dir, 'publisher-artifact.json')); - const prepare = (writerDir = cwd) => runPython(verifierFile, { - ARTIFACT_DIR: dir, RELEASE_VERSION: releaseVersion, BUILD_ID: releaseEnv.BUILD_ID, RECIPE_SHA: recipeSha, - SOURCE_SHA: commitSha, EXPECTED_MANIFEST_SHA256: crypto.createHash('sha256').update(manifest).digest('hex'), - PREPARE_WRITER: 'true', WRITER_DIR: writerDir, REGISTRY: writerRegistry, - }); - const interpreter = spawnSync('python3', ['-I', '-c', 'import sys; print(sys.executable)'], { encoding: 'utf8' }); - assert.equal(interpreter.status, 0, interpreter.stderr); - const executable = interpreter.stdout.trim(); - const statePath = path.join(scratch, 'registry.json'); - const callsPath = path.join(scratch, 'calls.jsonl'); - const state = Object.fromEntries(record.packages.map(entry => [entry.name, { - ...entry, latest: previousVersion, previousVersion, tarball: writerAttachment(entry.name), - }])); - // No real npm on PATH, even if the writer asks for an unexpected command. - fs.writeFileSync(path.join(scratch, 'npm'), `#!${executable} -import json, os, pathlib, shutil, sys -root = pathlib.Path(__file__).resolve().parent -args = sys.argv[1:] -command, target = args[:2] -def flag(name): - return args[args.index(name) + 1] -assert flag('--registry') == ${JSON.stringify(writerRegistry)} -assert '--ignore-scripts' in args and flag('--globalconfig') == '/dev/null' -assert command == 'publish' or '--prefer-online' in args -assert pathlib.Path(flag('--userconfig')).resolve() == pathlib.Path.cwd() / '.npmrc' -assert 'SYSTEM_ACCESSTOKEN' not in os.environ and 'NPM_CONFIG_REGISTRY' not in os.environ -state_path = root / 'registry.json' -state = json.loads(state_path.read_text()) -if command == 'publish': - name = next(n for n, e in state.items() if e['file'] == pathlib.Path(target).name) -elif command == 'pack': - name = next(n for n, e in state.items() - if target == flag('--registry') + n + '/-/' + n.split('/')[1] + '-' + e['version'] + '.tgz') -else: - name = '@' + target[1:].partition('@')[0] -entry = state[name] -version = entry['version'] -with (root / 'calls.jsonl').open('a') as log: - log.write(json.dumps([command, name, flag('--cache')]) + '\\n') -if command == 'view' and target == name: - if entry.get('metadata') == 'unavailable': - print('untrusted npm output fixture-only', file=sys.stderr) - sys.exit(1) - if entry.get('metadata') == 'malformed': - print('{"dist-tags":') - sys.exit(0) - latest = entry['latest'] - versions = sorted({entry['previousVersion'], latest} | ({version} if entry.get('present') else set()) | set(entry.get('extraVersions', []))) - print(json.dumps({'name': name, 'version': latest, 'versions': versions, 'dist-tags': {'latest': latest}})) -elif command == 'view' and target == name + '@' + version: - assert args[2:6] == ['name', 'version', 'dist.integrity', 'dist.tarball'] - print(json.dumps({'name': name, 'version': version, 'dist.integrity': entry.get('registryIntegrity', entry['integrity']), - 'dist.tarball': entry['tarball']})) -elif command == 'publish': - assert flag('--tag') == 'latest' and target.startswith('./') - assert not entry.get('present') - if not entry.get('dropWrite'): - entry.update({'present': True, 'latest': version}) - if entry.get('moveLatestFor'): - other = state[entry['moveLatestFor']] - other['latest'] = other['previousVersion'] - state_path.write_text(json.dumps(state)) - sys.exit(1 if entry.get('nonzeroWrite') else 0) -elif command == 'pack': - dest = pathlib.Path(flag('--pack-destination')) / entry['file'] - if entry.get('wrongBytes'): - dest.write_bytes(b'not the published attachment') - else: - shutil.copyfile(entry['file'], dest) -else: - sys.exit(13) -`, { mode: 0o700 }); - return { - dir, cwd, prepare, state, record, - run() { - fs.writeFileSync(statePath, JSON.stringify(state)); - fs.writeFileSync(callsPath, ''); - const result = runPython(pipelineFile, { PATH: scratch, DIR: cwd, REGISTRY: writerRegistry, RELEASE_VERSION: releaseVersion, - SYSTEM_ACCESSTOKEN: 'not-for-npm', NPM_CONFIG_REGISTRY: 'https://not-the-feed.invalid/' }, - { executable, cwd, index: 1 }); - const calls = fs.readFileSync(callsPath, 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line)); - const persisted = JSON.parse(fs.readFileSync(statePath, 'utf8')); - Object.assign(state, persisted); - return { ...result, calls, writes: calls.filter(([command]) => command === 'publish').map(([, name]) => name) }; - }, - }; -} - -function prepareWriter(fixture, authenticate = true) { - const prepared = fixture.prepare(); - assert.equal(prepared.status, 0, prepared.stderr); - if (authenticate) fs.appendFileSync(path.join(fixture.cwd, '.npmrc'), `${testTokenLine}\n`); -} - -test('writer copies only verified bytes to private scratch and will not use a missing WIF token', () => { - const fixture = writerFixture(); - prepareWriter(fixture, false); - assert.equal(fs.statSync(fixture.cwd).mode & 0o777, 0o700); - const { file } = fixture.record.packages[0]; - const original = fs.readFileSync(path.join(fixture.dir, file)); - fs.writeFileSync(path.join(fixture.dir, file), 'tampered'); - assert.deepEqual(fs.readFileSync(path.join(fixture.cwd, file)), original); - const tampered = fixture.prepare(path.join(workspace(), 'writer')); - assert.notEqual(tampered.status, 0); - assert.match(tampered.stderr, /identity or integrity mismatch/); - const result = fixture.run(); - assert.notEqual(result.status, 0); - assert.deepEqual(result.calls, []); -}); - -test('writer preflights the full cohort, reads back every publication and makes an exact retry a no-op', () => { - const fixture = writerFixture(); - prepareWriter(fixture); - const names = fixture.record.packages.map(item => item.name); - fixture.state[names[0]].tarball = writerAttachment(names[0], legacyWriterRegistry); - fixture.state[names[1]].tarball = writerAttachment(names[1]).replace('@microsoft/', '%40microsoft%2f'); - const result = fixture.run(); - assert.equal(result.status, 0, result.stderr); - const firstWrite = result.calls.findIndex(([command]) => command === 'publish'); - assert.deepEqual([...new Set(result.calls.slice(0, firstWrite).map(([, name]) => name))], names); - assert.deepEqual(result.writes, names); - const packs = result.calls.filter(([command]) => command === 'pack'); - assert.deepEqual(packs.map(([, name]) => name), names); - assert.equal(new Set(packs.map(([, , cache]) => cache)).size, 9); - assert.ok(packs.every(([, , cache]) => !result.calls.some(([command, , writeCache]) => command === 'publish' && cache === writeCache))); - const retry = fixture.run(); - assert.equal(retry.status, 0, retry.stderr); - assert.deepEqual(retry.writes, []); - assert.deepEqual(retry.calls.filter(([command]) => command === 'pack').map(([, name]) => name), names); -}); - -test('a changed private tarball blocks publishing the entire cohort', () => { - const fixture = writerFixture(); - prepareWriter(fixture); - const privateTarball = path.join(fixture.cwd, fixture.record.packages.at(-1).file); - fs.chmodSync(privateTarball, 0o600); - fs.appendFileSync(privateTarball, 'changed'); - const result = fixture.run(); - assert.notEqual(result.status, 0); - assert.match(result.stderr, /does not match the verified artifact/); - assert.deepEqual(result.writes, []); -}); - -test('the last package blocks all writes if latest is newer, bytes conflict, or registry reads are inconclusive', () => { - const fixture = writerFixture(); - prepareWriter(fixture); - const name = fixture.record.packages.at(-1).name; - const defaults = fixture.state[name]; - for (const change of [ - { latest: '5.1023.0' }, - { extraVersions: [`${version}+ambiguous`] }, - { present: true, latest: version, registryIntegrity: 'sha512-conflicting' }, - { present: true, latest: version, wrongBytes: true }, - { present: true }, - { metadata: 'unavailable' }, - { metadata: 'malformed' }, - ]) { - fixture.state[name] = { ...defaults, ...change }; - const result = fixture.run(); - assert.notEqual(result.status, 0, JSON.stringify(change)); - assert.deepEqual(result.writes, []); - assert.doesNotMatch(result.stderr + result.stdout, /fixture-only/); - } -}); - -test('writer rejects attachments outside the exact feed, package and version before packing or writing', () => { - const fixture = writerFixture(); - prepareWriter(fixture); - const { name } = fixture.record.packages.at(-1); - const approved = writerAttachment(name); - const otherName = fixture.record.packages[0].name; - Object.assign(fixture.state[name], { present: true, latest: version }); - for (const tarball of [ - null, - approved.replace('https:', 'http:'), - approved.replace('pkgs.dev.azure.com', 'other.invalid'), - approved.replace('/One/_packaging/', '/other/_packaging/'), - approved.replace('/microsoft-logic-apps/', '/other-feed/'), - writerAttachment(otherName), - approved.replace(`-${version}.tgz`, `-${previousVersion}.tgz`), - `${approved}?unexpected=1`, - ]) { - fixture.state[name].tarball = tarball; - const result = fixture.run(); - assert.notEqual(result.status, 0); - assert.match(result.stderr, /Unapproved registry attachment/); - assert.ok(result.calls.every(([command]) => command === 'view')); - } -}); - -test('writer reconciles a nonzero response with exact bytes, stops on an unproved result and resumes safely', () => { - const fixture = writerFixture(); - prepareWriter(fixture); - const [first, second, ...rest] = fixture.record.packages.map(item => item.name); - fixture.state[first].nonzeroWrite = true; - fixture.state[second].dropWrite = true; - const result = fixture.run(); - assert.notEqual(result.status, 0); - assert.deepEqual(result.writes, [first, second]); - assert.ok(result.calls.some(([command, name]) => command === 'pack' && name === first)); - fixture.state[second].dropWrite = false; - const retry = fixture.run(); - assert.equal(retry.status, 0, retry.stderr); - assert.deepEqual(retry.writes, [second, ...rest]); -}); - -test('writer stops after the first publish when registry readback differs despite matching metadata', () => { - const fixture = writerFixture(); - prepareWriter(fixture); - const [first] = fixture.record.packages; - fixture.state[first.name].wrongBytes = true; - const result = fixture.run(); - assert.notEqual(result.status, 0); - assert.deepEqual(result.writes, [first.name]); - assert.ok(result.calls.some(([command, name]) => command === 'pack' && name === first.name)); -}); - -test('writer fails if an earlier package is no longer latest at the end of publication', () => { - const fixture = writerFixture(); - prepareWriter(fixture); - const names = fixture.record.packages.map(item => item.name); - fixture.state[names.at(-1)].moveLatestFor = names[0]; - const result = fixture.run(); - assert.notEqual(result.status, 0); - assert.deepEqual(result.writes, names); - assert.match(result.stderr, /Final registry latest is not/); -}); - -test('accepts only canonical ASCII stable releaseVersion', () => { - assert.equal(parseReleaseVersion(releaseVersion), releaseVersion); - for (const value of ['v5.1022.0', '5.01022.0', '5.1022.00', '5.1022.0', '5.1022.0\n', '5.1022.0 ', '5.1022', '', undefined]) { - assert.throws(() => parseReleaseVersion(value), /Invalid releaseVersion/); - } -}); - -test('release runs must be manual, from this repository, with a numeric build ID, recipe SHA and canonical version', () => { - assert.deepEqual(releaseRunSource(releaseEnv), { - version: releaseVersion, - releaseTag: 'v5.1022.0', - releaseRef, - buildId: releaseEnv.BUILD_ID, - recipeSha, - }); - assert.equal(releaseRunSource({ ...releaseEnv, RECIPE_SHA: recipeSha.toUpperCase() }).recipeSha, recipeSha); - for (const [override, message] of [[{ BUILD_REASON: 'IndividualCI' }, /queued manually/], [{ SOURCE_REPOSITORY: 'fork/LogicAppsUX' }, /LogicAppsUX GitHub repository/], - [{ RELEASE_VERSION: '' }, /Invalid releaseVersion/], [{ BUILD_ID: '0' }, /build ID/], [{ BUILD_ID: '$(Build.BuildId)' }, /build ID/], [{ RECIPE_SHA: 'abc' }, /40-character/]]) { - assert.throws(() => releaseRunSource({ ...releaseEnv, ...override }), message); - } -}); - -test('release URL resolution peels the annotated tag and never reads assets or latest', async () => { - const api = releaseApi(); - const resolved = await resolveReleaseMetadata({ releaseRef, fetchImpl: api.fetchImpl }); - assert.deepEqual(resolved, { sourceRepository: 'Azure/LogicAppsUX', releaseTag: 'v5.1022.0', version, commitSha, releaseId: 7, releaseUrl }); - assert.deepEqual(api.calls, ['releases/tags/v5.1022.0', 'git/ref/tags/v5.1022.0', `git/tags/${api.tagObject}`, `git/commits/${commitSha}`]); - for (const change of [{ draft: true }, { prerelease: true }, { tag_name: 'v5.1023.0' }, { published_at: null }, { id: 0 }]) { - Object.assign(api.release, { draft: false, prerelease: false, tag_name: 'v5.1022.0', published_at: '2026-11-18T16:55:54Z', id: 7 }, change); - await assert.rejects(resolveReleaseMetadata({ releaseRef, fetchImpl: api.fetchImpl }), /not a verified published stable release/); - } - const missing = releaseApi(); - missing.responses.delete('releases/tags/v5.1022.0'); - await assert.rejects(resolveReleaseMetadata({ releaseRef, fetchImpl: missing.fetchImpl }), /unexpected HTTP 404/); -}); - -// Hosted runs failed on the post-build re-read; release reads are single-use, redirect-refusing and report sanitized causes only. -test('release reads close each connection, refuse redirects and sanitize failures without retrying', async () => { - const api = releaseApi(); - const inits = []; - await resolveReleaseMetadata({ releaseRef, fetchImpl: async (url, options) => { inits.push(options); return api.fetchImpl(url); } }); - assert.equal(inits.length, 4); - for (const init of inits) { - assert.equal(init.redirect, 'manual'); - assert.equal(init.headers.connection, 'close'); - assert.equal(init.headers.authorization, undefined); - assert(init.signal instanceof AbortSignal); - } - assert.equal(inits[0].headers.accept, 'application/vnd.github+json'); - const secretUrl = 'https://api.github.com/repos/Azure/LogicAppsUX/releases/tags/v5.1022.0?leak'; - const attempt = async (impl, pattern) => { - let calls = 0; - const error = await fetchReleaseJson(secretUrl, async (...args) => { calls++; return impl(...args); }, undefined, 'Probe') - .then(() => assert.fail('expected rejection'), err => err); - assert.match(error.message, pattern); - assert.doesNotMatch(error.message, /leak|https?:|api\.github|location|example/i); - assert.equal(calls, 1); - }; - const redirect = status => async () => ({ status, redirected: false, headers: new Map([['location', 'https://example.test/leak']]), text: async () => '' }); - for (const status of [0, 301, 302, 307, 308]) await attempt(redirect(status), new RegExp(`^Probe: refused redirect \\(HTTP ${status}\\)\\.$`)); - await attempt(async () => json({}, 200, true), /^Probe: refused redirect \(HTTP 200\)\.$/); - for (const status of [403, 404, 429, 500]) await attempt(async () => json({}, status), new RegExp(`^Probe: unexpected HTTP ${status}\\.$`)); - await attempt(async () => { throw new DOMException('signal timed out https://leak', 'TimeoutError'); }, /^Probe: timeout\.$/); - await attempt(async () => { throw new DOMException('aborted https://leak', 'AbortError'); }, /^Probe: timeout\.$/); - for (const code of ['ECONNRESET', 'ENOTFOUND', 'UND_ERR_SOCKET', 'UND_ERR_HEADERS_TIMEOUT', 'CERT_HAS_EXPIRED']) { - await attempt(async () => { throw new TypeError('fetch failed https://leak', { cause: Object.assign(new Error('leak'), { code }) }); }, - new RegExp(`^Probe: transport failure \\(${code}\\)\\.$`)); - } - await attempt(async () => { throw new TypeError('fetch failed', { cause: Object.assign(new Error('x'), { code: 'leak https://x' }) }); }, /^Probe: transport failure\.$/); - await attempt(async () => { throw Object.assign(new Error('Probe: unexpected HTTP 200 leak'), { sanitized: true }); }, /^Probe: transport failure\.$/); - await attempt(async () => ({ status: 200, redirected: false, text: async () => { throw new TypeError('terminated', { cause: { code: 'UND_ERR_SOCKET' } }); } }), - /^Probe: transport failure \(UND_ERR_SOCKET\)\.$/); - await attempt(async () => ({ status: 200, redirected: false, text: async () => '{bad' }), /^Probe: invalid JSON\.$/); -}); - -// Builds from a local repository checkout: no network source fetch is available to this path. -function releaseBuild({ repo, env: overrides = {}, failBuild = false }) { - const tmp = workspace(); - const env = { ...releaseEnv, RECIPE_SHA: gitFixture(repo, 'rev-parse', 'HEAD'), ...overrides, - AGENT_TMP: tmp, ARTIFACT_ROOT: path.join(tmp, 'out'), PATH: process.env.PATH }; - const sourceRoot = path.join(overrides.RELEASE_SCAN_ROOT ?? tmp, 'release-source'); - const calls = []; - const run = (command, args, { cwd }) => { - assert.equal(cwd, sourceRoot); - if (calls.length === 0) { - assert.equal(fs.readFileSync(path.join(cwd, 'release-source.txt'), 'utf8'), 'tagged bytes\n'); - assert.equal(gitFixture(cwd, 'rev-parse', 'HEAD'), gitFixture(repo, 'rev-parse', `${releaseRef}^{commit}`)); - fs.mkdirSync(path.join(cwd, 'node_modules')); - fs.writeFileSync(path.join(cwd, 'node_modules', '.modules.yaml'), 'fixture dependency metadata\n'); - } - calls.push(args); - if (failBuild && args.includes('build:lib')) { - return { status: 1, stdout: '', stderr: '' }; - } - if (command === process.execPath) { - for (const item of COHORT) { - const file = path.join(sourceRoot, item.directory, 'package.json'); - fs.writeFileSync(file, JSON.stringify({ ...JSON.parse(fs.readFileSync(file, 'utf8')), version })); - } - } - const packIndex = args.indexOf('pack'); - if (packIndex > 0) { - const item = COHORT.find(entry => path.join(sourceRoot, entry.directory) === args[packIndex - 1]); - fs.writeFileSync(path.join(env.ARTIFACT_ROOT, `${item.name.slice(1).replace('/', '-')}-${version}.tgz`), fixture(item).pack()); - } - return { status: 0, stdout: '', stderr: '' }; - }; - const logs = []; - const result = buildReleaseArtifact(env, text => logs.push(text), { run, recipeRoot: repo, sandbox: (e, p, build) => build(undefined) }); - return { result, logs, calls, env }; -} - -test('release build uses the annotated tag bytes rather than the recipe and verifies the nine tarballs with run provenance', async () => { - const { repo, sha } = releaseRepoFixture(); - const marker = path.join(repo, 'release-source.txt'); - fs.writeFileSync(marker, 'updated recipe bytes\n'); - gitFixture(repo, 'add', 'release-source.txt'); - gitFixture(repo, 'commit', '--quiet', '-m', 'recipe'); - const recipeHead = gitFixture(repo, 'rev-parse', 'HEAD'); - assert.notEqual(recipeHead, sha); - gitFixture(repo, 'remote', 'add', 'origin', path.join(repo, 'no-remote')); - - const { result, logs, calls, env } = releaseBuild({ repo }); - const artifact = await result; - assert.deepEqual(artifact.source, { repository: 'Azure/LogicAppsUX', releaseRef, verifiedSha: sha, version, buildId: env.BUILD_ID, recipeSha: recipeHead }); - assert.deepEqual(artifact.packages.map(entry => entry.name), COHORT.map(item => item.name)); - assert.match(logs[0], /Resolved refs\/tags\/v5\.1022\.0 to [0-9a-f]{40}; packing has not started/); - assert.match(logs.at(-1), /Packed and validated 9 release tarballs .*publication was not attempted/); - assert.equal(calls.filter(args => args.includes('pack')).length, 9); - assert.equal(fs.existsSync(path.join(env.AGENT_TMP, 'release-source')), false); - assert.equal(fs.readFileSync(marker, 'utf8'), 'updated recipe bytes\n'); - // The manifest goes through the inline verifier exactly as the hosted consumer job would see it. - const manifestPath = path.join(env.ARTIFACT_ROOT, 'publisher-artifact.json'); - const verify = runPython(verifierFile, { ARTIFACT_DIR: env.ARTIFACT_ROOT, RELEASE_VERSION: releaseVersion, BUILD_ID: env.BUILD_ID, - RECIPE_SHA: recipeHead, SOURCE_SHA: sha, PREPARE_WRITER: 'false', - EXPECTED_MANIFEST_SHA256: crypto.createHash('sha256').update(fs.readFileSync(manifestPath)).digest('hex') }); - assert.equal(verify.status, 0, verify.stderr); -}); - -test('hosted release keeps the exact tagged worktree and restores tracked manifests for Component Governance', async () => { - const { repo, sha } = releaseRepoFixture(); - const scanRoot = workspace(); - const { result, logs } = releaseBuild({ repo, env: { RELEASE_SCAN_ROOT: scanRoot } }); - assert.equal((await result).source.verifiedSha, sha); - const sourceRoot = path.join(scanRoot, 'release-source'); - assert.equal(gitFixture(sourceRoot, 'rev-parse', 'HEAD'), sha); - assert.equal(gitFixture(sourceRoot, 'status', '--porcelain', '--untracked-files=no'), ''); - assert.equal(fs.readFileSync(path.join(sourceRoot, 'node_modules', '.modules.yaml'), 'utf8'), 'fixture dependency metadata\n'); - assert.match(logs.at(-1), /Retaining tagged source .* for Component Governance/); -}); - -test('failed hosted release cleans the scan worktree', async () => { - const { repo } = releaseRepoFixture(); - const scanRoot = workspace(); - const { result } = releaseBuild({ repo, env: { RELEASE_SCAN_ROOT: scanRoot }, failBuild: true }); - await assert.rejects(result, /corepack failed: exit 1/); - assert.equal(fs.existsSync(path.join(scanRoot, 'release-source')), false); -}); - -test('release build accepts a lightweight local tag without GitHub API access', async (t) => { - const { repo, sha } = releaseRepoFixture({ tagType: 'lightweight' }); - const fetchCall = t.mock.method(globalThis, 'fetch', () => { throw new Error('unexpected network'); }); - const artifact = await releaseBuild({ repo }).result; - assert.equal(artifact.source.verifiedSha, sha); - assert.equal(fetchCall.mock.callCount(), 0); -}); - -test('release build fails before packaging without a valid version, recipe checkout and exact commit tag', async () => { - const missing = releaseRepoFixture({ tagType: 'none' }); - gitFixture(missing.repo, 'branch', releaseRef); - const noncommit = releaseRepoFixture({ tagType: 'noncommit' }); - for (const [repo, overrides, error] of [ - [missing.repo, { RELEASE_VERSION: '5.1022.0-beta.1' }, /Invalid releaseVersion/], - [missing.repo, { RECIPE_SHA: recipeSha }, /does not match expectedSha/], - [missing.repo, {}, /missing from the local checkout/], - [noncommit.repo, {}, /must peel to a commit/], - ]) { - const { result, calls, env } = releaseBuild({ repo, env: overrides }); - await assert.rejects(result, error); - assert.deepEqual(calls, []); - assert.equal(fs.existsSync(env.ARTIFACT_ROOT), false); + throw new Error(`Unexpected command: ${cmd} ${args.join(' ')}`); + }; + + const result = publishRelease( + { + RELEASE_VERSION: version, + TARBALL_DIR: tarballDir, + PUBLISH_NPMRC: npmrc, + NPM_REGISTRY: DEFAULT_REGISTRY, + }, + { run, log: msg => logs.push(msg) } + ); + + assert.deepEqual(result, { version, published: 6, skipped: 3 }); + + const viewCalls = calls.filter(c => c.args[0] === 'view'); + const publishCalls = calls.filter(c => c.args[0] === 'publish'); + + // Exactly one pre-publish view per package (no post-publish view or pack readback) + assert.equal(viewCalls.length, PACKAGES.length); + assert.equal(publishCalls.length, PACKAGES.length - alreadyInFeed.size); + assert.equal(calls.filter(c => c.args[0] === 'pack').length, 0); + + // Every publish call uses --tag latest and normal visible stdout/stderr (stdio: 'inherit') + for (const call of publishCalls) { + assert.equal(call.stdio, 'inherit'); + assert.ok(call.args.includes('--tag')); + assert.equal(call.args[call.args.indexOf('--tag') + 1], 'latest'); + assert.equal(call.args[call.args.indexOf('--registry') + 1], DEFAULT_REGISTRY); + assert.equal(call.args[call.args.indexOf('--userconfig') + 1], npmrc); + } +}); + +test('publishRelease fails clearly when npm publish exits non-zero or files are missing', () => { + const version = '5.1024.0'; + const tarballDir = createTempDir('tarballs-fail-'); + const npmrc = path.join(createTempDir('npmrc-fail-'), '.npmrc'); + fs.writeFileSync(npmrc, `registry=${DEFAULT_REGISTRY}\n`); + + // Missing tarball + assert.throws( + () => publishRelease({ RELEASE_VERSION: version, TARBALL_DIR: tarballDir, PUBLISH_NPMRC: npmrc }), + /Missing tarball/ + ); + + // Missing .npmrc + assert.throws( + () => publishRelease({ RELEASE_VERSION: version, TARBALL_DIR: tarballDir, PUBLISH_NPMRC: '/nonexistent/.npmrc' }), + /Authenticated \.npmrc file does not exist/ + ); + + // npm publish failure stops immediately + for (const pkg of PACKAGES) { + fs.writeFileSync(path.join(tarballDir, tarballName(pkg.name, version)), 'tgz-bytes'); + } + const run = (cmd, args) => { + if (cmd === 'npm' && args[0] === 'view') { + return { status: 0, stdout: '', stderr: '' }; } + return { status: 1 }; + }; + assert.throws( + () => publishRelease({ RELEASE_VERSION: version, TARBALL_DIR: tarballDir, PUBLISH_NPMRC: npmrc }, { run, log: () => {} }), + /npm publish failed \(exit 1\)/ + ); +}); + +test('main validates command arguments', () => { + assert.throws(() => main(['unknown']), /Unknown command/); + assert.throws(() => main(['build', 'extra']), /Unexpected arguments/); +}); + +test('npm-publish.yml keeps 1ES Official template, WIF auth, and single Publish stage', () => { + const yaml = fs.readFileSync(path.join(__dirname, '..', '.azure-pipelines', 'npm-publish.yml'), 'utf8'); + assert.match(yaml, /template:\s*v1\/1ES\.Official\.PipelineTemplate\.yml@1esPipelines/); + assert.match(yaml, /ref:\s*refs\/tags\/release/); + assert.match(yaml, /name:\s*Azure-Pipelines-1ESPT-ExDShared/); + assert.match(yaml, /useAgentBuildDirectory:\s*true/); + assert.match(yaml, /workloadIdentityServiceConnection:\s*21d5a1d8-11d3-425c-8d3a-e7f088725481/); + assert.match(yaml, /feedUrl:\s*'https:\/\/pkgs\.dev\.azure\.com\/msazure\/One\/_packaging\/microsoft-logic-apps\/npm\/registry\/'/); + assert.match(yaml, /condition:\s*succeeded\(\)/); + assert.match(yaml, /- stage:\s*Publish/); + assert.match(yaml, /- job:\s*BuildAndPublish/); + assert.doesNotMatch(yaml, /VerifyRelease|ProductionPublishNotActivated|npm-verify-release/); }); From cfc48e9f53d5a9950de4deb02c12c3d804ed5983 Mon Sep 17 00:00:00 2001 From: Krrish Mittal Date: Tue, 24 Nov 2026 19:33:16 -0800 Subject: [PATCH 2/2] chore(ci): restore main and hotfix branch condition on npm publish pipeline Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .azure-pipelines/npm-publish.yml | 2 +- scripts/ado-npm-publisher.test.cjs | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.azure-pipelines/npm-publish.yml b/.azure-pipelines/npm-publish.yml index 7a8730fad34..5b617b791b4 100644 --- a/.azure-pipelines/npm-publish.yml +++ b/.azure-pipelines/npm-publish.yml @@ -44,7 +44,7 @@ extends: - stage: Publish displayName: Build and publish npm packages lockBehavior: sequential - condition: succeeded() + condition: and(succeeded(), or(eq(variables['Build.SourceBranch'], 'refs/heads/main'), startsWith(variables['Build.SourceBranch'], 'refs/heads/hotfix/v'))) jobs: - job: BuildAndPublish displayName: Build release tag and publish to npm feed diff --git a/scripts/ado-npm-publisher.test.cjs b/scripts/ado-npm-publisher.test.cjs index f7b5421d5e6..6decf247efd 100644 --- a/scripts/ado-npm-publisher.test.cjs +++ b/scripts/ado-npm-publisher.test.cjs @@ -364,7 +364,7 @@ test('main validates command arguments', () => { assert.throws(() => main(['build', 'extra']), /Unexpected arguments/); }); -test('npm-publish.yml keeps 1ES Official template, WIF auth, and single Publish stage', () => { +test('npm-publish.yml keeps 1ES Official template, WIF auth, branch gate, and single Publish stage', () => { const yaml = fs.readFileSync(path.join(__dirname, '..', '.azure-pipelines', 'npm-publish.yml'), 'utf8'); assert.match(yaml, /template:\s*v1\/1ES\.Official\.PipelineTemplate\.yml@1esPipelines/); assert.match(yaml, /ref:\s*refs\/tags\/release/); @@ -372,7 +372,10 @@ test('npm-publish.yml keeps 1ES Official template, WIF auth, and single Publish assert.match(yaml, /useAgentBuildDirectory:\s*true/); assert.match(yaml, /workloadIdentityServiceConnection:\s*21d5a1d8-11d3-425c-8d3a-e7f088725481/); assert.match(yaml, /feedUrl:\s*'https:\/\/pkgs\.dev\.azure\.com\/msazure\/One\/_packaging\/microsoft-logic-apps\/npm\/registry\/'/); - assert.match(yaml, /condition:\s*succeeded\(\)/); + assert.match( + yaml, + /and\(succeeded\(\),\s*or\(eq\(variables\['Build\.SourceBranch'\],\s*'refs\/heads\/main'\),\s*startsWith\(variables\['Build\.SourceBranch'\],\s*'refs\/heads\/hotfix\/v'\)\)\)/ + ); assert.match(yaml, /- stage:\s*Publish/); assert.match(yaml, /- job:\s*BuildAndPublish/); assert.doesNotMatch(yaml, /VerifyRelease|ProductionPublishNotActivated|npm-verify-release/);