@plitzi/sdk-server 0.38.13 → 0.38.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +255 -0
- package/README.md +81 -7
- package/dist/core/auth/createAuth.d.ts +5 -0
- package/dist/core/auth/createAuth.js +5 -0
- package/dist/core/auth/csrf.d.ts +25 -0
- package/dist/core/auth/csrf.js +34 -32
- package/dist/core/auth/session.d.ts +10 -2
- package/dist/core/auth/session.js +31 -6
- package/dist/core/createServer.js +4 -0
- package/dist/core/http/stages/authRoutes.js +3 -0
- package/dist/core/http/stages/crossSiteWrites.d.ts +23 -0
- package/dist/core/http/stages/crossSiteWrites.js +44 -0
- package/dist/core/http/stages/crossSiteWrites.test.d.ts +1 -0
- package/dist/core/http/stages/exchangeRoute.js +2 -0
- package/dist/core/http/stages/sessionRenewal.js +2 -1
- package/dist/core/http/stages/signInRoute.js +1 -1
- package/dist/core/http/stages/static.js +1 -1
- package/dist/core/mimeTypes.d.ts +10 -1
- package/dist/core/mimeTypes.js +2 -1
- package/dist/core/oauth/authorize.js +2 -1
- package/dist/core/requestParser.d.ts +6 -0
- package/dist/core/requestParser.js +8 -2
- package/dist/core/requestParser.test.d.ts +1 -0
- package/dist/core/server/fleet/link.d.ts +1 -1
- package/dist/core/server/fleet/stores.js +1 -1
- package/dist/core/services/action.js +1 -1
- package/dist/core/services/realtime.js +1 -1
- package/dist/core/services/registry.js +2 -0
- package/dist/core/staticFiles.d.ts +2 -1
- package/dist/core/staticFiles.js +5 -5
- package/dist/functions-api.d.ts +5 -2
- package/dist/helpers/cache/keys.d.ts +1 -0
- package/dist/helpers/cache/keys.js +4 -3
- package/dist/helpers/flagOverrides.d.ts +2 -0
- package/dist/helpers/flagOverrides.js +2 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -1
- package/dist/modules/actions/tasks/realtime.js +1 -1
- package/dist/modules/authoringHost/index.d.ts +49 -0
- package/dist/modules/authoringHost/index.js +113 -0
- package/dist/modules/authoringHost/index.test.d.ts +1 -0
- package/dist/modules/functions/contract.d.ts +5 -2
- package/dist/modules/project/serveProject.d.ts +3 -2
- package/dist/modules/project/serveProject.js +85 -15
- package/dist/modules/realtime/hub.d.ts +7 -2
- package/dist/modules/realtime/hub.js +8 -4
- package/dist/modules/realtime/index.js +14 -7
- package/dist/modules/realtime/message.d.ts +3 -0
- package/dist/modules/realtime/message.js +5 -0
- package/dist/modules/realtime/retained.d.ts +24 -0
- package/dist/modules/realtime/retained.js +47 -0
- package/dist/modules/realtime/retained.test.d.ts +1 -0
- package/dist/modules/realtime/socket.js +1 -1
- package/dist/modules/rsc/handler.js +2 -1
- package/dist/modules/runtime/elsewhere.test.d.ts +1 -0
- package/dist/modules/runtime/inside.d.ts +21 -0
- package/dist/modules/runtime/inside.js +51 -3
- package/dist/modules/runtime/ownServer.test.d.ts +1 -0
- package/dist/modules/runtime/stages.d.ts +4 -1
- package/dist/modules/ssr/prepareRender.js +3 -2
- package/dist/modules/ssr/spaceDocument.js +5 -1
- package/dist/plugins/manager.d.ts +9 -0
- package/dist/plugins/manager.js +43 -1
- package/dist/runtime.d.ts +2 -1
- package/dist/runtime.js +2 -2
- package/package.json +3 -3
- package/skills/plitzi-authoring/SKILL.md +1 -1
- package/skills/plitzi-authoring/reference/index.md +3 -2
- package/skills/plitzi-authoring/reference/layouts.md +10 -0
- package/skills/plitzi-authoring/reference/plugin-reach.md +91 -0
- package/skills/plitzi-authoring/reference/plugins.md +19 -35
- package/skills/plitzi-authoring/reference/realtime.md +11 -0
- package/skills/plitzi-authoring/reference/testing.md +3 -1
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { serverLog } from "../../helpers/serverLog.js";
|
|
2
|
+
import { PREVIEW_TOKEN_PARAM, readDraftToken } from "../../core/previewToken.js";
|
|
3
|
+
import { createServer } from "../../core/createServer.js";
|
|
4
|
+
import { isRecord } from "@plitzi/sdk-shared/helpers/isRecord";
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
8
|
+
//#region src/modules/authoringHost/index.ts
|
|
9
|
+
/** The one space the host serves, which every page is a draft of. */
|
|
10
|
+
var SPACE_ID = 1;
|
|
11
|
+
/** An id is a file's name and a query's value: nothing that could be read as a path or need escaping. */
|
|
12
|
+
var ID = /^[\w-]{1,64}$/;
|
|
13
|
+
/** A day: how long a browser remembers which page it was looking at, for a reload that lost the address. */
|
|
14
|
+
var SESSION_TTL_MS = 864e5;
|
|
15
|
+
var isDocuments = (value) => isRecord(value) && isRecord(value.schema) && isRecord(value.style);
|
|
16
|
+
/** The pages `dir` holds — what is not one is said, and left where it is. */
|
|
17
|
+
var readPages = (dir) => {
|
|
18
|
+
const pages = /* @__PURE__ */ new Map();
|
|
19
|
+
for (const file of readdirSync(dir).filter((name) => name.endsWith(".json"))) {
|
|
20
|
+
const id = file.slice(0, -5);
|
|
21
|
+
let parsed;
|
|
22
|
+
try {
|
|
23
|
+
parsed = JSON.parse(readFileSync(path.join(dir, file), "utf-8"));
|
|
24
|
+
} catch {
|
|
25
|
+
parsed = void 0;
|
|
26
|
+
}
|
|
27
|
+
if (ID.test(id) && isDocuments(parsed)) pages.set(id, {
|
|
28
|
+
schema: parsed.schema,
|
|
29
|
+
style: parsed.style
|
|
30
|
+
});
|
|
31
|
+
else serverLog.warn("AuthoringHost", `${path.join(dir, file)} is not a page this host wrote: left out`);
|
|
32
|
+
}
|
|
33
|
+
return pages;
|
|
34
|
+
};
|
|
35
|
+
var createAuthoringHost = ({ dir, frameAncestors, ...config }) => {
|
|
36
|
+
mkdirSync(dir, { recursive: true });
|
|
37
|
+
const pages = readPages(dir);
|
|
38
|
+
const fileOf = (id) => path.join(dir, `${id}.json`);
|
|
39
|
+
const keep = (id, data) => {
|
|
40
|
+
writeFileSync(fileOf(id), JSON.stringify({
|
|
41
|
+
schema: data.schema,
|
|
42
|
+
style: data.style
|
|
43
|
+
}));
|
|
44
|
+
pages.set(id, {
|
|
45
|
+
schema: data.schema,
|
|
46
|
+
style: data.style
|
|
47
|
+
});
|
|
48
|
+
};
|
|
49
|
+
const drop = (id) => {
|
|
50
|
+
if (!pages.delete(id)) return false;
|
|
51
|
+
rmSync(fileOf(id), { force: true });
|
|
52
|
+
return true;
|
|
53
|
+
};
|
|
54
|
+
const draftStore = {
|
|
55
|
+
put: (token, data) => {
|
|
56
|
+
if (ID.test(token)) keep(token, data);
|
|
57
|
+
},
|
|
58
|
+
take: (token) => {
|
|
59
|
+
const data = pages.get(token);
|
|
60
|
+
return data ? {
|
|
61
|
+
data,
|
|
62
|
+
reusable: true,
|
|
63
|
+
spaceId: SPACE_ID
|
|
64
|
+
} : void 0;
|
|
65
|
+
},
|
|
66
|
+
drop: (token) => {
|
|
67
|
+
drop(token);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
const deployment = {
|
|
71
|
+
spaceId: SPACE_ID,
|
|
72
|
+
environment: "main",
|
|
73
|
+
revision: 0,
|
|
74
|
+
...frameAncestors ? { frameAncestors } : {}
|
|
75
|
+
};
|
|
76
|
+
return {
|
|
77
|
+
server: createServer({
|
|
78
|
+
...config,
|
|
79
|
+
preview: {
|
|
80
|
+
sessionTtlMs: SESSION_TTL_MS,
|
|
81
|
+
...config.preview
|
|
82
|
+
},
|
|
83
|
+
draftStore,
|
|
84
|
+
adapters: {
|
|
85
|
+
getOfflineData: () => Promise.resolve(void 0),
|
|
86
|
+
getSpaceDeployment: (req) => {
|
|
87
|
+
const id = readDraftToken(req);
|
|
88
|
+
if (id === void 0) return Promise.resolve({ error: {
|
|
89
|
+
code: 404,
|
|
90
|
+
message: `Nothing here: each page of this host is at the address put() answered — /?${PREVIEW_TOKEN_PARAM}=<id>`
|
|
91
|
+
} });
|
|
92
|
+
if (!pages.has(id)) return Promise.resolve({ error: {
|
|
93
|
+
code: 404,
|
|
94
|
+
message: `No page "${id}" here: put() it, or it was dropped`
|
|
95
|
+
} });
|
|
96
|
+
return Promise.resolve(deployment);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}),
|
|
100
|
+
put: (documents, { id = randomBytes(16).toString("base64url") } = {}) => {
|
|
101
|
+
if (!ID.test(id)) throw new Error(`A page id is letters, digits, "-" and "_", up to 64 of them — not "${id}"`);
|
|
102
|
+
keep(id, documents);
|
|
103
|
+
return {
|
|
104
|
+
id,
|
|
105
|
+
path: `/?${PREVIEW_TOKEN_PARAM}=${id}`
|
|
106
|
+
};
|
|
107
|
+
},
|
|
108
|
+
drop,
|
|
109
|
+
ids: () => [...pages.keys()]
|
|
110
|
+
};
|
|
111
|
+
};
|
|
112
|
+
//#endregion
|
|
113
|
+
export { createAuthoringHost };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -93,8 +93,11 @@ export type FunctionContext = {
|
|
|
93
93
|
* One step a server action can take, written by the space. The shape of the platform's own tasks — addressed as
|
|
94
94
|
* `<namespace>.<action>`, drawn in the builder from `params` — run with a {@link FunctionContext} rather than the
|
|
95
95
|
* platform's full one.
|
|
96
|
+
*
|
|
97
|
+
* `R` is what `run` answers: `taskAction(task, …)` hands it, with `T`, to a page that runs the action
|
|
98
|
+
* (`useServerAction`), so `FunctionTask<{ id: string }, Habit>` is typed at both ends.
|
|
96
99
|
*/
|
|
97
|
-
export type FunctionTask<T extends Record<string, unknown> = Record<string, unknown
|
|
100
|
+
export type FunctionTask<T extends Record<string, unknown> = Record<string, unknown>, R = unknown> = {
|
|
98
101
|
namespace: string;
|
|
99
102
|
action: string;
|
|
100
103
|
title: string;
|
|
@@ -105,7 +108,7 @@ export type FunctionTask<T extends Record<string, unknown> = Record<string, unkn
|
|
|
105
108
|
* what the server allows. Over the functions' own `limits`, for this task.
|
|
106
109
|
*/
|
|
107
110
|
limits?: FunctionTimeLimits;
|
|
108
|
-
run: (params: T, ctx: FunctionContext) =>
|
|
111
|
+
run: (params: T, ctx: FunctionContext) => R | Promise<R>;
|
|
109
112
|
};
|
|
110
113
|
/** What a route's handler gets besides the request: the context, and the `:params` its key named, by name. */
|
|
111
114
|
export type FunctionRouteContext = FunctionContext & {
|
|
@@ -49,7 +49,7 @@ export type ServeProjectOptions = ServeProjectBase & ({
|
|
|
49
49
|
/** The project's server, running. */
|
|
50
50
|
export type ServedProject = {
|
|
51
51
|
server: SSRServer;
|
|
52
|
-
/** Where it
|
|
52
|
+
/** Where this machine reaches it, as `tmp/dev-server.json` records it: `http://127.0.0.1:<port>`, `https` with a certificate. */
|
|
53
53
|
url: string;
|
|
54
54
|
/** Stops watching, closes the server and the runtime — what a signal does, for a caller that stops it itself. */
|
|
55
55
|
close: () => Promise<void>;
|
|
@@ -62,7 +62,8 @@ export type ServedProject = {
|
|
|
62
62
|
* space authored. A refusal of any of the three is printed as it is — the message is the whole report, every problem
|
|
63
63
|
* and its fix, and a stack would only point inside the SDK — and the process exits with 1. What it serves:
|
|
64
64
|
*
|
|
65
|
-
* - the port: `PORT`, or 8080 — the next free one from there while developing; `HOST`, loopback by default;
|
|
65
|
+
* - the port: `PORT`, or 8080 — the next free one from there while developing; `HOST`, loopback by default; HTTPS
|
|
66
|
+
* with `TLS_CERT` and `TLS_KEY` (`plitzi cert`), unless the project's options give `tls` themselves;
|
|
66
67
|
* - its plugins: every folder of `src/plugins` built from its source and server-rendered, every one of `vendor/plugins`
|
|
67
68
|
* as it was built, each with its server half;
|
|
68
69
|
* - its code: `src/functions/`, and the space's runtime (`src/runtime/` — compiled under `dist/` when the server runs
|
|
@@ -1,23 +1,27 @@
|
|
|
1
1
|
import { consoleLogger } from "../../helpers/serverLog.js";
|
|
2
2
|
import { isFleetWorker } from "../../core/server/fleet/role.js";
|
|
3
3
|
import { loadFunctions } from "../functions/load.js";
|
|
4
|
-
import { createServer } from "../../core/createServer.js";
|
|
4
|
+
import { createServer as createServer$1 } from "../../core/createServer.js";
|
|
5
5
|
import { closeOnSignals } from "../../core/server/closeOnSignals.js";
|
|
6
6
|
import { freePort } from "../../core/freePort.js";
|
|
7
7
|
import { createCloudAdapters } from "../../adapters/cloudAdapters.js";
|
|
8
8
|
import { createJsonAdapters } from "../../adapters/jsonAdapters.js";
|
|
9
9
|
import { createFileKv } from "../actions/runtime/fileKv.js";
|
|
10
10
|
import { credentialsFromEnv } from "../actions/runtime/credentials.js";
|
|
11
|
+
import { reachOwnServer } from "../runtime/inside.js";
|
|
11
12
|
import { loadRuntime, loadRuntimeModule } from "../runtime/bundle.js";
|
|
12
13
|
import { serveRuntime } from "../runtime/stages.js";
|
|
13
14
|
import { projectPlugins, watchProjectPlugins } from "./plugins.js";
|
|
14
15
|
import { createSpaceFailure } from "./spaceFailure.js";
|
|
15
16
|
import { watchSpace } from "./watchSpace.js";
|
|
16
17
|
import { fleetKv } from "../../core/server/fleet/stores.js";
|
|
17
|
-
import {
|
|
18
|
+
import { X509Certificate } from "node:crypto";
|
|
19
|
+
import { hostname, networkInterfaces } from "node:os";
|
|
20
|
+
import { isIP } from "node:net";
|
|
18
21
|
import path from "node:path";
|
|
19
22
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
20
23
|
import { assertProjectLayout, layoutFindingText } from "@plitzi/sdk-shared/project/layout";
|
|
24
|
+
import { localNetworkName, networkAddresses } from "@plitzi/sdk-shared/project/network";
|
|
21
25
|
import { DATA_DIR, DEV_SERVER_FILE, FUNCTIONS_DIR, KV_FILE, PROJECT_TMP, PUBLIC_DIR, RUNTIME_BUNDLE, RUNTIME_ENTRY } from "@plitzi/sdk-shared/project/paths";
|
|
22
26
|
import { projectModule, projectRoot } from "@plitzi/sdk-shared/project/root";
|
|
23
27
|
import { EMPTY_SCHEMA } from "@plitzi/sdk-shared/schema/schemaConstants";
|
|
@@ -68,10 +72,53 @@ var LOOPBACK = /* @__PURE__ */ new Set([
|
|
|
68
72
|
"::1",
|
|
69
73
|
"localhost"
|
|
70
74
|
]);
|
|
75
|
+
var ANY_ADDRESS = /* @__PURE__ */ new Set(["0.0.0.0", "::"]);
|
|
76
|
+
/** An address as a URL writes it: an IPv6 one in brackets. */
|
|
77
|
+
var urlHost = (address) => address.includes(":") ? `[${address}]` : address;
|
|
78
|
+
/** Where this machine reaches a server listening on `host`: its loopback, unless it listens on one address only. */
|
|
79
|
+
var localAddress = (host) => host === "::1" ? host : LOOPBACK.has(host) || ANY_ADDRESS.has(host) ? "127.0.0.1" : host;
|
|
71
80
|
/** Where another device reaches a server listening on `host`: this machine's own network addresses, when it is open. */
|
|
72
|
-
var
|
|
81
|
+
var addressesFor = (host) => {
|
|
73
82
|
if (LOOPBACK.has(host)) return [];
|
|
74
|
-
return (host
|
|
83
|
+
return ANY_ADDRESS.has(host) ? networkAddresses(networkInterfaces()) : [host];
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* HTTPS with no code of the project's: `TLS_CERT` and `TLS_KEY` in `.env`, the PEM certificate and its key — what
|
|
87
|
+
* `plitzi cert` makes, for a tablet on the Wi-Fi, whose browser gives a page served over http no microphone, camera,
|
|
88
|
+
* clipboard or service worker. Relative to the project's root.
|
|
89
|
+
*/
|
|
90
|
+
var tlsFromEnv = (root) => {
|
|
91
|
+
const { TLS_CERT: cert, TLS_KEY: key } = process.env;
|
|
92
|
+
if (!cert && !key) return;
|
|
93
|
+
if (!cert || !key) throw new Error("Set both TLS_CERT and TLS_KEY in .env — the certificate and its key — or neither.");
|
|
94
|
+
const read = (name, file) => {
|
|
95
|
+
try {
|
|
96
|
+
return readFileSync(path.resolve(root, file));
|
|
97
|
+
} catch {
|
|
98
|
+
throw new Error(`${name} in .env is "${file}", which cannot be read — \`plitzi cert\` makes the pair.`);
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
return {
|
|
102
|
+
cert: read("TLS_CERT", cert),
|
|
103
|
+
key: read("TLS_KEY", key)
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
/**
|
|
107
|
+
* What another device opens this server by, its certificate considered: every network address, and this machine's
|
|
108
|
+
* mDNS name when the certificate names it. The addresses the certificate does not name are said apart — a device that
|
|
109
|
+
* opens one is refused the page, which happens when the router hands this machine a new address.
|
|
110
|
+
*/
|
|
111
|
+
var reachedBy = (addresses, tls) => {
|
|
112
|
+
if (!tls || addresses.length === 0) return {
|
|
113
|
+
names: addresses,
|
|
114
|
+
unnamed: []
|
|
115
|
+
};
|
|
116
|
+
const certificate = new X509Certificate(tls.cert);
|
|
117
|
+
const name = localNetworkName(hostname());
|
|
118
|
+
return {
|
|
119
|
+
names: [...addresses, ...certificate.checkHost(name) ? [name] : []],
|
|
120
|
+
unnamed: addresses.filter((address) => (isIP(address) ? certificate.checkIP(address) : certificate.checkHost(address)) === void 0)
|
|
121
|
+
};
|
|
75
122
|
};
|
|
76
123
|
var actionLookups = (actions, connectors, credentials) => ({
|
|
77
124
|
getAction: (_spaceId, actionId) => Promise.resolve(actions.find((entry) => entry.id === actionId)),
|
|
@@ -118,8 +165,24 @@ var startProject = async (options) => {
|
|
|
118
165
|
if (developing) for (const warning of layout) console.warn(`[layout] ${layoutFindingText(warning)}`);
|
|
119
166
|
const host = process.env.HOST ?? "127.0.0.1";
|
|
120
167
|
const port = process.env.PORT ? Number(process.env.PORT) : developing ? await freePort(8080, host) : 8080;
|
|
121
|
-
|
|
122
|
-
const
|
|
168
|
+
const tls = serverOptions.tls ?? tlsFromEnv(root);
|
|
169
|
+
const scheme = tls ? "https" : "http";
|
|
170
|
+
const localUrl = `${scheme}://${urlHost(localAddress(host))}:${String(port)}`;
|
|
171
|
+
const reached = reachedBy(addressesFor(host), tls);
|
|
172
|
+
const network = reached.names.map((address) => `${scheme}://${urlHost(address)}:${String(port)}`);
|
|
173
|
+
/**
|
|
174
|
+
* Where people reach this server: `PUBLIC_URL` behind a proxy; open to the network, the address another device uses
|
|
175
|
+
* — what an OAuth provider sends a tablet back to; this machine's otherwise.
|
|
176
|
+
*/
|
|
177
|
+
const publicUrl = (process.env.PUBLIC_URL ?? network.at(0) ?? localUrl).replace(/\/+$/, "");
|
|
178
|
+
if (tls && process.env.PUBLIC_URL === void 0) await reachOwnServer({
|
|
179
|
+
publicUrl,
|
|
180
|
+
listener: {
|
|
181
|
+
host: localAddress(host),
|
|
182
|
+
port
|
|
183
|
+
},
|
|
184
|
+
cert: tls.cert
|
|
185
|
+
});
|
|
123
186
|
const { space, failure, name } = await spaceToServe(options, developing, root);
|
|
124
187
|
const plugins = await projectPlugins(root);
|
|
125
188
|
const held = options.space ? { ...space ? { documents: {
|
|
@@ -159,10 +222,11 @@ var startProject = async (options) => {
|
|
|
159
222
|
});
|
|
160
223
|
return keptKv;
|
|
161
224
|
});
|
|
162
|
-
const server = createServer({
|
|
225
|
+
const server = createServer$1({
|
|
163
226
|
logLevel: process.argv.includes("--verbose") ? "info" : "warn",
|
|
164
227
|
logger: consoleLogger,
|
|
165
228
|
...serverOptions,
|
|
229
|
+
...tls ? { tls } : {},
|
|
166
230
|
port,
|
|
167
231
|
devMode: serverOptions.devMode ?? developing,
|
|
168
232
|
devReload: serverOptions.devReload ?? serverOptions.devMode ?? developing,
|
|
@@ -181,19 +245,24 @@ var startProject = async (options) => {
|
|
|
181
245
|
...serverOptions.action,
|
|
182
246
|
...actions ? { lookups: actionLookups(actions, connectors, credentialsFromEnv()) } : {}
|
|
183
247
|
}
|
|
184
|
-
}, {
|
|
248
|
+
}, {
|
|
249
|
+
preAuth: [spaceFailure.stage],
|
|
250
|
+
data: runtime ? [runtime.stage] : []
|
|
251
|
+
});
|
|
185
252
|
await server.listen(port, host);
|
|
186
|
-
const url = `http://127.0.0.1:${String(port)}`;
|
|
187
253
|
if (speaks) {
|
|
188
254
|
mkdirSync(path.join(root, PROJECT_TMP), { recursive: true });
|
|
189
255
|
writeFileSync(path.join(root, DEV_SERVER_FILE), `${JSON.stringify({
|
|
190
256
|
name,
|
|
191
257
|
port,
|
|
192
|
-
url
|
|
258
|
+
url: localUrl,
|
|
259
|
+
network,
|
|
260
|
+
publicUrl
|
|
193
261
|
}, null, 2)}\n`);
|
|
194
|
-
console.log(`pages on ${
|
|
195
|
-
|
|
196
|
-
if (
|
|
262
|
+
console.log(`pages on ${localUrl}/`);
|
|
263
|
+
if (network.length > 0) console.log(`also on ${network.map((address) => `${address}/`).join(", ")} — anyone on this network can open it (HOST=${host})`);
|
|
264
|
+
else if (developing && LOOPBACK.has(host)) console.log("only this machine opens it: HOST=0.0.0.0 in .env opens it to your network (a phone on the Wi-Fi)");
|
|
265
|
+
if (reached.unnamed.length > 0) console.warn(`[tls] the certificate does not name ${reached.unnamed.join(", ")}: a device that opens it there is refused — \`plitzi cert\` makes one for this machine as it is now`);
|
|
197
266
|
}
|
|
198
267
|
const watching = developing ? [...held ? [watchSpace(root, (authored) => {
|
|
199
268
|
held.documents = authored;
|
|
@@ -209,7 +278,7 @@ var startProject = async (options) => {
|
|
|
209
278
|
const stopListening = closeOnSignals({ close });
|
|
210
279
|
return {
|
|
211
280
|
server,
|
|
212
|
-
url,
|
|
281
|
+
url: localUrl,
|
|
213
282
|
close: async () => {
|
|
214
283
|
stopListening();
|
|
215
284
|
await close();
|
|
@@ -224,7 +293,8 @@ var startProject = async (options) => {
|
|
|
224
293
|
* space authored. A refusal of any of the three is printed as it is — the message is the whole report, every problem
|
|
225
294
|
* and its fix, and a stack would only point inside the SDK — and the process exits with 1. What it serves:
|
|
226
295
|
*
|
|
227
|
-
* - the port: `PORT`, or 8080 — the next free one from there while developing; `HOST`, loopback by default;
|
|
296
|
+
* - the port: `PORT`, or 8080 — the next free one from there while developing; `HOST`, loopback by default; HTTPS
|
|
297
|
+
* with `TLS_CERT` and `TLS_KEY` (`plitzi cert`), unless the project's options give `tls` themselves;
|
|
228
298
|
* - its plugins: every folder of `src/plugins` built from its source and server-rendered, every one of `vendor/plugins`
|
|
229
299
|
* as it was built, each with its server half;
|
|
230
300
|
* - its code: `src/functions/`, and the space's runtime (`src/runtime/` — compiled under `dist/` when the server runs
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { RealtimeRetained } from './retained';
|
|
1
2
|
import { ChannelDeclaration, PubSubAdapter, RealtimeMessage, RealtimeSender } from '@plitzi/sdk-shared';
|
|
2
3
|
/** The space a connection belongs to: its topics are that space's and no other's. */
|
|
3
4
|
export type RealtimeSpace = {
|
|
@@ -38,7 +39,7 @@ export type RealtimeHub = ReturnType<typeof createRealtimeHub>;
|
|
|
38
39
|
* A hundred pages on one board are a hundred connections here and a single subscription to the adapter: a message
|
|
39
40
|
* arrives once and is written to each of them. The last one to leave a topic unsubscribes it.
|
|
40
41
|
*/
|
|
41
|
-
export declare const createRealtimeHub: (pubsub: PubSubAdapter) => {
|
|
42
|
+
export declare const createRealtimeHub: (pubsub: PubSubAdapter, retained: RealtimeRetained) => {
|
|
42
43
|
publish: (space: RealtimeSpace, message: RealtimeMessage) => Promise<void>;
|
|
43
44
|
from: (connection: RealtimeConnection, topic: string, type: string, data: unknown, echo?: boolean) => RealtimeMessage;
|
|
44
45
|
find: (token: string) => RealtimeConnection | undefined;
|
|
@@ -47,7 +48,11 @@ export declare const createRealtimeHub: (pubsub: PubSubAdapter) => {
|
|
|
47
48
|
* none. What stops a grant that is already in use; `grants.revoke` is what stops it being used again.
|
|
48
49
|
*/
|
|
49
50
|
revoke: (space: RealtimeSpace, topic: string, grant?: string) => Promise<void>;
|
|
50
|
-
/**
|
|
51
|
+
/**
|
|
52
|
+
* Subscribes a new connection to its topics, hands it what each `retain: true` one keeps, and tells the members of
|
|
53
|
+
* each presence channel it arrived. What is kept is read AFTER joining, so nothing said in between is missed; a
|
|
54
|
+
* message heard live and then kept arrives twice, and the page keeps the newer of a type by its `at`.
|
|
55
|
+
*/
|
|
51
56
|
connect: (connection: RealtimeConnection) => Promise<void>;
|
|
52
57
|
/** Unsubscribes a connection that went away, and tells the channels it announced itself on. */
|
|
53
58
|
disconnect: (connection: RealtimeConnection) => Promise<void>;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { warnRealtime } from "./failure.js";
|
|
2
|
+
import { isMessage } from "./message.js";
|
|
2
3
|
import { JOIN_TYPE, LEAVE_TYPE, REVOKED_TYPE } from "@plitzi/sdk-shared/realtime";
|
|
3
4
|
//#region src/modules/realtime/hub.ts
|
|
4
5
|
/** A space's topic, as the adapter knows it: namespaced, so two spaces never hear each other. */
|
|
@@ -10,8 +11,6 @@ var adapterTopic = ({ spaceId, environment }, topic) => `${spaceId}/${environmen
|
|
|
10
11
|
*/
|
|
11
12
|
var REVOKE_TYPE = "$revoke";
|
|
12
13
|
var revokedGrant = (data) => typeof data === "object" && data !== null && "grant" in data && typeof data.grant === "string" ? data.grant : void 0;
|
|
13
|
-
/** A message as the adapter carried it — written by this module, but read from a transport that is not. */
|
|
14
|
-
var isMessage = (value) => typeof value === "object" && value !== null && "topic" in value && typeof value.topic === "string" && "type" in value && typeof value.type === "string" && "from" in value && typeof value.from === "string" && "at" in value && typeof value.at === "number";
|
|
15
14
|
var parse = (raw) => {
|
|
16
15
|
try {
|
|
17
16
|
const value = JSON.parse(raw);
|
|
@@ -26,7 +25,7 @@ var parse = (raw) => {
|
|
|
26
25
|
* A hundred pages on one board are a hundred connections here and a single subscription to the adapter: a message
|
|
27
26
|
* arrives once and is written to each of them. The last one to leave a topic unsubscribes it.
|
|
28
27
|
*/
|
|
29
|
-
var createRealtimeHub = (pubsub) => {
|
|
28
|
+
var createRealtimeHub = (pubsub, retained) => {
|
|
30
29
|
const byToken = /* @__PURE__ */ new Map();
|
|
31
30
|
const local = /* @__PURE__ */ new Map();
|
|
32
31
|
const publish = (space, message) => pubsub.publish(adapterTopic(space, message.topic), JSON.stringify(message));
|
|
@@ -110,11 +109,16 @@ var createRealtimeHub = (pubsub) => {
|
|
|
110
109
|
from: "server",
|
|
111
110
|
at: Date.now()
|
|
112
111
|
}),
|
|
113
|
-
/**
|
|
112
|
+
/**
|
|
113
|
+
* Subscribes a new connection to its topics, hands it what each `retain: true` one keeps, and tells the members of
|
|
114
|
+
* each presence channel it arrived. What is kept is read AFTER joining, so nothing said in between is missed; a
|
|
115
|
+
* message heard live and then kept arrives twice, and the page keeps the newer of a type by its `at`.
|
|
116
|
+
*/
|
|
114
117
|
connect: async (connection) => {
|
|
115
118
|
byToken.set(connection.token, connection);
|
|
116
119
|
for (const [topic, declaration] of connection.topics) {
|
|
117
120
|
await join(connection, topic);
|
|
121
|
+
if (declaration.retain === true) (await retained.of(connection.space, topic)).forEach((message) => connection.send("message", message));
|
|
118
122
|
if (declaration.presence && !connection.observer) await publish(connection.space, from(connection, topic, JOIN_TYPE, null));
|
|
119
123
|
}
|
|
120
124
|
},
|
|
@@ -4,6 +4,7 @@ import { createRealtimeGrants } from "./grants.js";
|
|
|
4
4
|
import { createChannelResolver } from "./declarations.js";
|
|
5
5
|
import { createRealtimeHub } from "./hub.js";
|
|
6
6
|
import { createMemoryPubSub } from "./memoryPubSub.js";
|
|
7
|
+
import { createRealtimeRetained } from "./retained.js";
|
|
7
8
|
import { handleRealtimePublish, handleRealtimeSubscribe } from "./handlers.js";
|
|
8
9
|
import { handleRealtimeSocket } from "./socket.js";
|
|
9
10
|
import { matchChannel } from "@plitzi/sdk-shared/realtime";
|
|
@@ -20,9 +21,11 @@ var realtimeModuleFor = (config) => {
|
|
|
20
21
|
if (config.realtime === false || !getOfflineData) return;
|
|
21
22
|
const existing = modules.get(config);
|
|
22
23
|
if (existing) return existing;
|
|
23
|
-
const
|
|
24
|
+
const kv = config.action?.kv ?? fleetStore("realtime.kv", KV_METHODS) ?? createMemoryKv();
|
|
25
|
+
const retained = createRealtimeRetained(kv);
|
|
26
|
+
const hub = createRealtimeHub(config.realtime?.pubsub ?? createMemoryPubSub(), retained);
|
|
24
27
|
const resolveChannels = createChannelResolver(getOfflineData);
|
|
25
|
-
const grants = createRealtimeGrants(
|
|
28
|
+
const grants = createRealtimeGrants(kv);
|
|
26
29
|
const module = {
|
|
27
30
|
hub,
|
|
28
31
|
path: config.realtime?.path ?? "/_realtime",
|
|
@@ -32,16 +35,20 @@ var realtimeModuleFor = (config) => {
|
|
|
32
35
|
grants,
|
|
33
36
|
close: () => hub.closeAll(),
|
|
34
37
|
publish: async (space, topic, type, data) => {
|
|
35
|
-
const
|
|
36
|
-
if (!
|
|
38
|
+
const match = matchChannel(topic, await resolveChannels(space.spaceId, space.environment));
|
|
39
|
+
if (!match) throw new Error(`No channel of this space matches "${topic}": declare it in the space's \`channels\``);
|
|
37
40
|
if (!SERVER_TYPE.test(type)) throw new Error("A message type is 1-64 of A-Z a-z 0-9 _ . : -");
|
|
38
|
-
|
|
41
|
+
const retain = match.declaration.retain === true;
|
|
42
|
+
const message = {
|
|
39
43
|
topic,
|
|
40
44
|
type,
|
|
41
45
|
data,
|
|
42
46
|
from: "server",
|
|
43
|
-
at: Date.now()
|
|
44
|
-
|
|
47
|
+
at: Date.now(),
|
|
48
|
+
...retain ? { retained: true } : {}
|
|
49
|
+
};
|
|
50
|
+
if (retain) await retained.keep(space, message);
|
|
51
|
+
await hub.publish(space, message);
|
|
45
52
|
},
|
|
46
53
|
grant: async (space, topic, ttlSeconds) => {
|
|
47
54
|
const match = matchChannel(topic, await resolveChannels(space.spaceId, space.environment));
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
//#region src/modules/realtime/message.ts
|
|
2
|
+
/** A message as a transport or a store carried it — written by this module, but read from something that is not. */
|
|
3
|
+
var isMessage = (value) => typeof value === "object" && value !== null && "topic" in value && typeof value.topic === "string" && "type" in value && typeof value.type === "string" && "from" in value && typeof value.from === "string" && "at" in value && typeof value.at === "number";
|
|
4
|
+
//#endregion
|
|
5
|
+
export { isMessage };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { RealtimeSpace } from './hub';
|
|
2
|
+
import { ActionKvAdapter } from '../actions/types';
|
|
3
|
+
import { RealtimeMessage } from '@plitzi/sdk-shared';
|
|
4
|
+
/** The most types one topic keeps: state a page shows, never a log written one type per entry. */
|
|
5
|
+
export declare const MAX_RETAINED_TYPES = 64;
|
|
6
|
+
/** The most one topic keeps, as JSON: every page that joins is sent all of it. */
|
|
7
|
+
export declare const MAX_RETAINED_BYTES: number;
|
|
8
|
+
export type RealtimeRetained = {
|
|
9
|
+
/**
|
|
10
|
+
* Keeps `message` as its topic's latest of its type — or, with `null` data, forgets the type. Refused, before anything
|
|
11
|
+
* is sent, past {@link MAX_RETAINED_TYPES} types or {@link MAX_RETAINED_BYTES} for the topic.
|
|
12
|
+
*/
|
|
13
|
+
keep: (space: RealtimeSpace, message: RealtimeMessage) => Promise<void>;
|
|
14
|
+
/** What a topic keeps: the latest message of each type, oldest first. */
|
|
15
|
+
of: (space: RealtimeSpace, topic: string) => Promise<RealtimeMessage[]>;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* The messages of `retain: true` channels, kept in the store the actions' `kv` uses — beside the grants, so one replica
|
|
19
|
+
* keeps what another hands a page that joins, and nothing new has to be configured for it.
|
|
20
|
+
*
|
|
21
|
+
* One value per topic, written by compare-and-swap: two types said at once on one topic are both kept, never one
|
|
22
|
+
* written over the other. Keyed under `realtime-retained:`, which no key a flow writes can reach.
|
|
23
|
+
*/
|
|
24
|
+
export declare const createRealtimeRetained: (store: ActionKvAdapter) => RealtimeRetained;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { isMessage } from "./message.js";
|
|
2
|
+
/** The most one topic keeps, as JSON: every page that joins is sent all of it. */
|
|
3
|
+
var MAX_RETAINED_BYTES = 524288;
|
|
4
|
+
/** How many times a write is tried while other writes on the same topic keep landing first. */
|
|
5
|
+
var ATTEMPTS = 8;
|
|
6
|
+
/** A topic's kept messages, by type, as stored — read from a store something else could have written. */
|
|
7
|
+
var parseKept = (raw) => {
|
|
8
|
+
try {
|
|
9
|
+
const value = JSON.parse(raw ?? "{}");
|
|
10
|
+
if (typeof value !== "object" || value === null) return {};
|
|
11
|
+
return Object.fromEntries(Object.entries(value).filter((entry) => isMessage(entry[1])));
|
|
12
|
+
} catch {
|
|
13
|
+
return {};
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* The messages of `retain: true` channels, kept in the store the actions' `kv` uses — beside the grants, so one replica
|
|
18
|
+
* keeps what another hands a page that joins, and nothing new has to be configured for it.
|
|
19
|
+
*
|
|
20
|
+
* One value per topic, written by compare-and-swap: two types said at once on one topic are both kept, never one
|
|
21
|
+
* written over the other. Keyed under `realtime-retained:`, which no key a flow writes can reach.
|
|
22
|
+
*/
|
|
23
|
+
var createRealtimeRetained = (store) => {
|
|
24
|
+
const key = ({ spaceId, environment }, topic) => `realtime-retained:${String(spaceId)}:${environment}:${topic}`;
|
|
25
|
+
return {
|
|
26
|
+
keep: async (space, message) => {
|
|
27
|
+
const at = key(space, message.topic);
|
|
28
|
+
for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {
|
|
29
|
+
const raw = await store.get(at);
|
|
30
|
+
const kept = parseKept(raw);
|
|
31
|
+
const others = Object.fromEntries(Object.entries(kept).filter(([type]) => type !== message.type));
|
|
32
|
+
const next = message.data === null ? others : {
|
|
33
|
+
...others,
|
|
34
|
+
[message.type]: message
|
|
35
|
+
};
|
|
36
|
+
if (Object.keys(next).length > 64) throw new Error(`"${message.topic}" keeps at most ${String(64)} types of message: keep fewer, larger ones (one \`lists\` holding every list), or forget one with null`);
|
|
37
|
+
const written = JSON.stringify(next);
|
|
38
|
+
if (Buffer.byteLength(written) > 524288) throw new Error(`"${message.topic}" keeps at most ${String(MAX_RETAINED_BYTES / 1024)} KB, and "${message.type}" would take it past that: every page that joins is sent all of it — keep there what the screens show, the rest in kv`);
|
|
39
|
+
if (await store.swap(at, raw, written)) return;
|
|
40
|
+
}
|
|
41
|
+
throw new Error(`"${message.topic}" changed under ${String(ATTEMPTS)} writes in a row, so "${message.type}" was not kept: publish it again`);
|
|
42
|
+
},
|
|
43
|
+
of: async (space, topic) => Object.values(parseKept(await store.get(key(space, topic)))).sort((a, b) => a.at - b.at)
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
//#endregion
|
|
47
|
+
export { MAX_RETAINED_BYTES, createRealtimeRetained };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { requestOrigin } from "../../core/requestParser.js";
|
|
1
2
|
import { warnRealtime } from "./failure.js";
|
|
2
3
|
import { admit, answer, connectionFor, publishFrom } from "./handlers.js";
|
|
3
|
-
import { requestOrigin } from "../../core/requestParser.js";
|
|
4
4
|
import { frameText } from "../../helpers/wsFrame.js";
|
|
5
5
|
//#region src/modules/realtime/socket.ts
|
|
6
6
|
/** The largest frame a page may send: well above the largest message a channel may declare, and bounded. */
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { serverLog } from "../../helpers/serverLog.js";
|
|
2
|
+
import { requestAuthority } from "../../core/requestParser.js";
|
|
2
3
|
import { requestFlagOverrides } from "../../helpers/flagOverrides.js";
|
|
3
4
|
import { resolveDebugAuthorization } from "../../helpers/debugAuthorization.js";
|
|
4
5
|
import { DEFAULT_TTL_MS } from "../../helpers/cache/defaults.js";
|
|
@@ -114,7 +115,7 @@ var handleRsc = async (req, res, config, _pluginManager, cache, signal) => {
|
|
|
114
115
|
* A tester forcing flags from the dev tools sees data for features nobody else has on — and must never be handed a
|
|
115
116
|
* slice resolved without them. Their refreshes go around the cache both ways, like a draft's.
|
|
116
117
|
*/
|
|
117
|
-
const forcingFlags = Object.keys(forcedFlagsFromCookies(req.headers.cookie, req
|
|
118
|
+
const forcingFlags = Object.keys(forcedFlagsFromCookies(req.headers.cookie, requestAuthority(req))).length > 0;
|
|
118
119
|
const uncached = previewing || forcingFlags;
|
|
119
120
|
const ttlMs = config.rsc?.cacheTtlMs ?? DEFAULT_TTL_MS.rsc;
|
|
120
121
|
const isAuthenticated = !!req.ctx.user;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -13,3 +13,24 @@ export declare const reachSpaceInside: ({ publicUrl, insideUrl }: {
|
|
|
13
13
|
publicUrl: string;
|
|
14
14
|
insideUrl: string;
|
|
15
15
|
}) => Promise<void>;
|
|
16
|
+
export type OwnServer = {
|
|
17
|
+
/** Where people reach this server — the address its code writes and fetches. */
|
|
18
|
+
publicUrl: string;
|
|
19
|
+
/** Where this machine reaches it: the address and port it listens on. */
|
|
20
|
+
listener: {
|
|
21
|
+
host: string;
|
|
22
|
+
port: number;
|
|
23
|
+
};
|
|
24
|
+
/** The certificate it serves, PEM: the one a connection to it has to present to be taken as this server. */
|
|
25
|
+
cert: string | Buffer;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* A self-hosted server serving TLS itself, reached from its own process — the runtime calling its own MCP, a function
|
|
29
|
+
* calling a route of its own space: every request to its public address connects to its listener on this machine.
|
|
30
|
+
*
|
|
31
|
+
* Its certificate is usually a local one (mkcert, for a tablet on the Wi-Fi), which the browsers on that network were
|
|
32
|
+
* told to trust and Node was not, so these requests failed whatever the address said. They are taken when the peer
|
|
33
|
+
* presents exactly this server's certificate — its fingerprint, not a chain — and refused otherwise; nothing else the
|
|
34
|
+
* process reaches is verified any less.
|
|
35
|
+
*/
|
|
36
|
+
export declare const reachOwnServer: ({ publicUrl, listener, cert }: OwnServer) => Promise<void>;
|