@open-mercato/cli 0.10.1-develop.7601.1.e057b693a8 → 0.10.1-develop.7614.1.75d5ac1a6a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/agentic/guides/module-facts.json +152 -152
  2. package/dist/agentic/guides/module-facts.v2.json +152 -152
  3. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  4. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  5. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  6. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  7. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  8. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  9. package/dist/agentic/guides/modules/auth/index.md +1 -1
  10. package/dist/agentic/guides/modules/availability/index.md +1 -1
  11. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  12. package/dist/agentic/guides/modules/catalog/index.md +1 -1
  13. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  14. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  15. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  16. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  17. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  18. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  19. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  20. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  21. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  22. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  23. package/dist/agentic/guides/modules/configs/index.md +1 -1
  24. package/dist/agentic/guides/modules/content/index.md +1 -1
  25. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  26. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  27. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  28. package/dist/agentic/guides/modules/customers/index.md +1 -1
  29. package/dist/agentic/guides/modules/dashboards/index.md +1 -1
  30. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  31. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  32. package/dist/agentic/guides/modules/devices/index.md +1 -1
  33. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  34. package/dist/agentic/guides/modules/directory/index.md +1 -1
  35. package/dist/agentic/guides/modules/documents/index.md +1 -1
  36. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  37. package/dist/agentic/guides/modules/entities/index.md +1 -1
  38. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  39. package/dist/agentic/guides/modules/events/index.md +1 -1
  40. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  41. package/dist/agentic/guides/modules/forms/index.md +1 -1
  42. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  43. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  44. package/dist/agentic/guides/modules/generators/index.md +1 -1
  45. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  46. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  47. package/dist/agentic/guides/modules/messages/index.md +1 -1
  48. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  49. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  50. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  51. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  52. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  53. package/dist/agentic/guides/modules/planner/index.md +1 -1
  54. package/dist/agentic/guides/modules/portal/index.md +1 -1
  55. package/dist/agentic/guides/modules/progress/index.md +1 -1
  56. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  57. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  58. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  59. package/dist/agentic/guides/modules/resources/index.md +1 -1
  60. package/dist/agentic/guides/modules/sales/index.md +1 -1
  61. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  62. package/dist/agentic/guides/modules/search/index.md +1 -1
  63. package/dist/agentic/guides/modules/security/index.md +1 -1
  64. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  65. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  66. package/dist/agentic/guides/modules/sso/index.md +1 -1
  67. package/dist/agentic/guides/modules/staff/index.md +1 -1
  68. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  69. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  70. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  71. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  72. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  73. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  74. package/dist/agentic/guides/modules/translations/index.md +1 -1
  75. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  76. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  77. package/dist/agentic/guides/modules/wms/index.md +1 -1
  78. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  79. package/dist/agentic/guides/reference-module-facts.json +1 -1
  80. package/dist/agentic/guides/upstream/manifest.json +1 -1
  81. package/dist/agentic/shared/ai/skills/om-setup-ci/SKILL.md +42 -0
  82. package/dist/agentic/shared/ai/skills/om-setup-ci/scripts/setup-ci.mjs +525 -0
  83. package/dist/agentic/shared/ai/skills/om-setup-ci/scripts/verify-semgrep-rules.mjs +54 -0
  84. package/dist/agentic/shared/ai/skills/om-setup-ci/templates/docs/README.md +463 -0
  85. package/dist/agentic/shared/ai/skills/om-setup-ci/templates/github/actions/gitleaks/action.yml +25 -0
  86. package/dist/agentic/shared/ai/skills/om-setup-ci/templates/github/actions/playwright/action.yml +31 -0
  87. package/dist/agentic/shared/ai/skills/om-setup-ci/templates/github/actions/setup/action.yml +55 -0
  88. package/dist/agentic/shared/ai/skills/om-setup-ci/templates/github/dependabot.yml +27 -0
  89. package/dist/agentic/shared/ai/skills/om-setup-ci/templates/github/workflows/audit.yml +193 -0
  90. package/dist/agentic/shared/ai/skills/om-setup-ci/templates/github/workflows/ci.yml +477 -0
  91. package/dist/agentic/shared/ai/skills/om-setup-ci/templates/github/workflows/codeql.yml +63 -0
  92. package/dist/agentic/shared/ai/skills/om-setup-ci/templates/github/workflows/security.yml +254 -0
  93. package/dist/agentic/shared/ai/skills/om-setup-ci/templates/scripts/ci/audit-ci-allowlist.json +4 -0
  94. package/dist/agentic/shared/ai/skills/om-setup-ci/templates/scripts/ci/audit-ci.mjs +283 -0
  95. package/dist/agentic/shared/ai/skills/om-setup-ci/templates/scripts/ci/semgrep/open-mercato.fixture.txt +89 -0
  96. package/dist/agentic/shared/ai/skills/om-setup-ci/templates/scripts/ci/semgrep/open-mercato.yml +146 -0
  97. package/dist/agentic/shared/ai/skills/om-setup-ci/templates/scripts/ci/time-bomb-scanner.mjs +286 -0
  98. package/dist/agentic/shared/ai/skills/om-setup-ci/templates/scripts/ci/zap-rules.tsv +11 -0
  99. package/dist/agentic/shared/ai/skills/tiers.json +2 -1
  100. package/package.json +7 -7
@@ -0,0 +1,63 @@
1
+ # Generated by the Open Mercato om-setup-ci skill. Documentation: docs/ci/README.md
2
+ #
3
+ # GitHub CodeQL: dataflow-aware SAST for the app's TypeScript and for the
4
+ # workflows themselves. Results appear under Security → Code scanning.
5
+ # Requires a public repository or GitHub Code Security on a private one.
6
+ # Disable GitHub's "default setup" for CodeQL when using this workflow.
7
+ name: CodeQL
8
+
9
+ on:
10
+ push:
11
+ branches:
12
+ __OM_BRANCH_LIST__
13
+ pull_request:
14
+ branches:
15
+ __OM_BRANCH_LIST__
16
+ schedule:
17
+ - cron: '__OM_CODEQL_CRON__'
18
+ workflow_dispatch:
19
+
20
+ permissions:
21
+ contents: read
22
+
23
+ concurrency:
24
+ group: codeql-${{ github.event.pull_request.number || github.ref }}
25
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
26
+
27
+ jobs:
28
+ analyze:
29
+ name: Analyze (${{ matrix.language }})
30
+ runs-on: __OM_RUNNER__
31
+ timeout-minutes: 30
32
+ permissions:
33
+ contents: read
34
+ security-events: write
35
+ actions: read
36
+ strategy:
37
+ fail-fast: false
38
+ matrix:
39
+ language: [javascript-typescript, actions]
40
+ steps:
41
+ - name: Checkout repository
42
+ uses: __OM_ACTION_CHECKOUT__
43
+ with:
44
+ persist-credentials: false
45
+
46
+ - name: Initialize CodeQL
47
+ uses: __OM_ACTION_CODEQL_INIT__
48
+ with:
49
+ languages: ${{ matrix.language }}
50
+ build-mode: none
51
+ queries: security-extended
52
+ config: |
53
+ paths-ignore:
54
+ - .ai
55
+ - .mercato
56
+ - node_modules
57
+ - '**/__tests__'
58
+ - '**/__integration__'
59
+
60
+ - name: Analyze
61
+ uses: __OM_ACTION_CODEQL_ANALYZE__
62
+ with:
63
+ category: /language:${{ matrix.language }}
@@ -0,0 +1,254 @@
1
+ # Generated by the Open Mercato om-setup-ci skill. Documentation: docs/ci/README.md
2
+ #
3
+ # Pull requests are gated only on what they INTRODUCE. This nightly workflow
4
+ # scans `__OM_DEFAULT_BRANCH__` in full, so a secret buried in old history, a finding
5
+ # from a newly published rule or a fresh CVE in the base image is still found.
6
+ # While any scan fails it keeps one tracking issue open; the first clean run
7
+ # closes it.
8
+ name: Scheduled Security Scan
9
+
10
+ permissions:
11
+ contents: read
12
+
13
+ env:
14
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: 'true'
15
+
16
+ on:
17
+ schedule:
18
+ - cron: '__OM_SECURITY_CRON__'
19
+ workflow_dispatch:
20
+
21
+ concurrency:
22
+ group: scheduled-security-scan
23
+ cancel-in-progress: false
24
+
25
+ jobs:
26
+ #@if secrets
27
+ secrets:
28
+ name: Secret scan (full history)
29
+ runs-on: __OM_RUNNER__
30
+ timeout-minutes: 20
31
+ steps:
32
+ - name: Checkout repository
33
+ uses: __OM_ACTION_CHECKOUT__
34
+ with:
35
+ ref: __OM_DEFAULT_BRANCH__
36
+ fetch-depth: 0
37
+ persist-credentials: false
38
+
39
+ - name: Install Gitleaks
40
+ uses: ./.github/actions/gitleaks
41
+
42
+ - name: Scan the full history for secrets
43
+ run: '"$RUNNER_TEMP/gitleaks-bin/gitleaks" git --no-banner --redact --verbose .'
44
+
45
+ #@endif
46
+ #@if sast
47
+ sast:
48
+ name: Static analysis (full)
49
+ runs-on: __OM_RUNNER__
50
+ timeout-minutes: 30
51
+ steps:
52
+ - name: Checkout repository
53
+ uses: __OM_ACTION_CHECKOUT__
54
+ with:
55
+ ref: __OM_DEFAULT_BRANCH__
56
+ persist-credentials: false
57
+
58
+ - name: Run Semgrep with the Open Mercato rules
59
+ shell: bash
60
+ env:
61
+ SEMGREP_IMAGE: __OM_SEMGREP_IMAGE__
62
+ run: |
63
+ docker run --rm -v "$PWD:/src" -w /src "$SEMGREP_IMAGE" \
64
+ semgrep scan --metrics=off --error \
65
+ --config scripts/ci/semgrep/open-mercato.yml \
66
+ --exclude '**/__tests__/**' --exclude '**/__integration__/**' \
67
+ --exclude '*.test.*' --exclude '*.spec.*' \
68
+ src
69
+
70
+ #@endif
71
+ #@if imageScan
72
+ image:
73
+ name: Image scan (OS and npm packages)
74
+ runs-on: __OM_RUNNER__
75
+ timeout-minutes: 45
76
+ steps:
77
+ - name: Checkout repository
78
+ uses: __OM_ACTION_CHECKOUT__
79
+ with:
80
+ ref: __OM_DEFAULT_BRANCH__
81
+ persist-credentials: false
82
+
83
+ - name: Setup Docker Buildx
84
+ uses: __OM_ACTION_SETUP_BUILDX__
85
+
86
+ - name: Build production image
87
+ uses: __OM_ACTION_BUILD_PUSH__
88
+ with:
89
+ context: .
90
+ file: __OM_DOCKERFILE__
91
+ push: false
92
+ load: true
93
+ tags: app:nightly
94
+
95
+ # The base image's own global npm toolchain (/usr/local/lib/node_modules)
96
+ # is skipped: it is not shipped by the app, only a newer Node base image
97
+ # can fix it, and it would keep this scan red for reasons outside the
98
+ # app's control. The app's node_modules inside the image are scanned.
99
+ - name: Scan image with Trivy
100
+ shell: bash
101
+ env:
102
+ TRIVY_IMAGE: __OM_TRIVY_IMAGE__
103
+ run: |
104
+ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v "$PWD:/work" -w /work "$TRIVY_IMAGE" \
105
+ image --no-progress --skip-version-check --exit-code 1 --severity HIGH,CRITICAL --ignore-unfixed \
106
+ --skip-dirs /usr/local/lib/node_modules app:nightly
107
+
108
+ #@endif
109
+ #@if dast
110
+ # Passive OWASP ZAP baseline scan of the running app: security headers,
111
+ # cookie flags, information leaks and error disclosure. The app is booted
112
+ # exactly like the integration tests (ephemeral PostgreSQL), unauthenticated.
113
+ # Which alerts fail the job is set in scripts/ci/zap-rules.tsv.
114
+ dast:
115
+ name: Dynamic scan (OWASP ZAP)
116
+ runs-on: __OM_RUNNER__
117
+ timeout-minutes: 60
118
+ env:
119
+ OM_INTEGRATION_APP_READY_TIMEOUT_SECONDS: '180'
120
+ steps:
121
+ - name: Checkout repository
122
+ uses: __OM_ACTION_CHECKOUT__
123
+ with:
124
+ ref: __OM_DEFAULT_BRANCH__
125
+ persist-credentials: false
126
+
127
+ - name: Setup Node and dependencies
128
+ uses: ./.github/actions/setup
129
+
130
+ - name: Start the app on an ephemeral database
131
+ id: app
132
+ shell: bash
133
+ run: |
134
+ set -uo pipefail
135
+ LOG="$RUNNER_TEMP/ephemeral-app.log"
136
+ STATE=.ai/qa/ephemeral-env.json
137
+ nohup yarn test:integration:ephemeral:start > "$LOG" 2>&1 &
138
+ for _ in $(seq 1 180); do
139
+ if [ -f "$STATE" ] && node -e "process.exit(require('./$STATE').status === 'running' ? 0 : 1)"; then
140
+ BASE_URL=$(node -p "require('./$STATE').baseUrl")
141
+ if curl -fsS -o /dev/null "$BASE_URL"; then
142
+ echo "App is up at $BASE_URL"
143
+ echo "base_url=$BASE_URL" >> "$GITHUB_OUTPUT"
144
+ exit 0
145
+ fi
146
+ fi
147
+ sleep 5
148
+ done
149
+ echo "::error::The app did not become ready within 15 minutes."
150
+ tail -n 200 "$LOG"
151
+ exit 1
152
+
153
+ - name: Run the ZAP baseline scan
154
+ shell: bash
155
+ env:
156
+ BASE_URL: ${{ steps.app.outputs.base_url }}
157
+ ZAP_IMAGE: __OM_ZAP_IMAGE__
158
+ run: |
159
+ mkdir -p zap-report
160
+ cp scripts/ci/zap-rules.tsv zap-report/zap-rules.tsv
161
+ chmod -R a+rwX zap-report
162
+ docker run --rm --network host -v "$PWD/zap-report:/zap/wrk:rw" "$ZAP_IMAGE" \
163
+ zap-baseline.py -t "$BASE_URL" -c zap-rules.tsv -m 5 -I \
164
+ -r report.html -J report.json
165
+
166
+ - name: Upload the ZAP report
167
+ if: always()
168
+ uses: __OM_ACTION_UPLOAD_ARTIFACT__
169
+ with:
170
+ name: zap-report
171
+ path: zap-report
172
+ if-no-files-found: ignore
173
+ retention-days: 14
174
+
175
+ #@endif
176
+ report:
177
+ name: Tracking issue
178
+ if: always()
179
+ needs: [__OM_SECURITY_NEEDS__]
180
+ runs-on: __OM_RUNNER__
181
+ timeout-minutes: 5
182
+ permissions:
183
+ contents: read
184
+ issues: write
185
+ steps:
186
+ - name: Open, refresh or close the tracking issue
187
+ uses: __OM_ACTION_GITHUB_SCRIPT__
188
+ env:
189
+ NEEDS: ${{ toJSON(needs) }}
190
+ BRANCH: __OM_DEFAULT_BRANCH__
191
+ with:
192
+ script: |
193
+ const needs = JSON.parse(process.env.NEEDS)
194
+ const branch = process.env.BRANCH
195
+ const marker = `<!-- scheduled-security-scan:${branch} -->`
196
+ const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`
197
+ const failed = Object.keys(needs).filter((name) => ['failure', 'cancelled'].includes(needs[name].result))
198
+
199
+ const openIssues = await github.paginate(github.rest.issues.listForRepo, {
200
+ ...context.repo,
201
+ state: 'open',
202
+ labels: 'security',
203
+ per_page: 100,
204
+ })
205
+ const existing = openIssues.find((issue) => !issue.pull_request && (issue.body ?? '').includes(marker))
206
+
207
+ if (failed.length === 0) {
208
+ if (!existing) return
209
+ await github.rest.issues.createComment({
210
+ ...context.repo,
211
+ issue_number: existing.number,
212
+ body: `Every scheduled security scan passes again on \`${branch}\`. Closed from ${runUrl}.`,
213
+ })
214
+ await github.rest.issues.update({ ...context.repo, issue_number: existing.number, state: 'closed', state_reason: 'completed' })
215
+ return
216
+ }
217
+
218
+ const summary = Object.entries(needs).map(([name, job]) => `- \`${name}\`: ${job.result}`).join('\n')
219
+ const body = [
220
+ marker,
221
+ `The scheduled security scan is failing on \`${branch}\`.`,
222
+ '',
223
+ 'Opened and refreshed automatically by `.github/workflows/security.yml`; it closes itself on the first run where every scan passes.',
224
+ 'Open the run for the findings, and see `docs/ci/README.md` → *When a check fails* for how to resolve each scan.',
225
+ '',
226
+ `- Last checked: ${runUrl}`,
227
+ '',
228
+ '<!-- jobs:start -->',
229
+ summary,
230
+ '<!-- jobs:end -->',
231
+ ].join('\n')
232
+
233
+ if (!existing) {
234
+ const created = await github.rest.issues.create({
235
+ ...context.repo,
236
+ title: `security: scheduled security scan failing on \`${branch}\``,
237
+ body,
238
+ labels: ['security'],
239
+ })
240
+ core.notice(`Opened tracking issue #${created.data.number}.`)
241
+ } else {
242
+ const jobsOf = (text) => /<!-- jobs:start -->([\s\S]*?)<!-- jobs:end -->/.exec(text ?? '')?.[1].trim() ?? null
243
+ const changed = jobsOf(existing.body) !== jobsOf(body)
244
+ await github.rest.issues.update({ ...context.repo, issue_number: existing.number, body })
245
+ if (changed) {
246
+ await github.rest.issues.createComment({
247
+ ...context.repo,
248
+ issue_number: existing.number,
249
+ body: `The set of failing scans changed. Refreshed from ${runUrl}.`,
250
+ })
251
+ }
252
+ core.notice(`Refreshed tracking issue #${existing.number}.`)
253
+ }
254
+ core.setFailed(`Failing scans: ${failed.join(', ')}`)
@@ -0,0 +1,283 @@
1
+ #!/usr/bin/env node
2
+ // Dependency CVE audit for CI.
3
+ //
4
+ // Why this exists instead of a bare `yarn npm audit`:
5
+ // the npm registry's bulk advisories endpoint
6
+ // (https://registry.npmjs.org/-/npm/v1/security/advisories/bulk) currently
7
+ // returns a gzip-compressed body WITHOUT a `Content-Encoding: gzip` response
8
+ // header (and ignores `Accept-Encoding: identity`). Yarn 4.x's HTTP client
9
+ // correctly declines to auto-decompress a body with no encoding header, so
10
+ // `yarn npm audit` dies with `ParseError: ... is not valid JSON` before it can
11
+ // evaluate a single advisory — failing every audit whose result cache misses.
12
+ //
13
+ // This script performs the same audit (all resolved packages == `--all
14
+ // --recursive`, fail on `high`+ severity) but decompresses defensively by
15
+ // sniffing the gzip magic bytes, so it works whether or not npm sends the
16
+ // header. It NEVER softens the gate: it fails closed (exit 2) if advisory data
17
+ // cannot be retrieved, and exits 1 on any advisory at or above the threshold.
18
+ //
19
+ // Revert to `yarn npm audit --all --recursive --severity high` once the npm
20
+ // registry restores a correct `Content-Encoding` header on that endpoint.
21
+ //
22
+ // A flagged advisory with no upstream fix would otherwise block the gate
23
+ // forever; audit-ci-allowlist.json holds narrowly-scoped, justified
24
+ // exceptions (matched by GHSA id) for exactly that case.
25
+ //
26
+ // `--baseline <lockfile>` turns the gate into a "new advisories only" check:
27
+ // an advisory also flagged against the baseline lockfile (the PR base / the
28
+ // previous push) is reported but does not fail the run. Without it a PR that
29
+ // merely adds one clean dependency stays red for every advisory already on the
30
+ // base branch, which it can neither cause nor fix. Pre-existing advisories are
31
+ // owned by the scheduled `.github/workflows/audit.yml`, which runs without a
32
+ // baseline and keeps a tracking issue open until they are resolved.
33
+
34
+ import fs from 'node:fs'
35
+ import zlib from 'node:zlib'
36
+ import path from 'node:path'
37
+ import { setTimeout as delay } from 'node:timers/promises'
38
+ import { fileURLToPath, pathToFileURL } from 'node:url'
39
+
40
+ export const SEVERITY_ORDER = ['info', 'low', 'moderate', 'high', 'critical']
41
+ export const ENDPOINT = 'https://registry.npmjs.org/-/npm/v1/security/advisories/bulk'
42
+ export const ALLOWLIST_PATH = path.join(path.dirname(fileURLToPath(import.meta.url)), 'audit-ci-allowlist.json')
43
+
44
+ export function parseArgs(argv) {
45
+ const inlineSeverity = (argv.find((arg) => arg.startsWith('--severity=')) || '').split('=')[1]
46
+ const severityIndex = argv.indexOf('--severity')
47
+ const threshold = inlineSeverity
48
+ || (severityIndex >= 0 && argv[severityIndex + 1] && !argv[severityIndex + 1].startsWith('--')
49
+ ? argv[severityIndex + 1]
50
+ : 'high')
51
+ if (!SEVERITY_ORDER.includes(threshold)) {
52
+ throw new Error(`unknown --severity "${threshold}" (expected one of ${SEVERITY_ORDER.join(', ')})`)
53
+ }
54
+ const inlineBaseline = (argv.find((arg) => arg.startsWith('--baseline=')) || '').slice('--baseline='.length)
55
+ const baselineIndex = argv.indexOf('--baseline')
56
+ const separateBaseline = baselineIndex >= 0 ? argv[baselineIndex + 1] : undefined
57
+ if (baselineIndex >= 0 && (!separateBaseline || separateBaseline.startsWith('--'))) {
58
+ throw new Error('--baseline requires a lockfile path')
59
+ }
60
+ const baseline = inlineBaseline || separateBaseline
61
+ const lockArg = argv.find((arg, index) => arg.endsWith('yarn.lock') && !arg.startsWith('--') && (baselineIndex < 0 || index !== baselineIndex + 1))
62
+ return {
63
+ threshold,
64
+ lockPath: path.resolve(lockArg || 'yarn.lock'),
65
+ baselinePath: baseline ? path.resolve(baseline) : null,
66
+ }
67
+ }
68
+
69
+ export function readLockPackages(lockFile) {
70
+ // Yarn v4 lockfile: each top-level block carries `resolution: "<name>@<protocol>:<selector>"`
71
+ // and `version: "<resolved>"`. Only npm-protocol packages can carry npm advisories.
72
+ const raw = fs.readFileSync(lockFile, 'utf8')
73
+ const packages = new Map()
74
+ for (const block of raw.split(/\n(?=\S)/)) {
75
+ const resolutionMatch = block.match(/\n\s+resolution:\s+"([^"]+)"/)
76
+ const versionMatch = block.match(/\n\s+version:\s+"?([^"\n]+)"?/)
77
+ if (!resolutionMatch || !versionMatch) continue
78
+ const resolution = resolutionMatch[1]
79
+ const protocolMatch = resolution.match(/^(.+?)@(npm|patch):/)
80
+ if (!protocolMatch) continue // workspace/file/link/portal/git — no npm advisory surface
81
+ const name = protocolMatch[1]
82
+ const version = versionMatch[1].trim()
83
+ if (!name || !version) continue
84
+ if (!packages.has(name)) packages.set(name, new Set())
85
+ packages.get(name).add(version)
86
+ }
87
+ return packages
88
+ }
89
+
90
+ export function decodeAdvisoryResponse(bytes) {
91
+ const body = bytes.length >= 2 && bytes[0] === 0x1f && bytes[1] === 0x8b
92
+ ? zlib.gunzipSync(bytes).toString('utf8')
93
+ : bytes.toString('utf8')
94
+ const result = JSON.parse(body)
95
+ if (!result || typeof result !== 'object' || Array.isArray(result)) {
96
+ throw new Error('advisory response must be an object')
97
+ }
98
+ for (const [name, entries] of Object.entries(result)) {
99
+ if (!Array.isArray(entries)) throw new Error(`advisory response for ${name} must be an array`)
100
+ for (const advisory of entries) {
101
+ if (!advisory || typeof advisory !== 'object' || !SEVERITY_ORDER.includes(advisory.severity)) {
102
+ throw new Error(`advisory response for ${name} contains an invalid severity`)
103
+ }
104
+ }
105
+ }
106
+ return result
107
+ }
108
+
109
+ export async function fetchAdvisories(chunk, options = {}) {
110
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch
111
+ const endpoint = options.endpoint ?? ENDPOINT
112
+ const timeoutMs = options.timeoutMs ?? 15_000
113
+ const retryDelayMs = options.retryDelayMs ?? 250
114
+ let lastError
115
+ for (let attempt = 0; attempt < 3; attempt++) {
116
+ try {
117
+ const res = await fetchImpl(endpoint, {
118
+ method: 'POST',
119
+ headers: { 'content-type': 'application/json' },
120
+ body: JSON.stringify(chunk),
121
+ signal: AbortSignal.timeout(timeoutMs),
122
+ })
123
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
124
+ const bytes = Buffer.from(await res.arrayBuffer())
125
+ return decodeAdvisoryResponse(bytes)
126
+ } catch (error) {
127
+ lastError = error
128
+ if (attempt < 2 && retryDelayMs > 0) await delay(retryDelayMs * (2 ** attempt))
129
+ }
130
+ }
131
+ throw lastError
132
+ }
133
+
134
+ export function collectFlaggedAdvisories(advisories, threshold) {
135
+ const thresholdIndex = SEVERITY_ORDER.indexOf(threshold)
136
+ const flagged = []
137
+ for (const [name, entries] of Object.entries(advisories)) {
138
+ for (const advisory of entries) {
139
+ if (SEVERITY_ORDER.indexOf(advisory.severity) >= thresholdIndex) {
140
+ flagged.push({ name, severity: advisory.severity, range: advisory.vulnerable_versions, title: advisory.title, url: advisory.url })
141
+ }
142
+ }
143
+ }
144
+ flagged.sort((left, right) => SEVERITY_ORDER.indexOf(right.severity) - SEVERITY_ORDER.indexOf(left.severity))
145
+ return flagged
146
+ }
147
+
148
+ export function extractGhsaId(url) {
149
+ const match = typeof url === 'string' ? url.match(/GHSA-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}/i) : null
150
+ return match ? match[0].toUpperCase() : null
151
+ }
152
+
153
+ // Advisories with no upstream fix (e.g. an archived package) would otherwise
154
+ // block the gate forever. Each entry needs a recorded reason so the exception
155
+ // stays reviewable — see audit-ci-allowlist.json.
156
+ export function loadAllowlist(filePath = ALLOWLIST_PATH) {
157
+ if (!fs.existsSync(filePath)) return new Map()
158
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'))
159
+ if (!parsed || typeof parsed !== 'object' || typeof parsed.advisories !== 'object') {
160
+ throw new Error(`${filePath} must contain an "advisories" object`)
161
+ }
162
+ return new Map(Object.entries(parsed.advisories).map(([ghsaId, entry]) => [ghsaId.toUpperCase(), entry]))
163
+ }
164
+
165
+ export function partitionAllowlisted(flagged, allowlist) {
166
+ const blocking = []
167
+ const suppressed = []
168
+ for (const advisory of flagged) {
169
+ const ghsaId = extractGhsaId(advisory.url)
170
+ const exemption = ghsaId ? allowlist.get(ghsaId) : undefined
171
+ if (exemption) suppressed.push({ ...advisory, ghsaId, reason: exemption.reason })
172
+ else blocking.push(advisory)
173
+ }
174
+ return { blocking, suppressed }
175
+ }
176
+
177
+ function advisoryKey(advisory) {
178
+ return `${advisory.name}\u0000${extractGhsaId(advisory.url) ?? advisory.url ?? advisory.title}`
179
+ }
180
+
181
+ // An advisory is pre-existing when the same advisory on the same package is
182
+ // already flagged against the baseline lockfile — even if the change moved the
183
+ // package to another still-vulnerable version, it did not introduce the issue.
184
+ export function partitionByBaseline(flagged, baselineFlagged) {
185
+ const baselineKeys = new Set(baselineFlagged.map(advisoryKey))
186
+ const introduced = []
187
+ const preexisting = []
188
+ for (const advisory of flagged) {
189
+ if (baselineKeys.has(advisoryKey(advisory))) preexisting.push(advisory)
190
+ else introduced.push(advisory)
191
+ }
192
+ return { introduced, preexisting }
193
+ }
194
+
195
+ // Returns null (after logging) when the lockfile cannot be audited, so callers fail closed.
196
+ async function auditLockfile(lockPath, threshold, fetchImpl) {
197
+ const packages = readLockPackages(lockPath)
198
+ const names = [...packages.keys()]
199
+ if (names.length === 0) {
200
+ console.error(`audit-ci: no npm packages found in ${lockPath}`)
201
+ return null
202
+ }
203
+ const advisories = {}
204
+ for (let i = 0; i < names.length; i += 200) {
205
+ const chunk = {}
206
+ for (const name of names.slice(i, i + 200)) chunk[name] = [...packages.get(name)]
207
+ let result
208
+ try {
209
+ result = await fetchAdvisories(chunk, { fetchImpl })
210
+ } catch (error) {
211
+ // Fail closed — never pass the gate when advisory data is unavailable.
212
+ console.error(`audit-ci: could not retrieve advisories for ${lockPath} (batch ${i / 200 + 1}): ${error.message}`)
213
+ return null
214
+ }
215
+ Object.assign(advisories, result)
216
+ }
217
+ return { scanned: names.length, flagged: collectFlaggedAdvisories(advisories, threshold) }
218
+ }
219
+
220
+ export async function main(argv = process.argv.slice(2), { fetchImpl, allowlistPath } = {}) {
221
+ let options
222
+ try {
223
+ options = parseArgs(argv)
224
+ } catch (error) {
225
+ console.error(`audit-ci: ${error.message}`)
226
+ return 2
227
+ }
228
+
229
+ const { lockPath, threshold, baselinePath } = options
230
+ const audit = await auditLockfile(lockPath, threshold, fetchImpl)
231
+ if (!audit) return 2
232
+
233
+ let allowlist
234
+ try {
235
+ allowlist = loadAllowlist(allowlistPath)
236
+ } catch (error) {
237
+ // Fail closed — a broken allowlist must never silently suppress advisories.
238
+ console.error(`audit-ci: could not read allowlist: ${error.message}`)
239
+ return 2
240
+ }
241
+ const { blocking: unallowlisted, suppressed } = partitionAllowlisted(audit.flagged, allowlist)
242
+
243
+ let blocking = unallowlisted
244
+ let preexisting = []
245
+ if (baselinePath) {
246
+ const baselineAudit = await auditLockfile(baselinePath, threshold, fetchImpl)
247
+ if (!baselineAudit) return 2
248
+ ;({ introduced: blocking, preexisting } = partitionByBaseline(unallowlisted, baselineAudit.flagged))
249
+ }
250
+
251
+ console.log(`audit-ci: scanned ${audit.scanned} packages; threshold=${threshold}+${baselinePath ? `; baseline=${baselinePath}` : ''}`)
252
+ if (suppressed.length > 0) {
253
+ console.log(`audit-ci: ${suppressed.length} advisory(ies) allowlisted:`)
254
+ for (const advisory of suppressed) {
255
+ console.log(` [${advisory.severity}] ${advisory.name} ${advisory.range} — ${advisory.ghsaId}: ${advisory.reason}`)
256
+ }
257
+ }
258
+ if (preexisting.length > 0) {
259
+ console.log(`audit-ci: ${preexisting.length} advisory(ies) already present in the baseline (not introduced by this change; tracked by .github/workflows/audit.yml):`)
260
+ for (const advisory of preexisting) {
261
+ console.log(` [${advisory.severity}] ${advisory.name} ${advisory.range} — ${advisory.title} (${advisory.url})`)
262
+ }
263
+ }
264
+ if (blocking.length === 0) {
265
+ console.log(baselinePath ? 'audit-ci: no new advisories at or above threshold.' : 'audit-ci: no advisories at or above threshold.')
266
+ return 0
267
+ }
268
+ console.error(`audit-ci: ${blocking.length} ${baselinePath ? 'new ' : ''}advisory(ies) at or above ${threshold}:`)
269
+ for (const advisory of blocking) {
270
+ console.error(` [${advisory.severity}] ${advisory.name} ${advisory.range} — ${advisory.title} (${advisory.url})`)
271
+ }
272
+ return 1
273
+ }
274
+
275
+ const invokedPath = process.argv[1] ? pathToFileURL(path.resolve(process.argv[1])).href : null
276
+ if (invokedPath === import.meta.url) {
277
+ main().then((exitCode) => {
278
+ process.exitCode = exitCode
279
+ }).catch((error) => {
280
+ console.error(`audit-ci: unexpected failure: ${error.stack || error.message}`)
281
+ process.exitCode = 2
282
+ })
283
+ }