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: establish platform authorization and request isolation boundaries

HoshinoSuzumiBotbd87ce5c513d
diff --git a/.github/workflows/workspace-checks.yml b/.github/workflows/workspace-checks.yml
index c7495003..1c52fa11 100644
--- a/.github/workflows/workspace-checks.yml
+++ b/.github/workflows/workspace-checks.yml
@@ -59,3 +59,8 @@ jobs:
- run: node scripts/check-entry-boundaries.mjs --built ${{ matrix.entry }}
- run: pnpm exec wrangler deploy --dry-run --config apps/${{ matrix.entry }}/.output/server/wrangler.json --outdir /tmp/chronoframe-${{ matrix.entry }}-worker
- run: pnpm smoke:${{ matrix.entry }}
+ - name: Check marketing and portal Host routing
+ if: matrix.entry == 'cloud'
+ run: |
+ CHRONOFRAME_SMOKE_HOST=chronoframe.art pnpm smoke:cloud
+ CHRONOFRAME_SMOKE_HOST=app.chronoframe.art pnpm smoke:cloud
diff --git a/apps/cloud/app/middleware/platform.global.ts b/apps/cloud/app/middleware/platform.global.ts
index ac03dab3..d5826fe6 100644
--- a/apps/cloud/app/middleware/platform.global.ts
+++ b/apps/cloud/app/middleware/platform.global.ts
@@ -1,5 +1,10 @@
export default defineNuxtRouteMiddleware((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 })
+ }
if (path === '/dashboard' || path.startsWith('/dashboard/'))
return navigateTo('/signin', { redirectCode: 302 })
if (path === '/sites' || path.startsWith('/sites/')) {
diff --git a/apps/cloud/app/pages/index.vue b/apps/cloud/app/pages/index.vue
index e5063e51..1ea4a457 100644
--- a/apps/cloud/app/pages/index.vue
+++ b/apps/cloud/app/pages/index.vue
@@ -1,4 +1,9 @@
<script setup lang="ts">
+const signInUrl =
+ useRequestURL().hostname === 'chronoframe.art'
+ ? 'https://app.chronoframe.art/signin'
+ : '/signin'
+
useSeoMeta({
title: 'ChronoFrame — A home for your photography',
description:
@@ -15,7 +20,7 @@ useSeoMeta({
>
<nav aria-label="Main navigation">
<a href="https://chronoframe.bh8.ga/">Documentation</a
- ><NuxtLink to="/signin">Cloud access</NuxtLink>
+ ><NuxtLink :to="signInUrl">Cloud access</NuxtLink>
</nav>
</header>
<main>
@@ -32,7 +37,7 @@ useSeoMeta({
size="xl"
>Explore Self-hosted</UButton
><UButton
- to="/signin"
+ :to="signInUrl"
variant="outline"
size="xl"
>Cloud availability</UButton
diff --git a/packages/core/README.md b/packages/core/README.md
index 4c299030..07cd6411 100644
--- a/packages/core/README.md
+++ b/packages/core/README.md
@@ -30,3 +30,24 @@ checks the captured source version and atomically updates the photo reference,
resource generation, and any follow-up task. Failed or stale publications discard
only their own staged object; they never restore bytes over a newer edit. Prior
source objects remain available rather than being deleted during publication.
+
+## Platform request boundaries
+
+`createPlatformAccess` accepts an asynchronous `PlatformDirectory`; it does not
+open SQLite, infer `DEFAULT_SITE`, or accept client headers as identity. A session
+adapter must verify the platform cookie and expiry before passing its internal
+user ID. Membership is loaded for every authorization decision. Existing `admin`
+roles can mutate/manage a Site; `member` is read-only in this platform policy.
+Self-hosted authorization is unchanged.
+
+Public resolution accepts only a canonical DNS hostname from the direct request
+URL. The directory must return ownership-verified, active domain mappings and
+published Sites; forwarded host and caller-supplied Site IDs are not trusted.
+`platformCacheKey`/`platformStateKey` separate Site, audience, user/role, and Host.
+Only anonymous unprotected data may enter a public cache. Visitor-protected
+responses remain private/no-store, and verified grants must match Site, album,
+password revision, and expiry through `hasSiteVisitorGrant`.
+
+These interfaces establish the application boundary. They do not implement a
+persistent platform identity directory, email delivery, or signed session/grant
+cookies. Until adapters are connected, the cloud/site data routes stay unavailable.
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 1e7dbbe7..58e39d61 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -147,3 +147,4 @@ export * from './upload-preparation.ts'
export * from './site.ts'
export * from './publication.ts'
+export * from './platform.ts'
diff --git a/packages/core/src/platform.ts b/packages/core/src/platform.ts
new file mode 100644
index 00000000..0ede9252
--- /dev/null
+++ b/packages/core/src/platform.ts
@@ -0,0 +1,186 @@
+import { CoreError } from './errors.ts'
+import { assertSiteContext, siteCacheKey } from './site.ts'
+import type { SiteContext } from './site.ts'
+
+export type MembershipRole = 'admin' | 'member'
+export type SitePermission = 'read' | 'write' | 'manage'
+export interface PlatformSession {
+ /** Platform-local identity, resolved by a trusted session adapter. */
+ userId: number
+ expiresAt: number
+}
+export interface PlatformSite extends SiteContext {
+ workspaceId: number
+ published: boolean
+}
+export interface PlatformMembership {
+ userId: number
+ workspaceId: number
+ role: MembershipRole
+}
+export interface PlatformDirectory {
+ getSite(id: number): Promise<PlatformSite | null>
+ getMembership(
+ userId: number,
+ workspaceId: number,
+ ): Promise<PlatformMembership | null>
+ /** Return active, ownership-verified Host mappings only. Never infer a default Site. */
+ getPublishedSiteByHost(host: string): Promise<PlatformSite | null>
+}
+export interface PortalContext {
+ readonly kind: 'portal'
+ readonly site: Readonly<PlatformSite>
+ readonly userId: number
+ readonly role: MembershipRole
+}
+export interface PublicSiteContext {
+ readonly kind: 'public'
+ readonly site: Readonly<PlatformSite>
+ readonly host: string
+}
+function validId(id: number): boolean {
+ return Number.isSafeInteger(id) && id > 0
+}
+function validateSite(site: PlatformSite): void {
+ assertSiteContext(site)
+ if (!validId(site.workspaceId))
+ throw new CoreError(503, 'Invalid platform directory result')
+}
+
+/** DNS hostname only: callers supply the direct URL hostname, never forwarded headers. */
+export function normalizeSiteHost(input: string): string {
+ if (typeof input !== 'string' || input.length > 254)
+ throw new CoreError(400, 'Invalid Host')
+ const host = input.toLowerCase().replace(/\.$/, '')
+ if (
+ !host ||
+ host.length > 253 ||
+ !host.includes('.') ||
+ !host
+ .split('.')
+ .every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)) ||
+ /^[0-9.]+$/.test(host)
+ )
+ throw new CoreError(400, 'Invalid Host')
+ return host
+}
+
+/** No session user, admin flag or selected Site from the client grants membership. */
+export function createPlatformAccess(
+ directory: PlatformDirectory,
+ now = Date.now,
+) {
+ return {
+ async authorizeSite(
+ session: PlatformSession | null,
+ siteId: number,
+ permission: SitePermission,
+ ): Promise<PortalContext> {
+ if (
+ !session ||
+ !validId(session.userId) ||
+ !Number.isFinite(session.expiresAt) ||
+ session.expiresAt <= now()
+ ) {
+ throw new CoreError(401, 'Platform session required')
+ }
+ if (!validId(siteId)) throw new CoreError(404, 'Site not found')
+ if (!['read', 'write', 'manage'].includes(permission))
+ throw new CoreError(403, 'Permission denied')
+ const site = await directory.getSite(siteId)
+ if (!site || site.id !== siteId)
+ throw new CoreError(404, 'Site not found')
+ validateSite(site)
+ const membership = await directory.getMembership(
+ session.userId,
+ site.workspaceId,
+ )
+ // Treat missing membership as not found to avoid disclosing another tenant's Site.
+ if (
+ !membership ||
+ membership.userId !== session.userId ||
+ membership.workspaceId !== site.workspaceId
+ ) {
+ throw new CoreError(404, 'Site not found')
+ }
+ if (membership.role !== 'admin' && membership.role !== 'member')
+ throw new CoreError(403, 'Permission denied')
+ // Members can view content; mutation and membership/settings management require admin.
+ if (permission !== 'read' && membership.role !== 'admin')
+ throw new CoreError(403, 'Permission denied')
+ return Object.freeze({
+ kind: 'portal',
+ site: Object.freeze({ ...site }),
+ userId: session.userId,
+ role: membership.role,
+ })
+ },
+ async resolvePublicSite(
+ requestHostname: string,
+ ): Promise<PublicSiteContext> {
+ const host = normalizeSiteHost(requestHostname)
+ const site = await directory.getPublishedSiteByHost(host)
+ if (!site || !site.published) throw new CoreError(404, 'Site not found')
+ validateSite(site)
+ return Object.freeze({
+ kind: 'public',
+ site: Object.freeze({ ...site }),
+ host,
+ })
+ },
+ }
+}
+
+/**
+ * Separate audience and principal as well as Site.
+ * Public keys are only for anonymous, unprotected resources. Visitor-protected
+ * responses must be private/no-store and must not enter a shared public cache.
+ */
+export function platformCacheKey(
+ context: PortalContext | PublicSiteContext,
+ key: string,
+): string {
+ const audience =
+ context.kind === 'portal'
+ ? `portal:${context.userId}:${context.role}`
+ : `public:${context.host.length}:${context.host}`
+ return siteCacheKey(context.site, `${audience}:${key}`)
+}
+
+export interface SiteVisitorGrant {
+ siteId: number
+ albumId: number
+ /** Opaque password revision; rotating a password invalidates previous grants. */
+ revision: string
+ expiresAt: number
+}
+/** Grant signatures/cookies are checked by the adapter before this scope check. */
+export function hasSiteVisitorGrant(
+ context: PublicSiteContext,
+ grants: readonly SiteVisitorGrant[],
+ albumId: number,
+ revision: string,
+ now = Date.now(),
+): boolean {
+ return (
+ validId(albumId) &&
+ !!revision &&
+ grants.some(
+ (grant) =>
+ grant.siteId === context.site.id &&
+ grant.albumId === albumId &&
+ grant.revision === revision &&
+ Number.isFinite(grant.expiresAt) &&
+ grant.expiresAt > now,
+ )
+ )
+}
+
+/** A nonempty, framed scope for subscriptions and SSR state; no cross-tenant defaults. */
+export function platformStateKey(
+ context: PortalContext | PublicSiteContext,
+ resource: string,
+): string {
+ if (!resource) throw new CoreError(400, 'A state resource is required')
+ return platformCacheKey(context, resource)
+}
diff --git a/scripts/smoke-edge-entry.mjs b/scripts/smoke-edge-entry.mjs
index 9dca8fab..c15065f8 100644
--- a/scripts/smoke-edge-entry.mjs
+++ b/scripts/smoke-edge-entry.mjs
@@ -8,6 +8,8 @@ const entry = process.argv[2]
if (!['cloud', 'site'].includes(entry))
throw new Error('Expected cloud or site')
const port = entry === 'cloud' ? 8787 : 8788
+const originHost = process.env.CHRONOFRAME_SMOKE_HOST
+const portalOrigin = originHost === 'app.chronoframe.art'
const require = createRequire(import.meta.url)
const cli = resolve(
dirname(require.resolve('wrangler/package.json')),
@@ -19,6 +21,7 @@ const worker = spawn(
cli,
'dev',
'--local',
+ ...(originHost ? ['--local-upstream', originHost] : []),
'--config',
`apps/${entry}/.output/server/wrangler.json`,
'--port',
@@ -72,14 +75,18 @@ try {
assert.equal(response.status, 503, endpoint)
assert.equal(response.headers.get('cache-control'), 'no-store', endpoint)
}
- const home = await fetch(base)
- assert.equal(home.status, entry === 'cloud' ? 200 : 503)
- const html = await home.text()
- assert.ok(
- html.includes(
- entry === 'cloud' ? 'A home for the moments' : 'Service unavailable',
- ),
+ const home = await fetch(base, { redirect: 'manual' })
+ assert.equal(
+ home.status,
+ entry === 'cloud' ? (portalOrigin ? 302 : 200) : 503,
)
+ const html = await home.text()
+ if (!portalOrigin)
+ assert.ok(
+ html.includes(
+ entry === 'cloud' ? 'A home for the moments' : 'Service unavailable',
+ ),
+ )
if (entry === 'cloud') {
assert.equal((await fetch(base + '/signin')).status, 200)
const dashboard = await fetch(base + '/dashboard/photos', {
@@ -93,6 +100,17 @@ try {
)
assert.equal((await fetch(base + '/sites')).status, 503)
assert.equal((await fetch(base + '/albums')).status, 404)
+ if (portalOrigin) {
+ assert.ok(home.headers.get('location').endsWith('/signin'))
+ }
+ if (originHost === 'chronoframe.art') {
+ assert.ok(html.includes('https://app.chronoframe.art/signin'))
+ const forgedPortal = await fetch(base, {
+ headers: { 'x-forwarded-host': 'app.chronoframe.art' },
+ redirect: 'manual',
+ })
+ assert.equal(forgedPortal.status, 200)
+ }
} else {
assert.equal((await fetch(base + '/albums')).status, 503)
assert.equal((await fetch(base + '/dashboard')).status, 404)
diff --git a/tests/platform-boundaries.test.ts b/tests/platform-boundaries.test.ts
new file mode 100644
index 00000000..b24369c8
--- /dev/null
+++ b/tests/platform-boundaries.test.ts
@@ -0,0 +1,153 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import {
+ createPlatformAccess,
+ normalizeSiteHost,
+ platformCacheKey,
+ hasSiteVisitorGrant,
+ platformStateKey,
+} from '../packages/core/src/platform.ts'
+import type { PlatformDirectory } from '../packages/core/src/platform.ts'
+const sites = [
+ { id: 1, workspaceId: 10, published: true },
+ { id: 2, workspaceId: 20, published: true },
+]
+const directory: PlatformDirectory = {
+ async getSite(id) {
+ return sites.find((site) => site.id === id) ?? null
+ },
+ async getMembership(userId, workspaceId) {
+ return userId === 1 && workspaceId === 10
+ ? { userId, workspaceId, role: 'admin' }
+ : null
+ },
+ async getPublishedSiteByHost(host) {
+ return host === 'one.example.com'
+ ? sites[0]!
+ : host === 'two.example.com'
+ ? sites[1]!
+ : null
+ },
+}
+const access = createPlatformAccess(directory, () => 100)
+const session = { userId: 1, expiresAt: 200 }
+const status = (expected: number) => (error: unknown) =>
+ (error as { statusCode?: number }).statusCode === expected
+
+test('portal checks platform session and live Workspace membership for every Site request', async () => {
+ assert.equal((await access.authorizeSite(session, 1, 'write')).site.id, 1)
+ await assert.rejects(access.authorizeSite(session, 2, 'read'), status(404))
+ await assert.rejects(access.authorizeSite(null, 1, 'read'), status(401))
+ await assert.rejects(
+ access.authorizeSite({ ...session, expiresAt: 100 }, 1, 'read'),
+ status(401),
+ )
+ await assert.rejects(access.authorizeSite(session, -1, 'read'), status(404))
+ const member = createPlatformAccess(
+ {
+ ...directory,
+ async getMembership(userId, workspaceId) {
+ return { userId, workspaceId, role: 'member' }
+ },
+ },
+ () => 100,
+ )
+ assert.equal((await member.authorizeSite(session, 1, 'read')).role, 'member')
+ await assert.rejects(member.authorizeSite(session, 1, 'write'), status(403))
+ await assert.rejects(member.authorizeSite(session, 1, 'manage'), status(403))
+})
+
+test('revoked or mismatched membership and directory results cannot authorize a Site', async () => {
+ for (const membership of [
+ null,
+ { userId: 2, workspaceId: 10, role: 'admin' as const },
+ { userId: 1, workspaceId: 20, role: 'admin' as const },
+ ]) {
+ const resolver = createPlatformAccess(
+ {
+ ...directory,
+ async getMembership() {
+ return membership
+ },
+ },
+ () => 100,
+ )
+ await assert.rejects(
+ resolver.authorizeSite(session, 1, 'read'),
+ status(404),
+ )
+ }
+ const wrong = createPlatformAccess(
+ {
+ ...directory,
+ async getSite() {
+ return sites[1]!
+ },
+ },
+ () => 100,
+ )
+ await assert.rejects(wrong.authorizeSite(session, 1, 'read'), status(404))
+})
+
+test('public resolution only accepts canonical DNS hosts with an active published mapping', async () => {
+ assert.equal(normalizeSiteHost('ONE.Example.com.'), 'one.example.com')
+ assert.equal((await access.resolvePublicSite('ONE.Example.com.')).site.id, 1)
+ await assert.rejects(
+ access.resolvePublicSite('unknown.example.com'),
+ status(404),
+ )
+ const unpublished = createPlatformAccess({
+ ...directory,
+ async getPublishedSiteByHost() {
+ return { ...sites[0]!, published: false }
+ },
+ })
+ await assert.rejects(
+ unpublished.resolvePublicSite('one.example.com'),
+ status(404),
+ )
+ for (const host of [
+ 'https://one.example.com',
+ 'one.example.com:443',
+ 'one.example.com/evil',
+ 'one.example.com,evil.com',
+ '*.example.com',
+ '127.0.0.1',
+ 'one..example.com',
+ '-bad.example.com',
+ 'one.example.com\n',
+ ]) {
+ assert.throws(() => normalizeSiteHost(host), status(400), host)
+ }
+})
+
+test('cache, SSR and subscription keys separate Site, public Host, user and audience', async () => {
+ const publicOne = await access.resolvePublicSite('one.example.com')
+ const publicTwo = await access.resolvePublicSite('two.example.com')
+ const portal = await access.authorizeSite(session, 1, 'read')
+ const keys = [
+ publicOne,
+ publicTwo,
+ portal,
+ { ...portal, userId: 2 },
+ { ...publicOne, host: 'alias.example.com' },
+ ].map((context) => platformCacheKey(context, 'photos'))
+ assert.equal(new Set(keys).size, keys.length)
+ assert.equal(platformStateKey(publicOne, 'photos'), keys[0])
+ assert.throws(() => platformStateKey(publicOne, ''), status(400))
+ assert.ok(Object.isFrozen(publicOne.site))
+})
+
+test('visitor grants cannot cross sites, albums, password revisions or expiry', async () => {
+ const one = await access.resolvePublicSite('one.example.com')
+ const two = await access.resolvePublicSite('two.example.com')
+ const grants = [
+ { siteId: 1, albumId: 5, revision: 'current', expiresAt: 200 },
+ ]
+ assert.equal(hasSiteVisitorGrant(one, grants, 5, 'current', 100), true)
+ assert.equal(hasSiteVisitorGrant(two, grants, 5, 'current', 100), false)
+ assert.equal(hasSiteVisitorGrant(one, grants, 6, 'current', 100), false)
+ assert.equal(hasSiteVisitorGrant(one, grants, 5, 'rotated', 100), false)
+ assert.equal(hasSiteVisitorGrant(one, grants, 5, 'current', 200), false)
+})