nervur 0.20.1 → 0.20.2

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.
Files changed (131) hide show
  1. package/README.md +130 -8
  2. package/dist/browser/index.d.ts +35 -0
  3. package/dist/browser/index.js +188 -0
  4. package/dist/browser/worker.d.ts +12 -0
  5. package/dist/browser/worker.js +40 -0
  6. package/dist/browser.d.ts +1 -0
  7. package/dist/browser.js +7 -0
  8. package/dist/cli/command.d.ts +1 -1
  9. package/dist/cli/command.js +59 -16
  10. package/dist/cli/harbor.d.ts +9 -11
  11. package/dist/cli/harbor.js +81 -123
  12. package/dist/contract/index.d.ts +2 -1
  13. package/dist/contract/index.js +3 -7
  14. package/dist/edge/index.d.ts +57 -0
  15. package/dist/edge/index.js +306 -0
  16. package/dist/edge.d.ts +1 -0
  17. package/dist/edge.js +8 -0
  18. package/dist/folder/index.d.ts +4 -0
  19. package/dist/folder/index.js +57 -14
  20. package/dist/harbor/carrying.d.ts +17 -0
  21. package/dist/harbor/carrying.js +38 -0
  22. package/dist/harbor/catalogue.d.ts +2 -0
  23. package/dist/harbor/catalogue.js +28 -20
  24. package/dist/harbor/dock.d.ts +22 -3
  25. package/dist/harbor/dock.js +69 -13
  26. package/dist/harbor/harbor.d.ts +14 -4
  27. package/dist/harbor/harbor.js +144 -15
  28. package/dist/harbor/index.d.ts +6 -3
  29. package/dist/harbor/index.js +4 -1
  30. package/dist/harbor/package.d.ts +2 -0
  31. package/dist/harbor/package.js +15 -0
  32. package/dist/harbor/probe.d.ts +18 -0
  33. package/dist/harbor/probe.js +15 -0
  34. package/dist/harbor/registry.d.ts +1 -0
  35. package/dist/harbor/registry.js +11 -0
  36. package/dist/harbor/relay.d.ts +15 -0
  37. package/dist/harbor/relay.js +387 -0
  38. package/dist/harbor/root-line.js +4 -2
  39. package/dist/harbor/terrain.d.ts +12 -0
  40. package/dist/harbor/terrain.js +19 -0
  41. package/dist/http/index.d.ts +4 -0
  42. package/dist/http/index.js +156 -0
  43. package/dist/http/websocket.d.ts +29 -0
  44. package/dist/http/websocket.js +133 -0
  45. package/dist/index.d.ts +2 -1
  46. package/dist/index.js +8 -2
  47. package/dist/line/answer.d.ts +8 -0
  48. package/dist/line/answer.js +60 -0
  49. package/dist/line/frame.d.ts +34 -0
  50. package/dist/line/frame.js +81 -0
  51. package/dist/line/ground.d.ts +3 -0
  52. package/dist/line/ground.js +9 -0
  53. package/dist/line/index.d.ts +5 -0
  54. package/dist/line/index.js +9 -0
  55. package/dist/line/push.d.ts +7 -0
  56. package/dist/line/push.js +92 -0
  57. package/dist/line/web.d.ts +30 -0
  58. package/dist/line/web.js +181 -0
  59. package/dist/node/index.d.ts +32 -0
  60. package/dist/node/index.js +164 -0
  61. package/dist/node.d.ts +1 -0
  62. package/dist/node.js +7 -0
  63. package/dist/pointer/bodies.d.ts +2 -0
  64. package/dist/pointer/bodies.js +10 -0
  65. package/dist/pointer/world.d.ts +7 -1
  66. package/dist/pointer/world.js +6 -0
  67. package/dist/quo/address.d.ts +19 -0
  68. package/dist/quo/address.js +84 -0
  69. package/dist/quo/door.d.ts +1 -1
  70. package/dist/quo/door.js +4 -2
  71. package/dist/quo/index.d.ts +1 -0
  72. package/dist/quo/index.js +1 -0
  73. package/dist/quo/invitation.d.ts +1 -0
  74. package/dist/quo/invitation.js +9 -5
  75. package/dist/tcp/frame.d.ts +0 -4
  76. package/dist/tcp/frame.js +0 -10
  77. package/dist/tcp/index.d.ts +8 -2
  78. package/dist/tcp/index.js +123 -27
  79. package/dist/ward/index.d.ts +2 -2
  80. package/dist/ward/index.js +1 -1
  81. package/dist/ward/stance.d.ts +2 -0
  82. package/dist/ward/stance.js +3 -1
  83. package/dist/ward/ward-being.d.ts +2 -1
  84. package/dist/ward/ward-being.js +1 -1
  85. package/dist/ward/ward.d.ts +7 -0
  86. package/dist/ward/ward.js +6 -0
  87. package/package.json +21 -2
  88. package/src/browser/index.ts +207 -0
  89. package/src/browser/worker.ts +66 -0
  90. package/src/browser.ts +9 -0
  91. package/src/cli/command.ts +53 -17
  92. package/src/cli/harbor.ts +82 -116
  93. package/src/contract/index.ts +11 -8
  94. package/src/edge/index.ts +359 -0
  95. package/src/edge.ts +10 -0
  96. package/src/folder/index.ts +57 -12
  97. package/src/harbor/carrying.ts +56 -0
  98. package/src/harbor/catalogue.ts +32 -17
  99. package/src/harbor/dock.ts +88 -17
  100. package/src/harbor/harbor.ts +146 -17
  101. package/src/harbor/index.ts +6 -3
  102. package/src/harbor/package.ts +16 -0
  103. package/src/harbor/probe.ts +34 -0
  104. package/src/harbor/registry.ts +11 -0
  105. package/src/harbor/relay.ts +399 -0
  106. package/src/harbor/root-line.ts +4 -1
  107. package/src/harbor/terrain.ts +28 -2
  108. package/src/http/index.ts +150 -0
  109. package/src/http/websocket.ts +124 -0
  110. package/src/index.ts +35 -2
  111. package/src/line/answer.ts +59 -0
  112. package/src/line/frame.ts +88 -0
  113. package/src/line/ground.ts +19 -0
  114. package/src/line/index.ts +9 -0
  115. package/src/line/push.ts +112 -0
  116. package/src/line/web.ts +227 -0
  117. package/src/node/index.ts +170 -0
  118. package/src/node.ts +9 -0
  119. package/src/pointer/bodies.ts +11 -0
  120. package/src/pointer/world.ts +18 -2
  121. package/src/quo/address.ts +87 -0
  122. package/src/quo/door.ts +4 -2
  123. package/src/quo/index.ts +1 -0
  124. package/src/quo/invitation.ts +10 -6
  125. package/src/stand/stand.ts +60 -21
  126. package/src/tcp/index.ts +142 -31
  127. package/src/ward/index.ts +2 -2
  128. package/src/ward/stance.ts +6 -1
  129. package/src/ward/ward-being.ts +2 -2
  130. package/src/ward/ward.ts +16 -0
  131. package/src/tcp/frame.ts +0 -78
@@ -0,0 +1,227 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Quo over the web, `quo/CARRIER-WEB.md`, on what every engine has: fetch
3
+ // and the WebSocket client.
4
+ //
5
+ // WebDialer bytes to a ward pk at an address: `http` and `https` as
6
+ // one post each, `ws` and `wss` on one held line per
7
+ // address, which many asks share
8
+ // webFaculty the web carrier as a faculty of one harbor: it dials
9
+ // every web address the harbor routes, and listens where
10
+ // its cells say, through a listener the ground hands it
11
+ //
12
+ // A post that comes back with status 200 and a body is a reply, and every
13
+ // other status is nothing. A post the network refused, or a held line
14
+ // that did not open, was not dialed. A line that carried a box and closed
15
+ // answers nothing.
16
+ import type { AskSpec, JsonObject } from '../being/index.ts';
17
+ import { concat, hex, isHex, unhex } from '../crypto/index.ts';
18
+ import { CarrierFaculty, UNDIALED, type Dialed, type Ground, type GroundFaculty } from '../harbor/index.ts';
19
+ import { webAddress, type WebAddress } from '../quo/index.ts';
20
+ import { ownerAsk } from '../ward/index.ts';
21
+ import { askBody, readBody } from './frame.ts';
22
+
23
+ export const MIN_POST = 65;
24
+ export const MAX_POST = 64 + 1_048_576;
25
+ const MAX_ID = 0xffff_ffff;
26
+
27
+ // Bytes on a buffer of their own, as a body and a message take them.
28
+ const own = (bytes: Uint8Array): Uint8Array<ArrayBuffer> => new Uint8Array(bytes);
29
+
30
+ // One held line to one address.
31
+ class HeldLine {
32
+ readonly #socket: WebSocket;
33
+ readonly #waiting = new Map<number, (box: Uint8Array | null) => void>();
34
+ #next = 1;
35
+
36
+ private constructor(socket: WebSocket) {
37
+ this.#socket = socket;
38
+ socket.binaryType = 'arraybuffer';
39
+ socket.addEventListener('message', (e: MessageEvent) => {
40
+ const frame = typeof e.data === 'string' ? null : readBody(new Uint8Array(e.data as ArrayBuffer));
41
+ if (frame === null) return this.close();
42
+ if (frame.kind === 'ask') return;
43
+ const done = this.#waiting.get(frame.id);
44
+ this.#waiting.delete(frame.id);
45
+ done?.(frame.kind === 'reply' ? frame.box : null);
46
+ });
47
+ socket.addEventListener('close', () => {
48
+ for (const done of this.#waiting.values()) done(null);
49
+ this.#waiting.clear();
50
+ });
51
+ }
52
+
53
+ // A line that opened with the subprotocol `quo`, or null.
54
+ static open(href: string, onClose: () => void): Promise<HeldLine | null> {
55
+ return new Promise((resolve) => {
56
+ let socket: WebSocket;
57
+ try {
58
+ socket = new WebSocket(href, 'quo');
59
+ } catch {
60
+ resolve(null);
61
+ return;
62
+ }
63
+ const line = new HeldLine(socket);
64
+ socket.addEventListener('open', () => (socket.protocol === 'quo' ? resolve(line) : (socket.close(), resolve(null))));
65
+ socket.addEventListener('close', () => {
66
+ onClose();
67
+ resolve(null);
68
+ });
69
+ socket.addEventListener('error', () => resolve(null));
70
+ });
71
+ }
72
+
73
+ ask(pk: Uint8Array, box: Uint8Array): Promise<Uint8Array | null> {
74
+ if (this.#socket.readyState !== WebSocket.OPEN) return Promise.resolve(null);
75
+ const id = this.#next;
76
+ this.#next = this.#next === MAX_ID ? 1 : this.#next + 1;
77
+ return new Promise((resolve) => {
78
+ this.#waiting.set(id, resolve);
79
+ this.#socket.send(own(askBody(id, pk, box)));
80
+ });
81
+ }
82
+
83
+ close(): void {
84
+ this.#socket.close();
85
+ }
86
+ }
87
+
88
+ export class WebDialer {
89
+ readonly #lines = new Map<string, Promise<HeldLine | null>>();
90
+
91
+ dial(at: string, pk: string, bytes: Uint8Array): Promise<Dialed> {
92
+ const address = webAddress(at);
93
+ if (address === null || !isHex(pk, 64)) return Promise.resolve(UNDIALED);
94
+ return address.held ? this.#held(address, pk, bytes) : this.#post(address, pk, bytes);
95
+ }
96
+
97
+ async #post(address: WebAddress, pk: string, bytes: Uint8Array): Promise<Dialed> {
98
+ let response: Response;
99
+ try {
100
+ response = await fetch(address.href, { method: 'POST', body: own(concat(unhex(pk), bytes)) });
101
+ } catch {
102
+ return UNDIALED;
103
+ }
104
+ const body = new Uint8Array(await response.arrayBuffer().catch(() => new ArrayBuffer(0)));
105
+ return response.status === 200 && body.length > 0 ? body : null;
106
+ }
107
+
108
+ async #held(address: WebAddress, pk: string, bytes: Uint8Array): Promise<Dialed> {
109
+ let line = this.#lines.get(address.href);
110
+ if (!line) {
111
+ line = HeldLine.open(address.href, () => this.#lines.delete(address.href));
112
+ this.#lines.set(address.href, line);
113
+ void line.then((held) => held ?? this.#lines.delete(address.href));
114
+ }
115
+ const held = await line;
116
+ return held ? held.ask(unhex(pk), bytes) : UNDIALED;
117
+ }
118
+
119
+ async close(): Promise<void> {
120
+ const lines = [...this.#lines.values()];
121
+ this.#lines.clear();
122
+ for (const line of await Promise.all(lines)) line?.close();
123
+ }
124
+ }
125
+
126
+ // Where the web carrier listens, as its cells keep it: a host, the port it
127
+ // bound, the path it answers on, and the origins whose pages it answers.
128
+ export type WebListen = { host: string; port: number; path: string; origins: string[] };
129
+
130
+ // A listener a ground runs for the web carrier: it hands every ask it
131
+ // hears to the ground, and says the addresses it answers at, a post's and
132
+ // a held line's.
133
+ export interface WebListener {
134
+ readonly at: string[];
135
+ readonly port: number;
136
+ close(): Promise<void>;
137
+ }
138
+ export type WebServe = (ground: Ground, listen: WebListen) => Promise<WebListener>;
139
+
140
+ export const WEB = 'org.nervur.web';
141
+ export const WEB_OPENING = { key: 'web', kind: WEB } as const;
142
+
143
+ const listenOf = (value: unknown): WebListen | null => {
144
+ if (typeof value !== 'object' || value === null) return null;
145
+ const { host, port, path, origins } = value as Record<string, unknown>;
146
+ const fine =
147
+ typeof host === 'string' &&
148
+ Number.isInteger(port) &&
149
+ (port as number) >= 0 &&
150
+ (port as number) <= 65_535 &&
151
+ typeof path === 'string' &&
152
+ path.startsWith('/') &&
153
+ Array.isArray(origins) &&
154
+ origins.every((o) => typeof o === 'string');
155
+ return fine ? { host, port: port as number, path, origins: origins as string[] } : null;
156
+ };
157
+
158
+ // Quo over the web as a carrier faculty of one harbor, listening through
159
+ // `serve` where the ground has one:
160
+ //
161
+ // listen { host?, port?, path?, origins? }
162
+ // listen there from now on, 127.0.0.1, a free port, `/`
163
+ // and every origin unless named, and on every wake at the
164
+ // port it bound
165
+ // deaf listen nowhere from now on
166
+ export const webFaculty =
167
+ (serve?: WebServe): GroundFaculty =>
168
+ (ground: Ground) =>
169
+ class WebFaculty extends CarrierFaculty {
170
+ static override readonly kind: string = WEB;
171
+ static override asks: Record<string, AskSpec> = {
172
+ listen: ownerAsk('listen for Quo over the web, and on every wake'),
173
+ deaf: ownerAsk('listen nowhere'),
174
+ };
175
+
176
+ readonly #dialer = new WebDialer();
177
+ #listener: WebListener | undefined;
178
+
179
+ accepts(address: string): boolean {
180
+ return webAddress(address) !== null;
181
+ }
182
+
183
+ dial(address: string, pk: string, bytes: Uint8Array): Promise<Dialed> {
184
+ return this.#dialer.dial(address, pk, bytes);
185
+ }
186
+
187
+ override listening(): string[] {
188
+ return this.#listener ? [...this.#listener.at] : [];
189
+ }
190
+
191
+ override async awake(): Promise<void> {
192
+ const at = listenOf(this.cells.listen);
193
+ if (at && serve && !this.#listener) this.#listener = await serve(ground, at);
194
+ }
195
+
196
+ override async sleep(): Promise<void> {
197
+ await this.#dialer.close();
198
+ await this.#listener?.close();
199
+ this.#listener = undefined;
200
+ }
201
+
202
+ async listen(args: JsonObject): Promise<JsonObject> {
203
+ if (!serve) return { error: 'this ground listens nowhere on the web' };
204
+ const at = listenOf({ host: args.host ?? '127.0.0.1', port: args.port ?? 0, path: args.path ?? '/', origins: args.origins ?? ['*'] });
205
+ if (at === null) return { error: 'host is text, port a port, path a path and origins a list' };
206
+ await this.#listener?.close();
207
+ this.#listener = undefined;
208
+ try {
209
+ this.#listener = await serve(ground, at);
210
+ } catch (e) {
211
+ return { error: (e as Error).message };
212
+ }
213
+ this.cells.listen = { ...at, port: this.#listener.port };
214
+ return { at: [...this.#listener.at] };
215
+ }
216
+
217
+ async deaf(): Promise<JsonObject> {
218
+ await this.#listener?.close();
219
+ this.#listener = undefined;
220
+ delete this.cells.listen;
221
+ return { deaf: true };
222
+ }
223
+ };
224
+
225
+ // The ward pk and box a post carries, or null for a body that is no ask.
226
+ export const readPost = (body: Uint8Array): { pk: string; box: Uint8Array } | null =>
227
+ body.length < MIN_POST || body.length > MAX_POST ? null : { pk: hex(body.subarray(0, 64)), box: body.slice(64) };
@@ -0,0 +1,170 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // `nervur/node`: the Node ground. A harbor keeps its seed and sealed
3
+ // memory in a folder, finds its code among the modules it is handed and
4
+ // then in files, speaks TCP from genesis and the web and Web Push where
5
+ // the root opens them, and serves the root line on a local socket, so the
6
+ // `nervur` command reaches it while it stands.
7
+ //
8
+ // <dir>/seed the harbor's seed
9
+ // <dir>/<place>/ its sealed memory
10
+ // <dir>/root.sock the root line while the harbor is served, open to
11
+ // this user alone, or in the temporary folder for a
12
+ // folder too deep for a socket path
13
+ //
14
+ // One run holds a folder: a terrain refuses a folder another run serves.
15
+ import { createHash } from 'node:crypto';
16
+ import { chmod, rm } from 'node:fs/promises';
17
+ import { connect, createServer, type Server } from 'node:net';
18
+ import { homedir, tmpdir } from 'node:os';
19
+ import { join, resolve } from 'node:path';
20
+ import { pathToFileURL } from 'node:url';
21
+ import type { JsonObject } from '../being/index.ts';
22
+ import { Loader, type Loaded, type Module } from '../contract/index.ts';
23
+ import { FolderCustody, FolderMemory } from '../folder/index.ts';
24
+ import { rootLine, type GroundProbe, type Harbor, type RootRequest } from '../harbor/index.ts';
25
+ import { webGround } from '../http/index.ts';
26
+ import { webPush } from '../line/index.ts';
27
+ import { CryptoEntropy, HeldLoader, PointerTerrain } from '../pointer/index.ts';
28
+ import { TCP_OPENING, tcpFaculty } from '../tcp/index.ts';
29
+
30
+ export const NODE = 'node';
31
+
32
+ // Where a harbor of this user lives unless named: $NERVUR_DIR, then
33
+ // ~/.nervur.
34
+ export const harborDir = (env: Record<string, string | undefined> = process.env): string => env.NERVUR_DIR ?? join(homedir(), '.nervur');
35
+
36
+ // A socket path has a hundred bytes or so on every system, so a folder too
37
+ // deep for one puts its socket in this user's temporary folder, under a
38
+ // name drawn from the folder's own path.
39
+ const SOCKET_PATH = 100;
40
+ export const socketOf = (dir: string): string => {
41
+ const beside = join(resolve(dir), 'root.sock');
42
+ if (Buffer.byteLength(beside) <= SOCKET_PATH) return beside;
43
+ return join(tmpdir(), `nervur-${createHash('sha256').update(resolve(dir)).digest('hex').slice(0, 32)}.sock`);
44
+ };
45
+
46
+ // Code from a file: a module that exports `module`, `version` and
47
+ // `classes`, found again by its absolute path. A file that cannot be
48
+ // imported, or exports no module, is none.
49
+ export class ImportLoader extends Loader {
50
+ async load(from: string): Promise<Loaded | null> {
51
+ const path = resolve(from);
52
+ let exported: { module?: unknown; version?: unknown; classes?: unknown };
53
+ try {
54
+ exported = (await import(pathToFileURL(path).href)) as typeof exported;
55
+ } catch {
56
+ return null;
57
+ }
58
+ const { module, version, classes } = exported;
59
+ if (typeof module !== 'string' || typeof version !== 'string' || !Array.isArray(classes)) return null;
60
+ return { module, version, classes, from: path };
61
+ }
62
+ }
63
+
64
+ // The modules a harbor is handed, by name, and then files.
65
+ export class NodeLoader extends ImportLoader {
66
+ readonly #held: HeldLoader;
67
+ constructor(modules: readonly Module[] = []) {
68
+ super();
69
+ this.#held = new HeldLoader(modules);
70
+ }
71
+ override async load(from: string): Promise<Loaded | null> {
72
+ return (await this.#held.load(from)) ?? super.load(from);
73
+ }
74
+ }
75
+
76
+ // One root request over a served harbor's socket, or undefined where none
77
+ // is served.
78
+ export const askServed = (dir: string, request: RootRequest): Promise<JsonObject | undefined> =>
79
+ new Promise((done, fail) => {
80
+ const socket = connect(socketOf(dir));
81
+ let text = '';
82
+ socket.once('connect', () => socket.write(`${JSON.stringify(request)}\n`));
83
+ socket.on('data', (chunk: Buffer) => {
84
+ text += chunk.toString('utf8');
85
+ const end = text.indexOf('\n');
86
+ if (end < 0) return;
87
+ socket.end();
88
+ done(JSON.parse(text.slice(0, end)) as JsonObject);
89
+ });
90
+ socket.once('error', (e: NodeJS.ErrnoException) => (e.code === 'ENOENT' || e.code === 'ECONNREFUSED' ? done(undefined) : fail(e)));
91
+ });
92
+
93
+ export type NodeParts = {
94
+ readonly dir: string;
95
+ readonly modules?: readonly Module[];
96
+ // Whether its carriers wake, and whether it serves the root line.
97
+ readonly wakes?: boolean;
98
+ readonly serves?: boolean;
99
+ };
100
+
101
+ export class NodeTerrain extends PointerTerrain {
102
+ readonly dir: string;
103
+ readonly serves: boolean;
104
+ #server: Server | undefined;
105
+
106
+ constructor(parts: NodeParts) {
107
+ const entropy = new CryptoEntropy();
108
+ super({
109
+ entropy,
110
+ loader: new NodeLoader(parts.modules),
111
+ custody: new FolderCustody(parts.dir, entropy),
112
+ memory: new FolderMemory(parts.dir),
113
+ faculties: [tcpFaculty, webGround, webPush],
114
+ opens: [TCP_OPENING],
115
+ wakes: parts.wakes ?? true,
116
+ });
117
+ this.dir = parts.dir;
118
+ this.serves = parts.serves ?? true;
119
+ }
120
+
121
+ override async claim(): Promise<void> {
122
+ if ((await askServed(this.dir, {})) !== undefined) throw new Error(`a harbor is already served from ${this.dir}`);
123
+ }
124
+
125
+ // The root line on the socket. A socket file nobody answers on is a
126
+ // stale one, and is replaced.
127
+ override async stand(harbor: Harbor): Promise<void> {
128
+ if (!this.serves) return;
129
+ const root = socketOf(this.dir);
130
+ await rm(root, { force: true });
131
+ const server = createServer((socket) => {
132
+ let text = '';
133
+ socket.on('data', (chunk: Buffer) => {
134
+ text += chunk.toString('utf8');
135
+ for (let end = text.indexOf('\n'); end >= 0; end = text.indexOf('\n')) {
136
+ const line = text.slice(0, end);
137
+ text = text.slice(end + 1);
138
+ let value: unknown;
139
+ try {
140
+ value = JSON.parse(line);
141
+ } catch {
142
+ value = undefined;
143
+ }
144
+ void rootLine(harbor, value)
145
+ .catch(() => ({ error: 'the harbor threw' }))
146
+ .then((answer) => socket.write(`${JSON.stringify(answer)}\n`));
147
+ }
148
+ });
149
+ socket.on('error', () => socket.destroy());
150
+ });
151
+ await new Promise<void>((done) => server.listen(root, done));
152
+ await chmod(root, 0o600);
153
+ this.#server = server;
154
+ }
155
+
156
+ override async release(): Promise<void> {
157
+ const server = this.#server;
158
+ if (!server) return;
159
+ this.#server = undefined;
160
+ await new Promise((done) => server.close(done));
161
+ await rm(socketOf(this.dir), { force: true });
162
+ }
163
+ }
164
+
165
+ // Node, and the engines that answer as Node does.
166
+ export const nodeGround: GroundProbe = {
167
+ name: NODE,
168
+ fits: () => typeof process !== 'undefined' && typeof process.versions?.node === 'string',
169
+ terrain: ({ modules, where }) => new NodeTerrain({ dir: where ?? harborDir(), ...(modules ? { modules } : {}) }),
170
+ };
package/src/node.ts ADDED
@@ -0,0 +1,9 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // `nervur` as Node reads it: the main entry, with the Node ground added, so
3
+ // `Harbor.open()` keeps a harbor in a folder and serves its root line.
4
+ import { addGround } from './harbor/index.ts';
5
+ import { nodeGround } from './node/index.ts';
6
+
7
+ export * from './index.ts';
8
+
9
+ addGround(nodeGround);
@@ -53,6 +53,7 @@ export class VolatileMemory extends Memory {
53
53
  const entries = this.#places.get(place) ?? new Map<string, Uint8Array>();
54
54
  return Promise.resolve(new Map([...entries].map(([name, bytes]) => [name, bytes.slice()])));
55
55
  }
56
+ // One object holds it, so a keep is whole by the run of one turn.
56
57
  write(place: string, entries: ReadonlyMap<string, Uint8Array | null>): Promise<void> {
57
58
  let kept = this.#places.get(place);
58
59
  if (!kept) this.#places.set(place, (kept = new Map()));
@@ -60,6 +61,16 @@ export class VolatileMemory extends Memory {
60
61
  if (bytes === null) kept.delete(name);
61
62
  else kept.set(name, bytes.slice());
62
63
  }
64
+ if (kept.size === 0) this.#places.delete(place);
65
+ return Promise.resolve();
66
+ }
67
+
68
+ places(): Promise<string[]> {
69
+ return Promise.resolve([...this.#places.keys()]);
70
+ }
71
+
72
+ forget(place: string): Promise<void> {
73
+ this.#places.delete(place);
63
74
  return Promise.resolve();
64
75
  }
65
76
  }
@@ -4,7 +4,7 @@
4
4
  // restart drops a harbor and opens a new one on the terrain the world
5
5
  // keeps for it, so only what its memory kept comes back.
6
6
  import { Carrier, type Clock, type Custody, type Entropy, type Loader, type Memory, type Module } from '../contract/index.ts';
7
- import { Harbor, Terrain } from '../harbor/index.ts';
7
+ import { Harbor, Terrain, type GroundFaculty, type Opening } from '../harbor/index.ts';
8
8
  import { CryptoEntropy, HeldCustody, HeldLoader, SystemClock, VolatileMemory } from './bodies.ts';
9
9
 
10
10
  // A carrier that reaches no one: a harbor alone.
@@ -26,7 +26,17 @@ export class PointerCarrier extends Carrier {
26
26
  }
27
27
  }
28
28
 
29
- export type PointerParts = { entropy?: Entropy; clock?: Clock; custody?: Custody; memory?: Memory; carrier?: Carrier; loader?: Loader };
29
+ export type PointerParts = {
30
+ entropy?: Entropy;
31
+ clock?: Clock;
32
+ custody?: Custody;
33
+ memory?: Memory;
34
+ carrier?: Carrier;
35
+ loader?: Loader;
36
+ faculties?: readonly GroundFaculty[];
37
+ opens?: readonly Opening[];
38
+ wakes?: boolean;
39
+ };
30
40
 
31
41
  export class PointerTerrain extends Terrain {
32
42
  readonly entropy: Entropy;
@@ -35,6 +45,9 @@ export class PointerTerrain extends Terrain {
35
45
  readonly memory: Memory;
36
46
  readonly carrier: Carrier;
37
47
  readonly loader: Loader;
48
+ override readonly faculties: readonly GroundFaculty[];
49
+ override readonly opens: readonly Opening[];
50
+ override readonly wakes: boolean;
38
51
 
39
52
  constructor(parts: PointerParts = {}) {
40
53
  super();
@@ -44,6 +57,9 @@ export class PointerTerrain extends Terrain {
44
57
  this.memory = parts.memory ?? new VolatileMemory();
45
58
  this.carrier = parts.carrier ?? new NoCarrier();
46
59
  this.loader = parts.loader ?? new HeldLoader();
60
+ this.faculties = parts.faculties ?? [];
61
+ this.opens = parts.opens ?? [];
62
+ this.wakes = parts.wakes ?? true;
47
63
  }
48
64
  }
49
65
 
@@ -0,0 +1,87 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Addresses, as `SPEC.md` names them in an invitation's `at`: a URI of
3
+ // RFC 3986 whose scheme, read in any case, names a carrier.
4
+ // `CARRIER-TCP.md` writes `tcp://host:port`, and `CARRIER-WEB.md` writes
5
+ // `http` and `https` for the post and `ws` and `wss` for the held line.
6
+
7
+ // RFC 3986 appendix B, with the characters a URI may hold checked apart.
8
+ const SPLIT = /^(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/;
9
+ const URI_CHARS = /^(?:[A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=]|%[0-9A-Fa-f]{2})*$/;
10
+ const SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/;
11
+ const REG_NAME = /^(?:[A-Za-z0-9\-._~!$&'()*+,;=]|%[0-9A-Fa-f]{2})*$/;
12
+ const IP_LITERAL = /^\[(?:[0-9A-Fa-f:.]+|v[0-9A-Fa-f]+\.[A-Za-z0-9\-._~!$&'()*+,;=:]+)\]$/;
13
+
14
+ type Parts = { scheme: string; authority: string | null; userinfo: string | null; host: string | null; port: string | null; path: string; query: string | null; fragment: string | null };
15
+
16
+ // A URI with a scheme, taken apart, or null. `host` is as written,
17
+ // brackets included, and `port` the digits as written.
18
+ const parse = (s: unknown): Parts | null => {
19
+ if (typeof s !== 'string' || !URI_CHARS.test(s)) return null;
20
+ const m = SPLIT.exec(s);
21
+ if (!m || m[1] === undefined || !SCHEME.test(m[1])) return null;
22
+ const out: Parts = { scheme: m[1].toLowerCase(), authority: m[2] ?? null, userinfo: null, host: null, port: null, path: m[3] ?? '', query: m[4] ?? null, fragment: m[5] ?? null };
23
+ if (out.authority === null) return out;
24
+ let rest = out.authority;
25
+ const at = rest.lastIndexOf('@');
26
+ if (at >= 0) {
27
+ out.userinfo = rest.slice(0, at);
28
+ rest = rest.slice(at + 1);
29
+ }
30
+ const hp = /^(\[[^\]]*\]|[^:[\]]*)(?::([0-9]*))?$/.exec(rest);
31
+ if (!hp) return null;
32
+ const host = hp[1]!;
33
+ if (host.startsWith('[') ? !IP_LITERAL.test(host) : !REG_NAME.test(host)) return null;
34
+ out.host = host;
35
+ out.port = hp[2] ?? null;
36
+ return out;
37
+ };
38
+
39
+ // The host as a socket takes it: an IPv6 literal without its brackets.
40
+ const bare = (host: string): string => (host.startsWith('[') ? host.slice(1, -1) : host);
41
+
42
+ // The scheme an address names, lowercase, or null for what is no URI.
43
+ export const schemeOf = (s: unknown): string | null => parse(s)?.scheme ?? null;
44
+
45
+ export type TcpAddress = { host: string; port: number };
46
+
47
+ // A `tcp` address as `CARRIER-TCP.md` writes one, or null.
48
+ export const tcpAddress = (s: unknown): TcpAddress | null => {
49
+ const a = parse(s);
50
+ if (!a || a.scheme !== 'tcp' || a.authority === null) return null;
51
+ if (a.userinfo !== null || a.path !== '' || a.query !== null || a.fragment !== null) return null;
52
+ if (!a.host || a.port === null || !/^[0-9]+$/.test(a.port)) return null;
53
+ const port = Number(a.port);
54
+ if (port < 1 || port > 65_535) return null;
55
+ return { host: bare(a.host), port };
56
+ };
57
+
58
+ // The `tcp` address of a host and port.
59
+ export const tcpAt = (host: string, port: number): string => `tcp://${host.includes(':') ? `[${host}]` : host}:${port}`;
60
+
61
+ export type WebAddress = { scheme: 'http' | 'https' | 'ws' | 'wss'; secure: boolean; held: boolean; host: string; port: number; path: string; href: string };
62
+ const WEB = new Set(['http', 'https', 'ws', 'wss']);
63
+
64
+ // An address of `CARRIER-WEB.md`, or null. `path` is the path and query
65
+ // a request names, `/` when both are empty.
66
+ export const webAddress = (s: unknown): WebAddress | null => {
67
+ const a = parse(s);
68
+ if (!a || !WEB.has(a.scheme) || a.authority === null) return null;
69
+ if (a.userinfo !== null || a.fragment !== null || !a.host) return null;
70
+ if (a.port !== null && a.port !== '' && (!/^[0-9]+$/.test(a.port) || Number(a.port) > 65_535)) return null;
71
+ const scheme = a.scheme as WebAddress['scheme'];
72
+ const secure = scheme === 'https' || scheme === 'wss';
73
+ const port = a.port ? Number(a.port) : secure ? 443 : 80;
74
+ const path = `${a.path || '/'}${a.query !== null ? `?${a.query}` : ''}`;
75
+ return { scheme, secure, held: scheme === 'ws' || scheme === 'wss', host: bare(a.host), port, path, href: s as string };
76
+ };
77
+
78
+ // Whether a tcp or web address names the unspecified host, where a
79
+ // listener binds every interface and no caller can dial.
80
+ export const unspecified = (s: unknown): boolean => {
81
+ const host = (tcpAddress(s) ?? webAddress(s))?.host;
82
+ return host === '0.0.0.0' || host === '::';
83
+ };
84
+
85
+ // An invitation's `at` as `SPEC.md` reads it: the strings that are URIs
86
+ // with a scheme, in their order. A value that is no array is absent.
87
+ export const readAt = (value: unknown): string[] => (Array.isArray(value) ? value.filter((s): s is string => parse(s) !== null) : []);
package/src/quo/door.ts CHANGED
@@ -43,12 +43,14 @@ export class Door {
43
43
 
44
44
  // A new heir, held fresh, and its invitation. The lock is drawn at the
45
45
  // first invitation that names an heir, before the heir's secret.
46
- async invite(): Promise<{ heir: string; invitation: Invitation }> {
46
+ // A new heir, and its invitation, naming in `at` the addresses given.
47
+ async invite(at: readonly string[] = []): Promise<{ heir: string; invitation: Invitation }> {
47
48
  let lock = this.relations.lock();
48
49
  if (!lock) this.relations.setLock((lock = drawLock(this.draw)));
49
50
  const heir = await SigningKey.draw(this.draw);
50
51
  this.relations.set(heir.id, { state: 'fresh' });
51
- return { heir: heir.id, invitation: { ward: this.key.pk, heir: heir.id, secret: hex(heir.secret), lock: hex(lock.ek) } };
52
+ const invitation = { ward: this.key.pk, heir: heir.id, secret: hex(heir.secret), lock: hex(lock.ek), ...(at.length > 0 ? { at: [...at] } : {}) };
53
+ return { heir: heir.id, invitation };
52
54
  }
53
55
 
54
56
  // The door stops holding an heir. A fresh one leaves nothing, a spent one
package/src/quo/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // Quo's wire: keys, the invitation, the payload, the reply, the boxes, the
3
3
  // door and the standing. It knows no being, no ward and no terrain.
4
+ export { readAt, schemeOf, tcpAddress, tcpAt, unspecified, webAddress, type TcpAddress, type WebAddress } from './address.ts';
4
5
  export { Door, SPAN, type Behind, type Choice, type Judged } from './door.ts';
5
6
  export { readInvitation, type Invitation } from './invitation.ts';
6
7
  export { Ephemeral, SigningKey, WardKey, type Draw } from './keys.ts';
@@ -1,15 +1,19 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
- // The invitation: `{ ward, heir, secret, lock }`, a value with no route.
2
+ // The invitation: `{ ward, heir, secret, lock, at? }`. A door reads no
3
+ // route from it; `at`, when present, names where the ward is reached.
3
4
  import { EK, encapsulate, isHex, unhex } from '../crypto/index.ts';
5
+ import { readAt } from './address.ts';
4
6
 
5
- export type Invitation = { readonly ward: string; readonly heir: string; readonly secret: string; readonly lock: string };
7
+ export type Invitation = { readonly ward: string; readonly heir: string; readonly secret: string; readonly lock: string; readonly at?: string[] };
6
8
 
7
- // An invitation, or null for any other shape. A field beside the four is
8
- // ignored, and the lock is held to the modulus check.
9
+ // An invitation, or null for any other shape. A field beside the five is
10
+ // ignored, the lock is held to the modulus check, and `at` keeps the
11
+ // addresses it holds, an `at` with none or of another shape being absent.
9
12
  export const readInvitation = (value: unknown): Invitation | null => {
10
13
  if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;
11
- const { ward, heir, secret, lock } = value as Record<string, unknown>;
14
+ const { ward, heir, secret, lock, at } = value as Record<string, unknown>;
12
15
  if (!isHex(ward, 64) || !isHex(heir, 32) || !isHex(secret, 32) || !isHex(lock, EK)) return null;
13
16
  if (encapsulate(unhex(lock), new Uint8Array(32)) === null) return null;
14
- return { ward, heir, secret, lock };
17
+ const addresses = readAt(at);
18
+ return { ward, heir, secret, lock, ...(addresses.length > 0 ? { at: addresses } : {}) };
15
19
  };