@blogmcp/sdk 0.8.1 → 0.9.1

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 (89) hide show
  1. package/dist/community/channels.d.ts +12 -0
  2. package/dist/community/channels.js +7 -0
  3. package/dist/community/client.d.ts +211 -0
  4. package/dist/community/client.js +188 -0
  5. package/dist/community/index.d.ts +34 -0
  6. package/dist/community/index.js +93 -0
  7. package/dist/community/links.d.ts +73 -0
  8. package/dist/community/links.js +85 -0
  9. package/dist/community/messages.cs.d.ts +331 -0
  10. package/dist/community/messages.cs.js +342 -0
  11. package/dist/community/messages.d.ts +40 -0
  12. package/dist/community/messages.en.d.ts +315 -0
  13. package/dist/community/messages.en.js +313 -0
  14. package/dist/community/messages.js +66 -0
  15. package/dist/community/outcome.d.ts +96 -0
  16. package/dist/community/outcome.js +211 -0
  17. package/dist/community/poll.d.ts +35 -0
  18. package/dist/community/poll.js +70 -0
  19. package/dist/community/routes.d.ts +110 -0
  20. package/dist/community/routes.js +66 -0
  21. package/dist/community/server/bff.d.ts +123 -0
  22. package/dist/community/server/bff.js +214 -0
  23. package/dist/community/server/env.d.ts +20 -0
  24. package/dist/community/server/env.js +16 -0
  25. package/dist/community/server/host-routes.d.ts +15 -0
  26. package/dist/community/server/host-routes.js +35 -0
  27. package/dist/community/server/http.d.ts +64 -0
  28. package/dist/community/server/http.js +90 -0
  29. package/dist/community/server/index.d.ts +45 -0
  30. package/dist/community/server/index.js +19 -0
  31. package/dist/community/server/route-decision.d.ts +70 -0
  32. package/dist/community/server/route-decision.js +89 -0
  33. package/dist/community/server/unknown-path.d.ts +21 -0
  34. package/dist/community/server/unknown-path.js +11 -0
  35. package/dist/community/shapes.d.ts +472 -0
  36. package/dist/community/shapes.js +63 -0
  37. package/dist/community/store.d.ts +183 -0
  38. package/dist/community/store.js +423 -0
  39. package/dist/community/transport.d.ts +42 -0
  40. package/dist/community/transport.js +59 -0
  41. package/dist/core/client.d.ts +17 -0
  42. package/dist/core/client.js +58 -55
  43. package/dist/core/comments-legacy.d.ts +19 -0
  44. package/dist/core/comments-legacy.js +18 -0
  45. package/dist/core/index.d.ts +3 -0
  46. package/dist/core/index.js +107 -101
  47. package/dist/core/queries.d.ts +46 -0
  48. package/dist/core/queries.js +128 -84
  49. package/dist/core/seo.js +40 -39
  50. package/dist/core/translations/cs.json.js +6 -6
  51. package/dist/core/translations/en.json.js +1 -1
  52. package/dist/core/types.d.ts +23 -1
  53. package/dist/core/view-model.d.ts +7 -0
  54. package/dist/core/view-model.js +29 -25
  55. package/dist/packages/tripmap-core/dist/generated/maplibre-worker.bundle.js +1 -1
  56. package/dist/react/KbMdxContent.js +4 -3
  57. package/dist/vue/components/KbMdxContent.vue2.js +3 -2
  58. package/dist/vue/composables/useKbComments.d.ts +8 -0
  59. package/package.json +13 -4
  60. package/src/community/channels.ts +12 -0
  61. package/src/community/client.ts +437 -0
  62. package/src/community/index.ts +192 -0
  63. package/src/community/links.ts +174 -0
  64. package/src/community/messages.cs.ts +371 -0
  65. package/src/community/messages.en.ts +341 -0
  66. package/src/community/messages.ts +112 -0
  67. package/src/community/outcome.ts +317 -0
  68. package/src/community/poll.ts +154 -0
  69. package/src/community/routes.ts +139 -0
  70. package/src/community/server/bff.ts +530 -0
  71. package/src/community/server/env.ts +42 -0
  72. package/src/community/server/host-routes.ts +48 -0
  73. package/src/community/server/http.ts +175 -0
  74. package/src/community/server/index.ts +55 -0
  75. package/src/community/server/route-decision.ts +226 -0
  76. package/src/community/server/unknown-path.ts +32 -0
  77. package/src/community/shapes.ts +541 -0
  78. package/src/community/store.ts +786 -0
  79. package/src/community/transport.ts +111 -0
  80. package/src/core/client.ts +24 -1
  81. package/src/core/comments-legacy.ts +39 -0
  82. package/src/core/index.ts +8 -0
  83. package/src/core/queries.ts +93 -0
  84. package/src/core/seo.ts +5 -1
  85. package/src/core/translations/cs.json +3 -1
  86. package/src/core/translations/en.json +3 -1
  87. package/src/core/types.ts +19 -1
  88. package/src/core/view-model.ts +12 -1
  89. package/src/vue/composables/useKbComments.ts +8 -0
@@ -0,0 +1,530 @@
1
+ /**
2
+ * `createCommunityBff` — the server half a headless site puts in front of kb-api's community routes
3
+ * (docs/internal/m1-contracts.md §10.3, §3.4; community.md §3.7, §7.1, invariant 3). The page's community client
4
+ * POSTs to the site's own `basePath` (`/api/community`); the BFF forwards kb-api's host routes (host-routes.ts)
5
+ * with the host's member token, or the site's notice key for a visitor without a session, and answers everything
6
+ * else itself.
7
+ *
8
+ * The notice key (`community:notice`) and every member token live in this closure only: each goes into the
9
+ * `Authorization` header of its own upstream call and nowhere else — never into an answer, a log line or an
10
+ * error. Server-only: the factory throws when a global `window` exists. Runtime-neutral otherwise (Web `fetch`,
11
+ * `URL`, `AbortSignal.timeout`, no `node:*`): Nitro on Bun or Node, Next, React Router, a worker.
12
+ *
13
+ * Every request, in this order; a step that refuses answers alone and nothing after it runs:
14
+ * 1. the method: POST only. Anything else gets kb-api's uniform unknown-path answer, as kb-api itself and the
15
+ * blogs' proxies answer it.
16
+ * 2. the path: `<basePath>/v1/public/…` names kb-api's `/community/v1/public/…`, `<basePath>/trust/v1/notices/…`
17
+ * its `/trust/v1/notices/…`; `communityRouteDecision` judges that path in every spelling. Anything but
18
+ * `allow` (outside the base or the namespaces, a closed surface, an unlisted route, a strange spelling) gets
19
+ * the unknown-path answer byte for byte, and kb-api is not asked.
20
+ * 3. the Origin: exactly one of the site URLs' origins, `Sec-Fetch-Site: same-origin` when sent (the
21
+ * consultations' `isAllowedOrigin`): else 403 ORIGIN. The host's session is not looked at before this.
22
+ * 4. the body (`http.json()`): JSON only, at most 64 KB, parsed to validate and forwarded as the raw bytes:
23
+ * else 413 TOO_LARGE or 400 INVALID_JSON.
24
+ * 5. the upstream call: `POST <kbApiUrl><route>` with `Authorization: Bearer <member token>` when the host has
25
+ * a session (`memberToken`); else `Bearer <notice key>` on every allowed route — public and notice — when the
26
+ * site configured one; else no `Authorization` (a notice route then answers 503: the form needs the key or a
27
+ * session). Besides it the visitor's IP in `X-Blogmcp-Client-Ip` (`clientIpFrom`) and `Content-Type` —
28
+ * nothing else, never a cookie; `redirect: 'error'` (a redirect would carry the credential elsewhere),
29
+ * `cache: 'no-store'`, a timeout.
30
+ *
31
+ * Why the notice key travels on anonymous public calls too: kb-api takes the forwarded IP only behind a credential
32
+ * it trusts for that (a delegated member token, the site's verified `community:notice` key; m1-contracts.md §7.2,
33
+ * §7.14 P-RV5). Without the key an anonymous call (a public read without a session) is counted on the site
34
+ * server's own IP, and every anonymous visitor of the site shares one bucket of kb-api's public limiter. The key
35
+ * authorises nothing there: outside the notice routes kb-api treats a request that carries it exactly as an
36
+ * anonymous one (a scoped key leaves the caller anonymous — a write or a `me/*` call still answers UNAUTHORIZED,
37
+ * which the page reads as "sign in"); it only lets kb-api count the visitor by their own IP. A 401 is therefore
38
+ * the key's refusal on a notice route only.
39
+ *
40
+ * kb-api's status and body pass through, with the BFF's own headers (`Cache-Control: private, no-store`,
41
+ * `Referrer-Policy: same-origin`, `X-Robots-Tag: noindex`, `X-Frame-Options: DENY`, nosniff, JSON) and kb-api's
42
+ * `Retry-After`. The BFF's own refusals are kb-api's envelope `{ ok: false, code, message }`. UNAVAILABLE (503)
43
+ * is everything the visitor cannot fix: no answer or one that is not kb-api's JSON object, an answer that quotes
44
+ * the call's own credential, the site's notice key missing or refused, a member token the host returned that
45
+ * cannot be one, anything unexpected — logged by operation, code and status only; `handle` never throws.
46
+ */
47
+
48
+ import { assertServerOnly } from '../../core/server-only'
49
+ import { DEFAULT_CLIENT_IP_HEADER, KB_CLIENT_IP_HEADER, clientIpFrom, isHeaderName } from '../../consultations/server/client-ip'
50
+ import { isAllowedOrigin, originOf, siteOrigins } from '../../consultations/server/origin'
51
+ import {
52
+ COMMUNITY_BODY_MAX_BYTES,
53
+ isBytes,
54
+ isJsonContentType,
55
+ parseCommunityJson,
56
+ type CommunityHttp,
57
+ type CommunityJsonBody,
58
+ type CommunityJsonRefusal,
59
+ type CommunityResponse,
60
+ } from './http'
61
+ import { communityRouteDecision } from './route-decision'
62
+ import { communityUnknownPath } from './unknown-path'
63
+
64
+ /**
65
+ * What the BFF tells its logger: an outage or the unexpected. Never a body, a name, a token or an address. A
66
+ * subtype of the client's log event, so the page's `CommunityLogger` serves both.
67
+ */
68
+ export interface CommunityBffLogEvent {
69
+ /** The operation (`messages/post`, `notices/submit`), or `bff` before one is known. */
70
+ op: string
71
+ /** The client's code for every outage the BFF logs. */
72
+ outcome: 'unavailable'
73
+ /** kb-api's code when its answer named one (a code shape, else `other`), else null. */
74
+ kbCode: string | null
75
+ /** kb-api's HTTP status, or null when there was no answer. */
76
+ status: number | null
77
+ }
78
+
79
+ export interface CommunityBffConfig {
80
+ /**
81
+ * The server-side kb-api base URL the routes are under: kb-api's own origin inside the cluster, or the instance's
82
+ * public address WITH the `/api` prefix it serves kb-api under (`https://tenant.example/api` — a bare
83
+ * `https://tenant.example` reaches the blog, not kb-api).
84
+ */
85
+ kbApiUrl: string
86
+ /** The site's own URLs: their origins are the Origin allowlist. */
87
+ siteUrls: string[]
88
+ /** Origins allowed to POST besides the site URLs' own. */
89
+ allowedOrigins?: string[]
90
+ /**
91
+ * The host's session → the member's token for kb-api (the bare JWT, no `Bearer `), or null without a session:
92
+ * the storefront's delegated identity, a native blog's own session. Called once per forwarded request, only
93
+ * after the path, the Origin and the body passed. Throwing, or a value that cannot be a token: UNAVAILABLE.
94
+ */
95
+ memberToken: (http: CommunityHttp) => Promise<string | null>
96
+ /**
97
+ * The site's `community:notice` key, sent for a visitor without a session on every allowed route. On the notice
98
+ * routes it is the anonymous notifier's credential; on the public routes it authorises nothing (kb-api treats
99
+ * the call as anonymous) and only lets kb-api's limiter count each visitor by the IP the BFF forwards, instead
100
+ * of every anonymous visitor of the site sharing the site server's one bucket. Missing: the notice routes are
101
+ * UNAVAILABLE without a session, and anonymous public calls share that bucket.
102
+ */
103
+ noticeKey?: string | null
104
+ /**
105
+ * Where the page's client sends its requests — its `base` (`createCommunityClient`), the elements' `api-base` —
106
+ * in the grammar the client takes (`isRelativeCommunityBase`): an absolute path of plain segments, `/` the root.
107
+ * Default `/api/community`.
108
+ */
109
+ basePath?: string
110
+ /**
111
+ * The edge header holding the visitor's IP. Default `cf-connecting-ip`; `''` = none (not behind Cloudflare). kb-api
112
+ * uses the forwarded IP behind a delegated member token or the site's notice key only (see the module doc) — so
113
+ * for anonymous visitors, only when `noticeKey` is configured.
114
+ */
115
+ clientIpHeader?: string
116
+ /**
117
+ * Per kb-api request, in milliseconds (default 10 000): 1 … 2 147 483 647, the range a timer keeps; a fraction is
118
+ * rounded down. Anything else is the default, warned once.
119
+ */
120
+ timeoutMs?: number
121
+ /** The fetch for upstream calls, resolved per call (a test spy or a framework-patched global fetch is honoured). */
122
+ fetch?: () => typeof fetch
123
+ /** The clock (an HTTP-date `Retry-After`). */
124
+ now?: () => number
125
+ /** Gets outages and the unexpected only (the client's `CommunityLogger` fits); default one `console.warn` line. */
126
+ logger?: (e: CommunityBffLogEvent) => void
127
+ }
128
+
129
+ export interface CommunityBff {
130
+ /** One request of the page's client: its answer, never a throw. */
131
+ handle(http: CommunityHttp): Promise<CommunityResponse>
132
+ }
133
+
134
+ /** The BFF's own refusals (kb-api's envelope); the client maps them like kb-api's codes. */
135
+ export type CommunityBffCode = 'ORIGIN' | 'TOO_LARGE' | 'INVALID_JSON' | 'UNAVAILABLE'
136
+
137
+ /** Each refusal's status and its one fixed message (English, constant, nothing of the request). */
138
+ export const COMMUNITY_BFF_REFUSALS: Readonly<Record<CommunityBffCode, { readonly status: number; readonly message: string }>> =
139
+ Object.freeze({
140
+ ORIGIN: Object.freeze({ status: 403, message: 'This request did not come from the site' }),
141
+ TOO_LARGE: Object.freeze({ status: 413, message: 'The request body is too large' }),
142
+ INVALID_JSON: Object.freeze({ status: 400, message: 'The request body must be a JSON object' }),
143
+ // kb-api's own message for its UNAVAILABLE.
144
+ UNAVAILABLE: Object.freeze({ status: 503, message: 'Temporarily unavailable' }),
145
+ })
146
+
147
+ /** Headers of every answer the BFF gives or passes through (the unknown-path answer aside: it is kb-api's). */
148
+ const RESPONSE_HEADERS: Readonly<Record<string, string>> = Object.freeze({
149
+ 'Content-Type': 'application/json; charset=utf-8',
150
+ 'Cache-Control': 'private, no-store',
151
+ 'Referrer-Policy': 'same-origin',
152
+ 'X-Robots-Tag': 'noindex',
153
+ 'X-Frame-Options': 'DENY',
154
+ 'X-Content-Type-Options': 'nosniff',
155
+ })
156
+
157
+ export const DEFAULT_COMMUNITY_BASE_PATH = '/api/community'
158
+ const DEFAULT_TIMEOUT_MS = 10_000
159
+ /**
160
+ * The longest delay a timer keeps (a signed 32-bit one): past it Node's `AbortSignal.timeout` fires after 1 ms, and
161
+ * past 2^32 − 1 it throws, as it does on a fraction.
162
+ */
163
+ const TIMEOUT_MAX_MS = 2_147_483_647
164
+
165
+ /** A key or token that is safe as an HTTP header value (visible ASCII, no whitespace). */
166
+ const HEADER_TOKEN_RE = /^[\x21-\x7E]+$/
167
+ /** Longer than any token kb-api issues; past it the value is the host's bug, not a token. */
168
+ const TOKEN_MAX = 8192
169
+ /**
170
+ * A base path as the client takes it (its transport's BASE_RE): segments of unreserved characters, none starting
171
+ * with a dot, one trailing slash at most — so the prefix test reads it exactly.
172
+ */
173
+ const BASE_PATH_RE = /^(?:\/[A-Za-z0-9_~-][A-Za-z0-9._~-]*)*\/?$/
174
+ /** A kb-api code as it may appear in a log line; anything else is `other`. */
175
+ const LOGGABLE_CODE_RE = /^[A-Z][A-Z0-9_]{0,63}$/
176
+
177
+ const NOTICE_ROUTE_PREFIX = '/trust/v1/notices/'
178
+
179
+ // ───────────────────────── configuration ─────────────────────────
180
+
181
+ /**
182
+ * `basePath` without its trailing slash (`''` for the root), or a TypeError: a base the prefix test could misread
183
+ * is a programming error.
184
+ */
185
+ function basePathOf(value: unknown): string {
186
+ if (value === undefined) return DEFAULT_COMMUNITY_BASE_PATH
187
+ if (typeof value !== 'string' || !value.startsWith('/') || !BASE_PATH_RE.test(value)) {
188
+ throw new TypeError(
189
+ '[blogmcp-sdk] createCommunityBff basePath must be an absolute path of plain segments, like /api/community',
190
+ )
191
+ }
192
+ return value.replace(/\/$/, '')
193
+ }
194
+
195
+ /** kb-api's base URL without a trailing slash, or null when it is not an absolute http(s) URL without a query. */
196
+ function upstreamBase(value: unknown): string | null {
197
+ if (typeof value !== 'string' || value.trim() === '') return null
198
+ try {
199
+ const url = new URL(value.trim())
200
+ if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.search || url.hash) return null
201
+ return url.origin + url.pathname.replace(/\/+$/, '')
202
+ } catch {
203
+ return null
204
+ }
205
+ }
206
+
207
+ /** A key from config: trimmed (secret files end in a newline), null when empty or not header-safe. */
208
+ function keyOf(value: unknown, warnOnce: (key: string, message: string) => void): string | null {
209
+ if (typeof value !== 'string') return null
210
+ const key = value.trim()
211
+ if (key === '') return null
212
+ if (!HEADER_TOKEN_RE.test(key) || key.length > TOKEN_MAX) {
213
+ // Never echo the key.
214
+ warnOnce('notice_key_invalid', '[community] the notice key contains characters not allowed in an HTTP header — ignored.')
215
+ return null
216
+ }
217
+ return key
218
+ }
219
+
220
+ /**
221
+ * The upstream timeout in whole milliseconds a timer keeps (a fraction rounded down). A value outside that range
222
+ * would make every request an outage that looks like kb-api's, so it is the default instead, warned once.
223
+ */
224
+ function timeoutOf(value: unknown, warnOnce: (key: string, message: string) => void): number {
225
+ if (value === undefined) return DEFAULT_TIMEOUT_MS
226
+ const ms = typeof value === 'number' ? Math.floor(value) : Number.NaN
227
+ if (ms >= 1 && ms <= TIMEOUT_MAX_MS) return ms
228
+ warnOnce('timeout_ms', '[community] timeoutMs is not a number of milliseconds from 1 to 2147483647 — the default 10 s is used.')
229
+ return DEFAULT_TIMEOUT_MS
230
+ }
231
+
232
+ /** One line per outage, of codes and integers only; a logger that throws never breaks a request. */
233
+ function hygienicLogger(logger: (e: CommunityBffLogEvent) => void): (e: CommunityBffLogEvent) => void {
234
+ return (e) => {
235
+ const kbCode = typeof e.kbCode === 'string' ? (LOGGABLE_CODE_RE.test(e.kbCode) ? e.kbCode : 'other') : null
236
+ const status = typeof e.status === 'number' && Number.isInteger(e.status) ? e.status : null
237
+ try {
238
+ logger({ op: String(e.op).replace(/[^A-Za-z0-9_./-]/g, '').slice(0, 64), outcome: e.outcome, kbCode, status })
239
+ } catch {
240
+ // A logger that throws must not turn a handled failure into an unhandled one.
241
+ }
242
+ }
243
+ }
244
+
245
+ const defaultLogger = (e: CommunityBffLogEvent): void => {
246
+ console.warn(`[community] op=${e.op} outcome=${e.outcome} kb_code=${e.kbCode ?? 'none'} status=${e.status ?? 'none'}`)
247
+ }
248
+
249
+ // ───────────────────────── requests ─────────────────────────
250
+
251
+ /**
252
+ * The kb-api path a request names (see step 2 of the module doc), or null when it is not under `basePath`. Pure
253
+ * prefix work on the raw path: every spelling is left for the decision to judge.
254
+ */
255
+ function kbPathOf(basePath: string, path: unknown): string | null {
256
+ if (typeof path !== 'string') return null
257
+ const cut = path.search(/[?#]/)
258
+ const pathname = cut === -1 ? path : path.slice(0, cut)
259
+ if (!pathname.startsWith(`${basePath}/`)) return null
260
+ const rest = pathname.slice(basePath.length)
261
+ return rest.startsWith('/trust/') ? rest : `/community${rest}`
262
+ }
263
+
264
+ /** The operation of a host route, for log lines: `discussions/list`, `notices/submit`. */
265
+ function operationOf(upstreamPath: string): string {
266
+ return upstreamPath.replace(/^\/community\/v1\/public\//, '').replace(/^\/trust\/v1\//, '')
267
+ }
268
+
269
+ /** A kb-api answer's body as the object it must be — every answer of these routes is one — or null. */
270
+ function answerOf(text: string): Record<string, unknown> | null {
271
+ try {
272
+ const body: unknown = JSON.parse(text)
273
+ return typeof body === 'object' && body !== null && !Array.isArray(body) ? (body as Record<string, unknown>) : null
274
+ } catch {
275
+ return null
276
+ }
277
+ }
278
+
279
+ /** The code an answer names (for a log line), or null. */
280
+ function codeOf(answer: Record<string, unknown>): string | null {
281
+ return typeof answer.code === 'string' ? answer.code : null
282
+ }
283
+
284
+ /** kb-api's `Retry-After` in seconds (delta-seconds, or an HTTP date), or null when it sent none it could mean. */
285
+ function retryAfterOf(headers: Pick<Headers, 'get'>, now: number): number | null {
286
+ const value = headers.get('retry-after')?.trim()
287
+ if (!value) return null
288
+ if (/^\d{1,9}$/.test(value)) return Number(value)
289
+ const at = Date.parse(value)
290
+ return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - now) / 1000))
291
+ }
292
+
293
+ function respond(status: number, body: string, extra: Record<string, string> = {}): CommunityResponse {
294
+ return { status, headers: { ...RESPONSE_HEADERS, ...extra }, body }
295
+ }
296
+
297
+ /** One of the BFF's own refusals, in kb-api's envelope. */
298
+ function refusal(code: CommunityBffCode): CommunityResponse {
299
+ const { status, message } = COMMUNITY_BFF_REFUSALS[code]
300
+ return respond(status, JSON.stringify({ ok: false, code, message }))
301
+ }
302
+
303
+ /** `notice`: the site's notice key — on a public route kb-api reads the call as anonymous (see the module doc). */
304
+ type Credential =
305
+ | { kind: 'member' | 'notice'; token: string }
306
+ | { kind: 'anonymous' }
307
+ /** The visitor can do nothing about it: logged and answered UNAVAILABLE. */
308
+ | { kind: 'unavailable' }
309
+
310
+ // ───────────────────────── the BFF ─────────────────────────
311
+
312
+ export function createCommunityBff(c: CommunityBffConfig): CommunityBff {
313
+ assertServerOnly(
314
+ 'createCommunityBff',
315
+ "it holds the site's community notice key and its members' tokens, which must never reach the browser.",
316
+ )
317
+ const config = c ?? ({} as CommunityBffConfig)
318
+ if (typeof config.memberToken !== 'function') {
319
+ throw new TypeError('[blogmcp-sdk] createCommunityBff needs memberToken: (http) => Promise<string | null>')
320
+ }
321
+ const basePath = basePathOf(config.basePath)
322
+
323
+ const warned = new Set<string>()
324
+ const warnOnce = (key: string, message: string): void => {
325
+ if (warned.has(key)) return
326
+ warned.add(key)
327
+ console.warn(message)
328
+ }
329
+
330
+ const base = upstreamBase(config.kbApiUrl)
331
+ if (base === null) {
332
+ warnOnce('kb_api_url', '[community] kbApiUrl is not an absolute http(s) URL — every community request answers 503.')
333
+ }
334
+
335
+ const extras = Array.isArray(config.allowedOrigins) ? config.allowedOrigins : []
336
+ if (extras.some((o) => originOf(o) === null)) {
337
+ warnOnce('allowed_origins', '[community] an allowedOrigins entry is not an http(s) URL — ignored.')
338
+ }
339
+ const origins = siteOrigins(Array.isArray(config.siteUrls) ? config.siteUrls : [], extras)
340
+ if (origins.length === 0) {
341
+ warnOnce('site_urls', '[community] no usable siteUrls — every community request is refused (ORIGIN).')
342
+ }
343
+
344
+ let clientIpHeader = typeof config.clientIpHeader === 'string' ? config.clientIpHeader.trim() : DEFAULT_CLIENT_IP_HEADER
345
+ if (clientIpHeader !== '' && !isHeaderName(clientIpHeader)) {
346
+ warnOnce('client_ip_header', '[community] clientIpHeader is not an HTTP header name — no edge header is read.')
347
+ clientIpHeader = ''
348
+ }
349
+
350
+ const noticeKey = keyOf(config.noticeKey, warnOnce)
351
+ const timeoutMs = timeoutOf(config.timeoutMs, warnOnce)
352
+ const now = typeof config.now === 'function' ? config.now : Date.now
353
+ const fetchFn = (): typeof fetch => (typeof config.fetch === 'function' ? config.fetch() : globalThis.fetch)
354
+ const configured = config.logger
355
+ const log = hygienicLogger(typeof configured === 'function' ? (e) => configured.call(config, e) : defaultLogger)
356
+ const memberToken = config.memberToken
357
+
358
+ /** An outage of one request: logged, answered UNAVAILABLE. */
359
+ const unavailable = (op: string, kbCode: string | null = null, status: number | null = null): CommunityResponse => {
360
+ log({ op, outcome: 'unavailable', kbCode, status })
361
+ return refusal('UNAVAILABLE')
362
+ }
363
+
364
+ /**
365
+ * The bytes the BFF forwards: its own copy of what the adapter's `json()` read, judged again by the same rules —
366
+ * what was checked is what leaves, whatever the adapter. Null: the adapter has no `json()`.
367
+ */
368
+ async function bodyOf(
369
+ http: CommunityHttp,
370
+ ): Promise<{ ok: true; bytes: Uint8Array<ArrayBuffer> } | { ok: false; code: CommunityJsonRefusal } | null> {
371
+ if (typeof http.json !== 'function') {
372
+ warnOnce(
373
+ 'json_missing',
374
+ "[community] the request adapter has no json() — use the community server's fromWebRequest or add it.",
375
+ )
376
+ return null
377
+ }
378
+ let body: CommunityJsonBody
379
+ try {
380
+ body = await http.json()
381
+ } catch {
382
+ return { ok: false, code: 'INVALID_JSON' }
383
+ }
384
+ if (!body || typeof body !== 'object' || body.ok !== true) {
385
+ const tooLarge = !!body && typeof body === 'object' && body.ok === false && body.code === 'TOO_LARGE'
386
+ return { ok: false, code: tooLarge ? 'TOO_LARGE' : 'INVALID_JSON' }
387
+ }
388
+ if (!isBytes(body.bytes)) return { ok: false, code: 'INVALID_JSON' }
389
+ if (body.bytes.byteLength > COMMUNITY_BODY_MAX_BYTES) return { ok: false, code: 'TOO_LARGE' }
390
+ const own = new Uint8Array(body.bytes)
391
+ const verdict = parseCommunityJson(http.header('content-type'), own)
392
+ return verdict.ok ? { ok: true, bytes: own } : verdict
393
+ }
394
+
395
+ /**
396
+ * Whose call this is: the member when the host has a session; else the site's notice key on every route when it
397
+ * is configured; else nobody — or, on a notice route without either, nothing the BFF can send.
398
+ */
399
+ async function credentialOf(http: CommunityHttp, noticeRoute: boolean): Promise<Credential> {
400
+ const token: unknown = await memberToken(http)
401
+ if (token !== null && token !== undefined && token !== '') {
402
+ if (typeof token === 'string' && HEADER_TOKEN_RE.test(token) && token.length <= TOKEN_MAX) {
403
+ return { kind: 'member', token }
404
+ }
405
+ warnOnce(
406
+ 'member_token_invalid',
407
+ '[community] memberToken returned something that is not a token (the bare JWT, visible ASCII, no "Bearer ") — answered 503.',
408
+ )
409
+ return { kind: 'unavailable' }
410
+ }
411
+ if (noticeKey) return { kind: 'notice', token: noticeKey }
412
+ if (!noticeRoute) return { kind: 'anonymous' }
413
+ warnOnce(
414
+ 'notice_key',
415
+ '[community] no notice key (COMMUNITY_NOTICE_KEY) — the notice form works only for signed-in members.',
416
+ )
417
+ return { kind: 'unavailable' }
418
+ }
419
+
420
+ /** Step 5: the upstream call and its answer. */
421
+ async function forward(
422
+ op: string,
423
+ upstreamPath: string,
424
+ bytes: Uint8Array<ArrayBuffer>,
425
+ credential: { kind: 'member' | 'notice'; token: string } | { kind: 'anonymous' },
426
+ noticeRoute: boolean,
427
+ clientIp: string | null,
428
+ ): Promise<CommunityResponse> {
429
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' }
430
+ if (credential.kind !== 'anonymous') headers.Authorization = `Bearer ${credential.token}`
431
+ if (clientIp) headers[KB_CLIENT_IP_HEADER] = clientIp
432
+ let res: Response
433
+ try {
434
+ res = await fetchFn()(`${base}${upstreamPath}`, {
435
+ method: 'POST',
436
+ headers,
437
+ body: bytes,
438
+ redirect: 'error',
439
+ cache: 'no-store',
440
+ signal: AbortSignal.timeout(timeoutMs),
441
+ })
442
+ } catch {
443
+ // The cause is dropped on purpose: a fetch header error quotes the header's value (a key, a token).
444
+ return unavailable(op)
445
+ }
446
+ let text: string
447
+ try {
448
+ text = await res.text()
449
+ } catch {
450
+ return unavailable(op, null, res.status)
451
+ }
452
+ // kb-api answers a JSON object on every one of these routes; anything else came from something in between
453
+ // (a gateway's error page, a truncated body) and is not passed on.
454
+ const answer = isJsonContentType(res.headers.get('content-type')) ? answerOf(text) : null
455
+ if (answer === null) return unavailable(op, null, res.status)
456
+ // A member token lives on the site's server only, the notice key too: an answer that quotes the one this call
457
+ // carried (a kb-api bug) never reaches the browser.
458
+ if (credential.kind !== 'anonymous' && text.includes(credential.token)) {
459
+ warnOnce('credential_echo', "[community] kb-api's answer quoted the request's credential — not passed on (503).")
460
+ return unavailable(op, null, res.status)
461
+ }
462
+ // The visitor cannot fix the site's own key: an outage, never "sign in". Only a notice route's 401 is the key's
463
+ // refusal — on a public route kb-api reads the key as anonymous, and its 401 is the visitor's "sign in".
464
+ if (res.status === 401 && credential.kind === 'notice' && noticeRoute) {
465
+ warnOnce(
466
+ 'notice_key_refused',
467
+ '[community] kb-api refused the notice key — check COMMUNITY_NOTICE_KEY (scope community:notice).',
468
+ )
469
+ return unavailable(op, codeOf(answer), res.status)
470
+ }
471
+ if (res.status >= 500) log({ op, outcome: 'unavailable', kbCode: codeOf(answer), status: res.status })
472
+ const retryAfter = retryAfterOf(res.headers, now())
473
+ return respond(res.status, text, retryAfter === null ? {} : { 'Retry-After': String(retryAfter) })
474
+ }
475
+
476
+ async function serve(http: CommunityHttp, request: { op: string }): Promise<CommunityResponse> {
477
+ // 1. The method.
478
+ const method = typeof http.method === 'string' ? http.method.toUpperCase() : ''
479
+ if (method !== 'POST') return communityUnknownPath()
480
+
481
+ // 2. The path: only a listed route in its canonical spelling, never a closed surface.
482
+ const kbPath = kbPathOf(basePath, http.path)
483
+ const decision = kbPath === null ? null : communityRouteDecision('POST', kbPath)
484
+ if (decision?.kind !== 'allow') return communityUnknownPath()
485
+ request.op = operationOf(decision.upstreamPath)
486
+
487
+ // 3. The Origin, before the host's session is looked at.
488
+ if (!isAllowedOrigin(http, origins)) {
489
+ warnOnce(
490
+ 'origin',
491
+ '[community] a request was refused for its Origin (not one of siteUrls / allowedOrigins, or not same-origin) — ' +
492
+ "if the site's own pages are refused, check siteUrls.",
493
+ )
494
+ return refusal('ORIGIN')
495
+ }
496
+
497
+ // 4. The body.
498
+ const body = await bodyOf(http)
499
+ if (body === null) return unavailable(request.op)
500
+ if (!body.ok) return refusal(body.code)
501
+
502
+ // 5. The upstream call.
503
+ if (base === null) return unavailable(request.op)
504
+ const noticeRoute = decision.upstreamPath.startsWith(NOTICE_ROUTE_PREFIX)
505
+ const credential = await credentialOf(http, noticeRoute)
506
+ if (credential.kind === 'unavailable') return unavailable(request.op)
507
+ const clientIp = clientIpFrom(http, { header: clientIpHeader })
508
+ if (clientIp === null) {
509
+ warnOnce(
510
+ 'client_ip',
511
+ '[community] a request without a client IP (no valid edge header or X-Forwarded-For) — check clientIpHeader ' +
512
+ 'and the reverse-proxy configuration. kb-api counts a visitor by a forwarded IP only behind a delegated ' +
513
+ "member token or the site's notice key; without one the call is counted on the site server's own IP.",
514
+ )
515
+ }
516
+ return forward(request.op, decision.upstreamPath, body.bytes, credential, noticeRoute, clientIp)
517
+ }
518
+
519
+ return {
520
+ async handle(http: CommunityHttp): Promise<CommunityResponse> {
521
+ const request = { op: 'bff' }
522
+ try {
523
+ return await serve(http, request)
524
+ } catch {
525
+ // An adapter or a memberToken that throws, or a bug: an outage, never a throw (nothing of the error is logged).
526
+ return unavailable(request.op)
527
+ }
528
+ },
529
+ }
530
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The community BFF's key from the environment (docs/internal/m1-contracts.md §10.3, Appendix A) — one name for
3
+ * every headless host:
4
+ *
5
+ * {prefix}COMMUNITY_NOTICE_KEY the site's `community:notice` key: the notice form for a visitor without a session
6
+ *
7
+ * `prefix` is `''` for Next, React Router and a plain server, `'NUXT_'` for Nuxt (whose runtime config reads
8
+ * `NUXT_*`). The managed blogs read their own `KB_COMMUNITY_NOTICE_KEY`, which the platform provisions.
9
+ *
10
+ * A key is never PUBLIC: a variable in a namespace a framework bundles into page JavaScript —
11
+ * `NEXT_PUBLIC_COMMUNITY_*`, `NUXT_PUBLIC_COMMUNITY_*`, `PUBLIC_COMMUNITY_*` (SvelteKit, Astro), `VITE_COMMUNITY_*` —
12
+ * throws by its mere presence, whatever the prefix and before anything reads it. The message names the variable,
13
+ * never its value. (The Turnstile site key is public page config; name it outside these namespaces.)
14
+ */
15
+
16
+ import type { CommunityBffConfig } from './bff'
17
+
18
+ const PUBLIC_PREFIXES = ['NEXT_PUBLIC_COMMUNITY_', 'NUXT_PUBLIC_COMMUNITY_', 'PUBLIC_COMMUNITY_', 'VITE_COMMUNITY_'] as const
19
+
20
+ /** What the environment configures of `createCommunityBff`. */
21
+ export type CommunityServerEnv = Required<Pick<CommunityBffConfig, 'noticeKey'>>
22
+
23
+ export function communityServerEnv(
24
+ env: Record<string, string | undefined>,
25
+ o: { prefix?: '' | 'NUXT_' } = {},
26
+ ): CommunityServerEnv {
27
+ const vars = env ?? {}
28
+ for (const name of Object.keys(vars)) {
29
+ const v = vars[name]
30
+ if (typeof v === 'string' && v !== '' && PUBLIC_PREFIXES.some((p) => name.startsWith(p))) {
31
+ // The name only — never the value.
32
+ throw new Error(
33
+ `[blogmcp-sdk] ${name} is set — community keys are never PUBLIC (a public variable ends up in page ` +
34
+ 'JavaScript). Rename it without the public prefix and rotate the key.',
35
+ )
36
+ }
37
+ }
38
+ const p = o.prefix === 'NUXT_' ? 'NUXT_' : ''
39
+ const key = vars[`${p}COMMUNITY_NOTICE_KEY`]
40
+ const noticeKey = typeof key === 'string' ? key.trim() : ''
41
+ return { noticeKey: noticeKey === '' ? null : noticeKey }
42
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The host-session routes (docs/internal/m1-contracts.md §7.1, §10.3): every kb-api operation a managed blog's
3
+ * proxy or a headless site's BFF may forward for a host session — the public operations of Comments 2.0 and the
4
+ * notice form. One operation, one literal path, POST only; ids travel in the JSON body, never in the path.
5
+ *
6
+ * A copy of kb-api's `apps/knowledge-base/api/src/routes/community-public-routes.json`, which kb-api generates from
7
+ * its sealed routers. test/community/server/host-routes-drift.spec.ts reads that file as text and fails when the
8
+ * two differ, so a route kb-api adds or removes is a change here too: a route missing from this list answers the
9
+ * unknown path through every host, a stale one would forward to a path kb-api no longer serves. The team, adapter
10
+ * and platform surfaces are never in it (the team is not a host session; the others call kb-api themselves), nor
11
+ * is either closed surface — route-decision.ts refuses those whatever this list says.
12
+ */
13
+
14
+ import type { CommunityHostRoute } from './route-decision'
15
+
16
+ /** kb-api's allowlist, sorted by path as kb-api writes it. Frozen, every entry too. */
17
+ export const COMMUNITY_HOST_ROUTES: readonly CommunityHostRoute[] = Object.freeze([
18
+ Object.freeze({ method: 'POST', path: '/community/v1/public/blocks/list' }),
19
+ Object.freeze({ method: 'POST', path: '/community/v1/public/blocks/set' }),
20
+ Object.freeze({ method: 'POST', path: '/community/v1/public/discussions/head' }),
21
+ Object.freeze({ method: 'POST', path: '/community/v1/public/discussions/list' }),
22
+ Object.freeze({ method: 'POST', path: '/community/v1/public/legal/current' }),
23
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/appeals/file' }),
24
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/appeals/list' }),
25
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/appeals/withdraw' }),
26
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/consents/withdraw' }),
27
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/decisions/get' }),
28
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/decisions/list' }),
29
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/erase' }),
30
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/erase/cancel' }),
31
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/export' }),
32
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/get' }),
33
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/notifications/list' }),
34
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/notifications/mark-read' }),
35
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/onboard' }),
36
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/profile/update' }),
37
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/reports/list' }),
38
+ Object.freeze({ method: 'POST', path: '/community/v1/public/messages/delete' }),
39
+ Object.freeze({ method: 'POST', path: '/community/v1/public/messages/edit' }),
40
+ Object.freeze({ method: 'POST', path: '/community/v1/public/messages/post' }),
41
+ Object.freeze({ method: 'POST', path: '/community/v1/public/messages/report' }),
42
+ Object.freeze({ method: 'POST', path: '/community/v1/public/profile/get' }),
43
+ Object.freeze({ method: 'POST', path: '/community/v1/public/reactions/set' }),
44
+ Object.freeze({ method: 'POST', path: '/trust/v1/notices/appeal' }),
45
+ Object.freeze({ method: 'POST', path: '/trust/v1/notices/appeal/withdraw' }),
46
+ Object.freeze({ method: 'POST', path: '/trust/v1/notices/status' }),
47
+ Object.freeze({ method: 'POST', path: '/trust/v1/notices/submit' }),
48
+ ] as const)