auth

Main authentication module for my projects
git clone git://git.finwo.net/app/auth
Log | Files | Refs

main.ts (11557B)


      1 import morphdom from 'morphdom';
      2 import { TemplateAssets } from './runtime/assets';
      3 import { TemplateCache, withLock } from './runtime/cache';
      4 import { loadTemplateSet } from './runtime/layers';
      5 import { TemplateRenderer } from './runtime/render';
      6 import { bindActions } from './runtime/actions';
      7 import { createRouter, currentRoute, navigate } from './runtime/router';
      8 import type { LayerSource, LogFn, LogKind, TemplateManifest, TemplateSet } from './runtime/types';
      9 import './debug.css';
     10 
     11 type Theme = 'auto' | 'light' | 'dark';
     12 
     13 const cache = new TemplateCache();
     14 const app = document.querySelector<HTMLElement>('#app');
     15 const layersElement = document.querySelector<HTMLElement>('#poc-layers');
     16 const logElement = document.querySelector<HTMLElement>('#poc-log');
     17 const statusElement = document.querySelector<HTMLElement>('#poc-status');
     18 const themeKey = 'auth-template-poc:theme';
     19 
     20 let manifest: TemplateManifest | null = null;
     21 let templateSet: TemplateSet | null = null;
     22 let renderer: TemplateRenderer | null = null;
     23 let assets: TemplateAssets | null = null;
     24 let selectedOverlays = new Set<string>();
     25 let logs: string[] = [];
     26 let loading = false;
     27 let loadError: string | null = null;
     28 let renderError: string | null = null;
     29 let formError: string | null = null;
     30 let notice: string | null = null;
     31 let loadId = 0;
     32 let loadTimer: number | null = null;
     33 let revealed = false;
     34 let theme = readTheme();
     35 
     36 function readTheme(): Theme {
     37   const value = localStorage.getItem(themeKey);
     38   return value === 'light' || value === 'dark' ? value : 'auto';
     39 }
     40 
     41 function applyTheme() {
     42   if (theme === 'auto') {
     43     document.documentElement.removeAttribute('data-theme');
     44   } else {
     45     document.documentElement.setAttribute('data-theme', theme);
     46   }
     47   localStorage.setItem(themeKey, theme);
     48 }
     49 
     50 function cycleTheme() {
     51   const values: Theme[] = ['auto', 'light', 'dark'];
     52   theme = values[(values.indexOf(theme) + 1) % values.length];
     53   applyTheme();
     54   render();
     55 }
     56 
     57 function escapeHtml(value: string) {
     58   return value.replace(/[&<>"']/g, (character) => {
     59     const entities: Record<string, string> = {
     60       '&': '&amp;',
     61       '<': '&lt;',
     62       '>': '&gt;',
     63       '"': '&quot;',
     64       "'": '&#39;',
     65     };
     66     return entities[character];
     67   });
     68 }
     69 
     70 function addLog(kind: LogKind, message: string) {
     71   const timestamp = new Date().toLocaleTimeString();
     72   logs.push(`[${timestamp}] ${kind.padEnd(7)} ${message}`);
     73   if (logs.length > 80) logs = logs.slice(-80);
     74 }
     75 
     76 const log: LogFn = (kind, message) => {
     77   addLog(kind, message);
     78   syncDebug();
     79 };
     80 
     81 function layerSources() {
     82   if (!manifest) return [];
     83   const overlays = manifest.overlays.filter((layer) => selectedOverlays.has(layer.id));
     84   return [manifest.base, ...overlays];
     85 }
     86 
     87 function navItems(active: string) {
     88   return [
     89     { label: 'Overview', route: '/account/overview', icon: 'overview', active: active === 'overview' },
     90     { label: 'Security', route: '/account/security', icon: 'security', active: active === 'security' },
     91     { label: 'Apps', route: '/account/apps', icon: 'apps', active: active === 'apps' },
     92   ];
     93 }
     94 
     95 function accountData(page: string) {
     96   return {
     97     appName: 'Auth',
     98     user: {
     99       name: 'Demo User',
    100       username: 'demo',
    101       email: 'demo@example.com',
    102     },
    103     nav: navItems(page),
    104     theme: { value: theme },
    105     notice,
    106     page: {
    107       title: page === 'security' ? 'Security' : page === 'apps' ? 'Apps' : 'Overview',
    108       subtitle:
    109         page === 'security'
    110           ? 'Manage how you sign in and where this account is active.'
    111           : page === 'apps'
    112             ? 'Applications with access to this account.'
    113             : 'Identity and access settings for this account.',
    114     },
    115     identity: {
    116       name: 'Demo User',
    117       username: 'demo',
    118       email: 'demo@example.com',
    119       account: 'Acme',
    120     },
    121     access: {
    122       client: 'account',
    123       realm: 'Acme',
    124       scope: 'openid profile email',
    125       session: 'Active',
    126     },
    127     security: {
    128       source: 'Realm overlay example',
    129     },
    130     apps: {
    131       source: 'Realm overlay example',
    132     },
    133   };
    134 }
    135 
    136 function loginData() {
    137   return {
    138     realm: { name: 'Acme' },
    139     title: 'Sign in',
    140     notice,
    141     error: formError,
    142     login: {
    143       identifier: '',
    144       pending: loading,
    145     },
    146     theme: { value: theme },
    147   };
    148 }
    149 
    150 function pageForRoute(route: string) {
    151   if (route === '/login') return { app: 'login', page: 'identifier', data: loginData() };
    152   if (route === '/account/security') {
    153     return { app: 'account', page: 'security', data: accountData('security') };
    154   }
    155   if (route === '/account/apps') {
    156     return { app: 'account', page: 'apps', data: accountData('apps') };
    157   }
    158   return { app: 'account', page: 'overview', data: accountData('overview') };
    159 }
    160 
    161 function fallbackHtml(message: string) {
    162   return `
    163     <div class="poc-fallback">
    164       <div>
    165         <p class="poc-fallback-kicker">Template runtime</p>
    166         <h1>Template unavailable</h1>
    167         <p>${escapeHtml(message)}</p>
    168         <button class="poc-fallback-button" type="button" data-reload-templates>Try again</button>
    169       </div>
    170     </div>
    171   `;
    172 }
    173 
    174 function render() {
    175   if (!app) return;
    176 
    177   if (!renderer || !templateSet) {
    178     app.innerHTML = fallbackHtml(loadError || renderError || 'Loading template');
    179     syncDebug();
    180     return;
    181   }
    182 
    183   const { app: appName, page, data } = pageForRoute(currentRoute());
    184   const menuOpen = document.querySelector<HTMLDetailsElement>('.user-menu')?.open || false;
    185 
    186   try {
    187     const html = renderer.render(`${appName}/${page}`, data);
    188     const wrapper = document.createElement('div');
    189     wrapper.id = 'app';
    190     wrapper.innerHTML = html;
    191     morphdom(app, wrapper);
    192 
    193     const menu = document.querySelector<HTMLDetailsElement>('.user-menu');
    194     if (menu && menuOpen) menu.open = true;
    195 
    196     renderError = null;
    197   } catch (caught) {
    198     renderError = caught instanceof Error ? caught.message : String(caught);
    199     addLog('error', renderError);
    200     app.innerHTML = fallbackHtml(renderError);
    201   }
    202 
    203   syncDebug();
    204 }
    205 
    206 function setLoading(value: boolean) {
    207   loading = value;
    208   syncDebug();
    209 }
    210 
    211 async function reveal() {
    212   if (revealed) return;
    213   if (assets) await assets.stylesReady();
    214   document.documentElement.dataset.templateReady = '';
    215   revealed = true;
    216 }
    217 
    218 function scheduleLoad() {
    219   if (loadTimer !== null) window.clearTimeout(loadTimer);
    220   loadTimer = window.setTimeout(() => {
    221     loadTimer = null;
    222     loadTemplates();
    223   }, 0);
    224 }
    225 
    226 async function loadTemplates() {
    227   if (!manifest) return;
    228   const requestId = ++loadId;
    229   const sources = layerSources();
    230 
    231   setLoading(true);
    232   loadError = null;
    233   renderError = null;
    234   logs = [];
    235   render();
    236 
    237   try {
    238     const set = await withLock('auth-template-poc-install', () =>
    239       loadTemplateSet(sources, cache, log)
    240     );
    241     if (requestId !== loadId) return;
    242 
    243     const previousAssets = assets;
    244     const nextAssets = new TemplateAssets(set);
    245     const nextRenderer = new TemplateRenderer(set, nextAssets);
    246 
    247     assets = nextAssets;
    248     renderer = nextRenderer;
    249     templateSet = set;
    250     render();
    251     await nextAssets.stylesReady();
    252     previousAssets?.dispose();
    253 
    254     cache.setActive('demo', {
    255       digest: set.compositeDigest,
    256       layers: sources.map((layer) => ({ id: layer.id, digest: layer.digest })),
    257     });
    258     addLog('info', `active composite ${set.compositeDigest.slice(0, 12)}`);
    259     if (cache.storageMode === 'memory') {
    260       addLog('info', 'OPFS unavailable; using the in-memory layer cache');
    261     }
    262   } catch (caught) {
    263     if (requestId !== loadId) return;
    264     loadError = caught instanceof Error ? caught.message : String(caught);
    265     addLog('error', loadError);
    266   } finally {
    267     if (requestId === loadId) {
    268       setLoading(false);
    269       render();
    270       await reveal();
    271     }
    272   }
    273 }
    274 
    275 function sourceMarkup(layer: LayerSource, selected: boolean, selectable: boolean) {
    276   const checkbox = selectable
    277     ? `<input type="checkbox" data-overlay="${escapeHtml(layer.id)}" ${
    278         selected ? 'checked' : ''
    279       }>`
    280     : '<span class="poc-chip">base</span>';
    281 
    282   return `
    283     <div class="poc-layer">
    284       ${checkbox}
    285       <div class="poc-layer-body">
    286         <strong>${escapeHtml(layer.label)}</strong>
    287         <span>${escapeHtml(layer.id)} - ${escapeHtml(layer.digest.slice(0, 12))}</span>
    288       </div>
    289     </div>
    290   `;
    291 }
    292 
    293 function syncDebug() {
    294   if (statusElement) {
    295     statusElement.textContent = loading
    296       ? 'Installing template...'
    297       : loadError || renderError
    298         ? 'Template error'
    299         : templateSet
    300           ? `Active - ${templateSet.compositeDigest.slice(0, 12)}`
    301           : 'Idle';
    302     statusElement.dataset.state =
    303       loading ? 'loading' : loadError || renderError ? 'error' : 'ready';
    304   }
    305 
    306   if (layersElement && manifest) {
    307     layersElement.innerHTML = [
    308       sourceMarkup(manifest.base, true, false),
    309       ...manifest.overlays.map((layer) =>
    310         sourceMarkup(layer, selectedOverlays.has(layer.id), true)
    311       ),
    312     ].join('');
    313   }
    314 
    315   if (logElement) {
    316     logElement.textContent = logs.join('\n') || 'No runtime events yet.';
    317     logElement.scrollTop = logElement.scrollHeight;
    318   }
    319 }
    320 
    321 async function initialize() {
    322   applyTheme();
    323   bindActions(
    324     document.body,
    325     {
    326       'cycle-theme': () => cycleTheme(),
    327       'sign-out': () => {
    328         notice = 'Signed out (demo).';
    329         navigate('/login');
    330       },
    331     },
    332     {
    333       identifier: (_form, data) => {
    334         const identifier = String(data.get('identifier') || '').trim();
    335         if (!identifier) {
    336           formError = 'Enter an email address or username.';
    337           render();
    338           return;
    339         }
    340         notice = `Continuing as ${identifier} (demo).`;
    341         formError = null;
    342         navigate('/account/overview');
    343       },
    344     },
    345     navigate
    346   );
    347 
    348   document.addEventListener('click', (event) => {
    349     const menu = document.querySelector<HTMLDetailsElement>('.user-menu');
    350     if (menu?.open && !menu.contains(event.target as Node)) menu.open = false;
    351   });
    352 
    353   document.addEventListener('click', async (event) => {
    354     const target = event.target as Element | null;
    355     const page = target?.closest<HTMLElement>('[data-demo-page]');
    356     if (page) navigate(page.dataset.demoPage || '');
    357 
    358     if (target?.closest('[data-reload-templates]')) loadTemplates();
    359 
    360     if (target?.closest('[data-clear-opfs]')) {
    361       await cache.clearAll();
    362       logs = [];
    363       addLog('info', 'OPFS cache cleared');
    364       await loadTemplates();
    365     }
    366 
    367     if (target?.closest('[data-clear-meta]')) {
    368       cache.clearActive('demo');
    369       localStorage.removeItem(themeKey);
    370       theme = 'auto';
    371       applyTheme();
    372       addLog('info', 'localStorage metadata cleared');
    373       syncDebug();
    374     }
    375   });
    376 
    377   document.addEventListener('change', (event) => {
    378     const input = event.target as HTMLInputElement | null;
    379     if (!input?.matches('[data-overlay]')) return;
    380     const id = input.dataset.overlay || '';
    381     if (input.checked) selectedOverlays.add(id);
    382     else selectedOverlays.delete(id);
    383     scheduleLoad();
    384   });
    385 
    386   createRouter(() => {
    387     render();
    388   });
    389 
    390   try {
    391     const response = await fetch('./manifest.json', { cache: 'no-cache' });
    392     if (!response.ok) throw new Error(`Manifest request failed with ${response.status}`);
    393     manifest = (await response.json()) as TemplateManifest;
    394     addLog('info', `manifest api ${manifest.api}`);
    395     syncDebug();
    396     await loadTemplates();
    397   } catch (caught) {
    398     loadError = caught instanceof Error ? caught.message : String(caught);
    399     addLog('error', loadError);
    400     setLoading(false);
    401     render();
    402     await reveal();
    403   }
    404 }
    405 
    406 initialize();