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): provision workspaces and private site drafts

Timothy Yinc5cc58fe134a
diff --git a/apps/cloud/app/assets/cloud.css b/apps/cloud/app/assets/cloud.css
index 92bbfded..2c7a0aeb 100644
--- a/apps/cloud/app/assets/cloud.css
+++ b/apps/cloud/app/assets/cloud.css
@@ -928,7 +928,7 @@
display: none;
}
.cf-portal-grid {
- grid-template-columns: 1fr;
+ grid-template-columns: minmax(0, 1fr);
}
.cf-sidebar {
border-right: 0;
@@ -943,7 +943,10 @@
flex-direction: row;
}
.cf-sidebar nav a {
- min-width: 100px;
+ min-width: 0;
+ flex: 1;
+ justify-content: center;
+ padding-inline: 8px;
}
.cf-portal-main {
padding: 30px 20px 45px;
@@ -1200,3 +1203,48 @@
flex-shrink: 0;
}
}
+
+.cf-site-create {
+ margin-block: 1.5rem;
+}
+.cf-site-create .cf-form {
+ padding: 1.5rem;
+ max-width: 40rem;
+}
+.cf-site-address {
+ padding: 1rem;
+ overflow-wrap: anywhere;
+ font-size: 0.875rem;
+}
+.cf-site-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.75rem;
+}
+
+.cf-site-create .cf-form {
+ display: grid;
+ gap: 20px;
+ min-width: 0;
+}
+.cf-site-create .cf-field {
+ display: grid;
+ gap: 8px;
+ min-width: 0;
+}
+.cf-site-create label {
+ font-size: 13px;
+ font-weight: 550;
+}
+.cf-site-settings {
+ padding: 24px;
+}
+.cf-site-settings .cf-form {
+ padding: 24px 0 0;
+}
+.cf-site-settings .cf-site-address {
+ padding: 16px 0;
+}
+.cf-site-create .cf-page-description {
+ font-size: 13px;
+}
diff --git a/apps/cloud/app/components/CloudSiteCreate.vue b/apps/cloud/app/components/CloudSiteCreate.vue
new file mode 100644
index 00000000..6d809ef7
--- /dev/null
+++ b/apps/cloud/app/components/CloudSiteCreate.vue
@@ -0,0 +1,132 @@
+<script setup lang="ts">
+import { Plus, ArrowRight } from 'lucide-vue-next'
+const open = ref(false)
+const name = ref('')
+const slug = ref('')
+const busy = ref(false)
+const error = ref('')
+let requestId = ''
+watch([name, slug], () => {
+ requestId = ''
+ error.value = ''
+})
+const validSlug = computed(() =>
+ /^[a-z0-9](?:[a-z0-9-]{1,38}[a-z0-9])$/.test(slug.value),
+)
+async function show() {
+ open.value = true
+ await nextTick()
+ document.getElementById('site-name')?.focus()
+}
+async function create() {
+ if (busy.value) return
+ busy.value = true
+ error.value = ''
+ requestId ||= crypto.randomUUID()
+ try {
+ const result = await $fetch<{ site: { siteId: number } }>('/api/sites', {
+ method: 'POST',
+ body: { name: name.value, slug: slug.value, requestId },
+ })
+ await navigateTo(`/sites/${result.site.siteId}`)
+ } catch (cause) {
+ const status = (cause as { statusCode?: number }).statusCode
+ error.value =
+ status === 409
+ ? 'This address is already taken, or this request changed. Choose another address and try again.'
+ : status === 400
+ ? 'Check the site name and address. This address may be reserved.'
+ : status === 403
+ ? 'You cannot create another site in this workspace. The preview supports up to 10 sites.'
+ : 'Your site could not be created. Please try again.'
+ } finally {
+ busy.value = false
+ }
+}
+</script>
+<template>
+ <CloudCard class="cf-settings-card cf-site-create">
+ <div class="cf-setting-row">
+ <div>
+ <h2>Your next perspective</h2>
+ <p>
+ Create a private draft. You can add photographs and publish in a later
+ stage.
+ </p>
+ </div>
+ <CloudButton
+ v-if="!open"
+ @click="show"
+ ><Plus :size="16" />Create site</CloudButton
+ >
+ </div>
+ <form
+ v-if="open"
+ class="cf-form"
+ @submit.prevent="create"
+ >
+ <div class="cf-field">
+ <label for="site-name">Site name</label
+ ><CloudInput
+ id="site-name"
+ v-model="name"
+ required
+ maxlength="80"
+ autocomplete="off"
+ :disabled="busy"
+ />
+ </div>
+ <div class="cf-field">
+ <label for="site-slug">Site address</label
+ ><CloudInput
+ id="site-slug"
+ v-model="slug"
+ required
+ minlength="3"
+ maxlength="40"
+ pattern="[a-z0-9][a-z0-9-]{1,38}[a-z0-9]"
+ autocomplete="off"
+ autocapitalize="none"
+ spellcheck="false"
+ aria-describedby="site-address-help"
+ :disabled="busy"
+ />
+ <p
+ id="site-address-help"
+ class="cf-page-description"
+ >
+ 3–40 lowercase letters, numbers or hyphens; start and end with a
+ letter or number. Some addresses are reserved.
+ </p>
+ </div>
+ <p class="cf-site-address">
+ {{ slug || 'your-site' }}.site.chronoframe.art
+ </p>
+ <p class="cf-page-description">
+ This address is reserved for your draft. Public access is not enabled
+ yet. The address cannot be changed here.
+ </p>
+ <p
+ v-if="error"
+ role="alert"
+ class="cf-notice"
+ >
+ {{ error }}
+ </p>
+ <div class="cf-site-actions">
+ <CloudButton
+ type="submit"
+ :disabled="busy || !name.trim() || !validSlug"
+ >{{ busy ? 'Creating…' : 'Create draft'
+ }}<ArrowRight :size="15" /></CloudButton
+ ><CloudButton
+ type="button"
+ variant="ghost"
+ :disabled="busy"
+ @click="open = false"
+ >Cancel</CloudButton
+ >
+ </div>
+ </form>
+ </CloudCard>
+</template>
diff --git a/apps/cloud/app/components/CloudSiteSettings.vue b/apps/cloud/app/components/CloudSiteSettings.vue
new file mode 100644
index 00000000..8120fe2d
--- /dev/null
+++ b/apps/cloud/app/components/CloudSiteSettings.vue
@@ -0,0 +1,138 @@
+<script setup lang="ts">
+const props = defineProps<{ siteId: number }>()
+const context = useEntryContext()
+const {
+ data,
+ error: loadError,
+ refresh,
+} = await useFetch(`/api/sites/${props.siteId}/settings`, {
+ key: `site-settings-${props.siteId}`,
+})
+const name = ref(data.value?.site.name ?? '')
+const busy = ref(false)
+const message = ref('')
+const failed = ref(false)
+async function reload() {
+ await refresh()
+ name.value = data.value?.site.name ?? ''
+ message.value = ''
+}
+async function save(unpublish = false) {
+ if (!data.value || busy.value) return
+ busy.value = true
+ message.value = ''
+ failed.value = false
+ try {
+ const result = await $fetch(`/api/sites/${props.siteId}/settings`, {
+ method: 'PATCH',
+ body: {
+ name: name.value,
+ revision: data.value.site.revision,
+ published: unpublish ? false : !!data.value.site.published,
+ },
+ })
+ data.value = { site: { ...result.site, role: data.value.site.role } }
+ if (context.value?.siteId === props.siteId)
+ context.value = {
+ ...context.value,
+ name: result.site.name,
+ published: !!result.site.published,
+ }
+ message.value = 'Site settings saved.'
+ } catch (cause) {
+ failed.value = true
+ message.value =
+ (cause as { statusCode?: number }).statusCode === 409
+ ? 'This site changed in another session. Reload before saving again.'
+ : 'Settings could not be saved. Check your access and try again.'
+ } finally {
+ busy.value = false
+ }
+}
+</script>
+<template>
+ <CloudCard class="cf-settings-card cf-site-create cf-site-settings">
+ <h2 class="cf-section-label">Site settings</h2>
+ <div
+ v-if="loadError"
+ role="alert"
+ class="cf-notice"
+ >
+ Settings could not be loaded.<CloudButton
+ variant="ghost"
+ @click="reload"
+ >Reload settings</CloudButton
+ >
+ </div>
+ <template v-else-if="data">
+ <p
+ v-if="data.site.slug"
+ class="cf-site-address"
+ >
+ {{ data.site.slug }}.site.chronoframe.art
+ </p>
+ <p
+ v-else
+ class="cf-page-description"
+ >
+ This existing site keeps its current domain settings.
+ </p>
+ <p
+ v-if="!data.site.published"
+ class="cf-page-description"
+ >
+ Your draft is private. Publishing will become available when photo
+ storage and delivery are ready.
+ </p>
+ <form
+ v-if="data.site.role === 'admin'"
+ class="cf-form"
+ @submit.prevent="save()"
+ >
+ <div class="cf-field">
+ <label for="settings-site-name">Site name</label
+ ><CloudInput
+ id="settings-site-name"
+ v-model="name"
+ required
+ maxlength="80"
+ :disabled="busy"
+ />
+ </div>
+ <div class="cf-site-actions">
+ <CloudButton
+ type="submit"
+ :disabled="busy || !name.trim()"
+ >{{ busy ? 'Saving…' : 'Save changes' }}</CloudButton
+ ><CloudButton
+ type="button"
+ variant="ghost"
+ :disabled="busy"
+ @click="reload"
+ >Reload settings</CloudButton
+ ><CloudButton
+ v-if="data.site.published"
+ type="button"
+ variant="destructive"
+ :disabled="busy"
+ @click="save(true)"
+ >Unpublish site</CloudButton
+ >
+ </div>
+ </form>
+ <p
+ v-else
+ class="cf-page-description"
+ >
+ Only workspace administrators can change these settings.
+ </p>
+ <p
+ v-if="message"
+ :role="failed ? 'alert' : 'status'"
+ class="cf-notice"
+ >
+ {{ message }}
+ </p>
+ </template>
+ </CloudCard>
+</template>
diff --git a/apps/cloud/app/pages/account/index.vue b/apps/cloud/app/pages/account/index.vue
index 271d3c0b..72f4e4e4 100644
--- a/apps/cloud/app/pages/account/index.vue
+++ b/apps/cloud/app/pages/account/index.vue
@@ -56,9 +56,8 @@ const { data: security } = await useFetch('/api/auth/security')
<CloudThemeToggle /></div
></CloudCard>
<div class="cf-notice">
- <strong>Your email is verified.</strong>Workspace and site setup are
- coming in the next stage. We’ll keep the essentials here as your space
- grows.
+ <strong>Your email is verified.</strong>Your workspace is ready. Create
+ and manage your gallery drafts from Your sites.
</div>
<CloudCard class="cf-settings-card"
><div class="cf-setting-row">
diff --git a/apps/cloud/app/pages/sites/[siteId]/index.vue b/apps/cloud/app/pages/sites/[siteId]/index.vue
index 6a2227c6..c4ee07f7 100644
--- a/apps/cloud/app/pages/sites/[siteId]/index.vue
+++ b/apps/cloud/app/pages/sites/[siteId]/index.vue
@@ -5,7 +5,7 @@ const entrance = useCloudMotion()
import type { EntrySiteContext } from '@chronoframe/contracts/entry'
definePageMeta({ key: (route) => route.fullPath })
-useSeoMeta({ title: 'Manage site — ChronoFrame', robots: 'noindex' })
+useSeoMeta({ title: 'Manage site — ChronoFrame Cloud', robots: 'noindex' })
const context = useEntryContext()
const fetcher = useRequestFetch()
let stream: EventSource | undefined
@@ -89,6 +89,7 @@ onBeforeUnmount(() => stream?.close())
</div>
</dl></CloudCard
>
+ <CloudSiteSettings :site-id="context.siteId" />
<CloudCard
v-if="!context.capabilities.mediaManagement"
class="cf-empty"
@@ -100,7 +101,7 @@ onBeforeUnmount(() => stream?.close())
</div>
<h2>A space for what comes next.</h2>
<p>
- Photo management and publishing setup are coming in the next stage.
+ Photo storage, uploads and publishing are coming in the next stage.
For now, you can review your site and membership details here.
</p>
<CloudButton
diff --git a/apps/cloud/app/pages/sites/index.vue b/apps/cloud/app/pages/sites/index.vue
index 6c997151..e82dc9ad 100644
--- a/apps/cloud/app/pages/sites/index.vue
+++ b/apps/cloud/app/pages/sites/index.vue
@@ -2,6 +2,21 @@
import { motion } from 'motion-v'
import { ArrowUpRight, Images, Compass, ShieldCheck } from 'lucide-vue-next'
const entrance = useCloudMotion()
+const workspace = ref<{ name: string } | null>(null)
+const workspaceError = ref(false)
+async function prepareWorkspace() {
+ workspaceError.value = false
+ try {
+ workspace.value = (
+ await $fetch<{ workspace: { name: string } }>('/api/workspaces/default', {
+ method: 'POST',
+ })
+ ).workspace
+ } catch {
+ workspaceError.value = true
+ }
+}
+onMounted(prepareWorkspace)
import type { EntrySiteCatalog } from '@chronoframe/contracts/entry'
useSeoMeta({ title: 'Your sites — ChronoFrame Cloud', robots: 'noindex' })
@@ -31,6 +46,25 @@ const sites = computed(() =>
{{ sites.length === 1 ? 'site' : 'sites' }}</CloudBadge
>
</div>
+ <p
+ v-if="workspace"
+ class="cf-section-label"
+ >
+ {{ workspace.name }}
+ </p>
+ <div
+ v-if="workspaceError"
+ class="cf-notice"
+ role="alert"
+ >
+ Your workspace could not be opened.
+ <CloudButton
+ variant="ghost"
+ @click="prepareWorkspace"
+ >Try again</CloudButton
+ >
+ </div>
+ <CloudSiteCreate v-if="workspace" />
<div
v-if="sites.length"
class="cf-site-grid"
@@ -67,8 +101,8 @@ const sites = computed(() =>
</div>
<h2>Your next chapter starts here.</h2>
<p>
- You have no sites yet. Workspace and site creation are coming in the
- next stage. Your space is ready when you are.
+ You have no sites yet. Create your first draft above to reserve an
+ address and start shaping your gallery.
</p>
<CloudButton
as-child
diff --git a/apps/cloud/server/api/sites/[siteId]/settings.get.ts b/apps/cloud/server/api/sites/[siteId]/settings.get.ts
new file mode 100644
index 00000000..3265895b
--- /dev/null
+++ b/apps/cloud/server/api/sites/[siteId]/settings.get.ts
@@ -0,0 +1,9 @@
+import { getRouterParam } from 'h3'
+import { definePlatformHandler } from '../../../../../shared/platform/runtime'
+import { siteManagement } from '../../../utils/site-management'
+export default definePlatformHandler(async (event) => {
+ const { userId, store } = await siteManagement(event)
+ return {
+ site: await store.get(userId, Number(getRouterParam(event, 'siteId'))),
+ }
+})
diff --git a/apps/cloud/server/api/sites/[siteId]/settings.patch.ts b/apps/cloud/server/api/sites/[siteId]/settings.patch.ts
new file mode 100644
index 00000000..bead43b9
--- /dev/null
+++ b/apps/cloud/server/api/sites/[siteId]/settings.patch.ts
@@ -0,0 +1,17 @@
+import { getRouterParam } from 'h3'
+import { definePlatformHandler } from '../../../../../shared/platform/runtime'
+import {
+ siteManagement,
+ siteManagementBody,
+} from '../../../utils/site-management'
+export default definePlatformHandler(async (event) => {
+ const { userId, store } = await siteManagement(event, true)
+ const body = await siteManagementBody(event)
+ return {
+ site: await store.update(userId, Number(getRouterParam(event, 'siteId')), {
+ name: body.name,
+ revision: body.revision,
+ published: body.published,
+ }),
+ }
+})
diff --git a/apps/cloud/server/api/sites/index.post.ts b/apps/cloud/server/api/sites/index.post.ts
new file mode 100644
index 00000000..71ae8277
--- /dev/null
+++ b/apps/cloud/server/api/sites/index.post.ts
@@ -0,0 +1,13 @@
+import { definePlatformHandler } from '../../../../shared/platform/runtime'
+import { siteManagement, siteManagementBody } from '../../utils/site-management'
+export default definePlatformHandler(async (event) => {
+ const { userId, store } = await siteManagement(event, true)
+ const body = await siteManagementBody(event)
+ return {
+ site: await store.create(userId, {
+ name: body.name,
+ slug: body.slug,
+ requestId: body.requestId,
+ }),
+ }
+})
diff --git a/apps/cloud/server/api/workspaces/default.post.ts b/apps/cloud/server/api/workspaces/default.post.ts
new file mode 100644
index 00000000..719e45be
--- /dev/null
+++ b/apps/cloud/server/api/workspaces/default.post.ts
@@ -0,0 +1,6 @@
+import { definePlatformHandler } from '../../../../shared/platform/runtime'
+import { siteManagement } from '../../utils/site-management'
+export default definePlatformHandler(async (event) => {
+ const { userId, store } = await siteManagement(event, true)
+ return { workspace: await store.defaultWorkspace(userId) }
+})
diff --git a/apps/cloud/server/middleware/platform-boundary.ts b/apps/cloud/server/middleware/platform-boundary.ts
index ca92bb85..ac3c4ea8 100644
--- a/apps/cloud/server/middleware/platform-boundary.ts
+++ b/apps/cloud/server/middleware/platform-boundary.ts
@@ -18,8 +18,9 @@ export default defineEventHandler((event) => {
'/api/auth/logout',
'/api/auth/security',
'/api/sites',
+ '/api/workspaces/default',
].includes(path) ||
- /^\/api\/sites\/[1-9][0-9]*\/(?:context|events)$/.test(path)
+ /^\/api\/sites\/[1-9][0-9]*\/(?:context|events|settings)$/.test(path)
if (platformRoute || accountRouteAllowed(path, event.method)) return
if (path === '/api' || (path.startsWith('/api/') && path !== '/api/health')) {
throw createError({ statusCode: 503, statusMessage: 'Service unavailable' })
diff --git a/apps/cloud/server/utils/site-management.ts b/apps/cloud/server/utils/site-management.ts
new file mode 100644
index 00000000..f1321f05
--- /dev/null
+++ b/apps/cloud/server/utils/site-management.ts
@@ -0,0 +1,34 @@
+import { createError, getHeader, readBody } from 'h3'
+import type { H3Event } from 'h3'
+import { requirePlatformSession } from '../../../shared/platform/context'
+import {
+ platformDatabase,
+ platformPortalOrigin,
+} from '../../../shared/platform/runtime'
+import { createD1Provisioning } from '../../../../packages/platform/src/index'
+
+export async function siteManagement(event: H3Event, mutation = false) {
+ const config = useRuntimeConfig(event).platform
+ platformPortalOrigin(event, config.portalOrigin, mutation)
+ const session = await requirePlatformSession(event, config)
+ return {
+ userId: session.userId,
+ store: createD1Provisioning(platformDatabase(event)),
+ }
+}
+export async function siteManagementBody(event: H3Event) {
+ if (
+ !getHeader(event, 'content-type')?.startsWith('application/json') ||
+ Number(getHeader(event, 'content-length')) > 4096
+ )
+ throw createError({ statusCode: 400 })
+ const body: unknown = await readBody(event)
+ if (
+ !body ||
+ typeof body !== 'object' ||
+ Array.isArray(body) ||
+ JSON.stringify(body).length > 4096
+ )
+ throw createError({ statusCode: 400 })
+ return body as Record<string, unknown>
+}
diff --git a/apps/shared/platform/runtime.ts b/apps/shared/platform/runtime.ts
index 7ba9cacb..1c58b086 100644
--- a/apps/shared/platform/runtime.ts
+++ b/apps/shared/platform/runtime.ts
@@ -83,6 +83,7 @@ export function definePlatformHandler<T>(
401: 'Authentication required or invalid code',
403: 'Permission denied',
404: 'Site not found',
+ 409: 'Site address or settings conflict; reload and try again',
429: 'Please wait before trying again',
503: 'Platform service unavailable',
}
diff --git a/packages/platform/migrations/0004_workspace_sites.sql b/packages/platform/migrations/0004_workspace_sites.sql
new file mode 100644
index 00000000..ea8dbec5
--- /dev/null
+++ b/packages/platform/migrations/0004_workspace_sites.sql
@@ -0,0 +1,9 @@
+-- Nullable ownership preserves existing workspaces and memberships unchanged.
+ALTER TABLE platform_workspaces ADD COLUMN owner_user_id INTEGER REFERENCES platform_users(id);
+CREATE UNIQUE INDEX platform_workspace_owner ON platform_workspaces(owner_user_id);
+ALTER TABLE platform_sites ADD COLUMN slug TEXT;
+ALTER TABLE platform_sites ADD COLUMN created_at INTEGER NOT NULL DEFAULT 0;
+ALTER TABLE platform_sites ADD COLUMN revision INTEGER NOT NULL DEFAULT 1;
+ALTER TABLE platform_sites ADD COLUMN provision_key TEXT;
+CREATE UNIQUE INDEX platform_site_slug ON platform_sites(slug);
+CREATE UNIQUE INDEX platform_site_provision ON platform_sites(workspace_id, provision_key);
diff --git a/packages/platform/src/index.ts b/packages/platform/src/index.ts
index 0a1149d8..38febdbd 100644
--- a/packages/platform/src/index.ts
+++ b/packages/platform/src/index.ts
@@ -180,3 +180,10 @@ export function createD1SiteCatalog(db: PlatformD1) {
},
}
}
+
+export {
+ createD1Provisioning,
+ siteIdentity,
+ ProvisioningError,
+} from './provisioning.ts'
+export type { ManagedSite } from './provisioning.ts'
diff --git a/packages/platform/src/provisioning.ts b/packages/platform/src/provisioning.ts
new file mode 100644
index 00000000..7643ed42
--- /dev/null
+++ b/packages/platform/src/provisioning.ts
@@ -0,0 +1,194 @@
+import type { PlatformD1 } from './index.ts'
+
+export class ProvisioningError extends Error {
+ statusCode: number
+ constructor(statusCode: number, message: string) {
+ super(message)
+ this.statusCode = statusCode
+ }
+}
+const reserved = new Set([
+ 'www',
+ 'app',
+ 'api',
+ 'admin',
+ 'account',
+ 'auth',
+ 'cloud',
+ 'site',
+ 'sites',
+ 'staging',
+ 'preview',
+ 'production',
+ 'mail',
+ 'email',
+ 'noreply',
+ 'support',
+ 'help',
+ 'docs',
+ 'status',
+ 'assets',
+ 'static',
+ 'cdn',
+ 'chronoframe',
+])
+export function siteIdentity(name: unknown, slug: unknown) {
+ if (
+ typeof name !== 'string' ||
+ !name.trim() ||
+ name.trim().length > 80 ||
+ Array.from(name).some(
+ (char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127,
+ )
+ )
+ throw new ProvisioningError(400, 'Invalid site name')
+ if (
+ typeof slug !== 'string' ||
+ !/^[a-z0-9](?:[a-z0-9-]{1,38}[a-z0-9])$/.test(slug) ||
+ reserved.has(slug)
+ )
+ throw new ProvisioningError(400, 'Invalid site address')
+ return { name: name.trim(), slug }
+}
+export interface ManagedSite {
+ siteId: number
+ workspaceId: number
+ name: string
+ slug: string | null
+ published: number
+ revision: number
+}
+const fields =
+ 's.id AS siteId, s.workspace_id AS workspaceId, s.name, s.slug, s.published, s.revision'
+/** Transactional D1 writes retain live membership checks, including during retries. */
+export function createD1Provisioning(db: PlatformD1) {
+ 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
+ ON CONFLICT(owner_user_id) DO NOTHING`)
+ .bind(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
+ .prepare(`INSERT INTO platform_memberships(user_id, workspace_id, role)
+ SELECT ?, id, 'admin' FROM platform_workspaces WHERE owner_user_id = ? AND changes() = 1
+ ON CONFLICT(user_id, workspace_id) DO NOTHING`)
+ .bind(userId, userId),
+ ])
+ const workspace = await db
+ .prepare(`SELECT w.id, w.name, m.role FROM platform_workspaces w
+ JOIN platform_memberships m ON m.workspace_id = w.id AND m.user_id = ?
+ WHERE w.owner_user_id = ?`)
+ .bind(userId, userId)
+ .first<{ id: number; name: string; role: string }>()
+ if (!workspace) throw new ProvisioningError(403, 'Workspace unavailable')
+ return workspace
+ }
+ async function get(userId: number, siteId: number) {
+ 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')`)
+ .bind(siteId, userId)
+ .first<ManagedSite & { role: string }>()
+ if (!site) throw new ProvisioningError(404, 'Site not found')
+ return site
+ }
+ return {
+ defaultWorkspace,
+ get,
+ async create(
+ userId: number,
+ input: { name: unknown; slug: unknown; requestId: unknown },
+ ) {
+ const identity = siteIdentity(input.name, input.slug)
+ if (
+ typeof input.requestId !== 'string' ||
+ !/^[a-f0-9-]{36}$/.test(input.requestId)
+ )
+ throw new ProvisioningError(400, 'Invalid request identifier')
+ const workspace = await defaultWorkspace(userId)
+ const existing = await db
+ .prepare(`SELECT ${fields} FROM platform_sites s
+ JOIN platform_memberships m ON m.workspace_id = s.workspace_id
+ WHERE s.workspace_id = ? AND s.provision_key = ? AND m.user_id = ? AND m.role = 'admin'`)
+ .bind(workspace.id, input.requestId, userId)
+ .first<ManagedSite>()
+ if (existing) {
+ if (existing.name !== identity.name || existing.slug !== identity.slug)
+ throw new ProvisioningError(409, 'Request identifier already used')
+ return existing
+ }
+ try {
+ const site = await 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
+ ON CONFLICT(workspace_id, provision_key) DO UPDATE SET provision_key = excluded.provision_key
+ RETURNING id AS siteId, workspace_id AS workspaceId, name, slug, published, revision`)
+ .bind(
+ workspace.id,
+ identity.name,
+ identity.slug,
+ Date.now(),
+ input.requestId,
+ workspace.id,
+ userId,
+ workspace.id,
+ )
+ .first<ManagedSite>()
+ if (!site)
+ throw new ProvisioningError(
+ 403,
+ 'Workspace site limit reached or permission changed',
+ )
+ if (site.name !== identity.name || site.slug !== identity.slug)
+ throw new ProvisioningError(409, 'Request identifier already used')
+ return site
+ } catch (error) {
+ if (
+ String(error).includes(
+ 'UNIQUE constraint failed: platform_sites.slug',
+ )
+ )
+ throw new ProvisioningError(409, 'Site address is already taken')
+ throw error
+ }
+ },
+ async update(
+ userId: number,
+ siteId: number,
+ input: { name: unknown; revision: unknown; published: unknown },
+ ) {
+ const current = await get(userId, siteId)
+ if (current.role !== 'admin')
+ throw new ProvisioningError(403, 'Administrator required')
+ const name = siteIdentity(input.name, current.slug ?? 'legacy-site').name
+ if (
+ !Number.isSafeInteger(input.revision) ||
+ 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 = ?, 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')
+ RETURNING id AS siteId, workspace_id AS workspaceId, name, slug, published, revision`)
+ .bind(
+ name,
+ input.published ? 1 : 0,
+ siteId,
+ input.revision as number,
+ userId,
+ )
+ .first<ManagedSite>()
+ if (!result)
+ throw new ProvisioningError(409, 'Site changed; reload before saving')
+ return result
+ },
+ }
+}
diff --git a/tests/platform-provisioning.test.ts b/tests/platform-provisioning.test.ts
new file mode 100644
index 00000000..250f8d7a
--- /dev/null
+++ b/tests/platform-provisioning.test.ts
@@ -0,0 +1,231 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { createRequire } from 'node:module'
+import { readFile } from 'node:fs/promises'
+import {
+ createD1Provisioning,
+ siteIdentity,
+ type PlatformD1,
+} from '../packages/platform/src/index.ts'
+const require = createRequire(import.meta.url)
+const { Miniflare, convertV4MiniflareOptions } = createRequire(
+ require.resolve('wrangler/package.json'),
+)('miniflare')
+
+test('Site identity rejects reserved, malformed and ambiguous addresses', () => {
+ for (const slug of [
+ 'app',
+ 'admin',
+ 'chronoframe',
+ 'UPPER',
+ 'a',
+ 'ab',
+ '-abc',
+ 'abc-',
+ 'a.b',
+ 'a/b',
+ 'a'.repeat(41),
+ ])
+ assert.throws(() => siteIdentity('Gallery', slug))
+ for (const name of ['', ' ', 'a'.repeat(81), 'bad\nname'])
+ assert.throws(() => siteIdentity(name, 'valid-site'))
+ assert.deepEqual(siteIdentity(' My gallery ', 'valid-site'), {
+ name: 'My gallery',
+ slug: 'valid-site',
+ })
+})
+
+test('Real D1 provisioning preserves old tenants, serializes defaults and enforces admin, uniqueness and revisions', async () => {
+ const mf = new Miniflare(
+ convertV4MiniflareOptions({
+ modules: true,
+ compatibilityDate: '2026-10-22',
+ script: 'export default {fetch(){return new Response("test")}}',
+ d1Databases: ['DB'],
+ }),
+ )
+ try {
+ const db = await mf.getD1Database('DB')
+ async function migrate(name: string) {
+ const sql = await readFile(
+ new URL('../packages/platform/migrations/' + name, import.meta.url),
+ 'utf8',
+ )
+ for (const s of sql
+ .replace(/^--.*$/gm, '')
+ .split(';')
+ .map((s) => s.trim())
+ .filter(Boolean))
+ await db.prepare(s).run()
+ }
+ await migrate('0001_platform.sql')
+ await db
+ .prepare(
+ "INSERT INTO platform_users(id,email,created_at) VALUES(42,'[email protected]',1),(43,'[email protected]',1),(44,'[email protected]',1)",
+ )
+ .run()
+ await db
+ .prepare("INSERT INTO platform_workspaces VALUES(7,'Original workspace')")
+ .run()
+ await db
+ .prepare("INSERT INTO platform_sites VALUES(8,7,'Original gallery',1)")
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_memberships VALUES(42,7,'admin'),(43,7,'member')",
+ )
+ .run()
+ await migrate('0002_visitor_access.sql')
+ await migrate('0003_account_security.sql')
+ await migrate('0004_workspace_sites.sql')
+ await db
+ .prepare('UPDATE platform_users SET email_verified=0 WHERE id=44')
+ .run()
+ const store = createD1Provisioning(db as PlatformD1)
+ const defaults = await Promise.all(
+ Array.from({ length: 6 }, () => store.defaultWorkspace(42)),
+ )
+ assert.equal(new Set(defaults.map((w) => w.id)).size, 1)
+ assert.equal(defaults[0].role, 'admin')
+ assert.equal(
+ (
+ await db
+ .prepare(
+ 'SELECT COUNT(*) AS n FROM platform_workspaces WHERE owner_user_id=42',
+ )
+ .first()
+ ).n,
+ 1,
+ )
+ await assert.rejects(store.defaultWorkspace(44), { statusCode: 403 })
+ await assert.rejects(store.defaultWorkspace(999), { statusCode: 403 })
+ assert.equal((await store.get(42, 8)).name, 'Original gallery')
+ assert.equal((await store.get(43, 8)).role, 'member')
+ assert.equal((await store.get(42, 8)).published, 1)
+ await assert.rejects(
+ store.update(43, 8, { name: 'Hijack', published: false, revision: 1 }),
+ { statusCode: 403 },
+ )
+ const input = {
+ name: 'First gallery',
+ slug: 'first-gallery',
+ requestId: crypto.randomUUID(),
+ }
+ const first = await store.create(42, input)
+ assert.equal(first.published, 0)
+ assert.equal((await store.create(42, input)).siteId, first.siteId)
+ await assert.rejects(store.create(42, { ...input, name: 'Changed' }), {
+ statusCode: 409,
+ })
+ await assert.rejects(store.get(43, first.siteId), { statusCode: 404 })
+ await assert.rejects(
+ store.update(43, first.siteId, {
+ name: 'Hijack',
+ published: false,
+ revision: 1,
+ }),
+ { statusCode: 404 },
+ )
+ await assert.rejects(
+ store.create(43, { ...input, requestId: crypto.randomUUID() }),
+ { statusCode: 409 },
+ )
+ const updated = await store.update(42, first.siteId, {
+ name: 'Renamed',
+ published: false,
+ revision: 1,
+ })
+ assert.equal(updated.revision, 2)
+ await assert.rejects(
+ store.update(42, first.siteId, {
+ name: 'Stale',
+ published: false,
+ revision: 1,
+ }),
+ { statusCode: 409 },
+ )
+ await assert.rejects(
+ store.update(42, first.siteId, {
+ name: 'Renamed',
+ published: true,
+ revision: 2,
+ }),
+ { statusCode: 400 },
+ )
+ const races = await Promise.allSettled(
+ [42, 43].map((id) =>
+ store.create(id, {
+ name: 'Race',
+ slug: 'one-address',
+ requestId: crypto.randomUUID(),
+ }),
+ ),
+ )
+ assert.equal(races.filter((r) => r.status === 'fulfilled').length, 1)
+ // Draft creation never creates a public mapping, or alters the existing published gallery.
+ assert.equal(
+ (await db.prepare('SELECT COUNT(*) AS n FROM platform_domains').first())
+ .n,
+ 0,
+ )
+ assert.equal((await store.get(42, 8)).published, 1)
+ const oldUpdated = await store.update(42, 8, {
+ name: 'Original renamed',
+ published: true,
+ revision: 1,
+ })
+ assert.equal(oldUpdated.published, 1)
+ assert.equal(
+ (
+ await store.update(42, 8, {
+ name: 'Original renamed',
+ published: false,
+ revision: 2,
+ })
+ ).published,
+ 0,
+ )
+ // The pilot bound is enforced in the INSERT, including parallel writes.
+ await Promise.allSettled(
+ Array.from({ length: 15 }, (_, i) =>
+ store.create(42, {
+ name: 'Draft ' + i,
+ slug: 'limited-' + i,
+ requestId: crypto.randomUUID(),
+ }),
+ ),
+ )
+ assert.equal(
+ (
+ await db
+ .prepare(
+ 'SELECT COUNT(*) AS n FROM platform_sites WHERE workspace_id=?',
+ )
+ .bind(first.workspaceId)
+ .first()
+ ).n,
+ 10,
+ )
+ await db
+ .prepare(
+ 'DELETE FROM platform_memberships WHERE user_id=42 AND workspace_id=?',
+ )
+ .bind(first.workspaceId)
+ .run()
+ await assert.rejects(store.defaultWorkspace(42), { statusCode: 403 })
+ await assert.rejects(store.get(42, first.siteId), { statusCode: 404 })
+ assert.equal(
+ (
+ await db
+ .prepare(
+ 'SELECT COUNT(*) AS n FROM platform_memberships WHERE user_id=42 AND workspace_id=?',
+ )
+ .bind(first.workspaceId)
+ .first()
+ ).n,
+ 0,
+ )
+ } finally {
+ await mf.dispose()
+ }
+})