Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

feat(cloud): add plan entitlements and managed platform storage

Timothy Yinc1e7d62d4f1f
diff --git a/apps/cloud/app/components/CloudSitePublication.vue b/apps/cloud/app/components/CloudSitePublication.vue
index a994a15b..8f034f3e 100644
--- a/apps/cloud/app/components/CloudSitePublication.vue
+++ b/apps/cloud/app/components/CloudSitePublication.vue
@@ -8,8 +8,7 @@ const context = shallowRef(activeContext.value)
watch(activeContext, (next) => {
if (next?.scope === context.value?.scope) context.value = next
})
-const { admin, busy, photos, loading, failed, message, publish } =
- useCloudSiteMedia()
+const { admin, busy, failed, message, publish } = useCloudSiteMedia()
const { data, status, error, refresh } = useFetch<{
site: {
slug: string | null
@@ -87,9 +86,7 @@ async function unpublish() {
:variant="context?.published ? 'ghost' : 'default'"
size="sm"
:disabled="
- busy ||
- (!context?.published &&
- (!defaultDomainsReady || loading || !host || !photos.length))
+ busy || (!context?.published && (!defaultDomainsReady || !host))
"
:loading="busy"
@click="context?.published ? (unpublishOpen = true) : publish(true)"
@@ -166,17 +163,7 @@ async function unpublish() {
v-if="!context?.published"
class="cf-draft-hint"
>
- {{
- $t(
- loading
- ? 'cloud.ui.draftChecking'
- : !photos.length
- ? 'cloud.ui.draftNeedsPhoto'
- : admin
- ? 'cloud.ui.draftReady'
- : 'cloud.ui.draftAskAdmin',
- )
- }}
+ {{ $t(admin ? 'cloud.ui.draftReady' : 'cloud.ui.draftAskAdmin') }}
</p>
<p
v-else
diff --git a/apps/cloud/app/components/CloudStorageSettings.vue b/apps/cloud/app/components/CloudStorageSettings.vue
index 11f86c04..c6d0c863 100644
--- a/apps/cloud/app/components/CloudStorageSettings.vue
+++ b/apps/cloud/app/components/CloudStorageSettings.vue
@@ -1,6 +1,7 @@
<script setup lang="ts">
const {
connections,
+ allowance,
connectionId,
storage,
rotation,
@@ -35,6 +36,10 @@ const {
v-for="connection in connections"
:key="connection.id"
:value="connection.id"
+ :disabled="
+ connection.uploads_enabled === 0 ||
+ (!connection.pool_id && !allowance?.byosLimits.byos)
+ "
>
{{
$t('cloud.ui.connectionRevision', {
@@ -46,7 +51,11 @@ const {
</select></label
>
<details
- v-if="admin && connectionId"
+ v-if="
+ admin &&
+ connectionId &&
+ !connections.find((c) => c.id === connectionId)?.pool_id
+ "
class="cf-storage-details"
>
<summary>{{ $t('cloud.messages.rotateStorageCredentials') }}</summary>
@@ -80,7 +89,7 @@ const {
</form>
</details>
<details
- v-if="admin"
+ v-if="admin && allowance?.byosLimits.byos"
class="cf-storage-details"
>
<summary>{{ $t('cloud.messages.connectStorage') }}</summary>
diff --git a/apps/cloud/app/components/CloudUploadDrawer.vue b/apps/cloud/app/components/CloudUploadDrawer.vue
index 5845ceb4..a3bc7729 100644
--- a/apps/cloud/app/components/CloudUploadDrawer.vue
+++ b/apps/cloud/app/components/CloudUploadDrawer.vue
@@ -11,6 +11,8 @@ const {
currentFile,
cancel,
usage,
+ allowance,
+ fileLimit,
admin,
} = useCloudSiteMedia()
const context = useEntryContext().value,
@@ -50,13 +52,19 @@ async function dropFiles(event: DragEvent) {
><USelect
v-model="connectionId"
:items="
- connections.map((c) => ({ label: c.config.bucket, value: c.id }))
+ connections
+ .filter(
+ (c) =>
+ c.uploads_enabled !== 0 &&
+ (c.pool_id || allowance?.byosLimits.byos),
+ )
+ .map((c) => ({ label: c.config.bucket, value: c.id }))
"
class="w-full"
:disabled="uploading"
/></UFormField>
<i18n-t
- v-if="!connections.length"
+ v-if="!connections.length && allowance?.byosLimits.byos"
keypath="cloud.ui.connectStorageGuidance"
tag="p"
scope="global"
@@ -71,6 +79,12 @@ async function dropFiles(event: DragEvent) {
></template
>
</i18n-t>
+ <p
+ v-if="!connections.length && !allowance?.byosLimits.byos"
+ class="text-sm text-muted"
+ >
+ {{ $t('cloud.storageAllowance.unavailable') }}
+ </p>
<input
ref="input"
class="sr-only"
@@ -95,7 +109,9 @@ async function dropFiles(event: DragEvent) {
$t('cloud.messages.dropImagesHereOrChooseImagesAndMatchingMov')
}}</span
><span>{{
- $t('cloud.messages.upTo100MibPerPhotographIncludingItsPaired')
+ $t('cloud.storageAllowance.fileLimit', {
+ size: (fileLimit / 1048576).toFixed(0),
+ })
}}</span>
</button>
<div
@@ -117,6 +133,10 @@ async function dropFiles(event: DragEvent) {
$t('cloud.ui.uploadUsage', {
photos: usage.photos,
bytes: (usage.bytes / 1073741824).toFixed(2),
+ photoLimit: allowance?.limits.photos ?? '—',
+ uploadLimit: (
+ (allowance?.limits.monthlyBytes ?? 0) / 1073741824
+ ).toFixed(2),
})
}}
</p>
diff --git a/apps/cloud/app/composables/useCloudSiteMedia.ts b/apps/cloud/app/composables/useCloudSiteMedia.ts
index cf694339..37eca86a 100644
--- a/apps/cloud/app/composables/useCloudSiteMedia.ts
+++ b/apps/cloud/app/composables/useCloudSiteMedia.ts
@@ -30,6 +30,8 @@ export function useCloudMediaWorkspace(props: {
id: string
current_revision: number
healthy: number
+ uploads_enabled?: number
+ pool_id?: string | null
config: { bucket: string }
}[]
>([]),
@@ -47,6 +49,12 @@ export function useCloudMediaWorkspace(props: {
const usage = ref<{ photos: number; pending: number; bytes: number } | null>(
null,
)
+ const allowance = ref<{
+ plan: { id: string; name: string }
+ limits: Record<string, number>
+ byosLimits: Record<string, number>
+ storageBytes: number
+ } | null>(null)
const rotation = reactive({ accessKeyId: '', secretAccessKey: '' })
const editPhoto = reactive({
id: '',
@@ -71,6 +79,13 @@ export function useCloudMediaWorkspace(props: {
secretAccessKey: '',
})
const admin = computed(() => props.role === 'admin')
+ const fileLimit = computed(
+ () =>
+ (connections.value.find((c) => c.id === connectionId.value)?.pool_id
+ ? allowance.value?.limits
+ : allowance.value?.byosLimits
+ )?.fileBytes ?? 0,
+ )
let timer: ReturnType<typeof setInterval> | undefined,
controller: AbortController | undefined,
activeUpload: string | undefined,
@@ -90,7 +105,13 @@ export function useCloudMediaWorkspace(props: {
base.value + '/photos',
),
api<{ albums: typeof albums.value }>(base.value + '/albums'),
- api<{ usage: NonNullable<typeof usage.value> }>(base.value + '/usage'),
+ api<{
+ usage: NonNullable<typeof usage.value>
+ plan: { id: string; name: string }
+ limits: Record<string, number>
+ byosLimits: Record<string, number>
+ storageBytes: number
+ }>(base.value + '/usage'),
])
if (
generation !== reloadGeneration ||
@@ -98,12 +119,27 @@ export function useCloudMediaWorkspace(props: {
)
return
usage.value = u.usage
+ allowance.value = {
+ plan: u.plan,
+ limits: u.limits,
+ byosLimits: u.byosLimits,
+ storageBytes: u.storageBytes,
+ }
connections.value = s.connections
photos.value = p.photos
jobs.value = p.jobs
albums.value = a.albums
ready.value = true
- if (!connectionId.value) connectionId.value = s.connections[0]?.id ?? ''
+ if (
+ !connectionId.value ||
+ connections.value.find((c) => c.id === connectionId.value)
+ ?.uploads_enabled === 0 ||
+ (!u.byosLimits?.byos &&
+ !s.connections.find((c) => c.id === connectionId.value)?.pool_id)
+ )
+ connectionId.value =
+ s.connections.find((c) => c.pool_id && c.uploads_enabled !== 0)?.id ??
+ (u.byosLimits?.byos ? (s.connections[0]?.id ?? '') : '')
} catch (error) {
if (
generation !== reloadGeneration ||
@@ -346,11 +382,11 @@ export function useCloudMediaWorkspace(props: {
photo.name.replace(/\.[^.]+$/, '').toLowerCase(),
)
if (
- files.some((f) => f.size > 100 * 1024 * 1024) ||
+ files.some((f) => f.size > fileLimit.value) ||
files.some(
(file) =>
!isVideo(file) &&
- file.size + (companionFor(file)?.size ?? 0) > 100 * 1024 * 1024,
+ file.size + (companionFor(file)?.size ?? 0) > fileLimit.value,
) ||
files.every(isVideo)
) {
@@ -459,6 +495,8 @@ export function useCloudMediaWorkspace(props: {
jobs,
connections,
usage,
+ allowance,
+ fileLimit,
rotation,
editPhoto,
connectionId,
diff --git a/apps/cloud/app/pages/sites/[siteId]/domains.vue b/apps/cloud/app/pages/sites/[siteId]/domains.vue
index d6b06284..46feb514 100644
--- a/apps/cloud/app/pages/sites/[siteId]/domains.vue
+++ b/apps/cloud/app/pages/sites/[siteId]/domains.vue
@@ -285,13 +285,19 @@ async function copy(value: string) {
<CloudButton
v-if="data.admin"
size="sm"
- :disabled="busy || !data.enabled"
+ :disabled="busy || !data.enabled || !data.customDomainLimit"
@click="beginAdd"
><Plus :size="14" />{{ t('cloud.domains.add') }}</CloudButton
>
</div>
<p
- v-if="!data.enabled"
+ v-if="!data.customDomainLimit"
+ class="cf-notice"
+ >
+ {{ t('cloud.storageAllowance.noCustomDomains') }}
+ </p>
+ <p
+ v-else-if="!data.enabled"
class="cf-notice"
>
{{ t('cloud.domains.disabled') }}
diff --git a/apps/cloud/app/pages/sites/[siteId]/storage.vue b/apps/cloud/app/pages/sites/[siteId]/storage.vue
index bbe0e3e0..a146100d 100644
--- a/apps/cloud/app/pages/sites/[siteId]/storage.vue
+++ b/apps/cloud/app/pages/sites/[siteId]/storage.vue
@@ -1,5 +1,6 @@
<script setup lang="ts">
const { t } = useI18n()
+const { allowance } = useCloudSiteMedia()
definePageMeta({ layout: 'portal' })
useSeoMeta({
@@ -20,13 +21,11 @@ useSeoMeta({
<CloudStorageSettings /><CloudCard
><div class="cf-panel-heading">
<h2>{{ $t('cloud.messages.platformStorage') }}</h2>
- <CloudBadge>{{ $t('cloud.messages.comingLater') }}</CloudBadge>
- <p>
- {{
- $t(
- 'cloud.messages.managedStorageAndPlanAllowancesAreNotAvailableYet',
- )
- }}
+ <CloudBadge>{{ allowance?.plan.name ?? '—' }}</CloudBadge>
+ <p>{{ $t('cloud.storageAllowance.description') }}</p>
+ <p v-if="allowance">
+ {{ (allowance.storageBytes / 1048576).toFixed(1) }} MiB /
+ {{ (allowance.limits.storageBytes! / 1048576).toFixed(0) }} MiB
</p>
</div></CloudCard
>
diff --git a/apps/cloud/i18n/locales/en.json b/apps/cloud/i18n/locales/en.json
index df699222..3bc74759 100644
--- a/apps/cloud/i18n/locales/en.json
+++ b/apps/cloud/i18n/locales/en.json
@@ -110,7 +110,7 @@
"sites": "Sites",
"createSite": "Create site",
"createASite": "Create a site",
- "startWithAPrivateDraftYourAddressIsReserved": "Start with a private draft. Your address is reserved until publishing is available.",
+ "startWithAPrivateDraftYourAddressIsReserved": "Your site is published immediately after creation. No photographs or storage setup are required.",
"siteName": "Site name",
"siteAddress": "Site address",
"use340LowercaseLettersNumbersOrHyphensSome": "Use 3–40 lowercase letters, numbers or hyphens. Some addresses are reserved. The address cannot be changed here.",
@@ -250,7 +250,7 @@
"status": "Status",
"role": "Role",
"noSitesYet": "No sites yet",
- "createADraftAboveToReserveYourGalleryS": "Create a draft above to reserve your gallery’s address.",
+ "createADraftAboveToReserveYourGalleryS": "Create your first gallery. Empty galleries are published automatically.",
"onlySitesYouBelongToAppearHere": "Only sites you belong to appear here.",
"viewDocumentation": "View documentation",
"cover": "Cover",
@@ -310,7 +310,7 @@
"photographUpdated": "Photograph updated.",
"uploadUnavailable": "Upload unavailable",
"uploadFailed": "Upload failed",
- "eachPhotographAndItsMatchingLivePhotoMovMust": "Each photograph and its matching Live Photo MOV must total at most 100 MiB. A MOV must accompany a photograph with the same filename.",
+ "eachPhotographAndItsMatchingLivePhotoMovMust": "Each photograph and its paired video must fit within your plan’s file limit.",
"uploadVerifiedProcessingContinuesInTheBackground": "Upload verified. Processing continues in the background.",
"uploadCancelled": "Upload cancelled.",
"uploadInterruptedSelectTheSameFileToResumeIts": "Upload interrupted. Select the same file to resume its uploaded parts.",
@@ -436,7 +436,7 @@
"photoMembershipCount": "Photographs · {count}",
"securityFor": "Manage sign-in methods for {email}.",
"uploadProgress": "{progress}% · Uploading to your private bucket",
- "uploadUsage": "{photos} / 1,000 photographs · {bytes} / 5 GiB uploaded in 30 days",
+ "uploadUsage": "{photos} / {photoLimit} photographs · {bytes} / {uploadLimit} GiB uploaded in 30 days",
"connectionRevision": "{bucket} · revision {revision}",
"admin": "Admin",
"member": "Member",
@@ -451,7 +451,7 @@
"processingFailure": "Processing could not finish ({code}). Retry or contact the operator.",
"draftChecking": "This address returns 404 until you publish your gallery. Checking photographs…",
"draftNeedsPhoto": "This address returns 404 until you publish your gallery. Upload a photograph and wait for processing to finish before publishing.",
- "draftReady": "This address returns 404 until you publish your gallery. Ready to share? Select Publish gallery above.",
+ "draftReady": "Ready to publish, even without photographs.",
"draftAskAdmin": "This address returns 404 until you publish your gallery. Ask a workspace administrator to publish this gallery.",
"passwordSetupGuidance": "You signed in with an email code. {link} before enabling two-step verification.",
"connectStorageGuidance": "Connect your private storage in {link} before uploading.",
@@ -569,6 +569,12 @@
"removingHelp": "Public access has stopped. We are removing this connection.",
"expiredHelp": "This request expired before verification. Remove it and add the domain again.",
"checksPaused": "Checks are paused for this domain."
+ },
+ "storageAllowance": {
+ "description": "Storage is provided by your plan. Empty galleries are published automatically; uploading photographs is optional.",
+ "fileLimit": "Up to {size} MiB per photograph, including its paired video.",
+ "noCustomDomains": "Your plan does not include custom domains. Your default site address remains available.",
+ "unavailable": "Platform uploads are temporarily unavailable. Your site remains published; no custom storage setup is required."
}
}
}
diff --git a/apps/cloud/i18n/locales/zh-Hans.json b/apps/cloud/i18n/locales/zh-Hans.json
index 2dcf5037..9a845142 100644
--- a/apps/cloud/i18n/locales/zh-Hans.json
+++ b/apps/cloud/i18n/locales/zh-Hans.json
@@ -110,7 +110,7 @@
"sites": "站点",
"createSite": "创建站点",
"createASite": "创建站点",
- "startWithAPrivateDraftYourAddressIsReserved": "先创建一个私密草稿,发布前会为你保留站点地址。",
+ "startWithAPrivateDraftYourAddressIsReserved": "创建后站点会立即发布,无需先上传照片或配置存储。",
"siteName": "站点名称",
"siteAddress": "站点地址",
"use340LowercaseLettersNumbersOrHyphensSome": "使用 3–40 个小写字母、数字或连字符。部分地址已被保留,此处暂不支持修改地址。",
@@ -250,7 +250,7 @@
"status": "状态",
"role": "角色",
"noSitesYet": "暂无站点",
- "createADraftAboveToReserveYourGalleryS": "在上方创建草稿,预留图库地址。",
+ "createADraftAboveToReserveYourGalleryS": "创建你的第一个图库。空图库也会自动发布。",
"onlySitesYouBelongToAppearHere": "此处仅显示你加入的站点。",
"viewDocumentation": "查看文档",
"cover": "封面",
@@ -310,7 +310,7 @@
"photographUpdated": "照片已更新。",
"uploadUnavailable": "无法上传",
"uploadFailed": "上传失败",
- "eachPhotographAndItsMatchingLivePhotoMovMust": "每张照片及其配对的实况 MOV 视频总大小不能超过 100 MiB。MOV 文件必须与同名照片一起上传。",
+ "eachPhotographAndItsMatchingLivePhotoMovMust": "每张照片及配对视频必须在套餐的单文件上限内。",
"uploadVerifiedProcessingContinuesInTheBackground": "上传已验证,正在后台继续处理。",
"uploadCancelled": "上传已取消。",
"uploadInterruptedSelectTheSameFileToResumeIts": "上传已中断,重新选择同一文件即可继续上传剩余部分。",
@@ -436,7 +436,7 @@
"photoMembershipCount": "照片 · {count}",
"securityFor": "管理 {email} 的登录方式。",
"uploadProgress": "{progress}% · 正在上传到你的私有存储桶",
- "uploadUsage": "{photos} / 1,000 张照片 · {bytes} / 5 GiB(近 30 天上传量)",
+ "uploadUsage": "{photos} / {photoLimit} 张照片 · 30 天上传 {bytes} / {uploadLimit} GiB",
"connectionRevision": "{bucket} · 凭证版本 {revision}",
"admin": "管理员",
"member": "成员",
@@ -451,7 +451,7 @@
"processingFailure": "处理未能完成({code}),请重试或联系平台管理员。",
"draftChecking": "发布图库之前,访问此地址将返回 404。正在检查照片…",
"draftNeedsPhoto": "发布图库之前,访问此地址将返回 404。请先上传照片,等待处理完成后再发布。",
- "draftReady": "发布图库之前,访问此地址将返回 404。准备好分享了吗?点击上方的“发布图库”。",
+ "draftReady": "随时可以发布,即使图库中还没有照片。",
"draftAskAdmin": "发布图库之前,访问此地址将返回 404。请联系工作区管理员发布此图库。",
"passwordSetupGuidance": "你使用邮箱验证码登录。请先{link},再启用两步验证。",
"connectStorageGuidance": "上传前,请先在{link}中连接私有存储。",
@@ -569,6 +569,12 @@
"removingHelp": "已停止公开访问,正在移除此连接。",
"expiredHelp": "此申请在完成验证前已过期,请移除后重新添加域名。",
"checksPaused": "已暂停此域名的状态检查。"
+ },
+ "storageAllowance": {
+ "description": "按套餐提供平台存储。创建站点后自动发布,上传照片不是发布前置条件。",
+ "fileLimit": "每张照片最大 {size} MiB(包含配对视频)",
+ "noCustomDomains": "当前套餐不包含自定义域名,你仍可使用站点的默认地址。",
+ "unavailable": "平台上传暂不可用。你的站点仍已发布,无需配置自定义存储。"
}
}
}
diff --git a/apps/cloud/server/api/internal/worker/[action].post.ts b/apps/cloud/server/api/internal/worker/[action].post.ts
index 4f81a0b6..9b62297e 100644
--- a/apps/cloud/server/api/internal/worker/[action].post.ts
+++ b/apps/cloud/server/api/internal/worker/[action].post.ts
@@ -1,3 +1,7 @@
+import {
+ workspaceEntitlements,
+ workspaceUsageSQL,
+} from '@chronoframe/platform/entitlements'
import { createError, getHeader, getRequestWebStream, getRouterParam } from 'h3'
import { createCloudExecutionRepository } from '@chronoframe/database/cloud-execution'
import type { MediaDatabase } from '@chronoframe/database/cloud-media'
@@ -57,7 +61,12 @@ export default definePlatformHandler(async (event) => {
if (!item) throw createError({ statusCode: 503 })
return createCloudS3(
{ ...item.config, ...item.credentials },
- { allowedHosts },
+ {
+ allowedHosts:
+ 'poolId' in item
+ ? [...allowedHosts, new URL(item.config.endpoint).hostname]
+ : allowedHosts,
+ },
)
}
if (action === 'claim') {
@@ -317,6 +326,52 @@ export default definePlatformHandler(async (event) => {
lease.connectionId,
lease.connectionRevision,
)
+ const declared = body.assets as {
+ role: string
+ bytes: number
+ contentType: string
+ }[]
+ if (
+ declared.some((a) => !Number.isSafeInteger(a.bytes) || a.bytes < 1) ||
+ new Set(declared.map((a) => a.role)).size !== declared.length
+ )
+ throw createError({ statusCode: 400 })
+ const outputBytes = declared.reduce((n, a) => n + a.bytes, 0)
+ if (!Number.isSafeInteger(outputBytes))
+ throw createError({ statusCode: 400 })
+ const connection = await raw
+ .prepare(
+ 'SELECT c.pool_id,s.workspace_id FROM cloud_storage_connections c JOIN platform_sites s ON s.id=c.site_id WHERE c.site_id=? AND c.id=?',
+ )
+ .bind(lease.siteId, lease.connectionId)
+ .first<{ pool_id: string | null; workspace_id: number }>()
+ if (connection?.pool_id) {
+ const plan = await workspaceEntitlements(
+ raw,
+ connection.workspace_id,
+ 'platform',
+ )
+ const expression = workspaceUsageSQL(lease.siteId)
+ const reservation = await raw
+ .prepare(`UPDATE cloud_processing_jobs SET reserved_output_bytes=? WHERE site_id=? AND id=? AND attempt_id=? AND state='running' AND lease_until>?
+ AND ${expression.storage}-reserved_output_bytes+?<=? RETURNING id`)
+ .bind(
+ outputBytes,
+ lease.siteId,
+ lease.id,
+ lease.attemptId,
+ now,
+ now,
+ outputBytes,
+ plan.limits.storageBytes,
+ )
+ .first()
+ if (!reservation)
+ throw createError({
+ statusCode: 429,
+ statusMessage: 'Storage quota exceeded',
+ })
+ }
const outputs = []
for (const asset of body.assets as {
role: string
@@ -348,6 +403,22 @@ export default definePlatformHandler(async (event) => {
if (action === 'complete') {
if (!(await queue.heartbeat(lease, now, 120000))) return { ok: false }
const result = body.result as CloudMediaResult
+ const budget = await raw
+ .prepare(
+ `SELECT j.reserved_output_bytes,c.pool_id FROM cloud_processing_jobs j JOIN cloud_uploads u ON u.site_id=j.site_id AND u.id=j.upload_id JOIN cloud_storage_connections c ON c.site_id=u.site_id AND c.id=u.connection_id WHERE j.site_id=? AND j.id=? AND j.attempt_id=?`,
+ )
+ .bind(lease.siteId, lease.id, lease.attemptId)
+ .first<{ reserved_output_bytes: number; pool_id: string | null }>()
+ if (
+ budget?.pool_id &&
+ (!Array.isArray(result?.assets) ||
+ result.assets.some(
+ (a) => !Number.isSafeInteger(a.bytes) || a.bytes < 1,
+ ) ||
+ result.assets.reduce((n, a) => n + a.bytes, 0) >
+ budget.reserved_output_bytes)
+ )
+ throw createError({ statusCode: 409 })
if (!result || !Array.isArray(result.assets))
throw createError({ statusCode: 400 })
const canonical = await raw
diff --git a/apps/cloud/server/api/sites/[siteId]/domains.get.ts b/apps/cloud/server/api/sites/[siteId]/domains.get.ts
index fa17deac..b487f847 100644
--- a/apps/cloud/server/api/sites/[siteId]/domains.get.ts
+++ b/apps/cloud/server/api/sites/[siteId]/domains.get.ts
@@ -1,3 +1,4 @@
+import { workspaceEntitlements } from '@chronoframe/platform/entitlements'
import { getRouterParam } from 'h3'
import {
definePlatformHandler,
@@ -22,6 +23,8 @@ export default definePlatformHandler(async (event) => {
config.baseDomain,
)
return {
+ customDomainLimit: (await workspaceEntitlements(db, site.workspaceId))
+ .limits.customDomains,
defaultHostname,
legacyHostname: await legacySiteHost(db, siteId),
baseDomain: config.baseDomain,
diff --git a/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts b/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts
index f20ec14f..7e94f4f6 100644
--- a/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts
+++ b/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts
@@ -1,3 +1,7 @@
+import {
+ workspaceEntitlements,
+ workspaceUsageSQL,
+} from '@chronoframe/platform/entitlements'
import { DomainError } from '@chronoframe/platform/domains'
import { defaultSiteHost, validSiteSlug } from '@chronoframe/contracts/domains'
import type { MediaDatabase } from '@chronoframe/database/cloud-media'
@@ -49,8 +53,36 @@ export default definePlatformHandler(async (event) => {
const body = mutation ? await siteManagementBody(event, 131072) : {}
const now = Date.now()
if (kind === 'storage' && !id) {
- if (event.method === 'GET') return { connections: await vault.list() }
+ if (event.method === 'GET') {
+ const available = await raw
+ .prepare(
+ 'SELECT id,name FROM platform_storage_pools WHERE enabled=1 ORDER BY id LIMIT 1',
+ )
+ .first<{ id: string; name: string }>()
+ const plan = await workspaceEntitlements(
+ raw,
+ site.workspaceId,
+ 'platform',
+ )
+ let connections = await vault.list()
+ if (available && !connections.some((c) => c.pool_id === available.id)) {
+ await vault.attachPool(available.id, now)
+ connections = await vault.list()
+ }
+ return {
+ connections,
+ platformAvailable: !!available,
+ plan,
+ }
+ }
if (event.method !== 'POST') throw createError({ statusCode: 405 })
+ if (
+ !(await workspaceEntitlements(raw, site.workspaceId, 'byos')).limits.byos
+ )
+ throw createError({
+ statusCode: 403,
+ statusMessage: 'Your plan does not include custom storage',
+ })
if ((await vault.list()).length >= 20)
throw createError({ statusCode: 429 })
const config = {
@@ -83,6 +115,11 @@ export default definePlatformHandler(async (event) => {
) {
const old = await vault.get(ID(id))
if (!old) throw createError({ statusCode: 404 })
+ if (
+ 'poolId' in old ||
+ !(await workspaceEntitlements(raw, site.workspaceId, 'byos')).limits.byos
+ )
+ throw createError({ statusCode: 403 })
const credentials = {
accessKeyId: text(body.accessKeyId, 256),
secretAccessKey: text(body.secretAccessKey, 256),
@@ -97,6 +134,12 @@ export default definePlatformHandler(async (event) => {
return { ok: true }
}
if (kind === 'usage' && event.method === 'GET') {
+ const plan = await workspaceEntitlements(raw, site.workspaceId, 'platform')
+ const expression = workspaceUsageSQL(siteId)
+ const storageUsage = await raw
+ .prepare(`SELECT ${expression.storage} AS bytes`)
+ .bind(now)
+ .first<{ bytes: number }>()
const usage = (
await sql<{ photos: number; pending: number; bytes: number }>(
`SELECT (SELECT COUNT(*) FROM cloud_photos WHERE site_id=? AND deleted=0) AS photos,(SELECT COUNT(*) FROM cloud_uploads WHERE site_id=? AND state='pending' AND expires_at>?) AS pending,COALESCE((SELECT SUM(bytes) FROM cloud_usage_events WHERE site_id=? AND created_at>?),0) AS bytes`,
@@ -109,7 +152,11 @@ export default definePlatformHandler(async (event) => {
)[0]
return {
usage,
- limits: { fileBytes: 104857600, photos: 1000, monthlyBytes: 5368709120 },
+ limits: plan.limits,
+ byosLimits: (await workspaceEntitlements(raw, site.workspaceId, 'byos'))
+ .limits,
+ plan: { id: plan.id, name: plan.name },
+ storageBytes: storageUsage?.bytes ?? 0,
}
}
if (kind === 'uploads' && !id && event.method === 'POST') {
@@ -131,19 +178,36 @@ export default definePlatformHandler(async (event) => {
throw createError({ statusCode: 400 })
const ext = fileName.split('.').pop()?.toLowerCase() ?? '',
contentType = types[ext]
- if (!contentType || bytes + videoBytes > 104857600)
+ const storedConnection = await vault.get(connectionId)
+ if (!storedConnection) throw createError({ statusCode: 404 })
+ const managed = 'poolId' in storedConnection
+ const entitlement = await workspaceEntitlements(
+ raw,
+ site.workspaceId,
+ managed ? 'platform' : 'byos',
+ )
+ if (!managed && !entitlement.limits.byos)
+ throw createError({
+ statusCode: 403,
+ statusMessage: 'Your plan does not include custom storage',
+ })
+ if (managed && !storedConnection.enabled)
+ throw createError({
+ statusCode: 503,
+ statusMessage: 'Platform uploads temporarily unavailable',
+ })
+ if (!contentType || bytes + videoBytes > entitlement.limits.fileBytes)
throw createError({ statusCode: 400 })
let upload = await repository.upload(uploadId, userId)
if (!upload) {
- const stored = await vault.get(connectionId)
- if (!stored) throw createError({ statusCode: 404 })
+ const stored = storedConnection
+ const expression = workspaceUsageSQL(siteId)
const objectKey = `chronoframe/${siteId}/originals/${uploadId}/1/source.${ext}`
await db.batch([
db
- .prepare(`INSERT INTO cloud_uploads(site_id,id,owner_id,photo_id,source_version,connection_id,connection_revision,object_key,expected_bytes,expires_at,content_type,file_name,expected_video_bytes,video_key)
- SELECT ?,?,?,?,'1',?,?,?,?,?,?,?,?,? WHERE
- (SELECT COUNT(*) FROM cloud_photos WHERE site_id=? AND deleted=0)+(SELECT COUNT(*) FROM cloud_uploads WHERE site_id=? AND state='pending' AND expires_at>?)<1000 AND
- COALESCE((SELECT SUM(bytes) FROM cloud_usage_events WHERE site_id=? AND created_at>?),0)+COALESCE((SELECT SUM(expected_bytes+expected_video_bytes) FROM cloud_uploads WHERE site_id=? AND state='pending' AND expires_at>?),0)+?<=5368709120
+ .prepare(`INSERT INTO cloud_uploads(site_id,id,owner_id,photo_id,source_version,connection_id,connection_revision,object_key,expected_bytes,expires_at,content_type,file_name,expected_video_bytes,video_key,reserved_storage_bytes)
+ SELECT ?,?,?,?,'1',?,?,?,?,?,?,?,?,?,? WHERE
+ ${expression.photos}<? AND ${expression.monthly}+?<=? AND (?=0 OR ${expression.storage}+?<=?)
ON CONFLICT DO NOTHING`)
.bind(
siteId,
@@ -161,14 +225,17 @@ export default definePlatformHandler(async (event) => {
liveVideo
? `chronoframe/${siteId}/originals/${uploadId}/1/source.MOV`
: null,
- siteId,
- siteId,
+ managed ? bytes + videoBytes : 0,
now,
- siteId,
+ entitlement.limits.photos,
now - 30 * 86400000,
- siteId,
now,
bytes + videoBytes,
+ entitlement.limits.monthlyBytes,
+ managed ? 1 : 0,
+ now,
+ bytes + videoBytes,
+ entitlement.limits.storageBytes,
),
])
upload = await repository.upload(uploadId, userId)
@@ -669,8 +736,6 @@ export default definePlatformHandler(async (event) => {
String(useRuntimeConfig(event).public.defaultDomainsReady) !== 'true')
)
throw new DomainError(503, 'domain_routing_unavailable')
- if (published && !(await ctx.resources.listPhotos()).length)
- throw createError({ statusCode: 400 })
const hostname = validSiteSlug(site.slug)
? defaultSiteHost(
site.slug,
diff --git a/apps/cloud/server/middleware/00-account-session.ts b/apps/cloud/server/middleware/00-account-session.ts
index ce49f76d..bed32e2a 100644
--- a/apps/cloud/server/middleware/00-account-session.ts
+++ b/apps/cloud/server/middleware/00-account-session.ts
@@ -1,3 +1,4 @@
+import { platformDatabase } from '../../../shared/platform/runtime'
import { getCookie, getRequestHeaders } from 'h3'
import { cloudAccount } from '../utils/cloud-account'
/** Provide Cloud's account session to shared Site authorization, with numeric identity intact. */
@@ -8,7 +9,16 @@ export default defineEventHandler((event) => {
headers: new Headers(getRequestHeaders(event) as HeadersInit),
})
const id = Number(session?.user.id)
- return session &&
+ const control = session
+ ? await platformDatabase(event)
+ .prepare(
+ 'SELECT suspended FROM platform_account_controls WHERE user_id=?',
+ )
+ .bind(id)
+ .first<{ suspended: number }>()
+ : null
+ return !control?.suspended &&
+ session &&
session.user.emailVerified &&
Number.isSafeInteger(id) &&
id > 0
diff --git a/apps/cloud/server/utils/cloud-media.ts b/apps/cloud/server/utils/cloud-media.ts
index 10e7b9ab..899e303d 100644
--- a/apps/cloud/server/utils/cloud-media.ts
+++ b/apps/cloud/server/utils/cloud-media.ts
@@ -52,11 +52,12 @@ export async function cloudMedia(event: H3Event, mutation = false) {
throw createError({ statusCode: 429 })
}
const cfg = useRuntimeConfig(event).platform
- const vault = createStorageVault(
- raw,
- siteId,
- await createStorageCipher(cfg.storageSecret),
- )
+ const vault = createStorageVault(raw, siteId, {
+ seal: async (value, context) =>
+ (await createStorageCipher(cfg.storageSecret)).seal(value, context),
+ open: async (value, context) =>
+ (await createStorageCipher(cfg.storageSecret)).open(value, context),
+ })
const allowedHosts = cfg.s3EndpointHosts
.split(',')
.map((h) => h.trim())
@@ -68,7 +69,12 @@ export async function cloudMedia(event: H3Event, mutation = false) {
revision: item.revision,
s3: createCloudS3(
{ ...item.config, ...item.credentials },
- { allowedHosts },
+ {
+ allowedHosts:
+ 'poolId' in item
+ ? [...allowedHosts, new URL(item.config.endpoint).hostname]
+ : allowedHosts,
+ },
),
}
}
diff --git a/apps/shared/platform/media.ts b/apps/shared/platform/media.ts
index a598bd6e..d3f1c880 100644
--- a/apps/shared/platform/media.ts
+++ b/apps/shared/platform/media.ts
@@ -111,7 +111,11 @@ export async function privateMedia(
const s3 = createCloudS3(
{ ...stored.config, ...stored.credentials },
{
- allowedHosts: config.s3EndpointHosts
+ allowedHosts: (
+ ('poolId' in stored
+ ? new URL(stored.config.endpoint).hostname + ','
+ : '') + config.s3EndpointHosts
+ )
.split(',')
.map((v: string) => v.trim())
.filter(Boolean),
diff --git a/apps/worker/src/process.ts b/apps/worker/src/process.ts
index fc5f5151..f47b37d0 100644
--- a/apps/worker/src/process.ts
+++ b/apps/worker/src/process.ts
@@ -36,7 +36,7 @@ export async function boundedDownload(
signal: AbortSignal,
etag?: string,
) {
- if (!Number.isSafeInteger(expected) || expected < 1 || expected > 104857600)
+ if (!Number.isSafeInteger(expected) || expected < 1 || expected > 1073741824)
throw new WorkerProcessingError('invalid_source_size', false)
const parsed = new URL(url)
if (parsed.protocol !== 'https:')
@@ -147,7 +147,7 @@ export async function processWork(
: contentType === 'video/mp4'
? 'live-video'
: null
- if (!role || buffer.length > 104857600)
+ if (!role || buffer.length > 1073741824)
throw new Error('invalid_derivative')
derivatives.push({
role,
diff --git a/packages/contracts/src/domains.ts b/packages/contracts/src/domains.ts
index d85f7217..4e5bda62 100644
--- a/packages/contracts/src/domains.ts
+++ b/packages/contracts/src/domains.ts
@@ -105,6 +105,7 @@ export interface CustomDomain {
nextCheckAt: number
}
export interface DomainOverview {
+ customDomainLimit?: number
defaultHostname: string | null
legacyHostname: string | null
baseDomain: string
diff --git a/packages/platform/migrations/0014_entitlements.sql b/packages/platform/migrations/0014_entitlements.sql
new file mode 100644
index 00000000..3745f243
--- /dev/null
+++ b/packages/platform/migrations/0014_entitlements.sql
@@ -0,0 +1,42 @@
+CREATE TABLE platform_plans (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ policy_json TEXT NOT NULL CHECK(json_valid(policy_json)),
+ revision INTEGER NOT NULL DEFAULT 1,
+ active INTEGER NOT NULL DEFAULT 1 CHECK(active IN(0,1))
+);
+INSERT INTO platform_plans(id,name,policy_json) VALUES('free','Free','{"limits":{"byos":0,"storageBytes":1073741824,"fileBytes":20971520,"sites":1,"customDomains":0,"photos":1000,"monthlyBytes":5368709120},"rules":[]}');
+CREATE TABLE platform_workspace_plans (
+ workspace_id INTEGER PRIMARY KEY REFERENCES platform_workspaces(id),
+ plan_id TEXT NOT NULL REFERENCES platform_plans(id),
+ revision INTEGER NOT NULL DEFAULT 1
+);
+CREATE TABLE platform_storage_pools (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ current_revision INTEGER NOT NULL DEFAULT 1,
+ revision INTEGER NOT NULL DEFAULT 1,
+ enabled INTEGER NOT NULL DEFAULT 0 CHECK(enabled IN(0,1)),
+ checked_at INTEGER NOT NULL
+);
+CREATE TABLE platform_storage_pool_versions (
+ pool_id TEXT NOT NULL REFERENCES platform_storage_pools(id),
+ revision INTEGER NOT NULL,
+ public_json TEXT NOT NULL CHECK(json_valid(public_json)),
+ secret_ciphertext TEXT NOT NULL,
+ PRIMARY KEY(pool_id,revision)
+);
+ALTER TABLE cloud_storage_connections ADD COLUMN pool_id TEXT REFERENCES platform_storage_pools(id);
+ALTER TABLE cloud_storage_connections ADD COLUMN pool_revision INTEGER;
+CREATE UNIQUE INDEX cloud_site_pool ON cloud_storage_connections(site_id,pool_id) WHERE pool_id IS NOT NULL;
+ALTER TABLE cloud_uploads ADD COLUMN reserved_storage_bytes INTEGER NOT NULL DEFAULT 0;
+ALTER TABLE cloud_processing_jobs ADD COLUMN reserved_output_bytes INTEGER NOT NULL DEFAULT 0;
+CREATE TABLE platform_account_controls (
+ user_id INTEGER PRIMARY KEY REFERENCES platform_users(id),
+ suspended INTEGER NOT NULL DEFAULT 0 CHECK(suspended IN(0,1)),
+ revision INTEGER NOT NULL DEFAULT 1
+);
+ALTER TABLE platform_sites ADD COLUMN suspended INTEGER NOT NULL DEFAULT 0 CHECK(suspended IN(0,1));
+
+ALTER TABLE platform_workspaces ADD COLUMN created_at INTEGER NOT NULL DEFAULT 0;
+UPDATE platform_workspaces SET created_at=COALESCE((SELECT created_at FROM platform_users WHERE id=owner_user_id),CAST(strftime('%s','now') AS INTEGER)*1000);
diff --git a/packages/platform/package.json b/packages/platform/package.json
index 9a48fc0b..cc26060e 100644
--- a/packages/platform/package.json
+++ b/packages/platform/package.json
@@ -6,7 +6,8 @@
"license": "AGPL-3.0-only",
"exports": {
".": "./src/index.ts",
- "./domains": "./src/domains.ts"
+ "./domains": "./src/domains.ts",
+ "./entitlements": "./src/entitlements.ts"
},
"scripts": {
"type-check": "tsc --noEmit"
diff --git a/packages/platform/src/domains.ts b/packages/platform/src/domains.ts
index 6268d5ad..9635ca41 100644
--- a/packages/platform/src/domains.ts
+++ b/packages/platform/src/domains.ts
@@ -1,3 +1,4 @@
+import { workspaceEntitlements } from './entitlements.ts'
import {
DEFAULT_CNAME_TARGET,
DEFAULT_SITE_BASE,
@@ -110,7 +111,6 @@ export function createDomainManager(
const base = normalizeDomain(config.baseDomain || DEFAULT_SITE_BASE)
const target = normalizeDomain(config.cnameTarget || DEFAULT_CNAME_TARGET)
const resourceLimit = Math.max(1, Math.min(config.limit, 20))
- const workspaceLimit = Math.min(4, Math.max(1, Math.floor(resourceLimit / 2)))
const memberGuard = `EXISTS(SELECT 1 FROM platform_sites s JOIN platform_memberships m ON m.workspace_id=s.workspace_id WHERE s.id=? AND m.user_id=? AND m.role='admin')`
async function authorize(userId: number, siteId: number, admin = true) {
const row = await stmt(
@@ -188,6 +188,12 @@ export function createDomainManager(
}
if (existing && (existing.provider_id || existing.route_id))
throw new DomainError(409, 'domain_cleanup_pending')
+ const workspace = await stmt(
+ 'SELECT workspace_id FROM platform_sites WHERE id=?',
+ siteId,
+ ).first<{ workspace_id: number }>()
+ const plan = await workspaceEntitlements(db, workspace!.workspace_id)
+ if (!plan.limits.customDomains) throw new DomainError(403, 'domain_limit')
const generation = dependencies.id(),
time = now()
try {
@@ -197,7 +203,6 @@ export function createDomainManager(
AND (SELECT COUNT(*) FROM platform_custom_domains WHERE state<>'deleted' AND NOT ${HAS_PROVIDER})<?
AND (SELECT COUNT(*) FROM platform_custom_domains WHERE state<>'deleted')<?
AND (SELECT COUNT(*) FROM platform_custom_domains c JOIN platform_sites s ON s.id=c.site_id WHERE s.workspace_id=(SELECT workspace_id FROM platform_sites WHERE id=?) AND c.state<>'deleted')<?
- AND (SELECT COUNT(*) FROM platform_custom_domains WHERE site_id=? AND state<>'deleted')<2
ON CONFLICT(hostname) DO UPDATE SET site_id=excluded.site_id,generation=excluded.generation,revision=platform_custom_domains.revision+1,state='pending',created_at=excluded.created_at,expires_at=excluded.expires_at,next_check_at=excluded.next_check_at,dns_status=excluded.dns_status,provider_attempted=0,route_attempted=0,retry_requested=0,attempts=0,checked_at=NULL,verified_at=NULL,hostname_status='unknown',ssl_status='unknown',error=NULL,is_primary=0,redirects=0,lease_token=NULL,lease_until=NULL
WHERE platform_custom_domains.state='deleted' AND platform_custom_domains.provider_id IS NULL AND platform_custom_domains.route_id IS NULL`,
host,
@@ -212,8 +217,7 @@ export function createDomainManager(
PENDING_LIMIT,
resourceLimit + PENDING_LIMIT,
siteId,
- workspaceLimit,
- siteId,
+ plan.limits.customDomains,
)
await db.batch([
insertion,
diff --git a/packages/platform/src/entitlements.ts b/packages/platform/src/entitlements.ts
new file mode 100644
index 00000000..e4a69722
--- /dev/null
+++ b/packages/platform/src/entitlements.ts
@@ -0,0 +1,188 @@
+import type { PlatformD1 } from './index.ts'
+
+export const LIMIT_KEYS = [
+ 'byos',
+ 'storageBytes',
+ 'fileBytes',
+ 'sites',
+ 'customDomains',
+ 'photos',
+ 'monthlyBytes',
+] as const
+export type LimitKey = (typeof LIMIT_KEYS)[number]
+export type Limits = Record<LimitKey, number>
+export const FREE_LIMITS: Limits = {
+ byos: 0,
+ storageBytes: 1073741824,
+ fileBytes: 20971520,
+ sites: 1,
+ customDomains: 0,
+ photos: 1000,
+ monthlyBytes: 5368709120,
+}
+export type PolicyContext = {
+ storageMode: 'platform' | 'byos'
+ workspaceAgeDays: number
+ emailVerified: boolean
+}
+type Condition =
+ | { all: Condition[] }
+ | { any: Condition[] }
+ | {
+ field: keyof PolicyContext
+ op: 'eq' | 'gte' | 'lte'
+ value: string | number | boolean
+ }
+export interface PlanPolicy {
+ limits: Limits
+ rules: { when: Condition; limits: Partial<Limits> }[]
+}
+const plain = (v: unknown): v is Record<string, unknown> =>
+ !!v && typeof v === 'object' && !Array.isArray(v)
+export function validatePolicy(value: unknown): PlanPolicy {
+ if (
+ !plain(value) ||
+ !plain(value.limits) ||
+ !Array.isArray(value.rules) ||
+ value.rules.length > 32 ||
+ Object.keys(value).some((k) => !['limits', 'rules'].includes(k))
+ )
+ throw new Error('Invalid policy')
+ function limits(v: unknown, complete: boolean) {
+ if (
+ !plain(v) ||
+ Object.keys(v).some((k) => !LIMIT_KEYS.includes(k as LimitKey)) ||
+ (complete && LIMIT_KEYS.some((k) => !(k in v)))
+ )
+ throw new Error('Invalid limits')
+ if (Number(v.fileBytes ?? 0) > 1073741824 || Number(v.byos ?? 0) > 1)
+ throw new Error('Unsupported limit')
+ for (const n of Object.values(v))
+ if (!Number.isSafeInteger(n) || Number(n) < 0)
+ throw new Error('Limits must be non-negative safe integers')
+ }
+ if (Number(value.limits.byos) > 1) throw new Error('Invalid BYOS entitlement')
+ if (Number(value.limits.fileBytes) > 1073741824)
+ throw new Error('Maximum supported file size is 1 GiB')
+ let nodes = 0
+ function condition(v: unknown, depth = 0): void {
+ if (!plain(v) || depth > 4 || ++nodes > 128)
+ throw new Error('Invalid condition')
+ if ('all' in v || 'any' in v) {
+ const key = 'all' in v ? 'all' : 'any',
+ children = v[key]
+ if (
+ Object.keys(v).length !== 1 ||
+ !Array.isArray(children) ||
+ !children.length ||
+ children.length > 16
+ )
+ throw new Error('Invalid condition group')
+ children.forEach((c) => condition(c, depth + 1))
+ return
+ }
+ if (
+ Object.keys(v).sort().join(',') !== 'field,op,value' ||
+ !['storageMode', 'workspaceAgeDays', 'emailVerified'].includes(
+ String(v.field),
+ )
+ )
+ throw new Error('Invalid condition field')
+ if (v.field === 'workspaceAgeDays') {
+ if (
+ !['eq', 'gte', 'lte'].includes(String(v.op)) ||
+ !Number.isSafeInteger(v.value) ||
+ Number(v.value) < 0
+ )
+ throw new Error('Invalid numeric condition')
+ } else if (
+ v.op !== 'eq' ||
+ (v.field === 'storageMode'
+ ? !['platform', 'byos'].includes(String(v.value))
+ : typeof v.value !== 'boolean')
+ )
+ throw new Error('Invalid condition value')
+ }
+ limits(value.limits, true)
+ for (const rule of value.rules) {
+ if (!plain(rule) || Object.keys(rule).sort().join(',') !== 'limits,when')
+ throw new Error('Invalid rule')
+ condition(rule.when)
+ limits(rule.limits, false)
+ if (Number((rule.limits as Record<string, unknown>).byos ?? 0) > 1)
+ throw new Error('Invalid BYOS entitlement')
+ }
+ return structuredClone(value) as unknown as PlanPolicy
+}
+export function evaluatePolicy(
+ policy: PlanPolicy,
+ context: PolicyContext,
+): Limits {
+ function matches(c: Condition): boolean {
+ if ('all' in c) return c.all.every(matches)
+ if ('any' in c) return c.any.some(matches)
+ const a = context[c.field]
+ return c.op === 'eq'
+ ? a === c.value
+ : c.op === 'gte'
+ ? Number(a) >= Number(c.value)
+ : Number(a) <= Number(c.value)
+ }
+ const limits = { ...policy.limits }
+ for (const rule of policy.rules)
+ if (matches(rule.when)) Object.assign(limits, rule.limits)
+ return limits
+}
+export async function workspaceEntitlements(
+ db: PlatformD1,
+ workspaceId: number,
+ storageMode: 'platform' | 'byos' = 'platform',
+) {
+ const row = await db
+ .prepare(`SELECT p.id,p.name,p.revision,p.policy_json,w.owner_user_id,
+ w.created_at AS created_at,COALESCE(u.email_verified,0) AS email_verified
+ FROM platform_workspaces w LEFT JOIN platform_users u ON u.id=w.owner_user_id
+ JOIN platform_plans p ON p.id=COALESCE((SELECT plan_id FROM platform_workspace_plans WHERE workspace_id=w.id),'free') WHERE w.id=?`)
+ .bind(workspaceId)
+ .first<{
+ id: string
+ name: string
+ revision: number
+ policy_json: string
+ created_at: number
+ email_verified: number
+ }>()
+ if (!row) throw new Error('Workspace plan unavailable')
+ const context: PolicyContext = {
+ storageMode,
+ workspaceAgeDays: Math.max(
+ 0,
+ Math.floor((Date.now() - Number(row.created_at)) / 86400000),
+ ),
+ emailVerified: !!row.email_verified,
+ }
+ return {
+ id: row.id,
+ name: row.name,
+ revision: row.revision,
+ limits: evaluatePolicy(
+ validatePolicy(JSON.parse(row.policy_json)),
+ context,
+ ),
+ }
+}
+
+/** Correlated expressions keep admission and reservations in the same SQLite write. */
+export function workspaceUsageSQL(siteId: number) {
+ if (!Number.isSafeInteger(siteId) || siteId < 1)
+ throw new Error('Site required')
+ const sites = `SELECT id FROM platform_sites WHERE workspace_id=(SELECT workspace_id FROM platform_sites WHERE id=${siteId})`
+ return {
+ photos: `(SELECT COUNT(*) FROM cloud_photos WHERE site_id IN (${sites}) AND deleted=0)+(SELECT COUNT(*) FROM cloud_uploads WHERE site_id IN (${sites}) AND state='pending' AND expires_at>?)`,
+ monthly: `COALESCE((SELECT SUM(bytes) FROM cloud_usage_events WHERE site_id IN (${sites}) AND created_at>?),0)+COALESCE((SELECT SUM(expected_bytes+expected_video_bytes) FROM cloud_uploads WHERE site_id IN (${sites}) AND state='pending' AND expires_at>?),0)`,
+ storage: `COALESCE((SELECT SUM(u.expected_bytes+u.expected_video_bytes) FROM cloud_uploads u JOIN cloud_photos p ON p.site_id=u.site_id AND p.id=u.photo_id JOIN cloud_storage_connections c ON c.site_id=u.site_id AND c.id=u.connection_id WHERE u.site_id IN (${sites}) AND u.state='completed' AND p.deleted=0 AND c.pool_id IS NOT NULL),0)
+ +COALESCE((SELECT SUM(a.bytes) FROM cloud_media_assets a JOIN cloud_photos p ON p.site_id=a.site_id AND p.id=a.photo_id JOIN cloud_storage_connections c ON c.site_id=a.site_id AND c.id=a.connection_id WHERE a.site_id IN (${sites}) AND p.deleted=0 AND c.pool_id IS NOT NULL),0)
+ +COALESCE((SELECT SUM(reserved_storage_bytes) FROM cloud_uploads WHERE site_id IN (${sites}) AND state='pending' AND expires_at>?),0)
+ +COALESCE((SELECT SUM(reserved_output_bytes) FROM cloud_processing_jobs WHERE site_id IN (${sites}) AND state IN('queued','running','retry_wait')),0)`,
+ }
+}
diff --git a/packages/platform/src/index.ts b/packages/platform/src/index.ts
index 77032c3d..6a4e9f95 100644
--- a/packages/platform/src/index.ts
+++ b/packages/platform/src/index.ts
@@ -20,7 +20,7 @@ export function createD1Directory(
async getSite(id) {
const row = await db
.prepare(
- 'SELECT id, workspace_id AS workspaceId, published FROM platform_sites WHERE id = ?',
+ 'SELECT id, workspace_id AS workspaceId, published FROM platform_sites WHERE id = ? AND suspended=0',
)
.bind(id)
.first<{ id: number; workspaceId: number; published: number }>()
@@ -37,7 +37,7 @@ export function createD1Directory(
async getPublishedSiteByHost(host) {
const row = await db
.prepare(
- `SELECT s.id, s.workspace_id AS workspaceId, s.published FROM platform_domains d JOIN platform_sites s ON s.id=d.site_id LEFT JOIN platform_custom_domains cd ON cd.hostname=d.hostname WHERE d.hostname=? AND d.verified=1 AND d.active=1 AND s.published=1 AND (d.kind<>'custom' OR (cd.site_id=d.site_id AND cd.state='active' AND cd.verified_at>=?)) AND (d.kind<>'alias' OR d.redirect_until>?)`,
+ `SELECT s.id, s.workspace_id AS workspaceId, s.published FROM platform_domains d JOIN platform_sites s ON s.id=d.site_id LEFT JOIN platform_custom_domains cd ON cd.hostname=d.hostname WHERE d.hostname=? AND d.verified=1 AND d.active=1 AND s.published=1 AND s.suspended=0 AND (d.kind<>'custom' OR (cd.site_id=d.site_id AND cd.state='active' AND cd.verified_at>=?)) AND (d.kind<>'alias' OR d.redirect_until>?)`,
)
.bind(host, now() - DOMAIN_HEALTH_TTL, now())
.first<{ id: number; workspaceId: number; published: number }>()
diff --git a/packages/platform/src/provisioning.ts b/packages/platform/src/provisioning.ts
index d773c803..647b3d03 100644
--- a/packages/platform/src/provisioning.ts
+++ b/packages/platform/src/provisioning.ts
@@ -1,3 +1,4 @@
+import { workspaceEntitlements } from './entitlements.ts'
import { validSiteSlug, defaultSiteHost } from '@chronoframe/contracts/domains'
import type { PlatformD1 } from './index.ts'
@@ -76,10 +77,10 @@ export function createD1Provisioning(
async function defaultWorkspace(userId: number) {
await db.batch([
db
- .prepare(`INSERT INTO platform_workspaces(name, owner_user_id)
- SELECT 'My workspace', id FROM platform_users WHERE id = ? AND email_verified = 1
+ .prepare(`INSERT INTO platform_workspaces(name, owner_user_id, created_at)
+ SELECT 'My workspace', id, ? FROM platform_users WHERE id = ? AND email_verified = 1
ON CONFLICT(owner_user_id) DO NOTHING`)
- .bind(userId),
+ .bind(Date.now(), userId),
// Only the transaction that created the workspace grants its initial membership.
// A later read must never restore a membership that was explicitly revoked.
db
@@ -101,7 +102,7 @@ export function createD1Provisioning(
const site = await db
.prepare(`SELECT ${fields}, m.role FROM platform_sites s
JOIN platform_memberships m ON m.workspace_id = s.workspace_id
- WHERE s.id = ? AND m.user_id = ? AND m.role IN ('admin','member')`)
+ WHERE s.id = ? AND s.suspended=0 AND m.user_id = ? AND m.role IN ('admin','member')`)
.bind(siteId, userId)
.first<ManagedSite & { role: string }>()
if (!site) throw new ProvisioningError(404, 'Site not found')
@@ -132,12 +133,13 @@ export function createD1Provisioning(
throw new ProvisioningError(409, 'Request identifier already used')
return existing
}
+ const entitlement = await workspaceEntitlements(db, workspace.id)
try {
await db.batch([
db
- .prepare(`INSERT INTO platform_sites(workspace_id, name, slug, created_at, provision_key)
- SELECT ?, ?, ?, ?, ? WHERE EXISTS(SELECT 1 FROM platform_memberships WHERE workspace_id = ? AND user_id = ? AND role = 'admin')
- AND (SELECT COUNT(*) FROM platform_sites WHERE workspace_id = ?) < 10
+ .prepare(`INSERT INTO platform_sites(workspace_id, name, slug, created_at, provision_key, published)
+ SELECT ?, ?, ?, ?, ?, 1 WHERE EXISTS(SELECT 1 FROM platform_memberships WHERE workspace_id = ? AND user_id = ? AND role = 'admin')
+ AND (SELECT COUNT(*) FROM platform_sites WHERE workspace_id = ?) < ?
ON CONFLICT(workspace_id, provision_key) DO UPDATE SET provision_key = excluded.provision_key`)
.bind(
workspace.id,
@@ -148,6 +150,7 @@ export function createD1Provisioning(
workspace.id,
userId,
workspace.id,
+ entitlement.limits.sites,
),
db
.prepare(`INSERT INTO platform_site_slugs(slug,site_id)
@@ -213,9 +216,6 @@ export function createD1Provisioning(
typeof input.published !== 'boolean'
)
throw new ProvisioningError(400, 'Invalid site settings')
- // Publishing new galleries stays gated until media/storage and default routing are ready.
- if (input.published && !current.published)
- throw new ProvisioningError(400, 'Publishing is not available yet')
const result = await db
.prepare(`UPDATE platform_sites SET name = ?, published = ?, gallery_title = ?, gallery_slogan = ?, gallery_author = ?, gallery_avatar = ?, revision = revision + 1
WHERE id = ? AND revision = ? AND EXISTS(SELECT 1 FROM platform_memberships WHERE workspace_id = platform_sites.workspace_id AND user_id = ? AND role = 'admin')
diff --git a/packages/platform/src/storage-vault.ts b/packages/platform/src/storage-vault.ts
index a590bb74..0bebf715 100644
--- a/packages/platform/src/storage-vault.ts
+++ b/packages/platform/src/storage-vault.ts
@@ -26,16 +26,68 @@ export function createStorageVault(
if (!/^[a-zA-Z0-9_-]{1,128}$/.test(id))
throw new RangeError('Invalid connection ID')
}
+ async function managed(id: string) {
+ const row = await db
+ .prepare(`SELECT p.id,p.enabled,c.pool_revision AS revision,v.public_json,k.secret_ciphertext,p.current_revision
+ FROM cloud_storage_connections c JOIN platform_storage_pools p ON p.id=c.pool_id
+ JOIN platform_storage_pool_versions v ON v.pool_id=p.id AND v.revision=c.pool_revision
+ JOIN platform_storage_pool_versions k ON k.pool_id=p.id AND k.revision=p.current_revision
+ WHERE c.site_id=? AND c.id=?`)
+ .bind(siteId, id)
+ .first<{
+ id: string
+ enabled: number
+ revision: number
+ public_json: string
+ secret_ciphertext: string
+ current_revision: number
+ }>()
+ if (!row) return null
+ return {
+ revision: 1,
+ poolId: row.id,
+ enabled: !!row.enabled,
+ config: JSON.parse(row.public_json) as CloudStoragePublic,
+ credentials: await cipher.open(
+ row.secret_ciphertext,
+ JSON.stringify(['platform-storage', row.id, row.current_revision]),
+ ),
+ }
+ }
return {
+ async attachPool(poolId: string, now: number) {
+ const id = 'platform-' + poolId
+ validId(id)
+ await db.batch([
+ db
+ .prepare(`INSERT INTO cloud_storage_connections(site_id,id,current_revision,healthy,checked_at,pool_id,pool_revision)
+ SELECT ?,?,1,1,?,id,current_revision FROM platform_storage_pools WHERE id=? AND enabled=1
+ ON CONFLICT(site_id,id) DO NOTHING`)
+ .bind(siteId, id, now, poolId),
+ db
+ .prepare(`INSERT INTO cloud_storage_versions(site_id,connection_id,revision,public_json,secret_ciphertext)
+ SELECT ?,?,1,'{}','managed' WHERE EXISTS(SELECT 1 FROM cloud_storage_connections WHERE site_id=? AND id=? AND pool_id=?)
+ ON CONFLICT DO NOTHING`)
+ .bind(siteId, id, siteId, id, poolId),
+ ])
+ return db
+ .prepare(
+ 'SELECT id FROM cloud_storage_connections WHERE site_id=? AND id=?',
+ )
+ .bind(siteId, id)
+ .first()
+ },
async list() {
const result = (await db
.prepare(
- 'SELECT c.id,c.current_revision,c.healthy,c.checked_at,v.public_json FROM cloud_storage_connections c JOIN cloud_storage_versions v ON v.site_id=c.site_id AND v.connection_id=c.id AND v.revision=c.current_revision WHERE c.site_id=? ORDER BY c.id LIMIT 20',
+ 'SELECT c.id,c.current_revision,c.healthy,c.checked_at,c.pool_id,CASE WHEN c.pool_id IS NULL THEN 1 ELSE COALESCE(p.enabled,0) END AS uploads_enabled,v.public_json FROM cloud_storage_connections c JOIN cloud_storage_versions v ON v.site_id=c.site_id AND v.connection_id=c.id AND v.revision=c.current_revision LEFT JOIN platform_storage_pools p ON p.id=c.pool_id WHERE c.site_id=? ORDER BY c.id LIMIT 20',
)
.bind(siteId)) as unknown as { all<T>(): Promise<{ results: T[] }> }
return (
await result.all<{
id: string
+ pool_id: string | null
+ uploads_enabled: number
current_revision: number
healthy: number
checked_at: number | null
@@ -43,11 +95,15 @@ export function createStorageVault(
}>()
).results.map(({ public_json, ...record }) => ({
...record,
- config: JSON.parse(public_json) as CloudStoragePublic,
+ config: record.pool_id
+ ? { bucket: 'Platform storage' }
+ : (JSON.parse(public_json) as CloudStoragePublic),
}))
},
async get(id: string, revision?: number) {
validId(id)
+ const pool = await managed(id)
+ if (pool) return revision === undefined || revision === 1 ? pool : null
const row = await db
.prepare(
`SELECT v.revision,v.public_json,v.secret_ciphertext FROM cloud_storage_versions v JOIN cloud_storage_connections c ON c.site_id=v.site_id AND c.id=v.connection_id WHERE v.site_id=? AND v.connection_id=? AND v.revision=COALESCE(?,c.current_revision)`,
@@ -71,6 +127,8 @@ export function createStorageVault(
/** Object revisions pin bucket metadata; rotation replaces credentials for that same connection. */
async resolve(id: string, revision?: number) {
validId(id)
+ const pool = await managed(id)
+ if (pool) return revision === undefined || revision === 1 ? pool : null
const row = await db
.prepare(
`SELECT v.revision,v.public_json,c.current_revision,k.secret_ciphertext FROM cloud_storage_connections c JOIN cloud_storage_versions v ON v.site_id=c.site_id AND v.connection_id=c.id AND v.revision=COALESCE(?,c.current_revision) JOIN cloud_storage_versions k ON k.site_id=c.site_id AND k.connection_id=c.id AND k.revision=c.current_revision WHERE c.site_id=? AND c.id=?`,
@@ -122,6 +180,8 @@ export function createStorageVault(
now: number,
) {
validId(id)
+ if (await managed(id))
+ throw new CoreError(403, 'Managed credentials cannot be changed')
if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 1)
throw new RangeError('Revision required')
const revision = expectedRevision + 1
diff --git a/packages/storage/src/s3-edge.ts b/packages/storage/src/s3-edge.ts
index 6dabdbe9..c8ea9b6c 100644
--- a/packages/storage/src/s3-edge.ts
+++ b/packages/storage/src/s3-edge.ts
@@ -129,7 +129,7 @@ export function createCloudS3(
if (
!Number.isSafeInteger(bytes) ||
bytes < 1 ||
- bytes > 100 * 1024 * 1024
+ bytes > 1024 * 1024 * 1024
)
throw new Error('Invalid upload size')
return getSignedUrl(
diff --git a/tests/cloud-domains.test.ts b/tests/cloud-domains.test.ts
index 95a3cd24..11aa69ff 100644
--- a/tests/cloud-domains.test.ts
+++ b/tests/cloud-domains.test.ts
@@ -100,6 +100,11 @@ test('Real D1 custom domains fence claims, CNAME ownership transitions, provider
time,
)
.run()
+ await db
+ .prepare(
+ `UPDATE platform_plans SET policy_json=json_set(policy_json,'$.limits.sites',10,'$.limits.customDomains',4,'$.limits.byos',1) WHERE id='free'`,
+ )
+ .run()
const sites = createD1Provisioning(db)
const one = await sites.create(1, {
name: 'One',
@@ -710,6 +715,11 @@ test('Workspace quotas preserve capacity for other tenants and audit failures ro
time,
)
.run()
+ await db
+ .prepare(
+ `UPDATE platform_plans SET policy_json=json_set(policy_json,'$.limits.sites',10,'$.limits.customDomains',4,'$.limits.byos',1) WHERE id='free'`,
+ )
+ .run()
const sites = createD1Provisioning(db),
claims = []
for (let i = 0; i < 5; i++)
diff --git a/tests/cloud-storage.test.ts b/tests/cloud-storage.test.ts
index 2a1f95c8..d3fcb211 100644
--- a/tests/cloud-storage.test.ts
+++ b/tests/cloud-storage.test.ts
@@ -63,7 +63,7 @@ test('One S3 implementation rejects SSRF/redirect destinations and signs bounded
assert.equal(url.pathname, '/test-bucket/chronoframe/1/originals/image')
assert(!url.href.includes(config.secretAccessKey))
await assert.rejects(s3.signPut('../outside', 42, 'image/jpeg'))
- await assert.rejects(s3.signPut('valid', 101 * 1024 * 1024, 'image/jpeg'))
+ await assert.rejects(s3.signPut('valid', 1025 * 1024 * 1024, 'image/jpeg'))
let redirect: string | undefined
const transport = createCloudS3(config, {
fetch: async (input, init) => {
@@ -91,7 +91,8 @@ test('Credential vault authenticates Site/revision, keeps old objects usable and
const db = raw as PlatformD1
for (const sql of [
'CREATE TABLE platform_sites(id INTEGER PRIMARY KEY)',
- 'CREATE TABLE platform_users(id INTEGER PRIMARY KEY)',
+ 'CREATE TABLE platform_users(id INTEGER PRIMARY KEY,created_at INTEGER)',
+ 'CREATE TABLE platform_workspaces(id INTEGER PRIMARY KEY,owner_user_id INTEGER)',
'INSERT INTO platform_sites VALUES(1),(2)',
])
await raw.prepare(sql).run()
@@ -100,6 +101,7 @@ test('Credential vault authenticates Site/revision, keeps old objects usable and
'0006_cloud_execution.sql',
'0007_cloud_storage.sql',
'0009_cloud_usage_events.sql',
+ '0014_entitlements.sql',
]) {
const migration = await readFile(
new URL('../packages/platform/migrations/' + name, import.meta.url),
diff --git a/tests/platform-email-d1.test.ts b/tests/platform-email-d1.test.ts
index 50a1e41f..0d79c8e8 100644
--- a/tests/platform-email-d1.test.ts
+++ b/tests/platform-email-d1.test.ts
@@ -208,6 +208,9 @@ test('D1 directory never maps unverified/inactive domains or unrelated Workspace
'utf8',
),
)
+ sqlite.exec(
+ 'ALTER TABLE platform_sites ADD COLUMN suspended INTEGER NOT NULL DEFAULT 0',
+ )
const access = createPlatformAccess(createD1Directory(db), () => 100)
const session = { userId: 1, expiresAt: 200 }
assert.equal((await access.authorizeSite(session, 1, 'manage')).site.id, 1)
diff --git a/tests/platform-entitlements.test.ts b/tests/platform-entitlements.test.ts
new file mode 100644
index 00000000..99a059aa
--- /dev/null
+++ b/tests/platform-entitlements.test.ts
@@ -0,0 +1,277 @@
+import {
+ createDomainManager,
+ type DomainProvider,
+} from '../packages/platform/src/domains.ts'
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { createRequire } from 'node:module'
+import { readFile, readdir } from 'node:fs/promises'
+import {
+ FREE_LIMITS,
+ validatePolicy,
+ evaluatePolicy,
+ workspaceEntitlements,
+ workspaceUsageSQL,
+} from '../packages/platform/src/entitlements.ts'
+import {
+ createD1Provisioning,
+ createD1Directory,
+} from '../packages/platform/src/index.ts'
+import { createStorageVault } from '../packages/platform/src/storage-vault.ts'
+import { createStorageCipher } from '../packages/storage/src/credential-cipher.ts'
+const require = createRequire(import.meta.url),
+ { Miniflare, convertV4MiniflareOptions } = createRequire(
+ require.resolve('wrangler/package.json'),
+ )('miniflare')
+test('Plan rules compose ordered conditions without executable expressions or unbounded trees', () => {
+ const p = validatePolicy({
+ limits: FREE_LIMITS,
+ rules: [
+ {
+ when: {
+ all: [
+ { field: 'emailVerified', op: 'eq', value: true },
+ {
+ any: [
+ { field: 'workspaceAgeDays', op: 'gte', value: 30 },
+ { field: 'storageMode', op: 'eq', value: 'byos' },
+ ],
+ },
+ ],
+ },
+ limits: { sites: 2, byos: 1 },
+ },
+ {
+ when: { field: 'storageMode', op: 'eq', value: 'platform' },
+ limits: { storageBytes: 2 * 1073741824 },
+ },
+ ],
+ })
+ assert.equal(
+ evaluatePolicy(p, {
+ storageMode: 'platform',
+ workspaceAgeDays: 0,
+ emailVerified: true,
+ }).sites,
+ 1,
+ )
+ assert.equal(
+ evaluatePolicy(p, {
+ storageMode: 'platform',
+ workspaceAgeDays: 30,
+ emailVerified: true,
+ }).sites,
+ 2,
+ )
+ assert.equal(
+ evaluatePolicy(p, {
+ storageMode: 'platform',
+ workspaceAgeDays: 30,
+ emailVerified: true,
+ }).storageBytes,
+ 2147483648,
+ )
+ for (const value of [
+ { limits: { ...FREE_LIMITS, sites: -1 }, rules: [] },
+ {
+ limits: FREE_LIMITS,
+ rules: [
+ {
+ when: { field: '__proto__', op: 'eq', value: true },
+ limits: { sites: 5 },
+ },
+ ],
+ },
+ {
+ limits: FREE_LIMITS,
+ rules: [{ when: { all: [] }, limits: { sites: 5 } }],
+ },
+ { limits: { ...FREE_LIMITS, byos: 2 }, rules: [] },
+ ])
+ assert.throws(() => validatePolicy(value))
+})
+test('New workspaces are free; empty galleries auto-publish; quotas and managed credentials stay isolated', async () => {
+ const mf = new Miniflare(
+ convertV4MiniflareOptions({
+ modules: true,
+ script: 'export default {fetch(){return new Response("ok")}}',
+ compatibilityDate: '2026-10-26',
+ d1Databases: ['DB'],
+ }),
+ )
+ try {
+ const db = await mf.getD1Database('DB')
+ for (const f of (await readdir('packages/platform/migrations'))
+ .filter((f) => f.endsWith('.sql'))
+ .sort())
+ for (const q of (
+ await readFile('packages/platform/migrations/' + f, 'utf8')
+ )
+ .replace(/^--.*$/gm, '')
+ .split(';')
+ .map((v) => v.trim())
+ .filter(Boolean))
+ await db.prepare(q).run()
+ await db
+ .prepare(
+ "INSERT INTO platform_users(id,email,created_at,email_verified) VALUES(1,'[email protected]',?,1),(2,'[email protected]',?,1)",
+ )
+ .bind(Date.now(), Date.now())
+ .run()
+ const provision = createD1Provisioning(db),
+ directory = createD1Directory(db)
+ const results = await Promise.allSettled(
+ ['one-a', 'one-b'].map((slug) =>
+ provision.create(1, {
+ name: slug,
+ slug,
+ requestId: crypto.randomUUID(),
+ }),
+ ),
+ )
+ assert.equal(results.filter((r) => r.status === 'fulfilled').length, 1)
+ const one = results.find((r) => r.status === 'fulfilled')!.value
+ assert.equal(one.published, 1)
+ assert.equal(
+ (await directory.getPublishedSiteByHost(one.slug + '.chronoframe.art'))
+ ?.id,
+ one.siteId,
+ )
+ const free = await workspaceEntitlements(db, one.workspaceId, 'platform')
+ assert.deepEqual(free.limits, FREE_LIMITS)
+ const manager = createDomainManager(
+ db,
+ {
+ enabled: true,
+ routingReady: true,
+ baseDomain: 'chronoframe.art',
+ cnameTarget: 'cname.chronoframe.art',
+ limit: 20,
+ },
+ {
+ dns: async () => 'ready',
+ id: () => crypto.randomUUID(),
+ provider: new Proxy(
+ {},
+ {
+ get() {
+ return () => {
+ throw new Error(
+ 'Free tier must not allocate provider resources',
+ )
+ }
+ },
+ },
+ ) as DomainProvider,
+ },
+ )
+ await assert.rejects(manager.request(1, one.siteId, 'photos.example.com'), {
+ statusCode: 403,
+ code: 'domain_limit',
+ })
+ const two = await provision.create(2, {
+ name: 'Two',
+ slug: 'two-site',
+ requestId: crypto.randomUUID(),
+ })
+ const cipher = await createStorageCipher('test-'.repeat(10)),
+ vault = createStorageVault(db, one.siteId, cipher)
+ const config = {
+ endpoint: 'https://s3.amazonaws.com',
+ bucket: 'private-test',
+ region: 'us-east-1',
+ },
+ credentials = {
+ accessKeyId: 'example-access',
+ secretAccessKey: 'example-private',
+ }
+ const sealed = await cipher.seal(
+ credentials,
+ JSON.stringify(['platform-storage', 'main', 1]),
+ )
+ await db.batch([
+ db
+ .prepare(
+ "INSERT INTO platform_storage_pools(id,name,enabled,checked_at) VALUES('main','Main',1,?)",
+ )
+ .bind(Date.now()),
+ db
+ .prepare(
+ "INSERT INTO platform_storage_pool_versions VALUES('main',1,?,?)",
+ )
+ .bind(JSON.stringify(config), sealed),
+ ])
+ await vault.attachPool('main', Date.now())
+ const list = await vault.list()
+ assert.equal(list[0].config.bucket, 'Platform storage')
+ assert.ok(!JSON.stringify(list).includes('private-test'))
+ assert.ok(!JSON.stringify(list).includes('example-private'))
+ assert.deepEqual(
+ (await vault.resolve('platform-main'))?.credentials,
+ credentials,
+ )
+ assert.equal(
+ await createStorageVault(db, two.siteId, cipher).resolve('platform-main'),
+ null,
+ )
+ await assert.rejects(
+ vault.rotate('platform-main', 1, credentials, Date.now()),
+ { statusCode: 403 },
+ )
+ await db
+ .prepare("UPDATE platform_storage_pools SET enabled=0 WHERE id='main'")
+ .run()
+ assert.ok(await vault.resolve('platform-main'))
+ assert.equal((await vault.list())[0].uploads_enabled, 0)
+ assert.equal(
+ await createStorageVault(db, two.siteId, cipher).attachPool(
+ 'main',
+ Date.now(),
+ ),
+ null,
+ )
+ await db
+ .prepare('UPDATE platform_sites SET suspended=1 WHERE id=?')
+ .bind(one.siteId)
+ .run()
+ assert.equal(
+ await directory.getPublishedSiteByHost(one.slug + '.chronoframe.art'),
+ null,
+ )
+ const expr = workspaceUsageSQL(one.siteId),
+ now = Date.now()
+ // One write both checks capacity and reserves it; two simultaneous uploads cannot overspend.
+ const reserve = (id: string) =>
+ db
+ .prepare(
+ `INSERT INTO cloud_uploads(site_id,id,owner_id,photo_id,source_version,connection_id,object_key,expected_bytes,expires_at,reserved_storage_bytes) SELECT ?,?,1,?,'1','platform-main',?,700,?,700 WHERE ${expr.storage}+700<=1024`,
+ )
+ .bind(one.siteId, id, id, 'objects/' + id, now + 60000, now)
+ .run()
+ const admissions = await Promise.all([
+ reserve('upload-a'),
+ reserve('upload-b'),
+ ])
+ assert.equal(
+ admissions.reduce((n, r) => n + r.meta.changes, 0),
+ 1,
+ )
+ const usage = await db
+ .prepare(`SELECT ${expr.storage} AS bytes`)
+ .bind(now)
+ .first()
+ assert.equal(usage.bytes, 700)
+ // Cancellation releases reserved capacity without altering the other tenant.
+ await db
+ .prepare("UPDATE cloud_uploads SET state='cancelled' WHERE site_id=?")
+ .bind(one.siteId)
+ .run()
+ assert.equal(
+ (await db.prepare(`SELECT ${expr.storage} AS bytes`).bind(now).first())
+ .bytes,
+ 0,
+ )
+ } finally {
+ await mf.dispose()
+ }
+})
diff --git a/tests/platform-provisioning.test.ts b/tests/platform-provisioning.test.ts
index 2a158452..898ad27a 100644
--- a/tests/platform-provisioning.test.ts
+++ b/tests/platform-provisioning.test.ts
@@ -81,6 +81,19 @@ test('Real D1 provisioning preserves old tenants, serializes defaults and enforc
await migrate('0004_workspace_sites.sql')
await migrate('0011_site_identity.sql')
await migrate('0013_custom_domains.sql')
+ for (const migration of [
+ '0005_media_catalog.sql',
+ '0006_cloud_execution.sql',
+ '0007_cloud_storage.sql',
+ '0009_cloud_usage_events.sql',
+ '0014_entitlements.sql',
+ ])
+ await migrate(migration)
+ await db
+ .prepare(
+ `UPDATE platform_plans SET policy_json=json_set(policy_json,'$.limits.sites',10) WHERE id='free'`,
+ )
+ .run()
await db
.prepare('UPDATE platform_users SET email_verified=0 WHERE id=44')
.run()
@@ -115,7 +128,7 @@ test('Real D1 provisioning preserves old tenants, serializes defaults and enforc
requestId: crypto.randomUUID(),
}
const first = await store.create(42, input)
- assert.equal(first.published, 0)
+ assert.equal(first.published, 1)
assert.equal((await store.create(42, input)).siteId, first.siteId)
await assert.rejects(store.create(42, { ...input, name: 'Changed' }), {
statusCode: 409,
@@ -147,13 +160,15 @@ test('Real D1 provisioning preserves old tenants, serializes defaults and enforc
}),
{ statusCode: 409 },
)
- await assert.rejects(
- store.update(42, first.siteId, {
- name: 'Renamed',
- published: true,
- revision: 2,
- }),
- { statusCode: 400 },
+ assert.equal(
+ (
+ await store.update(42, first.siteId, {
+ name: 'Renamed',
+ published: true,
+ revision: 2,
+ })
+ ).published,
+ 1,
)
const races = await Promise.allSettled(
[42, 43].map((id) =>
@@ -165,7 +180,7 @@ test('Real D1 provisioning preserves old tenants, serializes defaults and enforc
),
)
assert.equal(races.filter((r) => r.status === 'fulfilled').length, 1)
- // Draft reservations never expose a public gallery or alter the existing published gallery.
+ // Newly created empty galleries publish without changing existing gallery settings.
assert.equal(
(
await db
@@ -174,7 +189,7 @@ test('Real D1 provisioning preserves old tenants, serializes defaults and enforc
)
.first()
).n,
- 0,
+ 2,
)
assert.equal((await store.get(42, 8)).published, 1)
const oldUpdated = await store.update(42, 8, {
diff --git a/tests/portal-review-regressions.test.ts b/tests/portal-review-regressions.test.ts
index cf881372..99c63d1b 100644
--- a/tests/portal-review-regressions.test.ts
+++ b/tests/portal-review-regressions.test.ts
@@ -78,6 +78,12 @@ test('Live Photo validation rejects the combined size before reserving any uploa
)
const media = module.useCloudMediaWorkspace({ siteId: 1, role: 'admin' })
media.connectionId.value = 'storage'
+ media.allowance.value = {
+ limits: { fileBytes: 100 * 1024 * 1024 },
+ byosLimits: { fileBytes: 100 * 1024 * 1024, byos: 1 },
+ plan: { id: 'test', name: 'Test' },
+ storageBytes: 0,
+ }
const mib = 1024 * 1024
for (const files of [
[
@@ -90,7 +96,7 @@ test('Live Photo validation rejects the combined size before reserving any uploa
const input = { files, value: 'chosen' }
await media.upload({ target: input })
assert.equal(media.failed.value, true)
- assert.match(media.message.value, /100 MiB/)
+ assert.match(media.message.value, /plan/)
assert.equal(input.value, '')
assert.equal(requests.length, 0)
}