@plitzi/sdk-kernel 0.39.2 → 0.39.4

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 (40) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +1 -1
  3. package/dist/build/index.mjs +1 -1
  4. package/dist/chunks/{csrf-BLWcaYOV.mjs → csrf-DMP4dVjc.mjs} +18 -4
  5. package/dist/chunks/{link-C9wyDS9H.mjs → link-CFSynFKL.mjs} +1 -1
  6. package/dist/chunks/{serverLog-BKaKjjc4.mjs → serverLog-BWNOjPMV.mjs} +71 -3
  7. package/dist/chunks/{stage-y6deE9LJ.mjs → stage-C62Zvzw_.mjs} +229 -12
  8. package/dist/chunks/{supervisor-Dh34v1vq.mjs → supervisor-D1gAW3nL.mjs} +2 -2
  9. package/dist/chunks/{tokens-CBd5tXut.mjs → tokens-BAV5YeT9.mjs} +14 -3
  10. package/dist/deployment/index.mjs +1 -1
  11. package/dist/engine/page.d.ts +1 -1
  12. package/dist/files/index.mjs +1 -1
  13. package/dist/http/index.mjs +21 -11
  14. package/dist/http/probes.d.ts +2 -0
  15. package/dist/identity/csrf.d.ts +16 -1
  16. package/dist/identity/index.d.ts +1 -1
  17. package/dist/identity/index.mjs +2 -2
  18. package/dist/identity/requestIdentity.d.ts +1 -1
  19. package/dist/index.d.ts +1 -1
  20. package/dist/log/index.mjs +1 -3
  21. package/dist/log/serverLog.d.ts +5 -1
  22. package/dist/outbound/index.mjs +66 -6
  23. package/dist/outbound/outboundGuard.d.ts +15 -4
  24. package/dist/pubsub/index.mjs +1 -1
  25. package/dist/stats/index.d.ts +3 -2
  26. package/dist/stats/index.mjs +2 -2
  27. package/dist/stats/metrics.d.ts +16 -0
  28. package/dist/stats/stage.d.ts +13 -7
  29. package/dist/stats/types.d.ts +14 -1
  30. package/dist/testing/index.mjs +1 -1
  31. package/dist/tokens/index.mjs +1 -1
  32. package/dist/tokens/tokens.d.ts +7 -2
  33. package/dist/trace/index.d.ts +27 -0
  34. package/dist/trace/index.mjs +43 -0
  35. package/dist/types/adapters.d.ts +6 -0
  36. package/dist/types/config.d.ts +1 -1
  37. package/dist/types/log.d.ts +4 -0
  38. package/dist/types/pipeline.d.ts +9 -0
  39. package/package.json +2 -2
  40. package/dist/chunks/tail-D-USrZIR.mjs +0 -55
@@ -14,6 +14,21 @@ export interface CsrfConfig {
14
14
  */
15
15
  allowedOrigins?: string[] | ((origin: string) => boolean);
16
16
  }
17
+ /** Where the echo is looked for, and the field a `<form>` may carry it in instead. */
18
+ /**
19
+ * The wire's names, said again by the page's half (`@plitzi/sdk-shared/csrf`), which runs where this cannot: the kernel
20
+ * imports no other Plitzi package's values (docs/en/server-packages.md, D3). `csrf.test.ts` holds the two to the same words.
21
+ */
22
+ export declare const CSRF_WIRE: {
23
+ readonly header: "x-csrf-token";
24
+ readonly field: "_csrf";
25
+ readonly cookieSuffix: "_csrf";
26
+ };
27
+ /**
28
+ * The name the token's cookie lands under on `hostname`: the session cookie's, and `_csrf`. Pure, so a page server that
29
+ * signs nothing can tell its pages which cookie to read (`<meta name="plitzi-csrf">`).
30
+ */
31
+ export declare const csrfCookieName: (hostname: string, cookie?: SSRAuthCookie) => string;
17
32
  /**
18
33
  * What kind of flow a request is reaching, which is what decides when a token is demanded.
19
34
  *
@@ -91,7 +106,7 @@ export declare const createCsrf: (config: CsrfConfig) => {
91
106
  /** The name the cookie lands under, for a client that reads it by hand. */
92
107
  cookieName: (hostname: string) => string;
93
108
  /** The header the echo is expected in, published by `GET /auth/csrf` so a client is never told it twice. */
94
- headerName: string;
109
+ headerName: "x-csrf-token";
95
110
  /** Readable on purpose: `httpOnly` would make it impossible for a page to echo it back. It is not a credential. */
96
111
  write: (req: CookieRequest, res: CookieSink, token: string) => void;
97
112
  /**
@@ -1,6 +1,6 @@
1
1
  export { requirementFor, createAuthorizer, checkPermission, checkSpaceAccess } from './authorize';
2
2
  export { readCookies, SPACE_TOKEN_PARAM, createCarriers, presentedOrigin } from './credentials';
3
- export { csrfFailureMessage, carrierOf, crossSiteRequest, createCsrf } from './csrf';
3
+ export { csrfFailureMessage, carrierOf, crossSiteRequest, createCsrf, csrfCookieName } from './csrf';
4
4
  export { authorizesDebugging, resolveDebugAuthorization } from './debugAuthorization';
5
5
  export { hostnameOf, ANY_DOMAIN, domainAllowed, normalizeDomain, frameAncestors, corsOrigins } from './domains';
6
6
  export { createIdentity } from './identity';
@@ -1,4 +1,4 @@
1
- import { i as csrfFailureMessage, n as createCsrf, r as crossSiteRequest, t as carrierOf } from "../chunks/csrf-BLWcaYOV.mjs";
1
+ import { a as csrfFailureMessage, i as csrfCookieName, n as createCsrf, r as crossSiteRequest, t as carrierOf } from "../chunks/csrf-DMP4dVjc.mjs";
2
2
  import { n as SCOPES, r as authFailureMessage, t as OFF_BROWSER_SPACE_SCOPES } from "../chunks/scopes-Co6ZjhAm.mjs";
3
3
  import { a as verifyPassword, i as hashPassword, n as activityDue, r as generateToken, t as SESSION_ACTIVITY_RESOLUTION_SECONDS } from "../chunks/sessionActivity-Ch7xuQ_o.mjs";
4
4
  import { _ as sessionHintValue, a as createSessionCookies, b as writeRenewalGuard, c as parseSessionHint, d as readRenewalGuard, f as readSessionHint, g as sessionHintCookieName, h as sessionCookieParams, i as clearSessionCookies, l as readFlowCookie, m as registrableDomain, n as appendCookies, o as isLocalHost, p as readSessionToken, r as clearFlowCookie, s as isPrivateNetworkHost, t as RENEWAL_GUARD_SECONDS, u as readRefreshToken, v as sessionReturnTarget, x as writeSessionCookies, y as writeFlowCookie } from "../chunks/session-B-dTEjeG.mjs";
@@ -728,4 +728,4 @@ var createSpaceTokenApi = ({ tokens, adapters }) => {
728
728
  }
729
729
  };
730
730
  };
731
- export { ANY_DOMAIN, OFF_BROWSER_SPACE_SCOPES, PREVIEW_COOKIE, PREVIEW_TOKEN_PARAM, RENEWAL_GUARD_SECONDS, SCOPES, SESSION_ACTIVITY_RESOLUTION_SECONDS, SPACE_TOKEN_PARAM, activityDue, appendCookies, authFailureMessage, authorizesDebugging, carrierOf, checkPermission, checkSpaceAccess, clearFlowCookie, clearSessionCookies, corsOrigins, createAuthorizer, createCarriers, createCsrf, createIdentity, createSessionCookies, createSpaceTokenApi, crossSiteRequest, csrfFailureMessage, domainAllowed, frameAncestors, generateToken, hashPassword, hostnameOf, isLocalHost, isPrivateNetworkHost, normalizeDomain, parseSessionHint, presentedOrigin, readCookies, readDraftToken, readFlowCookie, readRefreshToken, readRenewalGuard, readSessionHint, readSessionToken, registrableDomain, requirementFor, resolveDebugAuthorization, sessionCookieParams, sessionHintCookieName, sessionHintValue, sessionReturnTarget, verifyPassword, writeFlowCookie, writeRenewalGuard, writeSessionCookies };
731
+ export { ANY_DOMAIN, OFF_BROWSER_SPACE_SCOPES, PREVIEW_COOKIE, PREVIEW_TOKEN_PARAM, RENEWAL_GUARD_SECONDS, SCOPES, SESSION_ACTIVITY_RESOLUTION_SECONDS, SPACE_TOKEN_PARAM, activityDue, appendCookies, authFailureMessage, authorizesDebugging, carrierOf, checkPermission, checkSpaceAccess, clearFlowCookie, clearSessionCookies, corsOrigins, createAuthorizer, createCarriers, createCsrf, createIdentity, createSessionCookies, createSpaceTokenApi, crossSiteRequest, csrfCookieName, csrfFailureMessage, domainAllowed, frameAncestors, generateToken, hashPassword, hostnameOf, isLocalHost, isPrivateNetworkHost, normalizeDomain, parseSessionHint, presentedOrigin, readCookies, readDraftToken, readFlowCookie, readRefreshToken, readRenewalGuard, readSessionHint, readSessionToken, registrableDomain, requirementFor, resolveDebugAuthorization, sessionCookieParams, sessionHintCookieName, sessionHintValue, sessionReturnTarget, verifyPassword, writeFlowCookie, writeRenewalGuard, writeSessionCookies };
@@ -1,7 +1,7 @@
1
1
  import { SSRRequest, SSRResponseHelpers } from '../types';
2
2
  import { SSRUser } from '@plitzi/sdk-shared';
3
3
  /**
4
- * Who a request is, as every server that serves a space asks it (RFC 0032, §11 Q6): one object, so a page server and a
4
+ * Who a request is, as every server that serves a space asks it (docs/en/server-packages.md): one object, so a page server and a
5
5
  * worker are configured with the same answer. `createAuth` makes one (`ssrIdentityAdapters`); a deployment with its own
6
6
  * accounts writes its own. Absent, every request is a guest's.
7
7
  */
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `@plitzi/sdk-kernel`: what every Plitzi server process is built on, and nothing else (RFC 0032).
2
+ * `@plitzi/sdk-kernel`: what every Plitzi server process is built on, and nothing else (docs/en/server-packages.md).
3
3
  *
4
4
  * Its entries are its folders, each imported on its own so a process loads only what it uses:
5
5
  *
@@ -1,3 +1 @@
1
- import { a as isLogged, c as serverLog, i as defaultLogLevel, n as configureServerLog, o as logLevelOf, r as consoleLogger, s as renderLogEvent, t as SLOW_RUN_MS } from "../chunks/serverLog-BKaKjjc4.mjs";
2
- import { a as readLogTail, i as logQueryOf, r as keepLogLine, t as LOG_TAIL_SIZE } from "../chunks/tail-D-USrZIR.mjs";
3
- export { LOG_TAIL_SIZE, SLOW_RUN_MS, configureServerLog, consoleLogger, defaultLogLevel, isLogged, keepLogLine, logLevelOf, logQueryOf, readLogTail, renderLogEvent, serverLog };
1
+ export { u as LOG_TAIL_SIZE, t as SLOW_RUN_MS, n as configureServerLog, r as consoleLogger, i as defaultLogLevel, a as isLogged, f as keepLogLine, o as logLevelOf, p as logQueryOf, m as readLogTail, s as renderLogEvent, c as serverLog } from "../chunks/serverLog-BWNOjPMV.mjs";
@@ -1,4 +1,8 @@
1
1
  import { LogLevel, ServerLogEvent, ServerLogger } from '../types';
2
+ /** The trace an event is said in, when the work in hand is part of one: every line of a run carries it. */
3
+ export declare const traceField: () => {
4
+ traceId?: string;
5
+ };
2
6
  /**
3
7
  * From how long a run that worked is worth a line of its own, unless the deployment says (`configureServerLog`'s
4
8
  * `slowRunMs`): below it, a run that completed is `debug` — on a busy space every schedule and every call said
@@ -45,5 +49,5 @@ export declare const serverLog: {
45
49
  /** Whether a level would be said — to skip building a costly message nobody will read. */
46
50
  enabled: (level: LogLevel) => boolean;
47
51
  /** Hands an event to a sink the consumer wired itself (`onRun`, `onReject`) only when the process would say it. */
48
- emit: (logger: ServerLogger, event: ServerLogEvent) => void;
52
+ emit: (logger: ServerLogger, given: ServerLogEvent) => void;
49
53
  };
@@ -1,5 +1,5 @@
1
- import net, { BlockList, isIP } from "node:net";
2
1
  import { X509Certificate } from "node:crypto";
2
+ import net, { BlockList, isIP } from "node:net";
3
3
  import tls from "node:tls";
4
4
  import { lookup } from "node:dns/promises";
5
5
  // src/outbound/inside.ts
@@ -188,22 +188,79 @@ var privateOriginsOf = (origins) => (origins ?? []).map((origin) => {
188
188
  * spelled like.
189
189
  *
190
190
  * A name that does not resolve is ALLOWED through: there is nothing to judge, and the request is about to fail on
191
- * its own with a better error than this could give. What remains open is DNS rebinding — an attacker's own server
192
- * answering a public address here and a private one when the socket is opened a moment later — which is closed
193
- * only by resolving and connecting to the same address, and that belongs in the transport rather than here.
191
+ * its own with a better error than this could give.
192
+ *
193
+ * Judging the answer is half of it: the transport would resolve the name again when it opens the socket, and an
194
+ * attacker's own DNS can answer a public address here and a private one a moment later (DNS rebinding). So what was
195
+ * judged is kept (`vetted`), and `fetchOutbound` connects to it and to nothing else.
194
196
  */
195
197
  var assertOutboundAllowed = async (url, { lookup = resolveAll, privateOrigins = [] } = {}) => {
196
198
  if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`Request protocol "${url.protocol}" is not allowed`);
197
199
  if (privateOrigins.includes(url.origin)) return;
198
200
  if (isBlockedHost(url.hostname)) throw new Error("Request host is not allowed");
201
+ const hostname = url.hostname.replace(/^\[|\]$/g, "");
199
202
  let addresses;
200
203
  try {
201
- addresses = await lookup(url.hostname.replace(/^\[|\]$/g, ""));
204
+ addresses = await lookup(hostname);
202
205
  } catch {
203
206
  return;
204
207
  }
205
208
  if (addresses.some(({ address }) => isBlockedHost(address))) throw new Error("Request host is not allowed");
209
+ vet(hostname, addresses);
210
+ };
211
+ /**
212
+ * The addresses each name was judged to, for the moment between the judging and the socket. Seconds, not the
213
+ * record's TTL: the connection is opened right after, and a pooled one is never looked up again.
214
+ */
215
+ var VETTED_FOR_MS = 3e4;
216
+ var vetted = /* @__PURE__ */ new Map();
217
+ var vet = (hostname, addresses) => {
218
+ const now = Date.now();
219
+ vetted.forEach((entry, name) => {
220
+ if (entry.until <= now) vetted.delete(name);
221
+ });
222
+ vetted.set(hostname.toLowerCase(), {
223
+ addresses: addresses.map(({ address }) => ({
224
+ address,
225
+ family: isIP(address) === 6 ? 6 : 4
226
+ })),
227
+ until: now + VETTED_FOR_MS
228
+ });
229
+ };
230
+ /**
231
+ * How a guarded request's socket finds its peer: among the addresses the name was judged to, never by asking DNS
232
+ * again. A name nobody judged — one that did not resolve when it was — is not found, rather than resolved now.
233
+ */
234
+ var connectLookup = (hostname, options, callback) => {
235
+ const entry = vetted.get(hostname.toLowerCase());
236
+ const family = options.family === "IPv4" ? 4 : options.family === "IPv6" ? 6 : options.family;
237
+ const addresses = (entry && entry.until > Date.now() ? entry.addresses : []).filter((address) => !family || address.family === family);
238
+ if (addresses.length === 0) {
239
+ const error = /* @__PURE__ */ new Error(`getaddrinfo ENOTFOUND ${hostname} (not judged by the outbound guard)`);
240
+ error.code = "ENOTFOUND";
241
+ callback(error, []);
242
+ return;
243
+ }
244
+ if (options.all) {
245
+ callback(null, addresses);
246
+ return;
247
+ }
248
+ const [first] = addresses;
249
+ callback(null, first.address, first.family);
206
250
  };
251
+ var pinned;
252
+ /**
253
+ * The transport of every guarded request: Node's own `fetch`, whose sockets look their peer up in `connectLookup`.
254
+ *
255
+ * `undici` is imported when the first guarded request is sent, never with the module — loading the package installs
256
+ * a global dispatcher of its own, and every other `fetch` of the process must stay Node's. Its `Agent` speaks undici 8's
257
+ * handler interface and Node's `fetch` undici 7's, hence the wrapper; HTTP/1.1 only, as Node's `fetch` reaches a host
258
+ * (an answer over h2 reached it without its `content-encoding`, and nothing decoded it).
259
+ */
260
+ var pinnedDispatcher = () => pinned ??= import("undici").then(({ Agent, Dispatcher1Wrapper }) => new Dispatcher1Wrapper(new Agent({
261
+ allowH2: false,
262
+ connect: { lookup: connectLookup }
263
+ })));
207
264
  var MAX_REDIRECTS = 5;
208
265
  var REDIRECT_STATUSES = [
209
266
  301,
@@ -257,15 +314,18 @@ var redirectedInit = (init, status, crossOrigin) => {
257
314
  * therefore taken manually and each destination is checked before anything is sent to it.
258
315
  *
259
316
  * `base` is the caller's own transport — the action runner's is budgeted and capped — so every hop is also counted
260
- * against whatever that transport enforces.
317
+ * against whatever that transport enforces. It hands `init` on to Node's `fetch` as it got it: the `dispatcher` in it
318
+ * is what connects each hop to the addresses that were judged.
261
319
  */
262
320
  var fetchOutbound = async (base, url, init = {}, options = {}) => {
263
321
  let target = url;
264
322
  let request = init;
265
323
  for (let hop = 0;; hop += 1) {
266
324
  await assertOutboundAllowed(target, options);
325
+ const pin = options.privateOrigins?.includes(target.origin) ? {} : { dispatcher: await pinnedDispatcher() };
267
326
  const response = await base(target.toString(), {
268
327
  ...request,
328
+ ...pin,
269
329
  redirect: "manual"
270
330
  });
271
331
  const location = response.headers.get("location");
@@ -1,3 +1,4 @@
1
+ import { LookupAddress, LookupAllOptions, LookupOneOptions } from 'node:dns';
1
2
  /**
2
3
  * Whether a hostname — or an address a name resolved to — may never be the other end of an authored request.
3
4
  *
@@ -35,11 +36,19 @@ export declare const privateOriginsOf: (origins: readonly string[] | undefined)
35
36
  * spelled like.
36
37
  *
37
38
  * A name that does not resolve is ALLOWED through: there is nothing to judge, and the request is about to fail on
38
- * its own with a better error than this could give. What remains open is DNS rebinding — an attacker's own server
39
- * answering a public address here and a private one when the socket is opened a moment later — which is closed
40
- * only by resolving and connecting to the same address, and that belongs in the transport rather than here.
39
+ * its own with a better error than this could give.
40
+ *
41
+ * Judging the answer is half of it: the transport would resolve the name again when it opens the socket, and an
42
+ * attacker's own DNS can answer a public address here and a private one a moment later (DNS rebinding). So what was
43
+ * judged is kept (`vetted`), and `fetchOutbound` connects to it and to nothing else.
41
44
  */
42
45
  export declare const assertOutboundAllowed: (url: URL, { lookup, privateOrigins }?: OutboundOptions) => Promise<void>;
46
+ type LookupCallback = (error: NodeJS.ErrnoException | null, address: string | LookupAddress[], family?: number) => void;
47
+ /**
48
+ * How a guarded request's socket finds its peer: among the addresses the name was judged to, never by asking DNS
49
+ * again. A name nobody judged — one that did not resolve when it was — is not found, rather than resolved now.
50
+ */
51
+ export declare const connectLookup: (hostname: string, options: LookupOneOptions | LookupAllOptions, callback: LookupCallback) => void;
43
52
  /**
44
53
  * Sends an authored request, judging EVERY hop it takes by `assertOutboundAllowed`.
45
54
  *
@@ -48,7 +57,8 @@ export declare const assertOutboundAllowed: (url: URL, { lookup, privateOrigins
48
57
  * therefore taken manually and each destination is checked before anything is sent to it.
49
58
  *
50
59
  * `base` is the caller's own transport — the action runner's is budgeted and capped — so every hop is also counted
51
- * against whatever that transport enforces.
60
+ * against whatever that transport enforces. It hands `init` on to Node's `fetch` as it got it: the `dispatcher` in it
61
+ * is what connects each hop to the addresses that were judged.
52
62
  */
53
63
  export declare const fetchOutbound: (base: typeof fetch, url: URL, init?: RequestInit, options?: OutboundOptions) => Promise<Response>;
54
64
  /**
@@ -67,3 +77,4 @@ export declare const cappedResponse: (response: Response, maxBytes: number, refu
67
77
  * arrives; a message back refuses the answer with it.
68
78
  */
69
79
  alsoCount?: (bytes: number) => string | undefined) => Response;
80
+ export {};
@@ -1,4 +1,4 @@
1
- import { i as onBroadcast, n as channelName, t as broadcast } from "../chunks/link-C9wyDS9H.mjs";
1
+ import { i as onBroadcast, n as channelName, t as broadcast } from "../chunks/link-CFSynFKL.mjs";
2
2
  // src/pubsub/memoryPubSub.ts
3
3
  var isRelayed = (value) => typeof value === "object" && value !== null && "topic" in value && typeof value.topic === "string" && "message" in value && typeof value.message === "string";
4
4
  /**
@@ -1,9 +1,10 @@
1
1
  export { createStatsRecorder, statsRecorderFor } from './recorder';
2
- export { STATS_LOGS_PATH, STATS_PATH, statsConfigProblem, statsStage, withStopping } from './stage';
2
+ export { METRICS_CONTENT_TYPE, gaugesText, metricsText, processGauges } from './metrics';
3
+ export { STATS_LOGS_PATH, STATS_METRICS_PATH, STATS_PATH, deploymentGauges, statsConfigProblem, statsStage, withStopping } from './stage';
3
4
  export { createLocalPoolSource, readPools } from './pools';
4
5
  export { LOAD_LIMITS, cpuLimitCores, overloaded, processLoad } from './load';
5
6
  export { processMemoryLimit, sampleProcessMemory } from './memory';
6
7
  export type { MemoryReading } from './memory';
7
8
  export type { ProcessLoad } from './load';
8
9
  export type { StatsRecorder } from './recorder';
9
- export type { InstanceHealth, InstancePhase, InstanceStatus, NamedWork, PoolHealth, PoolInstance, PoolKnob, PoolOverride, PoolReport, PoolResources, PoolResourcesControl, PoolScaler, PoolSource, ProcessStats, RunEnd, RunLabel, SlowRun, StatsConfig, StatsMinute, StatsThresholds, StatsWindow } from './types';
10
+ export type { InstanceHealth, InstancePhase, InstanceStatus, NamedWork, PoolHealth, PoolInstance, PoolKnob, PoolOverride, PoolReport, PoolResources, PoolResourcesControl, PoolScaler, PoolSource, ProcessStats, RunEnd, RunLabel, SlowRun, StatsConfig, StatsGauge, StatsMinute, StatsThresholds, StatsWindow } from './types';
@@ -1,4 +1,4 @@
1
- import { a as createStatsRecorder, d as STATS_LOGS_PATH, f as STATS_PATH, n as statsStage, o as statsRecorderFor, r as withStopping, t as statsConfigProblem } from "../chunks/stage-y6deE9LJ.mjs";
1
+ import { _ as STATS_METRICS_PATH, c as METRICS_CONTENT_TYPE, d as processGauges, g as STATS_LOGS_PATH, i as withStopping, l as gaugesText, n as statsConfigProblem, o as createStatsRecorder, r as statsStage, s as statsRecorderFor, t as deploymentGauges, u as metricsText, v as STATS_PATH } from "../chunks/stage-C62Zvzw_.mjs";
2
2
  import { availableParallelism } from "node:os";
3
3
  import { readFileSync } from "node:fs";
4
4
  import { monitorEventLoopDelay, performance as performance$1 } from "node:perf_hooks";
@@ -225,4 +225,4 @@ var sampleProcessMemory = () => {
225
225
  };
226
226
  };
227
227
  };
228
- export { LOAD_LIMITS, STATS_LOGS_PATH, STATS_PATH, cpuLimitCores, createLocalPoolSource, createStatsRecorder, overloaded, processLoad, processMemoryLimit, readPools, sampleProcessMemory, statsConfigProblem, statsRecorderFor, statsStage, withStopping };
228
+ export { LOAD_LIMITS, METRICS_CONTENT_TYPE, STATS_LOGS_PATH, STATS_METRICS_PATH, STATS_PATH, cpuLimitCores, createLocalPoolSource, createStatsRecorder, deploymentGauges, gaugesText, metricsText, overloaded, processGauges, processLoad, processMemoryLimit, readPools, sampleProcessMemory, statsConfigProblem, statsRecorderFor, statsStage, withStopping };
@@ -0,0 +1,16 @@
1
+ import { ProcessStats, StatsGauge } from './types';
2
+ /** Prometheus's text format, the version every scraper reads. */
3
+ export declare const METRICS_CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8";
4
+ /**
5
+ * Gauges in Prometheus's text format: a `# HELP` and a `# TYPE` line once per name, the first help given winning, then
6
+ * one line a sample. Throws naming the first figure a scraper would refuse.
7
+ */
8
+ export declare const gaugesText: (gauges: StatsGauge[]) => string;
9
+ /**
10
+ * What `/_stats` says of a process, as gauges: who it is, its load now, its work over the last minute, quarter and hour
11
+ * (the `window` label) and its health. Labelled by its pool and its `process` — not `instance`, which a scraper keeps
12
+ * for the address it scraped.
13
+ */
14
+ export declare const processGauges: (stats: ProcessStats) => StatsGauge[];
15
+ /** A process's metrics: its own figures, and after them those its deployment adds (`StatsConfig.gauges`). */
16
+ export declare const metricsText: (stats: ProcessStats, extra?: StatsGauge[]) => string;
@@ -1,12 +1,18 @@
1
- import { STATS_LOGS_PATH, STATS_PATH } from '../http/probes';
2
- import { ProcessStats } from './types';
1
+ import { STATS_LOGS_PATH, STATS_METRICS_PATH, STATS_PATH } from '../http/probes';
2
+ import { ProcessStats, StatsConfig, StatsGauge } from './types';
3
3
  import { BaseContext, Stage } from '../http/types';
4
- export { STATS_LOGS_PATH, STATS_PATH };
4
+ export { STATS_LOGS_PATH, STATS_METRICS_PATH, STATS_PATH };
5
5
  /**
6
- * `GET /_stats`: this process's {@link ProcessStats} — and `GET /_stats/logs` the last lines of its log — for whoever holds its stats secret (`stats.secret`) — always
7
- * behind it, whether or not the path is also kept off the public network, because a self-hoster may have no network
8
- * policy to keep it there. A server configured with no `stats` answers nothing here, and the path goes on to what else
9
- * it serves.
6
+ * The deployment's own figures, checked as Prometheus would read them. One that fails — its read rejected, or a name a
7
+ * scraper refuses — is said in the log and by `plitzi_stats_gauges_failed`, and the answer keeps the process's own.
8
+ */
9
+ export declare const deploymentGauges: (stats: StatsConfig) => Promise<StatsGauge[]>;
10
+ /**
11
+ * `GET /_stats`: this process's {@link ProcessStats} — `GET /_stats/logs` the last lines of its log, and
12
+ * `GET /_stats/metrics` its stats as Prometheus metrics with the deployment's own after them — for whoever holds its stats
13
+ * secret (`stats.secret`) — always behind it, whether or not the path is also kept off the public network, because a
14
+ * self-hoster may have no network policy to keep it there. A server configured with no `stats` answers nothing here,
15
+ * and the path goes on to what else it serves.
10
16
  */
11
17
  export declare const statsStage: Stage;
12
18
  /** A process told to stop says so: `stopping`, finishing what it runs — what a deploy looks like on the pools' screen. */
@@ -1,5 +1,5 @@
1
1
  /**
2
- * What a process says of itself (RFC 0032, §7): who it is, how loaded, how its work went over the last minute, quarter
2
+ * What a process says of itself (docs/en/server-packages.md): who it is, how loaded, how its work went over the last minute, quarter
3
3
  * and hour, and whether that is healthy. Every server process is built on the kernel, so they all say it the same way —
4
4
  * page servers, workers, functions runners — and `readPools` reads them all alike.
5
5
  */
@@ -12,6 +12,19 @@ export type StatsConfig = {
12
12
  /** This instance's name in its pool. Defaults to the host's name and the process id. */
13
13
  instance?: string;
14
14
  thresholds?: StatsThresholds;
15
+ /**
16
+ * The deployment's own figures, said after the process's on `/_stats/metrics` — a queue's depth, its oldest wait —
17
+ * read when a scraper asks. One that rejects, or names what Prometheus refuses, is said in the log and as
18
+ * `plitzi_stats_gauges_failed`; the process's own figures are answered all the same.
19
+ */
20
+ gauges?: () => Promise<StatsGauge[]>;
21
+ };
22
+ /** One figure as `/_stats/metrics` says it: a Prometheus gauge, its value now and its labels. */
23
+ export type StatsGauge = {
24
+ name: string;
25
+ help: string;
26
+ value: number;
27
+ labels?: Record<string, string>;
15
28
  };
16
29
  /** Where `degraded` starts. Each is checked against the last fifteen minutes, and the slots and the lag as they are now. */
17
30
  export type StatsThresholds = {
@@ -1,6 +1,6 @@
1
1
  import { i as createStoreHost, n as createFleetHub, r as createListeners, t as createFleetClient } from "../chunks/channel-DnVf7PJB.mjs";
2
2
  import { r as selectRows, t as execute } from "../chunks/query-DGbrN3mN.mjs";
3
- import { r as generateTokenKeys } from "../chunks/tokens-CBd5tXut.mjs";
3
+ import { r as generateTokenKeys } from "../chunks/tokens-BAV5YeT9.mjs";
4
4
  // src/testing/certificates.ts
5
5
  /**
6
6
  * Self-signed certificates for tests alone — made for them, trusted by nothing, naming no real host. Kept as text so
@@ -1 +1 @@
1
- export { t as DEFAULT_LIFETIMES, n as createTokens, r as generateTokenKeys, i as userIdOf } from "../chunks/tokens-CBd5tXut.mjs";
1
+ export { t as DEFAULT_LIFETIMES, n as createTokens, r as generateTokenKeys, i as userIdOf } from "../chunks/tokens-BAV5YeT9.mjs";
@@ -177,8 +177,13 @@ export declare const createTokens: (config: TokenConfig) => {
177
177
  }>;
178
178
  /**
179
179
  * A token that no longer verifies for any reason the issuer can fix by re-minting — expiry, a pre-registered-
180
- * claims shape, or an issuer from a deployment this one is not. Used by the endpoints that hand tokens back
181
- * out, so a caller never has to know why.
180
+ * claims shape, an issuer from a deployment this one is not, or a key pair this one no longer holds. Used by the
181
+ * endpoints that hand tokens back out, so a caller never has to know why.
182
+ *
183
+ * A credential signed under keys rotated away from reads as `malformed` to `verify` (a `kid` it does not list, a
184
+ * signature it cannot check) — and so did every stored one after a deployment changed its pair, none re-minted. It
185
+ * is told from garbage by being a JWT at all: what never was one is not re-minted, or storing nonsense in a row would
186
+ * be a way to be handed a working credential.
182
187
  */
183
188
  needsRotation: (token: string) => boolean;
184
189
  /** Undefined for a credential that never expires, which is what a host should read as "no renewal needed". */
@@ -0,0 +1,27 @@
1
+ /**
2
+ * One trace for a run, across every process it crosses: the W3C Trace Context `traceparent` taken at the edge — or
3
+ * made there — and carried on every hop (the page server to the worker, the worker to the runner, a runtime). Each
4
+ * process answers a request as a span of its own in the caller's trace, and every line it logs meanwhile names the
5
+ * trace (`trace=…`), so the lines of one run are found together whichever instance said them. No vendor and no exporter:
6
+ * a deployment that wants spans in a collector reads them off the log events, or wraps the hops itself.
7
+ */
8
+ export declare const TRACEPARENT = "traceparent";
9
+ export type Trace = {
10
+ /** 32 hexadecimal characters: the same on every hop of one run. */
11
+ traceId: string;
12
+ /** 16 hexadecimal characters: this process's span. */
13
+ spanId: string;
14
+ /** The trace flags the caller sent (`01`, sampled), kept as they came. */
15
+ flags: string;
16
+ };
17
+ /** A caller's trace, from its `traceparent` — nothing from a header that is not one (an id of zeros is none, as W3C says). */
18
+ export declare const readTraceparent: (header: string | readonly string[] | undefined) => Trace | undefined;
19
+ /** A span of this process: in the caller's trace when there is one, the first of a new trace when there is none. */
20
+ export declare const spanOf: (parent?: Trace) => Trace;
21
+ export declare const traceparentOf: (trace: Trace) => string;
22
+ /** Runs work as a span of a trace: everything it awaits, and every line it logs, is that trace's. */
23
+ export declare const runInTrace: <T>(trace: Trace, work: () => T) => T;
24
+ /** The trace the work in hand is part of, when it is part of one. */
25
+ export declare const currentTrace: () => Trace | undefined;
26
+ /** The header a hop carries: the trace in hand as the caller of the next span. Empty outside a trace. */
27
+ export declare const traceHeaders: () => Record<string, string>;
@@ -0,0 +1,43 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { randomBytes } from "node:crypto";
3
+ // src/trace/index.ts
4
+ /**
5
+ * One trace for a run, across every process it crosses: the W3C Trace Context `traceparent` taken at the edge — or
6
+ * made there — and carried on every hop (the page server to the worker, the worker to the runner, a runtime). Each
7
+ * process answers a request as a span of its own in the caller's trace, and every line it logs meanwhile names the
8
+ * trace (`trace=…`), so the lines of one run are found together whichever instance said them. No vendor and no exporter:
9
+ * a deployment that wants spans in a collector reads them off the log events, or wraps the hops itself.
10
+ */
11
+ var TRACEPARENT = "traceparent";
12
+ var TRACEPARENT_FORMAT = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
13
+ var NONE = /^0+$/;
14
+ var hex = (bytes) => randomBytes(bytes).toString("hex");
15
+ /** A caller's trace, from its `traceparent` — nothing from a header that is not one (an id of zeros is none, as W3C says). */
16
+ var readTraceparent = (header) => {
17
+ const value = typeof header === "string" ? header : header?.[0];
18
+ const match = typeof value === "string" ? TRACEPARENT_FORMAT.exec(value.trim().toLowerCase()) : null;
19
+ if (!match || NONE.test(match[1]) || NONE.test(match[2])) return;
20
+ return {
21
+ traceId: match[1],
22
+ spanId: match[2],
23
+ flags: match[3]
24
+ };
25
+ };
26
+ /** A span of this process: in the caller's trace when there is one, the first of a new trace when there is none. */
27
+ var spanOf = (parent) => ({
28
+ traceId: parent?.traceId ?? hex(16),
29
+ spanId: hex(8),
30
+ flags: parent?.flags ?? "01"
31
+ });
32
+ var traceparentOf = (trace) => `00-${trace.traceId}-${trace.spanId}-${trace.flags}`;
33
+ var storage = new AsyncLocalStorage();
34
+ /** Runs work as a span of a trace: everything it awaits, and every line it logs, is that trace's. */
35
+ var runInTrace = (trace, work) => storage.run(trace, work);
36
+ /** The trace the work in hand is part of, when it is part of one. */
37
+ var currentTrace = () => storage.getStore();
38
+ /** The header a hop carries: the trace in hand as the caller of the next span. Empty outside a trace. */
39
+ var traceHeaders = () => {
40
+ const trace = currentTrace();
41
+ return trace ? { [TRACEPARENT]: traceparentOf(trace) } : {};
42
+ };
43
+ export { TRACEPARENT, currentTrace, readTraceparent, runInTrace, spanOf, traceHeaders, traceparentOf };
@@ -188,6 +188,12 @@ export type SSRAdapters = {
188
188
  } | {
189
189
  notRun: string;
190
190
  }>;
191
+ /**
192
+ * The space's own render credential (its public key), which a browser rendering a draft of it presents: the
193
+ * renderer's address names no space, and a draft is served only where its space is named. Absent, a look's picture
194
+ * is taken without it — which works only when the renderer's address is the space's own host.
195
+ */
196
+ getRenderCredential?: (spaceId: number) => Promise<string | undefined>;
191
197
  /** The space's own data: the draft's JSON files its server providers read (`/data/<file>`), and which copy they are.
192
198
  * When omitted, the MCP offers no data resource and refuses the data ops. */
193
199
  getData?: (spaceId: number) => Promise<DataDraft | undefined>;
@@ -4,7 +4,7 @@ import { SSRMiddleware, ServerEnvironment } from './pipeline';
4
4
  import { StatsConfig } from '../stats/types';
5
5
  import { ServerFlags } from '@plitzi/sdk-shared/flags';
6
6
  /**
7
- * What every Plitzi server process is configured with (RFC 0032, D12): its transport, its log, its health, the headers
7
+ * What every Plitzi server process is configured with (docs/en/server-packages.md, D12): its transport, its log, its health, the headers
8
8
  * it answers with, what it may reach, and the adapters it asks. A page server's configuration and the actions engine's
9
9
  * are both this and their own.
10
10
  */
@@ -8,6 +8,8 @@ type ServerLogEventBase = {
8
8
  error?: string;
9
9
  /** ISO-8601 timestamp of when the event was emitted. */
10
10
  timestamp: string;
11
+ /** The W3C trace the work was part of (`sdk-kernel/trace`): one id for every line of one run, on every process. */
12
+ traceId?: string;
11
13
  };
12
14
  /** What every log event carries, whatever layer it came from. */
13
15
  /**
@@ -112,6 +114,8 @@ export type ServerMessageLogEvent = {
112
114
  ok: boolean;
113
115
  error?: string;
114
116
  timestamp: string;
117
+ /** The trace it was said in, as every other event's. */
118
+ traceId?: string;
115
119
  };
116
120
  export type ServerLogEvent = ServerRequestLogEvent | McpToolLogEvent | McpResourceLogEvent | ActionRunLogEvent | ActionRejectLogEvent | ServerMessageLogEvent;
117
121
  /** The sink a consumer provides to receive every {@link ServerLogEvent} (see `SSRServerConfig.logger`). */
@@ -76,6 +76,8 @@ export type SSRTemplateProps = {
76
76
  title?: string;
77
77
  /** Meta description for the document, and the share-preview text derived from it. */
78
78
  description?: string;
79
+ /** The page's JSON-LD, each object as the text of its `<script type="application/ld+json">`, escaped for the tag. */
80
+ structuredData?: string[];
79
81
  /**
80
82
  * The head's tags besides the title and the JSON-LD — description, robots, Open Graph and card, the canonical
81
83
  * address, the icon, the browser's colour, the language — as `pageHeadTags` decides them. The server's own.
@@ -85,6 +87,13 @@ export type SSRTemplateProps = {
85
87
  cssPath?: string;
86
88
  /** Font Awesome's rules, after `cssPath`; its fonts are files beside it, fetched only for a style the page uses. */
87
89
  iconsCssPath?: string;
90
+ /**
91
+ * The space's own icon faces — the glyphs it names, cut from the whole font (`/_plitzi/icons/`) — declared after
92
+ * `iconsCssPath`'s, so a glyph in their range is fetched from them and any other from the whole font.
93
+ */
94
+ iconFaces?: string;
95
+ /** What the page's writes to the deployment's own APIs echo the CSRF token with (`@plitzi/sdk-shared/csrf`), as JSON. */
96
+ csrfHint?: string;
88
97
  /**
89
98
  * Where the page fetches the space from, when it travels beside the document rather than in its payload: the
90
99
  * page preloads it, and the bootstrap reads it before hydrating.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plitzi/sdk-kernel",
3
- "version": "0.39.2",
3
+ "version": "0.39.4",
4
4
  "license": "AGPL-3.0",
5
5
  "description": "What every Plitzi server process is built on: the HTTP pipeline, health and shutdown, the host → deployment resolution, and verifying who a request is.",
6
6
  "files": [
@@ -37,7 +37,7 @@
37
37
  "build:prod": "vite build"
38
38
  },
39
39
  "dependencies": {
40
- "@plitzi/sdk-shared": "0.39.2",
40
+ "@plitzi/sdk-shared": "0.39.4",
41
41
  "jsonwebtoken": "^9.0.3",
42
42
  "undici": "^8.12.4",
43
43
  "ws": "^8.22.2"
@@ -1,55 +0,0 @@
1
- // src/log/tail.ts
2
- /** How many lines a process keeps: a busy minute of a page server, an hour of a quiet worker. */
3
- var LOG_TAIL_SIZE = 1e3;
4
- var RANK = {
5
- error: 1,
6
- warn: 2,
7
- info: 3,
8
- debug: 4
9
- };
10
- var lines = [];
11
- var seq = 0;
12
- /** Keeps a line said by the deployment's own logger (`kind: 'app'`) beside the kernel's. */
13
- var keepLogLine = (level, text, kind = "app") => {
14
- seq += 1;
15
- lines.push({
16
- seq,
17
- at: (/* @__PURE__ */ new Date()).toISOString(),
18
- level,
19
- kind,
20
- text
21
- });
22
- if (lines.length > 1e3) lines.splice(0, lines.length - LOG_TAIL_SIZE);
23
- };
24
- /** Keeps an event, rendered, at its own level. */
25
- var keepLogEvent = (event, level, text) => {
26
- keepLogLine(level, text, event.kind);
27
- };
28
- /** What a reader asked for, oldest first, and the newest line's number — what it asks `since` next. */
29
- var readLogTail = ({ since = 0, level = "debug", limit = LOG_TAIL_SIZE, q } = {}) => {
30
- const needle = q?.trim().toLowerCase();
31
- return {
32
- lines: lines.filter((line) => line.seq > since && RANK[line.level] <= RANK[level] && (!needle || line.text.toLowerCase().includes(needle))).slice(-Math.min(Math.max(1, limit), LOG_TAIL_SIZE)),
33
- last: seq,
34
- kept: lines.length
35
- };
36
- };
37
- var LEVELS = [
38
- "error",
39
- "warn",
40
- "info",
41
- "debug"
42
- ];
43
- /** A log query from a request's query string, every value checked: what it cannot read is left at its default. */
44
- var logQueryOf = (query) => {
45
- const since = Number(query.since);
46
- const limit = Number(query.limit);
47
- const level = LEVELS.find((each) => each === query.level);
48
- return {
49
- ...Number.isInteger(since) && since > 0 ? { since } : {},
50
- ...Number.isInteger(limit) && limit > 0 ? { limit } : {},
51
- ...level ? { level } : {},
52
- ...query.q ? { q: query.q.slice(0, 200) } : {}
53
- };
54
- };
55
- export { readLogTail as a, logQueryOf as i, keepLogEvent as n, keepLogLine as r, LOG_TAIL_SIZE as t };