Luca448 commited on
Commit
4d4aa6f
·
1 Parent(s): f5930da

feat: release page lists asked files, multi-select, code remembered on the device

Browse files
src/api/iserv-filtered.js CHANGED
@@ -17,11 +17,65 @@ const FILTER_URL = process.env.ISERV_FILTER_URL || 'http://127.0.0.1:7862/filter
17
  let running = Promise.resolve(); // one IServ session at a time
18
  const RELEASE_MS = 10 * 60_000;
19
  const releases = new Map(); // "<task id>-<file number>" -> expiry time; memory only
 
20
  const FORM = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">
21
  <title>Freigabe</title><body style="font-family:sans-serif;max-width:30rem;margin:2rem auto;padding:0 1rem">
22
- <h1>Datei freigeben</h1><p>Die Datei wurde nicht auf Namen geprüft. Muse sieht sie nur nach deiner Freigabe (10 Minuten, einmal).</p>
23
- <form method="post"><p><label>Freigabe-IDs, z. B. 12-0, 12-1<br><input name="ids" required style="width:100%"></label></p>
24
- <p><label>Freigabe-Code<br><input name="code" type="password" required style="width:100%"></label></p><button>Freigeben</button></form>`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
  function sameSecret(offered, expected) {
27
  const a = Buffer.from(String(offered || ''));
@@ -61,16 +115,25 @@ async function cleanTasks(includeDone, withFiles, released) {
61
  export function registerIServFiltered(app) {
62
  app.get('/iserv/health', (req, res) => res.json({ status: 'ok' }));
63
  app.get('/iserv/freigabe', (req, res) => res.set('Cache-Control', 'no-store').type('html').send(FORM));
64
- app.post('/iserv/freigabe', express.urlencoded({ extended: false, limit: '4kb' }), async (req, res) => {
65
- res.set('Cache-Control', 'no-store').type('html');
66
  const approve = process.env.APPROVE_TOKEN;
67
  if (approve === process.env.API_BEARER_TOKEN || !sameSecret(req.body?.code, approve)) {
68
  await new Promise((r) => setTimeout(r, 1000)); // slows guessing
69
- return res.status(401).send('Nicht freigegeben.');
70
  }
71
- const ids = String(req.body.ids || '').split(/[\s,;]+/).filter((i) => /^\d{1,12}-\d{1,3}$/.test(i));
72
- ids.forEach((id) => releases.set(id, Date.now() + RELEASE_MS));
73
- res.send(`<meta charset="utf-8"><p>Freigegeben (10 Minuten, einmal): ${ids.join(', ') || 'nichts'}</p>`);
 
 
 
 
 
 
 
 
 
74
  });
75
  app.get('/iserv/tasks', async (req, res) => {
76
  res.set('Cache-Control', 'no-store');
@@ -85,6 +148,9 @@ export function registerIServFiltered(app) {
85
  const job = running.then(run, run);
86
  running = job.catch(() => {});
87
  const { status, body } = await job;
 
 
 
88
  res.status(status).json(body);
89
  });
90
  }
 
17
  let running = Promise.resolve(); // one IServ session at a time
18
  const RELEASE_MS = 10 * 60_000;
19
  const releases = new Map(); // "<task id>-<file number>" -> expiry time; memory only
20
+ const pending = new Map(); // id -> {name, aufgabe, until}: files Muse was told to ask about; memory only, filtered names
21
  const FORM = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">
22
  <title>Freigabe</title><body style="font-family:sans-serif;max-width:30rem;margin:2rem auto;padding:0 1rem">
23
+ <h1>Dateien freigeben</h1>
24
+ <p>Diese Dateien wurden nicht auf Namen geprüft. Muse sieht sie nur nach deiner Freigabe (10 Minuten, einmal).</p>
25
+ <form id="f"><p><label>Freigabe-Code<br><input id="code" type="password" autocomplete="current-password" required style="width:100%"></label></p>
26
+ <p><label><input id="keep" type="checkbox" checked> Code auf diesem Gerät merken</label>
27
+ <button type="button" id="forget">Vergessen</button></p>
28
+ <details open><summary id="sum">Dateien laden …</summary><div id="list"></div></details>
29
+ <p><button id="go" disabled>Freigeben</button> <button type="button" id="reload">Neu laden</button></p></form><p id="msg"></p>
30
+ <script>
31
+ const $ = (i) => document.getElementById(i);
32
+ const KEY = 'iserv-freigabe-code';
33
+ const saved = () => { try { return localStorage.getItem(KEY) || ''; } catch { return ''; } };
34
+ $('code').value = saved();
35
+ async function call(path, body) {
36
+ const r = await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
37
+ return { ok: r.ok, data: await r.json().catch(() => ({})) };
38
+ }
39
+ function show(items) {
40
+ const list = $('list');
41
+ list.textContent = '';
42
+ for (const it of items) {
43
+ const l = document.createElement('label');
44
+ l.style.display = 'block'; l.style.margin = '.5rem 0';
45
+ const c = document.createElement('input');
46
+ c.type = 'checkbox'; c.value = it.id; c.onchange = count;
47
+ l.append(c, ' ' + it.id + ': ' + it.name + (it.aufgabe ? ' (' + it.aufgabe + ')' : ''));
48
+ list.append(l);
49
+ }
50
+ count();
51
+ $('sum').textContent = items.length ? 'Gefragte Dateien (' + items.length + ')' : 'Keine Datei gefragt';
52
+ }
53
+ function count() {
54
+ const n = document.querySelectorAll('#list input:checked').length;
55
+ $('go').disabled = !n;
56
+ $('go').textContent = n ? n + ' freigeben' : 'Freigeben';
57
+ }
58
+ async function load() {
59
+ const code = $('code').value;
60
+ if (!code) return;
61
+ $('msg').textContent = '';
62
+ const { ok, data } = await call('/iserv/freigabe/liste', { code });
63
+ if (!ok) { $('sum').textContent = 'Code falsch'; $('list').textContent = ''; return; }
64
+ try { $('keep').checked ? localStorage.setItem(KEY, code) : localStorage.removeItem(KEY); } catch {}
65
+ show(data.pending);
66
+ }
67
+ $('f').onsubmit = async (e) => {
68
+ e.preventDefault();
69
+ const ids = [...document.querySelectorAll('#list input:checked')].map((c) => c.value);
70
+ const { ok, data } = await call('/iserv/freigabe', { code: $('code').value, ids });
71
+ $('msg').textContent = ok ? 'Freigegeben (10 Minuten, einmal): ' + data.released.join(', ') : 'Nicht freigegeben.';
72
+ if (ok) load();
73
+ };
74
+ $('reload').onclick = load;
75
+ $('forget').onclick = () => { try { localStorage.removeItem(KEY); } catch {} $('code').value = ''; };
76
+ $('code').onchange = load;
77
+ load();
78
+ </script>`;
79
 
80
  function sameSecret(offered, expected) {
81
  const a = Buffer.from(String(offered || ''));
 
115
  export function registerIServFiltered(app) {
116
  app.get('/iserv/health', (req, res) => res.json({ status: 'ok' }));
117
  app.get('/iserv/freigabe', (req, res) => res.set('Cache-Control', 'no-store').type('html').send(FORM));
118
+ const approver = async (req, res, next) => {
119
+ res.set('Cache-Control', 'no-store');
120
  const approve = process.env.APPROVE_TOKEN;
121
  if (approve === process.env.API_BEARER_TOKEN || !sameSecret(req.body?.code, approve)) {
122
  await new Promise((r) => setTimeout(r, 1000)); // slows guessing
123
+ return res.status(401).json({ error: 'unauthorized' });
124
  }
125
+ next();
126
+ };
127
+ const json = express.json({ limit: '4kb' });
128
+ app.post('/iserv/freigabe/liste', json, approver, (req, res) => {
129
+ const now = Date.now();
130
+ const items = [...pending].filter(([, v]) => v.until > now).map(([id, v]) => ({ id, name: v.name, aufgabe: v.aufgabe }));
131
+ res.json({ pending: items });
132
+ });
133
+ app.post('/iserv/freigabe', json, approver, (req, res) => {
134
+ const ids = (Array.isArray(req.body.ids) ? req.body.ids : []).filter((i) => typeof i === 'string' && /^\d{1,12}-\d{1,3}$/.test(i));
135
+ ids.forEach((id) => { releases.set(id, Date.now() + RELEASE_MS); pending.delete(id); });
136
+ res.json({ released: ids });
137
  });
138
  app.get('/iserv/tasks', async (req, res) => {
139
  res.set('Cache-Control', 'no-store');
 
148
  const job = running.then(run, run);
149
  running = job.catch(() => {});
150
  const { status, body } = await job;
151
+ for (const t of body.tasks || []) { // remember what Muse has to ask the user about
152
+ for (const a of t.anhaenge || []) if (a.freigabe) pending.set(a.freigabe, { name: a.name, aufgabe: t.titel, until: Date.now() + 60 * 60_000 });
153
+ }
154
  res.status(status).json(body);
155
  });
156
  }
tests/iserv-release.test.mjs CHANGED
@@ -9,29 +9,35 @@ const app = express();
9
  registerIServFiltered(app);
10
  const server = app.listen(0);
11
  const base = `http://127.0.0.1:${server.address().port}`;
12
- const post = (code, ids) => fetch(`${base}/iserv/freigabe`, {
13
- method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
14
- body: new URLSearchParams({ code, ids }),
15
  });
16
 
17
- test('form is served, wrong code and the API token are refused', async () => {
18
- assert.match(await (await fetch(`${base}/iserv/freigabe`)).text(), /Freigabe-Code/);
19
- assert.equal((await post('x'.repeat(20), '1-0')).status, 401);
20
- assert.equal((await post(process.env.API_BEARER_TOKEN, '1-0')).status, 401);
 
21
  });
22
 
23
- test('right code accepts only well-formed ids and echoes nothing else', async () => {
24
- const r = await post(process.env.APPROVE_TOKEN, '12-0, <script>, 7-1');
25
- const t = await r.text();
26
- assert.equal(r.status, 200);
27
- assert.match(t, /12-0, 7-1/);
28
- assert.doesNotMatch(t, /script/);
 
 
 
 
 
 
29
  });
30
 
31
  test('no approve token configured: nothing can be released', async () => {
32
  const saved = process.env.APPROVE_TOKEN;
33
  delete process.env.APPROVE_TOKEN;
34
- assert.equal((await post('', '1-0')).status, 401);
35
  process.env.APPROVE_TOKEN = saved;
36
  server.close();
37
  });
 
9
  registerIServFiltered(app);
10
  const server = app.listen(0);
11
  const base = `http://127.0.0.1:${server.address().port}`;
12
+ const post = (path, body) => fetch(`${base}/iserv/freigabe${path}`, {
13
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
 
14
  });
15
 
16
+ test('page is served with the stored-code and list logic', async () => {
17
+ const t = await (await fetch(`${base}/iserv/freigabe`)).text();
18
+ assert.match(t, /Freigabe-Code/);
19
+ assert.match(t, /localStorage/);
20
+ assert.match(t, /type="password"/);
21
  });
22
 
23
+ test('wrong code and the API token are refused on both routes', async () => {
24
+ for (const path of ['', '/liste']) {
25
+ assert.equal((await post(path, { code: 'x'.repeat(20), ids: ['1-0'] })).status, 401);
26
+ assert.equal((await post(path, { code: process.env.API_BEARER_TOKEN, ids: ['1-0'] })).status, 401);
27
+ }
28
+ });
29
+
30
+ test('right code lists nothing at first and accepts only well-formed ids', async () => {
31
+ const code = process.env.APPROVE_TOKEN;
32
+ assert.deepEqual(await (await post('/liste', { code })).json(), { pending: [] });
33
+ const r = await post('', { code, ids: ['12-0', '<script>', '7-1', 5] });
34
+ assert.deepEqual(await r.json(), { released: ['12-0', '7-1'] });
35
  });
36
 
37
  test('no approve token configured: nothing can be released', async () => {
38
  const saved = process.env.APPROVE_TOKEN;
39
  delete process.env.APPROVE_TOKEN;
40
+ assert.equal((await post('', { code: '', ids: ['1-0'] })).status, 401);
41
  process.env.APPROVE_TOKEN = saved;
42
  server.close();
43
  });