import type { TemplateSelection } from './template-browser'; import { createSecureUuid } from '../identity/secure-uuid'; import { catalogOwnerKey } from './catalog-cache'; import { parseTemplateOutput, templateIdentity } from './template-policy'; const prefix = 'fotogenic-template-v3:'; interface Handoff { selection: TemplateSelection; ownerKey: string; expires: number; destination: string } const destinationKey = (url: URL): string => `${url.pathname}?page=${url.searchParams.get('page') || ''}`; // One tab, one navigation, ten minutes. Generation authority is checked server-side. export const saveTemplateHandoff = (selection: TemplateSelection, destination: string): string | null => { const url = new URL(destination, location.href); const ownerKey = catalogOwnerKey(); if (url.origin !== location.origin || !ownerKey || !templateIdentity(selection.creationPresetId) || !parseTemplateOutput(selection.output)) return null; const token = createSecureUuid(); if (!token) return null; try { const value: Handoff = { selection, ownerKey, expires: Date.now() + 600000, destination: destinationKey(url) }; sessionStorage.setItem(prefix + token, JSON.stringify(value)); url.searchParams.delete('style'); url.searchParams.set('templateIntent', token); return url.href; } catch { return null; } }; const readTemplateHandoff = (consume: boolean): TemplateSelection | null => { const url = new URL(location.href); const token = url.searchParams.get('templateIntent'); if (!token || !/^[a-f0-9-]{36}$/.test(token)) return null; const clear = (): void => { sessionStorage.removeItem(prefix + token); sessionStorage.removeItem('fotogenic-template-v2:' + token); sessionStorage.removeItem('fotogenic-template:' + token); url.searchParams.delete('templateIntent'); history.replaceState(history.state, '', url.href); }; try { const raw = sessionStorage.getItem(prefix + token); if (!raw) { clear(); return null; } const value = JSON.parse(raw) as Handoff; if (!catalogOwnerKey() || value.ownerKey !== catalogOwnerKey() || value.destination !== destinationKey(url) || !Number.isFinite(value.expires) || value.expires < Date.now() || value.expires > Date.now() + 600000) { clear(); return null; } const selection = value.selection; if (!selection || !templateIdentity(selection.creationPresetId) || !parseTemplateOutput(selection.output) || Object.keys(selection).some(key => !['creationPresetId', 'output', 'modelSelection', 'environmentSelection', 'customInstructions'].includes(key)) || (selection.customInstructions !== undefined && (typeof selection.customInstructions !== 'string' || selection.customInstructions.length > 5000))) { clear(); return null; } if (consume) clear(); return selection; } catch { return null; } }; export const takeTemplateHandoff = (): TemplateSelection | null => readTemplateHandoff(true); export const peekTemplateHandoff = (): TemplateSelection | null => readTemplateHandoff(false); let handoffOwner = catalogOwnerKey(); let handoffConnected = Boolean(handoffOwner); window.addEventListener('fotogenic-ai:auth-changed', (event) => { const detail = (event as CustomEvent<{ auth?: { cacheOwner?: unknown; connected?: unknown }; cacheOwner?: unknown; connected?: unknown }>).detail; const auth = detail?.auth || detail; const owner = typeof auth?.cacheOwner === 'string' ? auth.cacheOwner : ''; const connected = typeof auth?.connected === 'boolean' ? auth.connected : Boolean(owner); if (owner === handoffOwner && connected === handoffConnected) return; handoffOwner = owner; handoffConnected = connected; try { for (let index = sessionStorage.length - 1; index >= 0; index--) { const key = sessionStorage.key(index); if (key?.startsWith(prefix) || key?.startsWith('fotogenic-template-v2:') || key?.startsWith('fotogenic-template:')) sessionStorage.removeItem(key); } } catch (error) { console.warn('Fotogenic AI: template navigation could not be cleared.', error instanceof Error ? error.name : 'Invalid storage'); } }); interface HandoffWindow extends Window { FotogenicAI?: { Shared?: { ui?: { templateHandoff?: { take: typeof takeTemplateHandoff; peek: typeof peekTemplateHandoff } } } } } const runtime = window as HandoffWindow; runtime.FotogenicAI ??= {}; runtime.FotogenicAI.Shared ??= {}; runtime.FotogenicAI.Shared.ui ??= {}; runtime.FotogenicAI.Shared.ui.templateHandoff = { take: takeTemplateHandoff, peek: peekTemplateHandoff };