@blueshed/joined 0.3.4 → 0.3.6
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/.claude/skills/joined/reference.md +21 -5
- package/.claude/skills/joined-door/SKILL.md +17 -2
- package/docs/introduction.md +6 -2
- package/package.json +1 -1
- package/src/mcp.ts +121 -38
- package/src/server.ts +61 -10
- package/src/skill.ts +109 -33
- package/src/upload.ts +137 -0
|
@@ -444,11 +444,19 @@ export const routes = (read: Read) => ({ "/trip/:n": page, "/trip/:n/trip.ics":
|
|
|
444
444
|
- **An open route** (`export const open = (read) => ({ "/card/:id": (req) => … })`) is anyone's, never guarded by
|
|
445
445
|
the group: a link's preview (og:title, og:image), a card for a stranger. Its `read` is as nobody (member 0):
|
|
446
446
|
owns and sees apply, so a part only some see isn't there, but the group's door doesn't: a document any member
|
|
447
|
-
sees whole is whole. So an open route shows only what it picks, and what it picks is public.
|
|
447
|
+
sees whole is whole. So an open route shows only what it picks, and what it picks is public. One that checks a
|
|
448
|
+
secret of its own (a mail's intake, a webhook) takes the server's `write` and `whole` too
|
|
449
|
+
(`open = (read, write, whole) => …`): `whole(doc)` is every item, as the server holds it, for it to find what it
|
|
450
|
+
needs (whose address a mail came to); what it answers is still its own to pick (`tests/apart/board/routes.ts`).
|
|
448
451
|
- **Two apps answering one path** are refused at start, open routes too.
|
|
449
452
|
- **The server writes** with the `write` a routes function is given beside `read` (`routes(read, write)`):
|
|
450
453
|
a webhook, an import, a job on the app's own timer. `write(doc, ops)` is shaped by the stories (only what
|
|
451
454
|
a story does), never asked of roles or `trust.ts`, by nobody, and told as any write; it throws `Refused`.
|
|
455
|
+
`write(doc, ops, { member, via, why, file })` is a member's write in place of nobody's (a paper a mail brought,
|
|
456
|
+
its member's): asked of their grants, the app's trust and the group's, as an agent's is, a member still in the
|
|
457
|
+
group; its change says `via` (a page shows "Peter via mail"), and its `why`; a `file` (`{ bytes, name }`) is kept
|
|
458
|
+
first, as a page's is (where they may put one, apart where the kind keeps them so), `"$file"` in the ops standing
|
|
459
|
+
for its value; answered `{ done, version, ids, file }`.
|
|
452
460
|
Never the group's document, and never a document's content from files at start: that's its seed (§13).
|
|
453
461
|
- **What follows from a write** is a rule over values where a definition can say it (`takes`: an order
|
|
454
462
|
taking stock, in the database, undone as the write is), and otherwise
|
|
@@ -620,10 +628,18 @@ Working: `src/icons.ts`; the members panel and every example.
|
|
|
620
628
|
kind's take `key`; a window isn't one (read the document). The door carries its own skill, how any document is
|
|
621
629
|
read and written there (`.claude/skills/joined-door/SKILL.md`, the one text, `src/skill.ts`): by MCP's skills
|
|
622
630
|
extension (`io.modelcontextprotocol/skills`, declared in `server/discover`; `skills/list`, `skills/get`, the
|
|
623
|
-
resource `skill://joined-door/SKILL.md`), and
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
631
|
+
resource `skill://joined-door/SKILL.md`), and by `read_skill`, a tool, which every client loads. Its instructions
|
|
632
|
+
are a few lines to every client, so none cuts them off (`opening`): its documents, who the agent acts as (its
|
|
633
|
+
member's id, so a field linking members is read), and where the skills are; nothing a skill says. Beside it each app has a skill of its own, served the same way
|
|
634
|
+
(`skill://<app>/SKILL.md`, written by `skillOf`): its words, then what each of its documents holds (its fields' types,
|
|
635
|
+
what a link is an id of, what an add needs, its tools), from the compiled rules as the tools are. Its words are its
|
|
636
|
+
`routes.ts`'s `instructions` (`examples/trip/routes.ts`), what's its own alone (what its documents mean, its people,
|
|
637
|
+
its clock), never how a read or a write goes. A change to how any document is read or written there changes that
|
|
638
|
+
skill with it (`tests/mcp.test.ts`). A document that names files has `upload_<doc>` too: the agent never sees its
|
|
639
|
+
key, so the server makes it a link (`src/upload.ts`), good once for 15 minutes, for its member and that document;
|
|
640
|
+
POSTed a file it's kept as a page's is and answered its value, opened in a browser it's a page to choose the file on,
|
|
641
|
+
and given `ops` (`"$file"` standing for the file) it makes that write as the agent's once the file's in
|
|
642
|
+
(`tests/upload.test.ts`). Never print the token: the URL holds it. A project with no
|
|
627
643
|
members (every story anonymous, hello) has no group and no agent's link: its door is anyone's, `POST /mcp` with no
|
|
628
644
|
token, as a stranger's page is, each write logged "by anyone" (`tests/server.test.ts`).
|
|
629
645
|
- **Never put `ROOT_TOKEN`, `.env`, the store (`joined.sqlite`, which holds the keys) or anyone's link in a commit,** nor in chat
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: joined-door
|
|
3
|
-
description: Use when reading or changing a joined document through its MCP door (the read_<doc> and
|
|
3
|
+
description: Use when reading or changing a joined document through its MCP door (the read_<doc>, write_<doc> and upload_<doc> tools), for how a read and a write go, an op's path, $n links, the forms a value takes, a file sent, and a refusal. For any app on joined, in any client.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# A joined document, through its door
|
|
@@ -8,7 +8,8 @@ description: Use when reading or changing a joined document through its MCP door
|
|
|
8
8
|
An app on joined keeps its documents, and every page open on them, in step. Its door gives you two tools for each
|
|
9
9
|
document your link may hold: `read_<doc>` and `write_<doc>` (a document you can't write has only its read). Their
|
|
10
10
|
descriptions say what each document holds and each op it takes: read them, they're written from the app's own rules.
|
|
11
|
-
|
|
11
|
+
A document that names files has `upload_<doc>` too. Each app has a skill of its own beside this one: its words, and
|
|
12
|
+
what each of its documents holds. Where your client doesn't load skills, `read_skill` reads any of them whole.
|
|
12
13
|
|
|
13
14
|
## Read first
|
|
14
15
|
|
|
@@ -34,6 +35,20 @@ The app's own words, where it has any, come after these.
|
|
|
34
35
|
write. In a value only, never in a path.
|
|
35
36
|
- Done answers `{"done": true, "version", "ids"}`, the ids of what it added, in order.
|
|
36
37
|
|
|
38
|
+
## A file
|
|
39
|
+
|
|
40
|
+
A file field's value is `file:<sha256>.<ext>`, a file the app keeps already: it comes in by `upload_<doc>`, never in a
|
|
41
|
+
write. You never see your link's key; the server does, so it makes the link for you:
|
|
42
|
+
|
|
43
|
+
- `upload_<doc>` (with `key`, for a kind's) and the file's `name` answers `{"url", "until"}`: a link good once, for 15
|
|
44
|
+
minutes, made for your link's member and that document alone.
|
|
45
|
+
- Where you can send bytes, POST the file to `url`: it answers `{"file": "file:…"}`, the value to write.
|
|
46
|
+
- Where you can't reach the site (a chat's sandbox), give `url` to your person: it opens a page to choose the file on.
|
|
47
|
+
Give the tool `ops` too, the write the file is for, `"$file"` in a value standing for it (`{"op": "add", "path":
|
|
48
|
+
"/papers/-", "value": {"move": 12, "file": "$file"}}`): it's made as yours once the file's in. Read the document
|
|
49
|
+
after, to see it there.
|
|
50
|
+
- A photo, an SVG, a PDF or a Markdown file, under 20 MB; anything else is refused, in words.
|
|
51
|
+
|
|
37
52
|
## Values
|
|
38
53
|
|
|
39
54
|
Each field's form is in the tool's schema; a value in another is refused, in words.
|
package/docs/introduction.md
CHANGED
|
@@ -167,8 +167,12 @@ into claude.ai's custom connectors, so Claude in a chat, on a phone too, can wor
|
|
|
167
167
|
- **A write is a page's write.** It lands whole or not at all, under the app's trust rules, the grants
|
|
168
168
|
and the group's, as the member via the agent, and every page holding the document sees it at once. A
|
|
169
169
|
refusal comes back in its own words: "greeting is a string".
|
|
170
|
-
- **An app can brief Claude.**
|
|
171
|
-
|
|
170
|
+
- **An app can brief Claude.** Each app has a skill at the door beside joined's own: what its documents
|
|
171
|
+
hold, from its rules, after its own words (its `routes.ts` may export `instructions`: the trip's say
|
|
172
|
+
how its times and places are written).
|
|
173
|
+
- **A file comes by a link the server makes.** Claude never sees its own key, so `upload_<doc>` asks the
|
|
174
|
+
server for a link to send one file by, for its member and that document: Claude sends it there, or,
|
|
175
|
+
in a chat that can't reach the site, gives it to you to open and choose the file.
|
|
172
176
|
- **Only an agent's link opens the door.** A member's own link, one taken back, or an unknown one is
|
|
173
177
|
refused, and the token is never printed.
|
|
174
178
|
|
package/package.json
CHANGED
package/src/mcp.ts
CHANGED
|
@@ -7,14 +7,19 @@
|
|
|
7
7
|
// rules, never the stories: read_<doc>, the document as its member sees it, and write_<doc>, one write, its ops typed
|
|
8
8
|
// as the grants allow; a kind's (trip:1) take the instance's key. A window isn't a tool's: a document is read as its
|
|
9
9
|
// member sees it, whole or one collection's items (some, by id). How any document is read and written here is the
|
|
10
|
-
// door's own skill (src/skill.ts), served by MCP's skills extension
|
|
11
|
-
//
|
|
10
|
+
// door's own skill (src/skill.ts), served by MCP's skills extension beside each app's own (its words, its routes.ts's
|
|
11
|
+
// `instructions`, and what its documents hold, from their rules), and by read_skill, a tool, to a client that doesn't
|
|
12
|
+
// load skills. A document that names files
|
|
13
|
+
// has upload_<doc> too: a link the server makes for the agent's member to send a file by (src/upload.ts), since the
|
|
14
|
+
// agent never sees its own key. It speaks both eras of MCP: the modern (2026-07-28), each request saying its
|
|
12
15
|
// version and the client's capabilities in its _meta, its headers checked against its body, server/discover in place
|
|
13
|
-
// of a handshake, and the skills extension declared; and the legacy, opened by initialize.
|
|
14
|
-
//
|
|
16
|
+
// of a handshake, and the skills extension declared; and the legacy, opened by initialize. Its instructions are a few
|
|
17
|
+
// lines to every client, so none is cut off: its documents, who the agent acts as, and where the skills are.
|
|
15
18
|
|
|
16
19
|
import { FORMS, SAID } from "./compile.ts";
|
|
17
|
-
import { skill, SKILLS } from "./skill.ts";
|
|
20
|
+
import { opening, skill, skillOf, SKILLS } from "./skill.ts";
|
|
21
|
+
import type { Made } from "./upload.ts";
|
|
22
|
+
import { schemeOf } from "./proxy.ts";
|
|
18
23
|
import type { Who } from "./members/group.ts";
|
|
19
24
|
import { upTo } from "./files.ts";
|
|
20
25
|
import { isOp, MESSAGE, NTH, OPS, parts, type Op, type Type } from "./ops.ts";
|
|
@@ -34,7 +39,16 @@ type Door = {
|
|
|
34
39
|
read(doc: string, member: number): Promise<Doc>;
|
|
35
40
|
/** A write by an agent's member; or, at a door that's anyone's, nobody's (null), as a stranger's page writes. */
|
|
36
41
|
write(doc: string, ops: Op[], why: string | undefined, who: Who | null): Promise<Written>;
|
|
37
|
-
|
|
42
|
+
/** Each app: its name, its words for an agent, and its documents. */
|
|
43
|
+
apps: { app: string; words: string; docs: string[] }[];
|
|
44
|
+
/** A link for a member's agent (nobody's, at a door that's anyone's) to send a file for a document by (src/upload.ts). */
|
|
45
|
+
upload?(
|
|
46
|
+
origin: string,
|
|
47
|
+
doc: string,
|
|
48
|
+
who: Who | null,
|
|
49
|
+
name: string,
|
|
50
|
+
then: { ops?: Op[]; why?: string },
|
|
51
|
+
): Promise<Made>;
|
|
38
52
|
version: string;
|
|
39
53
|
};
|
|
40
54
|
type Schema = Record<string, unknown>;
|
|
@@ -205,16 +219,41 @@ const ANYONE: Who = { member: 0, token: "" };
|
|
|
205
219
|
export function door(d: Door) {
|
|
206
220
|
const rpc = (id: unknown, result: unknown) => ({ jsonrpc: "2.0", id, result });
|
|
207
221
|
const fail = (id: unknown, code: number, message: string) => ({ jsonrpc: "2.0", id, error: { code, message } });
|
|
222
|
+
// each app's skill, beside the door's: its words and what its documents hold
|
|
223
|
+
const apps = d.apps.flatMap((a) => {
|
|
224
|
+
const rules = d.rules.filter((r) => a.docs.includes(r.doc));
|
|
225
|
+
return rules.length ? [skillOf(a.app, a.words, rules)] : [];
|
|
226
|
+
});
|
|
227
|
+
const skills = [skill, ...apps],
|
|
228
|
+
docs = d.rules.map((r) => (r.kind ? `${r.doc}:<key>` : r.doc));
|
|
229
|
+
const skillAt = (uri: unknown) => skills.find((s) => s.uri === uri);
|
|
208
230
|
|
|
209
231
|
/** The tools for a member's agent: each document's read and, where pages write it, its write; a kind's take its key. */
|
|
210
|
-
async function toolsFor(who: Who) {
|
|
232
|
+
async function toolsFor(who: Who, origin: string) {
|
|
211
233
|
const tools: {
|
|
212
234
|
name: string;
|
|
213
235
|
description: string;
|
|
214
236
|
inputSchema: Schema;
|
|
215
237
|
annotations: Schema;
|
|
216
238
|
run(args: any): Promise<Result> | Result;
|
|
217
|
-
}[] = [
|
|
239
|
+
}[] = [
|
|
240
|
+
{
|
|
241
|
+
name: "read_skill",
|
|
242
|
+
description: `One of this door's skills, its SKILL.md whole, for a client that doesn't load skills itself: ${skill.name}, how any document here is read and written${apps.length ? `; ${apps.map((a) => a.name).join(", ")}, what each app's documents hold and mean` : ""}. Read them before a write.`,
|
|
243
|
+
inputSchema: {
|
|
244
|
+
type: "object",
|
|
245
|
+
properties: { name: { type: "string", enum: skills.map((s) => s.name) } },
|
|
246
|
+
required: ["name"],
|
|
247
|
+
},
|
|
248
|
+
annotations: { readOnlyHint: true },
|
|
249
|
+
run: (args) => {
|
|
250
|
+
const asked = skills.find((s) => s.name === args.name);
|
|
251
|
+
return asked
|
|
252
|
+
? { content: [{ type: "text", text: asked.text }] }
|
|
253
|
+
: refused(`name: one of ${skills.map((s) => s.name).join(", ")}`);
|
|
254
|
+
},
|
|
255
|
+
},
|
|
256
|
+
];
|
|
218
257
|
for (const r of d.rules) {
|
|
219
258
|
// the document a call names: a kind's instance by its key (trip:1), or the one
|
|
220
259
|
const name = (args: { key?: unknown }) => (r.kind ? `${r.doc}:${args.key}` : r.doc);
|
|
@@ -223,7 +262,12 @@ export function door(d: Door) {
|
|
|
223
262
|
r.kind && !/^[1-9]\d*$/.test(String(args.key)) ? `key: which ${r.doc}, a whole number` : null;
|
|
224
263
|
if (!r.kind && (await d.holds(r.doc, who.member))) continue;
|
|
225
264
|
const key = r.kind
|
|
226
|
-
? {
|
|
265
|
+
? {
|
|
266
|
+
key: {
|
|
267
|
+
type: "integer",
|
|
268
|
+
description: `which ${r.doc}: the id of one of the ${r.kind.root} in ${r.kind.doc}`,
|
|
269
|
+
},
|
|
270
|
+
}
|
|
227
271
|
: {};
|
|
228
272
|
const colls = Object.entries(r.collections)
|
|
229
273
|
.filter(([, c]) => !c.own)
|
|
@@ -255,6 +299,22 @@ export function door(d: Door) {
|
|
|
255
299
|
// an op's path as it's said: an add by a first step, what it gives
|
|
256
300
|
const said = (o: (typeof ops)[number]) => `${o.path}${o.gives ? ` giving ${o.gives}` : ""}`;
|
|
257
301
|
if (r.type !== "shared" || !ops.length) continue;
|
|
302
|
+
const opsOfWrite = {
|
|
303
|
+
type: "array",
|
|
304
|
+
minItems: 1,
|
|
305
|
+
items: {
|
|
306
|
+
anyOf: ops.map((o) => ({
|
|
307
|
+
type: "object",
|
|
308
|
+
properties: {
|
|
309
|
+
op: { type: "string", enum: [o.op] },
|
|
310
|
+
path: { type: "string", pattern: o.pattern, description: said(o) },
|
|
311
|
+
...(o.value ? { value: o.value } : {}),
|
|
312
|
+
},
|
|
313
|
+
required: ["op", "path", ...(o.value ? ["value"] : [])],
|
|
314
|
+
})),
|
|
315
|
+
},
|
|
316
|
+
};
|
|
317
|
+
const why = { type: "string", description: "why, in a few words, where it helps those who read it" };
|
|
258
318
|
tools.push({
|
|
259
319
|
name: `write_${r.doc}`,
|
|
260
320
|
description: `One write to ${r.doc}, whole or not at all, told to every page at once: its ops, each one of ${ops.map((o) => `${o.op} ${said(o)}`).join(", ")}. {id} is an item's id, as read_${r.doc} shows it. Done answers with its version and the ids of what it added; refused, with why.`,
|
|
@@ -262,22 +322,8 @@ export function door(d: Door) {
|
|
|
262
322
|
type: "object",
|
|
263
323
|
properties: {
|
|
264
324
|
...key,
|
|
265
|
-
ops:
|
|
266
|
-
|
|
267
|
-
minItems: 1,
|
|
268
|
-
items: {
|
|
269
|
-
anyOf: ops.map((o) => ({
|
|
270
|
-
type: "object",
|
|
271
|
-
properties: {
|
|
272
|
-
op: { type: "string", enum: [o.op] },
|
|
273
|
-
path: { type: "string", pattern: o.pattern, description: said(o) },
|
|
274
|
-
...(o.value ? { value: o.value } : {}),
|
|
275
|
-
},
|
|
276
|
-
required: ["op", "path", ...(o.value ? ["value"] : [])],
|
|
277
|
-
})),
|
|
278
|
-
},
|
|
279
|
-
},
|
|
280
|
-
why: { type: "string", description: "why, in a few words, where it helps those who read it" },
|
|
325
|
+
ops: opsOfWrite,
|
|
326
|
+
why,
|
|
281
327
|
},
|
|
282
328
|
required: [...Object.keys(key), "ops"],
|
|
283
329
|
},
|
|
@@ -298,22 +344,56 @@ export function door(d: Door) {
|
|
|
298
344
|
return "why" in w ? refused(w.why) : answered(w);
|
|
299
345
|
},
|
|
300
346
|
});
|
|
347
|
+
// a file it names comes by a link the server makes: the agent never sees its own key, the server does
|
|
348
|
+
if (!d.upload || !Object.values(r.collections).some((c) => Object.values(c.fields).includes("file"))) continue;
|
|
349
|
+
const upload = d.upload;
|
|
350
|
+
tools.push({
|
|
351
|
+
name: `upload_${r.doc}`,
|
|
352
|
+
description: `A link to send one file to ${r.doc} by, made for you (you never see your key; the server does): good once, for 15 minutes, a photo, an SVG, a PDF or a Markdown file under 20 MB. POST the file's bytes to its url, answered its value (file:<sha256>.<ext>) to put in a write; or, where you can't reach the site, give the url to your person to open and choose the file. With ops, the write it's for, "$file" in a value standing for the file, that write is made as yours once the file is in, and the url answers it.`,
|
|
353
|
+
inputSchema: {
|
|
354
|
+
type: "object",
|
|
355
|
+
properties: {
|
|
356
|
+
...key,
|
|
357
|
+
name: {
|
|
358
|
+
type: "string",
|
|
359
|
+
description: "the file's name, as receipt.pdf (a Markdown file is known by its .md)",
|
|
360
|
+
},
|
|
361
|
+
ops: { ...opsOfWrite, description: 'the write it\'s for, made once the file is in: "$file" stands for it' },
|
|
362
|
+
why,
|
|
363
|
+
},
|
|
364
|
+
required: Object.keys(key),
|
|
365
|
+
},
|
|
366
|
+
annotations: { readOnlyHint: false, destructiveHint: false },
|
|
367
|
+
run: async (args) => {
|
|
368
|
+
if (args.ops !== undefined && (!Array.isArray(args.ops) || !args.ops.length || !args.ops.every(isOp)))
|
|
369
|
+
return refused(OPS);
|
|
370
|
+
const no = unkeyed(args) ?? (await d.holds(name(args), who.member));
|
|
371
|
+
if (no) return refused(no);
|
|
372
|
+
const made = await upload(origin, name(args), d.anyone ? null : who, String(args.name ?? ""), {
|
|
373
|
+
...(args.ops ? { ops: texted(r, args.ops) } : {}),
|
|
374
|
+
...(typeof args.why === "string" && args.why.trim() ? { why: args.why.trim() } : {}),
|
|
375
|
+
});
|
|
376
|
+
return "why" in made ? refused(made.why) : answered(made);
|
|
377
|
+
},
|
|
378
|
+
});
|
|
301
379
|
}
|
|
302
380
|
return tools;
|
|
303
381
|
}
|
|
304
382
|
|
|
305
383
|
/** One message, in its era: answered, or a notification (no id), which isn't. A modern answer says it's complete,
|
|
306
384
|
* and where it may be kept a while, for how long (none: the grants can change) and for whom. */
|
|
307
|
-
async function one(m: Message, who: Who, modern: boolean) {
|
|
385
|
+
async function one(m: Message, who: Who, modern: boolean, origin: string) {
|
|
308
386
|
if (m.id === undefined) return null;
|
|
309
387
|
const done = (result: object, kept?: "public" | "private") =>
|
|
310
388
|
rpc(
|
|
311
389
|
m.id,
|
|
312
390
|
modern ? { resultType: "complete", ...result, ...(kept ? { ttlMs: 0, cacheScope: kept } : {}) } : result,
|
|
313
391
|
);
|
|
314
|
-
// to
|
|
315
|
-
const
|
|
316
|
-
|
|
392
|
+
// the same few lines to every client: who the agent acts as, its member by id, so a document naming members is read
|
|
393
|
+
const as = d.anyone
|
|
394
|
+
? "anyone, as a stranger's page does"
|
|
395
|
+
: `member ${who.member}, by the link called ${JSON.stringify(who.agent?.label)}`;
|
|
396
|
+
const instructions = opening(apps, docs, as);
|
|
317
397
|
if (modern && m.method === "server/discover")
|
|
318
398
|
return done(
|
|
319
399
|
{
|
|
@@ -332,20 +412,21 @@ export function door(d: Door) {
|
|
|
332
412
|
instructions,
|
|
333
413
|
});
|
|
334
414
|
if (!modern && m.method === "ping") return rpc(m.id, {});
|
|
335
|
-
|
|
415
|
+
const asked = skillAt(m.params?.uri);
|
|
416
|
+
if (m.method === "resources/list") return done({ resources: skills.map((s) => s.resource) }, "public");
|
|
336
417
|
if (m.method === "resources/read")
|
|
337
|
-
return
|
|
338
|
-
? done({ contents: [{ uri:
|
|
418
|
+
return asked
|
|
419
|
+
? done({ contents: [{ uri: asked.uri, mimeType: "text/markdown", text: asked.text }] }, "public")
|
|
339
420
|
: fail(m.id, -32602, `there's no resource at ${m.params?.uri}`);
|
|
340
|
-
if (modern && m.method === "skills/list") return done({ skills:
|
|
421
|
+
if (modern && m.method === "skills/list") return done({ skills: skills.map((s) => s.entry) }, "public");
|
|
341
422
|
if (modern && m.method === "skills/get")
|
|
342
|
-
return
|
|
343
|
-
? done({ skill:
|
|
423
|
+
return asked
|
|
424
|
+
? done({ skill: asked.entry }, "public")
|
|
344
425
|
: fail(m.id, -32602, `No skill is served at ${m.params?.uri}`);
|
|
345
426
|
if (m.method === "tools/list")
|
|
346
|
-
return done({ tools: (await toolsFor(who)).map(({ run: _, ...t }) => t) }, "private");
|
|
427
|
+
return done({ tools: (await toolsFor(who, origin)).map(({ run: _, ...t }) => t) }, "private");
|
|
347
428
|
if (m.method === "tools/call") {
|
|
348
|
-
const tool = (await toolsFor(who)).find((t) => t.name === m.params?.name);
|
|
429
|
+
const tool = (await toolsFor(who, origin)).find((t) => t.name === m.params?.name);
|
|
349
430
|
return tool
|
|
350
431
|
? done(await tool.run(m.params.arguments ?? {}))
|
|
351
432
|
: fail(m.id, -32602, `no tool called ${m.params?.name}`);
|
|
@@ -401,7 +482,9 @@ export function door(d: Door) {
|
|
|
401
482
|
);
|
|
402
483
|
}
|
|
403
484
|
// never thrown: Bun's line for a request that throws names its URL, and the URL holds the agent's token
|
|
404
|
-
|
|
485
|
+
// where the door was asked, as a link it makes is said: the site's, behind its proxy too
|
|
486
|
+
const origin = `${schemeOf(req)}://${new URL(req.url).host}`;
|
|
487
|
+
const answer = await one(m, who!, version !== undefined, origin).catch((e) => {
|
|
405
488
|
console.error("the MCP door failed:", e);
|
|
406
489
|
return fail(m.id ?? null, -32603, "That wasn't done: the server had a problem with it.");
|
|
407
490
|
});
|
package/src/server.ts
CHANGED
|
@@ -23,6 +23,7 @@ import { doc as GROUP } from "./members/generated/rules.ts";
|
|
|
23
23
|
import { groupOf, say, type Data, type Who } from "./members/group.ts";
|
|
24
24
|
import { fromHere } from "./members/demo.ts";
|
|
25
25
|
import { door, type Written } from "./mcp.ts";
|
|
26
|
+
import { filled, uploads, type Uploads } from "./upload.ts";
|
|
26
27
|
import { bdflOf, type Asked, type Member } from "./members/trust.ts";
|
|
27
28
|
import {
|
|
28
29
|
attribute,
|
|
@@ -46,7 +47,7 @@ export { Refused };
|
|
|
46
47
|
export type { Reactions, Read, Trust };
|
|
47
48
|
import { upkeep, KEEP } from "./upkeep.ts";
|
|
48
49
|
import { folderOf } from "./file-value.ts";
|
|
49
|
-
import { filesAt, letGo, named, putsFile, routes as fileRoutes, type Files } from "./files.ts";
|
|
50
|
+
import { filesAt, keep, letGo, named, putsFile, routes as fileRoutes, type Files } from "./files.ts";
|
|
50
51
|
import { version } from "../package.json";
|
|
51
52
|
|
|
52
53
|
/** How many documents a page holds at once (each write views every one held): past it, one is let go first. */
|
|
@@ -147,8 +148,17 @@ const ICON = `${import.meta.dir}/icon.png`;
|
|
|
147
148
|
|
|
148
149
|
/** A write by the server itself, a route's or a job's: shaped as the stories say, but asked of no roles and no
|
|
149
150
|
* trust.ts, since it's the app's own; landed with what follows from it, and told. Its change, or Refused, once it
|
|
150
|
-
* has (await it). A route reads what it needs before it writes.
|
|
151
|
-
|
|
151
|
+
* has (await it). A route reads what it needs before it writes. Given `as`, it's a member's write in place of the
|
|
152
|
+
* server's (a paper a mail brought, its member's), made as an agent's is: under their grants, the app's trust and the
|
|
153
|
+
* group's, via the label it names, so every page says whose it is and how it came ("Peter via mail"); and with a file,
|
|
154
|
+
* the file kept first, as a page's is, where its member may put one, "$file" in the ops standing for it. Answered
|
|
155
|
+
* done, with its version, the ids it added, and the file's value; or Refused. */
|
|
156
|
+
export type Write = {
|
|
157
|
+
(doc: string, ops: Op[]): Promise<Change>;
|
|
158
|
+
(doc: string, ops: Op[], as: As): Promise<Written & { done: true; file?: string }>;
|
|
159
|
+
};
|
|
160
|
+
/** Whose a route's write is: a member of the group, via what (its label, as an agent's), why, and a file it brings. */
|
|
161
|
+
export type As = { member: number; via: string; why?: string; file?: { bytes: Uint8Array; name: string } };
|
|
152
162
|
/** A derived document (its app's derive.ts, exported from its routes.ts): what it is now, for a member (nobody, 0),
|
|
153
163
|
* read off the documents it's derived from. Read-only: its pages write the documents it's read from. */
|
|
154
164
|
export type Derive = (read: Read, member: number) => Record<string, { id: number }[]>;
|
|
@@ -187,8 +197,10 @@ type App = {
|
|
|
187
197
|
routes?: Routes | ((read: Read, write: Write) => Routes);
|
|
188
198
|
/** Routes anyone may ask, reading each document as nobody (member 0): owns and sees apply, so a part only some see
|
|
189
199
|
* isn't there, but the group's door doesn't, so a document any member sees whole is whole. An open route shows only
|
|
190
|
-
* what it picks, and what it picks is public.
|
|
191
|
-
|
|
200
|
+
* what it picks, and what it picks is public. One that checks a secret of its own (a mail's intake, a webhook) is
|
|
201
|
+
* given the server's write, and `whole`, each document as the server holds it, every item: what it answers is still
|
|
202
|
+
* its own to pick. */
|
|
203
|
+
open?: Open | ((read: Read, write: Write, whole: Read) => Open);
|
|
192
204
|
trust?: Trust;
|
|
193
205
|
reactions?: Reactions;
|
|
194
206
|
derive?: Derive;
|
|
@@ -461,7 +473,8 @@ export async function start({
|
|
|
461
473
|
const may = await asking;
|
|
462
474
|
if (fresh(ws, `may ${doc}`, JSON.stringify(may))) say(ws, { doc, may });
|
|
463
475
|
}
|
|
464
|
-
const write
|
|
476
|
+
const write = (async (doc: string, ops: Op[], as?: As) => {
|
|
477
|
+
if (as) return writeAs(doc, ops, as);
|
|
465
478
|
wrote();
|
|
466
479
|
if (docParts(doc).name === GROUP || !(await store.exists(doc))) throw new Refused(`the server can't write ${doc}`);
|
|
467
480
|
const why = await ungranted(doc, ops, null);
|
|
@@ -470,6 +483,23 @@ export async function start({
|
|
|
470
483
|
await tell(landed);
|
|
471
484
|
retime();
|
|
472
485
|
return landed.changes[0]!;
|
|
486
|
+
}) as Write;
|
|
487
|
+
/** A route's write as a member, via its label (Write's `as`): a member of the group still, the file kept first. */
|
|
488
|
+
const writeAs = async (doc: string, ops: Op[], as: As) => {
|
|
489
|
+
if (!members || !((await read(GROUP)).members as Member[]).some((m) => m.id === as.member))
|
|
490
|
+
throw new Refused(`member ${as.member} isn't in the group`);
|
|
491
|
+
const who: Who = { member: as.member, token: "", agent: { id: `via ${as.via}`, member: as.member, label: as.via } };
|
|
492
|
+
let file: string | undefined;
|
|
493
|
+
if (as.file) {
|
|
494
|
+
const no = await mayPutAs(doc, who);
|
|
495
|
+
if (no) throw new Refused(no);
|
|
496
|
+
const kept = await keep(filesKept, as.file.bytes, as.file.name, (await apart(doc)) ? folderOf(doc) : "");
|
|
497
|
+
if ("refused" in kept) throw new Refused(kept.refused);
|
|
498
|
+
file = kept.file;
|
|
499
|
+
}
|
|
500
|
+
const w = await written([{ doc, ops: file ? filled(ops, file) : ops, ...(as.why ? { why: as.why } : {}) }], who);
|
|
501
|
+
if ("why" in w) throw new Refused(w.why);
|
|
502
|
+
return file ? { ...w, file } : w;
|
|
473
503
|
};
|
|
474
504
|
/** A change undone: its inverse, guarded as delta's walk is (refused if a value it changed has been changed
|
|
475
505
|
* since), written as the server's own write, by whoever undoes it, and told as any change is; what the rules
|
|
@@ -545,15 +575,27 @@ export async function start({
|
|
|
545
575
|
holds: mayRead,
|
|
546
576
|
read: asMember,
|
|
547
577
|
write: (doc: string, ops: Op[], why: string | undefined, who: Who | null) => written([{ doc, ops, why }], who),
|
|
548
|
-
|
|
578
|
+
// each app's words and documents, for its skill (src/skill.ts)
|
|
579
|
+
apps: apps.flatMap((a) => {
|
|
580
|
+
const docs = docsOf(a)
|
|
581
|
+
.map((r) => r.doc)
|
|
582
|
+
.filter((doc) => doc !== GROUP && rules[doc]);
|
|
583
|
+
return docs.length || a.instructions
|
|
584
|
+
? [{ app: a.app || basename(dir), words: a.instructions?.trim() ?? "", docs }]
|
|
585
|
+
: [];
|
|
586
|
+
}),
|
|
587
|
+
upload: (...asked: Parameters<Uploads["link"]>) => uploading.link(...asked),
|
|
549
588
|
version,
|
|
550
589
|
};
|
|
551
590
|
/** Why someone may not send a file for a document (src/files.ts), or null: they may hold it, and may put a file in
|
|
552
591
|
* it (an add to a collection with a file field, or its replace), as a member by their link or a guest by its code. */
|
|
553
592
|
const mayPut = async (req: Request, doc: string) => {
|
|
554
593
|
if (anotherSite(req)) return "another site";
|
|
555
|
-
const signed = await group.at(req)
|
|
556
|
-
|
|
594
|
+
const signed = await group.at(req);
|
|
595
|
+
return mayPutAs(doc, signed instanceof Response ? null : signed);
|
|
596
|
+
};
|
|
597
|
+
/** The same, for whoever's known already: a member's agent by an upload link (src/upload.ts). */
|
|
598
|
+
const mayPutAs = async (doc: string, who: Who | null) => {
|
|
557
599
|
if (!(await store.exists(doc))) return `there's no document called ${doc}`;
|
|
558
600
|
return (
|
|
559
601
|
(await mayHold(doc, who?.member ?? null, !(members && rootToken))) ??
|
|
@@ -582,6 +624,13 @@ export async function start({
|
|
|
582
624
|
/** Whether a document's kind keeps its files apart, each instance's in a folder of its own. */
|
|
583
625
|
const apart = async (doc: string) =>
|
|
584
626
|
((await exists(doc)) || (await store.exists(doc))) && rulesOf(doc).kind?.files === "apart";
|
|
627
|
+
/** The links an agent at the door sends a file by, made for its member (src/upload.ts). */
|
|
628
|
+
const uploading = uploads({
|
|
629
|
+
files: filesKept,
|
|
630
|
+
mayPut: mayPutAs,
|
|
631
|
+
apart,
|
|
632
|
+
write: (doc, ops, why, who) => written([{ doc, ops, why }], who),
|
|
633
|
+
});
|
|
585
634
|
const routes: Routes = {
|
|
586
635
|
"/health": () => new Response("ok"),
|
|
587
636
|
"/version": () => Response.json({ joined: version, build }),
|
|
@@ -645,6 +694,8 @@ export async function start({
|
|
|
645
694
|
...(members ? {} : { "/mcp": mine(door({ ...agents, anyone: true })) }),
|
|
646
695
|
// a file a document names: sent by whoever may put one in it, kept by its hash, and served for good
|
|
647
696
|
...fileRoutes(filesKept, mayPut, mayHoldFiles, apart),
|
|
697
|
+
// and one sent by an agent's upload link, made for its member at the door
|
|
698
|
+
...uploading.routes,
|
|
648
699
|
};
|
|
649
700
|
const bundles = `/_page-${crypto.randomUUID()}`;
|
|
650
701
|
// an app's routes read the documents at once, as its rules do: each handler is run in settle, again until every
|
|
@@ -676,7 +727,7 @@ export async function start({
|
|
|
676
727
|
// door doesn't), so each shows only what it picks
|
|
677
728
|
const nobody: Read = (doc) => now(doc, 0);
|
|
678
729
|
for (const { app, open: of = {} } of apps)
|
|
679
|
-
for (const [path, answer] of Object.entries(typeof of === "function" ? of(nobody) : of)) {
|
|
730
|
+
for (const [path, answer] of Object.entries(typeof of === "function" ? of(nobody, write, now) : of)) {
|
|
680
731
|
if (path in routes) throw new Error(`${app || "the root"} and another app both answer ${path}`);
|
|
681
732
|
routes[path] = typeof answer === "function" ? settled(answer) : answer;
|
|
682
733
|
}
|
package/src/skill.ts
CHANGED
|
@@ -1,40 +1,116 @@
|
|
|
1
|
-
// The door's
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
1
|
+
// The door's skills, served as MCP's skills extension (SEP-2640, io.modelcontextprotocol/skills) says: each SKILL.md a
|
|
2
|
+
// resource at skill://<name>/SKILL.md, and its entry (its frontmatter as written, each file's sha256 digest and size)
|
|
3
|
+
// for skills/list and skills/get. The door's own (.claude/skills/joined-door): how any joined document is read and
|
|
4
|
+
// written, one text read from its file, never kept apart from it. And each
|
|
5
|
+
// app's: what its documents hold and mean, its own words (its routes.ts's `instructions`) and its documents' shapes,
|
|
6
|
+
// written from their compiled rules as their tools are, so it says what the app holds and never another thing. What the
|
|
7
|
+
// door says as it opens says none of it: where they are, and who's acting.
|
|
6
8
|
|
|
7
9
|
import { createHash } from "node:crypto";
|
|
10
|
+
import type { Rules } from "./write.ts";
|
|
8
11
|
|
|
9
12
|
/** The extension's name, as a server declares it among its capabilities' extensions. */
|
|
10
13
|
export const SKILLS = "io.modelcontextprotocol/skills";
|
|
11
14
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
|
|
21
|
-
uri
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
/** A skills/list entry, and skills/get's: its one file is its SKILL.md. */
|
|
25
|
-
entry: {
|
|
26
|
-
uri,
|
|
27
|
-
frontmatter,
|
|
28
|
-
resources: [{ uri, digest: `sha256:${createHash("sha256").update(bytes).digest("hex")}`, size: bytes.length }],
|
|
29
|
-
},
|
|
30
|
-
/** It as resources/list names it. */
|
|
31
|
-
resource: {
|
|
32
|
-
uri,
|
|
15
|
+
/** A skill as the door serves it: its SKILL.md whole, the words below its frontmatter, and how the extension and a
|
|
16
|
+
* resource say it. */
|
|
17
|
+
export type Skill = ReturnType<typeof served>;
|
|
18
|
+
|
|
19
|
+
/** A skill, from its SKILL.md. */
|
|
20
|
+
function served(text: string) {
|
|
21
|
+
const [, front = "", body = ""] = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text) ?? [];
|
|
22
|
+
/** Its frontmatter, as YAML reads it: its name and description, and whatever else it says. */
|
|
23
|
+
const frontmatter = Bun.YAML.parse(front) as { name: string; description: string };
|
|
24
|
+
const uri = `skill://${frontmatter.name}/SKILL.md`,
|
|
25
|
+
bytes = new TextEncoder().encode(text);
|
|
26
|
+
return {
|
|
33
27
|
name: frontmatter.name,
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
28
|
+
uri,
|
|
29
|
+
text,
|
|
30
|
+
body: body.trim(),
|
|
31
|
+
/** A skills/list entry, and skills/get's: its one file is its SKILL.md. */
|
|
32
|
+
entry: {
|
|
33
|
+
uri,
|
|
34
|
+
frontmatter,
|
|
35
|
+
resources: [{ uri, digest: `sha256:${createHash("sha256").update(bytes).digest("hex")}`, size: bytes.length }],
|
|
36
|
+
},
|
|
37
|
+
/** It as resources/list names it. */
|
|
38
|
+
resource: {
|
|
39
|
+
uri,
|
|
40
|
+
name: frontmatter.name,
|
|
41
|
+
description: frontmatter.description,
|
|
42
|
+
mimeType: "text/markdown",
|
|
43
|
+
size: bytes.length,
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The door's own skill. */
|
|
49
|
+
export const skill = served(await Bun.file(new URL("../.claude/skills/joined-door/SKILL.md", import.meta.url)).text());
|
|
50
|
+
|
|
51
|
+
/** What the door says as it opens, to every client alike: short, so no client cuts it, and nothing a skill says, so
|
|
52
|
+
* each fact is in one place. Its documents, who's acting, and where the skills are: as the client loads skills, or by
|
|
53
|
+
* read_skill, a tool, which every client loads. */
|
|
54
|
+
export const opening = (apps: Skill[], docs: string[], as: string) =>
|
|
55
|
+
[
|
|
56
|
+
`This is a joined app's door: its documents are ${docs.join(", ") || "none"}. You act as ${as}.`,
|
|
57
|
+
`How any document here is read and written is the skill ${skill.name}${
|
|
58
|
+
apps.length
|
|
59
|
+
? `, and what each app's documents hold and mean is its own skill: ${apps.map((a) => a.name).join(", ")}`
|
|
60
|
+
: ""
|
|
61
|
+
}. Load ${apps.length ? "them" : "it"} before a write, as your client loads skills, or by read_skill.`,
|
|
62
|
+
"Read before you write; a write is made whole or not at all.",
|
|
63
|
+
].join(" ");
|
|
64
|
+
|
|
65
|
+
type Collection = Rules["collections"][string] & { needs?: readonly string[] };
|
|
66
|
+
|
|
67
|
+
/** A collection's fields, as an agent reads them: each its type, a link what it's an id of, and what an add needs. */
|
|
68
|
+
const fieldsOf = (c: Collection) =>
|
|
69
|
+
Object.entries(c.fields)
|
|
70
|
+
.filter(([f]) => !(f in (c.fills ?? {})))
|
|
71
|
+
.map(([f, t]) => {
|
|
72
|
+
const to = c.links?.[f];
|
|
73
|
+
// the group's members are no document's collection: said as who they are (the door says which the agent's is)
|
|
74
|
+
const member = t === "ids" ? "members' ids, people in the group" : "a member's id, a person in the group";
|
|
75
|
+
const said = to === "members" ? member : to ? (t === "ids" ? `ids of ${to}` : `an id of ${to}`) : t;
|
|
76
|
+
return `${f} (${said}${c.needs?.includes(f) ? ", needed" : ""})`;
|
|
77
|
+
})
|
|
78
|
+
.join(", ");
|
|
79
|
+
|
|
80
|
+
/** A document's shape: its name (a kind's, by its key), its own fields, each collection's, and its tools. */
|
|
81
|
+
function shapeOf(r: Rules) {
|
|
82
|
+
const colls = Object.entries(r.collections) as [string, Collection][];
|
|
83
|
+
const files = colls.some(([, c]) => Object.values(c.fields).includes("file"));
|
|
84
|
+
const writes = r.type === "shared" && Object.keys(r.grants ?? {}).length;
|
|
85
|
+
return [
|
|
86
|
+
`## ${r.kind ? `${r.doc}:<key>` : r.doc}`,
|
|
87
|
+
"",
|
|
88
|
+
[
|
|
89
|
+
r.kind ? `One for each of the ${r.kind.root} in ${r.kind.doc}, its key that one's id.` : "",
|
|
90
|
+
`Read by read_${r.doc}${writes ? `, written by write_${r.doc}` : ", which only reads"}${
|
|
91
|
+
files && writes ? `; a file it names comes in by upload_${r.doc}` : ""
|
|
92
|
+
}.`,
|
|
93
|
+
]
|
|
94
|
+
.filter(Boolean)
|
|
95
|
+
.join(" "),
|
|
96
|
+
"",
|
|
97
|
+
...colls.map(([name, c]) => `- ${c.own ? "its own fields" : name}: ${fieldsOf(c)}`),
|
|
98
|
+
].join("\n");
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** An app's skill: its words, then what each of its documents holds. */
|
|
102
|
+
export function skillOf(app: string, words: string, rules: Rules[]): Skill {
|
|
103
|
+
const docs = rules.map((r) => (r.kind ? `${r.doc}:<key>` : r.doc)).join(", ");
|
|
104
|
+
const description = `Use when reading or writing the ${app} app's documents (${docs}): what they hold, and what they mean.`;
|
|
105
|
+
return served(
|
|
106
|
+
[
|
|
107
|
+
`---\nname: ${app}\ndescription: ${JSON.stringify(description)}\n---`,
|
|
108
|
+
`# ${app}`,
|
|
109
|
+
words,
|
|
110
|
+
"What each document holds: a field's type, a link an id of what it links to (or \"$1\", the write's first add), and what an add needs.",
|
|
111
|
+
...rules.map(shapeOf),
|
|
112
|
+
]
|
|
113
|
+
.filter(Boolean)
|
|
114
|
+
.join("\n\n") + "\n",
|
|
115
|
+
);
|
|
116
|
+
}
|
package/src/upload.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// An upload link: a file sent for a document by an agent at the MCP door, which has no page's sign-in to send one by
|
|
2
|
+
// (its member's key is in its connector's link, which it never sees: the server does). The door's upload_<doc> asks
|
|
3
|
+
// for one: a link short-lived and used once, made for the agent's member and that document alone, so whoever has it
|
|
4
|
+
// sends one file as that member could, and nothing more. POSTed the file's bytes (by an agent that can send them,
|
|
5
|
+
// Claude Code), it's kept as a page's file is (src/files.ts) and answered its value; opened in a browser, it's a page to
|
|
6
|
+
// choose the file on, for an agent in a chat whose sandbox can't reach the site: its person opens it. Where the agent
|
|
7
|
+
// said the write it's for ("$file" in a value standing for the file), that write is made as the agent's once the file
|
|
8
|
+
// is in, so the person who chose it needn't tell the agent anything. Kept in the server's memory: a restart lets every
|
|
9
|
+
// link go, as it does whatever was being answered.
|
|
10
|
+
|
|
11
|
+
import { folderOf, MOST, TOO_BIG } from "./file-value.ts";
|
|
12
|
+
import { keep, upTo, type Files } from "./files.ts";
|
|
13
|
+
import type { Written } from "./mcp.ts";
|
|
14
|
+
import type { Who } from "./members/group.ts";
|
|
15
|
+
import type { Op } from "./ops.ts";
|
|
16
|
+
|
|
17
|
+
/** How long a link is good for, in ms. */
|
|
18
|
+
export const GOOD_FOR = 15 * 60_000;
|
|
19
|
+
/** What stands for the file in the write a link is for. */
|
|
20
|
+
export const FILE = "$file";
|
|
21
|
+
|
|
22
|
+
/** What makes the links, and is sent their files: who may put a file in a document, and how it's written (by a
|
|
23
|
+
* member's agent, or nobody, at a door that's anyone's). */
|
|
24
|
+
type Uploading = {
|
|
25
|
+
files: Files;
|
|
26
|
+
/** Why a member may not put a file in a document, or null. */
|
|
27
|
+
mayPut(doc: string, who: Who | null): Promise<string | null>;
|
|
28
|
+
/** Whether a document's kind keeps its files apart. */
|
|
29
|
+
apart(doc: string): Promise<boolean>;
|
|
30
|
+
write(doc: string, ops: Op[], why: string | undefined, who: Who | null): Promise<Written>;
|
|
31
|
+
};
|
|
32
|
+
type Link = { doc: string; who: Who | null; name: string; until: number; ops?: Op[]; why?: string; busy?: boolean };
|
|
33
|
+
/** A link made: its address, and till when (ISO); or why not. */
|
|
34
|
+
export type Made = { url: string; until: string } | { why: string };
|
|
35
|
+
|
|
36
|
+
/** A write's ops with the file's value where "$file" stood. */
|
|
37
|
+
export const filled = (ops: Op[], file: string): Op[] =>
|
|
38
|
+
JSON.parse(JSON.stringify(ops), (_, v) => (v === FILE ? file : v));
|
|
39
|
+
|
|
40
|
+
const escaped = (s: string) =>
|
|
41
|
+
s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!);
|
|
42
|
+
|
|
43
|
+
/** The page a link opens in a browser: the file chosen, sent, and what came of it said. */
|
|
44
|
+
const page = (l: Link) => `<!doctype html>
|
|
45
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
46
|
+
<meta name="color-scheme" content="light dark"><title>A file for your agent</title>
|
|
47
|
+
<style>
|
|
48
|
+
body{font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:0 auto;padding:2rem 1rem}
|
|
49
|
+
h1{font-size:1.25rem;margin:0 0 .5rem}p{margin:.5rem 0}
|
|
50
|
+
label{display:block;border:2px dashed currentColor;border-radius:12px;padding:2rem 1rem;text-align:center;cursor:pointer;opacity:.8}
|
|
51
|
+
label:hover{opacity:1}input,[hidden]{display:none}#said{font-weight:600}
|
|
52
|
+
</style></head><body>
|
|
53
|
+
<h1>Your agent asked for ${escaped(l.name || "a file")}</h1>
|
|
54
|
+
<p>Choose it here${l.ops ? ", and it's put where your agent said" : ", and your agent has it"}. It goes to ${escaped(l.doc)}.</p>
|
|
55
|
+
<label>Choose the file, or drop it here<input type="file" accept="image/*,.pdf,.svg,.md"></label>
|
|
56
|
+
<p id="said" role="status"></p>
|
|
57
|
+
<script>
|
|
58
|
+
const said = document.getElementById("said"), input = document.querySelector("input");
|
|
59
|
+
async function send(file) {
|
|
60
|
+
said.textContent = "Sending " + file.name + "…";
|
|
61
|
+
const r = await fetch(location.pathname, { method: "POST", body: file }).catch(() => null);
|
|
62
|
+
const a = r && (await r.json().catch(() => null));
|
|
63
|
+
said.textContent = !a ? "That wasn't sent: try again." : a.refused ? a.refused : a.why ? "It's kept, but not put in: " + a.why : "Done: " + file.name + " is in. You can close this page.";
|
|
64
|
+
// sent: the link's used, so there's nothing more to choose
|
|
65
|
+
if (a && a.file) document.querySelector("label").hidden = true;
|
|
66
|
+
}
|
|
67
|
+
input.onchange = () => input.files[0] && send(input.files[0]);
|
|
68
|
+
document.body.ondragover = (e) => e.preventDefault();
|
|
69
|
+
document.body.ondrop = (e) => { e.preventDefault(); const f = e.dataTransfer.files[0]; f && send(f); };
|
|
70
|
+
</script></body></html>`;
|
|
71
|
+
|
|
72
|
+
/** The links: made for an agent at the door, and the route that's sent their files. */
|
|
73
|
+
export function uploads(d: Uploading, now = Date.now) {
|
|
74
|
+
const links = new Map<string, Link>();
|
|
75
|
+
/** A link still good, or none: one past its time is let go as it's asked for. */
|
|
76
|
+
const good = (nonce: string) => {
|
|
77
|
+
const l = links.get(nonce);
|
|
78
|
+
if (l && l.until > now()) return l;
|
|
79
|
+
links.delete(nonce);
|
|
80
|
+
return undefined;
|
|
81
|
+
};
|
|
82
|
+
const gone = () => Response.json({ refused: "That link has gone: ask your agent for another." }, { status: 404 });
|
|
83
|
+
return {
|
|
84
|
+
/** A link for an agent's member to send one file for a document, at the site the door was asked at. */
|
|
85
|
+
async link(origin: string, doc: string, who: Who | null, name: string, then: { ops?: Op[]; why?: string } = {}) {
|
|
86
|
+
const no = await d.mayPut(doc, who);
|
|
87
|
+
if (no) return { why: no } satisfies Made;
|
|
88
|
+
for (const [n, l] of links) if (l.until <= now()) links.delete(n);
|
|
89
|
+
const nonce = crypto.randomUUID().replaceAll("-", "") + crypto.randomUUID().replaceAll("-", ""),
|
|
90
|
+
until = now() + GOOD_FOR;
|
|
91
|
+
links.set(nonce, { doc, who, name, until, ...then });
|
|
92
|
+
return { url: `${origin}/upload/${nonce}`, until: new Date(until).toISOString() } satisfies Made;
|
|
93
|
+
},
|
|
94
|
+
routes: {
|
|
95
|
+
"/upload/:nonce": {
|
|
96
|
+
GET: (req: Request & { params: { nonce: string } }) => {
|
|
97
|
+
const l = good(req.params.nonce);
|
|
98
|
+
return l
|
|
99
|
+
? new Response(page(l), {
|
|
100
|
+
headers: {
|
|
101
|
+
"content-type": "text/html;charset=utf-8",
|
|
102
|
+
"cache-control": "no-store",
|
|
103
|
+
"content-security-policy": "frame-ancestors 'none'; base-uri 'none'; object-src 'none'",
|
|
104
|
+
"referrer-policy": "no-referrer",
|
|
105
|
+
},
|
|
106
|
+
})
|
|
107
|
+
: new Response("That link has gone: ask your agent for another.", { status: 404 });
|
|
108
|
+
},
|
|
109
|
+
async POST(req: Request & { params: { nonce: string } }) {
|
|
110
|
+
const l = good(req.params.nonce);
|
|
111
|
+
if (!l) return gone();
|
|
112
|
+
if (l.busy) return Response.json({ refused: "A file is being sent by this link already." }, { status: 409 });
|
|
113
|
+
if (Number(req.headers.get("content-length")) > MOST)
|
|
114
|
+
return Response.json({ refused: TOO_BIG }, { status: 413 });
|
|
115
|
+
l.busy = true;
|
|
116
|
+
try {
|
|
117
|
+
const bytes = await upTo(req, MOST);
|
|
118
|
+
if (!bytes) return Response.json({ refused: TOO_BIG }, { status: 413 });
|
|
119
|
+
// asked again as it's sent: what the member may do can have changed since the link was made
|
|
120
|
+
const no = await d.mayPut(l.doc, l.who);
|
|
121
|
+
if (no) return Response.json({ refused: no }, { status: 403 });
|
|
122
|
+
const kept = await keep(d.files, bytes, l.name, (await d.apart(l.doc)) ? folderOf(l.doc) : "");
|
|
123
|
+
if ("refused" in kept) return Response.json(kept, { status: 422 });
|
|
124
|
+
// used: a link sends one file
|
|
125
|
+
links.delete(req.params.nonce);
|
|
126
|
+
if (!l.ops) return Response.json(kept);
|
|
127
|
+
const w = await d.write(l.doc, filled(l.ops, kept.file), l.why, l.who);
|
|
128
|
+
return Response.json({ ...kept, ...w }, { status: "why" in w ? 422 : 200 });
|
|
129
|
+
} finally {
|
|
130
|
+
l.busy = false;
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
export type Uploads = ReturnType<typeof uploads>;
|