Repository navigation
feat: SHA-pinned actions, nonce CSP, auth scope prefetch, sharded webhook dispatch - #1521
Merged
Smartdevs17 merged 4 commits intoNov 21, 2026
Conversation
Every third-party action in .github/workflows (199 references, 25 actions) now uses a full commit SHA with the release as a trailing comment, so a moved tag or branch can no longer change what runs in CI. dtolnay/rust-toolchain picks the toolchain from its ref, so the pinned steps now pass toolchain: stable/nightly explicitly. Dependabot gains a github-actions entry that bumps SHA and comment together, grouping minor and patch updates. The top-level security-updates block is removed: it is not a Dependabot v2 key and made GitHub reject the entire config, so no update entry applied. scripts/workflow-pins.test.mjs fails make test-tooling on any unpinned reference, a missing version comment, one release pinned to two SHAs, a pinned rust-toolchain without a toolchain input, or an invalid Dependabot config. The CI tooling filter now also runs on any workflow or dependabot.yml change. CONTRIBUTING documents the policy. Closes Smartdevs17#1468
The delivery worker sent every due webhook one at a time in a single global pass and skipped whole ticks while a pass was in flight, so one slow or hanging endpoint (up to the 8s attempt timeout) delayed every merchant's deliveries. Due deliveries are now grouped by destination host and each host drains on its own lane (services/webhooks/shard-dispatcher.ts): - one request at a time per host, oldest first; - up to WEBHOOK_DISPATCH_MAX_CONCURRENT_SHARDS hosts in parallel (default 8), oldest-waiting hosts first when lanes are saturated; - a host still draining is skipped instead of started twice, which keeps the no-double-send guarantee the old global lock provided; - at most WEBHOOK_DISPATCH_MAX_BATCH_PER_SHARD deliveries per run (default 25) so one backlog cannot monopolise a lane. Invalid settings fail at worker start with the variable named. Observability: queue-wait (due to send) and lane-run percentiles, backlog, busy skips, saturation and deliver errors, served by GET /api/v1/webhooks/dispatch-stats, plus a once-a-minute saturation warning and per-shard error logs. Documented in docs/WEBHOOK_RETRY_STRATEGY.md and ENV_VARS.md. Closes Smartdevs17#1462
…ddleware
Every requirePermission/requireRole check rescanned the whole workspace
membership store for the same user, so a route with several checks paid
for several scans. The auth middleware now loads the principal's
memberships once after a strategy succeeds and attaches them as
req.workspaceScopes ({ userId, roles }); RBAC reads the role from there.
- Decisions are unchanged: the prefetched role is what getMemberRole
returns, and a missing workspace is still a 403.
- Scopes are bound to their user: another user falls back to a direct
lookup, and scopes present before authentication are cleared.
- A loader failure never blocks authentication; it is logged and RBAC
falls back to per-check lookups.
- createAuthMiddleware takes an optional loadWorkspaceScopes (custom
loader, or false to disable); getScopePrefetchStats() reports counts,
failures and timing.
Also fixes two latent bugs in the touched files: requireRole loaded
getMemberRole with a runtime require(), which fails under Vitest's ESM
loader (now a static import), and the API-key strategy imported
lookupApiKeyRecord, which was renamed to lookupApiKey in Smartdevs17#979 and made
every x-api-key request throw a TypeError.
Closes Smartdevs17#1464
middleware.ts now creates a fresh 128-bit nonce for every document request and sends a policy built by lib/csp.ts: script-src 'self' 'nonce-<random>' 'strict-dynamic'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; ... The nonce and policy are set on the forwarded request (next-intl copies request headers into its response) so Next.js stamps the nonce on every script it renders, and on the response so the browser enforces it. Injected scripts and inline handlers no longer run. Development adds 'unsafe-eval' and local HMR origins only under next dev. - The root layout calls connection() so pages render per request; a nonce cannot be added to statically prerendered HTML. - connect-src allows https:/wss: for wallet RPCs and WalletConnect, plus the configured API and realtime origins; styles keep 'unsafe-inline' because React/Radix/Web3Modal set inline style attributes. - /forms/embed/:id stays frameable by merchant sites; every other page sends frame-ancestors 'none' and X-Frame-Options: DENY. - CSP_REPORT_ONLY=true rolls the policy out as Report-Only; reports go to CSP_REPORT_URI or Sentry's security endpoint for the DSN, via report-uri, report-to and Reporting-Endpoints. - next.config.ts adds nosniff and Referrer-Policy headers. Verified on a production build: every <script> on /, /dashboard, /es/dashboard, a 404 and the embed pages carries the request's nonce. vitest inlines next-intl so the middleware can be tested directly. Closes Smartdevs17#1466
|
@JamesVictor-O is attempting to deploy a commit to the smartdevs17's projects Team on Vercel. A member of the Team first needs to authorize it. |
|
@JamesVictor-O Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits. You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR resolves four issues, one commit each. The issues' scope paths didn't all exist, so the work went where the code actually lives:
workers/webhookDispatcher/(not in repo)backend/src/services/webhooks.ts(the delivery worker) and the newservices/webhooks/shard-dispatcher.tsbackend/src/middleware/authenticate.ts(not in repo)backend/src/middleware/auth.ts, consumed bymiddleware/rbac.tsfrontend/middleware.ts,frontend/next.config.mjsfrontend/middleware.ts,frontend/next.config.ts, the newfrontend/lib/csp.ts.github/workflows/.github/workflows/,.github/dependabot.yml#1468 Pin all GitHub Actions to commit SHAs, with Dependabot automation
uses:references across 33 workflows (25 distinct actions) now pin a full commit SHA, with the release as a trailing comment:actions/checkout@11d5960a… # v4.4.0. Each version comment is the most specific release tag at that commit.dtolnay/rust-toolchainpicks the toolchain from its ref, so the 6 pinned steps that didn't already set one now passtoolchain: stable/nightlyexplicitly.dependabot.ymlgains agithub-actionsentry (weekly). It groups minor and patch bumps into one PR and gives each major bump its own PR. Dependabot updates the SHA and the comment together.security-updates:block isn't a Dependabot v2 key. GitHub rejects a config with unknown keys, so none of the update entries were taking effect. I removed the block and left a note: security updates are enabled under Settings > Code security.scripts/workflow-pins.test.mjsruns viamake test-toolingin the existing Repo tooling CI job. It fails on any unpinned reference, a missing version comment, one release pinned to two SHAs, a pinnedrust-toolchainwithout a toolchain input, or an invalid Dependabot config. The job's path filter now also covers.github/workflows/**and.github/dependabot.yml. CONTRIBUTING documents the policy.#1462 Shard the webhook delivery queue by domain
Problem:
processDueDeliveriessent every due webhook one at a time in a single global pass and skipped whole ticks while a pass was in flight. One slow or hanging endpoint, up to the 8s attempt timeout, therefore delayed every merchant's deliveries.Change: due deliveries are grouped by destination host, and each host drains on its own lane:
WEBHOOK_DISPATCH_MAX_CONCURRENT_SHARDShosts (default 8) drain in parallel. When lanes are saturated, the hosts that have waited longest go first.WEBHOOK_DISPATCH_MAX_BATCH_PER_SHARD(default 25) caps one lane run, so one host's backlog can't monopolise a lane.Observability:
GET /api/v1/webhooks/dispatch-statsreports queue-wait (due → send) and lane-run p50/p95/p99/max, the backlog, busy skips, saturation and deliver errors. A saturation warning is logged at most once a minute, and per-shard delivery errors are logged. Metrics use an in-process snapshot, likeoutbox/metrics.ts:observability/datadog.tsimportshot-shots, which isn't a dependency, so importing it would crash the worker.Unchanged: retries, backoff and dead-lettering.
Docs:
docs/WEBHOOK_RETRY_STRATEGY.mdandENV_VARS.md.#1464 Prefetch workspace scopes in the auth middleware
Every
requirePermission/requireRolecall rescanned the whole membership store for the same user. After a strategy succeeds, the auth middleware now loads the principal's memberships once (getWorkspaceScopes, a single pass) and attaches them asreq.workspaceScopes = { userId, roles }. RBAC reads the role from there:hasPermissionlookup.createAuthMiddleware(strategies, { loadWorkspaceScopes })accepts a custom loader (e.g. a database query) orfalse.getScopePrefetchStats()reports counts, failures and timing.Two latent bugs in these files are also fixed:
lookupApiKeyRecord, which was renamed tolookupApiKeyin feat: implement subscriptions export, workspaces, teams, and merchant audit trails #979, so everyx-api-keyrequest threw aTypeError. This fixes a previously failing test.requireRoleused a runtimerequire(), which fails under Vitest's ESM loader. It's now a static import.Docs:
docs/security/request-hardening.md, section 5.#1466 Strict CSP with per-request nonces for the dashboard
middleware.tscreates a fresh 128-bit nonce for every document request and sendsscript-src 'self' 'nonce-…' 'strict-dynamic'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; …, built bylib/csp.ts. The nonce and policy are also set on the forwarded request, which next-intl passes through, so Next.js stamps the nonce on every script it renders.connection()so pages render per request. A nonce can't be added to statically prerendered HTML, and without this the policy would block the scripts on those pages.connect-src:https:/wss:for wallet RPCs and WalletConnect, plus the configured API and realtime origins.frame-src: WalletConnect verify.worker-src:blob:for Sentry replay.'unsafe-inline', because React, Radix and Web3Modal set inline style attributes, which a nonce can't cover. Scripts stay strict.next devalone adds'unsafe-eval'and local HMR origins./forms/embed/:id(and locale variants), which merchants iframe on their own sites, stays frameable. Every other page sendsframe-ancestors 'none'andX-Frame-Options: DENY.CSP_REPORT_ONLY=truesends the policy as Report-Only (Next still nonces in that mode). Reports go toCSP_REPORT_URIor Sentry's security endpoint forNEXT_PUBLIC_SENTRY_DSN.next.config.tsaddsnosniffandReferrer-Policy.next-intlso the middleware can be tested directly; its ESM build importsnext/serverwithout an extension.Docs:
frontend/README.mdandENV_VARS.md.Verification
next buildsucceeds, with every page rendering dynamically. Onnext start, every<script>on/,/dashboard,/es/dashboard, a 404 page and the embed pages carries that response's nonce (34/34, 56/56, 56/56, 20/20, 30/30, 30/30). The embed pages sendframe-ancestors *and noX-Frame-Options. I couldn't check the browser console for runtime violations, so a quick manual look at the dashboard and wallet connect is worth doing before enforcing.CSP_REPORT_ONLY=truemakes that safe in staging.vitest): 47 new tests pass. The rest of the suite matchesmain: the same 31 failures, none new.vitest): 2908 passed, 344 failed. Onmainit's 2869 passed and 345 failed. No new failures, and one fixed: the API-key strategy test. New tests:shard-dispatcher.test.ts(21)webhooks.test.ts(4 new, plus the existing overlap test)auth-scope-prefetch.test.ts(13)node --test scripts/*.test.mjspasses, including 9 new pin-policy tests.commitlint.test.mjsfails locally onmainas well because commitlint isn't installed. All 33 workflows still parse.tsc: no new errors in the changed files.routes/webhooks.tshas pre-existingstring | string[]errors, shifted by one line by the new import.Closes #1462
Closes #1464
Closes #1466
Closes #1468