clavarium 0.2.536-next.1 → 0.2.538-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 +14 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/api.mjs +48 -6
- package/server/apikeys.mjs +2 -0
- package/server/bridge.mjs +16 -2
- package/server/conversations.mjs +40 -16
- package/server/dataformat.mjs +5 -1
- package/server/door.mjs +44 -16
- package/server/files.mjs +7 -4
- package/server/grants.mjs +6 -2
- package/server/main.mjs +59 -5
- package/server/operators.mjs +26 -3
- package/server/people.mjs +141 -0
- package/server/settingswords.mjs +2 -2
- package/server/sshconsole.mjs +16 -2
- package/server/vm.mjs +14 -3
- package/web/app.js +91 -18
- package/web/index.html +7 -3
- package/web/member.js +26 -0
- package/web/style.css +20 -14
package/deploy/updater.mjs
CHANGED
|
@@ -667,6 +667,15 @@ export class Updater {
|
|
|
667
667
|
const live = busy.filter((c) => !stale.includes(c));
|
|
668
668
|
return live.length ? `a machine is being built or restarted (${names(live)}): the update waits` : '';
|
|
669
669
|
}
|
|
670
|
+
/* MEMBERS AND AN OLDER RELEASE (#419). A release from before accounts and rights takes every account for an
|
|
671
|
+
administrator: once accounts and rights were used here (people.json written, at the first member), going back to
|
|
672
|
+
one is refused, by hand and by the watchdog -- as for a release that cannot read the data. Undefined: allowed. */
|
|
673
|
+
#membersBlock(to) {
|
|
674
|
+
/* A release that reads the lists of today (0.2.526-next.1 wrote another form: refused too). */
|
|
675
|
+
try { if (readFileSync(join(to.app, 'server', 'people.mjs'), 'utf8').includes('export const PEOPLE_LISTS')) return undefined; } catch { /* none: from before accounts */ }
|
|
676
|
+
const file = join(this.#o.data, 'people.json');
|
|
677
|
+
return existsSync(file) || existsSync(`${file}.bak`) ? `${to.version} does not know these members: it would not read who is an administrator` : undefined;
|
|
678
|
+
}
|
|
670
679
|
#dataFormat() { try { return JSON.parse(readFileSync(join(this.#o.data, 'data-format.json'), 'utf8')).format; } catch { return undefined; } }
|
|
671
680
|
|
|
672
681
|
/* Whether the lock is held by a process alive now -- of THIS start of the machine (25-11, on a test machine: frozen
|
|
@@ -722,6 +731,9 @@ export class Updater {
|
|
|
722
731
|
this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: error.message, ...(fetched ? { fetch: true } : {}), ...(typeof error.log === 'string' && error.log ? { log: error.log.slice(-LOG_MAX) } : {}) });
|
|
723
732
|
throw error;
|
|
724
733
|
}
|
|
734
|
+
/* Members here, and a release that would not read them (a newer number cut without them, say): not installed. */
|
|
735
|
+
const blocked = this.#membersBlock(release);
|
|
736
|
+
if (blocked) { rmSync(release.dir, { recursive: true, force: true }); this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: blocked }); throw new Refused(blocked); }
|
|
725
737
|
const before = this.#dataFormat();
|
|
726
738
|
let archive;
|
|
727
739
|
try {
|
|
@@ -763,6 +775,7 @@ export class Updater {
|
|
|
763
775
|
if (to.current) throw new Refused(`${id} is the release that runs`);
|
|
764
776
|
const format = this.#dataFormat();
|
|
765
777
|
if (format !== undefined && to.dataFormat < format) throw new Refused(`${to.version} cannot read the data of this version (format ${format}; it reads ${to.dataFormat})`);
|
|
778
|
+
const members = this.#membersBlock(to); if (members) throw new Refused(members);
|
|
766
779
|
const why = await this.busy(); if (why) throw new Refused(why);
|
|
767
780
|
const unlock = this.#lock();
|
|
768
781
|
try {
|
|
@@ -891,7 +904,7 @@ export class Updater {
|
|
|
891
904
|
const recent = failed && current && last && last.action === 'update' && last.result === 'done' && last.to === current.version && now - new Date(last.at) < WATCH_RECENT_MS;
|
|
892
905
|
const previous = recent ? this.releases().find((r) => !r.current && r.version === last.from) : undefined;
|
|
893
906
|
const format = this.#dataFormat();
|
|
894
|
-
if (previous && (format === undefined || previous.dataFormat >= format)) {
|
|
907
|
+
if (previous && (format === undefined || previous.dataFormat >= format) && !this.#membersBlock(previous)) {
|
|
895
908
|
let why = `${current.version} did not stay up (its service ${state === 'active' ? 'did not answer' : `was ${state}`}) nor came back after a restart (${failed}): back to ${previous.version}`;
|
|
896
909
|
this.#o.log(`watchdog: ${why}`);
|
|
897
910
|
this.#step('update', current.version, 'Going back');
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.538-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.538-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. */
|
|
@@ -591,6 +592,7 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
591
592
|
return send(403, { error: 'This request does not come from this site.' }), true;
|
|
592
593
|
}
|
|
593
594
|
const body = await readBody(request, pathname === '/api/setup/preview' || pathname === '/api/setup/import' ? SETUP_BODY_MAX : BODY_MAX);
|
|
595
|
+
if (request.stillAllowed && !request.stillAllowed()) throw new Refusal(403, 'Your account changed: sign in again.');
|
|
594
596
|
/* A SIGN-IN CODE (#405): answered before anything below can see this body (the journal, say). */
|
|
595
597
|
const codeOf = /^\/api\/conversations\/([^/]+)\/signin-code$/.exec(pathname);
|
|
596
598
|
if (codeOf && conversations.signinHelp) return send(200, await conversations.signinHelp.enterCode(decodeURIComponent(codeOf[1]), body?.code)), true;
|
|
@@ -791,13 +793,53 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
791
793
|
if (pathname === '/api/wifi/handover' && wifi) return send(202, await wifi.handover()), true;
|
|
792
794
|
if (pathname === '/api/meshcentral/enable' && meshcentral) return send(202, await meshcentral.enable()), true;
|
|
793
795
|
if (pathname === '/api/meshcentral/disable' && meshcentral) return send(200, await meshcentral.disable()), true;
|
|
794
|
-
if (pathname === '/api/operators' && team)
|
|
796
|
+
if (pathname === '/api/operators' && team) {
|
|
797
|
+
/* Its role said at once (#419): an account removed and added again does not come back as it was. */
|
|
798
|
+
const role = body.role === 'member' ? 'member' : body.role === 'admin' ? 'admin' : (team.people?.defaultRole?.() ?? 'admin');
|
|
799
|
+
const adding = String(body.email ?? '').trim().toLowerCase();
|
|
800
|
+
/* An account there already keeps its role: changed by its own way, with its checks (audit 6, 24-11). */
|
|
801
|
+
if (team.list().some((o) => o.email === adding)) throw new Refusal(409, 'This account exists already.');
|
|
802
|
+
/* Nothing of a past account of that address comes back with the new one. */
|
|
803
|
+
team.grants?.forgetSubject(`person:${adding}`);
|
|
804
|
+
const undo = team.people?.adding(adding, role);
|
|
805
|
+
let made;
|
|
806
|
+
try { made = await team.add(body.email); } catch (error) { undo?.(); throw error; }
|
|
807
|
+
return send(201, { ...made, role: team.people?.roleOf(made.email) ?? 'admin' }), true;
|
|
808
|
+
}
|
|
809
|
+
/* An account made an administrator or a member (#419): never oneself, never the last administrator. */
|
|
810
|
+
const roleOf = /^\/api\/operators\/([^/]{3,200})\/role$/.exec(pathname);
|
|
811
|
+
if (roleOf && team?.people) {
|
|
812
|
+
const email = decodeURIComponent(roleOf[1]).trim().toLowerCase();
|
|
813
|
+
if (email === identity) throw new Refusal(409, 'You cannot change your own role: ask another administrator.');
|
|
814
|
+
const changed = team.people.setRole(email, String(body.role ?? ''));
|
|
815
|
+
/* Made an administrator: what it was given as a member is forgotten, not given back if it is a member again (audit 13). */
|
|
816
|
+
if (team.people.roleOf(email) === 'admin') team.grants?.forgetSubject(`person:${email}`);
|
|
817
|
+
return send(200, { operators: changed }), true;
|
|
818
|
+
}
|
|
819
|
+
/* A conversation given to a member, or taken back: its chat (read or write) and/or its terminal (#419). */
|
|
820
|
+
const giving = /^\/api\/operators\/([^/]{3,200})\/(give|take)$/.exec(pathname);
|
|
821
|
+
if (giving && team?.people && team.grants) {
|
|
822
|
+
const email = decodeURIComponent(giving[1]).trim().toLowerCase();
|
|
823
|
+
if (!team.list().some((o) => o.email === email)) throw new Refusal(404, 'No such account.');
|
|
824
|
+
if (team.people.roleOf(email) !== 'member') throw new Refusal(409, 'Only a member is given conversations: an administrator has them all.');
|
|
825
|
+
const name = String(body.conversation ?? '');
|
|
826
|
+
if (!conversations.list().some((c) => c.name === name)) throw new Refusal(404, 'No such conversation.');
|
|
827
|
+
const rights = giving[2] === 'take' ? '' : `${body.chat === 'write' ? 'rw' : body.chat === 'read' ? 'r' : ''}${body.terminal === true ? 'x' : ''}`;
|
|
828
|
+
if (rights === '') team.grants.take(`person:${email}`, `conversation:${name}`);
|
|
829
|
+
else team.grants.give(`person:${email}`, `conversation:${name}`, rights);
|
|
830
|
+
team.people.changed?.();
|
|
831
|
+
return send(200, { given: team.grants.of(`person:${email}`, 'conversation').map((g) => ({ name: g.name, rights: g.rights })) }), true;
|
|
832
|
+
}
|
|
795
833
|
const op = /^\/api\/operators\/([^/]{3,200})\/(password|disable|enable|remove)$/.exec(pathname);
|
|
796
834
|
if (op && team) {
|
|
797
|
-
const email = decodeURIComponent(op[1]);
|
|
835
|
+
const email = decodeURIComponent(op[1]).trim().toLowerCase();
|
|
798
836
|
/* Not oneself out: another operator does it, or nobody would see it was a mistake. */
|
|
799
837
|
if (op[2] !== 'password' && op[2] !== 'enable' && email.toLowerCase() === identity) throw new Refusal(409, 'You cannot do that to your own account: ask another operator.');
|
|
800
|
-
|
|
838
|
+
const done = op[2] === 'password' ? await team.password(email) : { operators: await team[op[2]](email) };
|
|
839
|
+
/* Removed: its role and what it was given go with it (#419). */
|
|
840
|
+
if (op[2] === 'remove') { team.people?.removed(email); team.grants?.forgetSubject(`person:${email.toLowerCase()}`); }
|
|
841
|
+
team.people?.changed?.();
|
|
842
|
+
return send(200, done), true;
|
|
801
843
|
}
|
|
802
844
|
const renaming = /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/rename$/.exec(pathname);
|
|
803
845
|
/* Its machines that run get the new name or value now, as a secret given to them does. */
|
|
@@ -1034,8 +1076,8 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
1034
1076
|
if (typeof body?.escalate === 'boolean') return send(200, conversations.setStopEscalate(conversation, body.escalate)), true;
|
|
1035
1077
|
/* Its watchdog (watchdog.mjs): on or off, and how long it waits. */
|
|
1036
1078
|
if (body?.watchdog && typeof body.watchdog === 'object') return send(200, conversations.setWatchdog(conversation, { on: typeof body.watchdog.on === 'boolean' ? body.watchdog.on : undefined, delayMin: body.watchdog.delayMin })), true;
|
|
1037
|
-
/* Its shared machine's own memory (#221): the whole machine restarted, every conversation in it. */
|
|
1038
|
-
if (body?.machineMb !== undefined) return send(200, await conversations.resizeShared(conversation, { machineMb: body.machineMb })), true;
|
|
1079
|
+
/* Its shared machine's own memory, cores and disk (#221; 28-11): the whole machine restarted, every conversation in it. */
|
|
1080
|
+
if (body?.machineMb !== undefined || body?.machineDiskGb !== undefined || body?.machineCpus !== undefined) return send(200, await conversations.resizeShared(conversation, { machineMb: body.machineMb, diskGb: body.machineDiskGb, cpus: body.machineCpus })), true;
|
|
1039
1081
|
const resized = await conversations.resize(conversation, { memoryMb: body.memoryMb, diskGb: body.diskGb, cpus: body.cpus });
|
|
1040
1082
|
/* Asleep, nothing was started: the choice is only kept, for its wake. */
|
|
1041
1083
|
return send(resized.phase === 'restarting' ? 202 : 200, resized), true;
|
package/server/apikeys.mjs
CHANGED
|
@@ -1320,6 +1320,8 @@ export async function handleApiKeys(request, response, keys, originOk, headers =
|
|
|
1320
1320
|
for await (const piece of request) { text += piece; if (text.length > 16_384) return send(413, { error: 'Too long.' }); }
|
|
1321
1321
|
let body;
|
|
1322
1322
|
try { body = text ? JSON.parse(text) : {}; } catch { return send(400, { error: 'The request is not JSON.' }); }
|
|
1323
|
+
/* One made a member or disabled while its request came makes no key (audit 8). */
|
|
1324
|
+
if (request.stillAllowed && !request.stillAllowed()) return send(403, { error: 'Your account changed: sign in again.' });
|
|
1323
1325
|
if (!body || typeof body !== 'object') body = {};
|
|
1324
1326
|
if (pathname === '/api/apikeys') {
|
|
1325
1327
|
const made = keys.create({ label: body.label, scopes: body.scopes ?? [], conversations: body.conversations ?? {}, rooms: body.rooms ?? {}, boxes: body.boxes ?? {}, binders: body.binders ?? {}, days: body.days === undefined ? DEFAULT_DAYS : body.days }, who);
|
package/server/bridge.mjs
CHANGED
|
@@ -90,7 +90,9 @@ export const sameOrigin = makeOriginCheck();
|
|
|
90
90
|
const BY_ITSELF = /\x1b\[[IO]|\x1b\[\??[>=]?[\d;]*c|\x1b\[\d+;\d+R|\x1b\][\d;]*(?:rgb:[0-9a-fA-F/]+)?(?:\x07|\x1b\\)|\x1bP[^\x1b]*\x1b\\/g;
|
|
91
91
|
export const byHand = (typed) => String(typed ?? '').replace(BY_ITSELF, '').length > 0;
|
|
92
92
|
|
|
93
|
-
export
|
|
93
|
+
export const MEMBER_PATH = '/m/terminal';
|
|
94
|
+
|
|
95
|
+
export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () => {}, originOk = sameOrigin, gate = () => 'local', deviceName = () => undefined, memberName = () => undefined, onRejoin = () => {}, onTyped = () => {}, asleep = () => false }) {
|
|
94
96
|
const sockets = new WebSocketServer({ noServer: true });
|
|
95
97
|
const seats = new Seats();
|
|
96
98
|
/* THE DEVICES AT A TERMINAL, each with what lets it stay: asked again when the owner changes
|
|
@@ -98,6 +100,8 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
98
100
|
back used to end only at the next connection -- an open terminal went on (found 19-10). */
|
|
99
101
|
const deviceSeats = new Map(); /* viewer -> () => still allowed */
|
|
100
102
|
const revoked = new WeakSet();
|
|
103
|
+
/* Who a screen is, for What happened: a paired device, a member (#419), else the page of an administrator. */
|
|
104
|
+
const fromDevice = new WeakSet(); const fromMember = new WeakSet();
|
|
101
105
|
const allowed = (viewer) => {
|
|
102
106
|
if (revoked.has(viewer)) return false;
|
|
103
107
|
const still = deviceSeats.get(viewer);
|
|
@@ -120,9 +124,18 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
120
124
|
name = ask();
|
|
121
125
|
if (!isConversationName(name) || !originOk(request.headers)) { socket.destroy(); return; }
|
|
122
126
|
still = () => ask() === name;
|
|
127
|
+
} else if (url.pathname === MEMBER_PATH) {
|
|
128
|
+
/* A member (people.mjs, #419): the sign-in names it; the terminal of a conversation it was given, only. */
|
|
129
|
+
const wanted = url.searchParams.get('c') ?? '';
|
|
130
|
+
const ask = () => memberName(request.headers, wanted) ?? '';
|
|
131
|
+
name = ask();
|
|
132
|
+
if (!isConversationName(name) || !originOk(request.headers)) { socket.destroy(); return; }
|
|
133
|
+
still = () => ask() === name;
|
|
123
134
|
} else if (url.pathname === PATH) {
|
|
124
135
|
name = url.searchParams.get('c') ?? '';
|
|
125
136
|
if (!isConversationName(name) || !originOk(request.headers) || gate(request.headers) === undefined) { socket.destroy(); return; }
|
|
137
|
+
/* An administrator made a member, or an account disabled: its open terminals end too (#419). */
|
|
138
|
+
still = () => gate(request.headers) !== undefined;
|
|
126
139
|
} else return;
|
|
127
140
|
const cols = Number(url.searchParams.get('cols'));
|
|
128
141
|
const rows = Number(url.searchParams.get('rows'));
|
|
@@ -130,6 +143,7 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
130
143
|
const resume = url.searchParams.get('resume') === '1';
|
|
131
144
|
sockets.handleUpgrade(request, socket, head, (viewer) => {
|
|
132
145
|
if (still) { deviceSeats.set(viewer, still); viewer.on('close', () => deviceSeats.delete(viewer)); }
|
|
146
|
+
if (url.pathname === DEVICE_PATH) fromDevice.add(viewer); else if (url.pathname === MEMBER_PATH) fromMember.add(viewer);
|
|
133
147
|
seat(viewer, name, within(cols, COLS) ? cols : 80, within(rows, ROWS) ? rows : 24, resume);
|
|
134
148
|
});
|
|
135
149
|
});
|
|
@@ -186,7 +200,7 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
186
200
|
}
|
|
187
201
|
async function openNow(name, cols, rows, sink, say) {
|
|
188
202
|
/* Who opens it, for What happened when it wakes a sleeper: a screen, or this server (warm). */
|
|
189
|
-
const who = sink ? (
|
|
203
|
+
const who = sink ? (fromDevice.has(sink) ? 'a paired device' : fromMember.has(sink) ? 'a member' : 'a page') : undefined;
|
|
190
204
|
const terminal = await spawn(name, cols, rows, say, who);
|
|
191
205
|
/* While it was being opened another one may have been: the newest wins. */
|
|
192
206
|
if (live.has(name)) close(name);
|
package/server/conversations.mjs
CHANGED
|
@@ -188,7 +188,7 @@ export class Conversations {
|
|
|
188
188
|
if (c.phase === 'moving') store.patch(c.name, { phase: 'ready', step: undefined, moved: 'The server restarted while the work folder was being moved. The files are safe, in the machine: look at /work, /work.before-move and /work.moving.' });
|
|
189
189
|
/* A move into a shared machine cut short (14-11): back in its own machine, as it was -- never « build it
|
|
190
190
|
again », which would make its own machine anew and lose its tool's memory. */
|
|
191
|
-
if (c.phase === 'building' && c.movingTo) store.patch(c.name, { phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, sharedMachine: undefined, machineMb: undefined, machineUser: undefined, ...(c.movingFromMb ? { memoryMb: c.movingFromMb } : {}), movingTo: undefined, movingFromMb: undefined, stopped: true, moved: `The server restarted while it was moving to the shared machine ${c.movingTo}: it stays in its own machine, as it was. Move it again when you like.` });
|
|
191
|
+
if (c.phase === 'building' && c.movingTo) store.patch(c.name, { phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, sharedMachine: undefined, machineMb: undefined, machineDiskGb: undefined, machineCpus: undefined, machineUser: undefined, ...(c.movingFromMb ? { memoryMb: c.movingFromMb } : {}), movingTo: undefined, movingFromMb: undefined, stopped: true, moved: `The server restarted while it was moving to the shared machine ${c.movingTo}: it stays in its own machine, as it was. Move it again when you like.` });
|
|
192
192
|
else if (c.phase === 'building' && c.movingOutOf) store.patch(c.name, { phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, ...c.movingOutOf, movingOutOf: undefined, stopped: true, moved: `The server restarted while it was moving out of the shared machine ${c.movingOutOf.sharedMachine}: it stays there. Move it again when you like.` });
|
|
193
193
|
else if (c.phase === 'building') store.patch(c.name, { phase: 'failed', error: 'The server restarted while this conversation was being built. Build it again, or archive it.' });
|
|
194
194
|
/* A change of AI cut short before its switch: it kept its AI (the record changes in one write). */
|
|
@@ -338,6 +338,11 @@ export class Conversations {
|
|
|
338
338
|
|
|
339
339
|
/* The size of a shared machine: what its first conversation made it with (each of its conversations carries
|
|
340
340
|
it); undefined while none lives in it. */
|
|
341
|
+
/* Its disk and cores as the others in that machine know them (28-11), or nothing: the defaults it was made with. */
|
|
342
|
+
#machineSizesOf(machine) {
|
|
343
|
+
const peer = this.#store.all().find((x) => x.sharedMachine === machine && (Number.isInteger(x.machineDiskGb) || Number.isInteger(x.machineCpus)));
|
|
344
|
+
return peer ? { machineDiskGb: peer.machineDiskGb, machineCpus: peer.machineCpus } : {};
|
|
345
|
+
}
|
|
341
346
|
#machineMbOf(machine) {
|
|
342
347
|
const there = this.#store.all().filter((x) => x.sharedMachine === machine);
|
|
343
348
|
if (!there.length) return undefined;
|
|
@@ -374,7 +379,7 @@ export class Conversations {
|
|
|
374
379
|
}
|
|
375
380
|
if (this.#store.get(name)) throw new Refusal(409, 'A conversation already has this name.');
|
|
376
381
|
const now = new Date().toISOString();
|
|
377
|
-
const conversation = { name, ...(title ? { title } : {}), ...(group ? { group } : {}), tool, memoryMb: memory, cpus: cores, diskGb: disk, fixed: FIXES, ...(machine ? { sharedMachine: machine, machineMb: size } : {}), work: workOnDisk === true && !machine ? 'disk' : 'kept', phase: 'building', step: 'Starting the machine', createdAt: now, buildingSince: now, progress: buildProgress(now) };
|
|
382
|
+
const conversation = { name, ...(title ? { title } : {}), ...(group ? { group } : {}), tool, memoryMb: memory, cpus: cores, diskGb: disk, fixed: FIXES, ...(machine ? { sharedMachine: machine, machineMb: size, ...this.#machineSizesOf(machine) } : {}), work: workOnDisk === true && !machine ? 'disk' : 'kept', phase: 'building', step: 'Starting the machine', createdAt: now, buildingSince: now, progress: buildProgress(now) };
|
|
378
383
|
/* A new one comes first in its folder (or first of those in none). */
|
|
379
384
|
const { order, groups } = this.#order();
|
|
380
385
|
this.#store.put(conversation);
|
|
@@ -1496,7 +1501,7 @@ export class Conversations {
|
|
|
1496
1501
|
const carried = join(dir, 'state.tar.gz');
|
|
1497
1502
|
const back = (why) => {
|
|
1498
1503
|
/* Back to its own machine, as it was (stopped: the next opening wakes it). */
|
|
1499
|
-
this.#store.patch(name, { toolsStarted: c.toolsStarted, sharedMachine: undefined, machineMb: undefined, machineUser: undefined, memoryMb: c.memoryMb, phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, error: undefined, movingTo: undefined, movingFromMb: undefined, moveFailed: `Not moved: ${why}` });
|
|
1504
|
+
this.#store.patch(name, { toolsStarted: c.toolsStarted, sharedMachine: undefined, machineMb: undefined, machineDiskGb: undefined, machineCpus: undefined, machineUser: undefined, memoryMb: c.memoryMb, phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, error: undefined, movingTo: undefined, movingFromMb: undefined, moveFailed: `Not moved: ${why}` });
|
|
1500
1505
|
this.#fresh.add(name); this.#mountAgain.add(name);
|
|
1501
1506
|
try { this.renewed(name, `Not moved to the shared machine ${machine}: ${why} It stays in its own machine, as it was.`, false); } catch { /* told, nothing more */ }
|
|
1502
1507
|
};
|
|
@@ -1512,7 +1517,8 @@ export class Conversations {
|
|
|
1512
1517
|
const stopped = await this.#vms.stop(name);
|
|
1513
1518
|
if (stopped.code !== 0) return back(`its machine did not stop: ${firstLine(stopped.stderr) || `exit ${stopped.code}`}.`);
|
|
1514
1519
|
}
|
|
1515
|
-
|
|
1520
|
+
/* Its disk and cores are the machine's: those the others there know of (28-11). */
|
|
1521
|
+
this.#store.patch(name, { sharedMachine: machine, machineMb: size, memoryMb: memory, ...this.#machineSizesOf(machine) });
|
|
1516
1522
|
await this.#buildShared(name, tool, memory);
|
|
1517
1523
|
const now = this.#store.get(name);
|
|
1518
1524
|
if (!now) return undefined; /* archived meanwhile */
|
|
@@ -1602,7 +1608,7 @@ export class Conversations {
|
|
|
1602
1608
|
left = true;
|
|
1603
1609
|
}
|
|
1604
1610
|
/* Its own machine, as a new conversation's: built with its name, held before its tool starts. */
|
|
1605
|
-
this.#store.patch(name, { sharedMachine: undefined, machineMb: undefined, machineUser: undefined, memoryMb: memory, step: 'Starting the machine' });
|
|
1611
|
+
this.#store.patch(name, { sharedMachine: undefined, machineMb: undefined, machineDiskGb: undefined, machineCpus: undefined, machineUser: undefined, memoryMb: memory, step: 'Starting the machine' });
|
|
1606
1612
|
/* One left behind by an attempt cut short: not this conversation's any more. */
|
|
1607
1613
|
if ((await this.#vms.state(name, { fresh: true }).catch(() => undefined)) !== undefined) await this.#vms.removeVm(vmName(name)).catch(() => {});
|
|
1608
1614
|
this.#holding.add(name);
|
|
@@ -2472,30 +2478,48 @@ export class Conversations {
|
|
|
2472
2478
|
return this.#store.get(name);
|
|
2473
2479
|
}
|
|
2474
2480
|
|
|
2475
|
-
/* A SHARED MACHINE
|
|
2476
|
-
the largest limit of those in it
|
|
2477
|
-
interrupted, the page says so before. Each then finds
|
|
2478
|
-
|
|
2481
|
+
/* A SHARED MACHINE RESIZED (#221; disk and cores 28-11), from the settings of any conversation in it: its memory
|
|
2482
|
+
never less than the largest limit of those in it, its disk only grows, its cores up to the server's; stopped
|
|
2483
|
+
cleanly, set, started again -- every conversation in it is interrupted, the page says so before. Each then finds
|
|
2484
|
+
its place again (its work mounted) at its next opening. What is not given stays as it is. */
|
|
2485
|
+
async resizeShared(name, { machineMb, diskGb, cpus } = {}) {
|
|
2479
2486
|
const c = this.#busyCheck(name);
|
|
2480
2487
|
if (!c.sharedMachine) throw new Refusal(400, 'Not in a shared machine.');
|
|
2481
2488
|
const all = this.#store.all().filter((x) => x.sharedMachine === c.sharedMachine);
|
|
2489
|
+
const given = (v) => v !== undefined && v !== null && v !== '';
|
|
2482
2490
|
const now = this.#machineMbOf(c.sharedMachine);
|
|
2483
|
-
const
|
|
2491
|
+
const real = await this.#vms.size(name).catch(() => ({}));
|
|
2492
|
+
const diskNow = real?.diskGb ?? all.map((x) => x.machineDiskGb).find(Number.isInteger) ?? DISK_GB;
|
|
2493
|
+
const cpusNow = real?.cpus ?? all.map((x) => x.machineCpus).find(Number.isInteger) ?? 1;
|
|
2494
|
+
const size = given(machineMb) ? Number(machineMb) : now;
|
|
2495
|
+
const disk = given(diskGb) ? Number(diskGb) : diskNow;
|
|
2496
|
+
const cores = given(cpus) ? Number(cpus) : cpusNow;
|
|
2484
2497
|
const largest = Math.max(...all.map((x) => Number(x.memoryMb) || 0));
|
|
2485
|
-
if (!Number.isInteger(size) || size < Math.max(1024, largest) || size > 16384) throw new Refusal(400, `The machine ${c.sharedMachine} has ${Math.max(1024, largest)} to 16384 MB (no less than the largest of
|
|
2486
|
-
if (
|
|
2498
|
+
if (size !== now && (!Number.isInteger(size) || size < Math.max(1024, largest) || size > 16384)) throw new Refusal(400, `The machine ${c.sharedMachine} has ${Math.max(1024, largest)} to 16384 MB (no less than the largest limit of the conversations in it).`);
|
|
2499
|
+
if (!Number.isInteger(disk) || disk > DISK_MAX_GB) throw new Refusal(400, `A disk is at most ${DISK_MAX_GB} GB.`);
|
|
2500
|
+
if (disk < diskNow) throw new Refusal(400, `A disk can only grow: it has ${diskNow} GB.`);
|
|
2501
|
+
const hostCpus = availableParallelism();
|
|
2502
|
+
if (cores !== cpusNow && (!Number.isInteger(cores) || cores < 1 || cores > hostCpus)) throw new Refusal(400, `Cores: 1 to ${hostCpus}, those of this server, which its machines share.`);
|
|
2503
|
+
if (size === now && disk === diskNow && cores === cpusNow) throw new Refusal(409, 'Nothing to change: it already has this.');
|
|
2487
2504
|
for (const x of all) if (this.#acts.has(x.name)) throw this.#busy(x.name);
|
|
2488
2505
|
const state = await this.#vms.state(name, { fresh: true }).catch(() => undefined);
|
|
2489
2506
|
if (state === undefined) throw new Refusal(410, 'The shared machine no longer exists.');
|
|
2490
|
-
await this.room({ kind: 'grow', name, memoryMb: state === 'Running' ? Math.max(0, size - now) : 0, diskMb: 0 });
|
|
2507
|
+
await this.room({ kind: 'grow', name, memoryMb: state === 'Running' ? Math.max(0, size - now) : 0, diskMb: Math.max(0, disk - diskNow) * 1024 });
|
|
2491
2508
|
for (const x of all) { this.#cancelStop(x.name); this.drop(x.name); }
|
|
2492
2509
|
const fail = (what, r) => new Refusal(502, `${what}: ${firstLine(r.stderr) || firstLine(r.stdout) || `exit ${r.code}`}`);
|
|
2493
2510
|
if (state !== 'Stopped') { const r = await this.#vms.stop(name); if (r.code !== 0) throw fail('The shared machine did not stop', r); }
|
|
2494
|
-
const
|
|
2495
|
-
|
|
2511
|
+
const steps = [[size !== now, () => this.#vms.setMemory(name, size), 'Its memory could not be set'],
|
|
2512
|
+
[cores !== cpusNow, () => this.#vms.setCpus(name, cores), 'Its cores could not be set'],
|
|
2513
|
+
[disk !== diskNow, () => this.#vms.setDisk(name, disk), 'Its disk could not be grown']];
|
|
2514
|
+
for (const [wanted, run, what] of steps) {
|
|
2515
|
+
if (!wanted) continue;
|
|
2516
|
+
const r = await run();
|
|
2517
|
+
if (r.code !== 0) { await this.#vms.start(name).catch(() => undefined); throw fail(what, r); }
|
|
2518
|
+
}
|
|
2496
2519
|
const started = await this.#vms.start(name);
|
|
2520
|
+
const said = [size !== now ? `${size} MB` : '', cores !== cpusNow ? `${cores} core${cores > 1 ? 's' : ''}` : '', disk !== diskNow ? `a ${disk} GB disk` : ''].filter(Boolean).join(', ');
|
|
2497
2521
|
for (const x of all) {
|
|
2498
|
-
this.#store.patch(x.name, { machineMb: size, toolStarted: false, restarted: `Its shared machine was restarted with ${
|
|
2522
|
+
this.#store.patch(x.name, { machineMb: size, machineDiskGb: disk, machineCpus: cores, toolStarted: false, restarted: `Its shared machine was restarted with ${said}.` });
|
|
2499
2523
|
this.#mountAgain.add(x.name); this.#fresh.add(x.name);
|
|
2500
2524
|
}
|
|
2501
2525
|
if (started.code !== 0) throw fail('The shared machine did not start again', started);
|
package/server/dataformat.mjs
CHANGED
|
@@ -22,8 +22,11 @@ import { join } from 'node:path';
|
|
|
22
22
|
export const DATA_FORMAT = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).clavarium?.dataFormat ?? 1;
|
|
23
23
|
export const FORMAT_FILE = 'data-format.json';
|
|
24
24
|
|
|
25
|
-
/*
|
|
25
|
+
/* No migration yet. FORMAT 2 IS NOT TO BE USED: 0.2.527-next.1 wrote it for a day (accounts and rights, #419) with
|
|
26
|
+
nothing changed in the files, which blocked going back; it is read as 1 and written back as 1. The next real
|
|
27
|
+
change of format is 3. (Going back to a release from before accounts once members exist: refused, deploy/updater.mjs.) */
|
|
26
28
|
export const MIGRATIONS = {};
|
|
29
|
+
const SAME_AS_1 = 2;
|
|
27
30
|
|
|
28
31
|
export function dataFormat(dataDir) {
|
|
29
32
|
try { return JSON.parse(readFileSync(join(dataDir, FORMAT_FILE), 'utf8')).format; } catch { return undefined; }
|
|
@@ -37,6 +40,7 @@ export function migrateData(dataDir, { format = DATA_FORMAT, migrations = MIGRAT
|
|
|
37
40
|
try { existing = readdirSync(dataDir).some((f) => f.endsWith('.json')); } catch { /* a new directory */ }
|
|
38
41
|
found = existing ? 1 : format;
|
|
39
42
|
}
|
|
43
|
+
if (found === SAME_AS_1 && format === 1) { write(dataDir, 1); found = 1; }
|
|
40
44
|
if (!Number.isInteger(found) || found < 1) throw new Error(`${join(dataDir, FORMAT_FILE)} does not hold a format number`);
|
|
41
45
|
if (found > format) throw new Error(`The data in ${dataDir} is in format ${found}, written by a newer Clavarium; this one reads format ${format} at most. Go back to the newer version (Settings, Updates; or deploy/updater.mjs), or restore the backup made before the update.`);
|
|
42
46
|
const ran = [];
|
package/server/door.mjs
CHANGED
|
@@ -87,13 +87,18 @@ export function devicePairing(devices, headers, pairing) {
|
|
|
87
87
|
}
|
|
88
88
|
|
|
89
89
|
/* Returns true when the request was under /c/api/ (answered here). */
|
|
90
|
-
export async function handleDoor(request, response, { devices, conversations, resources, shortcuts, voice, originOk, headers, secure, talk, repair, tethers, mailboxes, signinCode }) {
|
|
90
|
+
export async function handleDoor(request, response, { devices, conversations, resources, shortcuts, voice, originOk, headers, secure, talk, repair, tethers, mailboxes, signinCode, person }) {
|
|
91
91
|
const url = new URL(request.url ?? '/', 'http://local');
|
|
92
|
-
|
|
92
|
+
/* A MEMBER (people.mjs, #419) comes through the same door, at /m/api/, as the person the sign-in names: no
|
|
93
|
+
pairing, no code, no key, no session of its own -- who it is comes from the gate alone, never from the address.
|
|
94
|
+
What it was given is read from the same table as a device's, under `person:<email>`. */
|
|
95
|
+
const base = person ? '/m/api' : '/c/api';
|
|
96
|
+
if (!url.pathname.startsWith(`${base}/`)) return false;
|
|
93
97
|
/* "/<pairing>/me" -> the pairing and "/me"; "/pair" has no pairing yet. */
|
|
94
|
-
const named = /^\/([0-9a-f-]{36})(\/.*)$/.exec(url.pathname.slice(
|
|
95
|
-
const pairing = named?.[1];
|
|
96
|
-
const route = named ? named[2] : url.pathname.slice(
|
|
98
|
+
const named = person ? null : /^\/([0-9a-f-]{36})(\/.*)$/.exec(url.pathname.slice(base.length));
|
|
99
|
+
const pairing = person ? person.key : named?.[1];
|
|
100
|
+
const route = named ? named[2] : url.pathname.slice(base.length);
|
|
101
|
+
const given_ = person ?? devices;
|
|
97
102
|
const send = (status, body, extra = {}) => {
|
|
98
103
|
response.writeHead(status, { ...headers, ...extra, 'content-type': 'application/json; charset=utf-8' }).end(JSON.stringify(body));
|
|
99
104
|
return true;
|
|
@@ -101,7 +106,8 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
101
106
|
try {
|
|
102
107
|
if (request.method === 'POST' && !originOk(request.headers)) return send(403, { error: 'This request does not come from this site.' });
|
|
103
108
|
|
|
104
|
-
/* ---- pairing: no session yet ---- */
|
|
109
|
+
/* ---- pairing: no session yet (never for a member: 404) ---- */
|
|
110
|
+
if (person && ['/pair', '/challenge', '/session', '/leave'].includes(route)) return send(404, { error: 'Not found.' });
|
|
105
111
|
if (request.method === 'POST' && route === '/pair') return send(201, devices.pair(await readJson(request)));
|
|
106
112
|
if (request.method === 'POST' && route === '/challenge') return send(200, devices.challenge(String((await readJson(request)).device ?? '')));
|
|
107
113
|
if (request.method === 'POST' && route === '/session') {
|
|
@@ -111,17 +117,21 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
111
117
|
}
|
|
112
118
|
|
|
113
119
|
/* ---- everything else: a device session, and its one conversation ---- */
|
|
114
|
-
if (devicePairing(devices, request.headers, pairing) === undefined) return send(401, { error: 'This device has no open session.' });
|
|
120
|
+
if (!person && devicePairing(devices, request.headers, pairing) === undefined) return send(401, { error: 'This device has no open session.' });
|
|
115
121
|
/* What this pairing was given: conversations to use, and things of its own to read or write. */
|
|
116
|
-
const given =
|
|
122
|
+
const given = given_.grantsOf(pairing);
|
|
117
123
|
const names = given.filter((g) => g.type === 'conversation').map((g) => g.name);
|
|
118
124
|
const own = given.filter((g) => g.type !== 'conversation').filter((g) => resources.get(g.name))
|
|
119
125
|
.map((g) => ({ name: g.name, type: g.type, access: g.rights.includes('w') ? 'write' : 'read' }));
|
|
120
|
-
const name = deviceConversation(devices, request.headers, pairing, url.searchParams.get('c') ?? undefined);
|
|
126
|
+
const name = person ? person.conversationOf(url.searchParams.get('c') ?? undefined) : deviceConversation(devices, request.headers, pairing, url.searchParams.get('c') ?? undefined);
|
|
121
127
|
const mine = name === undefined ? undefined : conversations.list().find((c) => c.name === name);
|
|
122
128
|
/* The parts of that conversation this pairing was given. */
|
|
123
|
-
const rights = name === undefined ? '' :
|
|
129
|
+
const rights = name === undefined ? '' : given_.rightsOn(pairing, name);
|
|
124
130
|
const part = { terminal: rights.includes('x'), chat: rights.includes('r') ? (rights.includes('w') ? 'write' : 'read') : null };
|
|
131
|
+
/* A member, once a body is read: still let in, still given that right (audits 8 and 10). A device: as before. */
|
|
132
|
+
const stillMay = (right) => !person || (person.still() && given_.rightsOn(pairing, name).includes(right));
|
|
133
|
+
/* A member writing in a folder, once what it sends has come: still let in, still given it (audit 11). */
|
|
134
|
+
const writesStill = () => { if (person && !person.still()) throw new Refusal(403, 'This conversation is not shared with you any more.'); if (person && !given_.rightsOn(pairing, name).includes('x')) throw new Refusal(403, 'This conversation is not shared with you any more.'); };
|
|
125
135
|
const need = (ok, what) => { if (!ok) throw new Refusal(403, `This device was not given ${what} of this conversation.`); };
|
|
126
136
|
/* Its chat alone: what is reached through the conversation is only what its chat holds. */
|
|
127
137
|
const chatOnly = mine !== undefined && !part.terminal;
|
|
@@ -183,20 +193,38 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
183
193
|
if (request.method === 'GET' && talking[1] === '/search') return send(200, talk.search(name, url.searchParams.get('q') ?? ''));
|
|
184
194
|
/* Reminding the tool and writing to it: a chat given to write in. Nothing else (turning it on, inviting the tool) is a device's. */
|
|
185
195
|
if (request.method === 'POST' && (talking[1] === undefined || talking[1] === '/remind' || talking[1] === '/file' || talking[1] === '/react')) need(part.chat === 'write', 'the chat to write in');
|
|
196
|
+
/* A reaction or an answer to a question reaches the tool as its owner's choice: not a member's (audit 6). */
|
|
197
|
+
if (person && request.method === 'POST' && talking[1] === '/react') throw new Refusal(403, 'A member writes; it does not react for the owner.');
|
|
186
198
|
if (request.method === 'POST' && talking[1] === '/react') { const body = await readJson(request); return send(200, await talk.react(name, body.to, body.reaction ?? null)); }
|
|
187
199
|
if (request.method === 'POST' && talking[1] === '/remind') return send(200, await talk.remind(name));
|
|
188
200
|
if (request.method === 'POST' && talking[1] === '/file') {
|
|
189
201
|
if (request.headers['content-type'] !== 'application/octet-stream') return send(400, { error: 'An attachment is a file.' });
|
|
190
|
-
|
|
202
|
+
const attached = await talk.attach(name, url.searchParams.get('name') ?? '', request);
|
|
203
|
+
/* A member disabled while its file came: not given back to it (audit 10). */
|
|
204
|
+
if (!stillMay('w')) throw new Refusal(403, 'This conversation is not shared with you any more.');
|
|
205
|
+
return send(201, attached);
|
|
191
206
|
}
|
|
192
|
-
if (request.method === 'POST' && talking[1] === undefined) { const body = await readJson(request);
|
|
207
|
+
if (request.method === 'POST' && talking[1] === undefined) { const body = await readJson(request);
|
|
208
|
+
/* Its right looked at again once the message is read: taken back meanwhile, nothing said (audit 8). */
|
|
209
|
+
if (!stillMay('w')) throw new Refusal(403, 'This conversation is not shared with you any more.'); if (part.terminal && signinCode && conversations.signinHelp?.codeInChat(name, body.text, body.files)) return send(201, { ...(await signinCode(name, body.text)), told: 'signin' }); /* A member's words (#419): said as theirs, so that the tool never takes them for its owner's. */
|
|
210
|
+
if (person) {
|
|
211
|
+
/* Every word of a member said as a member's: its text (a line of its own starting "[" cannot pass for
|
|
212
|
+
another mark), the notes of its files; no answer to a question, no way through (audit 6). */
|
|
213
|
+
const mark = `[${person.email}, a member]`;
|
|
214
|
+
const clean = (t) => String(t ?? '').replace(/[\u200B-\u200F\u2060\uFEFF]/g, '').replace(/[[\uFF3B]/g, '(');
|
|
215
|
+
const files = Array.isArray(body.files) ? body.files.map((f) => (f && typeof f === 'object' ? { ...f, note: `${mark} ${clean(f.note)}`.trim() } : f)) : body.files;
|
|
216
|
+
return send(201, await talk.say(name, `${mark} ${clean(body.text)}`.trim(), undefined, files, undefined, { quick: false }));
|
|
217
|
+
}
|
|
218
|
+
return send(201, await talk.say(name, body.text, body.answers, body.files, body.via, { quick: body.quick === true })); }
|
|
193
219
|
}
|
|
194
220
|
/* A sign-in code (#405): a device given its terminal could type it there; no other. Named twice, never guessed. */
|
|
195
221
|
const codeFor = /^\/conversations\/([^/]+)\/signin-code$/.exec(route);
|
|
196
222
|
if (request.method === 'POST' && codeFor && signinCode) {
|
|
197
223
|
need(part.terminal, 'the terminal');
|
|
198
224
|
if (decodeURIComponent(codeFor[1]) !== name) throw new Refusal(403, 'This device was not given the terminal of this conversation.');
|
|
199
|
-
|
|
225
|
+
const code = (await readJson(request)).code;
|
|
226
|
+
if (!stillMay('x')) throw new Refusal(403, 'This conversation is not shared with you any more.');
|
|
227
|
+
return send(200, await signinCode(name, code));
|
|
200
228
|
}
|
|
201
229
|
/* Its terminal does not come: only a device given it asks for it to be repaired. */
|
|
202
230
|
if (request.method === 'POST' && route === '/terminal/repair') { need(part.terminal, 'the terminal'); return send(200, await repair(name)); }
|
|
@@ -228,7 +256,7 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
228
256
|
}
|
|
229
257
|
/* A mail cited by its reference (mailref.mjs): only a mailbox this device was given to read. */
|
|
230
258
|
if (request.method === 'GET' && (route === '/mail/open' || route === '/mail/page')) {
|
|
231
|
-
return await mailRoute(route, url.searchParams, response, { tethers, headers, who: { id: `pairing:${pairing}`, name: 'A device' }, may: (t) => deviceMayRead(t, own, mailboxes), offline: mine?.offline === true });
|
|
259
|
+
return await mailRoute(route, url.searchParams, response, { tethers, headers, who: person ? { id: `person:${person.email}`, name: person.email } : { id: `pairing:${pairing}`, name: 'A device' }, may: (t) => deviceMayRead(t, own, mailboxes), offline: mine?.offline === true });
|
|
232
260
|
}
|
|
233
261
|
if (request.method === 'GET' && route === '/files/download') {
|
|
234
262
|
const file = await download(attached('read', 'open'), url.searchParams.get('p') ?? '');
|
|
@@ -240,13 +268,13 @@ export async function handleDoor(request, response, { devices, conversations, re
|
|
|
240
268
|
if (request.method === 'POST' && route === '/files/import') {
|
|
241
269
|
if (request.headers['content-type'] !== 'application/octet-stream') return send(400, { error: 'An import is a file.' });
|
|
242
270
|
return send(201, await importFile(attached('write'), url.searchParams.get('p') ?? '', url.searchParams.get('name') ?? '', request,
|
|
243
|
-
{ exists: url.searchParams.get('exists') ?? 'keep', dir: url.searchParams.get('dir') ?? '', batch: url.searchParams.get('batch') ?? undefined }));
|
|
271
|
+
{ exists: url.searchParams.get('exists') ?? 'keep', dir: url.searchParams.get('dir') ?? '', batch: url.searchParams.get('batch') ?? undefined, ok: writesStill }));
|
|
244
272
|
}
|
|
245
273
|
/* Thumbnails, editing, making, renaming, moving, removing: as listing
|
|
246
274
|
and importing are. A device given the chat alone has none of them
|
|
247
275
|
(`attached` refuses all but opening a file of the chat). */
|
|
248
276
|
/* A thumbnail is the file read, as opening it is: a device given the chat alone sees the pictures of its chat. */
|
|
249
|
-
const answer = await changeRoute(request.method, route, url.searchParams, request, (need) => attached(need, route === '/files/thumb' ? 'open' : undefined));
|
|
277
|
+
const answer = await changeRoute(request.method, route, url.searchParams, request, (need) => { if (need === 'write') writesStill(); return attached(need, route === '/files/thumb' ? 'open' : undefined); }, writesStill);
|
|
250
278
|
if (answer?.picture) {
|
|
251
279
|
response.writeHead(200, { ...headers, ...IMAGE_HEADERS, 'content-type': answer.picture.type, 'content-length': answer.picture.bytes.length });
|
|
252
280
|
response.end(answer.picture.bytes);
|
package/server/files.mjs
CHANGED
|
@@ -154,7 +154,8 @@ export async function mailFile(root, relative) {
|
|
|
154
154
|
is replaced; a folder never is), 'skip' (nothing written).
|
|
155
155
|
`dir`: subfolders under `relative` to make first (a folder dropped whole).
|
|
156
156
|
`batch`: an id the page gives one drop, bounded as a whole (see BATCH_MAX). */
|
|
157
|
-
|
|
157
|
+
/* `ok()`: looked at once the file has come, before it is put in place (it throws when the sender lost its right). */
|
|
158
|
+
export async function importFile(root, relative, name, request, { exists = 'keep', dir = '', batch, ok = () => {} } = {}) {
|
|
158
159
|
if (!isFileName(name)) throw new Refusal(400, 'A file name has no slash, does not start with a dot, and is at most 120 characters.');
|
|
159
160
|
if (!['keep', 'replace', 'skip'].includes(exists)) throw new Refusal(400, 'A name already taken is kept beside, replaced or skipped.');
|
|
160
161
|
const declared = Number(request.headers['content-length']);
|
|
@@ -187,6 +188,7 @@ export async function importFile(root, relative, name, request, { exists = 'keep
|
|
|
187
188
|
const [stem, ext] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ''];
|
|
188
189
|
for (let i = 2; await lstat(join(folderPath, final)).then(() => true, () => false); i++) final = `${stem} (${i})${ext}`;
|
|
189
190
|
} else if ((await lstat(join(folderPath, name)).catch(() => undefined))?.isDirectory()) throw new Refusal(409, `"${name}" is a folder here: it is not replaced by a file.`);
|
|
191
|
+
ok();
|
|
190
192
|
await rename(partial, join(folderPath, final));
|
|
191
193
|
return { name: final, size, ...(taken && exists === 'replace' && final === name ? { replaced: true } : {}) };
|
|
192
194
|
} catch (error) { await unlink(partial).catch(() => {}); throw error; }
|
|
@@ -402,7 +404,7 @@ export async function readText(root, relative) {
|
|
|
402
404
|
not at that version any more (the agent wrote it meanwhile), nothing is
|
|
403
405
|
written and the answer says so (409, kind "changed"); 'any' writes over
|
|
404
406
|
it all the same. `copy`: written beside it under a free name instead. */
|
|
405
|
-
export async function saveText(root, relative, request, { version, copy = false } = {}) {
|
|
407
|
+
export async function saveText(root, relative, request, { version, copy = false, ok = () => {} } = {}) {
|
|
406
408
|
const parts = []; let size = 0;
|
|
407
409
|
for await (const chunk of request) { size += chunk.length; if (size > EDIT_MAX) throw new Refusal(413, `A text edited here is ${EDIT_MAX / 1024 / 1024} MB at most.`); parts.push(chunk); }
|
|
408
410
|
const bytes = Buffer.concat(parts);
|
|
@@ -423,6 +425,7 @@ export async function saveText(root, relative, request, { version, copy = false
|
|
|
423
425
|
/* Looked at again, the moment before: a write of the agent in between is not lost silently. */
|
|
424
426
|
if (!copy && version !== 'any') { const now = await lstat(at.path).catch(() => undefined); if (!now?.isFile() || versionOf(now) !== version) throw changed(); }
|
|
425
427
|
if (copy && await lstat(target).then(() => true, () => false)) throw new Refusal(409, `"${name}" was just made by someone else: try again.`);
|
|
428
|
+
ok();
|
|
426
429
|
await rename(partial, target);
|
|
427
430
|
} catch (error) { await unlink(partial).catch(() => {}); throw error; }
|
|
428
431
|
return { name, version: versionOf(await lstat(target)), size: bytes.length };
|
|
@@ -495,7 +498,7 @@ async function bridgeFiles(root) {
|
|
|
495
498
|
}
|
|
496
499
|
|
|
497
500
|
export const CHANGE_ROUTES = ['/files/thumb', '/files/text', '/files/save', '/files/make', '/files/rename', '/files/move', '/files/remove', '/files/taken'];
|
|
498
|
-
export async function changeRoute(method, route, params, request, folder) {
|
|
501
|
+
export async function changeRoute(method, route, params, request, folder, ok = () => {}) {
|
|
499
502
|
if (!CHANGE_ROUTES.includes(route)) return undefined;
|
|
500
503
|
const p = params.get('p') ?? '';
|
|
501
504
|
if (method === 'GET' && route === '/files/thumb') {
|
|
@@ -509,7 +512,7 @@ export async function changeRoute(method, route, params, request, folder) {
|
|
|
509
512
|
const type = String(request.headers['content-type'] ?? '');
|
|
510
513
|
if (route === '/files/save') {
|
|
511
514
|
if (type !== 'application/octet-stream') return [400, { error: 'A text saved is sent as it is.' }];
|
|
512
|
-
return [200, await saveText(folder('write'), p, request, { version: params.get('version') ?? '', copy: params.get('copy') === '1' })];
|
|
515
|
+
return [200, await saveText(folder('write'), p, request, { version: params.get('version') ?? '', copy: params.get('copy') === '1', ok })];
|
|
513
516
|
}
|
|
514
517
|
if (!type.startsWith('application/json')) return [400, { error: 'The request is not JSON.' }];
|
|
515
518
|
const chunks = []; let size = 0;
|
package/server/grants.mjs
CHANGED
|
@@ -67,7 +67,7 @@ import { Refusal } from './conversations.mjs';
|
|
|
67
67
|
export const RIGHTS = Object.freeze({ conversation: 'rwxm', folder: 'rw', mailbox: 'r', git: 'rw', secret: 'x', server: 'rw', room: 'rwm', box: 'rw' });
|
|
68
68
|
/* What each of the server's own assets takes: its state and its jobs are read, rooms are made. */
|
|
69
69
|
const SERVER_RIGHTS = Object.freeze({ 'server:status': 'r', 'server:jobs': 'r', 'server:rooms': 'w', 'server:diagnostics': 'r' });
|
|
70
|
-
const SUBJECT = /^(conversation:[a-z]([a-z0-9-]{0,30}[a-z0-9])?|(pairing|apikey):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
|
|
70
|
+
const SUBJECT = /^(conversation:[a-z]([a-z0-9-]{0,30}[a-z0-9])?|(pairing|apikey):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|person:[a-z0-9._+-]{1,64}@([a-z0-9-]{1,63}\.)+[a-z]{2,24})$/;
|
|
71
71
|
const ASSET = /^(conversation|folder|mailbox|git):[a-z]([a-z0-9-]{0,30}[a-z0-9])?$|^secret:[A-Z][A-Z0-9_]{0,39}$|^server:(status|jobs|rooms|diagnostics)$|^(room|box):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
72
72
|
|
|
73
73
|
export const typeOf = (asset) => String(asset).split(':')[0];
|
|
@@ -114,7 +114,9 @@ export class Grants {
|
|
|
114
114
|
/* A secret is handed to a conversation, never to a device: a device
|
|
115
115
|
would be a way to read it. */
|
|
116
116
|
if (typeOf(asset) === 'secret' && !subject.startsWith('conversation:')) throw new Refusal(400, 'A secret is handed to a conversation, never shared with a device.');
|
|
117
|
-
|
|
117
|
+
/* A MEMBER (person:, people.mjs, #419) is given conversations only, in this version: its chat, its terminal. */
|
|
118
|
+
if (subject.startsWith('person:') && typeOf(asset) !== 'conversation') throw new Refusal(400, 'A member is given conversations only.');
|
|
119
|
+
if (typeOf(asset) === 'conversation' && !subject.startsWith('pairing:') && !subject.startsWith('apikey:') && !subject.startsWith('person:')) throw new Refusal(400, 'A conversation is shared with a device or an API key, not with another conversation.');
|
|
118
120
|
/* The state of the server is given to an API key only; an API key is given only that, and
|
|
119
121
|
conversations one by one -- their chat, to read or to write in, never their terminal. */
|
|
120
122
|
if (typeOf(asset) === 'server' && !subject.startsWith('apikey:')) throw new Refusal(400, 'The state of the server is given to an API key only.');
|
|
@@ -141,6 +143,8 @@ export class Grants {
|
|
|
141
143
|
/* Who has something on one asset: [{ subject, rights }]. */
|
|
142
144
|
on(asset) { return this.#store.all().filter((g) => g.asset === asset).map((g) => ({ subject: g.subject, rights: g.rights })); }
|
|
143
145
|
|
|
146
|
+
/* The subjects there are that start so ('person:'). */
|
|
147
|
+
subjects(prefix) { return [...new Set(this.#store.all().map((g) => g.subject).filter((s) => s.startsWith(prefix)))]; }
|
|
144
148
|
forgetSubject(subject) { for (const g of this.#store.all()) if (g.subject === subject) this.#store.remove(g.name); }
|
|
145
149
|
forgetAsset(asset) { for (const g of this.#store.all()) if (g.asset === asset) this.#store.remove(g.name); }
|
|
146
150
|
}
|