storage,server,cli: an oversized streamed body now rejects the upload() call with PAYLOAD_TOO_LARGE rather than resolving and erroring later when the bucket drains the stream. list() never sent include, and under r2_list_honor_include (every compat date since 2022-08-04) R2 omits httpMetadata/customMetadata from list entries unless asked. The projection copied both as if present, so a real bucket returned empty bags for every entry while head() on the same key returned them in full. R2BucketLike.list had no include either, so nothing COULD ask. The JS WhereInput evaluator behind rls() diverged from the SQL compiler it mirrors, twice, both fail-open on the write path. A non-array notIn passed every row where the compiler throws BAD_REQUEST — a policy written to keep admin rows out admitted one on write. And a NULL cell passed ne/notIn, where SQL's three-valued logic excludes it. Both are fixed at the shared operator evaluator, so the read filter, the write USING/WITH-CHECK gates and the expectPolicy harness all move together; in gets the same refusal, and eq/ne against a null operand keep folding to IS NULL/IS NOT NULL. The SQL side is unchanged. migrate generate emitted NOT NULL for a .nullable() column: the CLI derived nullability from v.optional alone, though the runtime rule is notNull AND not optional, and .nullable() is what clears notNull. A table created from the migration file rejected the null the column exists to accept while the auto-provisioned one took it. It now reads nullable off the FieldSnapshot the snapshot already carries. The gate was the real defect for the first two: the unit suite's fake bucket accepts any stream and returns whatever it stored, so only the workerd suite can see either. It now uploads a stream and asserts list metadata. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(storage): bound the buffered upload path and validate the cap that bounds it Capping a streamed upload buffers it, so maxSize is now the per-request memory ceiling — and nothing checked that it was a usable number. typeof NaN === "number" let a NaN cap into the branch, where seen > NaN is never true: the cap silently off while the whole body was still collected into the isolate, an unbounded buffer from something as ordinary as an unset byte-limit variable coerced with Number(...). A negative cap is the mirror image — seen > -1 is true on the first chunk, so every upload was refused. Both now fail up front as VALIDATION_ERROR. The ceiling is shared, not per request: N in-flight uploads hold up to N x maxSize against one ~128 MB isolate, so a 50 MB cap OOMs three uploads deep with every one inside its documented limit. A streamed maxSize above 16 MiB is therefore refused with a pointer to createMultipartUpload/createUploadHandler, which never hold the whole object. "Omit maxSize" is dropped as the escape hatch for large objects — the advisor lint fires on exactly that, so the two guidances contradicted each other; the lint's remediation now names the multipart path instead, which it does not flag. The counter accepts every BufferSource shape but re-enqueued the original chunk, and undici's Response body takes only Uint8Array, so an ArrayBuffer/DataView/Float32Array chunk failed with a bare TypeError: Received non-Uint8Array chunk — no code, nothing naming storage. Chunks are normalised to a Uint8Array view (no copy). workerd accepts the raw shapes, so this only ever broke under Node; the workerd suite now carries the case either way. Also documents that a list() page may hold fewer objects than limit, since R2 shrinks a page to fit the metadata include asks for — paginate on truncated/cursor. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(server): evaluate rls predicates under sql's three-valued logic The JS WhereInput evaluator folded SQL's UNKNOWN into false at each operator. That is the right answer at the top of a WHERE and the wrong one under a NOT: NOT UNKNOWN is UNKNOWN and still excludes the row, while !false is true and admits it. { NOT: { role: { ne: "admin" } } } against a NULL cell therefore admitted a row SQL excludes — fail-open on the write gate. The evaluator now carries the three values (FALSE < UNKNOWN < TRUE, so AND is the minimum, OR the maximum, NOT the reflection) and collapses them exactly once, in matchesWhere, where only TRUE keeps the row. No operator has to reason about whether UNKNOWN happens to be safe at its position. Closed by the same change: - in kept the mirror of the notIn bug. [null, "admin"].includes(null) is true in JS, so a NULL cell passed a membership check SQL excludes unconditionally. A write policy { tenantId: { in: allowedTenants } } whose list carried a null admitted a tenantId: null row that every read of the same policy then hid. - contains and the ordered comparators admitted a NULL cell under a NOT, for the reason ne did. A NULL *operand* on an ordered comparator stays FALSE, which is what the compiler emits. - an undefined operand — { ownerId: undefined }, { ownerId: { eq: undefined } }, or an undefined member of an in list — now raises BAD_REQUEST. It is a dropped variable: the SQL compiler binds the placeholder so the driver rejects the statement, while this evaluator compared with !== and quietly matched every row that lacked the column. - the equality shorthand reads an absent column as SQL NULL, so { role: null } means role IS NULL the way it does in SQL. The matchesOperators docblock claimed full NULL parity. It now names the three divergences that remain — case-sensitive contains, and two degenerate shapes that stay deliberately fail-closed. BREAKING: the evaluator also backs the legacy query() row filter and expectPolicy, so reads converge on the same answers. A NULL cell that a ne/in/notIn/contains read policy used to return from query() is now filtered out, matching what the SQL readers always did. A malformed operand that used to be ignored there now throws BAD_REQUEST from inside the filter, so an app with a scalar notIn or a dropped variable in a read policy goes from a silent wrong answer to a visible 400 on every legacy query(). Every row of the truth table pinned in rls-null-semantics.test.ts was produced by compiling the predicate with compileWhereSql, rendering it and running it on node:sqlite — none of it from memory. Eight of the sixteen cases fail against the pre-change evaluator, all in the fail-open direction. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
refactor(server): move the rls where evaluator into its own module rls/middleware.ts was 2,035 lines and 400 of them were a self-contained pure evaluator that has to be read against @lunora/shard-engine's where-sql.ts to be reviewed at all — the two are parallel implementations of one predicate language, and their agreement is a security property, not a nicety. Moved verbatim to rls/where-match.ts, which states that contract in its header: what the twin is for, why it exists twice, and where the pinned truth table lives. containsRelationPredicate and matchesWhere are the only two names the middleware used; matchesWhere stays re-exported from ./middleware so the in-process harness and the sibling middlewares keep one import site. No behaviour change — the only edit to a moved line is a JSDoc {@link} that no longer resolves across the file boundary. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
test(server): pin that a malformed NOT operand cannot admit a write Review raised { NOT: "a" } as a fail-open: the operand is cast to a WhereInput and recursed, and Object.keys("a") is ["0"], so it tests a column no document has. It was fail-open under the boolean evaluator — an absent column read FALSE and NOT flipped it to a write-admitting TRUE. The three-valued rewrite closed it: an absent column is UNKNOWN, kleeneNot(UNKNOWN) is UNKNOWN, and only TRUE admits. Verified by probe across string, array and number operands. No behaviour change — these are guard rails, and the comment says so rather than implying they repair something. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
test(server): type the malformed-NOT operands the evaluator is asked to refuse Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
Fixed
storage,server,cli: make streaming uploads work, and stop RLS writes failing open (#616) (c76d854)
adapters: the presence result types in all four ports, and the agent/agent-chat results in Angular, Solid and Vue, gained a required error member. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
chore(api): accept the onError and error members on the adapter primitives Presence, agent and agent-chat in the Solid, Svelte and Vue ports gain the error channel React already exposed. Additive only. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(config,runtime): repair alpha's typecheck, lint and tests after the audit merges Three PRs landed within a minute of each other and left alpha red on four checks. Every PR opened against it inherits the failure, which is what surfaced this: an adapters-only branch failing on packages/config. InferredBindings never gained usesNotify and usesR2sql, though CAPABILITY_SOURCES and the inference pass both emit them — six type errors across the interface, its Pick<> and two test fixtures. The members are now declared, and reconcile-bindings's fixture carries them. no-secrets flagged isTypeOnlyExportRegexFallback where it appears in prose, inside a {@link} in a doc block. Wrapped with the scoped disable this file already uses for frameworkComposePlugin two hundred lines above — and the reason deliberately does NOT repeat the flagged identifier, which is what made a first attempt at the disable trip the rule on its own comment. The package-manager probe's double could not satisfy all three of its gates at once: vitest/require-mock-type-parameters wants a type argument on vi.fn, arrow-body-style wants a concise body, and typeof spawnSync is a four-overload signature that a Mock<…> collapses to its last member. It now takes a generic matching its own implementation, with a single cast where the double is handed to the module factory — not spread over the assertions. pipeline-log-reader's test still asserted an unparenthesised WHERE. That is stale, not wrong output: SelectBuilder now wraps each .where() fragment so a condition containing OR cannot bind looser than the AND joining them, and @lunora/runtime is a cross-package consumer whose suite the change never ran. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(angular,vue,solid): keep a reactive skip skipped on SSR, and correct the error docs Two review findings, both verified before acting. paginatedQuery's reactive-args branch attaches no core during SSR, so skipped fell back to false while status fell back to "LoadingFirstPage". Since isLoading is !skipped && status === "LoadingFirstPage", a getter resolving to "skip" reported a spinner that never resolves — the exact defect this branch fixes for the attached case, surviving on the path with no core. The fallback now reads the getter, the same source the attached path uses. Angular is the only port with this shape; the other three read their args directly. The onError docblocks said the affected state freezes at its last value. It does not: the subscription primitive clears it. Checking each port rather than editing in bulk turned up a real divergence — Vue, Angular and Solid all set their value to undefined on error, while SVELTE alone leaves the value store untouched, so its stores genuinely do freeze. The eight clearing sites now say "cleared until a later frame arrives"; Svelte's two say freeze AND name the divergence, so the next reader sees it is deliberate rather than an oversight. The new SSR test was proved to discriminate: reverting the one-line fallback makes it fail, restoring it makes it pass. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
style(angular): flatten the SSR skip-test call to satisfy consistent-list-newline Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
chore(api,do): accept the two InferredBindings members and defuse the fixture token usesNotify and usesR2sql are additive on an interface the inference pass already populated; the snapshot now records them. The system-dispatch test's admin header tripped the secret scanner. The value is renamed to an obviously-inert test-admin-token matching the DO's own env fixture, with the scanner's own trailing allow marker — it has to sit ON the flagged line, not above it. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
Fixed
adapters: guard SSR in the Svelte, Angular and Vue primitives, and give four ports an error channel (#612) (b7ec05e)
ratelimit,auth:accessRoles() and the @lunora/cloudflare-access/roles subpath are removed. Use createAccessResolver({ roles }) instead. AccessRoleMap now exports from the package root. Corrects the three places that told a reader the two paths agree: the emit.ts comment claiming composeShapeReadWhere is "exactly the request-time path", the package docs, and the RLS concept page. The golden _generated/shard.ts fixture is regenerated for the emitted comment. Second fix in the same resolver: a platform identity carrying no usable id suppressed the configured JWT fallback. ?? falls through on nullish only, and readPlatformIdentity returns an object for any non-null object result, {} included — so a caller presenting a valid Cf-Access-Jwt-Assertion resolved anonymous with nothing verified and onError never firing. The resolver now falls through whenever the platform identity yields no identity, and stays fail-closed when neither path does. That trigger was reasoned from the code rather than observed — whether Cloudflare ever returns such an identity is unverified — so the fix is deliberately defensive. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(ratelimit): stop a reserve stranding a key and misreporting retry Three defects on the reserve path, all reachable through the public API and through token-budget.ts, which clamps an oversized charge to capacity and reserves it. A fixed window granted exactly one period's rate however many periods had elapsed, while the rejection path persists nothing. A debt of at least rate therefore re-projected against that same lone grant on every later call and the key stayed denied forever, told "retry next window" every window. The projection now grants one rate per elapsed window, the way the token bucket refills per elapsed millisecond; the existing capacity cap still bounds the result. The old test reserved 2 against rate 5 — a debt smaller than rate, which is the case that recovers — so it passed throughout, and now covers a debt of a full rate. The deny-list was stored verbatim while the incoming key was checked both normalized and raw, under a comment claiming either form worked. Only a byte-exact repeat of the stored string matched: with a trim+lowercase normalizer, denyList: ["Abuse@Example.com"] admitted a request keyed abuse@example.com that consumed from the same storage bucket, so a banned caller shed the ban by lower-casing their own email. Entries are now stored in both forms at construction. A sliding-window reserve derived its retryAfter from the pre-reserve count while persisting currentCount + count, so the time it reported was still denied when it arrived and the caller burned a rejected attempt — a re-queued durable write wakes on that hint verbatim. It is now derived from the count the call actually stores. The old assertion pinned 1200 under the title "reports when the pressure clears"; the true clear time is 1334, and the test now re-evaluates at the reported time to prove it is honoured. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(auth): trust cf-connecting-ip only behind Cloudflare resolveIp in the audit hooks returned cf-connecting-ip before consulting trustProxyHeaders, though that option's own docblock promises the opposite: "Defaults to false: off Cloudflare, with no trusted proxy configured, the audit record's ip is omitted rather than populated from a spoofable header." Off Cloudflare nothing overwrites that header, so an attacker setting it per request owned the ip on every sign-in, password-reset and mfa-disable row they generated — rows Studio surfaces through getAuthAuditLog. Forensic impact only: nothing enforces on the audit ip. It now applies the same onCloudflareEdge() gate that create-auth.ts's defaultIpAddressHeaders already applies, so this package's two client-IP resolvers cannot disagree about who a request came from. onCloudflareEdge moves from a file-private const to a named export of create-auth.ts; it is not re-exported from the package index, so the public API is unchanged. The existing cases asserting cf-connecting-ip did not say which runtime they ran on and passed under Node's navigator.userAgent; they now stub the Cloudflare one explicitly, alongside two new cases for the off-Cloudflare behaviour. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(runtime): key IP-less REST callers and 403 a deny-list hit createRestRateLimit charged its limit with no key at all when cf-connecting-ip was absent, putting every such caller in that limit's UNKEYED bucket — the same one a deliberately-global charge of the name uses — so one anonymous caller could drain an app-wide limit. This is the caller-pooling @lunora/ratelimit's own middleware refuses outright. They now share a named no-trusted-ip bucket, which keeps the blast radius to the IP-less callers themselves and makes the pooling visible in storage; pass options.key to key them properly. A deny-list hit carries retryAfter: Infinity and was mapped to 429 with the header Retry-After: Infinity, inviting a client to keep retrying a denial that never clears. It now answers 403 FORBIDDEN with no Retry-After, matching what both @lunora/ratelimit entry points produce. RateLimiterLike gains the optional reason the limiter already returns. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
Fixed
auth,sql-store,codegen: stop the auth migrator killing the isolate, and the global sweep re-running per request (#613) (f170c82), closes #599#601#600#601
ratelimit,auth: unstick a bricked limiter and close the deny-list bypass (#606) (fd7d6ad)
codegen:@lunora/config no longer exports ResourceGraph, NamedResource, ShardNamespaceResource, ProvisionResult or DriverContext, and DeployDriver is now { id, name, toolchain? } — infer and provision are gone. @lunora/bindings/images no longer exports DrawOverlay, and TransformOptions has no draw key. Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Fixed
codegen: gate on the context binding, not the identifier text (#609) (c0bc210)
storage,server,cli: an oversized streamed body now rejects the upload() call with PAYLOAD_TOO_LARGE rather than resolving and erroring later when the bucket drains the stream. list() never sent include, and under r2_list_honor_include (every compat date since 2022-08-04) R2 omits httpMetadata/customMetadata from list entries unless asked. The projection copied both as if present, so a real bucket returned empty bags for every entry while head() on the same key returned them in full. R2BucketLike.list had no include either, so nothing COULD ask. The JS WhereInput evaluator behind rls() diverged from the SQL compiler it mirrors, twice, both fail-open on the write path. A non-array notIn passed every row where the compiler throws BAD_REQUEST — a policy written to keep admin rows out admitted one on write. And a NULL cell passed ne/notIn, where SQL's three-valued logic excludes it. Both are fixed at the shared operator evaluator, so the read filter, the write USING/WITH-CHECK gates and the expectPolicy harness all move together; in gets the same refusal, and eq/ne against a null operand keep folding to IS NULL/IS NOT NULL. The SQL side is unchanged. migrate generate emitted NOT NULL for a .nullable() column: the CLI derived nullability from v.optional alone, though the runtime rule is notNull AND not optional, and .nullable() is what clears notNull. A table created from the migration file rejected the null the column exists to accept while the auto-provisioned one took it. It now reads nullable off the FieldSnapshot the snapshot already carries. The gate was the real defect for the first two: the unit suite's fake bucket accepts any stream and returns whatever it stored, so only the workerd suite can see either. It now uploads a stream and asserts list metadata. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(storage): bound the buffered upload path and validate the cap that bounds it Capping a streamed upload buffers it, so maxSize is now the per-request memory ceiling — and nothing checked that it was a usable number. typeof NaN === "number" let a NaN cap into the branch, where seen > NaN is never true: the cap silently off while the whole body was still collected into the isolate, an unbounded buffer from something as ordinary as an unset byte-limit variable coerced with Number(...). A negative cap is the mirror image — seen > -1 is true on the first chunk, so every upload was refused. Both now fail up front as VALIDATION_ERROR. The ceiling is shared, not per request: N in-flight uploads hold up to N x maxSize against one ~128 MB isolate, so a 50 MB cap OOMs three uploads deep with every one inside its documented limit. A streamed maxSize above 16 MiB is therefore refused with a pointer to createMultipartUpload/createUploadHandler, which never hold the whole object. "Omit maxSize" is dropped as the escape hatch for large objects — the advisor lint fires on exactly that, so the two guidances contradicted each other; the lint's remediation now names the multipart path instead, which it does not flag. The counter accepts every BufferSource shape but re-enqueued the original chunk, and undici's Response body takes only Uint8Array, so an ArrayBuffer/DataView/Float32Array chunk failed with a bare TypeError: Received non-Uint8Array chunk — no code, nothing naming storage. Chunks are normalised to a Uint8Array view (no copy). workerd accepts the raw shapes, so this only ever broke under Node; the workerd suite now carries the case either way. Also documents that a list() page may hold fewer objects than limit, since R2 shrinks a page to fit the metadata include asks for — paginate on truncated/cursor. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(server): evaluate rls predicates under sql's three-valued logic The JS WhereInput evaluator folded SQL's UNKNOWN into false at each operator. That is the right answer at the top of a WHERE and the wrong one under a NOT: NOT UNKNOWN is UNKNOWN and still excludes the row, while !false is true and admits it. { NOT: { role: { ne: "admin" } } } against a NULL cell therefore admitted a row SQL excludes — fail-open on the write gate. The evaluator now carries the three values (FALSE < UNKNOWN < TRUE, so AND is the minimum, OR the maximum, NOT the reflection) and collapses them exactly once, in matchesWhere, where only TRUE keeps the row. No operator has to reason about whether UNKNOWN happens to be safe at its position. Closed by the same change: - in kept the mirror of the notIn bug. [null, "admin"].includes(null) is true in JS, so a NULL cell passed a membership check SQL excludes unconditionally. A write policy { tenantId: { in: allowedTenants } } whose list carried a null admitted a tenantId: null row that every read of the same policy then hid. - contains and the ordered comparators admitted a NULL cell under a NOT, for the reason ne did. A NULL *operand* on an ordered comparator stays FALSE, which is what the compiler emits. - an undefined operand — { ownerId: undefined }, { ownerId: { eq: undefined } }, or an undefined member of an in list — now raises BAD_REQUEST. It is a dropped variable: the SQL compiler binds the placeholder so the driver rejects the statement, while this evaluator compared with !== and quietly matched every row that lacked the column. - the equality shorthand reads an absent column as SQL NULL, so { role: null } means role IS NULL the way it does in SQL. The matchesOperators docblock claimed full NULL parity. It now names the three divergences that remain — case-sensitive contains, and two degenerate shapes that stay deliberately fail-closed. BREAKING: the evaluator also backs the legacy query() row filter and expectPolicy, so reads converge on the same answers. A NULL cell that a ne/in/notIn/contains read policy used to return from query() is now filtered out, matching what the SQL readers always did. A malformed operand that used to be ignored there now throws BAD_REQUEST from inside the filter, so an app with a scalar notIn or a dropped variable in a read policy goes from a silent wrong answer to a visible 400 on every legacy query(). Every row of the truth table pinned in rls-null-semantics.test.ts was produced by compiling the predicate with compileWhereSql, rendering it and running it on node:sqlite — none of it from memory. Eight of the sixteen cases fail against the pre-change evaluator, all in the fail-open direction. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
refactor(server): move the rls where evaluator into its own module rls/middleware.ts was 2,035 lines and 400 of them were a self-contained pure evaluator that has to be read against @lunora/shard-engine's where-sql.ts to be reviewed at all — the two are parallel implementations of one predicate language, and their agreement is a security property, not a nicety. Moved verbatim to rls/where-match.ts, which states that contract in its header: what the twin is for, why it exists twice, and where the pinned truth table lives. containsRelationPredicate and matchesWhere are the only two names the middleware used; matchesWhere stays re-exported from ./middleware so the in-process harness and the sibling middlewares keep one import site. No behaviour change — the only edit to a moved line is a JSDoc {@link} that no longer resolves across the file boundary. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
test(server): pin that a malformed NOT operand cannot admit a write Review raised { NOT: "a" } as a fail-open: the operand is cast to a WhereInput and recursed, and Object.keys("a") is ["0"], so it tests a column no document has. It was fail-open under the boolean evaluator — an absent column read FALSE and NOT flipped it to a write-admitting TRUE. The three-valued rewrite closed it: an absent column is UNKNOWN, kleeneNot(UNKNOWN) is UNKNOWN, and only TRUE admits. Verified by probe across string, array and number operands. No behaviour change — these are guard rails, and the comment says so rather than implying they repair something. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
test(server): type the malformed-NOT operands the evaluator is asked to refuse Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
Fixed
storage,server,cli: make streaming uploads work, and stop RLS writes failing open (#616) (c76d854)
codegen:@lunora/config no longer exports ResourceGraph, NamedResource, ShardNamespaceResource, ProvisionResult or DriverContext, and DeployDriver is now { id, name, toolchain? } — infer and provision are gone. @lunora/bindings/images no longer exports DrawOverlay, and TransformOptions has no draw key. Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
cli:requiredPackagesFor / assertRequiredPackages take a signals object in place of the trailing hasVectors boolean. ImportSummary.storage carries capped ambiguous/unmigrated samples plus new ambiguousTotal / unmigratedTotal counts. InferredBindings gains usesNotify and usesR2sql. OfferDeps.resolveAuthUiItem may now return undefined, which callers must read as a refusal. verify and build accept --strict-advisories / --no-strict-advisories, and verify now fails on ERROR-level advisories under the same CI-on/local-off default as every other caller. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(cli): escape the NUL key separator and type the registry dispatch mocks The storage-remap dedup key used a raw NUL byte as its separator, which makes git treat the file as binary — invisible in diff, blame and review — and fails the no-nul-bytes postinstall gate, which turns every CI job red in its setup step while naming the cause in none of them. \\u0000 is byte-identical at runtime. The new registry-dispatch test's mocks returned { code, items } where all three runners return AddCommandResult (bindings/code/deps/skipped/written), and its toolbox cast named a wider options type than execute accepts. Neither surfaced earlier because the branch's verification skipped lint:types. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
Fixed
cli: make migrate fail loudly, and close thirteen more command defects (#608) (1eb481f)
codegen: gate on the context binding, not the identifier text (#609) (c0bc210)
ratelimit,auth:accessRoles() and the @lunora/cloudflare-access/roles subpath are removed. Use createAccessResolver({ roles }) instead. AccessRoleMap now exports from the package root. Corrects the three places that told a reader the two paths agree: the emit.ts comment claiming composeShapeReadWhere is "exactly the request-time path", the package docs, and the RLS concept page. The golden _generated/shard.ts fixture is regenerated for the emitted comment. Second fix in the same resolver: a platform identity carrying no usable id suppressed the configured JWT fallback. ?? falls through on nullish only, and readPlatformIdentity returns an object for any non-null object result, {} included — so a caller presenting a valid Cf-Access-Jwt-Assertion resolved anonymous with nothing verified and onError never firing. The resolver now falls through whenever the platform identity yields no identity, and stays fail-closed when neither path does. That trigger was reasoned from the code rather than observed — whether Cloudflare ever returns such an identity is unverified — so the fix is deliberately defensive. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(ratelimit): stop a reserve stranding a key and misreporting retry Three defects on the reserve path, all reachable through the public API and through token-budget.ts, which clamps an oversized charge to capacity and reserves it. A fixed window granted exactly one period's rate however many periods had elapsed, while the rejection path persists nothing. A debt of at least rate therefore re-projected against that same lone grant on every later call and the key stayed denied forever, told "retry next window" every window. The projection now grants one rate per elapsed window, the way the token bucket refills per elapsed millisecond; the existing capacity cap still bounds the result. The old test reserved 2 against rate 5 — a debt smaller than rate, which is the case that recovers — so it passed throughout, and now covers a debt of a full rate. The deny-list was stored verbatim while the incoming key was checked both normalized and raw, under a comment claiming either form worked. Only a byte-exact repeat of the stored string matched: with a trim+lowercase normalizer, denyList: ["Abuse@Example.com"] admitted a request keyed abuse@example.com that consumed from the same storage bucket, so a banned caller shed the ban by lower-casing their own email. Entries are now stored in both forms at construction. A sliding-window reserve derived its retryAfter from the pre-reserve count while persisting currentCount + count, so the time it reported was still denied when it arrived and the caller burned a rejected attempt — a re-queued durable write wakes on that hint verbatim. It is now derived from the count the call actually stores. The old assertion pinned 1200 under the title "reports when the pressure clears"; the true clear time is 1334, and the test now re-evaluates at the reported time to prove it is honoured. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(auth): trust cf-connecting-ip only behind Cloudflare resolveIp in the audit hooks returned cf-connecting-ip before consulting trustProxyHeaders, though that option's own docblock promises the opposite: "Defaults to false: off Cloudflare, with no trusted proxy configured, the audit record's ip is omitted rather than populated from a spoofable header." Off Cloudflare nothing overwrites that header, so an attacker setting it per request owned the ip on every sign-in, password-reset and mfa-disable row they generated — rows Studio surfaces through getAuthAuditLog. Forensic impact only: nothing enforces on the audit ip. It now applies the same onCloudflareEdge() gate that create-auth.ts's defaultIpAddressHeaders already applies, so this package's two client-IP resolvers cannot disagree about who a request came from. onCloudflareEdge moves from a file-private const to a named export of create-auth.ts; it is not re-exported from the package index, so the public API is unchanged. The existing cases asserting cf-connecting-ip did not say which runtime they ran on and passed under Node's navigator.userAgent; they now stub the Cloudflare one explicitly, alongside two new cases for the off-Cloudflare behaviour. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(runtime): key IP-less REST callers and 403 a deny-list hit createRestRateLimit charged its limit with no key at all when cf-connecting-ip was absent, putting every such caller in that limit's UNKEYED bucket — the same one a deliberately-global charge of the name uses — so one anonymous caller could drain an app-wide limit. This is the caller-pooling @lunora/ratelimit's own middleware refuses outright. They now share a named no-trusted-ip bucket, which keeps the blast radius to the IP-less callers themselves and makes the pooling visible in storage; pass options.key to key them properly. A deny-list hit carries retryAfter: Infinity and was mapped to 429 with the header Retry-After: Infinity, inviting a client to keep retrying a denial that never clears. It now answers 403 FORBIDDEN with no Retry-After, matching what both @lunora/ratelimit entry points produce. RateLimiterLike gains the optional reason the limiter already returns. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
Fixed
ratelimit,auth: unstick a bricked limiter and close the deny-list bypass (#606) (fd7d6ad)
codegen:@lunora/config no longer exports ResourceGraph, NamedResource, ShardNamespaceResource, ProvisionResult or DriverContext, and DeployDriver is now { id, name, toolchain? } — infer and provision are gone. @lunora/bindings/images no longer exports DrawOverlay, and TransformOptions has no draw key. Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
cli:requiredPackagesFor / assertRequiredPackages take a signals object in place of the trailing hasVectors boolean. ImportSummary.storage carries capped ambiguous/unmigrated samples plus new ambiguousTotal / unmigratedTotal counts. InferredBindings gains usesNotify and usesR2sql. OfferDeps.resolveAuthUiItem may now return undefined, which callers must read as a refusal. verify and build accept --strict-advisories / --no-strict-advisories, and verify now fails on ERROR-level advisories under the same CI-on/local-off default as every other caller. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(cli): escape the NUL key separator and type the registry dispatch mocks The storage-remap dedup key used a raw NUL byte as its separator, which makes git treat the file as binary — invisible in diff, blame and review — and fails the no-nul-bytes postinstall gate, which turns every CI job red in its setup step while naming the cause in none of them. \\u0000 is byte-identical at runtime. The new registry-dispatch test's mocks returned { code, items } where all three runners return AddCommandResult (bindings/code/deps/skipped/written), and its toolbox cast named a wider options type than execute accepts. Neither surfaced earlier because the branch's verification skipped lint:types. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
ratelimit,auth:accessRoles() and the @lunora/cloudflare-access/roles subpath are removed. Use createAccessResolver({ roles }) instead. AccessRoleMap now exports from the package root. Corrects the three places that told a reader the two paths agree: the emit.ts comment claiming composeShapeReadWhere is "exactly the request-time path", the package docs, and the RLS concept page. The golden _generated/shard.ts fixture is regenerated for the emitted comment. Second fix in the same resolver: a platform identity carrying no usable id suppressed the configured JWT fallback. ?? falls through on nullish only, and readPlatformIdentity returns an object for any non-null object result, {} included — so a caller presenting a valid Cf-Access-Jwt-Assertion resolved anonymous with nothing verified and onError never firing. The resolver now falls through whenever the platform identity yields no identity, and stays fail-closed when neither path does. That trigger was reasoned from the code rather than observed — whether Cloudflare ever returns such an identity is unverified — so the fix is deliberately defensive. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(ratelimit): stop a reserve stranding a key and misreporting retry Three defects on the reserve path, all reachable through the public API and through token-budget.ts, which clamps an oversized charge to capacity and reserves it. A fixed window granted exactly one period's rate however many periods had elapsed, while the rejection path persists nothing. A debt of at least rate therefore re-projected against that same lone grant on every later call and the key stayed denied forever, told "retry next window" every window. The projection now grants one rate per elapsed window, the way the token bucket refills per elapsed millisecond; the existing capacity cap still bounds the result. The old test reserved 2 against rate 5 — a debt smaller than rate, which is the case that recovers — so it passed throughout, and now covers a debt of a full rate. The deny-list was stored verbatim while the incoming key was checked both normalized and raw, under a comment claiming either form worked. Only a byte-exact repeat of the stored string matched: with a trim+lowercase normalizer, denyList: ["Abuse@Example.com"] admitted a request keyed abuse@example.com that consumed from the same storage bucket, so a banned caller shed the ban by lower-casing their own email. Entries are now stored in both forms at construction. A sliding-window reserve derived its retryAfter from the pre-reserve count while persisting currentCount + count, so the time it reported was still denied when it arrived and the caller burned a rejected attempt — a re-queued durable write wakes on that hint verbatim. It is now derived from the count the call actually stores. The old assertion pinned 1200 under the title "reports when the pressure clears"; the true clear time is 1334, and the test now re-evaluates at the reported time to prove it is honoured. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(auth): trust cf-connecting-ip only behind Cloudflare resolveIp in the audit hooks returned cf-connecting-ip before consulting trustProxyHeaders, though that option's own docblock promises the opposite: "Defaults to false: off Cloudflare, with no trusted proxy configured, the audit record's ip is omitted rather than populated from a spoofable header." Off Cloudflare nothing overwrites that header, so an attacker setting it per request owned the ip on every sign-in, password-reset and mfa-disable row they generated — rows Studio surfaces through getAuthAuditLog. Forensic impact only: nothing enforces on the audit ip. It now applies the same onCloudflareEdge() gate that create-auth.ts's defaultIpAddressHeaders already applies, so this package's two client-IP resolvers cannot disagree about who a request came from. onCloudflareEdge moves from a file-private const to a named export of create-auth.ts; it is not re-exported from the package index, so the public API is unchanged. The existing cases asserting cf-connecting-ip did not say which runtime they ran on and passed under Node's navigator.userAgent; they now stub the Cloudflare one explicitly, alongside two new cases for the off-Cloudflare behaviour. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(runtime): key IP-less REST callers and 403 a deny-list hit createRestRateLimit charged its limit with no key at all when cf-connecting-ip was absent, putting every such caller in that limit's UNKEYED bucket — the same one a deliberately-global charge of the name uses — so one anonymous caller could drain an app-wide limit. This is the caller-pooling @lunora/ratelimit's own middleware refuses outright. They now share a named no-trusted-ip bucket, which keeps the blast radius to the IP-less callers themselves and makes the pooling visible in storage; pass options.key to key them properly. A deny-list hit carries retryAfter: Infinity and was mapped to 429 with the header Retry-After: Infinity, inviting a client to keep retrying a denial that never clears. It now answers 403 FORBIDDEN with no Retry-After, matching what both @lunora/ratelimit entry points produce. RateLimiterLike gains the optional reason the limiter already returns. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
Fixed
auth,sql-store,codegen: stop the auth migrator killing the isolate, and the global sweep re-running per request (#613) (f170c82), closes #599#601#600#601
cli: make migrate fail loudly, and close thirteen more command defects (#608) (1eb481f)
codegen: gate on the context binding, not the identifier text (#609) (c0bc210)
ratelimit,auth: unstick a bricked limiter and close the deny-list bypass (#606) (fd7d6ad)
scheduler,workflow: give a scheduled workflow an idempotency key (#605) (0f3afb4)
codegen:@lunora/config no longer exports ResourceGraph, NamedResource, ShardNamespaceResource, ProvisionResult or DriverContext, and DeployDriver is now { id, name, toolchain? } — infer and provision are gone. @lunora/bindings/images no longer exports DrawOverlay, and TransformOptions has no draw key. Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
cli:requiredPackagesFor / assertRequiredPackages take a signals object in place of the trailing hasVectors boolean. ImportSummary.storage carries capped ambiguous/unmigrated samples plus new ambiguousTotal / unmigratedTotal counts. InferredBindings gains usesNotify and usesR2sql. OfferDeps.resolveAuthUiItem may now return undefined, which callers must read as a refusal. verify and build accept --strict-advisories / --no-strict-advisories, and verify now fails on ERROR-level advisories under the same CI-on/local-off default as every other caller. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(cli): escape the NUL key separator and type the registry dispatch mocks The storage-remap dedup key used a raw NUL byte as its separator, which makes git treat the file as binary — invisible in diff, blame and review — and fails the no-nul-bytes postinstall gate, which turns every CI job red in its setup step while naming the cause in none of them. \\u0000 is byte-identical at runtime. The new registry-dispatch test's mocks returned { code, items } where all three runners return AddCommandResult (bindings/code/deps/skipped/written), and its toolbox cast named a wider options type than execute accepts. Neither surfaced earlier because the branch's verification skipped lint:types. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
Fixed
cli: make migrate fail loudly, and close thirteen more command defects (#608) (1eb481f)
codegen: gate on the context binding, not the identifier text (#609) (c0bc210)
data:LocalMirror's onChange callback receives a "diff" | "clear" reason argument. A zero-argument callback is unaffected. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(replica): let a replay reach the log's own readers events() promises to yield every entry "continuing with every future applyEvent / replayFromLog call", but it streams off state-changed and replayFromLog emitted only replay-error/ready. Its phase-1 catch-up loop exits once, so every entry a replay appended was invisible to a generator already running. Each replayed entry now emits state-changed, the same notification applyEvent emits for the same reason. The same append also dropped the source entry's timestamp, so EventLog#append stamped Date.now() and a replay rewrote history to the moment it ran — forty lines below applyEvent, which pins the timestamp deliberately (REPLICA-07) so a timestamp-dependent reducer stays reproducible. It is pinned on both paths now. EventLog#append discarded an InputEvent's own required timestamp the same way, while commitAll has always preserved it; and getFrom(fromSeq, 0) returned { entries: [], hasMore: true }, which spins a paginating caller on a page it can never advance past — limit is now validated like maxEntries and truncateBelow's floor. Also corrects TableDiff.id's docblock: it describes a deriveInsertId derivation apply-diff.ts deliberately no longer does (hashing the diff id into a row key is what grew the mirror by a row a second). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(shard-engine): page and rank past a NULL sort column A rank sort column genuinely holds NULL — syncRankIndexEntry writes record[field] ?? null, so a document simply missing the field is a NULL in __sort_k<i>__ — and col > NULL / col < NULL are both UNKNOWN. The lexicographic seek used NULL-safe IS for the prefix equalities but a bare comparator at the pivot, so: - the rankPage that first reached the NULL group came back EMPTY, with isDone: false on the page before it, and pagination stopped there; and - rank() returned a confident position counted against a partial set, next to a correct total. Four sites had the same shape (the DO writer's seek and its countRankBefore, and the SQL store's twins of both). All four now go through one rankPivotConditionSql, which is the treatment pivotCondition already applies to the row-store's keyset seek: a NULL pivot resolves to "every non-null row" or "no row" depending on which side is sought, and a non-null pivot picks up the NULL group with an IS NULL arm when the ordering puts it there. A branch that cannot match is dropped rather than emitted as an always-false disjunct. The SQL store's rank ORDER BY also named no NULL placement, so on Postgres (NULLS LAST ascending) the NULL group sat opposite where the seek assumes it is. It now states the placement for the sort columns the way compileOrderBySql already does for every other read. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(sql-store): round-trip a scalar in an untyped column v.any(), v.union() and v.from() all store as TEXT — SQLite affinity TEXT, Postgres TEXT, MySQL LONGTEXT — and sqliteEncode keys off the runtime type, so a number or boolean written to one was COERCED by the engine on the way in: 42 landed as the text 42.0, true (encoded 1) as 1.0. The decode had no declared type to reverse that with, so the caller read back a string. The codec's own docblock claimed a scalar member "round-trips through SQLite's native column type"; it cannot, and the unit test that pinned the claim called sqliteDecode with a JS value that had never been bound to a column. sqliteEncode now takes the column's kind and writes a number or boolean in those three kinds in the marked, self-describing form the composites already use, which sqliteDecode reverses by the marker alone. Strings, bigints and composites keep the storage form they had: the WHERE path binds through the same function without a kind, and changing them would stop existing equality filters matching. Equality on an untyped numeric column did not match before this either (a stored 42.0 never equalled a bound 42), so nothing regresses. The kind reaches the encoder only where the caller knows which column it is filling — insert, upsert's soft-delete update, patch, replace — through serializeDocumentColumn. serializeColumnValue stays kind-blind because it also binds every WHERE comparison and the rank companion's sort keys, where both sides of a comparison have to agree byte for byte. The regression test writes and reads through a real column; asserting on sqliteDecode alone is what let this ship. api-snapshots/sql-store.api.md records this widening together with the SqlDialect.columnType one from the MySQL .unique() fix that follows, so the snapshot lands with that commit rather than being written twice. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(hyperdrive): index a .unique() column whole on mysql InnoDB cannot index a LONGTEXT without a key prefix, indexKeyPrefix supplies 191, and the synthesized .unique() index went through the same indexRef as every other index — so the constraint enforced uniqueness of the first 191 CHARACTERS. Two distinct 200-character values sharing that prefix raised ER_DUP_ENTRY, which mapWriteError surfaced as "unique constraint violation": a rejected write with a correct-looking error, on MySQL only, where D1 and Postgres both accept it. A .unique() character column is now declared VARCHAR(768) (768 × 4 bytes under utf8mb4 is exactly InnoDB's 3072-byte single-column key limit), bytes VARBINARY(768), and the synthesized index takes no prefix. A value past the bound is a loud write error rather than a wrong conflict. The numeric kinds and bigint's VARCHAR(64) key were already indexable whole and are unchanged, as are SQLite and Postgres, which index text of any length. Pre-existing MySQL tables keep the type they were created with — the same caveat the column collation carries, and for the same reason: CREATE TABLE IF NOT EXISTS does not reshape one. Converting is ALTER TABLE <t> MODIFY <col> VARCHAR(768) COLLATE utf8mb4_0900_bin.
data:SqlDialect.columnType takes an optional second argument { unique?: boolean }. A dialect implementing the one-argument signature still satisfies it. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
security(hyperdrive): reject a vector filter shape json cannot represent The containment-filter guard exists because a filter this store cannot honour must be an ERROR rather than a silent drop, and its own docblock names the case it then failed to catch. The walk recursed through Object.entries, which is [] for a Map, a Set, a Date or a class instance — so it inspected nothing and rejected nothing, while JSON.stringify turned the value into {}. metadata @> '{"tenant":{}}'::jsonb is satisfied by every row that has metadata at all: a filter that fails OPEN, across tenants. At the top level it was worse. Object.keys(someMap).length is 0, so the length > 0 gates skipped both the guard and the containment clause, and the query went out with no filter on it whatsoever. Both are now rejected by prototype — the only test that can see a shape whose own enumerable entries are not its contents — and the guard runs on any filter that is present rather than on one with countable keys.
data: a Date in a metadata filter is now rejected along with Map, Set and class instances. Pre-compute it into an equality-shaped metadata field. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
security(d1): decode a studio table as global only when it is The database browser branched on schema.tables[table] !== undefined — whether the schema declares that NAME — with no shardMode check, in six places. But only a .global() table lives in D1, so a same-named .shardBy()/root table describes a Durable Object's storage, not the D1 table being read. A schema declaring a shard-local user alongside better-auth's D1 user sent every read of the D1 table down the schema branch: it was decoded as a .global() row, so the password|secret|token|hash|salt|credential redaction never ran, and the same wrong branch simultaneously disabled the two guards that exist BECAUSE redaction is imperfect — the eq-filter equality oracle and the facet's masked bucket. Every site now goes through one globalTableDefinition, the test the admin export/import path already applies. Two ordering defects in the same reader: - the page read was LIMIT ? OFFSET ? with no ORDER BY, so which rows a page contains was up to the plan and two identical requests could disagree — a row could appear on two pages or on none. It now orders by the table's id (every .global() table has a TEXT primary key), or rowid for an external table without one. The shard browser keyset-paginates for the same reason. - the facet's ORDER BY count DESC had no tiebreaker, so which equally-frequent values land in the top-N — and whether the result reports truncated — was planner-dependent. It now breaks ties on the value. Also corrects the D1 dialect's docblock, which described bigint as "serialized as a decimal string" where the shared encoder writes the order-preserving 40-character key. Both sibling dialects describe it correctly, and this module is what the lunora migrate generate emitter reads for the physical column form. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
test(shard-engine): give the wide-where case more than one condition Object.fromEntries(Array.from({ length: 200 }, () => ["title", "kept"])) is { title: "kept" } — an object literal holds each key once. The only behavioural case in the expression-depth-cap suite therefore ran ONE condition while claiming 200, and passed identically with compileWhereSql's halving-pair nesting deleted. It now builds distinct fields. 90 of them, not 200, because the two caps meet here: one equality binds one parameter and the bound-parameter ceiling the suite above pins is 100, so a genuinely-200-term where is rejected before it can be executed at all. The structural widestChain assertions still cover the full 200 — those were never vacuous, and they are what discriminates against an un-nested implementation; a flat 90-term AND is well under stock SQLite's expression-depth limit, so this case cannot. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(d1): teach the migration lexer sqlite's other identifier quotings The single-statement check models '…', "…", -- and /* */, but not SQLite's […] or `… — both of which it accepts for MS-Access and MySQL compatibility. A ; inside either read as the statement terminator, so a perfectly valid migration was rejected with "contains more than one SQL statement". Bracket quoting has no escape (it ends at the first ]); backtick doubles to escape, like the other two. Two adjacent inconsistencies in the same class: - buildMysqlExec.all returned mysql2's result verbatim, where mysql2 hands back a ResultSetHeader rather than a row array for a statement that returns no rows. The sibling fromMysql2 normalises that to []; two adapters over one driver disagreeing about the same shape is how a caller ends up indexing into a non-array. Unreachable today. - advanceClientWatermark's module docblock said the watermark advances "in the same transaction" as the writes, while the function's own docblock forty lines down says it is NOT atomic with them. Both paths exist (shard-do.ts`); the module doc was the over-broad one and now names which is which. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(sql-store,d1,replica): close the review gaps in the round-26 data fixes Five review findings, each verified against the code before it was acted on. A UNIQUE index declared in definition.indexes never got the treatment a .unique() column got. indexRef consulted only the validator's own flag, so a declared unique index on a plain text field kept LONGTEXT and a (191) key prefix — enforcing uniqueness of the first 191 characters, which is the same false ER_DUP_ENTRY the column flag was fixed for, reachable through the other producer. Both producers now feed one fullValueIndexedFields set that decides the column type and the prefix together. A COMPOSITE unique index cannot be handled that way: InnoDB caps a key at 3072 bytes, so bounding two columns to 768 characters each overflows it. Those are now refused at migration time rather than silently prefixed, because a prefixed composite UNIQUE constrains something other than what was declared. The studio page reader chose its ORDER BY column with a test that conflated the two table kinds. resolveColumns returns DISPLAY names for a .global() table (_id, whose physical column is id) and PHYSICAL names for an external one, so an external table carrying a literal _id column ordered by an id it does not have. External tables are asked for their own primary key instead, which also covers WITHOUT ROWID — those have no rowid to fall back on. subscribeToMirror could lose a clear. applyDiff fans out to every onChange listener, and one of them may call clearData() while this listener is mid-frame; the assignment at the end of the callback then restored the map the clear had just reset, so the next identical frame reported no changes over an emptied table. The frame now captures a clear generation and publishes only if it still holds. Two docblocks corrected: mergeDiffs promised that distinct child sequences mint distinct ids, which an optional id, a shared timestamp fallback and a 64-bit digest all defeat; and the watermark contract cited commitMutationBookkeeping(…, { strict }), which takes no such argument — it calls advanceClientMutationWatermark({ strict: true }). Also dropped an edit-history sentence that described a previous wording rather than the contract. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
Fixed
data: stop the mirror, rank pagination and three adapters returning wrong answers (#604) (fb4a70c)
do: the persisted layout changed and the old __tables__ snapshot is not imported. A deployed registry starts empty and refills as each sharded table's onWrite hook re-registers. Importing it instead would mean thousands of writes inside blockConcurrencyWhile, whose 30-second cap RESETS the Durable Object — an unbootable registry in exactly the oversized case this fixes. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
Fixed
do: re-deliver rows a failed shape poke owes, and split the shard registry's storage (#611) (6f0915e)
Dependencies
@lunora/errors: upgraded to 1.0.0-alpha.32
@lunora/observability: upgraded to 1.0.0-alpha.57
@lunora/platform-cloudflare: upgraded to 1.0.0-alpha.33
auth,sql-store,codegen: stop the auth migrator killing the isolate, and the global sweep re-running per request (#613) (f170c82), closes #599#601#600#601
data:LocalMirror's onChange callback receives a "diff" | "clear" reason argument. A zero-argument callback is unaffected. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(replica): let a replay reach the log's own readers events() promises to yield every entry "continuing with every future applyEvent / replayFromLog call", but it streams off state-changed and replayFromLog emitted only replay-error/ready. Its phase-1 catch-up loop exits once, so every entry a replay appended was invisible to a generator already running. Each replayed entry now emits state-changed, the same notification applyEvent emits for the same reason. The same append also dropped the source entry's timestamp, so EventLog#append stamped Date.now() and a replay rewrote history to the moment it ran — forty lines below applyEvent, which pins the timestamp deliberately (REPLICA-07) so a timestamp-dependent reducer stays reproducible. It is pinned on both paths now. EventLog#append discarded an InputEvent's own required timestamp the same way, while commitAll has always preserved it; and getFrom(fromSeq, 0) returned { entries: [], hasMore: true }, which spins a paginating caller on a page it can never advance past — limit is now validated like maxEntries and truncateBelow's floor. Also corrects TableDiff.id's docblock: it describes a deriveInsertId derivation apply-diff.ts deliberately no longer does (hashing the diff id into a row key is what grew the mirror by a row a second). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(shard-engine): page and rank past a NULL sort column A rank sort column genuinely holds NULL — syncRankIndexEntry writes record[field] ?? null, so a document simply missing the field is a NULL in __sort_k<i>__ — and col > NULL / col < NULL are both UNKNOWN. The lexicographic seek used NULL-safe IS for the prefix equalities but a bare comparator at the pivot, so: - the rankPage that first reached the NULL group came back EMPTY, with isDone: false on the page before it, and pagination stopped there; and - rank() returned a confident position counted against a partial set, next to a correct total. Four sites had the same shape (the DO writer's seek and its countRankBefore, and the SQL store's twins of both). All four now go through one rankPivotConditionSql, which is the treatment pivotCondition already applies to the row-store's keyset seek: a NULL pivot resolves to "every non-null row" or "no row" depending on which side is sought, and a non-null pivot picks up the NULL group with an IS NULL arm when the ordering puts it there. A branch that cannot match is dropped rather than emitted as an always-false disjunct. The SQL store's rank ORDER BY also named no NULL placement, so on Postgres (NULLS LAST ascending) the NULL group sat opposite where the seek assumes it is. It now states the placement for the sort columns the way compileOrderBySql already does for every other read. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(sql-store): round-trip a scalar in an untyped column v.any(), v.union() and v.from() all store as TEXT — SQLite affinity TEXT, Postgres TEXT, MySQL LONGTEXT — and sqliteEncode keys off the runtime type, so a number or boolean written to one was COERCED by the engine on the way in: 42 landed as the text 42.0, true (encoded 1) as 1.0. The decode had no declared type to reverse that with, so the caller read back a string. The codec's own docblock claimed a scalar member "round-trips through SQLite's native column type"; it cannot, and the unit test that pinned the claim called sqliteDecode with a JS value that had never been bound to a column. sqliteEncode now takes the column's kind and writes a number or boolean in those three kinds in the marked, self-describing form the composites already use, which sqliteDecode reverses by the marker alone. Strings, bigints and composites keep the storage form they had: the WHERE path binds through the same function without a kind, and changing them would stop existing equality filters matching. Equality on an untyped numeric column did not match before this either (a stored 42.0 never equalled a bound 42), so nothing regresses. The kind reaches the encoder only where the caller knows which column it is filling — insert, upsert's soft-delete update, patch, replace — through serializeDocumentColumn. serializeColumnValue stays kind-blind because it also binds every WHERE comparison and the rank companion's sort keys, where both sides of a comparison have to agree byte for byte. The regression test writes and reads through a real column; asserting on sqliteDecode alone is what let this ship. api-snapshots/sql-store.api.md records this widening together with the SqlDialect.columnType one from the MySQL .unique() fix that follows, so the snapshot lands with that commit rather than being written twice. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(hyperdrive): index a .unique() column whole on mysql InnoDB cannot index a LONGTEXT without a key prefix, indexKeyPrefix supplies 191, and the synthesized .unique() index went through the same indexRef as every other index — so the constraint enforced uniqueness of the first 191 CHARACTERS. Two distinct 200-character values sharing that prefix raised ER_DUP_ENTRY, which mapWriteError surfaced as "unique constraint violation": a rejected write with a correct-looking error, on MySQL only, where D1 and Postgres both accept it. A .unique() character column is now declared VARCHAR(768) (768 × 4 bytes under utf8mb4 is exactly InnoDB's 3072-byte single-column key limit), bytes VARBINARY(768), and the synthesized index takes no prefix. A value past the bound is a loud write error rather than a wrong conflict. The numeric kinds and bigint's VARCHAR(64) key were already indexable whole and are unchanged, as are SQLite and Postgres, which index text of any length. Pre-existing MySQL tables keep the type they were created with — the same caveat the column collation carries, and for the same reason: CREATE TABLE IF NOT EXISTS does not reshape one. Converting is ALTER TABLE <t> MODIFY <col> VARCHAR(768) COLLATE utf8mb4_0900_bin.
data:SqlDialect.columnType takes an optional second argument { unique?: boolean }. A dialect implementing the one-argument signature still satisfies it. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
security(hyperdrive): reject a vector filter shape json cannot represent The containment-filter guard exists because a filter this store cannot honour must be an ERROR rather than a silent drop, and its own docblock names the case it then failed to catch. The walk recursed through Object.entries, which is [] for a Map, a Set, a Date or a class instance — so it inspected nothing and rejected nothing, while JSON.stringify turned the value into {}. metadata @> '{"tenant":{}}'::jsonb is satisfied by every row that has metadata at all: a filter that fails OPEN, across tenants. At the top level it was worse. Object.keys(someMap).length is 0, so the length > 0 gates skipped both the guard and the containment clause, and the query went out with no filter on it whatsoever. Both are now rejected by prototype — the only test that can see a shape whose own enumerable entries are not its contents — and the guard runs on any filter that is present rather than on one with countable keys.
data: a Date in a metadata filter is now rejected along with Map, Set and class instances. Pre-compute it into an equality-shaped metadata field. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
security(d1): decode a studio table as global only when it is The database browser branched on schema.tables[table] !== undefined — whether the schema declares that NAME — with no shardMode check, in six places. But only a .global() table lives in D1, so a same-named .shardBy()/root table describes a Durable Object's storage, not the D1 table being read. A schema declaring a shard-local user alongside better-auth's D1 user sent every read of the D1 table down the schema branch: it was decoded as a .global() row, so the password|secret|token|hash|salt|credential redaction never ran, and the same wrong branch simultaneously disabled the two guards that exist BECAUSE redaction is imperfect — the eq-filter equality oracle and the facet's masked bucket. Every site now goes through one globalTableDefinition, the test the admin export/import path already applies. Two ordering defects in the same reader: - the page read was LIMIT ? OFFSET ? with no ORDER BY, so which rows a page contains was up to the plan and two identical requests could disagree — a row could appear on two pages or on none. It now orders by the table's id (every .global() table has a TEXT primary key), or rowid for an external table without one. The shard browser keyset-paginates for the same reason. - the facet's ORDER BY count DESC had no tiebreaker, so which equally-frequent values land in the top-N — and whether the result reports truncated — was planner-dependent. It now breaks ties on the value. Also corrects the D1 dialect's docblock, which described bigint as "serialized as a decimal string" where the shared encoder writes the order-preserving 40-character key. Both sibling dialects describe it correctly, and this module is what the lunora migrate generate emitter reads for the physical column form. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
test(shard-engine): give the wide-where case more than one condition Object.fromEntries(Array.from({ length: 200 }, () => ["title", "kept"])) is { title: "kept" } — an object literal holds each key once. The only behavioural case in the expression-depth-cap suite therefore ran ONE condition while claiming 200, and passed identically with compileWhereSql's halving-pair nesting deleted. It now builds distinct fields. 90 of them, not 200, because the two caps meet here: one equality binds one parameter and the bound-parameter ceiling the suite above pins is 100, so a genuinely-200-term where is rejected before it can be executed at all. The structural widestChain assertions still cover the full 200 — those were never vacuous, and they are what discriminates against an un-nested implementation; a flat 90-term AND is well under stock SQLite's expression-depth limit, so this case cannot. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(d1): teach the migration lexer sqlite's other identifier quotings The single-statement check models '…', "…", -- and /* */, but not SQLite's […] or `… — both of which it accepts for MS-Access and MySQL compatibility. A ; inside either read as the statement terminator, so a perfectly valid migration was rejected with "contains more than one SQL statement". Bracket quoting has no escape (it ends at the first ]); backtick doubles to escape, like the other two. Two adjacent inconsistencies in the same class: - buildMysqlExec.all returned mysql2's result verbatim, where mysql2 hands back a ResultSetHeader rather than a row array for a statement that returns no rows. The sibling fromMysql2 normalises that to []; two adapters over one driver disagreeing about the same shape is how a caller ends up indexing into a non-array. Unreachable today. - advanceClientWatermark's module docblock said the watermark advances "in the same transaction" as the writes, while the function's own docblock forty lines down says it is NOT atomic with them. Both paths exist (shard-do.ts`); the module doc was the over-broad one and now names which is which. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(sql-store,d1,replica): close the review gaps in the round-26 data fixes Five review findings, each verified against the code before it was acted on. A UNIQUE index declared in definition.indexes never got the treatment a .unique() column got. indexRef consulted only the validator's own flag, so a declared unique index on a plain text field kept LONGTEXT and a (191) key prefix — enforcing uniqueness of the first 191 characters, which is the same false ER_DUP_ENTRY the column flag was fixed for, reachable through the other producer. Both producers now feed one fullValueIndexedFields set that decides the column type and the prefix together. A COMPOSITE unique index cannot be handled that way: InnoDB caps a key at 3072 bytes, so bounding two columns to 768 characters each overflows it. Those are now refused at migration time rather than silently prefixed, because a prefixed composite UNIQUE constrains something other than what was declared. The studio page reader chose its ORDER BY column with a test that conflated the two table kinds. resolveColumns returns DISPLAY names for a .global() table (_id, whose physical column is id) and PHYSICAL names for an external one, so an external table carrying a literal _id column ordered by an id it does not have. External tables are asked for their own primary key instead, which also covers WITHOUT ROWID — those have no rowid to fall back on. subscribeToMirror could lose a clear. applyDiff fans out to every onChange listener, and one of them may call clearData() while this listener is mid-frame; the assignment at the end of the callback then restored the map the clear had just reset, so the next identical frame reported no changes over an emptied table. The frame now captures a clear generation and publishes only if it still holds. Two docblocks corrected: mergeDiffs promised that distinct child sequences mint distinct ids, which an optional id, a shared timestamp fallback and a 64-bit digest all defeat; and the watermark contract cited commitMutationBookkeeping(…, { strict }), which takes no such argument — it calls advanceClientMutationWatermark({ strict: true }). Also dropped an edit-history sentence that described a previous wording rather than the contract. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
Fixed
data: stop the mirror, rank pagination and three adapters returning wrong answers (#604) (fb4a70c)
storage,server,cli: an oversized streamed body now rejects the upload() call with PAYLOAD_TOO_LARGE rather than resolving and erroring later when the bucket drains the stream. list() never sent include, and under r2_list_honor_include (every compat date since 2022-08-04) R2 omits httpMetadata/customMetadata from list entries unless asked. The projection copied both as if present, so a real bucket returned empty bags for every entry while head() on the same key returned them in full. R2BucketLike.list had no include either, so nothing COULD ask. The JS WhereInput evaluator behind rls() diverged from the SQL compiler it mirrors, twice, both fail-open on the write path. A non-array notIn passed every row where the compiler throws BAD_REQUEST — a policy written to keep admin rows out admitted one on write. And a NULL cell passed ne/notIn, where SQL's three-valued logic excludes it. Both are fixed at the shared operator evaluator, so the read filter, the write USING/WITH-CHECK gates and the expectPolicy harness all move together; in gets the same refusal, and eq/ne against a null operand keep folding to IS NULL/IS NOT NULL. The SQL side is unchanged. migrate generate emitted NOT NULL for a .nullable() column: the CLI derived nullability from v.optional alone, though the runtime rule is notNull AND not optional, and .nullable() is what clears notNull. A table created from the migration file rejected the null the column exists to accept while the auto-provisioned one took it. It now reads nullable off the FieldSnapshot the snapshot already carries. The gate was the real defect for the first two: the unit suite's fake bucket accepts any stream and returns whatever it stored, so only the workerd suite can see either. It now uploads a stream and asserts list metadata. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(storage): bound the buffered upload path and validate the cap that bounds it Capping a streamed upload buffers it, so maxSize is now the per-request memory ceiling — and nothing checked that it was a usable number. typeof NaN === "number" let a NaN cap into the branch, where seen > NaN is never true: the cap silently off while the whole body was still collected into the isolate, an unbounded buffer from something as ordinary as an unset byte-limit variable coerced with Number(...). A negative cap is the mirror image — seen > -1 is true on the first chunk, so every upload was refused. Both now fail up front as VALIDATION_ERROR. The ceiling is shared, not per request: N in-flight uploads hold up to N x maxSize against one ~128 MB isolate, so a 50 MB cap OOMs three uploads deep with every one inside its documented limit. A streamed maxSize above 16 MiB is therefore refused with a pointer to createMultipartUpload/createUploadHandler, which never hold the whole object. "Omit maxSize" is dropped as the escape hatch for large objects — the advisor lint fires on exactly that, so the two guidances contradicted each other; the lint's remediation now names the multipart path instead, which it does not flag. The counter accepts every BufferSource shape but re-enqueued the original chunk, and undici's Response body takes only Uint8Array, so an ArrayBuffer/DataView/Float32Array chunk failed with a bare TypeError: Received non-Uint8Array chunk — no code, nothing naming storage. Chunks are normalised to a Uint8Array view (no copy). workerd accepts the raw shapes, so this only ever broke under Node; the workerd suite now carries the case either way. Also documents that a list() page may hold fewer objects than limit, since R2 shrinks a page to fit the metadata include asks for — paginate on truncated/cursor. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(server): evaluate rls predicates under sql's three-valued logic The JS WhereInput evaluator folded SQL's UNKNOWN into false at each operator. That is the right answer at the top of a WHERE and the wrong one under a NOT: NOT UNKNOWN is UNKNOWN and still excludes the row, while !false is true and admits it. { NOT: { role: { ne: "admin" } } } against a NULL cell therefore admitted a row SQL excludes — fail-open on the write gate. The evaluator now carries the three values (FALSE < UNKNOWN < TRUE, so AND is the minimum, OR the maximum, NOT the reflection) and collapses them exactly once, in matchesWhere, where only TRUE keeps the row. No operator has to reason about whether UNKNOWN happens to be safe at its position. Closed by the same change: - in kept the mirror of the notIn bug. [null, "admin"].includes(null) is true in JS, so a NULL cell passed a membership check SQL excludes unconditionally. A write policy { tenantId: { in: allowedTenants } } whose list carried a null admitted a tenantId: null row that every read of the same policy then hid. - contains and the ordered comparators admitted a NULL cell under a NOT, for the reason ne did. A NULL *operand* on an ordered comparator stays FALSE, which is what the compiler emits. - an undefined operand — { ownerId: undefined }, { ownerId: { eq: undefined } }, or an undefined member of an in list — now raises BAD_REQUEST. It is a dropped variable: the SQL compiler binds the placeholder so the driver rejects the statement, while this evaluator compared with !== and quietly matched every row that lacked the column. - the equality shorthand reads an absent column as SQL NULL, so { role: null } means role IS NULL the way it does in SQL. The matchesOperators docblock claimed full NULL parity. It now names the three divergences that remain — case-sensitive contains, and two degenerate shapes that stay deliberately fail-closed. BREAKING: the evaluator also backs the legacy query() row filter and expectPolicy, so reads converge on the same answers. A NULL cell that a ne/in/notIn/contains read policy used to return from query() is now filtered out, matching what the SQL readers always did. A malformed operand that used to be ignored there now throws BAD_REQUEST from inside the filter, so an app with a scalar notIn or a dropped variable in a read policy goes from a silent wrong answer to a visible 400 on every legacy query(). Every row of the truth table pinned in rls-null-semantics.test.ts was produced by compiling the predicate with compileWhereSql, rendering it and running it on node:sqlite — none of it from memory. Eight of the sixteen cases fail against the pre-change evaluator, all in the fail-open direction. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
refactor(server): move the rls where evaluator into its own module rls/middleware.ts was 2,035 lines and 400 of them were a self-contained pure evaluator that has to be read against @lunora/shard-engine's where-sql.ts to be reviewed at all — the two are parallel implementations of one predicate language, and their agreement is a security property, not a nicety. Moved verbatim to rls/where-match.ts, which states that contract in its header: what the twin is for, why it exists twice, and where the pinned truth table lives. containsRelationPredicate and matchesWhere are the only two names the middleware used; matchesWhere stays re-exported from ./middleware so the in-process harness and the sibling middlewares keep one import site. No behaviour change — the only edit to a moved line is a JSDoc {@link} that no longer resolves across the file boundary. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
test(server): pin that a malformed NOT operand cannot admit a write Review raised { NOT: "a" } as a fail-open: the operand is cast to a WhereInput and recursed, and Object.keys("a") is ["0"], so it tests a column no document has. It was fail-open under the boolean evaluator — an absent column read FALSE and NOT flipped it to a write-admitting TRUE. The three-valued rewrite closed it: an absent column is UNKNOWN, kleeneNot(UNKNOWN) is UNKNOWN, and only TRUE admits. Verified by probe across string, array and number operands. No behaviour change — these are guard rails, and the comment says so rather than implying they repair something. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
test(server): type the malformed-NOT operands the evaluator is asked to refuse Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
Fixed
storage,server,cli: make streaming uploads work, and stop RLS writes failing open (#616) (c76d854)
auth,sql-store,codegen: stop the auth migrator killing the isolate, and the global sweep re-running per request (#613) (f170c82), closes #599#601#600#601
Dependencies
@lunora/d1: upgraded to 1.0.0-alpha.109
@lunora/errors: upgraded to 1.0.0-alpha.32
@lunora/queue: upgraded to 1.0.0-alpha.46
@lunora/sql-store: upgraded to 1.0.0-alpha.109
@lunora/workflow: upgraded to 1.0.0-alpha.46
@lunora/do: upgraded to 1.0.0-alpha.118
@lunora/platform-cloudflare: upgraded to 1.0.0-alpha.33
ratelimit,auth:accessRoles() and the @lunora/cloudflare-access/roles subpath are removed. Use createAccessResolver({ roles }) instead. AccessRoleMap now exports from the package root. Corrects the three places that told a reader the two paths agree: the emit.ts comment claiming composeShapeReadWhere is "exactly the request-time path", the package docs, and the RLS concept page. The golden _generated/shard.ts fixture is regenerated for the emitted comment. Second fix in the same resolver: a platform identity carrying no usable id suppressed the configured JWT fallback. ?? falls through on nullish only, and readPlatformIdentity returns an object for any non-null object result, {} included — so a caller presenting a valid Cf-Access-Jwt-Assertion resolved anonymous with nothing verified and onError never firing. The resolver now falls through whenever the platform identity yields no identity, and stays fail-closed when neither path does. That trigger was reasoned from the code rather than observed — whether Cloudflare ever returns such an identity is unverified — so the fix is deliberately defensive. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(ratelimit): stop a reserve stranding a key and misreporting retry Three defects on the reserve path, all reachable through the public API and through token-budget.ts, which clamps an oversized charge to capacity and reserves it. A fixed window granted exactly one period's rate however many periods had elapsed, while the rejection path persists nothing. A debt of at least rate therefore re-projected against that same lone grant on every later call and the key stayed denied forever, told "retry next window" every window. The projection now grants one rate per elapsed window, the way the token bucket refills per elapsed millisecond; the existing capacity cap still bounds the result. The old test reserved 2 against rate 5 — a debt smaller than rate, which is the case that recovers — so it passed throughout, and now covers a debt of a full rate. The deny-list was stored verbatim while the incoming key was checked both normalized and raw, under a comment claiming either form worked. Only a byte-exact repeat of the stored string matched: with a trim+lowercase normalizer, denyList: ["Abuse@Example.com"] admitted a request keyed abuse@example.com that consumed from the same storage bucket, so a banned caller shed the ban by lower-casing their own email. Entries are now stored in both forms at construction. A sliding-window reserve derived its retryAfter from the pre-reserve count while persisting currentCount + count, so the time it reported was still denied when it arrived and the caller burned a rejected attempt — a re-queued durable write wakes on that hint verbatim. It is now derived from the count the call actually stores. The old assertion pinned 1200 under the title "reports when the pressure clears"; the true clear time is 1334, and the test now re-evaluates at the reported time to prove it is honoured. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(auth): trust cf-connecting-ip only behind Cloudflare resolveIp in the audit hooks returned cf-connecting-ip before consulting trustProxyHeaders, though that option's own docblock promises the opposite: "Defaults to false: off Cloudflare, with no trusted proxy configured, the audit record's ip is omitted rather than populated from a spoofable header." Off Cloudflare nothing overwrites that header, so an attacker setting it per request owned the ip on every sign-in, password-reset and mfa-disable row they generated — rows Studio surfaces through getAuthAuditLog. Forensic impact only: nothing enforces on the audit ip. It now applies the same onCloudflareEdge() gate that create-auth.ts's defaultIpAddressHeaders already applies, so this package's two client-IP resolvers cannot disagree about who a request came from. onCloudflareEdge moves from a file-private const to a named export of create-auth.ts; it is not re-exported from the package index, so the public API is unchanged. The existing cases asserting cf-connecting-ip did not say which runtime they ran on and passed under Node's navigator.userAgent; they now stub the Cloudflare one explicitly, alongside two new cases for the off-Cloudflare behaviour. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(runtime): key IP-less REST callers and 403 a deny-list hit createRestRateLimit charged its limit with no key at all when cf-connecting-ip was absent, putting every such caller in that limit's UNKEYED bucket — the same one a deliberately-global charge of the name uses — so one anonymous caller could drain an app-wide limit. This is the caller-pooling @lunora/ratelimit's own middleware refuses outright. They now share a named no-trusted-ip bucket, which keeps the blast radius to the IP-less callers themselves and makes the pooling visible in storage; pass options.key to key them properly. A deny-list hit carries retryAfter: Infinity and was mapped to 429 with the header Retry-After: Infinity, inviting a client to keep retrying a denial that never clears. It now answers 403 FORBIDDEN with no Retry-After, matching what both @lunora/ratelimit entry points produce. RateLimiterLike gains the optional reason the limiter already returns. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
Fixed
ratelimit,auth: unstick a bricked limiter and close the deny-list bypass (#606) (fd7d6ad)
data:LocalMirror's onChange callback receives a "diff" | "clear" reason argument. A zero-argument callback is unaffected. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(replica): let a replay reach the log's own readers events() promises to yield every entry "continuing with every future applyEvent / replayFromLog call", but it streams off state-changed and replayFromLog emitted only replay-error/ready. Its phase-1 catch-up loop exits once, so every entry a replay appended was invisible to a generator already running. Each replayed entry now emits state-changed, the same notification applyEvent emits for the same reason. The same append also dropped the source entry's timestamp, so EventLog#append stamped Date.now() and a replay rewrote history to the moment it ran — forty lines below applyEvent, which pins the timestamp deliberately (REPLICA-07) so a timestamp-dependent reducer stays reproducible. It is pinned on both paths now. EventLog#append discarded an InputEvent's own required timestamp the same way, while commitAll has always preserved it; and getFrom(fromSeq, 0) returned { entries: [], hasMore: true }, which spins a paginating caller on a page it can never advance past — limit is now validated like maxEntries and truncateBelow's floor. Also corrects TableDiff.id's docblock: it describes a deriveInsertId derivation apply-diff.ts deliberately no longer does (hashing the diff id into a row key is what grew the mirror by a row a second). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(shard-engine): page and rank past a NULL sort column A rank sort column genuinely holds NULL — syncRankIndexEntry writes record[field] ?? null, so a document simply missing the field is a NULL in __sort_k<i>__ — and col > NULL / col < NULL are both UNKNOWN. The lexicographic seek used NULL-safe IS for the prefix equalities but a bare comparator at the pivot, so: - the rankPage that first reached the NULL group came back EMPTY, with isDone: false on the page before it, and pagination stopped there; and - rank() returned a confident position counted against a partial set, next to a correct total. Four sites had the same shape (the DO writer's seek and its countRankBefore, and the SQL store's twins of both). All four now go through one rankPivotConditionSql, which is the treatment pivotCondition already applies to the row-store's keyset seek: a NULL pivot resolves to "every non-null row" or "no row" depending on which side is sought, and a non-null pivot picks up the NULL group with an IS NULL arm when the ordering puts it there. A branch that cannot match is dropped rather than emitted as an always-false disjunct. The SQL store's rank ORDER BY also named no NULL placement, so on Postgres (NULLS LAST ascending) the NULL group sat opposite where the seek assumes it is. It now states the placement for the sort columns the way compileOrderBySql already does for every other read. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(sql-store): round-trip a scalar in an untyped column v.any(), v.union() and v.from() all store as TEXT — SQLite affinity TEXT, Postgres TEXT, MySQL LONGTEXT — and sqliteEncode keys off the runtime type, so a number or boolean written to one was COERCED by the engine on the way in: 42 landed as the text 42.0, true (encoded 1) as 1.0. The decode had no declared type to reverse that with, so the caller read back a string. The codec's own docblock claimed a scalar member "round-trips through SQLite's native column type"; it cannot, and the unit test that pinned the claim called sqliteDecode with a JS value that had never been bound to a column. sqliteEncode now takes the column's kind and writes a number or boolean in those three kinds in the marked, self-describing form the composites already use, which sqliteDecode reverses by the marker alone. Strings, bigints and composites keep the storage form they had: the WHERE path binds through the same function without a kind, and changing them would stop existing equality filters matching. Equality on an untyped numeric column did not match before this either (a stored 42.0 never equalled a bound 42), so nothing regresses. The kind reaches the encoder only where the caller knows which column it is filling — insert, upsert's soft-delete update, patch, replace — through serializeDocumentColumn. serializeColumnValue stays kind-blind because it also binds every WHERE comparison and the rank companion's sort keys, where both sides of a comparison have to agree byte for byte. The regression test writes and reads through a real column; asserting on sqliteDecode alone is what let this ship. api-snapshots/sql-store.api.md records this widening together with the SqlDialect.columnType one from the MySQL .unique() fix that follows, so the snapshot lands with that commit rather than being written twice. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(hyperdrive): index a .unique() column whole on mysql InnoDB cannot index a LONGTEXT without a key prefix, indexKeyPrefix supplies 191, and the synthesized .unique() index went through the same indexRef as every other index — so the constraint enforced uniqueness of the first 191 CHARACTERS. Two distinct 200-character values sharing that prefix raised ER_DUP_ENTRY, which mapWriteError surfaced as "unique constraint violation": a rejected write with a correct-looking error, on MySQL only, where D1 and Postgres both accept it. A .unique() character column is now declared VARCHAR(768) (768 × 4 bytes under utf8mb4 is exactly InnoDB's 3072-byte single-column key limit), bytes VARBINARY(768), and the synthesized index takes no prefix. A value past the bound is a loud write error rather than a wrong conflict. The numeric kinds and bigint's VARCHAR(64) key were already indexable whole and are unchanged, as are SQLite and Postgres, which index text of any length. Pre-existing MySQL tables keep the type they were created with — the same caveat the column collation carries, and for the same reason: CREATE TABLE IF NOT EXISTS does not reshape one. Converting is ALTER TABLE <t> MODIFY <col> VARCHAR(768) COLLATE utf8mb4_0900_bin.
data:SqlDialect.columnType takes an optional second argument { unique?: boolean }. A dialect implementing the one-argument signature still satisfies it. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
security(hyperdrive): reject a vector filter shape json cannot represent The containment-filter guard exists because a filter this store cannot honour must be an ERROR rather than a silent drop, and its own docblock names the case it then failed to catch. The walk recursed through Object.entries, which is [] for a Map, a Set, a Date or a class instance — so it inspected nothing and rejected nothing, while JSON.stringify turned the value into {}. metadata @> '{"tenant":{}}'::jsonb is satisfied by every row that has metadata at all: a filter that fails OPEN, across tenants. At the top level it was worse. Object.keys(someMap).length is 0, so the length > 0 gates skipped both the guard and the containment clause, and the query went out with no filter on it whatsoever. Both are now rejected by prototype — the only test that can see a shape whose own enumerable entries are not its contents — and the guard runs on any filter that is present rather than on one with countable keys.
data: a Date in a metadata filter is now rejected along with Map, Set and class instances. Pre-compute it into an equality-shaped metadata field. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
security(d1): decode a studio table as global only when it is The database browser branched on schema.tables[table] !== undefined — whether the schema declares that NAME — with no shardMode check, in six places. But only a .global() table lives in D1, so a same-named .shardBy()/root table describes a Durable Object's storage, not the D1 table being read. A schema declaring a shard-local user alongside better-auth's D1 user sent every read of the D1 table down the schema branch: it was decoded as a .global() row, so the password|secret|token|hash|salt|credential redaction never ran, and the same wrong branch simultaneously disabled the two guards that exist BECAUSE redaction is imperfect — the eq-filter equality oracle and the facet's masked bucket. Every site now goes through one globalTableDefinition, the test the admin export/import path already applies. Two ordering defects in the same reader: - the page read was LIMIT ? OFFSET ? with no ORDER BY, so which rows a page contains was up to the plan and two identical requests could disagree — a row could appear on two pages or on none. It now orders by the table's id (every .global() table has a TEXT primary key), or rowid for an external table without one. The shard browser keyset-paginates for the same reason. - the facet's ORDER BY count DESC had no tiebreaker, so which equally-frequent values land in the top-N — and whether the result reports truncated — was planner-dependent. It now breaks ties on the value. Also corrects the D1 dialect's docblock, which described bigint as "serialized as a decimal string" where the shared encoder writes the order-preserving 40-character key. Both sibling dialects describe it correctly, and this module is what the lunora migrate generate emitter reads for the physical column form. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
test(shard-engine): give the wide-where case more than one condition Object.fromEntries(Array.from({ length: 200 }, () => ["title", "kept"])) is { title: "kept" } — an object literal holds each key once. The only behavioural case in the expression-depth-cap suite therefore ran ONE condition while claiming 200, and passed identically with compileWhereSql's halving-pair nesting deleted. It now builds distinct fields. 90 of them, not 200, because the two caps meet here: one equality binds one parameter and the bound-parameter ceiling the suite above pins is 100, so a genuinely-200-term where is rejected before it can be executed at all. The structural widestChain assertions still cover the full 200 — those were never vacuous, and they are what discriminates against an un-nested implementation; a flat 90-term AND is well under stock SQLite's expression-depth limit, so this case cannot. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(d1): teach the migration lexer sqlite's other identifier quotings The single-statement check models '…', "…", -- and /* */, but not SQLite's […] or `… — both of which it accepts for MS-Access and MySQL compatibility. A ; inside either read as the statement terminator, so a perfectly valid migration was rejected with "contains more than one SQL statement". Bracket quoting has no escape (it ends at the first ]); backtick doubles to escape, like the other two. Two adjacent inconsistencies in the same class: - buildMysqlExec.all returned mysql2's result verbatim, where mysql2 hands back a ResultSetHeader rather than a row array for a statement that returns no rows. The sibling fromMysql2 normalises that to []; two adapters over one driver disagreeing about the same shape is how a caller ends up indexing into a non-array. Unreachable today. - advanceClientWatermark's module docblock said the watermark advances "in the same transaction" as the writes, while the function's own docblock forty lines down says it is NOT atomic with them. Both paths exist (shard-do.ts`); the module doc was the over-broad one and now names which is which. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
fix(sql-store,d1,replica): close the review gaps in the round-26 data fixes Five review findings, each verified against the code before it was acted on. A UNIQUE index declared in definition.indexes never got the treatment a .unique() column got. indexRef consulted only the validator's own flag, so a declared unique index on a plain text field kept LONGTEXT and a (191) key prefix — enforcing uniqueness of the first 191 characters, which is the same false ER_DUP_ENTRY the column flag was fixed for, reachable through the other producer. Both producers now feed one fullValueIndexedFields set that decides the column type and the prefix together. A COMPOSITE unique index cannot be handled that way: InnoDB caps a key at 3072 bytes, so bounding two columns to 768 characters each overflows it. Those are now refused at migration time rather than silently prefixed, because a prefixed composite UNIQUE constrains something other than what was declared. The studio page reader chose its ORDER BY column with a test that conflated the two table kinds. resolveColumns returns DISPLAY names for a .global() table (_id, whose physical column is id) and PHYSICAL names for an external one, so an external table carrying a literal _id column ordered by an id it does not have. External tables are asked for their own primary key instead, which also covers WITHOUT ROWID — those have no rowid to fall back on. subscribeToMirror could lose a clear. applyDiff fans out to every onChange listener, and one of them may call clearData() while this listener is mid-frame; the assignment at the end of the callback then restored the map the clear had just reset, so the next identical frame reported no changes over an emptied table. The frame now captures a clear generation and publishes only if it still holds. Two docblocks corrected: mergeDiffs promised that distinct child sequences mint distinct ids, which an optional id, a shared timestamp fallback and a 64-bit digest all defeat; and the watermark contract cited commitMutationBookkeeping(…, { strict }), which takes no such argument — it calls advanceClientMutationWatermark({ strict: true }). Also dropped an edit-history sentence that described a previous wording rather than the contract. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUuYamsU1YLmAQhtut9PLZ
Fixed
data: stop the mirror, rank pagination and three adapters returning wrong answers (#604) (fb4a70c)
Dependencies
@lunora/server: upgraded to 1.0.0-alpha.103
Open source
Built in the open, on purpose.
Nothing about Lunora is a black box. Read it, fork it, or send the fix yourself.