Skip to content

feat(notify): security + robustness hardening + delta tests (Wave 15: 182, 183, 192) - #195

Merged
prisis merged 13 commits into
alphafrom
advisor/192-delta-test-coverage
Jul 26, 2026
Merged

prisis merged 13 commits into
alphafrom
advisor/192-delta-test-coverage

Conversation

@prisis

@prisis prisis commented Jul 26, 2026 •

Copy link
Copy Markdown
Member

Wave 15 — @lunora/notify security + 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)

  • SSRF: Web Push endpoints are validated at register/storage time (https: + non-private/loopback/link-local/CGNAT host) via a new zero-dep shared/ssrf-host.ts (classifier reused from @lunora/browser's SSRF guard). Optional allowedPushOrigins allowlist.
  • Secret leak: ctx.push.list() and listDevices() now return the secret-stripped PushSubscriptionDevice[] (no keys/token); raw rows reachable only via the internal store.
  • Id collisions: subscription ids widened 32-bit → 64-bit, version-prefixed wp2_/fcm2_ with lazy migration.
  • VAPID rotation: subscribeToPush re-subscribes on applicationServerKey mismatch instead of dead-ending.

183 — robustness (SURF-05/06/07/08/14)

  • Subscription store memoized per isolate (no per-request CREATE TABLE).
  • Fault-tolerant broadcast: a throwing/mis-kinded recipient degrades to one failed outcome instead of aborting the fan-out; runPushBroadcastJob re-throws only on total failure so the queue retries.
  • user_id + kind indexes; Studio RPC filters server-side.
  • Re-register status/createdAt parity between D1 and memory stores.

192 — test coverage (HLTH-07/09/11, CLI-07/12)

  • notify /web urlBase64ToUint8Array padding cases; @lunora/client importRows (+ an it.fails resume-safety case that flips red when the content-key fix lands) + queryLogArchive; Studio sync-client-panel + 3 pure-logic specs registered in the unit project.

Verification (reviewer re-ran in each executor's worktree)

@lunora/notify 69 tests, @lunora/client 464 (+1 expected fail), @lunora/studio 831 + unit 216; runtime/studio tsc clean; eslint --max-warnings=0 clean on notify.

Generated by the /improve advisor workflow (audit → plan → isolated-worktree Opus executors → tech-lead review). Full plan text + review notes on the improve/alpha-audit branch under plans/.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added push subscription listing with limit support and secrets redaction.
    • Added allowedPushOrigins configuration to optionally restrict Web Push endpoint origins.
    • Added browser-side auto-replacement of existing subscriptions when the VAPID key changes.
  • Security
    • Web Push registration now enforces HTTPS endpoints and blocks private/internal hosts.
    • Public listing no longer exposes Web Push keys or FCM tokens.
  • Bug Fixes
    • Improved broadcast delivery outcome handling and retry behavior; fan-out is resilient to store write failures.
    • Preserved status/error on re-registration; refined store filtering and legacy-device deduplication.
  • Tests
    • Added additional unit test coverage (logic-only).

@netlify

netlify Bot commented Jul 26, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for lunorash ready!

Name Link
🔨 Latest commit 52e1df2
🔍 Latest deploy log https://app.netlify.com/projects/lunorash/deploys/6a65bc479d8dc4000897aa81
😎 Deploy Preview https://deploy-preview-195--lunorash.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@github-actions

Copy link
Copy Markdown
Contributor

Thank you for following the naming conventions! 🙏

@github-actions

Copy link
Copy Markdown
Contributor

Thank you for confirming the Contributor License Agreement! 🙏

@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: a0603ee2-9dba-4465-bdcf-c658bc0b2b8a

📥 Commits

Reviewing files that changed from the base of the PR and between 041426b and 52e1df2.

⛔ Files ignored due to path filters (13)
  • api-snapshots/runtime.api.md is excluded by none and included by none
  • packages/client/__tests__/lunora-client.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/notify/__tests__/helpers.ts is excluded by !**/__tests__/** and included by packages/**
  • packages/notify/__tests__/notify.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/notify/__tests__/queue.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/notify/__tests__/subscriptions.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/notify/__tests__/web.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/runtime/__tests__/notify-subscriptions-admin.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/studio/__tests__/features/logs/log-level-variant.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/studio/__tests__/features/logs/sync-client-panel.test.tsx is excluded by !**/__tests__/** and included by packages/**
  • packages/studio/__tests__/features/reports/instrument-format.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/studio/__tests__/features/traces/trace-geometry.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • shared/ssrf-host.ts is excluded by none and included by none
📒 Files selected for processing (16)
  • packages/browser/src/create-browser.ts
  • packages/browser/tsconfig.json
  • packages/client/src/lunora-client.ts
  • packages/notify/README.md
  • packages/notify/src/define-notify.ts
  • packages/notify/src/notify.ts
  • packages/notify/src/queue.ts
  • packages/notify/src/subscriptions/d1-store.ts
  • packages/notify/src/subscriptions/memory-store.ts
  • packages/notify/src/subscriptions/normalize.ts
  • packages/notify/src/types.ts
  • packages/notify/src/web.ts
  • packages/notify/tsconfig.json
  • packages/runtime/src/create-worker.ts
  • packages/studio/src/features/notifications/notifications-panel.tsx
  • packages/studio/vitest.config.ts

Walkthrough

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

Changes

Notification security and delivery

Layer / File(s) Summary
Registration security and public contracts
packages/notify/src/types.ts, packages/notify/src/define-notify.ts, packages/notify/src/subscriptions/normalize.ts, packages/notify/src/web.ts, packages/notify/README.md, packages/notify/src/notify.ts
Adds origin and endpoint validation, versioned subscription IDs with legacy eviction, VAPID-key checks, and secret-free public device listings.
Subscription storage and bounded listing
packages/notify/src/subscriptions/*, packages/notify/src/notify.ts, packages/runtime/src/create-worker.ts, packages/studio/...
Memoizes stores, preserves delivery status during re-registration, adds indexed and bounded filtering, and passes bounded filters through the admin RPC.
Delivery outcomes and queue retries
packages/notify/src/notify.ts, packages/notify/src/queue.ts
Converts send exceptions into failed outcomes, tolerates store update failures, aggregates errors, and retries broadcasts with failed deliveries.

Browser SSRF validation

Layer / File(s) Summary
Shared host and DNS validation
packages/browser/src/create-browser.ts
Uses shared private-host classification for navigation and sub-resources and adds DNS-over-HTTPS checks for DNS rebinding.

Package tooling and documentation

Layer / File(s) Summary
Package configuration and supporting documentation
packages/browser/tsconfig.json, packages/notify/tsconfig.json, packages/client/src/lunora-client.ts, packages/studio/vitest.config.ts
Removes TypeScript root/output constraints, clarifies positional import chunk IDs, and adds pure-logic specs to unit-test selection.

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
Loading

Possibly related PRs

Suggested labels: package: queue, package: d1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning It summarizes the change but omits several required template sections, including linked issues, test plan, checklist, notes, and the exact CLA text. Reformat the PR description to match the template and add linked issues, a checklist-style test plan, checklist items, notes for reviewers, and the exact CLA statement.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is specific and matches the main notify security, robustness, and test-coverage changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch advisor/192-delta-test-coverage

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

React Doctor found no new issues. 🎉

Reviewed by React Doctor for commit 52e1df2.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
packages/notify/src/subscriptions/memory-store.ts (1)

35-48: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Apply the cap while iterating.

result collects every match before slice, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2c4c597 and 041426b.

⛔ Files ignored due to path filters (11)
  • packages/client/__tests__/lunora-client.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/notify/__tests__/helpers.ts is excluded by !**/__tests__/** and included by packages/**
  • packages/notify/__tests__/notify.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/notify/__tests__/queue.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/notify/__tests__/subscriptions.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/notify/__tests__/web.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/studio/__tests__/features/logs/log-level-variant.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/studio/__tests__/features/logs/sync-client-panel.test.tsx is excluded by !**/__tests__/** and included by packages/**
  • packages/studio/__tests__/features/reports/instrument-format.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/studio/__tests__/features/traces/trace-geometry.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • shared/ssrf-host.ts is excluded by none and included by none
📒 Files selected for processing (13)
  • packages/notify/README.md
  • packages/notify/src/define-notify.ts
  • packages/notify/src/notify.ts
  • packages/notify/src/queue.ts
  • packages/notify/src/subscriptions/d1-store.ts
  • packages/notify/src/subscriptions/memory-store.ts
  • packages/notify/src/subscriptions/normalize.ts
  • packages/notify/src/types.ts
  • packages/notify/src/web.ts
  • packages/notify/tsconfig.json
  • packages/runtime/src/create-worker.ts
  • packages/studio/src/features/notifications/notifications-panel.tsx
  • packages/studio/vitest.config.ts

Comment thread packages/runtime/src/create-worker.ts Resolved
@codspeed

codspeed Bot commented Jul 26, 2026 •

Copy link
Copy Markdown

Merging this PR will regress 1 benchmark

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 1 improved benchmark
❌ 1 regressed benchmark
✅ 237 untouched benchmarks
⏩ 2 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

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

Open in CodSpeed

Footnotes

  1. 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. ↩

  2. 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. ↩

prisis and others added 13 commits July 26, 2026 09:50
…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>
@prisis
prisis force-pushed the advisor/192-delta-test-coverage branch from 112f2a5 to 52e1df2 Compare July 26, 2026 07:50
@prisis
prisis merged commit 66d8e11 into alpha Jul 26, 2026
15 of 17 checks passed
@prisis
prisis deleted the advisor/192-delta-test-coverage branch July 26, 2026 07:50
prisis added a commit that referenced this pull request Jul 26, 2026
* 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>
prisis added a commit that referenced this pull request Jul 28, 2026
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>
@github-actions

github-actions Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

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.
Please note this issue tracker is not a help forum. We recommend using our GitHub Discussions tab for questions.

@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Sep 8, 2026

This branch was previously deployed

1 inactive deployment
benchmarks — 52e1df2e Deployed Jul 26, 2026 by prisis via Benchmarks #993
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant