iPad and Screen Time helper; v2.0 roadmap
build-container / build (push) Successful in 5m57s

- Admin screen: the simple Screen Time setup, the web addresses the app needs, addresses devices were seen reaching, and a Check this device test
- Report-only Content-Security-Policy so devices report any other address a page loads (nothing is blocked)
- Pictures from other sites pass through the hub (/api/img): podcast search covers, Plex Home pictures, a VBV cover, search answers
- docs/v2-roadmap.md: the family-first 2.0 plan, with Family Chat (text only) and no photos or calls

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
nmemmertandClaude Sonnet 5.5 committed 2026-10-26 11:07:05 -04:00
1 parent 2d5aaad41a
commit 74592c25a5
14 files changed
+224 -7

No files matched your search

+2
View File
@@ -178,3 +178,5 @@ Files are kept in the data folder under `mystore/` (up to 1 GB each; extensions
- **Also:** reorder the queue with the arrows; *More like this* on an artist or song; an About note on albums and artists (Plex's own summary); **Save offline** on an album (plays with no signal); the player takes its colors from the album cover; **Share a line** in the lyrics makes a picture of the lyric over the cover; Featured shows a verse of the day when you have the Bible tab. - **Also:** reorder the queue with the arrows; *More like this* on an artist or song; an About note on albums and artists (Plex's own summary); **Save offline** on an album (plays with no signal); the player takes its colors from the album cover; **Share a line** in the lyrics makes a picture of the lyric over the cover; Featured shows a verse of the day when you have the Bible tab.
- Not included: crossfade or gapless (the player already keeps the next songs downloaded for quick changes), searching lyrics by a line, and a speaker picker. - Not included: crossfade or gapless (the player already keeps the next songs downloaded for quick changes), searching lyrics by a line, and a speaker picker.
**iPad and Screen Time:** Settings, Admin, *iPad and Screen Time* explains the simple setup (Screen Time, Content Restrictions, Web Content: **Limit Adult Websites**, and add only the hub's address under *Always Allow*), lists the web addresses the app needs (the hub, plus the document editor for the Office tab) for anyone using **Allowed Websites Only**, shows other addresses devices were actually seen reaching, and has a *Check this device* button to run on the iPad. The hub sends a report-only Content-Security-Policy (nothing is blocked) so devices report any other address a page loads, and pictures from other sites (podcast search covers, Plex Home pictures, a Verse By Verse cover, search answers) are passed through the hub (`/api/img`) so the browser only talks to the hub for them. Extensions and Sites you add may still reach their own addresses. If the document editor is put behind the same address as the hub (a reverse proxy path), even that one drops off the list.
+91
View File
@@ -0,0 +1,91 @@
# NE Hub 2.0 roadmap
A family-first hub. Status: `[ ]` planned, `[~]` in progress, `[x]` done. Size: S (a day or less), M (a few days), L (a week or more).
Decided: no photos tab, no voice or video calling (text messaging only).
## 1. Family Chat (a built-in messenger; text only)
A messenger inside the hub for the family, so family chats do not need Signal. Every hub account is a contact, and a "Family" group exists from the start. Family chats and Signal chats show in one inbox (labelled by source); people outside the family still use Signal. Messages are kept on the family's own server.
**Phase 1: the basics (L)**
- [ ] Direct chats and group chats (names, members, add and remove people)
- [ ] Text with links, emoji and line breaks
- [ ] Attachments: photos, video, files (stored on the server)
- [ ] Replies (quote), reactions
- [ ] Unread counts, search, drafts that survive closing the app
- [ ] Live delivery in the open app, push notifications in the background
- [ ] Mute and archive per chat
**Phase 2: feels like Signal (M)**
- [ ] Edit and delete for everyone
- [ ] Sent, delivered and read ticks
- [ ] Typing indicators and online presence
- [ ] Disappearing messages (a timer per chat)
- [ ] @mentions in groups, pinned messages, forward a message
**Phase 3: richer messages (M)**
- [ ] Voice notes (record and play, with a waveform)
- [ ] Link previews (fetched safely by the server)
- [ ] Polls
- [ ] GIF or sticker picker (optional)
- [ ] Share a place as a link
**Family extras (M)**
- [ ] Turn a message into a task, an event or a shopping item in one tap
- [ ] Share a song, recipe, book or podcast episode from the hub into a chat
- [ ] Pinned family announcement on Home ("dinner at 6")
- [ ] Kid accounts can only message family; parents can set quiet hours
**Privacy (decide first)**
- [ ] Open question: server-side storage on the family's own machine to start (TLS + encrypted disk), or end-to-end encryption from day one? Starting without E2EE and adding it later is much harder than choosing now.
- [ ] Per-person notification and privacy settings
Not planned: voice and video calls, stories, usernames and phone-number lookup, sealed sender.
## 2. Family core
- [ ] **Family Home (M):** one shared start page: who is around, today's family calendar, shared shopping list and chores, what everyone is listening to or reading
- [ ] **Shared lists and notes (M):** a real Notes and Lists tab the whole family edits (grocery, packing, gift ideas, house to-dos)
- [ ] **Chores and routines (M):** recurring chores per person, check-offs, optional points and a weekly summary; kids see their own
- [ ] **Family calendar (M):** a colour per person, a shared week view, birthdays from Contacts, event invitations inside the family
- [ ] **Meal planning (M):** a weekly plan from Recipes that builds the shopping list (and can flag what is already in the pantry)
- [ ] **Worship and devotion (S):** a shared daily verse, a Bible reading plan with check-ins, a family prayer list
## 3. Kids and safety
- [ ] **Kid profiles (M):** tabs limited per child, content filters (the Smashwords-style filter, Store, podcasts and music in a clean mode), screen-time limits
- [ ] **Approvals (S):** a child asks to add a book, app or extension and a parent approves
- [ ] **Simple mode (S):** a big-button layout with few tabs for young kids or grandparents
## 4. Everyday convenience
- [ ] **Search everywhere (M):** one search across mail, tasks, notes, recipes, contacts, books, songs, chats and Bible verses
- [ ] **Continue row (S):** the last audiobook, episode, book, movie and song on Home
- [ ] **Notifications center (M):** one inbox for reminders, chores, new episodes, mail and chat, with quiet hours per person
- [ ] **Tasks 2.0 (M):** projects, subtasks everywhere, due-time reminders, Today and Upcoming views
- [ ] **Mail 2.0 (L):** unified inbox, snooze, templates, attachments saved to Files
- [ ] **Contacts 2.0 (S):** anniversaries and reminders, gift ideas
## 5. Media
- [ ] **Movies & TV 2.0 (L):** mixes, favorites and stats like Music; a shared watchlist and a "movie night" vote
- [ ] **Podcast and audiobook stats (S):** listening history like Music has
- [ ] **Reading goals (S):** a family reading challenge with streaks; export notes and highlights
- [ ] **Casting (M):** pick AirPlay or Cast targets for audio
## 6. Reliability (the admin's side)
- [ ] **Browser smoke tests in CI (M):** many bugs this year showed only in the interface
- [ ] **Admin health page (S):** all good or something is down: Seafile, Plex, Mealie, mail, storage
- [ ] **Backup and restore screen (S):** one-click restore, per-person export
- [ ] **Offline mode (L):** tasks, lists, recipes, saved books and music keep working with no signal (worth it if the family travels)
- [ ] **Performance pass (S):** lazy-load the big pieces (the Bible text, the reader libraries)
- [ ] **Accessibility (M):** larger text and high-contrast settings, keyboard navigation everywhere, reduced motion
## 7. Platform (later)
- [ ] **Extensions 2.0 (L):** more hub data in the bridge (notes, music, recipes), a permissions screen, extension updates
- [ ] **Automations (L):** "when X then Y" rules (a new episode adds a task, a low pantry item adds to Shopping)
- [ ] **Themes (S):** accent colours and an AMOLED dark mode per person
## Suggested order
1. Family Chat phase 1, Family Home, Shared lists and notes, Chores
2. Kid profiles, Search everywhere, Notifications center, Family Chat phase 2
3. Meal planning, Family calendar, Family Chat phase 3 and family extras
4. Reliability items alongside everything, so each step stays safe to ship
## Done already (for reference, 1.x)
Store (books, audiobooks, radio, My Store, extensions), Recipes with a shared shopping list, Contacts, Music (Featured, Mixes, Favorites, Stats, smart and Family playlists), podcast discovery and transcript search, Smashwords with a family filter, and the sidebar and Radio fixes.
+1 -1
View File
@@ -5,7 +5,7 @@
"main": "server.js", "main": "server.js",
"scripts": { "scripts": {
"start": "node server.js", "start": "node server.js",
"test": "for t in smoke tasks push users cal plex player lyrics signal mail mail-imap files podcast abapi abdirect books store librivox radio vbv savefiles bible lrclib visualizer body transcript recipes contacts mystore caldav musicdata; do node tools/$t-test.js || exit 1; done", "test": "for t in smoke tasks push users cal plex player lyrics signal mail mail-imap files podcast abapi abdirect books store librivox radio vbv savefiles bible lrclib visualizer body transcript recipes contacts mystore caldav musicdata screentime; do node tools/$t-test.js || exit 1; done",
"audit": "npm audit --omit=dev --audit-level=high" "audit": "npm audit --omit=dev --audit-level=high"
}, },
"keywords": [], "keywords": [],
+1
View File
@@ -60,6 +60,7 @@
<script src="/file-history.js"></script> <script src="/file-history.js"></script>
<script src="/music-extras.js"></script> <script src="/music-extras.js"></script>
<script src="/music-more.js"></script> <script src="/music-more.js"></script>
<script src="/screentime-view.js"></script>
<script src="/calendar-views.js"></script> <script src="/calendar-views.js"></script>
<script src="/app.js"></script> <script src="/app.js"></script>
<script src="/search-view.js"></script> <script src="/search-view.js"></script>
+1 -1
View File
@@ -82,7 +82,7 @@ async function plexHomeBadge(st) {
} }
function plexSwitchSheet(users) { function plexSwitchSheet(users) {
const el = openSheet('Who is listening?', 'People in your Plex Home. Playlists, ratings and what you have played follow the person you pick.', const el = openSheet('Who is listening?', 'People in your Plex Home. Playlists, ratings and what you have played follow the person you pick.',
`<div class="list">${users.map((u, i) => `<button class="row" data-u="${i}"><span class="ic" style="background:var(--panel2);overflow:hidden;color:var(--text)">${u.thumb ? `<img src="${esc(u.thumb)}" alt="" referrerpolicy="no-referrer" style="width:100%;height:100%;object-fit:cover" onerror="this.remove()">` : esc([...u.title][0].toUpperCase())}</span> `<div class="list">${users.map((u, i) => `<button class="row" data-u="${i}"><span class="ic" style="background:var(--panel2);overflow:hidden;color:var(--text)">${u.thumb ? `<img src="${esc(stOk(u.thumb))}" alt="" referrerpolicy="no-referrer" style="width:100%;height:100%;object-fit:cover" onerror="this.remove()">` : esc([...u.title][0].toUpperCase())}</span>
<span class="grow"><b>${esc(u.title)}${u.current ? ' ✓' : ''}</b><small>${[u.admin ? 'Admin' : '', u.restricted ? 'Restricted' : '', u.protected ? 'PIN' : ''].filter(Boolean).join(' · ') || ' '}</small></span>${u.current ? '' : icon('chev', 'chev')}</button>`).join('')}</div> <span class="grow"><b>${esc(u.title)}${u.current ? ' ✓' : ''}</b><small>${[u.admin ? 'Admin' : '', u.restricted ? 'Restricted' : '', u.protected ? 'PIN' : ''].filter(Boolean).join(' · ') || ' '}</small></span>${u.current ? '' : icon('chev', 'chev')}</button>`).join('')}</div>
<div class="bar"><button class="btn ghost" id="sx" style="flex:1;justify-content:center">Close</button></div>`); <div class="bar"><button class="btn ghost" id="sx" style="flex:1;justify-content:center">Close</button></div>`);
el.querySelector('#sx').onclick = closeSheet; el.querySelector('#sx').onclick = closeSheet;
+1 -1
View File
@@ -65,7 +65,7 @@ async function pdHome() {
catch (e) { err.textContent = e.status === 502 || e.status === 409 || e.status === 400 ? 'Podgrab could not add that (it may already be there)' : e.message; if (btn) btn.disabled = false; } catch (e) { err.textContent = e.status === 502 || e.status === 409 || e.status === 400 ? 'Podgrab could not add that (it may already be there)' : e.message; if (btn) btn.disabled = false; }
}; };
const show = list => { const show = list => {
found = list; res.innerHTML = found.length ? found.map((f, i) => `<div class="row"><img class="art" alt="" style="width:48px;height:48px;border-radius:8px;flex:none" src="${esc(f.image || '')}" referrerpolicy="no-referrer" onerror="this.style.visibility='hidden'"><span class="grow"><b>${esc(f.title)}</b><small>${esc(f.author || '')}</small></span><button class="btn" data-i="${i}" style="min-height:36px">Add</button></div>`).join('') : '<p class="empty">Nothing found.</p>'; found = list; res.innerHTML = found.length ? found.map((f, i) => `<div class="row"><img class="art" alt="" style="width:48px;height:48px;border-radius:8px;flex:none" src="${esc(stOk(f.image))}" referrerpolicy="no-referrer" onerror="this.style.visibility='hidden'"><span class="grow"><b>${esc(f.title)}</b><small>${esc(f.author || '')}</small></span><button class="btn" data-i="${i}" style="min-height:36px">Add</button></div>`).join('') : '<p class="empty">Nothing found.</p>';
res.querySelectorAll('button[data-i]').forEach(b => b.onclick = () => add(found[b.dataset.i].feedUrl, b)); res.querySelectorAll('button[data-i]').forEach(b => b.onclick = () => add(found[b.dataset.i].feedUrl, b));
}; };
pdApi('/discover/topics').then(ts => { const box = el.querySelector('#pdtopics'); if (!box || !ts.length) return; box.innerHTML = ts.map(t => `<button class="btn ghost" data-t="${esc(t)}" style="min-height:32px;padding:0 12px">${esc(t)}</button>`).join(''); pdApi('/discover/topics').then(ts => { const box = el.querySelector('#pdtopics'); if (!box || !ts.length) return; box.innerHTML = ts.map(t => `<button class="btn ghost" data-t="${esc(t)}" style="min-height:32px;padding:0 12px">${esc(t)}</button>`).join('');
+31
View File
@@ -0,0 +1,31 @@
'use strict';
// ---- iPad and Screen Time (admin): which web addresses the app needs, the ones devices were seen reaching, and a check you run on the device itself.
const stOk = u => /^https?:\/\//i.test(u || '') ? '/api/img?u=' + encodeURIComponent(u) : (u || ''); // a picture from another site, passed through the hub so the browser only talks to the hub
async function screenTimeSheet() {
let d; try { d = await jfetch('/api/screentime'); } catch (e) { return toast(e.message); }
const row = (x, extra = '') => `<div class="row"><span class="grow"><b>${esc(x.host)}</b><small style="white-space:normal">${esc(x.why || ((x.what || []).join(', ') + ' · seen ' + x.n + (x.n === 1 ? ' time' : ' times')))}</small></span>${extra}<span class="stres" data-h="${esc(x.host)}"></span><button class="ibtn" data-c="${esc(x.host)}" aria-label="Copy ${esc(x.host)}" title="Copy">${icon('copy')}</button></div>`;
const hub = d.required[0].host;
const el = openSheet('iPad and Screen Time', 'Let the hub through Screen Time without adding each site one by one', `
<p style="margin:0 0 8px"><b>The simple way.</b> On the iPad: <b>Settings → Screen Time → Content &amp; Privacy Restrictions → Content Restrictions → Web Content</b>. Choose <b>Limit Adult Websites</b>, then under <b>Always Allow</b> tap <b>Add Website</b> and enter <b>${esc(hub)}</b>. Nothing else needs adding: the hub carries the music, books, podcasts and pictures itself.</p>
<p class="sub" style="white-space:normal">Only if you use <b>Allowed Websites Only</b> do you need to add every address below.</p>
<h2>Addresses the app needs</h2><div class="list">${d.required.map(x => row(x)).join('')}</div>
${d.seen.length ? `<h2>Others your devices reached</h2><p class="sub" style="white-space:normal">Seen while people used the app (a podcast cover, a weather extension, a site you added). Add only what you want available.</p><div class="list">${d.seen.map(x => row(x)).join('')}</div>` : '<p class="sub" style="white-space:normal">No other addresses have been seen yet. Use the app for a day on the iPad and any others will show up here.</p>'}
<h2>Only sometimes</h2><div class="list">${d.optional.map(x => row(x)).join('')}</div>
<div class="bar"><button class="btn ghost" id="stcopy" style="flex:1;justify-content:center">Copy the list</button><button class="btn" id="stchk" style="flex:1;justify-content:center">Check this device</button></div>
<p class="sub" style="white-space:normal">“Check this device” tries each address from the device you are on, and shows which ones Screen Time (or the network) is blocking. Run it on the iPad.</p>
${d.seen.length ? '<div class="bar"><button class="btn ghost" id="stclr">Clear the seen list</button></div>' : ''}`);
el.querySelector('.sheet').classList.add('wide');
el.querySelectorAll('[data-c]').forEach(b => b.onclick = () => { navigator.clipboard.writeText(b.dataset.c).then(() => toast('Copied ' + b.dataset.c), () => toast(b.dataset.c)); });
const all = [...d.required, ...d.seen, ...d.optional].map(x => x.host);
el.querySelector('#stcopy').onclick = () => navigator.clipboard.writeText(all.join('\n')).then(() => toast('Copied ' + all.length + ' addresses'), () => toast('Could not copy'));
el.querySelector('#stchk').onclick = async e => {
const b = e.currentTarget; b.disabled = true; b.textContent = 'Checking…';
await Promise.all(all.map(async h => {
const mark = el.querySelector(`.stres[data-h="${CSS.escape(h)}"]`); if (!mark) return;
try { await fetch(h === location.hostname ? '/manifest.webmanifest' : 'https://' + h + '/', { mode: 'no-cors', cache: 'no-store', signal: AbortSignal.timeout(8000) }); mark.textContent = ' ✓'; mark.style.color = 'var(--accent)'; mark.title = 'Reachable'; }
catch { mark.textContent = ' ✗'; mark.style.color = 'var(--danger)'; mark.title = 'Blocked or not reachable from this device'; }
}));
b.disabled = false; b.textContent = 'Check again';
};
if (el.querySelector('#stclr')) el.querySelector('#stclr').onclick = async () => { try { await jfetch('/api/screentime', { method: 'DELETE' }); closeSheet(); toast('Cleared'); } catch (x) { toast(x.message); } };
}
+1 -1
View File
@@ -107,7 +107,7 @@ function viewSearch() {
const mailHtml = (mailR.status === 'fulfilled' ? mailR.value.items || [] : []).slice(0, 8).map(m => `<a class="row" href="#/mail/m/${enc(m.id)}"><span class="ic" style="background:#d4392f">${icon('mail')}</span><span class="grow"><b>${esc(m.subject)}</b><small>${esc((m.from && (m.from.name || m.from.address)) || '')} · ${esc(new Date(m.date).toLocaleDateString())}</small></span></a>`).join(''); const mailHtml = (mailR.status === 'fulfilled' ? mailR.value.items || [] : []).slice(0, 8).map(m => `<a class="row" href="#/mail/m/${enc(m.id)}"><span class="ic" style="background:#d4392f">${icon('mail')}</span><span class="grow"><b>${esc(m.subject)}</b><small>${esc((m.from && (m.from.name || m.from.address)) || '')} · ${esc(new Date(m.date).toLocaleDateString())}</small></span></a>`).join('');
const d = ddg.status === 'fulfilled' ? ddg.value : {}; const d = ddg.status === 'fulfilled' ? ddg.value : {};
const card = (d.text || d.answer) ? `<div class="card2" style="padding:14px;margin-top:14px;display:flex;gap:12px;align-items:flex-start"> const card = (d.text || d.answer) ? `<div class="card2" style="padding:14px;margin-top:14px;display:flex;gap:12px;align-items:flex-start">
${d.image ? `<img alt="" src="${esc(d.image)}" referrerpolicy="no-referrer" style="width:72px;height:72px;object-fit:cover;border-radius:10px;flex:none">` : ''} ${d.image ? `<img alt="" src="${esc(stOk(d.image))}" referrerpolicy="no-referrer" style="width:72px;height:72px;object-fit:cover;border-radius:10px;flex:none">` : ''}
<div style="min-width:0"><small style="color:var(--muted)">From DuckDuckGo${d.source ? ' · ' + esc(d.source) : ''}</small> <div style="min-width:0"><small style="color:var(--muted)">From DuckDuckGo${d.source ? ' · ' + esc(d.source) : ''}</small>
${d.heading ? `<div style="font-weight:700;margin-top:2px">${esc(d.heading)}</div>` : ''}${d.answer ? `<div style="font-size:18px;margin-top:2px">${esc(d.answer)}</div>` : ''} ${d.heading ? `<div style="font-weight:700;margin-top:2px">${esc(d.heading)}</div>` : ''}${d.answer ? `<div style="font-size:18px;margin-top:2px">${esc(d.answer)}</div>` : ''}
${d.text ? `<p style="margin:4px 0 0;font-size:14px">${esc(d.text)}</p>` : ''}${d.url ? `<a href="${esc(d.url)}" target="_blank" rel="noopener" style="color:var(--accent);font-size:14px">Read more</a>` : ''}</div></div>` : ''; ${d.text ? `<p style="margin:4px 0 0;font-size:14px">${esc(d.text)}</p>` : ''}${d.url ? `<a href="${esc(d.url)}" target="_blank" rel="noopener" style="color:var(--accent);font-size:14px">Read more</a>` : ''}</div></div>` : '';
+2 -1
View File
@@ -95,6 +95,7 @@ function viewSettings() {
<div class="bar"><button class="btn" id="addperson">Add a person</button></div> <div class="bar"><button class="btn" id="addperson">Add a person</button></div>
<h2>Health</h2><div class="list" id="health"><div class="row"><span class="grow"><small>Checking…</small></span></div></div> <h2>Health</h2><div class="list" id="health"><div class="row"><span class="grow"><small>Checking…</small></span></div></div>
<h2>Storage</h2><div class="list" id="stor"><div class="row"><span class="grow"><small>Checking…</small></span></div></div> <h2>Storage</h2><div class="list" id="stor"><div class="row"><span class="grow"><small>Checking…</small></span></div></div>
<h2>iPad and Screen Time</h2><p class="sub" style="white-space:normal">Allow the hub on an iPad with Screen Time web limits, without adding every site one by one.</p><div class="bar"><button class="btn ghost" id="stbtn">Set up Screen Time</button></div>
<div class="bar"><a class="btn ghost" href="/api/backup" download>Download a backup</a></div><p class="sub">A .tar.gz of everything in /data (accounts, passkeys, tasks, events, settings, Signal history). Keep it private: it holds the session secret and encrypted sign-in tokens. Restore by unpacking it into the data volume.</p>` : ''} <div class="bar"><a class="btn ghost" href="/api/backup" download>Download a backup</a></div><p class="sub">A .tar.gz of everything in /data (accounts, passkeys, tasks, events, settings, Signal history). Keep it private: it holds the session secret and encrypted sign-in tokens. Restore by unpacking it into the data volume.</p>` : ''}
${isAdmin ? `<h2>Activity</h2><div class="list" id="audit"><div class="row"><span class="grow"><small>Loading…</small></span></div></div>` : ''} ${isAdmin ? `<h2>Activity</h2><div class="list" id="audit"><div class="row"><span class="grow"><small>Loading…</small></span></div></div>` : ''}
</div></div>`; </div></div>`;
@@ -130,7 +131,7 @@ function viewSettings() {
if (st.signedIn) { const b = $('#plexout'); b.hidden = false; b.onclick = async () => { await jfetch('/api/plex/logout', { method: 'POST' }); pl.a.pause(); pl.q = []; pl.i = -1; renderMini(); toast('Signed out of Plex'); viewSettings(); }; } if (st.signedIn) { const b = $('#plexout'); b.hidden = false; b.onclick = async () => { await jfetch('/api/plex/logout', { method: 'POST' }); pl.a.pause(); pl.q = []; pl.i = -1; renderMini(); toast('Signed out of Plex'); viewSettings(); }; }
}).catch(() => { const el = $('#plexst'); if (el) el.textContent = 'Unavailable'; }); }).catch(() => { const el = $('#plexst'); if (el) el.textContent = 'Unavailable'; });
const lk = $('#lookups'); if (lk) { lk.checked = store.get('lookups', true) !== false; lk.onchange = () => { store.set('lookups', lk.checked); toast(lk.checked ? 'Lookups on' : 'Lookups off'); }; } const lk = $('#lookups'); if (lk) { lk.checked = store.get('lookups', true) !== false; lk.onchange = () => { store.set('lookups', lk.checked); toast(lk.checked ? 'Lookups on' : 'Lookups off'); }; }
if (isAdmin) { loadPeople(); $('#addperson').onclick = () => addPersonSheet(); } if (isAdmin) { loadPeople(); $('#addperson').onclick = () => addPersonSheet(); $('#stbtn').onclick = () => screenTimeSheet(); }
if (isAdmin) jfetch('/api/health').then(h => { if (isAdmin) jfetch('/api/health').then(h => {
const row = (t, d, bad) => `<div class="row"><span class="grow"><b>${bad ? '⚠ ' : '✓ '}${t}</b><small style="white-space:normal;${bad ? 'color:var(--danger)' : ''}">${d}</small></span></div>`; const row = (t, d, bad) => `<div class="row"><span class="grow"><b>${bad ? '⚠ ' : '✓ '}${t}</b><small style="white-space:normal;${bad ? 'color:var(--danger)' : ''}">${d}</small></span></div>`;
const gb = n => (n / 1e9).toFixed(1) + ' GB', days = t => Math.floor((Date.now() - t) / 864e5); const gb = n => (n / 1e9).toFixed(1) + ' GB', days = t => Math.floor((Date.now() - t) / 864e5);
+1 -1
View File
@@ -1,5 +1,5 @@
// App-shell cache only; Seafile/API traffic always goes to the network. // App-shell cache only; Seafile/API traffic always goes to the network.
const CACHE = 'hub-v57'; const CACHE = 'hub-v58';
const SHARE = 'hub-share'; // files shared into the app from other apps, held until the person picks a folder const SHARE = 'hub-share'; // files shared into the app from other apps, held until the person picks a folder
const SHELL = ['/icon.svg', '/manifest.webmanifest', '/icons/icon-192.png', '/icons/apple-touch-icon.png']; const SHELL = ['/icon.svg', '/manifest.webmanifest', '/icons/icon-192.png', '/icons/apple-touch-icon.png'];
+1 -1
View File
@@ -17,7 +17,7 @@ pl.a.addEventListener('pause', () => vbSave()); pl.a.addEventListener('ended', (
const vbLeft = key => { const p = vbProg[key]; return p && p.pos > 10 && p.dur && p.pos < p.dur - 30 ? p : null; }; const vbLeft = key => { const p = vbProg[key]; return p && p.pos > 10 && p.dur && p.pos < p.dur - 30 ? p : null; };
const vbDone = key => { const p = vbProg[key]; return !!(p && p.dur && p.pos >= p.dur - 30); }; const vbDone = key => { const p = vbProg[key]; return !!(p && p.dur && p.pos >= p.dur - 30); };
const vbDate = d => { const t = Date.parse(d); return t > 0 ? new Date(t).toLocaleDateString([], { month: 'short', day: 'numeric', year: 'numeric' }) : ''; }; const vbDate = d => { const t = Date.parse(d); return t > 0 ? new Date(t).toLocaleDateString([], { month: 'short', day: 'numeric', year: 'numeric' }) : ''; };
const vbCover = (s, big) => `<span class="vimg" style="aspect-ratio:1/1;background:var(--panel2)"><img loading="lazy" alt="" referrerpolicy="no-referrer" src="${esc(s.cover || '')}" onerror="this.remove()"></span>`; const vbCover = (s, big) => `<span class="vimg" style="aspect-ratio:1/1;background:var(--panel2)"><img loading="lazy" alt="" referrerpolicy="no-referrer" src="${esc(stOk(s.cover))}" onerror="this.remove()"></span>`;
async function viewVbv(args = []) { async function viewVbv(args = []) {
const v = $('#view'); v.innerHTML = '<div class="wrap"><h1>Verse By Verse</h1><p class="empty">Loading…</p></div>'; const v = $('#view'); v.innerHTML = '<div class="wrap"><h1>Verse By Verse</h1><p class="empty">Loading…</p></div>';
+64
View File
@@ -0,0 +1,64 @@
// Helping an iPad on Screen Time "Allowed Websites Only": the app should need as few web addresses as possible, and an admin should be able to see exactly which ones.
// 1. The server sends a report-only Content-Security-Policy that says "only this site"; the browser reports every other address a page tries to load (nothing is blocked),
// and those are kept here, so the list comes from real use on the family's devices.
// 2. /api/img passes a picture from another site through the hub, so the browser only ever talks to the hub for it.
const fs = require('fs'), path = require('path');
const atomicWrite = require('./atomic');
const cal = require('./cal');
const { readBody } = require('./body');
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data'), FILE = () => path.join(DATA_DIR, 'hosts-seen.json');
const MAX_HOSTS = 300, MAX_IMG = 3 * 1024 * 1024;
const json = (res, code, o) => { res.writeHead(code, { 'content-type': 'application/json', 'cache-control': 'no-store' }); res.end(JSON.stringify(o)); };
const load = () => { try { const j = JSON.parse(fs.readFileSync(FILE(), 'utf8')); return j && typeof j === 'object' ? j : {}; } catch { return {}; } };
const save = o => atomicWrite(FILE(), JSON.stringify(o), { mode: 0o600 });
const ooHost = () => { try { return new URL(process.env.ONLYOFFICE_URL || 'https://onlyoffice.necloud.us').host; } catch { return ''; } };
/** The report-only policy: only this site (and the document editor's), for everything the browser loads from the network. */
function policy() {
const oo = (() => { try { return new URL(process.env.ONLYOFFICE_URL || 'https://onlyoffice.necloud.us').origin; } catch { return ''; } })();
return `default-src 'self' data: blob:; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: ${oo}; style-src 'self' 'unsafe-inline' ${oo}; img-src 'self' data: blob:; media-src 'self' data: blob:; connect-src 'self' blob: data:; font-src 'self' data:; frame-src 'self' blob: data: ${oo}; worker-src 'self' blob:; report-uri /api/csp-report`;
}
/** A browser's report of one address a page loaded from outside: kept as host -> { n, first, last, what }. */
function record(body, hubHost) {
let r; try { r = JSON.parse(body)['csp-report']; } catch { return; } if (!r) return;
let u; try { u = new URL(String(r['blocked-uri'] || r['blockedURI'] || '')); } catch { return; }
if (!/^https?:$/.test(u.protocol) || u.host === hubHost || /^(localhost|127\.|\[::1\])/.test(u.hostname)) return;
const db = load(), what = String(r['effective-directive'] || r['violated-directive'] || '').split(/\s/)[0].replace(/-src$/, '') || 'other', now = Date.now(), e = db[u.hostname];
if (e) { e.n++; e.last = now; if (!e.what.includes(what)) e.what.push(what); } else if (Object.keys(db).length < MAX_HOSTS) db[u.hostname] = { n: 1, first: now, last: now, what: [what] }; else return;
save(db);
}
function overview(req) {
const hub = req.headers['x-forwarded-host'] || req.headers.host || '', required = [{ host: hub.split(':')[0], why: 'The hub itself. Almost everything the app needs goes through it.' }];
if (ooHost() && ooHost() !== hub) required.push({ host: ooHost(), why: 'The document editor (the Office tab).' });
const seen = Object.entries(load()).filter(([h]) => !required.some(r => r.host === h)).map(([host, v]) => ({ host, ...v })).sort((a, b) => b.n - a.n);
const optional = [{ host: 'plex.tv', why: 'Only the first time, to sign in to Plex (a link that opens in the browser).' }];
return { required, optional, seen };
}
async function image(req, res, u) {
let url; try { url = new URL(u.searchParams.get('u') || ''); } catch { return json(res, 400, { error: 'Bad address' }); }
try {
let r; for (let hop = 0; hop < 4; hop++) {
await cal.assertPublic(url);
r = await fetch(url, { headers: { 'user-agent': 'NE-Hub/1.0', accept: 'image/*' }, redirect: 'manual', signal: AbortSignal.timeout(10000) });
if ([301, 302, 303, 307, 308].includes(r.status) && r.headers.get('location')) { url = new URL(r.headers.get('location'), url); try { await r.body?.cancel(); } catch {} continue; } break;
}
const type = (r.headers.get('content-type') || '').split(';')[0].trim().toLowerCase();
if (!r.ok || !/^image\/(jpeg|png|gif|webp)$/.test(type)) return json(res, 404, { error: 'Not a picture' });
if ((+r.headers.get('content-length') || 0) > MAX_IMG) return json(res, 413, { error: 'Too large' });
const chunks = []; let n = 0; for await (const c of r.body) { n += c.length; if (n > MAX_IMG) return json(res, 413, { error: 'Too large' }); chunks.push(c); }
res.writeHead(200, { 'content-type': type, 'cache-control': 'private, max-age=604800', 'x-content-type-options': 'nosniff' }); return res.end(Buffer.concat(chunks));
} catch { return json(res, 502, { error: 'Could not get that picture' }); }
}
async function handle(req, res, me) {
const u = new URL(req.url, 'http://x');
if (u.pathname === '/api/csp-report' && req.method === 'POST') { try { record(await readBody(req, 2e4), req.headers['x-forwarded-host'] || req.headers.host); } catch {} res.writeHead(204); return res.end(); }
if (u.pathname === '/api/img' && req.method === 'GET') return image(req, res, u);
if (u.pathname === '/api/screentime') {
if (!me || me.role !== 'admin') return json(res, 403, { error: 'Only an admin can see this' });
if (req.method === 'DELETE') { save({}); return json(res, 200, overview(req)); }
if (req.method === 'GET') return json(res, 200, overview(req));
}
return json(res, 404, { error: 'Not found' });
}
module.exports = { handle, policy, record, overview };
+3
View File
@@ -43,6 +43,7 @@ const savefiles = require('./savefiles'); // "Save to Files": copy books, lesson
const vbv = require('./vbv'); // Verse By Verse Ministry teaching (free Bible studies) const vbv = require('./vbv'); // Verse By Verse Ministry teaching (free Bible studies)
const recipes = require('./recipes'); // recipes and the shopping list, from Mealie (MEALIE_URL, MEALIE_TOKEN) const recipes = require('./recipes'); // recipes and the shopping list, from Mealie (MEALIE_URL, MEALIE_TOKEN)
const contacts = require('./contacts'); // each person's address book (mail suggestions, calendar birthdays, vCard import and export) const contacts = require('./contacts'); // each person's address book (mail suggestions, calendar birthdays, vCard import and export)
const screentime = require('./screentime'); // fewer web addresses for iPad Screen Time: a report-only policy, the list of what devices reached, and a picture pass-through
const musicdata = require('./musicdata'); // what was played, favorites, smart and Family playlists for Music const musicdata = require('./musicdata'); // what was played, favorites, smart and Family playlists for Music
const mystore = require('./mystore'); // My Store: your own books, music, apps and extensions for everyone to use const mystore = require('./mystore'); // My Store: your own books, music, apps and extensions for everyone to use
const radio = require('./radio'); // internet radio (Radio Browser directory, The Journey FM) const radio = require('./radio'); // internet radio (Radio Browser directory, The Journey FM)
@@ -575,6 +576,7 @@ function securityHeaders(res) {
res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Referrer-Policy', 'same-origin'); res.setHeader('Referrer-Policy', 'same-origin');
res.setHeader('Content-Security-Policy', "frame-ancestors 'self'; base-uri 'self'; object-src 'none'; form-action 'self'"); res.setHeader('Content-Security-Policy', "frame-ancestors 'self'; base-uri 'self'; object-src 'none'; form-action 'self'");
res.setHeader('Content-Security-Policy-Report-Only', screentime.policy()); // (reports only: nothing is blocked)
res.setHeader('Permissions-Policy', 'camera=(), geolocation=(), payment=()'); res.setHeader('Permissions-Policy', 'camera=(), geolocation=(), payment=()');
if (process.env.PUBLIC_URL && process.env.PUBLIC_URL.startsWith('https://')) res.setHeader('Strict-Transport-Security', 'max-age=15552000'); if (process.env.PUBLIC_URL && process.env.PUBLIC_URL.startsWith('https://')) res.setHeader('Strict-Transport-Security', 'max-age=15552000');
} }
@@ -654,6 +656,7 @@ async function handleRequest(req, res) {
if (pathname.startsWith('/api/podcast/')) return podcast.handle(req, res); if (pathname.startsWith('/api/podcast/')) return podcast.handle(req, res);
if (pathname.startsWith('/api/read/')) return books.handle(req, res); if (pathname.startsWith('/api/read/')) return books.handle(req, res);
if (pathname.startsWith('/api/radio/')) return radio.handle(req, res); if (pathname.startsWith('/api/radio/')) return radio.handle(req, res);
if (pathname === '/api/csp-report' || pathname === '/api/img' || pathname === '/api/screentime') return screentime.handle(req, res, user);
if (pathname.startsWith('/api/music/')) return musicdata.handle(req, res); if (pathname.startsWith('/api/music/')) return musicdata.handle(req, res);
if (pathname === '/api/store/my' || pathname.startsWith('/api/store/my/')) return mystore.handle(req, res); if (pathname === '/api/store/my' || pathname.startsWith('/api/store/my/')) return mystore.handle(req, res);
if (pathname === '/api/recipes' || pathname.startsWith('/api/recipes/')) return recipes.handle(req, res); if (pathname === '/api/recipes' || pathname.startsWith('/api/recipes/')) return recipes.handle(req, res);
+24
View File
@@ -0,0 +1,24 @@
// Screen Time helper: the report-only policy, what devices report reaching, the admin overview, and the picture pass-through refusing what it should.
const http = require('http'), assert = require('assert'), fs = require('fs'), os = require('os'), path = require('path');
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'nehub-st-')); process.env.ONLYOFFICE_URL = 'https://docs.example.org';
const users = require('../users'), st = require('../screentime');
const people = { a: users.create({ name: 'Ann', role: 'admin', handle: 'YQ' }), b: users.create({ name: 'Bob', role: 'user', handle: 'Yg' }) };
const rep = (uri, dir = 'img-src') => JSON.stringify({ 'csp-report': { 'blocked-uri': uri, 'effective-directive': dir, 'violated-directive': dir + " 'self'" } });
const hub = http.createServer((req, res) => { const me = req.headers['x-user'] === 'b' ? people.b : people.a; users.runAs(me, () => st.handle(req, res, me)); }).listen(0, async () => {
const port = hub.address().port, B = 'http://127.0.0.1:' + port, call = (p, o = {}) => fetch(B + p, { ...o, headers: { 'x-forwarded-host': 'hub.example.org', ...(o.headers || {}) } });
try {
const pol = st.policy(); assert.match(pol, /report-uri \/api\/csp-report/); assert.match(pol, /frame-src[^;]*https:\/\/docs\.example\.org/, 'the document editor is allowed'); assert.match(pol, /img-src 'self' data: blob:;/, 'pictures only from the hub');
for (const [u, d] of [['https://is1-ssl.mzstatic.com/a.jpg', 'img-src'], ['https://is1-ssl.mzstatic.com/b.jpg', 'img-src'], ['https://api.open-meteo.com/v1/forecast?x=1', 'connect-src'], ['inline', 'script-src'], ['data', 'img-src'], ['https://hub.example.org/x.png', 'img-src'], ['http://localhost:3000/x', 'img-src']]) assert.equal((await call('/api/csp-report', { method: 'POST', body: rep(u, d) })).status, 204);
assert.equal((await call('/api/csp-report', { method: 'POST', body: 'not json' })).status, 204, 'a garbled report is ignored, not an error');
let o = await (await call('/api/screentime')).json();
assert.equal(o.required[0].host, 'hub.example.org'); assert.deepEqual(o.required.map(x => x.host), ['hub.example.org', 'docs.example.org'], 'the hub and the editor');
assert.deepEqual(o.seen.map(x => [x.host, x.n]), [['is1-ssl.mzstatic.com', 2], ['api.open-meteo.com', 1]], 'outside addresses are counted; the hub itself, local addresses and non-addresses are left out'); assert.deepEqual(o.seen[1].what, ['connect']);
assert.equal((await call('/api/screentime', { headers: { 'x-user': 'b' } })).status, 403, 'only an admin sees the list');
o = await (await call('/api/screentime', { method: 'DELETE' })).json(); assert.deepEqual(o.seen, []);
// pictures from other sites
assert.equal((await call('/api/img?u=notaurl')).status, 400); assert.equal((await call('/api/img?u=' + encodeURIComponent('http://example.com/a.png'))).status, 502, 'only https');
assert.equal((await call('/api/img?u=' + encodeURIComponent('https://127.0.0.1/a.png'))).status, 502, 'never a private address'); assert.equal((await call('/api/img?u=' + encodeURIComponent('https://localhost/a.png'))).status, 502);
console.log('screentime ok');
} catch (e) { console.error(e); process.exitCode = 1; }
hub.close(); setTimeout(() => process.exit(process.exitCode || 0), 50);
});