@tacoshell/shell 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +6 -2
  3. package/package.json +40 -4
  4. package/src/background.ts +41 -0
  5. package/src/core/bus.ts +210 -0
  6. package/src/core/cards.ts +33 -0
  7. package/src/core/contrib.ts +70 -0
  8. package/src/core/cron.ts +63 -0
  9. package/src/core/cronfriendly.ts +70 -0
  10. package/src/core/csv.ts +36 -0
  11. package/src/core/csvfeature.ts +57 -0
  12. package/src/core/datasets.ts +367 -0
  13. package/src/core/domshot.ts +81 -0
  14. package/src/core/guards.ts +36 -0
  15. package/src/core/hosts.ts +15 -0
  16. package/src/core/hotkeys.ts +44 -0
  17. package/src/core/indicators.ts +62 -0
  18. package/src/core/jobs.ts +37 -0
  19. package/src/core/localdata.ts +88 -0
  20. package/src/core/log.ts +91 -0
  21. package/src/core/markdown.ts +57 -0
  22. package/src/core/nav.ts +105 -0
  23. package/src/core/notifyrules.ts +31 -0
  24. package/src/core/page.ts +91 -0
  25. package/src/core/prefs.ts +119 -0
  26. package/src/core/router.ts +78 -0
  27. package/src/core/search.ts +65 -0
  28. package/src/core/services.ts +178 -0
  29. package/src/core/sessions.ts +93 -0
  30. package/src/core/startpage.ts +28 -0
  31. package/src/core/storage.ts +54 -0
  32. package/src/core/systemtools.ts +85 -0
  33. package/src/core/tabfit.ts +30 -0
  34. package/src/core/templates.ts +48 -0
  35. package/src/core/text.ts +6 -0
  36. package/src/core/toasts.ts +13 -0
  37. package/src/core/vault.ts +208 -0
  38. package/src/env.d.ts +2 -0
  39. package/src/index.ts +58 -0
  40. package/src/styles.css +391 -0
  41. package/src/types.ts +133 -0
  42. package/src/ui/ActionModal.tsx +22 -0
  43. package/src/ui/App.tsx +241 -0
  44. package/src/ui/ClearableInput.tsx +23 -0
  45. package/src/ui/CsvFeature.tsx +151 -0
  46. package/src/ui/Icon.tsx +8 -0
  47. package/src/ui/ItemFeature.tsx +39 -0
  48. package/src/ui/Markdown.tsx +24 -0
  49. package/src/ui/Rail.tsx +135 -0
  50. package/src/ui/RelatedMenu.tsx +57 -0
  51. package/src/ui/Search.tsx +111 -0
  52. package/src/ui/Sessions.tsx +76 -0
  53. package/src/ui/SidePanel.tsx +150 -0
  54. package/src/ui/TabBar.tsx +56 -0
  55. package/src/ui/ViewHost.tsx +142 -0
  56. package/src/ui/hooks.ts +28 -0
  57. package/src/ui/settings/Datasets.tsx +172 -0
  58. package/src/ui/settings/ReleaseNotes.tsx +96 -0
  59. package/src/ui/settings/ScheduleEditor.tsx +57 -0
  60. package/src/ui/settings/Settings.tsx +339 -0
  61. package/src/ui/settings/SettingsTabs.tsx +63 -0
  62. package/src/ui/settings/Templates.tsx +52 -0
  63. package/src/ui/useContrib.ts +36 -0
@@ -0,0 +1,119 @@
1
+ // UI preferences (localStorage, page-only, never secrets: ADR-003) and user settings the service worker must read (chrome.storage.local).
2
+
3
+ import * as store from './storage.ts';
4
+
5
+ /** A tiny observable value for React's useSyncExternalStore. */
6
+ export function createStore<T>(initial: T) {
7
+ let value = initial;
8
+ const listeners = new Set<() => void>();
9
+ return {
10
+ get: () => value,
11
+ set(next: T) { value = next; for (const fn of listeners) fn(); },
12
+ subscribe(fn: () => void) { listeners.add(fn); return () => { listeners.delete(fn); }; },
13
+ };
14
+ }
15
+
16
+ const ls = () => (typeof localStorage !== 'undefined' ? localStorage : undefined);
17
+ export function pref<T>(key: string, fallback: T): T {
18
+ try { const raw = ls()?.getItem(`taco.${key}`); return raw == null ? fallback : (JSON.parse(raw) as T); } catch { return fallback; }
19
+ }
20
+ /** A preference that must be a list of strings: anything else a browser still has stored under that name (an older version saved a boolean) reads as empty. */
21
+ export function prefList(key: string): string[] {
22
+ const v = pref<unknown>(key, []);
23
+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
24
+ }
25
+ export function setPref(key: string, value: unknown) {
26
+ try { ls()?.setItem(`taco.${key}`, JSON.stringify(value)); } catch { /* private window or storage blocked: the pref just isn't remembered */ }
27
+ }
28
+
29
+ // ── Favorites: view keys, in the user's order (FR-FAV-1..3) ─────────────────────────────────────────────────────────
30
+ export const favorites = createStore<string[]>(pref('favorites', []));
31
+ export function toggleFavorite(key: string) {
32
+ const list = favorites.get();
33
+ const next = list.includes(key) ? list.filter((k) => k !== key) : [...list, key];
34
+ favorites.set(next);
35
+ setPref('favorites', next);
36
+ }
37
+ export function moveFavorite(key: string, delta: -1 | 1) {
38
+ const list = [...favorites.get()];
39
+ const i = list.indexOf(key), j = i + delta;
40
+ if (i < 0 || j < 0 || j >= list.length) return;
41
+ [list[i], list[j]] = [list[j], list[i]];
42
+ favorites.set(list);
43
+ setPref('favorites', list);
44
+ }
45
+
46
+ // ── Side panel: Log or Help share one slot (ADR-039) ─────────────────────────────────────────────────────────────────
47
+ export type Panel = 'log' | 'help' | null;
48
+ export const sidePanel = createStore<Panel>(pref<Panel>('side.panel', null));
49
+ export function togglePanel(p: Exclude<Panel, null>) {
50
+ const next = sidePanel.get() === p ? null : p;
51
+ sidePanel.set(next);
52
+ setPref('side.panel', next);
53
+ }
54
+
55
+ // ── User settings (chrome.storage.local, so the service worker can read the idle lock) ──────────────────────────────
56
+ export type ThemeMode = 'dark' | 'light' | 'system';
57
+ /** Notification preferences (ADR-041, v2 config/notifications.js). The service worker reads them, so they live in chrome.storage.local. */
58
+ export interface NotifySettings {
59
+ enabled: boolean;
60
+ items: Record<string, boolean>;
61
+ /** Chrome notifications only while the app isn't the focused window (the in-app toast always shows). */
62
+ onlyWhenAway: boolean;
63
+ /** "HH:MM"–"HH:MM", local time; empty = none. Nothing pops up during quiet hours (it's still in the Activity Log). */
64
+ quietFrom: string;
65
+ quietTo: string;
66
+ /** Keep Chrome notifications on screen until dismissed. */
67
+ sticky: boolean;
68
+ /** Count unseen notifications on the toolbar icon. */
69
+ badge: boolean;
70
+ }
71
+ export interface UserSettings {
72
+ theme: ThemeMode;
73
+ idleLockMinutes: number;
74
+ visibleLevels: string[];
75
+ notifications: NotifySettings;
76
+ /** The user's start page, overriding the app's default (null = use the app's default). "auto" | "home" | "reports" | "<module>/<view>". */
77
+ startPage: string | null;
78
+ /** Ask "Lock the vault?" before the header's Vault button locks it. Default on. */
79
+ confirmLock: boolean;
80
+ /** HotKeys (ADR-046): `map` = the user's combos by hotkey id; unset = the default. */
81
+ hotkeys: { enabled: boolean; map: Record<string, string> };
82
+ }
83
+ export const SETTINGS_KEY = 'taco.settings';
84
+ export const DEFAULT_NOTIFY: NotifySettings = { enabled: true, items: {}, onlyWhenAway: true, quietFrom: '', quietTo: '', sticky: false, badge: true };
85
+ export const settings = createStore<UserSettings>({ theme: 'dark', idleLockMinutes: 15, visibleLevels: ['info', 'warn', 'error', 'fatal'], notifications: { ...DEFAULT_NOTIFY }, confirmLock: true, startPage: null, hotkeys: { enabled: true, map: {} } });
86
+
87
+ // ── Theme: dark (default), light, or follow the system (v2 had dark / light) ─────────────────────────────────────────
88
+ let systemQuery: MediaQueryList | undefined;
89
+ export function applyTheme(mode: ThemeMode) {
90
+ if (typeof document === 'undefined') return;
91
+ const dark = mode === 'system' ? !!globalThis.matchMedia?.('(prefers-color-scheme: dark)').matches : mode === 'dark';
92
+ document.documentElement.dataset.theme = dark ? 'dark' : 'light';
93
+ if (mode === 'system' && !systemQuery && typeof matchMedia === 'function') {
94
+ systemQuery = matchMedia('(prefers-color-scheme: dark)');
95
+ systemQuery.addEventListener('change', () => { if (settings.get().theme === 'system') applyTheme('system'); });
96
+ }
97
+ }
98
+
99
+ export async function initSettings(defaults: { idleLockMinutes: number; visibleLevels: string[] }) {
100
+ const saved = await store.get<Partial<UserSettings>>('local', SETTINGS_KEY);
101
+ const merged: UserSettings = {
102
+ theme: saved?.theme ?? 'dark',
103
+ idleLockMinutes: saved?.idleLockMinutes ?? defaults.idleLockMinutes,
104
+ visibleLevels: saved?.visibleLevels ?? defaults.visibleLevels,
105
+ notifications: { ...DEFAULT_NOTIFY, ...(saved?.notifications ?? {}) },
106
+ confirmLock: saved?.confirmLock ?? true,
107
+ startPage: typeof saved?.startPage === 'string' ? saved.startPage : null,
108
+ hotkeys: { enabled: saved?.hotkeys?.enabled ?? true, map: saved?.hotkeys?.map ?? {} },
109
+ };
110
+ settings.set(merged);
111
+ applyTheme(merged.theme);
112
+ await store.set('local', SETTINGS_KEY, merged);
113
+ }
114
+ export async function updateSettings(patch: Partial<UserSettings>) {
115
+ const next = { ...settings.get(), ...patch };
116
+ settings.set(next);
117
+ if (patch.theme) applyTheme(patch.theme);
118
+ await store.set('local', SETTINGS_KEY, next);
119
+ }
@@ -0,0 +1,78 @@
1
+ // Hash router with guards on every navigation (ADR-036) and an in-memory context mailbox for showView.
2
+ // Routes: #/home · #/reports · #/v/<module>/<view> · #/settings/<page>[/<type>/<name>]
3
+
4
+ import * as guards from './guards.ts';
5
+ import { createStore } from './prefs.ts';
6
+ import { toast } from './toasts.ts';
7
+
8
+ export type Route =
9
+ | { page: 'home' } | { page: 'reports' }
10
+ | { page: 'view'; module: string; view: string }
11
+ | { page: 'settings'; sub: string; type?: string; name?: string };
12
+
13
+ export function parse(hash: string): Route | null {
14
+ const parts = hash.replace(/^#\/?/, '').split('/').map(decodeURIComponent);
15
+ if (!parts[0]) return null;
16
+ if (parts[0] === 'home') return { page: 'home' };
17
+ if (parts[0] === 'reports') return { page: 'reports' };
18
+ if (parts[0] === 'v' && parts[1] && parts[2]) return { page: 'view', module: parts[1], view: parts[2] };
19
+ if (parts[0] === 'settings') return { page: 'settings', sub: parts[1] || 'services', type: parts[2], name: parts[3] };
20
+ return null;
21
+ }
22
+
23
+ export const href = {
24
+ view: (module: string, view: string) => `#/v/${encodeURIComponent(module)}/${encodeURIComponent(view)}`,
25
+ settings: (sub: string, type?: string, name?: string) => `#/settings/${[sub, type, name].filter(Boolean).join('/')}`,
26
+ };
27
+
28
+ export const current = createStore<string>(typeof location !== 'undefined' ? location.hash : '');
29
+ let approved: string | null = null;
30
+
31
+ /** Contexts waiting for their view to mount (never stored; lost on reload: ADR-036). */
32
+ const mailbox = new Map<string, Record<string, unknown>>();
33
+ const liveHandlers = new Map<string, (ctx: Record<string, unknown>) => void>();
34
+ export const takeContext = (viewKey: string) => { const c = mailbox.get(viewKey); mailbox.delete(viewKey); return c; };
35
+ export function setLiveHandler(viewKey: string, fn: ((ctx: Record<string, unknown>) => void) | null) {
36
+ if (fn) liveHandlers.set(viewKey, fn); else liveHandlers.delete(viewKey);
37
+ }
38
+
39
+ const ask = () => guards.ask((q) => confirm(q), (reason) => toast(`Can't leave yet: ${reason}. Press Stop first, or wait for it to finish.`, 'error'));
40
+
41
+ /** Navigate (guarded). Returns false if a guard refused. */
42
+ export function go(hash: string, context?: Record<string, unknown>, viewKey?: string): boolean {
43
+ if (hash === location.hash) {
44
+ if (context && viewKey) {
45
+ const live = liveHandlers.get(viewKey);
46
+ if (live) live(context); else mailbox.set(viewKey, context);
47
+ }
48
+ return true;
49
+ }
50
+ if (!ask()) return false;
51
+ if (context && viewKey) mailbox.set(viewKey, context);
52
+ guards.clearAll();
53
+ approved = hash;
54
+ location.hash = hash;
55
+ return true;
56
+ }
57
+
58
+ export function start() {
59
+ let previous = location.hash;
60
+ addEventListener('hashchange', () => {
61
+ if (approved === location.hash) {
62
+ approved = null;
63
+ } else if (!ask()) {
64
+ history.replaceState(null, '', previous || '#/home'); // refuse: put the address back (no hashchange fires)
65
+ return;
66
+ } else {
67
+ guards.clearAll();
68
+ }
69
+ previous = location.hash;
70
+ current.set(location.hash);
71
+ });
72
+ addEventListener('beforeunload', (e) => { if (guards.anyActive()) e.preventDefault(); });
73
+ }
74
+
75
+ export function replace(hash: string) {
76
+ history.replaceState(null, '', hash);
77
+ current.set(hash);
78
+ }
@@ -0,0 +1,65 @@
1
+ // Header search: connectors opt in with a resolver, views offer Quick Actions for what it resolves to.
2
+ // term → (resolve per connector) → one context (picked, or inferred when there is only one) → Quick Action tiles → showView with that context.
3
+
4
+ import type { Context, SearchResult } from '@tacoshell/sdk';
5
+ import { serviceKey, type QuickActionDecl, type Registry, type RegistryService, type RegistryView } from '../types.ts';
6
+ import * as log from './log.ts';
7
+ import * as services from './services.ts';
8
+
9
+ export interface Hit { service: RegistryService; result: SearchResult }
10
+ export interface Outcome { hits: Hit[]; failed: string[] }
11
+ export interface Tile { view: RegistryView; action: QuickActionDecl; label: string; icon?: string }
12
+
13
+ /** Connectors that can resolve a term right now: they declare a resolver and are enabled and configured. */
14
+ export const resolvers = (reg: Registry, usable: (type: string, name: string) => boolean = services.isUsable) =>
15
+ reg.services.filter((s) => s.resolver && usable(s.type, s.name));
16
+
17
+ /** The search box hint: just "Find" (the resolvers' labels and hints are not shown). */
18
+ export function placeholder(_list?: RegistryService[]): string { return 'Find'; }
19
+
20
+ /** Asks every resolver at once. One that fails doesn't hide the others' results; its failure is reported and logged. */
21
+ export async function resolve(term: string, list: RegistryService[], run?: (s: RegistryService, term: string) => Promise<SearchResult[]>): Promise<Outcome> {
22
+ const ask = run ?? ((s, t) => {
23
+ const impl = services.implFor(s);
24
+ if (!impl?.resolve) throw new Error(`${s.label} declares a resolver but its implementation has no resolve().`);
25
+ return impl.resolve(t, services.contextFor(s));
26
+ });
27
+ const settled = await Promise.allSettled(list.map(async (s) => ask(s, term)));
28
+ const out: Outcome = { hits: [], failed: [] };
29
+ const seen = new Set<string>();
30
+ settled.forEach((r, i) => {
31
+ const s = list[i];
32
+ if (r.status === 'rejected') {
33
+ const message = (r.reason as Error)?.message ?? String(r.reason);
34
+ log.add('warn', `Search in ${s.label} failed: ${message}`, undefined, 'search');
35
+ out.failed.push(`${s.label}: ${message}`);
36
+ return;
37
+ }
38
+ for (const result of r.value ?? []) {
39
+ const k = `${serviceKey(s)}:${result.id}`;
40
+ if (!seen.has(k)) { seen.add(k); out.hits.push({ service: s, result }); }
41
+ }
42
+ });
43
+ log.add('debug', `Search "${term}": ${out.hits.length} result(s) from ${list.length} connector(s)`, undefined, 'search');
44
+ return out;
45
+ }
46
+
47
+ /** Quick Action tiles for a resolved service: every view that registered one for its type and whose own services are usable. */
48
+ export function tilesFor(reg: Registry, service: RegistryService, usable: (type: string, name: string) => boolean = services.isUsable): Tile[] {
49
+ return reg.views.flatMap((view) => (view.quickActions ?? [])
50
+ .filter((a) => a.service === service.type && view.requires.every((r) => usable(r.type, r.name)))
51
+ .map((action) => ({ view, action, label: action.label ?? view.label, icon: action.icon })));
52
+ }
53
+
54
+ /** The context handed to the view: `map` renames keys (view key → resolved key); without it, the resolved keys the view declares (or all of them if it declares none). */
55
+ export function contextFor(tile: Pick<Tile, 'view' | 'action'>, resolved: Context): Context {
56
+ const { map } = tile.action;
57
+ const out: Context = {};
58
+ if (map) {
59
+ for (const [viewKey, resolvedKey] of Object.entries(map)) if (resolved[resolvedKey] !== undefined) out[viewKey] = resolved[resolvedKey];
60
+ return out;
61
+ }
62
+ const declared = tile.view.context;
63
+ for (const [k, v] of Object.entries(resolved)) if (!declared || k in declared) out[k] = v;
64
+ return out;
65
+ }
@@ -0,0 +1,178 @@
1
+ // Service runtime (ADR-004, ADR-023, ADR-032, ADR-040): per-instance state, secrets in the vault, the auth-aware fetch, OAuth PKCE.
2
+
3
+ import type { ServiceContext, ServiceImpl } from '@tacoshell/sdk';
4
+ import { serviceKey, type AuthMode, type FieldDecl, type Registry, type RegistryService } from '../types.ts';
5
+ import { allowedBy } from './hosts.ts';
6
+ import * as log from './log.ts';
7
+ import { createStore } from './prefs.ts';
8
+ import * as store from './storage.ts';
9
+ import * as vault from './vault.ts';
10
+
11
+ const STATE_KEY = 'taco.services';
12
+ export interface ServiceState { enabled: boolean; mode: AuthMode; config: Record<string, string>; /** Current Session services appear in the header's Sessions menu unless the user hides them. */ hideFromSessions?: boolean; lastTest?: { ok: boolean; /** ok = connected, warn = works with a caveat, error = failed. */ status?: 'ok' | 'warn' | 'error'; at: number; detail: string } }
13
+
14
+ let registry: Registry | undefined;
15
+ let impls: Record<string, ServiceImpl> = {};
16
+ export const states = createStore<Record<string, ServiceState>>({});
17
+
18
+ export async function init(reg: Registry, implementations: Record<string, ServiceImpl>) {
19
+ registry = reg;
20
+ impls = implementations;
21
+ states.set((await store.get<Record<string, ServiceState>>('local', STATE_KEY)) ?? {});
22
+ }
23
+
24
+ export const find = (type: string, name: string) => registry?.services.find((s) => s.type === type && s.name === name);
25
+ export const stateOf = (s: RegistryService): ServiceState => states.get()[serviceKey(s)] ?? { enabled: true, mode: s.auth[0], config: {} };
26
+
27
+ export async function update(s: RegistryService, patch: Partial<ServiceState>) {
28
+ const next = { ...states.get(), [serviceKey(s)]: { ...stateOf(s), ...patch } };
29
+ states.set(next);
30
+ await store.set('local', STATE_KEY, next);
31
+ }
32
+
33
+ export const secretId = (s: RegistryService, field: string) => `${s.type}/${s.name}.${field}`;
34
+
35
+ /** Declared fields for the auth mode, plus the ones each mode implies when the service didn't declare them. */
36
+ export function fieldsFor(s: RegistryService, mode: AuthMode): FieldDecl[] {
37
+ const declared = (s.fields ?? []).filter((f) => !f.modes || f.modes.includes(mode));
38
+ const implied: Record<AuthMode, FieldDecl[]> = {
39
+ session: [],
40
+ apikey: [{ key: 'apiKey', label: 'API key', secret: true }],
41
+ basic: [{ key: 'username', label: 'Username' }, { key: 'password', label: 'Password or token', secret: true }],
42
+ oauth: [{ key: 'clientId', label: 'OAuth client ID' }],
43
+ none: [],
44
+ };
45
+ const out = [...declared];
46
+ for (const f of implied[mode]) if (!out.some((d) => d.key === f.key)) out.push(f);
47
+ return out;
48
+ }
49
+
50
+ /** The non-secret field values in force: what the user saved, else the field's declared default. Secrets never appear here. */
51
+ export function configOf(s: RegistryService): Record<string, string> {
52
+ const st = stateOf(s);
53
+ const out: Record<string, string> = { ...st.config };
54
+ for (const f of fieldsFor(s, st.mode)) {
55
+ if (f.secret) { delete out[f.key]; continue; }
56
+ if (!out[f.key]?.trim() && f.default !== undefined) out[f.key] = f.default;
57
+ }
58
+ return out;
59
+ }
60
+
61
+ export function isConfigured(s: RegistryService): boolean {
62
+ const st = stateOf(s);
63
+ const cfg = configOf(s);
64
+ const ok = fieldsFor(s, st.mode).every((f) => f.required === false || (f.secret ? vault.has(secretId(s, f.key)) : !!cfg[f.key]?.trim()));
65
+ return ok && (st.mode !== 'oauth' || vault.has(secretId(s, 'accessToken')));
66
+ }
67
+
68
+ export function isUsable(type: string, name: string) {
69
+ const s = find(type, name);
70
+ return !!s && stateOf(s).enabled && isConfigured(s);
71
+ }
72
+
73
+ const fill = (template: string, config: Record<string, string>) => template.replace(/\{(\w+)\}/g, (_, k: string) => encodeURIComponent(config[k] ?? ''));
74
+
75
+ export function contextFor(s: RegistryService): ServiceContext {
76
+ const st = stateOf(s);
77
+ const impl = impls[serviceKey(s)];
78
+ const source = `${s.label} (${serviceKey(s)})`;
79
+ const slog = log.logger(source);
80
+ const secret = async (field: string) => {
81
+ const v = await vault.get(secretId(s, field));
82
+ if (v === undefined) throw new Error(`${s.label}: "${field}" isn't set (Settings → Services → ${s.label}).`);
83
+ return v;
84
+ };
85
+ const ctx: ServiceContext = {
86
+ instance: { module: s.module, type: s.type, name: s.name },
87
+ config: configOf(s),
88
+ authMode: st.mode,
89
+ secret,
90
+ log: slog,
91
+ async fetch(url, init = {}) {
92
+ if (!url.startsWith('https://')) throw new Error(`${s.label}: only https:// URLs are allowed (${url}).`);
93
+ if (!allowedBy(url, s.hosts)) throw new Error(`${s.label}: ${new URL(url).host} isn't one of this service's declared hosts.`);
94
+ const headers = new Headers(init.headers);
95
+ let body = init.body;
96
+ if (init.json !== undefined) { headers.set('Content-Type', 'application/json'); body = JSON.stringify(init.json); }
97
+ if (impl?.authorize) { for (const [k, v] of Object.entries(await impl.authorize(ctx))) headers.set(k, v); } // the service's own auth replaces the mode's
98
+ else if (st.mode === 'apikey') headers.set(s.apiKey?.header ?? 'Authorization', `${s.apiKey?.prefix ?? 'Bearer '}${await secret('apiKey')}`);
99
+ else if (st.mode === 'basic') headers.set('Authorization', `Basic ${btoa(`${st.config.username ?? ''}:${await secret('password')}`)}`);
100
+ else if (st.mode === 'oauth') headers.set('Authorization', `Bearer ${await oauthToken(s)}`);
101
+ const method = (init.method ?? 'GET').toUpperCase();
102
+ try {
103
+ const res = await fetch(url, { ...init, body, headers, credentials: st.mode === 'session' ? 'include' : 'omit' });
104
+ log.add('debug', `${method} ${url} → ${res.status}`, init.json === undefined ? undefined : { payload: init.json }, source, 'api');
105
+ return res;
106
+ } catch (e) {
107
+ log.add('debug', `${method} ${url} → no response (${(e as Error).message})`, undefined, source, 'api');
108
+ throw e;
109
+ }
110
+ },
111
+ };
112
+ return ctx;
113
+ }
114
+
115
+ export async function test(s: RegistryService): Promise<{ ok: boolean; status: 'ok' | 'warn' | 'error'; detail: string }> {
116
+ const impl = impls[serviceKey(s)];
117
+ let result: { ok: boolean; status: 'ok' | 'warn' | 'error'; detail: string };
118
+ try {
119
+ const r = impl?.test ? await impl.test(contextFor(s)) : undefined;
120
+ const warn = r?.status === 'warn';
121
+ result = { ok: true, status: warn ? 'warn' : 'ok', detail: r?.detail ?? (r?.who ? `Connected as ${r.who}` : impl?.test ? 'Test passed' : 'No test defined by this service') };
122
+ } catch (e) {
123
+ result = { ok: false, status: 'error', detail: (e as Error).message };
124
+ }
125
+ await update(s, { lastTest: { ...result, at: Date.now() } });
126
+ log.add(result.status === 'ok' ? 'info' : result.status === 'warn' ? 'warn' : 'warn', `${s.label} (${serviceKey(s)}) test: ${result.detail}`, undefined, 'Settings › Services');
127
+ return result;
128
+ }
129
+
130
+ export const implFor = (s: RegistryService) => impls[serviceKey(s)];
131
+
132
+ // ── OAuth PKCE (ADR-004): redirect https://<id>.chromiumapp.org/oauth/<type>/<name>; random single-use state ────────
133
+ const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
134
+ export const redirectUrl = (s: RegistryService, extensionId: string) =>
135
+ typeof chrome !== 'undefined' && chrome.identity?.getRedirectURL ? chrome.identity.getRedirectURL(`oauth/${s.type}/${s.name}`) : `https://${extensionId}.chromiumapp.org/oauth/${s.type}/${s.name}`;
136
+
137
+ export async function connectOAuth(s: RegistryService) {
138
+ if (!s.oauth) throw new Error(`${s.label} doesn't declare oauth.authorizeUrl / tokenUrl in its module.`);
139
+ if (!chrome?.identity?.launchWebAuthFlow) throw new Error('OAuth sign-in needs the extension (chrome.identity).');
140
+ const st = stateOf(s);
141
+ if (!st.config.clientId) throw new Error('Enter the OAuth client ID first.');
142
+ const verifier = b64url(crypto.getRandomValues(new Uint8Array(32)));
143
+ const challenge = b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
144
+ const state = b64url(crypto.getRandomValues(new Uint8Array(16)));
145
+ const redirect = redirectUrl(s, registry!.app.extensionId);
146
+ const auth = new URL(fill(s.oauth.authorizeUrl, st.config));
147
+ auth.search = new URLSearchParams({ response_type: 'code', client_id: st.config.clientId, redirect_uri: redirect, code_challenge: challenge, code_challenge_method: 'S256', state, ...(s.oauth.scopes?.length ? { scope: s.oauth.scopes.join(' ') } : {}) }).toString();
148
+ const back = await chrome.identity.launchWebAuthFlow({ url: auth.toString(), interactive: true });
149
+ const q = new URL(back ?? '').searchParams;
150
+ if (q.get('state') !== state) throw new Error('OAuth state mismatch: sign-in refused.');
151
+ if (!q.get('code')) throw new Error(`Sign-in didn't return a code (${q.get('error') ?? 'no error given'}).`);
152
+ await exchange(s, { grant_type: 'authorization_code', code: q.get('code')!, redirect_uri: redirect, code_verifier: verifier, client_id: st.config.clientId });
153
+ log.add('info', `${s.label} (${serviceKey(s)}) connected with OAuth`, undefined, 'Settings › Services');
154
+ }
155
+
156
+ async function exchange(s: RegistryService, params: Record<string, string>) {
157
+ const res = await fetch(fill(s.oauth!.tokenUrl, stateOf(s).config), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(params), credentials: 'omit' });
158
+ if (!res.ok) throw new Error(`Token request failed (${res.status}).`);
159
+ const t = await res.json();
160
+ await vault.put(secretId(s, 'accessToken'), t.access_token);
161
+ if (t.refresh_token) await vault.put(secretId(s, 'refreshToken'), t.refresh_token);
162
+ await vault.put(secretId(s, 'expiresAt'), String(t.expires_in ? Date.now() + t.expires_in * 1000 : 0));
163
+ }
164
+
165
+ const refreshing = new Map<string, Promise<void>>();
166
+ async function oauthToken(s: RegistryService): Promise<string> {
167
+ const expiresAt = Number((await vault.get(secretId(s, 'expiresAt'))) ?? 0);
168
+ const refreshToken = await vault.get(secretId(s, 'refreshToken'));
169
+ if (expiresAt && Date.now() > expiresAt - 60_000 && refreshToken) {
170
+ // Providers that rotate refresh tokens break if two refreshes race, so one refresh per service at a time.
171
+ const key = serviceKey(s);
172
+ if (!refreshing.has(key)) refreshing.set(key, exchange(s, { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: stateOf(s).config.clientId ?? '' }).finally(() => refreshing.delete(key)));
173
+ await refreshing.get(key);
174
+ }
175
+ const token = await vault.get(secretId(s, 'accessToken'));
176
+ if (!token) throw new Error(`${s.label} isn't connected (Settings → Services → ${s.label} → Connect).`);
177
+ return token;
178
+ }
@@ -0,0 +1,93 @@
1
+ // Sessions: services signed in with "Current Session" (the user's own browser session) report whether that session is there.
2
+ // The header's Sessions icon is yellow only while a shown service has no active session; its menu lists every such service (green = detected and active, yellow = missing).
3
+
4
+ import type { Registry, RegistryService } from '../types.ts';
5
+ import { serviceKey } from '../types.ts';
6
+ import * as log from './log.ts';
7
+ import { createStore } from './prefs.ts';
8
+ import * as services from './services.ts';
9
+
10
+ export type SessionState = 'active' | 'missing' | 'checking';
11
+ export interface SessionStatus { state: SessionState; who?: string; detail?: string; at?: number }
12
+
13
+ export const statuses = createStore<Record<string, SessionStatus>>({});
14
+
15
+ /**
16
+ * Services that have a session to report and aren't turned off: those signed in with Current Session, and those with no HTTPS sign-in of their own
17
+ * (`auth: ["none"]`, e.g. a local bridge) that declare a `sessionRequirement`: they report their status with `session()`.
18
+ */
19
+ export const sessionServices = (reg: Registry): RegistryService[] =>
20
+ reg.services.filter((s) => {
21
+ const st = services.stateOf(s);
22
+ return st.enabled && ((s.auth.includes('session') && st.mode === 'session') || (s.auth.includes('none') && st.mode === 'none' && !!s.sessionRequirement));
23
+ });
24
+
25
+ /** The ones the menu shows: a user may hide a connected, active service from it (default: shown). */
26
+ export const shown = (reg: Registry) => sessionServices(reg).filter((s) => !services.stateOf(s).hideFromSessions);
27
+
28
+ export const statusOf = (s: RegistryService): SessionStatus | undefined => statuses.get()[serviceKey(s)];
29
+
30
+ /** How bad is "no session" for this service? Set by the service's `sessionRequirement`: required → danger, recommended → warning, optional → fine. */
31
+ export type Level = 'ok' | 'warn' | 'bad';
32
+ export const REQUIREMENT_LABEL = { required: 'Required', recommended: 'Recommended', optional: 'Optional' } as const;
33
+ const RANK: Record<Level, number> = { ok: 0, warn: 1, bad: 2 };
34
+
35
+ /** The color of one service's session: green when active (or missing but optional), yellow when missing and recommended, red when missing and required. undefined until it has been checked. */
36
+ export function levelOf(s: RegistryService, st: SessionStatus | undefined): Level | undefined {
37
+ if (!st || st.state === 'checking') return undefined;
38
+ if (st.state === 'active') return 'ok';
39
+ return s.sessionRequirement === 'required' ? 'bad' : s.sessionRequirement === 'optional' ? 'ok' : 'warn';
40
+ }
41
+
42
+ /** The header icon's one color: the worst level across every shown service (2 green + 1 red = red). undefined while nothing has been checked yet. */
43
+ export function worst(reg: Registry, all = statuses.get()): Level | undefined {
44
+ let out: Level | undefined;
45
+ for (const s of shown(reg)) {
46
+ const l = levelOf(s, all[serviceKey(s)]);
47
+ if (l && (!out || RANK[l] > RANK[out])) out = l;
48
+ }
49
+ return out;
50
+ }
51
+
52
+ const put = (s: RegistryService, st: SessionStatus) => statuses.set({ ...statuses.get(), [serviceKey(s)]: st });
53
+
54
+ /** Asks the service: its `session()` if it has one, else whether its `test()` passes. */
55
+ export async function check(s: RegistryService, run?: (s: RegistryService) => Promise<{ active: boolean; who?: string; detail?: string }>): Promise<SessionStatus> {
56
+ const before = statusOf(s);
57
+ put(s, { ...before, state: before?.state ?? 'checking' }); // keep the last known answer while re-checking: no flicker
58
+ let result: SessionStatus;
59
+ try {
60
+ const r = await (run ?? defaultRun)(s);
61
+ result = r.active ? { state: 'active', who: r.who, at: Date.now() } : { state: 'missing', detail: r.detail ?? 'No signed-in session detected', at: Date.now() };
62
+ } catch (e) {
63
+ result = { state: 'missing', detail: (e as Error).message, at: Date.now() };
64
+ }
65
+ if (before?.state !== result.state) log.add(result.state === 'active' ? 'info' : 'warn', `${s.label} session: ${result.state === 'active' ? `active${result.who ? ` (${result.who})` : ''}` : `missing (${result.detail})`}`, undefined, 'Sessions');
66
+ put(s, result);
67
+ return result;
68
+ }
69
+
70
+ async function defaultRun(s: RegistryService) {
71
+ const impl = services.implFor(s);
72
+ const ctx = services.contextFor(s);
73
+ if (impl?.session) return impl.session(ctx);
74
+ if (impl?.test) { const r = await impl.test(ctx); return { active: true, who: r?.who }; }
75
+ return { active: true, detail: 'No session check defined by this service' };
76
+ }
77
+
78
+ export const checkAll = (reg: Registry) => Promise.all(sessionServices(reg).map((s) => check(s)));
79
+
80
+ /** Can the service re-establish its session itself (its `reauth()`)? The Sessions menu then offers "Sign in again". */
81
+ export const canReauth = (s: RegistryService) => !!services.implFor(s)?.reauth;
82
+
83
+ /** Runs the service's `reauth()`, then checks the session again. Returns an error message, or null when it ran (the check says whether it worked). */
84
+ export async function reauth(s: RegistryService): Promise<string | null> {
85
+ const impl = services.implFor(s);
86
+ if (!impl?.reauth) return 'This service has no way to sign in again from here.';
87
+ put(s, { ...statusOf(s), state: 'checking' });
88
+ let error: string | null = null;
89
+ try { await impl.reauth(services.contextFor(s)); log.add('info', `${s.label}: sign-in again finished`, undefined, 'Sessions'); }
90
+ catch (e) { error = (e as Error).message; log.add('warn', `${s.label}: sign-in again failed: ${error}`, undefined, 'Sessions'); }
91
+ await check(s);
92
+ return error;
93
+ }
@@ -0,0 +1,28 @@
1
+ // The page the app opens on (ADR-064). The developer sets a default in taco.json (`settings.startPage`); the user can override it in
2
+ // Settings → Configuration → Start page. Values: "auto" (the first Featured action, else Home) · "home" · "reports" · a view key "<module>/<view>".
3
+ // Getting Started always comes first until a vault exists (ADR-047), and anything that no longer exists falls back to "auto".
4
+
5
+ import type { Registry, RegistryView } from '../types.ts';
6
+ import { viewKey } from '../types.ts';
7
+ import { href } from './router.ts';
8
+
9
+ export const START_AUTO = 'auto';
10
+
11
+ /** Does the app have Reports views (so "reports" is a possible start page)? */
12
+ const hasReportViews = (reg: Registry) => reg.views.some((v) => (v.nav.section ?? 'home') === 'reports');
13
+
14
+ /** The hash the app opens on. `firstFeatured` is the rail's first Featured action (`nav.home.featured[0]`). */
15
+ export function startHash(reg: Registry, firstFeatured: RegistryView | undefined, choice?: string | null, appDefault?: string): string {
16
+ const auto = () => (firstFeatured ? href.view(firstFeatured.module, firstFeatured.name) : '#/home');
17
+ for (const pick of [choice, appDefault]) {
18
+ if (!pick || pick === START_AUTO) { if (pick === START_AUTO) return auto(); continue; }
19
+ if (pick === 'home') return '#/home';
20
+ if (pick === 'reports') { if (hasReportViews(reg)) return '#/reports'; continue; }
21
+ const v = reg.views.find((x) => viewKey(x) === pick);
22
+ if (v) return href.view(v.module, v.name); // a view that was removed (or a module taken out of the app) falls through to the next choice
23
+ }
24
+ return auto();
25
+ }
26
+
27
+ /** The app default as the developer set it (for the "App default" line in Settings). */
28
+ export const appDefaultOf = (reg: Registry) => reg.settings.startPage ?? START_AUTO;
@@ -0,0 +1,54 @@
1
+ // chrome.storage with an in-memory fallback, so core logic runs in tests and in a plain browser tab.
2
+ // `local` = settings, ciphertext, service config (ADR-003). `session` = memory-only, cleared when the browser closes (the vault key).
3
+
4
+ export type Area = 'local' | 'session';
5
+ type Listener = (value: unknown) => void;
6
+
7
+ const memory: Record<Area, Map<string, unknown>> = { local: new Map(), session: new Map() };
8
+ const memoryListeners = new Map<string, Set<Listener>>();
9
+ const hasChrome = () => typeof chrome !== 'undefined' && !!chrome.storage?.local;
10
+
11
+ export async function get<T>(area: Area, key: string): Promise<T | undefined> {
12
+ if (!hasChrome()) return structuredClone(memory[area].get(key)) as T | undefined;
13
+ const got = await chrome.storage[area].get(key);
14
+ return got[key] as T | undefined;
15
+ }
16
+
17
+ export async function set(area: Area, key: string, value: unknown): Promise<void> {
18
+ if (!hasChrome()) {
19
+ memory[area].set(key, structuredClone(value));
20
+ for (const fn of memoryListeners.get(`${area}:${key}`) ?? []) fn(value);
21
+ return;
22
+ }
23
+ await chrome.storage[area].set({ [key]: value });
24
+ }
25
+
26
+ export async function remove(area: Area, key: string): Promise<void> {
27
+ if (!hasChrome()) {
28
+ memory[area].delete(key);
29
+ for (const fn of memoryListeners.get(`${area}:${key}`) ?? []) fn(undefined);
30
+ return;
31
+ }
32
+ await chrome.storage[area].remove(key);
33
+ }
34
+
35
+ /** Calls `fn(newValue)` whenever `key` changes in `area` (from any page or the service worker). */
36
+ export function onChange(area: Area, key: string, fn: Listener): () => void {
37
+ if (!hasChrome()) {
38
+ const k = `${area}:${key}`;
39
+ if (!memoryListeners.has(k)) memoryListeners.set(k, new Set());
40
+ memoryListeners.get(k)!.add(fn);
41
+ return () => memoryListeners.get(k)?.delete(fn);
42
+ }
43
+ const listener = (changes: Record<string, chrome.storage.StorageChange>, changedArea: string) => {
44
+ if (changedArea === area && key in changes) fn(changes[key].newValue);
45
+ };
46
+ chrome.storage.onChanged.addListener(listener);
47
+ return () => chrome.storage.onChanged.removeListener(listener);
48
+ }
49
+
50
+ /** Test helper: forget everything stored in memory. */
51
+ export function resetMemory() {
52
+ memory.local.clear();
53
+ memory.session.clear();
54
+ }