@stacksjs/ts-cloud 0.16.49 → 0.16.50

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 (208) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-z8k9mcn5.js → chunk-0wtshht7.js} +2 -2
  3. package/dist/bin/{chunk-v7t6f8aw.js → chunk-11y7yang.js} +2 -2
  4. package/dist/bin/chunk-2wh45zhk.js +2 -0
  5. package/dist/bin/chunk-334jngt2.js +1 -0
  6. package/dist/bin/{chunk-4yym8xm4.js → chunk-33ntxz01.js} +5 -5
  7. package/dist/bin/chunk-3k7y1h18.js +1 -0
  8. package/dist/bin/chunk-512ecg6y.js +1 -0
  9. package/dist/bin/{chunk-vhyp4xj0.js → chunk-5ny7rggt.js} +1 -1
  10. package/dist/bin/chunk-626npmtj.js +1 -0
  11. package/dist/bin/{chunk-zvbc92pc.js → chunk-734n0gkw.js} +1 -1
  12. package/dist/bin/chunk-74wppexz.js +1 -0
  13. package/dist/bin/chunk-7cs9nnjy.js +111 -0
  14. package/dist/bin/{chunk-q4dywv80.js → chunk-7czb1kgg.js} +2 -2
  15. package/dist/bin/chunk-7ewbxsan.js +1 -0
  16. package/dist/bin/{chunk-ynwbzsz8.js → chunk-7jj0g6jk.js} +158 -158
  17. package/dist/bin/{chunk-kbwm0sqv.js → chunk-811k54jq.js} +2 -2
  18. package/dist/bin/chunk-8ya34jz7.js +1 -0
  19. package/dist/bin/chunk-964xmgb6.js +1 -0
  20. package/dist/bin/{chunk-gyvkravq.js → chunk-9ehb4hc6.js} +5 -5
  21. package/dist/bin/chunk-azarn24c.js +1 -0
  22. package/dist/bin/chunk-cw3rhg1c.js +1 -0
  23. package/dist/bin/chunk-d2fq60kd.js +1 -0
  24. package/dist/bin/{chunk-01w4zbex.js → chunk-da6dmacg.js} +2 -2
  25. package/dist/bin/chunk-dpk5r544.js +1 -0
  26. package/dist/bin/{chunk-12x968en.js → chunk-dv2he3vc.js} +3 -3
  27. package/dist/bin/chunk-e6ewfmbp.js +1 -0
  28. package/dist/bin/{chunk-psmpw0ap.js → chunk-e7pce8jb.js} +3 -3
  29. package/dist/bin/{chunk-cf3jn2ey.js → chunk-f2t67d76.js} +3 -3
  30. package/dist/bin/chunk-f4mpkpbf.js +1 -0
  31. package/dist/bin/chunk-f9469h6q.js +1 -0
  32. package/dist/bin/chunk-fjbhvhqb.js +1 -0
  33. package/dist/bin/{chunk-nj9x0tb8.js → chunk-gr1ra9nj.js} +2 -2
  34. package/dist/bin/{chunk-3pazrfsf.js → chunk-hdqxyxs0.js} +7 -7
  35. package/dist/bin/{chunk-xdk0gmxt.js → chunk-hhmqsrfc.js} +1 -1
  36. package/dist/bin/{chunk-4mecfcjk.js → chunk-j2wkxp7d.js} +3 -3
  37. package/dist/bin/{chunk-dj03v81n.js → chunk-k9f94hg4.js} +113 -113
  38. package/dist/bin/{chunk-znd507q9.js → chunk-kmpvqby6.js} +8 -8
  39. package/dist/bin/{chunk-n7yefy09.js → chunk-m3xap663.js} +5 -5
  40. package/dist/bin/chunk-m7pbssep.js +1 -0
  41. package/dist/{chunk-6rcj3km0.js → bin/chunk-mcg4wg4j.js} +7 -7
  42. package/dist/bin/{chunk-03gqra5e.js → chunk-mdkd46c5.js} +83 -83
  43. package/dist/bin/chunk-n7xadeqe.js +1 -0
  44. package/dist/bin/{chunk-xe527q1k.js → chunk-ppd463ev.js} +2 -2
  45. package/dist/bin/{chunk-23m8kbwh.js → chunk-q2rqmc2x.js} +3 -3
  46. package/dist/bin/chunk-q9awn1n3.js +1 -0
  47. package/dist/bin/chunk-qsfhb3x7.js +1 -0
  48. package/dist/bin/chunk-r524t8v8.js +1 -0
  49. package/dist/bin/{chunk-7qbxq0be.js → chunk-rwbdtxte.js} +1 -1
  50. package/dist/bin/{chunk-v09tfezh.js → chunk-sa9c8vb5.js} +5 -5
  51. package/dist/bin/{chunk-6y6g726g.js → chunk-t970yjvz.js} +5 -5
  52. package/dist/bin/{chunk-cz2wq0tf.js → chunk-tcj1z34y.js} +5 -5
  53. package/dist/bin/{chunk-q8b77zgw.js → chunk-te52z1wk.js} +1 -1
  54. package/dist/bin/chunk-v2qk9jeb.js +1 -0
  55. package/dist/bin/{chunk-rdkr74y2.js → chunk-vavwhhrp.js} +1 -1
  56. package/dist/bin/chunk-w89fyres.js +1 -0
  57. package/dist/bin/{chunk-frzpqsbj.js → chunk-we2raqk3.js} +2 -2
  58. package/dist/bin/chunk-wgh66c5r.js +1 -0
  59. package/dist/bin/chunk-xaqkj8fn.js +1 -0
  60. package/dist/bin/{chunk-w29z877b.js → chunk-y12vn1h1.js} +2 -2
  61. package/dist/bin/{chunk-xx9mrcfs.js → chunk-yfa84s0c.js} +1 -1
  62. package/dist/bin/{chunk-5nmt4s5w.js → chunk-ytzcsskk.js} +2 -2
  63. package/dist/bin/{chunk-psvqpztv.js → chunk-z06jkvvr.js} +5 -5
  64. package/dist/bin/cli.js +203 -203
  65. package/dist/bin/dashboard-server.js +1 -1
  66. package/dist/chunk-09d6pdgx.js +1 -0
  67. package/dist/{chunk-yme6q7k4.js → chunk-0cz2s19h.js} +2 -2
  68. package/dist/{chunk-nryh43p1.js → chunk-0qgfe5ff.js} +3 -3
  69. package/dist/{chunk-kr8aeva1.js → chunk-18h7na1g.js} +549 -549
  70. package/dist/chunk-21mmcmm7.js +1 -0
  71. package/dist/{bin/chunk-k343q24p.js → chunk-3ncnrrvm.js} +7 -7
  72. package/dist/chunk-4abbccq7.js +2 -0
  73. package/dist/{chunk-rpng90t9.js → chunk-4yqd62rd.js} +1 -1
  74. package/dist/chunk-5hgcr7r2.js +709 -0
  75. package/dist/{chunk-x0ep5ybv.js → chunk-6m8p1n88.js} +13 -13
  76. package/dist/chunk-85fyadq0.js +448 -0
  77. package/dist/{chunk-fpkpwbv3.js → chunk-8b2mxhcm.js} +5 -5
  78. package/dist/{chunk-r3m1fjd4.js → chunk-9ggg2ktx.js} +2 -2
  79. package/dist/chunk-a8hs75xd.js +5 -0
  80. package/dist/chunk-ca191b00.js +6 -0
  81. package/dist/{chunk-jhtp3m31.js → chunk-cpba1hz2.js} +2 -2
  82. package/dist/{chunk-ynprwawa.js → chunk-erfh93dq.js} +2 -2
  83. package/dist/{chunk-22hfejjs.js → chunk-ffyx50xx.js} +1 -1
  84. package/dist/chunk-fqgvackc.js +138 -0
  85. package/dist/{chunk-jpdpr7k6.js → chunk-j99nkav5.js} +3 -3
  86. package/dist/chunk-jgsey18z.js +1 -0
  87. package/dist/{chunk-vb4t2r4r.js → chunk-jtvw9d4x.js} +1 -1
  88. package/dist/chunk-jytama4e.js +111 -0
  89. package/dist/chunk-m9r0a1v9.js +2 -0
  90. package/dist/{chunk-6mp1fyxe.js → chunk-nmnf1ha6.js} +4 -4
  91. package/dist/{chunk-e8k29wen.js → chunk-nnnhq6sx.js} +19 -19
  92. package/dist/chunk-qbsrs1gp.js +1 -0
  93. package/dist/{chunk-xzcpzxtj.js → chunk-qcj3hkba.js} +2 -2
  94. package/dist/chunk-r4kedmas.js +1 -0
  95. package/dist/{chunk-p7myt05d.js → chunk-r5mk071y.js} +5 -5
  96. package/dist/{chunk-xxq1ygp9.js → chunk-thdfk76k.js} +3 -3
  97. package/dist/chunk-tnqj2en4.js +1 -0
  98. package/dist/{chunk-da62knsv.js → chunk-zbx9yehq.js} +83 -83
  99. package/dist/{chunk-vjph4eh0.js → chunk-zf5wdx6v.js} +1 -1
  100. package/dist/deploy/index.js +1 -1
  101. package/dist/dns/index.js +1 -1
  102. package/dist/drivers/aws/provision.d.ts +2 -2
  103. package/dist/drivers/index.js +1 -1
  104. package/dist/drivers/shared/mail-provision.d.ts +2 -18
  105. package/dist/drivers/shared/rpx-gateway.d.ts +3 -1
  106. package/dist/index.js +60 -60
  107. package/dist/mail/index.d.ts +5 -0
  108. package/dist/mail/index.js +3 -0
  109. package/dist/mail/webmail.d.ts +35 -0
  110. package/dist/mail/webmail.test.d.ts +1 -0
  111. package/dist/operations/index.js +1 -1
  112. package/dist/protection/index.js +1 -1
  113. package/dist/spend/index.js +1 -1
  114. package/dist/ui/404.html +1 -1
  115. package/dist/ui/accept-invitation.html +1 -1
  116. package/dist/ui/access-denied.html +1 -1
  117. package/dist/ui/account/automation.html +6 -6
  118. package/dist/ui/account/security.html +2 -2
  119. package/dist/ui/applications/compose.html +5 -5
  120. package/dist/ui/applications/new.html +2 -2
  121. package/dist/ui/data/backups.html +6 -6
  122. package/dist/ui/data/services.html +6 -6
  123. package/dist/ui/data/volumes.html +6 -6
  124. package/dist/ui/index.html +6 -6
  125. package/dist/ui/infrastructure/topology.html +6 -6
  126. package/dist/ui/integrations.html +2 -2
  127. package/dist/ui/operations/alerts.html +6 -6
  128. package/dist/ui/operations/configuration.html +6 -6
  129. package/dist/ui/operations/jobs.html +6 -6
  130. package/dist/ui/operations/maintenance.html +6 -6
  131. package/dist/ui/operations/observability.html +6 -6
  132. package/dist/ui/operations/previews.html +6 -6
  133. package/dist/ui/operations/queue.html +6 -6
  134. package/dist/ui/operations/regions.html +6 -6
  135. package/dist/ui/operations/releases.html +6 -6
  136. package/dist/ui/operations/spend.html +6 -6
  137. package/dist/ui/operations/workloads.html +6 -6
  138. package/dist/ui/security.html +1 -1
  139. package/dist/ui/server/actions.html +6 -6
  140. package/dist/ui/server/activity.html +2 -2
  141. package/dist/ui/server/capacity.html +6 -6
  142. package/dist/ui/server/database.html +6 -6
  143. package/dist/ui/server/deployments.html +6 -6
  144. package/dist/ui/server/diagnostics.html +2 -2
  145. package/dist/ui/server/firewall.html +6 -6
  146. package/dist/ui/server/fleet.html +6 -6
  147. package/dist/ui/server/logs.html +5 -5
  148. package/dist/ui/server/metrics.html +6 -6
  149. package/dist/ui/server/security.html +1 -1
  150. package/dist/ui/server/services.html +1 -1
  151. package/dist/ui/server/sites.html +6 -6
  152. package/dist/ui/server/ssh-keys.html +6 -6
  153. package/dist/ui/server/team.html +5 -5
  154. package/dist/ui/server/terminal.html +2 -2
  155. package/dist/ui/serverless/alarms.html +6 -6
  156. package/dist/ui/serverless/assets.html +2 -2
  157. package/dist/ui/serverless/cost.html +2 -2
  158. package/dist/ui/serverless/data.html +6 -6
  159. package/dist/ui/serverless/deployments.html +2 -2
  160. package/dist/ui/serverless/firewall.html +2 -2
  161. package/dist/ui/serverless/functions.html +6 -6
  162. package/dist/ui/serverless/logs.html +6 -6
  163. package/dist/ui/serverless/metrics.html +2 -2
  164. package/dist/ui/serverless/queues.html +6 -6
  165. package/dist/ui/serverless/secrets.html +6 -6
  166. package/dist/ui/serverless/traces.html +6 -6
  167. package/dist/ui/serverless.html +6 -6
  168. package/package.json +7 -3
  169. package/dist/bin/chunk-1fj03993.js +0 -1
  170. package/dist/bin/chunk-1xxmyx0r.js +0 -1
  171. package/dist/bin/chunk-2pzh0wxc.js +0 -1
  172. package/dist/bin/chunk-45qr2bd3.js +0 -1
  173. package/dist/bin/chunk-4nn00brw.js +0 -1
  174. package/dist/bin/chunk-52w33yma.js +0 -1
  175. package/dist/bin/chunk-5f1n5d80.js +0 -1
  176. package/dist/bin/chunk-5mm6qn6m.js +0 -1
  177. package/dist/bin/chunk-5xr76cms.js +0 -1
  178. package/dist/bin/chunk-65yvjecx.js +0 -2
  179. package/dist/bin/chunk-d0tmmzy5.js +0 -1
  180. package/dist/bin/chunk-fqghdpvr.js +0 -1
  181. package/dist/bin/chunk-gkdr09xx.js +0 -1
  182. package/dist/bin/chunk-hhhrze6m.js +0 -1
  183. package/dist/bin/chunk-jrztbsnb.js +0 -1
  184. package/dist/bin/chunk-kqxk1pds.js +0 -1
  185. package/dist/bin/chunk-m8p7mw67.js +0 -1
  186. package/dist/bin/chunk-n2c6y0k1.js +0 -1
  187. package/dist/bin/chunk-pr1dg1km.js +0 -1
  188. package/dist/bin/chunk-pzj1ac7x.js +0 -1
  189. package/dist/bin/chunk-rgcrsd5m.js +0 -1
  190. package/dist/bin/chunk-thph4z3k.js +0 -1
  191. package/dist/bin/chunk-txykq6f1.js +0 -1
  192. package/dist/bin/chunk-vjg2fymw.js +0 -1
  193. package/dist/bin/chunk-ym9h629y.js +0 -111
  194. package/dist/bin/chunk-z8scg2vy.js +0 -1
  195. package/dist/bin/chunk-zjvg5pg8.js +0 -1
  196. package/dist/chunk-25sw2s70.js +0 -1
  197. package/dist/chunk-2pns2rkf.js +0 -111
  198. package/dist/chunk-2sc0s7pc.js +0 -6
  199. package/dist/chunk-7v7dwev4.js +0 -584
  200. package/dist/chunk-bdv3gpzb.js +0 -709
  201. package/dist/chunk-fh7apa5n.js +0 -2
  202. package/dist/chunk-gh0ghb21.js +0 -2
  203. package/dist/chunk-gqadvddh.js +0 -1
  204. package/dist/chunk-kpmxvpcv.js +0 -1
  205. package/dist/chunk-ksqhsz52.js +0 -1
  206. package/dist/chunk-p588apka.js +0 -1
  207. package/dist/chunk-vnarc5gc.js +0 -5
  208. package/dist/chunk-x7d93rxb.js +0 -1
@@ -1,4 +1,4 @@
1
- import{A}from"./chunk-dj03v81n.js";var ae=["project:read","config:read","config:write","deployments:read","deployments:create","deployments:cancel","deployments:rollback","runtime:read","runtime:restart","runtime:logs","runtime:terminal","data:read","data:write","data:admin","backups:read","backups:create","backups:restore","secrets:read","secrets:write","fleet:read","fleet:manage","users:read","users:manage","users:transfer-ownership","audit:read","billing:read","billing:manage","security:read","security:manage","security:waive","sources:read","sources:manage","applications:read","applications:manage","automation:read","automation:manage","tags:manage"],K=["project:read","config:read","deployments:read","runtime:read","runtime:logs","data:read","backups:read","security:read","sources:read","applications:read","billing:read"],oe={owner:new Set(ae),admin:new Set(ae.filter((e)=>e!=="users:transfer-ownership")),deployer:new Set([...K,"deployments:create","deployments:cancel","deployments:rollback","sources:manage","applications:manage"]),operator:new Set([...K,"runtime:restart","backups:create","security:manage","sources:manage","applications:manage"]),viewer:new Set(K),auditor:new Set(["project:read","config:read","deployments:read","runtime:read","data:read","backups:read","audit:read","security:read","sources:read","applications:read"])};function fn(e){return oe[e]}function P(e,t){if(e.type==="organization")return e.id===void 0||e.id===t.organizationId;if(!e.id)return!1;if(e.type==="project")return e.id===t.projectId;if(e.type==="environment")return e.id===t.environmentId;return e.id===t.resourceId}function re(e){let{membership:t,capability:r,target:i}=e;if(!t||t.status!=="active"||t.organizationId!==i.organizationId)return{allowed:!1,reason:"inactive-membership"};let a=e.grants.filter((s)=>s.organizationId===i.organizationId&&s.membershipId===t.id&&s.capability===r&&P(s.scope,i)),E=a.find((s)=>s.effect==="deny");if(E)return{allowed:!1,reason:"explicit-deny",inheritedFrom:{kind:"grant",id:E.id,scope:E.scope}};let T=a.find((s)=>s.effect==="allow");if(T)return{allowed:!0,reason:"explicit-allow",inheritedFrom:{kind:"grant",id:T.id,scope:T.scope}};if(!P(t.scope,i))return{allowed:!1,reason:"scope-mismatch"};if(fn(t.roleTemplate).has(r))return{allowed:!0,reason:"role-template",inheritedFrom:{kind:"membership",id:t.id,scope:t.scope}};return{allowed:!1,reason:"missing-capability"}}function hn(e){return ae.filter((t)=>re({...e,capability:t}).allowed)}import{createHash as S,randomBytes as Te}from"node:crypto";import{chmodSync as H,existsSync as Z,mkdirSync as se,statSync as de}from"node:fs";import{dirname as ee}from"node:path";import{Database as Ne}from"bun:sqlite";var l=40,j=[{version:1,name:"core_control_plane",sql:`
1
+ import{A}from"./chunk-k9f94hg4.js";var l=40,K=[{version:1,name:"core_control_plane",sql:`
2
2
  CREATE TABLE projects (
3
3
  id TEXT PRIMARY KEY,
4
4
  slug TEXT NOT NULL UNIQUE,
@@ -1475,26 +1475,26 @@ import{A}from"./chunk-dj03v81n.js";var ae=["project:read","config:read","config:
1475
1475
  -- once a minute, forever.
1476
1476
  CREATE INDEX telemetry_kind_scope_time_idx
1477
1477
  ON telemetry_records(project_id, kind, timestamp);
1478
- `}];class p extends Error{constructor(e,t,r){super(`${e} ${t} changed since version ${r}`);this.name="OptimisticConcurrencyError"}}class x extends Error{constructor(e,t){super(`Operation cannot transition from ${e} to ${t}`);this.name="InvalidOperationTransitionError"}}class I extends Error{constructor(e,t){super(`Control-plane schema version ${e} is newer than supported version ${t}`);this.name="UnsupportedSchemaVersionError"}}var te=65536,q=16384,ce=["succeeded","failed","cancelled","timed_out"],Le={queued:["running","cancelled","timed_out"],running:["queued","succeeded","failed","cancelled","timed_out"],succeeded:[],failed:["queued"],cancelled:["queued"],timed_out:["queued"]},_e=/(?:^|_)(?:authorization|cookie|credential|password|passwd|secret|token|api_?key|private_?key|access_?key)(?:$|_)/i,ie=/(?:authorization|password|secret|token|api[_-]?key|private[_-]?key|access[_-]?key)\s*[=:]\s*[^\s,;]+/gi;function _(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function d(e){return typeof e==="string"?e:void 0}function G(e,t){if(t&&_e.test(t))return"[REDACTED]";if(e===null||typeof e==="boolean"||typeof e==="number")return e;if(typeof e==="string")return e.replace(ie,"[REDACTED]");if(Array.isArray(e))return e.map((r)=>G(r));if(e&&typeof e==="object"){let r={};for(let[i,a]of Object.entries(e))r[i]=G(a,i);return r}return String(e??"")}function h(e,t=te){let r=G(e),i=JSON.stringify(r);if(Buffer.byteLength(i)<=t)return r;return{truncated:!0,originalBytes:Buffer.byteLength(i),preview:i.slice(0,Math.max(0,t-128))}}function N(e){return JSON.stringify(h(e))}function M(e){if(!e)return;let t=e.replace(ie,"[REDACTED]");return Buffer.byteLength(t)<=q?t:`${t.slice(0,q-24)}
1479
- [output truncated]`}function v(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),description:d(e.description),organizationId:d(e.organization_id),desiredConfigHash:d(e.desired_config_hash),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function D(e){return{id:String(e.id),projectId:String(e.project_id),slug:String(e.slug),name:String(e.name),kind:String(e.kind),region:d(e.region),desiredState:_(e.desired_state),discoveredState:_(e.discovered_state),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function y(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:d(e.environment_id),kind:String(e.kind),slug:String(e.slug),name:String(e.name),provider:d(e.provider),providerId:d(e.provider_id),desiredState:_(e.desired_state),discoveredState:_(e.discovered_state),metadata:_(e.metadata),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function f(e){return{id:String(e.id),kind:String(e.kind),externalId:d(e.external_id),displayName:String(e.display_name),metadata:_(e.metadata),disabledAt:d(e.disabled_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function u(e){return{id:String(e.id),projectId:d(e.project_id),environmentId:d(e.environment_id),resourceId:d(e.resource_id),actorId:d(e.actor_id),kind:String(e.kind),state:String(e.state),correlationId:String(e.correlation_id),idempotencyKey:d(e.idempotency_key),input:_(e.input),output:_(e.output),error:d(e.error),attempt:Number(e.attempt),priority:Number(e.priority),leaseOwner:d(e.lease_owner),leaseExpiresAt:d(e.lease_expires_at),cancelRequestedAt:d(e.cancel_requested_at),startedAt:d(e.started_at),finishedAt:d(e.finished_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Y(e){return{id:String(e.id),sequence:Number(e.sequence),organizationId:d(e.organization_id),projectId:d(e.project_id),operationId:d(e.operation_id),resourceId:d(e.resource_id),actorId:d(e.actor_id),correlationId:String(e.correlation_id),type:String(e.type),level:String(e.level),payload:_(e.payload),createdAt:String(e.created_at)}}function O(e){return{id:String(e.id),projectId:String(e.project_id),name:String(e.name),normalizedName:String(e.normalized_name),color:String(e.color),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function b(e){return{id:String(e.id),actorKey:String(e.actor_key),name:String(e.name),routeId:String(e.route_id),query:_(e.query),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function F(e){return{actorKey:String(e.actor_key),entityType:String(e.entity_type),entityId:String(e.entity_id),favorite:Number(e.favorite)===1,lastVisitedAt:String(e.last_visited_at),visitCount:Number(e.visit_count)}}function z(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function B(e){let t=String(e.scope_type);return{type:t,...t==="organization"?{}:{id:String(e.scope_id)}}}function k(e){return{id:String(e.id),organizationId:String(e.organization_id),actorId:String(e.actor_id),roleTemplate:String(e.role_template),scope:B(e),source:String(e.source??"manual"),status:String(e.status),sessionVersion:Number(e.session_version),lastActiveAt:d(e.last_active_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function R(e,t){let r=d(e.accepted_at),i=d(e.revoked_at),a=String(e.expires_at),E=i?"revoked":r?"accepted":a<=t?"expired":"pending";return{id:String(e.id),organizationId:String(e.organization_id),email:String(e.email),roleTemplate:String(e.role_template),scope:B(e),invitedByActorId:d(e.invited_by_actor_id),acceptedByActorId:d(e.accepted_by_actor_id),expiresAt:a,acceptedAt:r,revokedAt:i,state:E,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function w(e){return{id:String(e.id),organizationId:String(e.organization_id),membershipId:String(e.membership_id),effect:String(e.effect),capability:String(e.capability),scope:B(e),source:String(e.source??"manual"),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function g(e){return{type:e.type,id:e.id??null}}function le(e){return Array.from({length:e},()=>"?").join(", ")}function o(e,t,r){return e.run(t,r)}class Or{path;database;nowFn;idFn;constructor(e={}){this.path=e.path??A(e.cwd??process.cwd(),"control-plane.sqlite"),this.nowFn=e.now??(()=>new Date),this.idFn=e.id??(()=>crypto.randomUUID());let t=this.path===":memory:";if(!t){se(ee(this.path),{recursive:!0,mode:448});try{H(ee(this.path),448)}catch{}}if(this.database=new Ne(this.path,{create:!0,strict:!0}),this.database.run("PRAGMA foreign_keys = ON"),this.database.run(`PRAGMA busy_timeout = ${Math.max(100,e.busyTimeoutMs??5000)}`),!t)this.database.run("PRAGMA journal_mode = WAL"),this.database.run("PRAGMA synchronous = NORMAL");if(this.migrate(),!t)this.secureDatabaseFiles()}now(){return this.nowFn().toISOString()}secureDatabaseFiles(){for(let e of[this.path,`${this.path}-wal`,`${this.path}-shm`]){if(!Z(e))continue;try{H(e,384)}catch{}}}backupTo(e){this.database.run("VACUUM INTO ?",[e]);try{H(e,384)}catch{}}migrate(){let e=this.database.query("PRAGMA user_version").get(),t=Number(e?.user_version??0);if(t>l)throw new I(t,l);if(t===l)return;let r;if(t>0&&this.path!==":memory:")r=`${this.path}.v${t}.${Date.now()}.bak`,this.backupTo(r);try{if(this.database.transaction(()=>{for(let a of j){if(a.version<=t)continue;this.database.run(a.sql),o(this.database,"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",[a.version,a.name,this.now()]),this.database.run(`PRAGMA user_version = ${a.version}`)}}).exclusive(),r)this.setSetting("storage.last_backup",{path:r,createdAt:this.now(),reason:"pre-migration"})}catch(i){let a=r?` Restore from ${r}.`:"";throw Error(`Control-plane migration from schema ${t} failed.${a} ${i instanceof Error?i.message:String(i)}`)}}close(){if(this.path!==":memory:")this.secureDatabaseFiles();this.database.close()}transaction(e){return this.database.transaction(e).immediate()}createProject(e){let t=e.id??this.idFn(),r=this.now();return o(this.database,"INSERT INTO projects (id, slug, name, description, organization_id, desired_config_hash, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[t,e.slug,e.name,e.description??null,e.organizationId??null,e.desiredConfigHash??null,r,r]),this.getProject(t)}getProject(e){let t=this.database.query("SELECT * FROM projects WHERE id = ?").get(e);return t?v(t):void 0}getProjectBySlug(e){let t=this.database.query("SELECT * FROM projects WHERE slug = ?").get(e);return t?v(t):void 0}listProjects(){return this.database.query("SELECT * FROM projects ORDER BY name COLLATE NOCASE, id").all().map(v)}updateProject(e,t,r){let i=this.getProject(e);if(!i||i.version!==t)throw new p("Project",e,t);if(o(this.database,`UPDATE projects SET name = ?, description = ?, organization_id = ?, desired_config_hash = ?, version = version + 1, updated_at = ?
1478
+ `}];import{createHash as S,randomBytes as oe}from"node:crypto";import{chmodSync as H,existsSync as Z,mkdirSync as Te,statSync as se}from"node:fs";import{dirname as ee}from"node:path";import{Database as de}from"bun:sqlite";var ce=["project:read","config:read","config:write","deployments:read","deployments:create","deployments:cancel","deployments:rollback","runtime:read","runtime:restart","runtime:logs","runtime:terminal","data:read","data:write","data:admin","backups:read","backups:create","backups:restore","secrets:read","secrets:write","fleet:read","fleet:manage","users:read","users:manage","users:transfer-ownership","audit:read","billing:read","billing:manage","security:read","security:manage","security:waive","sources:read","sources:manage","applications:read","applications:manage","automation:read","automation:manage","tags:manage"],P=["project:read","config:read","deployments:read","runtime:read","runtime:logs","data:read","backups:read","security:read","sources:read","applications:read","billing:read"],Ee={owner:new Set(ce),admin:new Set(ce.filter((e)=>e!=="users:transfer-ownership")),deployer:new Set([...P,"deployments:create","deployments:cancel","deployments:rollback","sources:manage","applications:manage"]),operator:new Set([...P,"runtime:restart","backups:create","security:manage","sources:manage","applications:manage"]),viewer:new Set(P),auditor:new Set(["project:read","config:read","deployments:read","runtime:read","data:read","backups:read","audit:read","security:read","sources:read","applications:read"])};function bn(e){return Ee[e]}function j(e,t){if(e.type==="organization")return e.id===void 0||e.id===t.organizationId;if(!e.id)return!1;if(e.type==="project")return e.id===t.projectId;if(e.type==="environment")return e.id===t.environmentId;return e.id===t.resourceId}function re(e){let{membership:t,capability:r,target:i}=e;if(!t||t.status!=="active"||t.organizationId!==i.organizationId)return{allowed:!1,reason:"inactive-membership"};let a=e.grants.filter((s)=>s.organizationId===i.organizationId&&s.membershipId===t.id&&s.capability===r&&j(s.scope,i)),E=a.find((s)=>s.effect==="deny");if(E)return{allowed:!1,reason:"explicit-deny",inheritedFrom:{kind:"grant",id:E.id,scope:E.scope}};let T=a.find((s)=>s.effect==="allow");if(T)return{allowed:!0,reason:"explicit-allow",inheritedFrom:{kind:"grant",id:T.id,scope:T.scope}};if(!j(t.scope,i))return{allowed:!1,reason:"scope-mismatch"};if(bn(t.roleTemplate).has(r))return{allowed:!0,reason:"role-template",inheritedFrom:{kind:"membership",id:t.id,scope:t.scope}};return{allowed:!1,reason:"missing-capability"}}function Sn(e){return ce.filter((t)=>re({...e,capability:t}).allowed)}class p extends Error{constructor(e,t,r){super(`${e} ${t} changed since version ${r}`);this.name="OptimisticConcurrencyError"}}class x extends Error{constructor(e,t){super(`Operation cannot transition from ${e} to ${t}`);this.name="InvalidOperationTransitionError"}}class I extends Error{constructor(e,t){super(`Control-plane schema version ${e} is newer than supported version ${t}`);this.name="UnsupportedSchemaVersionError"}}var te=65536,q=16384,Ne=["succeeded","failed","cancelled","timed_out"],Le={queued:["running","cancelled","timed_out"],running:["queued","succeeded","failed","cancelled","timed_out"],succeeded:[],failed:["queued"],cancelled:["queued"],timed_out:["queued"]},_e=/(?:^|_)(?:authorization|cookie|credential|password|passwd|secret|token|api_?key|private_?key|access_?key)(?:$|_)/i,ie=/(?:authorization|password|secret|token|api[_-]?key|private[_-]?key|access[_-]?key)\s*[=:]\s*[^\s,;]+/gi;function _(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function d(e){return typeof e==="string"?e:void 0}function G(e,t){if(t&&_e.test(t))return"[REDACTED]";if(e===null||typeof e==="boolean"||typeof e==="number")return e;if(typeof e==="string")return e.replace(ie,"[REDACTED]");if(Array.isArray(e))return e.map((r)=>G(r));if(e&&typeof e==="object"){let r={};for(let[i,a]of Object.entries(e))r[i]=G(a,i);return r}return String(e??"")}function h(e,t=te){let r=G(e),i=JSON.stringify(r);if(Buffer.byteLength(i)<=t)return r;return{truncated:!0,originalBytes:Buffer.byteLength(i),preview:i.slice(0,Math.max(0,t-128))}}function N(e){return JSON.stringify(h(e))}function M(e){if(!e)return;let t=e.replace(ie,"[REDACTED]");return Buffer.byteLength(t)<=q?t:`${t.slice(0,q-24)}
1479
+ [output truncated]`}function v(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),description:d(e.description),organizationId:d(e.organization_id),desiredConfigHash:d(e.desired_config_hash),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function D(e){return{id:String(e.id),projectId:String(e.project_id),slug:String(e.slug),name:String(e.name),kind:String(e.kind),region:d(e.region),desiredState:_(e.desired_state),discoveredState:_(e.discovered_state),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function y(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:d(e.environment_id),kind:String(e.kind),slug:String(e.slug),name:String(e.name),provider:d(e.provider),providerId:d(e.provider_id),desiredState:_(e.desired_state),discoveredState:_(e.discovered_state),metadata:_(e.metadata),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function f(e){return{id:String(e.id),kind:String(e.kind),externalId:d(e.external_id),displayName:String(e.display_name),metadata:_(e.metadata),disabledAt:d(e.disabled_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function u(e){return{id:String(e.id),projectId:d(e.project_id),environmentId:d(e.environment_id),resourceId:d(e.resource_id),actorId:d(e.actor_id),kind:String(e.kind),state:String(e.state),correlationId:String(e.correlation_id),idempotencyKey:d(e.idempotency_key),input:_(e.input),output:_(e.output),error:d(e.error),attempt:Number(e.attempt),priority:Number(e.priority),leaseOwner:d(e.lease_owner),leaseExpiresAt:d(e.lease_expires_at),cancelRequestedAt:d(e.cancel_requested_at),startedAt:d(e.started_at),finishedAt:d(e.finished_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Y(e){return{id:String(e.id),sequence:Number(e.sequence),organizationId:d(e.organization_id),projectId:d(e.project_id),operationId:d(e.operation_id),resourceId:d(e.resource_id),actorId:d(e.actor_id),correlationId:String(e.correlation_id),type:String(e.type),level:String(e.level),payload:_(e.payload),createdAt:String(e.created_at)}}function O(e){return{id:String(e.id),projectId:String(e.project_id),name:String(e.name),normalizedName:String(e.normalized_name),color:String(e.color),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function b(e){return{id:String(e.id),actorKey:String(e.actor_key),name:String(e.name),routeId:String(e.route_id),query:_(e.query),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function F(e){return{actorKey:String(e.actor_key),entityType:String(e.entity_type),entityId:String(e.entity_id),favorite:Number(e.favorite)===1,lastVisitedAt:String(e.last_visited_at),visitCount:Number(e.visit_count)}}function z(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function B(e){let t=String(e.scope_type);return{type:t,...t==="organization"?{}:{id:String(e.scope_id)}}}function k(e){return{id:String(e.id),organizationId:String(e.organization_id),actorId:String(e.actor_id),roleTemplate:String(e.role_template),scope:B(e),source:String(e.source??"manual"),status:String(e.status),sessionVersion:Number(e.session_version),lastActiveAt:d(e.last_active_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function R(e,t){let r=d(e.accepted_at),i=d(e.revoked_at),a=String(e.expires_at),E=i?"revoked":r?"accepted":a<=t?"expired":"pending";return{id:String(e.id),organizationId:String(e.organization_id),email:String(e.email),roleTemplate:String(e.role_template),scope:B(e),invitedByActorId:d(e.invited_by_actor_id),acceptedByActorId:d(e.accepted_by_actor_id),expiresAt:a,acceptedAt:r,revokedAt:i,state:E,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function w(e){return{id:String(e.id),organizationId:String(e.organization_id),membershipId:String(e.membership_id),effect:String(e.effect),capability:String(e.capability),scope:B(e),source:String(e.source??"manual"),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function g(e){return{type:e.type,id:e.id??null}}function le(e){return Array.from({length:e},()=>"?").join(", ")}function o(e,t,r){return e.run(t,r)}class Lr{path;database;nowFn;idFn;constructor(e={}){this.path=e.path??A(e.cwd??process.cwd(),"control-plane.sqlite"),this.nowFn=e.now??(()=>new Date),this.idFn=e.id??(()=>crypto.randomUUID());let t=this.path===":memory:";if(!t){Te(ee(this.path),{recursive:!0,mode:448});try{H(ee(this.path),448)}catch{}}if(this.database=new de(this.path,{create:!0,strict:!0}),this.database.run("PRAGMA foreign_keys = ON"),this.database.run(`PRAGMA busy_timeout = ${Math.max(100,e.busyTimeoutMs??5000)}`),!t)this.database.run("PRAGMA journal_mode = WAL"),this.database.run("PRAGMA synchronous = NORMAL");if(this.migrate(),!t)this.secureDatabaseFiles()}now(){return this.nowFn().toISOString()}secureDatabaseFiles(){for(let e of[this.path,`${this.path}-wal`,`${this.path}-shm`]){if(!Z(e))continue;try{H(e,384)}catch{}}}backupTo(e){this.database.run("VACUUM INTO ?",[e]);try{H(e,384)}catch{}}migrate(){let e=this.database.query("PRAGMA user_version").get(),t=Number(e?.user_version??0);if(t>l)throw new I(t,l);if(t===l)return;let r;if(t>0&&this.path!==":memory:")r=`${this.path}.v${t}.${Date.now()}.bak`,this.backupTo(r);try{if(this.database.transaction(()=>{for(let a of K){if(a.version<=t)continue;this.database.run(a.sql),o(this.database,"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",[a.version,a.name,this.now()]),this.database.run(`PRAGMA user_version = ${a.version}`)}}).exclusive(),r)this.setSetting("storage.last_backup",{path:r,createdAt:this.now(),reason:"pre-migration"})}catch(i){let a=r?` Restore from ${r}.`:"";throw Error(`Control-plane migration from schema ${t} failed.${a} ${i instanceof Error?i.message:String(i)}`)}}close(){if(this.path!==":memory:")this.secureDatabaseFiles();this.database.close()}transaction(e){return this.database.transaction(e).immediate()}createProject(e){let t=e.id??this.idFn(),r=this.now();return o(this.database,"INSERT INTO projects (id, slug, name, description, organization_id, desired_config_hash, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[t,e.slug,e.name,e.description??null,e.organizationId??null,e.desiredConfigHash??null,r,r]),this.getProject(t)}getProject(e){let t=this.database.query("SELECT * FROM projects WHERE id = ?").get(e);return t?v(t):void 0}getProjectBySlug(e){let t=this.database.query("SELECT * FROM projects WHERE slug = ?").get(e);return t?v(t):void 0}listProjects(){return this.database.query("SELECT * FROM projects ORDER BY name COLLATE NOCASE, id").all().map(v)}updateProject(e,t,r){let i=this.getProject(e);if(!i||i.version!==t)throw new p("Project",e,t);if(o(this.database,`UPDATE projects SET name = ?, description = ?, organization_id = ?, desired_config_hash = ?, version = version + 1, updated_at = ?
1480
1480
  WHERE id = ? AND version = ?`,[r.name??i.name,r.description===null?null:r.description??i.description??null,r.organizationId===null?null:r.organizationId??i.organizationId??null,r.desiredConfigHash===null?null:r.desiredConfigHash??i.desiredConfigHash??null,this.now(),e,t]).changes!==1)throw new p("Project",e,t);return this.getProject(e)}createEnvironment(e){let t=e.id??this.idFn(),r=this.now();return o(this.database,`INSERT INTO environments (id, project_id, slug, name, kind, region, desired_state, discovered_state, created_at, updated_at)
1481
1481
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.projectId,e.slug,e.name,e.kind,e.region??null,N(e.desiredState??{}),N(e.discoveredState??{}),r,r]),D(this.database.query("SELECT * FROM environments WHERE id = ?").get(t))}listEnvironments(e){return this.database.query("SELECT * FROM environments WHERE project_id = ? ORDER BY name COLLATE NOCASE, id").all(e).map(D)}getEnvironmentBySlug(e,t){let r=this.database.query("SELECT * FROM environments WHERE project_id = ? AND slug = ?").get(e,t);return r?D(r):void 0}createResource(e){let t=e.id??this.idFn(),r=this.now();return o(this.database,`INSERT INTO resources (id, project_id, environment_id, kind, slug, name, provider, provider_id, desired_state, discovered_state, metadata, created_at, updated_at)
1482
1482
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.projectId,e.environmentId??null,e.kind,e.slug,e.name,e.provider??null,e.providerId??null,N(e.desiredState??{}),N(e.discoveredState??{}),N(e.metadata??{}),r,r]),y(this.database.query("SELECT * FROM resources WHERE id = ?").get(t))}listResources(e,t){return(t?this.database.query("SELECT * FROM resources WHERE project_id = ? AND environment_id = ? ORDER BY kind, name COLLATE NOCASE").all(e,t):this.database.query("SELECT * FROM resources WHERE project_id = ? ORDER BY kind, name COLLATE NOCASE").all(e)).map(y)}getResource(e){let t=this.database.query("SELECT * FROM resources WHERE id = ?").get(e);return t?y(t):void 0}updateResource(e,t,r){let i=this.getResource(e);if(!i||i.version!==t)throw new p("Resource",e,t);if(o(this.database,`UPDATE resources SET name = ?, provider = ?, provider_id = ?, desired_state = ?, discovered_state = ?, metadata = ?,
1483
1483
  version = version + 1, updated_at = ? WHERE id = ? AND version = ?`,[r.name??i.name,r.provider===null?null:r.provider??i.provider??null,r.providerId===null?null:r.providerId??i.providerId??null,N(r.desiredState??i.desiredState),N(r.discoveredState??i.discoveredState),N(r.metadata??i.metadata),this.now(),e,t]).changes!==1)throw new p("Resource",e,t);return this.getResource(e)}createActor(e){let t=e.id??this.idFn(),r=this.now();return o(this.database,"INSERT INTO actors (id, kind, external_id, display_name, metadata, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[t,e.kind,e.externalId??null,e.displayName,N(e.metadata??{}),r,r]),f(this.database.query("SELECT * FROM actors WHERE id = ?").get(t))}getActorByExternalId(e,t){let r=this.database.query("SELECT * FROM actors WHERE kind = ? AND external_id = ?").get(e,t);return r?f(r):void 0}getActor(e){let t=this.database.query("SELECT * FROM actors WHERE id = ?").get(e);return t?f(t):void 0}createOrganization(e){let t=e.slug.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$/.test(t))throw Error("Organization slugs must contain 3-64 lowercase letters, numbers, or dashes");let r=e.name.trim();if(!r||r.length>100)throw Error("Organization names must contain 1-100 characters");let i=e.id??this.idFn(),a=this.now();return o(this.database,"INSERT INTO organizations (id, slug, name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",[i,t,r,a,a]),this.getOrganization(i)}getOrganization(e){let t=this.database.query("SELECT * FROM organizations WHERE id = ?").get(e);return t?z(t):void 0}getOrganizationBySlug(e){let t=this.database.query("SELECT * FROM organizations WHERE slug = ?").get(e.trim().toLowerCase());return t?z(t):void 0}listOrganizations(e){return(e?this.database.query(`SELECT organizations.* FROM organizations JOIN organization_memberships ON organization_memberships.organization_id = organizations.id
1484
1484
  WHERE organization_memberships.actor_id = ? AND organization_memberships.status = 'active' ORDER BY organizations.name COLLATE NOCASE`).all(e):this.database.query("SELECT * FROM organizations ORDER BY name COLLATE NOCASE").all()).map(z)}normalizeAuthorizationScope(e,t={type:"organization"}){if(t.type==="organization"){if(t.id&&t.id!==e)throw Error("Organization scope does not match the requested organization");return{type:"organization"}}if(!t.id)throw Error(`${t.type} scopes require an ID`);if(!this.resolveAuthorizationTarget(e,t))throw Error("Authorization scope was not found in this organization");return{type:t.type,id:t.id}}resolveAuthorizationTarget(e,t){if(!this.getOrganization(e))return;if(t.type==="organization")return{organizationId:e};if(!t.id)return;if(t.type==="project"){let i=this.database.query("SELECT id FROM projects WHERE id = ? AND organization_id = ?").get(t.id,e);return i?{organizationId:e,projectId:String(i.id)}:void 0}if(t.type==="environment"){let i=this.database.query("SELECT environments.id, environments.project_id FROM environments JOIN projects ON projects.id = environments.project_id WHERE environments.id = ? AND projects.organization_id = ?").get(t.id,e);return i?{organizationId:e,projectId:String(i.project_id),environmentId:String(i.id)}:void 0}let r=this.database.query(`SELECT resources.id, resources.project_id, resources.environment_id FROM resources
1485
1485
  JOIN projects ON projects.id = resources.project_id WHERE resources.id = ? AND projects.organization_id = ?`).get(t.id,e);return r?{organizationId:e,projectId:String(r.project_id),environmentId:d(r.environment_id),resourceId:String(r.id)}:void 0}createMembership(e){if(!this.getActor(e.actorId))throw Error("Membership actor was not found");let t=this.normalizeAuthorizationScope(e.organizationId,e.scope);if(e.roleTemplate==="owner"&&t.type!=="organization")throw Error("Owners must be scoped to the organization");let r=e.id??this.idFn(),i=this.now();o(this.database,`INSERT INTO organization_memberships (id, organization_id, actor_id, role_template, scope_type, scope_id, source, created_at, updated_at)
1486
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,e.organizationId,e.actorId,e.roleTemplate,t.type,t.id??null,e.source??"manual",i,i]);let a=this.getMembership(r);return this.appendEvent({organizationId:e.organizationId,actorId:e.performedByActorId,type:"organization.membership.created",payload:{membershipId:r,actorId:e.actorId,roleTemplate:e.roleTemplate,scope:g(t)}}),a}getMembership(e){let t=this.database.query("SELECT * FROM organization_memberships WHERE id = ?").get(e);return t?k(t):void 0}getMembershipForActor(e,t){let r=this.database.query("SELECT * FROM organization_memberships WHERE organization_id = ? AND actor_id = ?").get(e,t);return r?k(r):void 0}listMemberships(e,t={}){let r=t.includeRevoked?"":"AND status = 'active'";return this.database.query(`SELECT * FROM organization_memberships WHERE organization_id = ? ${r} ORDER BY created_at, id`).all(e).map(k)}updateMembership(e){let t=this.getMembership(e.id);if(!t)throw Error("Membership was not found");let r=this.normalizeAuthorizationScope(t.organizationId,e.scope??t.scope);if(e.roleTemplate==="owner"&&r.type!=="organization")throw Error("Owners must be scoped to the organization");if(t.roleTemplate==="owner"&&t.status==="active"&&(e.roleTemplate!=="owner"||r.type!=="organization"))this.assertAnotherOwner(t);return o(this.database,"UPDATE organization_memberships SET role_template = ?, scope_type = ?, scope_id = ?, session_version = session_version + 1, updated_at = ? WHERE id = ?",[e.roleTemplate,r.type,r.id??null,this.now(),t.id]),this.appendEvent({organizationId:t.organizationId,actorId:e.actorId,type:"organization.membership.updated",payload:{membershipId:t.id,from:{roleTemplate:t.roleTemplate,scope:g(t.scope)},to:{roleTemplate:e.roleTemplate,scope:g(r)}}}),this.getMembership(t.id)}revokeMembership(e,t){let r=this.getMembership(e);if(!r)throw Error("Membership was not found");if(r.status==="revoked")return r;if(r.roleTemplate==="owner")this.assertAnotherOwner(r);return o(this.database,"UPDATE organization_memberships SET status = 'revoked', session_version = session_version + 1, updated_at = ? WHERE id = ?",[this.now(),e]),this.appendEvent({organizationId:r.organizationId,actorId:t,type:"organization.membership.revoked",payload:{membershipId:e}}),this.getMembership(e)}touchMembership(e){let t=this.now();o(this.database,"UPDATE organization_memberships SET last_active_at = ?, updated_at = ? WHERE id = ? AND status = ?",[t,t,e,"active"]);let r=this.getMembership(e);if(!r)throw Error("Membership was not found");return r}assertAnotherOwner(e){if(Number(this.database.query("SELECT COUNT(*) AS count FROM organization_memberships WHERE organization_id = ? AND status = ? AND role_template = 'owner'").get(e.organizationId,"active")?.count??0)<=1)throw Error("Cannot remove or demote the last organization owner")}createInvitation(e){let t=e.email.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)||t.length>254)throw Error("A valid invitation email is required");let r=this.normalizeAuthorizationScope(e.organizationId,e.scope);if(e.roleTemplate==="owner"&&r.type!=="organization")throw Error("Owners must be scoped to the organization");let i=Te(32).toString("base64url"),a=S("sha256").update(i).digest("hex"),E=e.id??this.idFn(),T=this.now(),s=new Date(this.nowFn().getTime()+Math.min(2592000000,Math.max(60000,e.expiresInMs??604800000))).toISOString();return o(this.database,`INSERT INTO organization_invitations (id, organization_id, email, role_template, scope_type, scope_id, token_hash, invited_by_actor_id, expires_at, created_at, updated_at)
1487
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[E,e.organizationId,t,e.roleTemplate,r.type,r.id??null,a,e.invitedByActorId??null,s,T,T]),this.appendEvent({organizationId:e.organizationId,actorId:e.invitedByActorId,type:"organization.invitation.created",payload:{invitationId:E,email:t,roleTemplate:e.roleTemplate,scope:g(r),expiresAt:s}}),{invitation:this.getInvitation(E),token:i}}getInvitation(e){let t=this.database.query("SELECT * FROM organization_invitations WHERE id = ?").get(e);return t?R(t,this.now()):void 0}listInvitations(e){return this.database.query("SELECT * FROM organization_invitations WHERE organization_id = ? ORDER BY created_at DESC").all(e).map((t)=>R(t,this.now()))}inspectInvitationToken(e){let t=S("sha256").update(e).digest("hex"),r=this.database.query("SELECT * FROM organization_invitations WHERE token_hash = ?").get(t);return r?R(r,this.now()):void 0}acceptInvitation(e,t){let r=S("sha256").update(e).digest("hex");return this.transaction(()=>{let i=this.database.query("SELECT * FROM organization_invitations WHERE token_hash = ?").get(r);if(!i)throw Error("Invitation is invalid");let a=R(i,this.now());if(a.state!=="pending")throw Error(`Invitation is ${a.state}`);if(!this.getActor(t))throw Error("Invitation actor was not found");if(o(this.database,"UPDATE organization_invitations SET accepted_by_actor_id = ?, accepted_at = ?, updated_at = ? WHERE id = ? AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > ?",[t,this.now(),this.now(),a.id,this.now()]).changes!==1)throw Error("Invitation is no longer available");let T=this.getMembershipForActor(a.organizationId,t),s=T??this.createMembership({organizationId:a.organizationId,actorId:t,roleTemplate:a.roleTemplate,scope:a.scope,source:"invitation"});if(T&&a.roleTemplate==="owner"&&T.roleTemplate!=="owner")s=this.updateMembership({id:T.id,roleTemplate:"owner",scope:{type:"organization"},actorId:t});else if(T)for(let c of fn(a.roleTemplate))this.upsertGrant({organizationId:a.organizationId,membershipId:T.id,effect:"allow",capability:c,scope:a.scope,source:"invitation"});return this.appendEvent({organizationId:a.organizationId,actorId:t,type:"organization.invitation.accepted",payload:{invitationId:a.id,membershipId:s.id}}),{invitation:this.getInvitation(a.id),membership:this.getMembership(s.id)}})}revokeInvitation(e,t){let r=this.getInvitation(e);if(!r)throw Error("Invitation was not found");if(r.acceptedAt)throw Error("Accepted invitations cannot be revoked");if(!r.revokedAt)o(this.database,"UPDATE organization_invitations SET revoked_at = ?, updated_at = ? WHERE id = ?",[this.now(),this.now(),e]);return this.appendEvent({organizationId:r.organizationId,actorId:t,type:"organization.invitation.revoked",payload:{invitationId:e}}),this.getInvitation(e)}reissueInvitation(e,t){let r=this.getInvitation(e);if(!r)throw Error("Invitation was not found");if(r.state==="accepted")throw Error("Accepted invitations cannot be reissued");return this.revokeInvitation(e,t),this.createInvitation({organizationId:r.organizationId,email:r.email,roleTemplate:r.roleTemplate,scope:r.scope,invitedByActorId:t})}upsertGrant(e){if(!ae.includes(e.capability))throw Error("Unknown authorization capability");let t=this.getMembership(e.membershipId);if(!t||t.organizationId!==e.organizationId)throw Error("Grant membership was not found in this organization");let r=this.normalizeAuthorizationScope(e.organizationId,e.scope),i=this.now(),a=this.database.query("SELECT * FROM authorization_grants WHERE membership_id = ? AND effect = ? AND capability = ? AND scope_type = ? AND scope_id IS ?").get(e.membershipId,e.effect,e.capability,r.type,r.id??null);if(a)return w(a);let E=e.id??this.idFn();return o(this.database,`INSERT INTO authorization_grants (id, organization_id, membership_id, effect, capability, scope_type, scope_id, source, created_at, updated_at)
1486
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,e.organizationId,e.actorId,e.roleTemplate,t.type,t.id??null,e.source??"manual",i,i]);let a=this.getMembership(r);return this.appendEvent({organizationId:e.organizationId,actorId:e.performedByActorId,type:"organization.membership.created",payload:{membershipId:r,actorId:e.actorId,roleTemplate:e.roleTemplate,scope:g(t)}}),a}getMembership(e){let t=this.database.query("SELECT * FROM organization_memberships WHERE id = ?").get(e);return t?k(t):void 0}getMembershipForActor(e,t){let r=this.database.query("SELECT * FROM organization_memberships WHERE organization_id = ? AND actor_id = ?").get(e,t);return r?k(r):void 0}listMemberships(e,t={}){let r=t.includeRevoked?"":"AND status = 'active'";return this.database.query(`SELECT * FROM organization_memberships WHERE organization_id = ? ${r} ORDER BY created_at, id`).all(e).map(k)}updateMembership(e){let t=this.getMembership(e.id);if(!t)throw Error("Membership was not found");let r=this.normalizeAuthorizationScope(t.organizationId,e.scope??t.scope);if(e.roleTemplate==="owner"&&r.type!=="organization")throw Error("Owners must be scoped to the organization");if(t.roleTemplate==="owner"&&t.status==="active"&&(e.roleTemplate!=="owner"||r.type!=="organization"))this.assertAnotherOwner(t);return o(this.database,"UPDATE organization_memberships SET role_template = ?, scope_type = ?, scope_id = ?, session_version = session_version + 1, updated_at = ? WHERE id = ?",[e.roleTemplate,r.type,r.id??null,this.now(),t.id]),this.appendEvent({organizationId:t.organizationId,actorId:e.actorId,type:"organization.membership.updated",payload:{membershipId:t.id,from:{roleTemplate:t.roleTemplate,scope:g(t.scope)},to:{roleTemplate:e.roleTemplate,scope:g(r)}}}),this.getMembership(t.id)}revokeMembership(e,t){let r=this.getMembership(e);if(!r)throw Error("Membership was not found");if(r.status==="revoked")return r;if(r.roleTemplate==="owner")this.assertAnotherOwner(r);return o(this.database,"UPDATE organization_memberships SET status = 'revoked', session_version = session_version + 1, updated_at = ? WHERE id = ?",[this.now(),e]),this.appendEvent({organizationId:r.organizationId,actorId:t,type:"organization.membership.revoked",payload:{membershipId:e}}),this.getMembership(e)}touchMembership(e){let t=this.now();o(this.database,"UPDATE organization_memberships SET last_active_at = ?, updated_at = ? WHERE id = ? AND status = ?",[t,t,e,"active"]);let r=this.getMembership(e);if(!r)throw Error("Membership was not found");return r}assertAnotherOwner(e){if(Number(this.database.query("SELECT COUNT(*) AS count FROM organization_memberships WHERE organization_id = ? AND status = ? AND role_template = 'owner'").get(e.organizationId,"active")?.count??0)<=1)throw Error("Cannot remove or demote the last organization owner")}createInvitation(e){let t=e.email.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)||t.length>254)throw Error("A valid invitation email is required");let r=this.normalizeAuthorizationScope(e.organizationId,e.scope);if(e.roleTemplate==="owner"&&r.type!=="organization")throw Error("Owners must be scoped to the organization");let i=oe(32).toString("base64url"),a=S("sha256").update(i).digest("hex"),E=e.id??this.idFn(),T=this.now(),s=new Date(this.nowFn().getTime()+Math.min(2592000000,Math.max(60000,e.expiresInMs??604800000))).toISOString();return o(this.database,`INSERT INTO organization_invitations (id, organization_id, email, role_template, scope_type, scope_id, token_hash, invited_by_actor_id, expires_at, created_at, updated_at)
1487
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[E,e.organizationId,t,e.roleTemplate,r.type,r.id??null,a,e.invitedByActorId??null,s,T,T]),this.appendEvent({organizationId:e.organizationId,actorId:e.invitedByActorId,type:"organization.invitation.created",payload:{invitationId:E,email:t,roleTemplate:e.roleTemplate,scope:g(r),expiresAt:s}}),{invitation:this.getInvitation(E),token:i}}getInvitation(e){let t=this.database.query("SELECT * FROM organization_invitations WHERE id = ?").get(e);return t?R(t,this.now()):void 0}listInvitations(e){return this.database.query("SELECT * FROM organization_invitations WHERE organization_id = ? ORDER BY created_at DESC").all(e).map((t)=>R(t,this.now()))}inspectInvitationToken(e){let t=S("sha256").update(e).digest("hex"),r=this.database.query("SELECT * FROM organization_invitations WHERE token_hash = ?").get(t);return r?R(r,this.now()):void 0}acceptInvitation(e,t){let r=S("sha256").update(e).digest("hex");return this.transaction(()=>{let i=this.database.query("SELECT * FROM organization_invitations WHERE token_hash = ?").get(r);if(!i)throw Error("Invitation is invalid");let a=R(i,this.now());if(a.state!=="pending")throw Error(`Invitation is ${a.state}`);if(!this.getActor(t))throw Error("Invitation actor was not found");if(o(this.database,"UPDATE organization_invitations SET accepted_by_actor_id = ?, accepted_at = ?, updated_at = ? WHERE id = ? AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > ?",[t,this.now(),this.now(),a.id,this.now()]).changes!==1)throw Error("Invitation is no longer available");let T=this.getMembershipForActor(a.organizationId,t),s=T??this.createMembership({organizationId:a.organizationId,actorId:t,roleTemplate:a.roleTemplate,scope:a.scope,source:"invitation"});if(T&&a.roleTemplate==="owner"&&T.roleTemplate!=="owner")s=this.updateMembership({id:T.id,roleTemplate:"owner",scope:{type:"organization"},actorId:t});else if(T)for(let c of bn(a.roleTemplate))this.upsertGrant({organizationId:a.organizationId,membershipId:T.id,effect:"allow",capability:c,scope:a.scope,source:"invitation"});return this.appendEvent({organizationId:a.organizationId,actorId:t,type:"organization.invitation.accepted",payload:{invitationId:a.id,membershipId:s.id}}),{invitation:this.getInvitation(a.id),membership:this.getMembership(s.id)}})}revokeInvitation(e,t){let r=this.getInvitation(e);if(!r)throw Error("Invitation was not found");if(r.acceptedAt)throw Error("Accepted invitations cannot be revoked");if(!r.revokedAt)o(this.database,"UPDATE organization_invitations SET revoked_at = ?, updated_at = ? WHERE id = ?",[this.now(),this.now(),e]);return this.appendEvent({organizationId:r.organizationId,actorId:t,type:"organization.invitation.revoked",payload:{invitationId:e}}),this.getInvitation(e)}reissueInvitation(e,t){let r=this.getInvitation(e);if(!r)throw Error("Invitation was not found");if(r.state==="accepted")throw Error("Accepted invitations cannot be reissued");return this.revokeInvitation(e,t),this.createInvitation({organizationId:r.organizationId,email:r.email,roleTemplate:r.roleTemplate,scope:r.scope,invitedByActorId:t})}upsertGrant(e){if(!ce.includes(e.capability))throw Error("Unknown authorization capability");let t=this.getMembership(e.membershipId);if(!t||t.organizationId!==e.organizationId)throw Error("Grant membership was not found in this organization");let r=this.normalizeAuthorizationScope(e.organizationId,e.scope),i=this.now(),a=this.database.query("SELECT * FROM authorization_grants WHERE membership_id = ? AND effect = ? AND capability = ? AND scope_type = ? AND scope_id IS ?").get(e.membershipId,e.effect,e.capability,r.type,r.id??null);if(a)return w(a);let E=e.id??this.idFn();return o(this.database,`INSERT INTO authorization_grants (id, organization_id, membership_id, effect, capability, scope_type, scope_id, source, created_at, updated_at)
1488
1488
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[E,e.organizationId,e.membershipId,e.effect,e.capability,r.type,r.id??null,e.source??"manual",i,i]),o(this.database,"UPDATE organization_memberships SET session_version = session_version + 1, updated_at = ? WHERE id = ?",[i,e.membershipId]),this.appendEvent({organizationId:e.organizationId,actorId:e.actorId,type:"organization.grant.created",payload:{grantId:E,membershipId:e.membershipId,effect:e.effect,capability:e.capability,scope:g(r)}}),this.getGrant(E)}getGrant(e){let t=this.database.query("SELECT * FROM authorization_grants WHERE id = ?").get(e);return t?w(t):void 0}listGrants(e){return this.database.query("SELECT * FROM authorization_grants WHERE membership_id = ? ORDER BY effect DESC, capability, scope_type, scope_id").all(e).map(w)}removeGrant(e,t){let r=this.getGrant(e);if(!r)return!1;let i=o(this.database,"DELETE FROM authorization_grants WHERE id = ?",[e]).changes===1;if(i)o(this.database,"UPDATE organization_memberships SET session_version = session_version + 1, updated_at = ? WHERE id = ?",[this.now(),r.membershipId]),this.appendEvent({organizationId:r.organizationId,actorId:t,type:"organization.grant.removed",payload:{grantId:e,membershipId:r.membershipId}});return i}createOperation(e){if(e.idempotencyKey){let a=this.database.query("SELECT * FROM operations WHERE idempotency_key = ?").get(e.idempotencyKey);if(a)return u(a)}let t=e.id??this.idFn(),r=e.correlationId??this.idFn(),i=this.now();try{return this.transaction(()=>(o(this.database,`INSERT INTO operations (id, project_id, environment_id, resource_id, actor_id, kind, state, correlation_id, idempotency_key, input, output, priority, created_at, updated_at)
1489
1489
  VALUES (?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, '{}', ?, ?, ?)`,[t,e.projectId??null,e.environmentId??null,e.resourceId??null,e.actorId??null,e.kind,r,e.idempotencyKey??null,N(e.input??{}),e.priority??0,i,i]),this.appendEvent({projectId:e.projectId,operationId:t,resourceId:e.resourceId,actorId:e.actorId,correlationId:r,type:"operation.queued",payload:{kind:e.kind}}),this.getOperation(t)))}catch(a){if(e.idempotencyKey){let E=this.database.query("SELECT * FROM operations WHERE idempotency_key = ?").get(e.idempotencyKey);if(E)return u(E)}throw a}}getOperation(e){let t=this.database.query("SELECT * FROM operations WHERE id = ?").get(e);return t?u(t):void 0}listOperations(e={}){let t=[],r=[];if(e.projectId)t.push("project_id = ?"),r.push(e.projectId);if(e.state)t.push("state = ?"),r.push(e.state);if(e.kind)t.push("kind = ?"),r.push(e.kind);if(e.before)t.push("created_at < ?"),r.push(e.before);let i=Math.min(500,Math.max(1,e.limit??100));r.push(i);let a=t.length?`WHERE ${t.join(" AND ")}`:"";return this.database.query(`SELECT * FROM operations ${a} ORDER BY created_at DESC, id DESC LIMIT ?`).all(...r).map(u)}claimNextOperation(e,t=60000,r){let i=this.now(),a=new Date(this.nowFn().getTime()+t).toISOString();return this.transaction(()=>{let E=r?.length?`AND kind IN (${le(r.length)})`:"",T=r?[...r]:[],s=this.database.query(`SELECT * FROM operations WHERE state = 'queued' ${E} ORDER BY priority DESC, created_at ASC, id ASC LIMIT 1`).get(...T);if(!s)return;let c=u(s);if(o(this.database,`UPDATE operations SET state = 'running', attempt = attempt + 1, lease_owner = ?, lease_expires_at = ?,
1490
1490
  started_at = COALESCE(started_at, ?), updated_at = ?, version = version + 1 WHERE id = ? AND state = 'queued' AND version = ?`,[e,a,i,i,c.id,c.version]).changes!==1)return;return this.appendEvent({projectId:c.projectId,operationId:c.id,resourceId:c.resourceId,actorId:c.actorId,correlationId:c.correlationId,type:"operation.running",payload:{attempt:c.attempt+1,workerId:e}}),this.getOperation(c.id)})}claimOperation(e,t,r=60000){let i=this.now(),a=new Date(this.nowFn().getTime()+r).toISOString();return this.transaction(()=>{let E=this.getOperation(e);if(!E||E.state!=="queued")return;if(o(this.database,`UPDATE operations SET state = 'running', attempt = attempt + 1, lease_owner = ?, lease_expires_at = ?,
1491
- started_at = COALESCE(started_at, ?), updated_at = ?, version = version + 1 WHERE id = ? AND state = 'queued' AND version = ?`,[t,a,i,i,E.id,E.version]).changes!==1)return;return this.appendEvent({projectId:E.projectId,operationId:E.id,resourceId:E.resourceId,actorId:E.actorId,correlationId:E.correlationId,type:"operation.running",payload:{attempt:E.attempt+1,workerId:t}}),this.getOperation(E.id)})}transitionOperation(e,t){return this.transaction(()=>{let r=this.getOperation(e);if(!r)throw Error(`Operation ${e} was not found`);let i=t.expectedVersion??r.version;if(r.version!==i)throw new p("Operation",e,i);if(!Le[r.state].includes(t.to))throw new x(r.state,t.to);let a=this.now(),E=ce.includes(t.to),T=t.to==="queued";if(o(this.database,`UPDATE operations SET state = ?, output = ?, error = ?, lease_owner = ?, lease_expires_at = ?,
1491
+ started_at = COALESCE(started_at, ?), updated_at = ?, version = version + 1 WHERE id = ? AND state = 'queued' AND version = ?`,[t,a,i,i,E.id,E.version]).changes!==1)return;return this.appendEvent({projectId:E.projectId,operationId:E.id,resourceId:E.resourceId,actorId:E.actorId,correlationId:E.correlationId,type:"operation.running",payload:{attempt:E.attempt+1,workerId:t}}),this.getOperation(E.id)})}transitionOperation(e,t){return this.transaction(()=>{let r=this.getOperation(e);if(!r)throw Error(`Operation ${e} was not found`);let i=t.expectedVersion??r.version;if(r.version!==i)throw new p("Operation",e,i);if(!Le[r.state].includes(t.to))throw new x(r.state,t.to);let a=this.now(),E=Ne.includes(t.to),T=t.to==="queued";if(o(this.database,`UPDATE operations SET state = ?, output = ?, error = ?, lease_owner = ?, lease_expires_at = ?,
1492
1492
  finished_at = ?, updated_at = ?, version = version + 1 WHERE id = ? AND version = ?`,[t.to,N(t.output??r.output),M(t.error)??null,T||E?null:t.leaseOwner??r.leaseOwner??null,T||E?null:t.leaseExpiresAt??r.leaseExpiresAt??null,E?a:null,a,e,i]).changes!==1)throw new p("Operation",e,i);return this.appendEvent({projectId:r.projectId,operationId:e,resourceId:r.resourceId,actorId:r.actorId,correlationId:r.correlationId,type:`operation.${t.to}`,level:t.to==="failed"?"error":"info",payload:{from:r.state,to:t.to,error:M(t.error)??null}}),this.getOperation(e)})}requestCancellation(e){let t=this.now();o(this.database,"UPDATE operations SET cancel_requested_at = ?, updated_at = ?, version = version + 1 WHERE id = ? AND state IN ('queued', 'running')",[t,t,e]);let r=this.getOperation(e);if(!r)throw Error(`Operation ${e} was not found`);return r}reconcileOrphanedOperations(e={}){let t=(e.now??this.nowFn()).toISOString(),r=e.policy??"fail",i=this.database.query("SELECT * FROM operations WHERE state = 'running' AND (lease_expires_at IS NULL OR lease_expires_at <= ?)").all(t).map(u),a=0,E=0;for(let T of i)if(r==="requeue")this.transitionOperation(T.id,{to:"queued",expectedVersion:T.version,error:"Worker lease expired; operation requeued after restart."}),a++;else this.transitionOperation(T.id,{to:"failed",expectedVersion:T.version,error:"Worker lease expired or dashboard restarted before completion."}),E++;return{requeued:a,failed:E}}appendEvent(e){let t=e.id??this.idFn(),r=e.correlationId??this.idFn(),i=e.organizationId??(e.projectId?d(this.database.query("SELECT organization_id FROM projects WHERE id = ?").get(e.projectId)?.organization_id):void 0);return o(this.database,`INSERT INTO events (id, organization_id, project_id, operation_id, resource_id, actor_id, correlation_id, type, level, payload, created_at)
1493
1493
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,i??null,e.projectId??null,e.operationId??null,e.resourceId??null,e.actorId??null,r,e.type,e.level??"info",N(e.payload??{}),this.now()]),Y(this.database.query("SELECT * FROM events WHERE id = ?").get(t))}listEvents(e={}){let t=[],r=[];if(e.organizationId)t.push("organization_id = ?"),r.push(e.organizationId);if(e.projectId)t.push("project_id = ?"),r.push(e.projectId);if(e.operationId)t.push("operation_id = ?"),r.push(e.operationId);if(e.resourceId)t.push("resource_id = ?"),r.push(e.resourceId);if(e.correlationId)t.push("correlation_id = ?"),r.push(e.correlationId);if(e.afterSequence!==void 0)t.push("sequence > ?"),r.push(e.afterSequence);let i=Math.min(1000,Math.max(1,e.limit??200));r.push(i);let a=t.length?`WHERE ${t.join(" AND ")}`:"";return this.database.query(`SELECT * FROM events ${a} ORDER BY sequence ASC LIMIT ?`).all(...r).map(Y)}setSetting(e,t){o(this.database,`INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)
1494
1494
  ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,[e,N(t),this.now()])}getSetting(e){let t=this.database.query("SELECT value FROM settings WHERE key = ?").get(e);return t?_(t.value):void 0}upsertTag(e,t,r="#5a8be0"){let i=t.trim().toLowerCase().replace(/\s+/g,"-");if(!/^[a-z0-9][a-z0-9-]{0,31}$/.test(i))throw Error("Tag names must contain 1-32 letters, numbers, or dashes");if(!/^#[0-9a-f]{6}$/i.test(r))throw Error("Tag colors must be six-digit hex colors");let a=this.now(),E=this.database.query("SELECT * FROM tags WHERE project_id = ? AND normalized_name = ?").get(e,i);if(E)return o(this.database,"UPDATE tags SET name = ?, color = ?, updated_at = ? WHERE id = ?",[t.trim(),r.toLowerCase(),a,String(E.id)]),O(this.database.query("SELECT * FROM tags WHERE id = ?").get(String(E.id)));let T=this.idFn();return o(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[T,e,t.trim(),i,r.toLowerCase(),a,a]),O(this.database.query("SELECT * FROM tags WHERE id = ?").get(T))}listTags(e){return this.database.query("SELECT * FROM tags WHERE project_id = ? ORDER BY normalized_name").all(e).map(O)}assignTag(e,t){if(!this.database.query("SELECT tags.id FROM tags JOIN resources ON resources.project_id = tags.project_id WHERE tags.id = ? AND resources.id = ?").get(t,e))throw Error("The tag and resource must belong to the same project");o(this.database,"INSERT OR IGNORE INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[e,t,this.now()])}removeTag(e,t){o(this.database,"DELETE FROM resource_tags WHERE resource_id = ? AND tag_id = ?",[e,t])}listResourceTags(e){return this.database.query(`SELECT resource_tags.resource_id, tags.* FROM resource_tags JOIN tags ON tags.id = resource_tags.tag_id
1495
1495
  WHERE tags.project_id = ? ORDER BY tags.normalized_name`).all(e).map((r)=>({resourceId:String(r.resource_id),tag:O(r)}))}saveFilter(e,t,r,i){let a=t.trim();if(!a||a.length>64)throw Error("Saved filter names must contain 1-64 characters");if(!r||r.length>160||/^[a-z][a-z0-9+.-]*:|^\/\//i.test(r))throw Error("Saved filter routes must be local route IDs or paths");let E=N(i);if(E.length>8192)throw Error("Saved filter queries must be smaller than 8 KB");let T=this.database.query("SELECT * FROM saved_filters WHERE actor_key = ? AND name = ?").get(e,a),s=this.now();if(T)return o(this.database,"UPDATE saved_filters SET route_id = ?, query = ?, updated_at = ? WHERE id = ?",[r,E,s,String(T.id)]),b(this.database.query("SELECT * FROM saved_filters WHERE id = ?").get(String(T.id)));let c=this.idFn();return o(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[c,e,a,r,E,s,s]),b(this.database.query("SELECT * FROM saved_filters WHERE id = ?").get(c))}listSavedFilters(e){return this.database.query("SELECT * FROM saved_filters WHERE actor_key = ? ORDER BY updated_at DESC, name").all(e).map(b)}deleteSavedFilter(e,t){return o(this.database,"DELETE FROM saved_filters WHERE actor_key = ? AND id = ?",[e,t]).changes===1}recordNavigation(e,t,r){let i=this.now();return o(this.database,`INSERT INTO navigation_items (actor_key, entity_type, entity_id, last_visited_at) VALUES (?, ?, ?, ?)
1496
1496
  ON CONFLICT(actor_key, entity_type, entity_id) DO UPDATE SET last_visited_at = excluded.last_visited_at, visit_count = visit_count + 1`,[e,t,r,i]),F(this.database.query("SELECT * FROM navigation_items WHERE actor_key = ? AND entity_type = ? AND entity_id = ?").get(e,t,r))}setFavorite(e,t,r,i){let a=this.now();return o(this.database,`INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at) VALUES (?, ?, ?, ?, ?)
1497
- ON CONFLICT(actor_key, entity_type, entity_id) DO UPDATE SET favorite = excluded.favorite`,[e,t,r,i?1:0,a]),F(this.database.query("SELECT * FROM navigation_items WHERE actor_key = ? AND entity_type = ? AND entity_id = ?").get(e,t,r))}listNavigation(e,t={}){let r=t.favoritesOnly?"AND favorite = 1":"",i=Math.min(100,Math.max(1,t.limit??20));return this.database.query(`SELECT * FROM navigation_items WHERE actor_key = ? ${r} ORDER BY favorite DESC, last_visited_at DESC LIMIT ?`).all(e,i).map(F)}compact(e={}){let t=new Date(this.nowFn().getTime()-(e.eventRetentionDays??90)*86400000).toISOString(),r=new Date(this.nowFn().getTime()-(e.operationRetentionDays??365)*86400000).toISOString(),i=this.transaction(()=>{let a=o(this.database,"DELETE FROM events WHERE created_at < ?",[t]).changes,E=o(this.database,"DELETE FROM operations WHERE created_at < ? AND state IN ('succeeded', 'failed', 'cancelled', 'timed_out')",[r]).changes;return{events:a,operations:E}});if(e.vacuum!==!1)this.database.run("VACUUM");return{deletedEvents:i.events,deletedOperations:i.operations,vacuumed:e.vacuum!==!1}}createBackup(e="manual"){if(this.path===":memory:")throw Error("Cannot create a filesystem backup for an in-memory control plane");let t=`${this.path}.${Date.now()}.bak`;return this.backupTo(t),this.setSetting("storage.last_backup",{path:t,createdAt:this.now(),reason:e}),t}integrityCheck(){let e=this.database.query("PRAGMA integrity_check").all();return e.length===1&&Object.values(e[0])[0]==="ok"?"ok":"corrupt"}health(){let e=Object.fromEntries(["queued","running","succeeded","failed","cancelled","timed_out"].map((a)=>[a,0]));for(let a of this.database.query("SELECT state, COUNT(*) AS count FROM operations GROUP BY state").all())e[String(a.state)]=Number(a.count);let t=this.database.query("PRAGMA journal_mode").get(),r=this.getSetting("storage.last_backup"),i=r&&!Array.isArray(r)&&typeof r==="object"&&typeof r.createdAt==="string"?r.createdAt:void 0;return{path:this.path,schemaVersion:Number(this.database.query("PRAGMA user_version").get()?.user_version??0),supportedSchemaVersion:l,integrity:this.integrityCheck(),journalMode:String(t?.journal_mode??"unknown"),databaseBytes:this.path!==":memory:"&&Z(this.path)?de(this.path).size:this.database.serialize().byteLength,lastBackupAt:i,operations:e,pendingRetryableOperations:e.queued+e.failed+e.timed_out}}exportSnapshot(){let e={};for(let t of this.database.query("SELECT key, value FROM settings ORDER BY key").all())e[String(t.key)]=_(t.value);return{format:"ts-cloud-control-plane",schemaVersion:l,exportedAt:this.now(),organizations:this.database.query("SELECT * FROM organizations ORDER BY id").all().map(z),memberships:this.database.query("SELECT * FROM organization_memberships ORDER BY id").all().map(k),invitations:this.database.query("SELECT * FROM organization_invitations ORDER BY id").all().map((t)=>({...R(t,this.now()),tokenHash:String(t.token_hash)})),grants:this.database.query("SELECT * FROM authorization_grants ORDER BY id").all().map(w),projects:this.database.query("SELECT * FROM projects ORDER BY id").all().map(v),environments:this.database.query("SELECT * FROM environments ORDER BY id").all().map(D),resources:this.database.query("SELECT * FROM resources ORDER BY id").all().map(y),actors:this.database.query("SELECT * FROM actors ORDER BY id").all().map(f),operations:this.database.query("SELECT * FROM operations ORDER BY id").all().map(u),events:this.database.query("SELECT * FROM events ORDER BY sequence").all().map(Y),settings:e,tags:this.database.query("SELECT * FROM tags ORDER BY id").all().map(O),resourceTags:this.database.query("SELECT * FROM resource_tags ORDER BY resource_id, tag_id").all().map((t)=>({resourceId:String(t.resource_id),tagId:String(t.tag_id),createdAt:String(t.created_at)})),savedFilters:this.database.query("SELECT * FROM saved_filters ORDER BY id").all().map(b),navigationItems:this.database.query("SELECT * FROM navigation_items ORDER BY actor_key, entity_type, entity_id").all().map(F)}}importSnapshot(e,t={}){if(e.format!=="ts-cloud-control-plane")throw Error("Unsupported control-plane snapshot format");if(e.schemaVersion>l)throw new I(e.schemaVersion,l);this.transaction(()=>{if((Number(this.database.query("SELECT COUNT(*) AS count FROM projects").get()?.count??0)>0||Number(this.database.query("SELECT COUNT(*) AS count FROM operations").get()?.count??0)>0)&&!t.replace)throw Error("Control plane is not empty; pass replace: true to import this snapshot");if(t.replace)this.database.run("DELETE FROM authorization_grants"),this.database.run("DELETE FROM organization_invitations"),this.database.run("DELETE FROM organization_memberships"),this.database.run("DELETE FROM resource_tags"),this.database.run("DELETE FROM tags"),this.database.run("DELETE FROM saved_filters"),this.database.run("DELETE FROM navigation_items"),this.database.run("DELETE FROM events"),this.database.run("DELETE FROM operations"),this.database.run("DELETE FROM resources"),this.database.run("DELETE FROM environments"),this.database.run("DELETE FROM projects"),this.database.run("DELETE FROM actors"),this.database.run("DELETE FROM organizations"),this.database.run("DELETE FROM settings");for(let i of e.organizations??[])o(this.database,"INSERT INTO organizations (id, slug, name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",[i.id,i.slug,i.name,i.createdAt,i.updatedAt]);for(let i of e.projects)o(this.database,`INSERT INTO projects (id, slug, name, description, organization_id, desired_config_hash, version, created_at, updated_at)
1497
+ ON CONFLICT(actor_key, entity_type, entity_id) DO UPDATE SET favorite = excluded.favorite`,[e,t,r,i?1:0,a]),F(this.database.query("SELECT * FROM navigation_items WHERE actor_key = ? AND entity_type = ? AND entity_id = ?").get(e,t,r))}listNavigation(e,t={}){let r=t.favoritesOnly?"AND favorite = 1":"",i=Math.min(100,Math.max(1,t.limit??20));return this.database.query(`SELECT * FROM navigation_items WHERE actor_key = ? ${r} ORDER BY favorite DESC, last_visited_at DESC LIMIT ?`).all(e,i).map(F)}compact(e={}){let t=new Date(this.nowFn().getTime()-(e.eventRetentionDays??90)*86400000).toISOString(),r=new Date(this.nowFn().getTime()-(e.operationRetentionDays??365)*86400000).toISOString(),i=this.transaction(()=>{let a=o(this.database,"DELETE FROM events WHERE created_at < ?",[t]).changes,E=o(this.database,"DELETE FROM operations WHERE created_at < ? AND state IN ('succeeded', 'failed', 'cancelled', 'timed_out')",[r]).changes;return{events:a,operations:E}});if(e.vacuum!==!1)this.database.run("VACUUM");return{deletedEvents:i.events,deletedOperations:i.operations,vacuumed:e.vacuum!==!1}}createBackup(e="manual"){if(this.path===":memory:")throw Error("Cannot create a filesystem backup for an in-memory control plane");let t=`${this.path}.${Date.now()}.bak`;return this.backupTo(t),this.setSetting("storage.last_backup",{path:t,createdAt:this.now(),reason:e}),t}integrityCheck(){let e=this.database.query("PRAGMA integrity_check").all();return e.length===1&&Object.values(e[0])[0]==="ok"?"ok":"corrupt"}health(){let e=Object.fromEntries(["queued","running","succeeded","failed","cancelled","timed_out"].map((a)=>[a,0]));for(let a of this.database.query("SELECT state, COUNT(*) AS count FROM operations GROUP BY state").all())e[String(a.state)]=Number(a.count);let t=this.database.query("PRAGMA journal_mode").get(),r=this.getSetting("storage.last_backup"),i=r&&!Array.isArray(r)&&typeof r==="object"&&typeof r.createdAt==="string"?r.createdAt:void 0;return{path:this.path,schemaVersion:Number(this.database.query("PRAGMA user_version").get()?.user_version??0),supportedSchemaVersion:l,integrity:this.integrityCheck(),journalMode:String(t?.journal_mode??"unknown"),databaseBytes:this.path!==":memory:"&&Z(this.path)?se(this.path).size:this.database.serialize().byteLength,lastBackupAt:i,operations:e,pendingRetryableOperations:e.queued+e.failed+e.timed_out}}exportSnapshot(){let e={};for(let t of this.database.query("SELECT key, value FROM settings ORDER BY key").all())e[String(t.key)]=_(t.value);return{format:"ts-cloud-control-plane",schemaVersion:l,exportedAt:this.now(),organizations:this.database.query("SELECT * FROM organizations ORDER BY id").all().map(z),memberships:this.database.query("SELECT * FROM organization_memberships ORDER BY id").all().map(k),invitations:this.database.query("SELECT * FROM organization_invitations ORDER BY id").all().map((t)=>({...R(t,this.now()),tokenHash:String(t.token_hash)})),grants:this.database.query("SELECT * FROM authorization_grants ORDER BY id").all().map(w),projects:this.database.query("SELECT * FROM projects ORDER BY id").all().map(v),environments:this.database.query("SELECT * FROM environments ORDER BY id").all().map(D),resources:this.database.query("SELECT * FROM resources ORDER BY id").all().map(y),actors:this.database.query("SELECT * FROM actors ORDER BY id").all().map(f),operations:this.database.query("SELECT * FROM operations ORDER BY id").all().map(u),events:this.database.query("SELECT * FROM events ORDER BY sequence").all().map(Y),settings:e,tags:this.database.query("SELECT * FROM tags ORDER BY id").all().map(O),resourceTags:this.database.query("SELECT * FROM resource_tags ORDER BY resource_id, tag_id").all().map((t)=>({resourceId:String(t.resource_id),tagId:String(t.tag_id),createdAt:String(t.created_at)})),savedFilters:this.database.query("SELECT * FROM saved_filters ORDER BY id").all().map(b),navigationItems:this.database.query("SELECT * FROM navigation_items ORDER BY actor_key, entity_type, entity_id").all().map(F)}}importSnapshot(e,t={}){if(e.format!=="ts-cloud-control-plane")throw Error("Unsupported control-plane snapshot format");if(e.schemaVersion>l)throw new I(e.schemaVersion,l);this.transaction(()=>{if((Number(this.database.query("SELECT COUNT(*) AS count FROM projects").get()?.count??0)>0||Number(this.database.query("SELECT COUNT(*) AS count FROM operations").get()?.count??0)>0)&&!t.replace)throw Error("Control plane is not empty; pass replace: true to import this snapshot");if(t.replace)this.database.run("DELETE FROM authorization_grants"),this.database.run("DELETE FROM organization_invitations"),this.database.run("DELETE FROM organization_memberships"),this.database.run("DELETE FROM resource_tags"),this.database.run("DELETE FROM tags"),this.database.run("DELETE FROM saved_filters"),this.database.run("DELETE FROM navigation_items"),this.database.run("DELETE FROM events"),this.database.run("DELETE FROM operations"),this.database.run("DELETE FROM resources"),this.database.run("DELETE FROM environments"),this.database.run("DELETE FROM projects"),this.database.run("DELETE FROM actors"),this.database.run("DELETE FROM organizations"),this.database.run("DELETE FROM settings");for(let i of e.organizations??[])o(this.database,"INSERT INTO organizations (id, slug, name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",[i.id,i.slug,i.name,i.createdAt,i.updatedAt]);for(let i of e.projects)o(this.database,`INSERT INTO projects (id, slug, name, description, organization_id, desired_config_hash, version, created_at, updated_at)
1498
1498
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.id,i.slug,i.name,i.description??null,i.organizationId??null,i.desiredConfigHash??null,i.version,i.createdAt,i.updatedAt]);for(let i of e.environments)o(this.database,`INSERT INTO environments (id, project_id, slug, name, kind, region, desired_state, discovered_state, version, created_at, updated_at)
1499
1499
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.id,i.projectId,i.slug,i.name,i.kind,i.region??null,N(i.desiredState),N(i.discoveredState),i.version,i.createdAt,i.updatedAt]);for(let i of e.resources)o(this.database,`INSERT INTO resources (id, project_id, environment_id, kind, slug, name, provider, provider_id, desired_state, discovered_state, metadata, version, created_at, updated_at)
1500
1500
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.id,i.projectId,i.environmentId??null,i.kind,i.slug,i.name,i.provider??null,i.providerId??null,N(i.desiredState),N(i.discoveredState),N(i.metadata),i.version,i.createdAt,i.updatedAt]);for(let i of e.actors)o(this.database,`INSERT INTO actors (id, kind, external_id, display_name, metadata, disabled_at, version, created_at, updated_at)
@@ -1504,4 +1504,4 @@ import{A}from"./chunk-dj03v81n.js";var ae=["project:read","config:read","config:
1504
1504
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.id,i.organizationId,i.membershipId,i.effect,i.capability,i.scope.type,i.scope.id??null,i.source??"manual",i.createdAt,i.updatedAt]);for(let i of e.operations)o(this.database,`INSERT INTO operations (id, project_id, environment_id, resource_id, actor_id, kind, state, correlation_id, idempotency_key,
1505
1505
  input, output, error, attempt, priority, lease_owner, lease_expires_at, cancel_requested_at, started_at, finished_at, version, created_at, updated_at)
1506
1506
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.id,i.projectId??null,i.environmentId??null,i.resourceId??null,i.actorId??null,i.kind,i.state,i.correlationId,i.idempotencyKey??null,N(i.input),N(i.output),M(i.error)??null,i.attempt,i.priority,i.leaseOwner??null,i.leaseExpiresAt??null,i.cancelRequestedAt??null,i.startedAt??null,i.finishedAt??null,i.version,i.createdAt,i.updatedAt]);for(let i of e.events)o(this.database,`INSERT INTO events (sequence, id, organization_id, project_id, operation_id, resource_id, actor_id, correlation_id, type, level, payload, created_at)
1507
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.sequence,i.id,i.organizationId??null,i.projectId??null,i.operationId??null,i.resourceId??null,i.actorId??null,i.correlationId,i.type,i.level,N(i.payload),i.createdAt]);for(let[i,a]of Object.entries(e.settings))o(this.database,"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)",[i,N(a),this.now()]);for(let i of e.tags??[])o(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.projectId,i.name,i.normalizedName,i.color,i.createdAt,i.updatedAt]);for(let i of e.resourceTags??[])o(this.database,"INSERT INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[i.resourceId,i.tagId,i.createdAt]);for(let i of e.savedFilters??[])o(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.actorKey,i.name,i.routeId,N(i.query),i.createdAt,i.updatedAt]);for(let i of e.navigationItems??[])o(this.database,"INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at, visit_count) VALUES (?, ?, ?, ?, ?, ?)",[i.actorKey,i.entityType,i.entityId,i.favorite?1:0,i.lastVisitedAt,i.visitCount])})}}var pe=new Set(["domain","domains","hostname","hostnames","url","repository","repo","image","label","labels"]),ue=new Set(["sha","commit","commitsha","release","releaseid"]);function ne(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=[];for(let[i,a]of Object.entries(e)){if(!t.has(i.toLowerCase()))continue;if(typeof a==="string")r.push(a);else if(Array.isArray(a))r.push(...a.filter((E)=>typeof E==="string"))}return r}function Q(e){return e.toLowerCase().trim().replace(/[^a-z0-9._:/@-]+/g," ")}function W(e,t,r){let i=Q(e),a=Q(t),E=Q(r);if(!i)return 0;if(a===i)return 1000;if(a.startsWith(i))return 800-Math.min(100,a.length-i.length);if(a.includes(i))return 650-Math.min(100,a.indexOf(i));let T=i.split(/\s+/).filter(Boolean);if(T.every((c)=>E.includes(c)))return 400+T.length*10;let s=0;for(let c of i){if(s=E.indexOf(c,s),s<0)return 0;s++}return Math.max(1,180-Math.floor(E.length/20))}function Ce(e,t){let r=e.kind.toLowerCase();if(r==="server"||r==="compute")return{type:"server",href:`/server/metrics?env=${encodeURIComponent(t)}`};if(r.includes("database")||["mysql","postgres","postgresql","sqlite","redis"].includes(r))return{type:"database",href:`/server/database?env=${encodeURIComponent(t)}&database=${encodeURIComponent(e.slug)}`};return{type:"service",href:`/server/sites?env=${encodeURIComponent(t)}&service=${encodeURIComponent(e.slug)}`}}function ra(e,t){let r=e.getProject(t.projectId);if(!r)return[];let i=e.listEnvironments(r.id),a=new Map(i.map((n)=>[n.id,n])),E=e.listResourceTags(r.id),T=new Map;for(let n of E){let L=T.get(n.resourceId)??[];L.push({id:n.tag.id,name:n.tag.name,color:n.tag.color}),T.set(n.resourceId,L)}let s=[],c=t.allowedResourceSlugs!==void 0;if(!c){s.push({type:"project",id:r.id,title:r.name,subtitle:r.slug,href:`/?project=${encodeURIComponent(r.slug)}`,tags:[],score:0});for(let n of i)s.push({type:"environment",id:n.id,title:n.name,subtitle:`${r.name} · ${n.kind}`,href:`/?env=${encodeURIComponent(n.slug)}`,environment:n.slug,tags:[],score:0})}let V=e.listResources(r.id).filter((n)=>!t.allowedResourceSlugs||t.allowedResourceSlugs.has(n.slug));for(let n of V){let L=n.environmentId?a.get(n.environmentId):void 0,C=T.get(n.id)??[],U=ne(n.desiredState,pe),m=[n.name,n.slug,n.kind,n.provider,n.providerId,L?.slug,...U,...C.map((Ee)=>Ee.name)].filter(Boolean).join(" "),X=Ce(n,L?.slug??i[0]?.slug??"");s.push({type:X.type,id:n.id,title:n.name,subtitle:[n.kind,...U.slice(0,2)].join(" · "),href:X.href,environment:L?.slug,provider:n.provider,tags:C,score:W(t.query,n.name,m)})}if(!c)for(let n of e.listOperations({projectId:r.id,limit:500})){let L=n.environmentId?a.get(n.environmentId):void 0,C=ne(n.input,ue),U=n.kind.includes("deploy"),m=C[0]??n.kind,X=[n.kind,n.id,n.correlationId,n.state,...C].join(" ");s.push({type:U?"deployment":"operation",id:n.id,title:m,subtitle:`${n.kind} · ${n.state}`,href:`/server/activity?env=${encodeURIComponent(L?.slug??i[0]?.slug??"")}&operation=${encodeURIComponent(n.id)}`,environment:L?.slug,status:n.state,tags:[],score:W(t.query,m,X)})}for(let n of s)if(n.score===0)n.score=W(t.query,n.title,`${n.title} ${n.subtitle} ${n.environment??""} ${n.provider??""}`);let J={service:0,server:1,database:2,deployment:3,environment:4,project:5,operation:6};return s.filter((n)=>n.score>0).sort((n,L)=>L.score-n.score||J[n.type]-J[L.type]||n.title.localeCompare(L.title)||n.id.localeCompare(L.id)).slice(0,Math.min(50,Math.max(1,t.limit??20)))}export{ae,fn,re,hn,h,Or,ra};
1507
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.sequence,i.id,i.organizationId??null,i.projectId??null,i.operationId??null,i.resourceId??null,i.actorId??null,i.correlationId,i.type,i.level,N(i.payload),i.createdAt]);for(let[i,a]of Object.entries(e.settings))o(this.database,"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)",[i,N(a),this.now()]);for(let i of e.tags??[])o(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.projectId,i.name,i.normalizedName,i.color,i.createdAt,i.updatedAt]);for(let i of e.resourceTags??[])o(this.database,"INSERT INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[i.resourceId,i.tagId,i.createdAt]);for(let i of e.savedFilters??[])o(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.actorKey,i.name,i.routeId,N(i.query),i.createdAt,i.updatedAt]);for(let i of e.navigationItems??[])o(this.database,"INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at, visit_count) VALUES (?, ?, ?, ?, ?, ?)",[i.actorKey,i.entityType,i.entityId,i.favorite?1:0,i.lastVisitedAt,i.visitCount])})}}var pe=new Set(["domain","domains","hostname","hostnames","url","repository","repo","image","label","labels"]),ue=new Set(["sha","commit","commitsha","release","releaseid"]);function ae(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=[];for(let[i,a]of Object.entries(e)){if(!t.has(i.toLowerCase()))continue;if(typeof a==="string")r.push(a);else if(Array.isArray(a))r.push(...a.filter((E)=>typeof E==="string"))}return r}function Q(e){return e.toLowerCase().trim().replace(/[^a-z0-9._:/@-]+/g," ")}function W(e,t,r){let i=Q(e),a=Q(t),E=Q(r);if(!i)return 0;if(a===i)return 1000;if(a.startsWith(i))return 800-Math.min(100,a.length-i.length);if(a.includes(i))return 650-Math.min(100,a.indexOf(i));let T=i.split(/\s+/).filter(Boolean);if(T.every((c)=>E.includes(c)))return 400+T.length*10;let s=0;for(let c of i){if(s=E.indexOf(c,s),s<0)return 0;s++}return Math.max(1,180-Math.floor(E.length/20))}function Ce(e,t){let r=e.kind.toLowerCase();if(r==="server"||r==="compute")return{type:"server",href:`/server/metrics?env=${encodeURIComponent(t)}`};if(r.includes("database")||["mysql","postgres","postgresql","sqlite","redis"].includes(r))return{type:"database",href:`/server/database?env=${encodeURIComponent(t)}&database=${encodeURIComponent(e.slug)}`};return{type:"service",href:`/server/sites?env=${encodeURIComponent(t)}&service=${encodeURIComponent(e.slug)}`}}function oa(e,t){let r=e.getProject(t.projectId);if(!r)return[];let i=e.listEnvironments(r.id),a=new Map(i.map((n)=>[n.id,n])),E=e.listResourceTags(r.id),T=new Map;for(let n of E){let L=T.get(n.resourceId)??[];L.push({id:n.tag.id,name:n.tag.name,color:n.tag.color}),T.set(n.resourceId,L)}let s=[],c=t.allowedResourceSlugs!==void 0;if(!c){s.push({type:"project",id:r.id,title:r.name,subtitle:r.slug,href:`/?project=${encodeURIComponent(r.slug)}`,tags:[],score:0});for(let n of i)s.push({type:"environment",id:n.id,title:n.name,subtitle:`${r.name} · ${n.kind}`,href:`/?env=${encodeURIComponent(n.slug)}`,environment:n.slug,tags:[],score:0})}let V=e.listResources(r.id).filter((n)=>!t.allowedResourceSlugs||t.allowedResourceSlugs.has(n.slug));for(let n of V){let L=n.environmentId?a.get(n.environmentId):void 0,C=T.get(n.id)??[],U=ae(n.desiredState,pe),m=[n.name,n.slug,n.kind,n.provider,n.providerId,L?.slug,...U,...C.map((ne)=>ne.name)].filter(Boolean).join(" "),X=Ce(n,L?.slug??i[0]?.slug??"");s.push({type:X.type,id:n.id,title:n.name,subtitle:[n.kind,...U.slice(0,2)].join(" · "),href:X.href,environment:L?.slug,provider:n.provider,tags:C,score:W(t.query,n.name,m)})}if(!c)for(let n of e.listOperations({projectId:r.id,limit:500})){let L=n.environmentId?a.get(n.environmentId):void 0,C=ae(n.input,ue),U=n.kind.includes("deploy"),m=C[0]??n.kind,X=[n.kind,n.id,n.correlationId,n.state,...C].join(" ");s.push({type:U?"deployment":"operation",id:n.id,title:m,subtitle:`${n.kind} · ${n.state}`,href:`/server/activity?env=${encodeURIComponent(L?.slug??i[0]?.slug??"")}&operation=${encodeURIComponent(n.id)}`,environment:L?.slug,status:n.state,tags:[],score:W(t.query,m,X)})}for(let n of s)if(n.score===0)n.score=W(t.query,n.title,`${n.title} ${n.subtitle} ${n.environment??""} ${n.provider??""}`);let J={service:0,server:1,database:2,deployment:3,environment:4,project:5,operation:6};return s.filter((n)=>n.score>0).sort((n,L)=>L.score-n.score||J[n.type]-J[L.type]||n.title.localeCompare(L.title)||n.id.localeCompare(L.id)).slice(0,Math.min(50,Math.max(1,t.limit??20)))}export{ce,bn,re,Sn,h,Lr,oa};
@@ -1,8 +1,8 @@
1
- var l={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},d={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function Ke(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function us(e){if(e.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(e))return!1;if(/\[[^\]]*\][+*]\{/.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}function b(e,r){let t=[],o=[],s=r;for(let n of e){if(n.enabled===!1)continue;if(n.key&&(n.key.source==="cookie"||n.key.source==="header")&&!n.key.name){o.push({ruleId:n.id,reason:"The rule keys on a header or cookie but names none."});continue}let c=n.path?fc(n.path):".*";if(!us(c)){o.push({ruleId:n.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let u=[`SecRule REQUEST_URI "@rx ${Ke(c)}"`];if(n.methods?.length)u.push(` "chain,id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${Ke(n.id)}'"`);else u.push(` "id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${Ke(n.id)}'"`);if(t.push(`# Marks requests governed by the ts-cloud rate limit "${Ke(n.id)}".`),t.push(u.join(" \\\n")),n.methods?.length)t.push(` SecRule REQUEST_METHOD "@within ${Ke(n.methods.join(" ").toUpperCase())}" "t:none"`);t.push(""),s++}return{lines:t,unmapped:o}}function fc(e){return`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function ui(e={},r=[]){let t=e.mode??l.mode,o=[],s=e.paranoiaLevel??l.paranoiaLevel,n=e.inboundThreshold??l.inboundThreshold,c=e.outboundThreshold??l.outboundThreshold,u=e.maxBodyBytes??l.maxBodyBytes,h=e.rejectOversizedBody!==!1;if(t==="blocking"&&s>=3)o.push(`Paranoia level ${s} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(t==="blocking")o.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!h)o.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(e.bypassPaths?.length)o.push(`${e.bypassPaths.length} path(s) bypass inspection entirely.`);let i=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${t}. Paranoia level: ${s}.`,""];if(t==="off")return i.push("SecRuleEngine Off",""),{config:`${i.join(`
1
+ var l={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},d={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function Xe(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function gs(e){if(e.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(e))return!1;if(/\[[^\]]*\][+*]\{/.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}function b(e,r){let t=[],o=[],s=r;for(let n of e){if(n.enabled===!1)continue;if(n.key&&(n.key.source==="cookie"||n.key.source==="header")&&!n.key.name){o.push({ruleId:n.id,reason:"The rule keys on a header or cookie but names none."});continue}let c=n.path?yc(n.path):".*";if(!gs(c)){o.push({ruleId:n.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let u=[`SecRule REQUEST_URI "@rx ${Xe(c)}"`];if(n.methods?.length)u.push(` "chain,id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${Xe(n.id)}'"`);else u.push(` "id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${Xe(n.id)}'"`);if(t.push(`# Marks requests governed by the ts-cloud rate limit "${Xe(n.id)}".`),t.push(u.join(" \\\n")),n.methods?.length)t.push(` SecRule REQUEST_METHOD "@within ${Xe(n.methods.join(" ").toUpperCase())}" "t:none"`);t.push(""),s++}return{lines:t,unmapped:o}}function yc(e){return`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function gi(e={},r=[]){let t=e.mode??l.mode,o=[],s=e.paranoiaLevel??l.paranoiaLevel,n=e.inboundThreshold??l.inboundThreshold,c=e.outboundThreshold??l.outboundThreshold,u=e.maxBodyBytes??l.maxBodyBytes,h=e.rejectOversizedBody!==!1;if(t==="blocking"&&s>=3)o.push(`Paranoia level ${s} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(t==="blocking")o.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!h)o.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(e.bypassPaths?.length)o.push(`${e.bypassPaths.length} path(s) bypass inspection entirely.`);let i=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${t}. Paranoia level: ${s}.`,""];if(t==="off")return i.push("SecRuleEngine Off",""),{config:`${i.join(`
2
2
  `)}
3
- `,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${u}`,`SecRequestBodyNoFilesLimit ${Math.min(u,131072)}`,`SecRequestBodyLimitAction ${h?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${Ke(e.auditLogPath??l.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${t==="blocking"?`deny,status:${e.blockStatus??l.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${s}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${n}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${c}"`,'SecAction "id:900003,phase:1,pass,nolog,t:none,setvar:tx.critical_anomaly_score=5,setvar:tx.error_anomaly_score=4,setvar:tx.warning_anomaly_score=3,setvar:tx.notice_anomaly_score=2"','SecAction "id:900004,phase:1,pass,nolog,t:none,setvar:tx.anomaly_score=0"',"");let g=d.bypassBase;for(let a of e.bypassPaths??[]){let y=fc(a);if(!us(y)){o.push(`Bypass path "${a}" was dropped: it compiles to an unsafe regular expression.`);continue}i.push(`# Inspection bypass for ${Ke(a)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${Ke(y)}" "id:${g},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),g++}let m=d.exclusionBase;for(let a of e.exclusions??[]){if(!Number.isInteger(a.ruleId)||a.ruleId<=0){o.push(`Exclusion with rule id "${a.ruleId}" was dropped: the id is not a positive integer.`);continue}if(i.push(`# ${Ke(a.reason)}`),a.pathPattern){if(!us(a.pathPattern)){o.push(`Exclusion for rule ${a.ruleId} was dropped: its path pattern is unsafe.`);continue}i.push(`SecRule REQUEST_URI "@rx ${Ke(a.pathPattern)}" "id:${m},phase:1,pass,nolog,ctl:ruleRemoveById=${a.ruleId}"`),m++}else i.push(`SecRuleRemoveById ${a.ruleId}`);i.push("")}let p=b(r,d.rateLimitBase);if(p.lines.length>0)i.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...p.lines);let f=d.customBase;for(let a of e.customRules??[])i.push(`# Operator-supplied rule ${f}.`,a.trim(),""),f++;if(t==="blocking")i.push("# Blocking decision: one rule, at the end, on the accumulated score.",`SecRule TX:ANOMALY_SCORE "@ge %{tx.inbound_anomaly_score_threshold}" "id:949110,phase:2,deny,status:${e.blockStatus??l.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${i.join(`
3
+ `,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${u}`,`SecRequestBodyNoFilesLimit ${Math.min(u,131072)}`,`SecRequestBodyLimitAction ${h?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${Xe(e.auditLogPath??l.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${t==="blocking"?`deny,status:${e.blockStatus??l.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${s}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${n}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${c}"`,'SecAction "id:900003,phase:1,pass,nolog,t:none,setvar:tx.critical_anomaly_score=5,setvar:tx.error_anomaly_score=4,setvar:tx.warning_anomaly_score=3,setvar:tx.notice_anomaly_score=2"','SecAction "id:900004,phase:1,pass,nolog,t:none,setvar:tx.anomaly_score=0"',"");let g=d.bypassBase;for(let a of e.bypassPaths??[]){let y=yc(a);if(!gs(y)){o.push(`Bypass path "${a}" was dropped: it compiles to an unsafe regular expression.`);continue}i.push(`# Inspection bypass for ${Xe(a)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${Xe(y)}" "id:${g},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),g++}let m=d.exclusionBase;for(let a of e.exclusions??[]){if(!Number.isInteger(a.ruleId)||a.ruleId<=0){o.push(`Exclusion with rule id "${a.ruleId}" was dropped: the id is not a positive integer.`);continue}if(i.push(`# ${Xe(a.reason)}`),a.pathPattern){if(!gs(a.pathPattern)){o.push(`Exclusion for rule ${a.ruleId} was dropped: its path pattern is unsafe.`);continue}i.push(`SecRule REQUEST_URI "@rx ${Xe(a.pathPattern)}" "id:${m},phase:1,pass,nolog,ctl:ruleRemoveById=${a.ruleId}"`),m++}else i.push(`SecRuleRemoveById ${a.ruleId}`);i.push("")}let p=b(r,d.rateLimitBase);if(p.lines.length>0)i.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...p.lines);let f=d.customBase;for(let a of e.customRules??[])i.push(`# Operator-supplied rule ${f}.`,a.trim(),""),f++;if(t==="blocking")i.push("# Blocking decision: one rule, at the end, on the accumulated score.",`SecRule TX:ANOMALY_SCORE "@ge %{tx.inbound_anomaly_score_threshold}" "id:949110,phase:2,deny,status:${e.blockStatus??l.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${i.join(`
4
4
  `)}
5
- `,unmappedRateLimits:p.unmapped,warnings:o,mode:t}}function ps(e={},r=[],t={}){let o=t.binary??"/usr/local/bin/zig-waf",s=t.configPath??"/etc/ts-cloud/waf.conf",n=ui(e,r);return`#!/usr/bin/env bash
5
+ `,unmappedRateLimits:p.unmapped,warnings:o,mode:t}}function fs(e={},r=[],t={}){let o=t.binary??"/usr/local/bin/zig-waf",s=t.configPath??"/etc/ts-cloud/waf.conf",n=gi(e,r);return`#!/usr/bin/env bash
6
6
  # Managed by ts-cloud. Installs the zig-waf ruleset.
7
7
  set -euo pipefail
8
8
 
@@ -33,5 +33,5 @@ fi
33
33
 
34
34
  mv "${s}.new" "${s}"
35
35
  echo "ts-cloud: WAF config installed (mode: ${n.mode})"
36
- `}function Hp(e,r){return e.map((t)=>({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"event",source:"zig-waf",name:t.action==="blocked"?"waf.blocked":"waf.matched",timestamp:t.timestamp,value:1,host:t.host,pathTemplate:t.path,method:t.method,attributes:{ruleId:t.ruleId??null,anomalyScore:t.anomalyScore,action:t.action,messages:t.messages.slice(0,5)}}))}
37
- export{Ke,us,fc,ui,ps,Hp};
36
+ `}function Gp(e,r){return e.map((t)=>({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"event",source:"zig-waf",name:t.action==="blocked"?"waf.blocked":"waf.matched",timestamp:t.timestamp,value:1,host:t.host,pathTemplate:t.path,method:t.method,attributes:{ruleId:t.ruleId??null,anomalyScore:t.anomalyScore,action:t.action,messages:t.messages.slice(0,5)}}))}
37
+ export{Xe,gs,yc,gi,fs,Gp};
@@ -0,0 +1 @@
1
+ import{W,Ao}from"./chunk-7czb1kgg.js";import"./chunk-rwbdtxte.js";import"./chunk-z06jkvvr.js";export{W as ACMClient,Ao as ACMDnsValidator};
@@ -1,7 +1,7 @@
1
- var Nd={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function h(e){return{...Nd,...e.thresholds}}var _=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function Kr(e){if(!_.test(e))return!1;let[t,n]=e.split("/");if(t.includes(":"))return n==null||Number(n)>=0&&Number(n)<=128;let s=t.split(".");if(s.length!==4||s.some((a)=>Number(a)>255||a===""))return!1;return n==null||Number(n)>=0&&Number(n)<=32}function f(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(Kr))]}function y(e){let t=(e??[80,443]).filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535);return[...new Set(t)].sort((n,s)=>n-s)}function kd(e={}){let t=h(e);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,t.synPerSecond*4)),"net.ipv4.tcp_synack_retries":"2","net.ipv4.tcp_abort_on_overflow":"1","net.ipv4.tcp_fin_timeout":"15","net.ipv4.tcp_keepalive_time":"300","net.ipv4.tcp_keepalive_intvl":"30","net.ipv4.tcp_keepalive_probes":"3","net.core.somaxconn":"4096","net.core.netdev_max_backlog":"16384","net.ipv4.conf.all.rp_filter":"1","net.ipv4.conf.default.rp_filter":"1","net.ipv4.conf.all.accept_source_route":"0","net.ipv4.conf.all.accept_redirects":"0","net.ipv4.conf.all.send_redirects":"0","net.ipv6.conf.all.accept_redirects":"0","net.ipv6.conf.all.accept_source_route":"0","net.ipv4.icmp_echo_ignore_broadcasts":"1","net.ipv4.icmp_ignore_bogus_error_responses":"1","net.netfilter.nf_conntrack_max":"262144","net.netfilter.nf_conntrack_tcp_timeout_established":"3600"}}function Bd(e={}){let t=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[n,s]of Object.entries(kd(e)))t.push(`${n} = ${s}`);return`${t.join(`
1
+ var zd={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function h(e){return{...zd,...e.thresholds}}var _=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function yo(e){if(!_.test(e))return!1;let[t,n]=e.split("/");if(t.includes(":"))return n==null||Number(n)>=0&&Number(n)<=128;let s=t.split(".");if(s.length!==4||s.some((a)=>Number(a)>255||a===""))return!1;return n==null||Number(n)>=0&&Number(n)<=32}function f(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(yo))]}function y(e){let t=(e??[80,443]).filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535);return[...new Set(t)].sort((n,s)=>n-s)}function Hd(e={}){let t=h(e);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,t.synPerSecond*4)),"net.ipv4.tcp_synack_retries":"2","net.ipv4.tcp_abort_on_overflow":"1","net.ipv4.tcp_fin_timeout":"15","net.ipv4.tcp_keepalive_time":"300","net.ipv4.tcp_keepalive_intvl":"30","net.ipv4.tcp_keepalive_probes":"3","net.core.somaxconn":"4096","net.core.netdev_max_backlog":"16384","net.ipv4.conf.all.rp_filter":"1","net.ipv4.conf.default.rp_filter":"1","net.ipv4.conf.all.accept_source_route":"0","net.ipv4.conf.all.accept_redirects":"0","net.ipv4.conf.all.send_redirects":"0","net.ipv6.conf.all.accept_redirects":"0","net.ipv6.conf.all.accept_source_route":"0","net.ipv4.icmp_echo_ignore_broadcasts":"1","net.ipv4.icmp_ignore_bogus_error_responses":"1","net.netfilter.nf_conntrack_max":"262144","net.netfilter.nf_conntrack_tcp_timeout_established":"3600"}}function qd(e={}){let t=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[n,s]of Object.entries(Hd(e)))t.push(`${n} = ${s}`);return`${t.join(`
2
2
  `)}
3
- `}function xd(e={}){let t=h(e),n=y(e.ports),s=f(e.allowlist),a=f(e.blocklist),l=e.monitorOnly?"counter":"counter drop",i=e.originProtection?.enabled?f(e.originProtection.cdnRanges):[],c=s.filter((r)=>!r.includes(":")),p=s.filter((r)=>r.includes(":")),u=a.filter((r)=>!r.includes(":")),o=["#!/usr/sbin/nft -f","# Managed by ts-cloud. Edits are overwritten on the next deploy.","","table inet ts_cloud_ddos","delete table inet ts_cloud_ddos","","table inet ts_cloud_ddos {"," # Sources that tripped a limit, with a timeout so a ban self-expires.",` set banned4 { type ipv4_addr; flags timeout; timeout ${t.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${t.banSeconds}s; }`];if(c.length>0)o.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${c.join(", ")} } }`);if(p.length>0)o.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${p.join(", ")} } }`);if(u.length>0)o.push(` set block4 { type ipv4_addr; flags interval; elements = { ${u.join(", ")} } }`);if(i.length>0)o.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${i.filter((r)=>!r.includes(":")).join(", ")} } }`);if(o.push(""," chain input {"," type filter hook input priority -150; policy accept;",""," # Established traffic is already paid for; never re-inspect it."," ct state established,related accept"," iif lo accept",""," # Invalid packets are never legitimate and are cheap to drop early."," ct state invalid counter drop"),c.length>0)o.push(" ip saddr @allow4 accept");if(p.length>0)o.push(" ip6 saddr @allow6 accept");if(u.length>0)o.push(" ip saddr @block4 counter drop");if(o.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),o.push(" # Nonsense TCP flag combinations: scanners and stack fingerprinting."," tcp flags & (fin|syn) == (fin|syn) counter drop"," tcp flags & (syn|rst) == (syn|rst) counter drop"," tcp flags & (fin|rst) == (fin|rst) counter drop"," tcp flags & (fin|ack) == fin counter drop"," tcp flags & (syn|fin|ack|rst|psh|urg) == 0x0 counter drop",""," # Ping stays usable, ping floods do not.",` ip protocol icmp icmp type echo-request limit rate ${t.icmpPerSecond}/second burst ${t.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),n.length>0){let r=n.join(", ");if(o.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${r} } ct state new limit rate ${t.synPerSecond}/second burst ${t.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${r} } ct state new meter conn_rate4 { ip saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned4 { ip saddr } ${l}`,` tcp dport { ${r} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned6 { ip6 saddr } ${l}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${r} } ct state new meter conn_count4 { ip saddr ct count over ${t.concurrentPerSource} } ${l}`,` tcp dport { ${r} } ct state new meter conn_count6 { ip6 saddr ct count over ${t.concurrentPerSource} } ${l}`,""),i.length>0)o.push(" # Origin protection: reject traffic that skipped the CDN and came"," # straight to the box, which is how an attacker bypasses the edge.",` tcp dport { ${r} } ip saddr != @cdn4 counter drop`,"")}return o.push(" }","}",""),o.join(`
4
- `)}function $i(e={}){return`#!/usr/bin/env bash
3
+ `}function Gd(e={}){let t=h(e),n=y(e.ports),s=f(e.allowlist),a=f(e.blocklist),l=e.monitorOnly?"counter":"counter drop",i=e.originProtection?.enabled?f(e.originProtection.cdnRanges):[],c=s.filter((r)=>!r.includes(":")),p=s.filter((r)=>r.includes(":")),u=a.filter((r)=>!r.includes(":")),o=["#!/usr/sbin/nft -f","# Managed by ts-cloud. Edits are overwritten on the next deploy.","","table inet ts_cloud_ddos","delete table inet ts_cloud_ddos","","table inet ts_cloud_ddos {"," # Sources that tripped a limit, with a timeout so a ban self-expires.",` set banned4 { type ipv4_addr; flags timeout; timeout ${t.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${t.banSeconds}s; }`];if(c.length>0)o.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${c.join(", ")} } }`);if(p.length>0)o.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${p.join(", ")} } }`);if(u.length>0)o.push(` set block4 { type ipv4_addr; flags interval; elements = { ${u.join(", ")} } }`);if(i.length>0)o.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${i.filter((r)=>!r.includes(":")).join(", ")} } }`);if(o.push(""," chain input {"," type filter hook input priority -150; policy accept;",""," # Established traffic is already paid for; never re-inspect it."," ct state established,related accept"," iif lo accept",""," # Invalid packets are never legitimate and are cheap to drop early."," ct state invalid counter drop"),c.length>0)o.push(" ip saddr @allow4 accept");if(p.length>0)o.push(" ip6 saddr @allow6 accept");if(u.length>0)o.push(" ip saddr @block4 counter drop");if(o.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),o.push(" # Nonsense TCP flag combinations: scanners and stack fingerprinting."," tcp flags & (fin|syn) == (fin|syn) counter drop"," tcp flags & (syn|rst) == (syn|rst) counter drop"," tcp flags & (fin|rst) == (fin|rst) counter drop"," tcp flags & (fin|ack) == fin counter drop"," tcp flags & (syn|fin|ack|rst|psh|urg) == 0x0 counter drop",""," # Ping stays usable, ping floods do not.",` ip protocol icmp icmp type echo-request limit rate ${t.icmpPerSecond}/second burst ${t.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),n.length>0){let r=n.join(", ");if(o.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${r} } ct state new limit rate ${t.synPerSecond}/second burst ${t.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${r} } ct state new meter conn_rate4 { ip saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned4 { ip saddr } ${l}`,` tcp dport { ${r} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned6 { ip6 saddr } ${l}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${r} } ct state new meter conn_count4 { ip saddr ct count over ${t.concurrentPerSource} } ${l}`,` tcp dport { ${r} } ct state new meter conn_count6 { ip6 saddr ct count over ${t.concurrentPerSource} } ${l}`,""),i.length>0)o.push(" # Origin protection: reject traffic that skipped the CDN and came"," # straight to the box, which is how an attacker bypasses the edge.",` tcp dport { ${r} } ip saddr != @cdn4 counter drop`,"")}return o.push(" }","}",""),o.join(`
4
+ `)}function Er(e={}){return`#!/usr/bin/env bash
5
5
  # Managed by ts-cloud. Installs L3/L4 flood mitigation.
6
6
  set -euo pipefail
7
7
 
@@ -13,11 +13,11 @@ fi
13
13
 
14
14
  install -d -m 0755 /etc/ts-cloud /etc/nftables.d
15
15
  cat > /etc/sysctl.d/90-ts-cloud-ddos.conf <<'SYSCTL_EOF'
16
- ${Bd(e)}SYSCTL_EOF
16
+ ${qd(e)}SYSCTL_EOF
17
17
  sysctl --system >/dev/null
18
18
 
19
19
  cat > /etc/nftables.d/ts-cloud-ddos.nft.new <<'NFT_EOF'
20
- ${xd(e)}NFT_EOF
20
+ ${Gd(e)}NFT_EOF
21
21
 
22
22
  # Syntax-check before applying: a bad ruleset would leave the box unprotected.
23
23
  if ! nft -c -f /etc/nftables.d/ts-cloud-ddos.nft.new; then
@@ -40,5 +40,5 @@ include "/etc/nftables.d/ts-cloud-ddos.nft"
40
40
  fi
41
41
  systemctl enable nftables >/dev/null 2>&1 || true
42
42
  echo "ts-cloud: L3/L4 mitigation active"
43
- `}var b=["off","monitor","rate_limit","challenge","lockdown"];function qp(e,t=[]){let n=[],s=Math.max(1,e.baselineRequestsPerSecond),a=e.requestsPerSecond/s,l=0,i=(g,v)=>{n.push(v),l=Math.max(l,b.indexOf(g))},c=a>=3;if(c)i("monitor",`Traffic is ${a.toFixed(1)}x the baseline.`);let p=e.topSourceShare>=0.25,u=e.errorRate>=0.25,o=(e.suspiciousAgentShare??0)>=0.5,r=e.uniqueSources>0&&e.requestsPerSecond/e.uniqueSources>=50;if(c&&p)i("rate_limit",`One source accounts for ${(e.topSourceShare*100).toFixed(0)}% of traffic.`);if(c&&r)i("rate_limit","Request rate per unique source is far above what a browser produces.");if(c&&u)i("challenge",`Error rate is ${(e.errorRate*100).toFixed(0)}% under load.`);if(c&&o)i("challenge","Most requests carry no recognisable browser agent.");if(a>=20&&(p||u||o||r))i("lockdown",`Traffic is ${a.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!c&&e.topSourceShare>=0.6&&e.requestsPerSecond>s)i("rate_limit","A single source dominates traffic without an overall surge.");let d=b[l],m={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[d];return{level:d,reasons:n,rateLimitFactor:m,challengeEnabled:d==="challenge"||d==="lockdown",staticOnly:d==="lockdown",banCandidates:d==="off"||d==="monitor"?[]:f(t)}}function Wr(e,t){return Math.max(1,Math.floor(e*t.rateLimitFactor))}
44
- export{Nd,Kr,kd,Bd,xd,$i,qp,Wr};
43
+ `}var b=["off","monitor","rate_limit","challenge","lockdown"];function am(e,t=[]){let n=[],s=Math.max(1,e.baselineRequestsPerSecond),a=e.requestsPerSecond/s,l=0,i=(g,v)=>{n.push(v),l=Math.max(l,b.indexOf(g))},c=a>=3;if(c)i("monitor",`Traffic is ${a.toFixed(1)}x the baseline.`);let p=e.topSourceShare>=0.25,u=e.errorRate>=0.25,o=(e.suspiciousAgentShare??0)>=0.5,r=e.uniqueSources>0&&e.requestsPerSecond/e.uniqueSources>=50;if(c&&p)i("rate_limit",`One source accounts for ${(e.topSourceShare*100).toFixed(0)}% of traffic.`);if(c&&r)i("rate_limit","Request rate per unique source is far above what a browser produces.");if(c&&u)i("challenge",`Error rate is ${(e.errorRate*100).toFixed(0)}% under load.`);if(c&&o)i("challenge","Most requests carry no recognisable browser agent.");if(a>=20&&(p||u||o||r))i("lockdown",`Traffic is ${a.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!c&&e.topSourceShare>=0.6&&e.requestsPerSecond>s)i("rate_limit","A single source dominates traffic without an overall surge.");let d=b[l],m={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[d];return{level:d,reasons:n,rateLimitFactor:m,challengeEnabled:d==="challenge"||d==="lockdown",staticOnly:d==="lockdown",banCandidates:d==="off"||d==="monitor"?[]:f(t)}}function bo(e,t){return Math.max(1,Math.floor(e*t.rateLimitFactor))}
44
+ export{zd,yo,Hd,qd,Gd,Er,am,bo};