@operad-io/engine 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -2
  3. package/config.schema.json +188 -0
  4. package/keys.schema.json +12 -0
  5. package/package.json +22 -4
  6. package/src/config/config.ts +627 -0
  7. package/src/config/index.ts +1 -0
  8. package/src/flow/define-flow.ts +57 -0
  9. package/src/flow/index.ts +5 -0
  10. package/src/flow/load.ts +41 -0
  11. package/src/flow/types.ts +107 -0
  12. package/src/flow/validate.ts +296 -0
  13. package/src/http/address.ts +142 -0
  14. package/src/http/index.ts +25 -0
  15. package/src/http/link.ts +20 -0
  16. package/src/http/server.ts +920 -0
  17. package/src/http/token.ts +90 -0
  18. package/src/index.ts +18 -0
  19. package/src/kernel/decide.ts +689 -0
  20. package/src/kernel/index.ts +3 -0
  21. package/src/kernel/state.ts +275 -0
  22. package/src/kernel/types.ts +366 -0
  23. package/src/log/errors.ts +77 -0
  24. package/src/log/facts.ts +50 -0
  25. package/src/log/index.ts +6 -0
  26. package/src/log/json-value.ts +67 -0
  27. package/src/log/open-log.ts +17 -0
  28. package/src/log/schema.ts +5 -0
  29. package/src/log/secret.ts +30 -0
  30. package/src/log/sqlite.ts +1011 -0
  31. package/src/log/types.ts +230 -0
  32. package/src/loop/code-watch.ts +486 -0
  33. package/src/loop/index.ts +3 -0
  34. package/src/loop/older-code.ts +58 -0
  35. package/src/loop/serve.ts +483 -0
  36. package/src/markdown.ts +451 -0
  37. package/src/notify/index.ts +10 -0
  38. package/src/notify/notify.ts +256 -0
  39. package/src/platform/file-lock.ts +385 -0
  40. package/src/platform/index.ts +13 -0
  41. package/src/platform/load.ts +18 -0
  42. package/src/platform/process-group.ts +675 -0
  43. package/src/platform/process-watch.ts +152 -0
  44. package/src/platform/sqlite-open.ts +104 -0
  45. package/src/platform/step-reap.ts +668 -0
  46. package/src/platform/watch.ts +158 -0
  47. package/src/platform/worker-reports.ts +34 -0
  48. package/src/plugin/action-schema.ts +550 -0
  49. package/src/plugin/declared-flows.ts +74 -0
  50. package/src/plugin/define-plugin.ts +12 -0
  51. package/src/plugin/errors.ts +73 -0
  52. package/src/plugin/filters.ts +46 -0
  53. package/src/plugin/harness.ts +50 -0
  54. package/src/plugin/home.ts +13 -0
  55. package/src/plugin/index.ts +65 -0
  56. package/src/plugin/install.ts +268 -0
  57. package/src/plugin/keys.ts +63 -0
  58. package/src/plugin/load.ts +256 -0
  59. package/src/plugin/logger.ts +30 -0
  60. package/src/plugin/object-facts.ts +132 -0
  61. package/src/plugin/open-store.ts +32 -0
  62. package/src/plugin/paging.ts +133 -0
  63. package/src/plugin/registry.ts +1786 -0
  64. package/src/plugin/secrets.ts +141 -0
  65. package/src/plugin/semver.ts +110 -0
  66. package/src/plugin/settings.ts +64 -0
  67. package/src/plugin/sqlite-store.ts +756 -0
  68. package/src/plugin/store.ts +318 -0
  69. package/src/plugin/types.ts +1243 -0
  70. package/src/plugin/usage.ts +157 -0
  71. package/src/plugin/validate.ts +1028 -0
  72. package/src/runner/answer.ts +156 -0
  73. package/src/runner/ask.ts +483 -0
  74. package/src/runner/cancel.ts +51 -0
  75. package/src/runner/errors.ts +20 -0
  76. package/src/runner/grants.ts +92 -0
  77. package/src/runner/index.ts +33 -0
  78. package/src/runner/limits.ts +403 -0
  79. package/src/runner/lock.ts +140 -0
  80. package/src/runner/runner.ts +1175 -0
  81. package/src/runner/service.ts +184 -0
  82. package/src/runner/step-worker.ts +303 -0
  83. package/src/testing/clock.ts +67 -0
  84. package/src/testing/index.ts +90 -0
  85. package/src/testing/types.ts +116 -0
  86. package/src/testing/world.ts +369 -0
  87. package/src/trigger/cron.ts +193 -0
  88. package/src/trigger/index.ts +32 -0
  89. package/src/trigger/kernel.ts +1221 -0
  90. package/src/trigger/rules.ts +300 -0
  91. package/src/trigger/store.ts +233 -0
  92. package/src/trigger/types.ts +156 -0
  93. package/src/util.ts +50 -0
  94. package/src/views/history.ts +634 -0
  95. package/src/views/index.ts +7 -0
  96. package/src/views/pending.ts +209 -0
  97. package/src/views/presentation.ts +2609 -0
  98. package/src/views/running.ts +255 -0
  99. package/src/views/settings.ts +452 -0
  100. package/src/views/types.ts +72 -0
  101. package/src/views/uploads.ts +228 -0
  102. package/triggers.schema.json +48 -0
@@ -0,0 +1,41 @@
1
+ import { resolve } from "node:path";
2
+ import { pathToFileURL } from "node:url";
3
+ import type { FlowDefinition, StepTypeRegistry } from "./types.ts";
4
+ import { FlowError, validateFlow } from "./validate.ts";
5
+ import { messageOf } from "../plugin/errors.ts";
6
+
7
+ let loadCount = 0;
8
+
9
+ /**
10
+ * Imports a TypeScript module whose default export is a `defineFlow` value and
11
+ * validates it. The file is named in every error that comes from the import.
12
+ */
13
+ export async function loadFlow(
14
+ path: string,
15
+ registry: StepTypeRegistry = [],
16
+ ): Promise<FlowDefinition> {
17
+ const absolute = resolve(path);
18
+ const url = pathToFileURL(absolute);
19
+ loadCount += 1;
20
+ url.searchParams.set("operad-load", String(loadCount));
21
+
22
+ let module: Record<string, unknown>;
23
+ try {
24
+ module = (await import(url.href)) as Record<string, unknown>;
25
+ } catch (error) {
26
+ throw new FlowError(`flow file "${path}": import failed: ${messageOf(error)}`, { cause: error });
27
+ }
28
+
29
+ const exported = module.default;
30
+ if (exported === undefined) {
31
+ throw new FlowError(`flow file "${path}": no default export`);
32
+ }
33
+ try {
34
+ return validateFlow(exported, registry);
35
+ } catch (error) {
36
+ if (error instanceof FlowError) {
37
+ throw new FlowError(`flow file "${path}": ${error.message}`, { cause: error });
38
+ }
39
+ throw error;
40
+ }
41
+ }
@@ -0,0 +1,107 @@
1
+ /** How a step behaves when a run resumes after a crash. */
2
+ export type Replay = "safe" | "unsafe";
3
+
4
+ /** The internal names of the four basic steps. Users see only "step". */
5
+ export type StepKind = "plugin" | "wait_person" | "wait" | "end";
6
+
7
+ /** How a flow ends. */
8
+ export type EndStatus = "done" | "failed" | "cancelled";
9
+
10
+ /** The reserved step id an edge points at to finish the flow. */
11
+ export const END = "end";
12
+
13
+ /**
14
+ * The shape a step must have before validation. `params` and `next` stay
15
+ * `unknown` here so that `defineFlow` keeps the literal result keys a caller
16
+ * wrote; validation and the conditional step check give them meaning.
17
+ */
18
+ export interface StepShape {
19
+ readonly id: string;
20
+ readonly kind: StepKind;
21
+ readonly params: unknown;
22
+ readonly replay: Replay;
23
+ readonly next?: unknown;
24
+ }
25
+
26
+ /** A flow definition: structure is data, step logic lives elsewhere. */
27
+ export interface FlowDefinition<S extends readonly StepShape[] = readonly StepShape[]> {
28
+ readonly name: string;
29
+ readonly entry: string;
30
+ readonly maxVisits?: number;
31
+ readonly steps: S;
32
+ }
33
+
34
+ /** Fields every step has. */
35
+ export interface StepBase {
36
+ readonly id: string;
37
+ readonly replay: Replay;
38
+ }
39
+
40
+ /** Calls a step type declared by a plugin. */
41
+ export interface PluginStep extends StepBase {
42
+ readonly kind: "plugin";
43
+ readonly params: {
44
+ /** `<plugin>/<step type>`, such as `dev/command`. */
45
+ readonly use: string;
46
+ readonly params: unknown;
47
+ };
48
+ readonly next: Readonly<Record<string, string>>;
49
+ }
50
+
51
+ /** Asks a person; the turn ends and the process holds nothing while waiting. */
52
+ export interface WaitPersonStep extends StepBase {
53
+ readonly kind: "wait_person";
54
+ readonly params: {
55
+ readonly prompt: string;
56
+ readonly choices: readonly string[];
57
+ /**
58
+ * Answers a timed-out step may hand over that this wait does not offer by
59
+ * itself. They need an edge in `next`, and are shown only when the step
60
+ * that asked hands one over.
61
+ */
62
+ readonly lateChoices?: readonly string[];
63
+ /**
64
+ * Shown when the step that led here was interrupted. `{step}` names that
65
+ * step, so one wait can explain what stopped.
66
+ */
67
+ readonly note?: string;
68
+ };
69
+ readonly next: Readonly<Record<string, string>>;
70
+ }
71
+
72
+ /** Waits for a time or for a plugin step's exit to change. */
73
+ export interface WaitStep extends StepBase {
74
+ readonly kind: "wait";
75
+ readonly params:
76
+ | { readonly afterSecs: number }
77
+ | { readonly check: string; readonly params?: unknown };
78
+ readonly next: Readonly<Record<"ready" | "interrupted", string>>;
79
+ }
80
+
81
+ /** Finishes the flow. */
82
+ export interface EndStep extends StepBase {
83
+ readonly kind: "end";
84
+ readonly params: { readonly status: EndStatus };
85
+ readonly next?: Readonly<Record<string, never>>;
86
+ }
87
+
88
+ export type Step = PluginStep | WaitPersonStep | WaitStep | EndStep;
89
+
90
+ /** One step type a plugin declares. */
91
+ export interface StepType {
92
+ /** The full use name, such as `dev/command`, matched exactly. */
93
+ readonly name: string;
94
+ /** The result names the step can produce. */
95
+ readonly results: readonly string[];
96
+ /** False when the step cannot run again from where a question left it. */
97
+ readonly resumable?: boolean | undefined;
98
+ /** Access profile fields this step applies. */
99
+ readonly enforces?: readonly string[] | undefined;
100
+ /** How long one run of the step may take, in seconds; unset uses the runner default. */
101
+ readonly timeoutSecs?: number | undefined;
102
+ /** Kept for the plugin loader that lands later; not interpreted here. */
103
+ readonly paramsSchema?: unknown;
104
+ }
105
+
106
+ /** The step types validation may see. A single declaration or a list of them. */
107
+ export type StepTypeRegistry = StepType | readonly StepType[];
@@ -0,0 +1,296 @@
1
+ import {
2
+ END,
3
+ type FlowDefinition,
4
+ type StepKind,
5
+ type StepShape,
6
+ type StepType,
7
+ type StepTypeRegistry,
8
+ } from "./types.ts";
9
+ import { isRecord } from "../util.ts";
10
+
11
+ /** A flow is not usable; the message names the flow, step and field. */
12
+ export class FlowError extends Error {
13
+ constructor(message: string, options?: ErrorOptions) {
14
+ super(message, options);
15
+ this.name = "FlowError";
16
+ }
17
+ }
18
+
19
+ function isStringArray(value: unknown): value is string[] {
20
+ return Array.isArray(value) && value.every((item): item is string => typeof item === "string");
21
+ }
22
+
23
+ function hasOwn(value: Record<string, unknown>, key: string): boolean {
24
+ return Object.prototype.hasOwnProperty.call(value, key);
25
+ }
26
+
27
+ function normalizeRegistry(registry: StepTypeRegistry): readonly StepType[] {
28
+ const entries: readonly StepType[] = Array.isArray(registry) ? registry : [registry];
29
+ for (const entry of entries) {
30
+ if (
31
+ !isRecord(entry) ||
32
+ typeof entry.name !== "string" ||
33
+ entry.name.length === 0 ||
34
+ !isStringArray(entry.results)
35
+ ) {
36
+ throw new FlowError("step type registry: each step type needs a name and a list of result names");
37
+ }
38
+ }
39
+ return entries;
40
+ }
41
+
42
+ /**
43
+ * A use name matches one declaration exactly, so a step type from another
44
+ * plugin is never accepted under the same short name.
45
+ */
46
+ function resolveStepType(registry: readonly StepType[], use: string): StepType | undefined {
47
+ return registry.find((entry) => entry.name === use);
48
+ }
49
+
50
+ interface CheckedStep extends StepShape {
51
+ readonly kind: StepKind;
52
+ readonly params: Record<string, unknown>;
53
+ readonly results: readonly string[];
54
+ readonly next: Readonly<Record<string, string>>;
55
+ }
56
+
57
+ function checkStep(
58
+ raw: unknown,
59
+ index: number,
60
+ flowName: string,
61
+ registry: readonly StepType[],
62
+ ): CheckedStep {
63
+ if (!isRecord(raw)) {
64
+ throw new FlowError(`flow "${flowName}": steps[${index}]: must be a step object`);
65
+ }
66
+ const id = raw.id;
67
+ if (typeof id !== "string" || id.length === 0) {
68
+ throw new FlowError(`flow "${flowName}": steps[${index}]: id: must be a non-empty string`);
69
+ }
70
+ const at = (field: string): string => `flow "${flowName}": step "${id}": ${field}`;
71
+
72
+ const kind = raw.kind;
73
+ if (kind !== "plugin" && kind !== "wait_person" && kind !== "wait" && kind !== "end") {
74
+ throw new FlowError(at(`kind: unknown step kind ${JSON.stringify(kind)}`));
75
+ }
76
+ if (raw.replay !== "safe" && raw.replay !== "unsafe") {
77
+ throw new FlowError(at('replay: must be "safe" or "unsafe"'));
78
+ }
79
+ const replay = raw.replay;
80
+ if (!isRecord(raw.params)) {
81
+ throw new FlowError(at("params: must be an object"));
82
+ }
83
+ const params = raw.params;
84
+
85
+ let results: readonly string[];
86
+ switch (kind) {
87
+ case "plugin": {
88
+ const use = params.use;
89
+ if (typeof use !== "string" || use.length === 0) {
90
+ throw new FlowError(at("params.use: must name a plugin step type"));
91
+ }
92
+ const type = resolveStepType(registry, use);
93
+ if (type === undefined) {
94
+ throw new FlowError(at(`params.use: unknown plugin step type "${use}"`));
95
+ }
96
+ if (!hasOwn(params, "params")) {
97
+ throw new FlowError(at("params.params: must be present, use {} when the step takes none"));
98
+ }
99
+ // An unsafe step can be interrupted by a crash before it finishes, even
100
+ // when its type declares no such result. The flow must say where that
101
+ // goes; a run must never end because a result had no edge.
102
+ results =
103
+ replay === "unsafe"
104
+ ? [...new Set([...type.results, "interrupted"])]
105
+ : type.results;
106
+ break;
107
+ }
108
+ case "wait_person": {
109
+ if (typeof params.prompt !== "string" || params.prompt.length === 0) {
110
+ throw new FlowError(at("params.prompt: must be a non-empty string"));
111
+ }
112
+ const choices = params.choices;
113
+ if (!isStringArray(choices)) {
114
+ throw new FlowError(at("params.choices: must be an array of strings"));
115
+ }
116
+ const lateChoices = params.lateChoices ?? [];
117
+ if (!isStringArray(lateChoices)) {
118
+ throw new FlowError(at("params.lateChoices: must be an array of strings"));
119
+ }
120
+ if (
121
+ params.note !== undefined &&
122
+ (typeof params.note !== "string" || params.note.length === 0)
123
+ ) {
124
+ throw new FlowError(at("params.note: must be a non-empty string"));
125
+ }
126
+ results = [...new Set([...choices, ...lateChoices, "interrupted"])];
127
+ break;
128
+ }
129
+ case "wait": {
130
+ const hasAfter = hasOwn(params, "afterSecs");
131
+ const hasCheck = hasOwn(params, "check");
132
+ if (hasAfter === hasCheck) {
133
+ throw new FlowError(at("params: exactly one of afterSecs or check is required"));
134
+ }
135
+ if (hasAfter) {
136
+ const afterSecs = params.afterSecs;
137
+ if (typeof afterSecs !== "number" || !Number.isFinite(afterSecs) || afterSecs < 0) {
138
+ throw new FlowError(at("params.afterSecs: must be zero or more seconds"));
139
+ }
140
+ } else {
141
+ const check = params.check;
142
+ if (typeof check !== "string" || check.length === 0) {
143
+ throw new FlowError(at("params.check: must name a plugin step type"));
144
+ }
145
+ if (resolveStepType(registry, check) === undefined) {
146
+ throw new FlowError(at(`params.check: unknown plugin step type "${check}"`));
147
+ }
148
+ if (hasOwn(params, "params") && !isRecord(params.params)) {
149
+ throw new FlowError(at("params.params: must be an object"));
150
+ }
151
+ }
152
+ results = ["ready", "interrupted"];
153
+ break;
154
+ }
155
+ case "end": {
156
+ const status = params.status;
157
+ if (status !== "done" && status !== "failed" && status !== "cancelled") {
158
+ throw new FlowError(at('params.status: must be "done", "failed" or "cancelled"'));
159
+ }
160
+ results = [];
161
+ break;
162
+ }
163
+ }
164
+
165
+ const rawNext = raw.next;
166
+ const next: Record<string, string> = {};
167
+ if (rawNext !== undefined) {
168
+ if (!isRecord(rawNext)) {
169
+ throw new FlowError(at("next: must be an object"));
170
+ }
171
+ for (const [result, target] of Object.entries(rawNext)) {
172
+ if (typeof target !== "string") {
173
+ throw new FlowError(at(`next.${result}: must name a step or "end"`));
174
+ }
175
+ // defineProperty: a result named "__proto__" must become an own key, not hit the setter.
176
+ Object.defineProperty(next, result, { value: target, enumerable: true, writable: true, configurable: true });
177
+ }
178
+ }
179
+
180
+ return { id, kind, params, replay, results, next };
181
+ }
182
+
183
+ /**
184
+ * Validates a flow against the four basic steps and the plugin step types the
185
+ * caller declares. Throws `FlowError` naming the flow, step and field; returns
186
+ * the flow when it is usable. Cycles are allowed.
187
+ */
188
+ export function validateFlow(flow: unknown, registry: StepTypeRegistry = []): FlowDefinition {
189
+ if (!isRecord(flow)) {
190
+ throw new FlowError("flow: must be an object");
191
+ }
192
+ const name = flow.name;
193
+ if (typeof name !== "string" || name.trim().length === 0) {
194
+ throw new FlowError("flow: name: must be a non-empty string");
195
+ }
196
+ const entry = flow.entry;
197
+ if (typeof entry !== "string" || entry.length === 0) {
198
+ throw new FlowError(`flow "${name}": entry: must be a non-empty string`);
199
+ }
200
+ if (!Array.isArray(flow.steps)) {
201
+ throw new FlowError(`flow "${name}": steps: must be an array`);
202
+ }
203
+ const rawSteps: readonly unknown[] = flow.steps;
204
+
205
+ const maxVisits = flow.maxVisits;
206
+ if (
207
+ maxVisits !== undefined &&
208
+ (typeof maxVisits !== "number" || !Number.isInteger(maxVisits) || maxVisits < 1)
209
+ ) {
210
+ throw new FlowError(`flow "${name}": maxVisits: must be a positive integer`);
211
+ }
212
+
213
+ const stepTypes = normalizeRegistry(registry);
214
+
215
+ const ids = new Set<string>();
216
+ for (let index = 0; index < rawSteps.length; index += 1) {
217
+ const raw = rawSteps[index];
218
+ if (!isRecord(raw)) {
219
+ throw new FlowError(`flow "${name}": steps[${index}]: must be a step object`);
220
+ }
221
+ const id = raw.id;
222
+ if (typeof id !== "string" || id.length === 0) {
223
+ throw new FlowError(`flow "${name}": steps[${index}]: id: must be a non-empty string`);
224
+ }
225
+ if (id === END) {
226
+ throw new FlowError(`flow "${name}": step "${id}": id: "end" is reserved`);
227
+ }
228
+ if (ids.has(id)) {
229
+ throw new FlowError(`flow "${name}": step "${id}": id: duplicate step id "${id}"`);
230
+ }
231
+ ids.add(id);
232
+ }
233
+
234
+ if (!ids.has(entry)) {
235
+ throw new FlowError(`flow "${name}": entry: "${entry}" is not a step`);
236
+ }
237
+
238
+ const steps = rawSteps.map((raw, index) => checkStep(raw, index, name, stepTypes));
239
+ const byId = new Map(steps.map((step) => [step.id, step]));
240
+
241
+ for (const step of steps) {
242
+ for (const result of new Set(step.results)) {
243
+ if (!hasOwn(step.next, result)) {
244
+ throw new FlowError(
245
+ `flow "${name}": step "${step.id}": next: no edge for result "${result}"`,
246
+ );
247
+ }
248
+ }
249
+ for (const [result, target] of Object.entries(step.next)) {
250
+ if (!step.results.includes(result)) {
251
+ throw new FlowError(
252
+ `flow "${name}": step "${step.id}": next.${result}: "${result}" is not a result of this step`,
253
+ );
254
+ }
255
+ if (target !== END && !ids.has(target)) {
256
+ throw new FlowError(
257
+ `flow "${name}": step "${step.id}": next.${result}: "${target}" is not a step`,
258
+ );
259
+ }
260
+ // A step that asked and ran out of grace hands its question to a wait.
261
+ if (
262
+ step.kind === "plugin" &&
263
+ result === "waiting" &&
264
+ byId.get(target)?.kind !== "wait_person"
265
+ ) {
266
+ throw new FlowError(
267
+ `flow "${name}": step "${step.id}": next.waiting: must name a wait_person step`,
268
+ );
269
+ }
270
+ }
271
+ }
272
+
273
+ const reachable = new Set<string>();
274
+ const queue: string[] = [entry];
275
+ for (let index = 0; index < queue.length; index += 1) {
276
+ const id = queue[index];
277
+ if (id === undefined || reachable.has(id)) continue;
278
+ reachable.add(id);
279
+ const step = byId.get(id);
280
+ if (step === undefined) continue;
281
+ for (const target of Object.values(step.next)) {
282
+ if (target !== END && !reachable.has(target)) queue.push(target);
283
+ }
284
+ }
285
+ for (const step of steps) {
286
+ if (!reachable.has(step.id)) {
287
+ throw new FlowError(
288
+ `flow "${name}": step "${step.id}": id: step is unreachable from entry "${entry}"`,
289
+ );
290
+ }
291
+ }
292
+
293
+ return maxVisits === undefined
294
+ ? { name, entry, steps }
295
+ : { name, entry, maxVisits, steps };
296
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * The addresses `http.listen` may name. A kernel port is reachable only from
3
+ * the machine itself, the local network, or a Tailscale network; a wildcard
4
+ * would open it to whatever the host is attached to.
5
+ */
6
+
7
+ import { isIP } from "node:net";
8
+ import { ConfigError } from "../config/config.ts";
9
+
10
+ /** The kinds of address an `http.listen` entry may be. */
11
+ export type ListenAddressKind =
12
+ | "loopback"
13
+ | "private"
14
+ | "link-local"
15
+ | "tailscale";
16
+
17
+ function ipv4Bytes(address: string): readonly number[] | undefined {
18
+ const parts = address.split(".");
19
+ if (parts.length !== 4) return undefined;
20
+ const bytes: number[] = [];
21
+ for (const part of parts) {
22
+ if (!/^(0|[1-9][0-9]{0,2})$/.test(part)) return undefined;
23
+ const value = Number(part);
24
+ if (value > 255) return undefined;
25
+ bytes.push(value);
26
+ }
27
+ return bytes;
28
+ }
29
+
30
+ function ipv4Group(text: string): number | undefined {
31
+ const bytes = ipv4Bytes(text);
32
+ if (bytes === undefined) return undefined;
33
+ const [first = 0, second = 0] = bytes;
34
+ return first * 256 + second;
35
+ }
36
+
37
+ function ipv6Groups(text: string): readonly number[] | undefined {
38
+ if (text.length === 0) return [];
39
+ const groups: number[] = [];
40
+ const parts = text.split(":");
41
+ for (const part of parts) {
42
+ // An embedded IPv4 address is the last part and stands for two groups.
43
+ if (part.includes(".")) {
44
+ const group = ipv4Group(part);
45
+ if (group === undefined) return undefined;
46
+ groups.push(Math.floor(group / 256), group % 256);
47
+ continue;
48
+ }
49
+ if (!/^[0-9a-fA-F]{1,4}$/.test(part)) return undefined;
50
+ groups.push(Number.parseInt(part, 16));
51
+ }
52
+ return groups;
53
+ }
54
+
55
+ function ipv6Value(address: string): bigint | undefined {
56
+ const halves = address.split("::");
57
+ if (halves.length > 2) return undefined;
58
+ const left = ipv6Groups(halves[0] ?? "");
59
+ if (left === undefined) return undefined;
60
+ let groups: number[];
61
+ if (halves.length === 2) {
62
+ const right = ipv6Groups(halves[1] ?? "");
63
+ if (right === undefined) return undefined;
64
+ const missing = 8 - left.length - right.length;
65
+ if (missing < 1) return undefined;
66
+ groups = [...left, ...Array.from({ length: missing }, () => 0), ...right];
67
+ } else {
68
+ groups = [...left];
69
+ }
70
+ if (groups.length !== 8) return undefined;
71
+ let value = 0n;
72
+ for (const group of groups) {
73
+ value = (value << 16n) | BigInt(group);
74
+ }
75
+ return value;
76
+ }
77
+
78
+ /**
79
+ * The class of an allowed listen address, or undefined when it must be
80
+ * refused. A wildcard (`0.0.0.0`, `::`) is always undefined.
81
+ */
82
+ export function listenAddressKind(
83
+ address: string,
84
+ ): ListenAddressKind | undefined {
85
+ const version = isIP(address);
86
+ if (version === 4) {
87
+ const bytes = ipv4Bytes(address);
88
+ if (bytes === undefined) return undefined;
89
+ const [first = 0, second = 0] = bytes;
90
+ if (first === 0 && second === 0 && bytes.every((byte) => byte === 0)) {
91
+ return undefined;
92
+ }
93
+ if (first === 127) return "loopback";
94
+ if (first === 10) return "private";
95
+ if (first === 172 && second >= 16 && second <= 31) return "private";
96
+ if (first === 192 && second === 168) return "private";
97
+ if (first === 169 && second === 254) return "link-local";
98
+ if (first === 100 && second >= 64 && second <= 127) return "tailscale";
99
+ return undefined;
100
+ }
101
+ if (version === 6) {
102
+ const value = ipv6Value(address);
103
+ if (value === undefined) return undefined;
104
+ if (value === 0n) return undefined;
105
+ if (value === 1n) return "loopback";
106
+ // fe80::/10
107
+ if (value >> 118n === 0x3fan) return "link-local";
108
+ // fd7a:115c:a1e0::/48
109
+ if (value >> 80n === 0xfd7a115ca1e0n) return "tailscale";
110
+ return undefined;
111
+ }
112
+ return undefined;
113
+ }
114
+
115
+ /** True when `address` may be named in `http.listen`. */
116
+ export function isAllowedListenAddress(address: string): boolean {
117
+ return listenAddressKind(address) !== undefined;
118
+ }
119
+
120
+ function refusal(address: string): string {
121
+ if (address === "0.0.0.0" || address === "::") {
122
+ return `http.listen: "${address}" is a wildcard address; name each address to listen on`;
123
+ }
124
+ return `http.listen: "${address}" is not a loopback, private, link-local or Tailscale address`;
125
+ }
126
+
127
+ /** Refuses the first entry that is not an allowed address, naming it. */
128
+ export function validateListenAddresses(listen: readonly string[]): void {
129
+ if (listen.length === 0) {
130
+ throw new ConfigError("http.listen: needs at least one address");
131
+ }
132
+ for (const address of listen) {
133
+ if (isIP(address) === 0) {
134
+ throw new ConfigError(
135
+ `http.listen: "${address}" is not an IP address`,
136
+ );
137
+ }
138
+ if (!isAllowedListenAddress(address)) {
139
+ throw new ConfigError(refusal(address));
140
+ }
141
+ }
142
+ }
@@ -0,0 +1,25 @@
1
+ export {
2
+ isAllowedListenAddress,
3
+ listenAddressKind,
4
+ validateListenAddresses,
5
+ type ListenAddressKind,
6
+ } from "./address.ts";
7
+ export { LINK_SCHEME, objectLink, pairLink } from "./link.ts";
8
+ export {
9
+ DEFAULT_HTTP_TOKEN_LABEL,
10
+ ensureHttpToken,
11
+ generateHttpToken,
12
+ readHttpToken,
13
+ rotateHttpToken,
14
+ tokensEqual,
15
+ type HttpToken,
16
+ } from "./token.ts";
17
+ export {
18
+ DEFAULT_KEEP_ALIVE_MS,
19
+ DEFAULT_STOP_TIMEOUT_MS,
20
+ displayNameOf,
21
+ HttpStopError,
22
+ startHttpServer,
23
+ type HttpServerHandle,
24
+ type HttpServerOptions,
25
+ } from "./server.ts";
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The links the app understands. An object link opens one object; a pairing
3
+ * link carries the address and the token of a `serve`, so a phone can scan it.
4
+ */
5
+
6
+ /** The scheme of every link. */
7
+ export const LINK_SCHEME = "operad://";
8
+
9
+ /**
10
+ * The link that opens one object: `operad://objects/<id>`, with the id as
11
+ * `get` takes it (`<type>:<id>`) and URL-encoded.
12
+ */
13
+ export function objectLink(type: string, id: string): string {
14
+ return `${LINK_SCHEME}objects/${encodeURIComponent(`${type}:${id}`)}`;
15
+ }
16
+
17
+ /** The link a QR code carries: `operad://pair?url=<url>&token=<token>`. */
18
+ export function pairLink(url: string, token: string): string {
19
+ return `${LINK_SCHEME}pair?url=${encodeURIComponent(url)}&token=${encodeURIComponent(token)}`;
20
+ }