Repository navigation
feat(notify): security + robustness hardening + delta tests (Wave 15: 182, 183, 192) - #195
Conversation
✅ Deploy Preview for lunorash ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
Thank you for following the naming conventions! 🙏 |
|
Thank you for confirming the Contributor License Agreement! 🙏 |
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: ⛔ Files ignored due to path filters (13)
📒 Files selected for processing (16)
WalkthroughThe notification system adds Web Push endpoint and VAPID validation, secret-free device listings, bounded subscription queries, persistent store reuse, resilient fan-out outcomes, and queue retries. Browser requests also gain shared private-host and DNS-rebinding checks. ChangesNotification security and delivery
Browser SSRF validation
Package tooling and documentation
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant QueueConsumer
participant runPushBroadcastJob
participant LunoraPush
participant deliver
participant SubscriptionStore
QueueConsumer->>runPushBroadcastJob: execute push broadcast job
runPushBroadcastJob->>LunoraPush: broadcast content
LunoraPush->>deliver: deliver to subscriptions
deliver->>SubscriptionStore: best-effort lifecycle update
deliver-->>LunoraPush: status, error, receipt
LunoraPush-->>runPushBroadcastJob: BroadcastResult
runPushBroadcastJob-->>QueueConsumer: complete or retry
Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
React Doctor found no new issues. 🎉 Reviewed by React Doctor for commit |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
packages/notify/src/subscriptions/memory-store.ts (1)
35-48: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winApply the cap while iterating.
resultcollects every match beforeslice, so a bounded listing still materializes the full audience. Stop once the normalized limit is reached.Proposed fix
list: (filter?: SubscriptionFilter): Promise<StoredSubscription[]> => { const result: StoredSubscription[] = []; + const limit = filter?.limit !== undefined && filter.limit > 0 ? Math.trunc(filter.limit) : undefined; for (const subscription of map.values()) { + if (limit !== undefined && result.length >= limit) { + break; + } + if (matches(subscription, filter)) { result.push(subscription); } } - const capped = filter?.limit !== undefined && filter.limit > 0 ? result.slice(0, Math.trunc(filter.limit)) : result; - - return Promise.resolve(capped); + return Promise.resolve(result);As per path instructions, library source must follow performance best practices.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/notify/src/subscriptions/memory-store.ts` around lines 35 - 48, Update the memory-store list implementation to normalize the positive filter.limit once and enforce that cap during iteration, stopping as soon as the number of collected matches reaches it. Avoid materializing all matching subscriptions before slicing, while preserving uncapped behavior for undefined or non-positive limits and the existing Promise result contract.Source: Path instructions
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/notify/src/subscriptions/d1-store.ts`:
- Around line 90-97: Update the canonical subscription write path to atomically
remove any matching legacy wp_/fcm_ row by endpoint/token identity when
inserting or upserting the wp2_/fcm2_ record. Ensure the replacement and
legacy-row deletion occur in the same transaction, while preserving the existing
canonical upsert behavior.
In `@packages/notify/src/subscriptions/normalize.ts`:
- Around line 108-152: Update the Web Push registration configuration around
assertPushEndpoint to surface a per-isolate startup warning when
allowedPushOrigins is absent or empty, matching the existing non-durable-store
warning mechanism. Keep endpoint validation behavior unchanged, and ensure the
warning clearly states that DNS rebinding remains possible and configuring
allowedPushOrigins closes the residual risk.
In `@packages/runtime/src/create-worker.ts`:
- Around line 2603-2618: Update the limit normalization in the subscription
listing flow around store.list so fractional positive rawLimit values cannot
produce zero after truncation. Ensure the final limit passed to store.list is
always a positive bounded integer, preserving the 1000 default and maximum cap.
---
Nitpick comments:
In `@packages/notify/src/subscriptions/memory-store.ts`:
- Around line 35-48: Update the memory-store list implementation to normalize
the positive filter.limit once and enforce that cap during iteration, stopping
as soon as the number of collected matches reaches it. Avoid materializing all
matching subscriptions before slicing, while preserving uncapped behavior for
undefined or non-positive limits and the existing Promise result contract.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 8ddad576-59d6-439d-9525-e656450913b7
⛔ Files ignored due to path filters (11)
packages/client/__tests__/lunora-client.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included bypackages/**packages/notify/__tests__/helpers.tsis excluded by!**/__tests__/**and included bypackages/**packages/notify/__tests__/notify.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included bypackages/**packages/notify/__tests__/queue.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included bypackages/**packages/notify/__tests__/subscriptions.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included bypackages/**packages/notify/__tests__/web.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included bypackages/**packages/studio/__tests__/features/logs/log-level-variant.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included bypackages/**packages/studio/__tests__/features/logs/sync-client-panel.test.tsxis excluded by!**/__tests__/**and included bypackages/**packages/studio/__tests__/features/reports/instrument-format.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included bypackages/**packages/studio/__tests__/features/traces/trace-geometry.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included bypackages/**shared/ssrf-host.tsis excluded by none and included by none
📒 Files selected for processing (13)
packages/notify/README.mdpackages/notify/src/define-notify.tspackages/notify/src/notify.tspackages/notify/src/queue.tspackages/notify/src/subscriptions/d1-store.tspackages/notify/src/subscriptions/memory-store.tspackages/notify/src/subscriptions/normalize.tspackages/notify/src/types.tspackages/notify/src/web.tspackages/notify/tsconfig.jsonpackages/runtime/src/create-worker.tspackages/studio/src/features/notifications/notifications-panel.tsxpackages/studio/vitest.config.ts
Merging this PR will regress 1 benchmark
|
| Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|
| ❌ | count, no attributes |
57.6 µs | 64.4 µs | -10.45% |
| ⚡ | flat 3 primitives (the notify.send attribute shape) |
62.7 µs | 55.6 µs | +12.89% |
Tip
Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.
Comparing advisor/192-delta-test-coverage (52e1df2) with alpha (0eab929)2
Footnotes
-
2 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩
-
No successful run was found on
alpha(cfd8078) during the generation of this report, so 0eab929 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩
…ns, VAPID rotation) Harden the client-supplied push subscription path in @lunora/notify: 1. Blind SSRF — validate the Web Push `endpoint` at register (storage) time: require an absolute https URL with a non-private/loopback/link-local/CGNAT host (via a new zero-dep `shared/ssrf-host.ts`, host-classifier logic reused from @lunora/browser's SSRF guard), plus an opt-in exact-origin `allowedPushOrigins` allowlist on defineNotify. 2. Secret leak — `ctx.push.list()` now returns the secret-stripped PushSubscriptionDevice projection (no `keys`/`token`); add `listDevices()` alias. Raw rows stay reachable only via the internal SubscriptionStore. 3. 32-bit id collisions — widen the subscription id from 32-bit FNV-1a (8 hex) to 64-bit (16 hex), version-prefixed `wp2_`/`fcm2_` so old rows age out via normal gone-pruning (lazy migration; never reuse a prefix). 4. VAPID rotation dead-ends — subscribeToPush now compares an existing browser subscription's applicationServerKey to the current VAPID key and unsubscribes+re-subscribes on mismatch instead of reusing a stale key. Tests: SSRF accept/reject + allowlist, list/listDevices projection, 64-bit version-prefixed ids + 50K no-collision sample, VAPID reuse-vs-resubscribe. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…o the queue A throwing recipient (transient provider/store error, or the push router's no-channel-configured throw) now degrades to a failed outcome inside deliver instead of rejecting the whole fan-out. runPushBroadcastJob re-throws when a non-empty audience received nothing so the queue retries; partial success acks. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…RPC server-side
Adds user_id/kind indexes to the subscription table, a limit on SubscriptionFilter
applied by both stores, and pushes { kind, userId, limit } down to the store from
the Studio listPushSubscriptions RPC instead of list-all-then-filter-in-memory.
Panel cursor pagination deferred with a note.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…-register The D1 upsert no longer overwrites last_status/last_error on re-register (dropped from DO UPDATE SET; markStatus stays their only writer) and put now reads back the actual stored row so createdAt is truthful, matching the memory store. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…gister parity
Adds mockThrowingPushProvider + fakeD1({ failOn }) doubles and tests: a throwing
recipient and a store-write error no longer abort the fan-out, an unconfigured
channel degrades one recipient to failed, runPushBroadcastJob rejects only on
total failure, and re-register preserves status/createdAt on both stores.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
….limit Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…host Delete @lunora/browser's inline copy of the private-host classifier and import isPrivateHost/normalizeHost (plus parseIpv4/isPrivateIpv4/isPrivateIpv6 for the DoH-rebinding extras) from shared/ssrf-host, so a single security boundary can't diverge across two copies. Add 6to4 (2002::/16) and Teredo (2001:0000::/32) to isPrivateIpv6 — both tunnel an embedded IPv4 and must be blocked — which now benefits browser and notify alike. Drop outDir/rootDir from the browser tsconfig (required for the inlined shared import). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…st twin - SSRF posture: warn once per isolate when a web-push subscription registers without allowedPushOrigins (the string classifier can't catch a public host that resolves to a private IP); strengthen the assertPushEndpoint / allowedPushOrigins docstrings to state that plainly. - 32→64-bit id migration: on a canonical put, evict the same device's legacy wp_/fcm_ (32-bit) row so broadcast no longer delivers to it twice forever; add legacyWebPushId/legacyFcmId/legacyIdFor and wire both stores. - Queue retry: throw only when failed>0, not on total>0 — an all-pruned broadcast is a successful prune, not a transient failure worth retrying. - Collapse the byte-identical list/listDevices twin down to list. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…lter - listPushSubscriptions: truncate the requested limit BEFORE the >0 test so a fractional limit in (0,1) falls back to the 1000 cap instead of collapsing to 0 — which the d1-store reads as "no LIMIT" and leaks the full table. - Re-apply the kind/userId predicate in memory after store.list (defense in depth): a store that ignores the pushed-down filter would otherwise return everything. Keeps the RPC correct regardless of store implementation. - Refresh the runtime API snapshot for the (pre-existing) list(filter?) surface. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The chunk idempotency key is positional (${importId}:${chunkIndex}), not
content-based, so a resume with a different chunkSize reuses a key for
different rows and silently DROPS them. State that caveat accurately; the
key logic itself is unchanged.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The in-memory userId predicate compares against a stored `userId: null` (mirroring the store's `userId IS NULL` semantics), a legitimate-null site — restructure the filter to a block body and annotate the comparison with an eslint-disable, matching the file's existing legitimate-null pattern. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
112f2a5 to
52e1df2
Compare
* feat(codegen): emit api.mutators.* typed references Custom mutators dispatched through `LUNORA_FUNCTIONS` but never appeared on the generated `api`, so a client `defineMutator` had no reference to bind and `serverRef` stayed an unchecked `"mutators:sendMessage"` string — the escape hatch dotflowy shipped 23 times (adoption finding #17). - `discoverMutators` lifts each mutator's `args` validator map and its `server` impl return type; `emitApi` renders them as `api.mutators.<name>: FunctionReference<"mutation", Args, Return>`. - `@lunora/db`'s reference overload was unusable on its own terms: `R extends MutatorReference<never>` rejects any reference carrying a concrete arg type, so a real generated reference fell through to the string overload. It now infers `TArgs` from the reference's phantom. - `_generated/server.ts` re-exports a project-bound `defineMutator` (typed `MutationCtx`), and discovery accepts the `_generated/server` specifier — no more hand-written mutator ctx type plus a cast per mutator. Two latent qualifier bugs surfaced with the first checker-rendered mutator types, both pre-existing for ordinary functions: an extensionless `import("./_generated/dataModel")` was a TS2835 inside `_generated/*`, and an `import("@lunora/values").Id<…>` was a TS2307 for an umbrella-only app. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(codegen): widen env for the defineNotify store factory `defineApp`'s `Env` is bound to `object` so a wrangler-generated `interface Env` is accepted, but `defineNotify`'s `store` factory takes `NotifyEnv` (`Record<string, unknown>`) — which an interface does not satisfy. Every app with a `lunora/notify.ts` therefore emitted an `app.ts` that failed tsc with TS2345, as `examples/notify-demo` does the moment it is regenerated. Widen at the call site, the same way the agent-binding lookup already does. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore(codegen): regenerate example generated files Picks up the project-typed `defineMutator` re-export in `_generated/server.ts`, plus the pre-existing drift the examples had accumulated against the emitter (notify-demo's `defineApp`/`AppTableName` blocks and the widened notify store call). Every example typechecks. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(plans): record the second-pass findings from dotflowy #310 Re-read of the merged port on top of #187: the reported `serverRef` gap (#17) plus its two causes (#17b/#17c, fixed here) and three open findings — writes have no `owner: true` counterpart to shapes (#22), `bindMutators`' collections map is type-erased so its `apply` seam went unused (#23), and a fire-and-forget mutator has no error hook (#24). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore(api): refresh the notify API snapshot Pre-existing drift on alpha — `@lunora/notify`'s public surface changed in #195 (`SubscriptionFilter.limit`, `normalizeRegisterInput` options, a typed `runPushBroadcastJob` result) without an `api:update`, so `api:check` fails on any branch that rebuilds it. No source change. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(codegen): accept umbrella imports in every discoverer Each discoverer hard-coded its own set of accepted module specifiers and three omitted `lunorash/server` — the subpath the umbrella exists to provide, and the one codegen itself emits into `_generated/*`. An unrecognized specifier is skipped silently, so declaring `query`/`mutation` through the umbrella dropped the function from both `api.ts` and `LUNORA_FUNCTIONS` (every call 404s at runtime), `cronJobs()` stopped emitting `_generated/crons.ts` entirely (the schedule never fires), and `defineMigration` left `LUNORA_MIGRATIONS` empty (`lunora migrate up` finds nothing) — with codegen still exiting `ok`. Reproduced against apps/playground, where a real `node_modules` lets the checker resolve the symbol and reach the gate. The fixture tests never caught it: with no resolvable package there is no symbol, so discovery falls back to matching identifier text and never consults the specifier. Replaced with one shared `module-specifiers.ts` used by functions, crons, migrations, mutators, shapes, env, and identity discovery. The new regression test installs a resolvable stub into the fixture's own `node_modules`, so it fails on all five factories if the umbrella entry is dropped again. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(server,db): owner-scoped mutators, typed collections, rejection hook Closes the three findings deferred from the dotflowy re-read (#22-24 in plans/170), each a boilerplate tax the only production port had to pay. `defineMutator` gains `owner: "<column>"` (#22). Before `server` runs it requires a verified identity — an anonymous caller is rejected outright, the fail-closed rule an owner-scoped `defineShape` already applies to reads — rejects a client-supplied owner that disagrees with the session as a 403, then sets the column to the verified value. So the impl reads `args[owner]` without trusting the client, replacing the `assertOwner(ctx, args.userId)` that opened all 23 of dotflowy's mutators. It names the column rather than taking a shape's `true`: a shape is bound to one table so `.ownedBy(field)` is unambiguous, while a mutator may write several. `contextUserId` moves to a shared module so reads and writes resolve "who is this" identically. `ClientMutatorContext` / `ClientMutatorDef` / `BindMutatorsContext` become generic over the collections map, and `initMutators<TCollections>()` binds `defineMutator` + `bindMutators` to a project's collections in one place (#23). `Collection` is invariant in its row type, so the old shared `Record<string, Collection<Row, string>>` both forced an `as never` on every entry and handed `apply` a type too wide to use — which is why every optimistic body ignored `context.collections` and closed over module state instead. `bindMutators` gains `onWriteRejected` (#24), symmetric with the outbox hook of the same name. Setting it also consumes the `isPersisted` rejection, so a fire-and-forget call no longer needs an app-level `.catch` wrapper; a caller that awaits still sees it. Opt-in on purpose: an unconditional `.catch` would swallow dropped writes for callers who never asked. All three are additive — the standalone `defineMutator`/`bindMutators` keep working against the widest map, and a mutator without `owner` is untouched. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
From better-auth-ui #195, #193, #169, #166, #74 and #337. #195 — the organization limits are now published by uiConfig(). better-auth enforces organizationLimit / allowUserToCreateOrganization server-side and exposes no endpoint that reports them, so a UI can only find out by being refused. The create form is disabled with the reason instead. A function-form allowUserToCreateOrganization is a per-request decision the endpoint cannot evaluate, so it reports allowed and lets the server refuse — the alternative hides the button from everyone because one user might be denied. #166 — the 2FA card no longer vanishes for an OAuth-only account; it explains that a password is needed first. A setting that is simply absent reads as 'this app doesn't support 2FA'. Only a successful accounts read that found no credential row counts: while loading, or on error, the card behaves as before — the flow gate's rule, don't hide what you cannot reason about. #74 — the TOTP key is shown beside the otpauth:// URI. Most authenticators reject a pasted URI, so a desktop app or a broken camera had no way in. #193 — createActiveMemberController resolves the signed-in user's role in the active organization, which otherwise means fetching the org and finding yourself in members at every call site. A rendering hint, not authorization. #337 — organization.showSlug hides the slug field; create already derives one from the name. #169 was already supported by that same fallback. #165 (organization custom fields) is not done: it needs an additionalFields design that spans every card, not a flag. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
This pull request has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. |
Wave 15 —
@lunora/notifysecurity + robustness (plans 182, 183, 192)This is a stacked branch:
182 → 183 → 192(each based on the prior's tip), so it lands the whole notify hardening delta as one unit.182 — security cluster (SURF-02/03/04/09)
https:+ non-private/loopback/link-local/CGNAT host) via a new zero-depshared/ssrf-host.ts(classifier reused from@lunora/browser's SSRF guard). OptionalallowedPushOriginsallowlist.ctx.push.list()andlistDevices()now return the secret-strippedPushSubscriptionDevice[](nokeys/token); raw rows reachable only via the internal store.wp2_/fcm2_with lazy migration.subscribeToPushre-subscribes onapplicationServerKeymismatch instead of dead-ending.183 — robustness (SURF-05/06/07/08/14)
CREATE TABLE).failedoutcome instead of aborting the fan-out;runPushBroadcastJobre-throws only on total failure so the queue retries.user_id+kindindexes; Studio RPC filters server-side.createdAtparity between D1 and memory stores.192 — test coverage (HLTH-07/09/11, CLI-07/12)
/weburlBase64ToUint8Arraypadding cases;@lunora/clientimportRows(+ anit.failsresume-safety case that flips red when the content-key fix lands) +queryLogArchive; Studiosync-client-panel+ 3 pure-logic specs registered in theunitproject.Verification (reviewer re-ran in each executor's worktree)
@lunora/notify69 tests,@lunora/client464 (+1 expected fail),@lunora/studio831 +unit216; runtime/studiotscclean; eslint--max-warnings=0clean on notify.Generated by the
/improveadvisor workflow (audit → plan → isolated-worktree Opus executors → tech-lead review). Full plan text + review notes on theimprove/alpha-auditbranch underplans/.🤖 Generated with Claude Code
Summary by CodeRabbit
limitsupport and secrets redaction.allowedPushOriginsconfiguration to optionally restrict Web Push endpoint origins.