Skip to content

feat: SHA-pinned actions, nonce CSP, auth scope prefetch, sharded webhook dispatch - #1521

Merged
Smartdevs17 merged 4 commits into
Smartdevs17:mainfrom
JamesVictor-O:feat/actions-pinning-csp-nonce-scopes-webhook-shards
Nov 21, 2026
Merged

Smartdevs17 merged 4 commits into
Smartdevs17:mainfrom
JamesVictor-O:feat/actions-pinning-csp-nonce-scopes-webhook-shards

Conversation

@JamesVictor-O

Copy link
Copy Markdown
Contributor

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:

Issue Scope in issue Where the code is
#1462 workers/webhookDispatcher/ (not in repo) backend/src/services/webhooks.ts (the delivery worker) and the new services/webhooks/shard-dispatcher.ts
#1464 backend/src/middleware/authenticate.ts (not in repo) backend/src/middleware/auth.ts, consumed by middleware/rbac.ts
#1466 frontend/middleware.ts, frontend/next.config.mjs frontend/middleware.ts, frontend/next.config.ts, the new frontend/lib/csp.ts
#1468 .github/workflows/ .github/workflows/, .github/dependabot.yml

#1468 Pin all GitHub Actions to commit SHAs, with Dependabot automation

  • All 199 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-toolchain picks the toolchain from its ref, so the 6 pinned steps that didn't already set one now pass toolchain: stable / nightly explicitly.
  • dependabot.yml gains a github-actions entry (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.
  • Fix: the top-level 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.mjs runs via make test-tooling in the existing Repo tooling CI job. It fails 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 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: processDueDeliveries sent 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:

  • One request at a time per host, oldest first, so merchants never get concurrent requests from us.
  • Up to WEBHOOK_DISPATCH_MAX_CONCURRENT_SHARDS hosts (default 8) drain in parallel. When lanes are saturated, the hosts that have waited longest go first.
  • A host still draining is skipped instead of started twice. This keeps the no-double-send guarantee the old global lock gave, without stalling other hosts.
  • WEBHOOK_DISPATCH_MAX_BATCH_PER_SHARD (default 25) caps one lane run, so one host's backlog can't monopolise a lane.
  • An invalid value for either setting fails at worker start, naming the variable.

Observability: GET /api/v1/webhooks/dispatch-stats reports 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, like outbox/metrics.ts: observability/datadog.ts imports hot-shots, which isn't a dependency, so importing it would crash the worker.

Unchanged: retries, backoff and dead-lettering.

Docs: docs/WEBHOOK_RETRY_STRATEGY.md and ENV_VARS.md.

#1464 Prefetch workspace scopes in the auth middleware

Every requirePermission/requireRole call 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 as req.workspaceScopes = { userId, roles }. RBAC reads the role from there:

  • Same decisions: a test compares every role and action against the direct hasPermission lookup.
  • Bound to one user: a check for another user falls back to a direct lookup, and scopes already present before authentication are cleared, never trusted.
  • A loader failure never blocks authentication: it's logged and RBAC falls back to per-check lookups.
  • createAuthMiddleware(strategies, { loadWorkspaceScopes }) accepts a custom loader (e.g. a database query) or false. getScopePrefetchStats() reports counts, failures and timing.

Two latent bugs in these files are also fixed:

Docs: docs/security/request-hardening.md, section 5.

#1466 Strict CSP with per-request nonces for the dashboard

middleware.ts creates a fresh 128-bit nonce for every document request and sends script-src 'self' 'nonce-…' 'strict-dynamic'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; …, built by lib/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.

  • Rendering: the root layout calls 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.
  • What's allowed, and why:
    • 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.
    • Styles keep 'unsafe-inline', because React, Radix and Web3Modal set inline style attributes, which a nonce can't cover. Scripts stay strict.
    • next dev alone adds 'unsafe-eval' and local HMR origins.
  • Embeds keep working: /forms/embed/:id (and locale variants), which merchants iframe on their own sites, stays frameable. Every other page sends frame-ancestors 'none' and X-Frame-Options: DENY.
  • Rollout and monitoring: CSP_REPORT_ONLY=true sends the policy as Report-Only (Next still nonces in that mode). Reports go to CSP_REPORT_URI or Sentry's security endpoint for NEXT_PUBLIC_SENTRY_DSN.
  • next.config.ts adds nosniff and Referrer-Policy.
  • Vitest now inlines next-intl so the middleware can be tested directly; its ESM build imports next/server without an extension.

Docs: frontend/README.md and ENV_VARS.md.

Verification

  • Production build: next build succeeds, with every page rendering dynamically. On next 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 send frame-ancestors * and no X-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=true makes that safe in staging.
  • Frontend tests (vitest): 47 new tests pass. The rest of the suite matches main: the same 31 failures, none new.
  • Backend tests (vitest): 2908 passed, 344 failed. On main it'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)
  • Repo tooling tests: node --test scripts/*.test.mjs passes, including 9 new pin-policy tests. commitlint.test.mjs fails locally on main as well because commitlint isn't installed. All 33 workflows still parse.
  • tsc: no new errors in the changed files. routes/webhooks.ts has pre-existing string | string[] errors, shifted by one line by the new import.

Closes #1462
Closes #1464
Closes #1466
Closes #1468

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
@vercel

vercel Bot commented Nov 20, 2026

Copy link
Copy Markdown

@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.

@drips-wave

drips-wave Bot commented Nov 20, 2026

Copy link
Copy Markdown

@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! 🚀

Learn more about application limits

@Smartdevs17
Smartdevs17 merged commit 1892393 into Smartdevs17:main Nov 21, 2026
29 of 63 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants