clavarium 0.2.250-beta.1 → 0.2.251-beta.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/updater.mjs +14 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/api.mjs +46 -4
- package/server/apikeys.mjs +2 -0
- package/server/bridge.mjs +16 -2
- package/server/dataformat.mjs +5 -1
- package/server/door.mjs +44 -16
- package/server/files.mjs +7 -4
- package/server/grants.mjs +6 -2
- package/server/main.mjs +59 -5
- package/server/operators.mjs +26 -3
- package/server/people.mjs +141 -0
- package/server/settingswords.mjs +2 -2
- package/server/sshconsole.mjs +16 -2
- package/server/vm.mjs +14 -3
- package/web/app.js +76 -14
- package/web/index.html +2 -2
- package/web/member.js +26 -0
- package/web/style.css +20 -14
package/deploy/updater.mjs
CHANGED
|
@@ -667,6 +667,15 @@ export class Updater {
|
|
|
667
667
|
const live = busy.filter((c) => !stale.includes(c));
|
|
668
668
|
return live.length ? `a machine is being built or restarted (${names(live)}): the update waits` : '';
|
|
669
669
|
}
|
|
670
|
+
/* MEMBERS AND AN OLDER RELEASE (#419). A release from before accounts and rights takes every account for an
|
|
671
|
+
administrator: once accounts and rights were used here (people.json written, at the first member), going back to
|
|
672
|
+
one is refused, by hand and by the watchdog -- as for a release that cannot read the data. Undefined: allowed. */
|
|
673
|
+
#membersBlock(to) {
|
|
674
|
+
/* A release that reads the lists of today (0.2.526-next.1 wrote another form: refused too). */
|
|
675
|
+
try { if (readFileSync(join(to.app, 'server', 'people.mjs'), 'utf8').includes('export const PEOPLE_LISTS')) return undefined; } catch { /* none: from before accounts */ }
|
|
676
|
+
const file = join(this.#o.data, 'people.json');
|
|
677
|
+
return existsSync(file) || existsSync(`${file}.bak`) ? `${to.version} does not know these members: it would not read who is an administrator` : undefined;
|
|
678
|
+
}
|
|
670
679
|
#dataFormat() { try { return JSON.parse(readFileSync(join(this.#o.data, 'data-format.json'), 'utf8')).format; } catch { return undefined; } }
|
|
671
680
|
|
|
672
681
|
/* Whether the lock is held by a process alive now -- of THIS start of the machine (25-11, on a test machine: frozen
|
|
@@ -722,6 +731,9 @@ export class Updater {
|
|
|
722
731
|
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) } : {}) });
|
|
723
732
|
throw error;
|
|
724
733
|
}
|
|
734
|
+
/* Members here, and a release that would not read them (a newer number cut without them, say): not installed. */
|
|
735
|
+
const blocked = this.#membersBlock(release);
|
|
736
|
+
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); }
|
|
725
737
|
const before = this.#dataFormat();
|
|
726
738
|
let archive;
|
|
727
739
|
try {
|
|
@@ -763,6 +775,7 @@ export class Updater {
|
|
|
763
775
|
if (to.current) throw new Refused(`${id} is the release that runs`);
|
|
764
776
|
const format = this.#dataFormat();
|
|
765
777
|
if (format !== undefined && to.dataFormat < format) throw new Refused(`${to.version} cannot read the data of this version (format ${format}; it reads ${to.dataFormat})`);
|
|
778
|
+
const members = this.#membersBlock(to); if (members) throw new Refused(members);
|
|
766
779
|
const why = await this.busy(); if (why) throw new Refused(why);
|
|
767
780
|
const unlock = this.#lock();
|
|
768
781
|
try {
|
|
@@ -891,7 +904,7 @@ export class Updater {
|
|
|
891
904
|
const recent = failed && current && last && last.action === 'update' && last.result === 'done' && last.to === current.version && now - new Date(last.at) < WATCH_RECENT_MS;
|
|
892
905
|
const previous = recent ? this.releases().find((r) => !r.current && r.version === last.from) : undefined;
|
|
893
906
|
const format = this.#dataFormat();
|
|
894
|
-
if (previous && (format === undefined || previous.dataFormat >= format)) {
|
|
907
|
+
if (previous && (format === undefined || previous.dataFormat >= format) && !this.#membersBlock(previous)) {
|
|
895
908
|
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}`;
|
|
896
909
|
this.#o.log(`watchdog: ${why}`);
|
|
897
910
|
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.251-beta.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.251-beta.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
|
@@ -493,7 +493,8 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
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
|
-
|
|
496
|
+
/* Each account with its role and, for a member, the conversations it was given (#419). */
|
|
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;
|
|
497
498
|
if (pathname === '/api/binder/people' && binders) return send(200, { people: binders.people(identity), changes: `${BOOT}:${binders.changes()}` }), true;
|
|
498
499
|
if (pathname === '/api/certificate' && certificate) return send(200, await certificate.about({ fresh: query.get('fresh') === '1' })), true;
|
|
499
500
|
/* This server's disk and memory (capacity.mjs): everything for Settings; only whether it is high for the list. */
|
|
@@ -591,6 +592,7 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
591
592
|
return send(403, { error: 'This request does not come from this site.' }), true;
|
|
592
593
|
}
|
|
593
594
|
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.');
|
|
594
596
|
/* A SIGN-IN CODE (#405): answered before anything below can see this body (the journal, say). */
|
|
595
597
|
const codeOf = /^\/api\/conversations\/([^/]+)\/signin-code$/.exec(pathname);
|
|
596
598
|
if (codeOf && conversations.signinHelp) return send(200, await conversations.signinHelp.enterCode(decodeURIComponent(codeOf[1]), body?.code)), true;
|
|
@@ -791,13 +793,53 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
791
793
|
if (pathname === '/api/wifi/handover' && wifi) return send(202, await wifi.handover()), true;
|
|
792
794
|
if (pathname === '/api/meshcentral/enable' && meshcentral) return send(202, await meshcentral.enable()), true;
|
|
793
795
|
if (pathname === '/api/meshcentral/disable' && meshcentral) return send(200, await meshcentral.disable()), true;
|
|
794
|
-
if (pathname === '/api/operators' && team)
|
|
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
|
+
}
|
|
795
833
|
const op = /^\/api\/operators\/([^/]{3,200})\/(password|disable|enable|remove)$/.exec(pathname);
|
|
796
834
|
if (op && team) {
|
|
797
|
-
const email = decodeURIComponent(op[1]);
|
|
835
|
+
const email = decodeURIComponent(op[1]).trim().toLowerCase();
|
|
798
836
|
/* Not oneself out: another operator does it, or nobody would see it was a mistake. */
|
|
799
837
|
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.');
|
|
800
|
-
|
|
838
|
+
const done = op[2] === 'password' ? await team.password(email) : { operators: await team[op[2]](email) };
|
|
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;
|
|
801
843
|
}
|
|
802
844
|
const renaming = /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/rename$/.exec(pathname);
|
|
803
845
|
/* Its machines that run get the new name or value now, as a secret given to them does. */
|
package/server/apikeys.mjs
CHANGED
|
@@ -1320,6 +1320,8 @@ 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.' });
|
|
1323
1325
|
if (!body || typeof body !== 'object') body = {};
|
|
1324
1326
|
if (pathname === '/api/apikeys') {
|
|
1325
1327
|
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,7 +90,9 @@ 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
|
|
93
|
+
export const MEMBER_PATH = '/m/terminal';
|
|
94
|
+
|
|
95
|
+
export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () => {}, originOk = sameOrigin, gate = () => 'local', deviceName = () => undefined, memberName = () => undefined, onRejoin = () => {}, onTyped = () => {}, asleep = () => false }) {
|
|
94
96
|
const sockets = new WebSocketServer({ noServer: true });
|
|
95
97
|
const seats = new Seats();
|
|
96
98
|
/* THE DEVICES AT A TERMINAL, each with what lets it stay: asked again when the owner changes
|
|
@@ -98,6 +100,8 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
98
100
|
back used to end only at the next connection -- an open terminal went on (found 19-10). */
|
|
99
101
|
const deviceSeats = new Map(); /* viewer -> () => still allowed */
|
|
100
102
|
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();
|
|
101
105
|
const allowed = (viewer) => {
|
|
102
106
|
if (revoked.has(viewer)) return false;
|
|
103
107
|
const still = deviceSeats.get(viewer);
|
|
@@ -120,9 +124,18 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
120
124
|
name = ask();
|
|
121
125
|
if (!isConversationName(name) || !originOk(request.headers)) { socket.destroy(); return; }
|
|
122
126
|
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;
|
|
123
134
|
} else if (url.pathname === PATH) {
|
|
124
135
|
name = url.searchParams.get('c') ?? '';
|
|
125
136
|
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;
|
|
126
139
|
} else return;
|
|
127
140
|
const cols = Number(url.searchParams.get('cols'));
|
|
128
141
|
const rows = Number(url.searchParams.get('rows'));
|
|
@@ -130,6 +143,7 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
130
143
|
const resume = url.searchParams.get('resume') === '1';
|
|
131
144
|
sockets.handleUpgrade(request, socket, head, (viewer) => {
|
|
132
145
|
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);
|
|
133
147
|
seat(viewer, name, within(cols, COLS) ? cols : 80, within(rows, ROWS) ? rows : 24, resume);
|
|
134
148
|
});
|
|
135
149
|
});
|
|
@@ -186,7 +200,7 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
186
200
|
}
|
|
187
201
|
async function openNow(name, cols, rows, sink, say) {
|
|
188
202
|
/* Who opens it, for What happened when it wakes a sleeper: a screen, or this server (warm). */
|
|
189
|
-
const who = sink ? (
|
|
203
|
+
const who = sink ? (fromDevice.has(sink) ? 'a paired device' : fromMember.has(sink) ? 'a member' : 'a page') : undefined;
|
|
190
204
|
const terminal = await spawn(name, cols, rows, say, who);
|
|
191
205
|
/* While it was being opened another one may have been: the newest wins. */
|
|
192
206
|
if (live.has(name)) close(name);
|
package/server/dataformat.mjs
CHANGED
|
@@ -22,8 +22,11 @@ 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
|
-
/*
|
|
25
|
+
/* No migration yet. FORMAT 2 IS NOT TO BE USED: 0.2.527-next.1 wrote it for a day (accounts and rights, #419) with
|
|
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.) */
|
|
26
28
|
export const MIGRATIONS = {};
|
|
29
|
+
const SAME_AS_1 = 2;
|
|
27
30
|
|
|
28
31
|
export function dataFormat(dataDir) {
|
|
29
32
|
try { return JSON.parse(readFileSync(join(dataDir, FORMAT_FILE), 'utf8')).format; } catch { return undefined; }
|
|
@@ -37,6 +40,7 @@ export function migrateData(dataDir, { format = DATA_FORMAT, migrations = MIGRAT
|
|
|
37
40
|
try { existing = readdirSync(dataDir).some((f) => f.endsWith('.json')); } catch { /* a new directory */ }
|
|
38
41
|
found = existing ? 1 : format;
|
|
39
42
|
}
|
|
43
|
+
if (found === SAME_AS_1 && format === 1) { write(dataDir, 1); found = 1; }
|
|
40
44
|
if (!Number.isInteger(found) || found < 1) throw new Error(`${join(dataDir, FORMAT_FILE)} does not hold a format number`);
|
|
41
45
|
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.`);
|
|
42
46
|
const ran = [];
|
package/server/door.mjs
CHANGED
|
@@ -87,13 +87,18 @@ 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, person }) {
|
|
91
91
|
const url = new URL(request.url ?? '/', 'http://local');
|
|
92
|
-
|
|
92
|
+
/* A MEMBER (people.mjs, #419) comes through the same door, at /m/api/, as the person the sign-in names: no
|
|
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;
|
|
93
97
|
/* "/<pairing>/me" -> the pairing and "/me"; "/pair" has no pairing yet. */
|
|
94
|
-
const named = /^\/([0-9a-f-]{36})(\/.*)$/.exec(url.pathname.slice(
|
|
95
|
-
const pairing = named?.[1];
|
|
96
|
-
const route = named ? named[2] : url.pathname.slice(
|
|
98
|
+
const named = person ? null : /^\/([0-9a-f-]{36})(\/.*)$/.exec(url.pathname.slice(base.length));
|
|
99
|
+
const pairing = person ? person.key : named?.[1];
|
|
100
|
+
const route = named ? named[2] : url.pathname.slice(base.length);
|
|
101
|
+
const given_ = person ?? devices;
|
|
97
102
|
const send = (status, body, extra = {}) => {
|
|
98
103
|
response.writeHead(status, { ...headers, ...extra, 'content-type': 'application/json; charset=utf-8' }).end(JSON.stringify(body));
|
|
99
104
|
return true;
|
|
@@ -101,7 +106,8 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
101
106
|
try {
|
|
102
107
|
if (request.method === 'POST' && !originOk(request.headers)) return send(403, { error: 'This request does not come from this site.' });
|
|
103
108
|
|
|
104
|
-
/* ---- pairing: no session yet ---- */
|
|
109
|
+
/* ---- pairing: no session yet (never for a member: 404) ---- */
|
|
110
|
+
if (person && ['/pair', '/challenge', '/session', '/leave'].includes(route)) return send(404, { error: 'Not found.' });
|
|
105
111
|
if (request.method === 'POST' && route === '/pair') return send(201, devices.pair(await readJson(request)));
|
|
106
112
|
if (request.method === 'POST' && route === '/challenge') return send(200, devices.challenge(String((await readJson(request)).device ?? '')));
|
|
107
113
|
if (request.method === 'POST' && route === '/session') {
|
|
@@ -111,17 +117,21 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
111
117
|
}
|
|
112
118
|
|
|
113
119
|
/* ---- everything else: a device session, and its one conversation ---- */
|
|
114
|
-
if (devicePairing(devices, request.headers, pairing) === undefined) return send(401, { error: 'This device has no open session.' });
|
|
120
|
+
if (!person && devicePairing(devices, request.headers, pairing) === undefined) return send(401, { error: 'This device has no open session.' });
|
|
115
121
|
/* What this pairing was given: conversations to use, and things of its own to read or write. */
|
|
116
|
-
const given =
|
|
122
|
+
const given = given_.grantsOf(pairing);
|
|
117
123
|
const names = given.filter((g) => g.type === 'conversation').map((g) => g.name);
|
|
118
124
|
const own = given.filter((g) => g.type !== 'conversation').filter((g) => resources.get(g.name))
|
|
119
125
|
.map((g) => ({ name: g.name, type: g.type, access: g.rights.includes('w') ? 'write' : 'read' }));
|
|
120
|
-
const name = deviceConversation(devices, request.headers, pairing, url.searchParams.get('c') ?? undefined);
|
|
126
|
+
const name = person ? person.conversationOf(url.searchParams.get('c') ?? undefined) : deviceConversation(devices, request.headers, pairing, url.searchParams.get('c') ?? undefined);
|
|
121
127
|
const mine = name === undefined ? undefined : conversations.list().find((c) => c.name === name);
|
|
122
128
|
/* The parts of that conversation this pairing was given. */
|
|
123
|
-
const rights = name === undefined ? '' :
|
|
129
|
+
const rights = name === undefined ? '' : given_.rightsOn(pairing, name);
|
|
124
130
|
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.'); };
|
|
125
135
|
const need = (ok, what) => { if (!ok) throw new Refusal(403, `This device was not given ${what} of this conversation.`); };
|
|
126
136
|
/* Its chat alone: what is reached through the conversation is only what its chat holds. */
|
|
127
137
|
const chatOnly = mine !== undefined && !part.terminal;
|
|
@@ -183,20 +193,38 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
183
193
|
if (request.method === 'GET' && talking[1] === '/search') return send(200, talk.search(name, url.searchParams.get('q') ?? ''));
|
|
184
194
|
/* 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. */
|
|
185
195
|
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.');
|
|
186
198
|
if (request.method === 'POST' && talking[1] === '/react') { const body = await readJson(request); return send(200, await talk.react(name, body.to, body.reaction ?? null)); }
|
|
187
199
|
if (request.method === 'POST' && talking[1] === '/remind') return send(200, await talk.remind(name));
|
|
188
200
|
if (request.method === 'POST' && talking[1] === '/file') {
|
|
189
201
|
if (request.headers['content-type'] !== 'application/octet-stream') return send(400, { error: 'An attachment is a file.' });
|
|
190
|
-
|
|
202
|
+
const attached = await talk.attach(name, url.searchParams.get('name') ?? '', request);
|
|
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);
|
|
191
206
|
}
|
|
192
|
-
if (request.method === 'POST' && talking[1] === undefined) { const body = await readJson(request);
|
|
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 })); }
|
|
193
219
|
}
|
|
194
220
|
/* A sign-in code (#405): a device given its terminal could type it there; no other. Named twice, never guessed. */
|
|
195
221
|
const codeFor = /^\/conversations\/([^/]+)\/signin-code$/.exec(route);
|
|
196
222
|
if (request.method === 'POST' && codeFor && signinCode) {
|
|
197
223
|
need(part.terminal, 'the terminal');
|
|
198
224
|
if (decodeURIComponent(codeFor[1]) !== name) throw new Refusal(403, 'This device was not given the terminal of this conversation.');
|
|
199
|
-
|
|
225
|
+
const code = (await readJson(request)).code;
|
|
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));
|
|
200
228
|
}
|
|
201
229
|
/* Its terminal does not come: only a device given it asks for it to be repaired. */
|
|
202
230
|
if (request.method === 'POST' && route === '/terminal/repair') { need(part.terminal, 'the terminal'); return send(200, await repair(name)); }
|
|
@@ -228,7 +256,7 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
228
256
|
}
|
|
229
257
|
/* A mail cited by its reference (mailref.mjs): only a mailbox this device was given to read. */
|
|
230
258
|
if (request.method === 'GET' && (route === '/mail/open' || route === '/mail/page')) {
|
|
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 });
|
|
259
|
+
return await mailRoute(route, url.searchParams, response, { tethers, headers, who: person ? { id: `person:${person.email}`, name: person.email } : { id: `pairing:${pairing}`, name: 'A device' }, may: (t) => deviceMayRead(t, own, mailboxes), offline: mine?.offline === true });
|
|
232
260
|
}
|
|
233
261
|
if (request.method === 'GET' && route === '/files/download') {
|
|
234
262
|
const file = await download(attached('read', 'open'), url.searchParams.get('p') ?? '');
|
|
@@ -240,13 +268,13 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
240
268
|
if (request.method === 'POST' && route === '/files/import') {
|
|
241
269
|
if (request.headers['content-type'] !== 'application/octet-stream') return send(400, { error: 'An import is a file.' });
|
|
242
270
|
return send(201, await importFile(attached('write'), url.searchParams.get('p') ?? '', url.searchParams.get('name') ?? '', request,
|
|
243
|
-
{ exists: url.searchParams.get('exists') ?? 'keep', dir: url.searchParams.get('dir') ?? '', batch: url.searchParams.get('batch') ?? undefined }));
|
|
271
|
+
{ exists: url.searchParams.get('exists') ?? 'keep', dir: url.searchParams.get('dir') ?? '', batch: url.searchParams.get('batch') ?? undefined, ok: writesStill }));
|
|
244
272
|
}
|
|
245
273
|
/* Thumbnails, editing, making, renaming, moving, removing: as listing
|
|
246
274
|
and importing are. A device given the chat alone has none of them
|
|
247
275
|
(`attached` refuses all but opening a file of the chat). */
|
|
248
276
|
/* A thumbnail is the file read, as opening it is: a device given the chat alone sees the pictures of its chat. */
|
|
249
|
-
const answer = await changeRoute(request.method, route, url.searchParams, request, (need) => attached(need, route === '/files/thumb' ? 'open' : undefined));
|
|
277
|
+
const answer = await changeRoute(request.method, route, url.searchParams, request, (need) => { if (need === 'write') writesStill(); return attached(need, route === '/files/thumb' ? 'open' : undefined); }, writesStill);
|
|
250
278
|
if (answer?.picture) {
|
|
251
279
|
response.writeHead(200, { ...headers, ...IMAGE_HEADERS, 'content-type': answer.picture.type, 'content-length': answer.picture.bytes.length });
|
|
252
280
|
response.end(answer.picture.bytes);
|
package/server/files.mjs
CHANGED
|
@@ -154,7 +154,8 @@ 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
|
-
|
|
157
|
+
/* `ok()`: looked at once the file has come, before it is put in place (it throws when the sender lost its right). */
|
|
158
|
+
export async function importFile(root, relative, name, request, { exists = 'keep', dir = '', batch, ok = () => {} } = {}) {
|
|
158
159
|
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.');
|
|
159
160
|
if (!['keep', 'replace', 'skip'].includes(exists)) throw new Refusal(400, 'A name already taken is kept beside, replaced or skipped.');
|
|
160
161
|
const declared = Number(request.headers['content-length']);
|
|
@@ -187,6 +188,7 @@ export async function importFile(root, relative, name, request, { exists = 'keep
|
|
|
187
188
|
const [stem, ext] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ''];
|
|
188
189
|
for (let i = 2; await lstat(join(folderPath, final)).then(() => true, () => false); i++) final = `${stem} (${i})${ext}`;
|
|
189
190
|
} 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();
|
|
190
192
|
await rename(partial, join(folderPath, final));
|
|
191
193
|
return { name: final, size, ...(taken && exists === 'replace' && final === name ? { replaced: true } : {}) };
|
|
192
194
|
} catch (error) { await unlink(partial).catch(() => {}); throw error; }
|
|
@@ -402,7 +404,7 @@ export async function readText(root, relative) {
|
|
|
402
404
|
not at that version any more (the agent wrote it meanwhile), nothing is
|
|
403
405
|
written and the answer says so (409, kind "changed"); 'any' writes over
|
|
404
406
|
it all the same. `copy`: written beside it under a free name instead. */
|
|
405
|
-
export async function saveText(root, relative, request, { version, copy = false } = {}) {
|
|
407
|
+
export async function saveText(root, relative, request, { version, copy = false, ok = () => {} } = {}) {
|
|
406
408
|
const parts = []; let size = 0;
|
|
407
409
|
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); }
|
|
408
410
|
const bytes = Buffer.concat(parts);
|
|
@@ -423,6 +425,7 @@ export async function saveText(root, relative, request, { version, copy = false
|
|
|
423
425
|
/* Looked at again, the moment before: a write of the agent in between is not lost silently. */
|
|
424
426
|
if (!copy && version !== 'any') { const now = await lstat(at.path).catch(() => undefined); if (!now?.isFile() || versionOf(now) !== version) throw changed(); }
|
|
425
427
|
if (copy && await lstat(target).then(() => true, () => false)) throw new Refusal(409, `"${name}" was just made by someone else: try again.`);
|
|
428
|
+
ok();
|
|
426
429
|
await rename(partial, target);
|
|
427
430
|
} catch (error) { await unlink(partial).catch(() => {}); throw error; }
|
|
428
431
|
return { name, version: versionOf(await lstat(target)), size: bytes.length };
|
|
@@ -495,7 +498,7 @@ async function bridgeFiles(root) {
|
|
|
495
498
|
}
|
|
496
499
|
|
|
497
500
|
export const CHANGE_ROUTES = ['/files/thumb', '/files/text', '/files/save', '/files/make', '/files/rename', '/files/move', '/files/remove', '/files/taken'];
|
|
498
|
-
export async function changeRoute(method, route, params, request, folder) {
|
|
501
|
+
export async function changeRoute(method, route, params, request, folder, ok = () => {}) {
|
|
499
502
|
if (!CHANGE_ROUTES.includes(route)) return undefined;
|
|
500
503
|
const p = params.get('p') ?? '';
|
|
501
504
|
if (method === 'GET' && route === '/files/thumb') {
|
|
@@ -509,7 +512,7 @@ export async function changeRoute(method, route, params, request, folder) {
|
|
|
509
512
|
const type = String(request.headers['content-type'] ?? '');
|
|
510
513
|
if (route === '/files/save') {
|
|
511
514
|
if (type !== 'application/octet-stream') return [400, { error: 'A text saved is sent as it is.' }];
|
|
512
|
-
return [200, await saveText(folder('write'), p, request, { version: params.get('version') ?? '', copy: params.get('copy') === '1' })];
|
|
515
|
+
return [200, await saveText(folder('write'), p, request, { version: params.get('version') ?? '', copy: params.get('copy') === '1', ok })];
|
|
513
516
|
}
|
|
514
517
|
if (!type.startsWith('application/json')) return [400, { error: 'The request is not JSON.' }];
|
|
515
518
|
const chunks = []; let size = 0;
|
package/server/grants.mjs
CHANGED
|
@@ -67,7 +67,7 @@ import { Refusal } from './conversations.mjs';
|
|
|
67
67
|
export const RIGHTS = Object.freeze({ conversation: 'rwxm', folder: 'rw', mailbox: 'r', git: 'rw', secret: 'x', server: 'rw', room: 'rwm', box: 'rw' });
|
|
68
68
|
/* What each of the server's own assets takes: its state and its jobs are read, rooms are made. */
|
|
69
69
|
const SERVER_RIGHTS = Object.freeze({ 'server:status': 'r', 'server:jobs': 'r', 'server:rooms': 'w', 'server:diagnostics': 'r' });
|
|
70
|
-
const SUBJECT = /^(conversation:[a-z]([a-z0-9-]{0,30}[a-z0-9])?|(pairing|apikey):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
|
|
70
|
+
const SUBJECT = /^(conversation:[a-z]([a-z0-9-]{0,30}[a-z0-9])?|(pairing|apikey):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|person:[a-z0-9._+-]{1,64}@([a-z0-9-]{1,63}\.)+[a-z]{2,24})$/;
|
|
71
71
|
const ASSET = /^(conversation|folder|mailbox|git):[a-z]([a-z0-9-]{0,30}[a-z0-9])?$|^secret:[A-Z][A-Z0-9_]{0,39}$|^server:(status|jobs|rooms|diagnostics)$|^(room|box):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
72
72
|
|
|
73
73
|
export const typeOf = (asset) => String(asset).split(':')[0];
|
|
@@ -114,7 +114,9 @@ export class Grants {
|
|
|
114
114
|
/* A secret is handed to a conversation, never to a device: a device
|
|
115
115
|
would be a way to read it. */
|
|
116
116
|
if (typeOf(asset) === 'secret' && !subject.startsWith('conversation:')) throw new Refusal(400, 'A secret is handed to a conversation, never shared with a device.');
|
|
117
|
-
|
|
117
|
+
/* A MEMBER (person:, people.mjs, #419) is given conversations only, in this version: its chat, its terminal. */
|
|
118
|
+
if (subject.startsWith('person:') && typeOf(asset) !== 'conversation') throw new Refusal(400, 'A member is given conversations only.');
|
|
119
|
+
if (typeOf(asset) === 'conversation' && !subject.startsWith('pairing:') && !subject.startsWith('apikey:') && !subject.startsWith('person:')) throw new Refusal(400, 'A conversation is shared with a device or an API key, not with another conversation.');
|
|
118
120
|
/* The state of the server is given to an API key only; an API key is given only that, and
|
|
119
121
|
conversations one by one -- their chat, to read or to write in, never their terminal. */
|
|
120
122
|
if (typeOf(asset) === 'server' && !subject.startsWith('apikey:')) throw new Refusal(400, 'The state of the server is given to an API key only.');
|
|
@@ -141,6 +143,8 @@ export class Grants {
|
|
|
141
143
|
/* Who has something on one asset: [{ subject, rights }]. */
|
|
142
144
|
on(asset) { return this.#store.all().filter((g) => g.asset === asset).map((g) => ({ subject: g.subject, rights: g.rights })); }
|
|
143
145
|
|
|
146
|
+
/* The subjects there are that start so ('person:'). */
|
|
147
|
+
subjects(prefix) { return [...new Set(this.#store.all().map((g) => g.subject).filter((s) => s.startsWith(prefix)))]; }
|
|
144
148
|
forgetSubject(subject) { for (const g of this.#store.all()) if (g.subject === subject) this.#store.remove(g.name); }
|
|
145
149
|
forgetAsset(asset) { for (const g of this.#store.all()) if (g.asset === asset) this.#store.remove(g.name); }
|
|
146
150
|
}
|
package/server/main.mjs
CHANGED
|
@@ -32,6 +32,7 @@ import { Vms, runner, HostTally } from './vm.mjs';
|
|
|
32
32
|
import { Resources, WORK_TAB } from './resources.mjs';
|
|
33
33
|
import { download } from './files.mjs';
|
|
34
34
|
import { makeGate, makeOriginCheck, readOperators } from './gate.mjs';
|
|
35
|
+
import { People } from './people.mjs';
|
|
35
36
|
import { Shortcuts } from './shortcuts.mjs';
|
|
36
37
|
import { hearBox, Dictation } from './voice.mjs';
|
|
37
38
|
import QRCode from 'qrcode';
|
|
@@ -176,6 +177,11 @@ try {
|
|
|
176
177
|
const DEVICE_FILES = Object.fromEntries(Object.entries(FILES).filter(([path]) => path !== '/').map(([path, file]) => [`/c${path}`, file]));
|
|
177
178
|
DEVICE_FILES['/c/'] = ['web/device.html', 'text/html; charset=utf-8'];
|
|
178
179
|
DEVICE_FILES['/c/device.js'] = ['web/device.js', 'text/javascript; charset=utf-8'];
|
|
180
|
+
/* A MEMBER's page (people.mjs, #419): the same files under /m/, behind the sign-in; its page is the device's,
|
|
181
|
+
told it is a member's, with member.js (no pairing) in place of device.js. */
|
|
182
|
+
const MEMBER_FILES = Object.fromEntries(Object.entries(FILES).filter(([path]) => path !== '/').map(([path, file]) => [`/m${path}`, file]));
|
|
183
|
+
MEMBER_FILES['/m/member.js'] = ['web/member.js', 'text/javascript; charset=utf-8'];
|
|
184
|
+
const memberPage = () => readFileSync(`${ROOT}web/device.html`, 'utf8').replace('data-door="device"', 'data-door="member"').replace('<script src="device.js"></script>', '<script src="member.js"></script>');
|
|
179
185
|
|
|
180
186
|
/* Nothing loads from anywhere else, and nothing may frame the page. */
|
|
181
187
|
const HEADERS = {
|
|
@@ -202,7 +208,7 @@ const withoutTmux = (env) => Object.fromEntries(Object.entries(env).filter(([key
|
|
|
202
208
|
|
|
203
209
|
const REFUSED = 'This Clavarium belongs to someone else: your account is not one of its operators.\n';
|
|
204
210
|
|
|
205
|
-
function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, machineList, features, apikeys, relayJoin, desks } = {}) {
|
|
211
|
+
function serve(port, conversations, resources, { gate = () => 'local', memberGate = () => undefined, personOf = null, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, machineList, features, apikeys, relayJoin, desks } = {}) {
|
|
206
212
|
/* Its manifest carries the name of this Clavarium, or the one a device chose (instance.mjs). */
|
|
207
213
|
const sendManifest = (response, url) => response.writeHead(200, { ...HEADERS, 'content-type': 'application/manifest+json' }).end(instance.manifest(new URL(url ?? '/', 'http://local').searchParams.get('name') ?? undefined));
|
|
208
214
|
const sendFile = async (response, file) => {
|
|
@@ -217,7 +223,7 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
|
|
|
217
223
|
try { const notice = updates?.notice(); if (notice) response.setHeader('x-clavarium-update', notice); } catch { /* never in the way of an answer */ }
|
|
218
224
|
/* The version that answers, to the page's own questions: a page loaded before an update starts again (app.js). */
|
|
219
225
|
/* Not to a program at /api/ext/: what it may read, its key says (apikeys.mjs). */
|
|
220
|
-
if (platform?.version && ((pathname.startsWith('/api/') && !pathname.startsWith('/api/ext/')) || pathname.startsWith('/c/api/'))) response.setHeader('x-clavarium-version', platform.version);
|
|
226
|
+
if (platform?.version && ((pathname.startsWith('/api/') && !pathname.startsWith('/api/ext/')) || pathname.startsWith('/c/api/') || pathname.startsWith('/m/api/'))) response.setHeader('x-clavarium-version', platform.version);
|
|
221
227
|
/* The device door first, and apart: it never consults the gate. */
|
|
222
228
|
/* An address that wakes a tool, called from outside by what its owner
|
|
223
229
|
runs elsewhere: the address is the right. Nothing else is looked at,
|
|
@@ -268,7 +274,22 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
|
|
|
268
274
|
}
|
|
269
275
|
/* Before anything else, static files included: see gate.mjs. */
|
|
270
276
|
const who = gate(request.headers);
|
|
277
|
+
/* Looked at again once a body is read: one made a member or disabled meanwhile does nothing more (audit 8). */
|
|
278
|
+
request.stillAllowed = () => gate(request.headers) !== undefined;
|
|
271
279
|
if (who === undefined) {
|
|
280
|
+
/* A MEMBER (people.mjs, #419): its own door, and nothing else of this server -- not a page, not an API,
|
|
281
|
+
not a file. A page it held from before (an administrator then) is told, and goes to its own. */
|
|
282
|
+
const member = memberGate(request.headers);
|
|
283
|
+
if (member !== undefined && door && personOf) {
|
|
284
|
+
if (await handleDoor(request, response, { ...door, person: { ...personOf(member), still: () => memberGate(request.headers) === member } })) return;
|
|
285
|
+
if (pathname === '/m/manifest.webmanifest' && request.method === 'GET') { sendManifest(response, request.url); return; }
|
|
286
|
+
if (pathname === '/m/' && (request.method === 'GET' || request.method === 'HEAD')) { response.writeHead(200, { ...HEADERS, 'content-type': 'text/html; charset=utf-8' }).end(memberPage()); return; }
|
|
287
|
+
const file = MEMBER_FILES[pathname];
|
|
288
|
+
if (file && (request.method === 'GET' || request.method === 'HEAD')) { await sendFile(response, file); return; }
|
|
289
|
+
if (pathname === '/' && request.method === 'GET') { response.writeHead(302, { ...HEADERS, location: '/m/' }).end(); return; }
|
|
290
|
+
response.writeHead(403, { ...HEADERS, 'x-clavarium-role': 'member', 'content-type': 'text/plain; charset=utf-8' }).end(REFUSED);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
272
293
|
response.writeHead(403, { ...HEADERS, 'content-type': 'text/plain; charset=utf-8' }).end(REFUSED);
|
|
273
294
|
return;
|
|
274
295
|
}
|
|
@@ -331,7 +352,23 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
331
352
|
if (migrated.ran.length) console.log(`data: format ${migrated.from} -> ${migrated.to}`);
|
|
332
353
|
/* Who may sign in, kept up to date from the page (operators.mjs); none: this machine only. */
|
|
333
354
|
const team = operators.length ? new Operators({ host: runner(host), store: new Store(`${dataDir}/operators.json`), initial: operators }) : null;
|
|
334
|
-
|
|
355
|
+
/* WHO IS WHAT (people.mjs, #419): the gate of everything there was admits ADMINISTRATORS only -- pages, API,
|
|
356
|
+
terminals, the SSH console, all of it -- so a member is refused there by default; members come in through
|
|
357
|
+
their own door alone (/m/, memberGate). With no member, everybody who may sign in passes, as before. */
|
|
358
|
+
const people = team ? new People({ path: `${dataDir}/people.json`, install: operators, accounts: () => team.list(), leaving: () => team.leaving, tell: (title, body) => { try { void alerts?.tell?.({ title, body, url: '/?open=settings&at=operators' })?.catch?.(() => {}); } catch { /* said in the log */ } console.error(`people: ${title}: ${body}`); } }) : null;
|
|
359
|
+
team?.useLastAdmin((email) => people.roleOf(email) === 'admin' && people.isLastAdmin(email));
|
|
360
|
+
/* The list changed outside the page too: an account gone takes its role and what it was given with it (audit 6). */
|
|
361
|
+
if (team) {
|
|
362
|
+
team.people = people;
|
|
363
|
+
team.onChanged = () => {
|
|
364
|
+
people.prune();
|
|
365
|
+
const here = new Set(team.list().map((o) => o.email));
|
|
366
|
+
if (here.size && team.grants) for (const s of team.grants.subjects('person:')) if (!here.has(s.slice('person:'.length))) team.grants.forgetSubject(s);
|
|
367
|
+
people.changed();
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
const gate = makeGate(team ? () => team.allowed().filter((e) => people.roleOf(e) === 'admin') : []);
|
|
371
|
+
const memberGate = team ? makeGate(() => team.allowed().filter((e) => people.roleOf(e) === 'member')) : () => undefined;
|
|
335
372
|
const originOk = makeOriginCheck(publicOrigin);
|
|
336
373
|
const instance = new Instance({ file: new JsonFile(`${dataDir}/instance.json`, {}), origin: publicOrigin, given: appName });
|
|
337
374
|
let repairTerminal = async () => { throw new Error('not ready'); };
|
|
@@ -352,6 +389,19 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
352
389
|
if (!all.jobs) all.jobs = jobs;
|
|
353
390
|
/* Who may do what with what: ONE table, shared by everything below. */
|
|
354
391
|
const grants = new Grants(new Store(`${dataDir}/grants.json`));
|
|
392
|
+
if (team) team.grants = grants;
|
|
393
|
+
/* A MEMBER, as the door sees it (door.mjs, #419): what the table gives `person:<email>`, conversations only. */
|
|
394
|
+
const personOf = team ? (given) => {
|
|
395
|
+
const email = String(given).trim().toLowerCase();
|
|
396
|
+
const subject = `person:${email}`;
|
|
397
|
+
const mine = () => grants.of(subject, 'conversation').map((g) => g.name).filter((n) => all.list().some((c) => c.name === n));
|
|
398
|
+
return {
|
|
399
|
+
email, key: subject,
|
|
400
|
+
grantsOf: () => grants.of(subject).filter((g) => g.type === 'conversation'),
|
|
401
|
+
rightsOn: (_key, name) => grants.rightsOf(subject, `conversation:${name}`),
|
|
402
|
+
conversationOf: (wanted) => { const m = mine(); if (wanted === undefined || wanted === '') return m[0]; return m.includes(wanted) ? wanted : undefined; },
|
|
403
|
+
};
|
|
404
|
+
} : null;
|
|
355
405
|
/* Folder-style boxes the owner drops assets into, to tidy the views and hand a whole box at once (groups.mjs). */
|
|
356
406
|
const groups = new Groups({ store: new Store(`${dataDir}/groups.json`) });
|
|
357
407
|
/* The providers and models OpenCode knows (models.dev), for a conversation set up from here (03-11). */
|
|
@@ -996,13 +1046,13 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
996
1046
|
answerer: answererConfig(env)?.models.length ?? 0, updates: updates.about(), team: team ? team.list().length : null,
|
|
997
1047
|
screen: await quick(screenNow(), 1500, null), catalogue: await quick(catalogue.providers().catch(() => []), 1500, []),
|
|
998
1048
|
}) });
|
|
999
|
-
const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, machineList, features, desks: new Desks({ file: new JsonFile(`${dataDir}/desktops.json`, {}) }), apikeys, relayJoin: host.length ? new RelayJoin({ host: asHost }) : null, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
|
|
1049
|
+
const { server, listening } = serve(port, all, folders, { gate, memberGate, personOf, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, machineList, features, desks: new Desks({ file: new JsonFile(`${dataDir}/desktops.json`, {}) }), apikeys, relayJoin: host.length ? new RelayJoin({ host: asHost }) : null, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
|
|
1000
1050
|
server.on('close', () => { closing = true; stopBinders(); stopTethers(); clearInterval(historyTimer); clearInterval(secretsTimer); clearInterval(trimTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopNetworkWatch(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(restartTimer); clearInterval(expiryTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); clearInterval(stopSigninHelp); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
|
|
1001
1051
|
let closing = false;
|
|
1002
1052
|
boxes.attach(server, WebSocketServer);
|
|
1003
1053
|
browsers.attach(server, WebSocketServer); server.on('close', () => browsers.shutdown());
|
|
1004
1054
|
/* A machine's shared SSH console, live in its asset panel (sshconsole.mjs): the same checks as the terminal. */
|
|
1005
|
-
attachConsole(server, { tethers, gate, originOk });
|
|
1055
|
+
const consoles = attachConsole(server, { tethers, gate, originOk });
|
|
1006
1056
|
/* The wake word's weekly threshold tuning (Sunday from 03:00, each box's own time): looked at every 10 minutes. */
|
|
1007
1057
|
const wakeWeekly = setInterval(() => { try { boxes.wakeWeekly(); } catch (error) { console.error(`wake tuning: ${error.message}`); } }, 10 * 60_000); wakeWeekly.unref?.(); server.on('close', () => clearInterval(wakeWeekly));
|
|
1008
1058
|
/* A collect session's clock: the stations asked, its end, the speaker told to stop (boxcollect.mjs). */
|
|
@@ -1033,7 +1083,11 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
1033
1083
|
gate, originOk,
|
|
1034
1084
|
/* Only a pairing given that conversation's terminal opens it. */
|
|
1035
1085
|
deviceName: (headers, pairing, wanted) => deviceTerminal(devices, headers, pairing, wanted),
|
|
1086
|
+
/* A member: a conversation whose terminal it was given, by name only (#419). */
|
|
1087
|
+
memberName: (headers, wanted) => { const m = memberGate(headers); if (m === undefined || !personOf) return undefined; const p = personOf(m); return p.conversationOf(wanted) === wanted && p.rightsOn(p.key, wanted).includes('x') ? wanted : undefined; },
|
|
1036
1088
|
});
|
|
1089
|
+
/* A role or a person's right changed: the terminals it held and lost go at once (#419). */
|
|
1090
|
+
people?.useChanged?.(() => { bridge.recheck(); consoles?.recheck?.(); });
|
|
1037
1091
|
all.drop = (name) => bridge.drop(name);
|
|
1038
1092
|
/* What a device was given changes: a terminal it holds and lost goes at once. */
|
|
1039
1093
|
devices.changed = () => bridge.recheck();
|