Extensions: hub bridge for tasks, contacts and calendar (asked of the person once), Sites in My Store, and four example extensions

- hub.tasks / hub.contacts / hub.calendar in the extension sandbox; each kind of access is approved by the person and remembered per extension
- My Store: Sites kind (any web link, optionally shown inside the hub)
- Examples: notes and checklists, habit tracker, kitchen converter and scaler, weather and verse of the day

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
nmemmertandClaude Sonnet 5.5 committed 2026-10-26 09:25:39 -04:00
1 parent f292294ad7
commit efd17f4263
8 files changed
+204 -18

No files matched your search

+2 -1
View File
@@ -159,7 +159,8 @@ One **Store** tab (turn it on per person) with sections for **Books** (the free
- **Books** (EPUB, PDF, MOBI, AZW3, DOCX): *Add to my library* puts a copy on that person's shelf, or download it.
- **Music** (MP3, M4A, AAC, FLAC, OGG, OPUS, WAV): an album can have many tracks; they play in the hub's player and can be downloaded.
- **Apps**: any files to download (an APK, an installer...), with an optional link and version. The hub does not run them.
- **Extensions**: one self-contained `.html` file that adds a feature to the hub. A person installs it from My Store and it opens inside the Store. It runs in a sandbox with no access to the hub's sign-in or data (and `connect-src https:` only), and talks to the hub through a small `hub` object: `hub.storage.get/set/all/remove` (its own settings for that person, up to 256 KB), `hub.user()` (the person's name), `hub.toast(text)` and `hub.open(url)`. See `docs/extensions/notepad.html` for a complete example.
- **Sites**: any website as a card. It opens in a new tab, or inside the hub if you tick *Open inside the hub* (some sites refuse to be shown that way).
- **Extensions**: one self-contained `.html` file that adds a feature to the hub. A person installs it from My Store and it opens inside the Store. It runs in a sandbox with no access to the hub's sign-in or data (and `connect-src https:` only), and talks to the hub through a small `hub` object: `hub.storage.get/set/all/remove` (its own settings for that person, up to 256 KB), `hub.user()` (the person's name), `hub.toast(text)` and `hub.open(url)`. It can also ask for hub data, which the person approves the first time (and which is forgotten when the extension is removed): `hub.tasks.lists() / list(listId) / add({ title, notes, due, list }) / complete(listId, taskId)`, `hub.contacts.list() / add({ name, email, phone, org })` and `hub.calendar.events(from, to) / add({ title, start, end, allDay })` (dates as `YYYY-MM-DD`, times as `YYYY-MM-DDTHH:MM`). A refused request rejects with an error. Ready-made examples are in `docs/extensions/`: **notes.html** (notes and checklists, can send items to Tasks), **tracker.html** (habit and Bible-reading streaks), **kitchen.html** (unit converter and recipe scaler that can add to your Shopping list), **weather.html** (forecast plus a verse of the day) and **notepad.html** (the smallest one).
Files are kept in the data folder under `mystore/` (up to 1 GB each; extensions up to 2 MB). Only an admin can add, change or delete items.
+32
View File
@@ -0,0 +1,32 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kitchen</title>
<style>
:root{--bg:#fff;--fg:#1b1e24;--mut:#6b7280;--line:#e0e3e9;--acc:#e0742b;--card:#f4f5f8}@media(prefers-color-scheme:dark){:root{--bg:#181b21;--fg:#eceef2;--mut:#8b93a3;--line:#2a2f38;--acc:#f0883e;--card:#20242c}}
*{box-sizing:border-box}body{margin:0;padding:14px;font:15px system-ui,sans-serif;background:var(--bg);color:var(--fg);max-width:720px}h2{margin:18px 0 8px}h2:first-child{margin-top:0}
input,select,textarea,button{font:inherit;color:inherit;background:var(--card);border:1px solid var(--line);border-radius:8px;padding:8px}button{cursor:pointer}button.p{background:var(--acc);color:#fff;border-color:var(--acc)}
.r{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin:6px 0}textarea{width:100%;height:150px}pre{background:var(--card);border-radius:8px;padding:10px;white-space:pre-wrap;margin:8px 0}.m{color:var(--mut);font-size:13px}
</style></head><body>
<h2>Convert</h2>
<div class="r"><input id="v" type="number" step="any" value="1" style="width:110px"><select id="from"></select><span>to</span><select id="to"></select></div><div id="out" style="font-size:22px;font-weight:600"></div>
<h2>Scale a recipe</h2>
<div class="r"><span>From</span><input id="a" type="number" min="1" value="4" style="width:70px"><span>servings to</span><input id="b" type="number" min="1" value="6" style="width:70px"></div>
<textarea id="t" placeholder="Paste ingredients, one per line&#10;2 cups flour&#10;1 1/2 tsp salt&#10;3/4 cup sugar"></textarea>
<div class="r"><button class="p" id="go">Scale</button><button id="sl" disabled>Add to my Shopping list</button></div><pre id="res" hidden></pre><div class="m" id="msg"></div>
<script>
var U={cup:['Volume',236.588],tbsp:['Volume',14.787],tsp:['Volume',4.929],ml:['Volume',1],l:['Volume',1000],'fl oz':['Volume',29.574],pint:['Volume',473.176],quart:['Volume',946.353],
g:['Weight',1],kg:['Weight',1000],oz:['Weight',28.3495],lb:['Weight',453.592]};
var opts=Object.keys(U).map(function(k){return '<option>'+k+'</option>'}).join('')+'<option>F</option><option>C</option>';
from.innerHTML=opts;to.innerHTML=opts;from.value='cup';to.value='ml';
function conv(){var x=parseFloat(v.value),f=from.value,t=to.value,o;if(isNaN(x)){out.textContent='';return}
if((f==='F'||f==='C')&&(t==='F'||t==='C'))o=f===t?x:f==='F'?(x-32)*5/9:x*9/5+32;
else if(U[f]&&U[t]&&U[f][0]===U[t][0])o=x*U[f][1]/U[t][1];else{out.textContent='Cannot convert '+(U[f]?U[f][0]:'temperature')+' to '+(U[t]?U[t][0]:'temperature').toLowerCase();return}
out.textContent=x+' '+f+' = '+(Math.round(o*100)/100)+' '+t}
[v,from,to].forEach(function(e){e.oninput=conv});conv();
var FR={'½':.5,'¼':.25,'¾':.75,'⅓':1/3,'⅔':2/3,'⅛':.125};
function num(s){s=s.trim();var m;if((m=/^(\d+)\s+(\d+)\/(\d+)$/.exec(s)))return +m[1]+m[2]/m[3];if((m=/^(\d+)\/(\d+)$/.exec(s)))return m[1]/m[2];if((m=/^(\d*)\s*([½¼¾⅓⅔⅛])$/.exec(s)))return (+m[1]||0)+FR[m[2]];return /^\d*\.?\d+$/.test(s)?parseFloat(s):null}
function show(n){var w=Math.floor(n+1e-9),f=n-w,names=[[0,''],[.125,'1/8'],[.25,'1/4'],[1/3,'1/3'],[.5,'1/2'],[2/3,'2/3'],[.75,'3/4'],[1,'']],best=names[0];names.forEach(function(c){if(Math.abs(c[0]-f)<Math.abs(best[0]-f))best=c});
if(Math.abs(best[0]-f)>0.04)return String(Math.round(n*100)/100);if(best[0]===1){w++;best=names[0]}return (w?w+(best[1]?' ':''):'')+best[1]||'0'}
var lines=[];
go.onclick=function(){var k=(+b.value)/(+a.value);if(!(k>0))return;lines=t.value.split('\n').map(function(l){return l.trim()}).filter(Boolean).map(function(l){var m=/^((?:\d+\s+)?\d+\/\d+|\d*\s*[½¼¾⅓⅔⅛]|\d*\.?\d+)(.*)$/.exec(l);if(!m)return l;var n=num(m[1]);return n==null?l:show(n*k)+m[2]});
res.hidden=false;res.textContent=lines.join('\n');sl.disabled=!lines.length;msg.textContent='Scaled by '+(Math.round(k*100)/100)+'x'};
sl.onclick=function(){sl.disabled=true;(function next(i){if(i>=lines.length){hub.toast('Added '+lines.length+' items to Shopping');sl.disabled=false;return}hub.tasks.add({list:'Shopping',title:lines[i]}).then(function(){next(i+1)},function(e){hub.toast(e.message);sl.disabled=false})})(0)};
</script></body></html>
+42
View File
@@ -0,0 +1,42 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Notes</title>
<style>
:root{--bg:#fff;--fg:#1b1e24;--mut:#6b7280;--line:#e0e3e9;--acc:#3d6bf0;--card:#f4f5f8}@media(prefers-color-scheme:dark){:root{--bg:#181b21;--fg:#eceef2;--mut:#8b93a3;--line:#2a2f38;--acc:#6a8cff;--card:#20242c}}
*{box-sizing:border-box}body{margin:0;font:15px system-ui,sans-serif;background:var(--bg);color:var(--fg);display:flex;height:100vh}
#side{width:240px;border-right:1px solid var(--line);display:flex;flex-direction:column}#side header{padding:10px;display:flex;gap:6px}
input,textarea,button{font:inherit;color:inherit;background:var(--card);border:1px solid var(--line);border-radius:8px;padding:8px}button{cursor:pointer}button.p{background:var(--acc);color:#fff;border-color:var(--acc)}
#list{overflow:auto;flex:1}.n{padding:10px 12px;border-bottom:1px solid var(--line);cursor:pointer}.n.on{background:var(--card)}.n b{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.n small{color:var(--mut)}
#main{flex:1;padding:12px;overflow:auto;min-width:0}#t{width:100%;font-size:20px;font-weight:600;margin-bottom:8px}#b{width:100%;height:60vh}
.it{display:flex;gap:8px;align-items:center;margin:4px 0}.it input[type=text]{flex:1}.it.d input[type=text]{text-decoration:line-through;color:var(--mut)}.bar{display:flex;gap:6px;margin:8px 0;flex-wrap:wrap}
@media(max-width:560px){body{flex-direction:column}#side{width:100%;height:38vh;border-right:0;border-bottom:1px solid var(--line)}}
</style></head><body>
<div id="side"><header><input id="q" placeholder="Search" style="flex:1;min-width:0"><button class="p" id="nn" title="New note">+ Note</button><button id="nl" title="New checklist">+ List</button></header><div id="list"></div></div>
<div id="main"><p style="color:var(--mut)">Pick a note, or make a new one.</p></div>
<script>
var notes=[],cur=null,q='',timer;
function id(){return Math.random().toString(36).slice(2,10)}
function save(){clearTimeout(timer);timer=setTimeout(function(){hub.storage.set('notes',notes)},400)}
function esc(s){return String(s).replace(/[&<>"]/g,function(c){return{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]})}
function drawList(){var l=notes.filter(function(n){var t=(n.title+' '+(n.body||'')+' '+(n.items||[]).map(function(i){return i.t}).join(' ')).toLowerCase();return !q||t.indexOf(q)>=0}).sort(function(a,b){return b.updated-a.updated});
document.getElementById('list').innerHTML=l.map(function(n){var sub=n.type==='list'?(n.items.filter(function(i){return i.done}).length+' of '+n.items.length+' done'):(n.body||'').slice(0,40);return '<div class="n'+(cur&&cur.id===n.id?' on':'')+'" data-i="'+n.id+'"><b>'+esc(n.title||'Untitled')+'</b><small>'+esc(sub)+'</small></div>'}).join('')||'<p style="padding:12px;color:var(--mut)">No notes.</p>';
[].forEach.call(document.querySelectorAll('.n'),function(e){e.onclick=function(){cur=notes.filter(function(n){return n.id===e.dataset.i})[0];drawList();drawMain()}})}
function touch(){cur.updated=Date.now();save()}
function drawMain(){var m=document.getElementById('main');if(!cur){m.innerHTML='<p style="color:var(--mut)">Pick a note, or make a new one.</p>';return}
var h='<input id="t" placeholder="Title" value="'+esc(cur.title)+'">';
if(cur.type==='list'){h+='<div id="items">'+cur.items.map(function(it,i){return '<div class="it'+(it.done?' d':'')+'"><input type="checkbox" data-c="'+i+'"'+(it.done?' checked':'')+'><input type="text" data-t="'+i+'" value="'+esc(it.t)+'"><button data-x="'+i+'">x</button></div>'}).join('')+'</div><div class="bar"><button id="ai">+ Item</button><button id="cl">Clear done</button><button id="ts" title="Add the open items to your Tasks">Send open items to Tasks</button></div>'}
else h+='<textarea id="b" placeholder="Write here">'+esc(cur.body||'')+'</textarea><div class="bar"><button id="tt" title="Add this note to your Tasks as a task">Make a task from the title</button></div>';
h+='<div class="bar"><button id="dl">Delete</button></div>';m.innerHTML=h;
document.getElementById('t').oninput=function(e){cur.title=e.target.value;touch();drawList()};
var b=document.getElementById('b');if(b)b.oninput=function(e){cur.body=e.target.value;touch()};
[].forEach.call(m.querySelectorAll('[data-c]'),function(e){e.onchange=function(){cur.items[+e.dataset.c].done=e.checked;touch();drawMain();drawList()}});
[].forEach.call(m.querySelectorAll('[data-t]'),function(e){e.oninput=function(){cur.items[+e.dataset.t].t=e.value;touch()};e.onkeydown=function(k){if(k.key==='Enter'){cur.items.splice(+e.dataset.t+1,0,{t:'',done:false});touch();drawMain();var x=m.querySelector('[data-t="'+(+e.dataset.t+1)+'"]');if(x)x.focus()}}});
[].forEach.call(m.querySelectorAll('[data-x]'),function(e){e.onclick=function(){cur.items.splice(+e.dataset.x,1);touch();drawMain();drawList()}});
var ai=document.getElementById('ai');if(ai)ai.onclick=function(){cur.items.push({t:'',done:false});touch();drawMain();var a=m.querySelectorAll('[data-t]');a[a.length-1].focus()};
var cl=document.getElementById('cl');if(cl)cl.onclick=function(){cur.items=cur.items.filter(function(i){return !i.done});touch();drawMain();drawList()};
var ts=document.getElementById('ts');if(ts)ts.onclick=function(){var open=cur.items.filter(function(i){return !i.done&&i.t.trim()});ts.disabled=true;(function next(k){if(k>=open.length){hub.toast('Sent '+open.length+' to Tasks');ts.disabled=false;return}hub.tasks.add({title:open[k].t}).then(function(){next(k+1)},function(e){hub.toast(e.message);ts.disabled=false})})(0)};
var tt=document.getElementById('tt');if(tt)tt.onclick=function(){hub.tasks.add({title:cur.title||'Untitled',notes:cur.body||''}).then(function(){hub.toast('Added to Tasks')},function(e){hub.toast(e.message)})};
document.getElementById('dl').onclick=function(){if(confirm('Delete this?')){notes=notes.filter(function(n){return n!==cur});cur=null;save();drawList();drawMain()}}}
function add(type){var n={id:id(),type:type,title:'',body:'',items:type==='list'?[{t:'',done:false}]:[],updated:Date.now()};notes.push(n);cur=n;save();drawList();drawMain();document.getElementById('t').focus()}
document.getElementById('nn').onclick=function(){add('note')};document.getElementById('nl').onclick=function(){add('list')};
document.getElementById('q').oninput=function(e){q=e.target.value.toLowerCase();drawList()};
hub.storage.get('notes').then(function(v){notes=Array.isArray(v)?v:[];drawList()});
</script></body></html>
+23
View File
@@ -0,0 +1,23 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Habits</title>
<style>
:root{--bg:#fff;--fg:#1b1e24;--mut:#6b7280;--line:#e0e3e9;--acc:#2f9e6e;--card:#f4f5f8}@media(prefers-color-scheme:dark){:root{--bg:#181b21;--fg:#eceef2;--mut:#8b93a3;--line:#2a2f38;--acc:#3dbb85;--card:#20242c}}
*{box-sizing:border-box}body{margin:0;padding:14px;font:15px system-ui,sans-serif;background:var(--bg);color:var(--fg)}h2{margin:0 0 10px}
input,button{font:inherit;color:inherit;background:var(--card);border:1px solid var(--line);border-radius:8px;padding:8px}button{cursor:pointer}button.p{background:var(--acc);color:#fff;border-color:var(--acc)}
.h{background:var(--card);border-radius:12px;padding:12px;margin:0 0 12px}.top{display:flex;gap:8px;align-items:center}.top b{flex:1}.streak{color:var(--mut);font-size:13px}
.g{display:grid;grid-template-columns:repeat(14,1fr);gap:3px;margin-top:10px}.g i{aspect-ratio:1;border-radius:3px;background:var(--line)}.g i.y{background:var(--acc)}.g i.t{outline:2px solid var(--fg)}
</style></head><body><h2>Habits</h2><div id="hs"></div>
<form id="f" style="display:flex;gap:6px"><input id="nh" placeholder="New habit (for example Read the Bible)" style="flex:1" required><button class="p">Add</button></form>
<script>
var habits=[],timer;
function save(){clearTimeout(timer);timer=setTimeout(function(){hub.storage.set('habits',habits)},300)}
function key(d){var m=d.getMonth()+1,x=d.getDate();return d.getFullYear()+'-'+(m<10?'0':'')+m+'-'+(x<10?'0':'')+x}
function back(n){var d=new Date();d.setDate(d.getDate()-n);return key(d)}
function streak(h){var s=0,i=h.days[back(0)]?0:1;while(h.days[back(i)]){s++;i++}return s}
function esc(s){return String(s).replace(/[&<>"]/g,function(c){return{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]})}
function draw(){document.getElementById('hs').innerHTML=habits.map(function(h,i){var cells='';for(var k=27;k>=0;k--){var d=back(k);cells+='<i class="'+(h.days[d]?'y':'')+(k===0?' t':'')+'" title="'+d+'"></i>'}
var done=h.days[back(0)];return '<div class="h"><div class="top"><b>'+esc(h.name)+'</b><span class="streak">'+streak(h)+' day streak</span><button class="'+(done?'':'p')+'" data-t="'+i+'">'+(done?'Done today':'Check in')+'</button><button data-x="'+i+'" title="Delete">x</button></div><div class="g">'+cells+'</div></div>'}).join('')||'<p style="color:var(--mut)">Add a habit to start a streak.</p>';
[].forEach.call(document.querySelectorAll('[data-t]'),function(b){b.onclick=function(){var h=habits[+b.dataset.t],t=back(0);if(h.days[t])delete h.days[t];else h.days[t]=1;save();draw()}});
[].forEach.call(document.querySelectorAll('[data-x]'),function(b){b.onclick=function(){if(confirm('Delete this habit and its history?')){habits.splice(+b.dataset.x,1);save();draw()}}})}
document.getElementById('f').onsubmit=function(e){e.preventDefault();var v=document.getElementById('nh').value.trim();if(v){habits.push({name:v,days:{}});document.getElementById('nh').value='';save();draw()}};
hub.storage.get('habits').then(function(v){habits=Array.isArray(v)?v:[{name:'Read the Bible',days:{}}];draw()});
</script></body></html>
+24
View File
@@ -0,0 +1,24 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Today</title>
<style>
:root{--bg:#fff;--fg:#1b1e24;--mut:#6b7280;--line:#e0e3e9;--acc:#3d6bf0;--card:#f4f5f8}@media(prefers-color-scheme:dark){:root{--bg:#181b21;--fg:#eceef2;--mut:#8b93a3;--line:#2a2f38;--acc:#6a8cff;--card:#20242c}}
*{box-sizing:border-box}body{margin:0;padding:14px;font:15px system-ui,sans-serif;background:var(--bg);color:var(--fg);max-width:720px}
input,button{font:inherit;color:inherit;background:var(--card);border:1px solid var(--line);border-radius:8px;padding:8px}button{cursor:pointer}
.c{background:var(--card);border-radius:12px;padding:14px;margin:0 0 12px}.big{font-size:40px;font-weight:600}.d{display:flex;gap:8px;overflow:auto}.d div{min-width:78px;text-align:center;background:var(--bg);border-radius:10px;padding:8px}.m{color:var(--mut);font-size:13px}blockquote{margin:0;font-size:17px;line-height:1.5}
</style></head><body>
<div class="c"><form id="f" style="display:flex;gap:6px"><input id="city" placeholder="City (for example Lynchburg)" style="flex:1"><button>Set</button></form><div id="w" class="m" style="margin-top:10px">Pick a city for the weather.</div></div>
<div class="c"><div class="m">Verse of the day</div><blockquote id="verse">Loading…</blockquote><div class="m" id="ref" style="margin-top:6px"></div></div>
<script>
var CODES={0:'Clear',1:'Mostly clear',2:'Partly cloudy',3:'Overcast',45:'Fog',48:'Fog',51:'Light drizzle',53:'Drizzle',55:'Heavy drizzle',61:'Light rain',63:'Rain',65:'Heavy rain',71:'Light snow',73:'Snow',75:'Heavy snow',80:'Showers',81:'Showers',82:'Heavy showers',95:'Thunderstorm',96:'Thunderstorm',99:'Thunderstorm'};
function esc(s){return String(s).replace(/[&<>"]/g,function(c){return{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]})}
function today(){var d=new Date();return d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate()}
function weather(p){document.getElementById('w').textContent='Loading…';
fetch('https://api.open-meteo.com/v1/forecast?latitude='+p.lat+'&longitude='+p.lon+'&current=temperature_2m,weather_code,wind_speed_10m&daily=weather_code,temperature_2m_max,temperature_2m_min&temperature_unit=fahrenheit&wind_speed_unit=mph&timezone=auto&forecast_days=6').then(function(r){return r.json()}).then(function(j){
var c=j.current,d=j.daily;document.getElementById('w').innerHTML='<div class="m">'+esc(p.name)+'</div><div class="big">'+Math.round(c.temperature_2m)+'&deg;F</div><div>'+(CODES[c.weather_code]||'')+', wind '+Math.round(c.wind_speed_10m)+' mph</div><div class="d" style="margin-top:10px">'+d.time.map(function(t,i){return '<div><div class="m">'+(i?new Date(t+'T12:00').toLocaleDateString([], {weekday:'short'}):'Today')+'</div><div>'+Math.round(d.temperature_2m_max[i])+'&deg;</div><div class="m">'+Math.round(d.temperature_2m_min[i])+'&deg;</div></div>'}).join('')+'</div>'}).catch(function(){document.getElementById('w').textContent='Could not load the weather.'})}
document.getElementById('f').onsubmit=function(e){e.preventDefault();var q=document.getElementById('city').value.trim();if(!q)return;
fetch('https://geocoding-api.open-meteo.com/v1/search?count=1&name='+encodeURIComponent(q)).then(function(r){return r.json()}).then(function(j){var g=j.results&&j.results[0];if(!g){document.getElementById('w').textContent='City not found.';return}
var p={name:g.name+(g.admin1?', '+g.admin1:''),lat:g.latitude,lon:g.longitude};hub.storage.set('place',p);weather(p)})};
hub.storage.get('place').then(function(p){if(p)weather(p)});
hub.storage.get('verse').then(function(v){if(v&&v.day===today()){showV(v);return}
fetch('https://bible-api.com/?random=verse').then(function(r){return r.json()}).then(function(j){var n={day:today(),text:String(j.text||'').trim(),ref:j.reference||''};hub.storage.set('verse',n);showV(n)}).catch(function(){document.getElementById('verse').textContent='Could not load a verse today.'})});
function showV(v){document.getElementById('verse').textContent=v.text;document.getElementById('ref').textContent=v.ref}
</script></body></html>
+18 -7
View File
@@ -12,7 +12,8 @@ const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
const ROOT = () => path.join(DATA_DIR, 'mystore'), ITEMS = () => path.join(ROOT(), 'items.json'), FILES = () => path.join(ROOT(), 'files');
const SEAFILE = () => (process.env.SEAFILE_URL || 'https://seafile.necloud.us').replace(/\/$/, '');
const MAX_FILE = 1024 * 1024 * 1024, MAX_COVER = 3 * 1024 * 1024, MAX_EXT = 2 * 1024 * 1024, MAX_STATE = 256 * 1024, MAX_FILES_PER_ITEM = 200;
const KINDS = ['book', 'music', 'app', 'extension'];
const KINDS = ['book', 'music', 'app', 'extension', 'link'];
const PERMS = ['tasks.read', 'tasks.write', 'contacts.read', 'contacts.write', 'calendar.read', 'calendar.write']; // what an extension may ask the person for
const BOOK_EXT = ['epub', 'pdf', 'mobi', 'azw3', 'azw', 'docx'];
const TYPES = { epub: 'application/epub+zip', pdf: 'application/pdf', mobi: 'application/x-mobipocket-ebook', azw3: 'application/vnd.amazon.mobi8-ebook', azw: 'application/vnd.amazon.ebook', docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
mp3: 'audio/mpeg', m4a: 'audio/mp4', aac: 'audio/aac', flac: 'audio/flac', ogg: 'audio/ogg', opus: 'audio/ogg', wav: 'audio/wav', html: 'text/html; charset=utf-8', apk: 'application/vnd.android.package-archive', zip: 'application/zip', dmg: 'application/x-apple-diskimage', exe: 'application/vnd.microsoft.portable-executable', pkg: 'application/octet-stream', txt: 'text/plain; charset=utf-8' };
@@ -32,11 +33,11 @@ const saveItems = l => { fs.mkdirSync(FILES(), { recursive: true, mode: 0o700 })
const fileOn = (item, fid) => path.join(FILES(), item.id + '-' + fid);
const coverOn = item => path.join(FILES(), item.id + '-cover');
const view = it => ({ id: it.id, kind: it.kind, title: it.title, creator: it.creator, description: it.description, version: it.version, url: it.url, cover: !!it.cover, added: it.added, updated: it.updated,
files: it.files.map(f => ({ id: f.id, name: f.name, size: f.size, ext: f.ext })), ...(it.kind === 'extension' ? { icon: it.icon || '' } : {}) });
files: it.files.map(f => ({ id: f.id, name: f.name, size: f.size, ext: f.ext })), ...(it.kind === 'extension' || it.kind === 'link' ? { icon: it.icon || '' } : {}), ...(it.kind === 'link' ? { embed: !!it.embed } : {}) });
// ---- the per-person bits: which extensions are installed, and each extension's saved settings
const stateFile = () => path.join(users.dir(), 'mystore.json');
const stateOf = () => { try { const j = JSON.parse(fs.readFileSync(stateFile(), 'utf8')); return { installed: Array.isArray(j.installed) ? j.installed : [], data: j.data && typeof j.data === 'object' ? j.data : {} }; } catch { return { installed: [], data: {} }; } };
const stateOf = () => { try { const j = JSON.parse(fs.readFileSync(stateFile(), 'utf8')); return { installed: Array.isArray(j.installed) ? j.installed : [], data: j.data && typeof j.data === 'object' ? j.data : {}, grants: j.grants && typeof j.grants === 'object' ? j.grants : {} }; } catch { return { installed: [], data: {}, grants: {} }; } };
const saveState = s => atomicWrite(stateFile(), JSON.stringify(s), { mode: 0o600 });
/** Stream a stored file, with Range support so audio can be skipped through. */
@@ -80,7 +81,10 @@ const EXT_CSP = "sandbox allow-scripts allow-forms allow-popups allow-modals; de
const EXT_META = '<meta http-equiv="Content-Security-Policy" content="' + EXT_CSP.replace(/^sandbox [^;]*; /, '').replace(/; frame-ancestors 'self'$/, '') + '">'; // (the same rules, for when the page is shown from the hub's own copy of it)
const BRIDGE = EXT_META + `<script>(function(){var n=0,w={};window.addEventListener('message',function(e){var m=e.data;if(m&&m.hub&&w[m.id]){var f=w[m.id];delete w[m.id];m.error?f[1](new Error(m.error)):f[0](m.result)}});
function call(method,args){return new Promise(function(ok,no){var id=++n;w[id]=[ok,no];parent.postMessage({hub:1,id:id,method:method,args:args||[]},'*')})}
window.hub={storage:{get:function(k){return call('storage.get',[k])},set:function(k,v){return call('storage.set',[k,v])},all:function(){return call('storage.all')},remove:function(k){return call('storage.remove',[k])}},toast:function(t){return call('toast',[String(t)])},user:function(){return call('user')},open:function(u){return call('open',[String(u)])}}})()</script>`;
window.hub={storage:{get:function(k){return call('storage.get',[k])},set:function(k,v){return call('storage.set',[k,v])},all:function(){return call('storage.all')},remove:function(k){return call('storage.remove',[k])}},toast:function(t){return call('toast',[String(t)])},user:function(){return call('user')},open:function(u){return call('open',[String(u)])},
tasks:{lists:function(){return call('tasks.lists')},list:function(l){return call('tasks.list',[{list:l}])},add:function(o){return call('tasks.add',[o])},complete:function(l,id){return call('tasks.complete',[{list:l,id:id}])}},
contacts:{list:function(){return call('contacts.list')},add:function(o){return call('contacts.add',[o])}},
calendar:{events:function(from,to){return call('calendar.events',[{from:from,to:to}])},add:function(o){return call('calendar.add',[o])}}}})()</script>`;
const withBridge = html => /<head[^>]*>/i.test(html) ? html.replace(/<head[^>]*>/i, m => m + BRIDGE) : BRIDGE + html;
async function handle(req, res) {
@@ -93,9 +97,11 @@ async function handle(req, res) {
if (b.id && !old) throw fail(404, 'Item not found'); if (!old && !KINDS.includes(b.kind)) throw fail(400, 'Choose what kind of thing this is');
const title = str(b.title, 120); if (!title) throw fail(400, 'Give it a title');
const url = str(b.url, 300); if (url && !/^https?:\/\/\S+$/i.test(url)) throw fail(400, 'The link must start with http');
if ((old ? old.kind : b.kind) === 'link' && !url) throw fail(400, 'Paste the address of the site');
const it = old || { id: newId(), kind: b.kind, files: [], cover: false, added: Date.now() };
Object.assign(it, { title, creator: str(b.creator, 120), description: str(b.description, 2000), version: str(b.version, 30), url, updated: Date.now() });
if (it.kind === 'extension') it.icon = str(b.icon, 4);
if (it.kind === 'extension' || it.kind === 'link') it.icon = str(b.icon, 4);
if (it.kind === 'link') it.embed = !!b.embed;
if (!old) { if (l.length >= 2000) throw fail(400, 'That is plenty of items'); l.push(it); } saveItems(l); return json(res, 200, view(it));
}
if ((m = /^\/items\/([0-9a-f]{12})$/.exec(p)) && req.method === 'DELETE') {
@@ -105,7 +111,7 @@ async function handle(req, res) {
if ((m = /^\/items\/([0-9a-f]{12})\/files$/.exec(p)) && req.method === 'POST') { // upload one file (the body is the file; its name is in ?name=) or copy one from Seafile (JSON { repo, path })
needAdmin(me); const l = loadItems(), it = l.find(x => x.id === m[1]); if (!it) throw fail(404, 'Item not found');
if (it.files.length >= MAX_FILES_PER_ITEM) throw fail(400, 'That is plenty of files for one item');
if (it.kind !== 'music' && it.kind !== 'app' && it.files.length >= 1) throw fail(400, 'This kind of item holds one file. Remove the old one first.');
if (it.kind === 'link') throw fail(400, 'A site has no files'); if (it.kind !== 'music' && it.kind !== 'app' && it.files.length >= 1) throw fail(400, 'This kind of item holds one file. Remove the old one first.');
const fid = newId(); let name, size;
if (/json/.test(req.headers['content-type'] || '')) { const b = JSON.parse(await readBody(req, 1e4) || '{}'), src = await fromSeafile(String(b.repo || ''), String(b.path || '')); name = src.name; const tmp = fileOn(it, fid) + '.part'; fs.mkdirSync(FILES(), { recursive: true, mode: 0o700 }); let n = 0; src.stream.on('data', c => { n += c.length; if (n > MAX_FILE) src.stream.destroy(fail(413, 'That file is too large')); }); await pipeline(src.stream, fs.createWriteStream(tmp, { mode: 0o600 })).catch(e => { fs.rm(tmp, { force: true }, () => {}); throw e.code ? e : fail(502, 'The copy did not finish'); }); fs.renameSync(tmp, fileOn(it, fid)); size = n; }
else { name = safeName(u.searchParams.get('name')); size = await receive(req, fileOn(it, fid), it.kind === 'extension' ? MAX_EXT : MAX_FILE); }
@@ -142,7 +148,12 @@ async function handle(req, res) {
}
if ((m = /^\/ext\/([0-9a-f]{12})\/(install|uninstall)$/.exec(p)) && req.method === 'POST') {
const it = loadItems().find(x => x.id === m[1]); if (!it || it.kind !== 'extension') throw fail(404, 'Not found');
const s = stateOf(); s.installed = s.installed.filter(x => x !== it.id); if (m[2] === 'install') s.installed.push(it.id); if (m[2] === 'uninstall') delete s.data[it.id]; saveState(s); return json(res, 200, { installed: s.installed });
const s = stateOf(); s.installed = s.installed.filter(x => x !== it.id); if (m[2] === 'install') s.installed.push(it.id); if (m[2] === 'uninstall') { delete s.data[it.id]; delete s.grants[it.id]; } saveState(s); return json(res, 200, { installed: s.installed });
}
if ((m = /^\/ext\/([0-9a-f]{12})\/grants$/.exec(p))) { // what the person has allowed this extension to reach in the hub
const it = loadItems().find(x => x.id === m[1]); if (!it || it.kind !== 'extension') throw fail(404, 'Not found'); const s = stateOf();
if (req.method === 'GET') return json(res, 200, { grants: s.grants[it.id] || [] });
if (req.method === 'POST') { const b = JSON.parse(await readBody(req, 1e4) || '{}'); s.grants[it.id] = [...new Set((Array.isArray(b.grants) ? b.grants : []).filter(x => PERMS.includes(x)))]; saveState(s); return json(res, 200, { grants: s.grants[it.id] }); }
}
if ((m = /^\/ext\/([0-9a-f]{12})\/data$/.exec(p))) { // the extension's own saved settings for this person
const it = loadItems().find(x => x.id === m[1]); if (!it || it.kind !== 'extension') throw fail(404, 'Not found'); const s = stateOf();
+56 -10
View File
@@ -3,7 +3,7 @@
// music, apps to download, and extensions that add features to the hub). The first three are the same screens as before, shown inside this one.
const stApi = (p, opts) => jfetch('/api/store/my' + p, opts);
const stOpt = (m, o) => ({ method: m, headers: { 'content-type': 'application/json' }, body: o ? JSON.stringify(o) : undefined });
const ST_KINDS = [['book', 'Books', 'book'], ['music', 'Music', 'music'], ['app', 'Apps', 'files'], ['extension', 'Extensions', 'cog']];
const ST_KINDS = [['book', 'Books', 'book'], ['music', 'Music', 'music'], ['app', 'Apps', 'files'], ['extension', 'Extensions', 'cog'], ['link', 'Sites', 'link']];
const stKind = k => ST_KINDS.find(x => x[0] === k) || ST_KINDS[2];
const stSize = b => fmtSize(+b || 0);
const stCover = it => it.cover ? `/api/store/my/items/${it.id}/cover?v=${it.updated}` : '';
@@ -14,7 +14,7 @@ let stItems = [], stInstalled = [], stAdmin = false, stFilter = 'all';
const stSections = () => [['books', 'Books', allowed('read')], ['audiobooks', 'Audiobooks', allowed('audio')], ['radio', 'Radio', allowed('radio')], ['mine', 'My Store', true]].filter(s => s[2]);
async function viewStore(args = []) {
const secs = stSections(), want = args[0] === 'ext' ? 'mine' : args[0], sec = (secs.find(s => s[0] === want) || secs[0])[0];
const secs = stSections(), want = args[0] === 'ext' || args[0] === 'site' ? 'mine' : args[0], sec = (secs.find(s => s[0] === want) || secs[0])[0];
const v = $('#view');
v.innerHTML = `<div class="wrap" id="stwrap"><div class="ptop"><h1>Store</h1></div><div class="seg">${secs.map(s => `<a href="#/store/${s[0]}" class="${s[0] === sec ? 'on' : ''}">${esc(s[1])}</a>`).join('')}</div><div id="stbody"></div></div>`;
const el = $('#stbody'), host = { el, hash: '#/store/' + sec };
@@ -22,6 +22,7 @@ async function viewStore(args = []) {
if (sec === 'audiobooks') return viewFreeBooks(host);
if (sec === 'radio') return viewRadio(host);
if (args[0] === 'ext' && args[1]) return stRunExt(el, args[1]);
if (args[0] === 'site' && args[1]) return stRunSite(el, args[1]);
return stMine(el);
}
@@ -42,7 +43,7 @@ async function stMine(el) {
};
draw();
}
const stCard = (it, run) => `<a class="vcard" href="#" data-it="${esc(it.id)}"${run ? ' data-run="1"' : ''}><span class="vimg" style="aspect-ratio:${it.kind === 'book' ? '2/3' : '1/1'};background:linear-gradient(135deg,hsl(${stHue(it.title)} 55% 40%),hsl(${stHue(it.title) + 40} 55% 28%));display:grid;place-items:center;color:#fff;font-size:40px">${it.cover ? `<img loading="lazy" alt="" src="${stCover(it)}" onerror="this.remove()">` : esc((it.kind === 'extension' && it.icon) || (it.title.match(/\p{L}|\p{N}/u) || ['?'])[0].toUpperCase())}</span>
const stCard = (it, run) => `<a class="vcard" href="#" data-it="${esc(it.id)}"${run ? ' data-run="1"' : ''}><span class="vimg" style="aspect-ratio:${it.kind === 'book' ? '2/3' : '1/1'};background:linear-gradient(135deg,hsl(${stHue(it.title)} 55% 40%),hsl(${stHue(it.title) + 40} 55% 28%));display:grid;place-items:center;color:#fff;font-size:40px">${it.cover ? `<img loading="lazy" alt="" src="${stCover(it)}" onerror="this.remove()">` : esc(((it.kind === 'extension' || it.kind === 'link') && it.icon) || (it.title.match(/\p{L}|\p{N}/u) || ['?'])[0].toUpperCase())}</span>
<b>${esc(it.title)}</b><small>${esc([stKind(it.kind)[1].replace(/s$/, ''), it.creator].filter(Boolean).join(' · '))}</small></a>`;
function stDetail(it, redraw) {
@@ -51,10 +52,11 @@ function stDetail(it, redraw) {
const el = openSheet(it.title, [stKind(k)[1].replace(/s$/, ''), it.creator, it.version && 'v' + it.version].filter(Boolean).join(' · '), `<div style="display:flex;gap:14px;align-items:flex-start">${it.cover ? `<span class="vimg" style="width:96px;flex:none;aspect-ratio:${k === 'book' ? '2/3' : '1/1'}"><img alt="" src="${stCover(it)}"></span>` : ''}
<div style="min-width:0">${it.description ? `<p style="margin:0;white-space:normal">${esc(it.description).replace(/\n/g, '<br>')}</p>` : '<p class="sub" style="margin:0">No description.</p>'}</div></div>
${k === 'music' || k === 'app' ? `<div class="list" style="margin-top:12px">${it.files.map((f, i) => `<div class="row"><span class="grow"><b>${esc(f.name)}</b><small>${esc(stSize(f.size))}</small></span>${k === 'music' ? `<button class="ibtn" data-play="${i}" aria-label="Play">${icon('play')}</button>` : ''}<a class="ibtn" href="${url(f)}?dl=1" download aria-label="Download">${icon('download')}</a></div>`).join('') || '<p class="empty">No files.</p>'}</div>` : ''}
<div class="err" id="sterr"></div><div class="bar" id="stbar" style="flex-wrap:wrap">
${k === 'link' ? `<p class="sub" style="margin:10px 0 0;word-break:break-all">${esc(it.url)}</p>` : ''}<div class="err" id="sterr"></div><div class="bar" id="stbar" style="flex-wrap:wrap">
${k === 'book' && f0 ? `${allowed('read') ? '<button class="btn" id="stlib">Add to my library</button>' : ''}<a class="btn ghost" href="${url(f0)}?dl=1" download>Download</a>` : ''}
${k === 'music' && it.files.length ? `<button class="btn" id="stplay">${icon('play')}Play</button>` : ''}
${k === 'app' && it.url ? `<a class="btn" href="${esc(it.url)}" target="_blank" rel="noopener noreferrer">Open link</a>` : ''}
${k === 'link' ? `<button class="btn" id="stopen">Open</button><a class="btn ghost" href="${esc(it.url)}" target="_blank" rel="noopener noreferrer">New tab</a>` : ''}
${k === 'extension' && f0 ? `<button class="btn" id="stinst">${isMine ? 'Open' : 'Install'}</button>${isMine ? '<button class="btn ghost" id="stun">Remove</button>' : ''}` : ''}
${stAdmin ? '<button class="btn ghost" id="stedit">Edit</button>' : ''}</div>`);
const err = t => { el.querySelector('#sterr').textContent = t; };
@@ -63,6 +65,7 @@ function stDetail(it, redraw) {
if (el.querySelector('#stplay')) el.querySelector('#stplay').onclick = () => play(0);
el.querySelectorAll('[data-play]').forEach(b => b.onclick = () => play(+b.dataset.play));
if (el.querySelector('#stlib')) el.querySelector('#stlib').onclick = async e => { const b = e.currentTarget; b.disabled = true; try { const r = await stApi(`/items/${it.id}/to-library`, stOpt('POST')); closeSheet(); toast(r.duplicate ? 'Already in your library' : 'Added to your library', { label: 'Open', run: () => { location.hash = '#/read/open/' + r.id; } }); } catch (x) { err(x.message); b.disabled = false; } };
if (el.querySelector('#stopen')) el.querySelector('#stopen').onclick = () => { closeSheet(); if (it.embed) location.hash = '#/store/site/' + it.id; else window.open(it.url, '_blank', 'noopener,noreferrer'); };
if (el.querySelector('#stinst')) el.querySelector('#stinst').onclick = async e => { const b = e.currentTarget; try { if (!isMine) { b.disabled = true; stInstalled = (await stApi(`/ext/${it.id}/install`, stOpt('POST'))).installed; } closeSheet(); location.hash = '#/store/ext/' + it.id; } catch (x) { err(x.message); b.disabled = false; } };
if (el.querySelector('#stun')) el.querySelector('#stun').onclick = () => { closeSheet(); confirmSheet('Remove this extension?', 'Its saved settings are forgotten too.', 'Remove', async () => { try { stInstalled = (await stApi(`/ext/${it.id}/uninstall`, stOpt('POST'))).installed; toast('Removed'); redraw(); } catch (x) { toast(x.message); } }); };
if (el.querySelector('#stedit')) el.querySelector('#stedit').onclick = () => { closeSheet(); stEdit(it, redraw); };
@@ -77,15 +80,17 @@ function stEdit(it, redraw) {
<label for="stt">Title</label><input type="text" id="stt" value="${esc(x.title)}" autocomplete="off" required>
<label for="stc" id="stcl">Author</label><input type="text" id="stc" value="${esc(x.creator)}" autocomplete="off">
<label for="std">Description</label><textarea id="std" rows="3">${esc(x.description)}</textarea>
<div id="stapp" hidden><label for="stv">Version</label><input type="text" id="stv" value="${esc(x.version)}" autocomplete="off"><label for="stu">Link (optional)</label><input type="url" id="stu" value="${esc(x.url)}" placeholder="https://…" autocapitalize="off"></div>
<div id="stver" hidden><label for="stv">Version</label><input type="text" id="stv" value="${esc(x.version)}" autocomplete="off"></div>
<div id="stlnk" hidden><label for="stu" id="stul">Link (optional)</label><input type="url" id="stu" value="${esc(x.url)}" placeholder="https://…" autocapitalize="off"></div>
<label id="stemb" class="row" style="cursor:pointer" hidden><span class="grow"><b>Open inside the hub</b><small>Some sites refuse to be shown this way; they open in a new tab instead</small></span><input type="checkbox" id="ste"${x.embed ? ' checked' : ''}></label>
<div id="stext" hidden><label for="sti">Icon (one letter or emoji)</label><input type="text" id="sti" value="${esc(x.icon || '')}" maxlength="2" style="width:80px"></div>
<label>Files</label><div id="stfl" class="list"></div>
<div class="bar" style="justify-content:flex-start;margin:6px 0"><label class="btn ghost" style="cursor:pointer;margin:0">${icon('plus')}Upload<input type="file" id="stup" hidden multiple></label>${allowed('files') ? `<button type="button" class="btn ghost" id="stsf">${icon('files')}From Files</button>` : ''}</div>
<div id="stfiles"><label>Files</label><div id="stfl" class="list"></div>
<div class="bar" style="justify-content:flex-start;margin:6px 0"><label class="btn ghost" style="cursor:pointer;margin:0">${icon('plus')}Upload<input type="file" id="stup" hidden multiple></label>${allowed('files') ? `<button type="button" class="btn ghost" id="stsf">${icon('files')}From Files</button>` : ''}</div></div>
<label>Cover picture</label><div class="bar" style="justify-content:flex-start;margin:4px 0"><label class="btn ghost" style="cursor:pointer;margin:0">${icon('plus')}Choose<input type="file" id="stcv" accept="image/jpeg,image/png,image/gif,image/webp" hidden></label><small id="stcvn" style="color:var(--muted)">${x.cover ? 'A cover is set' : ''}</small></div>
<div class="err" id="sterr"></div><div class="bar">${it ? '<button type="button" class="btn danger" id="stdel">Delete</button>' : ''}<button type="button" class="btn ghost" id="stx" style="flex:1;justify-content:center">Cancel</button><button class="btn" id="stok" style="flex:1;justify-content:center">${it ? 'Save' : 'Add'}</button></div></form>`);
const $e = s => el.querySelector(s), err = t => { $e('#sterr').textContent = t; };
let kind = x.kind; const files = [], existing = [...x.files]; let cover = null;
const kindUi = () => { kind = it ? x.kind : $e('#stk').value; $e('#stcl').textContent = kind === 'music' ? 'Artist' : kind === 'book' ? 'Author' : 'Made by'; $e('#stapp').hidden = kind !== 'app' && kind !== 'extension'; $e('#stext').hidden = kind !== 'extension';
const kindUi = () => { kind = it ? x.kind : $e('#stk').value; $e('#stcl').textContent = kind === 'music' ? 'Artist' : kind === 'book' ? 'Author' : 'Made by'; $e('#stver').hidden = kind !== 'app' && kind !== 'extension'; $e('#stlnk').hidden = kind !== 'app' && kind !== 'link'; $e('#stul').textContent = kind === 'link' ? 'Address of the site' : 'Link (optional)'; $e('#stemb').hidden = kind !== 'link'; $e('#stext').hidden = kind !== 'extension' && kind !== 'link'; $e('#stfiles').hidden = kind === 'link';
$e('#stup').accept = kind === 'book' ? '.epub,.pdf,.mobi,.azw3,.azw,.docx' : kind === 'music' ? 'audio/*,.mp3,.m4a,.flac,.ogg,.opus,.wav' : kind === 'extension' ? '.html' : ''; $e('#stup').multiple = kind === 'music' || kind === 'app'; };
const drawFiles = () => { $e('#stfl').innerHTML = [...existing.map((f, i) => [f.name, stSize(f.size), 'e', i]), ...files.map((f, i) => [f.name || f.path.split('/').pop(), f.size != null ? stSize(f.size) : 'from Files', 'n', i])].map(([n, s, t, i]) => `<div class="row"><span class="grow"><b>${esc(n)}</b><small>${esc(s)}</small></span><button type="button" class="ibtn" data-t="${t}" data-i="${i}" aria-label="Remove">${icon('trash')}</button></div>`).join('') || '<p class="sub" style="margin:8px 12px">No files yet.</p>';
el.querySelectorAll('#stfl [data-t]').forEach(b => b.onclick = () => { (b.dataset.t === 'e' ? existing : files).splice(+b.dataset.i, 1); drawFiles(); }); };
@@ -98,8 +103,8 @@ function stEdit(it, redraw) {
$e('#stf').onsubmit = async e => {
e.preventDefault(); const ok = $e('#stok'); ok.disabled = true; err('');
try {
if (!files.length && !existing.length && kind !== 'app') throw new Error('Add the file first');
let saved = await stApi('/items', stOpt('POST', { id: it && it.id, kind, title: $e('#stt').value, creator: $e('#stc').value, description: $e('#std').value, version: $e('#stv').value, url: $e('#stu').value, icon: $e('#sti') ? $e('#sti').value : '' }));
if (!files.length && !existing.length && kind !== 'app' && kind !== 'link') throw new Error('Add the file first');
let saved = await stApi('/items', stOpt('POST', { id: it && it.id, kind, title: $e('#stt').value, creator: $e('#stc').value, description: $e('#std').value, version: $e('#stv').value, url: $e('#stu').value, embed: !!$e('#ste').checked, icon: $e('#sti') ? $e('#sti').value : '' }));
if (!it) created = true;
for (const f of x.files) if (!existing.some(y => y.id === f.id)) saved = await stApi(`/items/${saved.id}/files/${f.id}`, { method: 'DELETE' });
let n = 0;
@@ -155,6 +160,36 @@ async function stRunExt(el, id) {
fetch(`/api/store/my/ext/${id}/page`).then(r => r.ok ? r.text() : Promise.reject(new Error('Could not load it'))).then(h => { frame.srcdoc = h; }).catch(e => { el.querySelector('#stframe').outerHTML = `<p class="err">${esc(e.message)}</p>`; });
const load = async () => data || (data = await stApi(`/ext/${id}/data`).catch(() => ({})));
const save = () => { clearTimeout(timer); timer = setTimeout(() => stApi(`/ext/${id}/data`, stOpt('POST', data)).catch(e => toast(e.message)), 400); };
// What an extension may ask the hub for. Each kind of access is asked of the person the first time and remembered until the extension is removed.
const WHY = { 'tasks.read': 'see your tasks', 'tasks.write': 'add tasks and mark them done', 'contacts.read': 'see your contacts', 'contacts.write': 'add contacts', 'calendar.read': 'see your calendar', 'calendar.write': 'add events to your calendar' };
let grants = null; const refused = new Set();
const allowedTo = async perm => {
if (!grants) grants = (await stApi(`/ext/${id}/grants`).catch(() => ({ grants: [] }))).grants;
if (grants.includes(perm)) return true; if (refused.has(perm) || !allowed(perm.split('.')[0] === 'calendar' ? 'calendar' : perm.split('.')[0])) return false;
const yes = await new Promise(ok => { let done = false; const el2 = openSheet('Allow access?', it.title, `<p>“${esc(it.title)}” would like to <b>${esc(WHY[perm])}</b>.</p><div class="bar"><button class="btn ghost" id="pno" style="flex:1;justify-content:center">Don't allow</button><button class="btn" id="pyes" style="flex:1;justify-content:center">Allow</button></div>`);
const fin = v => { if (!done) { done = true; closeSheet(); ok(v); } }; el2.querySelector('#pyes').onclick = () => fin(true); el2.querySelector('#pno').onclick = () => fin(false); el2.querySelector('.scrim').addEventListener('click', () => fin(false)); });
if (!yes) { refused.add(perm); return false; }
grants = [...grants, perm]; stApi(`/ext/${id}/grants`, stOpt('POST', { grants })).catch(() => {}); return true;
};
const jf = (p, o) => jfetch(p, o), pj = (m, b) => ({ method: m, headers: { 'content-type': 'application/json' }, body: JSON.stringify(b) });
const txt = (v, n) => String(v == null ? '' : v).slice(0, n), ymd = v => /^\d{4}-\d{2}-\d{2}$/.test(String(v)) ? String(v) : '';
const hubCall = async (method, a = {}) => {
const need = { 'tasks.lists': 'tasks.read', 'tasks.list': 'tasks.read', 'tasks.add': 'tasks.write', 'tasks.complete': 'tasks.write', 'contacts.list': 'contacts.read', 'contacts.add': 'contacts.write', 'calendar.events': 'calendar.read', 'calendar.add': 'calendar.write' }[method];
if (!need) throw new Error('Unknown request'); if (!a || typeof a !== 'object') a = {};
if (!(await allowedTo(need))) throw new Error('The person did not allow that');
const localList = async name => { const l = (await jf('/api/tasks/lists')).lists.filter(x => x.local), n = txt(name, 60).toLowerCase(); return (n && l.find(x => x.name.toLowerCase() === n)) || l.find(x => x.id === 'local:inbox') || l[0]; };
if (method === 'tasks.lists') return (await jf('/api/tasks/lists')).lists.map(l => ({ id: l.id, name: l.name }));
if (method === 'tasks.list') return (await jf('/api/tasks?list=' + encodeURIComponent(txt(a.list, 80)))).map(t => ({ id: t.id, title: t.title, notes: t.notes || '', due: t.due || '', done: !!t.done }));
if (method === 'tasks.add') { const l = await localList(a.list); if (!l) throw new Error('No task list'); await jf('/api/tasks', pj('POST', { list: l.id, fields: { title: txt(a.title, 200), notes: txt(a.notes, 2000), due: ymd(a.due), done: false } })); return { ok: true, list: l.name }; }
if (method === 'tasks.complete') { const list = txt(a.list, 80), t = (await jf('/api/tasks?list=' + encodeURIComponent(list))).find(x => x.id === a.id); if (!t) throw new Error('Task not found'); await jf('/api/tasks', pj('POST', { list, id: t.id, fields: { title: t.title, notes: t.notes || '', due: t.due || '', done: true } })); return { ok: true }; }
if (method === 'contacts.list') return (await ctApi('/')).map(c => ({ id: c.id, name: c.name, org: c.org, emails: c.emails.map(e => e.value), phones: c.phones.map(p => p.value), birthday: c.birthday }));
if (method === 'contacts.add') { const c = await ctApi('/', pj('POST', { name: txt(a.name, 120), org: txt(a.org, 120), emails: a.email ? [{ label: '', value: txt(a.email, 120) }] : [], phones: a.phone ? [{ label: '', value: txt(a.phone, 60) }] : [], birthday: txt(a.birthday, 12), notes: txt(a.notes, 2000) })); ctList = null; return { id: c.id }; }
if (method === 'calendar.events') { const f = ymd(a.from), t = ymd(a.to); if (!f || !t) throw new Error('Give from and to as YYYY-MM-DD'); const q = new URLSearchParams({ from: new Date(f + 'T00:00:00').getTime(), to: new Date(t + 'T23:59:59').getTime(), fd: f, td: t });
return (await jf('/api/cal/events?' + q)).events.slice(0, 500).map(e => ({ title: e.title, start: e.start, end: e.end, allDay: !!e.allDay, calendar: e.cal })); }
if (method === 'calendar.add') { const cals = await jf('/api/cal/list'), c = cals.find(x => x.local && !x.shared); if (!c) throw new Error('No calendar to add to'); const allDay = !!a.allDay, re = allDay ? /^\d{4}-\d{2}-\d{2}$/ : /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/;
if (!re.test(a.start || '')) throw new Error('start must be ' + (allDay ? 'YYYY-MM-DD' : 'YYYY-MM-DDTHH:MM')); const end = re.test(a.end || '') ? a.end : a.start;
await jf('/api/cal/event', pj('POST', { cal: c.id, fields: { title: txt(a.title, 200), location: txt(a.location, 200), notes: txt(a.notes, 2000), allDay, start: a.start, end, tz: Intl.DateTimeFormat().resolvedOptions().timeZone, repeat: 'none' } })); return { ok: true }; }
};
const onMsg = async e => {
if (!document.body.contains(frame)) return removeEventListener('message', onMsg);
if (e.source !== frame.contentWindow || !e.data || !e.data.hub) return;
@@ -166,6 +201,7 @@ async function stRunExt(el, id) {
else if (method === 'storage.remove') { delete (await load())[String(args[0])]; save(); result = true; }
else if (method === 'toast') { toast(String(args[0]).slice(0, 200)); result = true; }
else if (method === 'user') result = { name: ME ? ME.name : '' };
else if (method.startsWith('tasks.') || method.startsWith('contacts.') || method.startsWith('calendar.')) result = await hubCall(method, args[0]);
else if (method === 'open') { if (/^https?:\/\//i.test(String(args[0]))) window.open(String(args[0]), '_blank', 'noopener,noreferrer'); result = true; }
else throw new Error('Unknown request');
} catch (x) { error = x.message; }
@@ -173,3 +209,13 @@ async function stRunExt(el, id) {
};
addEventListener('message', onMsg);
}
/** A site shown inside the hub. It is another website in a frame of its own, so it cannot see anything of the hub's. */
async function stRunSite(el, id) {
try { await stLoad(); } catch (e) { el.innerHTML = `<p class="err">${esc(e.message)}</p>`; return; }
const it = stItems.find(x => x.id === id && x.kind === 'link');
if (!it) { el.innerHTML = '<p class="empty">That site is not in the store any more.</p>'; return; }
el.innerHTML = `<div class="bar" style="margin:0 0 8px;justify-content:flex-start"><a class="btn ghost" href="#/store/mine">${icon('back')}My Store</a><b style="flex:1">${esc(it.title)}</b><a class="btn ghost" href="${esc(it.url)}" target="_blank" rel="noopener noreferrer">New tab</a></div>
<iframe title="${esc(it.title)}" src="${esc(it.url)}" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox" referrerpolicy="no-referrer" style="width:100%;height:calc(100dvh - 190px);min-height:360px;border:1px solid var(--line);border-radius:12px;background:#fff"></iframe>
<p class="sub" style="margin-top:8px">If the page stays blank, that site does not allow being shown here. Use New tab.</p>`;
}
+7
View File
@@ -43,6 +43,13 @@ const hub = http.createServer((req, res) => users.runAs(req.headers['x-user'] ==
assert.equal((await post(`/ext/${ext.id}/data`, { big: 'x'.repeat(300000) }, bob)).status, 413);
assert.deepEqual((await (await post(`/ext/${ext.id}/uninstall`, {}, bob)).json()).installed, []); assert.deepEqual(await (await fetch(`${B}/ext/${ext.id}/data`, { headers: bob })).json(), {}, 'uninstalling forgets its settings');
assert.equal((await fetch(`${B}/ext/${book.id}/page`)).status, 404, 'only extensions are framed');
// permissions an extension has been given
assert.deepEqual(await (await fetch(`${B}/ext/${ext.id}/grants`, { headers: bob })).json(), { grants: [] }); assert.equal((await post(`/ext/${ext.id}/install`, {}, bob)).status, 200);
assert.deepEqual((await (await post(`/ext/${ext.id}/grants`, { grants: ['tasks.read', 'tasks.read', 'root.everything'] }, bob)).json()).grants, ['tasks.read'], 'only known permissions are kept');
assert.deepEqual(await (await fetch(`${B}/ext/${ext.id}/grants`)).json(), { grants: [] }, 'they are per person'); await post(`/ext/${ext.id}/uninstall`, {}, bob); assert.deepEqual((await (await fetch(`${B}/ext/${ext.id}/grants`, { headers: bob })).json()).grants, [], 'removing the extension takes them back');
// a site (a link, optionally shown inside the hub)
assert.equal((await post('/items', { kind: 'link', title: 'Site' })).status, 400, 'a site needs an address'); let site = await (await post('/items', { kind: 'link', title: 'Docs', url: 'https://example.com/', embed: true, icon: 'D' })).json(); assert.equal(site.embed, true); assert.equal(site.icon, 'D');
assert.equal((await put(`/items/${site.id}/files?name=a.html`, 'x')).status, 400, 'a site has no files');
// a Seafile copy needs a sign-in
r = await post(`/items/${alb.id}/files`, { repo: 'a'.repeat(36), path: '/x.mp3' }); assert.equal(r.status, 401);
// changing, deleting