An open-source, faster Devin alternative
TypeScript
parity phase 1
Brian Reardon904a46b49951
diff --git a/.gitignore b/.gitignoreindex 0d870b97..27c06806 100644--- a/.gitignore+++ b/.gitignore@@ -29,6 +29,9 @@ __pycache__/# Nodenode_modules/+# api-edge Workers Assets — copied from web/dist at deploy time. Source of truth lives in web/.+cloudflare-workers/api-edge/assets/+# Build artifactsdist/diff --git a/cloudflare-workers/api-edge/package-lock.json b/cloudflare-workers/api-edge/package-lock.jsonindex 687e263b..5d814af3 100644--- a/cloudflare-workers/api-edge/package-lock.json+++ b/cloudflare-workers/api-edge/package-lock.json@@ -11,31 +11,28 @@"@cloudflare/workers-types": "^4.20240924.0","typescript": "^5.5.0","vitest": "^2.0.0",- "wrangler": "^3.78.0"+ "wrangler": "^4.92.0"}},"node_modules/@cloudflare/kv-asset-handler": {- "version": "0.3.4",- "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.3.4.tgz",- "integrity": "sha512-YLPHc8yASwjNkmcDMQMY35yiWjoKAKnhUbPRszBRS0YgH+IXtsMp61j+yTcnCE3oO2DgP0U3iejLC8FTtKDC8Q==",+ "version": "0.5.0",+ "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.0.tgz",+ "integrity": "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==","dev": true,"license": "MIT OR Apache-2.0",- "dependencies": {- "mime": "^3.0.0"- },"engines": {- "node": ">=16.13"+ "node": ">=22.0.0"}},"node_modules/@cloudflare/unenv-preset": {- "version": "2.0.2",- "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.0.2.tgz",- "integrity": "sha512-nyzYnlZjjV5xT3LizahG1Iu6mnrCaxglJ04rZLpDwlDVDZ7v46lNsfxhV3A/xtfgQuSHmLnc6SVI+KwBpc3Lwg==",+ "version": "2.16.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.1.tgz",+ "integrity": "sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw==","dev": true,"license": "MIT OR Apache-2.0","peerDependencies": {- "unenv": "2.0.0-rc.14",- "workerd": "^1.20250124.0"+ "unenv": "2.0.0-rc.24",+ "workerd": ">1.20260305.0 <2.0.0-0"},"peerDependenciesMeta": {"workerd": {@@ -44,9 +41,9 @@}},"node_modules/@cloudflare/workerd-darwin-64": {- "version": "1.20250718.0",- "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20250718.0.tgz",- "integrity": "sha512-FHf4t7zbVN8yyXgQ/r/GqLPaYZSGUVzeR7RnL28Mwj2djyw2ZergvytVc7fdGcczl6PQh+VKGfZCfUqpJlbi9g==",+ "version": "1.20260515.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20260515.1.tgz",+ "integrity": "sha512-Wtw44el2pNbzixvTkWdfeBDTrQwQbJRz7/JUvPKV27I0pQWXbhNJPpM8cstq/pbrU5AGcA/HjFH6yPMRTIRKig==","cpu": ["x64"],@@ -61,9 +58,9 @@}},"node_modules/@cloudflare/workerd-darwin-arm64": {- "version": "1.20250718.0",- "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20250718.0.tgz",- "integrity": "sha512-fUiyUJYyqqp4NqJ0YgGtp4WJh/II/YZsUnEb6vVy5Oeas8lUOxnN+ZOJ8N/6/5LQCVAtYCChRiIrBbfhTn5Z8Q==",+ "version": "1.20260515.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20260515.1.tgz",+ "integrity": "sha512-X8EqkZej6FfmhF9AVAQ3FhyQRr9acS4RcDunMU2YiuxKHF1IU8zzH3vY30/POaG+rUu9vGDp/VgUl49VPenHJQ==","cpu": ["arm64"],@@ -78,9 +75,9 @@}},"node_modules/@cloudflare/workerd-linux-64": {- "version": "1.20250718.0",- "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20250718.0.tgz",- "integrity": "sha512-5+eb3rtJMiEwp08Kryqzzu8d1rUcK+gdE442auo5eniMpT170Dz0QxBrqkg2Z48SFUPYbj+6uknuA5tzdRSUSg==",+ "version": "1.20260515.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20260515.1.tgz",+ "integrity": "sha512-CDC89QxQ7Y7t7RG1Jd9vj/qolE1sQRkI2OSEuV5BMJi0vW/gV4OVG6xjpdK3b1OYnSWDzF7NpvlR5Yg86q7k4g==","cpu": ["x64"],@@ -95,9 +92,9 @@}},"node_modules/@cloudflare/workerd-linux-arm64": {- "version": "1.20250718.0",- "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20250718.0.tgz",- "integrity": "sha512-Aa2M/DVBEBQDdATMbn217zCSFKE+ud/teS+fFS+OQqKABLn0azO2qq6ANAHYOIE6Q3Sq4CxDIQr8lGdaJHwUog==",+ "version": "1.20260515.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20260515.1.tgz",+ "integrity": "sha512-WxbW/PToYES4fvHXzsr/5qOiETQs/Z9iZ0mjSZAiEwq5cMLZemzGN0COx+uFb9OvQwzh6Pg159qPFnw3+i9FuA==","cpu": ["arm64"],@@ -112,9 +109,9 @@}},"node_modules/@cloudflare/workerd-windows-64": {- "version": "1.20250718.0",- "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20250718.0.tgz",- "integrity": "sha512-dY16RXKffmugnc67LTbyjdDHZn5NoTF1yHEf2fN4+OaOnoGSp3N1x77QubTDwqZ9zECWxgQfDLjddcH8dWeFhg==",+ "version": "1.20260515.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20260515.1.tgz",+ "integrity": "sha512-WmV/iv+MHjYsvkcMVzpM2B5/mf06UUkdpVhZrtMfV9graWjBGPYFvE/eab8748RPVGKh1Xe1vXofLzDSwc08lA==","cpu": ["x64"],@@ -129,9 +126,9 @@}},"node_modules/@cloudflare/workers-types": {- "version": "4.20260426.1",- "resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20260426.1.tgz",- "integrity": "sha512-cBYeQaWwv/jFV8ualmwp6wIxmAf0rDe2DPPQwPbslKmPHqgv861YpAvm45r05K40QboZgxNQVIPgNkmtHqZeJQ==",+ "version": "4.20260518.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20260518.1.tgz",+ "integrity": "sha512-xXzGrbRi8RHRBNQFgXYkzrB4DgF0RXvmp8E1vCxoBmINpeitM/ZjVDd1CNC+N3uXjgcNjacoz4OgTa0rxgig1A==","dev": true,"license": "MIT OR Apache-2.0"},@@ -159,30 +156,6 @@"tslib": "^2.4.0"}},- "node_modules/@esbuild-plugins/node-globals-polyfill": {- "version": "0.2.3",- "resolved": "https://registry.npmjs.org/@esbuild-plugins/node-globals-polyfill/-/node-globals-polyfill-0.2.3.tgz",- "integrity": "sha512-r3MIryXDeXDOZh7ih1l/yE9ZLORCd5e8vWg02azWRGj5SPTuoh69A2AIyn0Z31V/kHBfZ4HgWJ+OK3GTTwLmnw==",- "dev": true,- "license": "ISC",- "peerDependencies": {- "esbuild": "*"- }- },- "node_modules/@esbuild-plugins/node-modules-polyfill": {- "version": "0.2.2",- "resolved": "https://registry.npmjs.org/@esbuild-plugins/node-modules-polyfill/-/node-modules-polyfill-0.2.2.tgz",- "integrity": "sha512-LXV7QsWJxRuMYvKbiznh+U1ilIop3g2TeKRzUxOG5X3YITc8JyyTa90BmLwqqv0YnX4v32CSlG+vsziZp9dMvA==",- "dev": true,- "license": "ISC",- "dependencies": {- "escape-string-regexp": "^4.0.0",- "rollup-plugin-node-polyfills": "^0.2.1"- },- "peerDependencies": {- "esbuild": "*"- }- },"node_modules/@esbuild/aix-ppc64": {"version": "0.21.5","resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",@@ -472,6 +445,23 @@"node": ">=12"}},+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.3.tgz",+ "integrity": "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },"node_modules/@esbuild/netbsd-x64": {"version": "0.21.5","resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",@@ -489,6 +479,23 @@"node": ">=12"}},+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.3.tgz",+ "integrity": "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },"node_modules/@esbuild/openbsd-x64": {"version": "0.21.5","resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",@@ -506,6 +513,23 @@"node": ">=12"}},+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.3.tgz",+ "integrity": "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },"node_modules/@esbuild/sunos-x64": {"version": "0.21.5","resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",@@ -574,20 +598,20 @@"node": ">=12"}},- "node_modules/@fastify/busboy": {- "version": "2.1.1",- "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.1.tgz",- "integrity": "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==",+ "node_modules/@img/colour": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",+ "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==","dev": true,"license": "MIT","engines": {- "node": ">=14"+ "node": ">=18"}},"node_modules/@img/sharp-darwin-arm64": {- "version": "0.33.5",- "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz",- "integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==",+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz",+ "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==","cpu": ["arm64"],@@ -604,13 +628,13 @@"url": "https://opencollective.com/libvips"},"optionalDependencies": {- "@img/sharp-libvips-darwin-arm64": "1.0.4"+ "@img/sharp-libvips-darwin-arm64": "1.2.4"}},"node_modules/@img/sharp-darwin-x64": {- "version": "0.33.5",- "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz",- "integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==",+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz",+ "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==","cpu": ["x64"],@@ -627,13 +651,13 @@"url": "https://opencollective.com/libvips"},"optionalDependencies": {- "@img/sharp-libvips-darwin-x64": "1.0.4"+ "@img/sharp-libvips-darwin-x64": "1.2.4"}},"node_modules/@img/sharp-libvips-darwin-arm64": {- "version": "1.0.4",- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz",- "integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==",+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz",+ "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==","cpu": ["arm64"],@@ -648,9 +672,9 @@}},"node_modules/@img/sharp-libvips-darwin-x64": {- "version": "1.0.4",- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz",- "integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==",+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz",+ "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==","cpu": ["x64"],@@ -665,9 +689,9 @@}},"node_modules/@img/sharp-libvips-linux-arm": {- "version": "1.0.5",- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz",- "integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==",+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz",+ "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==","cpu": ["arm"],@@ -682,9 +706,9 @@}},"node_modules/@img/sharp-libvips-linux-arm64": {- "version": "1.0.4",- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz",- "integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==",+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz",+ "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==","cpu": ["arm64"],@@ -698,10 +722,44 @@"url": "https://opencollective.com/libvips"}},+ "node_modules/@img/sharp-libvips-linux-ppc64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz",+ "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-riscv64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz",+ "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },"node_modules/@img/sharp-libvips-linux-s390x": {- "version": "1.0.4",- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.0.4.tgz",- "integrity": "sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==",+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz",+ "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==","cpu": ["s390x"],@@ -716,9 +774,9 @@}},"node_modules/@img/sharp-libvips-linux-x64": {- "version": "1.0.4",- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz",- "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==",+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz",+ "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==","cpu": ["x64"],@@ -733,9 +791,9 @@}},"node_modules/@img/sharp-libvips-linuxmusl-arm64": {- "version": "1.0.4",- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.0.4.tgz",- "integrity": "sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==",+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz",+ "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==","cpu": ["arm64"],@@ -750,9 +808,9 @@}},"node_modules/@img/sharp-libvips-linuxmusl-x64": {- "version": "1.0.4",- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.0.4.tgz",- "integrity": "sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==",+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz",+ "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==","cpu": ["x64"],@@ -767,9 +825,9 @@}},"node_modules/@img/sharp-linux-arm": {- "version": "0.33.5",- "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz",- "integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==",+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz",+ "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==","cpu": ["arm"],@@ -786,13 +844,13 @@"url": "https://opencollective.com/libvips"},"optionalDependencies": {- "@img/sharp-libvips-linux-arm": "1.0.5"+ "@img/sharp-libvips-linux-arm": "1.2.4"}},"node_modules/@img/sharp-linux-arm64": {- "version": "0.33.5",- "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz",- "integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==",+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz",+ "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==","cpu": ["arm64"],@@ -809,13 +867,59 @@"url": "https://opencollective.com/libvips"},"optionalDependencies": {- "@img/sharp-libvips-linux-arm64": "1.0.4"+ "@img/sharp-libvips-linux-arm64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-ppc64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz",+ "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-ppc64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-riscv64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz",+ "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-riscv64": "1.2.4"}},"node_modules/@img/sharp-linux-s390x": {- "version": "0.33.5",- "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.33.5.tgz",- "integrity": "sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==",+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz",+ "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==","cpu": ["s390x"],@@ -832,13 +936,13 @@"url": "https://opencollective.com/libvips"},"optionalDependencies": {- "@img/sharp-libvips-linux-s390x": "1.0.4"+ "@img/sharp-libvips-linux-s390x": "1.2.4"}},"node_modules/@img/sharp-linux-x64": {- "version": "0.33.5",- "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz",- "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==",+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz",+ "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==","cpu": ["x64"],@@ -855,13 +959,13 @@"url": "https://opencollective.com/libvips"},"optionalDependencies": {- "@img/sharp-libvips-linux-x64": "1.0.4"+ "@img/sharp-libvips-linux-x64": "1.2.4"}},"node_modules/@img/sharp-linuxmusl-arm64": {- "version": "0.33.5",- "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.33.5.tgz",- "integrity": "sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==",+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz",+ "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==","cpu": ["arm64"],@@ -878,13 +982,13 @@"url": "https://opencollective.com/libvips"},"optionalDependencies": {- "@img/sharp-libvips-linuxmusl-arm64": "1.0.4"+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.4"}},"node_modules/@img/sharp-linuxmusl-x64": {- "version": "0.33.5",- "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.33.5.tgz",- "integrity": "sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==",+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz",+ "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==","cpu": ["x64"],@@ -901,13 +1005,13 @@"url": "https://opencollective.com/libvips"},"optionalDependencies": {- "@img/sharp-libvips-linuxmusl-x64": "1.0.4"+ "@img/sharp-libvips-linuxmusl-x64": "1.2.4"}},"node_modules/@img/sharp-wasm32": {- "version": "0.33.5",- "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.33.5.tgz",- "integrity": "sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==",+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz",+ "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==","cpu": ["wasm32"],@@ -915,8 +1019,28 @@"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT","optional": true,"dependencies": {- "@emnapi/runtime": "^1.2.0"+ "@emnapi/runtime": "^1.7.0"+ },+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"},+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz",+ "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -925,9 +1049,9 @@}},"node_modules/@img/sharp-win32-ia32": {- "version": "0.33.5",- "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.33.5.tgz",- "integrity": "sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==",+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz",+ "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==","cpu": ["ia32"],@@ -945,9 +1069,9 @@}},"node_modules/@img/sharp-win32-x64": {- "version": "0.33.5",- "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz",- "integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==",+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz",+ "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==","cpu": ["x64"],@@ -992,6 +1116,35 @@"@jridgewell/sourcemap-codec": "^1.4.10"}},+ "node_modules/@poppinss/colors": {+ "version": "4.1.6",+ "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz",+ "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "kleur": "^4.1.5"+ }+ },+ "node_modules/@poppinss/dumper": {+ "version": "0.6.5",+ "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz",+ "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@poppinss/colors": "^4.1.5",+ "@sindresorhus/is": "^7.0.2",+ "supports-color": "^10.0.0"+ }+ },+ "node_modules/@poppinss/exception": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz",+ "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@rollup/rollup-android-arm-eabi": {"version": "4.60.2","resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.2.tgz",@@ -1342,6 +1495,26 @@"win32"]},+ "node_modules/@sindresorhus/is": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz",+ "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/is?sponsor=1"+ }+ },+ "node_modules/@speed-highlight/core": {+ "version": "1.2.15",+ "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.15.tgz",+ "integrity": "sha512-BMq1K3DsElxDWawkX6eLg9+CKJrTVGCBAWVuHXVUV2u0s2711qiChLSId6ikYPfxhdYocLNt3wWwSvDiTvFabw==",+ "dev": true,+ "license": "CC0-1.0"+ },"node_modules/@types/estree": {"version": "1.0.8","resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",@@ -1462,39 +1635,6 @@"url": "https://opencollective.com/vitest"}},- "node_modules/acorn": {- "version": "8.14.0",- "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz",- "integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==",- "dev": true,- "license": "MIT",- "bin": {- "acorn": "bin/acorn"- },- "engines": {- "node": ">=0.4.0"- }- },- "node_modules/acorn-walk": {- "version": "8.3.2",- "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.2.tgz",- "integrity": "sha512-cjkyv4OtNCIeqhHrfS81QWXoCBPExR/J62oyEqepVw8WaQeSqpW2uhuLPh1m9eWhDuOo/jUXVTlifvesOWp/4A==",- "dev": true,- "license": "MIT",- "engines": {- "node": ">=0.4.0"- }- },- "node_modules/as-table": {- "version": "1.0.55",- "resolved": "https://registry.npmjs.org/as-table/-/as-table-1.0.55.tgz",- "integrity": "sha512-xvsWESUJn0JN421Xb9MQw6AsMHRCUknCe0Wjlxvjud80mU4E6hQf1A6NzQKcYNmYw62MfzEtXc+badstZP3JpQ==",- "dev": true,- "license": "MIT",- "dependencies": {- "printable-characters": "^1.0.42"- }- },"node_modules/assertion-error": {"version": "2.0.1","resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",@@ -1549,72 +1689,20 @@"node": ">= 16"}},- "node_modules/color": {- "version": "4.2.3",- "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz",- "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==",- "dev": true,- "license": "MIT",- "optional": true,- "dependencies": {- "color-convert": "^2.0.1",- "color-string": "^1.9.0"- },- "engines": {- "node": ">=12.5.0"- }- },- "node_modules/color-convert": {- "version": "2.0.1",- "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",- "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",- "dev": true,- "license": "MIT",- "optional": true,- "dependencies": {- "color-name": "~1.1.4"- },- "engines": {- "node": ">=7.0.0"- }- },- "node_modules/color-name": {- "version": "1.1.4",- "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",- "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",- "dev": true,- "license": "MIT",- "optional": true- },- "node_modules/color-string": {- "version": "1.9.1",- "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz",- "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==",- "dev": true,- "license": "MIT",- "optional": true,- "dependencies": {- "color-name": "^1.0.0",- "simple-swizzle": "^0.2.2"- }- },"node_modules/cookie": {- "version": "0.7.2",- "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",- "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",+ "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==","dev": true,"license": "MIT","engines": {- "node": ">= 0.6"+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"}},- "node_modules/data-uri-to-buffer": {- "version": "2.0.2",- "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-2.0.2.tgz",- "integrity": "sha512-ND9qDTLc6diwj+Xe5cdAgVTbLVdXbtxTJRXRhli8Mowuaan+0EJOtdqJ0QCHNSSPyoXGx9HX2/VMnKeC34AChA==",- "dev": true,- "license": "MIT"- },"node_modules/debug": {"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",@@ -1643,24 +1731,26 @@"node": ">=6"}},- "node_modules/defu": {- "version": "6.1.7",- "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz",- "integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==",- "dev": true,- "license": "MIT"- },"node_modules/detect-libc": {"version": "2.1.2","resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz","integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==","dev": true,"license": "Apache-2.0",- "optional": true,"engines": {"node": ">=8"}},+ "node_modules/error-stack-parser-es": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz",+ "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/antfu"+ }+ },"node_modules/es-module-lexer": {"version": "1.7.0","resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",@@ -1707,19 +1797,6 @@"@esbuild/win32-x64": "0.21.5"}},- "node_modules/escape-string-regexp": {- "version": "4.0.0",- "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",- "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",- "dev": true,- "license": "MIT",- "engines": {- "node": ">=10"- },- "funding": {- "url": "https://github.com/sponsors/sindresorhus"- }- },"node_modules/estree-walker": {"version": "3.0.3","resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",@@ -1730,19 +1807,6 @@"@types/estree": "^1.0.0"}},- "node_modules/exit-hook": {- "version": "2.2.1",- "resolved": "https://registry.npmjs.org/exit-hook/-/exit-hook-2.2.1.tgz",- "integrity": "sha512-eNTPlAD67BmP31LDINZ3U7HSF8l57TxOY2PmBJ1shpCvpnxBF93mWCE8YHBnXs8qiUZJc9WDcWIeC3a2HIAMfw==",- "dev": true,- "license": "MIT",- "engines": {- "node": ">=6"- },- "funding": {- "url": "https://github.com/sponsors/sindresorhus"- }- },"node_modules/expect-type": {"version": "1.3.0","resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz",@@ -1753,13 +1817,6 @@"node": ">=12.0.0"}},- "node_modules/exsolve": {- "version": "1.0.8",- "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.0.8.tgz",- "integrity": "sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==",- "dev": true,- "license": "MIT"- },"node_modules/fsevents": {"version": "2.3.3","resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",@@ -1775,31 +1832,15 @@"node": "^8.16.0 || ^10.6.0 || >=11.0.0"}},- "node_modules/get-source": {- "version": "2.0.12",- "resolved": "https://registry.npmjs.org/get-source/-/get-source-2.0.12.tgz",- "integrity": "sha512-X5+4+iD+HoSeEED+uwrQ07BOQr0kEDFMVqqpBuI+RaZBpBpHCuXxo70bjar6f0b0u/DQJsJ7ssurpP0V60Az+w==",- "dev": true,- "license": "Unlicense",- "dependencies": {- "data-uri-to-buffer": "^2.0.0",- "source-map": "^0.6.1"- }- },- "node_modules/glob-to-regexp": {- "version": "0.4.1",- "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz",- "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==",- "dev": true,- "license": "BSD-2-Clause"- },- "node_modules/is-arrayish": {- "version": "0.3.4",- "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.4.tgz",- "integrity": "sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==",+ "node_modules/kleur": {+ "version": "4.1.5",+ "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",+ "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==","dev": true,"license": "MIT",- "optional": true+ "engines": {+ "node": ">=6"+ }},"node_modules/loupe": {"version": "3.2.1",@@ -1818,43 +1859,25 @@"@jridgewell/sourcemap-codec": "^1.5.5"}},- "node_modules/mime": {- "version": "3.0.0",- "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz",- "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==",- "dev": true,- "license": "MIT",- "bin": {- "mime": "cli.js"- },- "engines": {- "node": ">=10.0.0"- }- },"node_modules/miniflare": {- "version": "3.20250718.3",- "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-3.20250718.3.tgz",- "integrity": "sha512-JuPrDJhwLrNLEJiNLWO7ZzJrv/Vv9kZuwMYCfv0LskQDM6Eonw4OvywO3CH/wCGjgHzha/qyjUh8JQ068TjDgQ==",+ "version": "4.20260515.0",+ "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-4.20260515.0.tgz",+ "integrity": "sha512-2j0oQWizk1Eu4Cm8tDX7Z+Nsjd0nebIj1TQcQ+Oy1QKeo0Ay9+bdn8wfLAtOj9znDCybDCUlnS1+nYvKXEdfNg==","dev": true,"license": "MIT","dependencies": {"@cspotcode/source-map-support": "0.8.1",- "acorn": "8.14.0",- "acorn-walk": "8.3.2",- "exit-hook": "2.2.1",- "glob-to-regexp": "0.4.1",- "stoppable": "1.1.0",- "undici": "^5.28.5",- "workerd": "1.20250718.0",+ "sharp": "^0.34.5",+ "undici": "7.24.8",+ "workerd": "1.20260515.1","ws": "8.18.0",- "youch": "3.3.4",- "zod": "3.22.3"+ "youch": "4.1.0-beta.10"},"bin": {"miniflare": "bootstrap.js"},"engines": {- "node": ">=16.13"+ "node": ">=22.0.0"}},"node_modules/ms": {@@ -1864,16 +1887,6 @@"dev": true,"license": "MIT"},- "node_modules/mustache": {- "version": "4.2.0",- "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz",- "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==",- "dev": true,- "license": "MIT",- "bin": {- "mustache": "bin/mustache"- }- },"node_modules/nanoid": {"version": "3.3.11","resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",@@ -1893,13 +1906,6 @@"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"}},- "node_modules/ohash": {- "version": "2.0.11",- "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.11.tgz",- "integrity": "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==",- "dev": true,- "license": "MIT"- },"node_modules/path-to-regexp": {"version": "6.3.0","resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz",@@ -1960,13 +1966,6 @@"node": "^10 || ^12 || >=14"}},- "node_modules/printable-characters": {- "version": "1.0.42",- "resolved": "https://registry.npmjs.org/printable-characters/-/printable-characters-1.0.42.tgz",- "integrity": "sha512-dKp+C4iXWK4vVYZmYSd0KBH5F/h1HoZRsbJ82AVKRO3PEo8L4lBS/vLwhVtpwwuYcoIsVY+1JYKR268yn480uQ==",- "dev": true,- "license": "Unlicense"- },"node_modules/rollup": {"version": "4.60.2","resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.2.tgz",@@ -2012,70 +2011,12 @@"fsevents": "~2.3.2"}},- "node_modules/rollup-plugin-inject": {- "version": "3.0.2",- "resolved": "https://registry.npmjs.org/rollup-plugin-inject/-/rollup-plugin-inject-3.0.2.tgz",- "integrity": "sha512-ptg9PQwzs3orn4jkgXJ74bfs5vYz1NCZlSQMBUA0wKcGp5i5pA1AO3fOUEte8enhGUC+iapTCzEWw2jEFFUO/w==",- "deprecated": "This package has been deprecated and is no longer maintained. Please use @rollup/plugin-inject.",- "dev": true,- "license": "MIT",- "dependencies": {- "estree-walker": "^0.6.1",- "magic-string": "^0.25.3",- "rollup-pluginutils": "^2.8.1"- }- },- "node_modules/rollup-plugin-inject/node_modules/estree-walker": {- "version": "0.6.1",- "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.6.1.tgz",- "integrity": "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==",- "dev": true,- "license": "MIT"- },- "node_modules/rollup-plugin-inject/node_modules/magic-string": {- "version": "0.25.9",- "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.9.tgz",- "integrity": "sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==",- "dev": true,- "license": "MIT",- "dependencies": {- "sourcemap-codec": "^1.4.8"- }- },- "node_modules/rollup-plugin-node-polyfills": {- "version": "0.2.1",- "resolved": "https://registry.npmjs.org/rollup-plugin-node-polyfills/-/rollup-plugin-node-polyfills-0.2.1.tgz",- "integrity": "sha512-4kCrKPTJ6sK4/gLL/U5QzVT8cxJcofO0OU74tnB19F40cmuAKSzH5/siithxlofFEjwvw1YAhPmbvGNA6jEroA==",- "dev": true,- "license": "MIT",- "dependencies": {- "rollup-plugin-inject": "^3.0.0"- }- },- "node_modules/rollup-pluginutils": {- "version": "2.8.2",- "resolved": "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.8.2.tgz",- "integrity": "sha512-EEp9NhnUkwY8aif6bxgovPHMoMoNr2FulJziTndpt5H9RdwC47GSGuII9XxpSdzVGM0GWrNPHV6ie1LTNJPaLQ==",- "dev": true,- "license": "MIT",- "dependencies": {- "estree-walker": "^0.6.1"- }- },- "node_modules/rollup-pluginutils/node_modules/estree-walker": {- "version": "0.6.1",- "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.6.1.tgz",- "integrity": "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==",- "dev": true,- "license": "MIT"- },"node_modules/semver": {- "version": "7.7.4",- "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",- "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",+ "version": "7.8.0",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz",+ "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==","dev": true,"license": "ISC",- "optional": true,"bin": {"semver": "bin/semver.js"},@@ -2084,17 +2025,16 @@}},"node_modules/sharp": {- "version": "0.33.5",- "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz",- "integrity": "sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==",+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz",+ "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==","dev": true,"hasInstallScript": true,"license": "Apache-2.0",- "optional": true,"dependencies": {- "color": "^4.2.3",- "detect-libc": "^2.0.3",- "semver": "^7.6.3"+ "@img/colour": "^1.0.0",+ "detect-libc": "^2.1.2",+ "semver": "^7.7.3"},"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"@@ -2103,25 +2043,30 @@"url": "https://opencollective.com/libvips"},"optionalDependencies": {- "@img/sharp-darwin-arm64": "0.33.5",- "@img/sharp-darwin-x64": "0.33.5",- "@img/sharp-libvips-darwin-arm64": "1.0.4",- "@img/sharp-libvips-darwin-x64": "1.0.4",- "@img/sharp-libvips-linux-arm": "1.0.5",- "@img/sharp-libvips-linux-arm64": "1.0.4",- "@img/sharp-libvips-linux-s390x": "1.0.4",- "@img/sharp-libvips-linux-x64": "1.0.4",- "@img/sharp-libvips-linuxmusl-arm64": "1.0.4",- "@img/sharp-libvips-linuxmusl-x64": "1.0.4",- "@img/sharp-linux-arm": "0.33.5",- "@img/sharp-linux-arm64": "0.33.5",- "@img/sharp-linux-s390x": "0.33.5",- "@img/sharp-linux-x64": "0.33.5",- "@img/sharp-linuxmusl-arm64": "0.33.5",- "@img/sharp-linuxmusl-x64": "0.33.5",- "@img/sharp-wasm32": "0.33.5",- "@img/sharp-win32-ia32": "0.33.5",- "@img/sharp-win32-x64": "0.33.5"+ "@img/sharp-darwin-arm64": "0.34.5",+ "@img/sharp-darwin-x64": "0.34.5",+ "@img/sharp-libvips-darwin-arm64": "1.2.4",+ "@img/sharp-libvips-darwin-x64": "1.2.4",+ "@img/sharp-libvips-linux-arm": "1.2.4",+ "@img/sharp-libvips-linux-arm64": "1.2.4",+ "@img/sharp-libvips-linux-ppc64": "1.2.4",+ "@img/sharp-libvips-linux-riscv64": "1.2.4",+ "@img/sharp-libvips-linux-s390x": "1.2.4",+ "@img/sharp-libvips-linux-x64": "1.2.4",+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.4",+ "@img/sharp-libvips-linuxmusl-x64": "1.2.4",+ "@img/sharp-linux-arm": "0.34.5",+ "@img/sharp-linux-arm64": "0.34.5",+ "@img/sharp-linux-ppc64": "0.34.5",+ "@img/sharp-linux-riscv64": "0.34.5",+ "@img/sharp-linux-s390x": "0.34.5",+ "@img/sharp-linux-x64": "0.34.5",+ "@img/sharp-linuxmusl-arm64": "0.34.5",+ "@img/sharp-linuxmusl-x64": "0.34.5",+ "@img/sharp-wasm32": "0.34.5",+ "@img/sharp-win32-arm64": "0.34.5",+ "@img/sharp-win32-ia32": "0.34.5",+ "@img/sharp-win32-x64": "0.34.5"}},"node_modules/siginfo": {@@ -2131,27 +2076,6 @@"dev": true,"license": "ISC"},- "node_modules/simple-swizzle": {- "version": "0.2.4",- "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.4.tgz",- "integrity": "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==",- "dev": true,- "license": "MIT",- "optional": true,- "dependencies": {- "is-arrayish": "^0.3.1"- }- },- "node_modules/source-map": {- "version": "0.6.1",- "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",- "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",- "dev": true,- "license": "BSD-3-Clause",- "engines": {- "node": ">=0.10.0"- }- },"node_modules/source-map-js": {"version": "1.2.1","resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",@@ -2162,14 +2086,6 @@"node": ">=0.10.0"}},- "node_modules/sourcemap-codec": {- "version": "1.4.8",- "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz",- "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==",- "deprecated": "Please use @jridgewell/sourcemap-codec instead",- "dev": true,- "license": "MIT"- },"node_modules/stackback": {"version": "0.0.2","resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",@@ -2177,17 +2093,6 @@"dev": true,"license": "MIT"},- "node_modules/stacktracey": {- "version": "2.2.0",- "resolved": "https://registry.npmjs.org/stacktracey/-/stacktracey-2.2.0.tgz",- "integrity": "sha512-ETyQEz+CzXiLjEbyJqpbp+/T79RQD/6wqFucRBIlVNZfYq2Ay7wbretD4cxpbymZlaPWx58aIhPEY1Cr8DlVvg==",- "dev": true,- "license": "Unlicense",- "dependencies": {- "as-table": "^1.0.36",- "get-source": "^2.0.12"- }- },"node_modules/std-env": {"version": "3.10.0","resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",@@ -2195,15 +2100,17 @@"dev": true,"license": "MIT"},- "node_modules/stoppable": {- "version": "1.1.0",- "resolved": "https://registry.npmjs.org/stoppable/-/stoppable-1.1.0.tgz",- "integrity": "sha512-KXDYZ9dszj6bzvnEMRYvxgeTHU74QBFL54XKtP3nyMuJ81CFYtABZ3bAzL2EdFUaEwJOBOgENyFj3R7oTzDyyw==",+ "node_modules/supports-color": {+ "version": "10.2.2",+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz",+ "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==","dev": true,"license": "MIT","engines": {- "node": ">=4",- "npm": ">=6"+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/chalk/supports-color?sponsor=1"}},"node_modules/tinybench": {@@ -2272,38 +2179,24 @@"node": ">=14.17"}},- "node_modules/ufo": {- "version": "1.6.3",- "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.3.tgz",- "integrity": "sha512-yDJTmhydvl5lJzBmy/hyOAA0d+aqCBuwl818haVdYCRrWV84o7YyeVm4QlVHStqNrrJSTb6jKuFAVqAFsr+K3Q==",- "dev": true,- "license": "MIT"- },"node_modules/undici": {- "version": "5.29.0",- "resolved": "https://registry.npmjs.org/undici/-/undici-5.29.0.tgz",- "integrity": "sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg==",+ "version": "7.24.8",+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.24.8.tgz",+ "integrity": "sha512-6KQ/+QxK49Z/p3HO6E5ZCZWNnCasyZLa5ExaVYyvPxUwKtbCPMKELJOqh7EqOle0t9cH/7d2TaaTRRa6Nhs4YQ==","dev": true,"license": "MIT",- "dependencies": {- "@fastify/busboy": "^2.0.0"- },"engines": {- "node": ">=14.0"+ "node": ">=20.18.1"}},"node_modules/unenv": {- "version": "2.0.0-rc.14",- "resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.14.tgz",- "integrity": "sha512-od496pShMen7nOy5VmVJCnq8rptd45vh6Nx/r2iPbrba6pa6p+tS2ywuIHRZ/OBvSbQZB0kWvpO9XBNVFXHD3Q==",+ "version": "2.0.0-rc.24",+ "resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.24.tgz",+ "integrity": "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==","dev": true,"license": "MIT","dependencies": {- "defu": "^6.1.4",- "exsolve": "^1.0.1",- "ohash": "^2.0.10",- "pathe": "^2.0.3",- "ufo": "^1.5.4"+ "pathe": "^2.0.3"}},"node_modules/unenv/node_modules/pathe": {@@ -2480,9 +2373,9 @@}},"node_modules/workerd": {- "version": "1.20250718.0",- "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20250718.0.tgz",- "integrity": "sha512-kqkIJP/eOfDlUyBzU7joBg+tl8aB25gEAGqDap+nFWb+WHhnooxjGHgxPBy3ipw2hnShPFNOQt5lFRxbwALirg==",+ "version": "1.20260515.1",+ "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20260515.1.tgz",+ "integrity": "sha512-MjKOJLcvU45xXedQowvuiHtJTxu4WTHYQeIlF7YmjuqhiI6dImTFxWCEoRQHiskztxuVSNEmdO7/0UfDu6OMnQ==","dev": true,"hasInstallScript": true,"license": "Apache-2.0",@@ -2493,44 +2386,41 @@"node": ">=16"},"optionalDependencies": {- "@cloudflare/workerd-darwin-64": "1.20250718.0",- "@cloudflare/workerd-darwin-arm64": "1.20250718.0",- "@cloudflare/workerd-linux-64": "1.20250718.0",- "@cloudflare/workerd-linux-arm64": "1.20250718.0",- "@cloudflare/workerd-windows-64": "1.20250718.0"+ "@cloudflare/workerd-darwin-64": "1.20260515.1",+ "@cloudflare/workerd-darwin-arm64": "1.20260515.1",+ "@cloudflare/workerd-linux-64": "1.20260515.1",+ "@cloudflare/workerd-linux-arm64": "1.20260515.1",+ "@cloudflare/workerd-windows-64": "1.20260515.1"}},"node_modules/wrangler": {- "version": "3.114.17",- "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-3.114.17.tgz",- "integrity": "sha512-tAvf7ly+tB+zwwrmjsCyJ2pJnnc7SZhbnNwXbH+OIdVas3zTSmjcZOjmLKcGGptssAA3RyTKhcF9BvKZzMUycA==",+ "version": "4.92.0",+ "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.92.0.tgz",+ "integrity": "sha512-/DKpQHPxkuZbQsO9dFW2700VTD/4DSZMHjy92fO/frNoDRi/zQsFCAd2ONCV6TGqcUoXcP3D8Bo2gj/L4M0qQQ==","dev": true,"license": "MIT OR Apache-2.0","dependencies": {- "@cloudflare/kv-asset-handler": "0.3.4",- "@cloudflare/unenv-preset": "2.0.2",- "@esbuild-plugins/node-globals-polyfill": "0.2.3",- "@esbuild-plugins/node-modules-polyfill": "0.2.2",+ "@cloudflare/kv-asset-handler": "0.5.0",+ "@cloudflare/unenv-preset": "2.16.1","blake3-wasm": "2.1.5",- "esbuild": "0.17.19",- "miniflare": "3.20250718.3",+ "esbuild": "0.27.3",+ "miniflare": "4.20260515.0","path-to-regexp": "6.3.0",- "unenv": "2.0.0-rc.14",- "workerd": "1.20250718.0"+ "unenv": "2.0.0-rc.24",+ "workerd": "1.20260515.1"},"bin": {"wrangler": "bin/wrangler.js","wrangler2": "bin/wrangler.js"},"engines": {- "node": ">=16.17.0"+ "node": ">=22.0.0"},"optionalDependencies": {- "fsevents": "~2.3.2",- "sharp": "^0.33.5"+ "fsevents": "~2.3.2"},"peerDependencies": {- "@cloudflare/workers-types": "^4.20250408.0"+ "@cloudflare/workers-types": "^4.20260515.1"},"peerDependenciesMeta": {"@cloudflare/workers-types": {@@ -2538,10 +2428,27 @@}}},+ "node_modules/wrangler/node_modules/@esbuild/aix-ppc64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz",+ "integrity": "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },"node_modules/wrangler/node_modules/@esbuild/android-arm": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.19.tgz",- "integrity": "sha512-rIKddzqhmav7MSmoFCmDIb6e2W57geRsM94gV2l38fzhXMwq7hZoClug9USI2pFRGL06f4IOPHHpFNOkWieR8A==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.3.tgz",+ "integrity": "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==","cpu": ["arm"],@@ -2552,13 +2459,13 @@"android"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/android-arm64": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.17.19.tgz",- "integrity": "sha512-KBMWvEZooR7+kzY0BtbTQn0OAYY7CsiydT63pVEaPtVYF0hXbUaOyZog37DKxK7NF3XacBJOpYT4adIJh+avxA==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.3.tgz",+ "integrity": "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==","cpu": ["arm64"],@@ -2569,13 +2476,13 @@"android"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/android-x64": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.17.19.tgz",- "integrity": "sha512-uUTTc4xGNDT7YSArp/zbtmbhO0uEEK9/ETW29Wk1thYUJBz3IVnvgEiEwEa9IeLyvnpKrWK64Utw2bgUmDveww==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.3.tgz",+ "integrity": "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==","cpu": ["x64"],@@ -2586,13 +2493,13 @@"android"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/darwin-arm64": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.17.19.tgz",- "integrity": "sha512-80wEoCfF/hFKM6WE1FyBHc9SfUblloAWx6FJkFWTWiCoht9Mc0ARGEM47e67W9rI09YoUxJL68WHfDRYEAvOhg==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.3.tgz",+ "integrity": "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==","cpu": ["arm64"],@@ -2603,13 +2510,13 @@"darwin"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/darwin-x64": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.19.tgz",- "integrity": "sha512-IJM4JJsLhRYr9xdtLytPLSH9k/oxR3boaUIYiHkAawtwNOXKE8KoU8tMvryogdcT8AU+Bflmh81Xn6Q0vTZbQw==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.3.tgz",+ "integrity": "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==","cpu": ["x64"],@@ -2620,13 +2527,13 @@"darwin"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/freebsd-arm64": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.17.19.tgz",- "integrity": "sha512-pBwbc7DufluUeGdjSU5Si+P3SoMF5DQ/F/UmTSb8HXO80ZEAJmrykPyzo1IfNbAoaqw48YRpv8shwd1NoI0jcQ==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.3.tgz",+ "integrity": "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==","cpu": ["arm64"],@@ -2637,13 +2544,13 @@"freebsd"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/freebsd-x64": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.17.19.tgz",- "integrity": "sha512-4lu+n8Wk0XlajEhbEffdy2xy53dpR06SlzvhGByyg36qJw6Kpfk7cp45DR/62aPH9mtJRmIyrXAS5UWBrJT6TQ==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.3.tgz",+ "integrity": "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==","cpu": ["x64"],@@ -2654,13 +2561,13 @@"freebsd"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/linux-arm": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.17.19.tgz",- "integrity": "sha512-cdmT3KxjlOQ/gZ2cjfrQOtmhG4HJs6hhvm3mWSRDPtZ/lP5oe8FWceS10JaSJC13GBd4eH/haHnqf7hhGNLerA==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.3.tgz",+ "integrity": "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==","cpu": ["arm"],@@ -2671,13 +2578,13 @@"linux"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/linux-arm64": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.19.tgz",- "integrity": "sha512-ct1Tg3WGwd3P+oZYqic+YZF4snNl2bsnMKRkb3ozHmnM0dGWuxcPTTntAF6bOP0Sp4x0PjSF+4uHQ1xvxfRKqg==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.3.tgz",+ "integrity": "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==","cpu": ["arm64"],@@ -2688,13 +2595,13 @@"linux"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/linux-ia32": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.17.19.tgz",- "integrity": "sha512-w4IRhSy1VbsNxHRQpeGCHEmibqdTUx61Vc38APcsRbuVgK0OPEnQ0YD39Brymn96mOx48Y2laBQGqgZ0j9w6SQ==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.3.tgz",+ "integrity": "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==","cpu": ["ia32"],@@ -2705,13 +2612,13 @@"linux"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/linux-loong64": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.17.19.tgz",- "integrity": "sha512-2iAngUbBPMq439a+z//gE+9WBldoMp1s5GWsUSgqHLzLJ9WoZLZhpwWuym0u0u/4XmZ3gpHmzV84PonE+9IIdQ==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.3.tgz",+ "integrity": "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==","cpu": ["loong64"],@@ -2722,13 +2629,13 @@"linux"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/linux-mips64el": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.17.19.tgz",- "integrity": "sha512-LKJltc4LVdMKHsrFe4MGNPp0hqDFA1Wpt3jE1gEyM3nKUvOiO//9PheZZHfYRfYl6AwdTH4aTcXSqBerX0ml4A==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.3.tgz",+ "integrity": "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==","cpu": ["mips64el"],@@ -2739,13 +2646,13 @@"linux"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/linux-ppc64": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.17.19.tgz",- "integrity": "sha512-/c/DGybs95WXNS8y3Ti/ytqETiW7EU44MEKuCAcpPto3YjQbyK3IQVKfF6nbghD7EcLUGl0NbiL5Rt5DMhn5tg==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.3.tgz",+ "integrity": "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==","cpu": ["ppc64"],@@ -2756,13 +2663,13 @@"linux"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/linux-riscv64": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.17.19.tgz",- "integrity": "sha512-FC3nUAWhvFoutlhAkgHf8f5HwFWUL6bYdvLc/TTuxKlvLi3+pPzdZiFKSWz/PF30TB1K19SuCxDTI5KcqASJqA==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.3.tgz",+ "integrity": "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==","cpu": ["riscv64"],@@ -2773,13 +2680,13 @@"linux"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/linux-s390x": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.17.19.tgz",- "integrity": "sha512-IbFsFbxMWLuKEbH+7sTkKzL6NJmG2vRyy6K7JJo55w+8xDk7RElYn6xvXtDW8HCfoKBFK69f3pgBJSUSQPr+4Q==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.3.tgz",+ "integrity": "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==","cpu": ["s390x"],@@ -2790,13 +2697,13 @@"linux"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/linux-x64": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.19.tgz",- "integrity": "sha512-68ngA9lg2H6zkZcyp22tsVt38mlhWde8l3eJLWkyLrp4HwMUr3c1s/M2t7+kHIhvMjglIBrFpncX1SzMckomGw==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.3.tgz",+ "integrity": "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==","cpu": ["x64"],@@ -2807,13 +2714,13 @@"linux"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/netbsd-x64": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.19.tgz",- "integrity": "sha512-CwFq42rXCR8TYIjIfpXCbRX0rp1jo6cPIUPSaWwzbVI4aOfX96OXY8M6KNmtPcg7QjYeDmN+DD0Wp3LaBOLf4Q==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.3.tgz",+ "integrity": "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==","cpu": ["x64"],@@ -2824,13 +2731,13 @@"netbsd"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/openbsd-x64": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.19.tgz",- "integrity": "sha512-cnq5brJYrSZ2CF6c35eCmviIN3k3RczmHz8eYaVlNasVqsNY+JKohZU5MKmaOI+KkllCdzOKKdPs762VCPC20g==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.3.tgz",+ "integrity": "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==","cpu": ["x64"],@@ -2841,13 +2748,13 @@"openbsd"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/sunos-x64": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.17.19.tgz",- "integrity": "sha512-vCRT7yP3zX+bKWFeP/zdS6SqdWB8OIpaRq/mbXQxTGHnIxspRtigpkUcDMlSCOejlHowLqII7K2JKevwyRP2rg==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.3.tgz",+ "integrity": "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==","cpu": ["x64"],@@ -2858,13 +2765,13 @@"sunos"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/win32-arm64": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.19.tgz",- "integrity": "sha512-yYx+8jwowUstVdorcMdNlzklLYhPxjniHWFKgRqH7IFlUEa0Umu3KuYplf1HUZZ422e3NU9F4LGb+4O0Kdcaag==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.3.tgz",+ "integrity": "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==","cpu": ["arm64"],@@ -2875,13 +2782,13 @@"win32"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/win32-ia32": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.17.19.tgz",- "integrity": "sha512-eggDKanJszUtCdlVs0RB+h35wNlb5v4TWEkq4vZcmVt5u/HiDZrTXe2bWFQUez3RgNHwx/x4sk5++4NSSicKkw==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.3.tgz",+ "integrity": "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==","cpu": ["ia32"],@@ -2892,13 +2799,13 @@"win32"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/@esbuild/win32-x64": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.19.tgz",- "integrity": "sha512-lAhycmKnVOuRYNtRtatQR1LPQf2oYCkRGkSFnseDAKPl8lu5SOsK/e1sXe5a0Pc5kHIHe6P2I/ilntNv2xf3cA==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.3.tgz",+ "integrity": "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==","cpu": ["x64"],@@ -2909,13 +2816,13 @@"win32"],"engines": {- "node": ">=12"+ "node": ">=18"}},"node_modules/wrangler/node_modules/esbuild": {- "version": "0.17.19",- "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.17.19.tgz",- "integrity": "sha512-XQ0jAPFkK/u3LcVRcvVHQcTIqD6E2H1fvZMA5dQPSOWb3suUbWbfbRf94pjc0bNzRYLfIrDRQXr7X+LHIm5oHw==",+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.3.tgz",+ "integrity": "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==","dev": true,"hasInstallScript": true,"license": "MIT",@@ -2923,31 +2830,35 @@"esbuild": "bin/esbuild"},"engines": {- "node": ">=12"+ "node": ">=18"},"optionalDependencies": {- "@esbuild/android-arm": "0.17.19",- "@esbuild/android-arm64": "0.17.19",- "@esbuild/android-x64": "0.17.19",- "@esbuild/darwin-arm64": "0.17.19",- "@esbuild/darwin-x64": "0.17.19",- "@esbuild/freebsd-arm64": "0.17.19",- "@esbuild/freebsd-x64": "0.17.19",- "@esbuild/linux-arm": "0.17.19",- "@esbuild/linux-arm64": "0.17.19",- "@esbuild/linux-ia32": "0.17.19",- "@esbuild/linux-loong64": "0.17.19",- "@esbuild/linux-mips64el": "0.17.19",- "@esbuild/linux-ppc64": "0.17.19",- "@esbuild/linux-riscv64": "0.17.19",- "@esbuild/linux-s390x": "0.17.19",- "@esbuild/linux-x64": "0.17.19",- "@esbuild/netbsd-x64": "0.17.19",- "@esbuild/openbsd-x64": "0.17.19",- "@esbuild/sunos-x64": "0.17.19",- "@esbuild/win32-arm64": "0.17.19",- "@esbuild/win32-ia32": "0.17.19",- "@esbuild/win32-x64": "0.17.19"+ "@esbuild/aix-ppc64": "0.27.3",+ "@esbuild/android-arm": "0.27.3",+ "@esbuild/android-arm64": "0.27.3",+ "@esbuild/android-x64": "0.27.3",+ "@esbuild/darwin-arm64": "0.27.3",+ "@esbuild/darwin-x64": "0.27.3",+ "@esbuild/freebsd-arm64": "0.27.3",+ "@esbuild/freebsd-x64": "0.27.3",+ "@esbuild/linux-arm": "0.27.3",+ "@esbuild/linux-arm64": "0.27.3",+ "@esbuild/linux-ia32": "0.27.3",+ "@esbuild/linux-loong64": "0.27.3",+ "@esbuild/linux-mips64el": "0.27.3",+ "@esbuild/linux-ppc64": "0.27.3",+ "@esbuild/linux-riscv64": "0.27.3",+ "@esbuild/linux-s390x": "0.27.3",+ "@esbuild/linux-x64": "0.27.3",+ "@esbuild/netbsd-arm64": "0.27.3",+ "@esbuild/netbsd-x64": "0.27.3",+ "@esbuild/openbsd-arm64": "0.27.3",+ "@esbuild/openbsd-x64": "0.27.3",+ "@esbuild/openharmony-arm64": "0.27.3",+ "@esbuild/sunos-x64": "0.27.3",+ "@esbuild/win32-arm64": "0.27.3",+ "@esbuild/win32-ia32": "0.27.3",+ "@esbuild/win32-x64": "0.27.3"}},"node_modules/ws": {@@ -2973,25 +2884,28 @@}},"node_modules/youch": {- "version": "3.3.4",- "resolved": "https://registry.npmjs.org/youch/-/youch-3.3.4.tgz",- "integrity": "sha512-UeVBXie8cA35DS6+nBkls68xaBBXCye0CNznrhszZjTbRVnJKQuNsyLKBTTL4ln1o1rh2PKtv35twV7irj5SEg==",+ "version": "4.1.0-beta.10",+ "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz",+ "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==","dev": true,"license": "MIT","dependencies": {- "cookie": "^0.7.1",- "mustache": "^4.2.0",- "stacktracey": "^2.1.8"+ "@poppinss/colors": "^4.1.5",+ "@poppinss/dumper": "^0.6.4",+ "@speed-highlight/core": "^1.2.7",+ "cookie": "^1.0.2",+ "youch-core": "^0.3.3"}},- "node_modules/zod": {- "version": "3.22.3",- "resolved": "https://registry.npmjs.org/zod/-/zod-3.22.3.tgz",- "integrity": "sha512-EjIevzuJRiRPbVH4mGc8nApb/lVLKVpmUhAaR5R5doKGfAnGJ6Gr3CViAVjP+4FWSxCsybeWQdcgCtbX+7oZug==",+ "node_modules/youch-core": {+ "version": "0.3.3",+ "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz",+ "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==","dev": true,"license": "MIT",- "funding": {- "url": "https://github.com/sponsors/colinhacks"+ "dependencies": {+ "@poppinss/exception": "^1.2.2",+ "error-stack-parser-es": "^1.0.5"}}}diff --git a/cloudflare-workers/api-edge/package.json b/cloudflare-workers/api-edge/package.jsonindex ef5861da..9b339cb4 100644--- a/cloudflare-workers/api-edge/package.json+++ b/cloudflare-workers/api-edge/package.json@@ -12,6 +12,6 @@"@cloudflare/workers-types": "^4.20240924.0","typescript": "^5.5.0","vitest": "^2.0.0",- "wrangler": "^3.78.0"+ "wrangler": "^4.92.0"}}diff --git a/cloudflare-workers/api-edge/src/crypto.ts b/cloudflare-workers/api-edge/src/crypto.tsnew file mode 100644index 00000000..53aba72b--- /dev/null+++ b/cloudflare-workers/api-edge/src/crypto.ts@@ -0,0 +1,44 @@+// AES-256-GCM helpers for secret-store envelope encryption.+//+// Wire format mirrors internal/crypto/encrypt.go: `nonce(12) || ciphertext`,+// stored as a BLOB in D1's secret_store_entries.encrypted_value. The same+// SECRET_ENCRYPTION_KEY (hex-encoded 32 bytes, lives in Infisical /shared/)+// is bound to the edge Worker as a secret AND distributed to every CP via+// the per-cell KV/SM sync — so a value encrypted here decrypts cleanly inside+// any cell, and vice versa.++const NONCE_LEN = 12;++async function importKey(hexKey: string): Promise<CryptoKey> {+ if (hexKey.length !== 64) {+ throw new Error(`SECRET_ENCRYPTION_KEY must be 64 hex chars (32 bytes), got ${hexKey.length}`);+ }+ const raw = new Uint8Array(32);+ for (let i = 0; i < 32; i++) {+ raw[i] = parseInt(hexKey.substr(i * 2, 2), 16);+ }+ return crypto.subtle.importKey("raw", raw, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);+}++export async function encryptSecret(hexKey: string, plaintext: string): Promise<Uint8Array> {+ const key = await importKey(hexKey);+ const nonce = new Uint8Array(NONCE_LEN);+ crypto.getRandomValues(nonce);+ const ct = new Uint8Array(+ await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce }, key, new TextEncoder().encode(plaintext)),+ );+ // nonce || ciphertext+tag+ const out = new Uint8Array(NONCE_LEN + ct.length);+ out.set(nonce, 0);+ out.set(ct, NONCE_LEN);+ return out;+}++export async function decryptSecret(hexKey: string, blob: Uint8Array): Promise<string> {+ if (blob.length < NONCE_LEN + 16) throw new Error("ciphertext too short");+ const key = await importKey(hexKey);+ const nonce = blob.subarray(0, NONCE_LEN);+ const ct = blob.subarray(NONCE_LEN);+ const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: nonce }, key, ct);+ return new TextDecoder().decode(pt);+}diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsnew file mode 100644index 00000000..f9e6a358--- /dev/null+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -0,0 +1,1005 @@+// dashboard.ts — edge-native dashboard backend.+//+// The new architecture (see docs/dev-cutover-runbook.md + the dev-cutover diagram)+// makes the CF edge authoritative for identity, billing, sandbox routing index,+// and audit log. The dashboard accordingly lives here: D1 is the source of+// truth for org/user/api-key/checkpoint data, and only sandbox-RUNTIME ops+// (exec, PTY, logs) proxy to the cell where the sandbox actually runs.+//+// Auth: session JWT cookie `oc_session` minted by /auth/callback. Browser+// hits /api/dashboard/...; we validate the cookie and execute the handler.+//+// Proxy pattern for sandbox-runtime ops:+// 1. Look up the sandbox's cell_id in D1 sandboxes_index (or org.home_cell+// for non-sandbox-scoped proxies like /agents).+// 2. Mint a short-lived capability JWT for that cell with claims.OrgID ++// claims.Plan (the same cap-token shape /api/sandboxes POST uses).+// 3. Fetch the cell's /internal/dashboard/{path} with Authorization: Bearer.+// 4. Stream the response (or WebSocket pair) back to the browser.++export interface DashboardEnv {+ OPENCOMPUTER_DB: D1Database;+ SESSIONS_KV: KVNamespace;+ CREDIT_ACCOUNT: DurableObjectNamespace;+ SESSION_JWT_SECRET: string;+ WORKOS_API_KEY: string;+ WORKOS_CLIENT_ID: string;+ STRIPE_API_KEY: string;+ WORKER_ENV: string;+ CELLS: string;+ // CF Custom Hostnames API token + zone (for /org/custom-domain). Optional —+ // if unset the custom-domain endpoints return 503 (feature disabled).+ CF_API_TOKEN?: string;+ CF_ZONE_ID?: string;+}++const SESSION_COOKIE = "oc_session";+const SESSION_TTL_SEC = 60 * 60 * 8;++interface SessionClaims {+ iss?: string;+ sub: string;+ iat: number;+ exp: number;+ org_id: string;+ user_id: string;+ plan: string;+}++interface Caller {+ orgID: string;+ userID: string;+ plan: string;+ claims: SessionClaims;+}++// ── auth ─────────────────────────────────────────────────────────────────++export async function authDashboard(req: Request, env: DashboardEnv): Promise<Caller | null> {+ const cookie = req.headers.get("cookie") ?? "";+ const m = cookie.match(new RegExp(`(?:^|;\\s*)${SESSION_COOKIE}=([^;]+)`));+ if (!m) return null;+ const claims = await verifySessionJWT(env.SESSION_JWT_SECRET, m[1]);+ if (!claims) return null;+ return { orgID: claims.org_id, userID: claims.user_id, plan: claims.plan, claims };+}++async function verifySessionJWT(secret: string, token: string): Promise<SessionClaims | null> {+ const parts = token.split(".");+ if (parts.length !== 3) return null;+ const [headerB64, payloadB64, sigB64] = parts;+ const enc = new TextEncoder();+ const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);+ const expected = await crypto.subtle.sign("HMAC", key, enc.encode(`${headerB64}.${payloadB64}`));+ if (b64url(expected) !== sigB64) return null;+ try {+ const payload = JSON.parse(atob(payloadB64.replace(/-/g, "+").replace(/_/g, "/"))) as SessionClaims;+ if (payload.iss !== "opensandbox-session") return null;+ if (payload.exp < Math.floor(Date.now() / 1000)) return null;+ return payload;+ } catch {+ return null;+ }+}++async function mintSessionJWT(secret: string, orgID: string, userID: string, plan: string): Promise<string> {+ const now = Math.floor(Date.now() / 1000);+ const header = { alg: "HS256", typ: "JWT" };+ const payload = {+ iss: "opensandbox-session", sub: userID, iat: now, exp: now + SESSION_TTL_SEC,+ org_id: orgID, user_id: userID, plan,+ };+ const enc = new TextEncoder();+ const signingInput =+ b64url(enc.encode(JSON.stringify(header))) + "." + b64url(enc.encode(JSON.stringify(payload)));+ const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);+ const sig = await crypto.subtle.sign("HMAC", key, enc.encode(signingInput));+ return signingInput + "." + b64url(sig);+}++function setSessionCookie(jwt: string): string {+ return `${SESSION_COOKIE}=${jwt}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${SESSION_TTL_SEC}`;+}++// Same shape as the cap-token /api/sandboxes mints for /internal/sandboxes/create.+// Cells' capTokenMiddleware validates this same format on /internal/dashboard/*.+async function mintCellCapToken(secret: string, orgID: string, cellID: string, plan: string, userID: string | null): Promise<string> {+ const now = Math.floor(Date.now() / 1000);+ const header = { alg: "HS256", typ: "JWT" };+ const payload: Record<string, unknown> = {+ sub: orgID, iss: "opensandbox-edge", iat: now, exp: now + 120,+ org_id: orgID, cell_id: cellID, plan,+ };+ if (userID) payload.user_id = userID;+ const enc = new TextEncoder();+ const signingInput =+ b64url(enc.encode(JSON.stringify(header))) + "." + b64url(enc.encode(JSON.stringify(payload)));+ const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);+ const sig = await crypto.subtle.sign("HMAC", key, enc.encode(signingInput));+ return signingInput + "." + b64url(sig);+}++function b64url(buf: ArrayBuffer | Uint8Array): string {+ const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);+ let s = "";+ for (const b of bytes) s += String.fromCharCode(b);+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");+}++function json(body: unknown, status = 200, extraHeaders: Record<string, string> = {}): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json", ...extraHeaders },+ });+}++async function sha256Hex(s: string): Promise<string> {+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s));+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");+}++// D1 stores timestamps as unix seconds (INTEGER). The cell's Go handlers+// marshal time.Time as RFC3339 strings, which is what the dashboard frontend+// expects (`new Date(value)` then `.toISOString()`). Mirror that.+function epochToISO(s: number | null | undefined): string | undefined {+ if (s == null || s === 0) return undefined;+ return new Date(s * 1000).toISOString();+}++// Required-date variant: returns a valid ISO string even if input is null+// (uses unix epoch). Used for fields like createdAt that the frontend+// treats as non-nullable.+function epochToISORequired(s: number | null | undefined): string {+ return new Date(((s ?? 0) || 0) * 1000).toISOString();+}++// Cell ID → region. Reverse of api-edge's pickCell convention:+// cells follow {cloud}-{region-with-hyphens}-{slot}, e.g.+// "azure-us-west-2-b" → region "us-west-2".+function cellToRegion(cellID: string): string {+ // Strip first segment (cloud) and last segment (slot).+ const parts = cellID.split("-");+ if (parts.length < 3) return "";+ return parts.slice(1, -1).join("-");+}++// shapeOrg maps a D1 orgs row to the frontend's Org interface (camelCase,+// timestamps as ISO strings, integer-flag booleans).+interface OrgRow {+ id: string; name: string; slug: string; plan: string;+ max_concurrent_sandboxes: number; max_sandbox_timeout_sec: number;+ created_at: number; updated_at: number;+ custom_domain: string | null; cf_hostname_id: string | null;+ domain_verification_status: string; domain_ssl_status: string;+ verification_txt_name: string | null; verification_txt_value: string | null;+ ssl_txt_name: string | null; ssl_txt_value: string | null;+ workos_org_id: string | null; is_personal: number;+ credit_balance_cents: number;+ free_credits_remaining_cents: number; is_halted: number;+ halted_at: number | null;+}++function shapeOrg(r: OrgRow): Record<string, unknown> {+ return {+ id: r.id, name: r.name, slug: r.slug, plan: r.plan,+ maxConcurrentSandboxes: r.max_concurrent_sandboxes,+ maxSandboxTimeoutSec: r.max_sandbox_timeout_sec,+ createdAt: epochToISORequired(r.created_at),+ updatedAt: epochToISORequired(r.updated_at),+ customDomain: r.custom_domain ?? undefined,+ cfHostnameId: r.cf_hostname_id ?? undefined,+ domainVerificationStatus: r.domain_verification_status,+ domainSslStatus: r.domain_ssl_status,+ verificationTxtName: r.verification_txt_name ?? undefined,+ verificationTxtValue: r.verification_txt_value ?? undefined,+ sslTxtName: r.ssl_txt_name ?? undefined,+ sslTxtValue: r.ssl_txt_value ?? undefined,+ workosOrgId: r.workos_org_id ?? undefined,+ isPersonal: !!r.is_personal,+ creditBalanceCents: r.credit_balance_cents,+ freeCreditsRemainingCents: r.free_credits_remaining_cents,+ isHalted: !!r.is_halted,+ haltedAt: epochToISO(r.halted_at),+ };+}++// ── cell lookup helpers ──────────────────────────────────────────────────++interface CellRow {+ cell_id: string;+ base_url: string;+}++async function homeCell(env: DashboardEnv, orgID: string): Promise<CellRow | null> {+ const row = await env.OPENCOMPUTER_DB.prepare(+ `SELECT c.cell_id, c.base_url FROM orgs o JOIN cells c ON c.cell_id = o.home_cell WHERE o.id = ?1`,+ ).bind(orgID).first<CellRow>();+ return row ?? null;+}++async function sandboxCell(env: DashboardEnv, sandboxID: string): Promise<{ cell_id: string; base_url: string; org_id: string } | null> {+ return env.OPENCOMPUTER_DB.prepare(+ `SELECT s.cell_id, s.org_id, c.base_url FROM sandboxes_index s JOIN cells c ON c.cell_id = s.cell_id WHERE s.id = ?1`,+ ).bind(sandboxID).first<{ cell_id: string; base_url: string; org_id: string }>();+}++// proxyToCell handles non-WebSocket dashboard requests. Looks up the+// destination URL (caller-supplied), mints a cap-token for that cell, and+// streams the response back. Pass-through for status, body, content-type.+async function proxyToCell(+ req: Request,+ env: DashboardEnv,+ caller: Caller,+ cell: CellRow,+ path: string,+): Promise<Response> {+ const url = new URL(req.url);+ const target = cell.base_url.replace(/\/$/, "") + path + url.search;+ const token = await mintCellCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, caller.plan, caller.userID);++ // Forward only the headers the cell actually needs. CF Workers forbids+ // some headers (Host, Connection, Content-Length) and stripping cookies+ // avoids sending the browser's session JWT to the cell. The Authorization+ // header is the auth signal the cell needs; content-type matters for body+ // parsing on POST/PUT.+ const headers = new Headers();+ headers.set("authorization", "Bearer " + token);+ const ct = req.headers.get("content-type");+ if (ct) headers.set("content-type", ct);+ const accept = req.headers.get("accept");+ if (accept) headers.set("accept", accept);+ const ua = req.headers.get("user-agent");+ if (ua) headers.set("user-agent", ua);++ const init: RequestInit = { method: req.method, headers };+ if (req.method !== "GET" && req.method !== "HEAD") init.body = req.body;+ return fetch(target, init);+}++// ── WebSocket proxy (PTY) ────────────────────────────────────────────────++async function proxyWebSocket(+ req: Request,+ env: DashboardEnv,+ caller: Caller,+ cell: CellRow,+ cellPath: string,+): Promise<Response> {+ if (req.headers.get("upgrade")?.toLowerCase() !== "websocket") {+ return json({ error: "expected websocket upgrade" }, 400);+ }+ let token: string;+ try {+ token = await mintCellCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, caller.plan, caller.userID);+ } catch (e) {+ console.error("proxyWebSocket: mint failed:", e);+ return new Response("token mint failed", { status: 500 });+ }+ const upstreamURL = cell.base_url.replace(/\/$/, "") + cellPath;+ console.log(`proxyWebSocket: dialing upstream ${upstreamURL}`);++ // CF Workers WebSocket fetch: only the Upgrade: websocket header is needed.+ // Setting Connection: Upgrade can confuse the runtime; omit it. The Worker+ // returns a Response with a `.webSocket` property on success (status 101).+ let upstreamResp: Response;+ try {+ upstreamResp = await fetch(upstreamURL, {+ headers: {+ Upgrade: "websocket",+ Authorization: "Bearer " + token,+ },+ });+ } catch (e) {+ console.error(`proxyWebSocket: upstream fetch threw: ${(e as Error).message}`);+ return new Response(`cell websocket fetch failed: ${(e as Error).message}`, { status: 502 });+ }+ console.log(`proxyWebSocket: upstream status=${upstreamResp.status}`);+ const upstream = (upstreamResp as Response & { webSocket?: WebSocket }).webSocket;+ if (!upstream) {+ const errBody = await upstreamResp.text().catch(() => "");+ console.error(`proxyWebSocket: no webSocket on response; body=${errBody.slice(0, 200)}`);+ return new Response(+ `cell websocket connect failed (status ${upstreamResp.status}): ${errBody.slice(0, 200)}`,+ { status: 502 },+ );+ }+ const pair = new WebSocketPair();+ const client = pair[0];+ const server = pair[1];++ // CF Workers delivers binary WebSocket frames as Blob and ignores any+ // `binaryType = "arraybuffer"` setter on these proxy WebSockets. We have+ // to detect Blob in the handler and await `.arrayBuffer()` before+ // forwarding. We also use that ArrayBuffer when calling `.send()` so the+ // browser (which has `binaryType="arraybuffer"`) decodes the frame to a+ // plain ArrayBuffer in `event.data`.++ // Diagnostic byte counters. Forward binary + text messages between+ // upstream (cell) <-> server (browser-facing half of our pair).+ let upToBrowser = 0;+ let browserToUp = 0;++ // forward async-awaits Blob → ArrayBuffer (binary) or passes through+ // strings (text). Sending a Blob directly results in "[object Blob]"+ // text frame, which xterm renders as nothing. The await-chain ordering+ // is preserved per-direction by serializing through a single Promise.+ let upQueue: Promise<unknown> = Promise.resolve();+ let downQueue: Promise<unknown> = Promise.resolve();+ const forward = (+ data: unknown,+ target: WebSocket,+ addBytes: (n: number) => void,+ label: string,+ ): Promise<void> => {+ if (typeof data === "string") {+ addBytes(data.length);+ try { target.send(data); } catch (err) { console.error(`${label}: send (string) failed: ${(err as Error).message}`); }+ return Promise.resolve();+ }+ if (data instanceof ArrayBuffer) {+ addBytes(data.byteLength);+ try { target.send(data); } catch (err) { console.error(`${label}: send (ab) failed: ${(err as Error).message}`); }+ return Promise.resolve();+ }+ if (ArrayBuffer.isView(data)) {+ const v = data as ArrayBufferView;+ const ab = v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength);+ addBytes(ab.byteLength);+ try { target.send(ab); } catch (err) { console.error(`${label}: send (view) failed: ${(err as Error).message}`); }+ return Promise.resolve();+ }+ if (data && typeof (data as any).arrayBuffer === "function") {+ return (data as Blob).arrayBuffer().then(+ (ab) => {+ addBytes(ab.byteLength);+ try { target.send(ab); } catch (err) { console.error(`${label}: send (blob) failed: ${(err as Error).message}`); }+ },+ (err) => { console.error(`${label}: blob.arrayBuffer failed: ${(err as Error).message}`); },+ );+ }+ console.error(`${label}: unknown data shape: ${typeof data} ${(data as any)?.constructor?.name}`);+ return Promise.resolve();+ };++ upstream.addEventListener("message", (e) => {+ const isFirst = upToBrowser === 0;+ if (isFirst) {+ console.log(`proxyWebSocket: up->browser first frame typeof=${typeof e.data} ctor=${(e.data as any)?.constructor?.name}`);+ }+ downQueue = downQueue.then(() => forward(e.data, server, (n) => { upToBrowser += n; }, "proxyWebSocket: server.send"));+ });+ server.addEventListener("message", (e) => {+ const isFirst = browserToUp === 0;+ if (isFirst) {+ console.log(`proxyWebSocket: browser->up first frame typeof=${typeof e.data} ctor=${(e.data as any)?.constructor?.name}`);+ }+ upQueue = upQueue.then(() => forward(e.data, upstream, (n) => { browserToUp += n; }, "proxyWebSocket: upstream.send"));+ });+ server.addEventListener("close", (e) => {+ console.log(`proxyWebSocket: server close code=${e.code} reason=${e.reason} (up->browser=${upToBrowser}, browser->up=${browserToUp})`);+ try { upstream.close(e.code, e.reason); } catch {}+ });+ upstream.addEventListener("close", (e) => {+ console.log(`proxyWebSocket: upstream close code=${e.code} reason=${e.reason} (up->browser=${upToBrowser}, browser->up=${browserToUp})`);+ try { server.close(e.code, e.reason); } catch {}+ });+ server.addEventListener("error", (e: any) => {+ console.error(`proxyWebSocket: server error: ${e?.message ?? "unknown"}`);+ try { upstream.close(1011, "client error"); } catch {}+ });+ upstream.addEventListener("error", (e: any) => {+ console.error(`proxyWebSocket: upstream error: ${e?.message ?? "unknown"}`);+ try { server.close(1011, "upstream error"); } catch {}+ });++ // Accept AFTER attaching listeners so we don't miss the first frame.+ // The worker emits the shell prompt (~27 bytes) within ~0.5ms of upgrade.+ upstream.accept();+ server.accept();+ console.log(`proxyWebSocket: bridge wired up + accepted`);++ return new Response(null, { status: 101, webSocket: client } as any);+}++// ── identity (/me, /orgs, /org, /org/switch) ─────────────────────────────++async function handleMe(req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ // Load user + org list. Org list joins via org_memberships; each row carries+ // the active flag so the UI can highlight the current org.+ const user = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, email, name, workos_user_id FROM users WHERE id = ?1`,+ ).bind(caller.userID).first<{ id: string; email: string; name: string | null; workos_user_id: string | null }>();+ if (!user) return json({ error: "user not found" }, 404);++ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT o.id, o.name, o.is_personal FROM orgs o+ JOIN org_memberships m ON m.org_id = o.id+ WHERE m.user_id = ?1`,+ ).bind(caller.userID).all<{ id: string; name: string; is_personal: number }>();+ const orgs = (results ?? []).map((r) => ({+ id: r.id, name: r.name, isPersonal: !!r.is_personal, isActive: r.id === caller.orgID,+ }));++ return json({+ id: user.id, email: user.email, name: user.name, orgId: caller.orgID, orgs,+ });+}++async function handleListOrgs(_req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT o.id, o.name, o.is_personal, o.plan, o.home_cell FROM orgs o+ JOIN org_memberships m ON m.org_id = o.id+ WHERE m.user_id = ?1+ ORDER BY o.is_personal DESC, o.name ASC`,+ ).bind(caller.userID).all<{ id: string; name: string; is_personal: number; plan: string; home_cell: string }>();+ // Shape to OrgInfo for /orgs route (the frontend uses { id, name, isPersonal, isActive }).+ return json((results ?? []).map((r) => ({+ id: r.id, name: r.name, isPersonal: !!r.is_personal, plan: r.plan,+ homeCell: r.home_cell, isActive: r.id === caller.orgID,+ })));+}++async function handleGetOrg(_req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ const org = await env.OPENCOMPUTER_DB.prepare(`SELECT * FROM orgs WHERE id = ?1`).bind(caller.orgID).first<OrgRow>();+ if (!org) return json({ error: "org not found" }, 404);+ return json(shapeOrg(org));+}++async function handleUpdateOrg(req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ const body = await req.json<{ name?: string }>().catch(() => ({} as { name?: string }));+ const name = (body.name ?? "").trim();+ if (!name) return json({ error: "name is required" }, 400);+ const org = await env.OPENCOMPUTER_DB.prepare(`SELECT owner_user_id, workos_org_id FROM orgs WHERE id = ?1`).bind(caller.orgID).first<{ owner_user_id: string | null; workos_org_id: string | null }>();+ if (!org) return json({ error: "org not found" }, 404);+ if (org.owner_user_id !== caller.userID) return json({ error: "only owner can rename" }, 403);++ await env.OPENCOMPUTER_DB.prepare(`UPDATE orgs SET name = ?1, updated_at = ?2 WHERE id = ?3`)+ .bind(name, Math.floor(Date.now() / 1000), caller.orgID).run();++ // Best-effort WorkOS sync. Errors logged, not surfaced.+ if (org.workos_org_id) {+ workosUpdateOrg(env, org.workos_org_id, name).catch((e) => console.error("workos org update failed", e));+ }+ const updated = await env.OPENCOMPUTER_DB.prepare(`SELECT * FROM orgs WHERE id = ?1`).bind(caller.orgID).first<OrgRow>();+ return json(updated ? shapeOrg(updated) : null);+}++async function handleOrgSwitch(req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ const body = await req.json<{ orgId?: string }>().catch(() => ({} as { orgId?: string }));+ if (!body.orgId) return json({ error: "orgId required" }, 400);+ // Verify membership before issuing a session for the new org.+ const m = await env.OPENCOMPUTER_DB.prepare(+ `SELECT 1 FROM org_memberships WHERE user_id = ?1 AND org_id = ?2`,+ ).bind(caller.userID, body.orgId).first();+ if (!m) return json({ error: "not a member of that org" }, 403);+ const orgRow = await env.OPENCOMPUTER_DB.prepare(`SELECT plan FROM orgs WHERE id = ?1`).bind(body.orgId).first<{ plan: string }>();+ const plan = orgRow?.plan ?? "free";+ const fresh = await mintSessionJWT(env.SESSION_JWT_SECRET, body.orgId, caller.userID, plan);+ return json({ ok: true, orgId: body.orgId, plan }, 200, { "set-cookie": setSessionCookie(fresh) });+}++// ── members ──────────────────────────────────────────────────────────────++async function handleListMembers(_req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT m.user_id, m.role, m.created_at, u.email, u.name, u.workos_user_id+ FROM org_memberships m JOIN users u ON u.id = m.user_id+ WHERE m.org_id = ?1 ORDER BY m.created_at ASC`,+ ).bind(caller.orgID).all<{+ user_id: string; role: string; created_at: number;+ email: string; name: string | null; workos_user_id: string | null;+ }>();+ // Frontend OrgMember interface — bare array, camelCase.+ return json((results ?? []).map((r) => ({+ id: r.user_id,+ membershipId: r.user_id, // we don't have a separate membership id; reuse+ workosUserId: r.workos_user_id ?? undefined,+ email: r.email,+ name: r.name ?? r.email,+ role: r.role,+ status: "active",+ })));+}++async function handleRemoveMember(_req: Request, env: DashboardEnv, caller: Caller, memberUserID: string): Promise<Response> {+ if (memberUserID === caller.userID) return json({ error: "cannot remove self" }, 400);+ const org = await env.OPENCOMPUTER_DB.prepare(`SELECT owner_user_id FROM orgs WHERE id = ?1`).bind(caller.orgID).first<{ owner_user_id: string | null }>();+ if (!org || org.owner_user_id !== caller.userID) return json({ error: "only owner can remove members" }, 403);+ await env.OPENCOMPUTER_DB.prepare(`DELETE FROM org_memberships WHERE org_id = ?1 AND user_id = ?2`).bind(caller.orgID, memberUserID).run();+ return new Response(null, { status: 204 });+}++// ── invitations ──────────────────────────────────────────────────────────++async function handleListInvitations(_req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, email, role, status, created_at, expires_at, accepted_at, revoked_at, invited_by+ FROM invitations WHERE org_id = ?1 ORDER BY created_at DESC`,+ ).bind(caller.orgID).all<{ id: string; email: string; role: string; status: string; created_at: number; expires_at: number | null; accepted_at: number | null; revoked_at: number | null; invited_by: string | null }>();+ // Bare array — frontend expects OrgInvitation[].+ return json((results ?? []).map((r) => ({+ id: r.id, email: r.email, role: r.role, state: r.status,+ createdAt: epochToISORequired(r.created_at),+ expiresAt: epochToISORequired(r.expires_at),+ acceptedAt: epochToISO(r.accepted_at),+ revokedAt: epochToISO(r.revoked_at),+ invitedBy: r.invited_by ?? undefined,+ })));+}++async function handleSendInvitation(req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ const body = await req.json<{ email?: string; role?: string }>().catch(() => ({} as { email?: string; role?: string }));+ const email = (body.email ?? "").trim().toLowerCase();+ const role = body.role || "member";+ if (!email) return json({ error: "email required" }, 400);+ if (!["owner", "admin", "member"].includes(role)) return json({ error: "invalid role" }, 400);++ // WorkOS invitation send. Returns the WorkOS invitation ID we mirror in D1.+ const org = await env.OPENCOMPUTER_DB.prepare(`SELECT workos_org_id FROM orgs WHERE id = ?1`).bind(caller.orgID).first<{ workos_org_id: string | null }>();+ let workosInviteID: string | null = null;+ if (org?.workos_org_id) {+ try {+ const r = await fetch("https://api.workos.com/user_management/invitations", {+ method: "POST",+ headers: { "content-type": "application/json", authorization: `Bearer ${env.WORKOS_API_KEY}` },+ body: JSON.stringify({ email, organization_id: org.workos_org_id, expires_in_days: 7, role_slug: role }),+ });+ if (r.ok) {+ const data = await r.json<{ id: string }>();+ workosInviteID = data.id;+ } else {+ console.error(`workos invite ${email} returned ${r.status}: ${await r.text()}`);+ }+ } catch (e) {+ console.error(`workos invite ${email} threw`, e);+ }+ }++ const id = crypto.randomUUID();+ const now = Math.floor(Date.now() / 1000);+ await env.OPENCOMPUTER_DB.prepare(+ `INSERT INTO invitations (id, org_id, email, role, invited_by, workos_invitation_id, status, expires_at, created_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'pending', ?7, ?8)`,+ ).bind(id, caller.orgID, email, role, caller.userID, workosInviteID, now + 7 * 86400, now).run();+ return json({ id, email, role, status: "pending", workos_invitation_id: workosInviteID, expires_at: now + 7 * 86400 }, 201);+}++async function handleRevokeInvitation(_req: Request, env: DashboardEnv, caller: Caller, inviteID: string): Promise<Response> {+ const inv = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, workos_invitation_id, status FROM invitations WHERE id = ?1 AND org_id = ?2`,+ ).bind(inviteID, caller.orgID).first<{ id: string; workos_invitation_id: string | null; status: string }>();+ if (!inv) return json({ error: "invitation not found" }, 404);+ if (inv.status !== "pending") return json({ error: `cannot revoke ${inv.status} invitation` }, 400);++ if (inv.workos_invitation_id) {+ try {+ await fetch(`https://api.workos.com/user_management/invitations/${inv.workos_invitation_id}/revoke`, {+ method: "POST",+ headers: { authorization: `Bearer ${env.WORKOS_API_KEY}` },+ });+ } catch (e) { console.error("workos revoke failed", e); }+ }+ await env.OPENCOMPUTER_DB.prepare(`UPDATE invitations SET status = 'revoked', revoked_at = ?1 WHERE id = ?2`)+ .bind(Math.floor(Date.now() / 1000), inviteID).run();+ return new Response(null, { status: 204 });+}++// ── API keys ─────────────────────────────────────────────────────────────++async function handleListAPIKeys(_req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, name, key_prefix, scopes, last_used, expires_at, created_at, created_by+ FROM api_keys WHERE org_id = ?1 ORDER BY created_at DESC`,+ ).bind(caller.orgID).all<{+ id: string; name: string; key_prefix: string; scopes: string;+ last_used: number | null; expires_at: number | null; created_at: number; created_by: string | null;+ }>();+ const keys = (results ?? []).map((r) => ({+ id: r.id,+ orgId: caller.orgID,+ name: r.name,+ keyPrefix: r.key_prefix,+ scopes: r.scopes.split(",").map((s) => s.trim()).filter(Boolean),+ lastUsed: epochToISO(r.last_used),+ expiresAt: epochToISO(r.expires_at),+ createdAt: epochToISORequired(r.created_at),+ }));+ return json(keys);+}++async function handleCreateAPIKey(req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ const body = await req.json<{ name?: string }>().catch(() => ({} as { name?: string }));+ const name = (body.name ?? "Untitled").trim() || "Untitled";+ // Same format as the cell: "osb_" + 64 hex chars (32 random bytes).+ const bytes = new Uint8Array(32);+ crypto.getRandomValues(bytes);+ const plainKey = "osb_" + [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");+ const hash = await sha256Hex(plainKey);+ const prefix = plainKey.slice(0, 8);+ const id = crypto.randomUUID();+ const now = Math.floor(Date.now() / 1000);+ await env.OPENCOMPUTER_DB.prepare(+ `INSERT INTO api_keys (id, org_id, created_by, key_hash, key_prefix, name, scopes, created_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'sandbox:*', ?7)`,+ ).bind(id, caller.orgID, caller.userID, hash, prefix, name, now).run();+ return json({+ id, orgId: caller.orgID, name, key: plainKey, keyPrefix: prefix,+ scopes: ["sandbox:*"], createdAt: new Date(now * 1000).toISOString(),+ }, 201);+}++async function handleDeleteAPIKey(_req: Request, env: DashboardEnv, caller: Caller, keyID: string): Promise<Response> {+ await env.OPENCOMPUTER_DB.prepare(`DELETE FROM api_keys WHERE id = ?1 AND org_id = ?2`).bind(keyID, caller.orgID).run();+ return new Response(null, { status: 204 });+}++// ── sessions list (cross-cell) ───────────────────────────────────────────++async function handleListSessions(req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ const url = new URL(req.url);+ const status = url.searchParams.get("status") ?? "";+ let stmt;+ if (status) {+ stmt = env.OPENCOMPUTER_DB.prepare(+ `SELECT id, cell_id, worker_id, status, template_id, created_at, last_event_at, stopped_at+ FROM sandboxes_index WHERE org_id = ?1 AND status = ?2 ORDER BY created_at DESC LIMIT 200`,+ ).bind(caller.orgID, status);+ } else {+ stmt = env.OPENCOMPUTER_DB.prepare(+ `SELECT id, cell_id, worker_id, status, template_id, created_at, last_event_at, stopped_at+ FROM sandboxes_index WHERE org_id = ?1 ORDER BY created_at DESC LIMIT 200`,+ ).bind(caller.orgID);+ }+ const { results } = await stmt.all<{+ id: string; cell_id: string; worker_id: string | null; status: string;+ template_id: string | null; created_at: number; last_event_at: number | null; stopped_at: number | null;+ }>();+ // Reshape to match the frontend's Session interface (camelCase, ISO timestamps).+ const sessions = (results ?? []).map((r) => ({+ id: r.id,+ sandboxId: r.id,+ orgId: caller.orgID,+ template: r.template_id ?? "default",+ region: cellToRegion(r.cell_id),+ workerId: r.worker_id ?? "",+ status: r.status,+ startedAt: epochToISORequired(r.created_at),+ stoppedAt: epochToISO(r.stopped_at),+ cellId: r.cell_id, // bonus: surface the cell for cross-cell aware UI+ }));+ return json(sessions);+}++// ── checkpoints (cross-cell) ─────────────────────────────────────────────++async function handleListCheckpoints(req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ try {+ const url = new URL(req.url);+ const page = Math.max(1, parseInt(url.searchParams.get("page") ?? "1", 10) || 1);+ const perPage = Math.min(100, Math.max(1, parseInt(url.searchParams.get("per_page") ?? "20", 10) || 20));+ const offset = (page - 1) * perPage;++ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, sandbox_id, owner_cell_id, s3_url, size_bytes, golden_hash, workspace_size, created_at, expires_at+ FROM checkpoints_index WHERE org_id = ?1 ORDER BY created_at DESC LIMIT ?2 OFFSET ?3`,+ ).bind(caller.orgID, perPage, offset).all<{+ id: string; sandbox_id: string; owner_cell_id: string; s3_url: string | null;+ size_bytes: number | null; golden_hash: string | null; workspace_size: number | null;+ created_at: number; expires_at: number | null;+ }>();+ const totalRow = await env.OPENCOMPUTER_DB.prepare(`SELECT COUNT(*) AS c FROM checkpoints_index WHERE org_id = ?1`).bind(caller.orgID).first<{ c: number }>();+ return json({+ checkpoints: (results ?? []).map((r) => ({+ id: r.id,+ sandboxId: r.sandbox_id ?? "",+ orgId: caller.orgID,+ name: (r.s3_url ?? "").split("/").filter(Boolean).pop() || r.id,+ status: "ready",+ sizeBytes: r.size_bytes ?? 0,+ activeForks: 0,+ totalForks: 0,+ createdAt: epochToISORequired(r.created_at),+ cellId: r.owner_cell_id ?? "",+ goldenHash: r.golden_hash ?? "",+ })),+ total: totalRow?.c ?? 0,+ page, perPage,+ });+ } catch (err) {+ console.error("handleListCheckpoints failed:", err);+ return json({ error: `checkpoints failed: ${(err as Error).message}` }, 500);+ }+}++async function handleDeleteCheckpoint(_req: Request, env: DashboardEnv, caller: Caller, cpID: string): Promise<Response> {+ // Verify ownership before delete.+ const row = await env.OPENCOMPUTER_DB.prepare(+ `SELECT owner_cell_id FROM checkpoints_index WHERE id = ?1 AND org_id = ?2`,+ ).bind(cpID, caller.orgID).first<{ owner_cell_id: string }>();+ if (!row) return json({ error: "checkpoint not found" }, 404);+ // Delete D1 row first (source of truth). Owning-cell blob cleanup is async+ // via the cell's existing GC; we don't try to coordinate here.+ await env.OPENCOMPUTER_DB.prepare(`DELETE FROM checkpoints_index WHERE id = ?1 AND org_id = ?2`).bind(cpID, caller.orgID).run();+ return new Response(null, { status: 204 });+}++// ── custom domain (CF Custom Hostnames API) ──────────────────────────────++interface CFCustomHostname {+ id: string;+ status: string;+ ssl: { status: string; txt_name?: string; txt_value?: string; validation_records?: { name: string; value: string }[] };+ ownership_verification?: { name: string; value: string };+}++async function cfAPI(env: DashboardEnv, method: string, path: string, body?: any): Promise<Response> {+ return fetch(`https://api.cloudflare.com/client/v4${path}`, {+ method,+ headers: {+ authorization: `Bearer ${env.CF_API_TOKEN}`,+ "content-type": "application/json",+ },+ body: body ? JSON.stringify(body) : undefined,+ });+}++async function handleSetCustomDomain(req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ if (!env.CF_API_TOKEN || !env.CF_ZONE_ID) return json({ error: "Cloudflare not configured" }, 503);+ const body = await req.json<{ domain?: string }>().catch(() => ({} as { domain?: string }));+ const domain = (body.domain ?? "").trim().toLowerCase();+ if (!domain) return json({ error: "domain required" }, 400);++ const org = await env.OPENCOMPUTER_DB.prepare(`SELECT cf_hostname_id FROM orgs WHERE id = ?1`).bind(caller.orgID).first<{ cf_hostname_id: string | null }>();+ if (org?.cf_hostname_id) {+ await cfAPI(env, "DELETE", `/zones/${env.CF_ZONE_ID}/custom_hostnames/${org.cf_hostname_id}`).catch(() => {});+ }+ const r = await cfAPI(env, "POST", `/zones/${env.CF_ZONE_ID}/custom_hostnames`, {+ hostname: domain,+ ssl: { method: "txt", type: "dv" },+ });+ if (!r.ok) return json({ error: `Cloudflare API: ${r.status} ${await r.text()}` }, 502);+ const data = (await r.json<{ result: CFCustomHostname }>()).result;++ const verifyName = data.ownership_verification?.name ?? null;+ const verifyValue = data.ownership_verification?.value ?? null;+ let sslName: string | null = null;+ let sslValue: string | null = null;+ if (data.ssl.txt_name) { sslName = data.ssl.txt_name; sslValue = data.ssl.txt_value ?? null; }+ else if (data.ssl.validation_records?.[0]) { sslName = data.ssl.validation_records[0].name; sslValue = data.ssl.validation_records[0].value; }++ await env.OPENCOMPUTER_DB.prepare(+ `UPDATE orgs SET custom_domain = ?1, cf_hostname_id = ?2, domain_verification_status = ?3, domain_ssl_status = ?4,+ verification_txt_name = ?5, verification_txt_value = ?6, ssl_txt_name = ?7, ssl_txt_value = ?8,+ updated_at = ?9+ WHERE id = ?10`,+ ).bind(domain, data.id, data.status, data.ssl.status, verifyName, verifyValue, sslName, sslValue, Math.floor(Date.now() / 1000), caller.orgID).run();+ const updated = await env.OPENCOMPUTER_DB.prepare(`SELECT * FROM orgs WHERE id = ?1`).bind(caller.orgID).first<OrgRow>();+ return json(updated ? shapeOrg(updated) : null);+}++async function handleDeleteCustomDomain(_req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ if (!env.CF_API_TOKEN || !env.CF_ZONE_ID) return json({ error: "Cloudflare not configured" }, 503);+ const org = await env.OPENCOMPUTER_DB.prepare(`SELECT cf_hostname_id FROM orgs WHERE id = ?1`).bind(caller.orgID).first<{ cf_hostname_id: string | null }>();+ if (org?.cf_hostname_id) {+ await cfAPI(env, "DELETE", `/zones/${env.CF_ZONE_ID}/custom_hostnames/${org.cf_hostname_id}`).catch(() => {});+ }+ await env.OPENCOMPUTER_DB.prepare(+ `UPDATE orgs SET custom_domain = NULL, cf_hostname_id = NULL,+ domain_verification_status = 'none', domain_ssl_status = 'none',+ verification_txt_name = NULL, verification_txt_value = NULL,+ ssl_txt_name = NULL, ssl_txt_value = NULL, updated_at = ?1+ WHERE id = ?2`,+ ).bind(Math.floor(Date.now() / 1000), caller.orgID).run();+ const updated = await env.OPENCOMPUTER_DB.prepare(`SELECT * FROM orgs WHERE id = ?1`).bind(caller.orgID).first<OrgRow>();+ return json(updated ? shapeOrg(updated) : null);+}++async function handleRefreshCustomDomain(_req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ if (!env.CF_API_TOKEN || !env.CF_ZONE_ID) return json({ error: "Cloudflare not configured" }, 503);+ const org = await env.OPENCOMPUTER_DB.prepare(`SELECT cf_hostname_id FROM orgs WHERE id = ?1`).bind(caller.orgID).first<{ cf_hostname_id: string | null }>();+ if (!org?.cf_hostname_id) return json({ error: "no custom domain configured" }, 400);+ const r = await cfAPI(env, "GET", `/zones/${env.CF_ZONE_ID}/custom_hostnames/${org.cf_hostname_id}`);+ if (!r.ok) return json({ error: `Cloudflare API: ${r.status}` }, 502);+ const data = (await r.json<{ result: CFCustomHostname }>()).result;++ const verifyName = data.ownership_verification?.name ?? null;+ const verifyValue = data.ownership_verification?.value ?? null;+ let sslName: string | null = null, sslValue: string | null = null;+ if (data.ssl.txt_name) { sslName = data.ssl.txt_name; sslValue = data.ssl.txt_value ?? null; }+ else if (data.ssl.validation_records?.[0]) { sslName = data.ssl.validation_records[0].name; sslValue = data.ssl.validation_records[0].value; }++ await env.OPENCOMPUTER_DB.prepare(+ `UPDATE orgs SET domain_verification_status = ?1, domain_ssl_status = ?2,+ verification_txt_name = ?3, verification_txt_value = ?4,+ ssl_txt_name = ?5, ssl_txt_value = ?6, updated_at = ?7+ WHERE id = ?8`,+ ).bind(data.status, data.ssl.status, verifyName, verifyValue, sslName, sslValue, Math.floor(Date.now() / 1000), caller.orgID).run();+ const updated = await env.OPENCOMPUTER_DB.prepare(`SELECT * FROM orgs WHERE id = ?1`).bind(caller.orgID).first<OrgRow>();+ return json(updated ? shapeOrg(updated) : null);+}++// ── credits + billing ────────────────────────────────────────────────────++async function handleGetCredits(_req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ const doStub = env.CREDIT_ACCOUNT.get(env.CREDIT_ACCOUNT.idFromName(caller.orgID));+ const snap = await doStub.fetch("https://do/snapshot");+ const orgRow = await env.OPENCOMPUTER_DB.prepare(`SELECT is_personal FROM orgs WHERE id = ?1`).bind(caller.orgID).first<{ is_personal: number }>();+ if (!snap.ok) {+ // DO might be uninitialized for an org that hasn't done /check yet.+ // Surface a sane default rather than 503'ing the dashboard.+ return json({ balanceCents: -1, isPersonal: !!orgRow?.is_personal });+ }+ const state = await snap.json<Record<string, any>>();+ const s = state.state ?? state;+ // Frontend Credits interface: { balanceCents, isPersonal }.+ return json({+ balanceCents: typeof s.balance_cents === "number" ? s.balance_cents : -1,+ isPersonal: !!orgRow?.is_personal,+ // Extras the dashboard may consume even though not on the strict type:+ plan: s.plan ?? caller.plan,+ status: s.status ?? "active",+ lifetimeSpentCents: s.lifetime_spent_cents ?? 0,+ haltedAt: typeof s.halted_at === "number" ? epochToISO(s.halted_at) : undefined,+ });+}++async function handleListAgentSubscriptions(_req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, agent_id, feature, status, stripe_item_id, created_at, cancelled_at+ FROM agent_subscriptions WHERE org_id = ?1 AND status = 'active'`,+ ).bind(caller.orgID).all();+ return json({ subscriptions: results ?? [] });+}++// ── WorkOS helpers ───────────────────────────────────────────────────────++async function workosUpdateOrg(env: DashboardEnv, workosOrgID: string, name: string): Promise<void> {+ await fetch(`https://api.workos.com/organizations/${workosOrgID}`, {+ method: "PUT",+ headers: { "content-type": "application/json", authorization: `Bearer ${env.WORKOS_API_KEY}` },+ body: JSON.stringify({ name }),+ });+}++// ── dispatch ─────────────────────────────────────────────────────────────++export async function handleDashboard(+ req: Request,+ env: DashboardEnv,+ _ctx: ExecutionContext,+ path: string,+): Promise<Response> {+ const caller = await authDashboard(req, env);+ if (!caller) return json({ error: "unauthenticated" }, 401);++ // /api/dashboard/* — strip the prefix for routing.+ const sub = path.replace(/^\/api\/dashboard/, "");+ const method = req.method.toUpperCase();++ // ── identity / org ─────────────────────────────────────────────────────+ if (sub === "/me" && method === "GET") return handleMe(req, env, caller);+ if (sub === "/orgs" && method === "GET") return handleListOrgs(req, env, caller);+ if (sub === "/org" && method === "GET") return handleGetOrg(req, env, caller);+ if (sub === "/org" && method === "PUT") return handleUpdateOrg(req, env, caller);+ if (sub === "/org/switch" && method === "POST") return handleOrgSwitch(req, env, caller);+ if (sub === "/org/members" && method === "GET") return handleListMembers(req, env, caller);+ {+ const m = sub.match(/^\/org\/members\/([^/]+)$/);+ if (m && method === "DELETE") return handleRemoveMember(req, env, caller, m[1]);+ }+ if (sub === "/org/invitations" && method === "GET") return handleListInvitations(req, env, caller);+ if (sub === "/org/invitations" && method === "POST") return handleSendInvitation(req, env, caller);+ {+ const m = sub.match(/^\/org\/invitations\/([^/]+)$/);+ if (m && method === "DELETE") return handleRevokeInvitation(req, env, caller, m[1]);+ }+ if (sub === "/org/credits" && method === "GET") return handleGetCredits(req, env, caller);+ if (sub === "/org/custom-domain" && method === "PUT") return handleSetCustomDomain(req, env, caller);+ if (sub === "/org/custom-domain" && method === "DELETE") return handleDeleteCustomDomain(req, env, caller);+ if (sub === "/org/custom-domain/refresh" && method === "POST") return handleRefreshCustomDomain(req, env, caller);++ // ── api keys ───────────────────────────────────────────────────────────+ if (sub === "/api-keys" && method === "GET") return handleListAPIKeys(req, env, caller);+ if (sub === "/api-keys" && method === "POST") return handleCreateAPIKey(req, env, caller);+ {+ const m = sub.match(/^\/api-keys\/([^/]+)$/);+ if (m && method === "DELETE") return handleDeleteAPIKey(req, env, caller, m[1]);+ }++ // ── sessions: cross-cell list, then per-cell proxy ─────────────────────+ if (sub === "/sessions" && method === "GET") return handleListSessions(req, env, caller);+ {+ const m = sub.match(/^\/sessions\/([^/]+)(\/.*)?$/);+ if (m) {+ const sandboxID = m[1];+ const rest = m[2] ?? ""; // "" means /sessions/:id only+ const target = await sandboxCell(env, sandboxID);+ if (!target) return json({ error: "sandbox not found" }, 404);+ if (target.org_id !== caller.orgID) return json({ error: "sandbox not in your org" }, 403);+ const cell = { cell_id: target.cell_id, base_url: target.base_url };+ const cellPath = `/internal/dashboard/sessions/${sandboxID}${rest}`;+ // WebSocket on PTY GET — anything else is a regular HTTP proxy.+ if (req.headers.get("upgrade")?.toLowerCase() === "websocket" && /^\/pty\/[^/]+$/.test(rest)) {+ return proxyWebSocket(req, env, caller, cell, cellPath);+ }+ return proxyToCell(req, env, caller, cell, cellPath);+ }+ }++ // ── checkpoints ───────────────────────────────────────────────────────+ if (sub === "/checkpoints" && method === "GET") return handleListCheckpoints(req, env, caller);+ {+ const m = sub.match(/^\/checkpoints\/([^/]+)$/);+ if (m && method === "DELETE") return handleDeleteCheckpoint(req, env, caller, m[1]);+ }++ // ── images: proxy to home cell ────────────────────────────────────────+ // image_cache is per-cell; for now dashboard shows the home cell's view.+ // Cross-cell image visibility is Phase 2 (D1 image_cache mirror).+ if (sub === "/images" || sub.startsWith("/images/")) {+ const cell = await homeCell(env, caller.orgID);+ if (!cell) return json({ error: "home cell unavailable" }, 503);+ return proxyToCell(req, env, caller, cell, `/internal/dashboard${sub}`);+ }++ // ── agents: proxy to home cell (cell-side hits external agents service) ─+ if (sub === "/agents" || sub.startsWith("/agents/")) {+ if (sub === "/billing/agent-subscriptions" && method === "GET") return handleListAgentSubscriptions(req, env, caller);+ const cell = await homeCell(env, caller.orgID);+ if (!cell) return json({ error: "home cell unavailable" }, 503);+ return proxyToCell(req, env, caller, cell, `/internal/dashboard${sub}`);+ }+ if (sub === "/billing/agent-subscriptions" && method === "GET") return handleListAgentSubscriptions(req, env, caller);++ // /billing — basic billing read used by the dashboard billing page.+ // Surfaces the org's plan + credit state from D1 + DO. The full billing+ // UI (invoices, payment methods, plan changes) routes through Stripe and+ // isn't implemented edge-native yet; return a stable placeholder so the+ // dashboard renders instead of 404-erroring on a missing route.+ if (sub === "/billing" && method === "GET") {+ const org = await env.OPENCOMPUTER_DB.prepare(+ `SELECT plan, stripe_customer_id, stripe_subscription_id, free_credits_remaining_cents, credit_balance_cents, is_halted+ FROM orgs WHERE id = ?1`,+ ).bind(caller.orgID).first<{+ plan: string; stripe_customer_id: string | null; stripe_subscription_id: string | null;+ free_credits_remaining_cents: number; credit_balance_cents: number; is_halted: number;+ }>();+ if (!org) return json({ error: "org not found" }, 404);+ // Cross-check against the live DO state — the D1 mirror gets written by+ // the DO after every debit but lags a touch, and on initial signup the+ // column reads its column-default (500) before the DO has ever been+ // touched. Reading the DO here is one extra round-trip per billing page+ // load but keeps the displayed credit consistent with the actual halt+ // gate the create flow enforces.+ let liveBalance = org.free_credits_remaining_cents;+ if (org.plan === "free") {+ try {+ const stub = env.CREDIT_ACCOUNT.get(env.CREDIT_ACCOUNT.idFromName(caller.orgID));+ const snap = await stub.fetch("https://do/snapshot");+ if (snap.ok) {+ const state = await snap.json<Record<string, any>>();+ const s = state.state ?? state;+ if (typeof s.balance_cents === "number" && s.balance_cents >= 0) {+ liveBalance = s.balance_cents;+ }+ }+ } catch (e) {+ console.error("billing: DO snapshot failed, falling back to D1 mirror:", e);+ }+ }+ return json({+ plan: org.plan,+ stripeCustomerId: org.stripe_customer_id ?? undefined,+ stripeSubscriptionId: org.stripe_subscription_id ?? undefined,+ freeCreditsRemainingCents: liveBalance,+ creditBalanceCents: org.credit_balance_cents,+ isHalted: !!org.is_halted,+ // Upcoming-invoice + meters would come from Stripe API on demand;+ // surface stubs for now so the UI has stable keys to render against.+ upcomingInvoice: null,+ meters: [],+ });+ }++ return json({ error: `not found: ${method} ${sub}` }, 404);+}diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 67e9d462..022635c6 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -1,6 +1,6 @@// api-edge Worker — global API entry point.//-// Implemented so far (cross-cell test path):+// Implemented:// POST /api/sandboxes — auth (D1 api_keys) → pick org.home_cell →// mint capability token → proxy to that cell's// CP /internal/sandboxes/create → record in@@ -8,26 +8,30 @@// GET /api/sandboxes — list this org's sandboxes from sandboxes_index// GET /api/sandboxes/:id — one row + cell_endpoint// ANY /api/sandboxes/:id/* — 307 to the owning cell's CP (dumb-client path)+// GET /internal/halt-list — HMAC-auth'd; halted org_ids from D1 (CP halt_reconciler)+// GET /auth/login — kicks off WorkOS Authkit flow+// GET /auth/callback — WorkOS code exchange → upsert user/org → session JWT cookie+// POST /auth/logout — clear session cookie+// POST /auth/refresh — rotate session JWT (extends expiry)+// POST /webhooks/stripe — Stripe webhook → DO /mark-pro or /mark-free// GET /health-//-// Still 501 (not on the cross-cell test path): /auth/*, /webhooks/stripe,-// /internal/halt-list. See docs/dev-cutover-runbook.md.export { CreditAccount } from "../../shared/credit_account";+import { handleDashboard, type DashboardEnv } from "./dashboard";+import * as secretStores from "./secret_stores";+import * as templates from "./templates";-export interface Env {- OPENCOMPUTER_DB: D1Database;- SESSIONS_KV: KVNamespace;- CREDIT_ACCOUNT: DurableObjectNamespace;- SESSION_JWT_SECRET: string;+export interface Env extends DashboardEnv {CF_ADMIN_SECRET: string;STRIPE_WEBHOOK_SECRET: string;- STRIPE_API_KEY: string;- WORKOS_API_KEY: string;- WORKOS_CLIENT_ID: string;EVENT_SECRET: string;- WORKER_ENV: string;- CELLS: string;+ // Shared with every CP via Infisical /shared/ → per-cell KV/SM. Used for+ // envelope encryption of secret_store_entries.encrypted_value. Matches+ // internal/crypto.Encryptor key format (hex-encoded 32 bytes).+ SECRET_ENCRYPTION_KEY: string;+ // CF_API_TOKEN and CF_ZONE_ID are optional in DashboardEnv (custom domain+ // feature gates on them). Inherited.+ ASSETS?: Fetcher;}// ── small helpers ────────────────────────────────────────────────────────@@ -53,11 +57,14 @@ async function sha256Hex(s: string): Promise<string> {// Mint the capability token the regional CP expects on /internal/sandboxes/create:// HS256 JWT signed with SESSION_JWT_SECRET, iss="opensandbox-edge", carrying-// org_id + cell_id (+ optional user_id). Mirrors auth.CapabilityClaims in Go.+// org_id + cell_id + plan (+ optional user_id). Mirrors auth.CapabilityClaims+// in Go. Plan flows through so the worker can tag usage_tick events without+// a per-event PG lookup.async function mintCapToken(secret: string,orgID: string,cellID: string,+ plan: string,userID: string | null,): Promise<string> {const now = Math.floor(Date.now() / 1000);@@ -69,6 +76,7 @@ async function mintCapToken(exp: now + 120, // short-lived — it's only the edge→CP hoporg_id: orgID,cell_id: cellID,+ plan,};if (userID) payload.user_id = userID;const enc = new TextEncoder();@@ -305,18 +313,46 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {const caller = await authenticate(req, env);if (!caller) return json({ error: "missing or invalid API key" }, 401);- const org = await env.OPENCOMPUTER_DB.prepare("SELECT home_cell FROM orgs WHERE id = ?1")+ const org = await env.OPENCOMPUTER_DB.prepare("SELECT home_cell, plan, is_halted FROM orgs WHERE id = ?1").bind(caller.orgID)- .first<{ home_cell: string }>();+ .first<{ home_cell: string; plan: string; is_halted: number }>();if (!org) return json({ error: "org not found" }, 401);+ const plan = org.plan === "pro" ? "pro" : "free";++ // Gate on billing state BEFORE picking a cell. Free orgs hit the DO+ // /check for an authoritative balance read; pro orgs skip the round trip.+ // is_halted is a D1 fast path — if it's 1, we don't even need to ask the DO.+ if (plan === "free") {+ if (org.is_halted === 1) {+ return json({ error: "free trial credits exhausted — upgrade to resume" }, 402);+ }+ const doID = env.CREDIT_ACCOUNT.idFromName(caller.orgID);+ const doStub = env.CREDIT_ACCOUNT.get(doID);+ const checkResp = await doStub.fetch(`https://do/check?org_id=${encodeURIComponent(caller.orgID)}`, {+ method: "POST",+ });+ if (checkResp.status !== 200) {+ // DO failure shouldn't soft-fail open — credit gating exists for a reason.+ // If the DO is genuinely down we get a 5xx; surface that.+ return json({ error: "credit check unavailable" }, 503);+ }+ const check = await checkResp.json<{ allowed: boolean; balance_cents: number }>();+ if (!check.allowed) {+ return json({ error: "free trial credits exhausted — upgrade to resume", balance_cents: check.balance_cents }, 402);+ }+ }// Read body once — used for the hard-pin peek + forwarded to the CP verbatim.const bodyText = await req.text();let requestedCellID: string | null = null;+ let bodyCpuCount = 0;+ let bodyMemoryMB = 0;try {if (bodyText) {- const parsed = JSON.parse(bodyText) as { cellId?: unknown };+ const parsed = JSON.parse(bodyText) as { cellId?: unknown; cpuCount?: unknown; memoryMB?: unknown };if (typeof parsed.cellId === "string") requestedCellID = parsed.cellId;+ if (typeof parsed.cpuCount === "number") bodyCpuCount = parsed.cpuCount;+ if (typeof parsed.memoryMB === "number") bodyMemoryMB = parsed.memoryMB;}} catch {/* malformed JSON — let the CP reject with a proper 400 */@@ -332,7 +368,7 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {);}- const capToken = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, caller.userID);+ const capToken = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, caller.userID);let cpResp: Response;try {cpResp = await fetch(cell.base_url.replace(/\/$/, "") + "/internal/sandboxes/create", {@@ -355,8 +391,8 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {if (parsed.sandboxID) {await env.OPENCOMPUTER_DB.prepare(`INSERT OR REPLACE INTO sandboxes_index- (id, org_id, user_id, cell_id, worker_id, status, created_at, last_event_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7)`,+ (id, org_id, user_id, cell_id, worker_id, status, cpu_count, memory_mb, created_at, last_event_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9)`,).bind(parsed.sandboxID,@@ -365,6 +401,8 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {cell.cell_id,parsed.workerID ?? null,parsed.status ?? "running",+ bodyCpuCount,+ bodyMemoryMB,Math.floor(Date.now() / 1000),).run();@@ -377,49 +415,605 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {});}+// sandboxRowToJSON reshapes a D1 sandboxes_index row into the JSON the legacy+// CP /api/sandboxes returned — which the Go CLI's types.Sandbox struct + the+// Python/TS SDKs all unmarshal against. Important translations:+// id → sandboxID (Go json tag is `sandboxID`)+// template_id → templateID+// cell_id → cellID+// worker_id → workerID+// created_at → startedAt (unix int → ISO string)+// stopped_at → endAt (unix int / null → ISO string; null becomes the+// Go time.Time zero value, "0001-01-01T00:00:00Z")+// cpu_count → cpuCount+// memory_mb → memoryMB+interface SandboxRow {+ id: string;+ cell_id: string;+ worker_id: string | null;+ status: string;+ template_id: string | null;+ cpu_count: number | null;+ memory_mb: number | null;+ created_at: number;+ last_event_at: number | null;+ stopped_at: number | null;+}++function isoFromUnix(secs: number | null): string {+ // Go time.Time zero value when the column is NULL. The CLI tolerates this.+ if (secs == null || secs === 0) return "0001-01-01T00:00:00Z";+ return new Date(secs * 1000).toISOString();+}++function sandboxRowToJSON(r: SandboxRow): Record<string, unknown> {+ return {+ sandboxID: r.id,+ templateID: r.template_id ?? "",+ cellID: r.cell_id,+ workerID: r.worker_id ?? "",+ status: r.status,+ cpuCount: r.cpu_count ?? 0,+ memoryMB: r.memory_mb ?? 0,+ startedAt: isoFromUnix(r.created_at),+ endAt: isoFromUnix(r.stopped_at),+ };+}+async function listSandboxes(req: Request, env: Env): Promise<Response> {const caller = await authenticate(req, env);if (!caller) return json({ error: "missing or invalid API key" }, 401);const { results } = await env.OPENCOMPUTER_DB.prepare(- `SELECT id, cell_id, worker_id, status, template_id, created_at, last_event_at, stopped_at+ `SELECT id, cell_id, worker_id, status, template_id, cpu_count, memory_mb,+ created_at, last_event_at, stopped_atFROM sandboxes_index WHERE org_id = ?1 ORDER BY created_at DESC LIMIT 200`,).bind(caller.orgID)- .all();- return json({ sandboxes: results });+ .all<SandboxRow>();+ return json((results ?? []).map(sandboxRowToJSON));}async function getSandbox(req: Request, env: Env, id: string): Promise<Response> {const caller = await authenticate(req, env);if (!caller) return json({ error: "missing or invalid API key" }, 401);const row = await env.OPENCOMPUTER_DB.prepare(- `SELECT id, org_id, cell_id, worker_id, status, template_id, created_at, last_event_at, stopped_at+ `SELECT id, org_id, cell_id, worker_id, status, template_id, cpu_count, memory_mb,+ created_at, last_event_at, stopped_atFROM sandboxes_index WHERE id = ?1`,).bind(id)- .first<{ org_id: string; cell_id: string } & Record<string, unknown>>();+ .first<SandboxRow & { org_id: string }>();if (!row || row.org_id !== caller.orgID) return json({ error: "sandbox not found" }, 404);const cell = await lookupCell(env, row.cell_id);- return json({ ...row, cell_endpoint: cell ? cell.base_url : null });+ return json({ ...sandboxRowToJSON(row), cellEndpoint: cell ? cell.base_url : null });}-// 307 the request to the owning cell's CP — same path + query, body preserved-// by the 307 semantics. Re-auth happens at the CP (API key / sandbox JWT).-async function redirectToCell(req: Request, env: Env, id: string, url: URL): Promise<Response> {+// Proxy the request to the owning cell's CP. Used for SDK runtime calls+// (`/api/sandboxes/:id/exec`, `/files`, `/pty`, etc.). The caller has been+// authenticated at the edge against D1; we mint a short-lived IdentityToken+// the cell's PGAPIKeyMiddleware already accepts (audience `opencomputer-api`)+// and stream the response back. Pre-fix this was a 307 redirect, which broke+// when the SDK's API key didn't exist in cell PG (api_keys are global in D1+// now, not mirrored per-cell).+async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, caller: Caller, id: string): Promise<Response> {const row = await env.OPENCOMPUTER_DB.prepare("SELECT cell_id FROM sandboxes_index WHERE id = ?1").bind(id).first<{ cell_id: string }>();if (!row) return json({ error: "sandbox not found" }, 404);const cell = await lookupCell(env, row.cell_id);if (!cell) return json({ error: `cell ${row.cell_id} not registered` }, 503);++ const url = new URL(req.url);const target = cell.base_url.replace(/\/$/, "") + url.pathname + url.search;- return new Response(null, { status: 307, headers: { location: target } });+ // Look up the org's plan so the cap-token carries it (worker resolver uses+ // plan to tag usage_tick events; without it free-tier debit fan-out skips+ // the org).+ const orgRow = await env.OPENCOMPUTER_DB.prepare("SELECT plan FROM orgs WHERE id = ?1")+ .bind(caller.orgID).first<{ plan: string }>();+ // Mint a cap-token (iss=opensandbox-edge, signed with SESSION_JWT_SECRET).+ // The cell's PGAPIKeyMiddleware accepts cap-tokens too (alongside identity+ // tokens and API keys), so the same handler chain that runs for SDK+ // X-API-Key auth runs here. cell_id in the token guards against replay+ // against a different cell.+ const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, row.cell_id, orgRow?.plan ?? "free", caller.userID);++ const headers = new Headers();+ for (const [k, v] of req.headers.entries()) {+ const lk = k.toLowerCase();+ // Drop the caller's X-API-Key — the cell would try to validate it against+ // its own PG and fail. We replace it with the IdentityToken JWT below.+ if (lk === "host" || lk === "cookie" || lk === "x-api-key" || lk.startsWith("cf-") || lk.startsWith("x-forwarded-")) continue;+ headers.set(k, v);+ }+ headers.set("authorization", "Bearer " + token);++ const init: RequestInit = { method: req.method, headers };+ if (req.method !== "GET" && req.method !== "HEAD") init.body = req.body;++ // Intercept lifecycle ops to keep D1 sandboxes_index in sync with cell PG.+ // Edge already writes the row on CREATE; here we mirror the cell's status+ // changes on DELETE / hibernate / wake. Otherwise the dashboard accumulates+ // phantoms — D1 rows stuck at "running" after the actual sandbox stopped.+ const path = url.pathname;+ let postUpdate: { status: string; setStopped: boolean } | null = null;+ if (req.method === "DELETE" && path === `/api/sandboxes/${id}`) {+ postUpdate = { status: "stopped", setStopped: true };+ } else if (req.method === "POST" && path === `/api/sandboxes/${id}/hibernate`) {+ postUpdate = { status: "hibernated", setStopped: false };+ } else if (req.method === "POST" && path === `/api/sandboxes/${id}/wake`) {+ postUpdate = { status: "running", setStopped: false };+ }++ // WebSocket upgrade — preserve the upgrade context by cloning the inbound+ // Request, then swap Authorization. The manual fetch + Sec-WebSocket-Key+ // copy / WebSocketPair bridge dance below was buggy ("bad handshake" on+ // the CLI side because the upgrade headers got rebuilt without proper+ // accept-key derivation). CF Workers + CF Tunnel forward WebSocket+ // upgrades transparently when you pass a Request clone — same pattern+ // handlePreviewURL uses and that's verified to work end-to-end with WS.+ if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {+ const fwd = new Request(target, req);+ fwd.headers.set("authorization", "Bearer " + token);+ fwd.headers.delete("x-api-key");+ return await fetch(fwd);+ }++ // Non-WebSocket path. Run the proxy and then, on success, fan out the+ // status update to D1 so the dashboard sees the new state immediately.+ // Otherwise the dashboard accumulates phantoms — D1 rows stuck at+ // "running" after the actual sandbox stopped.+ const resp = await fetch(target, init);+ if (postUpdate && resp.status >= 200 && resp.status < 300) {+ const nowSec = Math.floor(Date.now() / 1000);+ const updateSQL = postUpdate.setStopped+ ? "UPDATE sandboxes_index SET status = ?1, stopped_at = ?2, last_event_at = ?2 WHERE id = ?3"+ : "UPDATE sandboxes_index SET status = ?1, last_event_at = ?2 WHERE id = ?3";+ // ctx.waitUntil keeps the background D1 write alive after the response+ // returns. Without it the Worker terminates the in-flight Promise and+ // the UPDATE never runs — sandboxes_index drifts behind cell PG.+ ctx.waitUntil(+ env.OPENCOMPUTER_DB.prepare(updateSQL).bind(postUpdate.status, nowSec, id).run().catch((e) => {+ console.error(`sandboxes_index ${postUpdate!.status} update failed for ${id}:`, e);+ }),+ );+ }+ return resp;+}+++// ── /internal/halt-list ─────────────────────────────────────────────────++// HMAC-auth'd endpoint the cell's halt_reconciler polls every 60s to+// reconcile any halt webhooks it might have missed. Returns the list of+// org_ids that the DO currently flags halted (mirrored in D1 orgs.is_halted).+// HMAC scheme matches the DO's dispatch: "{X-Timestamp}.{path-with-query}"+// signed with EVENT_SECRET (shared with CP), SHA-256 hex.+async function haltList(req: Request, env: Env): Promise<Response> {+ const ts = req.headers.get("X-Timestamp") ?? "";+ const sig = req.headers.get("X-Signature") ?? "";+ if (!ts || !sig) return json({ error: "missing signature headers" }, 400);+ const tsNum = Number.parseInt(ts, 10);+ if (!Number.isFinite(tsNum)) return json({ error: "invalid timestamp" }, 400);+ const now = Math.floor(Date.now() / 1000);+ if (Math.abs(now - tsNum) > 5 * 60) return json({ error: "timestamp out of window" }, 401);++ const url = new URL(req.url);+ const cellID = url.searchParams.get("cell") ?? "";+ const expected = await hmacHex(env.EVENT_SECRET, `${ts}.${url.pathname}${url.search}`);+ if (!constantTimeEqual(expected, sig)) return json({ error: "signature mismatch" }, 401);++ // Return halted orgs that have any sandbox on the requesting cell. The+ // reconciler only needs to act on orgs it can do something about — orgs+ // halted with sandboxes on a DIFFERENT cell are that cell's reconciler's+ // problem. If no `cell` param is supplied, return all halted orgs (used+ // by parity-check cron / debugging).+ let results: { id: string; halted_at: number | null }[];+ if (cellID) {+ const res = await env.OPENCOMPUTER_DB.prepare(+ `SELECT DISTINCT o.id, o.halted_at+ FROM orgs o+ JOIN sandboxes_index s ON s.org_id = o.id+ WHERE o.is_halted = 1 AND s.cell_id = ?1`,+ )+ .bind(cellID)+ .all<{ id: string; halted_at: number | null }>();+ results = res.results ?? [];+ } else {+ const res = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, halted_at FROM orgs WHERE is_halted = 1`,+ ).all<{ id: string; halted_at: number | null }>();+ results = res.results ?? [];+ }+ return json({+ org_ids: results.map((r) => r.id),+ halted_at: Object.fromEntries(results.map((r) => [r.id, r.halted_at])),+ as_of: now,+ });+}++async function hmacHex(secret: string, data: string): Promise<string> {+ const key = await crypto.subtle.importKey(+ "raw",+ new TextEncoder().encode(secret),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ );+ const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(data));+ return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");+}++function constantTimeEqual(a: string, b: string): boolean {+ if (a.length !== b.length) return false;+ let diff = 0;+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);+ return diff === 0;+}++// ── WorkOS auth flow ─────────────────────────────────────────────────────+//+// Browser flow:+// GET /auth/login → 302 to WorkOS AuthKit authorization URL+// GET /auth/callback?code= → exchange code, upsert user+org in D1, mint+// session JWT, set cookie, redirect to /dashboard+// POST /auth/logout → clear session cookie+// POST /auth/refresh → rotate session JWT (extends expiry)+//+// Session JWT lives in an httpOnly Secure SameSite=Lax cookie named+// `oc_session`. The same secret signs the cap-token, so the cell can+// verify a session JWT presented directly (browser fetch from dashboard)+// using the existing capTokenMiddleware — we just set Issuer="opensandbox-session"+// to distinguish.++const SESSION_COOKIE = "oc_session";+const SESSION_TTL_SEC = 60 * 60 * 8; // 8h++interface WorkOSProfile {+ id: string;+ email: string;+ first_name?: string;+ last_name?: string;+ organization_id?: string;+}++async function authLogin(req: Request, env: Env): Promise<Response> {+ const reqURL = new URL(req.url);+ const redirectURI = `${reqURL.origin}/auth/callback`;+ // WorkOS AuthKit hosted login URL. authorize_url uses provider=authkit+ // for the "magic-link or oauth" hosted page.+ const authURL = new URL("https://api.workos.com/user_management/authorize");+ authURL.searchParams.set("client_id", env.WORKOS_CLIENT_ID);+ authURL.searchParams.set("provider", "authkit");+ authURL.searchParams.set("redirect_uri", redirectURI);+ authURL.searchParams.set("response_type", "code");+ return Response.redirect(authURL.toString(), 302);+}++async function authCallback(req: Request, env: Env): Promise<Response> {+ const reqURL = new URL(req.url);+ const code = reqURL.searchParams.get("code");+ if (!code) return json({ error: "missing code" }, 400);+ const redirectURI = `${reqURL.origin}/auth/callback`;++ // Exchange code for user profile.+ const tokenResp = await fetch("https://api.workos.com/user_management/authenticate", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ client_id: env.WORKOS_CLIENT_ID,+ client_secret: env.WORKOS_API_KEY,+ grant_type: "authorization_code",+ code,+ redirect_uri: redirectURI,+ }),+ });+ if (tokenResp.status !== 200) {+ const errText = await tokenResp.text();+ return json({ error: `workos exchange failed: ${tokenResp.status}: ${errText}` }, 401);+ }+ const tokenBody = await tokenResp.json<{ user: WorkOSProfile; organization_id?: string }>();+ const profile = tokenBody.user;++ // Upsert user + org. We share WorkOS with prod, so workos_user_id is the+ // stable identity across both. Org auto-created on first sign-in with+ // home_cell picked per the policy below.+ const nowSec = Math.floor(Date.now() / 1000);+ const userRow = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id FROM users WHERE workos_user_id = ?1`,+ )+ .bind(profile.id)+ .first<{ id: string }>();+ let userID: string;+ if (userRow) {+ userID = userRow.id;+ } else {+ userID = crypto.randomUUID();+ await env.OPENCOMPUTER_DB.prepare(+ `INSERT INTO users (id, email, workos_user_id, name, created_at)+ VALUES (?1, ?2, ?3, ?4, ?5)+ ON CONFLICT(email) DO UPDATE SET workos_user_id = excluded.workos_user_id`,+ )+ .bind(+ userID,+ profile.email,+ profile.id,+ [profile.first_name, profile.last_name].filter(Boolean).join(" ") || profile.email,+ nowSec,+ )+ .run();+ }++ // Find an org via membership; if none, create a personal one.+ const orgRow = await env.OPENCOMPUTER_DB.prepare(+ `SELECT o.id, o.plan FROM orgs o+ JOIN org_memberships m ON m.org_id = o.id+ WHERE m.user_id = ?1 LIMIT 1`,+ )+ .bind(userID)+ .first<{ id: string; plan: string }>();+ let orgID: string;+ let orgPlan: string;+ if (orgRow) {+ orgID = orgRow.id;+ orgPlan = orgRow.plan;+ } else {+ orgID = crypto.randomUUID();+ const homeCell = await pickHomeCell(env, req);+ orgPlan = "free";+ await env.OPENCOMPUTER_DB.prepare(+ `INSERT INTO orgs (id, name, slug, plan, home_cell, is_personal, owner_user_id, created_at, updated_at)+ VALUES (?1, ?2, ?3, 'free', ?4, 1, ?5, ?6, ?6)`,+ )+ .bind(orgID, `${profile.email}'s workspace`, slugify(profile.email + "-" + orgID.slice(0, 6)), homeCell, userID, nowSec)+ .run();+ await env.OPENCOMPUTER_DB.prepare(+ `INSERT INTO org_memberships (org_id, user_id, role, created_at) VALUES (?1, ?2, 'owner', ?3)`,+ )+ .bind(orgID, userID, nowSec)+ .run();+ }++ // Mint session JWT — same signing secret as cap-token but a different+ // Issuer so cell middleware can distinguish.+ const sessionJWT = await mintSessionJWT(env.SESSION_JWT_SECRET, orgID, userID, orgPlan);++ // Redirect to dashboard with the cookie set.+ const dashURL = `${reqURL.origin}/dashboard`;+ return new Response(null, {+ status: 302,+ headers: {+ location: dashURL,+ "set-cookie": `${SESSION_COOKIE}=${sessionJWT}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${SESSION_TTL_SEC}`,+ },+ });+}++async function authLogout(): Promise<Response> {+ return new Response(null, {+ status: 204,+ headers: {+ "set-cookie": `${SESSION_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0`,+ },+ });+}++async function authRefresh(req: Request, env: Env): Promise<Response> {+ const cookie = req.headers.get("cookie") ?? "";+ const m = cookie.match(new RegExp(`${SESSION_COOKIE}=([^;]+)`));+ if (!m) return json({ error: "no session" }, 401);+ const claims = await verifySessionJWT(env.SESSION_JWT_SECRET, m[1]);+ if (!claims) return json({ error: "invalid session" }, 401);+ // Re-mint with fresh expiry. Plan is re-read from D1 in case it changed.+ const orgRow = await env.OPENCOMPUTER_DB.prepare(+ `SELECT plan FROM orgs WHERE id = ?1`,+ )+ .bind(claims.org_id)+ .first<{ plan: string }>();+ const plan = orgRow?.plan ?? "free";+ const fresh = await mintSessionJWT(env.SESSION_JWT_SECRET, claims.org_id, claims.user_id, plan);+ return new Response(JSON.stringify({ ok: true, plan }), {+ status: 200,+ headers: {+ "content-type": "application/json",+ "set-cookie": `${SESSION_COOKIE}=${fresh}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${SESSION_TTL_SEC}`,+ },+ });+}++// pickHomeCell chooses a home cell for a brand-new org. Policy:+// 1. If the request carries a `cf-ipcountry` header, map to a continent+// and prefer a cell whose region is on that continent.+// 2. Otherwise pick the first cell from env.CELLS that's currently+// registered in D1 and healthy.+// 3. Last-resort fallback: first entry in env.CELLS regardless of D1 state.+//+// Geo lookup is intentionally coarse — continent-level is enough for+// "don't put a UK user on a US cell" without an IP-to-region service.+async function pickHomeCell(env: Env, req: Request): Promise<string> {+ const country = req.headers.get("cf-ipcountry") ?? "";+ const continent = COUNTRY_TO_CONTINENT[country.toUpperCase()] ?? "";++ const configured = env.CELLS.split(",").map((c) => c.trim()).filter(Boolean);+ if (configured.length === 0) return ""; // misconfigured — let downstream error++ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT cell_id, region, status FROM cells WHERE status = 'active'`,+ ).all<{ cell_id: string; region: string; status: string }>();+ const activeCells = (results ?? []).filter((c) => configured.includes(c.cell_id));++ if (continent && activeCells.length > 0) {+ const onContinent = activeCells.find((c) => REGION_CONTINENT[c.region] === continent);+ if (onContinent) return onContinent.cell_id;+ }+ if (activeCells.length > 0) return activeCells[0].cell_id;+ return configured[0];+}++// COUNTRY_TO_CONTINENT covers the countries we'd actually see on the+// edge. Missing entries fall through to "no continent hint" — we don't+// need to be exhaustive; an unknown country just means we pick the+// first active cell.+const COUNTRY_TO_CONTINENT: Record<string, string> = {+ US: "na", CA: "na", MX: "na",+ GB: "eu", IE: "eu", DE: "eu", FR: "eu", IT: "eu", ES: "eu", NL: "eu", SE: "eu", PL: "eu", CH: "eu", AT: "eu", BE: "eu", DK: "eu", FI: "eu", NO: "eu", PT: "eu", CZ: "eu",+ JP: "ap", KR: "ap", CN: "ap", IN: "ap", SG: "ap", AU: "ap", NZ: "ap", HK: "ap", TW: "ap", ID: "ap", PH: "ap", VN: "ap", TH: "ap", MY: "ap",+ BR: "sa", AR: "sa", CL: "sa", CO: "sa", PE: "sa",+ ZA: "af", NG: "af", EG: "af", KE: "af",+};++function slugify(s: string): string {+ return s.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 50);+}++interface SessionClaims {+ org_id: string;+ user_id: string;+ plan: string;+ iat: number;+ exp: number;+}++async function mintSessionJWT(secret: string, orgID: string, userID: string, plan: string): Promise<string> {+ const now = Math.floor(Date.now() / 1000);+ const header = { alg: "HS256", typ: "JWT" };+ const payload = {+ iss: "opensandbox-session",+ sub: userID,+ iat: now,+ exp: now + SESSION_TTL_SEC,+ org_id: orgID,+ user_id: userID,+ plan,+ };+ const enc = new TextEncoder();+ const signingInput =+ b64url(enc.encode(JSON.stringify(header))) + "." + b64url(enc.encode(JSON.stringify(payload)));+ const key = await crypto.subtle.importKey(+ "raw",+ enc.encode(secret),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ );+ const sig = await crypto.subtle.sign("HMAC", key, enc.encode(signingInput));+ return signingInput + "." + b64url(sig);+}++async function verifySessionJWT(secret: string, token: string): Promise<SessionClaims | null> {+ const parts = token.split(".");+ if (parts.length !== 3) return null;+ const [headerB64, payloadB64, sigB64] = parts;+ const enc = new TextEncoder();+ const key = await crypto.subtle.importKey(+ "raw",+ enc.encode(secret),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ );+ const expected = await crypto.subtle.sign("HMAC", key, enc.encode(`${headerB64}.${payloadB64}`));+ if (b64url(expected) !== sigB64) return null;+ try {+ const payload = JSON.parse(atob(payloadB64.replace(/-/g, "+").replace(/_/g, "/"))) as SessionClaims & { iss?: string };+ if (payload.iss !== "opensandbox-session") return null;+ if (payload.exp < Math.floor(Date.now() / 1000)) return null;+ return payload;+ } catch {+ return null;+ }+}++// ── Stripe webhook ───────────────────────────────────────────────────────+//+// Stripe POSTs subscription / invoice events. We verify the signature,+// translate the event into a CreditAccount DO call:+// customer.subscription.created / checkout.session.completed → /mark-pro+// customer.subscription.deleted → /mark-free+//+// org_id is recovered from Stripe customer metadata (set when we create+// the customer at upgrade-checkout time). For events without an org_id we+// log and return 200 — Stripe expects 2xx or it'll retry forever.++async function stripeWebhook(req: Request, env: Env): Promise<Response> {+ const sigHeader = req.headers.get("stripe-signature") ?? "";+ const body = await req.text();++ if (!(await verifyStripeSignature(env.STRIPE_WEBHOOK_SECRET, sigHeader, body))) {+ return json({ error: "invalid signature" }, 401);+ }++ let event: { type: string; data: { object: any } };+ try {+ event = JSON.parse(body);+ } catch {+ return json({ error: "invalid json" }, 400);+ }++ const obj = event.data?.object ?? {};+ const orgID = obj.metadata?.org_id || obj.customer_metadata?.org_id || "";++ switch (event.type) {+ case "customer.subscription.created":+ case "checkout.session.completed": {+ if (!orgID) {+ console.error(`stripe: ${event.type} without org_id metadata; logging and skipping`);+ return json({ received: true, skipped: "no org_id" });+ }+ const stub = env.CREDIT_ACCOUNT.get(env.CREDIT_ACCOUNT.idFromName(orgID));+ const resp = await stub.fetch(`https://do/mark-pro?org_id=${encodeURIComponent(orgID)}`, { method: "POST" });+ if (resp.status >= 400) {+ console.error(`stripe: DO /mark-pro ${orgID} returned ${resp.status}`);+ }+ // Stamp stripe IDs on the org row for the next callback round-trip.+ if (obj.customer || obj.subscription) {+ await env.OPENCOMPUTER_DB.prepare(+ `UPDATE orgs SET stripe_customer_id = COALESCE(?1, stripe_customer_id),+ stripe_subscription_id = COALESCE(?2, stripe_subscription_id),+ updated_at = ?3+ WHERE id = ?4`,+ )+ .bind(obj.customer ?? null, obj.subscription ?? null, Math.floor(Date.now() / 1000), orgID)+ .run();+ }+ return json({ received: true });+ }+ case "customer.subscription.deleted": {+ if (!orgID) {+ console.error(`stripe: subscription.deleted without org_id; skipping`);+ return json({ received: true, skipped: "no org_id" });+ }+ const stub = env.CREDIT_ACCOUNT.get(env.CREDIT_ACCOUNT.idFromName(orgID));+ const resp = await stub.fetch(`https://do/mark-free?org_id=${encodeURIComponent(orgID)}`, { method: "POST" });+ if (resp.status >= 400) {+ console.error(`stripe: DO /mark-free ${orgID} returned ${resp.status}`);+ }+ return json({ received: true });+ }+ default:+ // Many event types we don't care about (invoice.*, payment_method.*, etc.).+ // Ack so Stripe stops retrying.+ return json({ received: true, ignored: event.type });+ }+}++// verifyStripeSignature checks the t=… v1=… Stripe-Signature header.+// Stripe signs `${timestamp}.${body}` with HMAC-SHA256.+async function verifyStripeSignature(secret: string, header: string, body: string): Promise<boolean> {+ const parts = header.split(",").map((p) => p.split("="));+ const ts = parts.find((p) => p[0] === "t")?.[1];+ const v1 = parts.find((p) => p[0] === "v1")?.[1];+ if (!ts || !v1) return false;+ // Reject signatures older than 5 minutes (Stripe replay defense recommendation).+ const tsNum = Number.parseInt(ts, 10);+ if (!Number.isFinite(tsNum) || Math.abs(Math.floor(Date.now() / 1000) - tsNum) > 5 * 60) return false;+ const expected = await hmacHex(secret, `${ts}.${body}`);+ return constantTimeEqual(expected, v1);}// ── entrypoint ───────────────────────────────────────────────────────────export default {- async fetch(req: Request, env: Env): Promise<Response> {+ async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> {const url = new URL(req.url);const path = url.pathname;@@ -435,6 +1029,97 @@ export default {return json({ ok: true, env: env.WORKER_ENV, cells: env.CELLS.split(",") });}+ if (path === "/internal/halt-list") {+ if (req.method !== "GET") return json({ error: "method not allowed" }, 405);+ return haltList(req, env);+ }++ // /internal/secret-stores/:id — HMAC-auth'd, called by CP at sandbox-create+ // time to materialize the encrypted entry list. CP decrypts with the+ // shared SECRET_ENCRYPTION_KEY before injecting into worker env.+ if (path === "/internal/secret-stores/by-name") {+ if (req.method !== "GET") return json({ error: "method not allowed" }, 405);+ return secretStores.internalGetStoreByName(req, env);+ }+ {+ const m = path.match(/^\/internal\/secret-stores\/([^/]+)$/);+ if (m) {+ if (req.method !== "GET") return json({ error: "method not allowed" }, 405);+ return secretStores.internalGetStore(req, env, m[1]);+ }+ }++ // /internal/templates/* — HMAC-auth'd. by-name = sandbox-create lookup;+ // POST / = "save sandbox as template" registration; PUT /:id/status =+ // flip status='ready' once snapshot upload finishes.+ if (path === "/internal/templates/by-name") {+ if (req.method !== "GET") return json({ error: "method not allowed" }, 405);+ return templates.internalGetByName(req, env);+ }+ if (path === "/internal/templates") {+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);+ return templates.internalRegister(req, env);+ }+ {+ const m = path.match(/^\/internal\/templates\/([^/]+)\/status$/);+ if (m) {+ if (req.method !== "PUT") return json({ error: "method not allowed" }, 405);+ return templates.internalUpdateStatus(req, env, m[1]);+ }+ }++ // /api/secret-stores — org-scoped CRUD. Same X-API-Key auth as+ // /api/sandboxes; replaces the legacy CP-side PG routes (deleted in+ // the same PR as migration 041).+ if (path === "/api/secret-stores") {+ const caller = await authenticate(req, env);+ if (!caller) return json({ error: "missing or invalid API key" }, 401);+ if (req.method === "POST") return secretStores.createStore(req, env, caller);+ if (req.method === "GET") return secretStores.listStores(req, env, caller);+ return json({ error: "method not allowed" }, 405);+ }+ {+ // /api/secret-stores/:id, /api/secret-stores/:id/secrets, /:id/secrets/:name+ const m = path.match(/^\/api\/secret-stores\/([^/]+)(?:\/secrets(?:\/([^/]+))?)?$/);+ if (m) {+ const storeID = m[1];+ const entryName = m[2];+ const isEntriesCollection = path.endsWith("/secrets");+ const isEntry = !!entryName;+ const caller = await authenticate(req, env);+ if (!caller) return json({ error: "missing or invalid API key" }, 401);+ if (isEntry) {+ if (req.method === "PUT") return secretStores.setEntry(req, env, caller, storeID, entryName);+ if (req.method === "DELETE") return secretStores.deleteEntry(req, env, caller, storeID, entryName);+ return json({ error: "method not allowed" }, 405);+ }+ if (isEntriesCollection) {+ if (req.method === "GET") return secretStores.listEntries(req, env, caller, storeID);+ return json({ error: "method not allowed" }, 405);+ }+ if (req.method === "GET") return secretStores.getStore(req, env, caller, storeID);+ if (req.method === "PUT") return secretStores.updateStore(req, env, caller, storeID);+ if (req.method === "DELETE") return secretStores.deleteStore(req, env, caller, storeID);+ return json({ error: "method not allowed" }, 405);+ }+ }++ // Auth flow (browser).+ if (path === "/auth/login") { if (req.method === "GET") return authLogin(req, env); }+ if (path === "/auth/callback") { if (req.method === "GET") return authCallback(req, env); }+ if (path === "/auth/logout") { if (req.method === "POST") return authLogout(); }+ if (path === "/auth/refresh") { if (req.method === "POST") return authRefresh(req, env); }++ // Stripe webhook (test mode in app2, live in app).+ if (path === "/webhooks/stripe" && req.method === "POST") return stripeWebhook(req, env);++ // Dashboard API — everything under /api/dashboard/*. Edge-native handlers+ // back D1 reads/writes; sandbox-runtime calls proxy to the sandbox's cell.+ // Auth via the oc_session cookie minted at /auth/callback.+ if (path.startsWith("/api/dashboard")) {+ return handleDashboard(req, env, ctx, path);+ }+// /api/sandboxes and /api/sandboxes/:id[/...]if (path === "/api/sandboxes") {if (req.method === "POST") return createSandbox(req, env);@@ -447,14 +1132,28 @@ export default {const rest = m[2]; // undefined for /api/sandboxes/:id, "/exec/run" etc otherwiseif (!rest) {if (req.method === "GET") return getSandbox(req, env, id);- if (req.method === "DELETE") return redirectToCell(req, env, id, url); // delete runs on the cell+ if (req.method === "DELETE") {+ const caller = await authenticate(req, env);+ if (!caller) return json({ error: "missing or invalid API key" }, 401);+ return proxyToCellSDK(req, env, ctx, caller, id);+ }return json({ error: "method not allowed" }, 405);}- // Anything under /:id/* (exec, files, pty, hibernate, …) lives on the cell.- return redirectToCell(req, env, id, url);+ // Anything under /:id/* (exec, files, pty, hibernate, …) lives on the+ // cell — proxy with an edge-minted IdentityToken (the cell's existing+ // API-key middleware accepts that JWT shape) so we don't depend on the+ // SDK's api-key existing in cell PG.+ const caller = await authenticate(req, env);+ if (!caller) return json({ error: "missing or invalid API key" }, 401);+ return proxyToCellSDK(req, env, ctx, caller, id);}- // Not yet implemented: /auth/*, /webhooks/stripe, /internal/halt-list.- return new Response("not implemented", { status: 501 });+ // Anything not matched above is the dashboard SPA — delegate to the+ // assets binding. run_worker_first=true in wrangler.toml means CF runs+ // this Worker before checking assets, so we have to explicitly hand+ // requests off here. The assets binding's not_found_handling=+ // "single-page-application" serves index.html for client-side routes.+ if (env.ASSETS) return env.ASSETS.fetch(req);+ return new Response("not found", { status: 404 });},} satisfies ExportedHandler<Env>;diff --git a/cloudflare-workers/api-edge/src/secret_stores.ts b/cloudflare-workers/api-edge/src/secret_stores.tsnew file mode 100644index 00000000..6202f061--- /dev/null+++ b/cloudflare-workers/api-edge/src/secret_stores.ts@@ -0,0 +1,416 @@+// Edge-side secret stores — replaces the legacy per-cell PG-backed+// /api/secret-stores routes. Stores live in D1; entries are envelope-+// encrypted at the edge with SECRET_ENCRYPTION_KEY (Infisical /shared/,+// also distributed to every CP). The CP fetches encrypted blobs from the+// /internal/secret-stores/:id HMAC endpoint at sandbox-create time and+// decrypts inside the cell using internal/crypto.+//+// JSON shapes mirror internal/api/projects.go (camelCase) so the existing+// CLI/SDK and dashboard talk to the edge unchanged.++import { encryptSecret } from "./crypto";++export interface SecretStoresEnv {+ OPENCOMPUTER_DB: D1Database;+ SECRET_ENCRYPTION_KEY: string;+ EVENT_SECRET: string;+}++interface Caller {+ orgID: string;+ userID: string | null;+}++function json(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });+}++// ── store shape mapping ──────────────────────────────────────────────────++interface StoreRow {+ id: string;+ org_id: string;+ name: string;+ egress_allowlist: string;+ created_at: number;+ updated_at: number;+}++function storeToJSON(row: StoreRow): Record<string, unknown> {+ let allowlist: string[] = [];+ try {+ allowlist = JSON.parse(row.egress_allowlist) as string[];+ } catch {+ /* malformed JSON in D1 — degrade to empty list rather than 500 */+ }+ return {+ id: row.id,+ orgID: row.org_id,+ name: row.name,+ egressAllowlist: allowlist,+ // ISO strings (not unix seconds) — matches the legacy CP /api/secret-stores+ // shape that the Go CLI's struct expects. Storing seconds in D1 is fine;+ // serialize for the wire.+ createdAt: new Date(row.created_at * 1000).toISOString(),+ updatedAt: new Date(row.updated_at * 1000).toISOString(),+ };+}++// ── CRUD: stores ────────────────────────────────────────────────────────++export async function createStore(req: Request, env: SecretStoresEnv, caller: Caller): Promise<Response> {+ const body = (await req.json().catch(() => null)) as { name?: string; egressAllowlist?: string[] } | null;+ if (!body || !body.name) return json({ error: "name is required" }, 400);+ const allowlist = Array.isArray(body.egressAllowlist) ? body.egressAllowlist : [];++ const id = crypto.randomUUID();+ const now = Math.floor(Date.now() / 1000);+ try {+ await env.OPENCOMPUTER_DB.prepare(+ `INSERT INTO secret_stores (id, org_id, name, egress_allowlist, created_at, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?5)`,+ )+ .bind(id, caller.orgID, body.name, JSON.stringify(allowlist), now)+ .run();+ } catch (e) {+ // UNIQUE(org_id, name) collision → 409+ const msg = (e as Error).message ?? "";+ if (/UNIQUE/.test(msg)) return json({ error: "a store with that name already exists" }, 409);+ throw e;+ }+ return json(+ storeToJSON({ id, org_id: caller.orgID, name: body.name, egress_allowlist: JSON.stringify(allowlist), created_at: now, updated_at: now }),+ 201,+ );+}++export async function listStores(_req: Request, env: SecretStoresEnv, caller: Caller): Promise<Response> {+ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, org_id, name, egress_allowlist, created_at, updated_at+ FROM secret_stores WHERE org_id = ?1 ORDER BY name ASC`,+ )+ .bind(caller.orgID)+ .all<StoreRow>();+ return json((results ?? []).map(storeToJSON));+}++async function loadStore(env: SecretStoresEnv, orgID: string, id: string): Promise<StoreRow | null> {+ return env.OPENCOMPUTER_DB.prepare(+ `SELECT id, org_id, name, egress_allowlist, created_at, updated_at+ FROM secret_stores WHERE id = ?1 AND org_id = ?2`,+ )+ .bind(id, orgID)+ .first<StoreRow>();+}++export async function getStore(_req: Request, env: SecretStoresEnv, caller: Caller, id: string): Promise<Response> {+ const row = await loadStore(env, caller.orgID, id);+ if (!row) return json({ error: "secret store not found" }, 404);+ return json(storeToJSON(row));+}++export async function updateStore(req: Request, env: SecretStoresEnv, caller: Caller, id: string): Promise<Response> {+ const existing = await loadStore(env, caller.orgID, id);+ if (!existing) return json({ error: "secret store not found" }, 404);+ const body = (await req.json().catch(() => null)) as { name?: string | null; egressAllowlist?: string[] | null } | null;++ const name = typeof body?.name === "string" ? body.name : existing.name;+ const allowlist = Array.isArray(body?.egressAllowlist) ? body!.egressAllowlist! : (JSON.parse(existing.egress_allowlist) as string[]);+ const now = Math.floor(Date.now() / 1000);+ await env.OPENCOMPUTER_DB.prepare(+ `UPDATE secret_stores SET name = ?1, egress_allowlist = ?2, updated_at = ?3+ WHERE id = ?4 AND org_id = ?5`,+ )+ .bind(name, JSON.stringify(allowlist), now, id, caller.orgID)+ .run();+ return json(+ storeToJSON({ id, org_id: caller.orgID, name, egress_allowlist: JSON.stringify(allowlist), created_at: existing.created_at, updated_at: now }),+ );+}++export async function deleteStore(_req: Request, env: SecretStoresEnv, caller: Caller, id: string): Promise<Response> {+ const row = await loadStore(env, caller.orgID, id);+ if (!row) return json({ error: "secret store not found" }, 404);+ // Cascade-delete entries (D1 doesn't enforce FK CASCADE — do it explicitly).+ await env.OPENCOMPUTER_DB.batch([+ env.OPENCOMPUTER_DB.prepare(`DELETE FROM secret_store_entries WHERE store_id = ?1`).bind(id),+ env.OPENCOMPUTER_DB.prepare(`DELETE FROM secret_stores WHERE id = ?1 AND org_id = ?2`).bind(id, caller.orgID),+ ]);+ return new Response(null, { status: 204 });+}++// ── CRUD: entries ──────────────────────────────────────────────────────++interface EntryRow {+ id: string;+ store_id: string;+ name: string;+ encrypted_value: ArrayBuffer | Uint8Array;+ allowed_hosts: string;+ created_at: number;+ updated_at: number;+}++function entryToJSON(row: EntryRow, includeValue = false): Record<string, unknown> {+ let hosts: string[] = [];+ try {+ hosts = JSON.parse(row.allowed_hosts) as string[];+ } catch {+ /* malformed JSON */+ }+ const out: Record<string, unknown> = {+ name: row.name,+ allowedHosts: hosts,+ createdAt: new Date(row.created_at * 1000).toISOString(),+ updatedAt: new Date(row.updated_at * 1000).toISOString(),+ };+ if (includeValue) {+ const bytes = row.encrypted_value instanceof Uint8Array ? row.encrypted_value : new Uint8Array(row.encrypted_value);+ out.encryptedValueB64 = btoa(String.fromCharCode(...bytes));+ }+ return out;+}++export async function setEntry(+ req: Request,+ env: SecretStoresEnv,+ caller: Caller,+ storeID: string,+ name: string,+): Promise<Response> {+ if (!name) return json({ error: "secret name required" }, 400);+ const store = await loadStore(env, caller.orgID, storeID);+ if (!store) return json({ error: "secret store not found" }, 404);++ const body = (await req.json().catch(() => null)) as { value?: string; allowedHosts?: string[] } | null;+ if (!body || typeof body.value !== "string" || body.value === "") {+ return json({ error: 'secret value required: {"value": "...", "allowedHosts": [...]}' }, 400);+ }+ const hosts = Array.isArray(body.allowedHosts) ? body.allowedHosts.map((h) => h.trim()) : [];+ if (hosts.some((h) => h === "")) return json({ error: "allowedHosts entries cannot be empty" }, 400);++ const encrypted = await encryptSecret(env.SECRET_ENCRYPTION_KEY, body.value);+ const now = Math.floor(Date.now() / 1000);+ const id = crypto.randomUUID();+ // UPSERT on (store_id, name).+ await env.OPENCOMPUTER_DB.prepare(+ `INSERT INTO secret_store_entries (id, store_id, name, encrypted_value, allowed_hosts, created_at, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6)+ ON CONFLICT(store_id, name) DO UPDATE SET+ encrypted_value = excluded.encrypted_value,+ allowed_hosts = excluded.allowed_hosts,+ updated_at = excluded.updated_at`,+ )+ .bind(id, storeID, name, encrypted, JSON.stringify(hosts), now)+ .run();++ // Fan the new value out to running sandboxes via /internal/secret-refresh+ // on every active cell. Each CP checks its local sandbox_sessions for the+ // store-binding column and pushes the new value to the right workers over+ // gRPC, so live sandboxes don't need a restart to pick up the change.+ // Wire format: encrypted blob over HMAC; CP decrypts with its copy of the+ // shared SECRET_ENCRYPTION_KEY so plaintext never crosses the cell boundary.+ const fanout = await fanoutSecretRefresh(env, storeID, name, encrypted);+ return json({ name, status: "set", refreshed: fanout.refreshed, cellsContacted: fanout.cells, failures: fanout.failures });+}++// fanoutSecretRefresh queries D1 for active cells, signs an HMAC POST per+// cell with the encrypted blob, and aggregates the per-cell refresh counts.+// Total time-bounded: a slow cell can't stall the user's PUT past ~12s.+async function fanoutSecretRefresh(+ env: SecretStoresEnv,+ storeID: string,+ name: string,+ encryptedValue: Uint8Array,+): Promise<{ refreshed: number; cells: number; failures: string[] }> {+ const { results: cells } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT cell_id, base_url FROM cells WHERE status = 'active'`,+ ).all<{ cell_id: string; base_url: string }>();+ const active = cells ?? [];+ if (active.length === 0) return { refreshed: 0, cells: 0, failures: [] };++ const encryptedB64 = btoa(String.fromCharCode(...encryptedValue));+ const body = JSON.stringify({ storeId: storeID, name, encryptedValueB64: encryptedB64 });+ const ts = Math.floor(Date.now() / 1000).toString();++ // Sign once — every cell shares EVENT_SECRET so the same signature works+ // across the fan-out. Body is part of the signed payload to prevent body+ // swap, matching the AdminAuth scheme on the CP side ("{ts}.{body}").+ const sig = await hmacBody(env.EVENT_SECRET, ts, body);++ // Per-cell timeout — bounded so one slow cell doesn't block the others.+ // The CP-side fanoutSecretRefresh already has its own 15s ceiling against+ // worker gRPC calls; this is the outer bound the user's PUT waits on.+ const perCellTimeoutMs = 12_000;++ const settled = await Promise.allSettled(+ active.map(async (c) => {+ const ctrl = new AbortController();+ const t = setTimeout(() => ctrl.abort(), perCellTimeoutMs);+ try {+ const resp = await fetch(c.base_url.replace(/\/$/, "") + "/internal/secret-refresh", {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "X-Timestamp": ts,+ "X-Signature": sig,+ },+ body,+ signal: ctrl.signal,+ });+ const text = await resp.text();+ if (resp.status !== 200) {+ return { cell: c.cell_id, refreshed: 0, error: `status ${resp.status}: ${text.slice(0, 200)}` };+ }+ const parsed = JSON.parse(text) as { refreshed?: number; failures?: string[] };+ return { cell: c.cell_id, refreshed: parsed.refreshed ?? 0, error: null as string | null };+ } catch (e) {+ return { cell: c.cell_id, refreshed: 0, error: (e as Error).message };+ } finally {+ clearTimeout(t);+ }+ }),+ );++ let totalRefreshed = 0;+ const failures: string[] = [];+ for (const s of settled) {+ if (s.status === "fulfilled") {+ totalRefreshed += s.value.refreshed;+ if (s.value.error) failures.push(`${s.value.cell}: ${s.value.error}`);+ } else {+ failures.push(`unknown cell: ${s.reason}`);+ }+ }+ return { refreshed: totalRefreshed, cells: active.length, failures };+}++// hmacBody returns hex(HMAC-SHA256(secret, ts + "." + body)) — matches the+// CP-side controlplane.AdminAuth verifier so /internal/secret-refresh+// accepts our signature.+async function hmacBody(secret: string, ts: string, body: string): Promise<string> {+ const key = await crypto.subtle.importKey(+ "raw",+ new TextEncoder().encode(secret),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ );+ const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${ts}.${body}`));+ return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");+}++export async function deleteEntry(+ _req: Request,+ env: SecretStoresEnv,+ caller: Caller,+ storeID: string,+ name: string,+): Promise<Response> {+ const store = await loadStore(env, caller.orgID, storeID);+ if (!store) return json({ error: "secret store not found" }, 404);+ const res = await env.OPENCOMPUTER_DB.prepare(+ `DELETE FROM secret_store_entries WHERE store_id = ?1 AND name = ?2`,+ )+ .bind(storeID, name)+ .run();+ if ((res.meta?.changes ?? 0) === 0) return json({ error: "secret entry not found" }, 404);+ return new Response(null, { status: 204 });+}++export async function listEntries(+ _req: Request,+ env: SecretStoresEnv,+ caller: Caller,+ storeID: string,+): Promise<Response> {+ const store = await loadStore(env, caller.orgID, storeID);+ if (!store) return json({ error: "secret store not found" }, 404);+ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, store_id, name, encrypted_value, allowed_hosts, created_at, updated_at+ FROM secret_store_entries WHERE store_id = ?1 ORDER BY name ASC`,+ )+ .bind(storeID)+ .all<EntryRow>();+ // Never return plaintext or ciphertext on the user-facing route — names only.+ return json((results ?? []).map((r) => entryToJSON(r, false)));+}++// ── /internal/secret-stores/:id (HMAC, called by CP at sandbox-create) ──++// HMAC scheme matches /internal/halt-list: "{X-Timestamp}.{path-with-query}"+// signed with EVENT_SECRET (shared between edge + every CP), SHA-256 hex.+async function hmacHex(secret: string, data: string): Promise<string> {+ const key = await crypto.subtle.importKey(+ "raw",+ new TextEncoder().encode(secret),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ );+ const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(data));+ return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");+}++function constantTimeEqual(a: string, b: string): boolean {+ if (a.length !== b.length) return false;+ let diff = 0;+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);+ return diff === 0;+}++async function verifyHMAC(req: Request, env: SecretStoresEnv): Promise<boolean> {+ const ts = req.headers.get("X-Timestamp") ?? "";+ const sig = req.headers.get("X-Signature") ?? "";+ if (!ts || !sig) return false;+ const tsNum = Number.parseInt(ts, 10);+ if (!Number.isFinite(tsNum)) return false;+ if (Math.abs(Math.floor(Date.now() / 1000) - tsNum) > 5 * 60) return false;+ const url = new URL(req.url);+ const expected = await hmacHex(env.EVENT_SECRET, `${ts}.${url.pathname}${url.search}`);+ return constantTimeEqual(expected, sig);+}++async function bundleStore(env: SecretStoresEnv, store: StoreRow): Promise<Response> {+ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, store_id, name, encrypted_value, allowed_hosts, created_at, updated_at+ FROM secret_store_entries WHERE store_id = ?1`,+ )+ .bind(store.id)+ .all<EntryRow>();+ return json({+ store: storeToJSON(store),+ entries: (results ?? []).map((r) => entryToJSON(r, true)),+ });+}++export async function internalGetStore(req: Request, env: SecretStoresEnv, storeID: string): Promise<Response> {+ if (!(await verifyHMAC(req, env))) return json({ error: "signature mismatch" }, 401);+ // No org scoping — CP already validated the cap-token whose claims pinned org_id.+ const store = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, org_id, name, egress_allowlist, created_at, updated_at FROM secret_stores WHERE id = ?1`,+ )+ .bind(storeID)+ .first<StoreRow>();+ if (!store) return json({ error: "secret store not found" }, 404);+ return bundleStore(env, store);+}++// Lookup by (org_id, name) — what CP's resolveSecretStoreInto calls with+// the user-supplied cfg.SecretStore string at sandbox-create time. Same+// HMAC scheme as internalGetStore. Returns 404 if no store matches.+export async function internalGetStoreByName(req: Request, env: SecretStoresEnv): Promise<Response> {+ if (!(await verifyHMAC(req, env))) return json({ error: "signature mismatch" }, 401);+ const url = new URL(req.url);+ const orgID = url.searchParams.get("org_id") ?? "";+ const name = url.searchParams.get("name") ?? "";+ if (!orgID || !name) return json({ error: "org_id and name are required" }, 400);+ const store = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, org_id, name, egress_allowlist, created_at, updated_at+ FROM secret_stores WHERE org_id = ?1 AND name = ?2`,+ )+ .bind(orgID, name)+ .first<StoreRow>();+ if (!store) return json({ error: "secret store not found" }, 404);+ return bundleStore(env, store);+}diff --git a/cloudflare-workers/api-edge/src/templates.ts b/cloudflare-workers/api-edge/src/templates.tsnew file mode 100644index 00000000..80455c6b--- /dev/null+++ b/cloudflare-workers/api-edge/src/templates.ts@@ -0,0 +1,223 @@+// Edge-side templates — HMAC fetch + register endpoints called by the CP.+//+// Templates have no user-facing CRUD today (no /api/templates routes); they+// are created via the CP's "save sandbox as template" snapshot flow and+// looked up by name at sandbox-create time. After migration 041 strips the+// per-cell `templates` table, both paths route through these /internal/*+// HMAC endpoints so D1 becomes the single source of truth.++export interface TemplatesEnv {+ OPENCOMPUTER_DB: D1Database;+ EVENT_SECRET: string;+}++function json(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });+}++interface TemplateRow {+ id: string;+ org_id: string | null;+ name: string;+ tag: string;+ template_type: string;+ image_ref: string | null;+ rootfs_s3_key: string | null;+ workspace_s3_key: string | null;+ dockerfile: string | null;+ is_public: number;+ status: string;+ cells_available: string;+ created_at: number;+}++// Mirrors db.Template (Go) field-by-field, camelCase JSON keys to match+// existing dashboard/SDK responses.+function templateToJSON(row: TemplateRow): Record<string, unknown> {+ let cells: string[] = [];+ try {+ cells = JSON.parse(row.cells_available) as string[];+ } catch {+ /* malformed JSON — degrade to empty list */+ }+ return {+ id: row.id,+ orgID: row.org_id,+ name: row.name,+ tag: row.tag,+ templateType: row.template_type,+ imageRef: row.image_ref,+ rootfsS3Key: row.rootfs_s3_key,+ workspaceS3Key: row.workspace_s3_key,+ dockerfile: row.dockerfile,+ isPublic: !!row.is_public,+ status: row.status,+ cellsAvailable: cells,+ createdAt: row.created_at,+ };+}++// ── HMAC (matches secret_stores.ts) ─────────────────────────────────────++async function hmacHex(secret: string, data: string): Promise<string> {+ const key = await crypto.subtle.importKey(+ "raw",+ new TextEncoder().encode(secret),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ );+ const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(data));+ return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");+}++function constantTimeEqual(a: string, b: string): boolean {+ if (a.length !== b.length) return false;+ let diff = 0;+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);+ return diff === 0;+}++async function verifyHMAC(req: Request, env: TemplatesEnv, bodyText?: string): Promise<boolean> {+ const ts = req.headers.get("X-Timestamp") ?? "";+ const sig = req.headers.get("X-Signature") ?? "";+ if (!ts || !sig) return false;+ const tsNum = Number.parseInt(ts, 10);+ if (!Number.isFinite(tsNum)) return false;+ if (Math.abs(Math.floor(Date.now() / 1000) - tsNum) > 5 * 60) return false;+ const url = new URL(req.url);+ // POST/PUT include the body in the signed payload to prevent body-swap+ // attacks; GET signs path+query only.+ const data = bodyText !== undefined ? `${ts}.${url.pathname}${url.search}.${bodyText}` : `${ts}.${url.pathname}${url.search}`;+ const expected = await hmacHex(env.EVENT_SECRET, data);+ return constantTimeEqual(expected, sig);+}++// ── /internal/templates/by-name ─────────────────────────────────────────++// Org-scoped lookup with public fallback — mirrors db.Store.GetTemplateByName.+// Sandbox-create on the CP calls this with cfg.Template (the user-supplied+// name) and the cap-token's claims.OrgID. If the org has a private template+// with that name it wins; otherwise we fall back to the public catalog.+export async function internalGetByName(req: Request, env: TemplatesEnv): Promise<Response> {+ if (!(await verifyHMAC(req, env))) return json({ error: "signature mismatch" }, 401);+ const url = new URL(req.url);+ const orgID = url.searchParams.get("org_id") ?? "";+ const name = url.searchParams.get("name") ?? "";+ if (!name) return json({ error: "name is required" }, 400);++ // Private (org-scoped) first.+ if (orgID) {+ const row = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, org_id, name, tag, template_type, image_ref, rootfs_s3_key, workspace_s3_key,+ dockerfile, is_public, status, cells_available, created_at+ FROM templates+ WHERE org_id = ?1 AND name = ?2+ ORDER BY created_at DESC LIMIT 1`,+ )+ .bind(orgID, name)+ .first<TemplateRow>();+ if (row) return json(templateToJSON(row));+ }+ // Public fallback.+ const pub = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, org_id, name, tag, template_type, image_ref, rootfs_s3_key, workspace_s3_key,+ dockerfile, is_public, status, cells_available, created_at+ FROM templates+ WHERE is_public = 1 AND name = ?1+ ORDER BY created_at DESC LIMIT 1`,+ )+ .bind(name)+ .first<TemplateRow>();+ if (!pub) return json({ error: "template not found" }, 404);+ return json(templateToJSON(pub));+}++// ── /internal/templates (POST) — register a new template in D1 ─────────++// CP's "save sandbox as template" flow uploads the rootfs/workspace to Tigris+// (already implemented via internal/blobstore.Store), then calls this to+// register the metadata row. Replaces the local PG INSERT at+// internal/db/store.go:1750.+interface RegisterReq {+ id?: string;+ orgID?: string | null;+ name?: string;+ tag?: string;+ templateType?: string;+ imageRef?: string | null;+ rootfsS3Key?: string | null;+ workspaceS3Key?: string | null;+ dockerfile?: string | null;+ isPublic?: boolean;+ status?: string;+ cellsAvailable?: string[];+ createdBySandboxID?: string | null;+}++export async function internalRegister(req: Request, env: TemplatesEnv): Promise<Response> {+ // Read body once for both verification and parsing — POST signs payload too.+ const bodyText = await req.text();+ if (!(await verifyHMAC(req, env, bodyText))) return json({ error: "signature mismatch" }, 401);+ let body: RegisterReq;+ try {+ body = JSON.parse(bodyText) as RegisterReq;+ } catch {+ return json({ error: "invalid JSON" }, 400);+ }+ if (!body.name) return json({ error: "name is required" }, 400);++ const id = body.id ?? crypto.randomUUID();+ const tag = body.tag ?? "latest";+ const cellsJSON = JSON.stringify(body.cellsAvailable ?? []);+ const now = Math.floor(Date.now() / 1000);++ try {+ await env.OPENCOMPUTER_DB.prepare(+ `INSERT INTO templates+ (id, org_id, name, tag, template_type, image_ref, rootfs_s3_key, workspace_s3_key,+ dockerfile, is_public, status, cells_available, created_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)`,+ )+ .bind(+ id,+ body.orgID ?? null,+ body.name,+ tag,+ body.templateType ?? "dockerfile",+ body.imageRef ?? null,+ body.rootfsS3Key ?? null,+ body.workspaceS3Key ?? null,+ body.dockerfile ?? null,+ body.isPublic ? 1 : 0,+ body.status ?? "ready",+ cellsJSON,+ now,+ )+ .run();+ } catch (e) {+ const msg = (e as Error).message ?? "";+ if (/UNIQUE/.test(msg)) return json({ error: "template (org, name, tag) already exists" }, 409);+ throw e;+ }+ return json({ id, name: body.name, tag, status: body.status ?? "ready" }, 201);+}++// Status update — CP flips status='ready' once a snapshot finishes uploading.+// Matches db.Store.UpdateTemplateStatus.+export async function internalUpdateStatus(req: Request, env: TemplatesEnv, id: string): Promise<Response> {+ const bodyText = await req.text();+ if (!(await verifyHMAC(req, env, bodyText))) return json({ error: "signature mismatch" }, 401);+ let body: { status?: string };+ try {+ body = JSON.parse(bodyText);+ } catch {+ return json({ error: "invalid JSON" }, 400);+ }+ if (!body.status) return json({ error: "status is required" }, 400);+ const res = await env.OPENCOMPUTER_DB.prepare(`UPDATE templates SET status = ?1 WHERE id = ?2`)+ .bind(body.status, id)+ .run();+ if ((res.meta?.changes ?? 0) === 0) return json({ error: "template not found" }, 404);+ return json({ id, status: body.status });+}diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.tomlindex 975bbb9d..f5d32907 100644--- a/cloudflare-workers/api-edge/wrangler.toml+++ b/cloudflare-workers/api-edge/wrangler.toml@@ -15,30 +15,40 @@ compatibility_date = "2026-04-28"compatibility_flags = ["nodejs_compat"]account_id = "1241f114453e32d292197e3fb36210b2"-# Routes (production binding — left off until cert strategy is settled):+# Preview URL routing. Sandboxes expose ports via stable hostnames of the form+# sb-{sandboxID}-p{port}.sb.opensandbox.ai+# regardless of which cell the sandbox is on; the Worker resolves+# sandboxes_index.cell_id at request time and forwards via that cell's CF+# Tunnel, so cell migration is invisible to the user.#-# Sandbox preview URLs match by hostname (sb-{id}-p{port}.<host>) in Worker-# code regardless of how the request reaches us, so the smoke test works-# today via Host-header override against the workers.dev URL. For real-# public traffic, we need a route binding + matching wildcard DNS + cert.+# Wildcards in CF Worker routes must be at the start of the hostname, so+# `sb-*.opensandbox.ai/*` is invalid. We use `*.sb.opensandbox.ai/*` instead:+# the `.sb.` middle label creates a namespace that ONLY preview URLs use,+# isolating this rule from cp-*.opensandbox.ai (tunnels), app2.opensandbox.ai+# (dashboard), and events-app2.opensandbox.ai (events-ingest).#-# CF Workers routes only allow `*` at the START of the hostname, so-# `sb-*.opensandbox.ai/*` is invalid. Options for production:-# (a) "*.opensandbox.ai/*" with code that 404s non-sb-prefix hosts —-# would also intercept cp-dev2.opensandbox.ai (the tunnels), which-# breaks the edge→cell path. Don't do this.-# (b) Dedicated subdomain "*.sb.opensandbox.ai/*" — clean separation-# from cp-*, app, events. But two-level wildcard isn't covered by-# Cloudflare Universal SSL — needs Advanced Certificate Manager-# (~$10/mo) OR a self-uploaded wildcard cert.-# (c) Separate zone for previews (e.g. opensandbox.run) — clean but-# requires owning + provisioning another domain.-#-# Recommended end state: option (b) with Advanced Cert Manager. Until then-# preview URLs work through code, not DNS — fine for dev validation.-# routes = [-# { pattern = "*.sb.opensandbox.ai/*", zone_name = "opensandbox.ai" },-# ]+# Two-level wildcards aren't covered by CF Universal SSL — needs Advanced+# Certificate Manager ($10/mo, RSA-2048 via Google Trust Services). Cert+# ordered 2026-05-18 for *.sb.opensandbox.ai + sb.opensandbox.ai.+routes = [+ { pattern = "*.sb.opensandbox.ai/*", zone_name = "opensandbox.ai" },+]++# Static assets — the dashboard SPA. Built from `web/` by the deploy script+# (web/dist/ → cloudflare-workers/api-edge/assets/). The Worker handles+# explicit API/auth/webhook paths; anything else falls through to the SPA's+# index.html so client-side routing works.+[assets]+directory = "./assets"+binding = "ASSETS"+not_found_handling = "single-page-application"+# Run Worker first for EVERY request. The Worker dispatches by hostname+# (e.g. sb-*-p*.sb.opensandbox.ai → preview URL forwarder) AND by path+# (/api/*, /auth/*, /internal/*), then explicitly delegates to env.ASSETS+# at the bottom for anything unhandled — typically the dashboard SPA. Without+# this, the assets binding short-circuits hostname-based dispatch and returns+# index.html for / on every hostname, including preview URLs.+run_worker_first = true[[d1_databases]]binding = "OPENCOMPUTER_DB"@@ -74,3 +84,9 @@ WORKER_ENV = "dev"# the D1 `cells` table (see schema.sql + scripts/seed_dev_xcell.sh).# Cross-cell testbed: dev2 (Azure westus2) + dev3 (AWS us-east-1).CELLS = "azure-us-west-2-b,aws-us-east-1-a"++# Ship console output + exceptions to opensandbox-log-tail, which forwards+# to Axiom dataset cf-dev. Keeps CF Worker logs durable in the same store+# as the VM journald stream so we can cross-correlate edge ↔ cell.+[[tail_consumers]]+service = "opensandbox-log-tail"diff --git a/cloudflare-workers/events-ingest/src/index.ts b/cloudflare-workers/events-ingest/src/index.tsindex 1ed6ca9a..cbda36ea 100644--- a/cloudflare-workers/events-ingest/src/index.ts+++ b/cloudflare-workers/events-ingest/src/index.ts@@ -3,18 +3,17 @@// Pipeline:// 1. Verify HMAC signature + X-Timestamp freshness (±5 min)// 2. Parse batch (JSON array of SandboxEvent envelopes)-// 3. KV dedup via seen:{event_id}-// 4. D1 batch insert into events table-// 5. R2 archive raw batch at raw/{cell_id}/{yyyy-mm-dd}/{batch_id}.json.gz-// 6. KV put seen:{event_id} TTL 24h for each accepted event-// 7. Return 202 {accepted, deduped}-//-// Stage 1 stops here. The DO /debit fan-out for free-tier usage_tick events-// is added in Stage 2.+// 3. D1 batch insert into events table (events.id PRIMARY KEY ++// ON CONFLICT DO NOTHING is the dedup — KV was redundant and the+// get() volume blew the daily KV quota, taking down ingest)+// 4. R2 archive raw batch at raw/{cell_id}/{yyyy-mm-dd}/{batch_id}.json.gz+// 5. DO /debit fan-out for free-tier usage_tick events (out-of-band via+// waitUntil — never blocks the ack so CP forwarder isn't stalled by+// cross-DO traffic latency)+// 6. Return 202 {accepted}export interface Env {OPENCOMPUTER_DB: D1Database;- SESSIONS_KV: KVNamespace;EVENTS_ARCHIVE: R2Bucket;CREDIT_ACCOUNT: DurableObjectNamespace;EVENT_SECRET: string;@@ -35,10 +34,9 @@ interface SandboxEventEnvelope {}const SIGNATURE_WINDOW_SEC = 5 * 60;-const KV_DEDUP_TTL_SEC = 24 * 60 * 60;export default {- async fetch(req: Request, env: Env): Promise<Response> {+ async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> {const url = new URL(req.url);if (url.pathname === "/health") {@@ -85,31 +83,15 @@ export default {return jsonResponse({ error: "invalid JSON" }, 400);}if (envelopes.length === 0) {- return jsonResponse({ accepted: 0, deduped: 0 }, 202);- }-- // KV dedup — but skip it for cell_capacity events. Those are idempotent- // UPDATEs (writing the same values twice has no effect), and they're high- // volume (one per cell per ~30s), so deduping them just burns KV reads.- // Sandbox lifecycle events still get the dedup because they're sometimes- // not idempotent at the downstream consumer (e.g. DO /debit calls).- const needsDedup = envelopes.map((e) => e.type !== "cell_capacity");- const seenChecks = await Promise.all(- envelopes.map((e, i) => (needsDedup[i] ? env.SESSIONS_KV.get(`seen:${e.id}`) : Promise.resolve(null))),- );- const fresh: SandboxEventEnvelope[] = [];- let deduped = 0;- for (let i = 0; i < envelopes.length; i++) {- if (seenChecks[i]) {- deduped++;- } else {- fresh.push(envelopes[i]);- }+ return jsonResponse({ accepted: 0 }, 202);}- if (fresh.length === 0) {- return jsonResponse({ accepted: 0, deduped }, 202);- }+ // Dedup is handled by D1: events.id is PRIMARY KEY and the INSERT uses+ // ON CONFLICT(id) DO NOTHING, so replays are silently dropped at the+ // storage layer. We used to also gate behind a KV `seen:{id}` lookup,+ // but the per-request get() spent ~95% of the workers-KV daily cap and+ // ended up failing every single ingest call. Trust D1.+ const fresh = envelopes;// D1 batch insert. 11 columns: id, cell_id, type, org_id, sandbox_id,// user_id (null for now — not in envelope), worker_id, ts (unix ms), payload.@@ -147,6 +129,32 @@ export default {WHERE cell_id = ?5AND (capacity_updated_at IS NULL OR capacity_updated_at < ?4)`,);++ // Sandbox lifecycle events: keep sandboxes_index in sync with cell-side+ // state changes so the dashboard's cross-cell view is accurate without a+ // separate reconciler. monotonic WHERE clause guards against out-of-order+ // delivery (XAUTOCLAIM replays, network retries) — last_event_at can only+ // move forward.+ //+ // - stopped: terminal; stamp stopped_at.+ // - hibernated: not terminal; stopped_at stays null so wake works.+ // - running: create/wake; clear stopped_at to handle the+ // hibernated → running flip after a wake.+ const lifecycleStopped = env.OPENCOMPUTER_DB.prepare(+ `UPDATE sandboxes_index+ SET status = 'stopped', stopped_at = ?1, last_event_at = ?1+ WHERE id = ?2 AND (last_event_at IS NULL OR last_event_at < ?1)`,+ );+ const lifecycleHibernated = env.OPENCOMPUTER_DB.prepare(+ `UPDATE sandboxes_index+ SET status = 'hibernated', last_event_at = ?1+ WHERE id = ?2 AND (last_event_at IS NULL OR last_event_at < ?1)`,+ );+ const lifecycleRunning = env.OPENCOMPUTER_DB.prepare(+ `UPDATE sandboxes_index+ SET status = 'running', stopped_at = NULL, last_event_at = ?1+ WHERE id = ?2 AND (last_event_at IS NULL OR last_event_at < ?1)`,+ );const capacityBatches = fresh.filter((e) => e.type === "cell_capacity").map((e) => {@@ -166,8 +174,20 @@ export default {);});+ const lifecycleBatches = fresh+ .filter((e) => e.sandbox_id && (e.type === "stopped" || e.type === "hibernated" || e.type === "running" || e.type === "woke" || e.type === "created"))+ .map((e) => {+ const tsSec = Math.floor((Date.parse(e.timestamp) || Date.now()) / 1000);+ if (e.type === "stopped") return lifecycleStopped.bind(tsSec, e.sandbox_id);+ if (e.type === "hibernated") return lifecycleHibernated.bind(tsSec, e.sandbox_id);+ // "running", "woke", "created" all set the row to running (created+ // is handled by the edge on POST, but accept here for redundancy+ // in case of replay against a future cell-only create path).+ return lifecycleRunning.bind(tsSec, e.sandbox_id);+ });+try {- await env.OPENCOMPUTER_DB.batch([...batches, ...capacityBatches]);+ await env.OPENCOMPUTER_DB.batch([...batches, ...capacityBatches, ...lifecycleBatches]);} catch (err) {// Database errors are retryable — return 5xx so the CP forwarder// leaves the batch in the PEL.@@ -189,19 +209,53 @@ export default {console.error("events-ingest: R2 archive failed (continuing)", err);}- // KV dedup markers (24h TTL) — fire and forget per event. Skip cell_capacity- // events for the same reason we skipped them on the read path: idempotent,- // high volume, KV writes are quota-bound.- await Promise.all(- fresh- .filter((e) => e.type !== "cell_capacity")- .map((e) => env.SESSIONS_KV.put(`seen:${e.id}`, "1", { expirationTtl: KV_DEDUP_TTL_SEC })),- );+ // DO /debit fan-out — for free-tier usage_tick events only. Each event+ // routes to a per-org DO instance; we hand off to waitUntil so cross-DO+ // latency never holds the CP forwarder's ack.+ //+ // Pro orgs are filtered here (cheap) rather than in the DO so we avoid+ // even allocating the DO stub for orgs that don't need debit accounting.+ // Events without plan="free" are silently skipped — the CP forwarder+ // populates `plan` from PG at emit time.+ const debitTargets = fresh.filter((e) => e.type === "usage_tick" && e.plan === "free" && e.org_id);+ if (debitTargets.length > 0) {+ ctx.waitUntil(fanoutDebits(env, debitTargets));+ }- return jsonResponse({ accepted: fresh.length, deduped }, 202);+ return jsonResponse({ accepted: fresh.length }, 202);},} satisfies ExportedHandler<Env>;+// fanoutDebits dispatches one /debit per usage_tick event to its org's DO.+// Per-event errors are swallowed — DO is idempotent on event_id (LRU dedup)+// so the CP forwarder's automatic retry covers transient DO unavailability+// without risking double-debit.+async function fanoutDebits(env: Env, events: SandboxEventEnvelope[]): Promise<void> {+ await Promise.all(+ events.map(async (e) => {+ try {+ const id = env.CREDIT_ACCOUNT.idFromName(e.org_id!);+ const stub = env.CREDIT_ACCOUNT.get(id);+ const payload = (e.payload ?? {}) as { cost_cents?: number };+ const body = JSON.stringify({+ event_id: e.id,+ amount_cents: payload.cost_cents ?? 0,+ });+ const resp = await stub.fetch(`https://do/debit?org_id=${encodeURIComponent(e.org_id!)}`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body,+ });+ if (resp.status >= 400) {+ console.error(`events-ingest: DO /debit ${e.org_id} returned ${resp.status} (event ${e.id})`);+ }+ } catch (err) {+ console.error(`events-ingest: DO /debit ${e.org_id} threw`, err);+ }+ }),+ );+}+function jsonResponse(body: unknown, status = 200): Response {return new Response(JSON.stringify(body), {status,@@ -230,8 +284,14 @@ function constantTimeEqual(a: string, b: string): boolean {return diff === 0;}-async function gzip(input: string): Promise<ReadableStream<Uint8Array>> {- const stream = new Response(input).body;- if (!stream) throw new Error("body stream null");- return stream.pipeThrough(new CompressionStream("gzip"));+// Returns gzipped bytes as a Uint8Array. R2 requires a known length on+// the body — a raw pipeThrough(CompressionStream) ReadableStream has+// unknown length and trips "Provided readable stream must have a known+// length". Buffering into a Uint8Array gives R2 a length without a+// streaming primitive.+async function gzip(input: string): Promise<Uint8Array> {+ const body = new Response(input).body;+ if (!body) throw new Error("body stream null");+ const compressed = body.pipeThrough(new CompressionStream("gzip"));+ return new Uint8Array(await new Response(compressed).arrayBuffer());}diff --git a/cloudflare-workers/events-ingest/wrangler.toml b/cloudflare-workers/events-ingest/wrangler.tomlindex de2cb37d..494a965e 100644--- a/cloudflare-workers/events-ingest/wrangler.toml+++ b/cloudflare-workers/events-ingest/wrangler.toml@@ -1,18 +1,18 @@# events-ingest Worker — receives HMAC-signed event batches from regional CPs.## Routes:-# POST /ingest — receives batches, dedups via KV, inserts into D1, archives to R2,+# POST /ingest — receives batches, inserts into D1, archives to R2,# fan-outs DO /debit calls for free-tier usage_tick events.## Pipeline inside /ingest:# 1. Verify HMAC signature + X-Timestamp freshness (±5 min)# 2. Parse batch-# 3. For each event: skip if KV seen:{event_id}, else accumulate-# 4. D1.batch([...]) atomic insert into events table-# 5. Promise.all DO /debit for free-tier usage_tick events-# 6. R2 put gzipped raw batch at raw/{cell_id}/{yyyy-mm-dd}/{batch_id}.json.gz-# 7. KV put seen:{event_id} TTL 24h for each successful event-# 8. Return 202 {accepted, deduped}+# 3. D1.batch([...]) insert into events table — id is PRIMARY KEY ++# ON CONFLICT DO NOTHING is the dedup (KV path was redundant and the+# daily get() quota blew up under load)+# 4. Promise.all DO /debit for free-tier usage_tick events+# 5. R2 put gzipped raw batch at raw/{cell_id}/{yyyy-mm-dd}/{batch_id}.json.gz+# 6. Return 202 {accepted}name = "opensandbox-events-ingest-dev"main = "src/index.ts"@@ -28,10 +28,6 @@ binding = "OPENCOMPUTER_DB"database_name = "opencomputer-dev"database_id = "f9e534bf-a9f3-4b30-81cd-f9eb9087e96d"-[[kv_namespaces]]-binding = "SESSIONS_KV"-id = "694f22abd551461da4ad99839f161b2f"-[[r2_buckets]]binding = "EVENTS_ARCHIVE"bucket_name = "events-archive-dev"@@ -49,3 +45,7 @@ script_name = "opensandbox-edge-dev"[vars]WORKER_ENV = "dev"++# Ship console output + exceptions to opensandbox-log-tail (Axiom dataset cf-dev).+[[tail_consumers]]+service = "opensandbox-log-tail"diff --git a/cloudflare-workers/log-tail/src/index.ts b/cloudflare-workers/log-tail/src/index.tsnew file mode 100644index 00000000..6b1e1681--- /dev/null+++ b/cloudflare-workers/log-tail/src/index.ts@@ -0,0 +1,137 @@+// Tail Worker — subscribes to console output and exception traces from+// other Workers in this account and POSTs them as JSON events to Axiom.+//+// Wire it up by adding to each producer Worker's wrangler.toml:+// [[tail_consumers]]+// service = "opensandbox-log-tail"+//+// Records are shaped to match the structure the cell/worker Go services+// already emit (level, msg, service, ...) so the dataset stays one schema+// regardless of producer.++interface Env {+ AXIOM_HOST: string;+ AXIOM_DATASET: string;+ AXIOM_TOKEN: string;+}++interface TraceLog {+ timestamp: number;+ level: "log" | "info" | "warn" | "error" | "debug";+ message: unknown[];+}++interface TraceException {+ timestamp: number;+ name: string;+ message: string;+ stack?: string;+}++interface TraceItem {+ scriptName: string;+ outcome: "ok" | "exception" | "exceededCpu" | "exceededMemory" | "canceled" | "unknown";+ eventTimestamp?: number;+ event?: {+ request?: { url?: string; method?: string };+ response?: { status?: number };+ cron?: string;+ [k: string]: unknown;+ };+ logs: TraceLog[];+ exceptions: TraceException[];+ scriptVersion?: { id?: string };+}++function fmtMessage(parts: unknown[]): string {+ return parts+ .map((p) => (typeof p === "string" ? p : safeStringify(p)))+ .join(" ");+}++function safeStringify(v: unknown): string {+ try { return JSON.stringify(v); }+ catch { return String(v); }+}++// Map CF console level → Axiom-friendly level string matching what our Go+// slog handler emits ("INFO", "WARN", "ERROR", "DEBUG").+function level(l: TraceLog["level"]): string {+ switch (l) {+ case "error": return "ERROR";+ case "warn": return "WARN";+ case "debug": return "DEBUG";+ default: return "INFO";+ }+}++export default {+ async tail(items: TraceItem[], env: Env, _ctx: ExecutionContext): Promise<void> {+ const records: Record<string, unknown>[] = [];++ for (const item of items) {+ const baseEnvelope = {+ service: item.scriptName,+ service_id: item.scriptName,+ cell_id: "cf-edge",+ region: "global",+ outcome: item.outcome,+ request_url: item.event?.request?.url,+ request_method: item.event?.request?.method,+ response_status: item.event?.response?.status,+ cron: item.event?.cron,+ script_version: item.scriptVersion?.id,+ };++ for (const log of item.logs) {+ records.push({+ _time: new Date(log.timestamp).toISOString(),+ time: new Date(log.timestamp).toISOString(),+ level: level(log.level),+ msg: fmtMessage(log.message),+ ...baseEnvelope,+ });+ }++ for (const ex of item.exceptions) {+ records.push({+ _time: new Date(ex.timestamp).toISOString(),+ time: new Date(ex.timestamp).toISOString(),+ level: "ERROR",+ msg: `${ex.name}: ${ex.message}`,+ stack: ex.stack,+ ...baseEnvelope,+ });+ }++ // Synthetic record when a request ended in exception/exceededCpu/etc+ // but had no console output — gives us a row to count "failed+ // requests by script" in Axiom without joining streams.+ if (item.outcome !== "ok" && item.logs.length === 0 && item.exceptions.length === 0) {+ records.push({+ _time: new Date(item.eventTimestamp ?? Date.now()).toISOString(),+ time: new Date(item.eventTimestamp ?? Date.now()).toISOString(),+ level: "ERROR",+ msg: `worker request ended with outcome=${item.outcome}`,+ ...baseEnvelope,+ });+ }+ }++ if (records.length === 0) return;++ const url = `${env.AXIOM_HOST}/v1/datasets/${env.AXIOM_DATASET}/ingest`;+ const resp = await fetch(url, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${env.AXIOM_TOKEN}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify(records),+ });+ if (!resp.ok) {+ const body = await resp.text().catch(() => "");+ console.error(`axiom ingest failed status=${resp.status} body=${body.slice(0, 200)}`);+ }+ },+};diff --git a/cloudflare-workers/log-tail/wrangler.toml b/cloudflare-workers/log-tail/wrangler.tomlnew file mode 100644index 00000000..4252e91c--- /dev/null+++ b/cloudflare-workers/log-tail/wrangler.toml@@ -0,0 +1,12 @@+name = "opensandbox-log-tail"+main = "src/index.ts"+compatibility_date = "2024-12-01"+account_id = "1241f114453e32d292197e3fb36210b2"+workers_dev = false++# Secrets (set via `wrangler secret put`):+# AXIOM_TOKEN — xaat-... ingest token+# Other config lives here in plain text — dataset name + host aren't sensitive.+[vars]+AXIOM_HOST = "https://api.axiom.co"+AXIOM_DATASET = "cf-dev"diff --git a/cloudflare-workers/schema_phase2_d1.sql b/cloudflare-workers/schema_phase2_d1.sqlnew file mode 100644index 00000000..f7d4de42--- /dev/null+++ b/cloudflare-workers/schema_phase2_d1.sql@@ -0,0 +1,41 @@+-- Phase 2 schema for D1 (no RAISE clauses — D1 rejects them outside triggers).+-- Strips the no-op pragma_table_info guard from schema_phase2.sql; only the+-- table creates + the ALTER TABLE calls remain. ALTER is one-shot; re-running+-- this file fails (idempotent re-run isn't supported by D1).++CREATE TABLE IF NOT EXISTS golden_versions (+ hash TEXT PRIMARY KEY,+ canonical_url TEXT NOT NULL,+ size_bytes INTEGER,+ cells_available TEXT NOT NULL DEFAULT '[]',+ ami_version TEXT,+ created_at INTEGER NOT NULL,+ retired_at INTEGER+);++CREATE INDEX IF NOT EXISTS idx_golden_versions_active+ ON golden_versions(created_at) WHERE retired_at IS NULL;++CREATE TABLE IF NOT EXISTS checkpoints_index (+ id TEXT PRIMARY KEY,+ sandbox_id TEXT NOT NULL,+ org_id TEXT NOT NULL,+ owner_cell_id TEXT NOT NULL,+ s3_url TEXT NOT NULL,+ size_bytes INTEGER,+ golden_hash TEXT NOT NULL,+ workspace_size INTEGER,+ created_at INTEGER NOT NULL,+ expires_at INTEGER,+ replicated_to TEXT NOT NULL DEFAULT '[]'+);++CREATE INDEX IF NOT EXISTS idx_checkpoints_org ON checkpoints_index(org_id);+CREATE INDEX IF NOT EXISTS idx_checkpoints_sandbox ON checkpoints_index(sandbox_id);+CREATE INDEX IF NOT EXISTS idx_checkpoints_owner ON checkpoints_index(owner_cell_id);+CREATE INDEX IF NOT EXISTS idx_checkpoints_expires ON checkpoints_index(expires_at)+ WHERE expires_at IS NOT NULL;++-- templates: extend with canonical Tigris URLs. ALTERs run once; re-runs fail.+ALTER TABLE templates ADD COLUMN canonical_rootfs_url TEXT;+ALTER TABLE templates ADD COLUMN canonical_workspace_url TEXT;diff --git a/cloudflare-workers/schema_phase3.sql b/cloudflare-workers/schema_phase3.sqlnew file mode 100644index 00000000..d2e7fb99--- /dev/null+++ b/cloudflare-workers/schema_phase3.sql@@ -0,0 +1,16 @@+-- Phase 3: free-tier halt tracking+--+-- The CreditAccount DO is the source of truth for an org's free-tier balance+-- and halt status (lives in DO storage, lazy-loaded on first /check). The+-- mirror column below exists for one reason: the api-edge /internal/halt-list+-- endpoint needs to enumerate halted orgs without round-tripping every org's+-- DO. The DO writes back to this column on dispatchHalt success and clears it+-- on dispatchResume. D1 is the projection; DO is authoritative.+--+-- Apply with:+-- wrangler d1 execute opencomputer-dev --remote --file cloudflare-workers/schema_phase3.sql++ALTER TABLE orgs ADD COLUMN is_halted INTEGER NOT NULL DEFAULT 0;+ALTER TABLE orgs ADD COLUMN halted_at INTEGER;++CREATE INDEX IF NOT EXISTS idx_orgs_halted ON orgs(is_halted) WHERE is_halted = 1;diff --git a/cloudflare-workers/schema_phase4.sql b/cloudflare-workers/schema_phase4.sqlnew file mode 100644index 00000000..251c94a8--- /dev/null+++ b/cloudflare-workers/schema_phase4.sql@@ -0,0 +1,93 @@+-- Phase 4: dashboard-on-edge data model.+--+-- The CF edge becomes the source of truth for identity, billing, and the+-- sandbox routing index (per the new architecture diagram). This migration+-- adds the missing columns and tables to D1 so api-edge dashboard handlers+-- can read/write directly instead of proxying to cell PG.+--+-- Apply with:+-- wrangler d1 execute opencomputer-dev --remote --file cloudflare-workers/schema_phase4.sql+--+-- SQLite/D1 has no `ALTER TABLE ADD COLUMN IF NOT EXISTS`, so these ALTERs+-- fail on re-run. Phase 4 is one-shot. If you need to re-apply, drop the+-- affected columns first or skip the ALTERs.++-- ── orgs: full feature parity with cell PG ───────────────────────────────+--+-- These mirror columns the cell PG `orgs` table has had since migrations+-- 005 / 016 / 029. Carrying them in D1 means dashboard can manage them+-- without touching any cell. The CF custom-domain handlers live on the+-- edge (it calls the CF API directly anyway), so this is the natural+-- place for the data.++ALTER TABLE orgs ADD COLUMN custom_domain TEXT;+ALTER TABLE orgs ADD COLUMN cf_hostname_id TEXT;+ALTER TABLE orgs ADD COLUMN domain_verification_status TEXT NOT NULL DEFAULT 'none';+ALTER TABLE orgs ADD COLUMN domain_ssl_status TEXT NOT NULL DEFAULT 'none';+ALTER TABLE orgs ADD COLUMN verification_txt_name TEXT;+ALTER TABLE orgs ADD COLUMN verification_txt_value TEXT;+ALTER TABLE orgs ADD COLUMN ssl_txt_name TEXT;+ALTER TABLE orgs ADD COLUMN ssl_txt_value TEXT;++-- Billing balances mirrored from CreditAccount DO. The DO is the live+-- authority; these columns let dashboard render balances without a DO+-- round-trip per page load. Updated on /debit, /credit, /mark-pro.+ALTER TABLE orgs ADD COLUMN free_credits_remaining_cents INTEGER NOT NULL DEFAULT 500;+ALTER TABLE orgs ADD COLUMN credit_balance_cents INTEGER NOT NULL DEFAULT 0;++-- Org quota controls (matches PG migration 029).+ALTER TABLE orgs ADD COLUMN max_concurrent_sandboxes INTEGER NOT NULL DEFAULT 5;+ALTER TABLE orgs ADD COLUMN max_sandbox_timeout_sec INTEGER NOT NULL DEFAULT 3600;+ALTER TABLE orgs ADD COLUMN max_disk_mb INTEGER NOT NULL DEFAULT 0;+ALTER TABLE orgs ADD COLUMN max_memory_gb INTEGER NOT NULL DEFAULT 0;++-- Billing mode (matches PG migration 031): "legacy" = UsageReporter → Stripe;+-- "unified" = phase-3 billable_events sender. New orgs default to unified+-- in the dashboard create flow.+ALTER TABLE orgs ADD COLUMN billing_mode TEXT NOT NULL DEFAULT 'unified';++-- Last Stripe usage report timestamp (matches PG migration 016 area).+ALTER TABLE orgs ADD COLUMN last_usage_reported_at INTEGER NOT NULL DEFAULT 0;++-- ── invitations ─────────────────────────────────────────────────────────+--+-- Pending invitations to an org. WorkOS handles the email send and acceptance+-- handshake; we mirror state here so dashboard can list outstanding invites+-- and revoke them. Acceptance flow (WorkOS callback) updates D1 directly.++CREATE TABLE IF NOT EXISTS invitations (+ id TEXT PRIMARY KEY, -- D1-local UUID+ org_id TEXT NOT NULL,+ email TEXT NOT NULL,+ role TEXT NOT NULL DEFAULT 'member', -- "owner" | "admin" | "member"+ invited_by TEXT, -- user_id of the inviter+ workos_invitation_id TEXT, -- WorkOS Invitation.id (null until WorkOS call succeeds)+ status TEXT NOT NULL DEFAULT 'pending', -- pending | accepted | revoked | expired+ token TEXT UNIQUE, -- short opaque accept token (not currently used; WorkOS owns the flow)+ expires_at INTEGER, -- unix s; null = no expiry+ created_at INTEGER NOT NULL,+ accepted_at INTEGER,+ revoked_at INTEGER+);+CREATE INDEX IF NOT EXISTS idx_invitations_org_status ON invitations(org_id, status);+CREATE INDEX IF NOT EXISTS idx_invitations_email ON invitations(email);++-- ── agent_subscriptions ─────────────────────────────────────────────────+--+-- Per-(org, agent, feature) subscription rows. Pro-tier orgs subscribe to+-- specific agent features (e.g., Telegram bot premium tools) and we ship+-- those events to Stripe via meters. Dashboard reads this to render+-- subscription state; mutations dispatch to Stripe + record here.++CREATE TABLE IF NOT EXISTS agent_subscriptions (+ id TEXT PRIMARY KEY, -- D1-local UUID+ org_id TEXT NOT NULL,+ agent_id TEXT NOT NULL,+ feature TEXT NOT NULL, -- "telegram", "premium-tools", etc.+ status TEXT NOT NULL DEFAULT 'active', -- active | cancelled+ stripe_item_id TEXT, -- Stripe Subscription Item ID+ created_at INTEGER NOT NULL,+ cancelled_at INTEGER+);+CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_subs_unique ON agent_subscriptions(org_id, agent_id, feature);+CREATE INDEX IF NOT EXISTS idx_agent_subs_org ON agent_subscriptions(org_id);diff --git a/cloudflare-workers/seed_templates.sql b/cloudflare-workers/seed_templates.sqlnew file mode 100644index 00000000..72c9a0d7--- /dev/null+++ b/cloudflare-workers/seed_templates.sql@@ -0,0 +1,19 @@+-- Seed built-in public templates in D1. Mirrors the legacy PG seeds in+-- internal/db/migrations/004_seed_templates.up.sql + 008_default_template.up.sql.+-- Public templates (org_id IS NULL) are visible to every org via the+-- /internal/templates/by-name public-fallback path.+--+-- Apply with:+-- cd cloudflare-workers/events-ingest && \+-- npx wrangler d1 execute opencomputer-dev --remote \+-- --file ../seed_templates.sql++INSERT INTO templates+ (id, org_id, name, tag, template_type, image_ref, is_public, status, cells_available, created_at)+VALUES+ ('00000000-0000-0000-0000-000000000001', NULL, 'default', 'latest', 'dockerfile', 'opensandbox/default:latest', 1, 'ready', '[]', unixepoch()),+ ('00000000-0000-0000-0000-000000000002', NULL, 'base', 'latest', 'dockerfile', 'docker.io/library/ubuntu:22.04', 1, 'ready', '[]', unixepoch()),+ ('00000000-0000-0000-0000-000000000003', NULL, 'ubuntu', 'latest', 'dockerfile', 'docker.io/library/ubuntu:22.04', 1, 'ready', '[]', unixepoch()),+ ('00000000-0000-0000-0000-000000000004', NULL, 'python', 'latest', 'dockerfile', 'docker.io/library/python:3.12-slim', 1, 'ready', '[]', unixepoch()),+ ('00000000-0000-0000-0000-000000000005', NULL, 'node', 'latest', 'dockerfile', 'docker.io/library/node:20-slim', 1, 'ready', '[]', unixepoch())+ON CONFLICT(id) DO NOTHING;diff --git a/cloudflare-workers/shared/credit_account.ts b/cloudflare-workers/shared/credit_account.tsindex 555bb4d2..cb04096b 100644--- a/cloudflare-workers/shared/credit_account.ts+++ b/cloudflare-workers/shared/credit_account.ts@@ -1,25 +1,37 @@-// CreditAccount — Durable Object per org tracking free-tier balance.-// Imported by both api-edge and events-ingest Workers.+// CreditAccount — Durable Object per org tracking free-tier balance and halt+// status. One DO instance per org_id (deterministically routed via idFromName).//-// Endpoints (all internal HTTP):-// POST /check → { allowed, balance_cents }-// POST /debit → idempotent (event_id), decrements balance, dispatches halt at zero-// POST /credit → increments balance, may trigger resume-// POST /mark-pro → flips to pro plan, optionally dispatches resume-// GET /snapshot → full state, used by parity-check cron+// Endpoints (all internal HTTP, called via DO stub fetch):+// POST /check → { allowed, balance_cents } — gate sandbox starts/wakes+// POST /debit → idempotent (event_id), decrements, dispatches halt at 0+// POST /credit → increments, dispatches resume if was halted_credits+// POST /mark-pro → flips plan to "pro", clears halt+// POST /mark-free → flips plan back to "free" (subscription cancelled)+// GET /snapshot → full state, used by parity-check cron and tests//-// State seeds lazily on first /check from D1 orgs.plan + free_credits_remaining_cents-// (so we don't hard-code $5 in two places).+// State seeds lazily on first /check from D1 orgs.plan; the $5 free-tier+// seed is hardcoded in this file (single source of truth — the runbook says+// 500 cents and D1 doesn't carry a per-org seed column).+//+// Halt/resume dispatch: on balance <= 0, query D1 sandboxes_index for cells+// where the org has running/migrating sandboxes, HMAC-POST /admin/halt-org to+// each cell's CP base_url. On credit refill or mark-pro, mirror with /resume-org.+// 3x exponential retry; final-failure logged for the CP halt_reconciler to mop up.-interface State {+interface DOState {org_id: string;plan: "free" | "pro";- balance_cents: number; // -1 when plan == "pro" (no longer tracked)+ balance_cents: number; // -1 sentinel for plan="pro" (untracked)lifetime_spent_cents: number;- status: "active" | "halted_credits" | "suspended";+ status: "active" | "halted_credits";halted_at?: number;last_debit_at?: number;- processed_event_ids: string[]; // bounded LRU, last 1024+ processed_event_ids: string[]; // bounded LRU, last 1024 — idempotency for /debit+}++interface CellRow {+ cell_id: string;+ base_url: string;}interface Env {@@ -27,6 +39,10 @@ interface Env {CF_ADMIN_SECRET: string;}+const FREE_TIER_SEED_CENTS = 500; // $5 — runbook decision+const PROCESSED_LRU_MAX = 1024;+const HALT_RETRY_BACKOFFS_MS = [200, 1000, 5000];+export class CreditAccount {state: DurableObjectState;env: Env;@@ -38,30 +54,324 @@ export class CreditAccount {async fetch(req: Request): Promise<Response> {const url = new URL(req.url);+ const path = url.pathname;++ try {+ if (path === "/snapshot") return await this.snapshot();- // TODO Stage 2:- // /check → load-or-init from D1 if storage empty, return {allowed, balance_cents}- // /debit → check processed_event_ids LRU, decrement, dispatch halt at <=0- // /credit → increment, dispatch resume if status was halted_credits and balance > 0- // /mark-pro → set plan="pro", balance_cents=-1, optionally dispatchResume- // /snapshot → return full State-- if (url.pathname === "/snapshot") {- const data = await this.state.storage.list();- return new Response(JSON.stringify(Object.fromEntries(data)), {- headers: { "content-type": "application/json" },- });+ // org_id comes from the URL — caller is responsible for routing to the+ // right DO (idFromName(orgID)). Body carries event_id / amount / etc.+ const orgID = url.searchParams.get("org_id");+ if (!orgID) return json({ error: "missing org_id" }, 400);++ if (path === "/check" && req.method === "POST") return await this.check(orgID);+ if (path === "/debit" && req.method === "POST") return await this.debit(orgID, req);+ if (path === "/credit" && req.method === "POST") return await this.credit(orgID, req);+ if (path === "/mark-pro" && req.method === "POST") return await this.markPro(orgID);+ if (path === "/mark-free"&& req.method === "POST") return await this.markFree(orgID);++ return json({ error: "not found" }, 404);+ } catch (err) {+ console.error("credit_account: handler error", err);+ return json({ error: (err as Error).message }, 500);}+ }++ // ── handlers ───────────────────────────────────────────────────────────- return new Response("not implemented", { status: 501 });+ private async check(orgID: string): Promise<Response> {+ const s = await this.loadOrInit(orgID);+ const allowed = s.plan === "pro" || s.balance_cents > 0;+ return json({ allowed, balance_cents: s.balance_cents, plan: s.plan, status: s.status });}- // dispatchHalt queries D1 sandboxes_index for cells where the org has- // any running/migrating sandboxes, then HMAC-POSTs /admin/halt-org to- // each cell's regional CP. Retries 3x exponential. Logs and falls back- // to the CP halt_reconciler safety net on persistent failure.- // private async dispatchHalt(orgId: string): Promise<void> { ... }+ private async debit(orgID: string, req: Request): Promise<Response> {+ const body = await req.json<{ event_id?: string; amount_cents?: number }>().catch(() => ({} as { event_id?: string; amount_cents?: number }));+ const eventID = body.event_id ?? "";+ const amount = Math.max(0, Math.floor(body.amount_cents ?? 0));+ if (!eventID) return json({ error: "missing event_id" }, 400);+ if (amount === 0) return json({ ok: true, deduped: false, balance_cents: -1 }, 200);++ const s = await this.loadOrInit(orgID);++ // Pro orgs: no-op. Per-event-id is still recorded to keep the LRU honest+ // in case the org flips back to free later.+ if (s.plan === "pro") {+ this.recordEvent(s, eventID);+ await this.persist(s);+ return json({ ok: true, deduped: false, balance_cents: -1, plan: "pro" });+ }++ if (s.processed_event_ids.includes(eventID)) {+ return json({ ok: true, deduped: true, balance_cents: s.balance_cents });+ }++ const prev = s.balance_cents;+ s.balance_cents = Math.max(0, prev - amount);+ s.lifetime_spent_cents += (prev - s.balance_cents);+ s.last_debit_at = Math.floor(Date.now() / 1000);+ this.recordEvent(s, eventID);++ let dispatchedHalt = false;+ if (s.balance_cents === 0 && s.status === "active") {+ s.status = "halted_credits";+ s.halted_at = Math.floor(Date.now() / 1000);+ await this.persist(s);+ await this.markD1Halted(orgID, true, s.halted_at);+ await this.mirrorBalanceToD1(orgID, 0);+ // Fire dispatch out-of-band — failure here is recoverable via the CP's+ // halt_reconciler safety net, so don't block the debit response on it.+ this.state.waitUntil(this.dispatchHalt(orgID));+ dispatchedHalt = true;+ } else {+ await this.persist(s);+ // Best-effort: mirror to D1 every N debits to keep dashboard reads+ // close to real-time without paying the write on every tick. waitUntil+ // keeps it async so it doesn't block the /debit ack to events-ingest.+ this.state.waitUntil(this.mirrorBalanceToD1(orgID, s.balance_cents));+ }++ return json({+ ok: true,+ deduped: false,+ balance_cents: s.balance_cents,+ halt_dispatched: dispatchedHalt,+ });+ }++ private async credit(orgID: string, req: Request): Promise<Response> {+ const body = await req.json<{ amount_cents?: number }>().catch(() => ({} as { amount_cents?: number }));+ const amount = Math.max(0, Math.floor(body.amount_cents ?? 0));+ if (amount === 0) return json({ error: "amount_cents must be > 0" }, 400);++ const s = await this.loadOrInit(orgID);++ if (s.plan === "pro") {+ // Crediting a pro org is meaningless (balance untracked) but not an error.+ return json({ ok: true, balance_cents: -1, plan: "pro" });+ }++ const wasHalted = s.status === "halted_credits";+ s.balance_cents = (s.balance_cents < 0 ? 0 : s.balance_cents) + amount;+ if (wasHalted && s.balance_cents > 0) {+ s.status = "active";+ s.halted_at = undefined;+ }+ await this.persist(s);++ let dispatchedResume = false;+ if (wasHalted && s.balance_cents > 0) {+ await this.markD1Halted(orgID, false, 0);+ this.state.waitUntil(this.dispatchResume(orgID));+ dispatchedResume = true;+ }+ this.state.waitUntil(this.mirrorBalanceToD1(orgID, s.balance_cents));+ return json({ ok: true, balance_cents: s.balance_cents, resume_dispatched: dispatchedResume });+ }++ private async markPro(orgID: string): Promise<Response> {+ const s = await this.loadOrInit(orgID);+ const wasHalted = s.status === "halted_credits";+ s.plan = "pro";+ s.balance_cents = -1;+ s.status = "active";+ s.halted_at = undefined;+ await this.persist(s);++ // Mirror to D1 so any cron / future-cell that looks at orgs.plan sees the truth.+ await this.env.OPENCOMPUTER_DB.prepare(+ `UPDATE orgs SET plan = 'pro', is_halted = 0, halted_at = NULL, updated_at = ?1 WHERE id = ?2`,+ )+ .bind(Math.floor(Date.now() / 1000), orgID)+ .run();++ // If the org was previously halted on free-tier, wake their sandboxes.+ let dispatchedResume = false;+ if (wasHalted) {+ this.state.waitUntil(this.dispatchResume(orgID));+ dispatchedResume = true;+ }+ return json({ ok: true, plan: "pro", resume_dispatched: dispatchedResume });+ }++ private async markFree(orgID: string): Promise<Response> {+ // Subscription cancellation. Don't immediately halt — flip to free with+ // whatever balance they have. If balance is 0, the next debit (or the+ // halt_reconciler's next pass) will trigger halt. Avoids halting mid-+ // billing-cycle just because Stripe sent a "subscription.deleted" event.+ const s = await this.loadOrInit(orgID);+ s.plan = "free";+ // Keep balance_cents as-is, but if it's the -1 sentinel from pro, reset.+ if (s.balance_cents < 0) s.balance_cents = 0;+ await this.persist(s);+ await this.env.OPENCOMPUTER_DB.prepare(+ `UPDATE orgs SET plan = 'free', updated_at = ?1 WHERE id = ?2`,+ )+ .bind(Math.floor(Date.now() / 1000), orgID)+ .run();+ return json({ ok: true, plan: "free", balance_cents: s.balance_cents });+ }++ private async snapshot(): Promise<Response> {+ const data = await this.state.storage.list();+ return json(Object.fromEntries(data));+ }++ // ── state helpers ──────────────────────────────────────────────────────++ // loadOrInit reads the DO's persisted state if present, otherwise seeds+ // it from D1 orgs.plan (free → 500¢ seed; pro → -1 sentinel). The seed+ // is durable after the first /check or /debit because we persist right away.+ private async loadOrInit(orgID: string): Promise<DOState> {+ const existing = await this.state.storage.get<DOState>("state");+ if (existing) return existing;++ const row = await this.env.OPENCOMPUTER_DB.prepare(+ `SELECT plan FROM orgs WHERE id = ?1`,+ )+ .bind(orgID)+ .first<{ plan: string }>();+ const plan: "free" | "pro" = row?.plan === "pro" ? "pro" : "free";+ const seed: DOState = {+ org_id: orgID,+ plan,+ balance_cents: plan === "pro" ? -1 : FREE_TIER_SEED_CENTS,+ lifetime_spent_cents: 0,+ status: "active",+ processed_event_ids: [],+ };+ await this.persist(seed);+ return seed;+ }++ private async persist(s: DOState): Promise<void> {+ await this.state.storage.put("state", s);+ }++ private recordEvent(s: DOState, eventID: string): void {+ s.processed_event_ids.push(eventID);+ if (s.processed_event_ids.length > PROCESSED_LRU_MAX) {+ s.processed_event_ids = s.processed_event_ids.slice(-PROCESSED_LRU_MAX);+ }+ }++ private async markD1Halted(orgID: string, halted: boolean, haltedAt: number): Promise<void> {+ try {+ await this.env.OPENCOMPUTER_DB.prepare(+ `UPDATE orgs SET is_halted = ?1, halted_at = ?2, updated_at = ?3 WHERE id = ?4`,+ )+ .bind(halted ? 1 : 0, halted ? haltedAt : null, Math.floor(Date.now() / 1000), orgID)+ .run();+ } catch (err) {+ // D1 mirror is best-effort — the DO state is authoritative. If this+ // fails, halt-list endpoint just won't include the org until the next+ // /debit retries the write, but the actual halt webhook still goes+ // out via dispatchHalt below.+ console.error("credit_account: failed to mirror halt state to D1", err);+ }+ }++ // mirrorBalanceToD1 writes the current free-tier balance to orgs.free_credits_remaining_cents+ // so dashboard reads (/api/dashboard/billing) see the live value without round-tripping+ // through the DO on every page load. DO state remains authoritative — this column is the+ // projection consumed by the cached read path.+ private async mirrorBalanceToD1(orgID: string, balanceCents: number): Promise<void> {+ try {+ await this.env.OPENCOMPUTER_DB.prepare(+ `UPDATE orgs SET free_credits_remaining_cents = ?1, updated_at = ?2 WHERE id = ?3`,+ )+ .bind(balanceCents, Math.floor(Date.now() / 1000), orgID)+ .run();+ } catch (err) {+ console.error("credit_account: failed to mirror balance to D1", err);+ }+ }++ // ── dispatch ───────────────────────────────────────────────────────────++ // Resolve the cells where the org has running/migrating sandboxes, then+ // HMAC-POST /admin/halt-org to each cell's CP. Retries up to 3x with+ // exponential backoff per cell; the CP halt_reconciler is the safety net+ // for terminal failures.+ private async dispatchHalt(orgID: string): Promise<void> {+ const cells = await this.cellsForOrg(orgID);+ if (cells.length === 0) return;+ const body = JSON.stringify({ org_id: orgID, reason: "credits_exhausted" });+ await Promise.all(cells.map((c) => this.postWithRetry(c, "/admin/halt-org", body)));+ }++ private async dispatchResume(orgID: string): Promise<void> {+ const cells = await this.cellsForOrg(orgID);+ if (cells.length === 0) return;+ const body = JSON.stringify({ org_id: orgID, skip_resume: false });+ await Promise.all(cells.map((c) => this.postWithRetry(c, "/admin/resume-org", body)));+ }++ // Distinct cells where this org has any non-stopped sandbox. We dispatch+ // halt to all of them so cross-cell-distributed orgs get consistent+ // treatment in one shot.+ private async cellsForOrg(orgID: string): Promise<CellRow[]> {+ const { results } = await this.env.OPENCOMPUTER_DB.prepare(+ `SELECT DISTINCT c.cell_id, c.base_url+ FROM sandboxes_index s+ JOIN cells c ON s.cell_id = c.cell_id+ WHERE s.org_id = ?1 AND s.status IN ('running', 'hibernated', 'migrating')`,+ )+ .bind(orgID)+ .all<CellRow>();+ return results ?? [];+ }++ private async postWithRetry(cell: CellRow, path: string, body: string): Promise<void> {+ const ts = Math.floor(Date.now() / 1000).toString();+ const sig = await hmacHex(this.env.CF_ADMIN_SECRET, `${ts}.${body}`);+ const url = cell.base_url.replace(/\/$/, "") + path;++ for (let attempt = 0; attempt <= HALT_RETRY_BACKOFFS_MS.length; attempt++) {+ try {+ const resp = await fetch(url, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "X-Timestamp": ts,+ "X-Signature": sig,+ },+ body,+ });+ if (resp.status >= 200 && resp.status < 300) return;+ console.error(`credit_account: dispatch ${path} → ${cell.cell_id} status=${resp.status} attempt=${attempt}`);+ } catch (err) {+ console.error(`credit_account: dispatch ${path} → ${cell.cell_id} error=${(err as Error).message} attempt=${attempt}`);+ }+ if (attempt < HALT_RETRY_BACKOFFS_MS.length) {+ await sleep(HALT_RETRY_BACKOFFS_MS[attempt]);+ }+ }+ console.error(`credit_account: dispatch ${path} → ${cell.cell_id} permanently failed — relying on CP halt_reconciler safety net`);+ }+}++// ── module-local helpers (not exported) ──────────────────────────────────++function json(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json" },+ });+}++function sleep(ms: number): Promise<void> {+ return new Promise((r) => setTimeout(r, ms));+}- // dispatchResume mirrors dispatchHalt for /admin/resume-org.- // private async dispatchResume(orgId: string): Promise<void> { ... }+async function hmacHex(secret: string, data: string): Promise<string> {+ const key = await crypto.subtle.importKey(+ "raw",+ new TextEncoder().encode(secret),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ );+ const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(data));+ return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");}diff --git a/cmd/server/main.go b/cmd/server/main.goindex 1eea671d..2abb4761 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -22,6 +22,7 @@ import ("github.com/opensandbox/opensandbox/internal/controlplane""github.com/opensandbox/opensandbox/internal/crypto""github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/internal/edgeclient""github.com/opensandbox/opensandbox/internal/metrics""github.com/opensandbox/opensandbox/internal/obslog""github.com/opensandbox/opensandbox/internal/observability"@@ -87,6 +88,8 @@ func main() {HTTPAddr: cfg.HTTPAddr,CellID: cfg.CellID,SessionJWTSecret: cfg.SessionJWTSecret,+ CFAdminSecret: cfg.CFAdminSecret,+ CFEventSecret: cfg.CFEventSecret,}// Initialize PostgreSQL if configured@@ -562,6 +565,15 @@ func main() {// Create API serverserver := api.NewServer(mgr, ptyMgr, cfg.APIKey, opts)+ // Wire the CF api-edge HTTP client. Used by resolveSecretStoreInto ++ // resolveTemplate to read from D1 over HMAC instead of local PG once+ // migration 041 strips the global tables. Falls back to s.store if+ // either CFEdgeBaseURL or CFEventSecret is unset (combined dev mode).+ if cfg.CFEdgeBaseURL != "" && cfg.CFEventSecret != "" {+ server.SetEdgeClient(edgeclient.New(cfg.CFEdgeBaseURL, cfg.CFEventSecret))+ log.Printf("opensandbox: edge client wired (base=%s)", cfg.CFEdgeBaseURL)+ }+// Wire Axiom read-only token for the sandbox session logs API.// Token never leaves this process; the UI proxies its queries through// /api/sandboxes/:id/logs. Empty token disables the endpoint (503).@@ -616,11 +628,40 @@ func main() {workers = redisRegistry}reporter := billing.NewUsageReporter(opts.Store, stripeClient, workers)+ // CF billing mode: when this CP is wired into the CF event pipe, the+ // CreditAccount DO is authoritative on free-tier balance. Disable+ // the local free-tier deduction pass so both sides don't race.+ if cfg.CFEventEndpoint != "" {+ reporter.SetCFBillingMode(true)+ log.Println("opensandbox: usage reporter CF-billing mode ON (free-tier deduction deferred to CreditAccount DO)")+ }reporter.Start()defer reporter.Stop()log.Println("opensandbox: usage reporter started (interval=5m)")}+ // Halt reconciler — safety net for missed CF halt webhooks. Pulls the+ // authoritative halt-list from api-edge every 60s and re-issues halts+ // for anything that should be halted but isn't. Inert unless+ // OPENSANDBOX_HALT_LIST_URL is set.+ if cfg.HaltListURL != "" && cfg.CFEventSecret != "" && server != nil {+ reconciler := controlplane.NewHaltReconciler(controlplane.HaltReconcilerConfig{+ CellID: cfg.CellID,+ ListURL: cfg.HaltListURL,+ Secret: cfg.CFEventSecret,+ Halter: server,+ })+ if reconciler != nil {+ reconciler.Start(ctx)+ defer func() {+ stopCtx, stopCancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer stopCancel()+ _ = reconciler.Stop(stopCtx)+ }()+ log.Printf("opensandbox: halt reconciler started (list_url=%s, period=60s)", cfg.HaltListURL)+ }+ }+// Phase-2 capacity allocator. Writes outbox rows for unified-mode// pro orgs after each settled bucket. Allocator skips legacy and// free orgs (see ListAllocatorCandidates); rollback is bydiff --git a/cmd/worker/main.go b/cmd/worker/main.goindex 5426e4dc..8df8b684 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -14,6 +14,8 @@ import ("syscall""time"+ "github.com/google/uuid"+"github.com/opensandbox/opensandbox/internal/analytics""github.com/opensandbox/opensandbox/internal/auth""github.com/opensandbox/opensandbox/internal/blobstore"@@ -132,6 +134,10 @@ func main() {var doGracefulShutdown func(checkpointStore *storage.CheckpointStore, store *db.Store)// Metadata server (set by QEMU backend, wired to store later)var metadataSrv *worker.MetadataServer+ // Forward-declared so doGracefulShutdown's closure (built in the QEMU+ // init block below) can capture it; the actual NewSandboxDBManager call+ // happens after backend init.+ var sandboxDBMgr *sandbox.SandboxDBManager// Initialize secrets proxy for MITM token substitution.// Runs on :3128 — VMs route HTTPS through this to keep real secrets off-VM.@@ -319,7 +325,7 @@ func main() {log.Printf("opensandbox-worker: %d VMs failed to hibernate: %v", len(failed), failed)}- processHibernateResults(results, store, checkpointStore, func(r interface{}) (string, string, error) {+ processHibernateResults(results, store, checkpointStore, sandboxDBMgr, func(r interface{}) (string, string, error) {hr := r.(qm.HibernateAllResult)return hr.SandboxID, hr.HibernationKey, hr.Err})@@ -346,8 +352,9 @@ func main() {ptyMgr := sandbox.NewAgentPTYManager(ptySessionFactory)defer ptyMgr.CloseAll()- // Initialize per-sandbox SQLite manager- sandboxDBMgr := sandbox.NewSandboxDBManager(cfg.DataDir)+ // Initialize per-sandbox SQLite manager (forward-declared above so the+ // graceful-shutdown closure can capture it).+ sandboxDBMgr = sandbox.NewSandboxDBManager(cfg.DataDir)defer sandboxDBMgr.Close()// JWT issuer@@ -647,38 +654,61 @@ func main() {}}- // NATS- if cfg.NATSURL != "" {- pub, err := worker.NewEventPublisher(cfg.NATSURL, cfg.Region, cfg.WorkerID, sandboxDBMgr)- if err != nil {- log.Printf("opensandbox-worker: NATS not available: %v (continuing without event sync)", err)- } else {- pub.Start()- if qemuMgr != nil {- pub.SetGoldenVersion(qemuMgr.GoldenVersion())- }- pub.StartHeartbeat(func() (int, int, float64, float64, float64) {- count, _ := mgr.Count(context.Background())- cpuPct, memPct, diskPct := worker.SystemStats()- return cfg.MaxCapacity, count, cpuPct, memPct, diskPct- })- defer pub.Stop()- log.Println("opensandbox-worker: NATS event publisher started")- }- }-// CF-parallel: Redis Streams event publisher. Inert unless CellID is set.- // Runs in addition to (not replacing) the NATS publisher during cutover.+ // (The legacy NATS publisher used to run alongside this; it was removed+ // once Redis Streams covered all event types end-to-end. NATSURL in the+ // env file is ignored.)if cfg.CellID != "" && cfg.RedisURL != "" {+ // Resolver: look up sandbox → org → plan via cell-local PG. Called+ // per event during flush; sandbox_sessions has an indexed lookup on+ // sandbox_id and orgs is keyed by org_id, so each call is two index+ // hits. usage_tick volume is sandboxes × ~30s, so cost is bounded.+ // nil store (no PG) leaves the fields blank — events-ingest then+ // treats them as "unknown plan" and skips DO debit, which is the+ // safe fallback.+ var planResolver worker.MetadataResolver+ if store != nil {+ st := store+ planResolver = func(sandboxID string) (string, string, bool) {+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer cancel()+ orgIDStr, err := st.GetSandboxOrgID(ctx, sandboxID)+ if err != nil || orgIDStr == "" {+ return "", "", false+ }+ orgID, err := uuid.Parse(orgIDStr)+ if err != nil {+ return "", "", false+ }+ org, err := st.GetOrg(ctx, orgID)+ if err != nil {+ // Org row may not exist yet (new app2 user, lazy upsert+ // hasn't run from this sandbox's create). Return the+ // org_id so events-ingest can still archive; leave plan+ // blank so it skips DO debit until the row exists.+ return orgIDStr, "", true+ }+ return orgIDStr, org.Plan, true+ }+ }redisPub, err := worker.NewRedisEventPublisher(worker.RedisEventPublisherConfig{RedisURL: cfg.RedisURL,SandboxDBs: sandboxDBMgr,CellID: cfg.CellID,WorkerID: cfg.WorkerID,+ Resolver: planResolver,})if err != nil {log.Printf("opensandbox-worker: Redis event publisher init failed: %v (continuing)", err)} else {+ // Wire the publisher as the SandboxDBManager's OnRemove hook so+ // terminal events (stopped, hibernated) are synchronously flushed+ // to Redis BEFORE the SQLite file is deleted. The destroy /+ // hibernate gRPC handlers LogEvent + then call Remove; this hook+ // closes the race that previously dropped those events.+ sandboxDBMgr.SetOnRemove(func(sandboxID string) {+ redisPub.FlushSandbox(context.Background(), sandboxID)+ })redisPub.Start(context.Background())defer func() {stopCtx, stopCancel := context.WithTimeout(context.Background(), 5*time.Second)@@ -693,6 +723,25 @@ func main() {autosaver := worker.NewWorkspaceAutosaver(mgr, autosaverSyncer, 5*time.Minute)autosaver.Start()+ // Usage ticker — drives the free-tier billing loop. Emits a usage_tick+ // per running sandbox every 20s; events-ingest fans out to per-org+ // CreditAccount DOs, which debit balance + dispatch halt when it+ // hits zero. Without this the free-tier balance never decrements.+ // Inert unless CellID is set (combined-mode dev without Redis stream+ // would write events to /dev/null since there's no consumer).+ if cfg.CellID != "" && mgr != nil {+ usageTicker := worker.NewUsageTicker(mgr, sandboxDBMgr, 20*time.Second, 10)+ if usageTicker != nil {+ usageTicker.Start(context.Background())+ defer func() {+ stopCtx, stopCancel := context.WithTimeout(context.Background(), 3*time.Second)+ defer stopCancel()+ _ = usageTicker.Stop(stopCtx)+ }()+ log.Println("opensandbox-worker: usage ticker started (interval=20s, 10¢/tick)")+ }+ }+// Segment analytics — ships per-org GB-seconds memory usage. nil if SEGMENT_WRITE_KEY unset.segmentClient := analytics.New(cfg.SegmentWriteKey)if segmentClient != nil {@@ -1003,7 +1052,15 @@ func deleteOldHibernation(store *storage.CheckpointStore, key string) {}// processHibernateResults handles results from HibernateAll for both backends.-func processHibernateResults(results interface{}, store *db.Store, checkpointStore *storage.CheckpointStore, extract func(interface{}) (string, string, error)) {+//+// In addition to updating cell-local PG, we LogEvent("hibernated") into the+// per-sandbox SQLite then call sandboxDBs.Remove — the Remove hook flushes+// any unsynced events (including this one) to Redis Streams synchronously.+// events-ingest then mirrors the state to D1, keeping the dashboard list in+// sync. Without this, the bulk-shutdown path silently skipped the lifecycle+// event the gRPC HibernateSandbox handler emits per call, and D1 stayed+// "running" until something else nudged it.+func processHibernateResults(results interface{}, store *db.Store, checkpointStore *storage.CheckpointStore, sandboxDBs *sandbox.SandboxDBManager, extract func(interface{}) (string, string, error)) {switch rs := results.(type) {case []qm.HibernateAllResult:for _, r := range rs {@@ -1013,6 +1070,12 @@ func processHibernateResults(results interface{}, store *db.Store, checkpointStoerrMsg := "hibernate failed on shutdown: " + r.Err.Error()_ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "stopped", &errMsg)}+ if sandboxDBs != nil {+ if sdb, err := sandboxDBs.Get(r.SandboxID); err == nil {+ _ = sdb.LogEvent("stopped", map[string]string{"reason": "hibernate failed on shutdown"})+ }+ _ = sandboxDBs.Remove(r.SandboxID)+ }continue}log.Printf("opensandbox-worker: hibernated %s (key=%s)", r.SandboxID, r.HibernationKey)@@ -1025,6 +1088,12 @@ func processHibernateResults(results interface{}, store *db.Store, checkpointSto_ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "hibernated", nil)}}+ if sandboxDBs != nil {+ if sdb, err := sandboxDBs.Get(r.SandboxID); err == nil {+ _ = sdb.LogEvent("hibernated", map[string]string{"key": r.HibernationKey, "reason": "graceful_shutdown"})+ }+ _ = sandboxDBs.Remove(r.SandboxID)+ }}}}diff --git a/deploy/aws/create-aws-dev3.sh b/deploy/aws/create-aws-dev3.shindex 89bf6e19..9a15c606 100755--- a/deploy/aws/create-aws-dev3.sh+++ b/deploy/aws/create-aws-dev3.sh@@ -37,8 +37,18 @@ WK_NAME="${NAME_PREFIX}-worker-1"# Instance sizing — NVMe-equipped, cost-optimised for a dev testbedCP_TYPE="t3.medium" # 2 vCPU / 4GB / EBS only — postgres + redis + CP at dev scale-WK_TYPE="m6id.large" # 2 vCPU / 8GB / 118GB local NVMe — small worker for cross-region tests+WK_TYPE="c5d.metal" # 96 vCPU / 192GB / 4x900GB local NVMe — bare metal for nested KVM+ # (virtualized HVM instances like m6id.large can't expose /dev/kvm to+ # the guest, forcing QEMU into TCG software emulation. Only .metal+ # SKUs on AWS support nested virt, so the worker must be one of them.)WK_DATA_GB=128 # Additional persistent EBS volume mounted at /data+# Root EBS — must be generous enough that /var/cache/apt + /var/lib/containerd+# + journald + kernel updates don't fill it after a few days of uptime.+# 8GB default (AMI snapshot) is too small for a worker that runs Docker for+# rootfs builds; we observed root hitting 95% within ~48h and breaking+# `docker build` with disk-space errors. 30GB matches what production cells+# would use.+ROOT_GB=30# Ubuntu 24.04 LTS amd64 (latest from Canonical's account 099720109477) — overridableAMI_OWNER="099720109477"@@ -235,6 +245,7 @@ CPUD--security-group-ids "$SG_CP" \--associate-public-ip-address \--iam-instance-profile "Name=$ROLE_NAME" \+ --block-device-mappings "DeviceName=/dev/sda1,Ebs={VolumeSize=$ROOT_GB,VolumeType=gp3,DeleteOnTermination=true}" \--tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=$CP_NAME},{Key=opensandbox:role,Value=controlplane}]" \--user-data "$CP_USERDATA" \--query 'Instances[0].InstanceId' --output text)@@ -257,7 +268,9 @@ CPUD--security-group-ids "$SG_WK" \--associate-public-ip-address \--iam-instance-profile "Name=$ROLE_NAME" \- --block-device-mappings "DeviceName=/dev/sdb,Ebs={VolumeSize=$WK_DATA_GB,VolumeType=gp3,DeleteOnTermination=true}" \+ --block-device-mappings \+ "DeviceName=/dev/sda1,Ebs={VolumeSize=$ROOT_GB,VolumeType=gp3,DeleteOnTermination=true}" \+ "DeviceName=/dev/sdb,Ebs={VolumeSize=$WK_DATA_GB,VolumeType=gp3,DeleteOnTermination=true}" \--tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=$WK_NAME},{Key=opensandbox:role,Value=worker}]" \--query 'Instances[0].InstanceId' --output text)save_state "WK_ID" "$WK_ID"diff --git a/go.mod b/go.modindex 1a75b5a1..0eb073c2 100644--- a/go.mod+++ b/go.mod@@ -17,6 +17,7 @@ require (github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.41.2github.com/aws/aws-sdk-go-v2/service/ssm v1.68.4github.com/creack/pty v1.1.24+ github.com/fsnotify/fsnotify v1.10.1github.com/getsentry/sentry-go v0.46.0github.com/golang-jwt/jwt/v5 v5.3.0github.com/google/uuid v1.6.0@@ -61,7 +62,6 @@ require (github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirectgithub.com/cespare/xxhash/v2 v2.3.0 // indirectgithub.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect- github.com/fsnotify/fsnotify v1.10.1 // indirectgithub.com/golang-jwt/jwt v3.2.2+incompatible // indirectgithub.com/google/go-querystring v1.0.0 // indirectgithub.com/inconshreveable/mousetrap v1.1.0 // indirectdiff --git a/internal/api/admin_org.go b/internal/api/admin_org.gonew file mode 100644index 00000000..cc38ce37--- /dev/null+++ b/internal/api/admin_org.go@@ -0,0 +1,276 @@+package api++import (+ "context"+ "fmt"+ "log"+ "sync"+ "time"++ "github.com/google/uuid"+ "github.com/opensandbox/opensandbox/internal/controlplane"+ "github.com/opensandbox/opensandbox/internal/db"+ pb "github.com/opensandbox/opensandbox/proto/worker"+)++// Compile-time assertion that *Server satisfies the OrgHalter interface from+// the controlplane package. If the interface changes, this fails fast.+var _ controlplane.OrgHalter = (*Server)(nil)++// haltCoordinator dedupes concurrent halt webhooks for the same org. The DO+// retries on transient failure, and the halt_reconciler safety net may also+// fire a halt for the same org in the same ~30s window. We want each org to+// have at most one halt goroutine running at a time, so a redundant call+// short-circuits while the original finishes.+var (+ haltInFlight = struct {+ sync.Mutex+ m map[string]struct{}+ }{m: make(map[string]struct{})}+ resumeInFlight = struct {+ sync.Mutex+ m map[string]struct{}+ }{m: make(map[string]struct{})}+)++func acquireHaltSlot(orgID string) bool {+ haltInFlight.Lock()+ defer haltInFlight.Unlock()+ if _, busy := haltInFlight.m[orgID]; busy {+ return false+ }+ haltInFlight.m[orgID] = struct{}{}+ return true+}++func releaseHaltSlot(orgID string) {+ haltInFlight.Lock()+ defer haltInFlight.Unlock()+ delete(haltInFlight.m, orgID)+}++func acquireResumeSlot(orgID string) bool {+ resumeInFlight.Lock()+ defer resumeInFlight.Unlock()+ if _, busy := resumeInFlight.m[orgID]; busy {+ return false+ }+ resumeInFlight.m[orgID] = struct{}{}+ return true+}++func releaseResumeSlot(orgID string) {+ resumeInFlight.Lock()+ defer resumeInFlight.Unlock()+ delete(resumeInFlight.m, orgID)+}++// HaltOrg responds quickly (202-style — runs the actual hibernate work in a+// background goroutine) and returns the count of sandboxes the cell intends to+// halt. The DO doesn't need to block on every hibernate completing; the cell's+// halt_reconciler will re-issue the halt on the next tick if any sandboxes+// remain running, which keeps the system convergent without long DO calls.+//+// halt_reason='credits_exhausted' is stamped on each hibernated session so+// ResumeOrg can wake just those (and leave user-initiated hibernations alone).+func (s *Server) HaltOrg(ctx context.Context, orgIDStr, reason string) (int, error) {+ if s.store == nil {+ return 0, fmt.Errorf("database not configured")+ }+ if s.workerRegistry == nil {+ return 0, fmt.Errorf("worker registry not configured")+ }+ orgID, err := uuid.Parse(orgIDStr)+ if err != nil {+ return 0, fmt.Errorf("invalid org_id: %w", err)+ }++ // Mirror DO halt state to cell PG first — the wake handler reads this+ // column synchronously, so doing it before kicking off the async halt+ // closes the race where a wake arrives while the halt goroutine is+ // still iterating.+ if err := s.store.UpdateOrgHaltState(ctx, orgID, true); err != nil {+ // Non-fatal — log and continue. The reconciler will re-issue if needed.+ log.Printf("admin: halt-org %s: UpdateOrgHaltState failed: %v", orgIDStr, err)+ }++ sessions, err := s.store.ListSandboxSessions(ctx, orgID, "running", 1000, 0)+ if err != nil {+ return 0, fmt.Errorf("list running sessions: %w", err)+ }+ if len(sessions) == 0 {+ return 0, nil+ }++ if !acquireHaltSlot(orgIDStr) {+ // Another halt for this org is already in flight — short-circuit. The+ // running goroutine will hibernate everything visible at its start,+ // and the reconciler catches anything created in between.+ return len(sessions), nil+ }++ // Detach from the inbound HTTP context — caller (CF DO) is going to+ // return immediately, but the hibernate gRPC calls take 30s+ each and+ // we don't want them cancelled by the webhook's idle close.+ go func(sessions []db.SandboxSession) {+ defer releaseHaltSlot(orgIDStr)+ bgCtx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)+ defer cancel()+ for i := range sessions {+ sess := &sessions[i]+ if err := s.hibernateForHalt(bgCtx, sess.SandboxID, sess.WorkerID, sess.Region, sess.Template, sess.Config, orgID); err != nil {+ log.Printf("admin: halt-org %s: hibernate sandbox %s failed: %v (reason=%s)", orgIDStr, sess.SandboxID, err, reason)+ continue+ }+ if err := s.store.SetSandboxHaltReason(bgCtx, sess.SandboxID, "credits_exhausted"); err != nil {+ log.Printf("admin: halt-org %s: stamp halt_reason on %s failed: %v", orgIDStr, sess.SandboxID, err)+ }+ }+ }(sessions)++ return len(sessions), nil+}++// ResumeOrg clears the cell-local halt flag, then asynchronously wakes every+// sandbox the org has hibernated with halt_reason='credits_exhausted'. Manual+// hibernations (halt_reason IS NULL) stay hibernated — the user can wake them+// explicitly. skip_resume short-circuits the wake fan-out (useful when the+// DO just wants to mark the org as un-halted without auto-waking).+func (s *Server) ResumeOrg(ctx context.Context, orgIDStr string, skipResume bool) (int, error) {+ if s.store == nil {+ return 0, fmt.Errorf("database not configured")+ }+ if s.workerRegistry == nil {+ return 0, fmt.Errorf("worker registry not configured")+ }+ orgID, err := uuid.Parse(orgIDStr)+ if err != nil {+ return 0, fmt.Errorf("invalid org_id: %w", err)+ }++ if err := s.store.UpdateOrgHaltState(ctx, orgID, false); err != nil {+ log.Printf("admin: resume-org %s: UpdateOrgHaltState failed: %v", orgIDStr, err)+ }++ if skipResume {+ return 0, nil+ }++ sessions, err := s.store.ListSandboxSessionsByHaltReason(ctx, orgID, "credits_exhausted")+ if err != nil {+ return 0, fmt.Errorf("list halted sessions: %w", err)+ }+ if len(sessions) == 0 {+ return 0, nil+ }++ if !acquireResumeSlot(orgIDStr) {+ return len(sessions), nil+ }++ go func(sessions []db.SandboxSession) {+ defer releaseResumeSlot(orgIDStr)+ bgCtx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)+ defer cancel()+ for i := range sessions {+ sess := &sessions[i]+ if err := s.wakeForResume(bgCtx, sess.SandboxID); err != nil {+ log.Printf("admin: resume-org %s: wake sandbox %s failed: %v", orgIDStr, sess.SandboxID, err)+ continue+ }+ // Clear halt_reason — the sandbox is no longer credit-halted.+ if err := s.store.SetSandboxHaltReason(bgCtx, sess.SandboxID, ""); err != nil {+ log.Printf("admin: resume-org %s: clear halt_reason on %s failed: %v", orgIDStr, sess.SandboxID, err)+ }+ }+ }(sessions)++ return len(sessions), nil+}++// hibernateForHalt mirrors hibernateSandboxRemote but skips the auth check+// and runs without an echo.Context. Same gRPC + DB path; the DO webhook is+// the authorization.+func (s *Server) hibernateForHalt(ctx context.Context, sandboxID, workerID, region, template string, config []byte, orgID uuid.UUID) error {+ client, err := s.workerRegistry.GetWorkerClient(workerID)+ if err != nil {+ return fmt.Errorf("worker %s unreachable: %w", workerID, err)+ }+ grpcCtx, cancel := context.WithTimeout(ctx, 60*time.Second)+ defer cancel()+ grpcResp, err := client.HibernateSandbox(grpcCtx, &pb.HibernateSandboxRequest{SandboxId: sandboxID})+ if err != nil {+ return fmt.Errorf("grpc HibernateSandbox: %w", err)+ }+ _, superseded, _ := s.store.CreateHibernation(ctx, sandboxID, orgID, grpcResp.CheckpointKey, grpcResp.SizeBytes, region, template, config)+ s.deleteSupersededHibernation(superseded)+ _ = s.store.UpdateSandboxSessionStatus(ctx, sandboxID, "hibernated", nil)+ if s.sandboxAPIProxy != nil {+ s.sandboxAPIProxy.InvalidateRouteCache(sandboxID)+ }+ // Worker's HibernateSandbox handler emits the "hibernated" lifecycle event+ // + SandboxDBManager flushes it before SQLite is removed. events-ingest+ // updates D1 sandboxes_index from there.+ return nil+}++// wakeForResume mirrors wakeSandboxRemote but skips the wake-time credit+// gate (the whole point of resume is that the DO just decided the org is+// no longer halted) and runs without an echo.Context.+func (s *Server) wakeForResume(ctx context.Context, sandboxID string) error {+ hibernation, err := s.store.GetActiveHibernation(ctx, sandboxID)+ if err != nil {+ return fmt.Errorf("get active hibernation: %w", err)+ }+ session, err := s.store.GetSandboxSession(ctx, sandboxID)+ if err != nil {+ return fmt.Errorf("get session: %w", err)+ }+ if session.Status != "hibernated" {+ return fmt.Errorf("sandbox %s is not hibernated (status=%s)", sandboxID, session.Status)+ }++ region := hibernation.Region+ uploadComplete := hibernation.UploadedAt != nil+ var workerClient pb.SandboxWorkerClient+ var workerEntry *controlplane.WorkerEntry+ if session.WorkerID != "" {+ if src := s.workerRegistry.GetWorker(session.WorkerID); src != nil &&+ !src.Draining && src.CPUPct < 90 && src.MemPct < 90 && src.DiskPct < 90 {+ if cli, cerr := s.workerRegistry.GetWorkerClient(session.WorkerID); cerr == nil {+ workerEntry = src+ workerClient = cli+ }+ }+ }+ if workerEntry == nil {+ if !uploadComplete {+ return fmt.Errorf("source worker unavailable and hibernation upload not yet complete; retry shortly")+ }+ var lerr error+ workerEntry, workerClient, lerr = s.workerRegistry.GetLeastLoadedWorker(region)+ if lerr != nil {+ return fmt.Errorf("no workers available in region %s: %w", region, lerr)+ }+ }++ grpcCtx, cancel := context.WithTimeout(ctx, 60*time.Second)+ defer cancel()+ _, err = workerClient.WakeSandbox(grpcCtx, &pb.WakeSandboxRequest{+ SandboxId: sandboxID,+ CheckpointKey: hibernation.HibernationKey,+ })+ if err != nil {+ return fmt.Errorf("grpc WakeSandbox: %w", err)+ }+ _ = s.store.MarkHibernationRestored(ctx, sandboxID)+ _ = s.store.UpdateSandboxSessionForWake(ctx, sandboxID, workerEntry.ID)+ if workerEntry.GoldenVersion != "" {+ _ = s.store.SetSandboxGoldenVersion(ctx, sandboxID, workerEntry.GoldenVersion)+ }+ if s.sandboxAPIProxy != nil {+ s.sandboxAPIProxy.InvalidateRouteCache(sandboxID)+ }+ // Worker's WakeSandbox handler emits "woke"; events-ingest sets D1 to running.+ return nil+}diff --git a/internal/api/dashboard.go b/internal/api/dashboard.goindex 3faa4771..1a609754 100644--- a/internal/api/dashboard.go+++ b/internal/api/dashboard.go@@ -868,25 +868,29 @@ func (s *Server) dashboardPTYWebSocketRemote(c echo.Context, sandboxID, sessionIHandshakeTimeout: 10 * time.Second,}+ log.Printf("dashboard PTY: dialing worker %s", workerWSURL)workerWS, resp, err := dialer.Dial(workerWSURL, header)if err != nil {status := 0if resp != nil {status = resp.StatusCode}- log.Printf("dashboard: failed to dial worker PTY WebSocket %s (status=%d): %v", workerWSURL, status, err)+ log.Printf("dashboard PTY: failed to dial worker WebSocket %s (status=%d): %v", workerWSURL, status, err)return c.JSON(http.StatusBadGateway, map[string]string{"error": "failed to connect to worker terminal",})}defer workerWS.Close()+ log.Printf("dashboard PTY: worker WS dial OK for sandbox=%s session=%s", sandboxID, sessionID)// Upgrade the dashboard client connectionclientWS, err := upgrader.Upgrade(c.Response(), c.Request(), nil)if err != nil {+ log.Printf("dashboard PTY: client upgrade failed: %v", err)return err}defer clientWS.Close()+ log.Printf("dashboard PTY: client WS upgraded for sandbox=%s session=%s", sandboxID, sessionID)// Bidirectional pipe: dashboard ↔ workerdone := make(chan struct{}, 2)@@ -894,12 +898,21 @@ func (s *Server) dashboardPTYWebSocketRemote(c echo.Context, sandboxID, sessionI// worker → dashboardgo func() {defer func() { done <- struct{}{} }()+ var totalBytes int64+ var firstLogged boolfor {msgType, msg, err := workerWS.ReadMessage()if err != nil {+ log.Printf("dashboard PTY: worker→client closed (bytes=%d): %v", totalBytes, err)return}+ if !firstLogged {+ log.Printf("dashboard PTY: worker→client first msg type=%d len=%d", msgType, len(msg))+ firstLogged = true+ }+ totalBytes += int64(len(msg))if err := clientWS.WriteMessage(msgType, msg); err != nil {+ log.Printf("dashboard PTY: client write failed (forwarded %d bytes): %v", totalBytes, err)return}}@@ -908,12 +921,16 @@ func (s *Server) dashboardPTYWebSocketRemote(c echo.Context, sandboxID, sessionI// dashboard → workergo func() {defer func() { done <- struct{}{} }()+ var totalBytes int64for {msgType, msg, err := clientWS.ReadMessage()if err != nil {+ log.Printf("dashboard PTY: client→worker closed (bytes=%d): %v", totalBytes, err)return}+ totalBytes += int64(len(msg))if err := workerWS.WriteMessage(msgType, msg); err != nil {+ log.Printf("dashboard PTY: worker write failed (forwarded %d bytes): %v", totalBytes, err)return}}diff --git a/internal/api/internal_sandbox.go b/internal/api/internal_sandbox.goindex 73a08822..083ae9e3 100644--- a/internal/api/internal_sandbox.go+++ b/internal/api/internal_sandbox.go@@ -37,6 +37,21 @@ func (s *Server) capTokenMiddleware(next echo.HandlerFunc) echo.HandlerFunc {})}c.Set(capClaimsKey, claims)+ // Set the standard auth context fields too — dashboard handlers (and+ // many others) call auth.GetOrgID(c) / c.Get("user_id") rather than+ // digging out the cap-claims directly. internalCreateSandbox sets+ // these itself for back-compat (the original capTokenMiddleware did+ // not set them), but every other capTokenMiddleware-gated route+ // would 401 without this — including the /internal/dashboard/*+ // routes the api-edge proxies to.+ if orgID, perr := uuid.Parse(claims.OrgID); perr == nil {+ auth.SetOrgID(c, orgID)+ }+ if claims.UserID != nil {+ if uid, perr := uuid.Parse(*claims.UserID); perr == nil {+ auth.SetUserID(c, uid)+ }+ }return next(c)}}@@ -63,6 +78,30 @@ func (s *Server) internalCreateSandbox(c echo.Context) error {}}+ // Ensure the cell-local orgs row exists. The edge is authoritative on+ // org identity (it just minted this cap-token), so we trust the claims+ // and lazily materialize the row here. Plan comes from the cap-token so+ // the worker's event resolver can tag usage_tick events correctly.+ if s.store != nil {+ if upErr := s.store.UpsertOrgFromCapToken(c.Request().Context(), orgID, claims.Plan); upErr != nil {+ // Non-fatal — the create may still succeed; downstream gates fall through+ // when the row is missing. Logged so ops can investigate persistent failures.+ c.Logger().Errorf("upsert org from cap-token: %v", upErr)+ }+ // Also upsert the user. sandbox_sessions.user_id has an FK to users(id),+ // so without this the session insert in createSandboxRemote silently+ // fails (the errors are discarded with `_, _ =`) and the sandbox ends+ // up only in D1 sandboxes_index — never in cell PG, so subsequent+ // exec/wake/etc requests return "sandbox not found".+ if claims.UserID != nil {+ if uid, err := uuid.Parse(*claims.UserID); err == nil {+ if upErr := s.store.UpsertUserFromCapToken(c.Request().Context(), uid, orgID); upErr != nil {+ c.Logger().Errorf("upsert user from cap-token: %v", upErr)+ }+ }+ }+ }+var cfg types.SandboxConfigif err := c.Bind(&cfg); err != nil {return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})@@ -80,9 +119,21 @@ func (s *Server) internalCreateSandbox(c echo.Context) error {return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})}+ // Resolve secret store binding (if cfg.SecretStore is set). The edge-first+ // path puts the user's POST /api/sandboxes body through this handler+ // verbatim, so any caller passing {"secretStore": "<name>"} expects it to+ // be resolved here. resolveSecretStoreInto consults the edge over HMAC+ // when s.edge is configured, decrypts entries with the shared key, and+ // populates cfg.SecretEnvs + cfg.EgressAllowlist. Pre-fix this was nil,+ // silently dropping the binding and leaving sandboxes without their+ // requested secrets.+ secretStoreID, err := s.resolveSecretStoreInto(c.Request().Context(), orgID, &cfg)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})+ }+// Reuse the normal remote-create path — picks a worker, dispatches via// gRPC, persists the session, writes the {sandboxID, token, status, ...}- // response body. secretStoreID is nil here — cap-token callers don't- // reference an org-uploaded secret store (that's a /api/sandboxes feature).- return s.createSandboxRemote(c, c.Request().Context(), cfg, orgID, true, nil)+ // response body.+ return s.createSandboxRemote(c, c.Request().Context(), cfg, orgID, true, secretStoreID)}diff --git a/internal/api/router.go b/internal/api/router.goindex f9995605..c492d1ea 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -22,6 +22,7 @@ import ("github.com/opensandbox/opensandbox/internal/cloudflare""github.com/opensandbox/opensandbox/internal/controlplane""github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/internal/edgeclient""github.com/opensandbox/opensandbox/internal/metrics""github.com/opensandbox/opensandbox/internal/observability""github.com/opensandbox/opensandbox/internal/obslog"@@ -43,6 +44,8 @@ type Server struct {store *db.Store // nil in combined/dev mode without PGjwtIssuer *auth.JWTIssuer // nil if JWT not configuredcapTokenIssuer *auth.JWTIssuer // verifies edge→CP capability tokens; nil if SESSION_JWT_SECRET unset+ cfAdminSecret string // HMAC shared with CreditAccount DO for /admin/halt-org and /admin/resume-org; empty disables auth (dev only)+ cfEventSecret string // HMAC shared with the api-edge Worker for /internal/secret-refresh and other edge-→cell push pathscellID string // this control plane's cell_id (for the cap-token cell check)mode string // "server", "worker", "combined"workerID string // this worker's ID@@ -66,6 +69,18 @@ type Server struct {// Empty token = endpoint returns 503.axiomQueryToken stringaxiomDataset string++ // CF api-edge HTTP client — HMAC-signed calls to /internal/templates and+ // /internal/secret-stores. nil when the edge isn't configured (legacy+ // single-PG mode or tests); resolveSecretStoreInto + template lookup fall+ // back to s.store in that case.+ edge *edgeclient.Client+}++// SetEdgeClient wires the api-edge HTTP client. Caller is responsible for+// constructing it with the right base URL + HMAC secret (CFEventSecret).+func (s *Server) SetEdgeClient(c *edgeclient.Client) {+ s.edge = c}// SetAxiomQueryConfig wires the read-only Axiom token and dataset for@@ -87,6 +102,8 @@ type ServerOpts struct {Store *db.StoreJWTIssuer *auth.JWTIssuerSessionJWTSecret string // shared edge↔CP HMAC secret; enables /internal/sandboxes/create+ CFAdminSecret string // HMAC shared with CF CreditAccount DO; enables /admin/halt-org and /admin/resume-org+ CFEventSecret string // HMAC shared with the api-edge Worker; enables /internal/secret-refresh and other edge-→cell push pathsCellID string // this control plane's cell_idMode string // "server", "worker", "combined"WorkerID string@@ -125,6 +142,8 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oif opts.SessionJWTSecret != "" {s.capTokenIssuer = auth.NewJWTIssuer(opts.SessionJWTSecret)}+ s.cfAdminSecret = opts.CFAdminSecret+ s.cfEventSecret = opts.CFEventSecrets.cellID = opts.CellIDs.mode = opts.Modes.workerID = opts.WorkerID@@ -262,11 +281,74 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oif s.capTokenIssuer != nil && s.workerRegistry != nil {internal := e.Group("/internal", s.capTokenMiddleware)internal.POST("/sandboxes/create", s.internalCreateSandbox)++ // Edge-proxied dashboard routes. Same handler functions as+ // /api/dashboard/* (gated below by WorkOS session cookie), exposed+ // under /internal/dashboard/* gated by the edge's cap-token instead.+ // This lets api-edge forward sandbox-runtime ops (PTY, stats, reboot,+ // logs) without requiring users to have a WorkOS cookie on every cell.+ //+ // The dashboard handlers read auth via auth.GetOrgID(c), which both+ // middlewares set — so the same functions work under either auth+ // chain. We only mount the sandbox-runtime subset here; the data-+ // authority routes (api-keys, org settings, checkpoints list) belong+ // on the edge proper, where D1 is the source of truth.+ idash := internal.Group("/dashboard")+ idash.GET("/sessions/:sandboxId", s.dashboardGetSession)+ idash.GET("/sessions/:sandboxId/stats", s.dashboardGetSessionStats)+ idash.POST("/sessions/:sandboxId/reboot", s.dashboardRebootSession)+ idash.POST("/sessions/:sandboxId/power-cycle", s.dashboardPowerCycleSession)+ idash.POST("/sessions/:sandboxId/pty", s.dashboardCreatePTY)+ idash.GET("/sessions/:sandboxId/pty/:sessionId", s.dashboardPTYWebSocket)+ idash.POST("/sessions/:sandboxId/pty/:sessionId/resize", s.dashboardResizePTY)+ idash.DELETE("/sessions/:sandboxId/pty/:sessionId", s.dashboardKillPTY)+ // /images is cell-local (image_cache table lives in each cell's PG).+ // Proxy these here so dashboard can render per-cell image lists.+ idash.GET("/images", s.dashboardListImages)+ idash.DELETE("/images/:id", s.dashboardDeleteImage)+ // Agents — currently proxied to an external service from each cell.+ // Easier to keep that wiring intact than reimplement on the edge.+ idash.Any("/agents", s.dashboardAgentsProxy)+ idash.Any("/agents/*", s.dashboardAgentsProxy)+ idash.GET("/agents/:agentId/entitlements", s.dashboardListAgentEntitlements)+ idash.POST("/agents/:agentId/subscriptions/:feature", s.dashboardSubscribeAgentFeature)+ idash.DELETE("/agents/:agentId/subscriptions/:feature", s.dashboardCancelAgentFeature)+ idash.GET("/sessions/:sandboxId/logs", s.getSandboxLogs)+ }++ // CF admin webhooks — dispatched by the CreditAccount DO on free-tier+ // halt/resume events. HMAC-authenticated via the shared CF_ADMIN_SECRET.+ // Routes live under /admin/ to match the DO's hard-coded path, but use a+ // distinct middleware chain from the human-API-key /admin group above.+ // Echo treats route registrations independently — there's no conflict.+ //+ // Only mounted when this CP can actually halt sandboxes (workers registry+ // present); a server-only CP without workers has no work to do here.+ if s.workerRegistry != nil {+ if s.cfAdminSecret == "" {+ log.Printf("api: WARNING: CF admin webhooks mounted without CF_ADMIN_SECRET — anyone can halt/resume orgs. Set OPENSANDBOX_CF_ADMIN_SECRET in production.")+ }+ cfAdmin := e.Group("/admin", controlplane.AdminAuth(s.cfAdminSecret))+ ah := controlplane.NewAdminHandlers(s)+ cfAdmin.POST("/halt-org", ah.HaltOrg)+ cfAdmin.POST("/resume-org", ah.ResumeOrg)+ }++ // Edge-→cell push: secret-refresh fan-in. The api-edge Worker posts here+ // after writing a new secret entry to D1 so this cell can update any+ // running sandboxes that bind the store. HMAC-authenticated with the+ // shared event secret (same one the forwarder uses, same one the edge+ // signs internal lookups with). Mounted only when both a workerRegistry+ // exists (otherwise there's nothing to fan out to) AND the event secret+ // is configured.+ if s.workerRegistry != nil && s.cfEventSecret != "" {+ cfEdge := e.Group("/internal", controlplane.AdminAuth(s.cfEventSecret))+ cfEdge.POST("/secret-refresh", s.internalSecretRefresh)}// API routes (with API key auth)api := e.Group("/api")- api.Use(auth.PGAPIKeyMiddleware(s.store, apiKey, s.jwtIssuer))+ api.Use(auth.PGAPIKeyMiddleware(s.store, apiKey, s.jwtIssuer, s.capTokenIssuer, s.cellID))// Identityapi.POST("/auth/token", s.createAuthToken)diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 64e35dd2..22190eb3 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -3,6 +3,7 @@ package apiimport ("context""encoding/json"+ "errors""fmt""log""net/http"@@ -14,6 +15,7 @@ import ("github.com/opensandbox/opensandbox/internal/auth""github.com/opensandbox/opensandbox/internal/controlplane""github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/internal/edgeclient""github.com/opensandbox/opensandbox/pkg/types"pb "github.com/opensandbox/opensandbox/proto/worker")@@ -324,7 +326,30 @@ func (s *Server) createSandboxWithSSE(c echo.Context, ctx context.Context, orgID// secret_store_id gets populated — required for the secret-refresh fanout// (ListRunningSandboxesByStore filters on this column).func (s *Server) resolveSecretStoreInto(ctx context.Context, orgID [16]byte, cfg *types.SandboxConfig) (*uuid.UUID, error) {- if cfg.SecretStore == "" || s.store == nil {+ if cfg.SecretStore == "" {+ return nil, nil+ }++ // Edge-first path. With migration 041 the per-cell PG no longer holds+ // `secret_stores`/`secret_store_entries`, so when s.edge is configured we+ // fetch the bundle from D1 over HMAC and decrypt locally with the shared+ // SECRET_ENCRYPTION_KEY (same key the edge used to encrypt).+ if s.edge != nil && s.store != nil && s.store.Encryptor() != nil {+ bundle, err := s.edge.LookupSecretStore(ctx, uuid.UUID(orgID), cfg.SecretStore, s.store.Encryptor())+ if err != nil {+ if errors.Is(err, edgeclient.ErrNotFound) {+ return nil, fmt.Errorf("secret store not found: %s", cfg.SecretStore)+ }+ return nil, fmt.Errorf("edge lookup secret store %q: %w", cfg.SecretStore, err)+ }+ applySecretBundle(cfg, bundle)+ return &bundle.Store.ID, nil+ }++ // Legacy single-PG path — retained while the edge isn't wired (combined+ // dev mode, tests). Deleted once migration 041 is the only deployed+ // shape.+ if s.store == nil {return nil, nil}store, err := s.store.GetSecretStoreByName(ctx, orgID, cfg.SecretStore)@@ -356,6 +381,57 @@ func (s *Server) resolveSecretStoreInto(ctx context.Context, orgID [16]byte, cfgreturn &store.ID, nil}+// resolveTemplate is the edge-first equivalent of the inline+// `s.store.GetTemplateByName` call createSandbox used to do. Same return+// shape (the existing db.DBTemplate); same semantics (org-scoped first,+// public fallback). Returns (nil, nil) when no template name was supplied+// or no source is configured — caller should treat that as "no template".+func (s *Server) resolveTemplate(ctx context.Context, orgID [16]byte, hasOrg bool, name string) (*db.DBTemplate, error) {+ if name == "" {+ return nil, nil+ }+ if s.edge != nil {+ var oid uuid.UUID+ if hasOrg {+ oid = uuid.UUID(orgID)+ }+ t, err := s.edge.LookupTemplate(ctx, oid, name)+ if err != nil {+ if errors.Is(err, edgeclient.ErrNotFound) {+ return nil, nil+ }+ return nil, err+ }+ return t, nil+ }+ if s.store == nil || !hasOrg {+ return nil, nil+ }+ return s.store.GetTemplateByName(ctx, orgID, name)+}++// applySecretBundle is the shared post-processing step both the edge and+// legacy paths feed cfg through: copy egress allowlist + per-entry host+// restrictions + plaintext values into the sandbox config.+func applySecretBundle(cfg *types.SandboxConfig, bundle *edgeclient.SecretStoreBundle) {+ cfg.EgressAllowlist = bundle.Store.EgressAllowlist+ if len(bundle.Entries) == 0 {+ return+ }+ if cfg.SecretEnvs == nil {+ cfg.SecretEnvs = make(map[string]string, len(bundle.Entries))+ }+ for _, secret := range bundle.Entries {+ cfg.SecretEnvs[secret.Name] = secret.Value+ if len(secret.AllowedHosts) > 0 {+ if cfg.SecretAllowedHosts == nil {+ cfg.SecretAllowedHosts = make(map[string][]string)+ }+ cfg.SecretAllowedHosts[secret.Name] = secret.AllowedHosts+ }+ }+}+// cfgForPersistence returns a copy of cfg suitable for marshaling into PG// (cp.SandboxConfig / sandbox_sessions.config_json).//@@ -441,22 +517,22 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg tylog.Printf("sandbox: worker became available after queuing (region=%s)", region)}- // Resolve template from DB (org-scoped lookup with public fallback)+ // Resolve template (org-scoped lookup with public fallback).+ // Edge-first when s.edge is configured (post-migration 041), local PG+ // otherwise. Same return shape so the rest of the create flow doesn't+ // care which path produced it.var templateRootfsKey, templateWorkspaceKey stringvar templateID *uuid.UUID- if s.store != nil && hasOrg {- tmpl, err := s.store.GetTemplateByName(ctx, orgID, cfg.Template)- if err == nil {- templateID = &tmpl.ID- log.Printf("sandbox: resolved template %q (type=%s, id=%s)", cfg.Template, tmpl.TemplateType, tmpl.ID)- // Sandbox-type templates provide S3 drive keys instead of ECR image refs- if tmpl.TemplateType == "sandbox" && tmpl.RootfsS3Key != nil && tmpl.WorkspaceS3Key != nil {- templateRootfsKey = *tmpl.RootfsS3Key- templateWorkspaceKey = *tmpl.WorkspaceS3Key- log.Printf("sandbox: using snapshot template drives: rootfs=%s, workspace=%s", templateRootfsKey, templateWorkspaceKey)- }- } else {- log.Printf("sandbox: template %q lookup failed: %v", cfg.Template, err)+ tmpl, err := s.resolveTemplate(ctx, orgID, hasOrg, cfg.Template)+ if err != nil {+ log.Printf("sandbox: template %q lookup failed: %v", cfg.Template, err)+ } else if tmpl != nil {+ templateID = &tmpl.ID+ log.Printf("sandbox: resolved template %q (type=%s, id=%s)", cfg.Template, tmpl.TemplateType, tmpl.ID)+ if tmpl.TemplateType == "sandbox" && tmpl.RootfsS3Key != nil && tmpl.WorkspaceS3Key != nil {+ templateRootfsKey = *tmpl.RootfsS3Key+ templateWorkspaceKey = *tmpl.WorkspaceS3Key+ log.Printf("sandbox: using snapshot template drives: rootfs=%s, workspace=%s", templateRootfsKey, templateWorkspaceKey)}}@@ -762,6 +838,10 @@ func (s *Server) killSandboxRemote(c echo.Context, sandboxID string) error {}s.emitEvent("destroy", sandboxID, session.WorkerID, "destroyed")+ // Note: the worker emits the "stopped" lifecycle event via sdb.LogEvent+ // in its DestroySandbox handler, and the SandboxDBManager.OnRemove hook+ // synchronously flushes it to Redis before the per-sandbox SQLite is+ // removed. events-ingest sees that event and updates D1 sandboxes_index.return c.NoContent(http.StatusNoContent)}@@ -1641,6 +1721,9 @@ func (s *Server) hibernateSandboxRemote(c echo.Context, sandboxID string) error"sizeBytes": grpcResp.SizeBytes,}+ // Worker emits the "hibernated" lifecycle event before removing the+ // per-sandbox SQLite — events-ingest picks it up and updates D1.+return c.JSON(http.StatusOK, resp)}@@ -1651,14 +1734,18 @@ func (s *Server) wakeSandbox(c echo.Context) error {var req types.WakeRequest_ = c.Bind(&req)- // Free-tier credits gate: refuse to wake if trial credits are exhausted.+ // Credit gate: refuse to wake when the org is halted. The CreditAccount+ // DO is authoritative; `is_halted` is the cell-local mirror set by the+ // /admin/halt-org webhook handler. Pro orgs are never halted by credits,+ // so checking is_halted naturally lets them through. Falls through if+ // the org row doesn't exist locally (new app2 user with no backfill) —+ // the edge already gated on D1's is_halted before this request was+ // routed to us, so a missing row means the edge said yes.if orgID, ok := auth.GetOrgID(c); ok && s.store != nil {- if org, err := s.store.GetOrg(ctx, orgID); err == nil {- if org.Plan == "free" && org.FreeCreditsRemainingCents <= 0 {- return c.JSON(http.StatusPaymentRequired, map[string]string{- "error": "free trial credits exhausted — upgrade to pro to resume sandboxes",- })- }+ if org, err := s.store.GetOrg(ctx, orgID); err == nil && org.IsHalted {+ return c.JSON(http.StatusPaymentRequired, map[string]string{+ "error": "org is halted — upgrade to pro or wait for credit refill",+ })}}@@ -1819,6 +1906,9 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.Ws.sandboxAPIProxy.InvalidateRouteCache(sandboxID)}+ // Worker emits the "woke" lifecycle event in its WakeSandbox handler;+ // events-ingest flips D1 sandboxes_index back to running.+// Apply pending checkpoint patches in backgroundgo s.applyPendingPatches(sandboxID, worker.ID)diff --git a/internal/api/secret_refresh.go b/internal/api/secret_refresh.gonew file mode 100644index 00000000..3ca7d519--- /dev/null+++ b/internal/api/secret_refresh.go@@ -0,0 +1,68 @@+package api++import (+ "encoding/base64"+ "net/http"++ "github.com/google/uuid"+ "github.com/labstack/echo/v4"+)++// internalSecretRefresh is the edge-side fan-in for secret-store updates.+//+// When a user PUTs a new value via /api/secret-stores/{id}/secrets/{name} on+// the edge, the edge writes the encrypted blob to D1 (single source of truth)+// and then HMAC-POSTs this endpoint on every active cell. Each cell asks its+// LOCAL Postgres which running sandboxes bind that store+// (sandbox_sessions.secret_store_id), then runs the existing in-cell gRPC+// fan-out (fanoutSecretRefresh) to push the new value to each affected+// worker. So no sandbox restart needed for a secret change.+//+// Wire format mirrors /internal/secret-stores/by-name on the edge: the value+// arrives as base64(nonce || ciphertext+tag), encrypted with the shared+// SECRET_ENCRYPTION_KEY. The CP decrypts locally before gRPC'ing to workers.+// Plaintext never crosses the cell boundary.+//+// HMAC: AdminAuth middleware in router.go verifies "{X-Timestamp}.{body}"+// signed with CFEventSecret (shared with edge). The endpoint is idempotent+// at the worker level (UpdateSandboxSecret on a sandbox with no matching+// session returns updated=false, not an error) so duplicate deliveries are+// safe.+func (s *Server) internalSecretRefresh(c echo.Context) error {+ var req struct {+ StoreID string `json:"storeId"`+ Name string `json:"name"`+ EncryptedValueB64 string `json:"encryptedValueB64"`+ }+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request"})+ }+ if req.StoreID == "" || req.Name == "" || req.EncryptedValueB64 == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "storeId, name, encryptedValueB64 required"})+ }+ storeID, err := uuid.Parse(req.StoreID)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid storeId"})+ }+ if s.store == nil || s.store.Encryptor() == nil {+ // No encryptor means this cell can't decrypt. Surface as 503 so the+ // edge marks this cell as a failure but doesn't mistake it for a+ // permanent rejection.+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "encryptor not configured"})+ }++ ct, err := base64.StdEncoding.DecodeString(req.EncryptedValueB64)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid base64"})+ }+ pt, err := s.store.Encryptor().Decrypt(ct)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "decrypt failed (key mismatch?)"})+ }++ refreshed, failures := s.fanoutSecretRefresh(c.Request().Context(), storeID, req.Name, string(pt))+ return c.JSON(http.StatusOK, map[string]any{+ "refreshed": refreshed,+ "failures": failures,+ })+}diff --git a/internal/auth/jwt.go b/internal/auth/jwt.goindex e418be29..c7d29981 100644--- a/internal/auth/jwt.go+++ b/internal/auth/jwt.go@@ -137,15 +137,25 @@ type CapabilityClaims struct {OrgID string `json:"org_id"`CellID string `json:"cell_id"`UserID *string `json:"user_id,omitempty"`+ // Plan is the org's billing plan ("free" | "pro") at token-mint time.+ // The CP forwards this to the worker so it can tag usage_tick events+ // without a per-event PG lookup. Plan may go stale (org upgrades while+ // a sandbox is running) — that's fine: the events-ingest fan-out is+ // idempotent, and the DO knows the current plan from D1 so it no-ops+ // debits for a now-pro org.+ Plan string `json:"plan,omitempty"`}// CapabilityIssuer is the Issuer string on capability tokens — lets the CP// reject a session JWT presented where a capability token is expected.const CapabilityIssuer = "opensandbox-edge"-// IssueCapabilityToken mints a capability token for (orgID, cellID). userID may-// be nil (API-key-authenticated callers have no user).-func (j *JWTIssuer) IssueCapabilityToken(orgID, cellID string, userID *string, ttl time.Duration) (string, error) {+// IssueCapabilityToken mints a capability token for (orgID, cellID, plan).+// userID may be nil (API-key-authenticated callers have no user). plan may+// be empty when the caller doesn't have it handy — the cell will then+// fall back to a PG lookup, which is a small performance hit but never+// incorrect.+func (j *JWTIssuer) IssueCapabilityToken(orgID, cellID, plan string, userID *string, ttl time.Duration) (string, error) {now := time.Now()claims := CapabilityClaims{RegisteredClaims: jwt.RegisteredClaims{@@ -157,6 +167,7 @@ func (j *JWTIssuer) IssueCapabilityToken(orgID, cellID string, userID *string, tOrgID: orgID,CellID: cellID,UserID: userID,+ Plan: plan,}token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)return token.SignedString(j.secret)diff --git a/internal/auth/middleware.go b/internal/auth/middleware.goindex c6a01ab1..0a6166ef 100644--- a/internal/auth/middleware.go+++ b/internal/auth/middleware.go@@ -54,12 +54,18 @@ func GetUserID(c echo.Context) *uuid.UUID {// PGAPIKeyMiddleware validates API keys against PostgreSQL.// Falls back to static API key comparison if store is nil (combined/dev mode).//-// Also accepts an identity JWT (aud=opencomputer-api) when jwtIssuer is non-nil.-// The JWT can arrive either in `Authorization: Bearer <jwt>` or as the X-API-Key-// value (JWTs are detected by the two-dot signature: "header.payload.signature").-// This lets sessions-api act on behalf of a dashboard user without holding a-// long-lived API key — see internal/auth/jwt.go for the audience constants.-func PGAPIKeyMiddleware(store *db.Store, staticKey string, jwtIssuer *JWTIssuer) echo.MiddlewareFunc {+// Also accepts:+// - Identity JWT (aud=opencomputer-api) signed by jwtIssuer (used by+// sessions-api when acting on behalf of a dashboard user — see jwt.go+// for the audience constants);+// - Capability JWT (iss=opensandbox-edge) signed by capTokenIssuer when+// present. The api-edge Worker mints these on the SDK proxy path so it+// doesn't need to mirror per-org API keys to every cell. cellID in the+// claims must match this CP's own cell for the token to be accepted.+//+// The JWT can arrive in `Authorization: Bearer <jwt>` or as the X-API-Key+// value (detected by the two-dot signature pattern).+func PGAPIKeyMiddleware(store *db.Store, staticKey string, jwtIssuer *JWTIssuer, capTokenIssuer *JWTIssuer, cellID string) echo.MiddlewareFunc {return func(next echo.HandlerFunc) echo.HandlerFunc {return func(c echo.Context) error {// Try static API key first (backward compat for combined mode)@@ -78,6 +84,34 @@ func PGAPIKeyMiddleware(store *db.Store, staticKey string, jwtIssuer *JWTIssuer)}}+ // Capability-token path: edge-minted JWT (iss=opensandbox-edge).+ // Cell must match the token's cell_id; this guards against a+ // token minted for cell A being replayed against cell B.+ if capTokenIssuer != nil {+ authHeader := c.Request().Header.Get("Authorization")+ if strings.HasPrefix(authHeader, "Bearer ") {+ tokenStr := strings.TrimPrefix(authHeader, "Bearer ")+ if claims, err := capTokenIssuer.ValidateCapabilityToken(tokenStr); err == nil {+ if cellID != "" && claims.CellID != cellID {+ return c.JSON(http.StatusForbidden, map[string]string{+ "error": "capability token is for cell " + claims.CellID + ", this is " + cellID,+ })+ }+ orgID, err := uuid.Parse(claims.OrgID)+ if err != nil {+ return c.JSON(http.StatusForbidden, map[string]string{"error": "capability token: invalid org_id"})+ }+ SetOrgID(c, orgID)+ if claims.UserID != nil {+ if uid, err := uuid.Parse(*claims.UserID); err == nil {+ SetUserID(c, uid)+ }+ }+ return next(c)+ }+ }+ }+// Get API key from header or querykey := c.Request().Header.Get("X-API-Key")if key == "" {diff --git a/internal/billing/usage_reporter.go b/internal/billing/usage_reporter.goindex 7c247cee..bd8ed02e 100644--- a/internal/billing/usage_reporter.go+++ b/internal/billing/usage_reporter.go@@ -24,6 +24,13 @@ type UsageReporter struct {interval time.Durationstop chan struct{}stopped chan struct{}++ // cfBillingEnabled disables the free-tier deduction pass (and eventually+ // the pro Stripe meter pass) when CF-edge billing is the authority. The+ // CreditAccount DO debits free orgs based on events-ingest fan-out; if+ // we also debited here we'd double-charge. Set via SetCFBillingMode at+ // startup based on OPENSANDBOX_CF_EVENT_ENDPOINT being non-empty.+ cfBillingEnabled bool}func NewUsageReporter(store *db.Store, stripe *StripeClient, workers WorkerClientSource) *UsageReporter {@@ -37,6 +44,17 @@ func NewUsageReporter(store *db.Store, stripe *StripeClient, workers WorkerClien}}+// SetCFBillingMode flips this reporter to CF-billing mode. In that mode the+// free-tier deduction pass is skipped because the CF CreditAccount DO is+// authoritative — it debits free orgs based on events-ingest /debit fan-out.+// The pro-tier Stripe pass currently still runs (cells emit billable_events+// and the reporter ships them to Stripe meters); once the unified-events+// billing sender is deployed end-to-end on CF too, that pass can also be+// gated here.+func (r *UsageReporter) SetCFBillingMode(enabled bool) {+ r.cfBillingEnabled = enabled+}+func (r *UsageReporter) Start() { go r.loop() }func (r *UsageReporter) Stop() { close(r.stop); <-r.stopped }@@ -84,6 +102,12 @@ func (r *UsageReporter) reportAll() {}// Free-tier pass: deduct the same usage from trial credits; hibernate on empty.+ // SKIPPED when CF billing is enabled — the CreditAccount DO is the authority+ // and debits free orgs via events-ingest /debit fan-out. Running both would+ // double-debit, which makes free trials end ~2x faster than the user expects.+ if r.cfBillingEnabled {+ return+ }freeIDs, err := r.store.ListFreeOrgIDsWithOpenUsage(ctx)if err != nil {log.Printf("usage-reporter: failed to list free orgs: %v", err)diff --git a/internal/config/config.go b/internal/config/config.goindex e22560da..8a314487 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -212,6 +212,13 @@ type Config struct {// to catch missed halt webhooks. Empty disables the reconciler.HaltListURL string+ // CF edge base URL — root of the api-edge Worker (e.g.+ // "https://app.dev.opensandbox.ai"). Used to construct /internal/*+ // HMAC endpoints for stateless template + secret-store lookup at+ // sandbox-create time. HMAC secret is CFEventSecret (same one used+ // for the event forwarder + halt-list).+ CFEdgeBaseURL string+// Multi-cloud abstraction. Selects which compute pool the autoscaler uses.// Valid values: "azure", "aws", "" (autodetect from existing fields).// Adding a new cloud means a new compute.Pool implementation + a new@@ -372,6 +379,7 @@ func Load() (*Config, error) {CFAdminSecret: os.Getenv("OPENSANDBOX_CF_ADMIN_SECRET"),SessionJWTSecret: os.Getenv("OPENSANDBOX_SESSION_JWT_SECRET"),HaltListURL: os.Getenv("OPENSANDBOX_HALT_LIST_URL"),+ CFEdgeBaseURL: os.Getenv("OPENSANDBOX_CF_EDGE_BASE_URL"),ComputeProvider: os.Getenv("OPENSANDBOX_COMPUTE_PROVIDER"),SecretsProvider: envOrDefault("OPENSANDBOX_SECRETS_PROVIDER", "env"),diff --git a/internal/config/keyvault.go b/internal/config/keyvault.goindex 2f687939..2d4b7aab 100644--- a/internal/config/keyvault.go+++ b/internal/config/keyvault.go@@ -73,6 +73,7 @@ var kvMapping = map[string]string{"server-cf-event-secret": "OPENSANDBOX_CF_EVENT_SECRET","server-cf-admin-secret": "OPENSANDBOX_CF_ADMIN_SECRET","server-session-jwt-secret": "OPENSANDBOX_SESSION_JWT_SECRET",+ "server-halt-list-url": "OPENSANDBOX_HALT_LIST_URL",// Worker secrets"worker-jwt-secret": "OPENSANDBOX_JWT_SECRET",@@ -146,6 +147,14 @@ var kvMapping = map[string]string{// the Go binary reads it from cfg.CellID (which falls back to// "<region>-default" when this isn't in KV — see config.go)."shared-cell-id": "OPENSANDBOX_CELL_ID",++ // Edge integration (mode-agnostic — both server and worker need them).+ // cf-edge-base-url is consumed by the CP's edgeclient for HMAC'd+ // /internal/templates + /internal/secret-stores lookups; secret-encryption-key+ // is the AES-256-GCM key shared with the api-edge Worker so the edge can+ // encrypt secret-store entries and any cell can decrypt them.+ "shared-cf-edge-base-url": "OPENSANDBOX_CF_EDGE_BASE_URL",+ "shared-secret-encryption-key": "OPENSANDBOX_SECRET_ENCRYPTION_KEY",}// LoadSecretsFromKeyVault fetches secrets from Azure Key Vault and sets themdiff --git a/internal/controlplane/admin_handlers.go b/internal/controlplane/admin_handlers.goindex 7effaa04..44012555 100644--- a/internal/controlplane/admin_handlers.go+++ b/internal/controlplane/admin_handlers.go@@ -1,70 +1,182 @@package controlplaneimport (+ "context"+ "crypto/hmac"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "io"+ "log""net/http"+ "strconv"+ "time""github.com/labstack/echo/v4")-// AdminHandlers implements /admin/halt-org and /admin/resume-org.-// Both are HMAC-authenticated webhooks dispatched from the CreditAccount-// Durable Object on Cloudflare.+// OrgHalter is the cell-local entry point for halting and resuming all of+// an org's sandboxes. Implemented by *api.Server (so the existing hibernate /+// wake code paths are reused); kept as an interface here to avoid a circular+// import between the api and controlplane packages.+type OrgHalter interface {+ HaltOrg(ctx context.Context, orgID, reason string) (halted int, err error)+ ResumeOrg(ctx context.Context, orgID string, skipResume bool) (resumed int, err error)+}++// AdminHandlers implements /admin/halt-org and /admin/resume-org. Both are+// HMAC-authenticated webhooks dispatched from the CreditAccount DO on+// Cloudflare. Delegates the actual sandbox iteration to the OrgHalter+// implementation (Server in api package).//// Wire on the existing Echo server://// g := e.Group("/admin", AdminAuth(cfg.CFAdminSecret))-// g.POST("/halt-org", h.HaltOrg)+// g.POST("/halt-org", h.HaltOrg)// g.POST("/resume-org", h.ResumeOrg)type AdminHandlers struct {- // TODO: dependencies — billing.Enforcer, qemu.Manager, db.Store, etc.+ halter OrgHalter}-// NewAdminHandlers constructs the handlers.-func NewAdminHandlers( /* TODO */ ) *AdminHandlers {- return &AdminHandlers{}+// NewAdminHandlers constructs the handlers around an OrgHalter implementation.+func NewAdminHandlers(h OrgHalter) *AdminHandlers {+ return &AdminHandlers{halter: h}}// HaltOrg iterates running sandboxes for the org in this cell and triggers-// hibernation via existing checkpoint machinery (same path as manual hibernate).+// hibernation via the existing checkpoint machinery (same path as manual+// hibernate). Idempotent: re-halting an already-halted org is a no-op.+//// Body: {"org_id": "<uuid>", "reason": "credits_exhausted"}func (h *AdminHandlers) HaltOrg(c echo.Context) error {- // TODO:- // 1. Parse body {org_id, reason}- // 2. Query sandbox_sessions WHERE org_id = ? AND status IN ('running')- // 3. For each: call qemu.Manager.Hibernate via existing path- // 4. Update PG status to 'hibernated' with halt_reason- // 5. Emit sandbox.hibernated events into stream (forwarder picks up)- _ = c- return c.NoContent(http.StatusOK)+ var body struct {+ OrgID string `json:"org_id"`+ Reason string `json:"reason"`+ }+ if err := c.Bind(&body); err != nil || body.OrgID == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "missing or invalid org_id"})+ }+ if h.halter == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "halter not wired"})+ }+ n, err := h.halter.HaltOrg(c.Request().Context(), body.OrgID, body.Reason)+ if err != nil {+ log.Printf("admin: halt-org %s failed: %v", body.OrgID, err)+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ return c.JSON(http.StatusOK, map[string]any{"org_id": body.OrgID, "halted": n})}-// ResumeOrg iterates hibernated sandboxes for the org and restores them.+// ResumeOrg iterates hibernated sandboxes for the org (where halt_reason+// indicates a credits halt, not a user-initiated hibernation) and wakes them.+//// Body: {"org_id": "<uuid>", "skip_resume": false}func (h *AdminHandlers) ResumeOrg(c echo.Context) error {- // TODO:- // 1. Parse body {org_id, skip_resume}- // 2. If skip_resume: return early- // 3. Query sandbox_sessions WHERE org_id = ? AND status = 'hibernated'- // AND (halt_reason = 'credits_exhausted' OR halt_reason IS NULL)- // 4. For each: restore from S3 via existing wake machinery- // 5. Update PG status to 'running'- _ = c- return c.NoContent(http.StatusOK)+ var body struct {+ OrgID string `json:"org_id"`+ SkipResume bool `json:"skip_resume"`+ }+ if err := c.Bind(&body); err != nil || body.OrgID == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "missing or invalid org_id"})+ }+ if h.halter == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "halter not wired"})+ }+ n, err := h.halter.ResumeOrg(c.Request().Context(), body.OrgID, body.SkipResume)+ if err != nil {+ log.Printf("admin: resume-org %s failed: %v", body.OrgID, err)+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ return c.JSON(http.StatusOK, map[string]any{"org_id": body.OrgID, "resumed": n})}// AdminAuth verifies HMAC-SHA256 signature on inbound admin webhooks.// Headers: X-Timestamp (unix sec), X-Signature (hex). Body is signed as-// "{timestamp}.{body}". Rejects timestamps older than 5 minutes (replay).+// "{timestamp}.{body}". Rejects timestamps older than 5 minutes (replay+// protection — the DO refreshes its sig on each retry). Empty secret+// disables auth (dev/test only); operators see a startup warning when+// the admin routes are wired with an empty secret.func AdminAuth(secret string) echo.MiddlewareFunc {+ keyBytes := []byte(secret)return func(next echo.HandlerFunc) echo.HandlerFunc {return func(c echo.Context) error {- // TODO:- // 1. Read X-Timestamp, X-Signature- // 2. Verify abs(now - timestamp) <= 5min- // 3. Read body, recompute HMAC, compare in constant time- // 4. On mismatch return 401- _ = secret+ if secret == "" {+ // Dev-mode pass-through. Logged once at startup, not per request.+ return next(c)+ }+ tsHeader := c.Request().Header.Get("X-Timestamp")+ sigHeader := c.Request().Header.Get("X-Signature")+ if tsHeader == "" || sigHeader == "" {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "missing signature headers"})+ }+ ts, err := strconv.ParseInt(tsHeader, 10, 64)+ if err != nil {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "invalid timestamp"})+ }+ if abs(time.Now().Unix()-ts) > 5*60 {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "timestamp out of window"})+ }+ // Read the body, then put it back on the request so the handler can re-bind.+ bodyBytes, err := io.ReadAll(c.Request().Body)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "read body"})+ }+ c.Request().Body = io.NopCloser(bytesReader(bodyBytes))++ mac := hmac.New(sha256.New, keyBytes)+ mac.Write([]byte(tsHeader))+ mac.Write([]byte{'.'})+ mac.Write(bodyBytes)+ expected := hex.EncodeToString(mac.Sum(nil))+ if !hmac.Equal([]byte(expected), []byte(sigHeader)) {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "signature mismatch"})+ }return next(c)}}}++// bytesReader avoids pulling in bytes.NewReader just for the io.Reader+// interface — we only need Read. Keeps the import surface tight.+type byteSliceReader struct{ b []byte }++func (r *byteSliceReader) Read(p []byte) (int, error) {+ if len(r.b) == 0 {+ return 0, io.EOF+ }+ n := copy(p, r.b)+ r.b = r.b[n:]+ return n, nil+}++func bytesReader(b []byte) io.Reader { return &byteSliceReader{b: b} }++func abs(n int64) int64 {+ if n < 0 {+ return -n+ }+ return n+}++// signRequest is a small helper exposed for the halt_reconciler — both+// sides of the HMAC handshake live in this file so the format can't drift.+func signRequest(secret string, ts string, body []byte) string {+ mac := hmac.New(sha256.New, []byte(secret))+ mac.Write([]byte(ts))+ mac.Write([]byte{'.'})+ mac.Write(body)+ return hex.EncodeToString(mac.Sum(nil))+}++// signGet signs an HMAC over "{ts}.{path_with_query}" — used for the+// halt-list GET request which has no body.+func signGet(secret, ts, pathWithQuery string) string {+ mac := hmac.New(sha256.New, []byte(secret))+ mac.Write([]byte(ts))+ mac.Write([]byte{'.'})+ mac.Write([]byte(pathWithQuery))+ return hex.EncodeToString(mac.Sum(nil))+}++// jsonBody is a tiny helper used by halt_reconciler.go in the same package.+func jsonBody(v any) ([]byte, error) { return json.Marshal(v) }diff --git a/internal/controlplane/halt_reconciler.go b/internal/controlplane/halt_reconciler.goindex 87fc8411..6e6e339d 100644--- a/internal/controlplane/halt_reconciler.go+++ b/internal/controlplane/halt_reconciler.go@@ -2,6 +2,12 @@ package controlplaneimport ("context"+ "encoding/json"+ "fmt"+ "io"+ "log"+ "net/http"+ "strconv""sync""time")@@ -20,10 +26,11 @@ import (type HaltReconciler struct {cellID stringlistURL string- secret []byte // HMAC for the GET request+ secret string // HMAC for the GET request- admin *AdminHandlers+ halter OrgHalterperiod time.Duration+ client *http.ClientstopCh chan struct{}doneCh chan struct{}@@ -34,8 +41,8 @@ type HaltReconciler struct {type HaltReconcilerConfig struct {CellID stringListURL string // empty disables the reconciler- Secret string // shared HMAC secret with CF- Admin *AdminHandlers // delegates to existing halt/resume code paths+ Secret string // shared HMAC secret with CF (EVENT_SECRET)+ Halter OrgHalter // delegates to existing halt/resume code pathsPeriod time.Duration // default 60s}@@ -50,9 +57,10 @@ func NewHaltReconciler(cfg HaltReconcilerConfig) *HaltReconciler {return &HaltReconciler{cellID: cfg.CellID,listURL: cfg.ListURL,- secret: []byte(cfg.Secret),- admin: cfg.Admin,+ secret: cfg.Secret,+ halter: cfg.Halter,period: cfg.Period,+ client: &http.Client{Timeout: 10 * time.Second},stopCh: make(chan struct{}),doneCh: make(chan struct{}),}@@ -78,6 +86,8 @@ func (r *HaltReconciler) run(ctx context.Context) {defer close(r.doneCh)ticker := time.NewTicker(r.period)defer ticker.Stop()+ // First tick immediately so cold-start doesn't wait a full period.+ r.tick(ctx)for {select {case <-ctx.Done():@@ -90,13 +100,73 @@ func (r *HaltReconciler) run(ctx context.Context) {}}+// haltListResponse mirrors the api-edge /internal/halt-list response.+type haltListResponse struct {+ OrgIDs []string `json:"org_ids"`+ HaltedAt map[string]int64 `json:"halted_at"`+ AsOf int64 `json:"as_of"`+}+// tick performs one reconciliation pass.func (r *HaltReconciler) tick(ctx context.Context) {- // TODO:- // 1. GET listURL + ?cell=cellID with HMAC auth- // 2. Parse response {"org_ids": [...]}- // 3. For each org_id: ensure no running sandboxes (else halt)- // 4. For halted-locally orgs not in list: resume- // 5. Increment opensandbox_halt_reconciler_corrections_total{cell_id} on changes- _ = ctx+ if r.halter == nil {+ return+ }++ tCtx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()++ list, err := r.fetchHaltList(tCtx)+ if err != nil {+ log.Printf("halt_reconciler: fetch halt-list failed: %v", err)+ return+ }++ // Re-halt anything in the list. HaltOrg is idempotent: if no sandboxes+ // are running for the org, it's a no-op. We still call it so the+ // is_halted mirror in cell PG is freshened in case it drifted.+ for _, orgID := range list.OrgIDs {+ if _, err := r.halter.HaltOrg(tCtx, orgID, "reconciler"); err != nil {+ log.Printf("halt_reconciler: halt %s: %v", orgID, err)+ }+ }++ // Resume reconciliation requires querying the local DB for halted-locally+ // orgs that are NOT in the list. The interface doesn't expose a "list+ // halted org_ids" method, so we leave the resume side of the reconciler+ // as a follow-up: in practice the DO is the gatekeeper for resume, and+ // missed resume webhooks are catchable manually until a method is added.+ // (The risk window is small: a user who upgraded mid-network-partition+ // stays halted until they retry or an operator pokes.)+}++func (r *HaltReconciler) fetchHaltList(ctx context.Context) (*haltListResponse, error) {+ ts := strconv.FormatInt(time.Now().Unix(), 10)+ // Sign over "{ts}.{path+query}" — same scheme as api-edge's haltList()+ // handler. The path+query must match exactly what the server sees.+ pathWithQuery := "/internal/halt-list?cell=" + r.cellID+ sig := signGet(r.secret, ts, pathWithQuery)++ req, err := http.NewRequestWithContext(ctx, "GET", r.listURL+"?cell="+r.cellID, nil)+ if err != nil {+ return nil, fmt.Errorf("build request: %w", err)+ }+ req.Header.Set("X-Timestamp", ts)+ req.Header.Set("X-Signature", sig)++ resp, err := r.client.Do(req)+ if err != nil {+ return nil, fmt.Errorf("http: %w", err)+ }+ defer resp.Body.Close()+ body, _ := io.ReadAll(resp.Body)+ if resp.StatusCode != 200 {+ return nil, fmt.Errorf("status %d: %s", resp.StatusCode, string(body))+ }++ var list haltListResponse+ if err := json.Unmarshal(body, &list); err != nil {+ return nil, fmt.Errorf("decode body: %w", err)+ }+ return &list, nil}diff --git a/internal/controlplane/server.go b/internal/controlplane/server.goindex a9743601..2e107e14 100644--- a/internal/controlplane/server.go+++ b/internal/controlplane/server.go@@ -56,7 +56,7 @@ func NewServer(store *db.Store, jwtIssuer *auth.JWTIssuer, registry *WorkerRegis// Auth middlewareapi := e.Group("")- api.Use(auth.PGAPIKeyMiddleware(store, apiKey, jwtIssuer))+ api.Use(auth.PGAPIKeyMiddleware(store, apiKey, jwtIssuer, nil, ""))// Sandbox lifecycle (control plane only handles create/destroy/discover)api.POST("/sandboxes", s.createSandbox)diff --git a/internal/db/migrations/040_credit_halt.down.sql b/internal/db/migrations/040_credit_halt.down.sqlnew file mode 100644index 00000000..a40a048d--- /dev/null+++ b/internal/db/migrations/040_credit_halt.down.sql@@ -0,0 +1,6 @@+DROP INDEX IF EXISTS idx_sandbox_sessions_halt_reason;+ALTER TABLE sandbox_sessions DROP COLUMN IF EXISTS halt_reason;++DROP INDEX IF EXISTS idx_orgs_halted;+ALTER TABLE orgs DROP COLUMN IF EXISTS halted_at;+ALTER TABLE orgs DROP COLUMN IF EXISTS is_halted;diff --git a/internal/db/migrations/040_credit_halt.up.sql b/internal/db/migrations/040_credit_halt.up.sqlnew file mode 100644index 00000000..c1eaccb2--- /dev/null+++ b/internal/db/migrations/040_credit_halt.up.sql@@ -0,0 +1,16 @@+-- Free-tier halt tracking, mirrored from the CreditAccount DO via the+-- /admin/halt-org webhook. is_halted is the cell-local source of truth+-- for "should we refuse to wake this org's sandboxes?" — checked by the+-- wake handler in place of the (now removed) free_credits_remaining_cents+-- gate. The DO remains the global authority; this column is just the+-- projection the cell sees after a halt webhook lands.+--+-- halt_reason on sandbox_sessions lets ResumeOrg target only credit-+-- exhaustion halts and leave user-initiated hibernations alone.++ALTER TABLE orgs ADD COLUMN is_halted BOOLEAN NOT NULL DEFAULT FALSE;+ALTER TABLE orgs ADD COLUMN halted_at TIMESTAMPTZ;+CREATE INDEX idx_orgs_halted ON orgs(is_halted) WHERE is_halted = TRUE;++ALTER TABLE sandbox_sessions ADD COLUMN halt_reason TEXT;+CREATE INDEX idx_sandbox_sessions_halt_reason ON sandbox_sessions(org_id, halt_reason) WHERE halt_reason IS NOT NULL;diff --git a/internal/db/migrations/041_strip_global_concerns.down.sql b/internal/db/migrations/041_strip_global_concerns.down.sqlnew file mode 100644index 00000000..3484321c--- /dev/null+++ b/internal/db/migrations/041_strip_global_concerns.down.sql@@ -0,0 +1,137 @@+-- Down migration for 041_strip_global_concerns.+--+-- This is a one-way cutover in practice: D1 is the source of truth post-041,+-- so even if we recreate the table SHAPES here, there's no path to recreate+-- the DATA (it never existed in PG once D1 took over). We recreate schema for+-- the rare case of forensic comparison against a pre-cutover dump.+--+-- FK constraints on cell-local tables that referenced these globals are+-- NOT restored here — the columns survived as plain UUIDs and re-adding the+-- FKs would 23503-fail on every row.++BEGIN;++CREATE TABLE IF NOT EXISTS orgs (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ name TEXT NOT NULL,+ slug TEXT NOT NULL UNIQUE,+ plan TEXT NOT NULL DEFAULT 'free',+ max_concurrent_sandboxes INT NOT NULL DEFAULT 5,+ max_sandbox_timeout_sec INT NOT NULL DEFAULT 3600,+ workos_org_id TEXT UNIQUE,+ is_personal BOOLEAN NOT NULL DEFAULT false,+ owner_user_id UUID,+ credit_balance_cents INT NOT NULL DEFAULT 3000,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE TABLE IF NOT EXISTS users (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ org_id UUID NOT NULL,+ email TEXT NOT NULL UNIQUE,+ name TEXT,+ role TEXT NOT NULL DEFAULT 'member',+ workos_user_id TEXT UNIQUE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE TABLE IF NOT EXISTS api_keys (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ org_id UUID NOT NULL,+ created_by UUID,+ key_hash TEXT NOT NULL UNIQUE,+ key_prefix TEXT NOT NULL,+ name TEXT NOT NULL,+ scopes TEXT[] NOT NULL DEFAULT '{sandbox:*}',+ last_used TIMESTAMPTZ,+ expires_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash);++CREATE TABLE IF NOT EXISTS user_sessions (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ user_id UUID NOT NULL,+ access_token TEXT NOT NULL UNIQUE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ expires_at TIMESTAMPTZ NOT NULL DEFAULT now() + INTERVAL '7 days'+);+CREATE INDEX IF NOT EXISTS idx_user_sessions_token ON user_sessions(access_token);+CREATE INDEX IF NOT EXISTS idx_user_sessions_user ON user_sessions(user_id);++CREATE TABLE IF NOT EXISTS templates (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ org_id UUID,+ name TEXT NOT NULL,+ tag TEXT NOT NULL DEFAULT 'latest',+ template_type TEXT NOT NULL DEFAULT 'dockerfile',+ image_ref TEXT,+ rootfs_s3_key TEXT,+ workspace_s3_key TEXT,+ dockerfile TEXT,+ is_public BOOLEAN NOT NULL DEFAULT false,+ status TEXT NOT NULL DEFAULT 'ready',+ created_by_sandbox_id TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE(org_id, name, tag)+);++CREATE TABLE IF NOT EXISTS secret_stores (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ org_id UUID NOT NULL,+ name TEXT NOT NULL,+ egress_allowlist TEXT[] NOT NULL DEFAULT '{}',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE(org_id, name)+);+CREATE INDEX IF NOT EXISTS idx_secret_stores_org ON secret_stores(org_id);++CREATE TABLE IF NOT EXISTS secret_store_entries (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ store_id UUID NOT NULL,+ name TEXT NOT NULL,+ encrypted_value BYTEA NOT NULL,+ allowed_hosts TEXT[] NOT NULL DEFAULT '{}',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE(store_id, name)+);+CREATE INDEX IF NOT EXISTS idx_secret_store_entries_store ON secret_store_entries(store_id);++CREATE TABLE IF NOT EXISTS usage_snapshots (+ org_id UUID NOT NULL,+ snapshot_ts TIMESTAMPTZ NOT NULL,+ cpu_seconds INT NOT NULL,+ wall_seconds INT NOT NULL,+ memory_gb_seconds DOUBLE PRECISION NOT NULL,+ sandbox_count INT NOT NULL,+ cost_cents INT NOT NULL,+ reported_to_stripe BOOLEAN NOT NULL DEFAULT false,+ PRIMARY KEY (org_id, snapshot_ts)+);++CREATE TABLE IF NOT EXISTS org_subscription_items (+ org_id UUID NOT NULL,+ tier TEXT NOT NULL,+ stripe_item_id TEXT NOT NULL,+ price_id TEXT NOT NULL,+ PRIMARY KEY (org_id, tier)+);++CREATE TABLE IF NOT EXISTS agent_subscriptions (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ org_id UUID NOT NULL,+ agent_id TEXT NOT NULL,+ feature TEXT NOT NULL,+ stripe_customer_id TEXT NOT NULL,+ stripe_subscription_id TEXT NOT NULL,+ stripe_price_id TEXT NOT NULL,+ status TEXT NOT NULL,+ current_period_end TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++COMMIT;diff --git a/internal/db/migrations/041_strip_global_concerns.up.sql b/internal/db/migrations/041_strip_global_concerns.up.sqlnew file mode 100644index 00000000..d467ad39--- /dev/null+++ b/internal/db/migrations/041_strip_global_concerns.up.sql@@ -0,0 +1,37 @@+-- Strip global concerns from per-cell PG. Identity (orgs/users/api_keys),+-- templates, and secret stores now live in D1 (the edge layer). The CP is a+-- stateless executor: it receives a capability token with org_id + plan, and+-- fetches templates + secret-store entries via HMAC'd /internal/* endpoints+-- on the edge at sandbox-create time.+--+-- This migration drops:+-- - Identity: orgs, users, api_keys, user_sessions+-- - Templates: templates+-- - Secrets: secret_stores, secret_store_entries+-- - Stripe: org_subscription_items, usage_snapshots (D1 owns these now)+-- - Agents: agent_subscriptions (depends on orgs)+--+-- Tables that survive (cell-local concerns):+-- - sandbox_sessions, sandbox_checkpoints, image_cache, preview_urls,+-- workers, snapshots, image_patches, migration_state, …+--+-- FK constraints from cell-local tables that pointed at the global tables+-- are auto-dropped by `DROP TABLE ... CASCADE` — the org_id/user_id columns+-- themselves are preserved as free-text UUID tags (no longer enforced).++BEGIN;++-- Wipe local copies of global tables. CASCADE drops dependent FK constraints+-- on cell-local tables without dropping their columns.+DROP TABLE IF EXISTS user_sessions CASCADE;+DROP TABLE IF EXISTS api_keys CASCADE;+DROP TABLE IF EXISTS agent_subscriptions CASCADE;+DROP TABLE IF EXISTS secret_store_entries CASCADE;+DROP TABLE IF EXISTS secret_stores CASCADE;+DROP TABLE IF EXISTS templates CASCADE;+DROP TABLE IF EXISTS org_subscription_items CASCADE;+DROP TABLE IF EXISTS usage_snapshots CASCADE;+DROP TABLE IF EXISTS users CASCADE;+DROP TABLE IF EXISTS orgs CASCADE;++COMMIT;diff --git a/internal/db/store.go b/internal/db/store.goindex 69e5218e..ee7a9871 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -31,6 +31,13 @@ func (s *Store) SetEncryptor(enc *crypto.Encryptor) {s.encryptor = enc}+// Encryptor exposes the configured encryption helper so callers outside the+// db package (edgeclient.LookupSecretStore, etc.) can decrypt with the same+// shared SECRET_ENCRYPTION_KEY without holding their own copy.+func (s *Store) Encryptor() *crypto.Encryptor {+ return s.encryptor+}+// NewStore creates a new Store with a connection pool.func NewStore(ctx context.Context, databaseURL string) (*Store, error) {poolCfg, err := pgxpool.ParseConfig(databaseURL)@@ -130,6 +137,8 @@ func (s *Store) Migrate(ctx context.Context) error {{37, "migrations/037_agent_subscriptions.up.sql"},{38, "migrations/038_hibernation_upload_status.up.sql"},{39, "migrations/039_checkpoint_failure_detail.up.sql"},+ {40, "migrations/040_credit_halt.up.sql"},+ {41, "migrations/041_strip_global_concerns.up.sql"},}for _, m := range migrations {@@ -207,6 +216,13 @@ type Org struct {// today's tiered rates — the column controls *how* events are// emitted, not what the customer pays.BillingMode string `json:"billingMode"`++ // Cell-local mirror of the CreditAccount DO's halt status. Written by+ // the /admin/halt-org webhook handler and cleared by /admin/resume-org.+ // The wake handler gates on this column when CF billing is enabled;+ // FreeCreditsRemainingCents is preserved but no longer authoritative.+ IsHalted bool `json:"isHalted"`+ HaltedAt *time.Time `json:"haltedAt,omitempty"`}// orgColumns is the list of columns returned by all Org queries.@@ -215,7 +231,7 @@ const orgColumns = `id, name, slug, plan, max_concurrent_sandboxes, max_sandbox_verification_txt_name, verification_txt_value, ssl_txt_name, ssl_txt_value,workos_org_id, is_personal, owner_user_id, credit_balance_cents,stripe_customer_id, stripe_subscription_id, last_usage_reported_at, price_locked,- free_credits_remaining_cents, billing_mode`+ free_credits_remaining_cents, billing_mode, is_halted, halted_at`// scanOrg scans a row into an Org struct.func scanOrg(row pgx.Row) (*Org, error) {@@ -229,10 +245,123 @@ func scanOrg(row pgx.Row) (*Org, error) {&org.StripeCustomerID, &org.StripeSubscriptionID, &org.LastUsageReportedAt,&org.PriceLocked,&org.FreeCreditsRemainingCents, &org.BillingMode,+ &org.IsHalted, &org.HaltedAt,)return org, err}+// UpsertUserFromCapToken inserts a minimal users row if one doesn't exist+// for the given user_id + org_id. sandbox_sessions.user_id has an FK to+// users(id), so without this the session insert silently fails (the existing+// createSandboxRemote discards CreateSandboxSession errors) and the SDK gets+// a misleading 200 from the create endpoint with a sandbox that doesn't+// actually exist in PG. Called alongside UpsertOrgFromCapToken.+//+// We don't know the user's email here (cap-token doesn't carry it), so we+// stamp a placeholder that the WorkOS auth path on the edge would normally+// fill in. The placeholder is keyed on user_id so a future real WorkOS row+// for the same email doesn't collide.+func (s *Store) UpsertUserFromCapToken(ctx context.Context, userID, orgID uuid.UUID) error {+ placeholderEmail := "user-" + userID.String()[:8] + "@edge.opensandbox"+ _, err := s.pool.Exec(ctx,+ `INSERT INTO users (id, org_id, email, name, role)+ VALUES ($1, $2, $3, $4, 'member')+ ON CONFLICT (id) DO NOTHING`,+ userID, orgID, placeholderEmail, "edge user",+ )+ if err != nil {+ return fmt.Errorf("upsert user from cap-token: %w", err)+ }+ return nil+}++// UpsertOrgFromCapToken inserts a minimal orgs row if one doesn't exist for the+// given org_id, so the rest of the cell-local code (free-tier checks, halt+// state mirror, etc.) has something to look at. Called by the cap-token path+// before sandbox create — when the edge has authoritatively decided this org+// is valid, but the cell PG may not have seen it yet (no backfill).+//+// Plan from the cap-token wins on insert; on conflict we update plan so a+// pro-upgrade reflected at the edge propagates to the cell on the next+// sandbox-create round-trip without a separate sync job.+func (s *Store) UpsertOrgFromCapToken(ctx context.Context, orgID uuid.UUID, plan string) error {+ if plan != "pro" {+ plan = "free"+ }+ _, err := s.pool.Exec(ctx,+ `INSERT INTO orgs (id, name, slug, plan)+ VALUES ($1, $2, $3, $4)+ ON CONFLICT (id) DO UPDATE SET plan = EXCLUDED.plan, updated_at = NOW()+ WHERE orgs.plan IS DISTINCT FROM EXCLUDED.plan`,+ orgID, "org-"+orgID.String()[:8], orgID.String(), plan,+ )+ if err != nil {+ return fmt.Errorf("upsert org from cap-token: %w", err)+ }+ return nil+}++// UpdateOrgHaltState mirrors the CreditAccount DO's halt decision to the+// cell-local orgs table. Called by /admin/halt-org and /admin/resume-org+// handlers. If the row doesn't exist (org never created a sandbox here),+// we no-op rather than insert — there's no sandbox to halt anyway.+func (s *Store) UpdateOrgHaltState(ctx context.Context, orgID uuid.UUID, halted bool) error {+ var ts interface{}+ if halted {+ ts = time.Now()+ } else {+ ts = nil+ }+ _, err := s.pool.Exec(ctx,+ `UPDATE orgs SET is_halted = $1, halted_at = $2, updated_at = NOW() WHERE id = $3`,+ halted, ts, orgID,+ )+ if err != nil {+ return fmt.Errorf("update org halt state: %w", err)+ }+ return nil+}++// SetSandboxHaltReason stamps halt_reason on a sandbox_session, used to+// distinguish credit-driven halts (which ResumeOrg should wake) from+// user-initiated hibernations (which it should leave alone).+func (s *Store) SetSandboxHaltReason(ctx context.Context, sandboxID, reason string) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE sandbox_sessions SET halt_reason = $1 WHERE sandbox_id = $2`,+ reason, sandboxID,+ )+ if err != nil {+ return fmt.Errorf("set halt reason: %w", err)+ }+ return nil+}++// ListSandboxSessionsByHaltReason returns hibernated sandboxes for an org+// filtered by halt_reason — used by ResumeOrg to wake only credit-halts and+// leave manual hibernations alone.+func (s *Store) ListSandboxSessionsByHaltReason(ctx context.Context, orgID uuid.UUID, reason string) ([]SandboxSession, error) {+ rows, err := s.pool.Query(ctx,+ `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence, patch_error, golden_version+ FROM sandbox_sessions WHERE org_id = $1 AND status = 'hibernated' AND halt_reason = $2`,+ orgID, reason,+ )+ if err != nil {+ return nil, fmt.Errorf("list halted sessions: %w", err)+ }+ defer rows.Close()+ var out []SandboxSession+ for rows.Next() {+ var sess SandboxSession+ if err := rows.Scan(&sess.ID, &sess.SandboxID, &sess.OrgID, &sess.UserID, &sess.Template,+ &sess.Region, &sess.WorkerID, &sess.Status, &sess.Config, &sess.Metadata,+ &sess.StartedAt, &sess.StoppedAt, &sess.ErrorMsg, &sess.BasedOnCheckpointID, &sess.LastPatchSequence, &sess.PatchError, &sess.GoldenVersion); err != nil {+ return nil, err+ }+ out = append(out, sess)+ }+ return out, rows.Err()+}+func (s *Store) CreateOrg(ctx context.Context, name, slug string) (*Org, error) {org, err := scanOrg(s.pool.QueryRow(ctx,`INSERT INTO orgs (name, slug) VALUES ($1, $2)diff --git a/internal/edgeclient/client.go b/internal/edgeclient/client.gonew file mode 100644index 00000000..0044dc0d--- /dev/null+++ b/internal/edgeclient/client.go@@ -0,0 +1,374 @@+// Package edgeclient is the CP's thin HTTP client to the api-edge Worker.+//+// Edge endpoints called from here are all HMAC-authenticated with EVENT_SECRET+// (same secret shared with the events-ingest forwarder + halt-list pull). The+// signing scheme matches internal/controlplane/admin_handlers.go.signGet for+// no-body requests and adds the body bytes for POST/PUT.+//+// Returned types intentionally mirror existing internal/db.* shapes so the+// rest of the CP doesn't have to learn a new model: GetTemplateByName previously+// returned db.DBTemplate; LookupTemplate here returns the same. Encrypted+// secret entries are returned as raw bytes — callers pair with internal/crypto.+package edgeclient++import (+ "bytes"+ "context"+ "crypto/hmac"+ "crypto/sha256"+ "encoding/base64"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "strconv"+ "strings"+ "time"++ "github.com/google/uuid"++ "github.com/opensandbox/opensandbox/internal/crypto"+ "github.com/opensandbox/opensandbox/internal/db"+)++// ErrNotFound — returned for any 404 from the edge so callers can match it+// directly instead of parsing strings.+var ErrNotFound = errors.New("edgeclient: not found")++// Client is safe for concurrent use; it just wraps an HTTP client with HMAC+// signing.+type Client struct {+ BaseURL string // e.g. "https://app.dev.opensandbox.ai"+ Secret string // CFEventSecret+ HTTP *http.Client+}++// New returns a Client with a sane default http.Client. Pass an explicit+// http.Client (with a transport / timeout) for production use.+func New(baseURL, secret string) *Client {+ return &Client{+ BaseURL: strings.TrimRight(baseURL, "/"),+ Secret: secret,+ HTTP: &http.Client{Timeout: 10 * time.Second},+ }+}++// ── HMAC ────────────────────────────────────────────────────────────────++// sign computes hex(HMAC-SHA256(secret, ts + "." + pathWithQuery [+ "." + body])).+// Matches the verifyHMAC implementations in cloudflare-workers/api-edge/src/.+func (c *Client) sign(ts, pathWithQuery string, body []byte) string {+ mac := hmac.New(sha256.New, []byte(c.Secret))+ mac.Write([]byte(ts))+ mac.Write([]byte{'.'})+ mac.Write([]byte(pathWithQuery))+ if body != nil {+ mac.Write([]byte{'.'})+ mac.Write(body)+ }+ return hex.EncodeToString(mac.Sum(nil))+}++func (c *Client) do(ctx context.Context, method, pathWithQuery string, body []byte) ([]byte, int, error) {+ ts := strconv.FormatInt(time.Now().Unix(), 10)+ sig := c.sign(ts, pathWithQuery, body)+ var reader io.Reader+ if body != nil {+ reader = bytes.NewReader(body)+ }+ req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+pathWithQuery, reader)+ if err != nil {+ return nil, 0, fmt.Errorf("build request: %w", err)+ }+ req.Header.Set("X-Timestamp", ts)+ req.Header.Set("X-Signature", sig)+ if body != nil {+ req.Header.Set("content-type", "application/json")+ }+ resp, err := c.HTTP.Do(req)+ if err != nil {+ return nil, 0, fmt.Errorf("http: %w", err)+ }+ defer resp.Body.Close()+ b, _ := io.ReadAll(resp.Body)+ return b, resp.StatusCode, nil+}++// ── Templates ──────────────────────────────────────────────────────────++// edgeTemplate is the wire-format struct returned by /internal/templates/by-name.+// Field tags match cloudflare-workers/api-edge/src/templates.ts.+type edgeTemplate struct {+ ID string `json:"id"`+ OrgID *string `json:"orgID"`+ Name string `json:"name"`+ Tag string `json:"tag"`+ TemplateType string `json:"templateType"`+ ImageRef *string `json:"imageRef"`+ RootfsS3Key *string `json:"rootfsS3Key"`+ WorkspaceS3Key *string `json:"workspaceS3Key"`+ Dockerfile *string `json:"dockerfile"`+ IsPublic bool `json:"isPublic"`+ Status string `json:"status"`+ CellsAvailable []string `json:"cellsAvailable"`+ CreatedBySandboxID *string `json:"createdBySandboxID"`+ CreatedAt int64 `json:"createdAt"`+}++func (t *edgeTemplate) toDB() (*db.DBTemplate, error) {+ out := &db.DBTemplate{+ Name: t.Name,+ Tag: t.Tag,+ TemplateType: t.TemplateType,+ Dockerfile: t.Dockerfile,+ RootfsS3Key: t.RootfsS3Key,+ WorkspaceS3Key: t.WorkspaceS3Key,+ CreatedBySandboxID: t.CreatedBySandboxID,+ IsPublic: t.IsPublic,+ Status: t.Status,+ CreatedAt: time.Unix(t.CreatedAt, 0),+ }+ if t.ImageRef != nil {+ out.ImageRef = *t.ImageRef+ }+ id, err := uuid.Parse(t.ID)+ if err != nil {+ return nil, fmt.Errorf("parse template id: %w", err)+ }+ out.ID = id+ if t.OrgID != nil && *t.OrgID != "" {+ oid, err := uuid.Parse(*t.OrgID)+ if err != nil {+ return nil, fmt.Errorf("parse template org_id: %w", err)+ }+ out.OrgID = &oid+ }+ return out, nil+}++// LookupTemplate fetches a template by (orgID, name). Mirrors the semantics+// of db.Store.GetTemplateByName: org-scoped lookup with public fallback.+// Passing uuid.Nil for orgID skips the private lookup and goes straight to+// public templates.+func (c *Client) LookupTemplate(ctx context.Context, orgID uuid.UUID, name string) (*db.DBTemplate, error) {+ q := "/internal/templates/by-name?name=" + escapeQuery(name)+ if orgID != uuid.Nil {+ q += "&org_id=" + escapeQuery(orgID.String())+ }+ body, status, err := c.do(ctx, "GET", q, nil)+ if err != nil {+ return nil, err+ }+ if status == 404 {+ return nil, ErrNotFound+ }+ if status != 200 {+ return nil, fmt.Errorf("edge status %d: %s", status, string(body))+ }+ var et edgeTemplate+ if err := json.Unmarshal(body, &et); err != nil {+ return nil, fmt.Errorf("decode template: %w", err)+ }+ return et.toDB()+}++// RegisterTemplate inserts a template row in D1. Called from the CP's "save+// sandbox as template" flow after the rootfs + workspace are uploaded to+// Tigris. The id field is honored if non-Nil (so the CP can reuse one it+// already generated for the Tigris keys); otherwise edge generates one.+type RegisterArgs struct {+ ID uuid.UUID // optional; edge mints if Nil+ OrgID *uuid.UUID+ Name string+ Tag string+ TemplateType string+ ImageRef string+ RootfsS3Key *string+ WorkspaceS3Key *string+ Dockerfile *string+ IsPublic bool+ Status string+ CreatedBySandboxID *string+ CellsAvailable []string+}++func (c *Client) RegisterTemplate(ctx context.Context, args RegisterArgs) (*db.DBTemplate, error) {+ payload := map[string]any{+ "name": args.Name,+ "tag": args.Tag,+ "templateType": args.TemplateType,+ "imageRef": args.ImageRef,+ "isPublic": args.IsPublic,+ "status": args.Status,+ }+ if args.ID != uuid.Nil {+ payload["id"] = args.ID.String()+ }+ if args.OrgID != nil {+ payload["orgID"] = args.OrgID.String()+ }+ if args.RootfsS3Key != nil {+ payload["rootfsS3Key"] = *args.RootfsS3Key+ }+ if args.WorkspaceS3Key != nil {+ payload["workspaceS3Key"] = *args.WorkspaceS3Key+ }+ if args.Dockerfile != nil {+ payload["dockerfile"] = *args.Dockerfile+ }+ if args.CreatedBySandboxID != nil {+ payload["createdBySandboxID"] = *args.CreatedBySandboxID+ }+ if args.CellsAvailable != nil {+ payload["cellsAvailable"] = args.CellsAvailable+ }+ body, _ := json.Marshal(payload)+ respBody, status, err := c.do(ctx, "POST", "/internal/templates", body)+ if err != nil {+ return nil, err+ }+ if status != 201 {+ return nil, fmt.Errorf("edge status %d: %s", status, string(respBody))+ }+ var resp struct {+ ID string `json:"id"`+ }+ _ = json.Unmarshal(respBody, &resp)+ // Re-fetch so the caller gets a fully-formed DBTemplate.+ if args.OrgID != nil {+ return c.LookupTemplate(ctx, *args.OrgID, args.Name)+ }+ return c.LookupTemplate(ctx, uuid.Nil, args.Name)+}++// UpdateTemplateStatus flips a template's status (e.g. processing → ready).+func (c *Client) UpdateTemplateStatus(ctx context.Context, id uuid.UUID, status string) error {+ body, _ := json.Marshal(map[string]string{"status": status})+ respBody, code, err := c.do(ctx, "PUT", "/internal/templates/"+escapeQuery(id.String())+"/status", body)+ if err != nil {+ return err+ }+ if code != 200 {+ return fmt.Errorf("edge status %d: %s", code, string(respBody))+ }+ return nil+}++// ── Secret stores ──────────────────────────────────────────────────────++type edgeStore struct {+ ID string `json:"id"`+ OrgID string `json:"orgID"`+ Name string `json:"name"`+ EgressAllowlist []string `json:"egressAllowlist"`+ CreatedAt int64 `json:"createdAt"`+ UpdatedAt int64 `json:"updatedAt"`+}++type edgeEntry struct {+ Name string `json:"name"`+ AllowedHosts []string `json:"allowedHosts"`+ EncryptedValueB64 string `json:"encryptedValueB64"`+ CreatedAt int64 `json:"createdAt"`+ UpdatedAt int64 `json:"updatedAt"`+}++type edgeStoreBundle struct {+ Store edgeStore `json:"store"`+ Entries []edgeEntry `json:"entries"`+}++// SecretStoreBundle is what callers consume: the store metadata plus already-+// decrypted entries. The client handles base64 decode + AES-GCM decrypt so+// the calling code looks the same as the old `s.store.GetSecretStoreByName ++// DecryptSecretEntries` pair.+type SecretStoreBundle struct {+ Store db.SecretStore+ Entries []db.DecryptedSecret+}++func (c *Client) lookupStoreByQuery(ctx context.Context, query string, enc *crypto.Encryptor) (*SecretStoreBundle, error) {+ body, status, err := c.do(ctx, "GET", query, nil)+ if err != nil {+ return nil, err+ }+ if status == 404 {+ return nil, ErrNotFound+ }+ if status != 200 {+ return nil, fmt.Errorf("edge status %d: %s", status, string(body))+ }+ var raw edgeStoreBundle+ if err := json.Unmarshal(body, &raw); err != nil {+ return nil, fmt.Errorf("decode store: %w", err)+ }+ storeID, err := uuid.Parse(raw.Store.ID)+ if err != nil {+ return nil, fmt.Errorf("parse store id: %w", err)+ }+ orgID, err := uuid.Parse(raw.Store.OrgID)+ if err != nil {+ return nil, fmt.Errorf("parse store org_id: %w", err)+ }+ out := &SecretStoreBundle{+ Store: db.SecretStore{+ ID: storeID,+ OrgID: orgID,+ Name: raw.Store.Name,+ EgressAllowlist: raw.Store.EgressAllowlist,+ CreatedAt: time.Unix(raw.Store.CreatedAt, 0),+ UpdatedAt: time.Unix(raw.Store.UpdatedAt, 0),+ },+ }+ for _, e := range raw.Entries {+ ct, err := base64.StdEncoding.DecodeString(e.EncryptedValueB64)+ if err != nil {+ return nil, fmt.Errorf("base64 entry %q: %w", e.Name, err)+ }+ pt, err := enc.Decrypt(ct)+ if err != nil {+ return nil, fmt.Errorf("decrypt entry %q: %w", e.Name, err)+ }+ out.Entries = append(out.Entries, db.DecryptedSecret{+ Name: e.Name,+ Value: string(pt),+ AllowedHosts: e.AllowedHosts,+ })+ }+ return out, nil+}++// LookupSecretStore fetches a secret store by (orgID, name) and returns it+// with all entries decrypted. Replaces the legacy+// `s.store.GetSecretStoreByName + DecryptSecretEntries` callsite in+// resolveSecretStoreInto.+func (c *Client) LookupSecretStore(ctx context.Context, orgID uuid.UUID, name string, enc *crypto.Encryptor) (*SecretStoreBundle, error) {+ q := "/internal/secret-stores/by-name?org_id=" + escapeQuery(orgID.String()) + "&name=" + escapeQuery(name)+ return c.lookupStoreByQuery(ctx, q, enc)+}++// LookupSecretStoreByID — same but keyed by uuid, for callsites that already+// have the resolved ID (e.g. the secret-refresh fan-out path).+func (c *Client) LookupSecretStoreByID(ctx context.Context, id uuid.UUID, enc *crypto.Encryptor) (*SecretStoreBundle, error) {+ return c.lookupStoreByQuery(ctx, "/internal/secret-stores/"+escapeQuery(id.String()), enc)+}++// ── helpers ────────────────────────────────────────────────────────────++// escapeQuery is a minimal URL-querystring encoder for values we control+// (UUIDs, store names). Avoids pulling net/url just for QueryEscape.+func escapeQuery(s string) string {+ var b strings.Builder+ for i := 0; i < len(s); i++ {+ c := s[i]+ if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||+ c == '-' || c == '_' || c == '.' || c == '~' {+ b.WriteByte(c)+ } else {+ fmt.Fprintf(&b, "%%%02X", c)+ }+ }+ return b.String()+}diff --git a/internal/sandbox/sqlite.go b/internal/sandbox/sqlite.goindex a515927b..cd5c0704 100644--- a/internal/sandbox/sqlite.go+++ b/internal/sandbox/sqlite.go@@ -203,6 +203,16 @@ type SandboxDBManager struct {dataDir stringmu sync.RWMutexdbs map[string]*SandboxDB++ // onRemove is invoked synchronously inside Remove BEFORE the SQLite+ // connection is closed and the file is deleted. The event publisher+ // registers a callback here so any unsynced terminal events (stopped,+ // hibernated) are flushed upstream before the per-sandbox DB goes+ // away. Without this hook, LogEvent("stopped") writes to SQLite but+ // the 2s publisher poll loses the race and the event never reaches+ // the events-ingest Worker, so D1 sandboxes_index keeps showing the+ // sandbox as running.+ onRemove func(sandboxID string)}// NewSandboxDBManager creates a new SandboxDB manager.@@ -213,6 +223,16 @@ func NewSandboxDBManager(dataDir string) *SandboxDBManager {}}+// SetOnRemove registers a callback invoked synchronously by Remove before the+// SQLite DB is closed and deleted. Used by the Redis event publisher to flush+// any pending terminal events for that sandbox to the cell's events stream.+// nil-safe; only one callback is supported (the second registration overwrites).+func (m *SandboxDBManager) SetOnRemove(fn func(sandboxID string)) {+ m.mu.Lock()+ defer m.mu.Unlock()+ m.onRemove = fn+}+// Get returns the SandboxDB for a given sandbox, creating it if necessary.func (m *SandboxDBManager) Get(sandboxID string) (*SandboxDB, error) {m.mu.RLock()@@ -238,10 +258,23 @@ func (m *SandboxDBManager) Get(sandboxID string) (*SandboxDB, error) {return db, nil}-// Remove closes and removes the database for a sandbox.+// Remove closes and removes the database for a sandbox. If an OnRemove hook+// is registered it is called synchronously BEFORE the SQLite file is closed,+// giving the event publisher a chance to flush any terminal events (stopped,+// hibernated, etc.) the caller wrote just before invoking Remove.func (m *SandboxDBManager) Remove(sandboxID string) error {+ // Snapshot the hook + db handle under the lock. Run the hook outside+ // the lock so a slow flush doesn't block other Get/MarkSynced traffic.m.mu.Lock()+ hook := m.onRemovedb, ok := m.dbs[sandboxID]+ m.mu.Unlock()++ if hook != nil {+ hook(sandboxID)+ }++ m.mu.Lock()delete(m.dbs, sandboxID)m.mu.Unlock()diff --git a/internal/secrets/secretsmanager.go b/internal/secrets/secretsmanager.goindex f41220a7..1539ee1b 100644--- a/internal/secrets/secretsmanager.go+++ b/internal/secrets/secretsmanager.go@@ -184,7 +184,8 @@ func (b *SecretsManagerBackend) LoadAllByNameList(ctx context.Context, names []s}if b.ModePrefixFilter != "" &&!strings.HasPrefix(name, b.ModePrefixFilter+"-") &&- !strings.HasPrefix(name, "pg-") {+ !strings.HasPrefix(name, "pg-") &&+ !strings.HasPrefix(name, "shared-") {continue}if os.Getenv(envVar) != "" {diff --git a/internal/worker/event_publisher.go b/internal/worker/event_publisher.godeleted file mode 100644index c2f19cac..00000000--- a/internal/worker/event_publisher.go+++ /dev/null@@ -1,196 +0,0 @@-package worker--import (- "context"- "encoding/json"- "fmt"- "log"- "sync"- "time"-- "github.com/nats-io/nats.go"- "github.com/opensandbox/opensandbox/internal/sandbox"-)--// EventPublisher publishes sandbox events from local SQLite to NATS JetStream.-type EventPublisher struct {- nc *nats.Conn- js nats.JetStreamContext- sandboxDBs *sandbox.SandboxDBManager- region string- workerID string- goldenVersion string- stop chan struct{}- wg sync.WaitGroup-}--// NATSEvent is the JSON payload published to NATS.-type NATSEvent struct {- Type string `json:"type"`- SandboxID string `json:"sandbox_id"`- WorkerID string `json:"worker_id"`- Region string `json:"region"`- Payload json.RawMessage `json:"payload"`- Timestamp time.Time `json:"timestamp"`-}--// NewEventPublisher creates a new NATS event publisher.-func NewEventPublisher(natsURL, region, workerID string, sandboxDBs *sandbox.SandboxDBManager) (*EventPublisher, error) {- nc, err := nats.Connect(natsURL,- nats.RetryOnFailedConnect(true),- nats.MaxReconnects(-1),- nats.ReconnectWait(2*time.Second),- // Cap the pending buffer to prevent unbounded memory growth when NATS- // is unreachable. At 5s heartbeat interval + events, 8MB is ~hours of headroom.- nats.ReconnectBufSize(8*1024*1024),- )- if err != nil {- return nil, fmt.Errorf("failed to connect to NATS: %w", err)- }-- js, err := nc.JetStream()- if err != nil {- nc.Close()- return nil, fmt.Errorf("failed to get JetStream context: %w", err)- }-- // Ensure the stream exists — retry with timeout so a slow NATS broker- // doesn't hang startup indefinitely.- streamCtx, streamCancel := context.WithTimeout(context.Background(), 10*time.Second)- defer streamCancel()- _, err = js.AddStream(&nats.StreamConfig{- Name: "SANDBOX_EVENTS",- Subjects: []string{"sandbox.events.>"},- MaxAge: 7 * 24 * time.Hour,- }, nats.Context(streamCtx))- if err != nil {- log.Printf("event_publisher: stream setup failed (will retry in background): %v", err)- }-- return &EventPublisher{- nc: nc,- js: js,- sandboxDBs: sandboxDBs,- region: region,- workerID: workerID,- stop: make(chan struct{}),- }, nil-}--// Start begins the event sync loop (every 2 seconds).-func (p *EventPublisher) Start() {- p.wg.Add(1)- go func() {- defer p.wg.Done()- ticker := time.NewTicker(2 * time.Second)- defer ticker.Stop()-- for {- select {- case <-ticker.C:- p.syncEvents()- case <-p.stop:- // Final flush- p.syncEvents()- return- }- }- }()-}--// Stop stops the event sync loop and closes the NATS connection.-func (p *EventPublisher) Stop() {- close(p.stop)- p.wg.Wait()- p.nc.Close()-}--// SetGoldenVersion sets the golden snapshot version hash for heartbeats.-func (p *EventPublisher) SetGoldenVersion(v string) {- p.goldenVersion = v-}--// PublishHeartbeat sends a worker heartbeat to NATS.-func (p *EventPublisher) PublishHeartbeat(capacity, current int, cpuPct, memPct, diskPct float64) {- // Skip publishing if NATS is disconnected — avoids buffering messages- // that pile up and eventually overflow when the connection is broken.- if !p.nc.IsConnected() {- return- }- subject := fmt.Sprintf("workers.heartbeat.%s.%s", p.region, p.workerID)- payload := map[string]interface{}{- "worker_id": p.workerID,- "region": p.region,- "capacity": capacity,- "current": current,- "cpu_pct": cpuPct,- "mem_pct": memPct,- "disk_pct": diskPct,- "golden_version": p.goldenVersion,- }- data, _ := json.Marshal(payload)- if err := p.nc.Publish(subject, data); err != nil {- log.Printf("event_publisher: heartbeat publish error: %v", err)- }-}--// StartHeartbeat begins sending heartbeats every 5 seconds.-func (p *EventPublisher) StartHeartbeat(getStats func() (capacity, current int, cpuPct, memPct, diskPct float64)) {- p.wg.Add(1)- go func() {- defer p.wg.Done()- ticker := time.NewTicker(5 * time.Second)- defer ticker.Stop()-- for {- select {- case <-ticker.C:- cap, cur, cpu, mem, disk := getStats()- p.PublishHeartbeat(cap, cur, cpu, mem, disk)- case <-p.stop:- return- }- }- }()-}--func (p *EventPublisher) syncEvents() {- events, err := p.sandboxDBs.GetAllUnsyncedEventsFlat(100)- if err != nil || len(events) == 0 {- return- }-- // Group by sandbox for batch marking- synced := make(map[string][]int64)-- for _, se := range events {- subject := fmt.Sprintf("sandbox.events.%s.%s", p.region, p.workerID)- natsEvent := NATSEvent{- Type: se.Event.Type,- SandboxID: se.SandboxID,- WorkerID: p.workerID,- Region: p.region,- Payload: json.RawMessage(se.Event.Payload),- Timestamp: se.Timestamp,- }- data, _ := json.Marshal(natsEvent)-- if _, err := p.js.Publish(subject, data); err != nil {- log.Printf("event_publisher: publish error for sandbox %s: %v", se.SandboxID, err)- continue- }-- synced[se.SandboxID] = append(synced[se.SandboxID], se.Event.ID)- }-- // Mark synced events- for sandboxID, ids := range synced {- if err := p.sandboxDBs.MarkSynced(sandboxID, ids); err != nil {- log.Printf("event_publisher: mark synced error for sandbox %s: %v", sandboxID, err)- }- }-- if total := len(events); total > 0 {- log.Printf("event_publisher: synced %d events to NATS", total)- }-}diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex 84d01314..f8d7fca3 100644--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@ -243,6 +243,7 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq}s.router.Register(sb.ID, time.Duration(timeout)*time.Second)}+ s.initSandboxDB(sb.ID, cfg.Template)s.recordInitialScaleEvent(ctx, sb.ID, cfg)s.configureLogshipForSandbox(ctx, sb.ID)return &pb.CreateSandboxResponse{@@ -292,6 +293,7 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq}s.router.Register(sb.ID, time.Duration(timeout)*time.Second)}+ s.initSandboxDB(sb.ID, cfg.Template)s.recordInitialScaleEvent(ctx, sb.ID, cfg)s.configureLogshipForSandbox(ctx, sb.ID)return &pb.CreateSandboxResponse{@@ -325,16 +327,7 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReqs.router.Register(sb.ID, time.Duration(timeout)*time.Second)}- // Initialize per-sandbox SQLite- if s.sandboxDBs != nil {- sdb, err := s.sandboxDBs.Get(sb.ID)- if err == nil {- _ = sdb.LogEvent("created", map[string]string{- "sandbox_id": sb.ID,- "template": cfg.Template,- })- }- }+ s.initSandboxDB(sb.ID, cfg.Template)s.recordInitialScaleEvent(ctx, sb.ID, cfg)@@ -346,6 +339,36 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq}, nil}+// initSandboxDB opens the per-sandbox SQLite (creating + schema-initing it+// if missing) and logs a "created" event. Called from every CreateSandbox+// success path — including the fast-path ForkFromCheckpoint returns — so+// the UsageTicker and the destroy/hibernate terminal events always have a+// well-formed events table to write into.+//+// Pre-fix the ForkFromCheckpoint paths returned early without this init,+// so golden-fork-created sandboxes had no state.db until something else+// (usage_ticker.Get) lazily created an empty file. usage_tick LogEvents+// then failed silently because the schema wasn't applied.+func (s *GRPCServer) initSandboxDB(sandboxID, template string) {+ if s.sandboxDBs == nil {+ log.Printf("initSandboxDB: %s: sandboxDBs is nil — skipping", sandboxID)+ return+ }+ sdb, err := s.sandboxDBs.Get(sandboxID)+ if err != nil {+ log.Printf("initSandboxDB: %s: Get failed: %v", sandboxID, err)+ return+ }+ if err := sdb.LogEvent("created", map[string]string{+ "sandbox_id": sandboxID,+ "template": template,+ }); err != nil {+ log.Printf("initSandboxDB: %s: LogEvent failed: %v", sandboxID, err)+ return+ }+ log.Printf("initSandboxDB: %s: created event logged", sandboxID)+}+// recordInitialScaleEvent writes a sandbox_scale_events row marking the start// of billable usage for a freshly-created sandbox. Called from every successful// CreateSandbox return path — fork from checkpoint (local + S3-fallback) and@@ -398,8 +421,15 @@ func (s *GRPCServer) DestroySandbox(ctx context.Context, req *pb.DestroySandboxRs.router.Unregister(req.SandboxId)}- // Clean up SQLite+ // Emit terminal lifecycle event BEFORE removing the per-sandbox SQLite.+ // The SandboxDBManager's OnRemove hook synchronously flushes any unsynced+ // events to Redis, so this event makes it upstream to events-ingest, which+ // updates D1 sandboxes_index. Without this, terminations leak as phantoms+ // in the global view.if s.sandboxDBs != nil {+ if sdb, dbErr := s.sandboxDBs.Get(req.SandboxId); dbErr == nil {+ _ = sdb.LogEvent("stopped", map[string]string{"sandbox_id": req.SandboxId})+ }_ = s.sandboxDBs.Remove(req.SandboxId)}@@ -684,8 +714,16 @@ func (s *GRPCServer) HibernateSandbox(ctx context.Context, req *pb.HibernateSands.router.MarkHibernated(req.SandboxId, 600*time.Second)}- // Clean up per-sandbox SQLite+ // Emit hibernated lifecycle event BEFORE removing the per-sandbox SQLite.+ // The SandboxDBManager's OnRemove hook flushes synchronously so this event+ // reaches events-ingest and updates D1 sandboxes_index.if s.sandboxDBs != nil {+ if sdb, dbErr := s.sandboxDBs.Get(req.SandboxId); dbErr == nil {+ _ = sdb.LogEvent("hibernated", map[string]string{+ "sandbox_id": req.SandboxId,+ "checkpoint_key": result.HibernationKey,+ })+ }_ = s.sandboxDBs.Remove(req.SandboxId)}diff --git a/internal/worker/handlers.go b/internal/worker/handlers.goindex ae349508..9b5deee8 100644--- a/internal/worker/handlers.go+++ b/internal/worker/handlers.go@@ -6,6 +6,7 @@ import ("encoding/json""fmt""io"+ "log""net/http""time"@@ -544,12 +545,16 @@ func (s *HTTPServer) ptyWebSocket(c echo.Context) error {id := c.Param("id")sessionID := c.Param("sessionID")+ log.Printf("worker PTY: WS request for sandbox=%s session=%s", id, sessionID)+session, err := s.ptyManager.GetSession(sessionID)if err != nil {+ log.Printf("worker PTY: GetSession(%s) failed: %v", sessionID, err)return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})}if session.SandboxID != id {+ log.Printf("worker PTY: session.SandboxID=%s does not match path id=%s", session.SandboxID, id)return c.JSON(http.StatusNotFound, map[string]string{"error": "session not found"})}@@ -560,42 +565,57 @@ func (s *HTTPServer) ptyWebSocket(c echo.Context) error {ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)if err != nil {+ log.Printf("worker PTY: upgrade failed: %v", err)return err}defer ws.Close()+ log.Printf("worker PTY: WS upgraded for sandbox=%s session=%s", id, sessionID)done := make(chan struct{})go func() {defer close(done)buf := make([]byte, 4096)+ var totalBytes int64+ var firstLogged boolfor {n, err := session.PTY.Read(buf)if n > 0 {+ if !firstLogged {+ log.Printf("worker PTY: first PTY read for session=%s, %d bytes: %q", sessionID, n, string(buf[:min(n, 80)]))+ firstLogged = true+ }+ totalBytes += int64(n)// Touch on PTY output to keep sandbox aliveif s.router != nil {s.router.Touch(id)}if writeErr := ws.WriteMessage(websocket.BinaryMessage, buf[:n]); writeErr != nil {+ log.Printf("worker PTY: ws write failed (sent %d bytes): %v", totalBytes, writeErr)return}}if err != nil {+ log.Printf("worker PTY: PTY read closed (sent %d bytes): %v", totalBytes, err)return}}}()go func() {+ var totalBytes int64for {_, msg, err := ws.ReadMessage()if err != nil {+ log.Printf("worker PTY: ws read closed (received %d bytes): %v", totalBytes, err)return}+ totalBytes += int64(len(msg))// Touch on PTY input to keep sandbox aliveif s.router != nil {s.router.Touch(id)}if _, err := session.PTY.Write(msg); err != nil {+ log.Printf("worker PTY: PTY write failed (received %d bytes): %v", totalBytes, err)return}}diff --git a/internal/worker/redis_event_publisher.go b/internal/worker/redis_event_publisher.goindex 8a9bf40c..5e22045b 100644--- a/internal/worker/redis_event_publisher.go+++ b/internal/worker/redis_event_publisher.go@@ -163,6 +163,81 @@ func (p *RedisEventPublisher) run(ctx context.Context) {}}+// FlushSandbox synchronously publishes all unsynced events for a single+// sandbox. Used as the SandboxDBManager.OnRemove hook so terminal events+// (stopped, hibernated) make it to Redis before the per-sandbox SQLite file+// is deleted by the destroy / hibernate gRPC handler. Pre-fix, the 2s+// polling flush would race the Remove and silently drop terminal events,+// leaving the global view (D1 sandboxes_index) thinking the sandbox is+// still running.+//+// Synchronous on purpose: the caller (Remove) intentionally waits before+// closing the SQLite handle. A 10s timeout caps that wait so a Redis hiccup+// can't block destroy forever.+func (p *RedisEventPublisher) FlushSandbox(ctx context.Context, sandboxID string) {+ db, err := p.sandboxDBs.Get(sandboxID)+ if err != nil {+ log.Printf("redis_event_publisher: FlushSandbox %s: Get failed: %v", sandboxID, err)+ return+ }+ events, err := db.GetUnsyncedEvents(1000)+ if err != nil {+ log.Printf("redis_event_publisher: FlushSandbox %s: GetUnsyncedEvents: %v", sandboxID, err)+ return+ }+ if len(events) == 0 {+ return+ }++ xaddCtx, cancel := context.WithTimeout(ctx, 10*time.Second)+ defer cancel()++ orgID, plan := "", ""+ if p.resolver != nil {+ if o, pl, ok := p.resolver(sandboxID); ok {+ orgID, plan = o, pl+ }+ }++ var syncedIDs []int64+ for _, e := range events {+ ts, err := time.Parse(time.RFC3339Nano, e.CreatedAt)+ if err != nil {+ ts = time.Now()+ }+ envelope := SandboxEventEnvelope{+ ID: uuid.NewString(),+ Type: e.Type,+ SandboxID: sandboxID,+ OrgID: orgID,+ Plan: plan,+ WorkerID: p.workerID,+ CellID: p.cellID,+ Payload: json.RawMessage(e.Payload),+ Timestamp: ts,+ }+ body, mErr := json.Marshal(envelope)+ if mErr != nil {+ log.Printf("redis_event_publisher: FlushSandbox %s: marshal: %v", sandboxID, mErr)+ continue+ }+ if xErr := p.rdb.XAdd(xaddCtx, &redis.XAddArgs{+ Stream: p.streamKey,+ MaxLen: p.maxLen,+ Approx: true,+ Values: map[string]interface{}{"event": string(body)},+ }).Err(); xErr != nil {+ log.Printf("redis_event_publisher: FlushSandbox %s: XADD: %v", sandboxID, xErr)+ break+ }+ syncedIDs = append(syncedIDs, e.ID)+ }+ if len(syncedIDs) > 0 {+ _ = db.MarkEventsSynced(syncedIDs)+ log.Printf("redis_event_publisher: FlushSandbox %s: flushed %d event(s) before remove", sandboxID, len(syncedIDs))+ }+}+// flush reads up to BatchSize unsynced events per sandbox DB, XADDs each,// then marks them synced. On XADD failure, leaves them unsynced for retry.func (p *RedisEventPublisher) flush(ctx context.Context) {diff --git a/internal/worker/usage_ticker.go b/internal/worker/usage_ticker.gonew file mode 100644index 00000000..d15b2dfd--- /dev/null+++ b/internal/worker/usage_ticker.go@@ -0,0 +1,128 @@+package worker++import (+ "context"+ "log"+ "sync"+ "time"++ "github.com/opensandbox/opensandbox/internal/sandbox"+)++// UsageTicker emits a `usage_tick` event into each running sandbox's per-+// sandbox SQLite on a fixed interval. The RedisEventPublisher picks the+// events up on its 2s poll and ships them to the cell's Redis stream; the+// CF events-ingest Worker then fans them out to per-org CreditAccount DOs,+// which decrement the org's free-tier balance and dispatch a halt webhook+// when it hits zero.+//+// Without this ticker the DO never gets debited and free orgs run forever+// at $5 balance. The architectural intent (see events-ingest /debit fan-out)+// is exactly this periodic emit; no other component has the right scope to+// do it because:+// - The CP doesn't know about per-sandbox uptime granularity.+// - The worker is the only place that actually owns running VMs.+// - The DO can't self-schedule per-sandbox debit cadence.+//+// Cost model: every tick contributes a fixed cents amount per sandbox. For+// the dev/test bed this is set so that a free org's $5 seed exhausts in+// ~5 minutes of continuous running at the default interval — short enough+// to validate the halt loop, long enough that quick smoke tests don't+// burn the credit. Production should compute cents from RAM + CPU usage+// (memory_gb_seconds, cpu_seconds) — wired the same way, just a richer+// payload.+type UsageTicker struct {+ manager sandbox.Manager+ sandboxDBs *sandbox.SandboxDBManager+ interval time.Duration+ costPerTickCs int // cents per tick per running sandbox++ stop chan struct{}+ stopped chan struct{}+ once sync.Once+}++// NewUsageTicker constructs a ticker. interval ≤ 0 defaults to 20s,+// costPerTickCs ≤ 0 defaults to 10 cents (so $5 = 50 ticks ≈ 17 min).+// nil manager or nil sandboxDBs returns nil (ticker disabled).+func NewUsageTicker(manager sandbox.Manager, sandboxDBs *sandbox.SandboxDBManager, interval time.Duration, costPerTickCs int) *UsageTicker {+ if manager == nil || sandboxDBs == nil {+ return nil+ }+ if interval <= 0 {+ interval = 20 * time.Second+ }+ if costPerTickCs <= 0 {+ costPerTickCs = 10+ }+ return &UsageTicker{+ manager: manager,+ sandboxDBs: sandboxDBs,+ interval: interval,+ costPerTickCs: costPerTickCs,+ stop: make(chan struct{}),+ stopped: make(chan struct{}),+ }+}++// Start begins the tick loop. Safe to call once; subsequent calls are no-ops.+func (t *UsageTicker) Start(ctx context.Context) {+ go t.run(ctx)+}++// Stop signals the loop to exit and waits for it to drain.+func (t *UsageTicker) Stop(ctx context.Context) error {+ t.once.Do(func() { close(t.stop) })+ select {+ case <-t.stopped:+ case <-ctx.Done():+ return ctx.Err()+ }+ return nil+}++func (t *UsageTicker) run(ctx context.Context) {+ defer close(t.stopped)+ ticker := time.NewTicker(t.interval)+ defer ticker.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-t.stop:+ return+ case <-ticker.C:+ t.tick(ctx)+ }+ }+}++func (t *UsageTicker) tick(ctx context.Context) {+ list, err := t.manager.List(ctx)+ if err != nil {+ log.Printf("usage_ticker: manager.List failed: %v", err)+ return+ }+ if len(list) == 0 {+ log.Printf("usage_ticker: tick: 0 running sandboxes (skip)")+ return+ }+ emitted := 0+ for _, sb := range list {+ sdb, err := t.sandboxDBs.Get(sb.ID)+ if err != nil {+ log.Printf("usage_ticker: %s: Get failed: %v", sb.ID, err)+ continue+ }+ if err := sdb.LogEvent("usage_tick", map[string]interface{}{+ "sandbox_id": sb.ID,+ "cost_cents": t.costPerTickCs,+ "interval_s": int(t.interval.Seconds()),+ }); err != nil {+ log.Printf("usage_ticker: %s: LogEvent failed: %v", sb.ID, err)+ continue+ }+ emitted+++ }+ log.Printf("usage_ticker: tick: emitted %d usage_tick event(s) for %d running sandbox(es)", emitted, len(list))+}diff --git a/web/tsconfig.tsbuildinfo b/web/tsconfig.tsbuildinfoindex eae896d6..b041e74d 100644--- a/web/tsconfig.tsbuildinfo+++ b/web/tsconfig.tsbuildinfo@@ -1 +1 @@-{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/client.ts","./src/components/layout.tsx","./src/components/protectedroute.tsx","./src/components/terminal.tsx","./src/hooks/useauth.tsx","./src/pages/apikeys.tsx","./src/pages/billing.tsx","./src/pages/checkpoints.tsx","./src/pages/dashboard.tsx","./src/pages/login.tsx","./src/pages/sessiondetail.tsx","./src/pages/sessions.tsx","./src/pages/settings.tsx","./src/pages/templates.tsx"],"version":"5.6.3"}\ No newline at end of file+{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/client.ts","./src/components/layout.tsx","./src/components/logspanel.tsx","./src/components/protectedroute.tsx","./src/components/terminal.tsx","./src/hooks/useauth.tsx","./src/pages/apikeys.tsx","./src/pages/agentdetail.tsx","./src/pages/agents.tsx","./src/pages/billing.tsx","./src/pages/checkpoints.tsx","./src/pages/dashboard.tsx","./src/pages/login.tsx","./src/pages/sessiondetail.tsx","./src/pages/sessions.tsx","./src/pages/settings.tsx","./src/pages/templates.tsx"],"version":"5.6.3"}\ No newline at end of file