Skip to content

feat(cloud): lunora cloud control plane on workers for platforms - #85

Open
prisis wants to merge 347 commits into
alphafrom
claude/cloud-platform-dx-ojvkmu
Open

prisis wants to merge 347 commits into
alphafrom
claude/cloud-platform-dx-ojvkmu

Conversation

@prisis

@prisis prisis commented Jul 1, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds Lunora Cloud — the managed-platform control plane — as apps/cloud (@lunora/cloud), dogfooded on Lunora itself and structured for later extraction into a private repo (see apps/cloud/EXTRACT.md), plus the GitHub pipeline that deploys it.

The control plane

  • Data model + functions (apps/cloud/lunora/): cells, organizations, members, invitations, projects, deployments, deploy keys, tenant secrets, platform usage, audit log — on the fluent function builders, with org-membership / deploy-key authorization and cross-org IDOR guards.
  • Deploy orchestration (src/deploy/): POST /v1/deploy streaming NDJSON, per-cell token-bucket + scheduler over the Alchemy 2 provision box (see below), preview deployments from GitHub webhooks, stored releases with rollback.
  • Workers-for-Platforms dispatcher (src/dispatcher/): hostname → tenant script resolution with per-plan runtime limits and per-request usage emission.
  • Billing + metering on @lunora/payment, Analytics Engine metering via @lunora/bindings/analytics.
  • Auth on @lunora/auth / better-auth: mail-backed verification/reset, optional OAuth, 2FA/passkeys, rate limiting.
  • Tenant cron + queue fan-out (WfP workaround): namespaced Workers get no cron triggers or queue consumers, so the control plane fans ticks/batches out through the dispatcher to new reserved runtime endpoints POST /_lunora/scheduled and POST /_lunora/queue added to @lunora/runtime's createWorker (scheduledTick / queueHandler seams).
  • Hosted studio SPA (src/client/), WS-through-dispatch spike (spikes/ws-dispatch/), and the gap register (apps/cloud/GAPS.md) that tracks what is still infrastructure-blocked.
  • License: PolyForm Noncommercial 1.0.0 (not the framework's FSL) — apps/cloud/LICENSE.md.

The deploy pipeline (new)

A cell is three Workers — lunora-cloud, lunora-dispatcher, lunora-log-tail — and until now they were published by hand from configs that had only a local-dev target.

  • Each wrangler config declares a staging and a production environment. Cloudflare inherits no resource binding into a named environment, so each block restates its vars, D1, R2, queue, DO, dispatch-namespace, Analytics Engine, pipeline, AI and version-metadata bindings — a key left out is a binding the deployed Worker does not have, and that only surfaces at runtime.
  • .github/workflows/deploy-cloud.yml: alpha → cloud-staging, main → cloud-production, or workflow_dispatch to either. It fires on packages/** / shared/** as well as apps/cloud/**, because the control plane bundles the workspace packages rather than resolving them at runtime. Cloudflare credentials live on the GitHub Environment, so production can carry a required reviewer.
  • A production deploy tags cloud-v<run> and cuts a GitHub Release back to the previous cloud tag. That namespace sits outside the @lunora/<pkg>@<version> shape semantic-release owns — apps/cloud is private and has no semver, so a tag in that namespace would read as a package release that never happened.
  • apps/cloud/scripts/check-deploy-config.ts (pnpm --filter @lunora/cloud run deploy:check <cell>) refuses a deploy while the selected environment still holds a <replace-with-…> id. Wrangler will publish a Worker bound to a D1 database that does not exist: green deploy, first query is the failure.

Two things the obvious pipeline gets wrong, both found by building it:

  • @cloudflare/vite-plugin emits its own deploy config at dist/server/wrangler.json with the env key flattened away, and picks the environment from CLOUDFLARE_ENV at build time. Passing --env to the wrangler call instead looks right and silently deploys the wrong cell's bindings.
  • lunora deploy cannot publish this app: its main is a hand-written entry Vite builds, so deploying the source config would bundle src/server.ts raw and ship a control plane with no studio. Its gates run as lunora verify before the build, and its health probe as --health-url after (opt-in via a CLOUD_HEALTH_URL environment variable — a cell's reachable origin is not derivable from CI).

Tenant provisioning on Alchemy 2

The hand-written Cloudflare REST provisioner (DO/D1/R2 only, other bindings dropped silently) is replaced.

  • The binding manifest is the contract (src/provision-contract.ts). lunora cloud deploy sends @lunora/config's buildBindingManifest output (the same document as lunora build --emit-bindings) plus static assets. The deploy handler validates it and refuses unsupported types by name before anything is created: provisioned per project — D1, R2, KV, queues, Analytics Engine; bound — Durable Objects, AI, browser, images, assets (ASSETS); routed — queue consumers; refused with a reason — Hyperdrive, Vectorize, pipelines, containers, workflows.
  • Provision box (containers/provision/): a trusted container running alchemy@2.0.0-beta.79 (with effect pinned to 4.0.0-rc.117, since rc.118 breaks it; @hono/node-server, hono, lodash and valibot overridden past their advisories — the box lockfile audits clean), state in Cloudflare.state() in the cell's own account. It holds the cell token, so it is separate from the build box, which runs untrusted tenant code; egress is limited to the Cloudflare API and the state-store Worker.
  • Per-project resource names are injective: {alias}--{binding}, with aliases restricted to ^[a-z0-9]+(-[a-z0-9]+)*$. The first naming scheme was not, and Alchemy adopts an existing D1 database by name — two tenants could have resolved to one database.
  • Per-project queues replace the shared tenant queue: batches route by queue name (platform-chosen), not by an address in the message body (tenant-written).

Releases and data

  • One stable script per project. Releases used to be new scripts (alias-vN), and a Durable Object namespace belongs to its script — so every deploy started tenants on an empty ShardDO. Each project is now one dispatch-namespace script updated in place; releases are stored in R2 (RELEASES) and a rollback re-provisions a stored one (refused if it would drop a Durable Object class). The health check runs after cutover and a failure redeploys the previous release. Workers for Platforms has no gradual deployments, so staged rollouts are refused rather than splitting data across two scripts.
  • Every kind deploys into the environment's one dispatch namespace (LUNORA_DISPATCH_NAMESPACE). Deploying to lunora-${kind} put previews where no dispatcher routes and staging's tenants outside lunora-staging.
  • Tenant backups (src/backup/tenant-*): daily snapshots of each project's data through the admin export into R2 (TENANT_BACKUPS), retention per plan (3 / 14 / 30), Back up now, download and restore in the studio. Restore is append-only (brings back deleted rows, does not rewind edited ones) and takes a pre-restore snapshot first. Not covered: R2 object bytes, KV, Vectorize.
  • Monorepos: per-project root directory (installed at the workspace root, built in the root directory, symlink-contained) and watch paths; pushes that touch nothing watched are recorded as skipped with the reason. Anything a push payload cannot prove fails open to building.

CLI

  • lunora cloud deploy derives the manifest from the built wrangler config when a Vite build left one (.wrangler/deploy/config.json), which is where the Cloudflare Vite plugin records the client build as assets.
  • lunora cloud eject writes a cleaned copy of the app's real wrangler.jsonc and an Alchemy 2 program, instead of a hard-coded template. @lunora/config's wranglerToAlchemy now emits Alchemy 2 (breaking: the 0.93 output is gone).

Before this can deploy

The pipeline is wired but the cells are not provisioned. One-time, per environment (documented in full in apps/cloud/README.md → Deploy):

  1. wrangler d1 create / r2 bucket create / queues create / pipelines create, then paste the ids over the <replace-with-…> placeholders. deploy:check lists exactly which are outstanding. New buckets: lunora-cloud-releases and the tenant-backups bucket (-staging variants on staging).
  2. Create the cloud-staging and cloud-production GitHub Environments with CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID. Token scopes: Workers Scripts:Edit, Workers KV:Edit, D1:Edit, R2:Edit, Queues:Edit, Workers for Platforms:Edit, Account Analytics:Read, Zone → Workers Routes:Edit.
  3. Run alchemy provider cloudflare bootstrap once per cell, so two first deploys do not race to create the Alchemy state store. The cell token the provision box receives needs edit on Workers Scripts (incl. Workers for Platforms), D1, R2, KV, Queues and Secrets Store, plus Workers subdomain read.
  4. wrangler secret put … --env <cell> for the Worker secrets (SECRET_ENCRYPTION_KEY, AUTH_SECRET, LUNORA_ADMIN_TOKEN, CLOUDFLARE_API_TOKEN, CREEM_*, GITHUB_WEBHOOK_SECRET, LUNORA_TAIL_SECRET, CONTROL_PLANE_TOKEN). .dev.vars.example documents each, and the symptom of leaving the optional ones unset.
  5. wrangler deploy builds both container images (build box, provision box) with the deploy host's Docker, so it needs a daemon with buildx.

Rebase

Rebased onto alpha again, which had moved 2443 commits ahead, then merged alpha once more for #912. Adapting to it:

  • usePreloadedQuery now returns T | undefined (fix(react): type a preloaded value as possibly undefined #861); the studio sections guard it.
  • alpha's CLI reference test requires a section per command; lunora cloud gained one.
  • @cloudflare/vite-plugin 1.54 treats ai as never-local, so pnpm dev opened a remote session and failed without credentials; remote bindings are now on only with a CLOUDFLARE_API_TOKEN.
  • _generated/ regenerated against alpha's codegen.

Registration is invite-only

apps/cloud now installs inviteOnly() (@lunora/auth/plugins), so account creation is a platform decision: no user row is written for an address with no unspent invitation, whatever minted it — /sign-up/email, an OAuth callback, or AuthAdmin.createUser.

Installing the plugin is what lights the operator path up end to end, because everything downstream is already wired here: it declares the signUpInvitation table (so ensureMigrated provisions it), createAuthAdmin grows create / list / revokeSignUpInvitation, @lunora/runtime exposes those as admin routes, and @lunora/studio renders its sign-up-invitations panel off capabilities.inviteOnly. The vendored sign-up form now reads ?invite= off the URL and submits it as inviteToken.

Two deliberate calls:

  • Team invitations are not bridged to it. lunora/invitations.ts invites someone into an organization; minting a sign-up invitation from one would let any org admin create accounts on a cell whose whole point is that they cannot. An invited teammate with no account needs a sign-up invitation from an operator first.
  • allowFirstUser only in dev, where scripts/seed.ts signs its user up through the real endpoint against an empty database. In production that carve-out is a race between deploying and the owner signing up, so the first invitation is seeded by hand.

Gaps found while auditing the new surface

Asked to check what the new features were missing, and four things were:

  • The two new reserved endpoints had no tests at all. /_lunora/scheduled and /_lunora/queue are the only path by which a Workers-for-Platforms tenant's cron and queue work runs, and nothing exercised them — a regression there is silent, because nothing else calls them. Added packages/runtime/__tests__/tenant-fanout.test.ts (9 cases: the admin gate, keyed cron dispatch, the 405/400 refusals, batch forwarding, the retry list, and malformed-message filtering).
  • QueueForwardBatch / QueueForwardHandler / QueueForwardMessage / QueueForwardResult were not exported by name. They appeared in the API snapshot only because WorkerOptions.queueHandler drags them into the emitted .d.ts — an app typing its own queueHandler (which is exactly what apps/cloud does) could not import them. Now exported from @lunora/runtime and lunorash.
  • None of the new public API was documented. Added: the fan-out endpoints and their scheduledTick / queueHandler options (packages/runtime/docs), per-query D1 cost accounting and d1QueryTag's cardinality rule (packages/d1/docs), LUNORA_AI_GATEWAY_TAGS and the per-call/per-deploy tag split (packages/ai/docs), and deploy attribution via version_metadata (concepts/observability).
  • Five per-call Intl constructions in the studio's format.ts / plan-catalog.ts, each rebuilding locale data per table row. Hoisted to module scope; regionNames() stays lazily memoised because Intl.DisplayNames can throw and a module-level throw would take down the chunk.

Checked and deliberately not changed: PlatformCapabilities needs no new key (the fan-out endpoints are how a WfP host emulates the existing cronTriggers / queues ratings, not a new feature), and apps/cloud/lunora/auth-ui/ is a badly stale registry copy (35 files differ, 38 missing upstream) — refreshing it is a 70-file change that does not belong in this PR.

Review threads

All 28 threads resolved. Of the 6 that were open:

  • TrafficCharts.tsx only-export-components (×2) — countryFlag / countryName and their Intl.DisplayNames helper moved to src/client/format.ts; the file now exports only components and their prop types.
  • js-hoist-intl — already fixed; Intl.DisplayNames is built once behind a lazily-memoised regionNames() (lazy, not module-scope, so a runtime without the region table degrades one column instead of taking down the chunk).
  • studio __proto__ — computed key, security intent unchanged.
  • TimeRangeProvider.tsx react-compiler-no-manual-memoization (×2) — not applied, with the reason now a comment in the file. React Compiler is not enabled for apps/cloud (it is for apps/studio, apps/docs, packages/studio, packages/react), and without it both hooks are load-bearing: deleting them reintroduces the context-value churn the memo exists to prevent. Enabling the compiler here is a separate change — this app's Vite plugin order is load-bearing.

Test plan

  • pnpm run build:packages:prod + pnpm run dist:check — 1465 files, no dev-build markers
  • pnpm run lint:types, lint:eslint, lint:prettier, lint:package-json, lint:generated
  • pnpm run api:check — 56 snapshots (config.api.md updated for the Alchemy 2 WranglerConfigShape)
  • pnpm run test — 69 projects; pnpm run test:workerd
  • Per-package: cloud 929, cli 1717, config 817, runtime 1183
  • Provision-box and build-box images build with Docker (legacy builder); the build box built a fixture pnpm monorepo from apps/web
  • npm audit on the provision-box lockfile — 0 vulnerabilities (dependency review flagged @hono/node-server@1.19.9)
  • Emitted Alchemy 2 programs type-check against the real alchemy@2.0.0-beta.79 / effect@4.0.0-rc.117 types
  • pnpm run e2e:cloud — needs Docker buildx to build the container images at dev start (not available where this was run)
  • A real provision against Cloudflare, and an actual deploy-cloud.yml run — need the credentials and provisioned resources above

Checklist

  • Conventional Commits (breaking changes noted in commit bodies)
  • Added or updated tests covering the change
  • Updated relevant docs (apps/cloud/README.md, GAPS.md, MULTIPLATFORM.md, docs/RESTORE.md, containers' READMEs, CLI + cloud docs pages)
  • packages/config and packages/cli changed for eject / manifest / Alchemy 2; no new package under packages/*
  • No migration impact for existing apps; wranglerToAlchemy's output changes (breaking, pre-release)

Environment

Worker secrets and variables the control plane reads. Values are never committed.

Name New in this PR Needed for
GITHUB_APP_ID, GITHUB_APP_PRIVATE_KEY no GitHub App tokens for push-to-deploy builds
GITHUB_WEBHOOK_SECRET no Verifying GitHub webhook deliveries
GITHUB_APP_SLUG yes Building the App install URL (/v1/github/install)
GITHUB_SETUP_STATE_SECRET yes Signing the setup state (openssl rand -hex 32)
GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET no GitHub login, and the account link that proves who installed a GitHub App
SECRET_ENCRYPTION_KEY no Sealing project secrets and notification channel secrets
LUNORA_ORIGIN_URL no Control-plane origin. Production still has a placeholder (TODO)
AUTH_URL no better-auth's origin. Production must set it (TODO, see wrangler.jsonc)

GitHub App settings, one-time: set the Setup URL to https://<control-plane>/v1/github/setup with "Redirect on update" off, and the App's login callback to the control plane's auth route.

🤖 Generated with Claude Code

@netlify

netlify Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for lunorash ready!

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

QR Code

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

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

@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

This PR introduces the apps/cloud control-plane application, including global data models, authorization, billing, deployment, routing, metering, CLI, hosted-studio UI, domain and secret management, documentation, and WebSocket dispatch validation. It also adds runtime forwarding endpoints for cron ticks and queue batches.

Changes

Lunora Cloud platform

Layer / File(s) Summary
Application foundation and data contracts
apps/cloud/package.json, apps/cloud/lunora/*, apps/cloud/src/billing/*, apps/cloud/*.json, apps/cloud/*.md
Adds application scaffolding, environment templates, tooling, documentation, global schemas, authorization helpers, entitlement plans, usage aggregation, spend caps, and dunning evaluation.
Control-plane domain operations
apps/cloud/lunora/*
Implements organization, membership, projects, invitations, deploy keys, deployments, domains, secrets, builds, logs, billing, usage, audit, and scheduled maintenance operations.
Deployment, routing, and integrations
apps/cloud/src/deploy/*, apps/cloud/src/cloudflare/*, apps/cloud/src/provision.ts, apps/cloud/src/admin/*, apps/cloud/src/secrets/*, apps/cloud/src/github/*, apps/cloud/src/mail/*, apps/cloud/src/dispatcher/*, apps/cloud/src/fanout/*, apps/cloud/src/metering/*, apps/cloud/src/server.ts
Adds Cloudflare provisioning, streamed deployment and rollback flows, encrypted secrets, HTTP routes, admin proxying, webhook handling, domain verification, tenant routing, fan-out, metering, authentication, and Worker entrypoints.
CLI and hosted studio
apps/cloud/src/cli/*, apps/cloud/src/client/*
Adds file-backed CLI configuration, deploy and rollback commands, and an authenticated React studio for organization, project, deployment, billing, secret, member, invitation, deploy-key, usage, build, domain, log, and activity management.

Runtime WfP forwarding

Layer / File(s) Summary
Forwarding endpoints and dispatch spike
packages/runtime/src/create-worker.ts, apps/cloud/spikes/ws-dispatch/*
Adds admin-gated /_lunora/scheduled and /_lunora/queue endpoints with queue forwarding support, plus a WebSocket Durable Object spike and probe for dispatch behavior.

Estimated code review effort: 5 (Critical) | ~120 minutes

Suggested labels: package: runtime, package: react, package: server, package: client

Possibly related PRs

  • anolilab/lunora#92: Adds the runtime readiness endpoint used by the related background-development lifecycle.

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant DeployRouter
  participant DeployHandler
  participant CellScheduler
  participant CloudflareProvisioner
  CLI->>DeployRouter: POST /v1/deploy with bearer deploy key
  DeployRouter->>DeployHandler: handleDeployRequest
  DeployHandler->>CellScheduler: runDeployment
  CellScheduler->>CloudflareProvisioner: deploy tenant bundle
  CloudflareProvisioner-->>DeployHandler: deployment result
  DeployHandler-->>CLI: NDJSON progress events
Loading
sequenceDiagram
  participant Client
  participant DispatcherWorker
  participant ControlPlane
  participant TenantWorker
  participant USAGE_ANALYTICS
  Client->>DispatcherWorker: request tenant hostname
  DispatcherWorker->>ControlPlane: resolve route and plan
  DispatcherWorker->>TenantWorker: dispatch with runtime limits
  TenantWorker-->>DispatcherWorker: tenant response
  DispatcherWorker->>USAGE_ANALYTICS: record request usage
  DispatcherWorker-->>Client: return tenant response
Loading
Pre-merge checks | Passed 5

✅ Passed checks (5 passed)

Check name Status Explanation
Docstring Coverage Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly identifies the addition of the Lunora Cloud control plane on Workers for Platforms and uses concise conventional-commit phrasing.
Description check Passed The description is comprehensive and covers the main implementation areas, testing, checklist status, environment requirements, known limitations, and pending live infrastructure validation. It omits …
Finishing Touches

🧪 Generate unit tests (beta)

  • Create PR with unit tests
  • Commit unit tests in branch claude/cloud-platform-dx-ojvkmu
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions

github-actions Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Thank you for following the naming conventions! 🙏

@github-actions

github-actions Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

React Doctor found no new issues. 🎉

Reviewed by React Doctor for commit bdf98b5.

@codspeed

codspeed Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

Merging this PR will regress 1 benchmark

⚠️ 32 benchmarks spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

⚠️ Different runtime environments detected

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

Open the report in CodSpeed to investigate

⚡ 2 improved benchmarks
❌ 1 regressed benchmark
✅ 292 untouched benchmarks
🆕 7 new benchmarks
⏩ 17 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ 4 after-insert no-op triggers 259.7 µs 290.4 µs -10.58%
⚡ per-id: 50 single-id UNION-ALL probes (pre-fix guardById loop) 5.9 ms 5 ms +16.62%
⚡ baseline (Object.keys + toInternal + path spread per field) 72.2 µs 65.4 µs +10.46%
🆕 deserialize every attachment and decide its liveness N/A 11.1 ms N/A
🆕 ⚠️ the session's liveness tick over 1,000 sockets N/A 52.3 ms N/A
🆕 decodeBoxMessage — progress line N/A 122.5 µs N/A
🆕 decodeBoxMessage — report, 500 aliases N/A 4.2 ms N/A
🆕 ⚠️ 16 jobs — start, 8 progress lines each, result N/A 417.7 µs N/A
🆕 flooding socket — refused at an empty bucket N/A 68.3 µs N/A
🆕 ready socket — progress frame N/A 137.1 µs N/A

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing claude/cloud-platform-dx-ojvkmu (55d9021) with alpha (393125b)

Open in CodSpeed

Footnotes

  1. 17 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Note

Due to the large number of review comments, Critical severity comments were prioritized as inline comments.

🟠 Major comments (35)
apps/cloud/spikes/ws-dispatch/tenant-worker.ts-29-29 (1)

29-29: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Mixed default and named exports in the same file.

WsRoom is a named export while the default export is also declared here. As per coding guidelines, "Never mix a default export with named exports in the same file; if a file exports more than one symbol, use named exports only."

♻️ Proposed fix to use named exports only
-export default {
+export const spikeWorker = {
     async fetch(request, env) {
         // One shared room for the spike (a single DO instance).
         const id = env.WS_DO.idFromName("spike-room");

         return env.WS_DO.get(id).fetch(request);
     },
 };

Note: tenant.wrangler.jsonc's "main": "tenant-worker.ts" requires a default export for the Workers entrypoint, so if this change is made, the wrangler config's expectations for the fetch handler export should be verified.

Also applies to: 96-103

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/spikes/ws-dispatch/tenant-worker.ts` at line 29, The file
currently mixes a named export for WsRoom with a default export, which violates
the export convention here. Update tenant-worker.ts so it uses a single export
style consistently: either remove the default export and export the Workers
handler by name, or if the entrypoint must stay default, move WsRoom to a
separate module and keep this file’s exports aligned with the worker entrypoint
contract. Check the symbols WsRoom and the fetch handler/default export together
to ensure the file no longer contains both export forms.

Source: Coding guidelines

apps/cloud/lunora/schema.ts-86-90 (1)

86-90: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

deployments.adminToken is stored as plaintext, per the inline comment.

The comment acknowledges this should be "envelope-encrypted at rest (§7)" but is "stored plain here for the scaffold." This token is a tenant admin bearer credential used by the admin proxy (§3) — anyone with D1 read access (backup leak, misconfigured binding, etc.) can impersonate the admin proxy for any tenant. src/secrets/crypto.ts already implements AES-256-GCM encryption for the secrets table; reusing that same encrypt/decrypt path for adminToken before this ships beyond the scaffold stage would close this gap with minimal new code.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/schema.ts` around lines 86 - 90, The deployments.adminToken
field is being persisted in plaintext, which should be replaced before this
leaves scaffold state. Update the deployments handling in schema.ts and the
associated read/write path to reuse the existing AES-256-GCM helpers from
src/secrets/crypto.ts so adminToken is encrypted before storage and decrypted on
retrieval. Keep the change localized around the deployments.adminToken symbol
and the same crypto flow used for the secrets table.
apps/cloud/lunora/.lunora-schema.json-336-363 (1)

336-363: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Generated schema is missing the plan field on organizations.

schema.ts defines organizations with cellId, createdAt, name, plan, slug (schema.ts lines 51-57), but this generated JSON's organizations table only lists cellId, createdAt, name, slug — plan is absent. If this JSON drives the actual D1 migration/column set, inserts that supply plan (as schema.ts requires it as non-optional) will either fail or silently write to a nonexistent column depending on how the generator/migrator consumes this file. This looks like a stale artifact that wasn't regenerated after plan was added to the table definition.

Regenerate .lunora-schema.json from the current schema.ts before merging.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/.lunora-schema.json` around lines 336 - 363, The generated
organizations schema is stale and is missing the required plan field that exists
in schema.ts. Regenerate the .lunora-schema.json artifact from the current
schema definition so the organizations table in the JSON matches the
Organizations model and includes plan alongside cellId, createdAt, name, and
slug.
apps/cloud/lunora/invitations.ts-49-65 (1)

49-65: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Prevent admins from inviting owners.

Line 52 allows owners/admins to invite, while Line 50 accepts role: "owner". This lets an admin create a pending owner invitation. Require owner privileges when arguments_.role === "owner".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/invitations.ts` around lines 49 - 65, The invite mutation
in invite currently lets admins create owner invitations because the role input
allows "owner" while assertMember only checks for ["owner", "admin"]. Update the
authorization logic in invite so that when arguments_.role is "owner", only an
owner can proceed, and keep the existing owner/admin access for non-owner roles.
Use the existing invite, assertMember, and arguments_.role symbols to route the
permission check cleanly before inserting the invitation.
apps/cloud/lunora/audit-log.ts-19-31 (1)

19-31: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Do not let arbitrary members forge audit records.

Any member, including viewers, can write free-form action and target values that look like authoritative audit events. Make this internal/system-only, or restrict roles and use an action enum derived by the server-side operation being audited.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/audit-log.ts` around lines 19 - 31, The audit-log record
mutation currently lets any member create free-form audit entries via record,
which allows forged system-like events. Update record in audit-log.ts to be
internal/system-only or enforce a stronger role check than assertMember before
inserting into auditLog, and avoid accepting arbitrary action/target strings by
deriving the action from server-side audit operations or replacing it with a
validated enum. Keep the insert logic in context.db.insert but ensure only
trusted server paths can call this mutation.
apps/cloud/lunora/usage.ts-43-63 (1)

43-63: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Validate metering quantity, period, and deployment ownership.

A valid deploy key can submit negative quantity values or attach usage to an unchecked deploymentId. That can undercount billing/quotas or create cross-org usage rows. Reject non-finite/negative quantities, constrain periodStart, and verify any deploymentId belongs to organizationId.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/usage.ts` around lines 43 - 63, The ingest mutation in
usage.ts only authorizes the deploy key and then writes platformUsage directly,
so add validation before context.db.insert: reject non-finite or negative
quantity values, enforce a sane periodStart range, and when
arguments_.deploymentId is present verify it belongs to
arguments_.organizationId using the deployment lookup/authorization path. Keep
the checks inside ingest so all usage submissions are validated before
persistence.
apps/cloud/lunora/usage.ts-94-133 (1)

94-133: 🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift

Avoid full-table rollups in the Worker.

findMany({}) loads the whole metering table before grouping. Platform usage is high-volume by design, so this can exceed Worker CPU/memory limits as data grows; page by closed period/org/kind or compact incrementally. As per path instructions, apps/**/*.ts: Review application code for performance considerations.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/usage.ts` around lines 94 - 133, The rollup in rollup
currently calls context.db.platformUsage.findMany({}) and loads the entire usage
table into memory before grouping, which is unsafe for high-volume Worker
execution. Update rollup to process only closed records in smaller batches or
paginate by period/org/kind, and keep the compaction incremental so the function
never requires a full-table scan. Use the existing rollup function and
PlatformUsageRow grouping logic as the main place to refactor.

Source: Path instructions

apps/cloud/lunora/organizations.ts-46-63 (1)

46-63: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Do not let public org creation self-assign plan or cell.

Any signed-in user can create an org with plan: "enterprise" and an arbitrary cellId, bypassing billing/entitlement and cell-placement controls. Keep these fields server-selected/admin-only for the public create flow.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/organizations.ts` around lines 46 - 63, The public
organization create mutation currently trusts client-provided cellId and plan
values, which allows signed-in users to self-assign enterprise access and
arbitrary cell placement. Update create in organizations.ts so the public flow
derives cellId and plan server-side (or strips them from input entirely), and
only accepts name/slug from the client while keeping plan defaulted to free and
cell assignment controlled by the server/admin path. Locate the mutation by its
create symbol and adjust the insert payload to use server-selected values rather
than arguments_.cellId or arguments_.plan.
apps/cloud/lunora/cells.ts-29-57 (1)

29-57: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Restrict cell inventory and registration to platform operators.

list exposes every Cloudflare account/dispatch namespace without auth, and register lets any signed-in user add a cell. These are fleet-control operations and should require a platform-admin/operator role.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/cells.ts` around lines 29 - 57, The cell inventory and
registration mutations in list and register are currently accessible too
broadly; both should be limited to platform operators. Add an explicit
platform-admin/operator authorization check in these functions, alongside the
existing auth guard in register, and ensure list also verifies the caller’s role
before returning any cells. Use the query.query and mutation handlers in
cells.ts to locate the access control points.
apps/cloud/lunora/organizations.ts-23-28 (1)

23-28: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Gate organization inventory behind platform-admin authorization.

Line 24 returns every organization, including slugs, plans, and cell IDs, without even requiring a signed-in user. This contradicts the “platform-admin surface” contract and leaks tenant metadata.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/organizations.ts` around lines 23 - 28, The organizations
inventory query in list is exposing tenant metadata without any access check.
Update the query.query handler to require a signed-in platform-admin before
calling context.db.organizations.findMany(), using the existing auth/role guard
pattern used elsewhere in the codebase. If the caller is not authorized, return
an appropriate access-denied response instead of returning OrganizationRow[].
apps/cloud/lunora/members.ts-30-54 (1)

30-54: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Prevent admins from granting owner privileges.

Line 33 allows both owners and admins to call add, while Line 31 accepts role: "owner". An admin can therefore promote another account to owner. Require an existing owner when assigning the owner role.

Proposed guard
-        await assertMember(context, arguments_.organizationId, ["owner", "admin"]);
+        const actor = await assertMember(context, arguments_.organizationId, ["owner", "admin"]);
+
+        if (arguments_.role === "owner" && actor.role !== "owner") {
+            throw new LunoraError("FORBIDDEN", "only owners can add owners");
+        }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/members.ts` around lines 30 - 54, The add mutation
currently lets admins assign the owner role because it only checks
assertMember(context, organizationId, ["owner", "admin"]) while accepting role
from the input. Update add in members.ts so that when arguments_.role is "owner"
it requires an existing owner (for example by using assertMember with only
"owner" or adding a separate guard before the insert), while still allowing
admins to create non-owner members. Keep the existing duplicate-member and quota
checks intact, and use the add mutation and assertMember helper as the main
points to locate the change.
apps/cloud/lunora/members.ts-57-65 (1)

57-65: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Protect owner removal and sole-owner invariants.

An admin can delete an owner, and the last owner can be removed, leaving the organization without an account that can recover owner-only operations. Fetch the target member before deletion and require another remaining owner.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/members.ts` around lines 57 - 65, The members.remove
mutation currently allows admins to delete owners and can delete the last
remaining owner. Update the remove flow in members.remove to first fetch the
target member, verify its role before deletion, and block removal when the
member is an owner and there is no other owner left in the organization. Use the
existing assertMember and assertRowInOrg checks as the entry point, then add a
remaining-owner check before context.db.delete(id).
apps/cloud/lunora/deploy-keys.ts-52-77 (1)

52-77: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Validate project ownership before issuing scoped deploy keys.

projectId is stored without checking that it belongs to organizationId. An org admin who knows another org’s project ID can mint a key row that later authorizes project-scoped paths against the wrong project.

Proposed guard
         await assertMember(context, arguments_.organizationId, ["owner", "admin"]);
+
+        if (arguments_.projectId) {
+            await assertRowInOrg(context, arguments_.projectId, arguments_.organizationId, "project");
+        }
 
         const key = formatDeployKey({
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/deploy-keys.ts` around lines 52 - 77, The deploy key
issuance flow in issue does not verify that the optional projectId belongs to
the provided organizationId before storing it. In the issue mutation, add a
lookup/validation step against the projects record using arguments_.projectId
and arguments_.organizationId, and reject the request unless the project is
owned by that organization. Keep the existing insert logic in context.db.insert
only after this ownership check passes.
apps/cloud/lunora/invitations.ts-49-51 (1)

49-51: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Make invitation role optional or update the HTTP caller.

The downstream invite route calls api.invitations.invite with only email and organizationId, but this mutation requires role, so hosted invites will fail validation.

Proposed fix
-    .input({ email: v.string(), organizationId: v.id("organizations"), role })
+    .input({ email: v.string(), organizationId: v.id("organizations"), role: v.optional(role) })
-            role: arguments_.role,
+            role: arguments_.role ?? "member",
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/invitations.ts` around lines 49 - 51, The invite mutation
currently requires role, but the hosted HTTP caller only passes email and
organizationId, so validation fails. Update the invitations.invite input schema
to make role optional, or change the caller to always supply a valid role; use
the invite mutation and its input definition to keep both sides aligned. Ensure
the mutation body handles the missing role safely if you make it optional.
apps/cloud/lunora/deployments.ts-10-25 (1)

10-25: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Encrypt adminToken before persisting it. The deployment row still stores this bearer token as plain text, even though it’s meant to be an at-rest secret and the repo already has envelope-encryption support in apps/cloud/src/secrets/crypto.ts. Encrypt on write and decrypt only in adminTarget to limit DB/backup exposure.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/deployments.ts` around lines 10 - 25, The DeploymentRow
adminToken is still being stored in plain text; update the deployment write path
to encrypt this secret before persisting it and only decrypt it when reading in
adminTarget. Use the existing envelope-encryption helpers from crypto.ts, and
make sure the change is applied wherever DeploymentRow is created or saved so
the stored value is never raw.
apps/cloud/lunora/deployments.ts-175-200 (1)

175-200: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Reject non-HTTPS deployment URLs at the mutation boundary

deployment.url is persisted and rendered directly as <a href={deployment.url}>; React 19 still allows javascript: hrefs, so a malicious deploy key or org member could store a link that executes script when clicked in the studio. Restrict this field to https:// (or otherwise parse and allow only safe schemes) in updateStatus.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/deployments.ts` around lines 175 - 200, The updateStatus
mutation currently accepts any deployment.url and stores it directly, which
allows unsafe schemes to be persisted. Add validation in updateStatus before
context.db.patch so only safe https:// URLs (or explicitly allowed safe schemes)
are accepted, and reject invalid values with a clear error. Use the existing
updateStatus mutation, its args.url handling, and the patch call as the main
place to enforce this boundary.
apps/cloud/lunora/projects.ts-27-35 (1)

27-35: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Make byGithubRepo internal. It’s only used from the GitHub webhook router, but exporting it as a public query lets any caller resolve organizationId/projectId from a guessed owner/name repo string. If this really needs to stay public, add an explicit rationale comment like planForScript; otherwise switch it to internalQuery.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/projects.ts` around lines 27 - 35, Make byGithubRepo
internal instead of a public query, since it is only consumed by the GitHub
webhook router and currently exposes organizationId/projectId lookups for
guessed owner/name values. Update the lunora/projects.ts export to use
internalQuery for byGithubRepo, and keep its existing repository input and
return shape so the webhook call site can still resolve projects. If there is a
legitimate reason to keep it public, add a short explicit rationale comment near
byGithubRepo such as planForScript; otherwise prefer the internal API.

Source: Path instructions

apps/cloud/lunora/billing.ts-38-57 (1)

38-57: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Validate priceId against known plan price ids before checkout.

priceId is taken verbatim from client input and passed straight to context.payments.createCheckout. If it doesn't match any priceIds entry in LUNORA_CLOUD_PLANS.plans (typo, stale id, wrong environment), the org gets billed but resolveEntitlements filters active subscription states by ACTIVE_STATES, unions features, and picks the maximum limit across concurrently-active plans only for price ids it recognizes — so the resulting subscription grants no plan/features/limits at all, i.e. the org pays and gets nothing.

🛡️ Proposed fix
+const KNOWN_PRICE_IDS = new Set(Object.values(LUNORA_CLOUD_PLANS.plans).flatMap((plan) => plan.priceIds));
+
 export const checkout = action
     .input({
         cancelUrl: v.string(),
         organizationId: v.id("organizations"),
         priceId: v.string(),
         successUrl: v.string(),
     })
     .action(async ({ ctx: context, args: { cancelUrl, organizationId, priceId, successUrl } }): Promise<{ url: string }> => {
         await assertMember(context, organizationId, ["owner", "admin"]);
+
+        if (!KNOWN_PRICE_IDS.has(priceId)) {
+            throw new LunoraError("BAD_REQUEST", `unknown priceId: ${priceId}`);
+        }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/billing.ts` around lines 38 - 57, The checkout action
currently forwards client-provided priceId directly into
context.payments.createCheckout, so validate it against the known priceIds in
LUNORA_CLOUD_PLANS.plans before creating the session. In checkout, reject
unknown or mismatched price ids early (for example, by checking the selected
plan list and aborting with an error) and only proceed when the priceId matches
a configured plan for the current environment. This keeps the billing flow
aligned with resolveEntitlements and prevents subscriptions that create charges
without granting any recognized plan features or limits.
apps/cloud/src/client/DeployKeysSection.tsx-42-54 (1)

42-54: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Revoke has no error handling or feedback.

revokeKey.mutate(...) is fired with void and no catch; a failed revoke (network error, stale org membership, etc.) fails silently with no UI feedback and an unhandled promise rejection.

🛡️ Proposed fix
                                         <button
                                             className="link danger"
-                                            onClick={() => {
-                                                void revokeKey.mutate({ id: key._id, organizationId });
+                                            onClick={() => {
+                                                void (async () => {
+                                                    try {
+                                                        await revokeKey.mutate({ id: key._id, organizationId });
+                                                    } catch (error_: unknown) {
+                                                        setError(error_ instanceof Error ? error_.message : "revoke failed");
+                                                    }
+                                                })();
                                             }}
                                             type="button"
                                         >
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/client/DeployKeysSection.tsx` around lines 42 - 54, The Revoke
action in DeployKeysSection fires revokeKey.mutate(...) without handling
failures, so add error handling and user feedback around that mutation. Update
the onClick flow to await or catch the revoke call, surface a visible error
state or toast on failure, and keep the button behavior aligned with the
existing revokeKey and organizationId usage so silent rejections do not occur.
apps/cloud/src/provision.ts-86-96 (1)

86-96: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Make tenant resource provisioning idempotent before enabling retries.

Every deploy creates D1/R2 resources from scriptName before script upload. That contradicts the deploy contract (“Safe to retry”) and can orphan or replace tenant state on redeploys/retries. Persist and reuse resource IDs/names, or implement explicit lookup/upsert semantics before binding them.

As per path instructions, apps/**/*.ts: “Review application code for: Best practices and potential issues; Proper error handling.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/provision.ts` around lines 86 - 96, The D1/R2 provisioning in
provision() is not idempotent because it always creates new resources from
spec.scriptName before upload, which breaks the deploy retry contract. Update
the logic around api.createD1Database and api.createR2Bucket to first look up or
reuse existing tenant resources, or persist and reuse the created IDs/names
across deploys, then bind the existing resource references instead of creating
replacements on every run.

Source: Path instructions

apps/cloud/src/deploy/orchestrator.ts-41-53 (1)

41-53: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Guard progress callback failures so deployments still reach a terminal outcome.

If onProgress fails during provisioning, runDeployment rejects before the provisioner runs and never emits/returns failed. If it fails while reporting failed, the failure path also escapes.

As per path instructions, apps/**/*.ts: “Review application code for: Proper error handling.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/deploy/orchestrator.ts` around lines 41 - 53, Guard the
progress reporting in runDeployment so onProgress failures do not abort the
deployment flow before a terminal state is reached. Wrap the emit calls in the
queued/provisioning/live and failed paths in their own try/catch (or otherwise
swallow/report callback errors) while preserving the main try/catch around
options.scheduler.run and options.provisioner.deploy(spec). Ensure the catch
block in orchestrator.ts still emits phase: "failed" and returns the failed
status even if emitting the failure update itself throws.

Source: Path instructions

apps/cloud/src/cli/config.ts-8-16 (1)

8-16: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Treat deployKey as a sensitive persistence contract.

deployKey is a bearer credential. The concrete file-backed store shown in context writes JSON with default permissions, which can make the key readable by other local users depending on umask. Require ConfigStore implementations to use user-only permissions or an OS credential store.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/cli/config.ts` around lines 8 - 16, The sensitive persistence
contract for deployKey is not enforced in ConfigStore, so the file-backed
implementation may persist a bearer credential with overly permissive defaults.
Update the ConfigStore contract and the concrete store that implements
read/write to require user-only protection or an OS credential store, and ensure
any JSON write path in the config handling honors restrictive permissions when
persisting CliConfig.deployKey.
apps/cloud/src/deploy/client.ts-50-92 (1)

50-92: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Fail closed on incomplete deploy streams.

If the connection ends before a terminal { done: true } event, this returns status: "unknown" instead of failing the deploy command. Also flush the TextDecoder before parsing the final buffered line.

Suggested fix
 let buffer = "";
+let sawDone = false;
 let status = "unknown";
@@
         if (event["done"] === true && typeof event["status"] === "string") {
+            sawDone = true;
             status = event["status"];
         }
@@
-    consume(buffer);
+    buffer += decoder.decode();
+    consume(buffer);
+
+    if (!sawDone) {
+        throw new Error("deploy stream ended before terminal done event");
+    }
 
     return { status };

As per path instructions, apps/**/*.ts: “Review application code for: Proper error handling.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/deploy/client.ts` around lines 50 - 92, The stream handling in
deploy/client.ts should fail closed when the reader ends before a terminal
DeployEvent with done: true is received, instead of returning status: "unknown".
Update the consume flow around reader.read(), buffer parsing, and the final
return so the deploy command throws or otherwise signals an error if no terminal
event was seen, and make sure the TextDecoder is flushed before parsing the last
buffered chunk so no partial UTF-8 data is dropped.

Source: Path instructions

apps/cloud/src/deploy/handler.ts-111-112 (1)

111-112: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Do not let the request body escalate the deploy-key environment.

body.kind overrides target.type, so a key verified for one environment can request another unless every backend implementation re-checks it. Enforce the key’s scoped type here before selecting the dispatch namespace.

Suggested fix
 const kind = body.kind ?? target.type;
+if (kind !== target.type) {
+    return json(403, { error: "deploy key is not authorized for this deployment kind" });
+}
 const { branch, projectId, scriptName } = body;

As per path instructions, apps/**/*.ts: “Review application code for: Best practices and potential issues.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/deploy/handler.ts` around lines 111 - 112, The deploy handler
currently lets body.kind override target.type, which can escalate the request
into a different environment namespace. In handler.ts, update the dispatch
selection so it is always constrained by the verified key’s scoped type from
target.type, and only use body.kind if it matches that scope or is otherwise
explicitly validated before dispatch. Keep the fix localized around the
kind/target.type resolution in the handler logic.

Source: Path instructions

apps/cloud/src/cloudflare/api.ts-143-185 (1)

143-185: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Encode dynamic Cloudflare path segments.

namespace and scriptName are interpolated directly into REST paths. A value containing /, ?, #, or % can address the wrong Cloudflare resource or produce hard-to-debug provisioning failures.

Suggested fix
+const pathSegment = (value: string): string => encodeURIComponent(value);
+
 deleteDispatchScript: async ({ namespace, scriptName }) => {
-    const response = await fetchImpl(`${base}/workers/dispatch/namespaces/${namespace}/scripts/${scriptName}`, {
+    const response = await fetchImpl(`${base}/workers/dispatch/namespaces/${pathSegment(namespace)}/scripts/${pathSegment(scriptName)}`, {
         headers: { authorization: authHeader },
         method: "DELETE",
     });
@@
-const response = await fetchImpl(`${base}/workers/dispatch/namespaces/${input.namespace}/scripts/${input.scriptName}`, {
+const response = await fetchImpl(`${base}/workers/dispatch/namespaces/${pathSegment(input.namespace)}/scripts/${pathSegment(input.scriptName)}`, {
@@
-await callJson(`/workers/dispatch/namespaces/${namespace}/scripts/${scriptName}/secrets`, "PUT", { name, text, type: "secret_text" });
+await callJson(`/workers/dispatch/namespaces/${pathSegment(namespace)}/scripts/${pathSegment(scriptName)}/secrets`, "PUT", { name, text, type: "secret_text" });

As per path instructions, apps/**/*.ts: “Review application code for: Best practices and potential issues; Proper error handling.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/cloudflare/api.ts` around lines 143 - 185, The Cloudflare REST
paths in deleteDispatchScript, putDispatchScript, and putSecret interpolate
namespace and scriptName directly, which can break or misroute requests when
values contain reserved characters. Update the path construction in
cloudflare/api.ts to URL-encode each dynamic segment before joining them into
the /workers/dispatch/namespaces/.../scripts/... endpoints, and keep the
existing fetch/callJson error handling intact. Use the affected methods
deleteDispatchScript, putDispatchScript, and putSecret as the fix points.

Source: Path instructions

apps/cloud/src/deploy/router.ts-210-221 (1)

210-221: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Separate mail-delivery failures from invite authorization failures.

If sendInvitationEmail fails after invitations.invite creates the token, the route returns 403 invite rejected, leaving a valid invitation behind while reporting the wrong failure class.

Suggested fix
-        await sendInvitationEmail(environment as unknown as Record<string, unknown>, { acceptUrl, to: invite.email });
+        try {
+            await sendInvitationEmail(environment as unknown as Record<string, unknown>, { acceptUrl, to: invite.email });
+        } catch (error) {
+            return jsonError(502, error instanceof Error ? error.message : "invitation email failed");
+        }
 
         return Response.json({ ok: true });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/deploy/router.ts` around lines 210 - 221, Separate the
email-delivery failure path from the invitation-creation path in the router
handler. In the try block around context.runMutation(api.invitations.invite) and
sendInvitationEmail, only return 403 via jsonError when the invite mutation
itself is rejected; if sendInvitationEmail fails after a token is created,
handle that as a distinct error class and return an appropriate server-error
response instead of “invite rejected.” Keep the token creation logic in the same
handler, but split the error handling so the router distinguishes invitation
authorization failures from mail delivery failures.
apps/cloud/src/deploy/router.ts-358-375 (1)

358-375: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Do not silently omit tenant secrets during deploys.

When SECRET_ENCRYPTION_KEY is missing, resolveSecrets returns {}. That can deploy tenants without their configured secrets instead of failing closed.

Suggested fix
             // Decrypt the project's stored secrets at the edge and hand them to the
-            // deploy spec. No-op when the master key isn't configured.
+            // deploy spec.
             resolveSecrets: async ({ key, organizationId, projectId }) => {
-                if (!environment.SECRET_ENCRYPTION_KEY) {
-                    return {};
-                }
-
                 const rows = await context.runQuery<EncryptedSecretRow[]>(api.secrets.listEncrypted, { deployKey: key, organizationId, projectId });
+
+                if (rows.length === 0) {
+                    return {};
+                }
+
+                if (!environment.SECRET_ENCRYPTION_KEY) {
+                    throw new Error("SECRET_ENCRYPTION_KEY not configured; refusing to deploy without tenant secrets");
+                }
+
                 const entries = await Promise.all(
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/deploy/router.ts` around lines 358 - 375, The resolveSecrets
callback in router.ts is failing open by returning an empty object when
SECRET_ENCRYPTION_KEY is missing, which can silently deploy without tenant
secrets. Update resolveSecrets to fail closed instead: in the branch that
currently checks environment.SECRET_ENCRYPTION_KEY, throw an error or otherwise
abort the deploy instead of returning {}. Keep the secret fetch/decrypt path
unchanged for the valid-key case, and make sure the behavior is tied to
resolveSecrets and decryptSecret so the missing-key case is impossible to
ignore.
apps/cloud/src/secrets/crypto.ts-14-23 (1)

14-23: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Reject non-hex master keys before importing AES keys.

Number.parseInt returns NaN for invalid hex pairs, and assigning that into Uint8Array coerces to 0. A malformed SECRET_ENCRYPTION_KEY can therefore become a different valid key instead of failing.

Suggested fix
 const hexToBytes = (hex: string): Uint8Array => {
-    if (hex.length % 2 !== 0) {
+    if (hex.length % 2 !== 0 || !/^[\da-f]+$/iu.test(hex)) {
         throw new Error("SECRET_ENCRYPTION_KEY must be hex");
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/secrets/crypto.ts` around lines 14 - 23, The hexToBytes helper
currently accepts malformed pairs because Number.parseInt can yield NaN and
Uint8Array coerces it to 0, so reject non-hex SECRET_ENCRYPTION_KEY values
before any AES key import. Update hexToBytes in crypto.ts to validate each hex
pair (or the full string) and throw on any invalid character instead of silently
converting it, so callers of the AES import path always fail fast on bad input.
apps/cloud/src/deploy/preview.ts-10-25 (1)

10-25: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Make preview script names collision-resistant.

slugify is lossy and truncated, so distinct branches can map to the same script id and overwrite the wrong preview deployment. Add a stable suffix from the original branch/project input, and keep an explicit non-empty fallback.

Suggested fix
-const slugify = (input: string): string => {
-    let value = input.toLowerCase().replaceAll(/[^a-z0-9]+/gu, "-");
+const hashFragment = (input: string): string => {
+    let hash = 7;
+
+    for (const character of input) {
+        hash = (hash * 31 + (character.codePointAt(0) ?? 0)) % 4_294_967_291;
+    }
+
+    return hash.toString(36);
+};
+
+const slugify = (input: string, maxLength = 40): string => {
+    let value = input.toLowerCase().replaceAll(/[^a-z0-9]+/gu, "-");
 
     while (value.startsWith("-")) {
         value = value.slice(1);
@@
         value = value.slice(0, -1);
     }
 
-    return value.slice(0, 40);
+    return value.slice(0, maxLength).replaceAll(/-+$/gu, "") || "x";
 };
 
 /** Deterministic dispatch-namespace script id for a project's branch preview. */
-export const previewScriptName = (projectSlug: string, branch: string): string => `${slugify(projectSlug)}-pr-${slugify(branch)}`;
+export const previewScriptName = (projectSlug: string, branch: string): string =>
+    `${slugify(projectSlug, 28)}-${hashFragment(projectSlug)}-pr-${slugify(branch, 20)}-${hashFragment(branch)}`;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/deploy/preview.ts` around lines 10 - 25, The
previewScriptName/slugify path is collision-prone because the current normalized
branch and project slug are truncated and can map different inputs to the same
script id. Update previewScriptName to append a stable suffix derived from the
original projectSlug and branch inputs (using a deterministic hash or similar)
so ids remain unique even after slugify truncation, and keep an explicit
non-empty fallback when the generated slug is empty. Ensure the fix is localized
around slugify and previewScriptName so the script name remains deterministic
and collision-resistant.
apps/cloud/src/deploy/router.ts-335-338 (1)

335-338: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Fail fast when Cloudflare provisioning credentials are missing.

Defaulting required credentials to empty strings pushes a configuration error into the deploy/provisioning flow, where it can fail late and obscure the root cause.

Suggested fix
         const cell = environment.LUNORA_CELL ?? "default";
         const appDomain = environment.LUNORA_APP_DOMAIN ?? "lunora.app";
-        const cloudflareApi = createHttpCloudflareApi({ accountId: environment.CLOUDFLARE_ACCOUNT_ID ?? "", apiToken: environment.CLOUDFLARE_API_TOKEN ?? "" });
+        if (!environment.CLOUDFLARE_ACCOUNT_ID || !environment.CLOUDFLARE_API_TOKEN) {
+            return Promise.resolve(jsonError(500, "Cloudflare provisioning credentials are not configured"));
+        }
+
+        const cloudflareApi = createHttpCloudflareApi({ accountId: environment.CLOUDFLARE_ACCOUNT_ID, apiToken: environment.CLOUDFLARE_API_TOKEN });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/deploy/router.ts` around lines 335 - 338, The Cloudflare
provisioning setup in createHttpCloudflareApi/createCloudflareProvisioner is
silently defaulting required credentials to empty strings, which delays
configuration failures. Update the router provisioning path to validate
environment.CLOUDFLARE_ACCOUNT_ID and environment.CLOUDFLARE_API_TOKEN before
calling createHttpCloudflareApi, and fail fast with a clear error if either is
missing. Keep the existing appDomain/urlForScript flow intact, but only
construct the cloudflareApi and provisioner once the required credentials are
present.

Source: Path instructions

apps/cloud/src/admin/proxy.ts-57-60 (1)

57-60: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Validate admin paths before forwarding with the bearer token.

request.path is caller-controlled and concatenated into a privileged URL. Reject .., empty segments, query fragments, and unsupported methods before attaching the tenant admin token.

Suggested fix
+const allowedAdminMethods = new Set(["GET", "POST"]);
+
+const normalizeAdminPath = (path: string): null | string => {
+    const segments = path.split("/");
+
+    if (segments.some((segment) => segment === "" || segment === "." || segment === ".." || segment.includes("?") || segment.includes("#"))) {
+        return null;
+    }
+
+    return segments.map(encodeURIComponent).join("/");
+};
+
 export const proxyAdminRequest = async (request: AdminProxyRequest, deps: AdminProxyDeps): Promise<Response> => {
     await deps.authorize(request.organizationId);
@@
 
     const fetchImpl = deps.fetch ?? globalThis.fetch;
-    const response = await fetchImpl(`${stripTrailingSlashes(target.url)}/_lunora/admin/${request.path}`, {
+    const method = request.method.toUpperCase();
+    const adminPath = normalizeAdminPath(request.path);
+
+    if (!adminPath || !allowedAdminMethods.has(method)) {
+        return json(400, { error: "invalid admin request" });
+    }
+
+    const response = await fetchImpl(`${stripTrailingSlashes(target.url)}/_lunora/admin/${adminPath}`, {
         body: request.body === undefined ? undefined : JSON.stringify(request.body),
         headers: { authorization: `Bearer ${target.adminToken}`, "content-type": "application/json" },
-        method: request.method,
+        method,
     });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/admin/proxy.ts` around lines 57 - 60, The proxy forwarding in
`proxy.ts` is using caller-controlled `request.path` and `request.method` to
build a privileged admin URL before attaching `target.adminToken`. Add
validation in the admin forwarding flow (around the `fetchImpl` call) to reject
path traversal and malformed paths such as `..`, empty segments, and any query
or fragment components, and only allow the intended HTTP methods. Keep the
bearer token attachment after validation so only sanitized admin requests are
proxied.
apps/cloud/src/deploy/router.ts-171-183 (1)

171-183: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Validate usage values before ingesting billing records.

kind is only typed at compile time, and quantity accepts negative values. A valid deploy key could submit negative or unknown usage and skew billing/metering unless every downstream mutation duplicates these guards.

Suggested fix
 type UsageKind = "cpuMs" | "requests" | "storageBytes";
+const usageKinds = new Set<UsageKind>(["cpuMs", "requests", "storageBytes"]);
@@
-    if (!usage?.deployKey || !usage.organizationId || !usage.kind || typeof usage.quantity !== "number" || typeof usage.periodStart !== "number") {
+    if (
+        !usage?.deployKey ||
+        !usage.organizationId ||
+        !usage.kind ||
+        !usageKinds.has(usage.kind) ||
+        typeof usage.quantity !== "number" ||
+        !Number.isFinite(usage.quantity) ||
+        usage.quantity < 0 ||
+        typeof usage.periodStart !== "number" ||
+        !Number.isFinite(usage.periodStart)
+    ) {
         return jsonError(400, "deployKey, organizationId, kind, quantity and periodStart are required");
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/deploy/router.ts` around lines 171 - 183, The usage validation
in router.ts only checks presence/type, but `api.usage.ingest` can still receive
invalid billing data. Update the request guard in the `ingest` handler to reject
negative `quantity` and unknown `kind` values before calling
`context.runMutation`, using the existing `usage` fields and the
`api.usage.ingest` entry point as the main locations to fix.

Source: Path instructions

apps/cloud/src/cli/file-store.ts-21-24 (1)

21-24: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Persisted config (including deployKey) is written with default file permissions.

writeFile doesn't set a restrictive mode, so the file lands with the process's default permissions (commonly world/group-readable). Since CliConfig persists a secret deployKey, other local users on a shared machine could read it.

🔒 Suggested fix
         write: async (config) => {
             await mkdir(dirname(path), { recursive: true });
-            await writeFile(path, `${JSON.stringify(config, null, 2)}\n`, "utf8");
+            await writeFile(path, `${JSON.stringify(config, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
         },
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/cli/file-store.ts` around lines 21 - 24, The write path in
file-store.ts persists CliConfig, including deployKey, with default permissions
via writeFile, which can leave the file readable by other users. Update the
write method in the file-store implementation to create the config file with
restrictive permissions (for example, owner-read/write only) when writing the
JSON payload, and keep the existing mkdir(dirname(path), { recursive: true })
flow intact.
apps/cloud/src/server.ts-144-144 (1)

144-144: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Cron/queue fan-out bypasses per-plan runtime limits.

dispatcher/worker.ts applies limitsForPlan(route.plan) when dispatching regular HTTP traffic (env.DISPATCHER.get(route.scriptName, undefined, { limits })), but here Env.DISPATCHER is typed without a limits/options parameter, and dispatchCronTick/dispatchQueueBatch call dispatcher.get(...) with none. Tenant cron and queue handlers therefore run without the plan-scaled CPU/subrequest caps enforced on the request path, letting a free-tier tenant's scheduled/queue work consume resources unconstrained by its plan.

Also applies to: 236-274

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/server.ts` at line 144, The cron/queue dispatch path is
bypassing plan-based runtime limits because Env.DISPATCHER and the calls in
dispatchCronTick and dispatchQueueBatch do not accept/pass the same options used
by regular HTTP dispatch. Update the DISPATCHER type to include the
options/limits parameter, then thread limitsForPlan(route.plan) through the
dispatcher.get calls in dispatchCronTick, dispatchQueueBatch, and any related
fan-out helpers so scheduled and queue handlers run with the same per-plan
CPU/subrequest caps as the request path.
apps/cloud/src/server.ts-405-417 (1)

405-417: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Auth initialization race: auth is visible before migration completes, and failures leave it poisoned.

auth is assigned at Line 410 synchronously, then ensureMigrated(...) is awaited at Line 411. Any concurrent request that lands in that window sees auth truthy, skips re-initialization, and proceeds straight to worker.fetch (which calls auth.api.getSession) against a schema that may not have finished migrating yet. Further, if ensureMigrated throws, auth stays set to the already-created (possibly unmigrated) instance — there's no reset, so the isolate is stuck in a broken state until it recycles.

🔒 Suggested guard against concurrent/failed init
+let authInitPromise: Promise<void> | null = null;
+
 export default {
     async fetch(request: Request, env: Env, context: ExecutionContextLike): Promise<Response> {
-        if (!auth) {
-            // Runtime auth instance uses the SQL adapter; a throwaway instance on
-            // the raw D1 drives the one-time schema migration (better-auth Kysely).
-            auth = createAuth({ ...authOptions(env), database: lunoraD1Adapter(env.DB as never) });
-            await ensureMigrated(createAuth({ ...authOptions(env), database: env.DB as never }));
-        }
+        if (!authInitPromise) {
+            authInitPromise = (async () => {
+                await ensureMigrated(createAuth({ ...authOptions(env), database: env.DB as never }));
+                auth = createAuth({ ...authOptions(env), database: lunoraD1Adapter(env.DB as never) });
+            })().catch((error) => {
+                authInitPromise = null;
+                throw error;
+            });
+        }
+
+        await authInitPromise;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/server.ts` around lines 405 - 417, `fetch` in `server.ts`
initializes `auth` before `ensureMigrated` completes, which can expose a
half-initialized instance and leave it stuck on failure. Update the
initialization flow in `fetch` so migration finishes successfully before
publishing `auth` to the shared singleton, and if migration throws, clear/reset
`auth` so the next request retries setup. Use the existing `auth`,
`ensureMigrated`, `createAuth`, and `worker.fetch` flow to keep the fix
localized.

Comment thread apps/cloud/lunora/secrets.ts Resolved
Comment thread apps/cloud/lunora/secrets.ts Resolved
Comment thread apps/cloud/src/deploy/handler.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (3)
apps/cloud/lunora/deployments.ts (1)

114-119: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Fetch the project directly instead of scanning all org projects.

Loading every project in the org to check membership of one projectId is O(n) and unnecessary — context.db.get(projectId) plus an org-match comparison (the same pattern used in adminTarget above) is O(1) and scales independently of project count.

As per path instructions, application code should be reviewed for performance considerations.

♻️ Suggested fix
-        // Integrity: the project must belong to the same org (no cross-org linkage).
-        const { page } = await context.db.projects.findMany({ where: { organizationId: arguments_.organizationId } });
-
-        if (!(page as unknown as ProjectRow[]).some((project) => project._id === arguments_.projectId)) {
-            throw new LunoraError("NOT_FOUND", "project not found in this organization");
-        }
+        // Integrity: the project must belong to the same org (no cross-org linkage).
+        const project = (await context.db.get(arguments_.projectId)) as { organizationId: Id<"organizations"> } | null;
+
+        if (!project || project.organizationId !== arguments_.organizationId) {
+            throw new LunoraError("NOT_FOUND", "project not found in this organization");
+        }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/deployments.ts` around lines 114 - 119, Replace the
org-wide scan in the project membership check with a direct lookup using
context.db.get(projectId), then compare the returned project’s organizationId
against arguments_.organizationId as done in adminTarget. Update the existing
validation in deployments.ts to use the fetched ProjectRow directly and throw
the same LunoraError if the project is missing or belongs to a different org,
avoiding the findMany/page iteration entirely.

Source: Path instructions

apps/cloud/lunora/audit-log.ts (1)

33-40: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Unbounded audit-log read.

list loads and sorts the entire audit history for an org on every call. Since this is an append-only, ever-growing log, this will degrade linearly with org age/activity. Consider adding a limit/cursor param (or a findMany order-by + limit if the facade supports it) instead of pulling the full table into memory.

As per path instructions, application code should be reviewed for performance considerations.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/audit-log.ts` around lines 33 - 40, The audit-log query in
list is reading and sorting the entire organization history in memory, which
will not scale. Update list to support bounded pagination by adding a limit
and/or cursor parameter, and prefer server-side ordering with findMany if
available so only the newest AuditRow entries are fetched. Keep assertMember and
the existing organizationId filter, but avoid returning all rows and calling
toSorted on the full result set.

Source: Path instructions

apps/cloud/src/client/styles.css (1)

1-13: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Stylelint: missing blank line before color-scheme declaration.

🎨 Suggested fix
     --ok: `#3ecf8e`;
+
     color-scheme: dark;
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/client/styles.css` around lines 1 - 13, The :root style block
in styles.css needs a blank line before the color-scheme declaration to satisfy
Stylelint. Update the CSS custom property section so the color-scheme: dark rule
is separated from the variable declarations by an empty line, keeping the
existing :root selector and variable names unchanged.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/cloud/lunora/organizations.ts`:
- Around line 23-28: The list query is currently returning every organization
without checking the caller’s access. Update the list handler in organization
query logic to scope results to the signed-in user, either by filtering through
membership data or by calling assertMember before returning rows, so
OrganizationList/OrganizationDashboard only receive organizations the caller
belongs to.

In `@apps/cloud/src/deploy/handler.ts`:
- Around line 203-217: The deployment flow in handler.ts needs to handle
failures from the onProgress callback and deps.backend.updateStatus the same way
as resolveSecrets, instead of letting them abort start. Wrap the runDeployment
await in a try/catch inside the handler logic, use the existing
deploymentId/key/status path to mark the deployment as failed on any rejection,
and move controller.close() into a finally block so the stream is always closed
even when progress reporting fails.

---

Nitpick comments:
In `@apps/cloud/lunora/audit-log.ts`:
- Around line 33-40: The audit-log query in list is reading and sorting the
entire organization history in memory, which will not scale. Update list to
support bounded pagination by adding a limit and/or cursor parameter, and prefer
server-side ordering with findMany if available so only the newest AuditRow
entries are fetched. Keep assertMember and the existing organizationId filter,
but avoid returning all rows and calling toSorted on the full result set.

In `@apps/cloud/lunora/deployments.ts`:
- Around line 114-119: Replace the org-wide scan in the project membership check
with a direct lookup using context.db.get(projectId), then compare the returned
project’s organizationId against arguments_.organizationId as done in
adminTarget. Update the existing validation in deployments.ts to use the fetched
ProjectRow directly and throw the same LunoraError if the project is missing or
belongs to a different org, avoiding the findMany/page iteration entirely.

In `@apps/cloud/src/client/styles.css`:
- Around line 1-13: The :root style block in styles.css needs a blank line
before the color-scheme declaration to satisfy Stylelint. Update the CSS custom
property section so the color-scheme: dark rule is separated from the variable
declarations by an empty line, keeping the existing :root selector and variable
names unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1b2e49d1-12bd-4980-9b2f-f7760c9f76cc

📥 Commits

Reviewing files that changed from the base of the PR and between 3f00d30 and b38103f.

⛔ Files ignored due to path filters (37)
  • CLOUD-PLAN.md is excluded by none and included by none
  • apps/cloud/__tests__/admin-proxy.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/authz.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/cli.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/cron-fanout.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/deploy-client.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/deployments.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/dispatcher-ws.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/dispatcher.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/entitlements.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/github-webhook.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/handler.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/idor.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/invitations.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/keys.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/metering.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/orchestrator.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/plans.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/preview.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/provision.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/queue-fanout.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/router.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/scheduler.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/secret-crypto.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/token-bucket.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/usage.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/lunora/_generated/api.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/crons.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/dataModel.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/drizzle.global.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/drizzle.shard.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/functions.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/openapi.json is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/openapi.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/server.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/shard.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/vectors.ts is excluded by !**/_generated/** and included by apps/**
📒 Files selected for processing (78)
  • apps/cloud/.dev.vars.example
  • apps/cloud/.gitignore
  • apps/cloud/EXTRACT.md
  • apps/cloud/LICENSE.md
  • apps/cloud/README.md
  • apps/cloud/dispatcher.wrangler.jsonc
  • apps/cloud/eslint.config.js
  • apps/cloud/index.html
  • apps/cloud/lunora/.lunora-schema.json
  • apps/cloud/lunora/audit-log.ts
  • apps/cloud/lunora/authz.ts
  • apps/cloud/lunora/billing.ts
  • apps/cloud/lunora/cells.ts
  • apps/cloud/lunora/crons.ts
  • apps/cloud/lunora/deploy-keys.ts
  • apps/cloud/lunora/deployments.ts
  • apps/cloud/lunora/entitlements.ts
  • apps/cloud/lunora/fanout.ts
  • apps/cloud/lunora/invitations.ts
  • apps/cloud/lunora/members.ts
  • apps/cloud/lunora/organizations.ts
  • apps/cloud/lunora/projects.ts
  • apps/cloud/lunora/schema.ts
  • apps/cloud/lunora/secrets.ts
  • apps/cloud/lunora/usage.ts
  • apps/cloud/package.json
  • apps/cloud/project.json
  • apps/cloud/spikes/ws-dispatch/README.md
  • apps/cloud/spikes/ws-dispatch/probe.mjs
  • apps/cloud/spikes/ws-dispatch/tenant-worker.ts
  • apps/cloud/spikes/ws-dispatch/tenant.wrangler.jsonc
  • apps/cloud/src/admin/proxy.ts
  • apps/cloud/src/billing/plans.ts
  • apps/cloud/src/billing/usage.ts
  • apps/cloud/src/cli/commands.ts
  • apps/cloud/src/cli/config.ts
  • apps/cloud/src/cli/file-store.ts
  • apps/cloud/src/client/ActivitySection.tsx
  • apps/cloud/src/client/App.tsx
  • apps/cloud/src/client/AsyncList.tsx
  • apps/cloud/src/client/BillingSection.tsx
  • apps/cloud/src/client/DeployKeysSection.tsx
  • apps/cloud/src/client/DeploymentsSection.tsx
  • apps/cloud/src/client/InvitationsSection.tsx
  • apps/cloud/src/client/Login.tsx
  • apps/cloud/src/client/MembersSection.tsx
  • apps/cloud/src/client/OrganizationDashboard.tsx
  • apps/cloud/src/client/OrganizationList.tsx
  • apps/cloud/src/client/ProjectsSection.tsx
  • apps/cloud/src/client/SecretsSection.tsx
  • apps/cloud/src/client/UsageSection.tsx
  • apps/cloud/src/client/auth-client.ts
  • apps/cloud/src/client/main.tsx
  • apps/cloud/src/client/styles.css
  • apps/cloud/src/client/types.ts
  • apps/cloud/src/cloudflare/api.ts
  • apps/cloud/src/deploy/client.ts
  • apps/cloud/src/deploy/handler.ts
  • apps/cloud/src/deploy/keys.ts
  • apps/cloud/src/deploy/orchestrator.ts
  • apps/cloud/src/deploy/preview.ts
  • apps/cloud/src/deploy/router.ts
  • apps/cloud/src/deploy/scheduler.ts
  • apps/cloud/src/deploy/token-bucket.ts
  • apps/cloud/src/dispatcher/route.ts
  • apps/cloud/src/dispatcher/worker.ts
  • apps/cloud/src/fanout/cron.ts
  • apps/cloud/src/fanout/queue.ts
  • apps/cloud/src/github/webhook.ts
  • apps/cloud/src/mail/notify.ts
  • apps/cloud/src/metering/analytics.ts
  • apps/cloud/src/provision.ts
  • apps/cloud/src/secrets/crypto.ts
  • apps/cloud/src/server.ts
  • apps/cloud/tsconfig.json
  • apps/cloud/vite.config.ts
  • apps/cloud/vitest.config.ts
  • apps/cloud/wrangler.jsonc
✅ Files skipped from review due to trivial changes (6)
  • apps/cloud/.gitignore
  • apps/cloud/project.json
  • apps/cloud/EXTRACT.md
  • apps/cloud/.dev.vars.example
  • apps/cloud/wrangler.jsonc
  • apps/cloud/lunora/.lunora-schema.json
🚧 Files skipped from review as they are similar to previous changes (61)
  • apps/cloud/vite.config.ts
  • apps/cloud/src/client/auth-client.ts
  • apps/cloud/vitest.config.ts
  • apps/cloud/src/client/AsyncList.tsx
  • apps/cloud/src/cli/file-store.ts
  • apps/cloud/src/client/ActivitySection.tsx
  • apps/cloud/lunora/fanout.ts
  • apps/cloud/src/billing/usage.ts
  • apps/cloud/src/client/DeploymentsSection.tsx
  • apps/cloud/src/cli/config.ts
  • apps/cloud/src/client/main.tsx
  • apps/cloud/lunora/crons.ts
  • apps/cloud/index.html
  • apps/cloud/spikes/ws-dispatch/probe.mjs
  • apps/cloud/src/client/UsageSection.tsx
  • apps/cloud/lunora/entitlements.ts
  • apps/cloud/src/client/MembersSection.tsx
  • apps/cloud/package.json
  • apps/cloud/tsconfig.json
  • apps/cloud/src/client/types.ts
  • apps/cloud/spikes/ws-dispatch/tenant.wrangler.jsonc
  • apps/cloud/lunora/schema.ts
  • apps/cloud/src/deploy/preview.ts
  • apps/cloud/dispatcher.wrangler.jsonc
  • apps/cloud/src/client/App.tsx
  • apps/cloud/src/fanout/queue.ts
  • apps/cloud/lunora/cells.ts
  • apps/cloud/lunora/projects.ts
  • apps/cloud/src/dispatcher/worker.ts
  • apps/cloud/src/provision.ts
  • apps/cloud/src/fanout/cron.ts
  • apps/cloud/src/dispatcher/route.ts
  • apps/cloud/src/admin/proxy.ts
  • apps/cloud/src/cli/commands.ts
  • apps/cloud/src/client/Login.tsx
  • apps/cloud/src/mail/notify.ts
  • apps/cloud/src/client/OrganizationList.tsx
  • apps/cloud/src/billing/plans.ts
  • apps/cloud/src/client/DeployKeysSection.tsx
  • apps/cloud/lunora/deploy-keys.ts
  • apps/cloud/src/deploy/orchestrator.ts
  • apps/cloud/lunora/invitations.ts
  • apps/cloud/src/client/InvitationsSection.tsx
  • apps/cloud/lunora/usage.ts
  • apps/cloud/src/deploy/token-bucket.ts
  • apps/cloud/src/client/OrganizationDashboard.tsx
  • apps/cloud/src/secrets/crypto.ts
  • apps/cloud/src/deploy/scheduler.ts
  • apps/cloud/src/client/ProjectsSection.tsx
  • apps/cloud/spikes/ws-dispatch/tenant-worker.ts
  • apps/cloud/lunora/authz.ts
  • apps/cloud/src/deploy/router.ts
  • apps/cloud/src/github/webhook.ts
  • apps/cloud/eslint.config.js
  • apps/cloud/lunora/members.ts
  • apps/cloud/src/cloudflare/api.ts
  • apps/cloud/lunora/secrets.ts
  • apps/cloud/src/server.ts
  • apps/cloud/src/client/SecretsSection.tsx
  • apps/cloud/src/client/BillingSection.tsx
  • apps/cloud/lunora/billing.ts

Comment thread apps/cloud/lunora/organizations.ts Resolved
Comment thread apps/cloud/src/deploy/handler.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ Duplicate comments (1)
apps/cloud/lunora/organizations.ts (1)

23-28: 🔒 Security & Privacy | 🟠 Major

list query still returns all organizations without authorization.

This was previously flagged: the query is public and returns every organization with no membership or admin gate. The code has not changed since the prior review.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/organizations.ts` around lines 23 - 28, Update the public
list query in list to enforce authorization before calling
context.db.organizations.findMany(). Require the established platform-admin or
organization-membership gate appropriate for this surface, and reject
unauthorized callers without returning any organization rows.
🧹 Nitpick comments (3)
apps/cloud/lunora/audit-log.ts (1)

33-39: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Bound and paginate audit-log reads.

This loads the entire organization log and then copies/sorts it in memory on every request. Add server-side newest-first ordering with a cursor and limit; if findMany already applies a bounded page, expose that pagination instead of returning all rows.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/audit-log.ts` around lines 33 - 39, Update the list query
and its auditLog.findMany call to use server-side newest-first ordering, a
cursor, and a bounded page limit. Expose the existing pagination result rather
than casting, copying, and sorting all rows in memory; preserve assertMember
authorization and the AuditRow response contract as appropriate.

Source: Path instructions

apps/cloud/lunora/deployments.ts (2)

147-161: 🧹 Nitpick | 🔵 Trivial

Expired previews are marked destroyed but Cloudflare resources are not torn down.

The comment acknowledges this is pending Alchemy integration, but until the provisioner's destroy is wired, expired preview deployments continue running on Cloudflare and incur costs. Track this as a follow-up task to avoid cost leaks once previews are in production use.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/deployments.ts` around lines 147 - 161, Update
cleanupExpiredPreviews to track the missing Cloudflare teardown as a follow-up
task, and ensure the provisioner’s destroy operation is wired into the
expiration flow before marking preview deployments destroyed so expired
resources do not continue running.

115-118: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Fetch the project by ID instead of loading all org projects.

The current validation fetches every project for the organization and filters in memory with .some(). A db.get(projectId) plus an organizationId equality check is O(1) and avoids loading unrelated projects as the org grows.

As per coding guidelines, review application code for performance considerations. As per path instructions, apps/**/*.ts: Review application code for performance considerations.

♻️ Proposed refactor
-        // Integrity: the project must belong to the same org (no cross-org linkage).
-        const { page } = await context.db.projects.findMany({ where: { organizationId: arguments_.organizationId } });
-
-        if (!(page as unknown as ProjectRow[]).some((project) => project._id === arguments_.projectId)) {
-            throw new LunoraError("NOT_FOUND", "project not found in this organization");
-        }
+        // Integrity: the project must belong to the same org (no cross-org linkage).
+        const project = await context.db.get(arguments_.projectId);
+
+        if (!project || project.organizationId !== arguments_.organizationId) {
+            throw new LunoraError("NOT_FOUND", "project not found in this organization");
+        }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/deployments.ts` around lines 115 - 118, Replace the
organization-wide findMany call and in-memory some check in the project
validation flow with a direct db.get using arguments_.projectId, then verify the
returned project’s organizationId matches arguments_.organizationId. Preserve
the existing NOT_FOUND LunoraError for missing projects or organization
mismatches.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/cloud/lunora/audit-log.ts`:
- Around line 19-30: Restrict the exported record mutation so ordinary members
cannot submit arbitrary audit events. Move the auditLog insert behind trusted
server-side operations or an internal mutation, and update callers to use that
path while preserving member-gated access for readers.

In `@apps/cloud/lunora/deployments.ts`:
- Around line 190-192: Update the authorization branch in updateStatus to use
the same allowed-role list as create when calling assertMember, while preserving
deployKey authorization. Ensure viewers cannot change deployment status unless
the existing create policy explicitly includes them.

In `@apps/cloud/README.md`:
- Line 24: Update the fenced code block in the README to include a language
identifier, using text or another appropriate language after the opening fence
so markdownlint MD040 passes.

---

Duplicate comments:
In `@apps/cloud/lunora/organizations.ts`:
- Around line 23-28: Update the public list query in list to enforce
authorization before calling context.db.organizations.findMany(). Require the
established platform-admin or organization-membership gate appropriate for this
surface, and reject unauthorized callers without returning any organization
rows.

---

Nitpick comments:
In `@apps/cloud/lunora/audit-log.ts`:
- Around line 33-39: Update the list query and its auditLog.findMany call to use
server-side newest-first ordering, a cursor, and a bounded page limit. Expose
the existing pagination result rather than casting, copying, and sorting all
rows in memory; preserve assertMember authorization and the AuditRow response
contract as appropriate.

In `@apps/cloud/lunora/deployments.ts`:
- Around line 147-161: Update cleanupExpiredPreviews to track the missing
Cloudflare teardown as a follow-up task, and ensure the provisioner’s destroy
operation is wired into the expiration flow before marking preview deployments
destroyed so expired resources do not continue running.
- Around line 115-118: Replace the organization-wide findMany call and in-memory
some check in the project validation flow with a direct db.get using
arguments_.projectId, then verify the returned project’s organizationId matches
arguments_.organizationId. Preserve the existing NOT_FOUND LunoraError for
missing projects or organization mismatches.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3338c878-a0bf-44c3-8def-c5d75c13f344

📥 Commits

Reviewing files that changed from the base of the PR and between b38103f and e4dd3c6.

⛔ Files ignored due to path filters (37)
  • CLOUD-PLAN.md is excluded by none and included by none
  • apps/cloud/__tests__/admin-proxy.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/authz.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/cli.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/cron-fanout.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/deploy-client.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/deployments.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/dispatcher-ws.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/dispatcher.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/entitlements.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/github-webhook.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/handler.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/idor.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/invitations.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/keys.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/metering.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/orchestrator.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/plans.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/preview.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/provision.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/queue-fanout.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/router.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/scheduler.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/secret-crypto.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/token-bucket.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/usage.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/lunora/_generated/api.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/crons.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/dataModel.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/drizzle.global.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/drizzle.shard.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/functions.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/openapi.json is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/openapi.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/server.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/shard.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/vectors.ts is excluded by !**/_generated/** and included by apps/**
📒 Files selected for processing (79)
  • apps/cloud/.dev.vars.example
  • apps/cloud/.gitignore
  • apps/cloud/EXTRACT.md
  • apps/cloud/GAPS.md
  • apps/cloud/LICENSE.md
  • apps/cloud/README.md
  • apps/cloud/dispatcher.wrangler.jsonc
  • apps/cloud/eslint.config.js
  • apps/cloud/index.html
  • apps/cloud/lunora/.lunora-schema.json
  • apps/cloud/lunora/audit-log.ts
  • apps/cloud/lunora/authz.ts
  • apps/cloud/lunora/billing.ts
  • apps/cloud/lunora/cells.ts
  • apps/cloud/lunora/crons.ts
  • apps/cloud/lunora/deploy-keys.ts
  • apps/cloud/lunora/deployments.ts
  • apps/cloud/lunora/entitlements.ts
  • apps/cloud/lunora/fanout.ts
  • apps/cloud/lunora/invitations.ts
  • apps/cloud/lunora/members.ts
  • apps/cloud/lunora/organizations.ts
  • apps/cloud/lunora/projects.ts
  • apps/cloud/lunora/schema.ts
  • apps/cloud/lunora/secrets.ts
  • apps/cloud/lunora/usage.ts
  • apps/cloud/package.json
  • apps/cloud/project.json
  • apps/cloud/spikes/ws-dispatch/README.md
  • apps/cloud/spikes/ws-dispatch/probe.mjs
  • apps/cloud/spikes/ws-dispatch/tenant-worker.ts
  • apps/cloud/spikes/ws-dispatch/tenant.wrangler.jsonc
  • apps/cloud/src/admin/proxy.ts
  • apps/cloud/src/billing/plans.ts
  • apps/cloud/src/billing/usage.ts
  • apps/cloud/src/cli/commands.ts
  • apps/cloud/src/cli/config.ts
  • apps/cloud/src/cli/file-store.ts
  • apps/cloud/src/client/ActivitySection.tsx
  • apps/cloud/src/client/App.tsx
  • apps/cloud/src/client/AsyncList.tsx
  • apps/cloud/src/client/BillingSection.tsx
  • apps/cloud/src/client/DeployKeysSection.tsx
  • apps/cloud/src/client/DeploymentsSection.tsx
  • apps/cloud/src/client/InvitationsSection.tsx
  • apps/cloud/src/client/Login.tsx
  • apps/cloud/src/client/MembersSection.tsx
  • apps/cloud/src/client/OrganizationDashboard.tsx
  • apps/cloud/src/client/OrganizationList.tsx
  • apps/cloud/src/client/ProjectsSection.tsx
  • apps/cloud/src/client/SecretsSection.tsx
  • apps/cloud/src/client/UsageSection.tsx
  • apps/cloud/src/client/auth-client.ts
  • apps/cloud/src/client/main.tsx
  • apps/cloud/src/client/styles.css
  • apps/cloud/src/client/types.ts
  • apps/cloud/src/cloudflare/api.ts
  • apps/cloud/src/deploy/client.ts
  • apps/cloud/src/deploy/handler.ts
  • apps/cloud/src/deploy/keys.ts
  • apps/cloud/src/deploy/orchestrator.ts
  • apps/cloud/src/deploy/preview.ts
  • apps/cloud/src/deploy/router.ts
  • apps/cloud/src/deploy/scheduler.ts
  • apps/cloud/src/deploy/token-bucket.ts
  • apps/cloud/src/dispatcher/route.ts
  • apps/cloud/src/dispatcher/worker.ts
  • apps/cloud/src/fanout/cron.ts
  • apps/cloud/src/fanout/queue.ts
  • apps/cloud/src/github/webhook.ts
  • apps/cloud/src/mail/notify.ts
  • apps/cloud/src/metering/analytics.ts
  • apps/cloud/src/provision.ts
  • apps/cloud/src/secrets/crypto.ts
  • apps/cloud/src/server.ts
  • apps/cloud/tsconfig.json
  • apps/cloud/vite.config.ts
  • apps/cloud/vitest.config.ts
  • apps/cloud/wrangler.jsonc
✅ Files skipped from review due to trivial changes (6)
  • apps/cloud/dispatcher.wrangler.jsonc
  • apps/cloud/src/client/ActivitySection.tsx
  • apps/cloud/.gitignore
  • apps/cloud/EXTRACT.md
  • apps/cloud/project.json
  • apps/cloud/.dev.vars.example
🚧 Files skipped from review as they are similar to previous changes (63)
  • apps/cloud/src/client/auth-client.ts
  • apps/cloud/package.json
  • apps/cloud/lunora/crons.ts
  • apps/cloud/vitest.config.ts
  • apps/cloud/src/client/types.ts
  • apps/cloud/spikes/ws-dispatch/tenant.wrangler.jsonc
  • apps/cloud/src/billing/usage.ts
  • apps/cloud/vite.config.ts
  • apps/cloud/src/cli/config.ts
  • apps/cloud/src/client/MembersSection.tsx
  • apps/cloud/src/deploy/orchestrator.ts
  • apps/cloud/src/mail/notify.ts
  • apps/cloud/src/client/App.tsx
  • apps/cloud/tsconfig.json
  • apps/cloud/src/cli/file-store.ts
  • apps/cloud/lunora/entitlements.ts
  • apps/cloud/lunora/fanout.ts
  • apps/cloud/lunora/cells.ts
  • apps/cloud/src/deploy/preview.ts
  • apps/cloud/src/github/webhook.ts
  • apps/cloud/src/client/SecretsSection.tsx
  • apps/cloud/src/client/OrganizationDashboard.tsx
  • apps/cloud/src/deploy/scheduler.ts
  • apps/cloud/index.html
  • apps/cloud/spikes/ws-dispatch/tenant-worker.ts
  • apps/cloud/src/deploy/token-bucket.ts
  • apps/cloud/src/fanout/queue.ts
  • apps/cloud/src/client/DeployKeysSection.tsx
  • apps/cloud/src/client/AsyncList.tsx
  • apps/cloud/src/client/DeploymentsSection.tsx
  • apps/cloud/src/billing/plans.ts
  • apps/cloud/src/client/UsageSection.tsx
  • apps/cloud/lunora/invitations.ts
  • apps/cloud/src/client/InvitationsSection.tsx
  • apps/cloud/src/dispatcher/worker.ts
  • apps/cloud/lunora/secrets.ts
  • apps/cloud/src/client/OrganizationList.tsx
  • apps/cloud/src/deploy/handler.ts
  • apps/cloud/lunora/deploy-keys.ts
  • apps/cloud/src/client/ProjectsSection.tsx
  • apps/cloud/lunora/.lunora-schema.json
  • apps/cloud/lunora/authz.ts
  • apps/cloud/lunora/members.ts
  • apps/cloud/src/dispatcher/route.ts
  • apps/cloud/src/cli/commands.ts
  • apps/cloud/src/client/Login.tsx
  • apps/cloud/src/fanout/cron.ts
  • apps/cloud/spikes/ws-dispatch/probe.mjs
  • apps/cloud/lunora/billing.ts
  • apps/cloud/src/provision.ts
  • apps/cloud/src/deploy/client.ts
  • apps/cloud/src/client/main.tsx
  • apps/cloud/wrangler.jsonc
  • apps/cloud/src/admin/proxy.ts
  • apps/cloud/eslint.config.js
  • apps/cloud/src/client/BillingSection.tsx
  • apps/cloud/lunora/schema.ts
  • apps/cloud/src/cloudflare/api.ts
  • apps/cloud/src/deploy/router.ts
  • apps/cloud/src/secrets/crypto.ts
  • apps/cloud/lunora/usage.ts
  • apps/cloud/src/server.ts
  • apps/cloud/lunora/projects.ts

Comment thread apps/cloud/lunora/audit-log.ts Resolved
Comment thread apps/cloud/lunora/deployments.ts Resolved
Comment thread apps/cloud/README.md Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/cloud/src/deploy/client.ts (1)

94-108: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Guard JSON.parse against malformed NDJSON lines.

An unhandled SyntaxError from JSON.parse on line 101 would propagate as a raw parse error with no context about the offending line. Since this consumes an external stream, partial chunks or non-JSON responses (e.g., an HTML error page) are realistic failure modes.

🛡️ Proposed fix
   const consume = (line: string): void => {
       const trimmed = line.trim();

       if (trimmed === "") {
           return;
       }

-      const event = JSON.parse(trimmed) as DeployEvent;
+      let event: DeployEvent;
+      try {
+          event = JSON.parse(trimmed) as DeployEvent;
+      } catch {
+          throw new Error(`deploy stream: received invalid JSON: ${trimmed.slice(0, 200)}`);
+      }

       onEvent(event);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/deploy/client.ts` around lines 94 - 108, Update the consume
function to catch JSON.parse failures for non-empty stream lines and throw or
report an error that includes clear context and the offending line, while
preserving normal DeployEvent handling for valid JSON.
♻️ Duplicate comments (1)
apps/cloud/lunora/deployments.ts (1)

333-335: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

updateStatus still allows any member role to change deployment status.

assertMember(context, existing.organizationId) is called without allowedRoles, so viewers can update deployment status. A past review flagged this and was marked addressed, but the current code still lacks the roles parameter.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/deployments.ts` around lines 333 - 335, Update the
authorization branch in updateStatus so the assertMember call receives the
allowed deployment-management roles, preventing viewers from changing deployment
status; keep authorizeDeployKey unchanged and reuse the existing role
configuration used by equivalent deployment mutation paths.
🧹 Nitpick comments (2)
apps/cloud/src/deploy/router.ts (1)

531-539: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Add a timeout to the release health check.

The health probe fetch(url, { method: "GET" }) has no AbortSignal/timeout. A freshly-uploaded worker that hangs (or a slow origin) blocks the pointer-swap decision and the streaming deploy response until the platform subrequest limit. Bound it with AbortSignal.timeout(...) and treat a timeout as unhealthy (return false).

♻️ Proposed timeout guard
         const healthCheck = async (url: string): Promise<boolean> => {
             try {
-                const response = await fetch(url, { method: "GET" });
+                const response = await fetch(url, { method: "GET", signal: AbortSignal.timeout(10_000) });

                 return response.status < 500;
             } catch {
                 return false;
             }
         };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/src/deploy/router.ts` around lines 531 - 539, Update the
healthCheck probe to pass an AbortSignal.timeout(...) to fetch, using the
deployment’s established timeout value or a suitable bounded duration. Ensure
timeout and other fetch failures return false, while preserving the existing
response.status < 500 health criterion.

Source: Path instructions

apps/cloud/lunora/usage.ts (1)

154-171: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Push the spend-cap filter into the query. This cron still scans every historical platformUsage row and filters old periods/kinds in memory. Applying the periodStart/kind predicate in findMany would keep the mutation bounded as the table grows.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/cloud/lunora/usage.ts` around lines 154 - 171, Update enforceSpendCaps
to pass a database filter to platformUsage.findMany that restricts rows to the
current period starting at periodStart and kinds "requests" or "cpuMs". Remove
the equivalent in-memory periodStart/kind filtering from the loop while
preserving aggregation in byOrg.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/cloud/lunora/deployments.ts`:
- Around line 219-222: Update rollback to fetch the target deployment before
authorization, then pass its projectId to authorizeDeployKey alongside
organizationId and deployKey. Preserve the existing member authorization path
and ensure the deployment is validated before allowing the rollback.

In `@apps/cloud/lunora/domains.ts`:
- Around line 118-121: Update routeForHostname to trim the hostname before
lowercasing it in the domains.findMany lookup, matching the normalization used
by add and preserving the existing query behavior.

In `@apps/cloud/src/dispatcher/worker.ts`:
- Around line 81-83: Validate the tenant-supplied custom.redirectTo and
custom.redirectStatusCode before calling Response.redirect in the custom
redirect branch, and handle invalid values without allowing an exception to
escape before the existing try block. Preserve valid redirects and the current
default status code behavior, while routing malformed control-plane data through
the worker’s established safe error/fallback path.

---

Outside diff comments:
In `@apps/cloud/src/deploy/client.ts`:
- Around line 94-108: Update the consume function to catch JSON.parse failures
for non-empty stream lines and throw or report an error that includes clear
context and the offending line, while preserving normal DeployEvent handling for
valid JSON.

---

Duplicate comments:
In `@apps/cloud/lunora/deployments.ts`:
- Around line 333-335: Update the authorization branch in updateStatus so the
assertMember call receives the allowed deployment-management roles, preventing
viewers from changing deployment status; keep authorizeDeployKey unchanged and
reuse the existing role configuration used by equivalent deployment mutation
paths.

---

Nitpick comments:
In `@apps/cloud/lunora/usage.ts`:
- Around line 154-171: Update enforceSpendCaps to pass a database filter to
platformUsage.findMany that restricts rows to the current period starting at
periodStart and kinds "requests" or "cpuMs". Remove the equivalent in-memory
periodStart/kind filtering from the loop while preserving aggregation in byOrg.

In `@apps/cloud/src/deploy/router.ts`:
- Around line 531-539: Update the healthCheck probe to pass an
AbortSignal.timeout(...) to fetch, using the deployment’s established timeout
value or a suitable bounded duration. Ensure timeout and other fetch failures
return false, while preserving the existing response.status < 500 health
criterion.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 20344d13-1f0a-461c-9b7e-1f8423f10bd1

📥 Commits

Reviewing files that changed from the base of the PR and between e4dd3c6 and d119eb2.

⛔ Files ignored due to path filters (13)
  • apps/cloud/__tests__/domains.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/handler.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/release.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/__tests__/spend.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by apps/**
  • apps/cloud/lunora/_generated/api.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/crons.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/dataModel.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/drizzle.global.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/functions.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/openapi.json is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/openapi.ts is excluded by !**/_generated/** and included by apps/**
  • apps/cloud/lunora/_generated/shard.ts is excluded by !**/_generated/** and included by apps/**
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml and included by none
📒 Files selected for processing (14)
  • apps/cloud/lunora/crons.ts
  • apps/cloud/lunora/deployments.ts
  • apps/cloud/lunora/domains.ts
  • apps/cloud/lunora/schema.ts
  • apps/cloud/lunora/usage.ts
  • apps/cloud/src/billing/spend.ts
  • apps/cloud/src/cli/commands.ts
  • apps/cloud/src/deploy/client.ts
  • apps/cloud/src/deploy/handler.ts
  • apps/cloud/src/deploy/orchestrator.ts
  • apps/cloud/src/deploy/router.ts
  • apps/cloud/src/dispatcher/route.ts
  • apps/cloud/src/dispatcher/worker.ts
  • apps/cloud/src/domains/verify.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/cloud/lunora/schema.ts

Comment thread apps/cloud/lunora/deployments.ts Resolved
Comment thread apps/cloud/lunora/domains.ts Resolved
Comment thread apps/cloud/src/dispatcher/worker.ts Resolved
@prisis

prisis commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

Note

🤖 Claude Opus 5.5 responding on behalf of prisis

On the new findings in the latest Qodo summary (none has an inline thread):

  • Queued tenant messages can be lost: fixed in 2be631a. When no live release owns a queue, the batch is now retried after 300 s instead of acked. "No owner" can't be told apart from a short gap during a deploy or fleet registration. A gap clears within a few redeliveries, and a truly ownerless message runs out the queue's max_retries and lands in its dead-letter queue. Acking after a count of our own would still throw it away.
  • Teardown can delete a live legacy tenant: fixed in 22ce955. aliasInUse and listPending's live-alias set now name a row by row.alias ?? row.scriptName, the rule the rest of teardown uses. A live deployment from before aliases existed therefore still keeps its alias in use.
  • Ejected apps lose log redaction: fixed in 78fe98b. The Alchemy emitter now writes the Worker's observability prop: enabled, headSamplingRate, logs and traces. Alchemy's Worker metadata has no field for redact_query_string or issues, so those go on the eject's unsupported list. lunora cloud eject warns about them and the ejected README lists them, instead of dropping them silently.
  • Busy organizations lose metric history: fixed in dacd850. metrics.series puts the time range in the query (at: { gte, lte }, served by by_org_at) and drains the range's pages with collectAll. The old limit: 5000 read only ever returned one 1,000-row page.
  • Standard trace errors miss the archive: fixed in 640a1ac. /v1/traces now archives the error events it ingested as well as the spans, as the native telemetry route does.
  • Removed members get a setup server error: fixed in 7c56991. isOwnerOrAdmin treats members.list's FORBIDDEN as "not an owner or admin", so a member removed mid-setup gets the flow's 403. Any other error is still thrown.
  • Paused apps with a custom queue handler keep processing messages: fixed in 3ec903b. A paused deployment now hands the pause to queueHandler only when WorkerOptions.queueHandlerHolds is true, which codegen sets for its handler. Otherwise the handler is not called, and every message is answered as a retry delayed by PAUSED_QUEUE_RETRY_SECONDS, as before. A hand-written handler that holds the batch itself sets the flag.

Each fix has a test that fails without it. On 75dd4ea these pass:

  • test:affected;
  • the workerd suites (runtime, do, shard-engine, d1, auth, cloud, sql-store, queue);
  • api:check, strict cloud codegen and the generated-files check;
  • oxlint, and deploy:check for staging and production.

prisis and others added 10 commits November 18, 2026 09:05
metrics.series is a live query that re-runs on every ingest, yet it drained up
to 100 D1 pages of raw points each run and folded a cut-short read as exact.

It now reads at most 10 pages (10k points) newest-first. When that budget runs
out the answer is flagged truncated, the bucket the cut landed in is dropped so
every bucket shown stays an exact average, and the Metrics tab shows a
"partial data" notice. Store groupBy groups by stored columns only and no
rollup table exists, so bucketing in the database is not available.

collectAll's second parameter is now an options object ({ maxPages,
onTruncated }); the one positional onTruncated caller (alerts) is updated.

BREAKING: metrics.series returns { series, truncated } instead of the bare
series array.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
archiveEvents sent decoded TelemetryEvents to the shared Pipeline/R2 archive
with no organizationId or recordType, so a tenant's archived events could not
be scoped, read back or deleted. Both /v1/traces and the native /v1/telemetry
route were affected.

archiveEvents now takes the organizationId and writes each event through
eventArchiveRecord, tagged recordType "event" (mirroring spanArchiveRecord).
The span readers already filter recordType = 'span', so they skip these rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
emitObservability read an omitted top-level `enabled` as false, so ejecting
`observability: {}`, a sampling-only block, or `logs.enabled: true` alone
deployed the Alchemy worker with observability off. Wrangler and
resolveObservabilitySampling treat a present block without the switch as on,
so the emitter now defaults it to DEFAULT_OBSERVABILITY.enabled; an explicit
`enabled: false` still disables it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A retried deploy of a deployment id the box already runs wrote into that release's directory,
deleting it first. A failed file write then left nothing for the rollback to restore. Lay the
release out in a `<id>.staging` sibling and replace the directory only once every file is written;
a failed write removes the staging copy and leaves the existing release untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
withdrawDesiredRelease cleared a box's intent whenever its release id matched, so a halted
rollout withdrew a rollback an operator had started onto the same release since. The withdraw
port now takes the run's upgrade job and clears only an intent with the same release id and
allowDowngrade, the same predicate the desires port already used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
createDeployment checked dropped Durable Object and Workflow classes only against the alias's
reached releases. A release that uploaded its script and then failed before verifying is not
among them, so the next release could stop binding its classes without allowDeleteClasses and
delete their data on a target that drops unbound classes. The guard now also counts the
alias's workerClasses and every pending converge's classes, the record kept for this.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BoxSessionDO.apply awaited recordHello's D1 read without asking whether its socket was still
the box's session. A reconnect that authenticated meanwhile recorded its own hello, and the
older handler then overwrote its versions, resources, fleets and last-seen time. recordHello
now takes a currency check asked after its read, and the handler stops before pushing routes,
config or an upgrade once a newer session has replaced its socket.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
replayDesiredRelease sent the upgrade a reconnecting box missed from a row read before its
release lookup. A revoke that landed in D1 meanwhile, before its close reached the session,
still got the box an upgrade job. The row is read again right before sending, and the job is
skipped when revokedAt is set, the intent changed, or the socket is no longer the session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
POST /v1/eject read the whole tenant export with Response.text() and embedded it in a JSON
body, so a tenant whose export outgrew Worker memory could not eject. The route now passes
the export through as the application/x-ndjson body and names the deployment in
x-lunora-project-slug, x-lunora-script-name and x-lunora-url headers.

lunora cloud eject reads that stream, writes export.ndjson first through a .partial file
renamed into place, and checks the export's end marker as it streams: once the 200 is sent a
failed export can only cut the body short, and a cut body leaves no file behind.

BREAKING CHANGE: /v1/eject answers an NDJSON stream with identity headers, not a JSON object
with a snapshot field. The CLI and the control plane must be upgraded together.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@prisis

prisis commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

Note

🤖 Claude Opus 5.5 responding on behalf of prisis

On the new findings in the latest two Qodo summaries (none has an inline thread):

  • Busy orgs' metric charts silently lose older points and Metric dashboards repeatedly scan raw data: fixed in b7dd36b. metrics.series now reads at most 10 pages (about 10,000 points), newest first. When it runs out it returns { series, truncated: true } and drops the oldest bucket, which it reached only partly, so every charted bucket is an exact average. The dashboard shows a "Partial data" notice. The store's groupBy only groups by stored columns and there is no metrics rollup, so this bounded read is the honest option short of building one.
  • OTLP error events are archived with no tenant attached: fixed in 2c23e8b. archiveEvents(events, organizationId) maps each event to { ...event, organizationId, recordType: "event" }, mirroring spanArchiveRecord. The native /v1/telemetry route had the same gap and is fixed too. The archive readers filter recordType = 'span', so they are unaffected.
  • Ejected apps lose request logs: fixed in 499f41d. An omitted top-level observability.enabled now resolves through the resolver's DEFAULT_OBSERVABILITY.enabled (on), not false. {}, a sampling-only block, and logs.enabled: true without a switch all eject as enabled.
  • Large tenants cannot eject data: fixed in 42d9de5. /v1/eject streams the tenant export through as application/x-ndjson and carries the deployment identity in headers. It no longer reads the export into one JSON body. The CLI streams it to a .partial file, checks the export's end marker, and renames the file only on success.
  • Reconnecting boxes retain stale state: fixed in df740e4. recordHello takes a current() check asked after its read. The authenticate path also stops before pushing routes, config or an upgrade once its socket has been replaced.
  • Revoked boxes can receive upgrade jobs: fixed in 0d9c69e. replayDesiredRelease re-reads the box row just before sending. It skips the job if the box is revoked, if the desired release or allowDowngrade changed, or if the socket is no longer ready.
  • A halted rollout cancels a newer rollback: fixed in d009555. withdrawDesiredRelease withdraws only when the release id and allowDowngrade both match the run's own job.
  • A later deploy can silently delete Durable Object data: fixed in 1c09ce1. The class guard now also counts the alias's converge record: workerClasses plus every pending entry, which worker-classes.ts keeps (stamped endedAt) when a failed release may already have uploaded. A release that uploaded and then failed before verifying therefore still protects its classes.
  • A failed retry removes rollback files: fixed in f7cc18a. A release is written into <id>.staging and swapped into place only after every file has been written. A failed write removes the staging directory and leaves the running release's files, which rollback needs, untouched.

Each fix has a test that fails without it. On a116c36 these pass:

  • test:affected;
  • the workerd suites (runtime, do, shard-engine, d1, auth, cloud, sql-store, queue);
  • api:check, strict cloud codegen and the generated-files check;
  • oxlint, hostd cargo test (with and without test-fakes), and deploy:check for staging and production.

@qodo-code-review

Copy link
Copy Markdown

ⓘ Qodo did not review this PR because this workspace reached its daily trial limit of 100 reviews. Reviews start again at 00:00 UTC. Choose a plan to continue now.

prisis and others added 4 commits November 18, 2026 09:39
The cloudflare-workers target only answers on its account's workers.dev subdomain and attaches
no Custom Domain, yet domains.add and the verify route accepted a hostname there, so a domain
could verify that never reached the Worker. Both now refuse a project whose target lists the
customDomains limitation, quoting that limitation's reason; verify covers a domain added before
the project moved to such a target.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
worker-secrets.sh left out every empty source, so a GitHub Environment missing AUTH_SECRET still
deployed a control plane that fails every request. A pair prefixed with `!` is now required: an
empty source fails the script, naming each missing secret, before any file is written. The
deploy marks AUTH_SECRET, SECRET_ENCRYPTION_KEY and LUNORA_ADMIN_TOKEN on the control plane and
CONTROL_PLANE_TOKEN on the dispatcher, which refuses all traffic without it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
forwardTailBatches ignored the /v1/logs/tail response, so a refused flush and a 200 with failed
batches both lost lines silently. A network error, 429 or 5xx (the route stored nothing) is now
retried once; a flush still refused, or batches counted as failed, are written to the tail
worker's own logs. It still never rejects, so tenants are not back-pressured, and a partly
stored flush is not resent, which would duplicate the lines it stored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SessionHandle::send fell back to removing the outbox's oldest frame once it held 2,000 frames
with no progress line among them, which could be a job result the control plane waits on, or
a report. Job submissions are unbounded, so completions outpacing the send budget reached it.

A full outbox now sheds the oldest progress line, drops an incoming progress line when there is
none, refuses an incoming report (send returns false, so ReportQueue::drain keeps it queued for
a later drain), and always takes a result, over the cap if need be.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@prisis

prisis commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

Note

🤖 Claude Opus 5.5 responding on behalf of prisis

On the new findings in the latest Qodo summary (none has an inline thread):

  • Custom domains verify but do not serve apps: fixed in 1893a6e. The customer-owned Cloudflare target already lists customDomains as a limitation ("not wired yet"), and the API wrapper has no Workers Custom Domains or routes call to attach one. So rather than verify a domain that never routes, domains.add, and verifyTarget for a domain added before its project moved, now refuse with that limitation's reason through assertTargetServesDomains. Attaching the domain on that target is still to be built.

  • Missing secrets break deployed cells: fixed in c0a87e9. A worker-secrets.sh pair prefixed with ! is required. An empty source then fails the step, names the missing secret and writes no file. deploy-cloud.yml marks the four the cells cannot start without as required:

    • AUTH_SECRET;
    • SECRET_ENCRYPTION_KEY;
    • LUNORA_ADMIN_TOKEN;
    • the dispatcher's CONTROL_PLANE_TOKEN.

    The tail and lineage secrets stay optional, since both degrade by design.

  • Failed tail ingestion silently loses logs: fixed in 02139b7. A tail flush is retried once on a network error, 429 or 5xx. In those cases the route stored nothing, so a retry cannot duplicate lines. A flush that still fails, or a 200 with a nonzero failed count, is logged to the tail worker's own logs. It does not throw: a tail invocation cannot be replayed, and the route does not say which batches failed, so a resend after a partial 200 would duplicate the lines it kept.

  • Backlogged boxes lose results and reports: fixed in 1a90ede. A full outbox makes room by dropping the oldest progress line. With no progress line left, an incoming progress line is dropped and an incoming report is refused, and ReportQueue::drain keeps a refused report queued. A job result is always accepted, over the cap if need be, so none is ever removed.

Each fix has a test that fails without it. On 1a90ede these pass:

  • test:affected;
  • the workerd suites (runtime, do, shard-engine, d1, auth, cloud, sql-store, queue);
  • api:check, strict cloud codegen and the generated-files check;
  • oxlint, hostd cargo test, and deploy:check for staging and production.

prisis and others added 5 commits November 18, 2026 10:11
A deploy key's kind ceiling was checked, but the caller's script name was not: a
preview key could send kind "preview" with the project's production alias and
converge the production Worker in place, with no production rollback target.

deployments.create now refuses a dev or preview release whose alias is the
project's reserved or active production alias, or one a standing production
release runs on. It covers the deploy endpoint and the git release path alike.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A preview build is recorded for every project connected to the repository whose
organization claimed the installation, but a closed pull request retired the
branch preview of only the first project resolveProject returned. The others
kept serving until their TTL.

closePreview now takes the repository and installation and retires the branch's
previews across the same candidate set builds.recordPush uses (installedProjects,
extracted from it). A closed event now carries its installation id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
recordResumedOnto marked the target release live, then patched the project's
active-deployment pointer, and skipped both once the target was live. Each
write commits alone, so a failed pointer patch left the halt retryable but
every retry skipped the patch, and the project kept pointing at the old release.

The pointer write now runs outside that guard and repairs a production pointer
on this alias that does not name the target.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
write_release_directory deleted a retried deployment's directory before renaming the staged
replacement into place, so a failed rename left the running release's files nowhere. Rename
the old directory aside to `<id>.previous` first, rename it back if the staged one cannot
take its place, and drop it only once the swap succeeded. A `.previous` left by a crash
between the renames, with no `<id>` beside it, is restored before the next swap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@prisis

prisis commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

Note

🤖 Claude Opus 5.5 responding on behalf of prisis

On the new findings in the latest Qodo summary (none has an inline thread):

  • Preview-only deploy keys can replace production code: fixed in 1e88359. deployments.create now refuses a dev or preview release with FORBIDDEN when its alias is the project's reserved production alias, its active alias, or one a production release still runs on. Putting the check in the mutation covers both the deploy endpoint and git releases. A preview key can still deploy a preview, but only onto its own alias, never the production Worker.
  • Closed pull requests leave previews running: fixed in 9959f9a. The candidate filter builds.recordPush uses for preview builds is now a shared helper, installedProjects. closePreview takes the closed event's installationId and retires the branch's previews in every project connected to the repository whose organization claimed that installation. The single project resolveProject returns is no longer the limit.
  • A failed resume leaves the live pointer stale: fixed in 6e4fc1d. The project-pointer write now sits outside the "target not yet live" guard. A production resume moves the pointer when it changed the live release, and also when the pointer is on this alias but names another release. A retry after a failed pointer write therefore repairs it, and a pointer on a different alias is never taken.
  • A failed retry erases a running release: fixed in 54ffa01. The swap now renames the running release aside to <id>.previous, then renames the staged release into place. If that rename fails, it renames .previous back. .previous is deleted only after a successful swap, and one left behind by a crash is restored before the next write.

Each fix has a test that fails without it. This push also merges the latest alpha, with the lockfile regenerated. On a3f3fed these pass:

  • test:affected;
  • the workerd suites (runtime, do, shard-engine, d1, auth, cloud, sql-store, queue);
  • api:check, strict cloud codegen and the generated-files check;
  • oxlint, lint:package-json, hostd cargo test, and deploy:check for staging and production.

prisis and others added 5 commits November 18, 2026 10:55
verifyBoxRequest accepted a timestamp up to the window's edge but recorded
its nonce as expiring at timestamp + window, judged on the session object's
own clock. A request signed right at the edge got a claim that was already
over, so a captured copy sent while the Worker's check still passed was
accepted again. The nonce now expires a full window after that, so the
timestamp check closes first whatever either clock reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
downloadTarball read the whole response with arrayBuffer() and checked its
size afterwards. A tarball served without content-length was buffered in
full before the 256 MiB limit applied, so an oversized archive could exhaust
the isolate. It now reads through readCappedBytes, which stops and cancels
the stream as soon as the running total passes the limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
forwardWithEgress checked a request's URL against the allowed origins but
passed the tenant's cf options to every hop, resolveOverride included, so an
allowlisted URL could be sent to another hostname. Under an enforcing policy
that one option is now removed before the first hop and every redirect; the
cache and image options stay. Without a policy there is no allowlist to step
around, so the tenant's cf is sent as it was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
reapStale marked a running backup or restore failed once its row was 30
minutes old, and assertIdle stopped counting it at the same age, whether or
not the request was still writing to the tenant. A large restore could
therefore lose its lock and let another operation start on the same project
while it was still committing.

Each running operation now heartbeats: every tenant call and every chunk of
a tenant response reports progress, and at most every five minutes that
writes heartbeatAt on its row (through the new internal heartbeat mutation
from the router, or directly from the sweep). A row is in flight while it
was created or heard from within the stale window; reapStale, activeOperation
and assertIdle all read that one rule, and assertIdle no longer filters
running rows by creation time in its query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@prisis

prisis commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

Note

🤖 Claude Opus 5.5 responding on behalf of prisis

On the new findings in the latest Qodo summary (none has an inline thread):

  • Tenant fetches can bypass egress rules: fixed in 888466f. Under an enforcing policy, outboundCf strips cf.resolveOverride on every hop: the first request, each redirect, and the path where the tenant handles redirects itself. It is the only Cloudflare fetch option that changes where a request goes, so the cache and image options the tenant set are kept. Without a policy there is no allowlist to bypass, so the tenant's cf is sent unchanged. Workerd tests cover both redirect paths.
  • Large source downloads can exhaust the Worker: fixed in 7fc1fbd. downloadTarball reads through the shared streaming reader, which cancels the body as soon as it passes 256 MiB, declared length or not.
  • Long restores can overlap on tenant data: fixed in eb76599. Running backups and restores now write heartbeatAt at most every five minutes, driven by each tenant call and each chunk of a tenant response. One rule, isInFlight, treats a running row as alive while it is within 30 minutes of its creation or its last heartbeat. reapStale, assertIdle and activeOperation all use that rule, so a long restore is no longer reaped and overlapped while it still streams.
  • Signed box requests can be replayed at the window edge: fixed in 7e3d586. The nonce now expires at timestamp + 2 × TIMESTAMP_WINDOW_MS. The timestamp check therefore always closes before the nonce record does, whatever the session object's clock reads. A request signed exactly at the edge is accepted once and refused on replay.

Each fix has a test that fails without it. This push also merges the latest alpha. On bdf98b5 these pass:

  • test:affected;
  • the workerd suites (runtime, do, shard-engine, d1, auth, cloud, sql-store, queue);
  • api:check, strict cloud codegen and the generated-files check;
  • oxlint, lint:package-json, and deploy:check for staging and production.

This branch had an error being deployed

1 failed deployment
benchmarks — bdf98b58 Deployed Nov 18, 2026 by prisis via Benchmarks #8027
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants