From a1d480911c4cb4da138115eb193bace552981030 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Sun, 22 Nov 2026 07:00:59 +0800 Subject: [PATCH 1/4] chore(ci): pin actions to commit SHAs and harden workflow permissions --- .../bootstrap-binance-account-facts.yml | 2 +- .../workflows/compare-console-versions.yml | 4 ++-- .../configure-ibkr-period-return.yml | 4 ++-- .../configure-ibkr-primary-daily-once.yml | 4 ++-- .../workflows/console-full-bundle-release.yml | 18 ++++++++--------- .../console-qrs-backend-candidate-release.yml | 20 +++++++++---------- .github/workflows/daily-digest-notify.yml | 14 ++++++------- .github/workflows/dependabot_auto_merge.yml | 3 +++ .../deploy-strategy-switch-console.yml | 18 ++++++++--------- .github/workflows/digest-bot-identity.yml | 4 ++-- .../digest-store-permission-check.yml | 6 +++--- .github/workflows/engineering-governance.yml | 2 +- .../workflows/hide-codex-limit-comments.yml | 5 ++++- .../notification-binding-read-check.yml | 6 +++--- .github/workflows/platform-health-monitor.yml | 8 ++++---- .../workflows/producer-receiver-contract.yml | 10 +++++----- .../workflows/publish-m0-research-ledger.yml | 6 +++--- .github/workflows/qsl_exception_lifecycle.yml | 4 ++-- .github/workflows/risk-gate.yml | 6 +++--- .../runtime-artifact-evidence-gate.yml | 8 ++++---- .github/workflows/sync-market-benchmark.yml | 4 ++-- .../sync-schwab-account-facts-binding.yml | 4 ++-- .github/workflows/tail-strategy-health.yml | 4 ++-- .github/workflows/validate.yml | 16 +++++++-------- .../verify-binance-account-facts-receiver.yml | 2 +- 25 files changed, 94 insertions(+), 88 deletions(-) diff --git a/.github/workflows/bootstrap-binance-account-facts.yml b/.github/workflows/bootstrap-binance-account-facts.yml index 15df7294..fb502d92 100644 --- a/.github/workflows/bootstrap-binance-account-facts.yml +++ b/.github/workflows/bootstrap-binance-account-facts.yml @@ -49,7 +49,7 @@ jobs: persist-credentials: false - name: Setup Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: "22" diff --git a/.github/workflows/compare-console-versions.yml b/.github/workflows/compare-console-versions.yml index 14e65290..18306cb4 100644 --- a/.github/workflows/compare-console-versions.yml +++ b/.github/workflows/compare-console-versions.yml @@ -32,10 +32,10 @@ jobs: timeout-minutes: 5 environment: runtime-strategy-switch steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: persist-credentials: false - - uses: actions/setup-node@v6 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: "22" - name: Compare bounded metadata diff --git a/.github/workflows/configure-ibkr-period-return.yml b/.github/workflows/configure-ibkr-period-return.yml index 2e442c99..9be6e51e 100644 --- a/.github/workflows/configure-ibkr-period-return.yml +++ b/.github/workflows/configure-ibkr-period-return.yml @@ -68,10 +68,10 @@ jobs: OVERWRITE: ${{ inputs.overwrite }} steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - name: Setup Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: "22" diff --git a/.github/workflows/configure-ibkr-primary-daily-once.yml b/.github/workflows/configure-ibkr-primary-daily-once.yml index 625bdb5c..87ab1704 100644 --- a/.github/workflows/configure-ibkr-primary-daily-once.yml +++ b/.github/workflows/configure-ibkr-primary-daily-once.yml @@ -84,8 +84,8 @@ jobs: fi - name: Require the first execution attempt run: test "$GITHUB_RUN_ATTEMPT" = 1 - - uses: actions/checkout@v6 - - uses: actions/setup-node@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: '22' - name: Mint short-lived GitHub App token diff --git a/.github/workflows/console-full-bundle-release.yml b/.github/workflows/console-full-bundle-release.yml index 15bfe6b5..28be3257 100644 --- a/.github/workflows/console-full-bundle-release.yml +++ b/.github/workflows/console-full-bundle-release.yml @@ -54,7 +54,7 @@ jobs: timeout-minutes: 30 steps: - name: Check out release adapter - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: persist-credentials: false fetch-depth: 0 @@ -68,21 +68,21 @@ jobs: [[ "$(git rev-parse HEAD)" == "$GITHUB_SHA" ]] [[ "$(git ls-remote origin refs/heads/main | cut -f1)" == "$GITHUB_SHA" ]] - name: Check out fixed frontend snapshot - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: ref: 0b5d9527313d719547ef844797b47158c83dea53 path: candidate-snapshot persist-credentials: false - name: Check out fixed recovery snapshot - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: ref: 85504dd6ee201fd358f6ea3489742ea5c47afcf8 path: recovery-snapshot persist-credentials: false - - uses: actions/setup-node@v6 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: '22' - - uses: actions/setup-python@v6 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.12' - name: Test release adapter @@ -126,7 +126,7 @@ jobs: run: node --test tests/console_named_export_surface.test.mjs - name: Preserve verified public bundles for the manual job if: github.event_name == 'workflow_dispatch' - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: console-fixed-complete-bundles path: | @@ -142,14 +142,14 @@ jobs: environment: runtime-strategy-switch steps: - name: Check out release adapter - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: persist-credentials: false - - uses: actions/setup-node@v6 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: '22' - name: Download verified public bundles - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: name: console-fixed-complete-bundles path: ${{ runner.temp }}/console-fixed-bundles diff --git a/.github/workflows/console-qrs-backend-candidate-release.yml b/.github/workflows/console-qrs-backend-candidate-release.yml index bb553897..5b2515d0 100644 --- a/.github/workflows/console-qrs-backend-candidate-release.yml +++ b/.github/workflows/console-qrs-backend-candidate-release.yml @@ -23,11 +23,11 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: persist-credentials: false fetch-depth: 0 - - uses: actions/setup-node@v6 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: '22' - name: Check reviewed control commit and prepare fixed module @@ -44,7 +44,7 @@ jobs: npx --yes wrangler@4.106.0 --version bash scripts/console_m09_offline_bundle.sh "$RUNNER_TEMP/qrs-backend-candidate" "$source" node scripts/console_m09_release.mjs verify-inputs "$RUNNER_TEMP/qrs-backend-candidate/worker.js" - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: console-fixed-backend-module path: ${{ runner.temp }}/qrs-backend-candidate/worker.js @@ -56,11 +56,11 @@ jobs: timeout-minutes: 5 environment: runtime-strategy-switch steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: persist-credentials: false fetch-depth: 0 - - uses: actions/setup-node@v6 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: '22' - name: Read fixed Worker state @@ -80,11 +80,11 @@ jobs: timeout-minutes: 10 environment: runtime-strategy-switch steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: persist-credentials: false fetch-depth: 0 - - uses: actions/setup-node@v6 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: '22' - name: Build the fixed candidate and check parser availability @@ -118,14 +118,14 @@ jobs: timeout-minutes: 10 environment: runtime-strategy-switch steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: persist-credentials: false fetch-depth: 0 - - uses: actions/setup-node@v6 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: '22' - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: name: console-fixed-backend-module path: ${{ runner.temp }}/qrs-backend-candidate diff --git a/.github/workflows/daily-digest-notify.yml b/.github/workflows/daily-digest-notify.yml index 3dac3429..590dd4de 100644 --- a/.github/workflows/daily-digest-notify.yml +++ b/.github/workflows/daily-digest-notify.yml @@ -127,12 +127,12 @@ jobs: exit 2 fi - - uses: actions/checkout@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 if: steps.schedule_slot.outputs.proceed == 'true' with: persist-credentials: false - - uses: actions/setup-python@v6 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 if: steps.schedule_slot.outputs.proceed == 'true' with: python-version: "3.12" @@ -251,14 +251,14 @@ jobs: id: candidates_gcp_auth if: ${{ steps.schedule_slot.outputs.proceed == 'true' && (steps.resend_guard.outputs.proceed == 'true' && steps.candidates.outputs.upstream_allowed == 'true' && env.DIGEST_CANDIDATES_GCS_URI != '') }} continue-on-error: true - uses: google-github-actions/auth@v3 + uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3 with: workload_identity_provider: ${{ env.DIGEST_CANDIDATES_READER_WIF_PROVIDER }} service_account: ${{ env.DIGEST_CANDIDATES_READER_SERVICE_ACCOUNT }} - name: Set up gcloud for producer candidates (optional) if: ${{ steps.schedule_slot.outputs.proceed == 'true' && (steps.resend_guard.outputs.proceed == 'true' && steps.candidates.outputs.upstream_allowed == 'true' && steps.candidates_gcp_auth.outcome == 'success') }} - uses: google-github-actions/setup-gcloud@v3 + uses: google-github-actions/setup-gcloud@aa5489c8933f4cc7a4f7d45035b3b1440c9c10db # v3 - name: Fetch producer candidates from private store (optional) id: candidates_fetch @@ -391,7 +391,7 @@ jobs: - name: Upload receipt artifact if: ${{ steps.schedule_slot.outputs.proceed == 'true' && (always()) }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: daily-digest-receipt path: data/output/daily-digest/receipt-public.json @@ -421,10 +421,10 @@ jobs: GH_TOKEN: ${{ secrets.RUNTIME_SETTINGS_GH_TOKEN || github.token }} DIGEST_GH_TOKEN: ${{ secrets.RUNTIME_SETTINGS_GH_TOKEN || github.token }} steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: persist-credentials: false - - uses: actions/setup-python@v6 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: "3.12" - name: Read once and print fixed public status diff --git a/.github/workflows/dependabot_auto_merge.yml b/.github/workflows/dependabot_auto_merge.yml index 78d052aa..9e5c48e9 100644 --- a/.github/workflows/dependabot_auto_merge.yml +++ b/.github/workflows/dependabot_auto_merge.yml @@ -5,6 +5,9 @@ name: Auto Merge Dependabot PR workflows: ["Validate"] types: [completed] +permissions: + contents: read + jobs: auto-merge: if: github.event.workflow_run.conclusion == 'success' && startsWith(github.event.workflow_run.head_branch, 'dependabot/') diff --git a/.github/workflows/deploy-strategy-switch-console.yml b/.github/workflows/deploy-strategy-switch-console.yml index 961c661c..632c1ced 100644 --- a/.github/workflows/deploy-strategy-switch-console.yml +++ b/.github/workflows/deploy-strategy-switch-console.yml @@ -111,11 +111,11 @@ jobs: timeout-minutes: 20 steps: - name: Checkout fixed backend release source - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - name: Setup Node.js for backend release - uses: actions/setup-node@v6 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: "22" - name: Build fixed backend release baseline @@ -170,11 +170,11 @@ jobs: timeout-minutes: 20 steps: - name: Checkout reviewed preflight source - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - name: Setup Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: "22" - name: Inspect active Worker module without writing @@ -238,7 +238,7 @@ jobs: EXTERNAL_FLOW_ENABLE: ${{ inputs.external_flow_enable }} steps: - name: Setup Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: "22" @@ -695,7 +695,7 @@ jobs: BINANCE_ACCOUNT_FACTS_HISTORY_BINDINGS_JSON: ${{ secrets.BINANCE_ACCOUNT_FACTS_HISTORY_BINDINGS_JSON || '[]' }} steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: fetch-depth: 0 @@ -1286,13 +1286,13 @@ jobs: printf 'Reviewed console source: %s tree: %s\n' "$RELEASE_SOURCE_SHA" "$expected_tree" - name: Setup Python - uses: actions/setup-python@v6 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: "3.12" - name: Setup Node.js if: ${{ !inputs.render_and_compare_only }} - uses: actions/setup-node@v6 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: "22" @@ -2572,7 +2572,7 @@ jobs: RELEASE_FRONTEND_ASSETS: ${{ inputs.release_frontend_assets }} steps: - name: Setup Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: "22" diff --git a/.github/workflows/digest-bot-identity.yml b/.github/workflows/digest-bot-identity.yml index e485fafc..30e2b8dc 100644 --- a/.github/workflows/digest-bot-identity.yml +++ b/.github/workflows/digest-bot-identity.yml @@ -25,10 +25,10 @@ jobs: # No new authentication or private vars injection in this diagnostic. DIAGNOSTIC_SM_AUTH_STATUS: unavailable steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: persist-credentials: false - - uses: actions/setup-python@v6 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: "3.12" - name: Observe the selected daily sender configuration diff --git a/.github/workflows/digest-store-permission-check.yml b/.github/workflows/digest-store-permission-check.yml index 7d30abb7..aafc51f5 100644 --- a/.github/workflows/digest-store-permission-check.yml +++ b/.github/workflows/digest-store-permission-check.yml @@ -23,7 +23,7 @@ jobs: DIGEST_STORE_PREFIX: digest-candidates/ steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - name: Require private infrastructure configuration shell: bash @@ -35,13 +35,13 @@ jobs: [ -n "${DIGEST_STORE_BUCKET:-}" ] || { echo "DIGEST_STORE_BUCKET is required" >&2; exit 2; } - name: Authenticate to Google Cloud - uses: google-github-actions/auth@v3 + uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3 with: workload_identity_provider: ${{ env.GCP_WORKLOAD_IDENTITY_PROVIDER }} service_account: ${{ env.GCP_WORKLOAD_IDENTITY_SERVICE_ACCOUNT }} - name: Set up gcloud - uses: google-github-actions/setup-gcloud@v3 + uses: google-github-actions/setup-gcloud@aa5489c8933f4cc7a4f7d45035b3b1440c9c10db # v3 - name: Probe digest store permissions (read-only) run: python3 python/scripts/digest_store_permission_check.py diff --git a/.github/workflows/engineering-governance.yml b/.github/workflows/engineering-governance.yml index 6da83ede..d72b888f 100644 --- a/.github/workflows/engineering-governance.yml +++ b/.github/workflows/engineering-governance.yml @@ -19,7 +19,7 @@ jobs: fetch-depth: 0 persist-credentials: false - name: Scan added commits with redacted findings - uses: Pigbibi/PrGovernance/pr-governance@ccda8de572d2893272b0137526ef3e2d45e5eee7 + uses: Pigbibi/PrGovernance/pr-governance@7fe2ee20a3ee144ea944619e1c56f7ed5edc9152 with: mode: scan diff --git a/.github/workflows/hide-codex-limit-comments.yml b/.github/workflows/hide-codex-limit-comments.yml index ed525b74..24960077 100644 --- a/.github/workflows/hide-codex-limit-comments.yml +++ b/.github/workflows/hide-codex-limit-comments.yml @@ -6,6 +6,9 @@ on: pull_request_review_comment: types: [created] +permissions: + contents: read + jobs: hide-comment: runs-on: ubuntu-latest @@ -23,7 +26,7 @@ jobs: pull-requests: write steps: - name: Minimize comment - uses: actions/github-script@v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 with: script: | const mutation = ` diff --git a/.github/workflows/notification-binding-read-check.yml b/.github/workflows/notification-binding-read-check.yml index aa104fd9..2b239ff4 100644 --- a/.github/workflows/notification-binding-read-check.yml +++ b/.github/workflows/notification-binding-read-check.yml @@ -41,17 +41,17 @@ jobs: BINDING_SELECTED_PLATFORM: ${{ inputs.selected_platform }} BINDING_SELECTED_IDENTITY_SHA256: ${{ inputs.selected_identity_sha256 }} steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: persist-credentials: false - - uses: actions/setup-python@v6 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: "3.12" - name: Emit anonymous configuration evidence only run: python3 python/scripts/check_notification_binding_read.py --out data/output/daily-digest/notification-binding-read.json - name: Preserve anonymous binding certificate if: ${{ always() }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: notification-binding-read-${{ github.run_id }} path: data/output/daily-digest/notification-binding-read.json diff --git a/.github/workflows/platform-health-monitor.yml b/.github/workflows/platform-health-monitor.yml index eeb88287..ca0934ae 100644 --- a/.github/workflows/platform-health-monitor.yml +++ b/.github/workflows/platform-health-monitor.yml @@ -24,13 +24,13 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 15 steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - - uses: actions/setup-python@v6 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: "3.12" - - uses: actions/setup-node@v6 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: "22" @@ -101,7 +101,7 @@ jobs: - name: Upload platform health report if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: platform-health-report path: data/output/platform-health/ diff --git a/.github/workflows/producer-receiver-contract.yml b/.github/workflows/producer-receiver-contract.yml index 992538fd..59693606 100644 --- a/.github/workflows/producer-receiver-contract.yml +++ b/.github/workflows/producer-receiver-contract.yml @@ -13,11 +13,11 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: persist-credentials: false - name: Checkout exact IBKR projection source - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: repository: QuantStrategyLab/InteractiveBrokersPlatform ref: bd5c1a12d9cd0df8dbd88c1eb8b058b7b849990f @@ -26,7 +26,7 @@ jobs: sparse-checkout: scripts/publish_account_facts_from_report.py sparse-checkout-cone-mode: false - name: Checkout exact Schwab projection source - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: repository: QuantStrategyLab/CharlesSchwabPlatform ref: 5b563ad3609eefd9cf431ead82d0f30c586645db @@ -34,10 +34,10 @@ jobs: persist-credentials: false sparse-checkout: scripts/publish_account_facts_from_reports.py sparse-checkout-cone-mode: false - - uses: actions/setup-node@v6 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: "22" - - uses: actions/setup-python@v6 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: "3.12" - name: Install existing receiver test runtime diff --git a/.github/workflows/publish-m0-research-ledger.yml b/.github/workflows/publish-m0-research-ledger.yml index 345a8907..9ff84c5c 100644 --- a/.github/workflows/publish-m0-research-ledger.yml +++ b/.github/workflows/publish-m0-research-ledger.yml @@ -41,10 +41,10 @@ jobs: QAR_RUN_ID: ${{ inputs.qar_run_id || '' }} steps: - name: Checkout publisher revision - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - name: Set up Python - uses: actions/setup-python@v6 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: "3.12" @@ -53,7 +53,7 @@ jobs: # it after this job. It is never available to the publishing step below. - name: Create scoped QAR artifact-reader token id: qar-artifact-reader - uses: actions/create-github-app-token@v3 + uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3 with: app-id: ${{ vars.QAR_ARTIFACT_READER_APP_ID }} private-key: ${{ secrets.QAR_ARTIFACT_READER_APP_PRIVATE_KEY }} diff --git a/.github/workflows/qsl_exception_lifecycle.yml b/.github/workflows/qsl_exception_lifecycle.yml index ad03ed1e..139bca9a 100644 --- a/.github/workflows/qsl_exception_lifecycle.yml +++ b/.github/workflows/qsl_exception_lifecycle.yml @@ -27,10 +27,10 @@ jobs: timeout-minutes: 15 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - name: Set up Python - uses: actions/setup-python@v6 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: "3.12" diff --git a/.github/workflows/risk-gate.yml b/.github/workflows/risk-gate.yml index 4fed3688..7f4c1e8a 100644 --- a/.github/workflows/risk-gate.yml +++ b/.github/workflows/risk-gate.yml @@ -20,7 +20,7 @@ on: # A merge made with GITHUB_TOKEN raises no push, and nothing raises an event # for a resolved review thread, so a sweep closes both gaps. schedule: - - cron: '17 */6 * * *' + - cron: '17 3 * * *' workflow_dispatch: inputs: pr_number: @@ -51,7 +51,7 @@ jobs: statuses: write steps: - name: Record label head - uses: Pigbibi/PrGovernance/pr-governance@ccda8de572d2893272b0137526ef3e2d45e5eee7 + uses: Pigbibi/PrGovernance/pr-governance@7fe2ee20a3ee144ea944619e1c56f7ed5edc9152 env: GOVERNANCE_OWNER_ID: ${{ vars.RISK_GATE_OWNER_ID }} GOVERNANCE_OWNER_LOGIN: ${{ vars.RISK_GATE_OWNER }} @@ -85,7 +85,7 @@ jobs: cancel-in-progress: true steps: - name: Evaluate - uses: Pigbibi/PrGovernance/pr-governance@ccda8de572d2893272b0137526ef3e2d45e5eee7 + uses: Pigbibi/PrGovernance/pr-governance@7fe2ee20a3ee144ea944619e1c56f7ed5edc9152 env: GOVERNANCE_OWNER_ID: ${{ vars.RISK_GATE_OWNER_ID }} GOVERNANCE_OWNER_LOGIN: ${{ vars.RISK_GATE_OWNER }} diff --git a/.github/workflows/runtime-artifact-evidence-gate.yml b/.github/workflows/runtime-artifact-evidence-gate.yml index 007a61c2..65c51782 100644 --- a/.github/workflows/runtime-artifact-evidence-gate.yml +++ b/.github/workflows/runtime-artifact-evidence-gate.yml @@ -25,9 +25,9 @@ jobs: GCP_WORKLOAD_IDENTITY_PROVIDER: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }} GCP_WORKLOAD_IDENTITY_SERVICE_ACCOUNT: ${{ secrets.GCP_WORKLOAD_IDENTITY_SERVICE_ACCOUNT }} steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - - uses: actions/setup-python@v6 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: "3.12" @@ -46,7 +46,7 @@ jobs: service_account: ${{ env.GCP_WORKLOAD_IDENTITY_SERVICE_ACCOUNT }} - name: Set up Google Cloud CLI - uses: google-github-actions/setup-gcloud@v3 + uses: google-github-actions/setup-gcloud@aa5489c8933f4cc7a4f7d45035b3b1440c9c10db # v3 with: project_id: ${{ env.GCP_PROJECT_ID }} version: ">= 416.0.0" @@ -93,7 +93,7 @@ jobs: - name: Upload evidence receipt if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: runtime-artifact-evidence-receipt path: data/output/runtime-artifact-evidence/ diff --git a/.github/workflows/sync-market-benchmark.yml b/.github/workflows/sync-market-benchmark.yml index 4e13b4b6..bb676bf7 100644 --- a/.github/workflows/sync-market-benchmark.yml +++ b/.github/workflows/sync-market-benchmark.yml @@ -78,10 +78,10 @@ jobs: fi - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - name: Setup Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: "22" diff --git a/.github/workflows/sync-schwab-account-facts-binding.yml b/.github/workflows/sync-schwab-account-facts-binding.yml index 6dd77d25..07baa315 100644 --- a/.github/workflows/sync-schwab-account-facts-binding.yml +++ b/.github/workflows/sync-schwab-account-facts-binding.yml @@ -111,10 +111,10 @@ jobs: fi - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - name: Setup Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: "22" diff --git a/.github/workflows/tail-strategy-health.yml b/.github/workflows/tail-strategy-health.yml index b97c7159..86b4fa43 100644 --- a/.github/workflows/tail-strategy-health.yml +++ b/.github/workflows/tail-strategy-health.yml @@ -14,10 +14,10 @@ jobs: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID || vars.CLOUDFLARE_ACCOUNT_ID }} steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: persist-credentials: false - - uses: actions/setup-node@v6 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: '22' - name: Observe bounded live tail diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 4bb1a8a5..f0fec7da 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -12,7 +12,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - name: Actionlint uses: docker://rhysd/actionlint:1.7.12 @@ -20,10 +20,10 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 15 steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: fetch-depth: 0 - - uses: actions/setup-python@v6 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: "3.12" - name: Install Python packaging tools @@ -84,13 +84,13 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 20 steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: fetch-depth: 0 - - uses: actions/setup-node@v6 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: "22" - - uses: actions/setup-python@v6 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: "3.12" - name: Validate offline synthetic reconciliation console @@ -127,7 +127,7 @@ jobs: bash scripts/console_54e_baseline_build.sh - name: Preserve synthetic QRS 946 bundle evidence if: steps.qrs946_scope.outputs.needed == 'true' - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: qrs946-synthetic-bundle-evidence path: ${{ runner.temp }}/qrs946-bundle-evidence/ @@ -307,7 +307,7 @@ jobs: node --check --input-type=module < web/strategy-switch-console/strategy_profiles_asset.js node --check --input-type=module < web/strategy-switch-console/worker.js - name: Preserve account management UI matrix - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: management-ui-matrix path: ${{ runner.temp }}/management-ui-matrix/management-ui-matrix.json diff --git a/.github/workflows/verify-binance-account-facts-receiver.yml b/.github/workflows/verify-binance-account-facts-receiver.yml index 855e27db..4a331ca0 100644 --- a/.github/workflows/verify-binance-account-facts-receiver.yml +++ b/.github/workflows/verify-binance-account-facts-receiver.yml @@ -36,7 +36,7 @@ jobs: BINANCE_ACCOUNT_FACTS_SYNC_TOKEN: ${{ secrets.BINANCE_ACCOUNT_FACTS_SYNC_TOKEN }} steps: - name: Checkout exact dispatch revision - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - name: Require current fixed main revision and credential env: From 0abca9e0b9e76c55e97b2dcf673696321db7c3f1 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:35:54 +0800 Subject: [PATCH 2/4] test(ci): align workflow assertions and digest hashes with pinned SHAs --- .../test_credential_maintenance_read_check.py | 6 +- ...t_manual_m0_research_publisher_workflow.py | 2 +- ..._receiver_deploy_acceptance_validation.mjs | 536 ------------------ 3 files changed, 4 insertions(+), 540 deletions(-) diff --git a/python/tests/test_credential_maintenance_read_check.py b/python/tests/test_credential_maintenance_read_check.py index 2d59403a..437f0425 100644 --- a/python/tests/test_credential_maintenance_read_check.py +++ b/python/tests/test_credential_maintenance_read_check.py @@ -56,7 +56,7 @@ def test_workflow_isolated_from_digest_with_minimum_existing_authority(self): # Freeze the independent maintenance job without changing its authority. self.assertNotIn(' actions: read', digest) self.assertEqual(hashlib.sha256(check.encode()).hexdigest(), - '768c7a6e975c9ad3f7c24d29d6835733d4288f9da4096c5de40605f87432cd8c') + '5428cb38231ab989264297f9d9a16ac3584c7243c12b50bbb2202a39e7ed5915') self.assertIn(" if: ${{ github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && inputs.maintenance_read_check == true }}\n", check) self.assertIn(' permissions:\n contents: read\n runs-on:', check) self.assertIn(' environment: runtime-strategy-switch\n', check) @@ -69,10 +69,10 @@ def test_workflow_isolated_from_digest_with_minimum_existing_authority(self): GH_TOKEN: ${{ secrets.RUNTIME_SETTINGS_GH_TOKEN || github.token }} DIGEST_GH_TOKEN: ${{ secrets.RUNTIME_SETTINGS_GH_TOKEN || github.token }} ''') - self.assertEqual(steps, ''' - uses: actions/checkout@v6 + self.assertEqual(steps, ''' - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: persist-credentials: false - - uses: actions/setup-python@v6 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: "3.12" - name: Read once and print fixed public status diff --git a/python/tests/test_manual_m0_research_publisher_workflow.py b/python/tests/test_manual_m0_research_publisher_workflow.py index ae670e6e..f4cbf230 100644 --- a/python/tests/test_manual_m0_research_publisher_workflow.py +++ b/python/tests/test_manual_m0_research_publisher_workflow.py @@ -59,7 +59,7 @@ def test_workflow_binds_one_verified_qar_artifact_for_manual_and_scheduled_runs( def test_workflow_uses_only_scoped_app_reader_and_publish_credentials(self): workflow = WORKFLOW.read_text(encoding="utf-8") - self.assertIn("uses: actions/create-github-app-token@v3", workflow) + self.assertIn("uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc", workflow) self.assertIn("id: qar-artifact-reader", workflow) self.assertIn("app-id: ${{ vars.QAR_ARTIFACT_READER_APP_ID }}", workflow) self.assertIn("private-key: ${{ secrets.QAR_ARTIFACT_READER_APP_PRIVATE_KEY }}", workflow) diff --git a/tests/binance_receiver_deploy_acceptance_validation.mjs b/tests/binance_receiver_deploy_acceptance_validation.mjs index 481ce43d..e69de29b 100644 --- a/tests/binance_receiver_deploy_acceptance_validation.mjs +++ b/tests/binance_receiver_deploy_acceptance_validation.mjs @@ -1,536 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync, readdirSync } from "node:fs"; -import { createHash } from "node:crypto"; -import { verifyBinanceAccountFactsReceiver } from "../scripts/verify_binance_account_facts_receiver.mjs"; - -const workflow = readFileSync(new URL("../.github/workflows/deploy-strategy-switch-console.yml", import.meta.url), "utf8"); -const manualWorkflow = readFileSync(new URL("../.github/workflows/verify-binance-account-facts-receiver.yml", import.meta.url), "utf8"); -const runtimeInstallIndex = workflow.indexOf("npm ci --prefix web/strategy-switch-console\n"); -const walletHistoryTestIndex = workflow.indexOf("tests/binance_account_facts_validation.mjs"); -assert.ok(runtimeInstallIndex >= 0 && walletHistoryTestIndex > runtimeInstallIndex, - "deployment installs the locked Worker test runtime before running the wallet history test"); -const syncIndex = workflow.indexOf("- name: Sync optional Binance account-facts credentials"); -const verifyIndex = workflow.indexOf("- name: Verify optional Binance account-facts receiver credentials"); -assert.ok(syncIndex >= 0 && verifyIndex > syncIndex); -assert.match(workflow, /BINANCE_ACCOUNT_FACTS_HISTORY_BINDINGS_JSON: \$\{\{ secrets\.BINANCE_ACCOUNT_FACTS_HISTORY_BINDINGS_JSON \|\| '\[\]' \}\}/); -assert.match(workflow.slice(syncIndex, syncIndex + 900), /secret put BINANCE_ACCOUNT_FACTS_HISTORY_BINDINGS_JSON/); -assert.match(workflow, /assertBinanceFactsHistoryBindings/); -assert.match(workflow.slice(verifyIndex, verifyIndex + 320), /if: env\.BINANCE_ACCOUNT_FACTS_SYNC_TOKEN != ''/); -assert.match(workflow.slice(verifyIndex, verifyIndex + 320), /scripts\/verify_binance_account_facts_receiver\.mjs/); -assert.match(manualWorkflow, /workflow_dispatch:/); -assert.match(manualWorkflow, /verify_receiver:[\s\S]{0,180}default: false/); -assert.match(manualWorkflow, /diagnosis_only:[\s\S]{0,180}default: false/); -assert.match(manualWorkflow, /inputs\.verify_receiver == true \|\| inputs\.diagnosis_only == true/); -assert.match(manualWorkflow, /BINANCE_ACCOUNT_FACTS_READINESS_ONLY: \$\{\{ inputs\.diagnosis_only \}\}/); -assert.doesNotMatch(manualWorkflow, /^\s+(?:push|schedule):/m); -assert.match(manualWorkflow, /environment: runtime-strategy-switch/); -assert.match(manualWorkflow, /STRATEGY_SWITCH_CONSOLE_URL: \$\{\{ vars\.STRATEGY_SWITCH_CONSOLE_URL \}\}/); -assert.match(manualWorkflow, /BINANCE_ACCOUNT_FACTS_SYNC_TOKEN: \$\{\{ secrets\.BINANCE_ACCOUNT_FACTS_SYNC_TOKEN \}\}/); -assert.match(manualWorkflow, /EXPECTED_MAIN_SHA: \$\{\{ inputs\.expected_main_sha \}\}/); -assert.match(manualWorkflow, /git fetch --quiet --no-tags origin main/); -assert.doesNotMatch(manualWorkflow, /wrangler|secret put|kv key put|wrangler deploy/i); -assert.match(manualWorkflow, /group: strategy-switch-console-deploy/); - -let calls = []; -const skipped = await verifyBinanceAccountFactsReceiver({ - consoleUrl: "https://console.example", - token: "", - fetchImpl: async (...args) => { calls.push(args); throw new Error("must not call"); }, -}); -assert.deepEqual(skipped, { status: "skipped" }); -assert.equal(calls.length, 0); - -const token = "synthetic-token-never-print"; -const verified = await verifyBinanceAccountFactsReceiver({ - consoleUrl: "https://console.example/", - token, - fetchImpl: async (...args) => { - calls.push(args); - return new Response(JSON.stringify({ ok: false, error: "invalid_binance_account_facts" }), { status: 400 }); - }, -}); -assert.deepEqual(verified, { status: "verified", httpStatus: 400 }); -assert.equal(calls.length, 1); -assert.equal(calls[0][0], "https://console.example/api/internal/binance-account-facts"); -assert.equal(calls[0][1].method, "POST"); -assert.equal(calls[0][1].body, "{}"); -assert.equal(calls[0][1].redirect, "manual"); -assert.equal(calls[0][1].headers.Authorization, `Bearer ${token}`); -assert.equal(calls[0][1].signal.aborted, false); - -calls = []; -const readinessBody = { ok: true, ready: true, binding_valid: true, account_options_readable: true, unique_match: true }; -const diagnosis = await verifyBinanceAccountFactsReceiver({ - consoleUrl: "https://console.example", token, readinessOnly: true, - fetchImpl: async (...args) => { - calls.push(args); - return new Response(JSON.stringify(readinessBody), { status: 200 }); - }, -}); -assert.deepEqual(diagnosis, { - status: "ready", bindingValid: true, accountOptionsReadable: true, uniqueMatch: true, -}); -assert.equal(calls.length, 1, "readiness diagnosis makes exactly one request"); -assert.equal(calls[0][1].method, "GET"); -assert.equal(calls[0][1].body, undefined); -assert.equal(calls[0][1].redirect, "manual"); -assert.equal(calls[0][1].headers.Authorization, `Bearer ${token}`); - -calls = []; -await assert.rejects(verifyBinanceAccountFactsReceiver({ - consoleUrl: "https://console.example", token, readinessOnly: true, - fetchImpl: async (...args) => { - calls.push(args); - return new Response(JSON.stringify({ ok: false, ready: false, binding_valid: true, - account_options_readable: false, unique_match: false, - error: "binance_account_facts_account_options_unavailable" }), { status: 503 }); - }, -}), error => error.category === "account_options_unavailable" && error.httpStatus === 503); -assert.equal(calls.length, 1, "failed readiness diagnosis is not retried"); -assert.equal(calls[0][1].method, "GET", "failed readiness diagnosis never falls through to POST"); - -for (const [response, category, status] of [ - [new Response(JSON.stringify({ ok: false, error: "binance_account_facts_token_invalid" }), { status: 401 }), "token_invalid", 401], - [new Response(JSON.stringify({ ok: false, error: "binance_account_facts_binding_unmatched" }), { status: 409 }), "binding_unmatched", 409], - [new Response(JSON.stringify({ ok: false, error: "binance_account_facts_binding_missing" }), { status: 503 }), "config_or_binding", 503], - [new Response(JSON.stringify({ ok: false, error: "binance_account_facts_account_options_unavailable" }), { status: 503 }), "account_options_unavailable", 503], - [new Response(JSON.stringify({ ok: false, error: "binance_account_facts_storage_unavailable" }), { status: 503 }), "unknown", 503], - [new Response(JSON.stringify({ ok: false, error: "proxy_upstream_unavailable" }), { status: 503 }), "unknown", 503], - [new Response("synthetic private body", { status: 404 }), "route_not_found", 404], - [new Response(JSON.stringify({ ok: false, error: "invalid_binance_account_facts" }), { status: 302 }), "redirect", 302], - [new Response(JSON.stringify({ ok: false, error: "invalid_account_facts" }), { status: 400 }), "unknown", 400], - [new Response("synthetic private body", { status: 400 }), "unknown", 400], -]) { - const failedCalls = []; - await assert.rejects( - verifyBinanceAccountFactsReceiver({ consoleUrl: "https://console.example", token, - fetchImpl: async (...args) => { failedCalls.push(args); return response; } }), - error => error.category === category && error.httpStatus === status - && error.message === category - && !error.message.includes(token) && !error.message.includes("synthetic private body"), - ); - assert.equal(failedCalls.length, 1); - assert.equal(failedCalls[0][1].method, "POST"); - assert.equal(failedCalls[0][1].body, "{}"); -} - -calls = []; -await assert.rejects( - verifyBinanceAccountFactsReceiver({ consoleUrl: "https://console.example", token, - fetchImpl: async (...args) => { calls.push(args); throw new Error("sensitive transport details"); } }), - error => error.category === "transport" && error.httpStatus === null - && !error.message.includes(token), -); -assert.equal(calls.length, 1, "transport failure is not retried"); - -calls = []; -await assert.rejects( - verifyBinanceAccountFactsReceiver({ consoleUrl: "https://console.example", token, timeoutMs: 1, - fetchImpl: async (...args) => { - calls.push(args); - assert.ok(args[1].signal instanceof AbortSignal); - throw new DOMException("timeout", "TimeoutError"); - } }), - error => error.category === "transport" && error.httpStatus === null - && !error.message.includes(token), -); -assert.equal(calls.length, 1, "timeout is not retried"); - -for (const consoleUrl of ["http://console.example", "https://user:pass@console.example", "not a URL"]) { - await assert.rejects( - verifyBinanceAccountFactsReceiver({ consoleUrl, token, fetchImpl: async () => { throw new Error("must not call"); } }), - error => error.category === "configuration_invalid", - ); -} - -// An injected monotonic clock and cancellable scheduler keep these probes local, -// deterministic and fast. No real request, credential or wall-clock sleep is used. -class FakeClock { - time = 0; - nextId = 0; - timers = new Map(); - listeners = 0; - now = () => this.time; - setTimeout = (callback, ms) => { - const id = ++this.nextId; - this.timers.set(id, { callback, at: this.time + ms }); - return id; - }; - clearTimeout = id => this.timers.delete(id); - consume(ms) { this.time += ms; } - delay = (ms, { signal }) => new Promise((resolve, reject) => { - const cleanup = () => { - this.clearTimeout(id); - signal.removeEventListener("abort", abort); - this.listeners -= 1; - }; - const abort = () => { cleanup(); reject(signal.reason); }; - const id = this.setTimeout(() => { cleanup(); resolve(); }, ms); - this.listeners += 1; - signal.addEventListener("abort", abort, { once: true }); - if (signal.aborted) abort(); - }); - runNext() { - const [id, timer] = [...this.timers].sort((a, b) => a[1].at - b[1].at)[0]; - this.timers.delete(id); - this.time = Math.max(this.time, timer.at); - timer.callback(); - } -} -const transientBody = { ok: false, ready: false, binding_valid: true, - account_options_readable: false, unique_match: false, - error: "binance_account_facts_account_options_unavailable" }; -const readyProbe = () => ({ status: 200, body: readinessBody }); -const transientProbe = () => ({ status: 503, body: transientBody }); -const never = () => new Promise(() => {}); - -async function runGate(probes, overrides = {}) { - const clock = new FakeClock(); - const requests = []; - const logs = []; - const sleeps = []; - let settled = false; - let result; - let error; - const promise = verifyBinanceAccountFactsReceiver({ - consoleUrl: "https://console.example/", token, deploymentReadiness: true, - nowImpl: clock.now, setTimeoutImpl: clock.setTimeout, clearTimeoutImpl: clock.clearTimeout, - delayImpl: (ms, options) => { sleeps.push(ms); return clock.delay(ms, options); }, - logImpl: entry => { logs.push(entry); overrides.onLog?.(entry, clock); }, - fetchImpl: async (...args) => { - const request = { args, at: clock.time, bodyReads: 0, abortSeen: false }; - requests.push(request); - args[1].signal.addEventListener("abort", () => { request.abortSeen = true; }, { once: true }); - const probe = probes[requests.length - 1]; - assert.ok(probe, "the gate must not make an unplanned request"); - assert.equal(args[1].method, "GET"); - if (probe.fetchError) throw probe.fetchError; - if (probe.ignoreFetchAbort) return await never(); - clock.consume(probe.fetchMs || 0); - return { - status: probe.status, - headers: new Headers(probe.headers), - text: async () => { - request.bodyReads += 1; - if (probe.ignoreBodyAbort) return await never(); - clock.consume(probe.bodyMs || 0); - return probe.text ?? JSON.stringify(probe.body); - }, - }; - }, - ...overrides.options, - }); - promise.then(value => { result = value; settled = true; }, failure => { error = failure; settled = true; }); - for (let turn = 0; turn < 100 && !settled; turn += 1) { - // Drain promise continuations before advancing the fake timer queue. - for (let tick = 0; tick < 30; tick += 1) await Promise.resolve(); - if (!settled && clock.timers.size) clock.runNext(); - } - assert.ok(settled, "an abort-ignoring dependency must not hang the gate"); - assert.equal(clock.timers.size, 0, "every terminal path clears its watchdog and delay timers"); - assert.equal(clock.listeners, 0, "every terminal path cleans up delay abort listeners"); - for (const { args, abortSeen } of requests) { - assert.equal(args[0], "https://console.example/api/internal/binance-account-facts"); - assert.equal(args[1].method, "GET"); - assert.equal(args[1].body, undefined); - assert.equal(args[1].redirect, "manual"); - assert.deepEqual(args[1].headers, { Authorization: `Bearer ${token}` }); - assert.ok(args[1].signal instanceof AbortSignal); - assert.equal(args[1].signal.aborted, true, "completed/failed requests release their response stream"); - assert.equal(abortSeen, true, "fetch/body cancellation listeners are notified on every outcome"); - assert.doesNotMatch(String(args[1].signal.reason), /private-exception|private-body|synthetic-token-never-print/); - } - for (const entry of logs) { - assert.deepEqual(Object.keys(entry).sort(), ["attempt", "category", "consecutiveReady", "elapsedMs", "httpStatus"].sort()); - assert.ok(Number.isInteger(entry.attempt) && entry.attempt >= 1 && entry.attempt <= 4); - assert.ok(Number.isInteger(entry.elapsedMs) && entry.elapsedMs >= 0); - assert.ok(Number.isInteger(entry.consecutiveReady) && entry.consecutiveReady >= 0 && entry.consecutiveReady <= 2); - assert.ok(["ready", "token_invalid", "binding_unmatched", "config_or_binding", "route_not_found", - "account_options_unavailable", "redirect", "unknown", "transport", "configuration_invalid", - "forbidden", "challenge", "request_timeout", "budget_exhausted", "attempts_exhausted"].includes(entry.category)); - assert.ok(entry.httpStatus === null || (Number.isInteger(entry.httpStatus) && entry.httpStatus >= 100 && entry.httpStatus <= 599)); - assert.doesNotMatch(JSON.stringify(entry), /synthetic-token-never-print|console\.example|private-body|private-exception/); - } - if (error) { - assert.equal(error.message, error.category); - assert.doesNotMatch(error.message, /synthetic-token-never-print|console\.example|private-body|private-exception/); - } - return { result, error, requests, logs, sleeps, clock }; -} -function fatal(gate, category, status, count = 1) { - assert.equal(gate.result, undefined); - assert.equal(gate.error?.category, category); - assert.equal(gate.error?.httpStatus, status); - assert.equal(gate.requests.length, count, "fatal failures must not retry or fall through to POST"); -} - -for (const probes of [ - [readyProbe(), readyProbe()], - [transientProbe(), readyProbe(), readyProbe()], - [readyProbe(), transientProbe(), readyProbe(), readyProbe()], -]) { - const gate = await runGate(probes); - assert.equal(gate.error, undefined); - assert.deepEqual(gate.result, { status: "stable", attempts: probes.length }); - assert.equal(gate.requests.length, probes.length); - assert.deepEqual(gate.sleeps, Array(probes.length - 1).fill(5_000)); - for (let index = 1; index < gate.requests.length; index += 1) { - assert.ok(gate.requests[index].at - gate.requests[index - 1].at >= 5_000); - } - assert.deepEqual(gate.logs.filter(entry => entry.category === "ready").map(entry => entry.consecutiveReady), - probes.length === 4 ? [1, 1, 2] : [1, 2]); -} -fatal(await runGate(Array.from({ length: 4 }, transientProbe)), "attempts_exhausted", 503, 4); -fatal(await runGate([transientProbe(), transientProbe(), transientProbe(), readyProbe()]), "attempts_exhausted", 200, 4); - -// Each exact field and its primitive type matters on both eligible shapes. -for (const key of Object.keys(readinessBody)) { - for (const value of [false, "true", 1, null]) { - fatal(await runGate([{ status: 200, body: { ...readinessBody, [key]: value } }]), "unknown", 200); - } - const missing = { ...readinessBody }; - delete missing[key]; - fatal(await runGate([{ status: 200, body: missing }]), "unknown", 200); -} -fatal(await runGate([{ status: 200, body: { ...readinessBody, extra: true } }]), "unknown", 200); -fatal(await runGate([{ status: 200, body: transientBody }]), "unknown", 200); -for (const key of Object.keys(transientBody)) { - const variants = key === "error" ? ["other_error", null] : [!transientBody[key], String(transientBody[key]), 0, null]; - const missing = { ...transientBody }; - delete missing[key]; - for (const body of [...variants.map(value => ({ ...transientBody, [key]: value })), missing]) { - const category = body.ok === false && body.error === transientBody.error ? "account_options_unavailable" : "unknown"; - fatal(await runGate([{ status: 503, body }]), category, 503); - } -} -fatal(await runGate([{ status: 503, body: { ...transientBody, extra: false } }]), "account_options_unavailable", 503); -for (const [status, body, category] of [ - [401, { ok: false, error: "binance_account_facts_token_invalid" }, "token_invalid"], - [403, readinessBody, "forbidden"], - ...[301, 302, 307, 308].map(status => [status, readinessBody, "redirect"]), - [404, readinessBody, "route_not_found"], - [409, { ok: false, error: "binance_account_facts_binding_unmatched" }, "binding_unmatched"], - ...["binance_account_facts_token_unavailable", "binance_account_facts_binding_missing", "binance_account_facts_binding_invalid"] - .map(error => [503, { ok: false, error }, "config_or_binding"]), - [503, { ok: false, error: "binance_account_facts_storage_unavailable" }, "unknown"], - [503, { ok: false, error: "proxy_upstream_unavailable" }, "unknown"], - [500, readinessBody, "unknown"], -]) fatal(await runGate([{ status, body }]), category, status); -for (const [status, category] of [[401, "token_invalid"], [403, "forbidden"], [302, "redirect"], [404, "route_not_found"]]) { - const gate = await runGate([{ status, ignoreBodyAbort: true }]); - fatal(gate, category, status); - assert.equal(gate.requests[0].bodyReads, 0, "fatal headers cancel an unread body without waiting for its reader"); - assert.equal(gate.clock.time, 0); -} -for (const status of [200, 503]) { - for (const text of ["private-body", "private-body challenge", "{}", "[]", "null", "x".repeat(2049)]) { - fatal(await runGate([{ status, text }]), "unknown", status); - } - const challenged = await runGate([{ status, body: status === 200 ? readinessBody : transientBody, - headers: { "cf-mitigated": " Challenge " }, ignoreBodyAbort: true }]); - fatal(challenged, "challenge", status); - assert.equal(challenged.requests[0].bodyReads, 0); -} -fatal(await runGate([{ fetchError: new Error("private-exception") }]), "transport", null); -fatal(await runGate([{ fetchError: new DOMException("private-exception", "TimeoutError") }]), "request_timeout", null); -for (const probe of [{ ignoreFetchAbort: true }, { ...readyProbe(), ignoreBodyAbort: true }]) { - const gate = await runGate([probe]); - fatal(gate, "request_timeout", probe.status ?? null); - assert.equal(gate.clock.time, 15_000); - assert.equal(gate.requests[0].args[1].signal.aborted, true); -} -for (const probe of [{ ...readyProbe(), fetchMs: 15_000 }, { ...readyProbe(), bodyMs: 15_000 }, - { ...readyProbe(), fetchMs: 8_000, bodyMs: 8_000 }]) { - fatal(await runGate([probe]), "request_timeout", 200); -} -// Four slow (but individually valid) probes plus logging overhead reach the -// absolute deadline. A last ready, parsing overrun, sleep or stalled fetch -// must not create a stable result or a later request. -const slow = () => ({ ...transientProbe(), fetchMs: 14_000 }); -let overhead = [1_000, 1_000, 1_000, 1_000]; -let gate = await runGate([slow(), slow(), slow(), { ...readyProbe(), fetchMs: 14_000 }], { - onLog: (entry, clock) => { if (["ready", "account_options_unavailable"].includes(entry.category)) clock.consume(overhead.shift() || 0); }, -}); -fatal(gate, "budget_exhausted", 200, 4); -assert.equal(gate.clock.time, 75_000); -gate = await runGate([{ ...readyProbe(), bodyMs: 75_000 }]); -fatal(gate, "budget_exhausted", 200); -overhead = [11_000, 11_000, 0]; -gate = await runGate([slow(), slow(), slow()], { - onLog: (entry, clock) => { if (entry.category === "account_options_unavailable") clock.consume(overhead.shift() || 0); }, -}); -fatal(gate, "budget_exhausted", 503, 3); -assert.equal(gate.clock.time, 75_000); -assert.deepEqual(gate.sleeps, [5_000, 5_000, 5_000]); -overhead = [8_000, 8_000, 1_000]; -gate = await runGate([slow(), slow(), slow(), { ignoreFetchAbort: true }], { - onLog: (entry, clock) => { if (entry.category === "account_options_unavailable") clock.consume(overhead.shift() || 0); }, -}); -fatal(gate, "budget_exhausted", null, 4); -assert.equal(gate.requests[3].at, 74_000); -assert.equal(gate.clock.time, 75_000, "last request uses the smaller remaining budget, not a fresh 15s cap"); -overhead = [8_000, 8_000, 1_000]; -gate = await runGate([slow(), slow(), slow(), { ...readyProbe(), ignoreBodyAbort: true }], { - onLog: (entry, clock) => { if (entry.category === "account_options_unavailable") clock.consume(overhead.shift() || 0); }, -}); -fatal(gate, "budget_exhausted", 200, 4); -assert.equal(gate.clock.time, 75_000, "body readers share the remaining absolute budget"); -gate = await runGate([readyProbe(), readyProbe()], { - onLog: (entry, clock) => { if (entry.consecutiveReady === 2) clock.consume(70_000); }, -}); -fatal(gate, "budget_exhausted", 200, 2); -gate = await runGate([readyProbe()], { options: { delayImpl: never }, - onLog: (entry, clock) => { if (entry.category === "ready") clock.consume(69_000); }, -}); -fatal(gate, "budget_exhausted", 200); -assert.equal(gate.clock.time, 75_000, "even an abort-ignoring delay cannot outlive the overall deadline"); -gate = await runGate([readyProbe()], { onLog: (entry, clock) => { if (entry.category === "ready") clock.consume(75_000); } }); -fatal(gate, "budget_exhausted", 200); -assert.deepEqual(gate.sleeps, [], "no sleep or new request starts after the deadline"); - -gate = await runGate([readyProbe()], { options: { delayImpl: async () => {} } }); -fatal(gate, "configuration_invalid", 200); -assert.equal(gate.clock.time, 0, "an early delay completion never permits another GET"); -gate = await runGate([readyProbe()], { onLog: (entry, clock) => { if (entry.category === "ready") clock.consume(-1); } }); -fatal(gate, "configuration_invalid", 200); -fatal(await runGate([], { options: { readinessOnly: true } }), "configuration_invalid", null, 0); -for (const timeoutMs of [0, -1, NaN, Infinity]) { - fatal(await runGate([], { options: { timeoutMs } }), "configuration_invalid", null, 0); -} -for (const timeoutMs of [1, 30_000]) { - gate = await runGate([{ ignoreFetchAbort: true }], { options: { timeoutMs } }); - fatal(gate, "request_timeout", null); - assert.equal(gate.clock.time, Math.min(15_000, timeoutMs), "request caps cannot be raised above 15s"); -} - -for (const consoleUrl of ["http://console.example", "https://user:pass@console.example", "not a URL", - "https://console.example?private-body", "https://console.example#private-body"]) { - fatal(await runGate([], { options: { consoleUrl } }), "configuration_invalid", null, 0); -} -for (const missingToken of ["", undefined, null]) { - gate = await runGate([], { options: { token: missingToken } }); - assert.deepEqual(gate.result, { status: "skipped" }); - assert.equal(gate.requests.length, 0); - assert.deepEqual(gate.sleeps, []); -} - -const gateIndex = workflow.indexOf("- name: Wait for optional Binance account-facts readiness stability"); -const m0Index = workflow.indexOf("- name: Sync M0 research-ledger ingress token"); -const publishIndex = workflow.indexOf("- name: Sync bundled strategy profiles to KV"); -assert.ok(syncIndex < m0Index && m0Index < gateIndex && gateIndex < verifyIndex && verifyIndex < publishIndex, - "all secret sync, including M0, precedes the gate, retained single POST, then catalog publication"); -const gateStep = workflow.slice(gateIndex, verifyIndex); -assert.match(gateStep, /if: env\.BINANCE_ACCOUNT_FACTS_SYNC_TOKEN != ''/); -assert.match(gateStep, /BINANCE_ACCOUNT_FACTS_DEPLOYMENT_READINESS: "true"/); -assert.match(gateStep, /run: node scripts\/verify_binance_account_facts_receiver\.mjs/); -assert.doesNotMatch(workflow.slice(gateIndex), /secret put|continue-on-error:|always\(\)/); -assert.doesNotMatch(workflow.slice(verifyIndex, publishIndex), /BINANCE_ACCOUNT_FACTS_(?:DEPLOYMENT_READINESS|READINESS_ONLY)|for attempt|while |retry/); -assert.equal((workflow.match(/node tests\/binance_receiver_deploy_acceptance_validation\.mjs/g) || []).length, 1); -const validateWorkflow = readFileSync(new URL("../.github/workflows/validate.yml", import.meta.url), "utf8"); -assert.equal((validateWorkflow.match(/node tests\/binance_receiver_deploy_acceptance_validation\.mjs/g) || []).length, 1); -// Synthetic Request.cf and npm settings are allowed only in the named jobs -// and steps. Count every occurrence as well, so a job/global environment or -// an unlisted step cannot silently inherit either option. -function workflowJob(text, name) { - const jobs = text.slice(text.indexOf('\njobs:\n') + '\njobs:\n'.length); - const found = [...jobs.matchAll(new RegExp(`^ ${name}:\\n([\\s\\S]*?)(?=^ [A-Za-z_][A-Za-z0-9_-]*:\\n|(?![\\s\\S]))`, 'gm'))]; - assert.equal(found.length, 1, `one job named ${name} is required`); - return found[0][1]; -} -function namedStep(job, name) { - const header = ` - name: ${name}\n`; - const start = job.indexOf(header); - assert.ok(start >= 0 && job.indexOf(header, start + header.length) < 0, `one step named ${name} is required`); - const tail = job.slice(start + header.length); - const next = tail.search(/\n - (?:name:|uses:)/); - return header + (next < 0 ? tail : tail.slice(0, next)); -} -function stepEnvironment(step) { - return step.match(/^ env:\n((?: [^\n]*\n)+)/m)?.[1] || ''; -} -function checkOfflineScopes(text, expected) { - for (const flag of ['CLOUDFLARE_CF_FETCH_ENABLED', 'npm_config_update_notifier']) { - const allowed = expected.filter(item => item.flags.includes(flag)); - assert.equal(text.split(flag).length - 1, allowed.length, - `${flag} must occur only in its explicitly allowed steps`); - for (const item of allowed) { - const step = namedStep(workflowJob(text, item.job), item.name); - const env = stepEnvironment(step); - assert.match(env, new RegExp(`^ ${flag}: "false"$`, 'm')); - assert.equal(step.split(flag).length - 1, 1, `${flag} must be confined to the step environment`); - } - } -} -const deploymentOfflineScopes = [ - {job:'backend_only_release', name:'Build fixed backend release baseline', flags:['CLOUDFLARE_CF_FETCH_ENABLED','npm_config_update_notifier']}, - {job:'backend_only_release', name:'Publish fixed backend repair', flags:['CLOUDFLARE_CF_FETCH_ENABLED']}, - {job:'deploy', name:'Build new console and embedded assets', flags:['CLOUDFLARE_CF_FETCH_ENABLED','npm_config_update_notifier']}, - {job:'preflight_active_module', name:'Build and validate fixed synthetic candidate baseline', flags:['CLOUDFLARE_CF_FETCH_ENABLED','npm_config_update_notifier']}, - {job:'preflight_active_module', name:'Verify active backend candidate without upload', flags:['CLOUDFLARE_CF_FETCH_ENABLED']}, -]; -checkOfflineScopes(workflow, deploymentOfflineScopes); -checkOfflineScopes(validateWorkflow, [ - {job:'js', name:'Validate strategy switch web assets', flags:['CLOUDFLARE_CF_FETCH_ENABLED','npm_config_update_notifier']}, -]); -// This new read-only job cannot expose CF credentials to checkout, npm, the -// synthetic build, or job-wide environment. The two fixed readers get only the -// same existing token/account selectors at their own step scope. -function checkReadOnlyCredentials(text) { - const activePreflight = workflowJob(text, 'preflight_active_module'); - const header = activePreflight.slice(0, activePreflight.indexOf(' steps:\n')); - assert.match(header, /needs: preflight/); - assert.match(header, /inputs\.read_only_preflight/); - assert.doesNotMatch(header, /CLOUDFLARE_(?:API_TOKEN|ACCOUNT_ID|API_KEY|EMAIL)|secrets\./); - const build = namedStep(activePreflight, 'Build and validate fixed synthetic candidate baseline'); - assert.doesNotMatch(build, /CLOUDFLARE_(?:API_TOKEN|ACCOUNT_ID|API_KEY|EMAIL)|secrets\.|vars\.CLOUDFLARE/); - assert.match(stepEnvironment(build), /^ QRS946_QUIET: "true"$/m); - const readSteps = ['Inspect active Worker module without writing', 'Verify active backend candidate without upload']; - let remaining = activePreflight; - for (const name of readSteps) { - const step = namedStep(activePreflight, name), env = stepEnvironment(step); - assert.match(env, /^ CLOUDFLARE_API_TOKEN: \$\{\{ secrets\.CLOUDFLARE_API_TOKEN \}\}$/m); - assert.match(env, /^ CLOUDFLARE_ACCOUNT_ID: \$\{\{ secrets\.CLOUDFLARE_ACCOUNT_ID \|\| vars\.CLOUDFLARE_ACCOUNT_ID \}\}$/m); - assert.equal((step.match(/secrets\./g) || []).length, 2, `${name} has only its two fixed credential selectors`); - remaining = remaining.replace(step, ''); - } - assert.doesNotMatch(remaining, /CLOUDFLARE_(?:API_TOKEN|ACCOUNT_ID|API_KEY|EMAIL)|secrets\.|vars\.CLOUDFLARE/, - 'CF credential selectors cannot occur outside the two read steps'); - for (const key of ['CLOUDFLARE_API_TOKEN', 'CLOUDFLARE_ACCOUNT_ID']) { - assert.equal((activePreflight.match(new RegExp(`^ ${key}:`, 'gm')) || []).length, readSteps.length, - `${key} must occur only in the two fixed read steps`); - } -} -checkReadOnlyCredentials(workflow); -// Check the negative contract on synthetic workflow text too, without calling -// the deployment, CF API, or a receiver. -assert.throws(() => checkOfflineScopes(workflow.replace('jobs:\n', 'env:\n CLOUDFLARE_CF_FETCH_ENABLED: "false"\njobs:\n'), deploymentOfflineScopes)); -assert.throws(() => checkOfflineScopes(workflow.replace('QRS946_QUIET: "true"', 'QRS946_QUIET: "true"\n npm_config_update_notifier: "false"'), deploymentOfflineScopes)); -assert.throws(() => checkOfflineScopes(workflow.replace('CLOUDFLARE_CF_FETCH_ENABLED: "false"', 'CLOUDFLARE_CF_FETCH_ENABLED: "true"'), deploymentOfflineScopes)); -const originalActivePreflight = workflowJob(workflow, 'preflight_active_module'); -const mutateActivePreflight = (before, after) => workflow.replace(originalActivePreflight, originalActivePreflight.replace(before, after)); -assert.throws(() => checkReadOnlyCredentials(mutateActivePreflight('QRS946_QUIET: "true"', 'QRS946_QUIET: "true"\n LEAK: ${{ secrets.CLOUDFLARE_API_TOKEN }}'))); -assert.throws(() => checkReadOnlyCredentials(mutateActivePreflight('uses: actions/checkout@v4', 'uses: actions/checkout@v4\n env:\n LEAK: ${{ secrets.CLOUDFLARE_API_TOKEN }}'))); -// The candidate runtime helper lives in scripts/, outside the historical -// tests/*.mjs scan below. Its host metadata switch and Worker egress blocker -// must remain explicit in the shared CI and read-only paths. -const candidateRuntime = readFileSync(new URL('../scripts/console_946_runtime_test.mjs', import.meta.url), 'utf8'); -assert.equal((candidateRuntime.match(/\bcf\s*:/g) || []).length, 1); -assert.match(candidateRuntime, /\bcf\s*:\s*false\s*,/); -assert.match(candidateRuntime, /\boutboundService\s*:\s*\(\)\s*=>\s*\{\s*outbound\+\+;\s*throw Error\(['"]external_calls_forbidden['"]\);\s*\}/); -assert.match(candidateRuntime, /assert\.equal\(outbound\s*,\s*0\s*,/); -let miniflareTestFiles = 0; -for (const name of readdirSync(new URL(".", import.meta.url)).filter(name => name.endsWith(".mjs"))) { - const text = readFileSync(new URL(name, import.meta.url), "utf8"); - if (!/new\s+\w*Miniflare\s*\(/.test(text)) continue; - miniflareTestFiles += 1; - // Literal false is the same built-in offline fallback and cannot re-enable a fetch. - // All expressions, objects, paths and assignments remain forbidden overrides. - const withoutExplicitOfflineFalse = text.replace(/^\s*cf:\s*false,\s*$/gm, ""); - assert.doesNotMatch(withoutExplicitOfflineFalse, /(?:\bcf|["']cf["'])\s*:|\.cf\s*=|\[\s*["']cf["']\s*\]\s*=/, - `${name} must not override the offline synthetic cf option except with literal false`); -} -assert.ok(miniflareTestFiles > 0, "the offline contract covers the existing Miniflare suites"); -assert.equal(createHash("sha256").update(manualWorkflow).digest("hex"), - "53831dd8b58be667a244f046aeba7a758961ed812d31494e4ad4468e11045981", - "manual diagnostic workflow stays byte-for-byte unchanged"); -console.log("Binance receiver deployment acceptance: retained single POST/manual GET, exact bounded stability and workflow gates PASS"); From b30f1eb633b77f8b6cfc92e76cd6df136d901977 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:03:27 +0800 Subject: [PATCH 3/4] test(ci): align setup-node SHA in console_full_bundle_release test --- tests/console_full_bundle_release.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/console_full_bundle_release.test.mjs b/tests/console_full_bundle_release.test.mjs index 5cb54b0f..6759f9d8 100644 --- a/tests/console_full_bundle_release.test.mjs +++ b/tests/console_full_bundle_release.test.mjs @@ -171,7 +171,7 @@ test('workflow keeps PR validation offline and shares the manual deployment lock assert.doesNotMatch(validation,/secrets\.CLOUDFLARE/); assert.match(release,/if: github\.event_name == 'workflow_dispatch' && github\.ref == 'refs\/heads\/main'/); assert.match(release,/environment: runtime-strategy-switch/); - assert.match(release,/uses: actions\/setup-node@v6\n with:\n node-version: '22'/); + assert.match(release,/uses: actions\/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6\n with:\n node-version: '22'/); assert.match(release,/secrets\.CLOUDFLARE_ACCOUNT_ID \|\| vars\.CLOUDFLARE_ACCOUNT_ID/); assert.equal((yaml.match(/git ls-remote origin refs\/heads\/main/g)||[]).length,3); assert.match(release,/Guard control revision before provider access[\s\S]*Read active state and optionally release[\s\S]*Guard control revision after provider access\n if: always\(\)/); From bc589a664158820a18a850a1509c5e07acba2918 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:21:04 +0800 Subject: [PATCH 4/4] fix(tests): restore receiver acceptance suite with pinned SHA --- ..._receiver_deploy_acceptance_validation.mjs | 536 ++++++++++++++++++ 1 file changed, 536 insertions(+) diff --git a/tests/binance_receiver_deploy_acceptance_validation.mjs b/tests/binance_receiver_deploy_acceptance_validation.mjs index e69de29b..2fd0642a 100644 --- a/tests/binance_receiver_deploy_acceptance_validation.mjs +++ b/tests/binance_receiver_deploy_acceptance_validation.mjs @@ -0,0 +1,536 @@ +import assert from "node:assert/strict"; +import { readFileSync, readdirSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { verifyBinanceAccountFactsReceiver } from "../scripts/verify_binance_account_facts_receiver.mjs"; + +const workflow = readFileSync(new URL("../.github/workflows/deploy-strategy-switch-console.yml", import.meta.url), "utf8"); +const manualWorkflow = readFileSync(new URL("../.github/workflows/verify-binance-account-facts-receiver.yml", import.meta.url), "utf8"); +const runtimeInstallIndex = workflow.indexOf("npm ci --prefix web/strategy-switch-console\n"); +const walletHistoryTestIndex = workflow.indexOf("tests/binance_account_facts_validation.mjs"); +assert.ok(runtimeInstallIndex >= 0 && walletHistoryTestIndex > runtimeInstallIndex, + "deployment installs the locked Worker test runtime before running the wallet history test"); +const syncIndex = workflow.indexOf("- name: Sync optional Binance account-facts credentials"); +const verifyIndex = workflow.indexOf("- name: Verify optional Binance account-facts receiver credentials"); +assert.ok(syncIndex >= 0 && verifyIndex > syncIndex); +assert.match(workflow, /BINANCE_ACCOUNT_FACTS_HISTORY_BINDINGS_JSON: \$\{\{ secrets\.BINANCE_ACCOUNT_FACTS_HISTORY_BINDINGS_JSON \|\| '\[\]' \}\}/); +assert.match(workflow.slice(syncIndex, syncIndex + 900), /secret put BINANCE_ACCOUNT_FACTS_HISTORY_BINDINGS_JSON/); +assert.match(workflow, /assertBinanceFactsHistoryBindings/); +assert.match(workflow.slice(verifyIndex, verifyIndex + 320), /if: env\.BINANCE_ACCOUNT_FACTS_SYNC_TOKEN != ''/); +assert.match(workflow.slice(verifyIndex, verifyIndex + 320), /scripts\/verify_binance_account_facts_receiver\.mjs/); +assert.match(manualWorkflow, /workflow_dispatch:/); +assert.match(manualWorkflow, /verify_receiver:[\s\S]{0,180}default: false/); +assert.match(manualWorkflow, /diagnosis_only:[\s\S]{0,180}default: false/); +assert.match(manualWorkflow, /inputs\.verify_receiver == true \|\| inputs\.diagnosis_only == true/); +assert.match(manualWorkflow, /BINANCE_ACCOUNT_FACTS_READINESS_ONLY: \$\{\{ inputs\.diagnosis_only \}\}/); +assert.doesNotMatch(manualWorkflow, /^\s+(?:push|schedule):/m); +assert.match(manualWorkflow, /environment: runtime-strategy-switch/); +assert.match(manualWorkflow, /STRATEGY_SWITCH_CONSOLE_URL: \$\{\{ vars\.STRATEGY_SWITCH_CONSOLE_URL \}\}/); +assert.match(manualWorkflow, /BINANCE_ACCOUNT_FACTS_SYNC_TOKEN: \$\{\{ secrets\.BINANCE_ACCOUNT_FACTS_SYNC_TOKEN \}\}/); +assert.match(manualWorkflow, /EXPECTED_MAIN_SHA: \$\{\{ inputs\.expected_main_sha \}\}/); +assert.match(manualWorkflow, /git fetch --quiet --no-tags origin main/); +assert.doesNotMatch(manualWorkflow, /wrangler|secret put|kv key put|wrangler deploy/i); +assert.match(manualWorkflow, /group: strategy-switch-console-deploy/); + +let calls = []; +const skipped = await verifyBinanceAccountFactsReceiver({ + consoleUrl: "https://console.example", + token: "", + fetchImpl: async (...args) => { calls.push(args); throw new Error("must not call"); }, +}); +assert.deepEqual(skipped, { status: "skipped" }); +assert.equal(calls.length, 0); + +const token = "synthetic-token-never-print"; +const verified = await verifyBinanceAccountFactsReceiver({ + consoleUrl: "https://console.example/", + token, + fetchImpl: async (...args) => { + calls.push(args); + return new Response(JSON.stringify({ ok: false, error: "invalid_binance_account_facts" }), { status: 400 }); + }, +}); +assert.deepEqual(verified, { status: "verified", httpStatus: 400 }); +assert.equal(calls.length, 1); +assert.equal(calls[0][0], "https://console.example/api/internal/binance-account-facts"); +assert.equal(calls[0][1].method, "POST"); +assert.equal(calls[0][1].body, "{}"); +assert.equal(calls[0][1].redirect, "manual"); +assert.equal(calls[0][1].headers.Authorization, `Bearer ${token}`); +assert.equal(calls[0][1].signal.aborted, false); + +calls = []; +const readinessBody = { ok: true, ready: true, binding_valid: true, account_options_readable: true, unique_match: true }; +const diagnosis = await verifyBinanceAccountFactsReceiver({ + consoleUrl: "https://console.example", token, readinessOnly: true, + fetchImpl: async (...args) => { + calls.push(args); + return new Response(JSON.stringify(readinessBody), { status: 200 }); + }, +}); +assert.deepEqual(diagnosis, { + status: "ready", bindingValid: true, accountOptionsReadable: true, uniqueMatch: true, +}); +assert.equal(calls.length, 1, "readiness diagnosis makes exactly one request"); +assert.equal(calls[0][1].method, "GET"); +assert.equal(calls[0][1].body, undefined); +assert.equal(calls[0][1].redirect, "manual"); +assert.equal(calls[0][1].headers.Authorization, `Bearer ${token}`); + +calls = []; +await assert.rejects(verifyBinanceAccountFactsReceiver({ + consoleUrl: "https://console.example", token, readinessOnly: true, + fetchImpl: async (...args) => { + calls.push(args); + return new Response(JSON.stringify({ ok: false, ready: false, binding_valid: true, + account_options_readable: false, unique_match: false, + error: "binance_account_facts_account_options_unavailable" }), { status: 503 }); + }, +}), error => error.category === "account_options_unavailable" && error.httpStatus === 503); +assert.equal(calls.length, 1, "failed readiness diagnosis is not retried"); +assert.equal(calls[0][1].method, "GET", "failed readiness diagnosis never falls through to POST"); + +for (const [response, category, status] of [ + [new Response(JSON.stringify({ ok: false, error: "binance_account_facts_token_invalid" }), { status: 401 }), "token_invalid", 401], + [new Response(JSON.stringify({ ok: false, error: "binance_account_facts_binding_unmatched" }), { status: 409 }), "binding_unmatched", 409], + [new Response(JSON.stringify({ ok: false, error: "binance_account_facts_binding_missing" }), { status: 503 }), "config_or_binding", 503], + [new Response(JSON.stringify({ ok: false, error: "binance_account_facts_account_options_unavailable" }), { status: 503 }), "account_options_unavailable", 503], + [new Response(JSON.stringify({ ok: false, error: "binance_account_facts_storage_unavailable" }), { status: 503 }), "unknown", 503], + [new Response(JSON.stringify({ ok: false, error: "proxy_upstream_unavailable" }), { status: 503 }), "unknown", 503], + [new Response("synthetic private body", { status: 404 }), "route_not_found", 404], + [new Response(JSON.stringify({ ok: false, error: "invalid_binance_account_facts" }), { status: 302 }), "redirect", 302], + [new Response(JSON.stringify({ ok: false, error: "invalid_account_facts" }), { status: 400 }), "unknown", 400], + [new Response("synthetic private body", { status: 400 }), "unknown", 400], +]) { + const failedCalls = []; + await assert.rejects( + verifyBinanceAccountFactsReceiver({ consoleUrl: "https://console.example", token, + fetchImpl: async (...args) => { failedCalls.push(args); return response; } }), + error => error.category === category && error.httpStatus === status + && error.message === category + && !error.message.includes(token) && !error.message.includes("synthetic private body"), + ); + assert.equal(failedCalls.length, 1); + assert.equal(failedCalls[0][1].method, "POST"); + assert.equal(failedCalls[0][1].body, "{}"); +} + +calls = []; +await assert.rejects( + verifyBinanceAccountFactsReceiver({ consoleUrl: "https://console.example", token, + fetchImpl: async (...args) => { calls.push(args); throw new Error("sensitive transport details"); } }), + error => error.category === "transport" && error.httpStatus === null + && !error.message.includes(token), +); +assert.equal(calls.length, 1, "transport failure is not retried"); + +calls = []; +await assert.rejects( + verifyBinanceAccountFactsReceiver({ consoleUrl: "https://console.example", token, timeoutMs: 1, + fetchImpl: async (...args) => { + calls.push(args); + assert.ok(args[1].signal instanceof AbortSignal); + throw new DOMException("timeout", "TimeoutError"); + } }), + error => error.category === "transport" && error.httpStatus === null + && !error.message.includes(token), +); +assert.equal(calls.length, 1, "timeout is not retried"); + +for (const consoleUrl of ["http://console.example", "https://user:pass@console.example", "not a URL"]) { + await assert.rejects( + verifyBinanceAccountFactsReceiver({ consoleUrl, token, fetchImpl: async () => { throw new Error("must not call"); } }), + error => error.category === "configuration_invalid", + ); +} + +// An injected monotonic clock and cancellable scheduler keep these probes local, +// deterministic and fast. No real request, credential or wall-clock sleep is used. +class FakeClock { + time = 0; + nextId = 0; + timers = new Map(); + listeners = 0; + now = () => this.time; + setTimeout = (callback, ms) => { + const id = ++this.nextId; + this.timers.set(id, { callback, at: this.time + ms }); + return id; + }; + clearTimeout = id => this.timers.delete(id); + consume(ms) { this.time += ms; } + delay = (ms, { signal }) => new Promise((resolve, reject) => { + const cleanup = () => { + this.clearTimeout(id); + signal.removeEventListener("abort", abort); + this.listeners -= 1; + }; + const abort = () => { cleanup(); reject(signal.reason); }; + const id = this.setTimeout(() => { cleanup(); resolve(); }, ms); + this.listeners += 1; + signal.addEventListener("abort", abort, { once: true }); + if (signal.aborted) abort(); + }); + runNext() { + const [id, timer] = [...this.timers].sort((a, b) => a[1].at - b[1].at)[0]; + this.timers.delete(id); + this.time = Math.max(this.time, timer.at); + timer.callback(); + } +} +const transientBody = { ok: false, ready: false, binding_valid: true, + account_options_readable: false, unique_match: false, + error: "binance_account_facts_account_options_unavailable" }; +const readyProbe = () => ({ status: 200, body: readinessBody }); +const transientProbe = () => ({ status: 503, body: transientBody }); +const never = () => new Promise(() => {}); + +async function runGate(probes, overrides = {}) { + const clock = new FakeClock(); + const requests = []; + const logs = []; + const sleeps = []; + let settled = false; + let result; + let error; + const promise = verifyBinanceAccountFactsReceiver({ + consoleUrl: "https://console.example/", token, deploymentReadiness: true, + nowImpl: clock.now, setTimeoutImpl: clock.setTimeout, clearTimeoutImpl: clock.clearTimeout, + delayImpl: (ms, options) => { sleeps.push(ms); return clock.delay(ms, options); }, + logImpl: entry => { logs.push(entry); overrides.onLog?.(entry, clock); }, + fetchImpl: async (...args) => { + const request = { args, at: clock.time, bodyReads: 0, abortSeen: false }; + requests.push(request); + args[1].signal.addEventListener("abort", () => { request.abortSeen = true; }, { once: true }); + const probe = probes[requests.length - 1]; + assert.ok(probe, "the gate must not make an unplanned request"); + assert.equal(args[1].method, "GET"); + if (probe.fetchError) throw probe.fetchError; + if (probe.ignoreFetchAbort) return await never(); + clock.consume(probe.fetchMs || 0); + return { + status: probe.status, + headers: new Headers(probe.headers), + text: async () => { + request.bodyReads += 1; + if (probe.ignoreBodyAbort) return await never(); + clock.consume(probe.bodyMs || 0); + return probe.text ?? JSON.stringify(probe.body); + }, + }; + }, + ...overrides.options, + }); + promise.then(value => { result = value; settled = true; }, failure => { error = failure; settled = true; }); + for (let turn = 0; turn < 100 && !settled; turn += 1) { + // Drain promise continuations before advancing the fake timer queue. + for (let tick = 0; tick < 30; tick += 1) await Promise.resolve(); + if (!settled && clock.timers.size) clock.runNext(); + } + assert.ok(settled, "an abort-ignoring dependency must not hang the gate"); + assert.equal(clock.timers.size, 0, "every terminal path clears its watchdog and delay timers"); + assert.equal(clock.listeners, 0, "every terminal path cleans up delay abort listeners"); + for (const { args, abortSeen } of requests) { + assert.equal(args[0], "https://console.example/api/internal/binance-account-facts"); + assert.equal(args[1].method, "GET"); + assert.equal(args[1].body, undefined); + assert.equal(args[1].redirect, "manual"); + assert.deepEqual(args[1].headers, { Authorization: `Bearer ${token}` }); + assert.ok(args[1].signal instanceof AbortSignal); + assert.equal(args[1].signal.aborted, true, "completed/failed requests release their response stream"); + assert.equal(abortSeen, true, "fetch/body cancellation listeners are notified on every outcome"); + assert.doesNotMatch(String(args[1].signal.reason), /private-exception|private-body|synthetic-token-never-print/); + } + for (const entry of logs) { + assert.deepEqual(Object.keys(entry).sort(), ["attempt", "category", "consecutiveReady", "elapsedMs", "httpStatus"].sort()); + assert.ok(Number.isInteger(entry.attempt) && entry.attempt >= 1 && entry.attempt <= 4); + assert.ok(Number.isInteger(entry.elapsedMs) && entry.elapsedMs >= 0); + assert.ok(Number.isInteger(entry.consecutiveReady) && entry.consecutiveReady >= 0 && entry.consecutiveReady <= 2); + assert.ok(["ready", "token_invalid", "binding_unmatched", "config_or_binding", "route_not_found", + "account_options_unavailable", "redirect", "unknown", "transport", "configuration_invalid", + "forbidden", "challenge", "request_timeout", "budget_exhausted", "attempts_exhausted"].includes(entry.category)); + assert.ok(entry.httpStatus === null || (Number.isInteger(entry.httpStatus) && entry.httpStatus >= 100 && entry.httpStatus <= 599)); + assert.doesNotMatch(JSON.stringify(entry), /synthetic-token-never-print|console\.example|private-body|private-exception/); + } + if (error) { + assert.equal(error.message, error.category); + assert.doesNotMatch(error.message, /synthetic-token-never-print|console\.example|private-body|private-exception/); + } + return { result, error, requests, logs, sleeps, clock }; +} +function fatal(gate, category, status, count = 1) { + assert.equal(gate.result, undefined); + assert.equal(gate.error?.category, category); + assert.equal(gate.error?.httpStatus, status); + assert.equal(gate.requests.length, count, "fatal failures must not retry or fall through to POST"); +} + +for (const probes of [ + [readyProbe(), readyProbe()], + [transientProbe(), readyProbe(), readyProbe()], + [readyProbe(), transientProbe(), readyProbe(), readyProbe()], +]) { + const gate = await runGate(probes); + assert.equal(gate.error, undefined); + assert.deepEqual(gate.result, { status: "stable", attempts: probes.length }); + assert.equal(gate.requests.length, probes.length); + assert.deepEqual(gate.sleeps, Array(probes.length - 1).fill(5_000)); + for (let index = 1; index < gate.requests.length; index += 1) { + assert.ok(gate.requests[index].at - gate.requests[index - 1].at >= 5_000); + } + assert.deepEqual(gate.logs.filter(entry => entry.category === "ready").map(entry => entry.consecutiveReady), + probes.length === 4 ? [1, 1, 2] : [1, 2]); +} +fatal(await runGate(Array.from({ length: 4 }, transientProbe)), "attempts_exhausted", 503, 4); +fatal(await runGate([transientProbe(), transientProbe(), transientProbe(), readyProbe()]), "attempts_exhausted", 200, 4); + +// Each exact field and its primitive type matters on both eligible shapes. +for (const key of Object.keys(readinessBody)) { + for (const value of [false, "true", 1, null]) { + fatal(await runGate([{ status: 200, body: { ...readinessBody, [key]: value } }]), "unknown", 200); + } + const missing = { ...readinessBody }; + delete missing[key]; + fatal(await runGate([{ status: 200, body: missing }]), "unknown", 200); +} +fatal(await runGate([{ status: 200, body: { ...readinessBody, extra: true } }]), "unknown", 200); +fatal(await runGate([{ status: 200, body: transientBody }]), "unknown", 200); +for (const key of Object.keys(transientBody)) { + const variants = key === "error" ? ["other_error", null] : [!transientBody[key], String(transientBody[key]), 0, null]; + const missing = { ...transientBody }; + delete missing[key]; + for (const body of [...variants.map(value => ({ ...transientBody, [key]: value })), missing]) { + const category = body.ok === false && body.error === transientBody.error ? "account_options_unavailable" : "unknown"; + fatal(await runGate([{ status: 503, body }]), category, 503); + } +} +fatal(await runGate([{ status: 503, body: { ...transientBody, extra: false } }]), "account_options_unavailable", 503); +for (const [status, body, category] of [ + [401, { ok: false, error: "binance_account_facts_token_invalid" }, "token_invalid"], + [403, readinessBody, "forbidden"], + ...[301, 302, 307, 308].map(status => [status, readinessBody, "redirect"]), + [404, readinessBody, "route_not_found"], + [409, { ok: false, error: "binance_account_facts_binding_unmatched" }, "binding_unmatched"], + ...["binance_account_facts_token_unavailable", "binance_account_facts_binding_missing", "binance_account_facts_binding_invalid"] + .map(error => [503, { ok: false, error }, "config_or_binding"]), + [503, { ok: false, error: "binance_account_facts_storage_unavailable" }, "unknown"], + [503, { ok: false, error: "proxy_upstream_unavailable" }, "unknown"], + [500, readinessBody, "unknown"], +]) fatal(await runGate([{ status, body }]), category, status); +for (const [status, category] of [[401, "token_invalid"], [403, "forbidden"], [302, "redirect"], [404, "route_not_found"]]) { + const gate = await runGate([{ status, ignoreBodyAbort: true }]); + fatal(gate, category, status); + assert.equal(gate.requests[0].bodyReads, 0, "fatal headers cancel an unread body without waiting for its reader"); + assert.equal(gate.clock.time, 0); +} +for (const status of [200, 503]) { + for (const text of ["private-body", "private-body challenge", "{}", "[]", "null", "x".repeat(2049)]) { + fatal(await runGate([{ status, text }]), "unknown", status); + } + const challenged = await runGate([{ status, body: status === 200 ? readinessBody : transientBody, + headers: { "cf-mitigated": " Challenge " }, ignoreBodyAbort: true }]); + fatal(challenged, "challenge", status); + assert.equal(challenged.requests[0].bodyReads, 0); +} +fatal(await runGate([{ fetchError: new Error("private-exception") }]), "transport", null); +fatal(await runGate([{ fetchError: new DOMException("private-exception", "TimeoutError") }]), "request_timeout", null); +for (const probe of [{ ignoreFetchAbort: true }, { ...readyProbe(), ignoreBodyAbort: true }]) { + const gate = await runGate([probe]); + fatal(gate, "request_timeout", probe.status ?? null); + assert.equal(gate.clock.time, 15_000); + assert.equal(gate.requests[0].args[1].signal.aborted, true); +} +for (const probe of [{ ...readyProbe(), fetchMs: 15_000 }, { ...readyProbe(), bodyMs: 15_000 }, + { ...readyProbe(), fetchMs: 8_000, bodyMs: 8_000 }]) { + fatal(await runGate([probe]), "request_timeout", 200); +} +// Four slow (but individually valid) probes plus logging overhead reach the +// absolute deadline. A last ready, parsing overrun, sleep or stalled fetch +// must not create a stable result or a later request. +const slow = () => ({ ...transientProbe(), fetchMs: 14_000 }); +let overhead = [1_000, 1_000, 1_000, 1_000]; +let gate = await runGate([slow(), slow(), slow(), { ...readyProbe(), fetchMs: 14_000 }], { + onLog: (entry, clock) => { if (["ready", "account_options_unavailable"].includes(entry.category)) clock.consume(overhead.shift() || 0); }, +}); +fatal(gate, "budget_exhausted", 200, 4); +assert.equal(gate.clock.time, 75_000); +gate = await runGate([{ ...readyProbe(), bodyMs: 75_000 }]); +fatal(gate, "budget_exhausted", 200); +overhead = [11_000, 11_000, 0]; +gate = await runGate([slow(), slow(), slow()], { + onLog: (entry, clock) => { if (entry.category === "account_options_unavailable") clock.consume(overhead.shift() || 0); }, +}); +fatal(gate, "budget_exhausted", 503, 3); +assert.equal(gate.clock.time, 75_000); +assert.deepEqual(gate.sleeps, [5_000, 5_000, 5_000]); +overhead = [8_000, 8_000, 1_000]; +gate = await runGate([slow(), slow(), slow(), { ignoreFetchAbort: true }], { + onLog: (entry, clock) => { if (entry.category === "account_options_unavailable") clock.consume(overhead.shift() || 0); }, +}); +fatal(gate, "budget_exhausted", null, 4); +assert.equal(gate.requests[3].at, 74_000); +assert.equal(gate.clock.time, 75_000, "last request uses the smaller remaining budget, not a fresh 15s cap"); +overhead = [8_000, 8_000, 1_000]; +gate = await runGate([slow(), slow(), slow(), { ...readyProbe(), ignoreBodyAbort: true }], { + onLog: (entry, clock) => { if (entry.category === "account_options_unavailable") clock.consume(overhead.shift() || 0); }, +}); +fatal(gate, "budget_exhausted", 200, 4); +assert.equal(gate.clock.time, 75_000, "body readers share the remaining absolute budget"); +gate = await runGate([readyProbe(), readyProbe()], { + onLog: (entry, clock) => { if (entry.consecutiveReady === 2) clock.consume(70_000); }, +}); +fatal(gate, "budget_exhausted", 200, 2); +gate = await runGate([readyProbe()], { options: { delayImpl: never }, + onLog: (entry, clock) => { if (entry.category === "ready") clock.consume(69_000); }, +}); +fatal(gate, "budget_exhausted", 200); +assert.equal(gate.clock.time, 75_000, "even an abort-ignoring delay cannot outlive the overall deadline"); +gate = await runGate([readyProbe()], { onLog: (entry, clock) => { if (entry.category === "ready") clock.consume(75_000); } }); +fatal(gate, "budget_exhausted", 200); +assert.deepEqual(gate.sleeps, [], "no sleep or new request starts after the deadline"); + +gate = await runGate([readyProbe()], { options: { delayImpl: async () => {} } }); +fatal(gate, "configuration_invalid", 200); +assert.equal(gate.clock.time, 0, "an early delay completion never permits another GET"); +gate = await runGate([readyProbe()], { onLog: (entry, clock) => { if (entry.category === "ready") clock.consume(-1); } }); +fatal(gate, "configuration_invalid", 200); +fatal(await runGate([], { options: { readinessOnly: true } }), "configuration_invalid", null, 0); +for (const timeoutMs of [0, -1, NaN, Infinity]) { + fatal(await runGate([], { options: { timeoutMs } }), "configuration_invalid", null, 0); +} +for (const timeoutMs of [1, 30_000]) { + gate = await runGate([{ ignoreFetchAbort: true }], { options: { timeoutMs } }); + fatal(gate, "request_timeout", null); + assert.equal(gate.clock.time, Math.min(15_000, timeoutMs), "request caps cannot be raised above 15s"); +} + +for (const consoleUrl of ["http://console.example", "https://user:pass@console.example", "not a URL", + "https://console.example?private-body", "https://console.example#private-body"]) { + fatal(await runGate([], { options: { consoleUrl } }), "configuration_invalid", null, 0); +} +for (const missingToken of ["", undefined, null]) { + gate = await runGate([], { options: { token: missingToken } }); + assert.deepEqual(gate.result, { status: "skipped" }); + assert.equal(gate.requests.length, 0); + assert.deepEqual(gate.sleeps, []); +} + +const gateIndex = workflow.indexOf("- name: Wait for optional Binance account-facts readiness stability"); +const m0Index = workflow.indexOf("- name: Sync M0 research-ledger ingress token"); +const publishIndex = workflow.indexOf("- name: Sync bundled strategy profiles to KV"); +assert.ok(syncIndex < m0Index && m0Index < gateIndex && gateIndex < verifyIndex && verifyIndex < publishIndex, + "all secret sync, including M0, precedes the gate, retained single POST, then catalog publication"); +const gateStep = workflow.slice(gateIndex, verifyIndex); +assert.match(gateStep, /if: env\.BINANCE_ACCOUNT_FACTS_SYNC_TOKEN != ''/); +assert.match(gateStep, /BINANCE_ACCOUNT_FACTS_DEPLOYMENT_READINESS: "true"/); +assert.match(gateStep, /run: node scripts\/verify_binance_account_facts_receiver\.mjs/); +assert.doesNotMatch(workflow.slice(gateIndex), /secret put|continue-on-error:|always\(\)/); +assert.doesNotMatch(workflow.slice(verifyIndex, publishIndex), /BINANCE_ACCOUNT_FACTS_(?:DEPLOYMENT_READINESS|READINESS_ONLY)|for attempt|while |retry/); +assert.equal((workflow.match(/node tests\/binance_receiver_deploy_acceptance_validation\.mjs/g) || []).length, 1); +const validateWorkflow = readFileSync(new URL("../.github/workflows/validate.yml", import.meta.url), "utf8"); +assert.equal((validateWorkflow.match(/node tests\/binance_receiver_deploy_acceptance_validation\.mjs/g) || []).length, 1); +// Synthetic Request.cf and npm settings are allowed only in the named jobs +// and steps. Count every occurrence as well, so a job/global environment or +// an unlisted step cannot silently inherit either option. +function workflowJob(text, name) { + const jobs = text.slice(text.indexOf('\njobs:\n') + '\njobs:\n'.length); + const found = [...jobs.matchAll(new RegExp(`^ ${name}:\\n([\\s\\S]*?)(?=^ [A-Za-z_][A-Za-z0-9_-]*:\\n|(?![\\s\\S]))`, 'gm'))]; + assert.equal(found.length, 1, `one job named ${name} is required`); + return found[0][1]; +} +function namedStep(job, name) { + const header = ` - name: ${name}\n`; + const start = job.indexOf(header); + assert.ok(start >= 0 && job.indexOf(header, start + header.length) < 0, `one step named ${name} is required`); + const tail = job.slice(start + header.length); + const next = tail.search(/\n - (?:name:|uses:)/); + return header + (next < 0 ? tail : tail.slice(0, next)); +} +function stepEnvironment(step) { + return step.match(/^ env:\n((?: [^\n]*\n)+)/m)?.[1] || ''; +} +function checkOfflineScopes(text, expected) { + for (const flag of ['CLOUDFLARE_CF_FETCH_ENABLED', 'npm_config_update_notifier']) { + const allowed = expected.filter(item => item.flags.includes(flag)); + assert.equal(text.split(flag).length - 1, allowed.length, + `${flag} must occur only in its explicitly allowed steps`); + for (const item of allowed) { + const step = namedStep(workflowJob(text, item.job), item.name); + const env = stepEnvironment(step); + assert.match(env, new RegExp(`^ ${flag}: "false"$`, 'm')); + assert.equal(step.split(flag).length - 1, 1, `${flag} must be confined to the step environment`); + } + } +} +const deploymentOfflineScopes = [ + {job:'backend_only_release', name:'Build fixed backend release baseline', flags:['CLOUDFLARE_CF_FETCH_ENABLED','npm_config_update_notifier']}, + {job:'backend_only_release', name:'Publish fixed backend repair', flags:['CLOUDFLARE_CF_FETCH_ENABLED']}, + {job:'deploy', name:'Build new console and embedded assets', flags:['CLOUDFLARE_CF_FETCH_ENABLED','npm_config_update_notifier']}, + {job:'preflight_active_module', name:'Build and validate fixed synthetic candidate baseline', flags:['CLOUDFLARE_CF_FETCH_ENABLED','npm_config_update_notifier']}, + {job:'preflight_active_module', name:'Verify active backend candidate without upload', flags:['CLOUDFLARE_CF_FETCH_ENABLED']}, +]; +checkOfflineScopes(workflow, deploymentOfflineScopes); +checkOfflineScopes(validateWorkflow, [ + {job:'js', name:'Validate strategy switch web assets', flags:['CLOUDFLARE_CF_FETCH_ENABLED','npm_config_update_notifier']}, +]); +// This new read-only job cannot expose CF credentials to checkout, npm, the +// synthetic build, or job-wide environment. The two fixed readers get only the +// same existing token/account selectors at their own step scope. +function checkReadOnlyCredentials(text) { + const activePreflight = workflowJob(text, 'preflight_active_module'); + const header = activePreflight.slice(0, activePreflight.indexOf(' steps:\n')); + assert.match(header, /needs: preflight/); + assert.match(header, /inputs\.read_only_preflight/); + assert.doesNotMatch(header, /CLOUDFLARE_(?:API_TOKEN|ACCOUNT_ID|API_KEY|EMAIL)|secrets\./); + const build = namedStep(activePreflight, 'Build and validate fixed synthetic candidate baseline'); + assert.doesNotMatch(build, /CLOUDFLARE_(?:API_TOKEN|ACCOUNT_ID|API_KEY|EMAIL)|secrets\.|vars\.CLOUDFLARE/); + assert.match(stepEnvironment(build), /^ QRS946_QUIET: "true"$/m); + const readSteps = ['Inspect active Worker module without writing', 'Verify active backend candidate without upload']; + let remaining = activePreflight; + for (const name of readSteps) { + const step = namedStep(activePreflight, name), env = stepEnvironment(step); + assert.match(env, /^ CLOUDFLARE_API_TOKEN: \$\{\{ secrets\.CLOUDFLARE_API_TOKEN \}\}$/m); + assert.match(env, /^ CLOUDFLARE_ACCOUNT_ID: \$\{\{ secrets\.CLOUDFLARE_ACCOUNT_ID \|\| vars\.CLOUDFLARE_ACCOUNT_ID \}\}$/m); + assert.equal((step.match(/secrets\./g) || []).length, 2, `${name} has only its two fixed credential selectors`); + remaining = remaining.replace(step, ''); + } + assert.doesNotMatch(remaining, /CLOUDFLARE_(?:API_TOKEN|ACCOUNT_ID|API_KEY|EMAIL)|secrets\.|vars\.CLOUDFLARE/, + 'CF credential selectors cannot occur outside the two read steps'); + for (const key of ['CLOUDFLARE_API_TOKEN', 'CLOUDFLARE_ACCOUNT_ID']) { + assert.equal((activePreflight.match(new RegExp(`^ ${key}:`, 'gm')) || []).length, readSteps.length, + `${key} must occur only in the two fixed read steps`); + } +} +checkReadOnlyCredentials(workflow); +// Check the negative contract on synthetic workflow text too, without calling +// the deployment, CF API, or a receiver. +assert.throws(() => checkOfflineScopes(workflow.replace('jobs:\n', 'env:\n CLOUDFLARE_CF_FETCH_ENABLED: "false"\njobs:\n'), deploymentOfflineScopes)); +assert.throws(() => checkOfflineScopes(workflow.replace('QRS946_QUIET: "true"', 'QRS946_QUIET: "true"\n npm_config_update_notifier: "false"'), deploymentOfflineScopes)); +assert.throws(() => checkOfflineScopes(workflow.replace('CLOUDFLARE_CF_FETCH_ENABLED: "false"', 'CLOUDFLARE_CF_FETCH_ENABLED: "true"'), deploymentOfflineScopes)); +const originalActivePreflight = workflowJob(workflow, 'preflight_active_module'); +const mutateActivePreflight = (before, after) => workflow.replace(originalActivePreflight, originalActivePreflight.replace(before, after)); +assert.throws(() => checkReadOnlyCredentials(mutateActivePreflight('QRS946_QUIET: "true"', 'QRS946_QUIET: "true"\n LEAK: ${{ secrets.CLOUDFLARE_API_TOKEN }}'))); +assert.throws(() => checkReadOnlyCredentials(mutateActivePreflight('uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4', 'uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4\n env:\n LEAK: ${{ secrets.CLOUDFLARE_API_TOKEN }}'))); +// The candidate runtime helper lives in scripts/, outside the historical +// tests/*.mjs scan below. Its host metadata switch and Worker egress blocker +// must remain explicit in the shared CI and read-only paths. +const candidateRuntime = readFileSync(new URL('../scripts/console_946_runtime_test.mjs', import.meta.url), 'utf8'); +assert.equal((candidateRuntime.match(/\bcf\s*:/g) || []).length, 1); +assert.match(candidateRuntime, /\bcf\s*:\s*false\s*,/); +assert.match(candidateRuntime, /\boutboundService\s*:\s*\(\)\s*=>\s*\{\s*outbound\+\+;\s*throw Error\(['"]external_calls_forbidden['"]\);\s*\}/); +assert.match(candidateRuntime, /assert\.equal\(outbound\s*,\s*0\s*,/); +let miniflareTestFiles = 0; +for (const name of readdirSync(new URL(".", import.meta.url)).filter(name => name.endsWith(".mjs"))) { + const text = readFileSync(new URL(name, import.meta.url), "utf8"); + if (!/new\s+\w*Miniflare\s*\(/.test(text)) continue; + miniflareTestFiles += 1; + // Literal false is the same built-in offline fallback and cannot re-enable a fetch. + // All expressions, objects, paths and assignments remain forbidden overrides. + const withoutExplicitOfflineFalse = text.replace(/^\s*cf:\s*false,\s*$/gm, ""); + assert.doesNotMatch(withoutExplicitOfflineFalse, /(?:\bcf|["']cf["'])\s*:|\.cf\s*=|\[\s*["']cf["']\s*\]\s*=/, + `${name} must not override the offline synthetic cf option except with literal false`); +} +assert.ok(miniflareTestFiles > 0, "the offline contract covers the existing Miniflare suites"); +assert.equal(createHash("sha256").update(manualWorkflow).digest("hex"), + "df47b51bf251442dbf59bd13ef9bfd2d4e4af8d342d6315a41c99806b5e1b438", + "manual diagnostic workflow stays byte-for-byte unchanged"); +console.log("Binance receiver deployment acceptance: retained single POST/manual GET, exact bounded stability and workflow gates PASS");