@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.
- package/LICENSE +28 -0
- package/README.md +6 -2
- package/package.json +40 -4
- package/src/background.ts +41 -0
- package/src/core/bus.ts +210 -0
- package/src/core/cards.ts +33 -0
- package/src/core/contrib.ts +70 -0
- package/src/core/cron.ts +63 -0
- package/src/core/cronfriendly.ts +70 -0
- package/src/core/csv.ts +36 -0
- package/src/core/csvfeature.ts +57 -0
- package/src/core/datasets.ts +367 -0
- package/src/core/domshot.ts +81 -0
- package/src/core/guards.ts +36 -0
- package/src/core/hosts.ts +15 -0
- package/src/core/hotkeys.ts +44 -0
- package/src/core/indicators.ts +62 -0
- package/src/core/jobs.ts +37 -0
- package/src/core/localdata.ts +88 -0
- package/src/core/log.ts +91 -0
- package/src/core/markdown.ts +57 -0
- package/src/core/nav.ts +105 -0
- package/src/core/notifyrules.ts +31 -0
- package/src/core/page.ts +91 -0
- package/src/core/prefs.ts +119 -0
- package/src/core/router.ts +78 -0
- package/src/core/search.ts +65 -0
- package/src/core/services.ts +178 -0
- package/src/core/sessions.ts +93 -0
- package/src/core/startpage.ts +28 -0
- package/src/core/storage.ts +54 -0
- package/src/core/systemtools.ts +85 -0
- package/src/core/tabfit.ts +30 -0
- package/src/core/templates.ts +48 -0
- package/src/core/text.ts +6 -0
- package/src/core/toasts.ts +13 -0
- package/src/core/vault.ts +208 -0
- package/src/env.d.ts +2 -0
- package/src/index.ts +58 -0
- package/src/styles.css +391 -0
- package/src/types.ts +133 -0
- package/src/ui/ActionModal.tsx +22 -0
- package/src/ui/App.tsx +241 -0
- package/src/ui/ClearableInput.tsx +23 -0
- package/src/ui/CsvFeature.tsx +151 -0
- package/src/ui/Icon.tsx +8 -0
- package/src/ui/ItemFeature.tsx +39 -0
- package/src/ui/Markdown.tsx +24 -0
- package/src/ui/Rail.tsx +135 -0
- package/src/ui/RelatedMenu.tsx +57 -0
- package/src/ui/Search.tsx +111 -0
- package/src/ui/Sessions.tsx +76 -0
- package/src/ui/SidePanel.tsx +150 -0
- package/src/ui/TabBar.tsx +56 -0
- package/src/ui/ViewHost.tsx +142 -0
- package/src/ui/hooks.ts +28 -0
- package/src/ui/settings/Datasets.tsx +172 -0
- package/src/ui/settings/ReleaseNotes.tsx +96 -0
- package/src/ui/settings/ScheduleEditor.tsx +57 -0
- package/src/ui/settings/Settings.tsx +339 -0
- package/src/ui/settings/SettingsTabs.tsx +63 -0
- package/src/ui/settings/Templates.tsx +52 -0
- package/src/ui/useContrib.ts +36 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// System tools (ADR-054): framework-provided Tools-menu entries a view switches on by listing them in its manifest:
|
|
2
|
+
// "tools": { "system": ["copy-chart", "copy-report"], "selector": "div.card" } (selector: which DIVs Copy Chart may pick; default: every div)
|
|
3
|
+
// Ported from CommunityOS v2 (lib/chartcopy.js, FR-TOOLS-1).
|
|
4
|
+
|
|
5
|
+
import type { Tool } from '@tacoshell/sdk';
|
|
6
|
+
import { blockToPng, paneToPng } from './domshot.ts';
|
|
7
|
+
import * as log from './log.ts';
|
|
8
|
+
import { toast } from './toasts.ts';
|
|
9
|
+
|
|
10
|
+
export const SYSTEM_TOOLS = ['copy-chart', 'copy-report'] as const;
|
|
11
|
+
export type SystemTool = (typeof SYSTEM_TOOLS)[number];
|
|
12
|
+
|
|
13
|
+
/** The view's content pane: what Copy Chart picks inside and what Copy Report pictures (without the 3rd-level bar, Log and Help). */
|
|
14
|
+
const pane = () => document.querySelector<HTMLElement>('main.content');
|
|
15
|
+
const isChrome = (el: Element) => el.matches('.subbar, .taco-pick');
|
|
16
|
+
|
|
17
|
+
async function toClipboard(blob: Blob, what: string) {
|
|
18
|
+
await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
|
|
19
|
+
log.add('info', `${what} copied to the clipboard (${Math.round(blob.size / 1024)} KB PNG)`, undefined, 'Tools');
|
|
20
|
+
toast(`${what} copied. Paste it where you need it.`);
|
|
21
|
+
}
|
|
22
|
+
const nextFrame = () => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
|
|
23
|
+
|
|
24
|
+
let cancelPick: (() => void) | null = null;
|
|
25
|
+
|
|
26
|
+
/** Copy Chart: hover outlines the nearest matching block, a click copies it as a PNG, Esc (or pressing it again) cancels. */
|
|
27
|
+
export function copyChart(selector = 'div') {
|
|
28
|
+
if (cancelPick) { cancelPick(); return; }
|
|
29
|
+
const scope = pane();
|
|
30
|
+
if (!scope) return toast('Nothing to copy on this page.', 'error');
|
|
31
|
+
const frame = Object.assign(document.createElement('div'), { className: 'taco-pick taco-pick-frame' });
|
|
32
|
+
const banner = Object.assign(document.createElement('div'), { className: 'taco-pick taco-pick-banner', textContent: 'Click a block to copy it as a picture · Esc to cancel' });
|
|
33
|
+
banner.setAttribute('role', 'status');
|
|
34
|
+
document.body.append(frame, banner);
|
|
35
|
+
const blockAt = (t: EventTarget | null) => {
|
|
36
|
+
if (!(t instanceof Element) || !scope.contains(t) || t.closest('.subbar')) return null;
|
|
37
|
+
const b = t.closest(selector);
|
|
38
|
+
return b && scope.contains(b) && b !== scope ? b : null;
|
|
39
|
+
};
|
|
40
|
+
const move = (e: MouseEvent) => {
|
|
41
|
+
const b = blockAt(e.target);
|
|
42
|
+
if (!b) { frame.style.display = 'none'; return; }
|
|
43
|
+
const r = b.getBoundingClientRect();
|
|
44
|
+
Object.assign(frame.style, { display: 'block', left: `${r.left}px`, top: `${r.top}px`, width: `${r.width}px`, height: `${r.height}px` });
|
|
45
|
+
};
|
|
46
|
+
const stop = () => {
|
|
47
|
+
document.removeEventListener('mousemove', move, true);
|
|
48
|
+
document.removeEventListener('click', click, true);
|
|
49
|
+
document.removeEventListener('keydown', key, true);
|
|
50
|
+
frame.remove(); banner.remove(); document.body.style.cursor = ''; cancelPick = null;
|
|
51
|
+
};
|
|
52
|
+
const key = (e: KeyboardEvent) => { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); stop(); toast('Copy Chart cancelled.'); } };
|
|
53
|
+
async function click(e: MouseEvent) {
|
|
54
|
+
const b = blockAt(e.target);
|
|
55
|
+
if (!b) return;
|
|
56
|
+
e.preventDefault(); e.stopPropagation();
|
|
57
|
+
stop(); // the outline and banner must not be in the picture
|
|
58
|
+
await nextFrame();
|
|
59
|
+
try { await toClipboard(await blockToPng(b), 'Chart'); } catch (err) { log.add('error', `Copy Chart failed: ${(err as Error).message}`, undefined, 'Tools'); toast(`Couldn't copy the chart: ${(err as Error).message}`, 'error'); }
|
|
60
|
+
}
|
|
61
|
+
document.addEventListener('mousemove', move, true);
|
|
62
|
+
document.addEventListener('click', click, true);
|
|
63
|
+
document.addEventListener('keydown', key, true);
|
|
64
|
+
document.body.style.cursor = 'crosshair';
|
|
65
|
+
cancelPick = stop;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Copy Report: the whole view pane (title and all content, full height) as one PNG. */
|
|
69
|
+
export async function copyReport() {
|
|
70
|
+
const p = pane();
|
|
71
|
+
if (!p) return toast('Nothing to copy on this page.', 'error');
|
|
72
|
+
toast('Copying the page…');
|
|
73
|
+
await nextFrame();
|
|
74
|
+
try { await toClipboard(await paneToPng(p, { skip: isChrome }), 'Page'); } catch (err) { log.add('error', `Copy Report failed: ${(err as Error).message}`, undefined, 'Tools'); toast(`Couldn't copy the page: ${(err as Error).message}`, 'error'); }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The Tools-menu entries for a view's `tools` declaration. Unknown names are ignored (the CLI rejects them at build time). */
|
|
78
|
+
export function systemToolsFor(decl: { system?: string[]; selector?: string } | undefined): Tool[] {
|
|
79
|
+
const out: Tool[] = [];
|
|
80
|
+
for (const name of decl?.system ?? []) {
|
|
81
|
+
if (name === 'copy-chart') out.push({ id: 'taco:copy-chart', label: 'Copy Chart', icon: 'fa-solid fa-camera', run: () => copyChart(decl?.selector || 'div') });
|
|
82
|
+
if (name === 'copy-report') out.push({ id: 'taco:copy-report', label: 'Copy Report', icon: 'fa-solid fa-images', run: () => copyReport() });
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Which 3rd-level tabs show and which go to "More" (pure, so it is unit-tested; the DOM measuring is in ui/TabBar.tsx).
|
|
2
|
+
|
|
3
|
+
/** Space kept clear between the tabs and the action buttons (Refresh …) on their right. Tabs that would reach into it move to "More". */
|
|
4
|
+
export const TAB_GUTTER = 64;
|
|
5
|
+
export const TAB_GAP = 4;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Which tabs show: the current one always (room is reserved for it first), then as many others, in order, as fit beside a More button.
|
|
9
|
+
* When even the current tab plus More won't fit, nothing shows but More (labelled with the current page), so the gutter is never entered.
|
|
10
|
+
*/
|
|
11
|
+
export function fit(widths: number[], moreWidth: number, avail: number, active: number): { shown: number[]; hidden: number[] } {
|
|
12
|
+
const all = widths.map((_, i) => i);
|
|
13
|
+
const total = widths.reduce((s, w) => s + w, 0) + TAB_GAP * Math.max(0, widths.length - 1);
|
|
14
|
+
if (total <= avail) return { shown: all, hidden: [] };
|
|
15
|
+
let used = moreWidth;
|
|
16
|
+
const chosen = new Set<number>();
|
|
17
|
+
if (active >= 0) {
|
|
18
|
+
used += widths[active] + TAB_GAP;
|
|
19
|
+
if (used > avail) return { shown: [], hidden: all };
|
|
20
|
+
chosen.add(active);
|
|
21
|
+
}
|
|
22
|
+
for (const i of all) {
|
|
23
|
+
if (i === active) continue;
|
|
24
|
+
if (used + widths[i] + TAB_GAP > avail) break;
|
|
25
|
+
used += widths[i] + TAB_GAP;
|
|
26
|
+
chosen.add(i);
|
|
27
|
+
}
|
|
28
|
+
const shown = all.filter((i) => chosen.has(i));
|
|
29
|
+
return { shown, hidden: all.filter((i) => !chosen.has(i)) };
|
|
30
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Templates (from CommunityOS v2 lib/templates.js): developer-shipped text the user may reword but not create. The shipped value is the default and the
|
|
2
|
+
// source of truth for which ${tokens} may be used (the module declares them). A user's edit is stored in the vault (item `template.<module>/<name>`).
|
|
3
|
+
// await templates.render(t, { alias: 'ada' }) → string; throws if a token has no value, so a blank never goes out in an email.
|
|
4
|
+
|
|
5
|
+
import type { RegistryTemplate } from '../types.ts';
|
|
6
|
+
import * as vault from './vault.ts';
|
|
7
|
+
|
|
8
|
+
const TOKEN = /\$\{\s*([A-Za-z_]\w*)\s*\}/g;
|
|
9
|
+
export const idOf = (t: { module: string; name: string }) => `${t.module}/${t.name}`;
|
|
10
|
+
const itemOf = (t: { module: string; name: string }) => `template.${idOf(t)}`;
|
|
11
|
+
|
|
12
|
+
export const tokensOf = (text: string) => [...new Set([...String(text).matchAll(TOKEN)].map((m) => m[1]))];
|
|
13
|
+
|
|
14
|
+
/** null when the edit is valid; otherwise a message naming the tokens the module didn't declare. */
|
|
15
|
+
export function validateEdit(t: Pick<RegistryTemplate, 'tokens'>, edited: string): string | null {
|
|
16
|
+
const bad = tokensOf(edited).filter((k) => !t.tokens.includes(k));
|
|
17
|
+
if (!bad.length) return null;
|
|
18
|
+
return `Unknown token${bad.length > 1 ? 's' : ''}: ${bad.map((k) => '${' + k + '}').join(', ')}. Allowed: ${t.tokens.map((k) => '${' + k + '}').join(', ') || 'none'}.`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface Resolved { value: string; edited: boolean; updatedAt?: number }
|
|
22
|
+
|
|
23
|
+
/** The effective text: the user's edit, unless it is stale (uses a token the module has since removed), then the shipped default. */
|
|
24
|
+
export async function get(t: RegistryTemplate): Promise<Resolved> {
|
|
25
|
+
let edit: { value?: unknown; updatedAt?: number } | null = null;
|
|
26
|
+
try { edit = JSON.parse((await vault.get(itemOf(t))) || 'null'); } catch { /* unreadable edit: use the default */ }
|
|
27
|
+
const usable = !!edit && typeof edit.value === 'string' && !validateEdit(t, edit.value);
|
|
28
|
+
return usable ? { value: edit!.value as string, edited: true, updatedAt: edit!.updatedAt } : { value: t.value, edited: false };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function save(t: RegistryTemplate, value: string) {
|
|
32
|
+
const err = validateEdit(t, value);
|
|
33
|
+
if (err) throw new Error(err);
|
|
34
|
+
if (value === t.value) return reset(t);
|
|
35
|
+
await vault.put(itemOf(t), JSON.stringify({ value, updatedAt: Date.now() }));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const reset = (t: RegistryTemplate) => vault.remove(itemOf(t));
|
|
39
|
+
|
|
40
|
+
/** Fills ${tokens} from `vars`; a token with no value throws. */
|
|
41
|
+
export function fill(text: string, vars: Record<string, unknown>, name = 'template'): string {
|
|
42
|
+
return text.replace(TOKEN, (_, k: string) => {
|
|
43
|
+
if (vars[k] == null) throw new Error(`Template “${name}” needs a value for \${${k}}.`);
|
|
44
|
+
return String(vars[k]);
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function render(t: RegistryTemplate, vars: Record<string, unknown>) { return fill((await get(t)).value, vars, t.name); }
|
package/src/core/text.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** The first `max` characters by grapheme: emoji and other multi-code-unit characters count once. */
|
|
2
|
+
export function clipText(text: string, max: number): string {
|
|
3
|
+
const s = String(text ?? '');
|
|
4
|
+
const seg = typeof Intl !== 'undefined' && 'Segmenter' in Intl ? [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(s)].map((x) => x.segment) : [...s];
|
|
5
|
+
return seg.slice(0, max).join('');
|
|
6
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// In-app toasts (bottom-right; errors stay until dismissed, others go after 4 s: UX.md).
|
|
2
|
+
import { createStore } from './prefs.ts';
|
|
3
|
+
|
|
4
|
+
export interface Toast { id: number; text: string; kind: 'info' | 'error'; title?: string }
|
|
5
|
+
export const toasts = createStore<Toast[]>([]);
|
|
6
|
+
let next = 1;
|
|
7
|
+
|
|
8
|
+
export function toast(text: string, kind: Toast['kind'] = 'info', title?: string) {
|
|
9
|
+
const t = { id: next++, text, kind, title };
|
|
10
|
+
toasts.set([...toasts.get(), t]);
|
|
11
|
+
if (kind !== 'error') setTimeout(() => dismiss(t.id), 4000);
|
|
12
|
+
}
|
|
13
|
+
export const dismiss = (id: number) => toasts.set(toasts.get().filter((t) => t.id !== id));
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// The vault (CommunityOS SECURITY.md crypto parameters; ADR-031, ADR-042).
|
|
2
|
+
// PBKDF2-SHA256 → AES-GCM-256, a fresh 12-byte IV per item, a verifier to check the passphrase.
|
|
3
|
+
// The unlocked key lives only in chrome.storage.session (memory, cleared when the browser closes); the idle lock removes it.
|
|
4
|
+
// While locked, reads and writes WAIT for the unlock prompt instead of failing, so a bulk run pauses and resumes.
|
|
5
|
+
|
|
6
|
+
import * as store from './storage.ts';
|
|
7
|
+
|
|
8
|
+
const FILE = 'taco.vault';
|
|
9
|
+
const SESSION_KEY = 'taco.vaultKey';
|
|
10
|
+
export const LOCK_REASON = 'taco.lockReason';
|
|
11
|
+
const VERIFIER = 'taco-vault-verifier-v1';
|
|
12
|
+
const enc = new TextEncoder();
|
|
13
|
+
const dec = new TextDecoder();
|
|
14
|
+
|
|
15
|
+
interface Sealed { iv: string; ct: string }
|
|
16
|
+
interface VaultFile { v: 1; salt: string; iterations: number; verifier: Sealed; items: Record<string, Sealed> }
|
|
17
|
+
export type VaultStatus = 'uninitialized' | 'locked' | 'unlocked';
|
|
18
|
+
|
|
19
|
+
function b64(bytes: Uint8Array): string {
|
|
20
|
+
let s = '';
|
|
21
|
+
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
22
|
+
return btoa(s);
|
|
23
|
+
}
|
|
24
|
+
const unb64 = (s: string) => Uint8Array.from(atob(s), (ch) => ch.charCodeAt(0));
|
|
25
|
+
|
|
26
|
+
async function derive(passphrase: string, salt: Uint8Array, iterations: number): Promise<CryptoKey> {
|
|
27
|
+
const base = await crypto.subtle.importKey('raw', enc.encode(passphrase), 'PBKDF2', false, ['deriveKey']);
|
|
28
|
+
return crypto.subtle.deriveKey({ name: 'PBKDF2', hash: 'SHA-256', salt: salt as BufferSource, iterations }, base, { name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']);
|
|
29
|
+
}
|
|
30
|
+
async function seal(key: CryptoKey, text: string): Promise<Sealed> {
|
|
31
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
32
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, enc.encode(text)));
|
|
33
|
+
return { iv: b64(iv), ct: b64(ct) };
|
|
34
|
+
}
|
|
35
|
+
async function open(key: CryptoKey, s: Sealed): Promise<string> {
|
|
36
|
+
return dec.decode(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: unb64(s.iv) as BufferSource }, key, unb64(s.ct) as BufferSource));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
let file: VaultFile | undefined;
|
|
40
|
+
let key: CryptoKey | null = null;
|
|
41
|
+
let loaded = false;
|
|
42
|
+
const listeners = new Set<(s: VaultStatus) => void>();
|
|
43
|
+
let waiters: (() => void)[] = [];
|
|
44
|
+
/** Set by the UI: shows the one shared unlock prompt when something waits on a locked vault. */
|
|
45
|
+
let unlockPrompt: (() => void) | undefined;
|
|
46
|
+
|
|
47
|
+
const emit = () => { const s = status(); for (const fn of listeners) fn(s); };
|
|
48
|
+
|
|
49
|
+
export function status(): VaultStatus {
|
|
50
|
+
if (!file) return 'uninitialized';
|
|
51
|
+
return key ? 'unlocked' : 'locked';
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Loads the vault and picks up a key unlocked in another tab of this browser session. Safe to call twice. */
|
|
55
|
+
export async function init() {
|
|
56
|
+
if (loaded) return;
|
|
57
|
+
loaded = true;
|
|
58
|
+
file = await store.get<VaultFile>('local', FILE);
|
|
59
|
+
const raw = await store.get<string>('session', SESSION_KEY);
|
|
60
|
+
if (file && raw) key = await crypto.subtle.importKey('raw', unb64(raw) as BufferSource, 'AES-GCM', true, ['encrypt', 'decrypt']);
|
|
61
|
+
// The idle lock (service worker) or another tab removes the session key: lock here too.
|
|
62
|
+
store.onChange('session', SESSION_KEY, (v) => { if (!v && key) { key = null; emit(); } });
|
|
63
|
+
emit();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export const subscribe = (fn: (s: VaultStatus) => void) => { listeners.add(fn); return () => listeners.delete(fn); };
|
|
67
|
+
export const setUnlockPrompt = (fn: () => void) => { unlockPrompt = fn; };
|
|
68
|
+
|
|
69
|
+
async function remember(k: CryptoKey) {
|
|
70
|
+
key = k;
|
|
71
|
+
await store.set('session', SESSION_KEY, b64(new Uint8Array(await crypto.subtle.exportKey('raw', k))));
|
|
72
|
+
await store.remove('session', LOCK_REASON);
|
|
73
|
+
const ready = waiters;
|
|
74
|
+
waiters = [];
|
|
75
|
+
ready.forEach((fn) => fn());
|
|
76
|
+
emit();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function create(passphrase: string, { minLength = 4, iterations = 600000 } = {}) {
|
|
80
|
+
if (file) throw new Error('A vault already exists.');
|
|
81
|
+
if (passphrase.length < minLength) throw new Error(`Use at least ${minLength} characters.`);
|
|
82
|
+
const salt = crypto.getRandomValues(new Uint8Array(16));
|
|
83
|
+
const k = await derive(passphrase, salt, iterations);
|
|
84
|
+
file = { v: 1, salt: b64(salt), iterations, verifier: await seal(k, VERIFIER), items: {} };
|
|
85
|
+
await store.set('local', FILE, file);
|
|
86
|
+
await remember(k);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Returns false for a wrong passphrase. */
|
|
90
|
+
export async function unlock(passphrase: string): Promise<boolean> {
|
|
91
|
+
if (!file) throw new Error('No vault yet.');
|
|
92
|
+
const k = await derive(passphrase, unb64(file.salt), file.iterations);
|
|
93
|
+
try {
|
|
94
|
+
if ((await open(k, file.verifier)) !== VERIFIER) return false;
|
|
95
|
+
} catch {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
await remember(k);
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ── Large data (datasets, ADR-028): one gzip + AES-GCM blob per id in its own storage key, so a big dataset doesn't rewrite the vault file ──
|
|
103
|
+
const DATA_PREFIX = 'taco.data.';
|
|
104
|
+
const DATA_INDEX = 'taco.dataIndex';
|
|
105
|
+
async function pipeBytes(bytes: Uint8Array, stream: CompressionStream | DecompressionStream): Promise<Uint8Array> {
|
|
106
|
+
return new Uint8Array(await new Response(new Blob([bytes as BlobPart]).stream().pipeThrough(stream)).arrayBuffer());
|
|
107
|
+
}
|
|
108
|
+
async function sealBytes(k: CryptoKey, bytes: Uint8Array): Promise<Sealed> {
|
|
109
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
110
|
+
return { iv: b64(iv), ct: b64(new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, k, bytes as BufferSource))) };
|
|
111
|
+
}
|
|
112
|
+
const openBytes = async (k: CryptoKey, s: Sealed) => new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: unb64(s.iv) as BufferSource }, k, unb64(s.ct) as BufferSource));
|
|
113
|
+
const dataIndex = async () => (await store.get<string[]>('local', DATA_INDEX)) ?? [];
|
|
114
|
+
|
|
115
|
+
export async function putData(id: string, text: string) {
|
|
116
|
+
await whenUnlocked();
|
|
117
|
+
await store.set('local', DATA_PREFIX + id, await sealBytes(key!, await pipeBytes(enc.encode(text), new CompressionStream('gzip'))));
|
|
118
|
+
const idx = await dataIndex();
|
|
119
|
+
if (!idx.includes(id)) await store.set('local', DATA_INDEX, [...idx, id]);
|
|
120
|
+
}
|
|
121
|
+
export async function getData(id: string): Promise<string | undefined> {
|
|
122
|
+
await whenUnlocked();
|
|
123
|
+
const sealed = await store.get<Sealed>('local', DATA_PREFIX + id);
|
|
124
|
+
return sealed ? dec.decode(await pipeBytes(await openBytes(key!, sealed), new DecompressionStream('gzip'))) : undefined;
|
|
125
|
+
}
|
|
126
|
+
export async function removeData(id: string) {
|
|
127
|
+
await store.remove('local', DATA_PREFIX + id);
|
|
128
|
+
await store.set('local', DATA_INDEX, (await dataIndex()).filter((x) => x !== id));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Re-encrypts every item with a key from the new passphrase and a new salt (v2 FR-VAULT-5). False if `current` is wrong. */
|
|
132
|
+
export async function changePassphrase(current: string, next: string, { minLength = 4 } = {}): Promise<boolean> {
|
|
133
|
+
if (!file) throw new Error('No vault yet.');
|
|
134
|
+
if (next.length < minLength) throw new Error(`Use at least ${minLength} characters.`);
|
|
135
|
+
const old = await derive(current, unb64(file.salt), file.iterations);
|
|
136
|
+
try { if ((await open(old, file.verifier)) !== VERIFIER) return false; } catch { return false; }
|
|
137
|
+
const salt = crypto.getRandomValues(new Uint8Array(16));
|
|
138
|
+
const k = await derive(next, salt, file.iterations);
|
|
139
|
+
const items: Record<string, Sealed> = {};
|
|
140
|
+
for (const [id, sealed] of Object.entries(file.items)) items[id] = await seal(k, await open(old, sealed));
|
|
141
|
+
for (const id of await dataIndex()) {
|
|
142
|
+
const blob = await store.get<Sealed>('local', DATA_PREFIX + id);
|
|
143
|
+
if (blob) await store.set('local', DATA_PREFIX + id, await sealBytes(k, await openBytes(old, blob)));
|
|
144
|
+
}
|
|
145
|
+
file = { ...file, salt: b64(salt), verifier: await seal(k, VERIFIER), items };
|
|
146
|
+
await store.set('local', FILE, file);
|
|
147
|
+
await remember(k);
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Deletes the vault and everything in it (secrets, module storage). There is no undo. */
|
|
152
|
+
export async function destroy() {
|
|
153
|
+
file = undefined;
|
|
154
|
+
key = null;
|
|
155
|
+
await store.remove('local', FILE);
|
|
156
|
+
await store.remove('session', SESSION_KEY);
|
|
157
|
+
for (const id of await dataIndex()) await store.remove('local', DATA_PREFIX + id);
|
|
158
|
+
await store.remove('local', DATA_INDEX);
|
|
159
|
+
emit();
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Item ids grouped by kind, for Settings (no values are decrypted). */
|
|
163
|
+
export function inventory() {
|
|
164
|
+
const ids = Object.keys(file?.items ?? {});
|
|
165
|
+
return { secrets: ids.filter((i) => !i.startsWith('module/')), moduleData: ids.filter((i) => i.startsWith('module/')) };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export async function lock(reason = 'manual') {
|
|
169
|
+
key = null;
|
|
170
|
+
await store.remove('session', SESSION_KEY);
|
|
171
|
+
await store.set('session', LOCK_REASON, reason);
|
|
172
|
+
emit();
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Resolves once the vault is unlocked; shows the shared unlock prompt (ADR-042). */
|
|
176
|
+
export function whenUnlocked(): Promise<void> {
|
|
177
|
+
if (key) return Promise.resolve();
|
|
178
|
+
if (!file) return Promise.reject(new Error('Create the vault first (Settings → Getting Started).'));
|
|
179
|
+
return new Promise((resolve) => { waiters.push(resolve); unlockPrompt?.(); });
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** True if an item exists. Works while locked (presence only, nothing is decrypted). */
|
|
183
|
+
export const has = (id: string) => !!file?.items[id];
|
|
184
|
+
|
|
185
|
+
export async function get(id: string): Promise<string | undefined> {
|
|
186
|
+
await whenUnlocked();
|
|
187
|
+
const item = file!.items[id];
|
|
188
|
+
return item ? open(key!, item) : undefined;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export async function put(id: string, value: string) {
|
|
192
|
+
await whenUnlocked();
|
|
193
|
+
file!.items[id] = await seal(key!, value);
|
|
194
|
+
await store.set('local', FILE, file);
|
|
195
|
+
emit();
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export async function remove(id: string) {
|
|
199
|
+
if (!file?.items[id]) return;
|
|
200
|
+
delete file.items[id];
|
|
201
|
+
await store.set('local', FILE, file);
|
|
202
|
+
emit();
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Test helper. */
|
|
206
|
+
export function resetForTests() {
|
|
207
|
+
file = undefined; key = null; loaded = false; waiters = []; listeners.clear(); unlockPrompt = undefined;
|
|
208
|
+
}
|
package/src/env.d.ts
ADDED
package/src/index.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// @tacoshell/shell entry: the generated app entry calls boot() with the registry and the bundled module code.
|
|
2
|
+
import { createElement } from 'react';
|
|
3
|
+
import { createRoot } from 'react-dom/client';
|
|
4
|
+
import type { ViewRef } from '@tacoshell/sdk';
|
|
5
|
+
import { createFramework, navigate, setRegistry } from './core/bus.ts';
|
|
6
|
+
import * as log from './core/log.ts';
|
|
7
|
+
import { initSettings } from './core/prefs.ts';
|
|
8
|
+
import * as router from './core/router.ts';
|
|
9
|
+
import * as services from './core/services.ts';
|
|
10
|
+
import * as datasets from './core/datasets.ts';
|
|
11
|
+
import * as jobs from './core/jobs.ts';
|
|
12
|
+
import * as store from './core/storage.ts';
|
|
13
|
+
import * as vault from './core/vault.ts';
|
|
14
|
+
import { App } from './ui/App.tsx';
|
|
15
|
+
import { ShellContext, type ShellInput } from './ui/hooks.ts';
|
|
16
|
+
// Font Awesome Free (user-approved dependency): bundled with the app, so it's packaged code, not remote code (MV3).
|
|
17
|
+
// Modules use it too: <i className="fa-solid fa-wand-magic-sparkles" />.
|
|
18
|
+
import '@fortawesome/fontawesome-free/css/all.min.css';
|
|
19
|
+
import './styles.css';
|
|
20
|
+
|
|
21
|
+
export type { ShellInput } from './ui/hooks.ts';
|
|
22
|
+
export type { Registry } from './types.ts';
|
|
23
|
+
|
|
24
|
+
/** Records app input so the service worker's idle lock knows the app is in use (ADR-042). Throttled to one write per 15 s. */
|
|
25
|
+
function trackActivity() {
|
|
26
|
+
let last = 0;
|
|
27
|
+
const mark = () => {
|
|
28
|
+
const now = Date.now();
|
|
29
|
+
if (now - last < 15_000) return;
|
|
30
|
+
last = now;
|
|
31
|
+
void store.set('session', 'taco.lastActivity', now);
|
|
32
|
+
};
|
|
33
|
+
for (const ev of ['keydown', 'pointerdown', 'wheel', 'touchstart']) addEventListener(ev, mark, { passive: true });
|
|
34
|
+
mark();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function boot(input: ShellInput) {
|
|
38
|
+
document.title = input.registry.app.displayName;
|
|
39
|
+
setRegistry(input.registry);
|
|
40
|
+
await Promise.all([log.init(), vault.init(), services.init(input.registry, input.services), datasets.init(input.registry, input.routines ?? {})]);
|
|
41
|
+
await initSettings({ idleLockMinutes: input.registry.settings.vault.idleLockMinutes, visibleLevels: input.registry.settings.activityLog.visibleLevels });
|
|
42
|
+
trackActivity();
|
|
43
|
+
datasets.startScheduler((module) => createFramework(module));
|
|
44
|
+
jobs.startJobs(input.registry, input.background ?? {}, (module, view) => createFramework(module, undefined, view));
|
|
45
|
+
router.start();
|
|
46
|
+
log.add('debug', `Started ${input.registry.app.displayName} ${input.registry.app.version} (${input.registry.modules.length} module(s))`, undefined, 'framework');
|
|
47
|
+
const root = document.getElementById('root')!;
|
|
48
|
+
createRoot(root).render(createElement(ShellContext.Provider, { value: input }, createElement(App)));
|
|
49
|
+
// A notification click handed over by the service worker, now or while the app was closed (ADR-041).
|
|
50
|
+
const openFromNotification = async (open: unknown) => {
|
|
51
|
+
const o = open as { view?: ViewRef; context?: Record<string, unknown> | null } | undefined;
|
|
52
|
+
if (!o?.view) return;
|
|
53
|
+
await store.remove('session', 'taco.notifyOpen');
|
|
54
|
+
await navigate(o.view, o.context ?? undefined);
|
|
55
|
+
};
|
|
56
|
+
void store.get('session', 'taco.notifyOpen').then(openFromNotification);
|
|
57
|
+
store.onChange('session', 'taco.notifyOpen', (v) => void openFromNotification(v));
|
|
58
|
+
}
|