@lunora/advisor 1.0.0-alpha.7 → 1.0.0-alpha.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +60 -5
  3. package/dist/index.d.mts +4005 -966
  4. package/dist/index.d.ts +4005 -966
  5. package/dist/index.mjs +1 -79
  6. package/dist/packem_shared/MAP_VERSION-DxkFCiLX.mjs +1 -0
  7. package/dist/packem_shared/actionFetchSsrf-BbWxy1Yf.mjs +1 -0
  8. package/dist/packem_shared/actionWithoutErrorHandling-rhzjCEqm.mjs +1 -0
  9. package/dist/packem_shared/adminRouteWithoutGuard-BbscPp1m.mjs +1 -0
  10. package/dist/packem_shared/aiRawRunEscapeHatch-DfhjYm43.mjs +1 -0
  11. package/dist/packem_shared/aiRunWithoutLogging-B0K93Pga.mjs +1 -0
  12. package/dist/packem_shared/aiToolSideEffectPromptInjection-DnWQOoKi.mjs +1 -0
  13. package/dist/packem_shared/aiUnboundedGenerationPublic-iu7crnSa.mjs +1 -0
  14. package/dist/packem_shared/allowUnauthenticatedShardAccessEnabled-D4aMNBb0.mjs +1 -0
  15. package/dist/packem_shared/argument-derived-sink-BpO3NPPM.mjs +1 -0
  16. package/dist/packem_shared/authApiCallWithoutHeaders-BHkik-EF.mjs +1 -0
  17. package/dist/packem_shared/authCsrfCheckDisabled-De9ammtV.mjs +1 -0
  18. package/dist/packem_shared/authEmailVerificationDisabled-BFKdJcx4.mjs +1 -0
  19. package/dist/packem_shared/authScimWithoutTransactions-DCtLXzks.mjs +1 -0
  20. package/dist/packem_shared/authSecureCookiesDisabled-B4WIzvMm.mjs +1 -0
  21. package/dist/packem_shared/authSessionFreshageZero-Bpcaf_Pe.mjs +1 -0
  22. package/dist/packem_shared/authTrustedOriginsWildcard-DjU9NXEm.mjs +1 -0
  23. package/dist/packem_shared/browserAllowPrivateTargets-Dxyeh6lg.mjs +1 -0
  24. package/dist/packem_shared/browserUserUrlWithoutAllowlist-BHBS6b0N.mjs +1 -0
  25. package/dist/packem_shared/circularFk-ZNjkhLaE.mjs +1 -0
  26. package/dist/packem_shared/classifySensitivity-B1kkm44P.mjs +1 -0
  27. package/dist/packem_shared/compareToBaseline-BwXFusQG.mjs +1 -0
  28. package/dist/packem_shared/constraintValidator-N339mfyx.mjs +1 -0
  29. package/dist/packem_shared/containerInstanceKeyFromUserInput-C8S4T3ty.mjs +1 -0
  30. package/dist/packem_shared/containerOversizedInstance-B9wW_sU5.mjs +1 -0
  31. package/dist/packem_shared/containerPublicInternet-g0TRsayn.mjs +1 -0
  32. package/dist/packem_shared/containerRuntimeEgressRelaxation-BQ2ZD1aV.mjs +1 -0
  33. package/dist/packem_shared/containerStartEnableInternetOverride-B62WUura.mjs +1 -0
  34. package/dist/packem_shared/dedupeCacheKeys-7JgxaQWV.mjs +1 -0
  35. package/dist/packem_shared/duplicateIndex-DFT7qLQD.mjs +1 -0
  36. package/dist/packem_shared/emptyIndex-Bp-Y81D0.mjs +1 -0
  37. package/dist/packem_shared/errorRateOutlier-CgK42sq0.mjs +1 -0
  38. package/dist/packem_shared/errorWithoutCatalog-0PbxiZL4.mjs +1 -0
  39. package/dist/packem_shared/exportSinkMisconfigured-DvpAaa6j.mjs +1 -0
  40. package/dist/packem_shared/externalSourceIncrementalNoDeletePath-DnoL64YY.mjs +1 -0
  41. package/dist/packem_shared/externalSourceOnGlobal-IYnALPlO.mjs +1 -0
  42. package/dist/packem_shared/externalSourceUnscoped-DqBp5jYr.mjs +1 -0
  43. package/dist/packem_shared/filterOnPrimaryKey-Db947tQY.mjs +1 -0
  44. package/dist/packem_shared/filterWithoutIndex-pIpqk-O8.mjs +1 -0
  45. package/dist/packem_shared/finding-BAVgqnCF.mjs +1 -0
  46. package/dist/packem_shared/fk-index-Bmk19RvQ.mjs +1 -0
  47. package/dist/packem_shared/flagGatesSecurityWithUnsafeDefault-DPGFEHTt.mjs +1 -0
  48. package/dist/packem_shared/fromServerSchema-9aaK1J7g.mjs +1 -0
  49. package/dist/packem_shared/geoIndexFieldNotGeopoint-DAGLZtaH.mjs +1 -0
  50. package/dist/packem_shared/geoIndexUnused-B5Oww9o2.mjs +1 -0
  51. package/dist/packem_shared/gradeFromScore-DW82YDVY.mjs +1 -0
  52. package/dist/packem_shared/hardcodedSecret-yu14ITlW.mjs +1 -0
  53. package/dist/packem_shared/helpers-DwlvEUCh.mjs +1 -0
  54. package/dist/packem_shared/hotShard-io-eF2Sx.mjs +1 -0
  55. package/dist/packem_shared/httpActionMissingAuthGuard-BZDdeW_D.mjs +1 -0
  56. package/dist/packem_shared/httpActionResponseHeaderInjection-D063rB7U.mjs +1 -0
  57. package/dist/packem_shared/hyperdriveOutsideAction-B8ffQwgl.mjs +1 -0
  58. package/dist/packem_shared/identityUndeclaredClaimTrusted-BYRYGQ74.mjs +1 -0
  59. package/dist/packem_shared/imagesUrlSourceFromUserInput-Cy5pc_dA.mjs +1 -0
  60. package/dist/packem_shared/indexReferencesUnknownField-BPJjE0zg.mjs +1 -0
  61. package/dist/packem_shared/indexUtilization-QfbIH_w4.mjs +1 -0
  62. package/dist/packem_shared/insertManyUnsafeUserData-xLYAkcKj.mjs +1 -0
  63. package/dist/packem_shared/kvUnscopedUserKeyIdor-B4lGxRxh.mjs +1 -0
  64. package/dist/packem_shared/mailInboundDispatchWithoutVerify-BivYJ5F9.mjs +1 -0
  65. package/dist/packem_shared/mailRecipientFromRequestInput-BR_oSh65.mjs +1 -0
  66. package/dist/packem_shared/maskUncoveredPiiColumn-DqPfZM2O.mjs +1 -0
  67. package/dist/packem_shared/maskWeakHashStrategyOnPii-DcEwc4Sz.mjs +1 -0
  68. package/dist/packem_shared/maskedRelationLeakViaWith-CxYk0MDW.mjs +1 -0
  69. package/dist/packem_shared/mutatorFullRowReplace-CEgecSGm.mjs +1 -0
  70. package/dist/packem_shared/nondeterministicQueryMutation-BZV_biUV.mjs +1 -0
  71. package/dist/packem_shared/normalizeIdUsedAsAuthorization-FjISSXJm.mjs +1 -0
  72. package/dist/packem_shared/notifyMissingPushConfig-C_GbVw3S.mjs +1 -0
  73. package/dist/packem_shared/notifySendOutsideAction-B9DcirhJ.mjs +1 -0
  74. package/dist/packem_shared/outputProjectionMissingOnPublicRead-9Pm9766s.mjs +1 -0
  75. package/dist/packem_shared/ownerFieldFromArgsNotAuth-D4K-_0aD.mjs +1 -0
  76. package/dist/packem_shared/paymentCreateWithoutAuthorize-CurtqN8K.mjs +1 -0
  77. package/dist/packem_shared/paymentWebhookWideTolerance-I7ingfR8.mjs +1 -0
  78. package/dist/packem_shared/plaintextSecretInWranglerVariables-CmbygN6_.mjs +1 -0
  79. package/dist/packem_shared/policyReferencesUnknownTable-D3WelAQa.mjs +1 -0
  80. package/dist/packem_shared/privilegedDispatchUnvalidatedPayload-74GuGye1.mjs +1 -0
  81. package/dist/packem_shared/privilegedFanoutFromPublicProcedure-sMsZN4uP.mjs +1 -0
  82. package/dist/packem_shared/procedure-protections-DRQotu9I.mjs +1 -0
  83. package/dist/packem_shared/procedureWithoutStructuredEvent-l40nx9tX.mjs +1 -0
  84. package/dist/packem_shared/publicArgumentUsesAny-BzdcoJ9C.mjs +1 -0
  85. package/dist/packem_shared/publicMutationWithoutRatelimit-CozomYXw.mjs +1 -0
  86. package/dist/packem_shared/publicTableRlsOptoutConfusion-CaWtPGAn.mjs +1 -0
  87. package/dist/packem_shared/queueWithoutDlq-BLY3iy9Q.mjs +1 -0
  88. package/dist/packem_shared/r2sqlOutsideAction-DCMAsAeM.mjs +1 -0
  89. package/dist/packem_shared/ratelimitDefaultMemoryStore-mOdI3Jmb.mjs +1 -0
  90. package/dist/packem_shared/ratelimitKeySpoofableOrGlobal-DaGId_Fh.mjs +1 -0
  91. package/dist/packem_shared/ratelimitMiddlewareFailOpen-CTWVosEc.mjs +1 -0
  92. package/dist/packem_shared/relationReferencesUnknownField-clqyB69Y.mjs +1 -0
  93. package/dist/packem_shared/relationReferencesUnknownTable-EOtKyaHx.mjs +1 -0
  94. package/dist/packem_shared/rlsUncoveredTable-DYHgnoos.mjs +1 -0
  95. package/dist/packem_shared/shapeTargetsGlobalTable-SAlq2N-T.mjs +1 -0
  96. package/dist/packem_shared/shapeUnknownTable-DhvsbEtT.mjs +1 -0
  97. package/dist/packem_shared/signupMutationWithoutDisposableGating-Tgv9SbsY.mjs +1 -0
  98. package/dist/packem_shared/softDeleteIncludeDeletedFromArgs-DgxpQHRA.mjs +1 -0
  99. package/dist/packem_shared/sqlInjectionRisk-D2NaT-5c.mjs +1 -0
  100. package/dist/packem_shared/storageGenerateUploadUrlNoContentTypePin-C9cjl6Jh.mjs +1 -0
  101. package/dist/packem_shared/storageKeyFromUserArgs-CI-6kyte.mjs +1 -0
  102. package/dist/packem_shared/storagePresignedUrlForPrivateContent-j7VhwIdu.mjs +1 -0
  103. package/dist/packem_shared/storageUploadWithoutContentTypeAllowlist-oxKLecuf.mjs +1 -0
  104. package/dist/packem_shared/storageUploadWithoutMaxSize-DUDxPutk.mjs +1 -0
  105. package/dist/packem_shared/tableWithoutInsert-BV7qsPKx.mjs +1 -0
  106. package/dist/packem_shared/ttlFieldNotTimestamp-BFiRkSZD.mjs +1 -0
  107. package/dist/packem_shared/unboundedStringArgument-DN8w1bg-.mjs +1 -0
  108. package/dist/packem_shared/unindexedForeignKey-DK4eWXkb.mjs +1 -0
  109. package/dist/packem_shared/unindexedRelationTarget-B5fFq1E8.mjs +1 -0
  110. package/dist/packem_shared/unrestrictedWhereBranch-YKiydie4.mjs +1 -0
  111. package/dist/packem_shared/userCreatingMutationWithoutCaptcha-DIeHIeTU.mjs +1 -0
  112. package/dist/packem_shared/vectorsNamespaceFromUserInput-Cyq5B2kF.mjs +1 -0
  113. package/dist/packem_shared/workflowDuplicateStepName-cXF6Rpvg.mjs +1 -0
  114. package/dist/packem_shared/workflowUnknownTarget-BzKlYSCg.mjs +1 -0
  115. package/dist/packem_shared/workflowUnused-D9fC9E9b.mjs +1 -0
  116. package/package.json +3 -2
  117. package/dist/packem_shared/AE_METRIC_EVENTS-DexctYv6.mjs +0 -85
  118. package/dist/packem_shared/adminRouteWithoutGuard-UUGBkAjU.mjs +0 -33
  119. package/dist/packem_shared/authApiCallWithoutHeaders-BeJhCZaf.mjs +0 -38
  120. package/dist/packem_shared/circularFk-B2freHrP.mjs +0 -84
  121. package/dist/packem_shared/constraintValidator-Dr9Py3FD.mjs +0 -186
  122. package/dist/packem_shared/containerOversizedInstance-5U1VKPRM.mjs +0 -36
  123. package/dist/packem_shared/containerPublicInternet-CuNerJE5.mjs +0 -30
  124. package/dist/packem_shared/duplicateIndex-BOublMSt.mjs +0 -57
  125. package/dist/packem_shared/emptyIndex-BX8EuEY7.mjs +0 -32
  126. package/dist/packem_shared/filterWithoutIndex-BYVeJaSs.mjs +0 -31
  127. package/dist/packem_shared/finding-Dm_zvzS1.mjs +0 -16
  128. package/dist/packem_shared/fk-index-IUK1ukgs.mjs +0 -7
  129. package/dist/packem_shared/fromServerSchema-DinF1nph.mjs +0 -50
  130. package/dist/packem_shared/hardcodedSecret-W2pz1UZB.mjs +0 -35
  131. package/dist/packem_shared/helpers-DNCkMWZQ.mjs +0 -4
  132. package/dist/packem_shared/hotShard-Ir5D0B6J.mjs +0 -48
  133. package/dist/packem_shared/hyperdriveOutsideAction-BgZqX7Xg.mjs +0 -30
  134. package/dist/packem_shared/indexReferencesUnknownField-DH0_dbUY.mjs +0 -36
  135. package/dist/packem_shared/indexUtilization-B5DMQ3bI.mjs +0 -45
  136. package/dist/packem_shared/maskUncoveredPiiColumn-DjGIPG6M.mjs +0 -61
  137. package/dist/packem_shared/nondeterministicQueryMutation-GXES1fLp.mjs +0 -35
  138. package/dist/packem_shared/policyReferencesUnknownTable-DtaIEovd.mjs +0 -38
  139. package/dist/packem_shared/publicArgumentUsesAny-C71b2NCf.mjs +0 -32
  140. package/dist/packem_shared/publicMutationWithoutRatelimit-xBpJ6GWK.mjs +0 -36
  141. package/dist/packem_shared/r2sqlOutsideAction-CtqxvMuV.mjs +0 -30
  142. package/dist/packem_shared/relationReferencesUnknownField-YznyXt_7.mjs +0 -54
  143. package/dist/packem_shared/relationReferencesUnknownTable-DrorpKYe.mjs +0 -33
  144. package/dist/packem_shared/rlsUncoveredTable-CxEfZ5eZ.mjs +0 -56
  145. package/dist/packem_shared/sqlInjectionRisk-zwytYGLt.mjs +0 -26
  146. package/dist/packem_shared/tableWithoutInsert-CbbaYIP4.mjs +0 -34
  147. package/dist/packem_shared/unboundedStringArgument-DThg2-wt.mjs +0 -32
  148. package/dist/packem_shared/unindexedForeignKey-BgJbKyqK.mjs +0 -45
  149. package/dist/packem_shared/unindexedRelationTarget-D6eyj6Xx.mjs +0 -53
  150. package/dist/packem_shared/userCreatingMutationWithoutCaptcha-CH31YsUZ.mjs +0 -42
  151. package/dist/packem_shared/workflowUnknownTarget-Cdd7WhKQ.mjs +0 -34
  152. package/dist/packem_shared/workflowUnused-D0jHxdz9.mjs +0 -38
@@ -0,0 +1 @@
1
+ import{i as n}from"./finding-BAVgqnCF.mjs";const i=3600,r={categories:["SECURITY"],description:"A payment webhook adapter configured with an implausibly wide `webhookToleranceSeconds` (over an hour). The timestamp tolerance is the webhook replay window; widening it far past the 300s default keeps captured signed events replayable long after capture, defeating the replay check.",facing:"EXTERNAL",level:"WARN",name:"payment_webhook_wide_tolerance",remediation:"Keep `webhookToleranceSeconds` at or near the 300s default — just enough for clock skew. If a wide window was set to work around retries or backfills, handle those with idempotency on the event id instead, not by loosening the replay-window guard.",run:o=>{if(o.paymentWebhooks===void 0)return[];const t=e=>e.toleranceSeconds!==void 0&&e.toleranceSeconds>=i;return o.paymentWebhooks.filter(e=>t(e)).map(e=>{const a=`\`${e.exportName}\` (${e.file}:${e.line.toString()})`;return n(r,{cacheKey:`payment_webhook_wide_tolerance:${e.file}:${e.line.toString()}`,detail:`\`${e.callee}\` in ${a} sets \`webhookToleranceSeconds\` to ${(e.toleranceSeconds??0).toString()}s (default 300s). That replay window keeps captured signed events valid long after capture.`,metadata:{callee:e.callee,exportName:e.exportName,file:e.file,line:e.line,toleranceSeconds:e.toleranceSeconds}})})},source:"static",title:"Payment webhook replay-tolerance window is implausibly wide"};export{r as default};
@@ -0,0 +1 @@
1
+ import{dedupeCacheKeys as r}from"./dedupeCacheKeys-7JgxaQWV.mjs";import{i as a}from"./finding-BAVgqnCF.mjs";const i={categories:["SECURITY"],description:"A plaintext secret is committed to `wrangler.jsonc`'s `vars` block. `vars` are cleartext — baked into the deployed Worker and checked into source control — so the secret leaks via the repo and the bundle, and rotating it needs a config edit plus a redeploy.",facing:"INTERNAL",level:"ERROR",name:"plaintext_secret_in_wrangler_vars",remediation:"Move the value out of `vars`: bind it through a Secrets Store (`ctx.secrets.get(<NAME>)`) or set it with `wrangler secret put <NAME>` and read it from `env.<NAME>`. Delete the `vars` entry and rotate the exposed value — assume it is already compromised. Public/publishable keys (name them `*_PUBLIC` / `*_PUBLISHABLE`) are exempt.",run:t=>t.wranglerVariables===void 0?[]:r(t.wranglerVariables.map(e=>a(i,{cacheKey:`plaintext_secret_in_wrangler_vars:${e.file}:${e.key}`,detail:`The \`vars\` entry \`${e.key}\` in ${e.file} holds a plaintext ${e.kind.replaceAll("_"," ")} (${e.preview}). \`vars\` ship in cleartext to the deployed Worker and are committed to source control — move it to a Secrets Store binding or \`wrangler secret put\` and rotate the exposed value.`,metadata:{file:e.file,key:e.key,kind:e.kind,preview:e.preview}}))),source:"static",title:"Plaintext secret in wrangler vars"};export{i as default};
@@ -0,0 +1 @@
1
+ import{i as s}from"./finding-BAVgqnCF.mjs";const i={categories:["SECURITY"],description:"An RLS policy is bound to a `table` name that does not exist in the schema. The `rls()` middleware never matches it, so the table the policy was meant to protect is left ungated — reads return unrestricted rows and writes are allowed.",facing:"EXTERNAL",level:"WARN",name:"policy_references_unknown_table",remediation:"Fix the policy's `table` to a real table name (check for a typo or a table that was renamed/removed). If the table is gone, delete the dead policy.",run:a=>{if(a.rlsProcedures===void 0)return[];const n=new Set(a.schema.tables.map(t=>t.name)),o=new Set,r=[];for(const t of a.rlsProcedures)for(const e of t.rlsTables)e===""||n.has(e)||o.has(e)||(o.add(e),r.push(s(i,{cacheKey:`policy_references_unknown_table:${e}`,detail:`An RLS policy in \`${t.exportName}\` (${t.file}) is bound to table \`${e}\`, which is not declared in the schema. The policy never matches, so \`${e}\` — if it exists under another name — is left ungated.`,metadata:{exportName:t.exportName,file:t.file,table:e}})));return r},source:"static",title:"RLS policy bound to an unknown table"};export{i as default};
@@ -0,0 +1 @@
1
+ import{i as n}from"./finding-BAVgqnCF.mjs";const o={categories:["SECURITY"],description:"A `defineQueue`/`defineWorkflow` handler forwards its untrusted payload (queue body / workflow params) straight into a `ctx.run` dispatch whose target is RLS-gated. The handler runs under the system identity with RLS disabled, so the target's row policy — the only thing guarding it — is bypassed, letting a caller act as any user / write across tenants.",facing:"EXTERNAL",level:"ERROR",name:"privileged_dispatch_unvalidated_payload",remediation:"Don't forward an unchecked queue body / workflow param into an RLS-gated function. Re-derive the ownership/identity keys from server-trusted state (or an argument you validate against it) before dispatching, or route the work through a function that re-checks the caller's identity rather than relying on the row policy the privileged handler skips.",run:r=>{if(r.privilegedDispatches===void 0)return[];const i=r.rlsProcedures??[],s=(e,a)=>i.some(t=>t.usesRls&&t.file===e&&t.exportName===a);return r.privilegedDispatches.filter(e=>s(e.targetFile,e.targetExport)).map(e=>{const a=e.dispatchKind==="queue"?"queue":"workflow",t=e.dispatchKind==="queue"?"queue message body":"workflow params";return n(o,{cacheKey:`privileged_dispatch_unvalidated_payload:${e.file}:${e.line.toString()}`,detail:`The ${a} handler \`${e.handlerExport}\` (${e.file}:${e.line.toString()}) forwards its untrusted ${t} straight into \`${e.targetFile}.${e.targetExport}\`, which is guarded by \`.use(rls(...))\`. The handler runs under the system identity with RLS disabled, so the target's row policy is bypassed — any ownership/identity field the payload controls lets a caller act as another user or write across tenants. Re-derive the identity keys from server-trusted state before dispatching, or route through a function that re-checks the caller.`,metadata:{dispatchKind:e.dispatchKind,file:e.file,handlerExport:e.handlerExport,line:e.line,targetExport:e.targetExport,targetFile:e.targetFile}})})},source:"static",title:"Privileged handler forwards untrusted payload into an RLS-gated function"};export{o as default};
@@ -0,0 +1 @@
1
+ import{i as a}from"./finding-BAVgqnCF.mjs";import{m as i}from"./procedure-protections-DRQotu9I.mjs";const r={categories:["SECURITY"],description:"A public procedure fans work out to a privileged dispatch surface (`ctx.scheduler.runAfter`/`runAt`, a `ctx.queues.<name>` send, or `ctx.workflows.<name>.create`) with no rate-limit guard. Each dispatch runs later under the system identity and bills the account, so an anonymous caller can amplify cost and flood the async surface in a loop.",facing:"EXTERNAL",level:"WARN",name:"privileged_fanout_from_public_procedure",remediation:"Gate the public entry point with a rate limit (`.use(rateLimit(...))` or a `protectPublic({ rateLimit })` bundle), or make the fan-out procedure internal and trigger it only from an authenticated, guarded path. Never expose an unbounded scheduler/queue/workflow dispatch to anonymous callers.",run:t=>t.procedureProtections===void 0?[]:t.procedureProtections.filter(e=>i(e.fanOut)&&e.visibility==="public"&&!e.usesRateLimit).map(e=>a(r,{cacheKey:`privileged_fanout_from_public_procedure:${e.file}:${e.exportName}`,detail:`\`${e.exportName}\` (${e.file}) is public and fans work out to a privileged dispatch surface (scheduler/queue/workflow) with no rate limit — an anonymous caller can drive that billable, system-identity dispatch in a loop. Add a rate-limit guard, or make it internal and trigger it from an authenticated path.`,metadata:{exportName:e.exportName,file:e.file,kind:e.kind}})),source:"static",title:"Public procedure fans out to a privileged dispatch surface"};export{r as default};
@@ -0,0 +1 @@
1
+ const i=t=>t!==!1;export{i as m};
@@ -0,0 +1 @@
1
+ import{i}from"./finding-BAVgqnCF.mjs";const o={categories:["SCHEMA"],description:"A public `mutation`/`action` emits no structured event. When it fails you get a stack trace with no request context — no ids, no tenant, no outcome — so the failure is visible but not searchable.",facing:"INTERNAL",level:"INFO",name:"procedure_without_structured_event",remediation:'Emit one event on the primary path: `ctx.log.info("<verb>", { … })`, or wrap the handler in `ctx.span("<name>", …)` to attach timing too.',run:t=>t.procedureProtections===void 0?[]:t.procedureProtections.filter(e=>e.visibility==="public"&&e.kind!=="query"&&e.emitsEvent===!1).map(e=>i(o,{cacheKey:`procedure_without_structured_event:${e.file}:${e.exportName}`,detail:`Public ${e.kind} \`${e.exportName}\` (${e.file}) emits no structured event. Add a \`ctx.log\` line or a \`ctx.span\` so a failure carries its request context.`,metadata:{exportName:e.exportName,file:e.file,kind:e.kind}})),source:"static",title:"Public write emits no structured event"};export{o as default};
@@ -0,0 +1 @@
1
+ import{i as t}from"./finding-BAVgqnCF.mjs";const n={categories:["SECURITY"],description:"A public procedure declares a `v.any()` argument. `v.any()` accepts arbitrary untyped input from an untrusted client — defeating validation and opening injection / oversized-payload abuse.",facing:"EXTERNAL",level:"WARN",name:"public_arg_uses_any",remediation:"Replace `v.any()` with a precise validator — `v.object({...})`, `v.string()`, `v.union(...)`, etc. If the shape is genuinely dynamic, model the known variants with `v.union` rather than accepting anything.",run:i=>i.argValidators===void 0?[]:i.argValidators.flatMap(e=>e.anyArgs.map(a=>t(n,{cacheKey:`public_arg_uses_any:${e.file}:${e.exportName}:${a}`,detail:`Arg \`${a}\` of public procedure \`${e.exportName}\` (${e.file}:${e.line.toString()}) is \`v.any()\` — untrusted input with no validation. Give it a precise validator.`,metadata:{argument:a,exportName:e.exportName,file:e.file,line:e.line}}))),source:"static",title:"Public argument uses v.any()"};export{n as default};
@@ -0,0 +1 @@
1
+ import{i as r}from"./finding-BAVgqnCF.mjs";import{i as a}from"./helpers-DwlvEUCh.mjs";const o=/contact|forgot|login|magic|otp|register|reset|signin|signup|subscribe|verify/iu,s={categories:["SECURITY"],description:"A public `mutation`/`action` has no `rateLimit` middleware. Publicly-callable writes are flood and brute-force targets — an attacker can exhaust writes, mail quota, or credits, or guess credentials on auth-shaped endpoints.",facing:"EXTERNAL",level:"WARN",name:"public_mutation_without_ratelimit",remediation:'Attach a rate limit: `.use(rateLimit(limiter, "<bucket>"))` from `@lunora/ratelimit`, or wrap the recommended public-procedure guards with `.use(protectPublic({ rateLimit, captcha }))` from `@lunora/server`. Genuinely-open writes can be acknowledged by adding a permissive limiter.',run:i=>i.procedureProtections===void 0?[]:i.procedureProtections.filter(e=>a(e)&&!e.usesRateLimit).map(e=>{const t=o.test(e.exportName);return r(s,{cacheKey:`public_mutation_without_ratelimit:${e.file}:${e.exportName}`,detail:`Public ${e.kind} \`${e.exportName}\` (${e.file}) has no rate limit${t?" — its name suggests an auth/abuse-sensitive endpoint, so this is high-risk":""}. Add \`.use(rateLimit(...))\` or \`.use(protectPublic({ rateLimit }))\`.`,metadata:{exportName:e.exportName,file:e.file,kind:e.kind,sensitive:t}})}),source:"static",title:"Public write without a rate limit"};export{s as default};
@@ -0,0 +1 @@
1
+ import{i as a}from"./finding-BAVgqnCF.mjs";import{o as i}from"./helpers-DwlvEUCh.mjs";const r={categories:["SECURITY"],description:'`.public()` opts a table OUT of the schema\'s `.rls("required")` enforcement — it does not mean the table holds public data. A `.public()` table whose columns look ownership- or PII-shaped (`userId`, `email`, `ssn`, …) is exempt from the row-security guard, not "safe to expose".',facing:"EXTERNAL",level:"WARN",name:"public_table_rls_optout_confusion",remediation:'Double-check this table actually needs the RLS opt-out. If it does not, remove `.public()` so `.rls("required")` covers it like every other table. If it genuinely must stay open (a shared lookup table, for instance), rename or comment it so the exemption is intentional rather than a name-implies-safety mistake, and make sure no procedure trusts `.public()` as an authorization boundary.',run:o=>{if(o.schema.rlsMode!=="required")return[];const s=[];for(const e of o.schema.tables){if(!e.isPublic)continue;const t=i(e);t.length!==0&&s.push(a(r,{cacheKey:`public_table_rls_optout_confusion:${e.name}`,detail:`Table "${e.name}" is \`.public()\` (opted OUT of the schema's \`.rls("required")\` enforcement) but carries ownership/PII-shaped column(s): ${t.join(", ")}. \`.public()\` means "exempt from RLS", not "safe to expose" — confirm this table really needs the opt-out.`,metadata:{columns:t,table:e.name}}))}return s},source:"static",title:"Public table opts out of RLS but carries sensitive columns"};export{r as default};
@@ -0,0 +1 @@
1
+ import{i as r}from"./finding-BAVgqnCF.mjs";const i={categories:["SCHEMA"],description:"A queue consumer drops a message once it exhausts `maxRetries` (default 3) delivery attempts. Without a `deadLetterQueue`, that message is deleted permanently with no record — route exhausted messages to a DLQ so you can inspect, alert on, and replay them.",facing:"INTERNAL",level:"WARN",name:"queue_without_dlq",remediation:'Add `deadLetterQueue: "<name>-dlq"` to the `defineQueue({...})` options and declare a consumer for that queue so exhausted messages are inspectable (an unconsumed DLQ still expires at the retention window). `vis generate lunora-queue` with the best-practice setup scaffolds both. If the queue is fire-and-forget and message loss is acceptable, this advisory can be ignored.',run:t=>{if(t.queues===void 0)return[];const n=new Set(t.queues.map(e=>e.tuning.deadLetterQueue).filter(e=>e!==void 0&&e!=="")),s=[];for(const e of t.queues){const u=e.tuning.deadLetterQueue;if(u!==void 0&&u!==""||n.has(e.name))continue;const a=typeof e.tuning.maxRetries=="number"?e.tuning.maxRetries:3;s.push(r(i,{cacheKey:`queue_without_dlq:${e.exportName}`,detail:`Queue "${e.exportName}" declares no \`deadLetterQueue\`, so a message that exhausts its retries (\`maxRetries\` = ${String(a)}, ~${String(a+1)} delivery attempts) is dropped and permanently lost.`,metadata:{maxRetries:a,mode:e.mode,queue:e.exportName}}))}return s},source:"static",title:"Queue has no dead-letter queue"};export{i as default};
@@ -0,0 +1 @@
1
+ import{i as t}from"./finding-BAVgqnCF.mjs";const a={categories:["SCHEMA"],description:"A `query`/`mutation` handler accesses R2 SQL via `ctx.r2sql`. R2 SQL queries external Apache Iceberg tables over REST (no Workers binding): queries are non-deterministic (like `fetch`) and the reads are invisible to live queries. `ctx.r2sql` is available on `ActionCtx` only and must be confined to `action` handlers.",facing:"EXTERNAL",level:"WARN",name:"r2sql_outside_action",remediation:"Move the `ctx.r2sql` access into an `action(...)` (the only context where it is typed), where external I/O is allowed. If a query/mutation needs the data, have the action read it via `ctx.r2sql` and write a projection into a `defineSchema` DO/D1 table — that write is tracked by live queries, whereas R2 SQL is not.",run:i=>i.r2sqlCalls===void 0?[]:i.r2sqlCalls.map(e=>t(a,{cacheKey:`r2sql_outside_action:${e.file}:${e.line.toString()}:${e.callee}`,detail:`\`${e.callee}(…)\` in ${e.exportName} (${e.file}:${e.line.toString()}) runs inside a ${e.kind} handler — R2 SQL's \`ctx.r2sql\` is non-deterministic and non-reactive, so it is available only in actions. Move the external query into an \`action\` and project the result into a Lunora table if a query/mutation needs it.`,metadata:{callee:e.callee,exportName:e.exportName,file:e.file,kind:e.kind,line:e.line}})),source:"static",title:"R2 SQL `ctx.r2sql` used outside an action"};export{a as default};
@@ -0,0 +1 @@
1
+ import{i}from"./finding-BAVgqnCF.mjs";const a={categories:["SECURITY"],description:"`new RateLimiter({...})` has no `store`, so it falls back to a per-instance in-memory store. On Workers each request may hit a different isolate, so the counter never sums across them — the limit silently under-counts and is effectively a no-op under load, giving false protection against brute-force and cost abuse.",facing:"EXTERNAL",level:"WARN",name:"ratelimit_default_memory_store",remediation:"Pass a shared, durable `store` to `new RateLimiter({...})` (a Durable-Object- or KV-backed store) so every Worker isolate reads and writes the same bucket. The default in-memory store is per-isolate and does not enforce a global limit.",run:t=>t.configCalls===void 0?[]:t.configCalls.filter(e=>e.callee==="RateLimiter"&&e.analyzable&&!e.presentKeys.includes("store")).map(e=>i(a,{cacheKey:`ratelimit_default_memory_store:${e.file}:${e.line.toString()}`,detail:`\`new RateLimiter({...})\` in ${e.file}:${e.line.toString()} has no \`store\` — it uses the per-instance in-memory store, which never sums across Worker isolates, so the limit silently under-counts under load. Pass a Durable-Object- or KV-backed \`store\` so the limit is enforced globally.`,metadata:{callee:e.callee,file:e.file,line:e.line}})),source:"static",title:"RateLimiter using the default in-memory store"};export{a as default};
@@ -0,0 +1 @@
1
+ import{i}from"./finding-BAVgqnCF.mjs";const a={categories:["SECURITY"],description:"A `rateLimit`/`dbRateLimit` middleware call's `key` selector is derived from the handler's `args` with no server-side scoping, so an attacker can rotate the key on every request (e.g. by resubmitting a different email/id) and never share a bucket with themselves — the limit never actually limits them.",facing:"EXTERNAL",level:"WARN",name:"ratelimit_key_spoofable_or_global",remediation:'Derive the rate-limit `key` from a server-trusted value — `ctx.auth.userId` for authenticated callers, `ctx.ip` for anonymous ones (e.g. `key: (ctx) => ctx.auth.userId ?? ctx.ip ?? "anon"`) — instead of an `args` field the caller controls.',run:t=>t.ratelimitKeySelectors===void 0?[]:t.ratelimitKeySelectors.map(e=>i(a,{cacheKey:`ratelimit_key_spoofable_or_global:${e.file}:${e.line.toString()}`,detail:`\`${e.callee}(…, "${e.limitName}", { key })\` in \`${e.exportName}\` (${e.file}:${e.line.toString()}) derives its \`key\` from \`args\` with no server-side scoping — an attacker can rotate the key per request and bypass the limit. Derive \`key\` from \`ctx.auth.userId\` / \`ctx.ip\` instead.`,metadata:{callee:e.callee,exportName:e.exportName,file:e.file,limitName:e.limitName,line:e.line}})),source:"static",title:"Rate-limit key derived from spoofable user input"};export{a as default};
@@ -0,0 +1 @@
1
+ import{i as r}from"./finding-BAVgqnCF.mjs";const l=["signin","signup","login","register","reset","password","otp","verify","payment","checkout"],n=i=>i.toLowerCase().replaceAll(/[^a-z0-9]+/gu,""),t=i=>{const e=n(i);return l.some(a=>e.includes(a))},o=i=>t(i.exportName)||t(i.limitName),s={categories:["SECURITY"],description:"A rate-limit or Turnstile middleware guarding a sensitive auth/payment procedure is configured `failOpen: true`, so a limiter store outage or a failed Turnstile siteverify silently admits every request — turning a transient failure into an unthrottled brute-force / abuse window.",facing:"EXTERNAL",level:"WARN",name:"ratelimit_middleware_fail_open",remediation:"Drop `failOpen: true` (the default is fail-closed) on the rate-limit / Turnstile guard for auth and payment flows, or move the escape hatch to a non-sensitive procedure. Prefer rejecting traffic with a 503 over admitting unlimited unauthenticated attempts when the limiter or siteverify is unavailable.",run:i=>i.failOpenGuards===void 0?[]:i.failOpenGuards.filter(e=>e.failOpen&&o(e)).map(e=>r(s,{cacheKey:`ratelimit_middleware_fail_open:${e.file}:${e.line.toString()}`,detail:`\`${e.callee}(...)\` in \`${e.exportName}\` (${e.file}:${e.line.toString()}) sets \`failOpen: true\` while guarding a sensitive flow — a limiter/siteverify outage then admits every request instead of rejecting it.`,metadata:{callee:e.callee,exportName:e.exportName,file:e.file,limitName:e.limitName,line:e.line}})),source:"static",title:"Fail-open rate-limit / CAPTCHA guard on a sensitive procedure"};export{s as default};
@@ -0,0 +1 @@
1
+ import{i as s}from"./finding-BAVgqnCF.mjs";import{t as c}from"./helpers-DwlvEUCh.mjs";const m=(o,i,r,t)=>{const e=o.get(t.table);if(!e)return[];const n=t.kind==="one"?r:e,a=t.kind==="one"?e:r,l=[];return i(n).has(t.field)||l.push({column:t.field,owner:n.name,side:"field"}),i(a).has(t.references)||l.push({column:t.references,owner:a.name,side:"references"}),l},d={categories:["SCHEMA"],description:"A relation references a foreign-key or referenced column that is not declared on its table, so the join can never resolve.",facing:"INTERNAL",level:"ERROR",name:"relation_references_unknown_field",remediation:"Fix the `field` / `references` column name in the relation, or add the missing column.",run:o=>{const i=new Map(o.schema.tables.map(e=>[e.name,e])),r=new Map,t=e=>{let n=r.get(e);return n||(n=c(e),r.set(e,n)),n};return o.schema.tables.flatMap(e=>e.relations.flatMap(n=>m(i,t,e,n).map(a=>s(d,{cacheKey:`relation_references_unknown_field:${e.name}:${n.name}:${a.side}`,detail:`Relation "${n.name}" on table "${e.name}" uses ${a.side} "${a.column}", which is not declared on table "${a.owner}".`,metadata:{column:a.column,owner:a.owner,relation:n.name,side:a.side,table:e.name}}))))},source:"static",title:"Relation references unknown field"};export{d as default};
@@ -0,0 +1 @@
1
+ import{i as r}from"./finding-BAVgqnCF.mjs";const l={categories:["SCHEMA"],description:"A relation targets a table that does not exist in the schema. The relation can never load — the target is a typo or a removed/renamed table.",facing:"INTERNAL",level:"ERROR",name:"relation_references_unknown_table",remediation:"Fix the target table name in the relation, or add the missing table to the schema.",run:t=>{const n=new Set(t.schema.tables.map(a=>a.name));return t.schema.tables.flatMap(a=>a.relations.filter(e=>!n.has(e.table)).map(e=>r(l,{cacheKey:`relation_references_unknown_table:${a.name}:${e.name}`,detail:`Relation "${e.name}" on table "${a.name}" targets table "${e.table}", which does not exist in the schema.`,metadata:{relation:e.name,table:a.name,target:e.table}})))},source:"static",title:"Relation references unknown table"};export{l as default};
@@ -0,0 +1 @@
1
+ import{i as a}from"./finding-BAVgqnCF.mjs";const l={categories:["SECURITY"],description:"A public procedure reads or writes a table that is covered by an RLS policy elsewhere in the app, but this procedure's builder chain does not include `.use(rls(...))`. The raw, unwrapped `ctx.db` silently bypasses every policy in the list.",facing:"EXTERNAL",level:"WARN",name:"rls_uncovered_table",remediation:"Add `.use(rls(policies))` to the procedure's builder chain — e.g. `c.use(rls(myPolicies)).query(...)` — so its `ctx.db` is wrapped by the same policy evaluator as the rest of the app. If this procedure is intentionally privileged (e.g. a background job), declare it with `internalQuery` / `internalMutation` / `internalAction` instead of the public builder so the intent is explicit.",run:s=>{if(s.rlsProcedures===void 0)return[];const r=new Set;for(const e of s.rlsProcedures)for(const i of e.rlsTables)i!==""&&r.add(i);if(r.size===0)return[];const o=[];for(const e of s.rlsProcedures){if(e.usesRls||e.visibility==="internal")continue;const i=new Set;for(const t of[...e.tablesRead,...e.tablesWritten])t!==""&&r.has(t)&&i.add(t);for(const t of i)o.push(a(l,{cacheKey:`rls_uncovered_table:${e.file}:${e.exportName}:${t}`,detail:`\`${e.exportName}\` in ${e.file} accesses table \`${t}\` without \`.use(rls(...))\` — the table is policy-gated elsewhere in the app but this procedure bypasses those policies entirely.`,metadata:{exportName:e.exportName,file:e.file,table:t}}))}return o},source:"static",title:"RLS-gated table accessed without rls() middleware"};export{l as default};
@@ -0,0 +1 @@
1
+ import{i as l}from"./finding-BAVgqnCF.mjs";const s={categories:["PERFORMANCE"],description:"A `defineShape` replicates from a `.global()` table. Global tables live outside the shard DO's SQLite op-log, so the shape is served through the cross-shard tier — coordinator/poll-refreshed and latency-tiered, not poke-live like a sharded shape.",facing:"EXTERNAL",level:"WARN",name:"shape_targets_global_table",remediation:"Expected if you want the cross-shard tier — just don't assume poke-live freshness; global shapes refresh on a poll. For live updates, replicate from a sharded table instead (denormalize the columns you need into the shard).",run:a=>{if(a.shapes===void 0)return[];const t=new Set(a.schema.tables.filter(e=>e.shardKind==="global").map(e=>e.name));return a.shapes.filter(e=>e.table!==void 0&&t.has(e.table)).map(e=>l(s,{cacheKey:`shape_targets_global_table:${e.exportName}`,detail:`Shape \`${e.exportName}\` (${e.file}) replicates from the \`.global()\` table \`${e.table}\`. It is served through the cross-shard global tier — poll-refreshed and latency-tiered, not poke-live.`,metadata:{exportName:e.exportName,file:e.file,table:e.table}}))},source:"static",title:"Shape replicates from a global (cross-shard) table"};export{s as default};
@@ -0,0 +1 @@
1
+ import{i as s}from"./finding-BAVgqnCF.mjs";const n={categories:["SCHEMA"],description:"A `defineShape` is bound to a `table` name that does not exist in the schema. The shape can never resolve a rowset — its subscription seeds empty and errors at the first flush.",facing:"INTERNAL",level:"ERROR",name:"shape_unknown_table",remediation:"Fix the shape's `table` to a real table name (check for a typo or a table that was renamed/removed).",run:a=>{if(a.shapes===void 0)return[];const t=new Set(a.schema.tables.map(e=>e.name));return a.shapes.filter(e=>e.table!==void 0&&!t.has(e.table)).map(e=>s(n,{cacheKey:`shape_unknown_table:${e.exportName}`,detail:`Shape \`${e.exportName}\` (${e.file}) replicates from table \`${e.table}\`, which is not declared in the schema. The shape can never resolve a rowset.`,metadata:{exportName:e.exportName,file:e.file,table:e.table}}))},source:"static",title:"Shape bound to an unknown table"};export{n as default};
@@ -0,0 +1 @@
1
+ import{i as s}from"./finding-BAVgqnCF.mjs";import{m as i}from"./procedure-protections-DRQotu9I.mjs";import{i as o}from"./helpers-DwlvEUCh.mjs";const r={categories:["SECURITY"],description:"A public `mutation`/`action` that creates a user/session/account row has no disposable-email gate. Throwaway mailboxes farm free trials, evade bans, and pollute the user table.",facing:"EXTERNAL",level:"WARN",name:"signup_mutation_without_disposable_gating",remediation:"Add `.use(emailGateMiddleware({ email: (ctx) => ctx.args.email }))` from `@lunora/auth/email-guard` to reject disposable domains at signup, or gate better-auth's native signup with `withEmailGate(...)` / `emailGateDatabaseHooks(...)`.",run:a=>{if(a.procedureProtections===void 0)return[];const t=[];for(const e of a.procedureProtections)!o(e)||!i(e.writesUserTable)||e.usesEmailGate||i(e.hasEmailArg)&&t.push(s(r,{cacheKey:`signup_mutation_without_disposable_gating:${e.file}:${e.exportName}`,detail:`Public ${e.kind} \`${e.exportName}\` (${e.file}) writes a user/session/account table but has no disposable-email gate. Add \`.use(emailGateMiddleware(...))\` from \`@lunora/auth/email-guard\`.`,metadata:{exportName:e.exportName,file:e.file,kind:e.kind,writesUserTable:e.writesUserTable}}));return t},source:"static",title:"Account-creating write without a disposable-email gate"};export{r as default};
@@ -0,0 +1 @@
1
+ import{i as o}from"./finding-BAVgqnCF.mjs";const d={categories:["SECURITY"],description:"A `.public()` read passes `includeDeleted` (hardcoded `true` or derived from `args`) on a `.softDelete()` table, resurfacing soft-deleted rows to callers that should never see them.",facing:"EXTERNAL",level:"INFO",name:"soft_delete_include_deleted_from_args",remediation:"Drop `includeDeleted` from the public read so soft-deleted rows stay hidden, or move the trash/restore view behind an internal (or RLS/role-gated) procedure. Never wire `includeDeleted` from `args` on a public read — an attacker can set it to see rows the app treats as deleted.",run:t=>{if(t.softDeleteReads===void 0)return[];const r=new Set(t.schema.tables.filter(e=>e.softDelete!==void 0).map(e=>e.name));return r.size===0?[]:t.softDeleteReads.filter(e=>e.visibility==="public"&&e.table!==""&&r.has(e.table)&&(e.hardcodedTrue||e.fromArgs)).map(e=>{const a=`\`${e.exportName}\` (${e.file}:${e.line.toString()})`,l=e.fromArgs?`The public read in ${a} wires \`includeDeleted\` from request \`args\` on soft-delete table \`${e.table}\`, letting any caller resurface soft-deleted rows the app treats as gone.`:`The public read in ${a} hardcodes \`includeDeleted: true\` on soft-delete table \`${e.table}\`, returning soft-deleted rows to every caller.`;return o(d,{cacheKey:`soft_delete_include_deleted_from_args:${e.file}:${e.line.toString()}:${e.table}`,detail:l,metadata:{exportName:e.exportName,file:e.file,line:e.line,source:e.fromArgs?"args":"literal",table:e.table}})})},source:"static",title:"Soft-deleted rows resurfaced via includeDeleted on a public read"};export{d as default};
@@ -0,0 +1 @@
1
+ import{i}from"./finding-BAVgqnCF.mjs";const n={categories:["SECURITY"],description:"A `ctx.sql` tagged-template interpolates an unparameterized string-building expression (concatenation or nested template) instead of a bound value — splicing raw text into the query and reopening SQL injection.",facing:"EXTERNAL",level:"ERROR",name:"sql_injection_risk",remediation:"Pass the value through a bound placeholder so the driver parameterizes it — keep request input inside a `ctx.sql` placeholder instead of concatenating it into the query string. Never build SQL text from request input by hand.",run:t=>t.sqlInterpolations===void 0?[]:t.sqlInterpolations.map(e=>i(n,{cacheKey:`sql_injection_risk:${e.file}:${e.line.toString()}`,detail:`\`ctx.sql\` in \`${e.exportName}\` (${e.file}:${e.line.toString()}) interpolates a string-building expression instead of a bound value — a SQL-injection vector. Pass the value through a bound placeholder so the driver parameterizes it.`,metadata:{exportName:e.exportName,file:e.file,line:e.line}})),source:"static",title:"Possible SQL injection in ctx.sql interpolation"};export{n as default};
@@ -0,0 +1 @@
1
+ import{i as n}from"./finding-BAVgqnCF.mjs";const a={categories:["SECURITY"],description:"A `ctx.storage.generateUploadUrl(key, …)` call has no `contentType` pin, so the signed PUT URL it mints authorizes any content-type/size the client chooses — `upload()`'s `allowedContentTypes`/`maxSize` guards never run for a client-side PUT against this URL.",facing:"EXTERNAL",level:"WARN",name:"storage_generate_upload_url_no_content_type_pin",remediation:"Pass `contentType` to `ctx.storage.generateUploadUrl(key, { contentType })` so the signature only authorizes a PUT with that exact content-type. If the client's upload size/type also needs bounding, prefer `upload()`/`store()` (with `allowedContentTypes`/`maxSize`) over a client-side signed PUT.",run:t=>t.storageUploads===void 0?[]:t.storageUploads.filter(e=>e.method==="generateUploadUrl"&&e.analyzable&&!e.presentKeys.includes("contentType")).map(e=>n(a,{cacheKey:`storage_generate_upload_url_no_content_type_pin:${e.file}:${e.line.toString()}`,detail:`\`ctx.storage.generateUploadUrl\` in \`${e.exportName}\` (${e.file}:${e.line.toString()}) has no \`contentType\` pin — the signed PUT it mints accepts any type/size, minted client-side and bypassing \`upload()\`'s guards.`,metadata:{exportName:e.exportName,file:e.file,line:e.line}})),source:"static",title:"generateUploadUrl signed PUT with no content-type pin"};export{a as default};
@@ -0,0 +1 @@
1
+ import{i}from"./finding-BAVgqnCF.mjs";const o={categories:["SECURITY"],description:"A `ctx.storage.*` call uses an R2 object key taken directly from the handler's `args` with no server-side scoping. The bucket methods key by the caller-supplied string, so any caller can read, overwrite, or delete another user's object — object-level IDOR.",facing:"EXTERNAL",level:"ERROR",name:"storage_key_from_user_args",remediation:"Prefix the object key with a server-trusted identity (e.g. `${ctx.auth.userId}/…`) or resolve the object through a record the caller is known to own. Never pass request input straight through as an R2 object key.",run:t=>t.storageKeyAccesses===void 0?[]:t.storageKeyAccesses.map(e=>{const r=`\`ctx.storage.*.${e.method}\` in \`${e.exportName}\` (${e.file}:${e.line.toString()})`,s={exportName:e.exportName,file:e.file,line:e.line,method:e.method,visibility:e.visibility??"unknown"};return e.visibility==="internal"?i(o,{cacheKey:`storage_key_from_user_args:${e.file}:${e.line.toString()}`,detail:`${r} uses an object key derived from \`args\` with no server-side scoping. This is expected for an \`internal\` procedure — no caller can reach it directly, so the key is only ever supplied by trusted server code. Audit the PUBLIC procedures that dispatch to it: if one forwards \`args\` straight through, the IDOR is there.`,facing:"INTERNAL",level:"INFO",metadata:s}):i(o,{cacheKey:`storage_key_from_user_args:${e.file}:${e.line.toString()}`,detail:`${r} uses an object key derived from \`args\` with no server-side scoping — any caller can read/overwrite/delete another user's object (IDOR). Prefix the key with a server-trusted identity (e.g. \`\${ctx.auth.userId}/…\`) or resolve the object through an owned record.`,metadata:s})}),source:"static",title:"R2 object key taken directly from user args (IDOR)"};export{o as default};
@@ -0,0 +1 @@
1
+ import{i as l}from"./finding-BAVgqnCF.mjs";const g=new Set(["getPresignedUrl","getSignedUrl"]),d=8640*60,s=t=>t.method==="getPresignedUrl",a=t=>g.has(t.method)&&t.expiresInSeconds!==void 0&&t.expiresInSeconds>=d,c={categories:["SECURITY"],description:"`ctx.storage.getPresignedUrl(...)` mints a native S3 SigV4 URL that resolves directly against R2, bypassing the Worker's auth/RLS/rate-limit entirely — the wrong choice for private or policy-gated content. Either signer minting an `expiresInSeconds` near the shared 7-day ceiling also hands out a long-lived bearer credential.",facing:"EXTERNAL",level:"WARN",name:"storage_presigned_url_for_private_content",remediation:"For private/per-user/policy-gated content, use `getSignedUrl` (resolves back through the Worker, so your auth/RLS/rate-limit gates still run) instead of `getPresignedUrl`. Reserve `getPresignedUrl` for genuinely public or bulk content. On either signer, keep `expiresInSeconds` as short as the use case allows — well under the 7-day ceiling — rather than minting a near-maximum-lifetime URL.",run:t=>t.storageUploads===void 0?[]:t.storageUploads.filter(e=>s(e)||a(e)).map(e=>{const n=s(e),o=a(e),r=`\`${e.exportName}\` (${e.file}:${e.line.toString()})`;let i;return n&&o?i=`\`ctx.storage.getPresignedUrl\` in ${r} mints a native S3 SigV4 URL — bypasses the Worker's auth/RLS/rate-limit entirely — with an \`expiresInSeconds\` of ${(e.expiresInSeconds??0).toString()}s, near the 7-day signing ceiling.`:n?i=`\`ctx.storage.getPresignedUrl\` in ${r} mints a native S3 SigV4 URL that resolves directly against R2, bypassing the Worker's auth/RLS/rate-limit entirely. Use \`getSignedUrl\` for app-gated access to private content.`:i=`\`ctx.storage.${e.method}\` in ${r} requests an \`expiresInSeconds\` of ${(e.expiresInSeconds??0).toString()}s, near the 7-day signing ceiling — a leaked link stays valid for almost a week.`,l(c,{cacheKey:`storage_presigned_url_for_private_content:${e.file}:${e.line.toString()}`,detail:i,metadata:{expiresInSeconds:e.expiresInSeconds,exportName:e.exportName,file:e.file,line:e.line,method:e.method}})}),source:"static",title:"Native presigned URL or near-max-TTL signed URL for private content"};export{c as default};
@@ -0,0 +1 @@
1
+ import{i as o}from"./finding-BAVgqnCF.mjs";const a=new Set(["store","upload"]),l={categories:["SECURITY"],description:"A `ctx.storage.upload`/`store` call has no `allowedContentTypes` allowlist, so an uploader can store any content-type — including `text/html` or `image/svg+xml` — which, served back from `publicBaseUrl`, is a stored-XSS vector against your own origin.",facing:"EXTERNAL",level:"WARN",name:"storage_upload_without_content_type_allowlist",remediation:'Pass `allowedContentTypes: ["image/png", "image/jpeg", …]` to `ctx.storage.upload`/`store` so an uploaded object\'s `contentType` must match an approved list. Reject anything HTML/SVG/script-executable unless the app genuinely needs to serve it.',run:t=>t.storageUploads===void 0?[]:t.storageUploads.filter(e=>a.has(e.method)&&e.analyzable&&!e.presentKeys.includes("allowedContentTypes")).map(e=>o(l,{cacheKey:`storage_upload_without_content_type_allowlist:${e.file}:${e.line.toString()}`,detail:`\`ctx.storage.${e.method}\` in \`${e.exportName}\` (${e.file}:${e.line.toString()}) has no \`allowedContentTypes\` allowlist — any content-type is accepted, including \`text/html\`/\`image/svg+xml\`, a stored-XSS risk if the object is served from \`publicBaseUrl\`.`,metadata:{exportName:e.exportName,file:e.file,line:e.line,method:e.method}})),source:"static",title:"Storage upload with no content-type allowlist"};export{l as default};
@@ -0,0 +1 @@
1
+ import{i as t}from"./finding-BAVgqnCF.mjs";const o=new Set(["store","upload"]),i={categories:["SECURITY"],description:"A `ctx.storage.upload`/`store` call has no `maxSize` cap, so a caller can push an unbounded body straight into R2 through the Worker — unbounded storage/billing exhaustion, and for a streamed body, unbounded worker time.",facing:"EXTERNAL",level:"WARN",name:"storage_upload_without_max_size",remediation:"Pass a `maxSize` (bytes) to `ctx.storage.upload`/`store` sized to the largest legitimate object the app accepts. `ArrayBuffer`/`Blob` bodies are rejected up front when oversized; a `ReadableStream` body is aborted mid-transfer once the limit is exceeded.",run:a=>a.storageUploads===void 0?[]:a.storageUploads.filter(e=>o.has(e.method)&&e.analyzable&&!e.presentKeys.includes("maxSize")).map(e=>t(i,{cacheKey:`storage_upload_without_max_size:${e.file}:${e.line.toString()}`,detail:`\`ctx.storage.${e.method}\` in \`${e.exportName}\` (${e.file}:${e.line.toString()}) has no \`maxSize\` cap — a caller can push an unbounded body into R2, exhausting storage/billing.`,metadata:{exportName:e.exportName,file:e.file,line:e.line,method:e.method}})),source:"static",title:"Storage upload with no size cap"};export{i as default};
@@ -0,0 +1 @@
1
+ import{i}from"./finding-BAVgqnCF.mjs";const n={categories:["SCHEMA"],description:'No function inserts into this table via `ctx.db.insert("<table>", …)`. It may be read-only by design (seeded by a migration, replicated, or written through a path the advisor can\'t see) — or it may be dead schema.',facing:"INTERNAL",level:"INFO",name:"table_without_insert",remediation:'If the table should be writable, add a mutation that calls `ctx.db.insert("<table>", …)`. If it is read-only or seeded elsewhere, this advisory can be ignored.',run:t=>{if(t.inserts===void 0)return[];const a=new Set(t.inserts.filter(e=>e.table!=="").map(e=>e.table));return t.schema.tables.filter(e=>!a.has(e.name)&&e.externallyManaged!==!0).map(e=>i(n,{cacheKey:`table_without_insert:${e.name}`,detail:`No function calls \`ctx.db.insert("${e.name}", …)\` — table "${e.name}" has no discovered insert path.`,metadata:{table:e.name}}))},source:"static",title:"Table has no insert path"};export{n as default};
@@ -0,0 +1 @@
1
+ import{i as o}from"./finding-BAVgqnCF.mjs";const l=new Set(["date","number","timestamp"]),m={categories:["SCHEMA"],description:"A `.ttl(field)` policy points at a column that is not an epoch-millisecond timestamp, so the alarm sweep's `field < now` comparison can't decide expiry correctly.",facing:"INTERNAL",level:"ERROR",name:"ttl_field_not_timestamp",remediation:"Point `.ttl(field)` at a `v.timestamp()` / `v.date()` / `v.number()` (epoch-ms) column, or add such a column.",run:n=>{const a=[];for(const e of n.schema.tables){const{ttl:t}=e;if(!t)continue;const i=e.columnKinds?.[t.field];i===void 0||l.has(i)||a.push(o(m,{cacheKey:`ttl_field_not_timestamp:${e.name}:${t.field}`,detail:`Table "${e.name}" declares \`.ttl("${t.field}")\`, but "${t.field}" is a ${i} column, not an epoch-millisecond timestamp.`,metadata:{field:t.field,kind:i,table:e.name}}))}return a},source:"static",title:"TTL field is not a timestamp"};export{m as default};
@@ -0,0 +1 @@
1
+ import{i as t}from"./finding-BAVgqnCF.mjs";const i={categories:["SECURITY"],description:"A public `v.string()` argument has no maximum-length bound. An unbounded string lets a client submit arbitrarily large input — abusing storage and CPU on every request that processes it.",facing:"EXTERNAL",level:"INFO",name:"unbounded_string_arg",remediation:"Add a max-length bound via `.check(...)` / `.meta({ maxLength })` on the string validator (e.g. cap a name at 256, a body at a few KB). Size the cap to the field's real-world maximum.",run:n=>n.argValidators===void 0?[]:n.argValidators.flatMap(e=>e.unboundedStringArgs.map(a=>t(i,{cacheKey:`unbounded_string_arg:${e.file}:${e.exportName}:${a}`,detail:`Arg \`${a}\` of public procedure \`${e.exportName}\` (${e.file}:${e.line.toString()}) is an unbounded \`v.string()\`. Add a max-length bound to cap payload size.`,metadata:{argument:a,exportName:e.exportName,file:e.file,line:e.line}}))),source:"static",title:"Public string argument has no length bound"};export{i as default};
@@ -0,0 +1 @@
1
+ import{i as s}from"./finding-BAVgqnCF.mjs";import{l as r,P as d,s as c}from"./fk-index-Bmk19RvQ.mjs";const f={categories:["PERFORMANCE"],description:"A foreign-key column declared by a `one` relation has no index leading with it. Reads that filter or join on the column full-scan the table, which gets linearly slower as rows accumulate.",facing:"EXTERNAL",level:"INFO",name:"unindexed_foreign_key",remediation:'Add a secondary index leading with the FK column, e.g. `.index("byAuthorId", ["authorId"])`.',run:t=>{const o=[];for(const a of t.schema.tables){const i=r(a);for(const n of a.relations){if(n.kind!=="one")continue;const e=n.field;if(e===d||i.has(e))continue;const l=c(e);o.push(s(f,{cacheKey:`unindexed_foreign_key:${a.name}:${e}`,detail:`Relation "${n.name}" on table "${a.name}" references "${n.table}" via column "${e}", which is not the leading column of any index. Reads filtering or joining on "${e}" full-scan "${a.name}".`,metadata:{fkColumn:e,references:{column:n.references,table:n.table},relation:n.name,suggestedIndex:{fields:[e],name:l},table:a.name}}))}}return o},source:"static",title:"Unindexed foreign key"};export{f as default};
@@ -0,0 +1 @@
1
+ import{i as d}from"./finding-BAVgqnCF.mjs";import{P as c,l as m,s as u}from"./fk-index-Bmk19RvQ.mjs";const f={categories:["PERFORMANCE"],description:"A `many` relation's foreign-key column on the target table has no index leading with it. Relation predicates (`some`/`none`/`every`) and `with:` child reads filter the target on that column, full-scanning it as rows accumulate.",facing:"EXTERNAL",level:"INFO",name:"unindexed_relation_target",remediation:'Add a secondary index on the target table leading with the FK column, e.g. `.index("byAuthorId", ["authorId"])`.',run:o=>{const i=[],s=new Map(o.schema.tables.map(t=>[t.name,t]));for(const t of o.schema.tables)for(const e of t.relations){if(e.kind!=="many")continue;const a=s.get(e.table);if(a===void 0)continue;const n=e.field;if(n===c||a.relations.some(l=>l.kind==="one"&&l.field===n)||m(a).has(n))continue;const r=u(n);i.push(d(f,{cacheKey:`unindexed_relation_target:${e.table}:${n}`,detail:`Relation "${e.name}" on table "${t.name}" is a to-many over "${e.table}" via its column "${n}", which is not the leading column of any index on "${e.table}". Relation predicates (\`some\`/\`none\`/\`every\`) and \`with:\` reads of "${e.name}" full-scan "${e.table}".`,metadata:{fkColumn:n,references:{column:e.references,table:t.name},relation:e.name,suggestedIndex:{fields:[n],name:r},table:e.table}}))}return i},source:"static",title:"Unindexed relation target"};export{f as default};
@@ -0,0 +1 @@
1
+ import{i as n}from"./finding-BAVgqnCF.mjs";const t={"empty-object":"`{}`",undefined:"`undefined`"},a={categories:["SECURITY"],description:"A branching `defineShape({ where })` / `definePolicy({ when })` predicate returns `{}` or `undefined` from one arm. A row predicate is a filter, not a boolean: `{}` matches EVERY row, so an arm meant to deny instead replicates or exposes the whole table — silently.",facing:"EXTERNAL",level:"ERROR",name:"unrestricted_where_branch",remediation:"Return `deny()` (from `@lunora/server`) — or `false`, which compiles to the same vacuously-false `{ OR: [] }` predicate — from the denial arm. Reach for `allowAll()` only when that arm genuinely means 'no further restriction'. For an owner check, prefer `.ownedBy(field)` on the table plus `defineShape({ owner: true })`, which derives the predicate from the verified identity and cannot be written backwards.",run:r=>r.unrestrictedWhereBranches===void 0?[]:r.unrestrictedWhereBranches.map(e=>n(a,{cacheKey:`unrestricted_where_branch:${e.file}:${e.line.toString()}:${e.key}`,detail:`\`${e.owner}\` \`${e.exportName}\` (${e.file}:${e.line.toString()}) returns ${t[e.form]} from one arm of its \`${e.key}\` predicate. A predicate is a filter, not a boolean — ${t[e.form]} imposes no restriction, so this arm matches every row instead of none. Return \`deny()\` (or \`false\`) if it was meant to deny; use \`allowAll()\` to state an intentionally unrestricted arm.`,metadata:{exportName:e.exportName,file:e.file,form:e.form,key:e.key,line:e.line,owner:e.owner}})),source:"static",title:"Predicate arm returns an unrestricted filter"};export{a as default};
@@ -0,0 +1 @@
1
+ import{i as t}from"./finding-BAVgqnCF.mjs";import{m as i}from"./procedure-protections-DRQotu9I.mjs";import{i as r}from"./helpers-DwlvEUCh.mjs";const s=a=>a.writesUserTable===!0?"writes a user/session table":a.callsMail===!0?"sends mail":a.analyzableBody===!1?"may write a user/session table or send mail — its handler body could not be read":"may write a user/session table or send mail — at least one could not be determined",o={categories:["SECURITY"],description:"A public `mutation`/`action` that creates a user/session or sends mail has no CAPTCHA / bot check. Account-creating and mail-sending endpoints are prime automated-abuse targets (credential stuffing, mailbox flooding, disposable-account farming).",facing:"EXTERNAL",level:"WARN",name:"user_creating_mutation_without_captcha",remediation:"Add a server-verified human check: `.use(verifyTurnstile({ secret, token }))` from `@lunora/auth`, or wrap it with `.use(protectPublic({ rateLimit, captcha }))` from `@lunora/server`. Pair with a rate limit for defense in depth.",run:a=>a.procedureProtections===void 0?[]:a.procedureProtections.filter(e=>r(e)&&(i(e.writesUserTable)||i(e.callsMail))&&!e.usesCaptcha).map(e=>t(o,{cacheKey:`user_creating_mutation_without_captcha:${e.file}:${e.exportName}`,detail:`Public ${e.kind} \`${e.exportName}\` (${e.file}) ${s(e)} but has no CAPTCHA check. Add \`.use(verifyTurnstile(...))\` or \`.use(protectPublic({ captcha }))\`.`,metadata:{callsMail:e.callsMail,exportName:e.exportName,file:e.file,kind:e.kind,writesUserTable:e.writesUserTable}})),source:"static",title:"Account-creating / mail-sending write without a CAPTCHA"};export{o as default};
@@ -0,0 +1 @@
1
+ import{m as t}from"./argument-derived-sink-BpO3NPPM.mjs";const a=t({cacheKey:e=>`vectors_namespace_from_user_input:${e.file}:${e.line.toString()}`,categories:["SECURITY"],description:"A `ctx.vectors.query`/`upsert`/`upsertMany` call uses a `namespace` derived from the handler's `args` with no server-side scoping. A Vectorize namespace partitions one index into isolated sub-collections, so an unscoped namespace lets any caller read or poison another tenant's vectors.",detail:e=>`\`ctx.vectors.${e.method}\` in \`${e.exportName}\` (${e.file}:${e.line.toString()}) uses a Vectorize namespace derived from \`args\` with no server-side scoping — any caller can read or poison another tenant's vectors. Derive the namespace from a server-trusted identity (e.g. \`\${ctx.auth.orgId}\`), never from \`args\`.`,facing:"EXTERNAL",getAccesses:e=>e.vectorNamespaceAccesses,level:"WARN",metadata:e=>({exportName:e.exportName,file:e.file,line:e.line,method:e.method}),name:"vectors_namespace_from_user_input",remediation:"Derive the `namespace` from a server-trusted identity (e.g. `${ctx.auth.orgId}`), never from `args`.",title:"Vectorize namespace derived from unscoped user input"});export{a as default};
@@ -0,0 +1 @@
1
+ import{i as l}from"./finding-BAVgqnCF.mjs";const p={categories:["SCHEMA"],description:"Two durable steps in this workflow share a name. Cloudflare memoizes a step by its name, so on replay the second call returns the first step's cached result instead of running its body — silently skipping the work without an error.",facing:"INTERNAL",level:"ERROR",name:"workflow_duplicate_step_name",remediation:"Give every `step.do` / `step.sleep` / `step.sleepUntil` / `step.waitForEvent` call in the workflow a unique name. If a step legitimately repeats (e.g. a loop), make the name distinct per iteration by interpolating the item id into the step name.",run:a=>{if(a.workflows===void 0)return[];const o=[];for(const t of a.workflows){const{steps:n}=t;if(n===void 0||n.length===0)continue;const s=new Map,r=new Set;for(const e of n){const i=s.get(e.name);if(i===void 0){s.set(e.name,e.line);continue}r.has(e.name)||(r.add(e.name),o.push(l(p,{cacheKey:`workflow_duplicate_step_name:${t.exportName}:${e.name}`,detail:`Workflow "${t.exportName}" reuses the durable step name "${e.name}" (first at line ${String(i)}, again at line ${String(e.line)}). The second call returns the first's cached result instead of running.`,metadata:{firstLine:i,line:e.line,stepName:e.name,workflow:t.exportName}})))}}return o},source:"static",title:"Duplicate durable step name in workflow"};export{p as default};
@@ -0,0 +1 @@
1
+ import{i as w}from"./finding-BAVgqnCF.mjs";const l={categories:["SCHEMA"],description:'A `ctx.workflows.get("<name>")` call references a workflow that is not declared by any `defineWorkflow` export in `lunora/workflows.ts`. The name is a typo or points at a removed/renamed workflow — the call throws at runtime.',facing:"INTERNAL",level:"ERROR",name:"workflow_unknown_target",remediation:'Fix the workflow name in the `ctx.workflows.get("…")` call, or add the missing `defineWorkflow` export to `lunora/workflows.ts`.',run:e=>{if(e.workflows===void 0||e.workflowCalls===void 0)return[];const r=new Set(e.workflows.map(o=>o.exportName));return e.workflowCalls.filter(o=>o.workflow!==""&&!r.has(o.workflow)).map(o=>w(l,{cacheKey:`workflow_unknown_target:${o.file}:${o.exportName}:${o.workflow}`,detail:`\`ctx.workflows.get("${o.workflow}")\` in "${o.exportName}" (${o.file}) references workflow "${o.workflow}", which is not declared in lunora/workflows.ts.`,metadata:{exportName:o.exportName,file:o.file,line:o.line,workflow:o.workflow}}))},source:"static",title:"Workflow call references unknown workflow"};export{l as default};
@@ -0,0 +1 @@
1
+ import{i as a}from"./finding-BAVgqnCF.mjs";const i={categories:["SCHEMA"],description:'No function starts this workflow via `ctx.workflows.get("<name>")`. It may be triggered through a path the advisor can\'t see (the Cloudflare API, a wrangler invocation, a cross-service binding) — or it may be dead code that still deploys as a billable WorkflowEntrypoint.',facing:"INTERNAL",level:"INFO",name:"workflow_unused",remediation:'If the workflow should be triggered in-app, start it from a mutation/action with `ctx.workflows.get("<name>").create({ params })`. If it is started externally or is no longer needed, this advisory can be ignored (or remove the `defineWorkflow` export).',run:o=>{if(o.workflows===void 0)return[];const t=o.workflowCalls??[];if(t.some(e=>e.workflow===""))return[];const r=new Set(t.map(e=>e.workflow));return o.workflows.filter(e=>!r.has(e.exportName)).map(e=>a(i,{cacheKey:`workflow_unused:${e.exportName}`,detail:`No function calls \`ctx.workflows.get("${e.exportName}")\` — workflow "${e.exportName}" is declared but never started in app code.`,metadata:{workflow:e.exportName}}))},source:"static",title:"Workflow is never started"};export{i as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/advisor",
3
- "version": "1.0.0-alpha.7",
3
+ "version": "1.0.0-alpha.71",
4
4
  "description": "Schema & query lints (splinter-style advisors) for Lunora, feeding the Studio Advisors view",
5
5
  "keywords": [
6
6
  "advisor",
@@ -46,7 +46,8 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/server": "1.0.0-alpha.6"
49
+ "@lunora/errors": "1.0.0-alpha.16",
50
+ "@lunora/server": "1.0.0-alpha.66"
50
51
  },
51
52
  "engines": {
52
53
  "node": "^22.15.0 || >=24.11.0"
@@ -1,85 +0,0 @@
1
- const DATASET_NAME_PATTERN = /^[\w.-]+$/u;
2
- const AE_METRIC_EVENTS = {
3
- /** `lunora.index.hit` — one row per `(table, index)` use. `blob2`=table, `blob3`=index. */
4
- indexHit: { event: "lunora.index.hit", index: "blob3", table: "blob2" },
5
- /** `lunora.shard.request` — one row per shard dispatch. `blob2`=shardKey, `blob3`=group. */
6
- shardRequest: { event: "lunora.shard.request", group: "blob3", shardKey: "blob2" },
7
- /** `lunora.table.scan` — one row per full-scan. `blob2`=table. */
8
- tableScan: { event: "lunora.table.scan", table: "blob2" }
9
- };
10
- const toCount = (value) => {
11
- const numeric = typeof value === "number" ? value : Number(value);
12
- return Number.isFinite(numeric) ? numeric : 0;
13
- };
14
- const toText = (value) => {
15
- if (typeof value === "string") {
16
- return value;
17
- }
18
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
19
- return String(value);
20
- }
21
- return "";
22
- };
23
- const assertDataset = (dataset) => {
24
- if (!DATASET_NAME_PATTERN.test(dataset)) {
25
- throw new Error(`@lunora/advisor: invalid Analytics Engine dataset name "${dataset}" — expected a bare table identifier.`);
26
- }
27
- };
28
- const sqlString = (value) => `'${value.replaceAll("\\", "\\\\").replaceAll("'", "''")}'`;
29
- const queryOrEmpty = async (source, sql) => {
30
- try {
31
- const result = await source.query(sql);
32
- return result.rows;
33
- } catch {
34
- return [];
35
- }
36
- };
37
- const loadShardTraffic = async (source, options) => {
38
- const { event, group, shardKey } = AE_METRIC_EVENTS.shardRequest;
39
- const groupFilter = options.group === void 0 ? "" : ` AND ${group} = ${sqlString(options.group)}`;
40
- const sql = `SELECT ${shardKey} AS shardKey, ${group} AS shardGroup, sum(_sample_interval) AS requests FROM ${options.dataset} WHERE blob1 = ${sqlString(event)}${groupFilter} GROUP BY shardKey, shardGroup`;
41
- const rows = await queryOrEmpty(source, sql);
42
- return rows.map((row) => {
43
- const shardGroup = toText(row.shardGroup);
44
- return {
45
- ...shardGroup === "" ? {} : { group: shardGroup },
46
- requests: toCount(row.requests),
47
- shardKey: toText(row.shardKey)
48
- };
49
- });
50
- };
51
- const loadTableScans = async (source, options) => {
52
- const { event, table } = AE_METRIC_EVENTS.tableScan;
53
- const sql = `SELECT ${table} AS scanTable, sum(_sample_interval) AS scans FROM ${options.dataset} WHERE blob1 = ${sqlString(event)} GROUP BY scanTable`;
54
- const rows = await queryOrEmpty(source, sql);
55
- return rows.map((row) => {
56
- return { scans: toCount(row.scans), table: toText(row.scanTable) };
57
- });
58
- };
59
- const loadIndexHits = async (source, options) => {
60
- const { event, index, table } = AE_METRIC_EVENTS.indexHit;
61
- const sql = `SELECT ${table} AS hitTable, ${index} AS hitIndex, sum(_sample_interval) AS reads FROM ${options.dataset} WHERE blob1 = ${sqlString(event)} GROUP BY hitTable, hitIndex`;
62
- const rows = await queryOrEmpty(source, sql);
63
- const hits = rows.map((row) => {
64
- return { index: toText(row.hitIndex), reads: toCount(row.reads), table: toText(row.hitTable) };
65
- });
66
- if (options.declaredIndexes === void 0) {
67
- return hits;
68
- }
69
- const seen = new Set(hits.map((hit) => `${hit.table}\0${hit.index}`));
70
- const zeros = options.declaredIndexes.filter((declared) => !seen.has(`${declared.table}\0${declared.index}`)).map((declared) => {
71
- return { index: declared.index, reads: 0, table: declared.table };
72
- });
73
- return [...hits, ...zeros];
74
- };
75
- const loadAnalyticsRuntimeMetrics = async (source, options) => {
76
- assertDataset(options.dataset);
77
- const [shardTraffic, tableScans, indexHits] = await Promise.all([
78
- loadShardTraffic(source, options),
79
- loadTableScans(source, options),
80
- loadIndexHits(source, options)
81
- ]);
82
- return { indexHits, shardTraffic, tableScans };
83
- };
84
-
85
- export { AE_METRIC_EVENTS, loadAnalyticsRuntimeMetrics };
@@ -1,33 +0,0 @@
1
- import { e as emit } from './finding-Dm_zvzS1.mjs';
2
-
3
- const adminRouteWithoutGuard = {
4
- categories: ["SECURITY"],
5
- description: "An `httpRoute` on an admin/privileged path has no visible auth/admin guard. REST routes aren't covered by RLS, so an unguarded `/admin/*` route is callable by anyone who reaches the URL.",
6
- facing: "EXTERNAL",
7
- level: "WARN",
8
- name: "admin_route_without_guard",
9
- remediation: "Assert an authenticated, authorized caller at the top of the handler — check `ctx.auth` / `getSession(...)`, or a `requireAdmin`-style guard — and reject (401/403) before doing privileged work. For machine callers, verify a secret with a timing-safe compare.",
10
- run: (context) => {
11
- if (context.adminRoutes === void 0) {
12
- return [];
13
- }
14
- const findings = [];
15
- for (const route of context.adminRoutes) {
16
- if (route.usesGuard) {
17
- continue;
18
- }
19
- findings.push(
20
- emit(adminRouteWithoutGuard, {
21
- cacheKey: `admin_route_without_guard:${route.file}:${route.method}:${route.path}`,
22
- detail: `Route \`${route.method} ${route.path}\` (\`${route.exportName}\` in ${route.file}) is on an admin/privileged path but its handler shows no auth/admin guard. Assert an authorized caller before doing privileged work.`,
23
- metadata: { exportName: route.exportName, file: route.file, method: route.method, path: route.path }
24
- })
25
- );
26
- }
27
- return findings;
28
- },
29
- source: "static",
30
- title: "Admin route without an auth guard"
31
- };
32
-
33
- export { adminRouteWithoutGuard as default };
@@ -1,38 +0,0 @@
1
- import { e as emit } from './finding-Dm_zvzS1.mjs';
2
-
3
- const authApiCallWithoutHeaders = {
4
- categories: ["SECURITY"],
5
- description: "A `ctx.authApi.<method>(...)` call omits `headers` — better-auth skips session authorization and runs the call with full server-to-server privileges, regardless of the caller's identity.",
6
- facing: "EXTERNAL",
7
- level: "WARN",
8
- name: "auth_api_call_without_headers",
9
- remediation: "Pass the inbound `headers` from the incoming request into every `ctx.authApi.*` call: `ctx.authApi.<method>({ body, headers: request.headers })`. See the `withAuthPlugins` middleware doc for details.",
10
- run: (context) => {
11
- if (context.authApiCalls === void 0) {
12
- return [];
13
- }
14
- const findings = [];
15
- const occurrenceCount = /* @__PURE__ */ new Map();
16
- for (const call of context.authApiCalls) {
17
- if (call.hasHeaders) {
18
- continue;
19
- }
20
- const baseKey = `${call.file}:${call.line.toString()}:${call.method}`;
21
- const occurrence = (occurrenceCount.get(baseKey) ?? 0) + 1;
22
- occurrenceCount.set(baseKey, occurrence);
23
- const occurrenceSuffix = occurrence > 1 ? `:${occurrence.toString()}` : "";
24
- findings.push(
25
- emit(authApiCallWithoutHeaders, {
26
- cacheKey: `auth_api_call_without_headers:${baseKey}${occurrenceSuffix}`,
27
- detail: `\`ctx.authApi.${call.method || "<method>"}(…)\` in ${call.exportName} (${call.file}:${call.line.toString()}) is called without \`headers\` — better-auth skips session authorization, so this runs with full privileges. Pass the inbound \`headers\`.`,
28
- metadata: { exportName: call.exportName, file: call.file, line: call.line, method: call.method }
29
- })
30
- );
31
- }
32
- return findings;
33
- },
34
- source: "static",
35
- title: "Privileged ctx.authApi call missing headers"
36
- };
37
-
38
- export { authApiCallWithoutHeaders as default };
@@ -1,84 +0,0 @@
1
- import { e as emit } from './finding-Dm_zvzS1.mjs';
2
-
3
- const circularFk = {
4
- categories: ["SCHEMA"],
5
- description: "A chain of foreign-key relations forms a cycle (e.g. A → B → C → A). Circular FK dependencies can cause unexpected behavior during DELETE operations — a CASCADE chain may loop indefinitely, and even a RESTRICT cycle prevents deletion of any row in the loop without temporarily disabling constraints.",
6
- facing: "INTERNAL",
7
- level: "WARN",
8
- name: "circular_fk",
9
- remediation: "Remove or break the cycle by dropping at least one FK relation from the loop. Consider replacing the circular dependency with a nullable FK and explicit application logic, or restructure the schema using a junction table.",
10
- run: (context) => {
11
- const findings = [];
12
- const edges = /* @__PURE__ */ new Map();
13
- for (const table of context.schema.tables) {
14
- for (const relation of table.relations) {
15
- if (relation.kind !== "one") {
16
- continue;
17
- }
18
- let targets = edges.get(table.name);
19
- if (targets === void 0) {
20
- targets = /* @__PURE__ */ new Set();
21
- edges.set(table.name, targets);
22
- }
23
- targets.add(relation.table);
24
- }
25
- }
26
- const onStack = /* @__PURE__ */ new Set();
27
- const reported = /* @__PURE__ */ new Set();
28
- const reportBackEdge = (neighbor, path) => {
29
- const cycleStart = path.indexOf(neighbor);
30
- if (cycleStart === -1) {
31
- return;
32
- }
33
- const cycle = path.slice(cycleStart);
34
- if (cycle.length < 2) {
35
- return;
36
- }
37
- let minIndex = 0;
38
- for (let index = 1; index < cycle.length; index += 1) {
39
- if (cycle[index] < cycle[minIndex]) {
40
- minIndex = index;
41
- }
42
- }
43
- const canonical = [...cycle.slice(minIndex), ...cycle.slice(0, minIndex)];
44
- const key = canonical.join("→");
45
- if (reported.has(key)) {
46
- return;
47
- }
48
- reported.add(key);
49
- const displayPath = [...canonical, canonical[0]].join(" → ");
50
- findings.push(
51
- emit(circularFk, {
52
- cacheKey: `circular_fk:${key}`,
53
- detail: `Circular foreign-key dependency detected: ${displayPath}. This cycle can cause unexpected behavior during DELETE operations.`,
54
- metadata: {
55
- cycle: canonical,
56
- path: displayPath,
57
- tables: canonical
58
- }
59
- })
60
- );
61
- };
62
- const dfs = (node, path) => {
63
- onStack.add(node);
64
- path.push(node);
65
- for (const neighbor of edges.get(node) ?? []) {
66
- if (onStack.has(neighbor)) {
67
- reportBackEdge(neighbor, path);
68
- } else {
69
- dfs(neighbor, path);
70
- }
71
- }
72
- path.pop();
73
- onStack.delete(node);
74
- };
75
- for (const table of context.schema.tables) {
76
- dfs(table.name, []);
77
- }
78
- return findings;
79
- },
80
- source: "static",
81
- title: "Circular foreign-key dependency"
82
- };
83
-
84
- export { circularFk as default };