Repository navigation
Conversation
✅ Deploy Preview for lunorash ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughThis PR introduces the ChangesLunora Cloud platform
Runtime WfP forwarding
Estimated code review effort: 5 (Critical) | ~120 minutes Suggested labels: Possibly related PRs
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
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
Pre-merge checks |
|
|
Thank you for following the naming conventions! 🙏 |
|
React Doctor found no new issues. 🎉 Reviewed by React Doctor for commit |
Merging this PR will regress 1 benchmark
|
| 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)
Footnotes
-
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. ↩
There was a problem hiding this comment.
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 winMixed default and named exports in the same file.
WsRoomis 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.adminTokenis 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.tsalready implements AES-256-GCM encryption for thesecretstable; reusing that same encrypt/decrypt path foradminTokenbefore 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 winGenerated schema is missing the
planfield onorganizations.
schema.tsdefinesorganizationswithcellId,createdAt,name,plan,slug(schema.ts lines 51-57), but this generated JSON'sorganizationstable only listscellId,createdAt,name,slug—planis absent. If this JSON drives the actual D1 migration/column set, inserts that supplyplan(asschema.tsrequires 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 afterplanwas added to the table definition.Regenerate
.lunora-schema.jsonfrom the currentschema.tsbefore 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 winPrevent 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 whenarguments_.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 winDo not let arbitrary members forge audit records.
Any member, including viewers, can write free-form
actionandtargetvalues 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 winValidate metering quantity, period, and deployment ownership.
A valid deploy key can submit negative
quantityvalues or attach usage to an uncheckeddeploymentId. That can undercount billing/quotas or create cross-org usage rows. Reject non-finite/negative quantities, constrainperiodStart, and verify anydeploymentIdbelongs toorganizationId.🤖 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 liftAvoid 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 winDo not let public org creation self-assign plan or cell.
Any signed-in user can create an org with
plan: "enterprise"and an arbitrarycellId, 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 winRestrict cell inventory and registration to platform operators.
listexposes every Cloudflare account/dispatch namespace without auth, andregisterlets 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 winGate 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 winPrevent admins from granting owner privileges.
Line 33 allows both owners and admins to call
add, while Line 31 acceptsrole: "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 winProtect 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 winValidate project ownership before issuing scoped deploy keys.
projectIdis stored without checking that it belongs toorganizationId. 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 winMake invitation role optional or update the HTTP caller.
The downstream invite route calls
api.invitations.invitewith onlyorganizationId, but this mutation requiresrole, 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 liftEncrypt
adminTokenbefore 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 inapps/cloud/src/secrets/crypto.ts. Encrypt on write and decrypt only inadminTargetto 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 winReject non-HTTPS deployment URLs at the mutation boundary
deployment.urlis persisted and rendered directly as<a href={deployment.url}>; React 19 still allowsjavascript:hrefs, so a malicious deploy key or org member could store a link that executes script when clicked in the studio. Restrict this field tohttps://(or otherwise parse and allow only safe schemes) inupdateStatus.🤖 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 winMake
byGithubRepointernal. It’s only used from the GitHub webhook router, but exporting it as a public query lets any caller resolveorganizationId/projectIdfrom a guessedowner/namerepo string. If this really needs to stay public, add an explicit rationale comment likeplanForScript; otherwise switch it tointernalQuery.🤖 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 winValidate
priceIdagainst known plan price ids before checkout.
priceIdis taken verbatim from client input and passed straight tocontext.payments.createCheckout. If it doesn't match anypriceIdsentry inLUNORA_CLOUD_PLANS.plans(typo, stale id, wrong environment), the org gets billed butresolveEntitlementsfilters 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 winRevoke has no error handling or feedback.
revokeKey.mutate(...)is fired withvoidand 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 liftMake tenant resource provisioning idempotent before enabling retries.
Every deploy creates D1/R2 resources from
scriptNamebefore script upload. That contradicts thedeploycontract (“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 winGuard progress callback failures so deployments still reach a terminal outcome.
If
onProgressfails duringprovisioning,runDeploymentrejects before the provisioner runs and never emits/returnsfailed. If it fails while reportingfailed, 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 winTreat
deployKeyas a sensitive persistence contract.
deployKeyis 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. RequireConfigStoreimplementations 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 winFail closed on incomplete deploy streams.
If the connection ends before a terminal
{ done: true }event, this returnsstatus: "unknown"instead of failing the deploy command. Also flush theTextDecoderbefore 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 winDo not let the request body escalate the deploy-key environment.
body.kindoverridestarget.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 winEncode dynamic Cloudflare path segments.
namespaceandscriptNameare 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 winSeparate mail-delivery failures from invite authorization failures.
If
sendInvitationEmailfails afterinvitations.invitecreates the token, the route returns403 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 winDo not silently omit tenant secrets during deploys.
When
SECRET_ENCRYPTION_KEYis missing,resolveSecretsreturns{}. 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 winReject non-hex master keys before importing AES keys.
Number.parseIntreturnsNaNfor invalid hex pairs, and assigning that intoUint8Arraycoerces to0. A malformedSECRET_ENCRYPTION_KEYcan 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 winMake preview script names collision-resistant.
slugifyis 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 winFail 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 winValidate admin paths before forwarding with the bearer token.
request.pathis 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 winValidate usage values before ingesting billing records.
kindis only typed at compile time, andquantityaccepts 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 winPersisted config (including
deployKey) is written with default file permissions.
writeFiledoesn't set a restrictivemode, so the file lands with the process's default permissions (commonly world/group-readable). SinceCliConfigpersists a secretdeployKey, 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 liftCron/queue fan-out bypasses per-plan runtime limits.
dispatcher/worker.tsapplieslimitsForPlan(route.plan)when dispatching regular HTTP traffic (env.DISPATCHER.get(route.scriptName, undefined, { limits })), but hereEnv.DISPATCHERis typed without alimits/options parameter, anddispatchCronTick/dispatchQueueBatchcalldispatcher.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 liftAuth initialization race:
authis visible before migration completes, and failures leave it poisoned.
authis assigned at Line 410 synchronously, thenensureMigrated(...)is awaited at Line 411. Any concurrent request that lands in that window seesauthtruthy, skips re-initialization, and proceeds straight toworker.fetch(which callsauth.api.getSession) against a schema that may not have finished migrating yet. Further, ifensureMigratedthrows,authstays 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.
ee7fe7f to
b38103f
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
apps/cloud/lunora/deployments.ts (1)
114-119: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winFetch the project directly instead of scanning all org projects.
Loading every project in the org to check membership of one
projectIdis O(n) and unnecessary —context.db.get(projectId)plus an org-match comparison (the same pattern used inadminTargetabove) 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 winUnbounded audit-log read.
listloads 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 alimit/cursor param (or afindManyorder-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 valueStylelint: missing blank line before
color-schemedeclaration.🎨 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
⛔ Files ignored due to path filters (37)
CLOUD-PLAN.mdis excluded by none and included by noneapps/cloud/__tests__/admin-proxy.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/authz.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/cli.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/cron-fanout.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/deploy-client.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/deployments.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/dispatcher-ws.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/dispatcher.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/entitlements.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/github-webhook.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/handler.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/idor.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/invitations.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/keys.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/metering.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/orchestrator.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/plans.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/preview.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/provision.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/queue-fanout.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/router.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/scheduler.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/secret-crypto.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/token-bucket.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/usage.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/lunora/_generated/api.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/crons.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/dataModel.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/drizzle.global.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/drizzle.shard.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/functions.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/openapi.jsonis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/openapi.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/server.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/shard.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/vectors.tsis excluded by!**/_generated/**and included byapps/**
📒 Files selected for processing (78)
apps/cloud/.dev.vars.exampleapps/cloud/.gitignoreapps/cloud/EXTRACT.mdapps/cloud/LICENSE.mdapps/cloud/README.mdapps/cloud/dispatcher.wrangler.jsoncapps/cloud/eslint.config.jsapps/cloud/index.htmlapps/cloud/lunora/.lunora-schema.jsonapps/cloud/lunora/audit-log.tsapps/cloud/lunora/authz.tsapps/cloud/lunora/billing.tsapps/cloud/lunora/cells.tsapps/cloud/lunora/crons.tsapps/cloud/lunora/deploy-keys.tsapps/cloud/lunora/deployments.tsapps/cloud/lunora/entitlements.tsapps/cloud/lunora/fanout.tsapps/cloud/lunora/invitations.tsapps/cloud/lunora/members.tsapps/cloud/lunora/organizations.tsapps/cloud/lunora/projects.tsapps/cloud/lunora/schema.tsapps/cloud/lunora/secrets.tsapps/cloud/lunora/usage.tsapps/cloud/package.jsonapps/cloud/project.jsonapps/cloud/spikes/ws-dispatch/README.mdapps/cloud/spikes/ws-dispatch/probe.mjsapps/cloud/spikes/ws-dispatch/tenant-worker.tsapps/cloud/spikes/ws-dispatch/tenant.wrangler.jsoncapps/cloud/src/admin/proxy.tsapps/cloud/src/billing/plans.tsapps/cloud/src/billing/usage.tsapps/cloud/src/cli/commands.tsapps/cloud/src/cli/config.tsapps/cloud/src/cli/file-store.tsapps/cloud/src/client/ActivitySection.tsxapps/cloud/src/client/App.tsxapps/cloud/src/client/AsyncList.tsxapps/cloud/src/client/BillingSection.tsxapps/cloud/src/client/DeployKeysSection.tsxapps/cloud/src/client/DeploymentsSection.tsxapps/cloud/src/client/InvitationsSection.tsxapps/cloud/src/client/Login.tsxapps/cloud/src/client/MembersSection.tsxapps/cloud/src/client/OrganizationDashboard.tsxapps/cloud/src/client/OrganizationList.tsxapps/cloud/src/client/ProjectsSection.tsxapps/cloud/src/client/SecretsSection.tsxapps/cloud/src/client/UsageSection.tsxapps/cloud/src/client/auth-client.tsapps/cloud/src/client/main.tsxapps/cloud/src/client/styles.cssapps/cloud/src/client/types.tsapps/cloud/src/cloudflare/api.tsapps/cloud/src/deploy/client.tsapps/cloud/src/deploy/handler.tsapps/cloud/src/deploy/keys.tsapps/cloud/src/deploy/orchestrator.tsapps/cloud/src/deploy/preview.tsapps/cloud/src/deploy/router.tsapps/cloud/src/deploy/scheduler.tsapps/cloud/src/deploy/token-bucket.tsapps/cloud/src/dispatcher/route.tsapps/cloud/src/dispatcher/worker.tsapps/cloud/src/fanout/cron.tsapps/cloud/src/fanout/queue.tsapps/cloud/src/github/webhook.tsapps/cloud/src/mail/notify.tsapps/cloud/src/metering/analytics.tsapps/cloud/src/provision.tsapps/cloud/src/secrets/crypto.tsapps/cloud/src/server.tsapps/cloud/tsconfig.jsonapps/cloud/vite.config.tsapps/cloud/vitest.config.tsapps/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
3e57b0d to
e4dd3c6
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
apps/cloud/lunora/organizations.ts (1)
23-28: 🔒 Security & Privacy | 🟠 Major
listquery 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 winBound 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
findManyalready 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 | 🔵 TrivialExpired previews are marked destroyed but Cloudflare resources are not torn down.
The comment acknowledges this is pending Alchemy integration, but until the provisioner's
destroyis 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 winFetch 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(). Adb.get(projectId)plus anorganizationIdequality 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
⛔ Files ignored due to path filters (37)
CLOUD-PLAN.mdis excluded by none and included by noneapps/cloud/__tests__/admin-proxy.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/authz.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/cli.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/cron-fanout.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/deploy-client.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/deployments.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/dispatcher-ws.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/dispatcher.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/entitlements.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/github-webhook.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/handler.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/idor.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/invitations.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/keys.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/metering.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/orchestrator.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/plans.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/preview.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/provision.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/queue-fanout.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/router.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/scheduler.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/secret-crypto.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/token-bucket.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/usage.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/lunora/_generated/api.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/crons.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/dataModel.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/drizzle.global.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/drizzle.shard.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/functions.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/openapi.jsonis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/openapi.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/server.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/shard.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/vectors.tsis excluded by!**/_generated/**and included byapps/**
📒 Files selected for processing (79)
apps/cloud/.dev.vars.exampleapps/cloud/.gitignoreapps/cloud/EXTRACT.mdapps/cloud/GAPS.mdapps/cloud/LICENSE.mdapps/cloud/README.mdapps/cloud/dispatcher.wrangler.jsoncapps/cloud/eslint.config.jsapps/cloud/index.htmlapps/cloud/lunora/.lunora-schema.jsonapps/cloud/lunora/audit-log.tsapps/cloud/lunora/authz.tsapps/cloud/lunora/billing.tsapps/cloud/lunora/cells.tsapps/cloud/lunora/crons.tsapps/cloud/lunora/deploy-keys.tsapps/cloud/lunora/deployments.tsapps/cloud/lunora/entitlements.tsapps/cloud/lunora/fanout.tsapps/cloud/lunora/invitations.tsapps/cloud/lunora/members.tsapps/cloud/lunora/organizations.tsapps/cloud/lunora/projects.tsapps/cloud/lunora/schema.tsapps/cloud/lunora/secrets.tsapps/cloud/lunora/usage.tsapps/cloud/package.jsonapps/cloud/project.jsonapps/cloud/spikes/ws-dispatch/README.mdapps/cloud/spikes/ws-dispatch/probe.mjsapps/cloud/spikes/ws-dispatch/tenant-worker.tsapps/cloud/spikes/ws-dispatch/tenant.wrangler.jsoncapps/cloud/src/admin/proxy.tsapps/cloud/src/billing/plans.tsapps/cloud/src/billing/usage.tsapps/cloud/src/cli/commands.tsapps/cloud/src/cli/config.tsapps/cloud/src/cli/file-store.tsapps/cloud/src/client/ActivitySection.tsxapps/cloud/src/client/App.tsxapps/cloud/src/client/AsyncList.tsxapps/cloud/src/client/BillingSection.tsxapps/cloud/src/client/DeployKeysSection.tsxapps/cloud/src/client/DeploymentsSection.tsxapps/cloud/src/client/InvitationsSection.tsxapps/cloud/src/client/Login.tsxapps/cloud/src/client/MembersSection.tsxapps/cloud/src/client/OrganizationDashboard.tsxapps/cloud/src/client/OrganizationList.tsxapps/cloud/src/client/ProjectsSection.tsxapps/cloud/src/client/SecretsSection.tsxapps/cloud/src/client/UsageSection.tsxapps/cloud/src/client/auth-client.tsapps/cloud/src/client/main.tsxapps/cloud/src/client/styles.cssapps/cloud/src/client/types.tsapps/cloud/src/cloudflare/api.tsapps/cloud/src/deploy/client.tsapps/cloud/src/deploy/handler.tsapps/cloud/src/deploy/keys.tsapps/cloud/src/deploy/orchestrator.tsapps/cloud/src/deploy/preview.tsapps/cloud/src/deploy/router.tsapps/cloud/src/deploy/scheduler.tsapps/cloud/src/deploy/token-bucket.tsapps/cloud/src/dispatcher/route.tsapps/cloud/src/dispatcher/worker.tsapps/cloud/src/fanout/cron.tsapps/cloud/src/fanout/queue.tsapps/cloud/src/github/webhook.tsapps/cloud/src/mail/notify.tsapps/cloud/src/metering/analytics.tsapps/cloud/src/provision.tsapps/cloud/src/secrets/crypto.tsapps/cloud/src/server.tsapps/cloud/tsconfig.jsonapps/cloud/vite.config.tsapps/cloud/vitest.config.tsapps/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
There was a problem hiding this comment.
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 winGuard
JSON.parseagainst malformed NDJSON lines.An unhandled
SyntaxErrorfromJSON.parseon 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
updateStatusstill allows any member role to change deployment status.
assertMember(context, existing.organizationId)is called withoutallowedRoles, 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 winAdd a timeout to the release health check.
The health probe
fetch(url, { method: "GET" })has noAbortSignal/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 withAbortSignal.timeout(...)and treat a timeout as unhealthy (returnfalse).♻️ 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 winPush the spend-cap filter into the query. This cron still scans every historical
platformUsagerow and filters old periods/kinds in memory. Applying theperiodStart/kindpredicate infindManywould 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
⛔ Files ignored due to path filters (13)
apps/cloud/__tests__/domains.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/handler.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/release.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/__tests__/spend.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included byapps/**apps/cloud/lunora/_generated/api.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/crons.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/dataModel.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/drizzle.global.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/functions.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/openapi.jsonis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/openapi.tsis excluded by!**/_generated/**and included byapps/**apps/cloud/lunora/_generated/shard.tsis excluded by!**/_generated/**and included byapps/**pnpm-lock.yamlis excluded by!**/pnpm-lock.yamland included by none
📒 Files selected for processing (14)
apps/cloud/lunora/crons.tsapps/cloud/lunora/deployments.tsapps/cloud/lunora/domains.tsapps/cloud/lunora/schema.tsapps/cloud/lunora/usage.tsapps/cloud/src/billing/spend.tsapps/cloud/src/cli/commands.tsapps/cloud/src/deploy/client.tsapps/cloud/src/deploy/handler.tsapps/cloud/src/deploy/orchestrator.tsapps/cloud/src/deploy/router.tsapps/cloud/src/dispatcher/route.tsapps/cloud/src/dispatcher/worker.tsapps/cloud/src/domains/verify.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/cloud/lunora/schema.ts
|
Note 🤖 Claude Opus 5.5 responding on behalf of prisis On the new findings in the latest Qodo summary (none has an inline thread):
Each fix has a test that fails without it. On 75dd4ea these pass:
|
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>
|
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):
Each fix has a test that fails without it. On a116c36 these pass:
|
|
ⓘ 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. |
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>
|
Note 🤖 Claude Opus 5.5 responding on behalf of prisis On the new findings in the latest Qodo summary (none has an inline thread):
Each fix has a test that fails without it. On 1a90ede these pass:
|
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>
|
Note 🤖 Claude Opus 5.5 responding on behalf of prisis On the new findings in the latest Qodo summary (none has an inline thread):
Each fix has a test that fails without it. This push also merges the latest
|
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>
|
Note 🤖 Claude Opus 5.5 responding on behalf of prisis On the new findings in the latest Qodo summary (none has an inline thread):
Each fix has a test that fails without it. This push also merges the latest
|
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 (seeapps/cloud/EXTRACT.md), plus the GitHub pipeline that deploys it.The control plane
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.src/deploy/):POST /v1/deploystreaming NDJSON, per-cell token-bucket + scheduler over the Alchemy 2 provision box (see below), preview deployments from GitHub webhooks, stored releases with rollback.src/dispatcher/): hostname → tenant script resolution with per-plan runtime limits and per-request usage emission.@lunora/payment, Analytics Engine metering via@lunora/bindings/analytics.@lunora/auth/ better-auth: mail-backed verification/reset, optional OAuth, 2FA/passkeys, rate limiting.POST /_lunora/scheduledandPOST /_lunora/queueadded to@lunora/runtime'screateWorker(scheduledTick/queueHandlerseams).src/client/), WS-through-dispatch spike (spikes/ws-dispatch/), and the gap register (apps/cloud/GAPS.md) that tracks what is still infrastructure-blocked.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.stagingand aproductionenvironment. 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, orworkflow_dispatchto either. It fires onpackages/**/shared/**as well asapps/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.cloud-v<run>and cuts a GitHub Release back to the previous cloud tag. That namespace sits outside the@lunora/<pkg>@<version>shapesemantic-releaseowns —apps/cloudis 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-pluginemits its own deploy config atdist/server/wrangler.jsonwith theenvkey flattened away, and picks the environment fromCLOUDFLARE_ENVat build time. Passing--envto the wrangler call instead looks right and silently deploys the wrong cell's bindings.lunora deploycannot publish this app: itsmainis a hand-written entry Vite builds, so deploying the source config would bundlesrc/server.tsraw and ship a control plane with no studio. Its gates run aslunora verifybefore the build, and its health probe as--health-urlafter (opt-in via aCLOUD_HEALTH_URLenvironment 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.
src/provision-contract.ts).lunora cloud deploysends@lunora/config'sbuildBindingManifestoutput (the same document aslunora 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.containers/provision/): a trusted container runningalchemy@2.0.0-beta.79(witheffectpinned to4.0.0-rc.117, since rc.118 breaks it;@hono/node-server,hono,lodashandvalibotoverridden past their advisories — the box lockfile audits clean), state inCloudflare.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.{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.Releases and data
alias-vN), and a Durable Object namespace belongs to its script — so every deploy started tenants on an emptyShardDO. 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.LUNORA_DISPATCH_NAMESPACE). Deploying tolunora-${kind}put previews where no dispatcher routes and staging's tenants outsidelunora-staging.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.CLI
lunora cloud deployderives 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 asassets.lunora cloud ejectwrites a cleaned copy of the app's realwrangler.jsoncand an Alchemy 2 program, instead of a hard-coded template.@lunora/config'swranglerToAlchemynow 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):wrangler d1 create/r2 bucket create/queues create/pipelines create, then paste the ids over the<replace-with-…>placeholders.deploy:checklists exactly which are outstanding. New buckets:lunora-cloud-releasesand the tenant-backups bucket (-stagingvariants on staging).cloud-stagingandcloud-productionGitHub Environments withCLOUDFLARE_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.alchemy provider cloudflare bootstraponce 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.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.exampledocuments each, and the symptom of leaving the optional ones unset.wrangler deploybuilds both container images (build box, provision box) with the deploy host's Docker, so it needs a daemon withbuildx.Rebase
Rebased onto
alphaagain, which had moved 2443 commits ahead, then mergedalphaonce more for #912. Adapting to it:usePreloadedQuerynow returnsT | undefined(fix(react): type a preloaded value as possibly undefined #861); the studio sections guard it.lunora cloudgained one.@cloudflare/vite-plugin1.54 treatsaias never-local, sopnpm devopened a remote session and failed without credentials; remote bindings are now on only with aCLOUDFLARE_API_TOKEN._generated/regenerated against alpha's codegen.Registration is invite-only
apps/cloudnow installsinviteOnly()(@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, orAuthAdmin.createUser.Installing the plugin is what lights the operator path up end to end, because everything downstream is already wired here: it declares the
signUpInvitationtable (soensureMigratedprovisions it),createAuthAdmingrowscreate/list/revokeSignUpInvitation,@lunora/runtimeexposes those as admin routes, and@lunora/studiorenders its sign-up-invitations panel offcapabilities.inviteOnly. The vendored sign-up form now reads?invite=off the URL and submits it asinviteToken.Two deliberate calls:
lunora/invitations.tsinvites 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.allowFirstUseronly in dev, wherescripts/seed.tssigns 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:
/_lunora/scheduledand/_lunora/queueare 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. Addedpackages/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/QueueForwardResultwere not exported by name. They appeared in the API snapshot only becauseWorkerOptions.queueHandlerdrags them into the emitted.d.ts— an app typing its ownqueueHandler(which is exactly whatapps/clouddoes) could not import them. Now exported from@lunora/runtimeandlunorash.scheduledTick/queueHandleroptions (packages/runtime/docs), per-query D1 cost accounting andd1QueryTag's cardinality rule (packages/d1/docs),LUNORA_AI_GATEWAY_TAGSand the per-call/per-deploy tag split (packages/ai/docs), and deploy attribution viaversion_metadata(concepts/observability).Intlconstructions in the studio'sformat.ts/plan-catalog.ts, each rebuilding locale data per table row. Hoisted to module scope;regionNames()stays lazily memoised becauseIntl.DisplayNamescan throw and a module-level throw would take down the chunk.Checked and deliberately not changed:
PlatformCapabilitiesneeds no new key (the fan-out endpoints are how a WfP host emulates the existingcronTriggers/queuesratings, not a new feature), andapps/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.tsxonly-export-components(×2) —countryFlag/countryNameand theirIntl.DisplayNameshelper moved tosrc/client/format.ts; the file now exports only components and their prop types.js-hoist-intl— already fixed;Intl.DisplayNamesis built once behind a lazily-memoisedregionNames()(lazy, not module-scope, so a runtime without the region table degrades one column instead of taking down the chunk).__proto__— computed key, security intent unchanged.TimeRangeProvider.tsxreact-compiler-no-manual-memoization(×2) — not applied, with the reason now a comment in the file. React Compiler is not enabled forapps/cloud(it is forapps/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 markerspnpm run lint:types,lint:eslint,lint:prettier,lint:package-json,lint:generatedpnpm run api:check— 56 snapshots (config.api.mdupdated for the Alchemy 2WranglerConfigShape)pnpm run test— 69 projects;pnpm run test:workerdapps/webnpm auditon the provision-box lockfile — 0 vulnerabilities (dependency review flagged@hono/node-server@1.19.9)alchemy@2.0.0-beta.79/effect@4.0.0-rc.117typespnpm run e2e:cloud— needs Dockerbuildxto build the container images at dev start (not available where this was run)deploy-cloud.ymlrun — need the credentials and provisioned resources aboveChecklist
apps/cloud/README.md,GAPS.md,MULTIPLATFORM.md,docs/RESTORE.md, containers' READMEs, CLI + cloud docs pages)packages/configandpackages/clichanged for eject / manifest / Alchemy 2; no new package underpackages/*wranglerToAlchemy's output changes (breaking, pre-release)Environment
Worker secrets and variables the control plane reads. Values are never committed.
GITHUB_APP_ID,GITHUB_APP_PRIVATE_KEYGITHUB_WEBHOOK_SECRETGITHUB_APP_SLUG/v1/github/install)GITHUB_SETUP_STATE_SECRETopenssl rand -hex 32)GITHUB_CLIENT_ID,GITHUB_CLIENT_SECRETSECRET_ENCRYPTION_KEYLUNORA_ORIGIN_URLAUTH_URLwrangler.jsonc)GitHub App settings, one-time: set the Setup URL to
https://<control-plane>/v1/github/setupwith "Redirect on update" off, and the App's login callback to the control plane's auth route.🤖 Generated with Claude Code