clavarium 0.2.528-next.1 → 0.2.530-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/updater.mjs +1 -14
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/api.mjs +4 -42
- package/server/apikeys.mjs +0 -2
- 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 +5 -59
- package/server/operators.mjs +3 -26
- package/server/settingswords.mjs +2 -2
- package/server/sshconsole.mjs +2 -16
- package/web/app.js +14 -76
- package/web/index.html +2 -2
- package/web/style.css +14 -20
- package/server/people.mjs +0 -134
- package/web/member.js +0 -26
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.530-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.530-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
|
@@ -493,8 +493,7 @@ 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
|
-
|
|
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,49 +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
|
-
team.people?.adding(adding, role);
|
|
805
|
-
const made = await team.add(body.email);
|
|
806
|
-
return send(201, { ...made, role: team.people?.roleOf(made.email) ?? 'admin' }), true;
|
|
807
|
-
}
|
|
808
|
-
/* An account made an administrator or a member (#419): never oneself, never the last administrator. */
|
|
809
|
-
const roleOf = /^\/api\/operators\/([^/]{3,200})\/role$/.exec(pathname);
|
|
810
|
-
if (roleOf && team?.people) {
|
|
811
|
-
const email = decodeURIComponent(roleOf[1]).trim().toLowerCase();
|
|
812
|
-
if (email === identity) throw new Refusal(409, 'You cannot change your own role: ask another administrator.');
|
|
813
|
-
return send(200, { operators: team.people.setRole(email, String(body.role ?? '')) }), true;
|
|
814
|
-
}
|
|
815
|
-
/* A conversation given to a member, or taken back: its chat (read or write) and/or its terminal (#419). */
|
|
816
|
-
const giving = /^\/api\/operators\/([^/]{3,200})\/(give|take)$/.exec(pathname);
|
|
817
|
-
if (giving && team?.people && team.grants) {
|
|
818
|
-
const email = decodeURIComponent(giving[1]).trim().toLowerCase();
|
|
819
|
-
if (!team.list().some((o) => o.email === email)) throw new Refusal(404, 'No such account.');
|
|
820
|
-
if (team.people.roleOf(email) !== 'member') throw new Refusal(409, 'Only a member is given conversations: an administrator has them all.');
|
|
821
|
-
const name = String(body.conversation ?? '');
|
|
822
|
-
if (!conversations.list().some((c) => c.name === name)) throw new Refusal(404, 'No such conversation.');
|
|
823
|
-
const rights = giving[2] === 'take' ? '' : `${body.chat === 'write' ? 'rw' : body.chat === 'read' ? 'r' : ''}${body.terminal === true ? 'x' : ''}`;
|
|
824
|
-
if (rights === '') team.grants.take(`person:${email}`, `conversation:${name}`);
|
|
825
|
-
else team.grants.give(`person:${email}`, `conversation:${name}`, rights);
|
|
826
|
-
team.people.changed?.();
|
|
827
|
-
return send(200, { given: team.grants.of(`person:${email}`, 'conversation').map((g) => ({ name: g.name, rights: g.rights })) }), true;
|
|
828
|
-
}
|
|
794
|
+
if (pathname === '/api/operators' && team) return send(201, await team.add(body.email)), true;
|
|
829
795
|
const op = /^\/api\/operators\/([^/]{3,200})\/(password|disable|enable|remove)$/.exec(pathname);
|
|
830
796
|
if (op && team) {
|
|
831
|
-
const email = decodeURIComponent(op[1])
|
|
797
|
+
const email = decodeURIComponent(op[1]);
|
|
832
798
|
/* Not oneself out: another operator does it, or nobody would see it was a mistake. */
|
|
833
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.');
|
|
834
|
-
|
|
835
|
-
/* Removed: its role and what it was given go with it (#419). */
|
|
836
|
-
if (op[2] === 'remove') { team.people?.removed(email); team.grants?.forgetSubject(`person:${email.toLowerCase()}`); }
|
|
837
|
-
team.people?.changed?.();
|
|
838
|
-
return send(200, done), true;
|
|
800
|
+
return send(200, op[2] === 'password' ? await team.password(email) : { operators: await team[op[2]](email) }), true;
|
|
839
801
|
}
|
|
840
802
|
const renaming = /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/rename$/.exec(pathname);
|
|
841
803
|
/* Its machines that run get the new name or value now, as a secret given to them does. */
|
package/server/apikeys.mjs
CHANGED
|
@@ -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;
|
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})$/;
|
|
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,9 +114,7 @@ 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
|
-
|
|
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.');
|
|
117
|
+
if (typeOf(asset) === 'conversation' && !subject.startsWith('pairing:') && !subject.startsWith('apikey:')) throw new Refusal(400, 'A conversation is shared with a device or an API key, not with another conversation.');
|
|
120
118
|
/* The state of the server is given to an API key only; an API key is given only that, and
|
|
121
119
|
conversations one by one -- their chat, to read or to write in, never their terminal. */
|
|
122
120
|
if (typeOf(asset) === 'server' && !subject.startsWith('apikey:')) throw new Refusal(400, 'The state of the server is given to an API key only.');
|
|
@@ -143,8 +141,6 @@ export class Grants {
|
|
|
143
141
|
/* Who has something on one asset: [{ subject, rights }]. */
|
|
144
142
|
on(asset) { return this.#store.all().filter((g) => g.asset === asset).map((g) => ({ subject: g.subject, rights: g.rights })); }
|
|
145
143
|
|
|
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)))]; }
|
|
148
144
|
forgetSubject(subject) { for (const g of this.#store.all()) if (g.subject === subject) this.#store.remove(g.name); }
|
|
149
145
|
forgetAsset(asset) { for (const g of this.#store.all()) if (g.asset === asset) this.#store.remove(g.name); }
|
|
150
146
|
}
|
package/server/main.mjs
CHANGED
|
@@ -32,7 +32,6 @@ 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';
|
|
36
35
|
import { Shortcuts } from './shortcuts.mjs';
|
|
37
36
|
import { hearBox, Dictation } from './voice.mjs';
|
|
38
37
|
import QRCode from 'qrcode';
|
|
@@ -177,11 +176,6 @@ try {
|
|
|
177
176
|
const DEVICE_FILES = Object.fromEntries(Object.entries(FILES).filter(([path]) => path !== '/').map(([path, file]) => [`/c${path}`, file]));
|
|
178
177
|
DEVICE_FILES['/c/'] = ['web/device.html', 'text/html; charset=utf-8'];
|
|
179
178
|
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>');
|
|
185
179
|
|
|
186
180
|
/* Nothing loads from anywhere else, and nothing may frame the page. */
|
|
187
181
|
const HEADERS = {
|
|
@@ -208,7 +202,7 @@ const withoutTmux = (env) => Object.fromEntries(Object.entries(env).filter(([key
|
|
|
208
202
|
|
|
209
203
|
const REFUSED = 'This Clavarium belongs to someone else: your account is not one of its operators.\n';
|
|
210
204
|
|
|
211
|
-
function serve(port, conversations, resources, { gate = () => 'local',
|
|
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 } = {}) {
|
|
212
206
|
/* Its manifest carries the name of this Clavarium, or the one a device chose (instance.mjs). */
|
|
213
207
|
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));
|
|
214
208
|
const sendFile = async (response, file) => {
|
|
@@ -223,7 +217,7 @@ function serve(port, conversations, resources, { gate = () => 'local', memberGat
|
|
|
223
217
|
try { const notice = updates?.notice(); if (notice) response.setHeader('x-clavarium-update', notice); } catch { /* never in the way of an answer */ }
|
|
224
218
|
/* The version that answers, to the page's own questions: a page loaded before an update starts again (app.js). */
|
|
225
219
|
/* Not to a program at /api/ext/: what it may read, its key says (apikeys.mjs). */
|
|
226
|
-
if (platform?.version && ((pathname.startsWith('/api/') && !pathname.startsWith('/api/ext/')) || pathname.startsWith('/c/api/')
|
|
220
|
+
if (platform?.version && ((pathname.startsWith('/api/') && !pathname.startsWith('/api/ext/')) || pathname.startsWith('/c/api/'))) response.setHeader('x-clavarium-version', platform.version);
|
|
227
221
|
/* The device door first, and apart: it never consults the gate. */
|
|
228
222
|
/* An address that wakes a tool, called from outside by what its owner
|
|
229
223
|
runs elsewhere: the address is the right. Nothing else is looked at,
|
|
@@ -274,22 +268,7 @@ function serve(port, conversations, resources, { gate = () => 'local', memberGat
|
|
|
274
268
|
}
|
|
275
269
|
/* Before anything else, static files included: see gate.mjs. */
|
|
276
270
|
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;
|
|
279
271
|
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
|
-
}
|
|
293
272
|
response.writeHead(403, { ...HEADERS, 'content-type': 'text/plain; charset=utf-8' }).end(REFUSED);
|
|
294
273
|
return;
|
|
295
274
|
}
|
|
@@ -352,23 +331,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
352
331
|
if (migrated.ran.length) console.log(`data: format ${migrated.from} -> ${migrated.to}`);
|
|
353
332
|
/* Who may sign in, kept up to date from the page (operators.mjs); none: this machine only. */
|
|
354
333
|
const team = operators.length ? new Operators({ host: runner(host), store: new Store(`${dataDir}/operators.json`), initial: operators }) : null;
|
|
355
|
-
|
|
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;
|
|
334
|
+
const gate = makeGate(team ? () => team.allowed() : []);
|
|
372
335
|
const originOk = makeOriginCheck(publicOrigin);
|
|
373
336
|
const instance = new Instance({ file: new JsonFile(`${dataDir}/instance.json`, {}), origin: publicOrigin, given: appName });
|
|
374
337
|
let repairTerminal = async () => { throw new Error('not ready'); };
|
|
@@ -389,19 +352,6 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
389
352
|
if (!all.jobs) all.jobs = jobs;
|
|
390
353
|
/* Who may do what with what: ONE table, shared by everything below. */
|
|
391
354
|
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;
|
|
405
355
|
/* Folder-style boxes the owner drops assets into, to tidy the views and hand a whole box at once (groups.mjs). */
|
|
406
356
|
const groups = new Groups({ store: new Store(`${dataDir}/groups.json`) });
|
|
407
357
|
/* The providers and models OpenCode knows (models.dev), for a conversation set up from here (03-11). */
|
|
@@ -1046,13 +996,13 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
1046
996
|
answerer: answererConfig(env)?.models.length ?? 0, updates: updates.about(), team: team ? team.list().length : null,
|
|
1047
997
|
screen: await quick(screenNow(), 1500, null), catalogue: await quick(catalogue.providers().catch(() => []), 1500, []),
|
|
1048
998
|
}) });
|
|
1049
|
-
const { server, listening } = serve(port, all, folders, { gate,
|
|
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) });
|
|
1050
1000
|
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(); });
|
|
1051
1001
|
let closing = false;
|
|
1052
1002
|
boxes.attach(server, WebSocketServer);
|
|
1053
1003
|
browsers.attach(server, WebSocketServer); server.on('close', () => browsers.shutdown());
|
|
1054
1004
|
/* A machine's shared SSH console, live in its asset panel (sshconsole.mjs): the same checks as the terminal. */
|
|
1055
|
-
|
|
1005
|
+
attachConsole(server, { tethers, gate, originOk });
|
|
1056
1006
|
/* The wake word's weekly threshold tuning (Sunday from 03:00, each box's own time): looked at every 10 minutes. */
|
|
1057
1007
|
const wakeWeekly = setInterval(() => { try { boxes.wakeWeekly(); } catch (error) { console.error(`wake tuning: ${error.message}`); } }, 10 * 60_000); wakeWeekly.unref?.(); server.on('close', () => clearInterval(wakeWeekly));
|
|
1058
1008
|
/* A collect session's clock: the stations asked, its end, the speaker told to stop (boxcollect.mjs). */
|
|
@@ -1083,11 +1033,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
1083
1033
|
gate, originOk,
|
|
1084
1034
|
/* Only a pairing given that conversation's terminal opens it. */
|
|
1085
1035
|
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; },
|
|
1088
1036
|
});
|
|
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?.(); });
|
|
1091
1037
|
all.drop = (name) => bridge.drop(name);
|
|
1092
1038
|
/* What a device was given changes: a terminal it holds and lost goes at once. */
|
|
1093
1039
|
devices.changed = () => bridge.recheck();
|
package/server/operators.mjs
CHANGED
|
@@ -46,10 +46,7 @@ export class Operators {
|
|
|
46
46
|
const r = await this.#host(['operator', 'list']);
|
|
47
47
|
if (r.code !== 0) throw new Refusal(502, `Who may sign in could not be read: ${firstLine(r.stderr) || `exit ${r.code}`}`);
|
|
48
48
|
const read = String(r.stdout).split('\n').map((l) => l.split('\t')).filter(([e, s]) => EMAIL.test(e ?? '') && ['enabled', 'disabled'].includes(s));
|
|
49
|
-
const before = JSON.stringify(this.#list);
|
|
50
49
|
if (read.length) this.#list = read.map(([email, state]) => ({ email, enabled: state === 'enabled' }));
|
|
51
|
-
/* Changed outside the page (the host program): whoever lost their place loses their terminals at once (#419). */
|
|
52
|
-
if (JSON.stringify(this.#list) !== before) { try { this.onChanged?.(); } catch { /* the minute's recheck sees it */ } }
|
|
53
50
|
return this.list();
|
|
54
51
|
}
|
|
55
52
|
async #do(argv, input) {
|
|
@@ -74,29 +71,9 @@ export class Operators {
|
|
|
74
71
|
await this.#do(['operator', 'password', e], `${password}\n`);
|
|
75
72
|
return { email: e, password };
|
|
76
73
|
}
|
|
77
|
-
|
|
78
|
-
#lastAdmin = () => false;
|
|
79
|
-
useLastAdmin(fn) { this.#lastAdmin = fn; }
|
|
80
|
-
#keep(email) { if (this.#lastAdmin(email)) throw new Refusal(409, 'The last administrator cannot be disabled or removed.'); }
|
|
81
|
-
/* Disabled or removed now: not counted as an administrator from the check on, so that two of them taking each
|
|
82
|
-
other out at once cannot leave none (audit 6, 24-11). One at a time, too. */
|
|
83
|
-
leaving = new Set();
|
|
84
|
-
#turn = Promise.resolve();
|
|
85
|
-
#leave(email, verb) {
|
|
86
|
-
const e = this.#email(email);
|
|
87
|
-
const go = async () => {
|
|
88
|
-
this.#keep(e);
|
|
89
|
-
this.leaving.add(e);
|
|
90
|
-
try { await this.#do(['operator', verb, e]); } finally { this.leaving.delete(e); }
|
|
91
|
-
this.#unlock(e);
|
|
92
|
-
return this.list();
|
|
93
|
-
};
|
|
94
|
-
const p = this.#turn.then(go, go); this.#turn = p.catch(() => {});
|
|
95
|
-
return p;
|
|
96
|
-
}
|
|
97
|
-
async disable(email) { return this.#leave(email, 'disable'); }
|
|
74
|
+
async disable(email) { await this.#do(['operator', 'disable', this.#email(email)]); this.#unlock(this.#email(email)); return this.list(); }
|
|
98
75
|
async enable(email) { await this.#do(['operator', 'enable', this.#email(email)]); this.#unlock(this.#email(email)); return this.list(); }
|
|
99
|
-
async remove(email) {
|
|
76
|
+
async remove(email) { await this.#do(['operator', 'remove', this.#email(email)]); this.#unlock(this.#email(email)); return this.list(); }
|
|
100
77
|
#unlock(email) { const locks = { ...(this.#store.get('locks') ?? {}) }; delete locks[email]; this.#store.put({ name: 'locks', ...locks }); }
|
|
101
78
|
|
|
102
79
|
/* At each turn: too many failed sign-ins lock an address for a while; a lock that is over is lifted. */
|
|
@@ -114,7 +91,7 @@ export class Operators {
|
|
|
114
91
|
if (Number(n) < FAILS_MAX || locks[email]) continue;
|
|
115
92
|
const one = this.#list.find((o) => o.email === email && o.enabled);
|
|
116
93
|
if (!one) continue;
|
|
117
|
-
if (this.allowed().length === 1
|
|
94
|
+
if (this.allowed().length === 1) {
|
|
118
95
|
if (this.#said.get(email) !== 'last') { this.#said.set(email, 'last'); this.#tell(`${n} failed sign-ins as ${email}`, 'It is the last operator: not locked out. Change its password if this was not you.'); }
|
|
119
96
|
continue;
|
|
120
97
|
}
|
package/server/settingswords.mjs
CHANGED
|
@@ -7,7 +7,7 @@ export const SETTINGS_WORDS_FR = {
|
|
|
7
7
|
'set-ch-general': 'Général', 'set-ch-machine': 'Machine', 'set-ch-access': 'Accès', 'set-ch-sharing': 'Partage', 'set-ch-chat': 'Chat',
|
|
8
8
|
'set-ch-wakeups': 'Réveils', 'set-ch-answerer': 'Répondeur', 'set-ch-health': 'Santé', 'set-ch-advanced': 'Avancé',
|
|
9
9
|
'set-ch-s-general': 'Général', 'set-ch-s-about': 'À propos', 'set-ch-s-screen': 'Écran', 'set-ch-s-alerts': 'Alertes',
|
|
10
|
-
'set-ch-s-resources': 'Ressources', 'set-ch-s-operators': '
|
|
10
|
+
'set-ch-s-resources': 'Ressources', 'set-ch-s-operators': 'Administrateurs', 'set-ch-s-network': 'Réseau', 'set-ch-s-remote-screen': 'Écran à distance',
|
|
11
11
|
'set-ch-s-words': 'Écran du chat', 'set-ch-s-dictation': 'Dictée', 'set-ch-s-shortcuts': 'Raccourcis', 'set-ch-s-thread': 'Événements du chat',
|
|
12
12
|
'set-ch-s-updates': 'Mises à jour', 'set-ch-s-binders': 'Classeurs', 'set-ch-s-events': 'Activité', 'set-ch-s-jobs': 'Tâches', 'set-ch-s-logs': 'Journaux',
|
|
13
13
|
'set-ch-s-usage': 'Usage', 'set-ch-s-backup': 'Sauvegarde', 'set-ch-s-advanced': 'Avancé',
|
|
@@ -59,7 +59,7 @@ export const SETTINGS_WORDS_FR = {
|
|
|
59
59
|
'set-lang-device': 'La langue de chaque appareil', 'set-res-now': 'Mémoire {m} % · disque {d} %',
|
|
60
60
|
'set-share-memory': 'Mémoire par machine', 'set-share-disk': 'Disque par machine', 'set-share-others': 'Autres',
|
|
61
61
|
'set-share-rest': 'Système et autres', 'set-share-else': 'Tout le reste', 'set-share-free': 'Libre', 'set-share-used': 'Utilisé', 'set-share-of': 'sur {total}',
|
|
62
|
-
'set-binders-max': 'Les agents en font {n} au plus', 'set-admin-1': '1 administrateur', 'set-admins': '{n} administrateurs',
|
|
62
|
+
'set-binders-max': 'Les agents en font {n} au plus', 'set-admin-1': '1 administrateur', 'set-admins': '{n} administrateurs',
|
|
63
63
|
'set-backup-now': 'Exporter · importer', 'set-git-key': '1 clé git', 'set-git-keys': '{n} clés git', 'set-restart': 'redémarrer',
|
|
64
64
|
'set-logs-now': 'Clavarium, machines, système',
|
|
65
65
|
/* Diagnostics › Charge (vm.mjs HostTally): les commandes à l'hôte, par fenêtre de 5 minutes. */
|
package/server/sshconsole.mjs
CHANGED
|
@@ -41,8 +41,6 @@ const machineOf = (tethers, id) => {
|
|
|
41
41
|
};
|
|
42
42
|
|
|
43
43
|
export function attachConsole(server, { tethers, gate = () => 'local', originOk }) {
|
|
44
|
-
/* Each open console and whether it may stay: looked at again when a role changes (#419), not only every 30 s. */
|
|
45
|
-
const open = new Map();
|
|
46
44
|
const sockets = new WebSocketServer({ noServer: true, maxPayload: KEYS_MAX });
|
|
47
45
|
server.on('upgrade', (request, socket, head) => {
|
|
48
46
|
const url = new URL(request.url ?? '/', 'http://local');
|
|
@@ -50,19 +48,10 @@ export function attachConsole(server, { tethers, gate = () => 'local', originOk
|
|
|
50
48
|
const target = machineOf(tethers, url.searchParams.get('target'));
|
|
51
49
|
if (!originOk(request.headers) || gate(request.headers) === undefined || !target) { socket.destroy(); return; }
|
|
52
50
|
const cols = Number(url.searchParams.get('cols')); const rows = Number(url.searchParams.get('rows'));
|
|
53
|
-
sockets.handleUpgrade(request, socket, head, (ws) => {
|
|
54
|
-
/* Still an administrator (#419): made a member, disabled, removed -- the console ends at once. */
|
|
55
|
-
const still = () => gate(request.headers) !== undefined;
|
|
56
|
-
const look = () => { if (!still()) { try { ws.close(4403, 'not allowed any more'); } catch { /* gone */ } } };
|
|
57
|
-
const watch = setInterval(look, 30_000); watch.unref?.();
|
|
58
|
-
open.set(ws, look); ws.on('close', () => open.delete(ws));
|
|
59
|
-
ws.on('close', () => clearInterval(watch));
|
|
60
|
-
ws.on('message', () => { if (!still()) { try { ws.close(4403, 'not allowed any more'); } catch { /* gone */ } } });
|
|
61
|
-
void seat(ws, target, whoOf(request.headers), { cols, rows }, still);
|
|
62
|
-
});
|
|
51
|
+
sockets.handleUpgrade(request, socket, head, (ws) => { void seat(ws, target, whoOf(request.headers), { cols, rows }); });
|
|
63
52
|
});
|
|
64
53
|
|
|
65
|
-
async function seat(ws, target, who, { cols, rows }
|
|
54
|
+
async function seat(ws, target, who, { cols, rows }) {
|
|
66
55
|
const send = (data, binary = false) => { if (ws.readyState === 1) ws.send(data, { binary }); };
|
|
67
56
|
let handle = null; let gone = false; const early = [];
|
|
68
57
|
const onEvent = (e) => {
|
|
@@ -84,7 +73,6 @@ export function attachConsole(server, { tethers, gate = () => 'local', originOk
|
|
|
84
73
|
/* What came meanwhile is in the replay already: only the latest state is said again. */
|
|
85
74
|
if (early.some((e) => e.type === 'closed')) { try { ws.close(CLOSE_ENDED, 'ended'); } catch { /* gone */ } return; }
|
|
86
75
|
ws.on('message', (data, binary) => {
|
|
87
|
-
if (!still()) return;
|
|
88
76
|
if (binary) { handle.write(Buffer.from(data).toString('utf8')); return; }
|
|
89
77
|
let m; try { m = JSON.parse(String(data)); } catch { return; }
|
|
90
78
|
if (m?.type === 'resize') handle.resize(Number(m.cols), Number(m.rows));
|
|
@@ -94,8 +82,6 @@ export function attachConsole(server, { tethers, gate = () => 'local', originOk
|
|
|
94
82
|
else if (m?.type === 'interrupt') handle.interrupt();
|
|
95
83
|
});
|
|
96
84
|
}
|
|
97
|
-
/* `recheck`: each open console looked at now (a role changed, #419). */
|
|
98
|
-
sockets.recheck = () => { for (const look of [...open.values()]) look(); };
|
|
99
85
|
return sockets;
|
|
100
86
|
}
|
|
101
87
|
|
package/web/app.js
CHANGED
|
@@ -18,14 +18,12 @@
|
|
|
18
18
|
|
|
19
19
|
/* A paired device gets the same page with less in it, and asks its own
|
|
20
20
|
door: see server/door.mjs. */
|
|
21
|
-
|
|
22
|
-
const MEMBER = document.documentElement.dataset.door === 'member';
|
|
23
|
-
const DEVICE = document.documentElement.dataset.door === 'device' || MEMBER;
|
|
21
|
+
const DEVICE = document.documentElement.dataset.door === 'device';
|
|
24
22
|
/* THE KIT (kit.js): the pieces every screen shares -- the state's point, the conversation's card... */
|
|
25
23
|
const KIT = window.clavariumKit;
|
|
26
24
|
/* On a paired device, every request names the pairing it speaks for:
|
|
27
25
|
the address is completed once the device has signed in. */
|
|
28
|
-
let API =
|
|
26
|
+
let API = DEVICE ? '/c/api' : '/api';
|
|
29
27
|
let pairing = '';
|
|
30
28
|
let deviceShared = [];
|
|
31
29
|
/* The parts of its conversation this device was given: its terminal, its
|
|
@@ -91,12 +89,10 @@
|
|
|
91
89
|
the page is leaving. */
|
|
92
90
|
let serverVersion = '';
|
|
93
91
|
const leaving = (r) => {
|
|
94
|
-
/* Made a member while this administrators' page was open (#419): its own page, at once. */
|
|
95
|
-
if (!DEVICE && r.status === 403 && r.headers.get('x-clavarium-role') === 'member') { location.replace('/m/'); return true; }
|
|
96
92
|
const update = r.headers.get('x-clavarium-update') ?? '';
|
|
97
93
|
if (update || r.headers.get('x-clavarium-down')) {
|
|
98
94
|
const [kind, to] = update ? update.split(' ') : ['', ''];
|
|
99
|
-
location.replace(`${
|
|
95
|
+
location.replace(`${DEVICE ? '/c' : ''}/maintenance.html?${new URLSearchParams({ kind, ...(to ? { to } : {}), back: location.pathname + location.search })}`);
|
|
100
96
|
return true;
|
|
101
97
|
}
|
|
102
98
|
const version = r.headers.get('x-clavarium-version') ?? '';
|
|
@@ -848,7 +844,7 @@
|
|
|
848
844
|
say('connecting', 'connecting');
|
|
849
845
|
fit.fit();
|
|
850
846
|
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
|
|
851
|
-
const where =
|
|
847
|
+
const where = DEVICE ? `/c/terminal?d=${pairing}&c=${encodeURIComponent(name)}&cols=${terminal.cols}&rows=${terminal.rows}${resume ? '&resume=1' : ''}` : `/terminal?c=${encodeURIComponent(name)}&cols=${terminal.cols}&rows=${terminal.rows}${resume ? '&resume=1' : ''}`;
|
|
852
848
|
const mine = new WebSocket(`${scheme}://${location.host}${where}`);
|
|
853
849
|
socket = mine;
|
|
854
850
|
mine.binaryType = 'arraybuffer';
|
|
@@ -1330,7 +1326,7 @@
|
|
|
1330
1326
|
let appName = 'Clavarium';
|
|
1331
1327
|
let pageTitle = '';
|
|
1332
1328
|
const INSTALL_NAME = 'clavarium-install-name';
|
|
1333
|
-
const MANIFEST =
|
|
1329
|
+
const MANIFEST = DEVICE ? '/c/manifest.webmanifest' : '/manifest.webmanifest';
|
|
1334
1330
|
const manifestLink = document.querySelector('link[rel="manifest"]');
|
|
1335
1331
|
const installName = () => { try { return localStorage.getItem(INSTALL_NAME) ?? ''; } catch { return ''; } };
|
|
1336
1332
|
const pointManifest = (name) => { if (manifestLink) manifestLink.href = name ? `${MANIFEST}?name=${encodeURIComponent(name)}` : MANIFEST; };
|
|
@@ -1353,7 +1349,7 @@
|
|
|
1353
1349
|
return j;
|
|
1354
1350
|
};
|
|
1355
1351
|
/* The name a person reads; a conversation made before free names is read by its identifier. */
|
|
1356
|
-
const shownName = (c) => (c && typeof c.title === 'string' && c.title ? c.title :
|
|
1352
|
+
const shownName = (c) => (c && typeof c.title === 'string' && c.title ? c.title : c?.name ?? '');
|
|
1357
1353
|
/* It needs its owner: it asks or waits, its answerer asks, it failed, its machine is unwell. Said even when it is hidden. */
|
|
1358
1354
|
/* Its tool asks or waits for its owner, and the owner has not written since (talk.mjs, brief). */
|
|
1359
1355
|
const talkNeeds = (c) => Boolean(c.talk && (c.talk.needs ?? (c.talk.waiting > 0 || c.talk.state === 'waiting')));
|
|
@@ -1996,8 +1992,6 @@
|
|
|
1996
1992
|
const mePath = () => `${API}/me?c=${encodeURIComponent(current)}`;
|
|
1997
1993
|
let r = await fetch(mePath());
|
|
1998
1994
|
if (leaving(r)) return;
|
|
1999
|
-
/* A member whose account was changed or removed (#419): said plainly, nothing more tried. */
|
|
2000
|
-
if (MEMBER && r.status === 403) { shut(uiSaid('set-member-gone', 'Nothing is shared with you now.')); return; }
|
|
2001
1995
|
if (r.status === 401) {
|
|
2002
1996
|
/* The session ended: the device signs again, quietly. */
|
|
2003
1997
|
const door = await window.clavariumDoor();
|
|
@@ -8332,47 +8326,11 @@
|
|
|
8332
8326
|
$('access-devices-here').addEventListener('click', () => { void openAccessPage('map', { of: current }); });
|
|
8333
8327
|
|
|
8334
8328
|
/* ---------- Settings: this device, and the platform ---------- */
|
|
8335
|
-
/* What a member may use, conversation by conversation (#419): Chat to read, Chat, Chat and terminal, Terminal. */
|
|
8336
|
-
const GIVE_LEVELS = () => [['r', uiSaid('set-give-read', 'Read only')], ['rw', uiSaid('set-give-chat', 'Chat')], ['rwx', uiSaid('set-give-both', 'Chat + terminal')], ['x', uiSaid('set-give-terminal', 'Terminal')], ['', uiSaid('set-give-none', 'Remove access')]];
|
|
8337
|
-
function memberGiven(o) {
|
|
8338
|
-
const box = el('div', 'op-given');
|
|
8339
|
-
const given = new Map((o.given ?? []).map((g) => [g.name, g.rights]));
|
|
8340
|
-
const label = (n) => conversations.find((c) => c.name === n)?.chatName || n;
|
|
8341
|
-
const set = async (name, rights) => {
|
|
8342
|
-
$('operators-error').hidden = true;
|
|
8343
|
-
const body = { conversation: name, chat: rights.includes('w') ? 'write' : rights.includes('r') ? 'read' : null, terminal: rights.includes('x') };
|
|
8344
|
-
try { await post(`${API}/operators/${encodeURIComponent(o.email)}/${rights ? 'give' : 'take'}`, body); }
|
|
8345
|
-
catch (error) { $('operators-error').textContent = error.message; $('operators-error').hidden = false; }
|
|
8346
|
-
await paintOperators();
|
|
8347
|
-
};
|
|
8348
|
-
const level = (name, rights) => {
|
|
8349
|
-
const sel = el('select'); sel.setAttribute('aria-label', `What ${o.email} may use in ${label(name)}`);
|
|
8350
|
-
for (const [v, l] of GIVE_LEVELS()) { const opt = el('option', '', l); opt.value = v; sel.append(opt); }
|
|
8351
|
-
sel.value = GIVE_LEVELS().some(([v]) => v === rights) ? rights : 'rw';
|
|
8352
|
-
sel.addEventListener('change', () => void set(name, sel.value));
|
|
8353
|
-
return sel;
|
|
8354
|
-
};
|
|
8355
|
-
if (given.size === 0) box.append(el('small', '', uiSaid('set-given-none', 'Nothing shared yet.')));
|
|
8356
|
-
/* What a chat or a terminal really gives (audit 24-11): what its AI can reach -- its folders, mail, keys. */
|
|
8357
|
-
else box.append(el('small', 'hint', uiSaid('set-given-ai', 'Chat and terminal: all its AI can reach.')));
|
|
8358
|
-
for (const [name, rights] of given) { const line = el('div', 'op-given-line'); line.append(el('span', '', label(name)), level(name, rights)); box.append(line); }
|
|
8359
|
-
const rest = conversations.filter((c) => !given.has(c.name));
|
|
8360
|
-
if (rest.length) {
|
|
8361
|
-
const add = el('select', 'op-give-add'); add.setAttribute('aria-label', `Give ${o.email} a conversation`);
|
|
8362
|
-
const first = el('option', '', uiSaid('set-give-add', 'Share a conversation…')); first.value = ''; add.append(first);
|
|
8363
|
-
for (const c of rest) { const opt = el('option', '', label(c.name)); opt.value = c.name; add.append(opt); }
|
|
8364
|
-
add.addEventListener('change', () => { if (add.value) void set(add.value, 'rw'); });
|
|
8365
|
-
box.append(add);
|
|
8366
|
-
}
|
|
8367
|
-
return box;
|
|
8368
|
-
}
|
|
8369
8329
|
/* ADMINISTRATORS: who may sign in (server/operators.mjs); a password is shown once, then never again. */
|
|
8370
8330
|
async function paintOperators() {
|
|
8371
8331
|
const got = await fetch(`${API}/operators`).then((r) => (r.ok ? r.json() : null)).catch(() => null);
|
|
8372
8332
|
$('settings-ch-operators').hidden = !got || got.local === true;
|
|
8373
8333
|
if (!got || got.local) return;
|
|
8374
|
-
if (got.defaultRole && !$('operators-role').dataset.touched) $('operators-role').value = got.defaultRole;
|
|
8375
|
-
$('operators-role').onchange = () => { $('operators-role').dataset.touched = '1'; };
|
|
8376
8334
|
const rows = $('operators-rows'); rows.replaceChildren();
|
|
8377
8335
|
const act = async (path) => {
|
|
8378
8336
|
$('operators-error').hidden = true;
|
|
@@ -8381,34 +8339,17 @@
|
|
|
8381
8339
|
await paintOperators();
|
|
8382
8340
|
};
|
|
8383
8341
|
for (const o of got.operators) {
|
|
8384
|
-
const row = el('div', 'list-item folder'); row.dataset.email = o.email;
|
|
8342
|
+
const row = el('div', 'list-item folder'); row.dataset.email = o.email;
|
|
8385
8343
|
const name = el('div', 'set-what'); name.append(el('b', '', o.email));
|
|
8386
8344
|
const word = o.locked ? `Locked until ${new Date(o.locked).toLocaleTimeString([], { timeStyle: 'short' })}` : o.enabled ? (o.email === got.me ? 'You' : '') : 'Disabled';
|
|
8387
8345
|
if (word) name.append(el('small', '', word));
|
|
8388
8346
|
const buttons = [['password', 'New password']];
|
|
8389
8347
|
if (o.email !== got.me) buttons.push(o.enabled ? ['disable', 'Disable'] : ['enable', 'Enable'], ['remove', 'Remove']);
|
|
8390
8348
|
const acts = el('div', 'set-control');
|
|
8391
|
-
/* ITS ROLE (#419): an administrator does everything; a member sees only what it is given. Never one's own. */
|
|
8392
|
-
if (o.email !== got.me) {
|
|
8393
|
-
const role = el('select', 'op-role'); role.setAttribute('aria-label', `Role of ${o.email}`);
|
|
8394
|
-
for (const [v, l] of [['admin', uiSaid('set-role-admin', 'Administrator')], ['member', uiSaid('set-role-member', 'Member')]]) { const opt = el('option', '', l); opt.value = v; role.append(opt); }
|
|
8395
|
-
role.value = o.role ?? 'admin';
|
|
8396
|
-
role.addEventListener('change', async () => {
|
|
8397
|
-
$('operators-error').hidden = true;
|
|
8398
|
-
try { await post(`${API}/operators/${encodeURIComponent(o.email)}/role`, { role: role.value }); }
|
|
8399
|
-
catch (error) { $('operators-error').textContent = error.message; $('operators-error').hidden = false; }
|
|
8400
|
-
await paintOperators();
|
|
8401
|
-
});
|
|
8402
|
-
acts.append(role);
|
|
8403
|
-
} else name.append(el('small', '', o.role === 'member' ? uiSaid('set-role-member', 'Member') : uiSaid('set-role-admin', 'Administrator')));
|
|
8404
8349
|
acts.append(...buttons.map(([verb, label]) => { const b = el('button', verb === 'remove' ? 'danger' : '', label); b.type = 'button'; b.dataset.act = verb; b.addEventListener('click', () => void act([o.email, verb])); return b; }));
|
|
8405
8350
|
row.append(name, acts);
|
|
8406
8351
|
rows.append(row);
|
|
8407
|
-
/* WHAT A MEMBER WAS GIVEN (#419): each conversation, its chat and/or its terminal; one more added from a list. */
|
|
8408
|
-
if (o.role === 'member') rows.append(memberGiven(o));
|
|
8409
8352
|
}
|
|
8410
|
-
/* Its line in the chapter's head: counted once the rows are there (#419). */
|
|
8411
|
-
void paintSettingsStates().catch(() => {});
|
|
8412
8353
|
}
|
|
8413
8354
|
/* API KEYS (server/apikeys.mjs): what a program or an AI elsewhere may read with a key. Made with no
|
|
8414
8355
|
scope until one is ticked; its secret shown this once, then never; revoked at once, confirmed in place.
|
|
@@ -8633,7 +8574,7 @@
|
|
|
8633
8574
|
$('operators-new').addEventListener('submit', async (event) => {
|
|
8634
8575
|
event.preventDefault();
|
|
8635
8576
|
$('operators-error').hidden = true;
|
|
8636
|
-
try { const r = await post(`${API}/operators`, { email: $('operators-email').value.trim()
|
|
8577
|
+
try { const r = await post(`${API}/operators`, { email: $('operators-email').value.trim() }); showPassword(r.email, r.password); $('operators-email').value = ''; }
|
|
8637
8578
|
catch (error) { $('operators-error').textContent = error.message; $('operators-error').hidden = false; }
|
|
8638
8579
|
await paintOperators();
|
|
8639
8580
|
});
|
|
@@ -8829,11 +8770,8 @@
|
|
|
8829
8770
|
const shortcuts = [...document.querySelectorAll('#settings-shortcuts .list-item b')].map((b) => b.textContent);
|
|
8830
8771
|
chapterNow('s-shortcuts', shortcuts.length ? shortcuts.slice(0, 3).join(' · ') + (shortcuts.length > 3 ? ` +${shortcuts.length - 3}` : '') : uiSaid('set-none', 'None'));
|
|
8831
8772
|
if ($('binders-agent-lists').value !== '') chapterNow('s-binders', uiSaid('set-binders-max', 'Agents make up to {n}', { n: $('binders-agent-lists').value }));
|
|
8832
|
-
|
|
8833
|
-
|
|
8834
|
-
const members = accountRows.filter((r) => r.dataset.role === 'member').length;
|
|
8835
|
-
const admins = accountRows.length - members;
|
|
8836
|
-
chapterNow('s-operators', accountRows.length ? `${uiSaid(admins === 1 ? 'set-admin-1' : 'set-admins', admins === 1 ? '1 administrator' : '{n} administrators', { n: admins })}${members ? ` · ${uiSaid(members === 1 ? 'set-member-1' : 'set-members', members === 1 ? '1 member' : '{n} members', { n: members })}` : ''}` : '');
|
|
8773
|
+
const admins = $('operators-rows').children.length;
|
|
8774
|
+
chapterNow('s-operators', admins ? uiSaid(admins === 1 ? 'set-admin-1' : 'set-admins', admins === 1 ? '1 administrator' : '{n} administrators', { n: admins }) : '');
|
|
8837
8775
|
chapterNow('s-backup', uiSaid('set-backup-now', 'Export · import'));
|
|
8838
8776
|
const shelf = $('shelf-state').textContent.split(' · ')[0];
|
|
8839
8777
|
const keys = $('git-hosts').children.length;
|
|
@@ -13882,8 +13820,8 @@
|
|
|
13882
13820
|
/* A device may have been given several conversations, each by a code of
|
|
13883
13821
|
its own. One is shown at a time; the others are a tap away. */
|
|
13884
13822
|
function offerOthers(others) {
|
|
13885
|
-
$('others').hidden =
|
|
13886
|
-
$('others').textContent = others.length > 0 ? `Conversations (${others.length + 1})` :
|
|
13823
|
+
$('others').hidden = false;
|
|
13824
|
+
$('others').textContent = others.length > 0 ? `Conversations (${others.length + 1})` : 'This device';
|
|
13887
13825
|
$('others').onclick = () => {
|
|
13888
13826
|
const rows = $('others-rows');
|
|
13889
13827
|
rows.replaceChildren();
|
|
@@ -13892,7 +13830,7 @@
|
|
|
13892
13830
|
const name = document.createElement('b'); name.textContent = isCurrent ? `${label} (shown now)` : label;
|
|
13893
13831
|
const open = document.createElement('button'); open.type = 'button'; open.className = 'primary'; open.textContent = 'Open'; open.hidden = isCurrent;
|
|
13894
13832
|
open.addEventListener('click', () => { void window.clavariumShowPairing(id, conversation); });
|
|
13895
|
-
const leave = document.createElement('button'); leave.type = 'button'; leave.textContent = 'Remove from this device';
|
|
13833
|
+
const leave = document.createElement('button'); leave.type = 'button'; leave.textContent = 'Remove from this device';
|
|
13896
13834
|
leave.addEventListener('click', () => {
|
|
13897
13835
|
leave.textContent = 'Yes, remove it'; leave.className = 'danger';
|
|
13898
13836
|
leave.onclick = async () => { await window.clavariumLeave(id); location.reload(); };
|
|
@@ -13924,7 +13862,7 @@
|
|
|
13924
13862
|
say(fresh ? 'pairing' : 'connecting', 'connecting');
|
|
13925
13863
|
const door = await window.clavariumDoor();
|
|
13926
13864
|
if (!door.ok) { shut(door.message); return; }
|
|
13927
|
-
pairing = door.pairing; API =
|
|
13865
|
+
pairing = door.pairing; API = `/c/api/${pairing}`; current = door.conversation ?? '';
|
|
13928
13866
|
document.documentElement.dataset.pairing = pairing; /* not a secret: a name, useless without the key */
|
|
13929
13867
|
offerOthers(door.others);
|
|
13930
13868
|
welcoming = fresh && door.conversation !== null;
|
package/web/index.html
CHANGED
|
@@ -1163,10 +1163,10 @@
|
|
|
1163
1163
|
<section class="settings-group" id="settings-group-access" data-group="access" role="tabpanel" aria-label="Access">
|
|
1164
1164
|
<!-- WHO MAY SIGN IN (server/operators.mjs): hidden on this machine alone. -->
|
|
1165
1165
|
<details class="chapter" id="settings-ch-operators" data-chapter="s-operators" hidden>
|
|
1166
|
-
<summary><span class="chapter-title" data-said="set-ch-s-operators">
|
|
1166
|
+
<summary><span class="chapter-title" data-said="set-ch-s-operators">Administrators</span><span class="chapter-about">Who may sign in.</span></summary>
|
|
1167
1167
|
<div class="chapter-body">
|
|
1168
1168
|
<div id="operators-rows"></div>
|
|
1169
|
-
<form id="operators-new" class="set-row" autocomplete="off"><div class="set-what"><label for="operators-email"
|
|
1169
|
+
<form id="operators-new" class="set-row" autocomplete="off"><div class="set-what"><label for="operators-email">Add an administrator</label><small>Email address</small><small class="tip" hidden>Locked 15 min after 5 failures. The last administrator is never locked or removed.</small></div><div class="set-control"><input id="operators-email" type="email" placeholder="someone@example.com" spellcheck="false" autocapitalize="off" required><button type="submit">Add</button></div></form>
|
|
1170
1170
|
<div id="operators-password" class="as-form" hidden><p><b id="operators-password-for"></b>: its password, shown <b>this once</b>. Give it to them yourself.</p><div class="row"><input id="operators-password-value" readonly spellcheck="false"><button type="button" id="operators-password-copy">Copy</button><button type="button" id="operators-password-done">Done</button></div></div>
|
|
1171
1171
|
<p class="error" id="operators-error" role="alert" hidden></p>
|
|
1172
1172
|
</div>
|
package/web/style.css
CHANGED
|
@@ -195,8 +195,8 @@ footer#keys { border-top: 0; }
|
|
|
195
195
|
.device { display: flex; align-items: center; gap: 10px; padding: 8px 0; border-top: 1px solid var(--line); flex-wrap: wrap; }
|
|
196
196
|
.device b { flex: 1; min-width: 120px; } .device small { color: var(--ink2); }
|
|
197
197
|
button.danger { border-color: var(--danger); color: var(--danger); }
|
|
198
|
-
html
|
|
199
|
-
html
|
|
198
|
+
html[data-door="device"] #app { display: block; }
|
|
199
|
+
html[data-door="device"] #room { height: 100%; }
|
|
200
200
|
#secret-rows { display: flex; flex-direction: column; }
|
|
201
201
|
#secret-new { display: flex; flex-direction: column; gap: 6px; max-width: 560px; }
|
|
202
202
|
#secret-new label { font-size: .75rem; color: var(--ink2); }
|
|
@@ -1148,9 +1148,9 @@ button.inline:hover { color: var(--brass-ink); }
|
|
|
1148
1148
|
.item[data-hidden="true"] { opacity: .7; }
|
|
1149
1149
|
|
|
1150
1150
|
/* ---------- THE BAR (G): « · state dot + name · [Chat | Terminal | Assets N] · settings ---------- */
|
|
1151
|
-
html:not([data-door="device"])
|
|
1152
|
-
html:not([data-door="device"])
|
|
1153
|
-
html:not([data-door="device"])
|
|
1151
|
+
html:not([data-door="device"]) #room > header { flex-wrap: nowrap; }
|
|
1152
|
+
html:not([data-door="device"]) #room > header #state { flex: 0 0 auto; width: 10px; height: 10px; overflow: hidden; font-size: 0; color: transparent; }
|
|
1153
|
+
html:not([data-door="device"]) #room > header #state::before { width: 10px; height: 10px; margin: 0; vertical-align: top; }
|
|
1154
1154
|
.views { display: inline-flex; flex: 0 0 auto; gap: 2px; padding: 3px; border: 1px solid var(--line); border-radius: 10px; background: var(--bg); }
|
|
1155
1155
|
.views button { display: inline-flex; align-items: center; gap: 6px; border: 0; background: transparent; color: var(--ink2); border-radius: 7px; padding: 5px 11px; }
|
|
1156
1156
|
.views button[aria-pressed="true"] { background: var(--panel); color: var(--ink); box-shadow: 0 0 0 1px var(--line); }
|
|
@@ -1159,7 +1159,7 @@ html:not([data-door="device"]):not([data-door="member"]) #room > header #state::
|
|
|
1159
1159
|
header .ic, #folders .ic { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; flex: 0 0 auto; }
|
|
1160
1160
|
#folders { display: inline-flex; align-items: center; gap: 6px; flex: 0 0 auto; }
|
|
1161
1161
|
@media (max-width: 900px) { .views button span, #folders span { display: none; } .views button { padding: 6px 10px; } }
|
|
1162
|
-
@media (max-width: 700px) { html:not([data-door="device"])
|
|
1162
|
+
@media (max-width: 700px) { html:not([data-door="device"]) #room > header #menu { display: none; } }
|
|
1163
1163
|
|
|
1164
1164
|
/* The chat's display settings: an eye, not sliders (Parley draws its own sign; it is masked here). */
|
|
1165
1165
|
#simple-thread .parley-prefs-open svg, #salon-thread .parley-prefs-open svg { display: none; }
|
|
@@ -1490,7 +1490,7 @@ select.pill { appearance: auto; }
|
|
|
1490
1490
|
.rv-tree { position: static; max-height: none; }
|
|
1491
1491
|
}
|
|
1492
1492
|
@media (max-width: 700px) {
|
|
1493
|
-
html:not([data-door="device"])
|
|
1493
|
+
html:not([data-door="device"]) #room > header .views button, html:not([data-door="device"]) #room > header #folders, html:not([data-door="device"]) #room > header .topbar-lead-back { min-height: 36px; height: 36px; }
|
|
1494
1494
|
.views { padding: 2px; }
|
|
1495
1495
|
}
|
|
1496
1496
|
#copy-close, #files-close, #preview-close { font-size: 1.375rem; line-height: 1; min-width: 40px; padding: 4px 10px; }
|
|
@@ -2583,7 +2583,7 @@ header.topbar > :is(.topbar-fold, .topbar-lead-back):hover { color: var(--ink);
|
|
|
2583
2583
|
header.topbar > .topbar-lead-back[hidden] { display: none; }
|
|
2584
2584
|
@media (max-width: 700px) { header.topbar > .topbar-fold { display: none; } }
|
|
2585
2585
|
@media (min-width: 701px) { header.topbar > .topbar-lead-back { display: none; } }
|
|
2586
|
-
header.topbar .bar-state, html:not([data-door="device"])
|
|
2586
|
+
header.topbar .bar-state, html:not([data-door="device"]) header.topbar #state { width: 10px; height: 10px; border-radius: 50%; flex: none; }
|
|
2587
2587
|
header.topbar .bar-state { background: var(--ok); }
|
|
2588
2588
|
header.topbar .bar-state[hidden] { display: none; }
|
|
2589
2589
|
/* A room one of whose AIs speaks now: its dot as a conversation's at work, the words under its name. */
|
|
@@ -2600,7 +2600,7 @@ header.topbar .views .icon-btn { width: auto; height: auto; }
|
|
|
2600
2600
|
header.topbar .views button { height: 32px; min-height: 32px; padding-block: 0; }
|
|
2601
2601
|
@media (max-width: 700px) { header.topbar { height: 48px; min-height: 48px; padding: 0 8px; gap: 6px; } }
|
|
2602
2602
|
/* A device's page (/c/): the same bar, its own controls may take a second line on a narrow screen (its menu "..."). */
|
|
2603
|
-
html
|
|
2603
|
+
html[data-door="device"] header.topbar { height: auto; }
|
|
2604
2604
|
/* A place's top bar stays at the top while its page scrolls (05-11), edge to edge over the page's own margins.
|
|
2605
2605
|
(A page with a bar starts at its bar: no margin above it, so it sticks where it rests.) */
|
|
2606
2606
|
:is(.sheet, #newconv, #salon-new):has(> header.topbar) { padding-top: 0; }
|
|
@@ -3179,11 +3179,11 @@ button.kit-switch[aria-checked="true"]::after { left: 18px; background: var(--ok
|
|
|
3179
3179
|
#machines-confirm { margin: 8px 16px; }
|
|
3180
3180
|
/* A phone (13-11): the bar's five buttons tighter, so that all stay on the screen -- its name gives way, never the bar. */
|
|
3181
3181
|
@media (max-width: 480px) {
|
|
3182
|
-
html:not([data-door="device"])
|
|
3183
|
-
html:not([data-door="device"])
|
|
3184
|
-
html:not([data-door="device"])
|
|
3185
|
-
html:not([data-door="device"])
|
|
3186
|
-
html:not([data-door="device"])
|
|
3182
|
+
html:not([data-door="device"]) #room > header #name { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
3183
|
+
html:not([data-door="device"]) #room > header :is(.bar-right, .views) { flex: none; }
|
|
3184
|
+
html:not([data-door="device"]) #room > header .views { gap: 0; padding: 2px; }
|
|
3185
|
+
html:not([data-door="device"]) #room > header .views button { gap: 4px; padding-inline: 7px; }
|
|
3186
|
+
html:not([data-door="device"]) #room > header .views .count { min-width: 1.2em; padding: 1px 4px; }
|
|
3187
3187
|
}
|
|
3188
3188
|
/* At hand (13-11): a switch's name never under its buttons -- the name keeps its width, the buttons wrap. */
|
|
3189
3189
|
.hand-switches .set-row > .set-what { flex: none; }
|
|
@@ -3455,9 +3455,3 @@ span.tile-spark { display: block; height: 22px; }
|
|
|
3455
3455
|
#signin-code .error { margin: 0; }
|
|
3456
3456
|
#signin-code button { align-self: flex-end; min-height: 40px; }
|
|
3457
3457
|
.companion-yours { margin: 2px 0 8px; font-size: .75rem; color: var(--ink2); }
|
|
3458
|
-
|
|
3459
|
-
/* What a member was given (#419): under its account, indented. */
|
|
3460
|
-
.op-given{display:flex;flex-direction:column;gap:6px;margin:-4px 0 10px 18px;padding-left:10px;border-left:2px solid var(--line, #ccc)}
|
|
3461
|
-
.op-given-line{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap}
|
|
3462
|
-
.op-given-line span{min-width:0;overflow-wrap:anywhere}
|
|
3463
|
-
.op-role{margin-right:6px}
|
package/server/people.mjs
DELETED
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
/* WHO IS AN ADMINISTRATOR, WHO A MEMBER (24-11, #419).
|
|
2
|
-
*
|
|
3
|
-
* BEFORE ANY MEMBER (no file): every account that may sign in (operators.mjs) is an ADMINISTRATOR, as every account
|
|
4
|
-
* was before this file existed -- an update changes nothing for the accounts already there.
|
|
5
|
-
*
|
|
6
|
-
* THE FIRST MEMBER writes the file, and from then on BOTH lists are written out: the administrators by name (every
|
|
7
|
-
* account there was then, but the new member) and the members. An account in neither -- added outside the page,
|
|
8
|
-
* or between two steps -- is a MEMBER: nothing is ever given by default (audit 24-11).
|
|
9
|
-
*
|
|
10
|
-
* Two rules on top, never broken:
|
|
11
|
-
* - ONE ACCOUNT, AN ADMINISTRATOR: when only one account exists (enabled or not: a member must never become the
|
|
12
|
-
* only one by having the others locked out), it is an administrator, whatever was written;
|
|
13
|
-
* - THE LAST ADMINISTRATOR stays one: it cannot be made a member (nor, in operators.mjs, disabled, removed or
|
|
14
|
-
* locked out after failed sign-ins).
|
|
15
|
-
*
|
|
16
|
-
* KEPT where nothing half-written is ever read: written to a new file renamed over the old one, the good one before
|
|
17
|
-
* it kept as `.bak`. Both unreadable: the lists last read stay in use; at a start with none, the accounts the
|
|
18
|
-
* server was installed with (`install`, its --operators) are the administrators and every other one a member --
|
|
19
|
-
* never everybody locked out, never a member made an administrator. It is said, loudly.
|
|
20
|
-
*/
|
|
21
|
-
import { readFileSync, writeFileSync, renameSync, existsSync, copyFileSync, mkdirSync } from 'node:fs';
|
|
22
|
-
import { dirname } from 'node:path';
|
|
23
|
-
import { Refusal } from './conversations.mjs';
|
|
24
|
-
|
|
25
|
-
export const ROLES = Object.freeze(['admin', 'member']);
|
|
26
|
-
/* What deploy/updater.mjs looks for in a release before going back to it: it reads these lists (#419). */
|
|
27
|
-
export const PEOPLE_LISTS = 1;
|
|
28
|
-
const low = (e) => String(e ?? '').trim().toLowerCase();
|
|
29
|
-
|
|
30
|
-
export class People {
|
|
31
|
-
#path; #lists = null; #damaged = false; #accounts; #tell; #install; #changed = () => {};
|
|
32
|
-
/* `accounts()`: every account there is, enabled or not ([{ email, enabled }], operators.mjs).
|
|
33
|
-
`install`: the accounts the server was started with (--operators), the administrators of last resort. */
|
|
34
|
-
#leaving;
|
|
35
|
-
/* `leaving()`: the accounts being disabled or removed right now (operators.mjs), already not counted. */
|
|
36
|
-
constructor({ path, accounts = () => [], tell = () => {}, install = [], leaving = () => [] }) {
|
|
37
|
-
this.#path = path; this.#accounts = accounts; this.#tell = tell; this.#install = install.map(low); this.#leaving = leaving;
|
|
38
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
39
|
-
this.#load();
|
|
40
|
-
}
|
|
41
|
-
/* Told when a role changes: the terminals of whoever lost something end at once (bridge.recheck). */
|
|
42
|
-
useChanged(fn) { this.#changed = fn; }
|
|
43
|
-
changed() { try { this.#changed(); } catch { /* the minute's recheck sees it */ } }
|
|
44
|
-
|
|
45
|
-
#read(file) {
|
|
46
|
-
const data = JSON.parse(readFileSync(file, 'utf8'));
|
|
47
|
-
if (!data || !Array.isArray(data.admins) || !Array.isArray(data.members)) throw new Error('not a roles file');
|
|
48
|
-
return { admins: [...new Set(data.admins.map(low))], members: [...new Set(data.members.map(low))] };
|
|
49
|
-
}
|
|
50
|
-
#load() {
|
|
51
|
-
if (!existsSync(this.#path) && !existsSync(`${this.#path}.bak`)) { this.#lists = null; return; }
|
|
52
|
-
for (const file of [this.#path, `${this.#path}.bak`]) {
|
|
53
|
-
try { this.#lists = this.#read(file); this.#damaged = false; return; } catch { /* the next one */ }
|
|
54
|
-
}
|
|
55
|
-
this.#damaged = true;
|
|
56
|
-
this.#tell('The file of who is an administrator cannot be read', `${this.#path}: until it is repaired, the accounts this server was installed with are its administrators, every other one a member.`);
|
|
57
|
-
}
|
|
58
|
-
#save() {
|
|
59
|
-
const tmp = `${this.#path}.new`;
|
|
60
|
-
writeFileSync(tmp, `${JSON.stringify(this.#lists, null, 1)}\n`, { mode: 0o600 });
|
|
61
|
-
if (existsSync(this.#path)) { try { this.#read(this.#path); copyFileSync(this.#path, `${this.#path}.bak`); } catch { /* the old one was bad: no copy of it */ } }
|
|
62
|
-
renameSync(tmp, this.#path);
|
|
63
|
-
this.#damaged = false;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
#all() { return (this.#accounts() ?? []).map((a) => ({ email: low(a.email), enabled: a.enabled !== false })); }
|
|
67
|
-
|
|
68
|
-
/* 'admin' or 'member'. */
|
|
69
|
-
roleOf(email) {
|
|
70
|
-
const e = low(email);
|
|
71
|
-
if (this.#all().length <= 1) return 'admin';
|
|
72
|
-
if (this.#damaged) return this.#install.includes(e) ? 'admin' : 'member';
|
|
73
|
-
if (this.#lists === null) return 'admin';
|
|
74
|
-
return this.#lists.admins.includes(e) && !this.#lists.members.includes(e) ? 'admin' : 'member';
|
|
75
|
-
}
|
|
76
|
-
/* The enabled administrators. */
|
|
77
|
-
admins() { const out = new Set([...this.#leaving()].map(low)); return this.#all().filter((a) => a.enabled && !out.has(a.email) && this.roleOf(a.email) === 'admin').map((a) => a.email); }
|
|
78
|
-
/* Whether taking `email` out of the administrators (made a member, disabled, removed, locked out) leaves none. */
|
|
79
|
-
isLastAdmin(email) {
|
|
80
|
-
const e = low(email);
|
|
81
|
-
const admins = this.admins();
|
|
82
|
-
return admins.length <= 1 && (admins.length === 0 || admins[0] === e);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/* The lists written out at the first member: every account there is now an administrator, as it was. */
|
|
86
|
-
#seed() { if (this.#lists === null) this.#lists = { admins: this.#all().map((a) => a.email), members: [] }; }
|
|
87
|
-
#put(e, role) {
|
|
88
|
-
this.#lists.admins = this.#lists.admins.filter((x) => x !== e);
|
|
89
|
-
this.#lists.members = this.#lists.members.filter((x) => x !== e);
|
|
90
|
-
(role === 'admin' ? this.#lists.admins : this.#lists.members).push(e);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
setRole(email, role) {
|
|
94
|
-
const e = low(email);
|
|
95
|
-
if (!ROLES.includes(role)) throw new Refusal(400, 'A role is admin or member.');
|
|
96
|
-
if (!this.#all().some((a) => a.email === e)) throw new Refusal(404, 'No such account.');
|
|
97
|
-
if (this.#damaged) throw new Refusal(503, 'The file of who is an administrator cannot be read: repair it first.');
|
|
98
|
-
if (role === this.roleOf(e)) return this.list();
|
|
99
|
-
if (role === 'member' && this.isLastAdmin(e)) throw new Refusal(409, 'The last administrator cannot be made a member.');
|
|
100
|
-
this.#seed(); this.#put(e, role); this.#save();
|
|
101
|
-
this.changed();
|
|
102
|
-
return this.list();
|
|
103
|
-
}
|
|
104
|
-
/* An account ABOUT TO BE added, its role said first: never an administrator for a moment by mistake, and an
|
|
105
|
-
account removed then added again does not come back as it was. */
|
|
106
|
-
adding(email, role) {
|
|
107
|
-
const e = low(email);
|
|
108
|
-
if (!ROLES.includes(role) || this.#damaged) return;
|
|
109
|
-
if (this.#lists === null && role === 'admin') return;
|
|
110
|
-
this.#seed(); this.#put(e, role); this.#save();
|
|
111
|
-
}
|
|
112
|
-
/* An account removed: its role forgotten with it. */
|
|
113
|
-
removed(email) {
|
|
114
|
-
const e = low(email);
|
|
115
|
-
if (this.#lists === null || this.#damaged) return;
|
|
116
|
-
this.#lists.admins = this.#lists.admins.filter((x) => x !== e);
|
|
117
|
-
this.#lists.members = this.#lists.members.filter((x) => x !== e);
|
|
118
|
-
this.#save();
|
|
119
|
-
}
|
|
120
|
-
/* Accounts gone outside the page (the host program): their roles forgotten. Returns the addresses forgotten. */
|
|
121
|
-
prune() {
|
|
122
|
-
if (this.#lists === null || this.#damaged) return [];
|
|
123
|
-
const here = new Set(this.#all().map((a) => a.email));
|
|
124
|
-
if (here.size === 0) return [];
|
|
125
|
-
const gone = [...this.#lists.admins, ...this.#lists.members].filter((e) => !here.has(e));
|
|
126
|
-
if (!gone.length) return [];
|
|
127
|
-
this.#lists.admins = this.#lists.admins.filter((e) => here.has(e)); this.#lists.members = this.#lists.members.filter((e) => here.has(e));
|
|
128
|
-
this.#save();
|
|
129
|
-
return gone;
|
|
130
|
-
}
|
|
131
|
-
/* The role a new account gets when none is said: a member (24-11, its owner's choice); an administrator is ticked. */
|
|
132
|
-
defaultRole() { return 'member'; }
|
|
133
|
-
list() { return this.#all().map((a) => ({ ...a, role: this.roleOf(a.email) })); }
|
|
134
|
-
}
|
package/web/member.js
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
/* THE MEMBER'S PAGE (people.mjs, #419): the page of a paired device, for a person signed in whom an administrator
|
|
2
|
-
made a member. No code, no key, no session of its own: who it is comes from the sign-in, checked by the server
|
|
3
|
-
at each request. What it was given, and only that, is shown; the server refuses the rest whatever this page does. */
|
|
4
|
-
(() => {
|
|
5
|
-
const KEPT = 'clavarium-member-current';
|
|
6
|
-
const kept = () => { try { return localStorage.getItem(KEPT) ?? ''; } catch { return ''; } };
|
|
7
|
-
/* Resolves as the device page's does: { ok, pairing, conversation, others: [{ pairing, name }] } or { ok: false, message }. */
|
|
8
|
-
window.clavariumDoor = async () => {
|
|
9
|
-
try {
|
|
10
|
-
const r = await fetch('/m/api/me');
|
|
11
|
-
if (r.status === 403 || r.status === 401) return { ok: false, message: 'This account may not use this page now. Ask an administrator.' };
|
|
12
|
-
if (!r.ok) throw new Error(`The server answered ${r.status}.`);
|
|
13
|
-
const me = await r.json();
|
|
14
|
-
const names = Array.isArray(me.conversations) ? me.conversations : [];
|
|
15
|
-
if (names.length === 0 && !(me.shared ?? []).length) return { ok: false, message: 'Nothing has been given to you yet. Ask an administrator to give you a conversation.' };
|
|
16
|
-
const current = names.includes(kept()) ? kept() : (names[0] ?? null);
|
|
17
|
-
return { ok: true, pairing: 'member', conversation: current, others: names.filter((n) => n !== current).map((name) => ({ pairing: 'member', name })) };
|
|
18
|
-
} catch (error) {
|
|
19
|
-
return { ok: false, message: error.message };
|
|
20
|
-
}
|
|
21
|
-
};
|
|
22
|
-
window.clavariumShowPairing = async (_id, name) => { try { localStorage.setItem(KEPT, name ?? ''); } catch { /* this visit only */ } location.reload(); };
|
|
23
|
-
/* A member does not take a conversation off: an administrator does. */
|
|
24
|
-
window.clavariumLeave = async () => {};
|
|
25
|
-
window.clavariumForgetDevice = async () => {};
|
|
26
|
-
})();
|