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: complete P3 site contexts and entry capabilities

HoshinoSuzumiBot42fa905ff72f
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index dc865db1..b7639dca 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,6 +1,6 @@
# Contributing
-Contributions to code, documentation and translations are welcome. The detailed guide is available in [English](https://chronoframe.bh8.ga/development/contributing.html) and [简体中文](https://chronoframe.bh8.ga/zh/development/contributing.html).
+Contributions to code, documentation and translations are welcome. The detailed guide is available in [English](https://docs.chronoframe.art/development/contributing.html) and [简体中文](https://docs.chronoframe.art/zh/development/contributing.html).
Use Node.js 22, matching the Docker build, and the project's pinned pnpm 10.34.6. This repository contains workspace packages; install dependencies with pnpm.
diff --git a/README.md b/README.md
index 4471b01d..71724610 100644
--- a/README.md
+++ b/README.md
@@ -30,7 +30,7 @@
ChronoFrame is a self-hosted photo gallery. Upload your photos and it extracts EXIF, creates previews and identifies shooting locations. Visitors can browse by time, album or map, zoom into large images and play Live Photos.
-[Live demo](https://lens.bh8.ga) · [Documentation](https://chronoframe.bh8.ga/) · [Changelog](https://chronoframe.bh8.ga/changelog)
+[Live demo](https://lens.bh8.ga) · [Documentation](https://docs.chronoframe.art/) · [Changelog](https://docs.chronoframe.art/changelog)
## ✨ Features
@@ -77,7 +77,7 @@ Open `http://localhost:3000` and use the setup wizard to create your administrat
Keep the `./data` mount: it holds the database, settings, session secret and local photos when using the path above.
-Use HTTPS for a public deployment. See [Getting Started](https://chronoframe.bh8.ga/guide/getting-started) and the [update guide](https://chronoframe.bh8.ga/guide/updates) for proxies, backups and migration from older versions.
+Use HTTPS for a public deployment. See [Getting Started](https://docs.chronoframe.art/guide/getting-started) and the [update guide](https://docs.chronoframe.art/guide/updates) for proxies, backups and migration from older versions.
## 📖 Usage
@@ -85,7 +85,7 @@ Sign in and open `/dashboard` to upload and organize photos. After upload, the t
For Apple Live Photos, the image and MOV must share a filename, such as `IMG_1234.heic` and `IMG_1234.mov`; either can be uploaded first. Image formats include JPEG, PNG, WebP, GIF, BMP, TIFF and HEIC / HEIF.
-Album passwords control access through ChronoFrame. If S3, OpenList or a CDN exposes public image URLs, manage access in that service too. Read [Using ChronoFrame](https://chronoframe.bh8.ga/guide/usage) for details.
+Album passwords control access through ChronoFrame. If S3, OpenList or a CDN exposes public image URLs, manage access in that service too. Read [Using ChronoFrame](https://docs.chronoframe.art/guide/usage) for details.
## 📸 Screenshots
@@ -114,7 +114,7 @@ pnpm build # Build the application
pnpm docs:build # Build documentation
```
-After changing the database schema, run `pnpm db:generate` and review the SQL. Generating migrations is unnecessary just to start the app. See the [contributing guide](https://chronoframe.bh8.ga/development/contributing.html) for more.
+After changing the database schema, run `pnpm db:generate` and review the SQL. Generating migrations is unnecessary just to start the app. See the [contributing guide](https://docs.chronoframe.art/development/contributing.html) for more.
## 📄 License
diff --git a/README_zh.md b/README_zh.md
index 11386d79..0ae6ea6e 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -30,7 +30,7 @@
ChronoFrame 是一个可以自行部署的照片画廊。上传照片后,应用会提取 EXIF、生成预览并整理拍摄地点;访客可以按时间、相册或地图浏览,也能查看大图和播放实况照片。
-[在线演示](https://lens.bh8.ga) · [使用文档](https://chronoframe.bh8.ga/zh/) · [更新日志](https://chronoframe.bh8.ga/zh/changelog)
+[在线演示](https://lens.bh8.ga) · [使用文档](https://docs.chronoframe.art/zh/) · [更新日志](https://docs.chronoframe.art/zh/changelog)
## ✨ 功能
@@ -77,7 +77,7 @@ docker run -d --name chronoframe --restart unless-stopped \
请保留 `./data` 挂载,其中包含数据库、设置、会话密钥,以及采用上述路径时的本地照片。
-部署到公网时使用 HTTPS。反向代理、数据备份和旧版迁移见[快速开始](https://chronoframe.bh8.ga/zh/guide/getting-started)和[升级指南](https://chronoframe.bh8.ga/zh/guide/updates)。
+部署到公网时使用 HTTPS。反向代理、数据备份和旧版迁移见[快速开始](https://docs.chronoframe.art/zh/guide/getting-started)和[升级指南](https://docs.chronoframe.art/zh/guide/updates)。
## 📖 使用
@@ -85,7 +85,7 @@ docker run -d --name chronoframe --restart unless-stopped \
Apple Live Photo 的图片和 MOV 文件需要相同文件名,例如 `IMG_1234.heic` 和 `IMG_1234.mov`,上传顺序不限。照片支持 JPEG、PNG、WebP、GIF、BMP、TIFF、HEIC / HEIF 等格式。
-密码相册限制的是通过 ChronoFrame 访问的内容。如果 S3、OpenList 或 CDN 提供公开的图片直链,需要同时管理外部服务的权限。详见[日常使用](https://chronoframe.bh8.ga/zh/guide/usage)。
+密码相册限制的是通过 ChronoFrame 访问的内容。如果 S3、OpenList 或 CDN 提供公开的图片直链,需要同时管理外部服务的权限。详见[日常使用](https://docs.chronoframe.art/zh/guide/usage)。
## 📸 截图
@@ -114,7 +114,7 @@ pnpm build # 构建应用
pnpm docs:build # 构建文档
```
-修改数据库 schema 后,使用 `pnpm db:generate` 生成迁移并检查 SQL。仅启动项目时无需生成迁移。更多说明见[贡献指南](https://chronoframe.bh8.ga/zh/development/contributing.html)。
+修改数据库 schema 后,使用 `pnpm db:generate` 生成迁移并检查 SQL。仅启动项目时无需生成迁移。更多说明见[贡献指南](https://docs.chronoframe.art/zh/development/contributing.html)。
## 📄 许可证
diff --git a/apps/cloud/app/middleware/platform.global.ts b/apps/cloud/app/middleware/platform.global.ts
index d5826fe6..86b99113 100644
--- a/apps/cloud/app/middleware/platform.global.ts
+++ b/apps/cloud/app/middleware/platform.global.ts
@@ -1,15 +1,27 @@
-export default defineNuxtRouteMiddleware((to) => {
+export default defineNuxtRouteMiddleware(async (to) => {
const path = to.path.toLowerCase()
- // The portal host never renders the marketing homepage. Do not infer login
- // from a shared/self-hosted cookie; platform identity is connected separately.
- if (path === '/' && useRequestURL().hostname === 'app.chronoframe.art') {
- return navigateTo('/signin', { redirectCode: 302 })
- }
+ const context = useEntryContext()
+ context.value = null
+ if (path === '/' && useRequestURL().hostname === 'app.chronoframe.art')
+ return navigateTo('/sites', { redirectCode: 302 })
if (path === '/dashboard' || path.startsWith('/dashboard/'))
- return navigateTo('/signin', { redirectCode: 302 })
+ return navigateTo('/sites', { redirectCode: 302 })
if (path === '/sites' || path.startsWith('/sites/')) {
- return abortNavigation(
- createError({ statusCode: 503, statusMessage: 'Service unavailable' }),
- )
+ const fetcher = useRequestFetch()
+ const session = await fetcher('/api/auth/session')
+ if (!session.authenticated)
+ return navigateTo('/signin', { redirectCode: 302 })
+ if (path !== '/sites') {
+ const match = /^\/sites\/([1-9][0-9]*)$/.exec(path)
+ if (!match)
+ return abortNavigation(
+ createError({ statusCode: 404, statusMessage: 'Page not found' }),
+ )
+ try {
+ context.value = await fetcher(`/api/sites/${match[1]}/context`)
+ } catch (error) {
+ return abortNavigation(error as Error)
+ }
+ }
}
})
diff --git a/apps/cloud/app/pages/account.vue b/apps/cloud/app/pages/account.vue
index de2ccd55..6f8d303a 100644
--- a/apps/cloud/app/pages/account.vue
+++ b/apps/cloud/app/pages/account.vue
@@ -4,6 +4,9 @@ const { data: session } = await useFetch('/api/auth/session')
if (!session.value?.authenticated) await navigateTo('/signin')
async function signOut() {
await $fetch('/api/auth/logout', { method: 'POST' })
+ clearNuxtData()
+ useEntryContext().value = null
+ useSettingsStore().$reset()
await navigateTo('/signin')
}
</script>
@@ -19,6 +22,7 @@ async function signOut() {
Your email is verified. Workspace and site setup are coming in the next
stage.
</p>
+ <NuxtLink to="/sites">Your sites</NuxtLink>
<UButton @click="signOut">Sign out</UButton>
</main>
</template>
diff --git a/apps/cloud/app/pages/index.vue b/apps/cloud/app/pages/index.vue
index 1ea4a457..c0ab6a0c 100644
--- a/apps/cloud/app/pages/index.vue
+++ b/apps/cloud/app/pages/index.vue
@@ -19,7 +19,7 @@ useSeoMeta({
>ChronoFrame</NuxtLink
>
<nav aria-label="Main navigation">
- <a href="https://chronoframe.bh8.ga/">Documentation</a
+ <a href="https://docs.chronoframe.art/">Documentation</a
><NuxtLink :to="signInUrl">Cloud access</NuxtLink>
</nav>
</header>
diff --git a/apps/cloud/app/pages/sites/[siteId]/index.vue b/apps/cloud/app/pages/sites/[siteId]/index.vue
new file mode 100644
index 00000000..ca7a17ac
--- /dev/null
+++ b/apps/cloud/app/pages/sites/[siteId]/index.vue
@@ -0,0 +1,48 @@
+<script setup lang="ts">
+import type { EntrySiteContext } from '@chronoframe/contracts/entry'
+definePageMeta({ key: (route) => route.fullPath })
+useSeoMeta({ title: 'Manage site — ChronoFrame', robots: 'noindex' })
+const context = useEntryContext()
+const fetcher = useRequestFetch()
+let stream: EventSource | undefined
+watch(
+ () => context.value?.scope,
+ () => stream?.close(),
+ { flush: 'sync' },
+)
+onMounted(() => {
+ const snapshot = context.value
+ if (!snapshot?.capabilities.subscriptions) return
+ const invalidate = () => {
+ stream?.close()
+ if (context.value?.scope !== snapshot.scope) return
+ context.value = null
+ void navigateTo('/sites')
+ }
+ const updateContext = (update: EntrySiteContext) => {
+ if (context.value?.scope !== snapshot.scope) return
+ if (update.scope !== snapshot.scope) return invalidate()
+ context.value = update
+ }
+ stream = new EventSource(`/api/sites/${snapshot.siteId}/events`)
+ stream.addEventListener('context', (event) => {
+ try {
+ updateContext(JSON.parse((event as MessageEvent).data))
+ } catch {
+ invalidate()
+ }
+ })
+ // A short stream reconnects every 15 seconds and rechecks live membership.
+ stream.onerror = () => {
+ void fetcher<EntrySiteContext>(`/api/sites/${snapshot.siteId}/context`)
+ .then(updateContext)
+ .catch(invalidate)
+ }
+})
+onBeforeUnmount(() => stream?.close())
+</script>
+<template>
+ <main class="cloud-message">
+ <SiteContextCard /><NuxtLink to="/sites">Switch site</NuxtLink>
+ </main>
+</template>
diff --git a/apps/cloud/app/pages/sites/index.vue b/apps/cloud/app/pages/sites/index.vue
index 35533856..d2575c7b 100644
--- a/apps/cloud/app/pages/sites/index.vue
+++ b/apps/cloud/app/pages/sites/index.vue
@@ -1 +1,37 @@
-<template><div /></template>
+<script setup lang="ts">
+useSeoMeta({ title: 'Your sites — ChronoFrame', robots: 'noindex' })
+const { data, error } = await useFetch('/api/sites', {
+ key: 'platform-site-list',
+ cache: 'no-store',
+})
+if (error.value)
+ throw createError({
+ statusCode: error.value.statusCode ?? 503,
+ statusMessage: 'Unable to load sites',
+ })
+</script>
+<template>
+ <main class="cloud-message">
+ <h1>Your sites</h1>
+ <ul
+ v-if="data?.sites.length"
+ class="space-y-4"
+ >
+ <li
+ v-for="site in data.sites"
+ :key="site.siteId"
+ >
+ <NuxtLink :to="`/sites/${site.siteId}`">{{ site.name }}</NuxtLink>
+ <span>
+ · {{ site.role }} ·
+ {{ site.published ? 'Published' : 'Not published' }}</span
+ >
+ </li>
+ </ul>
+ <p v-else>
+ You have no sites yet. Workspace and site creation are coming in the next
+ stage.
+ </p>
+ <NuxtLink to="/account">Your account</NuxtLink>
+ </main>
+</template>
diff --git a/apps/cloud/nuxt.config.ts b/apps/cloud/nuxt.config.ts
index 209ce2bf..f973d7e0 100644
--- a/apps/cloud/nuxt.config.ts
+++ b/apps/cloud/nuxt.config.ts
@@ -1,3 +1,4 @@
+import { CLOUD_CAPABILITIES } from '../../packages/contracts/src/entry'
import { sharedUi } from '../nuxt.shared'
import { fileURLToPath } from 'node:url'
const galleryPages = fileURLToPath(
@@ -16,6 +17,10 @@ export default defineNuxtConfig({
extends: ['../../packages/console', '../../packages/gallery'],
runtimeConfig: {
...sharedUi.runtimeConfig,
+ public: {
+ ...sharedUi.runtimeConfig.public,
+ capabilities: CLOUD_CAPABILITIES,
+ },
session: { name: 'chronoframe-cloud' },
platform: {
portalOrigin: 'https://app.chronoframe.art',
diff --git a/apps/cloud/server/api/sites/[siteId]/context.get.ts b/apps/cloud/server/api/sites/[siteId]/context.get.ts
index 65b656de..8c76e380 100644
--- a/apps/cloud/server/api/sites/[siteId]/context.get.ts
+++ b/apps/cloud/server/api/sites/[siteId]/context.get.ts
@@ -1,20 +1,11 @@
import { definePlatformHandler } from '../../../../../platform.runtime'
import {
- platformAccess,
- platformPortalOrigin,
- platformSession,
-} from '../../../../../platform.runtime'
-export default definePlatformHandler(async (event) => {
- const config = useRuntimeConfig(event).platform
- platformPortalOrigin(event, config.portalOrigin)
- const context = await platformAccess(event).authorizeSite(
- await platformSession(event, config.secret),
- Number(getRouterParam(event, 'siteId')),
- 'read',
- )
- return {
- siteId: context.site.id,
- workspaceId: context.site.workspaceId,
- role: context.role,
- }
-})
+ portalSiteContext,
+ siteContextDTO,
+} from '../../../../../platform-context'
+export default definePlatformHandler(async (event) =>
+ siteContextDTO(
+ event,
+ await portalSiteContext(event, useRuntimeConfig(event).platform),
+ ),
+)
diff --git a/apps/cloud/server/api/sites/[siteId]/events.get.ts b/apps/cloud/server/api/sites/[siteId]/events.get.ts
new file mode 100644
index 00000000..b9612545
--- /dev/null
+++ b/apps/cloud/server/api/sites/[siteId]/events.get.ts
@@ -0,0 +1,15 @@
+import { definePlatformHandler } from '../../../../../platform.runtime'
+import {
+ portalSiteContext,
+ siteContextDTO,
+} from '../../../../../platform-context'
+/** Each reconnect rechecks live membership; never hold a stale authorized stream open. */
+export default definePlatformHandler(async (event) => {
+ const context = await siteContextDTO(
+ event,
+ await portalSiteContext(event, useRuntimeConfig(event).platform),
+ )
+ setResponseHeader(event, 'Content-Type', 'text/event-stream')
+ setResponseHeader(event, 'X-Accel-Buffering', 'no')
+ return `retry: 15000\nevent: context\ndata: ${JSON.stringify(context)}\n\n`
+})
diff --git a/apps/cloud/server/api/sites/index.get.ts b/apps/cloud/server/api/sites/index.get.ts
new file mode 100644
index 00000000..3224a9b5
--- /dev/null
+++ b/apps/cloud/server/api/sites/index.get.ts
@@ -0,0 +1,17 @@
+import {
+ definePlatformHandler,
+ platformDatabase,
+} from '../../../../platform.runtime'
+import { requirePlatformSession } from '../../../../platform-context'
+import { createD1SiteCatalog } from '../../../../../packages/platform/src/index'
+export default definePlatformHandler(async (event) => {
+ const session = await requirePlatformSession(
+ event,
+ useRuntimeConfig(event).platform,
+ )
+ return {
+ sites: await createD1SiteCatalog(platformDatabase(event)).list(
+ session.userId,
+ ),
+ }
+})
diff --git a/apps/cloud/server/middleware/platform-boundary.ts b/apps/cloud/server/middleware/platform-boundary.ts
index 557b0780..381d9956 100644
--- a/apps/cloud/server/middleware/platform-boundary.ts
+++ b/apps/cloud/server/middleware/platform-boundary.ts
@@ -17,7 +17,9 @@ export default defineEventHandler((event) => {
'/api/auth/status',
'/api/auth/session',
'/api/auth/logout',
- ].includes(path) || /^\/api\/sites\/[1-9][0-9]*\/context$/.test(path)
+ '/api/sites',
+ ].includes(path) ||
+ /^\/api\/sites\/[1-9][0-9]*\/(?:context|events)$/.test(path)
if (platformRoute) return
if (path === '/api' || (path.startsWith('/api/') && path !== '/api/health')) {
throw createError({ statusCode: 503, statusMessage: 'Service unavailable' })
diff --git a/apps/platform-context.ts b/apps/platform-context.ts
new file mode 100644
index 00000000..5b3f1547
--- /dev/null
+++ b/apps/platform-context.ts
@@ -0,0 +1,69 @@
+import { platformStateKey } from '../packages/core/src/platform'
+import { createD1SiteCatalog } from '../packages/platform/src/index'
+import {
+ CLOUD_CAPABILITIES,
+ SITE_CAPABILITIES,
+} from '../packages/contracts/src/entry'
+import type { EntrySiteContext } from '../packages/contracts/src/entry'
+import type {
+ PortalContext,
+ PublicSiteContext,
+} from '../packages/core/src/platform'
+import {
+ platformAccess,
+ platformDatabase,
+ platformPortalOrigin,
+ platformSession,
+ platformRequestURL,
+} from './platform.runtime'
+import { createError, getRouterParam } from 'h3'
+import type { H3Event } from 'h3'
+
+export async function portalSiteContext(
+ event: H3Event,
+ config: { portalOrigin: string; secret: string },
+) {
+ platformPortalOrigin(event, config.portalOrigin)
+ return platformAccess(event).authorizeSite(
+ await platformSession(event, config.secret),
+ Number(getRouterParam(event, 'siteId')),
+ 'read',
+ )
+}
+export async function publicSiteContext(event: H3Event) {
+ return platformAccess(event).resolvePublicSite(
+ platformRequestURL(event).hostname,
+ )
+}
+export async function siteContextDTO(
+ event: H3Event,
+ context: PortalContext | PublicSiteContext,
+): Promise<EntrySiteContext> {
+ return {
+ siteId: context.site.id,
+ name: await createD1SiteCatalog(platformDatabase(event)).name(
+ context.site.id,
+ ),
+ scope: platformStateKey(context, 'ui'),
+ published: context.site.published,
+ audience: context.kind,
+ capabilities:
+ context.kind === 'portal' ? CLOUD_CAPABILITIES : SITE_CAPABILITIES,
+ ...(context.kind === 'portal'
+ ? { role: context.role, workspaceId: context.site.workspaceId }
+ : {}),
+ }
+}
+export async function requirePlatformSession(
+ event: H3Event,
+ config: { portalOrigin: string; secret: string },
+) {
+ platformPortalOrigin(event, config.portalOrigin)
+ const session = await platformSession(event, config.secret)
+ if (!session)
+ throw createError({
+ statusCode: 401,
+ statusMessage: 'Platform session required',
+ })
+ return session
+}
diff --git a/apps/platform-visitor.ts b/apps/platform-visitor.ts
new file mode 100644
index 00000000..7aae7913
--- /dev/null
+++ b/apps/platform-visitor.ts
@@ -0,0 +1,201 @@
+import { createError, getCookie, getHeader, setCookie } from 'h3'
+import type { H3Event } from 'h3'
+import type {
+ PublicSiteContext,
+ SiteVisitorGrant,
+} from '../packages/core/src/platform.ts'
+import { hasSiteVisitorGrant } from '../packages/core/src/platform.ts'
+import { platformDatabase, platformRequestURL } from './platform.runtime.ts'
+import { createEmailCodeCrypto } from './platform-crypto.ts'
+
+const encoder = new TextEncoder()
+const COOKIE = '__Host-chronoframe-visitor'
+const TTL = 60 * 60 * 1000
+const iterations = 600_000
+export async function visitorPasswordHash(
+ password: string,
+ salt: string,
+): Promise<string> {
+ const key = await crypto.subtle.importKey(
+ 'raw',
+ encoder.encode(password),
+ 'PBKDF2',
+ false,
+ ['deriveBits'],
+ )
+ const bits = await crypto.subtle.deriveBits(
+ { name: 'PBKDF2', hash: 'SHA-256', salt: encoder.encode(salt), iterations },
+ key,
+ 256,
+ )
+ return Array.from(new Uint8Array(bits), (b) =>
+ b.toString(16).padStart(2, '0'),
+ ).join('')
+}
+async function signingKey(secret: string) {
+ if (encoder.encode(secret).length < 32) throw createError({ statusCode: 503 })
+ return crypto.subtle.importKey(
+ 'raw',
+ encoder.encode(secret),
+ { name: 'HMAC', hash: 'SHA-256' },
+ false,
+ ['sign', 'verify'],
+ )
+}
+export async function encodeVisitorGrants(
+ secret: string,
+ host: string,
+ grants: readonly SiteVisitorGrant[],
+): Promise<string> {
+ const body = btoa(
+ String.fromCharCode(...encoder.encode(JSON.stringify(grants))),
+ )
+ const signature = await crypto.subtle.sign(
+ 'HMAC',
+ await signingKey(secret),
+ encoder.encode(JSON.stringify(['visitor-v1', host, body])),
+ )
+ return body + '.' + btoa(String.fromCharCode(...new Uint8Array(signature)))
+}
+export async function decodeVisitorGrants(
+ secret: string,
+ host: string,
+ token: string | undefined,
+): Promise<SiteVisitorGrant[]> {
+ if (!token || token.length > 4096) return []
+ try {
+ const [body, signature, extra] = token.split('.')
+ if (!body || !signature || extra) return []
+ const valid = await crypto.subtle.verify(
+ 'HMAC',
+ await signingKey(secret),
+ Uint8Array.from(atob(signature), (c) => c.charCodeAt(0)),
+ encoder.encode(JSON.stringify(['visitor-v1', host, body])),
+ )
+ if (!valid) return []
+ const grants = JSON.parse(
+ new TextDecoder().decode(
+ Uint8Array.from(atob(body), (c) => c.charCodeAt(0)),
+ ),
+ )
+ if (!Array.isArray(grants) || grants.length > 10) return []
+ return grants.filter(
+ (g) =>
+ g &&
+ Number.isSafeInteger(g.siteId) &&
+ g.siteId > 0 &&
+ Number.isSafeInteger(g.albumId) &&
+ g.albumId > 0 &&
+ typeof g.revision === 'string' &&
+ Number.isFinite(g.expiresAt) &&
+ g.expiresAt > Date.now() &&
+ g.expiresAt <= Date.now() + TTL,
+ )
+ } catch {
+ return []
+ }
+}
+async function policy(
+ event: H3Event,
+ context: PublicSiteContext,
+ albumId: number,
+) {
+ if (!Number.isSafeInteger(albumId) || albumId < 1)
+ throw createError({ statusCode: 404 })
+ const result = await platformDatabase(event)
+ .prepare(
+ 'SELECT revision, salt, password_hash AS passwordHash FROM platform_album_access WHERE site_id = ? AND album_id = ?',
+ )
+ .bind(context.site.id, albumId)
+ .first<{ revision: string; salt: string; passwordHash: string }>()
+ if (!result) throw createError({ statusCode: 404 })
+ if (
+ !result.revision ||
+ result.revision.length > 128 ||
+ !result.salt ||
+ result.salt.length > 128 ||
+ !/^[0-9a-f]{64}$/.test(result.passwordHash)
+ )
+ throw createError({ statusCode: 503 })
+ return result
+}
+export async function visitorAccess(
+ event: H3Event,
+ context: PublicSiteContext,
+ albumId: number,
+ secret: string,
+) {
+ const current = await policy(event, context, albumId)
+ const grants = await decodeVisitorGrants(
+ secret,
+ context.host,
+ getCookie(event, COOKIE),
+ )
+ return {
+ albumId,
+ unlocked: hasSiteVisitorGrant(context, grants, albumId, current.revision),
+ }
+}
+export async function unlockVisitor(
+ event: H3Event,
+ context: PublicSiteContext,
+ albumId: number,
+ password: unknown,
+ secret: string,
+) {
+ if (getHeader(event, 'origin') !== platformRequestURL(event).origin)
+ throw createError({ statusCode: 403 })
+ if (
+ typeof password !== 'string' ||
+ password.length < 1 ||
+ password.length > 1024
+ )
+ throw createError({ statusCode: 400 })
+ const current = await policy(event, context, albumId)
+ const client = getHeader(event, 'cf-connecting-ip')
+ if (!event.context.cloudflare || !client)
+ throw createError({ statusCode: 503 })
+ const mac = await createEmailCodeCrypto(secret)
+ const clientKey = await mac.mac(['visitor-attempt', context.site.id, client])
+ const window = Math.floor(Date.now() / 60_000)
+ const row = await platformDatabase(event)
+ .prepare(`INSERT INTO platform_visitor_limits(key, window_start, attempts) VALUES(?, ?, 1)
+ ON CONFLICT(key) DO UPDATE SET attempts = CASE WHEN window_start = excluded.window_start THEN attempts + 1 ELSE 1 END, window_start = excluded.window_start RETURNING attempts`)
+ .bind(clientKey, window)
+ .first<{ attempts: number }>()
+ if (!row || row.attempts > 5) throw createError({ statusCode: 429 })
+ const hash = await visitorPasswordHash(password, current.salt)
+ // Verify equality with Web Crypto rather than comparing password-derived strings.
+ const hashKey = await signingKey(secret)
+ const proof = await crypto.subtle.sign(
+ 'HMAC',
+ hashKey,
+ encoder.encode(current.passwordHash),
+ )
+ if (
+ !(await crypto.subtle.verify('HMAC', hashKey, proof, encoder.encode(hash)))
+ )
+ throw createError({ statusCode: 401 })
+ const grants = (
+ await decodeVisitorGrants(secret, context.host, getCookie(event, COOKIE))
+ ).filter((g) => g.siteId === context.site.id && g.albumId !== albumId)
+ grants.push({
+ siteId: context.site.id,
+ albumId,
+ revision: current.revision,
+ expiresAt: Date.now() + TTL,
+ })
+ setCookie(
+ event,
+ COOKIE,
+ await encodeVisitorGrants(secret, context.host, grants.slice(-10)),
+ {
+ httpOnly: true,
+ secure: true,
+ sameSite: 'lax',
+ path: '/',
+ maxAge: TTL / 1000,
+ },
+ )
+ return { albumId, unlocked: true }
+}
diff --git a/apps/platform.runtime.ts b/apps/platform.runtime.ts
index c93adf85..7e5a59c7 100644
--- a/apps/platform.runtime.ts
+++ b/apps/platform.runtime.ts
@@ -11,11 +11,11 @@ import type { H3Event, EventHandler, EventHandlerRequest } from 'h3'
import {
createD1Directory,
createD1Sessions,
-} from '../packages/platform/src/index'
-import type { PlatformD1 } from '../packages/platform/src/index'
-import { createPlatformAccess } from '../packages/core/src/platform'
-import type { PlatformSession } from '../packages/core/src/platform'
-import { createEmailCodeCrypto } from './platform-crypto'
+} from '../packages/platform/src/index.ts'
+import type { PlatformD1 } from '../packages/platform/src/index.ts'
+import { createPlatformAccess } from '../packages/core/src/platform.ts'
+import type { PlatformSession } from '../packages/core/src/platform.ts'
+import { createEmailCodeCrypto } from './platform-crypto.ts'
export const PLATFORM_COOKIE = '__Host-chronoframe-session'
export function platformDatabase(event: H3Event): PlatformD1 {
diff --git a/apps/self-hosted/app/plugins/custom-scripts.ts b/apps/self-hosted/app/plugins/custom-scripts.ts
index 6e47f799..3204696e 100644
--- a/apps/self-hosted/app/plugins/custom-scripts.ts
+++ b/apps/self-hosted/app/plugins/custom-scripts.ts
@@ -15,6 +15,7 @@ import { parseScriptTags } from '#gallery/utils/parseScriptTags'
* useHead 自动同步 DOM。
*/
export default defineNuxtPlugin(() => {
+ if (!useEntryCapabilities().customScripts) return
const headScriptsRef = useSettingRef('analytics:headScripts')
const bodyScriptsRef = useSettingRef('analytics:bodyScripts')
diff --git a/apps/self-hosted/nuxt.config.ts b/apps/self-hosted/nuxt.config.ts
index 5d8558cb..e85f7fa9 100644
--- a/apps/self-hosted/nuxt.config.ts
+++ b/apps/self-hosted/nuxt.config.ts
@@ -1,3 +1,4 @@
+import { SELF_HOSTED_CAPABILITIES } from '../../packages/contracts/src/entry'
import pkg from '../../package.json'
import type { AnalyticsConfig } from './shared/types/config'
import { dayjsLocales } from '../../packages/gallery/i18n/i18n.options'
@@ -31,6 +32,7 @@ export default defineNuxtConfig({
runtimeConfig: {
public: {
+ capabilities: SELF_HOSTED_CAPABILITIES,
console: {
apiBase: '',
signInPath: '/signin',
diff --git a/apps/site/.env.example b/apps/site/.env.example
index 09c25333..50c94b70 100644
--- a/apps/site/.env.example
+++ b/apps/site/.env.example
@@ -1,2 +1,5 @@
# App-local configuration; the root Self-hosted .env is not loaded.
# NUXT_SESSION_PASSWORD=replace-with-a-unique-secret-of-at-least-32-characters
+
+# Independent Site/Preview visitor-grant signing secret (never the portal secret):
+# NUXT_PLATFORM_SECRET=use-an-independent-random-secret-of-at-least-32-bytes
diff --git a/apps/site/app/middleware/site.global.ts b/apps/site/app/middleware/site.global.ts
index 6e828784..7cf1eae9 100644
--- a/apps/site/app/middleware/site.global.ts
+++ b/apps/site/app/middleware/site.global.ts
@@ -1,12 +1,24 @@
-/** A default Site is never inferred from an untrusted request Host. */
-export default defineNuxtRouteMiddleware((to) => {
- const path = to.path.toLowerCase()
- if (path === '/dashboard' || path.startsWith('/dashboard/')) {
+export default defineNuxtRouteMiddleware(async (to) => {
+ const context = useEntryContext()
+ context.value = null
+ if (
+ to.path.toLowerCase() === '/dashboard' ||
+ to.path.toLowerCase().startsWith('/dashboard/')
+ )
return abortNavigation(
createError({ statusCode: 404, statusMessage: 'Page not found' }),
)
+ try {
+ context.value = await useRequestFetch()('/api/public/context')
+ } catch (error) {
+ return abortNavigation(error as Error)
}
- return abortNavigation(
- createError({ statusCode: 503, statusMessage: 'Service unavailable' }),
- )
+ // Photo repositories are delivered in P4; never fall back to Self-hosted data.
+ if (to.path !== '/')
+ return abortNavigation(
+ createError({
+ statusCode: 503,
+ statusMessage: 'Gallery content is not available yet',
+ }),
+ )
})
diff --git a/apps/site/app/pages/index.vue b/apps/site/app/pages/index.vue
new file mode 100644
index 00000000..db268eb8
--- /dev/null
+++ b/apps/site/app/pages/index.vue
@@ -0,0 +1,10 @@
+<script setup lang="ts">
+const context = useEntryContext()
+useSeoMeta({
+ title: () => context.value?.name ?? 'ChronoFrame',
+ robots: 'noindex',
+})
+</script>
+<template>
+ <main class="mx-auto max-w-3xl p-8"><SiteContextCard /></main>
+</template>
diff --git a/apps/site/nuxt.config.ts b/apps/site/nuxt.config.ts
index 73c67d16..6aa385d4 100644
--- a/apps/site/nuxt.config.ts
+++ b/apps/site/nuxt.config.ts
@@ -1,3 +1,4 @@
+import { SITE_CAPABILITIES } from '../../packages/contracts/src/entry'
import { sharedUi } from '../nuxt.shared'
export default defineNuxtConfig({
...sharedUi,
@@ -12,6 +13,11 @@ export default defineNuxtConfig({
extends: ['../../packages/gallery'],
runtimeConfig: {
...sharedUi.runtimeConfig,
+ public: {
+ ...sharedUi.runtimeConfig.public,
+ capabilities: SITE_CAPABILITIES,
+ },
session: { name: 'chronoframe-site' },
+ platform: { secret: '' },
},
})
diff --git a/apps/site/server/api/public/albums/[albumId]/access.get.ts b/apps/site/server/api/public/albums/[albumId]/access.get.ts
new file mode 100644
index 00000000..7e2693b6
--- /dev/null
+++ b/apps/site/server/api/public/albums/[albumId]/access.get.ts
@@ -0,0 +1,11 @@
+import { definePlatformHandler } from '../../../../../../platform.runtime'
+import { publicSiteContext } from '../../../../../../platform-context'
+import { visitorAccess } from '../../../../../../platform-visitor'
+export default definePlatformHandler(async (event) =>
+ visitorAccess(
+ event,
+ await publicSiteContext(event),
+ Number(getRouterParam(event, 'albumId')),
+ useRuntimeConfig(event).platform.secret,
+ ),
+)
diff --git a/apps/site/server/api/public/albums/[albumId]/unlock.post.ts b/apps/site/server/api/public/albums/[albumId]/unlock.post.ts
new file mode 100644
index 00000000..1c5ed88a
--- /dev/null
+++ b/apps/site/server/api/public/albums/[albumId]/unlock.post.ts
@@ -0,0 +1,14 @@
+import { definePlatformHandler } from '../../../../../../platform.runtime'
+import { publicSiteContext } from '../../../../../../platform-context'
+import { unlockVisitor } from '../../../../../../platform-visitor'
+export default definePlatformHandler(async (event) => {
+ const context = await publicSiteContext(event)
+ const body = await readBody(event)
+ return unlockVisitor(
+ event,
+ context,
+ Number(getRouterParam(event, 'albumId')),
+ body?.password,
+ useRuntimeConfig(event).platform.secret,
+ )
+})
diff --git a/apps/site/server/api/public/context.get.ts b/apps/site/server/api/public/context.get.ts
index 761c10b8..4302d86b 100644
--- a/apps/site/server/api/public/context.get.ts
+++ b/apps/site/server/api/public/context.get.ts
@@ -1,11 +1,5 @@
import { definePlatformHandler } from '../../../../platform.runtime'
-import {
- platformAccess,
- platformRequestURL,
-} from '../../../../platform.runtime'
-export default definePlatformHandler(async (event) => {
- const context = await platformAccess(event).resolvePublicSite(
- platformRequestURL(event).hostname,
- )
- return { siteId: context.site.id, host: context.host }
-})
+import { publicSiteContext, siteContextDTO } from '../../../../platform-context'
+export default definePlatformHandler(async (event) =>
+ siteContextDTO(event, await publicSiteContext(event)),
+)
diff --git a/apps/site/server/middleware/platform-boundary.ts b/apps/site/server/middleware/platform-boundary.ts
index 891caf6d..9a2b89b4 100644
--- a/apps/site/server/middleware/platform-boundary.ts
+++ b/apps/site/server/middleware/platform-boundary.ts
@@ -10,7 +10,11 @@ export default defineEventHandler((event) => {
statusMessage: 'Invalid request path',
})
}
- if (path === '/api/public/context') return
+ if (
+ path === '/api/public/context' ||
+ /^\/api\/public\/albums\/[1-9][0-9]*\/(?:access|unlock)$/.test(path)
+ )
+ return
if (path === '/api' || (path.startsWith('/api/') && path !== '/api/health')) {
throw createError({ statusCode: 503, statusMessage: 'Service unavailable' })
}
diff --git a/packages/console/README.md b/packages/console/README.md
index d90ef5a5..4ba4f517 100644
--- a/packages/console/README.md
+++ b/packages/console/README.md
@@ -8,3 +8,10 @@ server APIs; the dashboard session check is a presentation guard.
The entry sets `runtimeConfig.public.console`: `apiBase` (application API origin),
`signInPath`, `galleryPath`, and optional `navigation` groups. Issued storage URLs
are not prefixed. The Self-hosted entry retains its existing defaults.
+
+Shared console requests use the entry-provided Site context and capability profile.
+Storage selectors honor the advertised provider support list; subscriptions close
+on a Site/account switch. Authorization is always rechecked by server adapters.
+Self-hosted retains instance sessions, SQLite, Local/S3/OpenList, custom scripts,
+and unlimited quota. Cloud advertises only implemented platform capabilities;
+media management and plan enforcement are delivered by later SaaS phases.
diff --git a/packages/console/app/composables/useConsoleApi.ts b/packages/console/app/composables/useConsoleApi.ts
index 0d6069ec..b937552e 100644
--- a/packages/console/app/composables/useConsoleApi.ts
+++ b/packages/console/app/composables/useConsoleApi.ts
@@ -1,26 +1,13 @@
-/** Apply the entry API base using request-scoped fetch, preserving SSR cookies. */
+import { useEntryApi, useEntryFetch } from '#gallery/composables/useEntryApi'
export function useConsoleApi() {
- const baseURL = useRuntimeConfig().public.console.apiBase
- // Keep the implementation boundary independent of Nuxt's recursive route types.
- // Callers retain the same generic response inference as the original $fetch.
- const fetcher = useRequestFetch() as (
- request: unknown,
- options?: Record<string, unknown>,
- ) => Promise<unknown>
- return ((request: unknown, options?: Record<string, unknown>) =>
- fetcher(request, { baseURL, ...options })) as typeof $fetch
+ return useEntryApi(useRuntimeConfig().public.console.apiBase)
}
-/** Preserve useFetch inference without instantiating its generic overloads here. */
export const useConsoleFetch = ((
request: unknown,
options?: Record<string, unknown>,
-) => {
- const fetcher = useFetch as (
- request: unknown,
- options?: Record<string, unknown>,
- ) => unknown
- return fetcher(request, {
- baseURL: useRuntimeConfig().public.console.apiBase,
- ...options,
- })
-}) as typeof useFetch
+) =>
+ useEntryFetch(
+ request,
+ options,
+ useRuntimeConfig().public.console.apiBase,
+ )) as typeof useFetch
diff --git a/packages/console/app/layouts/dashboard.vue b/packages/console/app/layouts/dashboard.vue
index 78ca0640..9dc39260 100644
--- a/packages/console/app/layouts/dashboard.vue
+++ b/packages/console/app/layouts/dashboard.vue
@@ -93,7 +93,7 @@ const defaultNavItems = computed<NavigationMenuItem[][]>(() => [
{
label: $t('dashboard.nav.documentation'),
icon: 'tabler:book',
- to: 'https://chronoframe.bh8.ga/',
+ to: 'https://docs.chronoframe.art/',
target: '_blank',
},
{
diff --git a/packages/console/app/pages/dashboard/logs.vue b/packages/console/app/pages/dashboard/logs.vue
index e7221c4a..6f331967 100644
--- a/packages/console/app/pages/dashboard/logs.vue
+++ b/packages/console/app/pages/dashboard/logs.vue
@@ -5,6 +5,8 @@ const consoleApiBase = useRuntimeConfig().public.console.apiBase.replace(
)
const consoleApi = useConsoleApi()
+const entryContext = useEntryContext()
+const capabilities = useEntryCapabilities()
definePageMeta({
layout: 'dashboard',
@@ -412,11 +414,11 @@ const appendLines = (lines: string[]) => {
}
const openLiveStream = () => {
- if (disposed) return
+ if (disposed || !capabilities.subscriptions) return
connectionState.value = 'connecting'
eventSource?.close()
const source = new EventSource(
- `${consoleApiBase}/api/system/logs?stream=1&offset=${liveOffset}&identity=${encodeURIComponent(fileIdentity)}`,
+ `${consoleApiBase}${entryRequestPath(`/api/system/logs?stream=1&offset=${liveOffset}&identity=${encodeURIComponent(fileIdentity)}`, entryContext.value)}`,
{ withCredentials: true },
)
eventSource = source
@@ -567,6 +569,18 @@ onMounted(() => {
connectLogStream()
})
+watch(
+ () => entryContext.value?.scope,
+ () => {
+ disposed = true
+ requestController?.abort()
+ eventSource?.close()
+ if (reconnectTimer) clearTimeout(reconnectTimer)
+ logs.value = []
+ },
+ { flush: 'sync' },
+)
+
onUnmounted(() => {
disposed = true
requestController?.abort()
diff --git a/packages/console/app/pages/dashboard/settings/storage.vue b/packages/console/app/pages/dashboard/settings/storage.vue
index f1218ef1..9f8c3977 100644
--- a/packages/console/app/pages/dashboard/settings/storage.vue
+++ b/packages/console/app/pages/dashboard/settings/storage.vue
@@ -99,23 +99,26 @@ const getStorageDestination = (storage: SettingStorageProvider) => {
}
}
-const providerOptions = computed(() => [
- {
- label: $t('settings.storage.providers.s3'),
- value: 's3',
- icon: PROVIDER_ICON.s3,
- },
- {
- label: $t('settings.storage.providers.local'),
- value: 'local',
- icon: PROVIDER_ICON.local,
- },
- {
- label: $t('settings.storage.providers.openlist'),
- value: 'openlist',
- icon: PROVIDER_ICON.openlist,
- },
-])
+const capabilities = useEntryCapabilities()
+const providerOptions = computed(() =>
+ [
+ {
+ label: $t('settings.storage.providers.s3'),
+ value: 's3',
+ icon: PROVIDER_ICON.s3,
+ },
+ {
+ label: $t('settings.storage.providers.local'),
+ value: 'local',
+ icon: PROVIDER_ICON.local,
+ },
+ {
+ label: $t('settings.storage.providers.openlist'),
+ value: 'openlist',
+ icon: PROVIDER_ICON.openlist,
+ },
+ ].filter((option) => capabilities.storageProviders.includes(option.value)),
+)
const storageConfigState = reactive<{
name: string
diff --git a/packages/contracts/package.json b/packages/contracts/package.json
index 3b581997..5054b94b 100644
--- a/packages/contracts/package.json
+++ b/packages/contracts/package.json
@@ -11,7 +11,8 @@
"./location": "./src/location.ts",
"./resources": "./src/resources.ts",
"./settings": "./src/settings.ts",
- "./queue": "./src/queue.ts"
+ "./queue": "./src/queue.ts",
+ "./entry": "./src/entry.ts"
},
"scripts": {
"type-check": "tsc --noEmit"
diff --git a/packages/contracts/src/entry.ts b/packages/contracts/src/entry.ts
new file mode 100644
index 00000000..63b7da11
--- /dev/null
+++ b/packages/contracts/src/entry.ts
@@ -0,0 +1,65 @@
+/** Public presentation capabilities, never authorization or a source of billing limits. */
+export interface EntryCapabilities {
+ edition: 'self-hosted' | 'cloud' | 'site'
+ identity: 'instance' | 'platform' | 'visitor'
+ database: 'sqlite' | 'd1'
+ storageProviders: readonly string[]
+ quota: 'unlimited' | 'plan'
+ mediaManagement: boolean
+ subscriptions: boolean
+ customScripts: boolean
+}
+export const SELF_HOSTED_CAPABILITIES: EntryCapabilities = {
+ edition: 'self-hosted',
+ identity: 'instance',
+ database: 'sqlite',
+ storageProviders: ['local', 's3', 'openlist'],
+ quota: 'unlimited',
+ mediaManagement: true,
+ subscriptions: true,
+ customScripts: true,
+}
+export const CLOUD_CAPABILITIES: EntryCapabilities = {
+ edition: 'cloud',
+ identity: 'platform',
+ database: 'd1',
+ storageProviders: [],
+ quota: 'plan',
+ mediaManagement: false,
+ subscriptions: true,
+ customScripts: false,
+}
+export const SITE_CAPABILITIES: EntryCapabilities = {
+ ...CLOUD_CAPABILITIES,
+ edition: 'site',
+ identity: 'visitor',
+ subscriptions: false,
+}
+export interface EntrySiteContext {
+ siteId: number
+ scope: string
+ name: string
+ published: boolean
+ audience: 'portal' | 'public'
+ role?: 'admin' | 'member'
+ workspaceId?: number
+ capabilities: EntryCapabilities
+}
+
+export function entryRequestPath(
+ path: string,
+ context: EntrySiteContext | null,
+): string {
+ if (!context) return path
+ if (
+ !path.startsWith('/api/') ||
+ decodeURIComponent(path.split('?')[0]!).includes('..') ||
+ /[#\\]/.test(path)
+ )
+ throw new Error('A scoped API path is required')
+ const prefix =
+ context.audience === 'portal'
+ ? `/api/sites/${context.siteId}`
+ : '/api/public'
+ return prefix + path.slice(4)
+}
diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts
index cceac9cf..157cdd21 100644
--- a/packages/contracts/src/index.ts
+++ b/packages/contracts/src/index.ts
@@ -4,3 +4,5 @@ export * from './photo.ts'
export * from './location.ts'
export * from './resources.ts'
export * from './settings.ts'
+
+export * from './entry.ts'
diff --git a/packages/gallery/README.md b/packages/gallery/README.md
index eb2ac6de..93b7aa7c 100644
--- a/packages/gallery/README.md
+++ b/packages/gallery/README.md
@@ -9,3 +9,10 @@ The host supplies the session adapter and `runtimeConfig.public.gallery.apiBase`
The entry owns its photo query and chooses public or authenticated data; the
viewer accepts that collection. This layer never imports console or server
implementations. Shared source modules are available through `./shared/*`.
+
+Entry middleware installs a request-local `EntrySiteContext` before rendering.
+Shared API helpers derive portal/public paths from that context and frame async
+cache keys with its Site/audience/principal scope. Site/account changes clear
+settings and viewer state; late settings responses cannot repopulate the old scope.
+Self-hosted uses its existing unprefixed APIs when no platform context is installed.
+Public capability flags describe available UI features, not authorization.
diff --git a/packages/gallery/app/components/SiteContextCard.vue b/packages/gallery/app/components/SiteContextCard.vue
new file mode 100644
index 00000000..d27a59a6
--- /dev/null
+++ b/packages/gallery/app/components/SiteContextCard.vue
@@ -0,0 +1,18 @@
+<script setup lang="ts">
+const context = useEntryContext()
+const capabilities = computed(() => context.value?.capabilities)
+</script>
+<template>
+ <section
+ v-if="context"
+ aria-label="Site details"
+ class="space-y-4"
+ >
+ <h1 class="text-3xl font-semibold">{{ context.name }}</h1>
+ <p>{{ context.published ? 'Published' : 'Not published' }}</p>
+ <p v-if="context.audience === 'portal'">Your role: {{ context.role }}</p>
+ <p v-if="!capabilities?.mediaManagement">
+ Photo management and publishing setup are coming in the next stage.
+ </p>
+ </section>
+</template>
diff --git a/packages/gallery/app/composables/useEntryApi.ts b/packages/gallery/app/composables/useEntryApi.ts
new file mode 100644
index 00000000..7fc63d58
--- /dev/null
+++ b/packages/gallery/app/composables/useEntryApi.ts
@@ -0,0 +1,29 @@
+import { useEntryContext, entryRequestPath } from './useEntryContext'
+/** Snapshot the context for this request; a route switch cannot retarget an in-flight request. */
+export function useEntryApi(baseURL: string) {
+ const context = useEntryContext()
+ const fetcher = useRequestFetch() as typeof $fetch
+ return ((request: string, options?: Record<string, unknown>) => {
+ const snapshot = context.value
+ return fetcher(entryRequestPath(request, snapshot), { ...options, baseURL })
+ }) as typeof $fetch
+}
+export function useEntryFetch(
+ request: unknown,
+ options: Record<string, unknown> | undefined,
+ baseURL: string,
+) {
+ const context = useEntryContext()
+ const path = computed(() =>
+ entryRequestPath(String(toValue(request as string)), context.value),
+ )
+ const key = computed(
+ () =>
+ `${context.value?.scope ?? 'self-hosted'}:fetch:${String(toValue(options?.key as string) ?? path.value)}`,
+ )
+ const fetcher = useFetch as (
+ request: unknown,
+ options: Record<string, unknown>,
+ ) => unknown
+ return fetcher(path, { ...options, baseURL, key })
+}
diff --git a/packages/gallery/app/composables/useEntryContext.ts b/packages/gallery/app/composables/useEntryContext.ts
new file mode 100644
index 00000000..e2e6d2e8
--- /dev/null
+++ b/packages/gallery/app/composables/useEntryContext.ts
@@ -0,0 +1,18 @@
+import type {
+ EntrySiteContext,
+ EntryCapabilities,
+} from '@chronoframe/contracts/entry'
+import { SELF_HOSTED_CAPABILITIES } from '@chronoframe/contracts/entry'
+
+/** Request-local on SSR; replaced before rendering any different tenant/account. */
+export function useEntryContext() {
+ return useState<EntrySiteContext | null>('entry-site-context', () => null)
+}
+export function useEntryCapabilities(): EntryCapabilities {
+ return (
+ useEntryContext().value?.capabilities ??
+ (useRuntimeConfig().public.capabilities as EntryCapabilities | undefined) ??
+ SELF_HOSTED_CAPABILITIES
+ )
+}
+export { entryRequestPath } from '@chronoframe/contracts/entry'
diff --git a/packages/gallery/app/composables/useGalleryApi.ts b/packages/gallery/app/composables/useGalleryApi.ts
index b7342c6c..50392cc7 100644
--- a/packages/gallery/app/composables/useGalleryApi.ts
+++ b/packages/gallery/app/composables/useGalleryApi.ts
@@ -1,26 +1,13 @@
-/** Apply the entry API base using request-scoped fetch, preserving SSR cookies. */
+import { useEntryApi, useEntryFetch } from './useEntryApi'
export function useGalleryApi() {
- const baseURL = useRuntimeConfig().public.gallery.apiBase
- // Keep the implementation boundary independent of Nuxt's recursive route types.
- // Callers retain the same generic response inference as the original $fetch.
- const fetcher = useRequestFetch() as (
- request: unknown,
- options?: Record<string, unknown>,
- ) => Promise<unknown>
- return ((request: unknown, options?: Record<string, unknown>) =>
- fetcher(request, { baseURL, ...options })) as typeof $fetch
+ return useEntryApi(useRuntimeConfig().public.gallery.apiBase)
}
-/** Preserve useFetch inference without instantiating its generic overloads here. */
export const useGalleryFetch = ((
request: unknown,
options?: Record<string, unknown>,
-) => {
- const fetcher = useFetch as (
- request: unknown,
- options?: Record<string, unknown>,
- ) => unknown
- return fetcher(request, {
- baseURL: useRuntimeConfig().public.gallery.apiBase,
- ...options,
- })
-}) as typeof useFetch
+) =>
+ useEntryFetch(
+ request,
+ options,
+ useRuntimeConfig().public.gallery.apiBase,
+ )) as typeof useFetch
diff --git a/packages/gallery/app/composables/useImageLoader.ts b/packages/gallery/app/composables/useImageLoader.ts
index a1313738..6970bd8b 100644
--- a/packages/gallery/app/composables/useImageLoader.ts
+++ b/packages/gallery/app/composables/useImageLoader.ts
@@ -24,7 +24,7 @@ export const useImageLoader = (
const t = $i18n.t
if (highResLoaded || !isCurrentImage || error) return null
- const loaderManager = new ImageLoaderManager()
+ const loaderManager = new ImageLoaderManager(useEntryContext().value?.scope)
const cleanup = () => {
loaderManager.cleanup()
diff --git a/packages/gallery/app/libs/image-loader-manager.ts b/packages/gallery/app/libs/image-loader-manager.ts
index 8e171296..e52d0a1b 100644
--- a/packages/gallery/app/libs/image-loader-manager.ts
+++ b/packages/gallery/app/libs/image-loader-manager.ts
@@ -41,7 +41,15 @@ const normalImageCache: LRUCache<string, ImageLoaderCacheResult> = new LRUCache<
}
})
+export function clearImageLoaderCache() {
+ normalImageCache.clear()
+}
+
export class ImageLoaderManager {
+ private readonly scope: string
+ constructor(scope = 'self-hosted') {
+ this.scope = scope
+ }
private lastXHR: XMLHttpRequest | null = null
private timer: NodeJS.Timeout | null = null
@@ -152,7 +160,7 @@ export class ImageLoaderManager {
callbacks: ImageLoaderCallbacks,
) {
const { onUpdateLoadingState } = callbacks
- const cacheKey = originalUrl
+ const cacheKey = JSON.stringify([this.scope, originalUrl])
const cacheResult = normalImageCache.get(cacheKey)
if (cacheResult) {
onUpdateLoadingState?.({
diff --git a/packages/gallery/app/plugins/entry-context.ts b/packages/gallery/app/plugins/entry-context.ts
new file mode 100644
index 00000000..2fb1281f
--- /dev/null
+++ b/packages/gallery/app/plugins/entry-context.ts
@@ -0,0 +1,22 @@
+import { clearImageLoaderCache } from '../libs/image-loader-manager'
+/** Drop tenant-owned client state before another Site is rendered. Preferences stay local. */
+export default defineNuxtPlugin(() => {
+ const context = useEntryContext()
+ const settings = useSettingsStore()
+ const viewer = useViewerState()
+ watch(
+ () => context.value?.scope,
+ (scope, previous) => {
+ if (scope === previous) return
+ if (import.meta.client) clearImageLoaderCache()
+ settings.$reset()
+ viewer.scopedPhotos = null
+ viewer.isViewerOpen = false
+ viewer.currentPhotoIndex = 0
+ viewer.isDirectAccess = false
+ viewer.clearReturnRoute()
+ clearNuxtData((key) => key.startsWith(`${previous}:fetch:`))
+ },
+ { flush: 'sync' },
+ )
+})
diff --git a/packages/gallery/app/stores/settings.ts b/packages/gallery/app/stores/settings.ts
index b0fc2384..4e30cbd1 100644
--- a/packages/gallery/app/stores/settings.ts
+++ b/packages/gallery/app/stores/settings.ts
@@ -60,19 +60,23 @@ export const useSettingsStore = defineStore('settings', {
this.isLoading = true
this.error = null
+ const context = useEntryContext()
+ const scope = context.value?.scope
try {
const response = await useGalleryApi()<PublicSettingsResponse>(
'/api/system/settings/all',
)
+ if (context.value?.scope !== scope) return
this.data = response.data
this.isInitialized = true
} catch (error) {
+ if (context.value?.scope !== scope) return
this.error = error as Error
console.error('[Settings] Failed to initialize settings:', error)
throw error
} finally {
- this.isLoading = false
+ if (context.value?.scope === scope) this.isLoading = false
}
},
@@ -114,19 +118,23 @@ export const useSettingsStore = defineStore('settings', {
this.isLoading = true
this.error = null
+ const context = useEntryContext()
+ const scope = context.value?.scope
try {
const response = await useGalleryApi()<PublicSettingsResponse>(
'/api/system/settings/all',
)
+ if (context.value?.scope !== scope) return
this.data = response.data
this.isInitialized = true
} catch (error) {
+ if (context.value?.scope !== scope) return
this.error = error as Error
console.error('[Settings] Failed to refresh settings:', error)
throw error
} finally {
- this.isLoading = false
+ if (context.value?.scope === scope) this.isLoading = false
}
},
},
diff --git a/packages/platform/README.md b/packages/platform/README.md
index 9edef725..76e5f655 100644
--- a/packages/platform/README.md
+++ b/packages/platform/README.md
@@ -54,3 +54,15 @@ POSTs require the configured portal Origin.
These account APIs do not provision a default Workspace/Site, publish tenants,
or enable the photo-management backend. Those remain later integration work.
+
+P3 request integration exposes a membership-filtered Site catalog and short-lived
+context subscriptions. Every reconnect rechecks the session and Membership.
+Host-resolved public contexts contain no platform identity or Workspace details.
+All context responses and SSR pages are private and are not shared-cache entries.
+
+`0002_visitor_access.sql` stores Site/album password policies and attempt counters.
+The gallery access adapter issues signed, host-only Secure/HttpOnly visitor cookies
+only after password verification. Grants are scoped to Host, Site, album, password
+revision and expiry. Configure an independent `NUXT_PLATFORM_SECRET` on the Site
+Worker and its Preview. Policy provisioning and photo repositories remain P4 work;
+these endpoints never infer a default album or reuse a platform session.
diff --git a/packages/platform/migrations/0002_visitor_access.sql b/packages/platform/migrations/0002_visitor_access.sql
new file mode 100644
index 00000000..79f8752d
--- /dev/null
+++ b/packages/platform/migrations/0002_visitor_access.sql
@@ -0,0 +1,14 @@
+-- Access policy only. Album/media business repositories are introduced separately.
+CREATE TABLE IF NOT EXISTS platform_album_access (
+ site_id INTEGER NOT NULL REFERENCES platform_sites(id),
+ album_id INTEGER NOT NULL CHECK(album_id > 0),
+ revision TEXT NOT NULL,
+ salt TEXT NOT NULL,
+ password_hash TEXT NOT NULL,
+ PRIMARY KEY(site_id, album_id)
+);
+CREATE TABLE IF NOT EXISTS platform_visitor_limits (
+ key TEXT PRIMARY KEY,
+ window_start INTEGER NOT NULL,
+ attempts INTEGER NOT NULL
+);
diff --git a/packages/platform/src/index.ts b/packages/platform/src/index.ts
index f2108016..e7d0194f 100644
--- a/packages/platform/src/index.ts
+++ b/packages/platform/src/index.ts
@@ -139,3 +139,41 @@ export function createD1Sessions(db: PlatformD1) {
},
}
}
+
+export interface PlatformSiteSummary {
+ siteId: number
+ workspaceId: number
+ name: string
+ published: boolean
+ role: 'admin' | 'member'
+}
+export function createD1SiteCatalog(db: PlatformD1) {
+ return {
+ async list(userId: number): Promise<PlatformSiteSummary[]> {
+ // JSON aggregation avoids exposing driver-specific `all()` result types.
+ const row = await db
+ .prepare(`SELECT json_group_array(json_object(
+ 'siteId', id, 'workspaceId', workspace_id, 'name', name,
+ 'published', published, 'role', role)) AS items FROM (
+ SELECT s.id, s.workspace_id, s.name, s.published, m.role
+ FROM platform_sites s JOIN platform_memberships m ON m.workspace_id = s.workspace_id
+ WHERE m.user_id = ? AND m.role IN ('admin', 'member') ORDER BY s.id
+ )`)
+ .bind(userId)
+ .first<{ items: string }>()
+ return (
+ JSON.parse(row?.items ?? '[]') as (Omit<
+ PlatformSiteSummary,
+ 'published'
+ > & { published: number })[]
+ ).map((site) => ({ ...site, published: site.published === 1 }))
+ },
+ async name(siteId: number): Promise<string> {
+ const row = await db
+ .prepare('SELECT name FROM platform_sites WHERE id = ?')
+ .bind(siteId)
+ .first<{ name: string }>()
+ return row?.name ?? 'ChronoFrame'
+ },
+ }
+}
diff --git a/scripts/check-entry-boundaries.mjs b/scripts/check-entry-boundaries.mjs
index ee6d5f98..53c2534f 100644
--- a/scripts/check-entry-boundaries.mjs
+++ b/scripts/check-entry-boundaries.mjs
@@ -28,6 +28,8 @@ for (const entry of ['cloud', 'site']) {
'apps/platform.runtime.ts',
'apps/platform-crypto.ts',
'apps/platform-email.ts',
+ 'apps/platform-context.ts',
+ 'apps/platform-visitor.ts',
]) {
const code = await readFile(file, 'utf8')
for (const match of code.matchAll(
diff --git a/scripts/smoke-edge-entry.mjs b/scripts/smoke-edge-entry.mjs
index 0f28b2a7..3252b28a 100644
--- a/scripts/smoke-edge-entry.mjs
+++ b/scripts/smoke-edge-entry.mjs
@@ -93,15 +93,22 @@ try {
redirect: 'manual',
})
assert.equal(dashboard.status, 302)
- assert.ok(dashboard.headers.get('location').endsWith('/signin'))
+ assert.ok(
+ new URL(dashboard.headers.get('location'), base).pathname === '/sites',
+ )
assert.equal(
(await fetch(base + '/DASHBOARD', { redirect: 'manual' })).status,
302,
)
- assert.equal((await fetch(base + '/sites')).status, 503)
+ assert.equal(
+ (await fetch(base + '/sites', { redirect: 'manual' })).status,
+ 302,
+ )
assert.equal((await fetch(base + '/albums')).status, 404)
if (portalOrigin) {
- assert.ok(home.headers.get('location').endsWith('/signin'))
+ assert.ok(
+ new URL(home.headers.get('location'), base).pathname === '/sites',
+ )
}
if (originHost === 'chronoframe.art') {
const links = [...html.matchAll(/\bhref="([^"]*)"/g)]
diff --git a/tests/entry-context.test.ts b/tests/entry-context.test.ts
new file mode 100644
index 00000000..f49f8407
--- /dev/null
+++ b/tests/entry-context.test.ts
@@ -0,0 +1,107 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import {
+ SELF_HOSTED_CAPABILITIES,
+ CLOUD_CAPABILITIES,
+ SITE_CAPABILITIES,
+ entryRequestPath,
+} from '../packages/contracts/src/entry.ts'
+import {
+ encodeVisitorGrants,
+ decodeVisitorGrants,
+ visitorPasswordHash,
+} from '../apps/platform-visitor.ts'
+import { hasSiteVisitorGrant } from '../packages/core/src/platform.ts'
+
+const secret = 'independent-site-test-secret-at-least-32-bytes'
+test('entry capabilities keep Self-hosted providers/unlimited quota and disable unavailable SaaS media', () => {
+ assert.deepEqual(SELF_HOSTED_CAPABILITIES.storageProviders, [
+ 'local',
+ 's3',
+ 'openlist',
+ ])
+ assert.equal(SELF_HOSTED_CAPABILITIES.quota, 'unlimited')
+ assert.equal(SELF_HOSTED_CAPABILITIES.mediaManagement, true)
+ assert.equal(CLOUD_CAPABILITIES.database, 'd1')
+ assert.equal(CLOUD_CAPABILITIES.customScripts, false)
+ assert.equal(SITE_CAPABILITIES.identity, 'visitor')
+ assert.equal(SITE_CAPABILITIES.mediaManagement, false)
+})
+test('shared transport scopes API routes and rejects path traversal or foreign origins', () => {
+ const context = {
+ siteId: 7,
+ scope: 'site:7',
+ name: 'seven',
+ published: true,
+ audience: 'portal' as const,
+ capabilities: CLOUD_CAPABILITIES,
+ }
+ assert.equal(
+ entryRequestPath('/api/photos?offset=2', context),
+ '/api/sites/7/photos?offset=2',
+ )
+ assert.equal(
+ entryRequestPath('/api/albums/8/unlock', {
+ ...context,
+ audience: 'public',
+ }),
+ '/api/public/albums/8/unlock',
+ )
+ assert.equal(entryRequestPath('/api/photos', null), '/api/photos')
+ for (const path of [
+ 'https://evil.example/api/photos',
+ '//evil.example/api/photos',
+ '/api/../auth',
+ '/api/%2e%2e/auth',
+ '/api/\\evil',
+ ])
+ assert.throws(() => entryRequestPath(path, context))
+})
+test('signed visitor grants reject another Host, Site, album, revision, expiry and tampering', async () => {
+ const grants = [
+ {
+ siteId: 1,
+ albumId: 3,
+ revision: 'version-one',
+ expiresAt: Date.now() + 60_000,
+ },
+ ]
+ const token = await encodeVisitorGrants(secret, 'one.example.com', grants)
+ const verified = await decodeVisitorGrants(secret, 'one.example.com', token)
+ const context = {
+ kind: 'public' as const,
+ site: { id: 1, workspaceId: 1, published: true },
+ host: 'one.example.com',
+ }
+ assert.equal(hasSiteVisitorGrant(context, verified, 3, 'version-one'), true)
+ assert.equal(
+ hasSiteVisitorGrant(
+ { ...context, site: { ...context.site, id: 2 } },
+ verified,
+ 3,
+ 'version-one',
+ ),
+ false,
+ )
+ assert.equal(hasSiteVisitorGrant(context, verified, 4, 'version-one'), false)
+ assert.equal(hasSiteVisitorGrant(context, verified, 3, 'rotated'), false)
+ assert.deepEqual(
+ await decodeVisitorGrants(secret, 'two.example.com', token),
+ [],
+ )
+ assert.deepEqual(
+ await decodeVisitorGrants(secret, 'one.example.com', token + 'changed'),
+ [],
+ )
+ const expired = await encodeVisitorGrants(secret, 'one.example.com', [
+ { ...grants[0]!, expiresAt: Date.now() - 1 },
+ ])
+ assert.deepEqual(
+ await decodeVisitorGrants(secret, 'one.example.com', expired),
+ [],
+ )
+ assert.notEqual(
+ await visitorPasswordHash('password', 'salt-one'),
+ await visitorPasswordHash('password', 'salt-two'),
+ )
+})
diff --git a/tests/gallery-image-cache.test.ts b/tests/gallery-image-cache.test.ts
new file mode 100644
index 00000000..27362d89
--- /dev/null
+++ b/tests/gallery-image-cache.test.ts
@@ -0,0 +1,47 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import vm from 'node:vm'
+import ts from 'typescript'
+
+test('image Blob cache does not reuse another Site/principal URL and clears on scope changes', async () => {
+ const load = (path: string, imports: Record<string, unknown>) => {
+ const exports: Record<string, any> = {}
+ const code = ts.transpileModule(readFileSync(path, 'utf8'), {
+ compilerOptions: {
+ module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2022,
+ },
+ }).outputText
+ vm.runInNewContext(code, {
+ exports,
+ URL,
+ console,
+ require: (name: string) => {
+ assert.ok(name in imports, name)
+ return imports[name]
+ },
+ })
+ return exports
+ }
+ const lru = load('packages/gallery/app/libs/lru.ts', {})
+ const module = load('packages/gallery/app/libs/image-loader-manager.ts', {
+ './lru': lru,
+ 'file-type': {},
+ })
+ const first = new module.ImageLoaderManager('site1:user1')
+ const second = new module.ImageLoaderManager('site2:user1')
+ const third = new module.ImageLoaderManager('site1:user2')
+ const image = new Blob(['test-image'], { type: 'image/jpeg' })
+ const src = '/private/image.jpg'
+ assert.equal((await first.processNormalImage(image, src, {})).blobSrc, src)
+ assert.match(
+ (await first.processNormalImage(image, src, {})).blobSrc,
+ /^blob:/,
+ )
+ assert.equal((await second.processNormalImage(image, src, {})).blobSrc, src)
+ assert.equal((await third.processNormalImage(image, src, {})).blobSrc, src)
+ module.clearImageLoaderCache()
+ assert.equal((await first.processNormalImage(image, src, {})).blobSrc, src)
+ module.clearImageLoaderCache()
+})
diff --git a/tests/platform-email-d1.test.ts b/tests/platform-email-d1.test.ts
index 6ebc6e6a..5e0a01d9 100644
--- a/tests/platform-email-d1.test.ts
+++ b/tests/platform-email-d1.test.ts
@@ -352,3 +352,27 @@ test('email and client hourly limits are enforced across distinct challenges', a
sqlite.close()
}
})
+
+test('D1 Site catalog lists only current memberships, including unpublished owned sites', async () => {
+ const { createD1SiteCatalog } =
+ await import('../packages/platform/src/index.ts')
+ const { sqlite, db } = await database()
+ try {
+ sqlite.exec(`INSERT INTO platform_users VALUES(1,'[email protected]',1),(2,'[email protected]',1);
+ INSERT INTO platform_workspaces VALUES(1,'one'),(2,'two');
+ INSERT INTO platform_sites VALUES(1,1,'one-public',1),(2,2,'two-private',0),(3,1,'one-draft',0);
+ INSERT INTO platform_memberships VALUES(1,1,'admin'),(2,2,'member');`)
+ assert.deepEqual(
+ (await createD1SiteCatalog(db).list(1)).map((s) => s.siteId),
+ [1, 3],
+ )
+ assert.deepEqual(
+ (await createD1SiteCatalog(db).list(2)).map((s) => s.siteId),
+ [2],
+ )
+ sqlite.exec('DELETE FROM platform_memberships WHERE user_id = 1')
+ assert.deepEqual(await createD1SiteCatalog(db).list(1), [])
+ } finally {
+ sqlite.close()
+ }
+})
diff --git a/tests/ui-api.test.ts b/tests/ui-api.test.ts
index 7731e43c..77eb54cf 100644
--- a/tests/ui-api.test.ts
+++ b/tests/ui-api.test.ts
@@ -3,48 +3,95 @@ import { readFileSync } from 'node:fs'
import test from 'node:test'
import vm from 'node:vm'
import ts from 'typescript'
+import {
+ entryRequestPath,
+ CLOUD_CAPABILITIES,
+} from '../packages/contracts/src/entry.ts'
+import type { EntrySiteContext } from '../packages/contracts/src/entry.ts'
for (const name of ['console', 'gallery'])
- test(`${name} API adapter delegates to request-scoped SSR fetch without requiring a factory`, async () => {
+ test(`${name} transport preserves SSR request fetch and scopes async data across Sites and users`, async () => {
const title = name[0]!.toUpperCase() + name.slice(1)
- const calls: unknown[] = []
- const exports: Record<string, any> = {}
- const scopedFetch = async (request: unknown, options: unknown) => {
- calls.push({ request, options })
+ const calls: { request: string; options: Record<string, unknown> }[] = []
+ const context: { value: EntrySiteContext | null } = { value: null }
+ const value = (input: any): any =>
+ typeof input === 'function'
+ ? input()
+ : input && typeof input === 'object' && 'value' in input
+ ? input.value
+ : input
+ const scopedFetch = async (request: unknown, options: any) => {
+ calls.push({
+ request: value(request),
+ options: {
+ ...options,
+ ...(options.key ? { key: value(options.key) } : {}),
+ },
+ })
return { authenticated: true }
}
- const code = ts.transpileModule(
- readFileSync(
- `packages/${name}/app/composables/use${title}Api.ts`,
- 'utf8',
- ),
- { compilerOptions: { module: ts.ModuleKind.CommonJS } },
- ).outputText
- vm.runInNewContext(code, {
- exports,
- useRuntimeConfig: () => ({
- public: { [name]: { apiBase: 'https://portal.example.com' } },
- }),
+ const globals = {
+ useRuntimeConfig: () => ({ public: { [name]: { apiBase: '' } } }),
useRequestFetch: () => scopedFetch,
useFetch: scopedFetch,
+ computed: (get: () => unknown) => ({
+ get value() {
+ return get()
+ },
+ }),
+ toValue: value,
+ }
+ const load = (path: string, imports: Record<string, unknown>) => {
+ const exports: Record<string, any> = {}
+ const code = ts.transpileModule(readFileSync(path, 'utf8'), {
+ compilerOptions: { module: ts.ModuleKind.CommonJS },
+ }).outputText
+ vm.runInNewContext(code, {
+ ...globals,
+ exports,
+ require: (key: string) => {
+ assert.ok(key in imports, key)
+ return imports[key]
+ },
+ })
+ return exports
+ }
+ const shared = load('packages/gallery/app/composables/useEntryApi.ts', {
+ './useEntryContext': { useEntryContext: () => context, entryRequestPath },
})
+ const api = load(`packages/${name}/app/composables/use${title}Api.ts`, {
+ [name === 'console'
+ ? '#gallery/composables/useEntryApi'
+ : './useEntryApi']: shared,
+ })
+ const fetcher = api[`use${title}Api`]()
assert.equal(
- (await exports[`use${title}Api`]()('/api/photos', { method: 'GET' }))
- .authenticated,
+ (await fetcher('/api/photos', { method: 'GET' })).authenticated,
true,
)
- await exports[`use${title}Fetch`]('/api/albums')
- assert.equal(
- JSON.stringify(calls),
- JSON.stringify([
- {
- request: '/api/photos',
- options: { baseURL: 'https://portal.example.com', method: 'GET' },
- },
- {
- request: '/api/albums',
- options: { baseURL: 'https://portal.example.com' },
- },
- ]),
- )
+ assert.equal(calls.at(-1)!.request, '/api/photos')
+ context.value = {
+ siteId: 1,
+ scope: 'site:1:portal:user1',
+ audience: 'portal',
+ name: 'one',
+ published: true,
+ capabilities: CLOUD_CAPABILITIES,
+ }
+ await api[`use${title}Fetch`]('/api/albums', { key: 'albums' })
+ assert.equal(calls.at(-1)!.request, '/api/sites/1/albums')
+ const firstKey = calls.at(-1)!.options.key
+ context.value = {
+ ...context.value,
+ siteId: 2,
+ scope: 'site:2:portal:user1',
+ }
+ await api[`use${title}Fetch`]('/api/albums', { key: 'albums' })
+ assert.equal(calls.at(-1)!.request, '/api/sites/2/albums')
+ assert.notEqual(calls.at(-1)!.options.key, firstKey)
+ context.value = { ...context.value, scope: 'site:2:portal:user2' }
+ await api[`use${title}Fetch`]('/api/albums', { key: 'albums' })
+ assert.ok(String(calls.at(-1)!.options.key).includes('user2'))
+ await fetcher('/api/photos', { baseURL: 'https://untrusted.example' })
+ assert.equal(calls.at(-1)!.options.baseURL, '')
})