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