@blogmcp/sdk 0.8.1 → 0.9.0

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 (88) 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 +92 -0
  7. package/dist/community/links.d.ts +65 -0
  8. package/dist/community/links.js +81 -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 +457 -0
  36. package/dist/community/shapes.js +51 -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/react/KbMdxContent.js +4 -3
  56. package/dist/vue/components/KbMdxContent.vue2.js +3 -2
  57. package/dist/vue/composables/useKbComments.d.ts +8 -0
  58. package/package.json +13 -4
  59. package/src/community/channels.ts +12 -0
  60. package/src/community/client.ts +437 -0
  61. package/src/community/index.ts +190 -0
  62. package/src/community/links.ts +166 -0
  63. package/src/community/messages.cs.ts +371 -0
  64. package/src/community/messages.en.ts +341 -0
  65. package/src/community/messages.ts +112 -0
  66. package/src/community/outcome.ts +317 -0
  67. package/src/community/poll.ts +154 -0
  68. package/src/community/routes.ts +139 -0
  69. package/src/community/server/bff.ts +530 -0
  70. package/src/community/server/env.ts +42 -0
  71. package/src/community/server/host-routes.ts +48 -0
  72. package/src/community/server/http.ts +175 -0
  73. package/src/community/server/index.ts +55 -0
  74. package/src/community/server/route-decision.ts +226 -0
  75. package/src/community/server/unknown-path.ts +32 -0
  76. package/src/community/shapes.ts +513 -0
  77. package/src/community/store.ts +786 -0
  78. package/src/community/transport.ts +111 -0
  79. package/src/core/client.ts +24 -1
  80. package/src/core/comments-legacy.ts +39 -0
  81. package/src/core/index.ts +8 -0
  82. package/src/core/queries.ts +93 -0
  83. package/src/core/seo.ts +5 -1
  84. package/src/core/translations/cs.json +3 -1
  85. package/src/core/translations/en.json +3 -1
  86. package/src/core/types.ts +19 -1
  87. package/src/core/view-model.ts +12 -1
  88. package/src/vue/composables/useKbComments.ts +8 -0
@@ -0,0 +1,175 @@
1
+ /**
2
+ * The request/response seam between the community BFF and a framework (docs/internal/m1-contracts.md §10.3): the
3
+ * consultations' `ConsultationHttp` plus the request's path and its JSON body. `fromWebRequest` is the ready-made
4
+ * adapter for anything that speaks Web `Request`/`Response` (Next route handlers, React Router resource routes,
5
+ * Nitro's `toWebRequest`, workers); another framework writes its own in a few lines (the kit's `h3Http`) and
6
+ * reads the body through `parseCommunityJson`, so every adapter answers the same.
7
+ *
8
+ * Composed on the consultations' seam (src/consultations/server/http.ts), not copied: `method`, `header`,
9
+ * `cookie` (the host's own session, which `memberToken` reads), `setCookie` and `form` are its. The BFF reads no
10
+ * cookie and forwards none.
11
+ *
12
+ * The JSON body: `application/json` only (a charset, when named, is UTF-8), at most 64 KB — kb-api's own limit for
13
+ * these routes, so whatever passes here passes there — read no further than that, valid UTF-8 that parses to a
14
+ * JSON object (every operation's body is one). The bytes come back exactly as received: the BFF forwards them as
15
+ * they are, never re-serialised.
16
+ */
17
+
18
+ import {
19
+ fromWebRequest as consultationFromWebRequest,
20
+ type ConsultationHttp,
21
+ type ConsultationResponse,
22
+ } from '../../consultations/server/http'
23
+
24
+ /** The largest JSON body in bytes: kb-api's `express.json({ limit: '64kb' })` on every community router. */
25
+ export const COMMUNITY_BODY_MAX_BYTES = 65_536
26
+
27
+ /** Why a request has no JSON body the BFF forwards. */
28
+ export type CommunityJsonRefusal = 'TOO_LARGE' | 'INVALID_JSON'
29
+
30
+ export type CommunityJsonBody =
31
+ /** `bytes` exactly as received (what the BFF forwards); `value` is what they parse to. */
32
+ | { ok: true; bytes: Uint8Array; value: Record<string, unknown> }
33
+ | { ok: false; code: CommunityJsonRefusal }
34
+
35
+ export interface CommunityHttp extends ConsultationHttp {
36
+ /**
37
+ * The request's URL path as received — still percent-encoded, e.g. `/api/community/v1/public/me/get`. A query
38
+ * or fragment is ignored; the BFF judges every spelling of what is left.
39
+ */
40
+ path: string
41
+ /**
42
+ * The JSON body (see the module doc), read once: every call answers the same. An adapter MUST enforce what
43
+ * `fromWebRequest` enforces — `parseCommunityJson` over at most COMMUNITY_BODY_MAX_BYTES, reading stopped past
44
+ * them. `form()` reads the same body: an adapter serves one of them per request.
45
+ */
46
+ json(): Promise<CommunityJsonBody>
47
+ }
48
+
49
+ /** What the BFF answers: the status, every header, and the body as text (JSON; a HEAD answer sends none). */
50
+ export type CommunityResponse = ConsultationResponse<string>
51
+
52
+ const TOO_LARGE: CommunityJsonBody = Object.freeze({ ok: false, code: 'TOO_LARGE' })
53
+ const INVALID_JSON: CommunityJsonBody = Object.freeze({ ok: false, code: 'INVALID_JSON' })
54
+
55
+ /** Statuses a `Response` may not carry a body with. */
56
+ const NULL_BODY_STATUSES: ReadonlySet<number> = new Set([101, 103, 204, 205, 304])
57
+
58
+ /** `application/json`, with no charset or a UTF-8 one (RFC 8259: JSON between systems is UTF-8). */
59
+ export function isJsonContentType(contentType: unknown): boolean {
60
+ if (typeof contentType !== 'string') return false
61
+ const [type, ...params] = contentType.split(';')
62
+ if (type!.trim().toLowerCase() !== 'application/json') return false
63
+ for (const param of params) {
64
+ const eq = param.indexOf('=')
65
+ const name = (eq === -1 ? param : param.slice(0, eq)).trim().toLowerCase()
66
+ if (name !== 'charset') continue
67
+ const charset = eq === -1 ? '' : param.slice(eq + 1).trim().replace(/^"(.*)"$/, '$1').toLowerCase()
68
+ if (charset !== 'utf-8' && charset !== 'utf8') return false
69
+ }
70
+ return true
71
+ }
72
+
73
+ /** A byte array, also one from another realm (a Node `Buffer` is one too). */
74
+ export function isBytes(value: unknown): value is Uint8Array {
75
+ return Object.prototype.toString.call(value) === '[object Uint8Array]'
76
+ }
77
+
78
+ /**
79
+ * The verdict on a request body: its `Content-Type` and its bytes → the JSON object they hold, or why there is
80
+ * none. Never throws. The rules of every adapter's `json()` (and the BFF's own check of what an adapter hands it).
81
+ */
82
+ export function parseCommunityJson(contentType: unknown, bytes: unknown): CommunityJsonBody {
83
+ if (!isJsonContentType(contentType) || !isBytes(bytes)) return INVALID_JSON
84
+ if (bytes.byteLength > COMMUNITY_BODY_MAX_BYTES) return TOO_LARGE
85
+ let value: unknown
86
+ try {
87
+ // fatal: bytes that are no UTF-8 are no JSON; ignoreBOM: a BOM stays in the text, which JSON.parse refuses —
88
+ // what kb-api gets is what was checked here.
89
+ value = JSON.parse(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes))
90
+ } catch {
91
+ return INVALID_JSON
92
+ }
93
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return INVALID_JSON
94
+ return Object.freeze({ ok: true, bytes, value: value as Record<string, unknown> })
95
+ }
96
+
97
+ /** The body, at most `max` bytes: refused by its declared length, or as soon as the stream grows past it. */
98
+ async function readLimited(req: Request, max: number): Promise<Uint8Array | 'too_large' | null> {
99
+ const declared = Number(req.headers.get('content-length'))
100
+ if (Number.isFinite(declared) && declared > max) return 'too_large'
101
+ if (!req.body) return new Uint8Array(0)
102
+ const chunks: Uint8Array[] = []
103
+ let size = 0
104
+ try {
105
+ const reader = req.body.getReader()
106
+ for (;;) {
107
+ const { done, value } = await reader.read()
108
+ if (done) break
109
+ size += value.byteLength
110
+ if (size > max) {
111
+ // The rest is never read.
112
+ await reader.cancel().catch(() => {})
113
+ return 'too_large'
114
+ }
115
+ chunks.push(value)
116
+ }
117
+ } catch {
118
+ // A body already read, or a stream that broke off: no body.
119
+ return null
120
+ }
121
+ const bytes = new Uint8Array(size)
122
+ let offset = 0
123
+ for (const chunk of chunks) {
124
+ bytes.set(chunk, offset)
125
+ offset += chunk.byteLength
126
+ }
127
+ return bytes
128
+ }
129
+
130
+ async function readJson(req: Request): Promise<CommunityJsonBody> {
131
+ const contentType = req.headers.get('content-type')
132
+ // A body that is not JSON is never read at all.
133
+ if (!isJsonContentType(contentType)) return INVALID_JSON
134
+ const bytes = await readLimited(req, COMMUNITY_BODY_MAX_BYTES)
135
+ if (bytes === 'too_large') return TOO_LARGE
136
+ if (bytes === null) return INVALID_JSON
137
+ return parseCommunityJson(contentType, bytes)
138
+ }
139
+
140
+ /** The path of an absolute request URL, as the URL parser serialises it (no query, no fragment). */
141
+ function pathOf(url: string): string {
142
+ try {
143
+ return new URL(url).pathname
144
+ } catch {
145
+ return ''
146
+ }
147
+ }
148
+
149
+ /**
150
+ * A `CommunityHttp` over a Web `Request`, and `respond` to turn the BFF's answer into a `Response`: its status, its
151
+ * headers, every `Set-Cookie` the host queued (`memberToken` may refresh its own session) and its body as it is —
152
+ * none for a HEAD request or a status that takes none.
153
+ */
154
+ export function fromWebRequest(req: Request): { http: CommunityHttp; respond(r: CommunityResponse): Response } {
155
+ const seam = consultationFromWebRequest(req)
156
+ let body: Promise<CommunityJsonBody> | null = null
157
+
158
+ const http: CommunityHttp = {
159
+ ...seam.http,
160
+ path: pathOf(req.url),
161
+ // Memoised: the body stream can be read only once.
162
+ json: () => (body ??= readJson(req)),
163
+ }
164
+ const head = req.method.toUpperCase() === 'HEAD'
165
+
166
+ return {
167
+ http,
168
+ respond(r: CommunityResponse): Response {
169
+ // The consultations' respond writes the headers and the queued cookies; the body is the BFF's text unchanged.
170
+ const carrier = seam.respond({ status: r.status, headers: r.headers, body: null })
171
+ const empty = head || NULL_BODY_STATUSES.has(r.status) || typeof r.body !== 'string'
172
+ return new Response(empty ? null : r.body, { status: r.status, headers: carrier.headers })
173
+ },
174
+ }
175
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * `@blogmcp/sdk/community/server` — the server half of the community (docs/internal/m1-contracts.md §3.4, §10.3):
3
+ * the host-session route decision a managed blog's `/api` proxy runs (which kb-api paths a host session may reach:
4
+ * kb-api's allowlist of public and notice operations; the uniform unknown-path answer for everything else in its
5
+ * `/community` and `/trust` namespaces), and the BFF a headless site mounts in front of those routes.
6
+ *
7
+ * SERVER-ONLY by contract, like `@blogmcp/sdk/consultations/server`: `createCommunityBff` holds the site's notice
8
+ * key and its members' tokens and throws when a global `window` exists. What keeps the entry out of page
9
+ * JavaScript is structural too — the hosts import it from server code only (their import-boundary specs) and
10
+ * `scripts/verify-pack.mjs` fails a browser bundle that contains it. The browser half is `@blogmcp/sdk/community`.
11
+ * Runtime-neutral: no `node:*`, so it runs in Nitro on Bun or Node, in Next, in React Router and in a worker.
12
+ *
13
+ * ```ts
14
+ * // A React Router resource route, app/routes/api/community.$.tsx (POST only):
15
+ * const bff = createCommunityBff({
16
+ * // kb-api WITH the `/api` prefix the instance serves it under: KB_API_URL = https://<instance>/api
17
+ * // (or `${process.env.BLOGMCP_API_URL}/api`); the BFF appends `/community/v1/public/…` and `/trust/v1/notices/…`.
18
+ * kbApiUrl: process.env.KB_API_URL!, siteUrls: ['https://shop.example'],
19
+ * memberToken: async (http) => (await sessionOf(http))?.memberJwt ?? null,
20
+ * ...communityServerEnv(process.env),
21
+ * })
22
+ * export async function action({ request }: { request: Request }) {
23
+ * const { http, respond } = fromWebRequest(request)
24
+ * return respond(await bff.handle(http))
25
+ * }
26
+ *
27
+ * // A proxy that forwards on its own (the managed blogs): before its other rules, before any cookie or Bearer work.
28
+ * const decision = communityRouteDecision(request.method, path)
29
+ * if (decision.kind === 'deny') {
30
+ * const answer = communityUnknownPath()
31
+ * return new Response(request.method === 'HEAD' ? null : answer.body, { status: answer.status, headers: answer.headers })
32
+ * }
33
+ * if (decision.kind === 'allow') return forward(decision.upstreamPath) // the bearer, no cookie, the Origin checked
34
+ * ```
35
+ */
36
+
37
+ export {
38
+ COMMUNITY_NAMESPACES,
39
+ COMMUNITY_HOST_ROUTES,
40
+ isCommunityNamespacePath,
41
+ communityRouteDecision,
42
+ } from './route-decision'
43
+ export type { CommunityHostRoute, CommunityRouteDecision } from './route-decision'
44
+
45
+ export { COMMUNITY_UNKNOWN_PATH_BODY, communityUnknownPath } from './unknown-path'
46
+ export type { CommunityUnknownPathAnswer } from './unknown-path'
47
+
48
+ export { createCommunityBff } from './bff'
49
+ export type { CommunityBff, CommunityBffCode, CommunityBffConfig, CommunityBffLogEvent } from './bff'
50
+
51
+ export { communityServerEnv } from './env'
52
+ export type { CommunityServerEnv } from './env'
53
+
54
+ export { COMMUNITY_BODY_MAX_BYTES, fromWebRequest, parseCommunityJson } from './http'
55
+ export type { CommunityHttp, CommunityJsonBody, CommunityJsonRefusal, CommunityResponse } from './http'
@@ -0,0 +1,226 @@
1
+ /**
2
+ * The host-session route decision (docs/internal/m1-contracts.md §3.4; community.md §7.1, invariant 3): what a
3
+ * managed blog's `/api` proxy or a headless site's BFF does with a request for a kb-api path.
4
+ *
5
+ * kb-api's `/community` and `/trust` namespaces are open to a host session only through an allowlist of literal
6
+ * routes (COMMUNITY_HOST_ROUTES: kb-api's public and notice operations, host-routes.ts). The proxy answers
7
+ * everything else in them itself, with the uniform unknown-path answer, before it reads a cookie or computes a
8
+ * Bearer, and kb-api is never asked. Two surfaces stay closed to every proxy and BFF whatever the list holds: the
9
+ * private routes (only the member's browser calls them, directly, with a key-bound private session) and the staff
10
+ * routes (only the staff console).
11
+ *
12
+ * Deny by default, so the namespace test is conservative: a path is in a namespace when ANY reading of it is —
13
+ * raw and decoded once, twice, … until stable (an escape run that is no UTF-8 still decodes its ASCII bytes),
14
+ * lower-cased (Express routes case-insensitively), `\` read as `/`, empty and `.` segments dropped, `..` kept or
15
+ * resolved, cut at a `?` or `#` the decoding produced, with what a URL parser strips (tab, newline, blanks at the
16
+ * ends) or every control and blank removed, and leading `api` segments skipped. A false positive costs a 404 for
17
+ * a strange path; a false negative would hand kb-api a request the proxy promised never to send. The URL parser
18
+ * counts because the Next proxy forwards segments Next has already decoded once, and `fetch` then reads `%2e%2e`
19
+ * as `..` and drops a tab. A namespace path with a `..` segment, a malformed escape or a `%` left after decoding
20
+ * is denied, as is one that does not settle within MAX_DECODE_PASSES. The input is a path relative to kb-api's
21
+ * root: anything but a string, and an absolute URL (a caller passing `request.url`), fails closed.
22
+ *
23
+ * `allow` takes the canonical spelling of a listed route exactly — lower case, `[a-z0-9_-]` segments, no `%`, no
24
+ * `.`, no doubled or trailing slash, at most one leading `/` and one `api/` first segment, the route's method —
25
+ * and never a private or staff path, whatever the list says.
26
+ */
27
+
28
+ import { COMMUNITY_HOST_ROUTES } from './host-routes'
29
+
30
+ /** The kb-api namespaces a host session may reach only through the allowlist. */
31
+ export const COMMUNITY_NAMESPACES: readonly ['community', 'trust'] = Object.freeze(['community', 'trust'] as const)
32
+
33
+ export interface CommunityHostRoute {
34
+ readonly method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
35
+ /**
36
+ * The literal kb-api path as kb-api mounts it: `/community/v1/public/…` or `/trust/v1/…` — a leading `/`, lower
37
+ * case, no `/api` prefix, no query. A request matches only its canonical spelling.
38
+ */
39
+ readonly path: string
40
+ }
41
+
42
+ /** The host-session routes (method + literal path under the namespaces): kb-api's allowlist (host-routes.ts, S8). */
43
+ export { COMMUNITY_HOST_ROUTES }
44
+
45
+ /**
46
+ * The surfaces no host session ever reaches, whatever COMMUNITY_HOST_ROUTES holds (community.md invariant 3):
47
+ * the member's private routes and the staff console's routes. The only place under src/ that spells them out
48
+ * (test/community/server/boundary.spec.ts).
49
+ */
50
+ export const COMMUNITY_CLOSED_PATHS = Object.freeze(['community/v1/private', 'community/v1/staff'] as const)
51
+
52
+ /** What a proxy or BFF does with a request. */
53
+ export type CommunityRouteDecision =
54
+ /** Not a namespace path: the proxy's existing rules apply. */
55
+ | { kind: 'outside' }
56
+ /** Answer `communityUnknownPath()`, call nothing upstream. */
57
+ | { kind: 'deny' }
58
+ /** A host route: forward to kb-api's `upstreamPath` (never in M0c). */
59
+ | { kind: 'allow'; upstreamPath: string }
60
+
61
+ const OUTSIDE: CommunityRouteDecision = Object.freeze({ kind: 'outside' })
62
+ const DENY: CommunityRouteDecision = Object.freeze({ kind: 'deny' })
63
+
64
+ /** Decoding passes before a path that still changes is judged a namespace path (fail closed). */
65
+ const MAX_DECODE_PASSES = 8
66
+
67
+ /** `scheme://…`, blanks before it included: a URL where a path belongs. */
68
+ const ABSOLUTE_URL_RE = /^[\u0000-\u0020]*[a-z][a-z0-9+.-]*:\/\//i
69
+
70
+ /** One or more escapes in a row (one UTF-8 sequence may span several). */
71
+ const ESCAPE_RUN_RE = /(?:%[0-9a-f]{2})+/gi
72
+ /** The escape of an ASCII byte. */
73
+ const ASCII_ESCAPE_RE = /%([0-7][0-9a-f])/gi
74
+ /** A `%` that starts no escape. */
75
+ const BARE_PERCENT_RE = /%(?![0-9a-f]{2})/i
76
+ /** What a URL parser removes anywhere in its input. */
77
+ const URL_STRIPPED_RE = /[\t\n\r]/g
78
+ /** What a URL parser trims off the ends of its input: C0 controls and the space. */
79
+ const URL_TRIMMED_RE = /^[\u0000-\u0020]+|[\u0000-\u0020]+$/g
80
+ /** Every control character and blank. */
81
+ const CONTROLS_AND_BLANKS_RE = /[\u0000-\u0020\u007f]/g
82
+
83
+ const NAMESPACE_SET: ReadonlySet<string> = new Set(COMMUNITY_NAMESPACES)
84
+ const CLOSED_SEGMENTS: readonly (readonly string[])[] = COMMUNITY_CLOSED_PATHS.map((p) => p.split('/'))
85
+ /** A canonical namespace path; group 1 is the path under kb-api's root. */
86
+ const CANONICAL_RE = new RegExp(`^/?(?:api/)?((?:${COMMUNITY_NAMESPACES.join('|')})(?:/[a-z0-9_-]+)+)$`)
87
+
88
+ /** The path without its query and fragment: they never decide. */
89
+ function withoutQuery(path: string): string {
90
+ const cut = path.search(/[?#]/)
91
+ return cut === -1 ? path : path.slice(0, cut)
92
+ }
93
+
94
+ /** One decoding pass that never throws: an escape run that is no UTF-8 decodes its ASCII bytes and keeps the rest. */
95
+ function decodeOnce(text: string): { text: string; malformed: boolean } {
96
+ let malformed = BARE_PERCENT_RE.test(text)
97
+ const decoded = text.replace(ESCAPE_RUN_RE, (run) => {
98
+ try {
99
+ return decodeURIComponent(run)
100
+ } catch {
101
+ malformed = true
102
+ return run.replace(ASCII_ESCAPE_RE, (_, hex: string) => String.fromCharCode(parseInt(hex, 16)))
103
+ }
104
+ })
105
+ return { text: decoded, malformed }
106
+ }
107
+
108
+ /** The text, what a URL parser makes of it, and the text without any control or blank — each also cut at `?` / `#`. */
109
+ function variantsOf(text: string): string[] {
110
+ const out = new Set<string>()
111
+ const views = [
112
+ text,
113
+ text.replace(URL_STRIPPED_RE, '').replace(URL_TRIMMED_RE, ''),
114
+ text.replace(CONTROLS_AND_BLANKS_RE, ''),
115
+ ]
116
+ for (const view of views) {
117
+ out.add(view)
118
+ // A `?` or `#` the decoding produced ends the path for whoever parses it as a URL again.
119
+ const cut = view.search(/[?#]/)
120
+ if (cut !== -1) out.add(view.slice(0, cut))
121
+ }
122
+ return [...out]
123
+ }
124
+
125
+ function segmentsOf(text: string): string[] {
126
+ return text
127
+ .toLowerCase()
128
+ .replace(/\\/g, '/')
129
+ .split('/')
130
+ .filter((s) => s !== '' && s !== '.')
131
+ }
132
+
133
+ /** `..` resolved the way a URL parser resolves it (never above the root). */
134
+ function resolveDots(segments: readonly string[]): string[] {
135
+ const out: string[] = []
136
+ for (const s of segments) {
137
+ if (s === '..') out.pop()
138
+ else out.push(s)
139
+ }
140
+ return out
141
+ }
142
+
143
+ /** Without the leading `api` segments (kb-api mounts every router under `/x` and `/api/x`). */
144
+ function skipApi(segments: readonly string[]): readonly string[] {
145
+ let i = 0
146
+ while (segments[i] === 'api') i++
147
+ return segments.slice(i)
148
+ }
149
+
150
+ interface PathReading {
151
+ /** Every segment list the path can be read as, leading `api` segments skipped. */
152
+ readings: readonly (readonly string[])[]
153
+ /** A `..` segment, a malformed escape, a `%` left after the last pass, or a path that did not settle. */
154
+ suspicious: boolean
155
+ /** Still changing after MAX_DECODE_PASSES. */
156
+ unsettled: boolean
157
+ }
158
+
159
+ function readPath(path: string): PathReading {
160
+ const texts = [withoutQuery(path)]
161
+ let malformed = false
162
+ let settled = false
163
+ for (let pass = 0; pass <= MAX_DECODE_PASSES; pass++) {
164
+ const current = texts[texts.length - 1]!
165
+ const next = decodeOnce(current)
166
+ malformed ||= next.malformed
167
+ if (next.text === current) {
168
+ settled = true
169
+ break
170
+ }
171
+ if (pass < MAX_DECODE_PASSES) texts.push(next.text)
172
+ }
173
+
174
+ const readings: (readonly string[])[] = []
175
+ let dotDot = false
176
+ for (const text of texts) {
177
+ for (const variant of variantsOf(text)) {
178
+ const segments = segmentsOf(variant)
179
+ if (segments.includes('..')) dotDot = true
180
+ readings.push(skipApi(segments), skipApi(resolveDots(segments)))
181
+ }
182
+ }
183
+ const last = texts[texts.length - 1]!
184
+ return { readings, suspicious: dotDot || malformed || last.includes('%') || !settled, unsettled: !settled }
185
+ }
186
+
187
+ const inNamespace = (r: PathReading) => r.unsettled || r.readings.some((s) => s.length > 0 && NAMESPACE_SET.has(s[0]!))
188
+
189
+ const isClosed = (r: PathReading) =>
190
+ r.readings.some((s) => CLOSED_SEGMENTS.some((closed) => closed.every((segment, i) => s[i] === segment)))
191
+
192
+ /** A caller's bug, failing closed: not a string, or a URL where the path belongs. */
193
+ const notAPath = (path: unknown) => typeof path !== 'string' || ABSOLUTE_URL_RE.test(path)
194
+
195
+ /** Is `path` (relative to kb-api's root, with or without an `api/` first segment) in a namespace — in any spelling? */
196
+ export function isCommunityNamespacePath(path: string): boolean {
197
+ return notAPath(path) || inNamespace(readPath(path))
198
+ }
199
+
200
+ /**
201
+ * The decision against a given allowlist — `communityRouteDecision` is this with COMMUNITY_HOST_ROUTES. Exported
202
+ * for the SDK's tests (an allowlist that names a private or staff path must still open nothing); not part of the
203
+ * entry.
204
+ */
205
+ export function decideCommunityRoute(
206
+ routes: readonly CommunityHostRoute[],
207
+ method: string,
208
+ path: string,
209
+ ): CommunityRouteDecision {
210
+ if (notAPath(path)) return DENY
211
+ const reading = readPath(path)
212
+ if (!inNamespace(reading)) return OUTSIDE
213
+ // Before the allowlist is looked at: no list can open the closed surfaces or a strange spelling.
214
+ if (reading.suspicious || isClosed(reading)) return DENY
215
+ const canonical = CANONICAL_RE.exec(withoutQuery(path))?.[1]
216
+ if (canonical === undefined) return DENY
217
+ const upstreamPath = `/${canonical}`
218
+ const verb = typeof method === 'string' ? method.toUpperCase() : ''
219
+ const listed = Array.isArray(routes) && routes.some((r) => r?.method === verb && r.path === upstreamPath)
220
+ return listed ? Object.freeze({ kind: 'allow', upstreamPath }) : DENY
221
+ }
222
+
223
+ /** What a proxy or BFF does with a request for `path`. */
224
+ export function communityRouteDecision(method: string, path: string): CommunityRouteDecision {
225
+ return decideCommunityRoute(COMMUNITY_HOST_ROUTES, method, path)
226
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * kb-api's one answer for a path it does not serve, the closed community routes included
3
+ * (docs/internal/m1-contracts.md §3.2), for a proxy or a BFF to send ITSELF: a request the boundary denies is
4
+ * answered without asking kb-api, so the answer must be the bytes kb-api would have sent. The body is pinned
5
+ * to kb-api's `routes/unknown-path-body.ts` (test/community/server/drift.spec.ts).
6
+ *
7
+ * `UNKNOWN_PATH`, not `NOT_FOUND`: NOT_FOUND is a route's answer for a resource that does not exist, and the
8
+ * platform's erasure ends a row for good on it; a call that lands on an unknown path must stay retryable. The
9
+ * answer never repeats the path, the method or the query.
10
+ */
11
+
12
+ /** The body, byte for byte (`=== UNKNOWN_PATH_BODY` of kb-api). */
13
+ export const COMMUNITY_UNKNOWN_PATH_BODY = '{"code":"UNKNOWN_PATH","error":"Not found"}'
14
+
15
+ /** The headers kb-api sends with it (its helmet headers aside, which a proxy does not imitate). */
16
+ const UNKNOWN_PATH_HEADERS: Readonly<Record<string, string>> = Object.freeze({
17
+ 'Content-Type': 'application/json; charset=utf-8',
18
+ 'Cache-Control': 'no-store',
19
+ })
20
+
21
+ export interface CommunityUnknownPathAnswer {
22
+ status: 404
23
+ /** Exactly these, nothing else: `Content-Type` and `Cache-Control`. A fresh object on every call. */
24
+ headers: Record<string, string>
25
+ /** {@link COMMUNITY_UNKNOWN_PATH_BODY}. A HEAD answer sends the status and the headers only. */
26
+ body: string
27
+ }
28
+
29
+ /** The uniform unknown-path answer (§3.2). A fresh object on every call: a caller may add to its headers. */
30
+ export function communityUnknownPath(): CommunityUnknownPathAnswer {
31
+ return { status: 404, headers: { ...UNKNOWN_PATH_HEADERS }, body: COMMUNITY_UNKNOWN_PATH_BODY }
32
+ }