@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.
Files changed (73) hide show
  1. package/CHANGELOG.md +255 -0
  2. package/README.md +81 -7
  3. package/dist/core/auth/createAuth.d.ts +5 -0
  4. package/dist/core/auth/createAuth.js +5 -0
  5. package/dist/core/auth/csrf.d.ts +25 -0
  6. package/dist/core/auth/csrf.js +34 -32
  7. package/dist/core/auth/session.d.ts +10 -2
  8. package/dist/core/auth/session.js +31 -6
  9. package/dist/core/createServer.js +4 -0
  10. package/dist/core/http/stages/authRoutes.js +3 -0
  11. package/dist/core/http/stages/crossSiteWrites.d.ts +23 -0
  12. package/dist/core/http/stages/crossSiteWrites.js +44 -0
  13. package/dist/core/http/stages/crossSiteWrites.test.d.ts +1 -0
  14. package/dist/core/http/stages/exchangeRoute.js +2 -0
  15. package/dist/core/http/stages/sessionRenewal.js +2 -1
  16. package/dist/core/http/stages/signInRoute.js +1 -1
  17. package/dist/core/http/stages/static.js +1 -1
  18. package/dist/core/mimeTypes.d.ts +10 -1
  19. package/dist/core/mimeTypes.js +2 -1
  20. package/dist/core/oauth/authorize.js +2 -1
  21. package/dist/core/requestParser.d.ts +6 -0
  22. package/dist/core/requestParser.js +8 -2
  23. package/dist/core/requestParser.test.d.ts +1 -0
  24. package/dist/core/server/fleet/link.d.ts +1 -1
  25. package/dist/core/server/fleet/stores.js +1 -1
  26. package/dist/core/services/action.js +1 -1
  27. package/dist/core/services/realtime.js +1 -1
  28. package/dist/core/services/registry.js +2 -0
  29. package/dist/core/staticFiles.d.ts +2 -1
  30. package/dist/core/staticFiles.js +5 -5
  31. package/dist/functions-api.d.ts +5 -2
  32. package/dist/helpers/cache/keys.d.ts +1 -0
  33. package/dist/helpers/cache/keys.js +4 -3
  34. package/dist/helpers/flagOverrides.d.ts +2 -0
  35. package/dist/helpers/flagOverrides.js +2 -1
  36. package/dist/index.d.ts +2 -0
  37. package/dist/index.js +2 -1
  38. package/dist/modules/actions/tasks/realtime.js +1 -1
  39. package/dist/modules/authoringHost/index.d.ts +49 -0
  40. package/dist/modules/authoringHost/index.js +113 -0
  41. package/dist/modules/authoringHost/index.test.d.ts +1 -0
  42. package/dist/modules/functions/contract.d.ts +5 -2
  43. package/dist/modules/project/serveProject.d.ts +3 -2
  44. package/dist/modules/project/serveProject.js +85 -15
  45. package/dist/modules/realtime/hub.d.ts +7 -2
  46. package/dist/modules/realtime/hub.js +8 -4
  47. package/dist/modules/realtime/index.js +14 -7
  48. package/dist/modules/realtime/message.d.ts +3 -0
  49. package/dist/modules/realtime/message.js +5 -0
  50. package/dist/modules/realtime/retained.d.ts +24 -0
  51. package/dist/modules/realtime/retained.js +47 -0
  52. package/dist/modules/realtime/retained.test.d.ts +1 -0
  53. package/dist/modules/realtime/socket.js +1 -1
  54. package/dist/modules/rsc/handler.js +2 -1
  55. package/dist/modules/runtime/elsewhere.test.d.ts +1 -0
  56. package/dist/modules/runtime/inside.d.ts +21 -0
  57. package/dist/modules/runtime/inside.js +51 -3
  58. package/dist/modules/runtime/ownServer.test.d.ts +1 -0
  59. package/dist/modules/runtime/stages.d.ts +4 -1
  60. package/dist/modules/ssr/prepareRender.js +3 -2
  61. package/dist/modules/ssr/spaceDocument.js +5 -1
  62. package/dist/plugins/manager.d.ts +9 -0
  63. package/dist/plugins/manager.js +43 -1
  64. package/dist/runtime.d.ts +2 -1
  65. package/dist/runtime.js +2 -2
  66. package/package.json +3 -3
  67. package/skills/plitzi-authoring/SKILL.md +1 -1
  68. package/skills/plitzi-authoring/reference/index.md +3 -2
  69. package/skills/plitzi-authoring/reference/layouts.md +10 -0
  70. package/skills/plitzi-authoring/reference/plugin-reach.md +91 -0
  71. package/skills/plitzi-authoring/reference/plugins.md +19 -35
  72. package/skills/plitzi-authoring/reference/realtime.md +11 -0
  73. package/skills/plitzi-authoring/reference/testing.md +3 -1
@@ -1,4 +1,4 @@
1
- import { isIP } from "node:net";
1
+ import { BlockList, isIP } from "node:net";
2
2
  //#region src/core/auth/session.ts
3
3
  var LOCAL_HOSTS = [
4
4
  "localhost",
@@ -10,6 +10,30 @@ var LOCAL_HOSTS = [
10
10
  * refuse one on a single-label host) and lax SameSite, because Secure + SameSite=None over plain http is dropped.
11
11
  */
12
12
  var isLocalHost = (hostname) => LOCAL_HOSTS.includes(hostname) || hostname.endsWith(".localhost");
13
+ /**
14
+ * The addresses a home or office network hands out — RFC 1918, link-local, the shared range a mesh VPN (Tailscale)
15
+ * gives each device, IPv6 unique- and link-local — which a phone on the same Wi-Fi opens a development server on.
16
+ */
17
+ var PRIVATE_NETWORK = new BlockList();
18
+ PRIVATE_NETWORK.addSubnet("10.0.0.0", 8);
19
+ PRIVATE_NETWORK.addSubnet("172.16.0.0", 12);
20
+ PRIVATE_NETWORK.addSubnet("192.168.0.0", 16);
21
+ PRIVATE_NETWORK.addSubnet("169.254.0.0", 16);
22
+ PRIVATE_NETWORK.addSubnet("100.64.0.0", 10);
23
+ PRIVATE_NETWORK.addSubnet("fc00::", 7, "ipv6");
24
+ PRIVATE_NETWORK.addSubnet("fe80::", 10, "ipv6");
25
+ /**
26
+ * Whether the host is this machine as another device on its network reaches it: a private address, or the name
27
+ * mDNS gives it (`studio.local` — one label before `.local`, so a deployment's own `app.example.local` sub-domains,
28
+ * which share cookies across siblings over https, are not taken for one). Such a server is opened over plain http
29
+ * from a tablet, and gets the local cookie profile: a Secure cookie written over http is dropped.
30
+ */
31
+ var isPrivateNetworkHost = (hostname) => {
32
+ const address = hostname.replace(/^\[(.*)\]$/, "$1");
33
+ const family = isIP(address);
34
+ if (family === 0) return /^[^.]+\.local$/.test(hostname);
35
+ return PRIVATE_NETWORK.check(address, family === 4 ? "ipv4" : "ipv6");
36
+ };
13
37
  var isIpAddress = (hostname) => isIP(hostname) !== 0;
14
38
  /**
15
39
  * The last two labels of the host, so a session established on one sub-domain is carried by its siblings — an app
@@ -17,7 +41,7 @@ var isIpAddress = (hostname) => isIP(hostname) !== 0;
17
41
  * Domain on a single-label host, and one written for an address would never be sent back to it.
18
42
  */
19
43
  var registrableDomain = (hostname) => {
20
- if (isLocalHost(hostname) || isIpAddress(hostname)) return;
44
+ if (isLocalHost(hostname) || isIpAddress(hostname) || isPrivateNetworkHost(hostname)) return;
21
45
  const match = /([^.]+\.[^.]+)$/.exec(hostname);
22
46
  return match ? `.${match[1]}` : void 0;
23
47
  };
@@ -28,11 +52,12 @@ var resolve = (value, hostname, fallback) => {
28
52
  /**
29
53
  * Everything about how a session cookie is written, derived from the request host unless the deployment says
30
54
  * otherwise. The defaults are the ones a server on a real domain needs: a cookie shared across sub-domains, and
31
- * SameSite=None + Secure so it survives the app and the API being different hosts. A local server gets the
32
- * opposite, because Secure + SameSite=None over plain http is dropped by every browser.
55
+ * SameSite=None + Secure so it survives the app and the API being different hosts. A local server — this machine, or
56
+ * this machine as its network reaches it — gets the opposite, because Secure + SameSite=None over plain http is
57
+ * dropped by every browser.
33
58
  */
34
59
  var sessionCookieParams = (hostname, config = {}) => {
35
- const local = isLocalHost(hostname);
60
+ const local = isLocalHost(hostname) || isPrivateNetworkHost(hostname);
36
61
  return {
37
62
  name: resolve(config.name, hostname, "plitzi_session"),
38
63
  domain: resolve(config.domain, hostname, registrableDomain(hostname)),
@@ -209,4 +234,4 @@ var createSessionCookies = (config) => ({
209
234
  }
210
235
  });
211
236
  //#endregion
212
- export { appendCookies, clearFlowCookie, clearSessionCookies, createSessionCookies, isLocalHost, parseSessionHint, readFlowCookie, readRefreshToken, readRenewalGuard, readSessionHint, readSessionToken, registrableDomain, sessionCookieParams, sessionHintCookieName, sessionHintValue, sessionReturnTarget, writeFlowCookie, writeRenewalGuard, writeSessionCookies };
237
+ export { appendCookies, clearFlowCookie, clearSessionCookies, createSessionCookies, isLocalHost, isPrivateNetworkHost, parseSessionHint, readFlowCookie, readRefreshToken, readRenewalGuard, readSessionHint, readSessionToken, registrableDomain, sessionCookieParams, sessionHintCookieName, sessionHintValue, sessionReturnTarget, writeFlowCookie, writeRenewalGuard, writeSessionCookies };
@@ -82,6 +82,10 @@ var createServer = ({ auth, sessionRenewal, ...config }, extensions) => {
82
82
  exchangePath: false,
83
83
  ...config,
84
84
  authCookie: config.authCookie ?? auth.cookieConfig,
85
+ crossSiteWrites: {
86
+ ...config.crossSiteWrites,
87
+ origins: [...config.crossSiteWrites?.origins ?? [], ...auth.platformOrigins]
88
+ },
85
89
  pageAuth: config.pageAuth ?? auth.pageAuth,
86
90
  adapters: {
87
91
  ...auth.ssrAdapters,
@@ -1,6 +1,7 @@
1
1
  import { readRawBody } from "../../requestParser.js";
2
2
  import { isNavigation, safeRedirectTarget } from "../navigation.js";
3
3
  import { clearSessionCookies, writeSessionCookies } from "../../auth/session.js";
4
+ import { refusedCrossSite } from "./crossSiteWrites.js";
4
5
  import { exchangeStage } from "./exchangeRoute.js";
5
6
  import { signInStage } from "./signInRoute.js";
6
7
  //#region src/core/http/stages/authRoutes.ts
@@ -24,6 +25,7 @@ var loginStage = async (ctx) => {
24
25
  const { config, raw, req, res } = ctx;
25
26
  const loginPath = config.loginPath === false ? null : config.loginPath ?? "/auth/login";
26
27
  if (!loginPath || req.method !== "POST" || req.path !== loginPath) return false;
28
+ if (refusedCrossSite(ctx)) return true;
27
29
  req.body = await readRawBody(raw);
28
30
  const session = await config.adapters.authenticate?.(parseCredentials(req), req);
29
31
  if (session) writeSessionCookies(req, res, session, config.authCookie);
@@ -49,6 +51,7 @@ var logoutStage = async (ctx) => {
49
51
  const { config, raw, req, res } = ctx;
50
52
  const logoutPath = config.logoutPath === false ? null : config.logoutPath ?? "/auth/logout";
51
53
  if (!logoutPath || req.method !== "POST" || req.path !== logoutPath) return false;
54
+ if (refusedCrossSite(ctx)) return true;
52
55
  req.body = await readRawBody(raw);
53
56
  await config.adapters.endSession?.(req);
54
57
  clearSessionCookies(req, res, config.authCookie);
@@ -0,0 +1,23 @@
1
+ import { BaseContext, Stage } from '../types';
2
+ /**
3
+ * Whether this request is a write a page on another site caused, and so is refused — answered here, 403
4
+ * `reason: 'foreign'`, when it is.
5
+ *
6
+ * Not only a write a session cookie could authenticate: a server holding credentials of its own (a token for somebody's
7
+ * calendar, an API key) or a tool with no sign-in at all acts for whoever reaches it, and a plain form POST from any
8
+ * page open in the same browser reaches it without a preflight. Passes:
9
+ *
10
+ * - a safe method;
11
+ * - `Authorization` — a page on another site cannot set it without a preflight this server never allows;
12
+ * - a request that is not a browser's (no `Sec-Fetch-Site`, no `Origin`): a webhook, `curl`, another server;
13
+ * - a page of this site (`same-origin`, `same-site`), or of an origin in `crossSiteWrites.origins`;
14
+ * - a path in `crossSiteWrites.paths` — a form other sites post to by design.
15
+ */
16
+ export declare const refusedCrossSite: (ctx: BaseContext) => boolean;
17
+ /**
18
+ * Every write the page server answers after it — server actions, realtime publishes, a space's `/fn/` routes and its
19
+ * runtime's endpoints, the deployment's own data stages — refused when another site caused it (see
20
+ * {@link refusedCrossSite}). After the stages that gate themselves (`preAuth`: the `/auth` flows with their own CSRF,
21
+ * MCP and its OAuth, the preview's shared secret), before everything else.
22
+ */
23
+ export declare const crossSiteWritesStage: Stage;
@@ -0,0 +1,44 @@
1
+ import { carrierOf, crossSiteRequest } from "../../auth/csrf.js";
2
+ //#region src/core/http/stages/crossSiteWrites.ts
3
+ /** GET, HEAD and OPTIONS change nothing: a link or an `<img>` from anywhere is how the web works. */
4
+ var SAFE_METHODS = /* @__PURE__ */ new Set([
5
+ "GET",
6
+ "HEAD",
7
+ "OPTIONS"
8
+ ]);
9
+ /**
10
+ * Whether this request is a write a page on another site caused, and so is refused — answered here, 403
11
+ * `reason: 'foreign'`, when it is.
12
+ *
13
+ * Not only a write a session cookie could authenticate: a server holding credentials of its own (a token for somebody's
14
+ * calendar, an API key) or a tool with no sign-in at all acts for whoever reaches it, and a plain form POST from any
15
+ * page open in the same browser reaches it without a preflight. Passes:
16
+ *
17
+ * - a safe method;
18
+ * - `Authorization` — a page on another site cannot set it without a preflight this server never allows;
19
+ * - a request that is not a browser's (no `Sec-Fetch-Site`, no `Origin`): a webhook, `curl`, another server;
20
+ * - a page of this site (`same-origin`, `same-site`), or of an origin in `crossSiteWrites.origins`;
21
+ * - a path in `crossSiteWrites.paths` — a form other sites post to by design.
22
+ */
23
+ var refusedCrossSite = (ctx) => {
24
+ const { req, res, config } = ctx;
25
+ const allowed = config.crossSiteWrites;
26
+ if (SAFE_METHODS.has(req.method.toUpperCase()) || req.headers.authorization !== void 0 || allowed?.paths?.(req.path) === true || !crossSiteRequest(carrierOf(req), (origin) => allowed?.origins?.includes(origin) === true)) return false;
27
+ ctx.operation = "refused:cross-site";
28
+ res.setStatus(403);
29
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
30
+ res.send(JSON.stringify({
31
+ error: `A page on another site may not ${req.method} ${req.path} here: name its origin in the server's \`crossSiteWrites.origins\`, or the path in \`crossSiteWrites.paths\``,
32
+ reason: "foreign"
33
+ }));
34
+ return true;
35
+ };
36
+ /**
37
+ * Every write the page server answers after it — server actions, realtime publishes, a space's `/fn/` routes and its
38
+ * runtime's endpoints, the deployment's own data stages — refused when another site caused it (see
39
+ * {@link refusedCrossSite}). After the stages that gate themselves (`preAuth`: the `/auth` flows with their own CSRF,
40
+ * MCP and its OAuth, the preview's shared secret), before everything else.
41
+ */
42
+ var crossSiteWritesStage = refusedCrossSite;
43
+ //#endregion
44
+ export { crossSiteWritesStage, refusedCrossSite };
@@ -0,0 +1 @@
1
+ export {};
@@ -1,5 +1,6 @@
1
1
  import { readRawBody } from "../../requestParser.js";
2
2
  import { writeSessionCookies } from "../../auth/session.js";
3
+ import { refusedCrossSite } from "./crossSiteWrites.js";
3
4
  //#region src/core/http/stages/exchangeRoute.ts
4
5
  var parseBody = (req) => {
5
6
  if (!req.body) return {};
@@ -30,6 +31,7 @@ var exchangeStage = async (ctx) => {
30
31
  const { config, raw, req, res } = ctx;
31
32
  const exchangePath = config.exchangePath === false ? null : config.exchangePath ?? "/auth/exchange";
32
33
  if (!exchangePath || req.method !== "POST" || req.path !== exchangePath) return false;
34
+ if (refusedCrossSite(ctx)) return true;
33
35
  if (!config.adapters.exchangeCredential) {
34
36
  res.setStatus(404);
35
37
  res.end();
@@ -1,3 +1,4 @@
1
+ import { requestAuthority } from "../../requestParser.js";
1
2
  import { readRenewalGuard, readSessionHint, readSessionToken, writeRenewalGuard } from "../../auth/session.js";
2
3
  import { isDocumentNavigation, renewForNavigation } from "../../auth/renewal.js";
3
4
  //#region src/core/http/stages/sessionRenewal.ts
@@ -9,7 +10,7 @@ var nowInSeconds = () => Math.floor(Date.now() / 1e3);
9
10
  * read off the authority rather than taken whole, so a forged `Host` cannot put anything but digits after the name.
10
11
  */
11
12
  var pageUrl = (req) => {
12
- const authority = req.headers[":authority"] ?? req.headers.host ?? "";
13
+ const authority = requestAuthority(req);
13
14
  const port = /:(\d{1,5})$/u.exec(authority)?.[1];
14
15
  return `${req.protocol}://${req.hostname}${port ? `:${port}` : ""}${req.path}${req.search}`;
15
16
  };
@@ -1,5 +1,5 @@
1
- import { readCookies } from "../../auth/credentials.js";
2
1
  import { requestOrigin } from "../../requestParser.js";
2
+ import { readCookies } from "../../auth/credentials.js";
3
3
  import { safeRedirectTarget } from "../navigation.js";
4
4
  import { appendCookies, writeSessionCookies } from "../../auth/session.js";
5
5
  import { createHash, randomBytes } from "node:crypto";
@@ -1,7 +1,7 @@
1
1
  import { resolveSdkAssetsDir } from "../../sdkAssets.js";
2
2
  import { serveStatic } from "../../staticFiles.js";
3
3
  //#region src/core/http/stages/static.ts
4
- var publicDirStage = (ctx) => ctx.config.publicDir ? serveStatic(ctx.req, ctx.res, ctx.config.publicDir) : false;
4
+ var publicDirStage = (ctx) => ctx.config.publicDir ? serveStatic(ctx.req, ctx.res, ctx.config.publicDir, "revalidate") : false;
5
5
  var wellKnownStage = (ctx) => {
6
6
  if (!ctx.req.path.startsWith("/.well-known/")) return false;
7
7
  ctx.res.setStatus(404);
@@ -1,4 +1,13 @@
1
1
  export declare const MIME_TYPES: Record<string, string>;
2
2
  export declare const IMMUTABLE_EXTS: Set<string>;
3
3
  export declare const getMimeType: (filePath: string) => string;
4
- export declare const getCacheControl: (filePath: string) => string;
4
+ /**
5
+ * How long a browser may keep a file without asking again.
6
+ *
7
+ * `versioned` is for a directory whose URLs change with their content — the SDK bundle and the plugins, addressed
8
+ * with `?v=` — where a script or a stylesheet never changes under its URL and is kept for a year. `revalidate` is for
9
+ * files a project keeps by name and may rewrite while it runs (`public/`): kept, but asked about every time, which
10
+ * the `ETag` answers with an empty `304` when nothing changed.
11
+ */
12
+ export type StaticCachePolicy = 'versioned' | 'revalidate';
13
+ export declare const getCacheControl: (filePath: string, policy?: StaticCachePolicy) => string;
@@ -33,7 +33,8 @@ var IMMUTABLE_EXTS = /* @__PURE__ */ new Set([
33
33
  var getMimeType = (filePath) => {
34
34
  return MIME_TYPES[filePath.slice(filePath.lastIndexOf(".")).toLowerCase()] ?? "application/octet-stream";
35
35
  };
36
- var getCacheControl = (filePath) => {
36
+ var getCacheControl = (filePath, policy = "versioned") => {
37
+ if (policy === "revalidate") return "no-cache";
37
38
  const ext = filePath.slice(filePath.lastIndexOf(".")).toLowerCase();
38
39
  return IMMUTABLE_EXTS.has(ext) ? "public, max-age=31536000, immutable" : "public, max-age=3600";
39
40
  };
@@ -1,3 +1,4 @@
1
+ import { requestAuthority } from "../requestParser.js";
1
2
  import { renderConsentPage } from "./consentPage.js";
2
3
  import { dropPending, getClient, getPending, putCode, putPending } from "./records.js";
3
4
  import { issueContextFor } from "./issueContext.js";
@@ -49,7 +50,7 @@ var renderConsent = (res, view) => {
49
50
  * the server is mounted under a prefix, which resolving `/authorize` against it would drop. The same joining the
50
51
  * discovery document publishes the endpoint by.
51
52
  */
52
- var authorizeEndpoint = (config, req) => new URL(`${(config.issuer ?? `https://${req.headers.host ?? ""}`).replace(/\/+$/u, "")}${AUTHORIZE_PATH}`);
53
+ var authorizeEndpoint = (config, req) => new URL(`${(config.issuer ?? `https://${requestAuthority(req)}`).replace(/\/+$/u, "")}${AUTHORIZE_PATH}`);
53
54
  /** The same endpoint, as the path the grant screen's form posts to — this server's own origin, whatever it is. */
54
55
  var authorizeAction = (config) => config.issuer ? `${new URL(config.issuer).pathname.replace(/\/+$/u, "")}${AUTHORIZE_PATH}` : AUTHORIZE_PATH;
55
56
  var authorizeUrl = (config, req, params) => {
@@ -1,6 +1,12 @@
1
1
  import { SSRRequest } from '@plitzi/sdk-shared';
2
2
  import { IncomingMessage } from 'node:http';
3
3
  export declare const parseRequest: (raw: IncomingMessage) => SSRRequest;
4
+ /**
5
+ * The host the request was addressed to, port included (`localhost:8080`): HTTP/2's `:authority` — an HTTP/2
6
+ * request has no `Host` header at all — else `Host`. What names this origin's cookies (`debugCookieName` and the
7
+ * rest carry the port), so a server reached over HTTP/2 must read it here, never `req.headers.host`.
8
+ */
9
+ export declare const requestAuthority: (req: Pick<SSRRequest, "headers">) => string;
4
10
  /** The public origin the request was addressed to (proxy-aware via x-forwarded-proto, port included), or an empty
5
11
  * string when the request carries no usable authority. */
6
12
  export declare const requestOrigin: (req: SSRRequest) => string;
@@ -34,10 +34,16 @@ var parseRequest = (raw) => {
34
34
  };
35
35
  };
36
36
  var AUTHORITY_RE = /^[a-zA-Z0-9.-]{1,253}(?::\d{1,5})?$/u;
37
+ /**
38
+ * The host the request was addressed to, port included (`localhost:8080`): HTTP/2's `:authority` — an HTTP/2
39
+ * request has no `Host` header at all — else `Host`. What names this origin's cookies (`debugCookieName` and the
40
+ * rest carry the port), so a server reached over HTTP/2 must read it here, never `req.headers.host`.
41
+ */
42
+ var requestAuthority = (req) => req.headers[":authority"] ?? req.headers["host"] ?? "";
37
43
  /** The public origin the request was addressed to (proxy-aware via x-forwarded-proto, port included), or an empty
38
44
  * string when the request carries no usable authority. */
39
45
  var requestOrigin = (req) => {
40
- const authority = req.headers[":authority"] ?? req.headers["host"] ?? "";
46
+ const authority = requestAuthority(req);
41
47
  return AUTHORITY_RE.test(authority) ? `${req.protocol}://${authority}` : "";
42
48
  };
43
49
  var headerValue = (value) => (Array.isArray(value) ? value[0] : value)?.trim() ?? "";
@@ -70,4 +76,4 @@ var readRawBytes = (raw) => new Promise((resolve, reject) => {
70
76
  });
71
77
  var readRawBody = async (raw) => (await readRawBytes(raw)).toString("utf8");
72
78
  //#endregion
73
- export { clientIp, forwardedIp, parseRequest, readRawBody, readRawBytes, requestOrigin };
79
+ export { clientIp, forwardedIp, parseRequest, readRawBody, readRawBytes, requestAuthority, requestOrigin };
@@ -0,0 +1 @@
1
+ export {};
@@ -4,7 +4,7 @@ import { HostedStore, Remote, StoreMethods } from './channel';
4
4
  * (`role.ts`). A single server never reaches past `fleetStore`, which answers it nothing.
5
5
  */
6
6
  /** The stores a single process keeps in memory by default, which the workers of a fleet share (see `stores.ts`). */
7
- export type FleetStoreName = 'actions.kv' | 'realtime.grants' | 'actions.jobs' | 'ssr.drafts' | 'auth.rateLimit';
7
+ export type FleetStoreName = 'actions.kv' | 'realtime.kv' | 'actions.jobs' | 'ssr.drafts' | 'auth.rateLimit';
8
8
  /**
9
9
  * The primary's hub: it answers its workers from the stores in `catalogue`, made when first asked for, and passes
10
10
  * broadcasts on. Started before the first fork, so no worker can ask before anyone is answering.
@@ -24,7 +24,7 @@ var fleetKv = (make) => {
24
24
  */
25
25
  var FLEET_STORES = {
26
26
  "actions.kv": hostable(() => deploymentKv ?? createMemoryKv(), KV_METHODS),
27
- "realtime.grants": hostable(createMemoryKv, KV_METHODS),
27
+ "realtime.kv": hostable(createMemoryKv, KV_METHODS),
28
28
  "actions.jobs": hostable(() => createMemoryJobQueue(), JOB_QUEUE_METHODS),
29
29
  "ssr.drafts": hostable(createMemoryDraftStore, DRAFT_STORE_METHODS),
30
30
  "auth.rateLimit": hostable(() => ({ check: createMemoryRateLimit() }), RATE_LIMIT_METHODS)
@@ -1,9 +1,9 @@
1
1
  import { connectorLookupsOf } from "../configSeam.js";
2
+ import { clientIp, readRawBody } from "../requestParser.js";
2
3
  import { handleActionCall } from "../../modules/actions/transport/callHandler.js";
3
4
  import { handleActionCatalog } from "../../modules/actions/transport/catalogHandler.js";
4
5
  import { handleActionWebhook } from "../../modules/actions/transport/webhookHandler.js";
5
6
  import { handleActionCancel } from "../../modules/actions/transport/cancelHandler.js";
6
- import { clientIp, readRawBody } from "../requestParser.js";
7
7
  import { handleAction } from "../../modules/actions/connectorWrite.js";
8
8
  //#region src/core/services/action.ts
9
9
  var LINEAGE_HEADER = "x-plitzi-action-lineage";
@@ -1,5 +1,5 @@
1
- import { handleRealtimePublish, handleRealtimeSubscribe } from "../../modules/realtime/handlers.js";
2
1
  import { readRawBody } from "../requestParser.js";
2
+ import { handleRealtimePublish, handleRealtimeSubscribe } from "../../modules/realtime/handlers.js";
3
3
  import { handleRealtimeSocket } from "../../modules/realtime/socket.js";
4
4
  //#region src/core/services/realtime.ts
5
5
  /**
@@ -5,6 +5,7 @@ import { rscStage } from "./rsc.js";
5
5
  import { spaceDocumentStage } from "./spaceDocument.js";
6
6
  import { imagesStage } from "../http/stages/images.js";
7
7
  import { notFoundStage, ssrStage } from "./ssr.js";
8
+ import { crossSiteWritesStage } from "../http/stages/crossSiteWrites.js";
8
9
  import { authRoutesStages } from "../http/stages/authRoutes.js";
9
10
  import { fontAssetsStage } from "../http/stages/fontAssets.js";
10
11
  import { healthStage } from "../http/stages/health.js";
@@ -25,6 +26,7 @@ var buildPagePipeline = (services, extensions = {}) => {
25
26
  sdkAssetsStage
26
27
  ];
27
28
  stages.push(...extensions.preAuth ?? []);
29
+ stages.push(crossSiteWritesStage);
28
30
  stages.push(createMiddlewaresStage());
29
31
  if (services.rsc) stages.push(rscStage);
30
32
  stages.push(actionStage);
@@ -1,2 +1,3 @@
1
+ import { StaticCachePolicy } from './mimeTypes';
1
2
  import { SSRRequest, SSRResponseHelpers } from '@plitzi/sdk-shared';
2
- export declare const serveStatic: (req: SSRRequest, res: SSRResponseHelpers, rootDir: string) => boolean;
3
+ export declare const serveStatic: (req: SSRRequest, res: SSRResponseHelpers, rootDir: string, cache?: StaticCachePolicy) => boolean;
@@ -6,11 +6,11 @@ import fs from "node:fs";
6
6
  var compressedFiles = new CompressedFileCache(16777216);
7
7
  var isText = (mimeType) => /^text\/|javascript|json|xml|svg/.test(mimeType);
8
8
  var buildEtag = (stat) => `"${stat.mtimeMs.toString(36)}-${stat.size.toString(36)}"`;
9
- var serveFile = (req, res, filePath, stat) => {
9
+ var serveFile = (req, res, filePath, stat, cache) => {
10
10
  const etag = buildEtag(stat);
11
11
  const ifNoneMatch = req.headers["if-none-match"];
12
12
  res.setHeader("ETag", etag);
13
- res.setHeader("Cache-Control", getCacheControl(filePath));
13
+ res.setHeader("Cache-Control", getCacheControl(filePath, cache));
14
14
  res.setHeader("Last-Modified", stat.mtime.toUTCString());
15
15
  if (ifNoneMatch === etag) {
16
16
  res.setStatus(304);
@@ -27,7 +27,7 @@ var serveFile = (req, res, filePath, stat) => {
27
27
  res.send(fs.readFileSync(filePath));
28
28
  return true;
29
29
  };
30
- var serveStatic = (req, res, rootDir) => {
30
+ var serveStatic = (req, res, rootDir, cache = "versioned") => {
31
31
  const relative = req.path.replace(/^\/+/, "");
32
32
  const filePath = path.resolve(rootDir, relative);
33
33
  const resolvedRoot = path.resolve(rootDir);
@@ -41,9 +41,9 @@ var serveStatic = (req, res, rootDir) => {
41
41
  if (stat.isDirectory()) {
42
42
  const indexPath = path.join(filePath, "index.html");
43
43
  if (!fs.existsSync(indexPath)) return false;
44
- return serveFile(req, res, indexPath, fs.statSync(indexPath));
44
+ return serveFile(req, res, indexPath, fs.statSync(indexPath), cache);
45
45
  }
46
- return serveFile(req, res, filePath, stat);
46
+ return serveFile(req, res, filePath, stat, cache);
47
47
  };
48
48
  //#endregion
49
49
  export { serveStatic };
@@ -160,8 +160,11 @@ export declare type FunctionsDefinition = {
160
160
  * One step a server action can take, written by the space. The shape of the platform's own tasks — addressed as
161
161
  * `<namespace>.<action>`, drawn in the builder from `params` — run with a {@link FunctionContext} rather than the
162
162
  * platform's full one.
163
+ *
164
+ * `R` is what `run` answers: `taskAction(task, …)` hands it, with `T`, to a page that runs the action
165
+ * (`useServerAction`), so `FunctionTask<{ id: string }, Habit>` is typed at both ends.
163
166
  */
164
- export declare type FunctionTask<T extends Record<string, unknown> = Record<string, unknown>> = {
167
+ export declare type FunctionTask<T extends Record<string, unknown> = Record<string, unknown>, R = unknown> = {
165
168
  namespace: string;
166
169
  action: string;
167
170
  title: string;
@@ -172,7 +175,7 @@ export declare type FunctionTask<T extends Record<string, unknown> = Record<stri
172
175
  * what the server allows. Over the functions' own `limits`, for this task.
173
176
  */
174
177
  limits?: FunctionTimeLimits;
175
- run: (params: T, ctx: FunctionContext) => unknown;
178
+ run: (params: T, ctx: FunctionContext) => R | Promise<R>;
176
179
  };
177
180
 
178
181
  /**
@@ -39,6 +39,7 @@ export declare const buildHtmlCacheKey: (accessToken: string | undefined, spaceI
39
39
  headers: {
40
40
  cookie?: string;
41
41
  host?: string;
42
+ ":authority"?: string;
42
43
  };
43
44
  }) => string;
44
45
  /**
@@ -1,3 +1,4 @@
1
+ import { requestAuthority } from "../../core/requestParser.js";
1
2
  import { ssrPaintedCookieName } from "../paintedCookie.js";
2
3
  import { readCookie } from "../readCookie.js";
3
4
  import { flagsCookieName } from "@plitzi/sdk-shared/flags";
@@ -54,9 +55,9 @@ var buildHtmlCacheKey = (accessToken = "anonymous", spaceId, environment, revisi
54
55
  revision: String(revision),
55
56
  flags: flagsVersionOf(req),
56
57
  theme: themeFromCookies(req.headers.cookie) ?? "",
57
- painted: readCookie(req.headers.cookie, ssrPaintedCookieName(req.headers.host)) ?? "",
58
- debugHidden: readCookie(req.headers.cookie, debugCookieName(req.headers.host)) === "false" ? "debug-off" : "",
59
- forcedFlags: readCookie(req.headers.cookie, flagsCookieName(req.headers.host)) ?? "",
58
+ painted: readCookie(req.headers.cookie, ssrPaintedCookieName(requestAuthority(req))) ?? "",
59
+ debugHidden: readCookie(req.headers.cookie, debugCookieName(requestAuthority(req))) === "false" ? "debug-off" : "",
60
+ forcedFlags: readCookie(req.headers.cookie, flagsCookieName(requestAuthority(req))) ?? "",
60
61
  hostname: req.hostname,
61
62
  path: req.path,
62
63
  search: req.search
@@ -13,6 +13,7 @@ export declare const forcedFlagsFor: (req: {
13
13
  headers: {
14
14
  cookie?: string;
15
15
  host?: string;
16
+ ":authority"?: string;
16
17
  };
17
18
  }, authorized: boolean | (() => Promise<boolean>)) => Promise<Record<string, boolean> | undefined>;
18
19
  /** Both layers this server answers for, for one request. */
@@ -20,6 +21,7 @@ export declare const requestFlagOverrides: (config: Pick<SSRServerConfig, "flags
20
21
  headers: {
21
22
  cookie?: string;
22
23
  host?: string;
24
+ ":authority"?: string;
23
25
  };
24
26
  }, space: {
25
27
  spaceId: number;
@@ -1,3 +1,4 @@
1
+ import { requestAuthority } from "../core/requestParser.js";
1
2
  import { forcedFlagsFromCookies } from "@plitzi/sdk-shared/flags";
2
3
  //#region src/helpers/flagOverrides.ts
3
4
  /** The deployment's own layer for one space: `config.flags`, asked per space when it is a function. */
@@ -8,7 +9,7 @@ var serverFlagsFor = (config, space) => typeof config.flags === "function" ? con
8
9
  * mean reading the space.
9
10
  */
10
11
  var forcedFlagsFor = async (req, authorized) => {
11
- const forced = forcedFlagsFromCookies(req.headers.cookie, req.headers.host);
12
+ const forced = forcedFlagsFromCookies(req.headers.cookie, requestAuthority(req));
12
13
  if (Object.keys(forced).length === 0) return;
13
14
  return (typeof authorized === "boolean" ? authorized : await authorized()) ? forced : void 0;
14
15
  };
package/dist/index.d.ts CHANGED
@@ -12,6 +12,7 @@ export { createAuthAdapters } from './adapters/authAdapters';
12
12
  export { authoringPreview, createMemoryCache, createSpaceAdapters, fixedSpace, presentsCredential, refuse, verifiedDomain, wildcardSubdomain } from './adapters/space';
13
13
  export { createLocalFontStore, hostedPathsOf } from './core/fontStore';
14
14
  export { createMemoryDraftStore, takeDraftOverride } from './modules/ssr/preview';
15
+ export { createAuthoringHost } from './modules/authoringHost';
15
16
  export { createMemoryPubSub } from './modules/realtime/memoryPubSub';
16
17
  export { createRedisPubSub } from './modules/realtime/redisPubSub';
17
18
  export { PREVIEW_TOKEN_PARAM } from './core/previewToken';
@@ -27,5 +28,6 @@ export type { FontStore, StoredFont } from './core/fontStore';
27
28
  export type { PubSubAdapter, SSRRealtimeConfig } from '@plitzi/sdk-shared';
28
29
  export type { RedisPubSubClients } from './modules/realtime/redisPubSub';
29
30
  export type { ResolvedServices, ServerConfig } from './core/createServer';
31
+ export type { AuthoringHost, AuthoringHostConfig } from './modules/authoringHost';
30
32
  export type { Closable, CloseOnSignalsOptions } from './core/server/closeOnSignals';
31
33
  export type { BaseContext, PipelineExtensions, SSRContext, Stage } from './core/http/types';
package/dist/index.js CHANGED
@@ -19,5 +19,6 @@ import { createMemoryCache, refuse } from "./adapters/space/types.js";
19
19
  import { authoringPreview, fixedSpace, presentsCredential, verifiedDomain, wildcardSubdomain } from "./adapters/space/resolvers.js";
20
20
  import { createSpaceAdapters } from "./adapters/space/index.js";
21
21
  import { createLocalFontStore, hostedPathsOf } from "./core/fontStore.js";
22
+ import { createAuthoringHost } from "./modules/authoringHost/index.js";
22
23
  import { createRedisPubSub } from "./modules/realtime/redisPubSub.js";
23
- export { PREVIEW_TOKEN_PARAM, authoringPreview, buildHealthPayload, closeOnSignals, consoleLogger, createAuthAdapters, createCloudAdapters, createConnectorResolver, createJsonAdapters, createLocalFontStore, createMemoryCache, createMemoryDraftStore, createMemoryPubSub, createRedisPubSub, createServer, createSpaceAdapters, fetchConnectorRecords, fixedSpace, freePort, hostedPathsOf, isLogged, loadFunctions, loadFunctionsSource, logLevelOf, presentsCredential, readFunctionsDir, rebaseMedia, refuse, registerHealthCheck, renderLogEvent, resolveRscData, resolveServices, serverLog, takeDraftOverride, unusedPort, verifiedDomain, wildcardSubdomain, writeConnectorRecord };
24
+ export { PREVIEW_TOKEN_PARAM, authoringPreview, buildHealthPayload, closeOnSignals, consoleLogger, createAuthAdapters, createAuthoringHost, createCloudAdapters, createConnectorResolver, createJsonAdapters, createLocalFontStore, createMemoryCache, createMemoryDraftStore, createMemoryPubSub, createRedisPubSub, createServer, createSpaceAdapters, fetchConnectorRecords, fixedSpace, freePort, hostedPathsOf, isLogged, loadFunctions, loadFunctionsSource, logLevelOf, presentsCredential, readFunctionsDir, rebaseMedia, refuse, registerHealthCheck, renderLogEvent, resolveRscData, resolveServices, serverLog, takeDraftOverride, unusedPort, verifiedDomain, wildcardSubdomain, writeConnectorRecord };
@@ -13,7 +13,7 @@ var realtimeTasks = [
13
13
  namespace: "realtime",
14
14
  action: "publish",
15
15
  title: "Publish On Channel",
16
- description: "Sends a message to every page subscribed to a topic of one of the space’s channels.",
16
+ description: "Sends a message to every page subscribed to a topic of one of the space’s channels. On a `retain: true` channel it is also kept, the latest of its type, for every page that joins later; `null` data forgets it.",
17
17
  params: {
18
18
  topic: {
19
19
  type: "text",
@@ -0,0 +1,49 @@
1
+ import { ServerConfig } from '../../core/createServer';
2
+ import { AuthoredDocuments } from '../project/watchSpace';
3
+ import { SSRServer } from '@plitzi/sdk-shared';
4
+ /**
5
+ * Pages somebody else authored — an agent designing a screen, a visitor's own page — served as a project's pages are,
6
+ * each at an address of its own, from one server.
7
+ *
8
+ * Each page is a space kept as a draft of the host's one space (`?__pt=<id>`), which is how a page server tells many
9
+ * apart on one host: the page arrives with its whole space in it, every page after it is the browser's, and a reload
10
+ * that lost the address finds it again in the draft's cookie. So a page here is drawn in the browser alone — no server
11
+ * provider, action, function or channel of its own: it is data and its look.
12
+ *
13
+ * Author them where they cannot reach anything (`authorIsolated` of `@plitzi/sdk-authoring/node`) and serve them here,
14
+ * on an origin of their own — never the app's, whose cookies a page somebody else wrote would then run beside.
15
+ *
16
+ * ```ts
17
+ * const host = createAuthoringHost({ dir: 'tmp/pages', port: 8091, frameAncestors: ['https://localhost:8080'] });
18
+ * await host.server.listen(8091, '0.0.0.0');
19
+ *
20
+ * const result = await authorIsolated('tmp/pages/weather.ts');
21
+ * if (result.ok) {
22
+ * const { path } = host.put(result.space, { id: 'weather' }); // `/?__pt=weather`
23
+ * }
24
+ * ```
25
+ */
26
+ export type AuthoringHostConfig = Omit<ServerConfig, 'adapters' | 'auth' | 'draftStore'> & {
27
+ /** Where the pages are kept, `<id>.json` each — read back when the host starts, so a restart serves them still. */
28
+ dir: string;
29
+ /** Who may show the pages in an iframe, as CSP `frame-ancestors` sources: the app that shows them. */
30
+ frameAncestors?: string[];
31
+ };
32
+ export type AuthoringHost = {
33
+ server: SSRServer;
34
+ /**
35
+ * Keeps a space under `id` — a new one when left out, which nobody can guess — replacing what it held, and answers
36
+ * the address its pages are at: its home is `path`, any other page that path with the page's own in front of `?`.
37
+ */
38
+ put: (documents: AuthoredDocuments, options?: {
39
+ id?: string;
40
+ }) => {
41
+ id: string;
42
+ path: string;
43
+ };
44
+ /** Forgets a page: its address answers 404 from then on. Whether there was one. */
45
+ drop: (id: string) => boolean;
46
+ /** The ids it serves. */
47
+ ids: () => string[];
48
+ };
49
+ export declare const createAuthoringHost: ({ dir, frameAncestors, ...config }: AuthoringHostConfig) => AuthoringHost;