clavarium 0.2.525-next.1 → 0.2.526-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/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/api.mjs +34 -3
- package/server/bridge.mjs +12 -1
- package/server/door.mjs +17 -11
- package/server/grants.mjs +5 -2
- package/server/main.mjs +46 -4
- package/server/operators.mjs +7 -3
- package/server/people.mjs +105 -0
- package/server/settingswords.mjs +2 -2
- package/web/app.js +67 -12
- package/web/index.html +2 -2
- package/web/member.js +26 -0
- package/web/style.css +6 -0
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.526-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.526-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,7 +493,8 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
493
493
|
if (pathname === '/api/wifi' && wifi) return send(200, await wifi.status()), true;
|
|
494
494
|
if (pathname === '/api/wifi/scan' && wifi) return send(200, await wifi.scan()), true;
|
|
495
495
|
if (pathname === '/api/meshcentral' && meshcentral) return send(200, await meshcentral.status()), true;
|
|
496
|
-
|
|
496
|
+
/* Each account with its role and, for a member, the conversations it was given (#419). */
|
|
497
|
+
if (pathname === '/api/operators') return send(200, team ? { operators: team.list().map((o) => ({ ...o, role: team.people?.roleOf(o.email) ?? 'admin', ...(team.people?.roleOf(o.email) === 'member' ? { given: team.grants?.of(`person:${o.email}`, 'conversation').map((g) => ({ name: g.name, rights: g.rights })) ?? [] } : {}) })), me: identity, defaultRole: team.people?.defaultRole?.() ?? 'admin' } : { local: true }), true;
|
|
497
498
|
if (pathname === '/api/binder/people' && binders) return send(200, { people: binders.people(identity), changes: `${BOOT}:${binders.changes()}` }), true;
|
|
498
499
|
if (pathname === '/api/certificate' && certificate) return send(200, await certificate.about({ fresh: query.get('fresh') === '1' })), true;
|
|
499
500
|
/* This server's disk and memory (capacity.mjs): everything for Settings; only whether it is high for the list. */
|
|
@@ -791,13 +792,43 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
791
792
|
if (pathname === '/api/wifi/handover' && wifi) return send(202, await wifi.handover()), true;
|
|
792
793
|
if (pathname === '/api/meshcentral/enable' && meshcentral) return send(202, await meshcentral.enable()), true;
|
|
793
794
|
if (pathname === '/api/meshcentral/disable' && meshcentral) return send(200, await meshcentral.disable()), true;
|
|
794
|
-
if (pathname === '/api/operators' && team)
|
|
795
|
+
if (pathname === '/api/operators' && team) {
|
|
796
|
+
/* Its role said at once (#419): an account removed and added again does not come back as it was. */
|
|
797
|
+
const role = body.role === 'member' ? 'member' : body.role === 'admin' ? 'admin' : (team.people?.defaultRole?.() ?? 'admin');
|
|
798
|
+
const made = await team.add(body.email);
|
|
799
|
+
team.people?.added(made.email, role);
|
|
800
|
+
return send(201, { ...made, role: team.people?.roleOf(made.email) ?? 'admin' }), true;
|
|
801
|
+
}
|
|
802
|
+
/* An account made an administrator or a member (#419): never oneself, never the last administrator. */
|
|
803
|
+
const roleOf = /^\/api\/operators\/([^/]{3,200})\/role$/.exec(pathname);
|
|
804
|
+
if (roleOf && team?.people) {
|
|
805
|
+
const email = decodeURIComponent(roleOf[1]).toLowerCase();
|
|
806
|
+
if (email === identity) throw new Refusal(409, 'You cannot change your own role: ask another administrator.');
|
|
807
|
+
return send(200, { operators: team.people.setRole(email, String(body.role ?? '')) }), true;
|
|
808
|
+
}
|
|
809
|
+
/* A conversation given to a member, or taken back: its chat (read or write) and/or its terminal (#419). */
|
|
810
|
+
const giving = /^\/api\/operators\/([^/]{3,200})\/(give|take)$/.exec(pathname);
|
|
811
|
+
if (giving && team?.people && team.grants) {
|
|
812
|
+
const email = decodeURIComponent(giving[1]).toLowerCase();
|
|
813
|
+
if (team.people.roleOf(email) !== 'member') throw new Refusal(409, 'Only a member is given conversations: an administrator has them all.');
|
|
814
|
+
const name = String(body.conversation ?? '');
|
|
815
|
+
if (!conversations.list().some((c) => c.name === name)) throw new Refusal(404, 'No such conversation.');
|
|
816
|
+
const rights = giving[2] === 'take' ? '' : `${body.chat === 'write' ? 'rw' : body.chat === 'read' ? 'r' : ''}${body.terminal === true ? 'x' : ''}`;
|
|
817
|
+
if (rights === '') team.grants.take(`person:${email}`, `conversation:${name}`);
|
|
818
|
+
else team.grants.give(`person:${email}`, `conversation:${name}`, rights);
|
|
819
|
+
team.people.changed?.();
|
|
820
|
+
return send(200, { given: team.grants.of(`person:${email}`, 'conversation').map((g) => ({ name: g.name, rights: g.rights })) }), true;
|
|
821
|
+
}
|
|
795
822
|
const op = /^\/api\/operators\/([^/]{3,200})\/(password|disable|enable|remove)$/.exec(pathname);
|
|
796
823
|
if (op && team) {
|
|
797
824
|
const email = decodeURIComponent(op[1]);
|
|
798
825
|
/* Not oneself out: another operator does it, or nobody would see it was a mistake. */
|
|
799
826
|
if (op[2] !== 'password' && op[2] !== 'enable' && email.toLowerCase() === identity) throw new Refusal(409, 'You cannot do that to your own account: ask another operator.');
|
|
800
|
-
|
|
827
|
+
const done = op[2] === 'password' ? await team.password(email) : { operators: await team[op[2]](email) };
|
|
828
|
+
/* Removed: its role and what it was given go with it (#419). */
|
|
829
|
+
if (op[2] === 'remove') { team.people?.removed(email); team.grants?.forgetSubject(`person:${email.toLowerCase()}`); }
|
|
830
|
+
team.people?.changed?.();
|
|
831
|
+
return send(200, done), true;
|
|
801
832
|
}
|
|
802
833
|
const renaming = /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/rename$/.exec(pathname);
|
|
803
834
|
/* Its machines that run get the new name or value now, as a secret given to them does. */
|
package/server/bridge.mjs
CHANGED
|
@@ -90,7 +90,9 @@ export const sameOrigin = makeOriginCheck();
|
|
|
90
90
|
const BY_ITSELF = /\x1b\[[IO]|\x1b\[\??[>=]?[\d;]*c|\x1b\[\d+;\d+R|\x1b\][\d;]*(?:rgb:[0-9a-fA-F/]+)?(?:\x07|\x1b\\)|\x1bP[^\x1b]*\x1b\\/g;
|
|
91
91
|
export const byHand = (typed) => String(typed ?? '').replace(BY_ITSELF, '').length > 0;
|
|
92
92
|
|
|
93
|
-
export
|
|
93
|
+
export const MEMBER_PATH = '/m/terminal';
|
|
94
|
+
|
|
95
|
+
export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () => {}, originOk = sameOrigin, gate = () => 'local', deviceName = () => undefined, memberName = () => undefined, onRejoin = () => {}, onTyped = () => {}, asleep = () => false }) {
|
|
94
96
|
const sockets = new WebSocketServer({ noServer: true });
|
|
95
97
|
const seats = new Seats();
|
|
96
98
|
/* THE DEVICES AT A TERMINAL, each with what lets it stay: asked again when the owner changes
|
|
@@ -120,9 +122,18 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
120
122
|
name = ask();
|
|
121
123
|
if (!isConversationName(name) || !originOk(request.headers)) { socket.destroy(); return; }
|
|
122
124
|
still = () => ask() === name;
|
|
125
|
+
} else if (url.pathname === MEMBER_PATH) {
|
|
126
|
+
/* A member (people.mjs, #419): the sign-in names it; the terminal of a conversation it was given, only. */
|
|
127
|
+
const wanted = url.searchParams.get('c') ?? '';
|
|
128
|
+
const ask = () => memberName(request.headers, wanted) ?? '';
|
|
129
|
+
name = ask();
|
|
130
|
+
if (!isConversationName(name) || !originOk(request.headers)) { socket.destroy(); return; }
|
|
131
|
+
still = () => ask() === name;
|
|
123
132
|
} else if (url.pathname === PATH) {
|
|
124
133
|
name = url.searchParams.get('c') ?? '';
|
|
125
134
|
if (!isConversationName(name) || !originOk(request.headers) || gate(request.headers) === undefined) { socket.destroy(); return; }
|
|
135
|
+
/* An administrator made a member, or an account disabled: its open terminals end too (#419). */
|
|
136
|
+
still = () => gate(request.headers) !== undefined;
|
|
126
137
|
} else return;
|
|
127
138
|
const cols = Number(url.searchParams.get('cols'));
|
|
128
139
|
const rows = Number(url.searchParams.get('rows'));
|
package/server/door.mjs
CHANGED
|
@@ -87,13 +87,18 @@ export function devicePairing(devices, headers, pairing) {
|
|
|
87
87
|
}
|
|
88
88
|
|
|
89
89
|
/* Returns true when the request was under /c/api/ (answered here). */
|
|
90
|
-
export async function handleDoor(request, response, { devices, conversations, resources, shortcuts, voice, originOk, headers, secure, talk, repair, tethers, mailboxes, signinCode }) {
|
|
90
|
+
export async function handleDoor(request, response, { devices, conversations, resources, shortcuts, voice, originOk, headers, secure, talk, repair, tethers, mailboxes, signinCode, person }) {
|
|
91
91
|
const url = new URL(request.url ?? '/', 'http://local');
|
|
92
|
-
|
|
92
|
+
/* A MEMBER (people.mjs, #419) comes through the same door, at /m/api/, as the person the sign-in names: no
|
|
93
|
+
pairing, no code, no key, no session of its own -- who it is comes from the gate alone, never from the address.
|
|
94
|
+
What it was given is read from the same table as a device's, under `person:<email>`. */
|
|
95
|
+
const base = person ? '/m/api' : '/c/api';
|
|
96
|
+
if (!url.pathname.startsWith(`${base}/`)) return false;
|
|
93
97
|
/* "/<pairing>/me" -> the pairing and "/me"; "/pair" has no pairing yet. */
|
|
94
|
-
const named = /^\/([0-9a-f-]{36})(\/.*)$/.exec(url.pathname.slice(
|
|
95
|
-
const pairing = named?.[1];
|
|
96
|
-
const route = named ? named[2] : url.pathname.slice(
|
|
98
|
+
const named = person ? null : /^\/([0-9a-f-]{36})(\/.*)$/.exec(url.pathname.slice(base.length));
|
|
99
|
+
const pairing = person ? person.key : named?.[1];
|
|
100
|
+
const route = named ? named[2] : url.pathname.slice(base.length);
|
|
101
|
+
const given_ = person ?? devices;
|
|
97
102
|
const send = (status, body, extra = {}) => {
|
|
98
103
|
response.writeHead(status, { ...headers, ...extra, 'content-type': 'application/json; charset=utf-8' }).end(JSON.stringify(body));
|
|
99
104
|
return true;
|
|
@@ -101,7 +106,8 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
101
106
|
try {
|
|
102
107
|
if (request.method === 'POST' && !originOk(request.headers)) return send(403, { error: 'This request does not come from this site.' });
|
|
103
108
|
|
|
104
|
-
/* ---- pairing: no session yet ---- */
|
|
109
|
+
/* ---- pairing: no session yet (never for a member: 404) ---- */
|
|
110
|
+
if (person && ['/pair', '/challenge', '/session', '/leave'].includes(route)) return send(404, { error: 'Not found.' });
|
|
105
111
|
if (request.method === 'POST' && route === '/pair') return send(201, devices.pair(await readJson(request)));
|
|
106
112
|
if (request.method === 'POST' && route === '/challenge') return send(200, devices.challenge(String((await readJson(request)).device ?? '')));
|
|
107
113
|
if (request.method === 'POST' && route === '/session') {
|
|
@@ -111,16 +117,16 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
111
117
|
}
|
|
112
118
|
|
|
113
119
|
/* ---- everything else: a device session, and its one conversation ---- */
|
|
114
|
-
if (devicePairing(devices, request.headers, pairing) === undefined) return send(401, { error: 'This device has no open session.' });
|
|
120
|
+
if (!person && devicePairing(devices, request.headers, pairing) === undefined) return send(401, { error: 'This device has no open session.' });
|
|
115
121
|
/* What this pairing was given: conversations to use, and things of its own to read or write. */
|
|
116
|
-
const given =
|
|
122
|
+
const given = given_.grantsOf(pairing);
|
|
117
123
|
const names = given.filter((g) => g.type === 'conversation').map((g) => g.name);
|
|
118
124
|
const own = given.filter((g) => g.type !== 'conversation').filter((g) => resources.get(g.name))
|
|
119
125
|
.map((g) => ({ name: g.name, type: g.type, access: g.rights.includes('w') ? 'write' : 'read' }));
|
|
120
|
-
const name = deviceConversation(devices, request.headers, pairing, url.searchParams.get('c') ?? undefined);
|
|
126
|
+
const name = person ? person.conversationOf(url.searchParams.get('c') ?? undefined) : deviceConversation(devices, request.headers, pairing, url.searchParams.get('c') ?? undefined);
|
|
121
127
|
const mine = name === undefined ? undefined : conversations.list().find((c) => c.name === name);
|
|
122
128
|
/* The parts of that conversation this pairing was given. */
|
|
123
|
-
const rights = name === undefined ? '' :
|
|
129
|
+
const rights = name === undefined ? '' : given_.rightsOn(pairing, name);
|
|
124
130
|
const part = { terminal: rights.includes('x'), chat: rights.includes('r') ? (rights.includes('w') ? 'write' : 'read') : null };
|
|
125
131
|
const need = (ok, what) => { if (!ok) throw new Refusal(403, `This device was not given ${what} of this conversation.`); };
|
|
126
132
|
/* Its chat alone: what is reached through the conversation is only what its chat holds. */
|
|
@@ -228,7 +234,7 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
228
234
|
}
|
|
229
235
|
/* A mail cited by its reference (mailref.mjs): only a mailbox this device was given to read. */
|
|
230
236
|
if (request.method === 'GET' && (route === '/mail/open' || route === '/mail/page')) {
|
|
231
|
-
return await mailRoute(route, url.searchParams, response, { tethers, headers, who: { id: `pairing:${pairing}`, name: 'A device' }, may: (t) => deviceMayRead(t, own, mailboxes), offline: mine?.offline === true });
|
|
237
|
+
return await mailRoute(route, url.searchParams, response, { tethers, headers, who: person ? { id: `person:${person.email}`, name: person.email } : { id: `pairing:${pairing}`, name: 'A device' }, may: (t) => deviceMayRead(t, own, mailboxes), offline: mine?.offline === true });
|
|
232
238
|
}
|
|
233
239
|
if (request.method === 'GET' && route === '/files/download') {
|
|
234
240
|
const file = await download(attached('read', 'open'), url.searchParams.get('p') ?? '');
|
package/server/grants.mjs
CHANGED
|
@@ -67,7 +67,7 @@ import { Refusal } from './conversations.mjs';
|
|
|
67
67
|
export const RIGHTS = Object.freeze({ conversation: 'rwxm', folder: 'rw', mailbox: 'r', git: 'rw', secret: 'x', server: 'rw', room: 'rwm', box: 'rw' });
|
|
68
68
|
/* What each of the server's own assets takes: its state and its jobs are read, rooms are made. */
|
|
69
69
|
const SERVER_RIGHTS = Object.freeze({ 'server:status': 'r', 'server:jobs': 'r', 'server:rooms': 'w', 'server:diagnostics': 'r' });
|
|
70
|
-
const SUBJECT = /^(conversation:[a-z]([a-z0-9-]{0,30}[a-z0-9])?|(pairing|apikey):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
|
|
70
|
+
const SUBJECT = /^(conversation:[a-z]([a-z0-9-]{0,30}[a-z0-9])?|(pairing|apikey):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|person:[a-z0-9._+-]{1,64}@([a-z0-9-]{1,63}\.)+[a-z]{2,24})$/;
|
|
71
71
|
const ASSET = /^(conversation|folder|mailbox|git):[a-z]([a-z0-9-]{0,30}[a-z0-9])?$|^secret:[A-Z][A-Z0-9_]{0,39}$|^server:(status|jobs|rooms|diagnostics)$|^(room|box):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
72
72
|
|
|
73
73
|
export const typeOf = (asset) => String(asset).split(':')[0];
|
|
@@ -75,6 +75,7 @@ export const nameOf = (asset) => String(asset).slice(String(asset).indexOf(':')
|
|
|
75
75
|
export const conversationSubject = (name) => `conversation:${name}`;
|
|
76
76
|
export const pairingSubject = (id) => `pairing:${id}`;
|
|
77
77
|
export const apiKeySubject = (id) => `apikey:${id}`;
|
|
78
|
+
export const personSubject = (email) => `person:${String(email).toLowerCase()}`;
|
|
78
79
|
|
|
79
80
|
/* The rights asked for, in the one order they are written, or a refusal:
|
|
80
81
|
only letters this type of asset takes, at least one, none twice. */
|
|
@@ -114,7 +115,9 @@ export class Grants {
|
|
|
114
115
|
/* A secret is handed to a conversation, never to a device: a device
|
|
115
116
|
would be a way to read it. */
|
|
116
117
|
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
|
+
/* A MEMBER (person:, people.mjs, #419) is given conversations only, in this version: its chat, its terminal. */
|
|
119
|
+
if (subject.startsWith('person:') && typeOf(asset) !== 'conversation') throw new Refusal(400, 'A member is given conversations only.');
|
|
120
|
+
if (typeOf(asset) === 'conversation' && !subject.startsWith('pairing:') && !subject.startsWith('apikey:') && !subject.startsWith('person:')) throw new Refusal(400, 'A conversation is shared with a device or an API key, not with another conversation.');
|
|
118
121
|
/* The state of the server is given to an API key only; an API key is given only that, and
|
|
119
122
|
conversations one by one -- their chat, to read or to write in, never their terminal. */
|
|
120
123
|
if (typeOf(asset) === 'server' && !subject.startsWith('apikey:')) throw new Refusal(400, 'The state of the server is given to an API key only.');
|
package/server/main.mjs
CHANGED
|
@@ -32,6 +32,7 @@ import { Vms, runner, HostTally } from './vm.mjs';
|
|
|
32
32
|
import { Resources, WORK_TAB } from './resources.mjs';
|
|
33
33
|
import { download } from './files.mjs';
|
|
34
34
|
import { makeGate, makeOriginCheck, readOperators } from './gate.mjs';
|
|
35
|
+
import { People } from './people.mjs';
|
|
35
36
|
import { Shortcuts } from './shortcuts.mjs';
|
|
36
37
|
import { hearBox, Dictation } from './voice.mjs';
|
|
37
38
|
import QRCode from 'qrcode';
|
|
@@ -176,6 +177,11 @@ try {
|
|
|
176
177
|
const DEVICE_FILES = Object.fromEntries(Object.entries(FILES).filter(([path]) => path !== '/').map(([path, file]) => [`/c${path}`, file]));
|
|
177
178
|
DEVICE_FILES['/c/'] = ['web/device.html', 'text/html; charset=utf-8'];
|
|
178
179
|
DEVICE_FILES['/c/device.js'] = ['web/device.js', 'text/javascript; charset=utf-8'];
|
|
180
|
+
/* A MEMBER's page (people.mjs, #419): the same files under /m/, behind the sign-in; its page is the device's,
|
|
181
|
+
told it is a member's, with member.js (no pairing) in place of device.js. */
|
|
182
|
+
const MEMBER_FILES = Object.fromEntries(Object.entries(FILES).filter(([path]) => path !== '/').map(([path, file]) => [`/m${path}`, file]));
|
|
183
|
+
MEMBER_FILES['/m/member.js'] = ['web/member.js', 'text/javascript; charset=utf-8'];
|
|
184
|
+
const memberPage = () => readFileSync(`${ROOT}web/device.html`, 'utf8').replace('data-door="device"', 'data-door="member"').replace('<script src="device.js"></script>', '<script src="member.js"></script>');
|
|
179
185
|
|
|
180
186
|
/* Nothing loads from anywhere else, and nothing may frame the page. */
|
|
181
187
|
const HEADERS = {
|
|
@@ -202,7 +208,7 @@ const withoutTmux = (env) => Object.fromEntries(Object.entries(env).filter(([key
|
|
|
202
208
|
|
|
203
209
|
const REFUSED = 'This Clavarium belongs to someone else: your account is not one of its operators.\n';
|
|
204
210
|
|
|
205
|
-
function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, machineList, features, apikeys, relayJoin, desks } = {}) {
|
|
211
|
+
function serve(port, conversations, resources, { gate = () => 'local', memberGate = () => undefined, personOf = null, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, machineList, features, apikeys, relayJoin, desks } = {}) {
|
|
206
212
|
/* Its manifest carries the name of this Clavarium, or the one a device chose (instance.mjs). */
|
|
207
213
|
const sendManifest = (response, url) => response.writeHead(200, { ...HEADERS, 'content-type': 'application/manifest+json' }).end(instance.manifest(new URL(url ?? '/', 'http://local').searchParams.get('name') ?? undefined));
|
|
208
214
|
const sendFile = async (response, file) => {
|
|
@@ -217,7 +223,7 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
|
|
|
217
223
|
try { const notice = updates?.notice(); if (notice) response.setHeader('x-clavarium-update', notice); } catch { /* never in the way of an answer */ }
|
|
218
224
|
/* The version that answers, to the page's own questions: a page loaded before an update starts again (app.js). */
|
|
219
225
|
/* Not to a program at /api/ext/: what it may read, its key says (apikeys.mjs). */
|
|
220
|
-
if (platform?.version && ((pathname.startsWith('/api/') && !pathname.startsWith('/api/ext/')) || pathname.startsWith('/c/api/'))) response.setHeader('x-clavarium-version', platform.version);
|
|
226
|
+
if (platform?.version && ((pathname.startsWith('/api/') && !pathname.startsWith('/api/ext/')) || pathname.startsWith('/c/api/') || pathname.startsWith('/m/api/'))) response.setHeader('x-clavarium-version', platform.version);
|
|
221
227
|
/* The device door first, and apart: it never consults the gate. */
|
|
222
228
|
/* An address that wakes a tool, called from outside by what its owner
|
|
223
229
|
runs elsewhere: the address is the right. Nothing else is looked at,
|
|
@@ -269,6 +275,19 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
|
|
|
269
275
|
/* Before anything else, static files included: see gate.mjs. */
|
|
270
276
|
const who = gate(request.headers);
|
|
271
277
|
if (who === undefined) {
|
|
278
|
+
/* A MEMBER (people.mjs, #419): its own door, and nothing else of this server -- not a page, not an API,
|
|
279
|
+
not a file. A page it held from before (an administrator then) is told, and goes to its own. */
|
|
280
|
+
const member = memberGate(request.headers);
|
|
281
|
+
if (member !== undefined && door && personOf) {
|
|
282
|
+
if (await handleDoor(request, response, { ...door, person: personOf(member) })) return;
|
|
283
|
+
if (pathname === '/m/manifest.webmanifest' && request.method === 'GET') { sendManifest(response, request.url); return; }
|
|
284
|
+
if (pathname === '/m/' && (request.method === 'GET' || request.method === 'HEAD')) { response.writeHead(200, { ...HEADERS, 'content-type': 'text/html; charset=utf-8' }).end(memberPage()); return; }
|
|
285
|
+
const file = MEMBER_FILES[pathname];
|
|
286
|
+
if (file && (request.method === 'GET' || request.method === 'HEAD')) { await sendFile(response, file); return; }
|
|
287
|
+
if (pathname === '/' && request.method === 'GET') { response.writeHead(302, { ...HEADERS, location: '/m/' }).end(); return; }
|
|
288
|
+
response.writeHead(403, { ...HEADERS, 'x-clavarium-role': 'member', 'content-type': 'text/plain; charset=utf-8' }).end(REFUSED);
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
272
291
|
response.writeHead(403, { ...HEADERS, 'content-type': 'text/plain; charset=utf-8' }).end(REFUSED);
|
|
273
292
|
return;
|
|
274
293
|
}
|
|
@@ -331,7 +350,14 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
331
350
|
if (migrated.ran.length) console.log(`data: format ${migrated.from} -> ${migrated.to}`);
|
|
332
351
|
/* Who may sign in, kept up to date from the page (operators.mjs); none: this machine only. */
|
|
333
352
|
const team = operators.length ? new Operators({ host: runner(host), store: new Store(`${dataDir}/operators.json`), initial: operators }) : null;
|
|
334
|
-
|
|
353
|
+
/* WHO IS WHAT (people.mjs, #419): the gate of everything there was admits ADMINISTRATORS only -- pages, API,
|
|
354
|
+
terminals, the SSH console, all of it -- so a member is refused there by default; members come in through
|
|
355
|
+
their own door alone (/m/, memberGate). With no member, everybody who may sign in passes, as before. */
|
|
356
|
+
const people = team ? new People({ path: `${dataDir}/people.json`, accounts: () => team.list(), 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;
|
|
357
|
+
team?.useLastAdmin((email) => people.roleOf(email) === 'admin' && people.isLastAdmin(email));
|
|
358
|
+
if (team) team.people = people;
|
|
359
|
+
const gate = makeGate(team ? () => team.allowed().filter((e) => people.roleOf(e) === 'admin') : []);
|
|
360
|
+
const memberGate = team ? makeGate(() => team.allowed().filter((e) => people.roleOf(e) === 'member')) : () => undefined;
|
|
335
361
|
const originOk = makeOriginCheck(publicOrigin);
|
|
336
362
|
const instance = new Instance({ file: new JsonFile(`${dataDir}/instance.json`, {}), origin: publicOrigin, given: appName });
|
|
337
363
|
let repairTerminal = async () => { throw new Error('not ready'); };
|
|
@@ -352,6 +378,18 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
352
378
|
if (!all.jobs) all.jobs = jobs;
|
|
353
379
|
/* Who may do what with what: ONE table, shared by everything below. */
|
|
354
380
|
const grants = new Grants(new Store(`${dataDir}/grants.json`));
|
|
381
|
+
if (team) team.grants = grants;
|
|
382
|
+
/* A MEMBER, as the door sees it (door.mjs, #419): what the table gives `person:<email>`, conversations only. */
|
|
383
|
+
const personOf = team ? (email) => {
|
|
384
|
+
const subject = `person:${email}`;
|
|
385
|
+
const mine = () => grants.of(subject, 'conversation').map((g) => g.name).filter((n) => all.list().some((c) => c.name === n));
|
|
386
|
+
return {
|
|
387
|
+
email, key: subject,
|
|
388
|
+
grantsOf: () => grants.of(subject).filter((g) => g.type === 'conversation'),
|
|
389
|
+
rightsOn: (_key, name) => grants.rightsOf(subject, `conversation:${name}`),
|
|
390
|
+
conversationOf: (wanted) => { const m = mine(); if (wanted === undefined || wanted === '') return m[0]; return m.includes(wanted) ? wanted : undefined; },
|
|
391
|
+
};
|
|
392
|
+
} : null;
|
|
355
393
|
/* Folder-style boxes the owner drops assets into, to tidy the views and hand a whole box at once (groups.mjs). */
|
|
356
394
|
const groups = new Groups({ store: new Store(`${dataDir}/groups.json`) });
|
|
357
395
|
/* The providers and models OpenCode knows (models.dev), for a conversation set up from here (03-11). */
|
|
@@ -996,7 +1034,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
996
1034
|
answerer: answererConfig(env)?.models.length ?? 0, updates: updates.about(), team: team ? team.list().length : null,
|
|
997
1035
|
screen: await quick(screenNow(), 1500, null), catalogue: await quick(catalogue.providers().catch(() => []), 1500, []),
|
|
998
1036
|
}) });
|
|
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) });
|
|
1037
|
+
const { server, listening } = serve(port, all, folders, { gate, memberGate, personOf, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, machineList, features, desks: new Desks({ file: new JsonFile(`${dataDir}/desktops.json`, {}) }), apikeys, relayJoin: host.length ? new RelayJoin({ host: asHost }) : null, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
|
|
1000
1038
|
server.on('close', () => { closing = true; stopBinders(); stopTethers(); clearInterval(historyTimer); clearInterval(secretsTimer); clearInterval(trimTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopNetworkWatch(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(restartTimer); clearInterval(expiryTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); clearInterval(stopSigninHelp); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
|
|
1001
1039
|
let closing = false;
|
|
1002
1040
|
boxes.attach(server, WebSocketServer);
|
|
@@ -1033,7 +1071,11 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
1033
1071
|
gate, originOk,
|
|
1034
1072
|
/* Only a pairing given that conversation's terminal opens it. */
|
|
1035
1073
|
deviceName: (headers, pairing, wanted) => deviceTerminal(devices, headers, pairing, wanted),
|
|
1074
|
+
/* A member: a conversation whose terminal it was given, by name only (#419). */
|
|
1075
|
+
memberName: (headers, wanted) => { const m = memberGate(headers); if (m === undefined || !personOf) return undefined; const p = personOf(m); return p.conversationOf(wanted) === wanted && p.rightsOn(p.key, wanted).includes('x') ? wanted : undefined; },
|
|
1036
1076
|
});
|
|
1077
|
+
/* A role or a person's right changed: the terminals it held and lost go at once (#419). */
|
|
1078
|
+
people?.useChanged?.(() => bridge.recheck());
|
|
1037
1079
|
all.drop = (name) => bridge.drop(name);
|
|
1038
1080
|
/* What a device was given changes: a terminal it holds and lost goes at once. */
|
|
1039
1081
|
devices.changed = () => bridge.recheck();
|
package/server/operators.mjs
CHANGED
|
@@ -71,9 +71,13 @@ export class Operators {
|
|
|
71
71
|
await this.#do(['operator', 'password', e], `${password}\n`);
|
|
72
72
|
return { email: e, password };
|
|
73
73
|
}
|
|
74
|
-
|
|
74
|
+
/* The last administrator stays (people.mjs): `lastAdmin(email)` says whether it is that one. */
|
|
75
|
+
#lastAdmin = () => false;
|
|
76
|
+
useLastAdmin(fn) { this.#lastAdmin = fn; }
|
|
77
|
+
#keep(email) { if (this.#lastAdmin(email)) throw new Refusal(409, 'The last administrator cannot be disabled or removed.'); }
|
|
78
|
+
async disable(email) { this.#keep(this.#email(email)); await this.#do(['operator', 'disable', this.#email(email)]); this.#unlock(this.#email(email)); return this.list(); }
|
|
75
79
|
async enable(email) { await this.#do(['operator', 'enable', this.#email(email)]); this.#unlock(this.#email(email)); return this.list(); }
|
|
76
|
-
async remove(email) { await this.#do(['operator', 'remove', this.#email(email)]); this.#unlock(this.#email(email)); return this.list(); }
|
|
80
|
+
async remove(email) { this.#keep(this.#email(email)); await this.#do(['operator', 'remove', this.#email(email)]); this.#unlock(this.#email(email)); return this.list(); }
|
|
77
81
|
#unlock(email) { const locks = { ...(this.#store.get('locks') ?? {}) }; delete locks[email]; this.#store.put({ name: 'locks', ...locks }); }
|
|
78
82
|
|
|
79
83
|
/* At each turn: too many failed sign-ins lock an address for a while; a lock that is over is lifted. */
|
|
@@ -91,7 +95,7 @@ export class Operators {
|
|
|
91
95
|
if (Number(n) < FAILS_MAX || locks[email]) continue;
|
|
92
96
|
const one = this.#list.find((o) => o.email === email && o.enabled);
|
|
93
97
|
if (!one) continue;
|
|
94
|
-
if (this.allowed().length === 1) {
|
|
98
|
+
if (this.allowed().length === 1 || this.#lastAdmin(email)) {
|
|
95
99
|
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.'); }
|
|
96
100
|
continue;
|
|
97
101
|
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/* WHO IS AN ADMINISTRATOR, WHO A MEMBER (24-11, #419).
|
|
2
|
+
*
|
|
3
|
+
* Every account that may sign in (operators.mjs) is, by default, an ADMINISTRATOR: it may do everything, as
|
|
4
|
+
* every account did before this file existed -- an update changes nothing for the accounts already there. An
|
|
5
|
+
* administrator makes another account a MEMBER, who sees only the conversations given to it (grants.mjs,
|
|
6
|
+
* `person:<email>`), through its own door (/m/, door.mjs), and nothing else: the gate of everything else
|
|
7
|
+
* (gate.mjs, main.mjs) admits administrators only.
|
|
8
|
+
*
|
|
9
|
+
* Two rules on top, never broken:
|
|
10
|
+
* - ONE ACCOUNT, AN ADMINISTRATOR: when only one account exists (enabled or not: a member must never become
|
|
11
|
+
* the only one by having the others locked out), it is an administrator, whatever was written;
|
|
12
|
+
* - THE LAST ADMINISTRATOR stays one: it cannot be made a member (nor, in operators.mjs, disabled, removed or
|
|
13
|
+
* locked out after failed sign-ins).
|
|
14
|
+
*
|
|
15
|
+
* KEPT where nothing half-written is ever read: written to a new file renamed over the old one, the good one
|
|
16
|
+
* before it kept as `.bak`. Unreadable both: nobody is taken for an administrator but the one account alone,
|
|
17
|
+
* and it is said -- a damaged file never hands a member everything.
|
|
18
|
+
*/
|
|
19
|
+
import { readFileSync, writeFileSync, renameSync, existsSync, copyFileSync, mkdirSync } from 'node:fs';
|
|
20
|
+
import { dirname } from 'node:path';
|
|
21
|
+
import { Refusal } from './conversations.mjs';
|
|
22
|
+
|
|
23
|
+
export const ROLES = Object.freeze(['admin', 'member']);
|
|
24
|
+
|
|
25
|
+
export class People {
|
|
26
|
+
#path; #roles = {}; #damaged = false; #accounts; #tell; #changed = () => {};
|
|
27
|
+
/* Told when a role changes: the terminals of whoever lost something end at once (bridge.recheck). */
|
|
28
|
+
useChanged(fn) { this.#changed = fn; }
|
|
29
|
+
/* `accounts()`: every account there is, enabled or not ([{ email, enabled }], operators.mjs). */
|
|
30
|
+
constructor({ path, accounts = () => [], tell = () => {} }) {
|
|
31
|
+
this.#path = path; this.#accounts = accounts; this.#tell = tell;
|
|
32
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
33
|
+
this.#load();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
#read(file) {
|
|
37
|
+
const data = JSON.parse(readFileSync(file, 'utf8'));
|
|
38
|
+
if (!data || typeof data !== 'object' || !data.roles || typeof data.roles !== 'object') throw new Error('not a roles file');
|
|
39
|
+
return Object.fromEntries(Object.entries(data.roles).filter(([e, r]) => typeof e === 'string' && ROLES.includes(r)));
|
|
40
|
+
}
|
|
41
|
+
#load() {
|
|
42
|
+
if (!existsSync(this.#path) && !existsSync(`${this.#path}.bak`)) { this.#roles = {}; return; }
|
|
43
|
+
for (const file of [this.#path, `${this.#path}.bak`]) {
|
|
44
|
+
try { this.#roles = this.#read(file); this.#damaged = false; return; } catch { /* the next one */ }
|
|
45
|
+
}
|
|
46
|
+
this.#damaged = true; this.#roles = {};
|
|
47
|
+
this.#tell('The file of who is an administrator cannot be read', `${this.#path}: until it is repaired, only an account alone is an administrator.`);
|
|
48
|
+
}
|
|
49
|
+
#save() {
|
|
50
|
+
const tmp = `${this.#path}.new`;
|
|
51
|
+
writeFileSync(tmp, `${JSON.stringify({ roles: this.#roles }, null, 1)}\n`, { mode: 0o600 });
|
|
52
|
+
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 */ } }
|
|
53
|
+
renameSync(tmp, this.#path);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
#all() { return (this.#accounts() ?? []).map((a) => ({ email: String(a.email).toLowerCase(), enabled: a.enabled !== false })); }
|
|
57
|
+
|
|
58
|
+
/* 'admin' or 'member'. */
|
|
59
|
+
roleOf(email) {
|
|
60
|
+
const e = String(email ?? '').toLowerCase();
|
|
61
|
+
const all = this.#all();
|
|
62
|
+
if (all.length <= 1) return 'admin';
|
|
63
|
+
if (this.#damaged) return 'member';
|
|
64
|
+
return this.#roles[e] === 'member' ? 'member' : 'admin';
|
|
65
|
+
}
|
|
66
|
+
damaged() { return this.#damaged; }
|
|
67
|
+
/* The enabled administrators. */
|
|
68
|
+
admins() { return this.#all().filter((a) => a.enabled && this.roleOf(a.email) === 'admin').map((a) => a.email); }
|
|
69
|
+
/* Whether taking `email` out of the administrators (made a member, disabled, removed, locked out) leaves none. */
|
|
70
|
+
isLastAdmin(email) {
|
|
71
|
+
const e = String(email ?? '').toLowerCase();
|
|
72
|
+
const admins = this.admins();
|
|
73
|
+
return admins.length <= 1 && (admins.length === 0 || admins[0] === e);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
setRole(email, role) {
|
|
77
|
+
const e = String(email ?? '').toLowerCase();
|
|
78
|
+
if (!ROLES.includes(role)) throw new Refusal(400, 'A role is admin or member.');
|
|
79
|
+
if (!this.#all().some((a) => a.email === e)) throw new Refusal(404, 'No such account.');
|
|
80
|
+
if (this.#damaged) throw new Refusal(503, 'The file of who is an administrator cannot be read: repair it first.');
|
|
81
|
+
if (role === 'member' && this.roleOf(e) === 'admin' && this.isLastAdmin(e)) throw new Refusal(409, 'The last administrator cannot be made a member.');
|
|
82
|
+
if (role === 'admin') delete this.#roles[e]; else this.#roles[e] = 'member';
|
|
83
|
+
this.#save();
|
|
84
|
+
try { this.#changed(); } catch { /* the minute's recheck sees it */ }
|
|
85
|
+
return this.list();
|
|
86
|
+
}
|
|
87
|
+
/* An account added: its role, said at once (a removed account added again does not come back as it was). */
|
|
88
|
+
added(email, role) {
|
|
89
|
+
const e = String(email ?? '').toLowerCase();
|
|
90
|
+
if (!ROLES.includes(role)) return;
|
|
91
|
+
if (role === 'admin') delete this.#roles[e]; else this.#roles[e] = 'member';
|
|
92
|
+
if (!this.#damaged) this.#save();
|
|
93
|
+
}
|
|
94
|
+
/* An account removed: its role forgotten with it. */
|
|
95
|
+
removed(email) {
|
|
96
|
+
const e = String(email ?? '').toLowerCase();
|
|
97
|
+
if (!(e in this.#roles) || this.#damaged) return;
|
|
98
|
+
delete this.#roles[e]; this.#save();
|
|
99
|
+
}
|
|
100
|
+
/* Said to whoever waits on a change (a right taken: its terminal ends). */
|
|
101
|
+
changed() { try { this.#changed(); } catch { /* the minute's recheck sees it */ } }
|
|
102
|
+
/* The role a new account gets when none is said: a member (24-11, its owner's choice); an administrator is ticked. */
|
|
103
|
+
defaultRole() { return 'member'; }
|
|
104
|
+
list() { return this.#all().map((a) => ({ ...a, role: this.roleOf(a.email) })); }
|
|
105
|
+
}
|
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': 'Comptes', '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', 'set-member-1': '1 membre', 'set-members': '{n} membres',
|
|
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/web/app.js
CHANGED
|
@@ -18,12 +18,14 @@
|
|
|
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
|
-
|
|
21
|
+
/* A MEMBER (#419) has the page of a device: the same screens, what it was given only, at /m/ (member.js). */
|
|
22
|
+
const MEMBER = document.documentElement.dataset.door === 'member';
|
|
23
|
+
const DEVICE = document.documentElement.dataset.door === 'device' || MEMBER;
|
|
22
24
|
/* THE KIT (kit.js): the pieces every screen shares -- the state's point, the conversation's card... */
|
|
23
25
|
const KIT = window.clavariumKit;
|
|
24
26
|
/* On a paired device, every request names the pairing it speaks for:
|
|
25
27
|
the address is completed once the device has signed in. */
|
|
26
|
-
let API = DEVICE ? '/c/api' : '/api';
|
|
28
|
+
let API = MEMBER ? '/m/api' : DEVICE ? '/c/api' : '/api';
|
|
27
29
|
let pairing = '';
|
|
28
30
|
let deviceShared = [];
|
|
29
31
|
/* The parts of its conversation this device was given: its terminal, its
|
|
@@ -89,10 +91,12 @@
|
|
|
89
91
|
the page is leaving. */
|
|
90
92
|
let serverVersion = '';
|
|
91
93
|
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; }
|
|
92
96
|
const update = r.headers.get('x-clavarium-update') ?? '';
|
|
93
97
|
if (update || r.headers.get('x-clavarium-down')) {
|
|
94
98
|
const [kind, to] = update ? update.split(' ') : ['', ''];
|
|
95
|
-
location.replace(`${DEVICE ? '/c' : ''}/maintenance.html?${new URLSearchParams({ kind, ...(to ? { to } : {}), back: location.pathname + location.search })}`);
|
|
99
|
+
location.replace(`${MEMBER ? '/m' : DEVICE ? '/c' : ''}/maintenance.html?${new URLSearchParams({ kind, ...(to ? { to } : {}), back: location.pathname + location.search })}`);
|
|
96
100
|
return true;
|
|
97
101
|
}
|
|
98
102
|
const version = r.headers.get('x-clavarium-version') ?? '';
|
|
@@ -844,7 +848,7 @@
|
|
|
844
848
|
say('connecting', 'connecting');
|
|
845
849
|
fit.fit();
|
|
846
850
|
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
|
|
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' : ''}`;
|
|
851
|
+
const where = MEMBER ? `/m/terminal?c=${encodeURIComponent(name)}&cols=${terminal.cols}&rows=${terminal.rows}${resume ? '&resume=1' : ''}` : 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' : ''}`;
|
|
848
852
|
const mine = new WebSocket(`${scheme}://${location.host}${where}`);
|
|
849
853
|
socket = mine;
|
|
850
854
|
mine.binaryType = 'arraybuffer';
|
|
@@ -1326,7 +1330,7 @@
|
|
|
1326
1330
|
let appName = 'Clavarium';
|
|
1327
1331
|
let pageTitle = '';
|
|
1328
1332
|
const INSTALL_NAME = 'clavarium-install-name';
|
|
1329
|
-
const MANIFEST = DEVICE ? '/c/manifest.webmanifest' : '/manifest.webmanifest';
|
|
1333
|
+
const MANIFEST = MEMBER ? '/m/manifest.webmanifest' : DEVICE ? '/c/manifest.webmanifest' : '/manifest.webmanifest';
|
|
1330
1334
|
const manifestLink = document.querySelector('link[rel="manifest"]');
|
|
1331
1335
|
const installName = () => { try { return localStorage.getItem(INSTALL_NAME) ?? ''; } catch { return ''; } };
|
|
1332
1336
|
const pointManifest = (name) => { if (manifestLink) manifestLink.href = name ? `${MANIFEST}?name=${encodeURIComponent(name)}` : MANIFEST; };
|
|
@@ -8326,11 +8330,44 @@
|
|
|
8326
8330
|
$('access-devices-here').addEventListener('click', () => { void openAccessPage('map', { of: current }); });
|
|
8327
8331
|
|
|
8328
8332
|
/* ---------- Settings: this device, and the platform ---------- */
|
|
8333
|
+
/* What a member may use, conversation by conversation (#419): Chat to read, Chat, Chat and terminal, Terminal. */
|
|
8334
|
+
const GIVE_LEVELS = [['', 'Nothing'], ['r', 'Read the chat'], ['rw', 'Chat'], ['rwx', 'Chat and terminal'], ['x', 'Terminal']];
|
|
8335
|
+
function memberGiven(o) {
|
|
8336
|
+
const box = el('div', 'op-given');
|
|
8337
|
+
const given = new Map((o.given ?? []).map((g) => [g.name, g.rights]));
|
|
8338
|
+
const label = (n) => conversations.find((c) => c.name === n)?.chatName || n;
|
|
8339
|
+
const set = async (name, rights) => {
|
|
8340
|
+
$('operators-error').hidden = true;
|
|
8341
|
+
const body = { conversation: name, chat: rights.includes('w') ? 'write' : rights.includes('r') ? 'read' : null, terminal: rights.includes('x') };
|
|
8342
|
+
try { await post(`${API}/operators/${encodeURIComponent(o.email)}/${rights ? 'give' : 'take'}`, body); }
|
|
8343
|
+
catch (error) { $('operators-error').textContent = error.message; $('operators-error').hidden = false; }
|
|
8344
|
+
await paintOperators();
|
|
8345
|
+
};
|
|
8346
|
+
const level = (name, rights) => {
|
|
8347
|
+
const sel = el('select'); sel.setAttribute('aria-label', `What ${o.email} may use in ${label(name)}`);
|
|
8348
|
+
for (const [v, l] of GIVE_LEVELS) { const opt = el('option', '', l); opt.value = v; sel.append(opt); }
|
|
8349
|
+
sel.value = GIVE_LEVELS.some(([v]) => v === rights) ? rights : 'rw';
|
|
8350
|
+
sel.addEventListener('change', () => void set(name, sel.value));
|
|
8351
|
+
return sel;
|
|
8352
|
+
};
|
|
8353
|
+
if (given.size === 0) box.append(el('small', '', 'Given nothing yet.'));
|
|
8354
|
+
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); }
|
|
8355
|
+
const rest = conversations.filter((c) => !given.has(c.name));
|
|
8356
|
+
if (rest.length) {
|
|
8357
|
+
const add = el('select', 'op-give-add'); add.setAttribute('aria-label', `Give ${o.email} a conversation`);
|
|
8358
|
+
const first = el('option', '', 'Give a conversation...'); first.value = ''; add.append(first);
|
|
8359
|
+
for (const c of rest) { const opt = el('option', '', label(c.name)); opt.value = c.name; add.append(opt); }
|
|
8360
|
+
add.addEventListener('change', () => { if (add.value) void set(add.value, 'rw'); });
|
|
8361
|
+
box.append(add);
|
|
8362
|
+
}
|
|
8363
|
+
return box;
|
|
8364
|
+
}
|
|
8329
8365
|
/* ADMINISTRATORS: who may sign in (server/operators.mjs); a password is shown once, then never again. */
|
|
8330
8366
|
async function paintOperators() {
|
|
8331
8367
|
const got = await fetch(`${API}/operators`).then((r) => (r.ok ? r.json() : null)).catch(() => null);
|
|
8332
8368
|
$('settings-ch-operators').hidden = !got || got.local === true;
|
|
8333
8369
|
if (!got || got.local) return;
|
|
8370
|
+
if (got.defaultRole && !$('operators-role').dataset.touched) $('operators-role').value = got.defaultRole;
|
|
8334
8371
|
const rows = $('operators-rows'); rows.replaceChildren();
|
|
8335
8372
|
const act = async (path) => {
|
|
8336
8373
|
$('operators-error').hidden = true;
|
|
@@ -8339,16 +8376,31 @@
|
|
|
8339
8376
|
await paintOperators();
|
|
8340
8377
|
};
|
|
8341
8378
|
for (const o of got.operators) {
|
|
8342
|
-
const row = el('div', 'list-item folder'); row.dataset.email = o.email;
|
|
8379
|
+
const row = el('div', 'list-item folder'); row.dataset.email = o.email; row.dataset.role = o.role ?? 'admin';
|
|
8343
8380
|
const name = el('div', 'set-what'); name.append(el('b', '', o.email));
|
|
8344
8381
|
const word = o.locked ? `Locked until ${new Date(o.locked).toLocaleTimeString([], { timeStyle: 'short' })}` : o.enabled ? (o.email === got.me ? 'You' : '') : 'Disabled';
|
|
8345
8382
|
if (word) name.append(el('small', '', word));
|
|
8346
8383
|
const buttons = [['password', 'New password']];
|
|
8347
8384
|
if (o.email !== got.me) buttons.push(o.enabled ? ['disable', 'Disable'] : ['enable', 'Enable'], ['remove', 'Remove']);
|
|
8348
8385
|
const acts = el('div', 'set-control');
|
|
8386
|
+
/* ITS ROLE (#419): an administrator does everything; a member sees only what it is given. Never one's own. */
|
|
8387
|
+
if (o.email !== got.me) {
|
|
8388
|
+
const role = el('select', 'op-role'); role.setAttribute('aria-label', `Role of ${o.email}`);
|
|
8389
|
+
for (const [v, l] of [['admin', 'Administrator'], ['member', 'Member']]) { const opt = el('option', '', l); opt.value = v; role.append(opt); }
|
|
8390
|
+
role.value = o.role ?? 'admin';
|
|
8391
|
+
role.addEventListener('change', async () => {
|
|
8392
|
+
$('operators-error').hidden = true;
|
|
8393
|
+
try { await post(`${API}/operators/${encodeURIComponent(o.email)}/role`, { role: role.value }); }
|
|
8394
|
+
catch (error) { $('operators-error').textContent = error.message; $('operators-error').hidden = false; }
|
|
8395
|
+
await paintOperators();
|
|
8396
|
+
});
|
|
8397
|
+
acts.append(role);
|
|
8398
|
+
} else name.append(el('small', '', o.role === 'member' ? 'Member' : 'Administrator'));
|
|
8349
8399
|
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; }));
|
|
8350
8400
|
row.append(name, acts);
|
|
8351
8401
|
rows.append(row);
|
|
8402
|
+
/* WHAT A MEMBER WAS GIVEN (#419): each conversation, its chat and/or its terminal; one more added from a list. */
|
|
8403
|
+
if (o.role === 'member') rows.append(memberGiven(o));
|
|
8352
8404
|
}
|
|
8353
8405
|
}
|
|
8354
8406
|
/* API KEYS (server/apikeys.mjs): what a program or an AI elsewhere may read with a key. Made with no
|
|
@@ -8574,7 +8626,7 @@
|
|
|
8574
8626
|
$('operators-new').addEventListener('submit', async (event) => {
|
|
8575
8627
|
event.preventDefault();
|
|
8576
8628
|
$('operators-error').hidden = true;
|
|
8577
|
-
try { const r = await post(`${API}/operators`, { email: $('operators-email').value.trim() }); showPassword(r.email, r.password); $('operators-email').value = ''; }
|
|
8629
|
+
try { const r = await post(`${API}/operators`, { email: $('operators-email').value.trim(), role: $('operators-role').value }); showPassword(r.email, r.password); $('operators-email').value = ''; }
|
|
8578
8630
|
catch (error) { $('operators-error').textContent = error.message; $('operators-error').hidden = false; }
|
|
8579
8631
|
await paintOperators();
|
|
8580
8632
|
});
|
|
@@ -8770,8 +8822,11 @@
|
|
|
8770
8822
|
const shortcuts = [...document.querySelectorAll('#settings-shortcuts .list-item b')].map((b) => b.textContent);
|
|
8771
8823
|
chapterNow('s-shortcuts', shortcuts.length ? shortcuts.slice(0, 3).join(' · ') + (shortcuts.length > 3 ? ` +${shortcuts.length - 3}` : '') : uiSaid('set-none', 'None'));
|
|
8772
8824
|
if ($('binders-agent-lists').value !== '') chapterNow('s-binders', uiSaid('set-binders-max', 'Agents make up to {n}', { n: $('binders-agent-lists').value }));
|
|
8773
|
-
|
|
8774
|
-
|
|
8825
|
+
/* Accounts (#419): the administrators, and the members beside them. */
|
|
8826
|
+
const accountRows = [...$('operators-rows').querySelectorAll('[data-email]')];
|
|
8827
|
+
const members = accountRows.filter((r) => r.dataset.role === 'member').length;
|
|
8828
|
+
const admins = accountRows.length - members;
|
|
8829
|
+
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 })}` : ''}` : '');
|
|
8775
8830
|
chapterNow('s-backup', uiSaid('set-backup-now', 'Export · import'));
|
|
8776
8831
|
const shelf = $('shelf-state').textContent.split(' · ')[0];
|
|
8777
8832
|
const keys = $('git-hosts').children.length;
|
|
@@ -13821,7 +13876,7 @@
|
|
|
13821
13876
|
its own. One is shown at a time; the others are a tap away. */
|
|
13822
13877
|
function offerOthers(others) {
|
|
13823
13878
|
$('others').hidden = false;
|
|
13824
|
-
$('others').textContent = others.length > 0 ? `Conversations (${others.length + 1})` : 'This device';
|
|
13879
|
+
$('others').textContent = others.length > 0 ? `Conversations (${others.length + 1})` : MEMBER ? 'Conversations' : 'This device';
|
|
13825
13880
|
$('others').onclick = () => {
|
|
13826
13881
|
const rows = $('others-rows');
|
|
13827
13882
|
rows.replaceChildren();
|
|
@@ -13830,7 +13885,7 @@
|
|
|
13830
13885
|
const name = document.createElement('b'); name.textContent = isCurrent ? `${label} (shown now)` : label;
|
|
13831
13886
|
const open = document.createElement('button'); open.type = 'button'; open.className = 'primary'; open.textContent = 'Open'; open.hidden = isCurrent;
|
|
13832
13887
|
open.addEventListener('click', () => { void window.clavariumShowPairing(id, conversation); });
|
|
13833
|
-
const leave = document.createElement('button'); leave.type = 'button'; leave.textContent = 'Remove from this device';
|
|
13888
|
+
const leave = document.createElement('button'); leave.type = 'button'; leave.textContent = 'Remove from this device'; leave.hidden = MEMBER;
|
|
13834
13889
|
leave.addEventListener('click', () => {
|
|
13835
13890
|
leave.textContent = 'Yes, remove it'; leave.className = 'danger';
|
|
13836
13891
|
leave.onclick = async () => { await window.clavariumLeave(id); location.reload(); };
|
|
@@ -13862,7 +13917,7 @@
|
|
|
13862
13917
|
say(fresh ? 'pairing' : 'connecting', 'connecting');
|
|
13863
13918
|
const door = await window.clavariumDoor();
|
|
13864
13919
|
if (!door.ok) { shut(door.message); return; }
|
|
13865
|
-
pairing = door.pairing; API = `/c/api/${pairing}`; current = door.conversation ?? '';
|
|
13920
|
+
pairing = door.pairing; API = MEMBER ? '/m/api' : `/c/api/${pairing}`; current = door.conversation ?? '';
|
|
13866
13921
|
document.documentElement.dataset.pairing = pairing; /* not a secret: a name, useless without the key */
|
|
13867
13922
|
offerOthers(door.others);
|
|
13868
13923
|
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">Accounts</span><span class="chapter-about">Who may sign in, and what each sees.</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">Add an
|
|
1169
|
+
<form id="operators-new" class="set-row" autocomplete="off"><div class="set-what"><label for="operators-email">Add an account</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><select id="operators-role" aria-label="Role of the new account"><option value="member">Member</option><option value="admin">Administrator</option></select><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/member.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
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
|
+
})();
|
package/web/style.css
CHANGED
|
@@ -3455,3 +3455,9 @@ 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}
|