@johnhenry/wsh 0.39.0 → 0.41.0
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/README.md +126 -8
- package/package.json +1 -1
- package/src/host.d.ts +97 -0
- package/src/host.mjs +2 -0
- package/src/memory-host.d.ts +10 -1
- package/src/memory-host.mjs +16 -2
- package/src/messages.gen.mjs +37 -0
- package/src/refusal.mjs +42 -0
- package/src/reverse-host.mjs +33 -12
- package/src/server/connection.mjs +37 -13
- package/src/server/index.d.ts +11 -0
- package/src/server/index.mjs +12 -0
- package/src/shares.mjs +440 -0
package/src/shares.mjs
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Operator-side shared folders, the HOST half (#159). Browser-safe: it imports nothing from `node:*`.
|
|
3
|
+
*
|
|
4
|
+
* A host that has no disk of its own (a tab) can use directories that live on the OPERATOR's machine for the life of
|
|
5
|
+
* a session: the operator's `wsh --share NAME=/abs/dir[:ro|:rw]` offers them (`ShareOffer`), and this module hands the
|
|
6
|
+
* embedder an object of async file operations per share -- `onShare(name, fs, who)` -- that it can mount. Every
|
|
7
|
+
* operation is a bounded `ShareRequest` this host sends and the operator's client answers (`ShareReply`).
|
|
8
|
+
*
|
|
9
|
+
* The client is the file server and enforces confinement; this side enforces what a host can: the request window the
|
|
10
|
+
* offer promised (`max_inflight`), a per-request deadline, the size of a reply, the shape of what comes back (a client
|
|
11
|
+
* that answers nonsense gets an `EIO`, never a thrown TypeError in the embedder's code), and that nothing is asked
|
|
12
|
+
* before an offer. Share names, counts and limits from the offer are validated and clamped.
|
|
13
|
+
*
|
|
14
|
+
* Negotiation: a host that passes `onShare` lists the feature `shares` in `ServerHello.features`. A client with shares
|
|
15
|
+
* to offer sends ONE `ShareOffer` after login (inside whatever sealing the session has, so a sealed session protects
|
|
16
|
+
* file data with no extra crypto here). A host without `onShare` never lists the feature and ignores an offer.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { MSG, shareRequest } from './messages.gen.mjs';
|
|
20
|
+
|
|
21
|
+
/** The `ServerHello` feature of a host that can use shares. */
|
|
22
|
+
export const SHARES_FEATURE = 'shares';
|
|
23
|
+
|
|
24
|
+
const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
25
|
+
const ERRNOS = new Set(['ENOENT', 'EEXIST', 'ENOTDIR', 'EISDIR', 'ENOTEMPTY', 'EACCES', 'EPERM', 'EROFS', 'EINVAL', 'EBADF', 'ELOOP',
|
|
26
|
+
'ENAMETOOLONG', 'ENOSPC', 'EMFILE', 'EBUSY', 'EAGAIN', 'EXDEV', 'EFBIG', 'ENOTSUP', 'ESTALE', 'EIO']);
|
|
27
|
+
const MAX_SHARES = 16;
|
|
28
|
+
const MAX_ROOT_BYTES = 4096;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The advisory root path of each share from `ShareOffer.paths` (#164): an array exactly as long as `shares`, each entry an
|
|
32
|
+
* absolute string of at most 4096 bytes without NUL. Anything else is `undefined` (never an error): the host cannot verify it.
|
|
33
|
+
* @returns {Array<string | undefined>}
|
|
34
|
+
*/
|
|
35
|
+
function offeredRoots(paths, count) {
|
|
36
|
+
const none = new Array(count).fill(undefined);
|
|
37
|
+
if (!Array.isArray(paths) || paths.length !== count) return none;
|
|
38
|
+
return paths.map((p) => (typeof p === 'string' && p.startsWith('/') && !p.includes('\0') && new TextEncoder().encode(p).length <= MAX_ROOT_BYTES ? p : undefined));
|
|
39
|
+
}
|
|
40
|
+
const MAX_INFLIGHT = 64;
|
|
41
|
+
const MIN_BYTES = 4096;
|
|
42
|
+
const MAX_BYTES = 4 * 1024 * 1024;
|
|
43
|
+
/** Requests waiting for a slot of the window, per connection; beyond that a call fails with `EAGAIN` at once. */
|
|
44
|
+
const QUEUE_LIMIT = 4096;
|
|
45
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
46
|
+
const DEFAULT_MAX_FILE_BYTES = 64 * 1024 * 1024;
|
|
47
|
+
const MAX_LIST_ENTRIES = 2_000_000;
|
|
48
|
+
|
|
49
|
+
/** An error from the operator's side of a share, with the errno-like code the wire carries (`error.code === error.errno`). */
|
|
50
|
+
export class ShareError extends Error {
|
|
51
|
+
constructor(errno, message) {
|
|
52
|
+
super(`${errno}: ${message}`);
|
|
53
|
+
this.name = 'ShareError';
|
|
54
|
+
this.errno = errno;
|
|
55
|
+
this.code = errno;
|
|
56
|
+
this.wsh = true;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const clampInt = (v, lo, hi) => Math.min(hi, Math.max(lo, Number.isFinite(v) ? Math.trunc(v) : lo));
|
|
61
|
+
const text = (v, max = 200) => (typeof v === 'string' ? v.replace(/[\u0000-\u001f\u007f]/g, ' ').slice(0, max) : '');
|
|
62
|
+
|
|
63
|
+
/** An attribute map from the wire, as a plain object a caller can rely on. */
|
|
64
|
+
function toAttr(a) {
|
|
65
|
+
if (!a || typeof a !== 'object') throw new ShareError('EIO', 'the operator sent no attributes');
|
|
66
|
+
const type = a.type === 'file' || a.type === 'directory' || a.type === 'symlink' ? a.type : null;
|
|
67
|
+
if (!type) throw new ShareError('EIO', 'the operator sent an unknown file type');
|
|
68
|
+
const n = (v) => (Number.isFinite(v) ? Number(v) : 0);
|
|
69
|
+
return {
|
|
70
|
+
type, size: n(a.size), mode: n(a.mode) & 0o777, mtimeMs: n(a.mtime_ms), atimeMs: n(a.atime_ms), ctimeMs: n(a.ctime_ms), nlink: n(a.nlink), ino: n(a.ino),
|
|
71
|
+
isFile: () => type === 'file', isDirectory: () => type === 'directory', isSymbolicLink: () => type === 'symlink',
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const toBytes = (v, what) => {
|
|
76
|
+
if (v instanceof Uint8Array) return v;
|
|
77
|
+
if (v === undefined || v === null) return new Uint8Array(0);
|
|
78
|
+
throw new ShareError('EIO', `the operator sent ${what} that is not bytes`);
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The per-connection engine: one request window shared by every share of the connection.
|
|
83
|
+
* @param {{ send: (m: object) => unknown, log?: (line: string) => void, timeoutMs?: number }} io
|
|
84
|
+
*/
|
|
85
|
+
function createCore({ send, log = () => {}, timeoutMs = DEFAULT_TIMEOUT_MS }) {
|
|
86
|
+
let window = 1;
|
|
87
|
+
let maxBytes = MIN_BYTES;
|
|
88
|
+
let nextId = 1;
|
|
89
|
+
let closed = false;
|
|
90
|
+
const inflight = new Map(); // id -> { job, abandoned }
|
|
91
|
+
const queue = [];
|
|
92
|
+
const stats = { requests: 0, replies: 0, errors: 0, bytesDown: 0, bytesUp: 0, timeouts: 0 };
|
|
93
|
+
|
|
94
|
+
function pump() {
|
|
95
|
+
while (!closed && inflight.size < window && queue.length) start(queue.shift());
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function start(job) {
|
|
99
|
+
if (job.done) return;
|
|
100
|
+
let id = nextId;
|
|
101
|
+
for (let i = 0; inflight.has(id); i += 1) { id = (id % 0xffffffff) + 1; if (i > 0xffff) { finish(job, new ShareError('EAGAIN', 'no request id free')); return; } }
|
|
102
|
+
nextId = (id % 0xffffffff) + 1;
|
|
103
|
+
job.id = id;
|
|
104
|
+
inflight.set(id, { job, abandoned: false });
|
|
105
|
+
stats.requests += 1;
|
|
106
|
+
if (job.fields.data) stats.bytesUp += job.fields.data.byteLength;
|
|
107
|
+
try {
|
|
108
|
+
Promise.resolve(send(shareRequest({ requestId: id, share: job.share, op: job.op, ...job.fields }))).catch(() => {});
|
|
109
|
+
} catch (e) { inflight.delete(id); finish(job, new ShareError('EIO', `could not send: ${e.message}`)); }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function finish(job, err, value) {
|
|
113
|
+
if (job.done) return;
|
|
114
|
+
job.done = true;
|
|
115
|
+
clearTimeout(job.timer);
|
|
116
|
+
if (err) job.reject(err); else job.resolve(value);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
stats,
|
|
121
|
+
get maxBytes() { return maxBytes; },
|
|
122
|
+
configure(offer) { window = offer.maxInflight; maxBytes = offer.maxBytes; pump(); },
|
|
123
|
+
/** Send one request and resolve with the (validated-as-ok) reply. */
|
|
124
|
+
call(share, op, fields = {}) {
|
|
125
|
+
return new Promise((resolve, reject) => {
|
|
126
|
+
if (closed) { reject(new ShareError('EIO', 'the connection to the operator is gone')); return; }
|
|
127
|
+
const job = { share, op, fields, resolve, reject, done: false, id: 0, timer: null };
|
|
128
|
+
if (queue.length >= QUEUE_LIMIT) { reject(new ShareError('EAGAIN', 'too many share requests are waiting')); return; }
|
|
129
|
+
job.timer = setTimeout(() => {
|
|
130
|
+
stats.timeouts += 1;
|
|
131
|
+
const q = queue.indexOf(job);
|
|
132
|
+
if (q >= 0) queue.splice(q, 1);
|
|
133
|
+
// A request already sent keeps its slot until the operator answers (or the connection ends): the window
|
|
134
|
+
// the offer promised is not exceeded because one answer is slow.
|
|
135
|
+
const entry = inflight.get(job.id);
|
|
136
|
+
if (entry) entry.abandoned = true;
|
|
137
|
+
finish(job, new ShareError('EIO', `the operator did not answer ${op} within ${timeoutMs} ms`));
|
|
138
|
+
}, timeoutMs);
|
|
139
|
+
job.timer.unref?.();
|
|
140
|
+
queue.push(job);
|
|
141
|
+
pump();
|
|
142
|
+
});
|
|
143
|
+
},
|
|
144
|
+
reply(m) {
|
|
145
|
+
const entry = inflight.get(m.request_id);
|
|
146
|
+
if (!entry) return; // unknown or already answered: ignored
|
|
147
|
+
inflight.delete(m.request_id);
|
|
148
|
+
stats.replies += 1;
|
|
149
|
+
const { job, abandoned } = entry;
|
|
150
|
+
if (!abandoned) {
|
|
151
|
+
if (m.ok === true) {
|
|
152
|
+
const data = m.data;
|
|
153
|
+
if (data instanceof Uint8Array) {
|
|
154
|
+
stats.bytesDown += data.byteLength;
|
|
155
|
+
if (data.byteLength > maxBytes) { stats.errors += 1; finish(job, new ShareError('EIO', 'the operator sent more data than it offered')); pump(); return; }
|
|
156
|
+
}
|
|
157
|
+
finish(job, null, m);
|
|
158
|
+
} else {
|
|
159
|
+
stats.errors += 1;
|
|
160
|
+
const errno = ERRNOS.has(m.errno) ? m.errno : 'EIO';
|
|
161
|
+
finish(job, new ShareError(errno, text(m.message) || errno));
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
pump();
|
|
165
|
+
},
|
|
166
|
+
close() {
|
|
167
|
+
if (closed) return;
|
|
168
|
+
closed = true;
|
|
169
|
+
const gone = () => new ShareError('EIO', 'the connection to the operator is gone');
|
|
170
|
+
for (const { job } of inflight.values()) finish(job, gone());
|
|
171
|
+
inflight.clear();
|
|
172
|
+
for (const job of queue.splice(0)) finish(job, gone());
|
|
173
|
+
},
|
|
174
|
+
get closed() { return closed; },
|
|
175
|
+
log,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** An open file on the operator's machine. */
|
|
180
|
+
class ShareFile {
|
|
181
|
+
#core; #share; #handle; #inline; #writable; #closed = false;
|
|
182
|
+
constructor(core, share, handle, attr, { inline = null, writable = false } = {}) {
|
|
183
|
+
this.#core = core; this.#share = share; this.#handle = handle; this.#inline = inline; this.#writable = writable;
|
|
184
|
+
this.attr = attr;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Read up to `length` bytes at `offset`: `{ data, eof }`. */
|
|
188
|
+
async read(offset, length) {
|
|
189
|
+
if (this.#closed) throw new ShareError('EBADF', 'the file is closed');
|
|
190
|
+
if (!(Number.isSafeInteger(offset) && offset >= 0) || !(Number.isSafeInteger(length) && length >= 0)) throw new ShareError('EINVAL', 'read needs a non-negative offset and length');
|
|
191
|
+
if (this.#inline) {
|
|
192
|
+
const data = this.#inline.subarray(offset, offset + length);
|
|
193
|
+
return { data, eof: offset + length >= this.#inline.byteLength };
|
|
194
|
+
}
|
|
195
|
+
const n = Math.min(length, this.#core.maxBytes);
|
|
196
|
+
const r = await this.#core.call(this.#share, 'read', { handle: this.#handle, offset, length: n });
|
|
197
|
+
return { data: toBytes(r.data, 'read data'), eof: r.eof === true };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Write `data` at `offset` (a share offered `:rw`); resolves with the bytes written. */
|
|
201
|
+
async write(offset, data) {
|
|
202
|
+
if (this.#closed) throw new ShareError('EBADF', 'the file is closed');
|
|
203
|
+
if (!this.#writable) throw new ShareError('EBADF', 'the file is not open for writing');
|
|
204
|
+
let done = 0;
|
|
205
|
+
while (done < data.byteLength) {
|
|
206
|
+
const chunk = data.subarray(done, done + this.#core.maxBytes);
|
|
207
|
+
const r = await this.#core.call(this.#share, 'write', { handle: this.#handle, offset: offset + done, data: chunk });
|
|
208
|
+
const w = Number(r.written);
|
|
209
|
+
if (!Number.isSafeInteger(w) || w < 0 || w > chunk.byteLength) throw new ShareError('EIO', 'the operator reported a bad write size');
|
|
210
|
+
done += w;
|
|
211
|
+
if (w === 0) break;
|
|
212
|
+
}
|
|
213
|
+
return done;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async setattr(changes) {
|
|
217
|
+
if (this.#closed) throw new ShareError('EBADF', 'the file is closed');
|
|
218
|
+
if (!this.#handle) throw new ShareError('EBADF', 'this file is read-only and complete: use fs.setattr(path, ...)');
|
|
219
|
+
const r = await this.#core.call(this.#share, 'setattr', { handle: this.#handle, attr: wireAttr(changes) });
|
|
220
|
+
return toAttr(r.attr);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async truncate(size) { return this.setattr({ size }); }
|
|
224
|
+
|
|
225
|
+
async close() {
|
|
226
|
+
if (this.#closed) return;
|
|
227
|
+
this.#closed = true;
|
|
228
|
+
if (this.#handle) await this.#core.call(this.#share, 'close', { handle: this.#handle }).catch(() => {});
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function wireAttr(c = {}) {
|
|
233
|
+
const out = {};
|
|
234
|
+
if (c.mode !== undefined) out.mode = c.mode;
|
|
235
|
+
if (c.atimeMs !== undefined) out.atime_ms = c.atimeMs;
|
|
236
|
+
if (c.mtimeMs !== undefined) out.mtime_ms = c.mtimeMs;
|
|
237
|
+
if (c.size !== undefined) out.size = c.size;
|
|
238
|
+
return out;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* The object an embedder mounts: async file operations on one share. Paths are relative to the share root
|
|
243
|
+
* ("/"-separated; a leading "/" means the root); `..` is refused by the operator's client. Errors are `ShareError`s
|
|
244
|
+
* with `.code` an errno-like string (`ENOENT`, `EROFS`, ...).
|
|
245
|
+
*/
|
|
246
|
+
function createShareFs(core, name, writable, signal, root) {
|
|
247
|
+
const call = (op, fields) => core.call(name, op, fields);
|
|
248
|
+
const norm = (p) => { if (typeof p !== 'string') throw new ShareError('EINVAL', 'a path must be a string'); return p; };
|
|
249
|
+
const maxFileBytes = DEFAULT_MAX_FILE_BYTES;
|
|
250
|
+
|
|
251
|
+
const fs = {
|
|
252
|
+
name,
|
|
253
|
+
/** Whether the operator offered writes. */
|
|
254
|
+
writable,
|
|
255
|
+
/** The share's root path on the operator's machine, as the operator typed it, or undefined. ADVISORY and unverified (#164). */
|
|
256
|
+
get root() { return root; },
|
|
257
|
+
maxFileBytes,
|
|
258
|
+
/** Aborted when the connection to the operator ends. */
|
|
259
|
+
signal,
|
|
260
|
+
/** Counters for this connection (requests, replies, errors, bytes each way): the evidence that batching works. */
|
|
261
|
+
get stats() { return { ...core.stats }; },
|
|
262
|
+
|
|
263
|
+
async stat(path) { return toAttr((await call('stat', { path: norm(path) })).attr); },
|
|
264
|
+
async lstat(path) { return toAttr((await call('lstat', { path: norm(path) })).attr); },
|
|
265
|
+
async readlink(path) {
|
|
266
|
+
const r = await call('readlink', { path: norm(path) });
|
|
267
|
+
if (typeof r.target !== 'string') throw new ShareError('EIO', 'the operator sent no link target');
|
|
268
|
+
return r.target;
|
|
269
|
+
},
|
|
270
|
+
|
|
271
|
+
/** Every entry of a directory WITH its attributes, sorted by name (the pages are followed): `[{ name, type, size, mode, mtimeMs, ..., target? }]`. */
|
|
272
|
+
async readdir(path) {
|
|
273
|
+
const out = [];
|
|
274
|
+
let cursor;
|
|
275
|
+
for (;;) {
|
|
276
|
+
const r = await call('readdir', { path: norm(path), ...(cursor !== undefined ? { cursor } : {}) });
|
|
277
|
+
if (!Array.isArray(r.entries)) throw new ShareError('EIO', 'the operator sent no entries');
|
|
278
|
+
for (const e of r.entries) {
|
|
279
|
+
if (!e || typeof e.name !== 'string' || !e.name || e.name.includes('/') || e.name.includes('\0') || e.name === '.' || e.name === '..') throw new ShareError('EIO', 'the operator sent a bad directory entry');
|
|
280
|
+
const entry = { name: e.name, ...toAttr(e) };
|
|
281
|
+
if (typeof e.target === 'string') entry.target = e.target;
|
|
282
|
+
out.push(entry);
|
|
283
|
+
}
|
|
284
|
+
if (out.length > MAX_LIST_ENTRIES) throw new ShareError('EFBIG', 'directory has too many entries');
|
|
285
|
+
if (r.cursor === undefined || r.cursor === null) break;
|
|
286
|
+
if (typeof r.cursor !== 'string' || (cursor !== undefined && r.cursor <= cursor)) throw new ShareError('EIO', 'the operator\'s directory cursor did not advance');
|
|
287
|
+
cursor = r.cursor;
|
|
288
|
+
}
|
|
289
|
+
return out;
|
|
290
|
+
},
|
|
291
|
+
|
|
292
|
+
/** Open a file. `flags`: any of `read`, `write`, `create`, `excl`, `trunc`. */
|
|
293
|
+
async open(path, flags = ['read'], { mode, inlineBytes } = {}) {
|
|
294
|
+
const f = [...flags];
|
|
295
|
+
const wantsWrite = f.includes('write') || f.includes('create') || f.includes('trunc');
|
|
296
|
+
const r = await call('open', { path: norm(path), flags: f, ...(mode !== undefined ? { mode } : {}), ...(inlineBytes !== undefined ? { length: inlineBytes } : {}) });
|
|
297
|
+
const attr = toAttr(r.attr);
|
|
298
|
+
if (r.handle === undefined || r.handle === null) {
|
|
299
|
+
// Whole file, read-only, no handle: it came with the open.
|
|
300
|
+
if (wantsWrite || r.eof !== true || !(r.data instanceof Uint8Array)) throw new ShareError('EIO', 'the operator sent no file handle');
|
|
301
|
+
return new ShareFile(core, name, 0, attr, { inline: r.data });
|
|
302
|
+
}
|
|
303
|
+
if (!Number.isSafeInteger(r.handle) || r.handle <= 0) throw new ShareError('EIO', 'the operator sent a bad handle');
|
|
304
|
+
return new ShareFile(core, name, r.handle, attr, { writable: wantsWrite, inline: r.eof === true && r.data instanceof Uint8Array && !wantsWrite ? r.data : null });
|
|
305
|
+
},
|
|
306
|
+
|
|
307
|
+
/** Create a NEW file (`EEXIST` if the name is taken, a link included) and open it for writing. */
|
|
308
|
+
async create(path, { mode } = {}) {
|
|
309
|
+
const r = await call('create', { path: norm(path), ...(mode !== undefined ? { mode } : {}) });
|
|
310
|
+
if (!Number.isSafeInteger(r.handle) || r.handle <= 0) throw new ShareError('EIO', 'the operator sent a bad handle');
|
|
311
|
+
return new ShareFile(core, name, r.handle, toAttr(r.attr), { writable: true });
|
|
312
|
+
},
|
|
313
|
+
|
|
314
|
+
/** The whole content of a file: one round trip when it is small (it rides the open), else ranges of the offered size. */
|
|
315
|
+
async readFile(path, { maxBytes = maxFileBytes } = {}) {
|
|
316
|
+
const file = await fs.open(path, ['read'], { inlineBytes: core.maxBytes });
|
|
317
|
+
try {
|
|
318
|
+
if (file.attr.size > maxBytes) throw new ShareError('EFBIG', `the file is ${file.attr.size} bytes, more than ${maxBytes}`);
|
|
319
|
+
const parts = [];
|
|
320
|
+
let offset = 0;
|
|
321
|
+
for (;;) {
|
|
322
|
+
const { data, eof } = await file.read(offset, core.maxBytes);
|
|
323
|
+
if (data.byteLength) parts.push(data);
|
|
324
|
+
offset += data.byteLength;
|
|
325
|
+
if (offset > maxBytes) throw new ShareError('EFBIG', `the file is bigger than ${maxBytes} bytes`);
|
|
326
|
+
if (eof || data.byteLength === 0) break;
|
|
327
|
+
}
|
|
328
|
+
if (parts.length === 1) return parts[0];
|
|
329
|
+
const all = new Uint8Array(offset);
|
|
330
|
+
let at = 0;
|
|
331
|
+
for (const p of parts) { all.set(p, at); at += p.byteLength; }
|
|
332
|
+
return all;
|
|
333
|
+
} finally { await file.close(); }
|
|
334
|
+
},
|
|
335
|
+
|
|
336
|
+
/** Replace (or create) a file with `data`. Needs `:rw`. */
|
|
337
|
+
async writeFile(path, data, { mode, truncate = true } = {}) {
|
|
338
|
+
const file = await fs.open(path, ['write', 'create', ...(truncate ? ['trunc'] : [])], { mode });
|
|
339
|
+
try { return await file.write(0, data); } finally { await file.close(); }
|
|
340
|
+
},
|
|
341
|
+
|
|
342
|
+
async mkdir(path, { mode } = {}) { return toAttr((await call('mkdir', { path: norm(path), ...(mode !== undefined ? { mode } : {}) })).attr); },
|
|
343
|
+
async unlink(path) { await call('unlink', { path: norm(path) }); },
|
|
344
|
+
async rmdir(path) { await call('rmdir', { path: norm(path) }); },
|
|
345
|
+
async rename(from, to) { await call('rename', { path: norm(from), to: norm(to) }); },
|
|
346
|
+
/** `changes`: any of `mode`, `atimeMs`, `mtimeMs`, `size` (a new size is a truncate). */
|
|
347
|
+
async setattr(path, changes) { return toAttr((await call('setattr', { path: norm(path), attr: wireAttr(changes) })).attr); },
|
|
348
|
+
async truncate(path, size) { return fs.setattr(path, { size }); },
|
|
349
|
+
async chmod(path, mode) { return fs.setattr(path, { mode }); },
|
|
350
|
+
async utimes(path, atimeMs, mtimeMs) { return fs.setattr(path, { atimeMs, mtimeMs }); },
|
|
351
|
+
|
|
352
|
+
// ── the shape of an injected `fs` backend (`createMemoryHost({ fs })`, `createWshServer({ fs })`) ───────────────
|
|
353
|
+
// A share can be served onward as a host's own file backend: `createMemoryHost({ fs: share })`.
|
|
354
|
+
async operate(op, clientPath, { offset, length, newPath, data } = {}) {
|
|
355
|
+
const entry = (e, nameOf) => ({ name: nameOf, size: e.size, modified: Math.floor(e.mtimeMs / 1000), type: e.type, ...(e.target !== undefined ? { symlink_target: e.target } : {}) });
|
|
356
|
+
switch (op) {
|
|
357
|
+
case 'list': return { entries: (await fs.readdir(clientPath || '/')).map((e) => entry(e, e.name)), metadata: { path: clientPath || '/' } };
|
|
358
|
+
case 'stat': { const a = await fs.lstat(clientPath); return { metadata: entry(a, String(clientPath).split('/').filter(Boolean).pop() ?? '') }; }
|
|
359
|
+
case 'read': {
|
|
360
|
+
const file = await fs.open(clientPath, ['read']);
|
|
361
|
+
try {
|
|
362
|
+
const want = Math.min(Number(length ?? core.maxBytes), core.maxBytes);
|
|
363
|
+
const { data: bytes } = await file.read(Math.max(0, Number(offset ?? 0)), want);
|
|
364
|
+
return { metadata: { data: bytes, size: file.attr.size } };
|
|
365
|
+
} finally { await file.close(); }
|
|
366
|
+
}
|
|
367
|
+
case 'write': { await fs.writeAt(clientPath, data, offset); return { metadata: { written: data.byteLength } }; }
|
|
368
|
+
case 'mkdir': await fs.mkdir(clientPath); return { metadata: {} };
|
|
369
|
+
case 'remove': { const a = await fs.lstat(clientPath); await (a.isDirectory() ? fs.rmdir(clientPath) : fs.unlink(clientPath)); return { metadata: { removed: clientPath } }; }
|
|
370
|
+
case 'rename': await fs.rename(clientPath, newPath); return { metadata: { renamed: clientPath, to: newPath } };
|
|
371
|
+
default: throw new ShareError('ENOTSUP', `"${op}" is not offered (list, stat, read, write, rename, mkdir, remove)`);
|
|
372
|
+
}
|
|
373
|
+
},
|
|
374
|
+
async readWhole(clientPath) { return fs.readFile(clientPath); },
|
|
375
|
+
async writeWhole(clientPath, bytes) { await fs.writeFile(clientPath, bytes); },
|
|
376
|
+
async writeAt(clientPath, bytes, offset = 0) {
|
|
377
|
+
const file = await fs.open(clientPath, ['write', 'create']);
|
|
378
|
+
try { await file.write(Number(offset), bytes); } finally { await file.close(); }
|
|
379
|
+
},
|
|
380
|
+
};
|
|
381
|
+
return fs;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* The shares of ONE connection. `handle(m)` takes the messages that are about shares; `close()` ends everything.
|
|
386
|
+
* @param {object} io
|
|
387
|
+
* @param {(m: object) => unknown} io.send - send a message to the operator (through the connection's sealing, if any)
|
|
388
|
+
* @param {(name: string, fs: object, who: { username: string | null, fingerprint: string | null }) => unknown} io.onShare
|
|
389
|
+
* @param {() => { username: string | null, fingerprint: string | null }} io.who
|
|
390
|
+
* @param {(line: string) => void} [io.log]
|
|
391
|
+
* @param {number} [io.timeoutMs]
|
|
392
|
+
*/
|
|
393
|
+
export function createShareSession({ send, onShare, who, log = () => {}, timeoutMs }) {
|
|
394
|
+
const core = createCore({ send, log, timeoutMs });
|
|
395
|
+
const abort = new AbortController();
|
|
396
|
+
let offered = false;
|
|
397
|
+
const shares = new Map();
|
|
398
|
+
|
|
399
|
+
function offer(m) {
|
|
400
|
+
if (offered) { log('ignored a second ShareOffer'); return; }
|
|
401
|
+
offered = true;
|
|
402
|
+
const names = Array.isArray(m.shares) ? m.shares : [];
|
|
403
|
+
if (!names.length || names.length > MAX_SHARES || names.some((n) => typeof n !== 'string' || !NAME_RE.test(n)) || new Set(names).size !== names.length) {
|
|
404
|
+
log('ignored a ShareOffer with bad share names');
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
const writable = new Set(Array.isArray(m.writable) ? m.writable.filter((n) => names.includes(n)) : []);
|
|
408
|
+
core.configure({ maxInflight: clampInt(m.max_inflight, 1, MAX_INFLIGHT), maxBytes: clampInt(m.max_bytes, MIN_BYTES, MAX_BYTES) });
|
|
409
|
+
const roots = offeredRoots(m.paths, names.length);
|
|
410
|
+
for (const [i, name] of names.entries()) {
|
|
411
|
+
const fs = createShareFs(core, name, writable.has(name), abort.signal, roots[i]);
|
|
412
|
+
shares.set(name, fs);
|
|
413
|
+
Promise.resolve()
|
|
414
|
+
.then(() => onShare(name, fs, who()))
|
|
415
|
+
.catch((e) => log(`onShare(${JSON.stringify(name)}) threw: ${e?.message ?? e}`));
|
|
416
|
+
}
|
|
417
|
+
log(`shares offered: ${names.map((n) => `${n}${writable.has(n) ? ' (rw)' : ''}`).join(', ')}`);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
return {
|
|
421
|
+
/** The shares offered so far, by name. */
|
|
422
|
+
shares,
|
|
423
|
+
stats: core.stats,
|
|
424
|
+
/** @returns {boolean} whether `m` was about shares (and has been dealt with). */
|
|
425
|
+
handle(m) {
|
|
426
|
+
switch (m.type) {
|
|
427
|
+
case MSG.SHARE_OFFER: offer(m); return true;
|
|
428
|
+
case MSG.SHARE_REPLY: core.reply(m); return true;
|
|
429
|
+
case MSG.SHARE_REQUEST: log('ignored a ShareRequest from the operator (only the host asks)'); return true;
|
|
430
|
+
default: return false;
|
|
431
|
+
}
|
|
432
|
+
},
|
|
433
|
+
close() { abort.abort(); core.close(); },
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** Validate an `onShare` option (a function, or absent). */
|
|
438
|
+
export function validateOnShare(onShare, who) {
|
|
439
|
+
if (onShare !== undefined && onShare !== null && typeof onShare !== 'function') throw new TypeError(`${who}: onShare must be a function (name, fs, who) => void`);
|
|
440
|
+
}
|