@plitzi/sdk-server 0.39.3 → 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 (66) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +49 -7
  3. package/dist/auth.d.ts +3 -2
  4. package/dist/auth.js +26 -107
  5. package/dist/cache.js +1 -1
  6. package/dist/chunks/{buildBody-W9D8ySNY.js → buildBody-BSC0UbjP.js} +352 -110
  7. package/dist/chunks/{core-TlrWmT4B.js → core-w7FIMpgv.js} +86 -4
  8. package/dist/chunks/{createServer-Bd_b7T3k.js → createServer-BQ0KE0Qu.js} +157 -34
  9. package/dist/chunks/{platform-DhdFYWm5.js → platform-C0AVlwpB.js} +2 -2
  10. package/dist/chunks/throttle-CRiZB6_A.js +330 -0
  11. package/dist/chunks/{token-B2uY9JzU.js → token-CBUubxtm.js} +1 -1
  12. package/dist/chunks/views/template.ejs +7 -0
  13. package/dist/core/auth/api/context.d.ts +4 -4
  14. package/dist/core/auth/api/values.d.ts +6 -0
  15. package/dist/core/auth/createAuth.d.ts +1 -1
  16. package/dist/core/auth/throttle.d.ts +54 -4
  17. package/dist/core/createServer.d.ts +1 -1
  18. package/dist/core/platform.d.ts +1 -1
  19. package/dist/core/services/iconFaces.d.ts +3 -0
  20. package/dist/core/services/llmsTxt.d.ts +15 -0
  21. package/dist/core/services/robotsTxt.d.ts +2 -8
  22. package/dist/core/services/securityTxt.d.ts +10 -0
  23. package/dist/handlers.js +1 -1
  24. package/dist/helpers/documentParts.d.ts +10 -0
  25. package/dist/helpers/paintedCookie.d.ts +15 -1
  26. package/dist/index.d.ts +1 -1
  27. package/dist/index.js +3 -3
  28. package/dist/modules/icons/glyphs.d.ts +21 -0
  29. package/dist/modules/icons/handler.d.ts +11 -0
  30. package/dist/modules/icons/spaceIcons.d.ts +26 -0
  31. package/dist/modules/rsc/connectorRscData.d.ts +4 -2
  32. package/dist/modules/rsc/resolveRscData.d.ts +4 -1
  33. package/dist/modules/ssr/csrfHint.d.ts +12 -0
  34. package/dist/modules/ssr/defaultFavicon.d.ts +1 -1
  35. package/dist/modules/ssr/spaceDocument.d.ts +8 -1
  36. package/dist/oauth.js +1 -1
  37. package/dist/platform.d.ts +1 -1
  38. package/dist/platform.js +1 -1
  39. package/dist/project.js +3 -3
  40. package/dist/spaces.js +1 -1
  41. package/dist/ssr.js +1 -1
  42. package/dist/types/config.d.ts +24 -0
  43. package/dist/types/index.d.ts +1 -1
  44. package/package.json +10 -8
  45. package/skills/plitzi-authoring/recipes/accordion.ts +3 -1
  46. package/skills/plitzi-authoring/recipes/carousel.ts +68 -63
  47. package/skills/plitzi-authoring/recipes/detail-page.ts +43 -33
  48. package/skills/plitzi-authoring/recipes/embed-and-svg.ts +16 -11
  49. package/skills/plitzi-authoring/recipes/every-few-seconds.ts +52 -42
  50. package/skills/plitzi-authoring/recipes/feature-flag.ts +7 -2
  51. package/skills/plitzi-authoring/recipes/filter-a-list.ts +39 -31
  52. package/skills/plitzi-authoring/recipes/forms-and-modals.ts +34 -28
  53. package/skills/plitzi-authoring/recipes/from-tailwind.ts +11 -6
  54. package/skills/plitzi-authoring/recipes/link-to-a-section.ts +11 -6
  55. package/skills/plitzi-authoring/recipes/link-with-data.ts +21 -16
  56. package/skills/plitzi-authoring/recipes/marquee.ts +17 -12
  57. package/skills/plitzi-authoring/recipes/plugin.ts +16 -10
  58. package/skills/plitzi-authoring/recipes/scroll-a-row.ts +30 -25
  59. package/skills/plitzi-authoring/recipes/server-data.ts +15 -10
  60. package/skills/plitzi-authoring/recipes/show-data.ts +32 -24
  61. package/skills/plitzi-authoring/recipes/style-a-page.ts +9 -4
  62. package/skills/plitzi-authoring/recipes/typed-data.ts +26 -21
  63. package/skills/plitzi-authoring/recipes/usable-without-sight.ts +16 -11
  64. package/skills/plitzi-authoring/reference/authoring-errors.md +3 -0
  65. package/skills/plitzi-authoring/reference/efficiency.md +2 -1
  66. package/dist/chunks/throttle-BH7JLIOF.js +0 -108
@@ -0,0 +1,330 @@
1
+ import { fleetStore, forwardedIp } from "@plitzi/sdk-kernel/http";
2
+ import { randomUUID } from "node:crypto";
3
+ // src/core/auth/api/values.ts
4
+ /**
5
+ * The address a request came from: what the host resolved (`req.ip` behind its `trust proxy`), else what the proxy in
6
+ * front says — `X-Forwarded-For` and the headers an edge sets in its place. The same reading for a session's device
7
+ * and for the sign-in throttle, on any edge (a load balancer, a CDN, an ingress) and with none.
8
+ */
9
+ var addressOf = (carrier) => {
10
+ if (!carrier) return;
11
+ return carrier.ip || forwardedIp(carrier.headers) || void 0;
12
+ };
13
+ var clientOf = (carrier) => {
14
+ if (!carrier) return;
15
+ const userAgent = carrier.headers["user-agent"];
16
+ const ip = addressOf(carrier);
17
+ const client = {
18
+ ...typeof userAgent === "string" && userAgent ? { userAgent } : {},
19
+ ...ip ? { ip } : {},
20
+ ...carrier.hostname ? { host: carrier.hostname.toLowerCase() } : {}
21
+ };
22
+ return client.userAgent || client.ip || client.host ? client : void 0;
23
+ };
24
+ /**
25
+ * The account store, as auth needs to see it. Every method is optional except the three the session cycle cannot do
26
+ * without, and **what is absent decides what this server offers**: a deployment with no `createAccount` has no
27
+ * signup, and its route answers 404 rather than failing at runtime. That rule is what lets one server serve a
28
+ * deployment with its own user table and one that signs everybody in through an external provider.
29
+ */
30
+ var refuse = (status, error, reason) => ({
31
+ ok: false,
32
+ status,
33
+ body: reason ? {
34
+ error,
35
+ reason
36
+ } : { error }
37
+ });
38
+ var NOT_OFFERED = refuse(404, "Not found");
39
+ /**
40
+ * A field from a request body, as a string. Numbers count: JSON carries an all-digits password as a number, and a
41
+ * client that sends one has supplied a password — refusing it as "credentials are required" is a lie about what
42
+ * arrived. Objects and arrays do not, since `[object Object]` is not a value anybody sent.
43
+ */
44
+ var asText = (value) => {
45
+ if (typeof value === "string") return value;
46
+ return typeof value === "number" && Number.isFinite(value) ? String(value) : "";
47
+ };
48
+ var asString = (value) => asText(value).trim();
49
+ /**
50
+ * The destination a caller named, for a mail to carry — or nothing at all.
51
+ *
52
+ * Carried, not judged: the kernel has no redirect policy, and the link it ends up in is composed by the deployment,
53
+ * which vets it there (`createRedirectPolicy`). Absent rather than empty when there is none, so a mail template never
54
+ * has to know that `''` means "nowhere".
55
+ */
56
+ var destinationOf = (value) => {
57
+ const redirect = asString(value);
58
+ return redirect ? { redirect } : {};
59
+ };
60
+ var now = () => Math.floor(Date.now() / 1e3);
61
+ var HOUR = 3600;
62
+ /**
63
+ * How long the things this server mails or hands out stay good for. Constants rather than configuration: each is a
64
+ * security answer with one sensible value, and an option here is a question every deployment has to work out an
65
+ * answer to before it can start.
66
+ */
67
+ var LIFETIME = {
68
+ /** A code from an email. Long enough to go and find it, short enough that a stolen one is worthless. */
69
+ signInCode: 600,
70
+ /** A reset link IS a password, and it sits in an inbox, a mail archive, a forwarded ticket. */
71
+ resetLink: HOUR,
72
+ /** Confirming an address is not a credential in the same way, and people read their mail tomorrow. */
73
+ confirmLink: 24 * HOUR,
74
+ /** A borrowed session — see `admin.impersonate`. Short, and it cannot renew. */
75
+ impersonation: 900
76
+ };
77
+ var STATUSES = [
78
+ "active",
79
+ "inactive",
80
+ "blocked"
81
+ ];
82
+ /**
83
+ * Why an account may not hold a session, when it may not.
84
+ *
85
+ * `active` answers whether it may sign in at all; `verified` answers whether its owner can do anything about that.
86
+ * A deployment where confirming an address is what makes an account active — Plitzi is one — refuses both through
87
+ * the same flag, so a screen told only `inactive` has to tell somebody whose address has simply never answered that
88
+ * their password was wrong. It was, in fact, right.
89
+ */
90
+ var deniedReason = (account) => account && !account.verified ? "unverified" : "inactive";
91
+ /** An account as it may be shown. Never the password hash, and never the credentials — not even to an admin. */
92
+ var profileOf = (account) => ({
93
+ id: account.id,
94
+ username: account.username,
95
+ email: account.email,
96
+ active: account.active,
97
+ verified: account.verified
98
+ });
99
+ // src/core/auth/throttle.ts
100
+ /**
101
+ * The rate limit a deployment gets without asking for one.
102
+ *
103
+ * This used to be a required-to-be-safe option: no `rateLimit`, no limit, and sign-in was an unmetered password
104
+ * oracle. Nobody sets an option they have not read about, so the effect of "there is no sensible default" was that
105
+ * the common deployment shipped without any — which is not a neutral outcome, it is the bad one.
106
+ *
107
+ * It counts in memory by default, and that is an honest limitation rather than a hidden one: several replicas each
108
+ * keep their own window, so four replicas tolerate four times the attempts. Four times a small number is still a small
109
+ * number, and it beats infinity. A deployment of several replicas passes `rateLimit: createRateLimit({ counts:
110
+ * redisThrottleCounts(redis) })`: one count for all of them. The workers of one server are one replica: they count in
111
+ * the primary (`fleetRateLimit`).
112
+ */
113
+ /** Attempts allowed per window, per key, per action. */
114
+ var LIMITS = {
115
+ /** Credential stuffing is the thing being priced out. Ten wrong passwords in five minutes is already a lot. */
116
+ login: {
117
+ attempts: 10,
118
+ windowSeconds: 300
119
+ },
120
+ signup: {
121
+ attempts: 5,
122
+ windowSeconds: 3600
123
+ },
124
+ /** Mailing flows are throttled by address, or the endpoint is a way to send somebody a hundred emails. */
125
+ forgotPassword: {
126
+ attempts: 5,
127
+ windowSeconds: 3600
128
+ },
129
+ /** By token: without this a reset token is guessable by trying, however opaque it is. */
130
+ resetPassword: {
131
+ attempts: 10,
132
+ windowSeconds: 3600
133
+ },
134
+ changePassword: {
135
+ attempts: 10,
136
+ windowSeconds: 300
137
+ },
138
+ exchange: {
139
+ attempts: 30,
140
+ windowSeconds: 300
141
+ },
142
+ /** Six digits is a million guesses, so the limit is what makes a second factor worth anything. */
143
+ mfa: {
144
+ attempts: 5,
145
+ windowSeconds: 300
146
+ },
147
+ passwordless: {
148
+ attempts: 5,
149
+ windowSeconds: 900
150
+ }
151
+ };
152
+ /**
153
+ * Signing in is counted three ways when the address is known, so a stranger who knows a username cannot keep its owner
154
+ * out, and one password tried over many usernames is still slowed:
155
+ *
156
+ * - **the account from one address** — `LIMITS.login`: the failures that address made on it, and only it is refused;
157
+ * - **one address over any accounts** — a password sprayed over usernames;
158
+ * - **the account from anywhere** — a ceiling well above the first: an address read from `X-Forwarded-For` can be
159
+ * spelled by the client, and rotating it must not buy unlimited guesses on one account.
160
+ *
161
+ * With no address, the account alone, at `LIMITS.login` — what it always was.
162
+ */
163
+ var LOGIN_FROM_ADDRESS = {
164
+ attempts: 30,
165
+ windowSeconds: 300
166
+ };
167
+ var LOGIN_ACCOUNT_CEILING = {
168
+ attempts: 100,
169
+ windowSeconds: 300
170
+ };
171
+ /** Stop the map growing without bound on a server nobody is attacking politely. */
172
+ var SWEEP_EVERY = 1e3;
173
+ var countersOf = (attempt) => {
174
+ const address = attempt.address ?? addressOf(attempt.carrier);
175
+ if (attempt.action !== "login" || !address) return [{
176
+ key: `${attempt.action}:${attempt.key}`,
177
+ ...LIMITS[attempt.action]
178
+ }];
179
+ return [
180
+ {
181
+ key: `login:${attempt.key}@${address}`,
182
+ ...LIMITS.login
183
+ },
184
+ {
185
+ key: `login@${address}`,
186
+ ...LOGIN_FROM_ADDRESS,
187
+ spray: true
188
+ },
189
+ {
190
+ key: `login:${attempt.key}`,
191
+ ...LOGIN_ACCOUNT_CEILING
192
+ }
193
+ ];
194
+ };
195
+ /** The counts in this process's memory: one replica's, or a fleet's primary's (`fleetRateLimit`). */
196
+ var memoryThrottleCounts = () => {
197
+ const hits = /* @__PURE__ */ new Map();
198
+ let sinceSweep = 0;
199
+ const sweep = (now) => {
200
+ for (const [key, { windowSeconds, times }] of hits) {
201
+ const live = times.filter((at) => at > now - windowSeconds);
202
+ if (live.length === 0) hits.delete(key);
203
+ else hits.set(key, {
204
+ windowSeconds,
205
+ times: live
206
+ });
207
+ }
208
+ };
209
+ return {
210
+ attempt: (counters, now) => {
211
+ if (++sinceSweep >= SWEEP_EVERY) {
212
+ sinceSweep = 0;
213
+ sweep(now);
214
+ }
215
+ const recent = counters.map((counter) => ({
216
+ counter,
217
+ times: (hits.get(counter.key)?.times ?? []).filter((at) => at > now - counter.windowSeconds)
218
+ }));
219
+ const full = recent.filter(({ counter, times }) => times.length >= counter.attempts);
220
+ if (full.length > 0) {
221
+ const retryAfter = Math.max(...full.map(({ counter, times }) => Math.max(1, times[0] + counter.windowSeconds - now)));
222
+ return Promise.resolve({
223
+ allowed: false,
224
+ retryAfter
225
+ });
226
+ }
227
+ recent.forEach(({ counter, times }) => {
228
+ hits.set(counter.key, {
229
+ windowSeconds: counter.windowSeconds,
230
+ times: [...times, now]
231
+ });
232
+ });
233
+ return Promise.resolve({ allowed: true });
234
+ },
235
+ succeeded: (counters) => {
236
+ for (const counter of counters) if (counter.spray) hits.get(counter.key)?.times.pop();
237
+ else hits.delete(counter.key);
238
+ return Promise.resolve();
239
+ }
240
+ };
241
+ };
242
+ /**
243
+ * Every window read and, none full, the attempt added to each — in one script, so no other replica's attempt lands
244
+ * between the read and the write. A window is a sorted set of the attempts' seconds; its key expires with its window.
245
+ * `ARGV`: now, a member unique to this attempt, then each counter's attempts and window.
246
+ */
247
+ var ATTEMPT_SCRIPT = `
248
+ local now = tonumber(ARGV[1])
249
+ local retry = 0
250
+ for i = 1, #KEYS do
251
+ local attempts = tonumber(ARGV[1 + i * 2])
252
+ local window = tonumber(ARGV[2 + i * 2])
253
+ redis.call('ZREMRANGEBYSCORE', KEYS[i], '-inf', now - window)
254
+ if redis.call('ZCARD', KEYS[i]) >= attempts then
255
+ local oldest = redis.call('ZRANGE', KEYS[i], 0, 0, 'WITHSCORES')
256
+ retry = math.max(retry, 1, tonumber(oldest[2]) + window - now)
257
+ end
258
+ end
259
+ if retry > 0 then
260
+ return retry
261
+ end
262
+ for i = 1, #KEYS do
263
+ redis.call('ZADD', KEYS[i], now, ARGV[2])
264
+ redis.call('EXPIRE', KEYS[i], tonumber(ARGV[2 + i * 2]))
265
+ end
266
+ return 0`;
267
+ /** Each counter forgotten, or — `ARGV[i]` is `1` — its latest attempt given back. */
268
+ var SUCCEEDED_SCRIPT = `
269
+ for i = 1, #KEYS do
270
+ if ARGV[i] == '1' then
271
+ redis.call('ZPOPMAX', KEYS[i])
272
+ else
273
+ redis.call('DEL', KEYS[i])
274
+ end
275
+ end
276
+ return 0`;
277
+ /**
278
+ * The counts in a Redis every replica reaches, so the replicas hold one count between them. `prefix` names the keys —
279
+ * keep a `{hash tag}` in it on a Redis Cluster: a script's keys must share a slot.
280
+ */
281
+ var redisThrottleCounts = (redis, { prefix = "{auth-throttle}:" } = {}) => ({
282
+ attempt: async (counters, now) => {
283
+ const waitSeconds = Number(await redis.eval(ATTEMPT_SCRIPT, counters.length, ...counters.map((counter) => `${prefix}${counter.key}`), now, `${String(now)}:${randomUUID()}`, ...counters.flatMap((counter) => [counter.attempts, counter.windowSeconds])));
284
+ return waitSeconds > 0 ? {
285
+ allowed: false,
286
+ retryAfter: waitSeconds
287
+ } : { allowed: true };
288
+ },
289
+ succeeded: async (counters) => {
290
+ await redis.eval(SUCCEEDED_SCRIPT, counters.length, ...counters.map((counter) => `${prefix}${counter.key}`), ...counters.map((counter) => counter.spray ? "1" : "0"));
291
+ }
292
+ });
293
+ /**
294
+ * The rate limit a deployment gets: the policy — which counts an attempt is held to, and what a success gives back —
295
+ * over a store of counts, this process's memory unless it is handed one the replicas share.
296
+ */
297
+ var createRateLimit = ({ counts = memoryThrottleCounts(), now = () => Date.now() } = {}) => async (attempt) => {
298
+ const counters = countersOf(attempt);
299
+ /**
300
+ * It worked, so nothing is being guarded against any more. Without this the counter cannot tell ten failures
301
+ * from ten sign-ins — the check runs before the password is examined — and an app that signs the same account
302
+ * in repeatedly would lock it out by succeeding. The address's own count keeps its other accounts' failures: it
303
+ * gives back only the attempt that worked.
304
+ */
305
+ if (attempt.succeeded) {
306
+ await counts.succeeded(counters);
307
+ return { allowed: true };
308
+ }
309
+ return counts.attempt(counters, Math.floor(now() / 1e3));
310
+ };
311
+ /** Every method of the store, for the copy a fleet's workers share (`FleetStores`, `core/server/fleet/link.ts`). */
312
+ var RATE_LIMIT_METHODS = { check: true };
313
+ /**
314
+ * In a worker of a fleet, the primary's {@link createRateLimit} in memory, so an attacker spreading attempts over
315
+ * connections meets one counter rather than one per worker. Nothing anywhere else.
316
+ */
317
+ var fleetRateLimit = () => {
318
+ const shared = fleetStore("auth.rateLimit", RATE_LIMIT_METHODS);
319
+ if (!shared) return;
320
+ return (attempt) => {
321
+ const address = addressOf(attempt.carrier);
322
+ return shared.check({
323
+ action: attempt.action,
324
+ key: attempt.key,
325
+ ...address ? { address } : {},
326
+ ...attempt.succeeded ? { succeeded: true } : {}
327
+ });
328
+ };
329
+ };
330
+ export { redisThrottleCounts as a, STATUSES as c, clientOf as d, deniedReason as f, refuse as g, profileOf as h, memoryThrottleCounts as i, asString as l, now as m, createRateLimit as n, LIFETIME as o, destinationOf as p, fleetRateLimit as r, NOT_OFFERED as s, RATE_LIMIT_METHODS as t, asText as u };
@@ -1,4 +1,4 @@
1
- import { h as escapeHtml } from "./core-TlrWmT4B.js";
1
+ import { h as escapeHtml } from "./core-w7FIMpgv.js";
2
2
  import { forwardedIp, requestAuthority, requestOrigin } from "@plitzi/sdk-kernel/http";
3
3
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
4
4
  // src/core/oauth/consentPage.ts
@@ -3,6 +3,9 @@
3
3
  <head>
4
4
  <meta charset="utf-8" />
5
5
  <title><%= locals.title || '' %></title>
6
+ <% if (locals.csrfHint) { %>
7
+ <meta name="plitzi-csrf" content="<%= locals.csrfHint %>" />
8
+ <% } %>
6
9
  <%
7
10
  /*
8
11
  What a link preview, a search engine and the browser read of the page, as `pageHeadTags` (@plitzi/sdk-shared)
@@ -92,6 +95,10 @@
92
95
  <% if (locals.iconsCssPath) { %>
93
96
  <link href="<%= locals.iconsCssPath %>" rel="stylesheet" />
94
97
  <% } %>
98
+ <%# The space's own glyphs, after the whole font's faces: what is in their range is fetched from them alone. %>
99
+ <% if (locals.iconFaces) { %>
100
+ <style data-plitzi-icons><%- locals.iconFaces %></style>
101
+ <% } %>
95
102
 
96
103
  <% if (!locals.ssrOnly) { %>
97
104
  <%#
@@ -47,10 +47,10 @@ export declare const createAuthContext: ({ tokens, identity, adapters, config }:
47
47
  adminPermission: string;
48
48
  impersonationPermission: string | undefined;
49
49
  policy: import('./types').PasswordPolicy;
50
- rateLimit: (attempt: ThrottleAttempt) => Promise<boolean | {
50
+ rateLimit: ((attempt: ThrottleAttempt) => Promise<boolean | {
51
51
  allowed: boolean;
52
52
  retryAfter?: number;
53
- }>;
53
+ }>) | ((attempt: import('../throttle').CountedAttempt) => Promise<import('../throttle').ThrottleVerdict>);
54
54
  onMailError: ((error: unknown, message: {
55
55
  to: string;
56
56
  template: string;
@@ -60,7 +60,7 @@ export declare const createAuthContext: ({ tokens, identity, adapters, config }:
60
60
  csrf: {
61
61
  issue: (sessionToken?: string) => string;
62
62
  cookieName: (hostname: string) => string;
63
- headerName: string;
63
+ headerName: "x-csrf-token";
64
64
  write: (req: import('@plitzi/sdk-kernel/identity').CookieRequest, res: import('@plitzi/sdk-kernel/identity').CookieSink, token: string) => void;
65
65
  clear: (req: import('@plitzi/sdk-kernel/identity').CookieRequest, res: import('@plitzi/sdk-kernel/identity').CookieSink) => void;
66
66
  read: (carrier: import('@plitzi/sdk-kernel/identity').CsrfCarrier) => string | undefined;
@@ -76,7 +76,7 @@ export declare const createAuthContext: ({ tokens, identity, adapters, config }:
76
76
  to: string;
77
77
  template: string;
78
78
  data: Record<string, string>;
79
- }) => Promise<void>;
79
+ }) => void;
80
80
  throttleSucceeded: (attempt: Omit<ThrottleAttempt, "succeeded">) => void;
81
81
  throttled: (attempt: ThrottleAttempt) => Promise<AuthOutcome | undefined>;
82
82
  rejectPassword: (value: string, context?: {
@@ -1,5 +1,11 @@
1
1
  import { AuthOutcome } from './types';
2
2
  import { AccountRecord, SessionClient, AccountStatus, CredentialCarrier, AuthFailure } from '@plitzi/sdk-kernel/identity';
3
+ /**
4
+ * The address a request came from: what the host resolved (`req.ip` behind its `trust proxy`), else what the proxy in
5
+ * front says — `X-Forwarded-For` and the headers an edge sets in its place. The same reading for a session's device
6
+ * and for the sign-in throttle, on any edge (a load balancer, a CDN, an ingress) and with none.
7
+ */
8
+ export declare const addressOf: (carrier?: CredentialCarrier) => string | undefined;
3
9
  export declare const clientOf: (carrier?: CredentialCarrier) => SessionClient | undefined;
4
10
  /**
5
11
  * The account store, as auth needs to see it. Every method is optional except the three the session cycle cannot do
@@ -201,7 +201,7 @@ export declare const createAuth: (config: AuthConfig) => {
201
201
  csrf: {
202
202
  issue: (sessionToken?: string) => string;
203
203
  cookieName: (hostname: string) => string;
204
- headerName: string;
204
+ headerName: "x-csrf-token";
205
205
  write: (req: import('@plitzi/sdk-kernel/identity').CookieRequest, res: CookieSink, token: string) => void;
206
206
  clear: (req: import('@plitzi/sdk-kernel/identity').CookieRequest, res: CookieSink) => void;
207
207
  read: (carrier: import('@plitzi/sdk-kernel/identity').CsrfCarrier) => string | undefined;
@@ -1,16 +1,66 @@
1
1
  import { ThrottleAttempt } from './api';
2
2
  import { StoreMethods } from '@plitzi/sdk-kernel/http';
3
- export declare const createMemoryRateLimit: () => ((attempt: ThrottleAttempt) => Promise<{
3
+ /** An attempt as the count reads it: the address resolved before it crosses to a fleet's primary (`fleetRateLimit`). */
4
+ export type CountedAttempt = Omit<ThrottleAttempt, 'carrier'> & {
5
+ carrier?: ThrottleAttempt['carrier'];
6
+ address?: string;
7
+ };
8
+ /**
9
+ * One count an attempt is held to: its key, the attempts its window holds, and the window. `spray` marks the address's
10
+ * count over any accounts, which a success gives back one attempt of rather than forgetting.
11
+ */
12
+ export type ThrottleCounter = {
13
+ key: string;
14
+ attempts: number;
15
+ windowSeconds: number;
16
+ spray?: boolean;
17
+ };
18
+ export type ThrottleVerdict = {
4
19
  allowed: boolean;
5
20
  retryAfter?: number;
6
- }>);
21
+ };
22
+ /**
23
+ * Where attempts are counted: this process's memory by default ({@link memoryThrottleCounts}), or a store the replicas
24
+ * share ({@link redisThrottleCounts}), so the eleventh failure is refused by whichever replica it reaches.
25
+ *
26
+ * `attempt` is ONE operation over every counter it is handed: each window read and, when none is full, the attempt
27
+ * recorded on all of them — atomically. A store that read and then wrote let a hundred attempts sent at once all read
28
+ * an empty window and all be let through.
29
+ */
30
+ export type ThrottleCounts = {
31
+ /** Refused, with when to come back, when any counter's window is full; else recorded on every one, at `now` (s). */
32
+ attempt: (counters: ThrottleCounter[], now: number) => Promise<ThrottleVerdict>;
33
+ /** It worked: each counter forgotten — a `spray` one gives back its latest attempt alone. */
34
+ succeeded: (counters: ThrottleCounter[]) => Promise<void>;
35
+ };
36
+ /** The counts in this process's memory: one replica's, or a fleet's primary's (`fleetRateLimit`). */
37
+ export declare const memoryThrottleCounts: () => ThrottleCounts;
38
+ /** What {@link redisThrottleCounts} asks of a Redis client: `EVAL`, as ioredis spells it. */
39
+ export type ThrottleRedis = {
40
+ eval: (script: string, numKeys: number, ...args: (string | number)[]) => Promise<unknown>;
41
+ };
42
+ /**
43
+ * The counts in a Redis every replica reaches, so the replicas hold one count between them. `prefix` names the keys —
44
+ * keep a `{hash tag}` in it on a Redis Cluster: a script's keys must share a slot.
45
+ */
46
+ export declare const redisThrottleCounts: (redis: ThrottleRedis, { prefix }?: {
47
+ prefix?: string;
48
+ }) => ThrottleCounts;
49
+ /**
50
+ * The rate limit a deployment gets: the policy — which counts an attempt is held to, and what a success gives back —
51
+ * over a store of counts, this process's memory unless it is handed one the replicas share.
52
+ */
53
+ export declare const createRateLimit: ({ counts, now }?: {
54
+ counts?: ThrottleCounts;
55
+ now?: () => number;
56
+ }) => ((attempt: CountedAttempt) => Promise<ThrottleVerdict>);
7
57
  type RateLimitStore = {
8
- check: ReturnType<typeof createMemoryRateLimit>;
58
+ check: ReturnType<typeof createRateLimit>;
9
59
  };
10
60
  /** Every method of the store, for the copy a fleet's workers share (`FleetStores`, `core/server/fleet/link.ts`). */
11
61
  export declare const RATE_LIMIT_METHODS: StoreMethods<RateLimitStore>;
12
62
  /**
13
- * In a worker of a fleet, the primary's {@link createMemoryRateLimit}, so an attacker spreading attempts over
63
+ * In a worker of a fleet, the primary's {@link createRateLimit} in memory, so an attacker spreading attempts over
14
64
  * connections meets one counter rather than one per worker. Nothing anywhere else.
15
65
  */
16
66
  export declare const fleetRateLimit: () => ((attempt: ThrottleAttempt) => Promise<{
@@ -8,7 +8,7 @@ export type { PipelineExtensions } from './http/pageContext';
8
8
  export type { ResolvedServices } from './services/resolve';
9
9
  /**
10
10
  * What a page server is not configured with: the actions engine's own configuration, which `createPlatform` builds the
11
- * engine from and hands the server (`engine`), or a worker runs elsewhere (RFC 0032, D12).
11
+ * engine from and hands the server (`engine`), or a worker runs elsewhere (docs/en/server-packages.md, D12).
12
12
  */
13
13
  declare const ENGINE_KEYS: readonly ["action", "functions", "connectors", "realtime"];
14
14
  export type ServerConfig = Omit<SSRServerConfig, 'adapters' | (typeof ENGINE_KEYS)[number]> & {
@@ -5,7 +5,7 @@ import { EngineOptions } from '@plitzi/sdk-actions/types';
5
5
  /** A page server and its actions engine in one process: the page server's configuration and the engine's. */
6
6
  export type PlatformConfig = Omit<ServerConfig, 'engine'> & EngineOptions;
7
7
  /**
8
- * Pages and actions in one process (RFC 0032, D11): the actions engine built from `action`, `functions`, `connectors`
8
+ * Pages and actions in one process (docs/en/server-packages.md, D11): the actions engine built from `action`, `functions`, `connectors`
9
9
  * and `realtime`, and handed to the page server `createServer` makes of the rest. What `yarn start`, a project's own
10
10
  * server and most self-hosted deployments run; a deployment whose actions run on a worker of their own uses
11
11
  * `createServer` for its pages.
@@ -0,0 +1,3 @@
1
+ import { SSRContext } from '../http/pageContext';
2
+ import { Stage } from '@plitzi/sdk-kernel/http';
3
+ export declare const iconFacesStage: Stage<SSRContext>;
@@ -0,0 +1,15 @@
1
+ import { SSRContext } from '../http/pageContext';
2
+ import { Stage } from '@plitzi/sdk-kernel/http';
3
+ import { Schema } from '@plitzi/sdk-shared';
4
+ export declare const LLMS_TXT_PATH = "/llms.txt";
5
+ /**
6
+ * The index an assistant reads (llmstxt.org): the site's name, the home page's description as its summary, and a link
7
+ * to each page the sitemap lists with its SEO title and description — the same words a search result shows.
8
+ */
9
+ export declare const llmsTxtOf: (schema: Schema, origin: string) => string;
10
+ /**
11
+ * `/llms.txt`: the space's own (`settings.llmsTxt`), or the one its pages make (`llmsTxtOf`). A space that keeps
12
+ * assistants out (`blockAiCrawlers: ['assistants']`) answers 404 — an index for them invites what it refuses. Never the
13
+ * space's page for that address, which an assistant would read as the index.
14
+ */
15
+ export declare const llmsTxtStage: Stage<SSRContext>;
@@ -3,14 +3,8 @@ import { Stage } from '@plitzi/sdk-kernel/http';
3
3
  /** What a space that says nothing answers: everything may be crawled. */
4
4
  export declare const DEFAULT_ROBOTS_TXT = "User-agent: *\nAllow: /\n";
5
5
  /**
6
- * The crawlers that gather pages to train AI models, by the user agent each reads `/robots.txt` as — what a space that
7
- * says `blockAiCrawlers` keeps out. A search engine's own crawler is none of them: Googlebot reads on, Google-Extended
8
- * (the one that trains) does not.
9
- */
10
- export declare const AI_CRAWLERS: readonly ["GPTBot", "ChatGPT-User", "OAI-SearchBot", "ClaudeBot", "anthropic-ai", "Google-Extended", "Applebot-Extended", "CCBot", "PerplexityBot", "Bytespider", "Amazonbot", "meta-externalagent"];
11
- /**
12
- * `/robots.txt`: the space's own (`settings.robotsTxt`) or one that lets crawlers read everything, then — when the space
13
- * keeps them out (`settings.blockAiCrawlers`) — a `Disallow: /` for each AI crawler, and the address of its sitemap
6
+ * `/robots.txt`: the space's own (`settings.robotsTxt`) or one that lets crawlers read everything, then a `Disallow: /`
7
+ * for each AI crawler of the kinds the space keeps out (`settings.blockAiCrawlers`), and the address of its sitemap
14
8
  * unless its own text names one. Never the space's page for an address it has none for: a crawler reads a 404 page as
15
9
  * "no rules", and an HTML page as rules it cannot parse.
16
10
  */
@@ -0,0 +1,10 @@
1
+ import { SSRContext } from '../http/pageContext';
2
+ import { Stage } from '@plitzi/sdk-kernel/http';
3
+ export declare const SECURITY_TXT_PATH = "/.well-known/security.txt";
4
+ /**
5
+ * `/.well-known/security.txt` (RFC 9116): the space's own words (`settings.securityTxt`), as plain text — where somebody
6
+ * who found a flaw writes, and until when that holds. A space that says nothing answers 404: a contact the site never
7
+ * gave would send a researcher's report nowhere. Never the space's page for that address, which a reader takes for the
8
+ * file.
9
+ */
10
+ export declare const securityTxtStage: Stage<SSRContext>;
package/dist/handlers.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as authRoutes, n as renewForNavigation, r as applySessionOutcome, t as isDocumentNavigation } from "./chunks/renewal-D98v6-Jd.js";
2
- import { a as handleRegister, b as protectedResourceMetadata, i as handleAuthorizeSubmit, l as sendErrorJson, n as handleToken, r as handleAuthorizeStart, t as handleRevoke, y as authorizationServerMetadata } from "./chunks/token-B2uY9JzU.js";
2
+ import { a as handleRegister, b as protectedResourceMetadata, i as handleAuthorizeSubmit, l as sendErrorJson, n as handleToken, r as handleAuthorizeStart, t as handleRevoke, y as authorizationServerMetadata } from "./chunks/token-CBUubxtm.js";
3
3
  import { serverLog } from "@plitzi/sdk-kernel/log";
4
4
  import { authFailureMessage, carrierOf, createAuthorizer, csrfFailureMessage } from "@plitzi/sdk-kernel/identity";
5
5
  // src/core/handlers/authRouteHandlers.ts
@@ -0,0 +1,10 @@
1
+ import { Schema } from '@plitzi/sdk-shared';
2
+ /**
3
+ * Whether this space is sent in parts: unless it asks for the whole (`settings.wholeDocument`), or has a single page —
4
+ * nothing to fetch later, so the shell would only be split for nothing.
5
+ */
6
+ export declare const sentInParts: (schema: Schema) => boolean;
7
+ /** The schema a page is sent with: the shell, that page's part and its layouts' — the same object for every visit. */
8
+ export declare const pageSchemaOf: (schema: Schema, withheld: readonly string[], pageId: string) => Schema;
9
+ /** A part's text by its name, for this group of visitors; none for a name their shell does not give. */
10
+ export declare const partTextOf: (schema: Schema, withheld: readonly string[], name: string) => string | undefined;
@@ -1,5 +1,6 @@
1
+ import { SSRPaintedDefaults } from '../types/config';
1
2
  import { SSRRequest } from '@plitzi/sdk-kernel/types';
2
- import { Schema } from '@plitzi/sdk-shared';
3
+ import { Environment, Schema } from '@plitzi/sdk-shared';
3
4
  /**
4
5
  * The name the painted state of a server-rendered page is kept under, for this request's host.
5
6
  *
@@ -19,3 +20,16 @@ export declare const requestPaintedState: (req: Pick<SSRRequest, "headers" | "ho
19
20
  keys: ReadonlySet<string>;
20
21
  state: Record<string, unknown> | undefined;
21
22
  };
23
+ type PaintedState = ReturnType<typeof requestPaintedState>;
24
+ /**
25
+ * `requestPaintedState` with the deployment's defaults (`paintedDefaults`) for the keys the cookie holds none of — for
26
+ * an account the request proved, never a guest: a guest's page is cached for every guest, and a default is an
27
+ * account's. Another account's entry holds nothing for this one (`paintedStateFor`), so after a change of account the
28
+ * defaults are this account's. A deployment that fails to answer is said in the log, and the page is drawn without.
29
+ */
30
+ export declare const requestPaintedStateWithDefaults: (req: Pick<SSRRequest, "headers" | "hostname">, settings: Pick<Schema["settings"], "keepState" | "paintedState" | "browserState"> | undefined, scope: {
31
+ spaceId: number;
32
+ environment: Environment;
33
+ account: number | string | undefined;
34
+ }, defaults: SSRPaintedDefaults | undefined) => Promise<PaintedState>;
35
+ export {};
package/dist/index.d.ts CHANGED
@@ -21,4 +21,4 @@ export type { PubSubAdapter, SSRRealtimeConfig } from '@plitzi/sdk-shared';
21
21
  export type { ResolvedServices, ServerConfig } from './core/createServer';
22
22
  export type { AuthoringHost, AuthoringHostConfig } from './hosts/authoringHost';
23
23
  export type { PipelineExtensions, SSRContext } from './core/http/pageContext';
24
- export type { CacheFilter, CacheManager, PluginRegistry, SSRCacheConfig, SSRFontsConfig, SSRImagesConfig, SSRPageServerConfig, SSRPlugin, SSRRenderLimitConfig, SSRRscConfig, SSRServer, SSRServerConfig, SSRSignInConfig, SSRTemplateFn, SSRVisitorCredentialsConfig, ServerServices, SharedPage, SharedPageFacts, SharedPageStore } from './types';
24
+ export type { CacheFilter, CacheManager, PluginRegistry, SSRCacheConfig, SSRFontsConfig, SSRImagesConfig, SSRPageServerConfig, SSRPaintedDefaults, SSRPaintedDefaultsContext, SSRPlugin, SSRRenderLimitConfig, SSRRscConfig, SSRServer, SSRServerConfig, SSRSignInConfig, SSRTemplateFn, SSRVisitorCredentialsConfig, ServerServices, SharedPage, SharedPageFacts, SharedPageStore } from './types';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { r as resolveRscData, t as createServer } from "./chunks/createServer-Bd_b7T3k.js";
2
- import { a as presentsCredential, c as wildcardSubdomain, d as createAuthAdapters, f as createJsonAdapters, i as fixedSpace, k as createCacheInvalidator, l as createMemoryCache, n as createSpaceAdapters, nt as DEFAULT_IGNORED_QUERY_PARAMS, o as renderGrant, p as createCloudAdapters, r as authoringPreview, s as verifiedDomain, t as createRedisPageStore, u as refuse } from "./chunks/core-TlrWmT4B.js";
3
- import { S as createMemoryDraftStore, b as resolveServices, w as takeDraftOverride } from "./chunks/buildBody-W9D8ySNY.js";
1
+ import { r as resolveRscData, t as createServer } from "./chunks/createServer-BQ0KE0Qu.js";
2
+ import { M as createCacheInvalidator, a as presentsCredential, at as DEFAULT_IGNORED_QUERY_PARAMS, c as wildcardSubdomain, d as createAuthAdapters, f as createJsonAdapters, i as fixedSpace, l as createMemoryCache, n as createSpaceAdapters, o as renderGrant, p as createCloudAdapters, r as authoringPreview, s as verifiedDomain, t as createRedisPageStore, u as refuse } from "./chunks/core-w7FIMpgv.js";
3
+ import { E as createMemoryDraftStore, O as takeDraftOverride, _ as resolveServices } from "./chunks/buildBody-BSC0UbjP.js";
4
4
  import path from "node:path";
5
5
  import { serverLog } from "@plitzi/sdk-kernel/log";
6
6
  import { isRecord } from "@plitzi/sdk-shared/helpers";
@@ -0,0 +1,21 @@
1
+ /** A face of the icon font, as the SDK's icon stylesheet declares it: the family, the weight and its file. */
2
+ export type IconFace = {
3
+ key: 'solid' | 'regular' | 'brands';
4
+ family: string;
5
+ weight: string;
6
+ file: string;
7
+ };
8
+ /** Every icon name the SDK's sheet draws, its glyph, and which names are the brands' face. */
9
+ export type IconGlyphs = {
10
+ codepoints: ReadonlyMap<string, number>;
11
+ brands: ReadonlySet<string>;
12
+ faces: IconFace[];
13
+ };
14
+ /**
15
+ * The SDK's icon stylesheet read for what it draws: each name's glyph, the faces and their files. The sheet is Font
16
+ * Awesome's sheets one after another (`apps/sdk`'s `iconsPlugin`), the brands' last: a name declared after the brands'
17
+ * face is a brand.
18
+ */
19
+ export declare const parseIconGlyphs: (css: string) => IconGlyphs;
20
+ /** The glyphs of the SDK installed at `sdkDir`, read once per process. */
21
+ export declare const iconGlyphsAt: (sdkDir: string) => IconGlyphs;