clavarium 0.2.529-next.1 → 0.2.531-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/deploy/clavarium-host +32 -10
- package/deploy/multipass-refresh.mjs +30 -5
- package/deploy/updater.mjs +1 -14
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/api.mjs +5 -47
- package/server/apikeys.mjs +3 -5
- package/server/bridge.mjs +2 -16
- package/server/dataformat.mjs +1 -5
- package/server/door.mjs +16 -44
- package/server/files.mjs +4 -7
- package/server/grants.mjs +2 -6
- package/server/main.mjs +6 -60
- package/server/operators.mjs +3 -26
- package/server/serverlogs.mjs +15 -8
- package/server/settingswords.mjs +2 -2
- package/server/sshconsole.mjs +2 -16
- package/server/vmwatch.mjs +19 -8
- package/web/app.js +14 -76
- package/web/index.html +3 -2
- package/web/style.css +14 -20
- package/server/people.mjs +0 -141
- package/web/member.js +0 -26
package/deploy/clavarium-host
CHANGED
|
@@ -956,10 +956,21 @@ case "$AREA $VERB" in
|
|
|
956
956
|
"vm revive")
|
|
957
957
|
# The VM manager has not answered for minutes: its daemon restarted
|
|
958
958
|
# (every machine is suspended and resumed). Asked by the server as its
|
|
959
|
-
# owner chose (vmwatch.mjs: at night, always, or never by itself)
|
|
960
|
-
#
|
|
961
|
-
|
|
962
|
-
|
|
959
|
+
# owner chose (vmwatch.mjs: at night, always, or never by itself); or by
|
|
960
|
+
# its owner, confirmed in Settings, Machines.
|
|
961
|
+
# hard (25-11: a restart left it mute for hours): stopped, its daemon process
|
|
962
|
+
# ended if it stayed (by its exact name), then started.
|
|
963
|
+
[ $# -le 1 ] || usage
|
|
964
|
+
if [ $# -eq 1 ]; then
|
|
965
|
+
[ "$1" = "hard" ] || refuse "vm revive [hard]"
|
|
966
|
+
if [ "$SAY" = "yes" ]; then echo "snap stop multipass.multipassd; pkill -KILL -x multipassd; snap start multipass.multipassd"; exit 0; fi
|
|
967
|
+
timeout 120 snap stop multipass.multipassd || true
|
|
968
|
+
pkill -KILL -x multipassd 2>/dev/null || true
|
|
969
|
+
sleep 2
|
|
970
|
+
run timeout 120 snap start multipass.multipassd
|
|
971
|
+
else
|
|
972
|
+
run timeout 170 snap restart multipass.multipassd
|
|
973
|
+
fi ;;
|
|
963
974
|
"vm states")
|
|
964
975
|
# EVERY MACHINE'S STATE AT ONCE: one question to the VM manager instead of one per
|
|
965
976
|
# machine. It answers one question at a time, and a machine frozen inside makes each
|
|
@@ -1219,13 +1230,15 @@ case "$AREA $VERB" in
|
|
|
1219
1230
|
# WHAT THE SERVER'S PROGRAMS SAID, for Settings (This server, Logs): one
|
|
1220
1231
|
# source, over a span; read-only, bounded. The page masks what looks
|
|
1221
1232
|
# like a secret before showing it.
|
|
1222
|
-
# server logs <clavarium|machines|updates|web|signin|tunnel|system> <10m|1|6|24|168|boot>
|
|
1233
|
+
# server logs <clavarium|machines|updates|web|signin|tunnel|system> <10m|1|6|24|168|boot|prev> [<from> <until> [<lines>]]
|
|
1234
|
+
# prev: the boot BEFORE this one (what led to a restart, 25-11). <from> <until>: a window, HH:MM or
|
|
1235
|
+
# YYYY-MM-DD HH:MM (or - for none), within that boot for boot and prev. <lines>: the newest 50 to 20000.
|
|
1223
1236
|
# 17-11: a journal flooded by sudo (a line a second, the server's own calls of this program)
|
|
1224
1237
|
# took more than the page waits. The server's unit is read by indexed fields, its own output
|
|
1225
1238
|
# only (stdout), not sudo's syslog lines; sudo and PAM session lines are left out of any
|
|
1226
1239
|
# source; the read is given LOGS_SECONDS, then what it said by then is shown, with a NOTE
|
|
1227
1240
|
# on stderr -- never a bare failure.
|
|
1228
|
-
[ $# -
|
|
1241
|
+
[ $# -ge 2 ] && [ $# -le 5 ] || usage
|
|
1229
1242
|
# A unit by its fields: what it wrote, and what systemd said of it.
|
|
1230
1243
|
unit() { printf '%s\n' "_SYSTEMD_UNIT=$1" + "UNIT=$1" "_PID=1" +; }
|
|
1231
1244
|
case "$1" in
|
|
@@ -1242,13 +1255,22 @@ case "$AREA $VERB" in
|
|
|
1242
1255
|
system) matches=(-k) ;;
|
|
1243
1256
|
*) refuse "not a source of logs: $1" ;;
|
|
1244
1257
|
esac
|
|
1245
|
-
case "$2" in 10m) since=(--since "-10min") ;; 1|6|24|168) since=(--since "-$2h") ;; boot) since=(-b) ;; *) refuse "not a span: $2 (10m, 1, 6, 24, 168 hours, or
|
|
1246
|
-
|
|
1247
|
-
|
|
1258
|
+
case "$2" in 10m) since=(--since "-10min") ;; 1|6|24|168) since=(--since "-$2h") ;; boot) since=(-b) ;; prev) since=(-b -1) ;; *) refuse "not a span: $2 (10m, 1, 6, 24, 168 hours, boot or prev)" ;; esac
|
|
1259
|
+
window='^([0-9]{4}-[0-9]{2}-[0-9]{2} )?[0-9]{2}:[0-9]{2}$'
|
|
1260
|
+
from="${3:--}"; until="${4:--}"; lines="${5:-20000}"
|
|
1261
|
+
[ "$from" = "-" ] || [[ "$from" =~ $window ]] || refuse "not a time: $from (HH:MM or YYYY-MM-DD HH:MM)"
|
|
1262
|
+
[ "$until" = "-" ] || [[ "$until" =~ $window ]] || refuse "not a time: $until (HH:MM or YYYY-MM-DD HH:MM)"
|
|
1263
|
+
[[ "$lines" =~ ^[0-9]{2,5}$ ]] && [ "$lines" -ge 50 ] && [ "$lines" -le 20000 ] || refuse "not a number of lines: $lines (50 to 20000)"
|
|
1264
|
+
# A window replaces an hour span; within a boot it narrows it.
|
|
1265
|
+
if [ "$from" != "-" ] || [ "$until" != "-" ]; then case "$2" in boot|prev) : ;; *) since=() ;; esac; fi
|
|
1266
|
+
[ "$from" = "-" ] || since+=(--since "$from")
|
|
1267
|
+
[ "$until" = "-" ] || since+=(--until "$until")
|
|
1268
|
+
# The newest $lines lines at most (20000 by default): more is too much to read on a page, and to send.
|
|
1269
|
+
if [ "$SAY" = "yes" ]; then echo "journalctl ${matches[*]} ${since[*]} -o short-iso --no-pager -q -n $lines (sudo and PAM session lines left out; ${LOGS_SECONDS}s at most)"; exit 0; fi
|
|
1248
1270
|
out="$(mktemp)"; err="$(mktemp)"
|
|
1249
1271
|
trap 'rm -f -- "$out" "$err"' EXIT
|
|
1250
1272
|
code=0
|
|
1251
|
-
timeout -k 5 "$LOGS_SECONDS" "$JOURNALCTL" "${matches[@]}" "${since[@]}" -o short-iso --no-pager -q -n
|
|
1273
|
+
timeout -k 5 "$LOGS_SECONDS" "$JOURNALCTL" "${matches[@]}" "${since[@]}" -o short-iso --no-pager -q -n "$lines" >"$out" 2>"$err" || code=$?
|
|
1252
1274
|
grep -avE ' (sudo|pkexec)\[[0-9]+\]: | pam_unix\((sudo|sudo-i|pkexec):session\)' "$out" | cut -c1-2000 || true
|
|
1253
1275
|
case "$code" in
|
|
1254
1276
|
0) : ;;
|
|
@@ -55,21 +55,46 @@ export async function multipassTurn({ run, mode, inWindow, busy, state, save, lo
|
|
|
55
55
|
}
|
|
56
56
|
|
|
57
57
|
const answers = async () => { for (let i = 0; i < BACK_TRIES; i += 1) { if ((await sh([multipass, 'list', '--format', 'json'], 30_000)).code === 0) return true; await sleep(BACK_EVERY_MS); } return false; };
|
|
58
|
+
/* MUTE AFTER ITS UPDATE (25-11, on a real server: four machines started, then its daemon died and stayed mute for
|
|
59
|
+
three hours). Not waited for: its daemon restarted, then stopped and started for sure, then -- right after its
|
|
60
|
+
own update -- snap's previous revision of it put back. Each step said. True once it answers. */
|
|
61
|
+
const rescue = async ({ updated }) => {
|
|
62
|
+
if (await answers()) return true;
|
|
63
|
+
const steps = [
|
|
64
|
+
['its daemon is restarted', ['snap', 'restart', 'multipass.multipassd']],
|
|
65
|
+
['its daemon is stopped and started for sure', null],
|
|
66
|
+
...(updated ? [['its previous version is put back', ['snap', 'revert', 'multipass']]] : []),
|
|
67
|
+
];
|
|
68
|
+
for (const [what, argv] of steps) {
|
|
69
|
+
log(`multipass: it does not answer: ${what}`);
|
|
70
|
+
if (argv) await sh(argv, REFRESH_MS);
|
|
71
|
+
else { await sh(['snap', 'stop', 'multipass.multipassd'], SNAP_MS); await sh(['pkill', '-KILL', '-x', 'multipassd'], 30_000); await sleep(2_000); await sh(['snap', 'start', 'multipass.multipassd'], SNAP_MS); }
|
|
72
|
+
if (await answers()) { log(`multipass: it answers again (${what})`); return true; }
|
|
73
|
+
}
|
|
74
|
+
return false;
|
|
75
|
+
};
|
|
58
76
|
/* Started again; what could not be stays written down, for the next turn. */
|
|
59
|
-
const back = async (names) => {
|
|
60
|
-
if (!(await
|
|
77
|
+
const back = async (names, { updated = false } = {}) => {
|
|
78
|
+
if (!(await rescue({ updated }))) { log('multipass: it still does not answer: its machines are started at the next turn; the server\'s watch keeps trying'); return names; }
|
|
61
79
|
const left = [];
|
|
62
80
|
for (const name of names) {
|
|
63
81
|
let r = await sh([multipass, 'start', name], MACHINE_MS);
|
|
64
82
|
if (r.code !== 0) { await sleep(BACK_EVERY_MS); r = await sh([multipass, 'start', name], MACHINE_MS); }
|
|
65
|
-
if (r.code !== 0) {
|
|
83
|
+
if (r.code !== 0) {
|
|
84
|
+
/* It died while they were started (25-11): rescued, then this one tried once more. */
|
|
85
|
+
const mute = (await sh([multipass, 'list', '--format', 'json'], 30_000)).code !== 0;
|
|
86
|
+
if (mute && await rescue({ updated })) r = await sh([multipass, 'start', name], MACHINE_MS);
|
|
87
|
+
if (r.code !== 0) { left.push(name); log(`multipass: ${name} could not be started again: ${first(r)}`); }
|
|
88
|
+
}
|
|
66
89
|
}
|
|
67
90
|
return left;
|
|
68
91
|
};
|
|
69
92
|
|
|
70
93
|
const pending = state().multipassRefresh?.machines ?? [];
|
|
71
94
|
if (pending.length) {
|
|
72
|
-
|
|
95
|
+
/* Its own update lately (a day): putting its previous version back is still one of the ways. */
|
|
96
|
+
const lately = Date.parse(state().multipassRefresh?.triedAt ?? '');
|
|
97
|
+
const left = await back(pending, { updated: Number.isFinite(lately) && now() - lately < 86_400_000 });
|
|
73
98
|
save({ multipassRefresh: { ...state().multipassRefresh, machines: left } });
|
|
74
99
|
if (left.length) return `${left.length} machine(s) still to start again`;
|
|
75
100
|
log('multipass: the machines of the last update are running again');
|
|
@@ -103,7 +128,7 @@ export async function multipassTurn({ run, mode, inWindow, busy, state, save, lo
|
|
|
103
128
|
/* --ignore-running: a client of Multipass still open (a terminal, a command) would make snap refuse (seen on a real machine); its machine is asleep. */
|
|
104
129
|
const done = await sh(['snap', 'refresh', 'multipass', '--ignore-running'], REFRESH_MS);
|
|
105
130
|
log(done.code === 0 ? 'multipass: updated' : `multipass: its update failed: ${first(done)}`);
|
|
106
|
-
const left = await back(running);
|
|
131
|
+
const left = await back(running, { updated: done.code === 0 });
|
|
107
132
|
save({ multipassRefresh: { ...state().multipassRefresh, machines: left } });
|
|
108
133
|
log(left.length ? `multipass: ${left.length} machine(s) to start again at the next turn` : 'multipass: its machines are running again');
|
|
109
134
|
return done.code === 0 ? 'updated' : 'update failed';
|
package/deploy/updater.mjs
CHANGED
|
@@ -666,15 +666,6 @@ export class Updater {
|
|
|
666
666
|
const live = busy.filter((c) => !stale.includes(c));
|
|
667
667
|
return live.length ? `a machine is being built or restarted (${names(live)}): the update waits` : '';
|
|
668
668
|
}
|
|
669
|
-
/* MEMBERS AND AN OLDER RELEASE (#419). A release from before accounts and rights takes every account for an
|
|
670
|
-
administrator: once accounts and rights were used here (people.json written, at the first member), going back to
|
|
671
|
-
one is refused, by hand and by the watchdog -- as for a release that cannot read the data. Undefined: allowed. */
|
|
672
|
-
#membersBlock(to) {
|
|
673
|
-
/* A release that reads the lists of today (0.2.526-next.1 wrote another form: refused too). */
|
|
674
|
-
try { if (readFileSync(join(to.app, 'server', 'people.mjs'), 'utf8').includes('export const PEOPLE_LISTS')) return undefined; } catch { /* none: from before accounts */ }
|
|
675
|
-
const file = join(this.#o.data, 'people.json');
|
|
676
|
-
return existsSync(file) || existsSync(`${file}.bak`) ? `${to.version} does not know these members: it would not read who is an administrator` : undefined;
|
|
677
|
-
}
|
|
678
669
|
#dataFormat() { try { return JSON.parse(readFileSync(join(this.#o.data, 'data-format.json'), 'utf8')).format; } catch { return undefined; } }
|
|
679
670
|
|
|
680
671
|
#lock() {
|
|
@@ -710,9 +701,6 @@ export class Updater {
|
|
|
710
701
|
this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: error.message, ...(fetched ? { fetch: true } : {}), ...(typeof error.log === 'string' && error.log ? { log: error.log.slice(-LOG_MAX) } : {}) });
|
|
711
702
|
throw error;
|
|
712
703
|
}
|
|
713
|
-
/* Members here, and a release that would not read them (a newer number cut without them, say): not installed. */
|
|
714
|
-
const blocked = this.#membersBlock(release);
|
|
715
|
-
if (blocked) { rmSync(release.dir, { recursive: true, force: true }); this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: blocked }); throw new Refused(blocked); }
|
|
716
704
|
const before = this.#dataFormat();
|
|
717
705
|
let archive;
|
|
718
706
|
try {
|
|
@@ -754,7 +742,6 @@ export class Updater {
|
|
|
754
742
|
if (to.current) throw new Refused(`${id} is the release that runs`);
|
|
755
743
|
const format = this.#dataFormat();
|
|
756
744
|
if (format !== undefined && to.dataFormat < format) throw new Refused(`${to.version} cannot read the data of this version (format ${format}; it reads ${to.dataFormat})`);
|
|
757
|
-
const members = this.#membersBlock(to); if (members) throw new Refused(members);
|
|
758
745
|
const why = await this.busy(); if (why) throw new Refused(why);
|
|
759
746
|
const unlock = this.#lock();
|
|
760
747
|
try {
|
|
@@ -883,7 +870,7 @@ export class Updater {
|
|
|
883
870
|
const recent = failed && current && last && last.action === 'update' && last.result === 'done' && last.to === current.version && now - new Date(last.at) < WATCH_RECENT_MS;
|
|
884
871
|
const previous = recent ? this.releases().find((r) => !r.current && r.version === last.from) : undefined;
|
|
885
872
|
const format = this.#dataFormat();
|
|
886
|
-
if (previous && (format === undefined || previous.dataFormat >= format)
|
|
873
|
+
if (previous && (format === undefined || previous.dataFormat >= format)) {
|
|
887
874
|
let why = `${current.version} did not stay up (its service ${state === 'active' ? 'did not answer' : `was ${state}`}) nor came back after a restart (${failed}): back to ${previous.version}`;
|
|
888
875
|
this.#o.log(`watchdog: ${why}`);
|
|
889
876
|
this.#step('update', current.version, 'Going back');
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.531-next.1",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "clavarium",
|
|
9
|
-
"version": "0.2.
|
|
9
|
+
"version": "0.2.531-next.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
package/package.json
CHANGED
package/server/api.mjs
CHANGED
|
@@ -486,15 +486,14 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
486
486
|
}
|
|
487
487
|
/* What this server asked of the host, by 5-minute window, and its own event loop (vm.mjs HostTally). */
|
|
488
488
|
if (pathname === '/api/server/load' && serverLogs) return send(200, serverLogs.load()), true;
|
|
489
|
-
if (pathname === '/api/server/logs' && serverLogs) { const r = await serverLogs.start(query.get('source') ?? 'clavarium', query.get('span') ?? '10m'); return send(r.pending ? 202 : 200, r), true; }
|
|
489
|
+
if (pathname === '/api/server/logs' && serverLogs) { const r = await serverLogs.start(query.get('source') ?? 'clavarium', query.get('span') ?? '10m', undefined, { from: query.get('from') || undefined, until: query.get('until') || undefined, lines: query.get('lines') || undefined }); return send(r.pending ? 202 : 200, r), true; }
|
|
490
490
|
if (pathname === '/api/machines/disks' && machinesMove) return send(200, await machinesMove.disks()), true;
|
|
491
491
|
if (pathname === '/api/machines/places' && machinesMove) return send(200, await machinesMove.places()), true;
|
|
492
492
|
if (pathname === '/api/machines/moving' && machinesMove) return send(200, await machinesMove.moving()), true;
|
|
493
493
|
if (pathname === '/api/wifi' && wifi) return send(200, await wifi.status()), true;
|
|
494
494
|
if (pathname === '/api/wifi/scan' && wifi) return send(200, await wifi.scan()), true;
|
|
495
495
|
if (pathname === '/api/meshcentral' && meshcentral) return send(200, await meshcentral.status()), true;
|
|
496
|
-
|
|
497
|
-
if (pathname === '/api/operators') return send(200, team ? { operators: team.list().map((o) => ({ ...o, role: team.people?.roleOf(o.email) ?? 'admin', ...(team.people?.roleOf(o.email) === 'member' ? { given: team.grants?.of(`person:${o.email}`, 'conversation').map((g) => ({ name: g.name, rights: g.rights })) ?? [] } : {}) })), me: identity, defaultRole: team.people?.defaultRole?.() ?? 'admin' } : { local: true }), true;
|
|
496
|
+
if (pathname === '/api/operators') return send(200, team ? { operators: team.list(), me: identity } : { local: true }), true;
|
|
498
497
|
if (pathname === '/api/binder/people' && binders) return send(200, { people: binders.people(identity), changes: `${BOOT}:${binders.changes()}` }), true;
|
|
499
498
|
if (pathname === '/api/certificate' && certificate) return send(200, await certificate.about({ fresh: query.get('fresh') === '1' })), true;
|
|
500
499
|
/* This server's disk and memory (capacity.mjs): everything for Settings; only whether it is high for the list. */
|
|
@@ -592,7 +591,6 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
592
591
|
return send(403, { error: 'This request does not come from this site.' }), true;
|
|
593
592
|
}
|
|
594
593
|
const body = await readBody(request, pathname === '/api/setup/preview' || pathname === '/api/setup/import' ? SETUP_BODY_MAX : BODY_MAX);
|
|
595
|
-
if (request.stillAllowed && !request.stillAllowed()) throw new Refusal(403, 'Your account changed: sign in again.');
|
|
596
594
|
/* A SIGN-IN CODE (#405): answered before anything below can see this body (the journal, say). */
|
|
597
595
|
const codeOf = /^\/api\/conversations\/([^/]+)\/signin-code$/.exec(pathname);
|
|
598
596
|
if (codeOf && conversations.signinHelp) return send(200, await conversations.signinHelp.enterCode(decodeURIComponent(codeOf[1]), body?.code)), true;
|
|
@@ -793,53 +791,13 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
793
791
|
if (pathname === '/api/wifi/handover' && wifi) return send(202, await wifi.handover()), true;
|
|
794
792
|
if (pathname === '/api/meshcentral/enable' && meshcentral) return send(202, await meshcentral.enable()), true;
|
|
795
793
|
if (pathname === '/api/meshcentral/disable' && meshcentral) return send(200, await meshcentral.disable()), true;
|
|
796
|
-
if (pathname === '/api/operators' && team)
|
|
797
|
-
/* Its role said at once (#419): an account removed and added again does not come back as it was. */
|
|
798
|
-
const role = body.role === 'member' ? 'member' : body.role === 'admin' ? 'admin' : (team.people?.defaultRole?.() ?? 'admin');
|
|
799
|
-
const adding = String(body.email ?? '').trim().toLowerCase();
|
|
800
|
-
/* An account there already keeps its role: changed by its own way, with its checks (audit 6, 24-11). */
|
|
801
|
-
if (team.list().some((o) => o.email === adding)) throw new Refusal(409, 'This account exists already.');
|
|
802
|
-
/* Nothing of a past account of that address comes back with the new one. */
|
|
803
|
-
team.grants?.forgetSubject(`person:${adding}`);
|
|
804
|
-
const undo = team.people?.adding(adding, role);
|
|
805
|
-
let made;
|
|
806
|
-
try { made = await team.add(body.email); } catch (error) { undo?.(); throw error; }
|
|
807
|
-
return send(201, { ...made, role: team.people?.roleOf(made.email) ?? 'admin' }), true;
|
|
808
|
-
}
|
|
809
|
-
/* An account made an administrator or a member (#419): never oneself, never the last administrator. */
|
|
810
|
-
const roleOf = /^\/api\/operators\/([^/]{3,200})\/role$/.exec(pathname);
|
|
811
|
-
if (roleOf && team?.people) {
|
|
812
|
-
const email = decodeURIComponent(roleOf[1]).trim().toLowerCase();
|
|
813
|
-
if (email === identity) throw new Refusal(409, 'You cannot change your own role: ask another administrator.');
|
|
814
|
-
const changed = team.people.setRole(email, String(body.role ?? ''));
|
|
815
|
-
/* Made an administrator: what it was given as a member is forgotten, not given back if it is a member again (audit 13). */
|
|
816
|
-
if (team.people.roleOf(email) === 'admin') team.grants?.forgetSubject(`person:${email}`);
|
|
817
|
-
return send(200, { operators: changed }), true;
|
|
818
|
-
}
|
|
819
|
-
/* A conversation given to a member, or taken back: its chat (read or write) and/or its terminal (#419). */
|
|
820
|
-
const giving = /^\/api\/operators\/([^/]{3,200})\/(give|take)$/.exec(pathname);
|
|
821
|
-
if (giving && team?.people && team.grants) {
|
|
822
|
-
const email = decodeURIComponent(giving[1]).trim().toLowerCase();
|
|
823
|
-
if (!team.list().some((o) => o.email === email)) throw new Refusal(404, 'No such account.');
|
|
824
|
-
if (team.people.roleOf(email) !== 'member') throw new Refusal(409, 'Only a member is given conversations: an administrator has them all.');
|
|
825
|
-
const name = String(body.conversation ?? '');
|
|
826
|
-
if (!conversations.list().some((c) => c.name === name)) throw new Refusal(404, 'No such conversation.');
|
|
827
|
-
const rights = giving[2] === 'take' ? '' : `${body.chat === 'write' ? 'rw' : body.chat === 'read' ? 'r' : ''}${body.terminal === true ? 'x' : ''}`;
|
|
828
|
-
if (rights === '') team.grants.take(`person:${email}`, `conversation:${name}`);
|
|
829
|
-
else team.grants.give(`person:${email}`, `conversation:${name}`, rights);
|
|
830
|
-
team.people.changed?.();
|
|
831
|
-
return send(200, { given: team.grants.of(`person:${email}`, 'conversation').map((g) => ({ name: g.name, rights: g.rights })) }), true;
|
|
832
|
-
}
|
|
794
|
+
if (pathname === '/api/operators' && team) return send(201, await team.add(body.email)), true;
|
|
833
795
|
const op = /^\/api\/operators\/([^/]{3,200})\/(password|disable|enable|remove)$/.exec(pathname);
|
|
834
796
|
if (op && team) {
|
|
835
|
-
const email = decodeURIComponent(op[1])
|
|
797
|
+
const email = decodeURIComponent(op[1]);
|
|
836
798
|
/* Not oneself out: another operator does it, or nobody would see it was a mistake. */
|
|
837
799
|
if (op[2] !== 'password' && op[2] !== 'enable' && email.toLowerCase() === identity) throw new Refusal(409, 'You cannot do that to your own account: ask another operator.');
|
|
838
|
-
|
|
839
|
-
/* Removed: its role and what it was given go with it (#419). */
|
|
840
|
-
if (op[2] === 'remove') { team.people?.removed(email); team.grants?.forgetSubject(`person:${email.toLowerCase()}`); }
|
|
841
|
-
team.people?.changed?.();
|
|
842
|
-
return send(200, done), true;
|
|
800
|
+
return send(200, op[2] === 'password' ? await team.password(email) : { operators: await team[op[2]](email) }), true;
|
|
843
801
|
}
|
|
844
802
|
const renaming = /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/rename$/.exec(pathname);
|
|
845
803
|
/* Its machines that run get the new name or value now, as a secret given to them does. */
|
package/server/apikeys.mjs
CHANGED
|
@@ -599,8 +599,8 @@ export const PROFILE_TOOL = {
|
|
|
599
599
|
export const LOGS_TOOL = {
|
|
600
600
|
name: 'clavarium_logs',
|
|
601
601
|
title: 'Logs of this Clavarium',
|
|
602
|
-
description: 'Read-only: what one of the server\'s programs said
|
|
603
|
-
inputSchema: { type: 'object', properties: { source: { type: 'string' }, span: { type: 'string' } }, additionalProperties: false },
|
|
602
|
+
description: 'Read-only: what one of the server\'s programs said, as Settings reads it (secrets masked). source: clavarium (default), machines, updates, web, signin, tunnel, system. span: 10m (default), 1, 6, 24, 168 (hours), boot (since this start) or prev (the start before it: what led to a restart). from/until: a window, HH:MM or YYYY-MM-DD HH:MM (within boot or prev for those). lines: the newest 50 to 20000 (2000 by default here). A big journal takes a while: {pending: true} means ask again in a moment.',
|
|
603
|
+
inputSchema: { type: 'object', properties: { source: { type: 'string' }, span: { type: 'string' }, from: { type: 'string' }, until: { type: 'string' }, lines: { type: 'integer', minimum: 50, maximum: 20000 } }, additionalProperties: false },
|
|
604
604
|
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
605
605
|
};
|
|
606
606
|
export const CONVERSATIONS_TOOL = {
|
|
@@ -1233,7 +1233,7 @@ export async function handleExternal(request, response, { keys, status, chats =
|
|
|
1233
1233
|
if (!diagnostics) throw new Refusal(404, 'Not available on this server.');
|
|
1234
1234
|
if (name === LOAD_TOOL.name) return result(diagnostics.load());
|
|
1235
1235
|
if (name === PROFILE_TOOL.name) return result(await diagnostics.profile(args.seconds ?? 10));
|
|
1236
|
-
const r = await diagnostics.logs(typeof args.source === 'string' ? args.source : 'clavarium', typeof args.span === 'string' ? args.span : '10m');
|
|
1236
|
+
const r = await diagnostics.logs(typeof args.source === 'string' ? args.source : 'clavarium', typeof args.span === 'string' ? args.span : '10m', { from: typeof args.from === 'string' ? args.from : undefined, until: typeof args.until === 'string' ? args.until : undefined, lines: Number.isInteger(args.lines) ? args.lines : 2000 });
|
|
1237
1237
|
return result(r.pending ? r : { ...r, text: masked(r.text ?? '') });
|
|
1238
1238
|
}
|
|
1239
1239
|
if (name === JOB_LOG_TOOL.name) {
|
|
@@ -1320,8 +1320,6 @@ export async function handleApiKeys(request, response, keys, originOk, headers =
|
|
|
1320
1320
|
for await (const piece of request) { text += piece; if (text.length > 16_384) return send(413, { error: 'Too long.' }); }
|
|
1321
1321
|
let body;
|
|
1322
1322
|
try { body = text ? JSON.parse(text) : {}; } catch { return send(400, { error: 'The request is not JSON.' }); }
|
|
1323
|
-
/* One made a member or disabled while its request came makes no key (audit 8). */
|
|
1324
|
-
if (request.stillAllowed && !request.stillAllowed()) return send(403, { error: 'Your account changed: sign in again.' });
|
|
1325
1323
|
if (!body || typeof body !== 'object') body = {};
|
|
1326
1324
|
if (pathname === '/api/apikeys') {
|
|
1327
1325
|
const made = keys.create({ label: body.label, scopes: body.scopes ?? [], conversations: body.conversations ?? {}, rooms: body.rooms ?? {}, boxes: body.boxes ?? {}, binders: body.binders ?? {}, days: body.days === undefined ? DEFAULT_DAYS : body.days }, who);
|
package/server/bridge.mjs
CHANGED
|
@@ -90,9 +90,7 @@ export const sameOrigin = makeOriginCheck();
|
|
|
90
90
|
const BY_ITSELF = /\x1b\[[IO]|\x1b\[\??[>=]?[\d;]*c|\x1b\[\d+;\d+R|\x1b\][\d;]*(?:rgb:[0-9a-fA-F/]+)?(?:\x07|\x1b\\)|\x1bP[^\x1b]*\x1b\\/g;
|
|
91
91
|
export const byHand = (typed) => String(typed ?? '').replace(BY_ITSELF, '').length > 0;
|
|
92
92
|
|
|
93
|
-
export
|
|
94
|
-
|
|
95
|
-
export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () => {}, originOk = sameOrigin, gate = () => 'local', deviceName = () => undefined, memberName = () => undefined, onRejoin = () => {}, onTyped = () => {}, asleep = () => false }) {
|
|
93
|
+
export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () => {}, originOk = sameOrigin, gate = () => 'local', deviceName = () => undefined, onRejoin = () => {}, onTyped = () => {}, asleep = () => false }) {
|
|
96
94
|
const sockets = new WebSocketServer({ noServer: true });
|
|
97
95
|
const seats = new Seats();
|
|
98
96
|
/* THE DEVICES AT A TERMINAL, each with what lets it stay: asked again when the owner changes
|
|
@@ -100,8 +98,6 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
100
98
|
back used to end only at the next connection -- an open terminal went on (found 19-10). */
|
|
101
99
|
const deviceSeats = new Map(); /* viewer -> () => still allowed */
|
|
102
100
|
const revoked = new WeakSet();
|
|
103
|
-
/* Who a screen is, for What happened: a paired device, a member (#419), else the page of an administrator. */
|
|
104
|
-
const fromDevice = new WeakSet(); const fromMember = new WeakSet();
|
|
105
101
|
const allowed = (viewer) => {
|
|
106
102
|
if (revoked.has(viewer)) return false;
|
|
107
103
|
const still = deviceSeats.get(viewer);
|
|
@@ -124,18 +120,9 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
124
120
|
name = ask();
|
|
125
121
|
if (!isConversationName(name) || !originOk(request.headers)) { socket.destroy(); return; }
|
|
126
122
|
still = () => ask() === name;
|
|
127
|
-
} else if (url.pathname === MEMBER_PATH) {
|
|
128
|
-
/* A member (people.mjs, #419): the sign-in names it; the terminal of a conversation it was given, only. */
|
|
129
|
-
const wanted = url.searchParams.get('c') ?? '';
|
|
130
|
-
const ask = () => memberName(request.headers, wanted) ?? '';
|
|
131
|
-
name = ask();
|
|
132
|
-
if (!isConversationName(name) || !originOk(request.headers)) { socket.destroy(); return; }
|
|
133
|
-
still = () => ask() === name;
|
|
134
123
|
} else if (url.pathname === PATH) {
|
|
135
124
|
name = url.searchParams.get('c') ?? '';
|
|
136
125
|
if (!isConversationName(name) || !originOk(request.headers) || gate(request.headers) === undefined) { socket.destroy(); return; }
|
|
137
|
-
/* An administrator made a member, or an account disabled: its open terminals end too (#419). */
|
|
138
|
-
still = () => gate(request.headers) !== undefined;
|
|
139
126
|
} else return;
|
|
140
127
|
const cols = Number(url.searchParams.get('cols'));
|
|
141
128
|
const rows = Number(url.searchParams.get('rows'));
|
|
@@ -143,7 +130,6 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
143
130
|
const resume = url.searchParams.get('resume') === '1';
|
|
144
131
|
sockets.handleUpgrade(request, socket, head, (viewer) => {
|
|
145
132
|
if (still) { deviceSeats.set(viewer, still); viewer.on('close', () => deviceSeats.delete(viewer)); }
|
|
146
|
-
if (url.pathname === DEVICE_PATH) fromDevice.add(viewer); else if (url.pathname === MEMBER_PATH) fromMember.add(viewer);
|
|
147
133
|
seat(viewer, name, within(cols, COLS) ? cols : 80, within(rows, ROWS) ? rows : 24, resume);
|
|
148
134
|
});
|
|
149
135
|
});
|
|
@@ -200,7 +186,7 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
200
186
|
}
|
|
201
187
|
async function openNow(name, cols, rows, sink, say) {
|
|
202
188
|
/* Who opens it, for What happened when it wakes a sleeper: a screen, or this server (warm). */
|
|
203
|
-
const who = sink ? (
|
|
189
|
+
const who = sink ? (deviceSeats.has(sink) ? 'a paired device' : 'a page') : undefined;
|
|
204
190
|
const terminal = await spawn(name, cols, rows, say, who);
|
|
205
191
|
/* While it was being opened another one may have been: the newest wins. */
|
|
206
192
|
if (live.has(name)) close(name);
|
package/server/dataformat.mjs
CHANGED
|
@@ -22,11 +22,8 @@ import { join } from 'node:path';
|
|
|
22
22
|
export const DATA_FORMAT = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).clavarium?.dataFormat ?? 1;
|
|
23
23
|
export const FORMAT_FILE = 'data-format.json';
|
|
24
24
|
|
|
25
|
-
/*
|
|
26
|
-
nothing changed in the files, which blocked going back; it is read as 1 and written back as 1. The next real
|
|
27
|
-
change of format is 3. (Going back to a release from before accounts once members exist: refused, deploy/updater.mjs.) */
|
|
25
|
+
/* None yet: format 1 is the only one. The next one adds its step here. */
|
|
28
26
|
export const MIGRATIONS = {};
|
|
29
|
-
const SAME_AS_1 = 2;
|
|
30
27
|
|
|
31
28
|
export function dataFormat(dataDir) {
|
|
32
29
|
try { return JSON.parse(readFileSync(join(dataDir, FORMAT_FILE), 'utf8')).format; } catch { return undefined; }
|
|
@@ -40,7 +37,6 @@ export function migrateData(dataDir, { format = DATA_FORMAT, migrations = MIGRAT
|
|
|
40
37
|
try { existing = readdirSync(dataDir).some((f) => f.endsWith('.json')); } catch { /* a new directory */ }
|
|
41
38
|
found = existing ? 1 : format;
|
|
42
39
|
}
|
|
43
|
-
if (found === SAME_AS_1 && format === 1) { write(dataDir, 1); found = 1; }
|
|
44
40
|
if (!Number.isInteger(found) || found < 1) throw new Error(`${join(dataDir, FORMAT_FILE)} does not hold a format number`);
|
|
45
41
|
if (found > format) throw new Error(`The data in ${dataDir} is in format ${found}, written by a newer Clavarium; this one reads format ${format} at most. Go back to the newer version (Settings, Updates; or deploy/updater.mjs), or restore the backup made before the update.`);
|
|
46
42
|
const ran = [];
|
package/server/door.mjs
CHANGED
|
@@ -87,18 +87,13 @@ export function devicePairing(devices, headers, pairing) {
|
|
|
87
87
|
}
|
|
88
88
|
|
|
89
89
|
/* Returns true when the request was under /c/api/ (answered here). */
|
|
90
|
-
export async function handleDoor(request, response, { devices, conversations, resources, shortcuts, voice, originOk, headers, secure, talk, repair, tethers, mailboxes, signinCode
|
|
90
|
+
export async function handleDoor(request, response, { devices, conversations, resources, shortcuts, voice, originOk, headers, secure, talk, repair, tethers, mailboxes, signinCode }) {
|
|
91
91
|
const url = new URL(request.url ?? '/', 'http://local');
|
|
92
|
-
|
|
93
|
-
pairing, no code, no key, no session of its own -- who it is comes from the gate alone, never from the address.
|
|
94
|
-
What it was given is read from the same table as a device's, under `person:<email>`. */
|
|
95
|
-
const base = person ? '/m/api' : '/c/api';
|
|
96
|
-
if (!url.pathname.startsWith(`${base}/`)) return false;
|
|
92
|
+
if (!url.pathname.startsWith('/c/api/')) return false;
|
|
97
93
|
/* "/<pairing>/me" -> the pairing and "/me"; "/pair" has no pairing yet. */
|
|
98
|
-
const named =
|
|
99
|
-
const pairing =
|
|
100
|
-
const route = named ? named[2] : url.pathname.slice(
|
|
101
|
-
const given_ = person ?? devices;
|
|
94
|
+
const named = /^\/([0-9a-f-]{36})(\/.*)$/.exec(url.pathname.slice('/c/api'.length));
|
|
95
|
+
const pairing = named?.[1];
|
|
96
|
+
const route = named ? named[2] : url.pathname.slice('/c/api'.length);
|
|
102
97
|
const send = (status, body, extra = {}) => {
|
|
103
98
|
response.writeHead(status, { ...headers, ...extra, 'content-type': 'application/json; charset=utf-8' }).end(JSON.stringify(body));
|
|
104
99
|
return true;
|
|
@@ -106,8 +101,7 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
106
101
|
try {
|
|
107
102
|
if (request.method === 'POST' && !originOk(request.headers)) return send(403, { error: 'This request does not come from this site.' });
|
|
108
103
|
|
|
109
|
-
/* ---- pairing: no session yet
|
|
110
|
-
if (person && ['/pair', '/challenge', '/session', '/leave'].includes(route)) return send(404, { error: 'Not found.' });
|
|
104
|
+
/* ---- pairing: no session yet ---- */
|
|
111
105
|
if (request.method === 'POST' && route === '/pair') return send(201, devices.pair(await readJson(request)));
|
|
112
106
|
if (request.method === 'POST' && route === '/challenge') return send(200, devices.challenge(String((await readJson(request)).device ?? '')));
|
|
113
107
|
if (request.method === 'POST' && route === '/session') {
|
|
@@ -117,21 +111,17 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
117
111
|
}
|
|
118
112
|
|
|
119
113
|
/* ---- everything else: a device session, and its one conversation ---- */
|
|
120
|
-
if (
|
|
114
|
+
if (devicePairing(devices, request.headers, pairing) === undefined) return send(401, { error: 'This device has no open session.' });
|
|
121
115
|
/* What this pairing was given: conversations to use, and things of its own to read or write. */
|
|
122
|
-
const given =
|
|
116
|
+
const given = devices.grantsOf(pairing);
|
|
123
117
|
const names = given.filter((g) => g.type === 'conversation').map((g) => g.name);
|
|
124
118
|
const own = given.filter((g) => g.type !== 'conversation').filter((g) => resources.get(g.name))
|
|
125
119
|
.map((g) => ({ name: g.name, type: g.type, access: g.rights.includes('w') ? 'write' : 'read' }));
|
|
126
|
-
const name =
|
|
120
|
+
const name = deviceConversation(devices, request.headers, pairing, url.searchParams.get('c') ?? undefined);
|
|
127
121
|
const mine = name === undefined ? undefined : conversations.list().find((c) => c.name === name);
|
|
128
122
|
/* The parts of that conversation this pairing was given. */
|
|
129
|
-
const rights = name === undefined ? '' :
|
|
123
|
+
const rights = name === undefined ? '' : devices.rightsOn(pairing, name);
|
|
130
124
|
const part = { terminal: rights.includes('x'), chat: rights.includes('r') ? (rights.includes('w') ? 'write' : 'read') : null };
|
|
131
|
-
/* A member, once a body is read: still let in, still given that right (audits 8 and 10). A device: as before. */
|
|
132
|
-
const stillMay = (right) => !person || (person.still() && given_.rightsOn(pairing, name).includes(right));
|
|
133
|
-
/* A member writing in a folder, once what it sends has come: still let in, still given it (audit 11). */
|
|
134
|
-
const writesStill = () => { if (person && !person.still()) throw new Refusal(403, 'This conversation is not shared with you any more.'); if (person && !given_.rightsOn(pairing, name).includes('x')) throw new Refusal(403, 'This conversation is not shared with you any more.'); };
|
|
135
125
|
const need = (ok, what) => { if (!ok) throw new Refusal(403, `This device was not given ${what} of this conversation.`); };
|
|
136
126
|
/* Its chat alone: what is reached through the conversation is only what its chat holds. */
|
|
137
127
|
const chatOnly = mine !== undefined && !part.terminal;
|
|
@@ -193,38 +183,20 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
193
183
|
if (request.method === 'GET' && talking[1] === '/search') return send(200, talk.search(name, url.searchParams.get('q') ?? ''));
|
|
194
184
|
/* Reminding the tool and writing to it: a chat given to write in. Nothing else (turning it on, inviting the tool) is a device's. */
|
|
195
185
|
if (request.method === 'POST' && (talking[1] === undefined || talking[1] === '/remind' || talking[1] === '/file' || talking[1] === '/react')) need(part.chat === 'write', 'the chat to write in');
|
|
196
|
-
/* A reaction or an answer to a question reaches the tool as its owner's choice: not a member's (audit 6). */
|
|
197
|
-
if (person && request.method === 'POST' && talking[1] === '/react') throw new Refusal(403, 'A member writes; it does not react for the owner.');
|
|
198
186
|
if (request.method === 'POST' && talking[1] === '/react') { const body = await readJson(request); return send(200, await talk.react(name, body.to, body.reaction ?? null)); }
|
|
199
187
|
if (request.method === 'POST' && talking[1] === '/remind') return send(200, await talk.remind(name));
|
|
200
188
|
if (request.method === 'POST' && talking[1] === '/file') {
|
|
201
189
|
if (request.headers['content-type'] !== 'application/octet-stream') return send(400, { error: 'An attachment is a file.' });
|
|
202
|
-
|
|
203
|
-
/* A member disabled while its file came: not given back to it (audit 10). */
|
|
204
|
-
if (!stillMay('w')) throw new Refusal(403, 'This conversation is not shared with you any more.');
|
|
205
|
-
return send(201, attached);
|
|
190
|
+
return send(201, await talk.attach(name, url.searchParams.get('name') ?? '', request));
|
|
206
191
|
}
|
|
207
|
-
if (request.method === 'POST' && talking[1] === undefined) { const body = await readJson(request);
|
|
208
|
-
/* Its right looked at again once the message is read: taken back meanwhile, nothing said (audit 8). */
|
|
209
|
-
if (!stillMay('w')) throw new Refusal(403, 'This conversation is not shared with you any more.'); if (part.terminal && signinCode && conversations.signinHelp?.codeInChat(name, body.text, body.files)) return send(201, { ...(await signinCode(name, body.text)), told: 'signin' }); /* A member's words (#419): said as theirs, so that the tool never takes them for its owner's. */
|
|
210
|
-
if (person) {
|
|
211
|
-
/* Every word of a member said as a member's: its text (a line of its own starting "[" cannot pass for
|
|
212
|
-
another mark), the notes of its files; no answer to a question, no way through (audit 6). */
|
|
213
|
-
const mark = `[${person.email}, a member]`;
|
|
214
|
-
const clean = (t) => String(t ?? '').replace(/[\u200B-\u200F\u2060\uFEFF]/g, '').replace(/[[\uFF3B]/g, '(');
|
|
215
|
-
const files = Array.isArray(body.files) ? body.files.map((f) => (f && typeof f === 'object' ? { ...f, note: `${mark} ${clean(f.note)}`.trim() } : f)) : body.files;
|
|
216
|
-
return send(201, await talk.say(name, `${mark} ${clean(body.text)}`.trim(), undefined, files, undefined, { quick: false }));
|
|
217
|
-
}
|
|
218
|
-
return send(201, await talk.say(name, body.text, body.answers, body.files, body.via, { quick: body.quick === true })); }
|
|
192
|
+
if (request.method === 'POST' && talking[1] === undefined) { const body = await readJson(request); if (part.terminal && signinCode && conversations.signinHelp?.codeInChat(name, body.text, body.files)) return send(201, { ...(await signinCode(name, body.text)), told: 'signin' }); return send(201, await talk.say(name, body.text, body.answers, body.files, body.via, { quick: body.quick === true })); }
|
|
219
193
|
}
|
|
220
194
|
/* A sign-in code (#405): a device given its terminal could type it there; no other. Named twice, never guessed. */
|
|
221
195
|
const codeFor = /^\/conversations\/([^/]+)\/signin-code$/.exec(route);
|
|
222
196
|
if (request.method === 'POST' && codeFor && signinCode) {
|
|
223
197
|
need(part.terminal, 'the terminal');
|
|
224
198
|
if (decodeURIComponent(codeFor[1]) !== name) throw new Refusal(403, 'This device was not given the terminal of this conversation.');
|
|
225
|
-
|
|
226
|
-
if (!stillMay('x')) throw new Refusal(403, 'This conversation is not shared with you any more.');
|
|
227
|
-
return send(200, await signinCode(name, code));
|
|
199
|
+
return send(200, await signinCode(name, (await readJson(request)).code));
|
|
228
200
|
}
|
|
229
201
|
/* Its terminal does not come: only a device given it asks for it to be repaired. */
|
|
230
202
|
if (request.method === 'POST' && route === '/terminal/repair') { need(part.terminal, 'the terminal'); return send(200, await repair(name)); }
|
|
@@ -256,7 +228,7 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
256
228
|
}
|
|
257
229
|
/* A mail cited by its reference (mailref.mjs): only a mailbox this device was given to read. */
|
|
258
230
|
if (request.method === 'GET' && (route === '/mail/open' || route === '/mail/page')) {
|
|
259
|
-
return await mailRoute(route, url.searchParams, response, { tethers, headers, who:
|
|
231
|
+
return await mailRoute(route, url.searchParams, response, { tethers, headers, who: { id: `pairing:${pairing}`, name: 'A device' }, may: (t) => deviceMayRead(t, own, mailboxes), offline: mine?.offline === true });
|
|
260
232
|
}
|
|
261
233
|
if (request.method === 'GET' && route === '/files/download') {
|
|
262
234
|
const file = await download(attached('read', 'open'), url.searchParams.get('p') ?? '');
|
|
@@ -268,13 +240,13 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
268
240
|
if (request.method === 'POST' && route === '/files/import') {
|
|
269
241
|
if (request.headers['content-type'] !== 'application/octet-stream') return send(400, { error: 'An import is a file.' });
|
|
270
242
|
return send(201, await importFile(attached('write'), url.searchParams.get('p') ?? '', url.searchParams.get('name') ?? '', request,
|
|
271
|
-
{ exists: url.searchParams.get('exists') ?? 'keep', dir: url.searchParams.get('dir') ?? '', batch: url.searchParams.get('batch') ?? undefined
|
|
243
|
+
{ exists: url.searchParams.get('exists') ?? 'keep', dir: url.searchParams.get('dir') ?? '', batch: url.searchParams.get('batch') ?? undefined }));
|
|
272
244
|
}
|
|
273
245
|
/* Thumbnails, editing, making, renaming, moving, removing: as listing
|
|
274
246
|
and importing are. A device given the chat alone has none of them
|
|
275
247
|
(`attached` refuses all but opening a file of the chat). */
|
|
276
248
|
/* A thumbnail is the file read, as opening it is: a device given the chat alone sees the pictures of its chat. */
|
|
277
|
-
const answer = await changeRoute(request.method, route, url.searchParams, request, (need) =>
|
|
249
|
+
const answer = await changeRoute(request.method, route, url.searchParams, request, (need) => attached(need, route === '/files/thumb' ? 'open' : undefined));
|
|
278
250
|
if (answer?.picture) {
|
|
279
251
|
response.writeHead(200, { ...headers, ...IMAGE_HEADERS, 'content-type': answer.picture.type, 'content-length': answer.picture.bytes.length });
|
|
280
252
|
response.end(answer.picture.bytes);
|
package/server/files.mjs
CHANGED
|
@@ -154,8 +154,7 @@ export async function mailFile(root, relative) {
|
|
|
154
154
|
is replaced; a folder never is), 'skip' (nothing written).
|
|
155
155
|
`dir`: subfolders under `relative` to make first (a folder dropped whole).
|
|
156
156
|
`batch`: an id the page gives one drop, bounded as a whole (see BATCH_MAX). */
|
|
157
|
-
|
|
158
|
-
export async function importFile(root, relative, name, request, { exists = 'keep', dir = '', batch, ok = () => {} } = {}) {
|
|
157
|
+
export async function importFile(root, relative, name, request, { exists = 'keep', dir = '', batch } = {}) {
|
|
159
158
|
if (!isFileName(name)) throw new Refusal(400, 'A file name has no slash, does not start with a dot, and is at most 120 characters.');
|
|
160
159
|
if (!['keep', 'replace', 'skip'].includes(exists)) throw new Refusal(400, 'A name already taken is kept beside, replaced or skipped.');
|
|
161
160
|
const declared = Number(request.headers['content-length']);
|
|
@@ -188,7 +187,6 @@ export async function importFile(root, relative, name, request, { exists = 'keep
|
|
|
188
187
|
const [stem, ext] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ''];
|
|
189
188
|
for (let i = 2; await lstat(join(folderPath, final)).then(() => true, () => false); i++) final = `${stem} (${i})${ext}`;
|
|
190
189
|
} else if ((await lstat(join(folderPath, name)).catch(() => undefined))?.isDirectory()) throw new Refusal(409, `"${name}" is a folder here: it is not replaced by a file.`);
|
|
191
|
-
ok();
|
|
192
190
|
await rename(partial, join(folderPath, final));
|
|
193
191
|
return { name: final, size, ...(taken && exists === 'replace' && final === name ? { replaced: true } : {}) };
|
|
194
192
|
} catch (error) { await unlink(partial).catch(() => {}); throw error; }
|
|
@@ -404,7 +402,7 @@ export async function readText(root, relative) {
|
|
|
404
402
|
not at that version any more (the agent wrote it meanwhile), nothing is
|
|
405
403
|
written and the answer says so (409, kind "changed"); 'any' writes over
|
|
406
404
|
it all the same. `copy`: written beside it under a free name instead. */
|
|
407
|
-
export async function saveText(root, relative, request, { version, copy = false
|
|
405
|
+
export async function saveText(root, relative, request, { version, copy = false } = {}) {
|
|
408
406
|
const parts = []; let size = 0;
|
|
409
407
|
for await (const chunk of request) { size += chunk.length; if (size > EDIT_MAX) throw new Refusal(413, `A text edited here is ${EDIT_MAX / 1024 / 1024} MB at most.`); parts.push(chunk); }
|
|
410
408
|
const bytes = Buffer.concat(parts);
|
|
@@ -425,7 +423,6 @@ export async function saveText(root, relative, request, { version, copy = false,
|
|
|
425
423
|
/* Looked at again, the moment before: a write of the agent in between is not lost silently. */
|
|
426
424
|
if (!copy && version !== 'any') { const now = await lstat(at.path).catch(() => undefined); if (!now?.isFile() || versionOf(now) !== version) throw changed(); }
|
|
427
425
|
if (copy && await lstat(target).then(() => true, () => false)) throw new Refusal(409, `"${name}" was just made by someone else: try again.`);
|
|
428
|
-
ok();
|
|
429
426
|
await rename(partial, target);
|
|
430
427
|
} catch (error) { await unlink(partial).catch(() => {}); throw error; }
|
|
431
428
|
return { name, version: versionOf(await lstat(target)), size: bytes.length };
|
|
@@ -498,7 +495,7 @@ async function bridgeFiles(root) {
|
|
|
498
495
|
}
|
|
499
496
|
|
|
500
497
|
export const CHANGE_ROUTES = ['/files/thumb', '/files/text', '/files/save', '/files/make', '/files/rename', '/files/move', '/files/remove', '/files/taken'];
|
|
501
|
-
export async function changeRoute(method, route, params, request, folder
|
|
498
|
+
export async function changeRoute(method, route, params, request, folder) {
|
|
502
499
|
if (!CHANGE_ROUTES.includes(route)) return undefined;
|
|
503
500
|
const p = params.get('p') ?? '';
|
|
504
501
|
if (method === 'GET' && route === '/files/thumb') {
|
|
@@ -512,7 +509,7 @@ export async function changeRoute(method, route, params, request, folder, ok = (
|
|
|
512
509
|
const type = String(request.headers['content-type'] ?? '');
|
|
513
510
|
if (route === '/files/save') {
|
|
514
511
|
if (type !== 'application/octet-stream') return [400, { error: 'A text saved is sent as it is.' }];
|
|
515
|
-
return [200, await saveText(folder('write'), p, request, { version: params.get('version') ?? '', copy: params.get('copy') === '1'
|
|
512
|
+
return [200, await saveText(folder('write'), p, request, { version: params.get('version') ?? '', copy: params.get('copy') === '1' })];
|
|
516
513
|
}
|
|
517
514
|
if (!type.startsWith('application/json')) return [400, { error: 'The request is not JSON.' }];
|
|
518
515
|
const chunks = []; let size = 0;
|