@blogmcp/sdk 0.6.0 → 0.7.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 (208) hide show
  1. package/dist/consultations/channel-text.d.ts +118 -0
  2. package/dist/consultations/channel-text.js +40 -0
  3. package/dist/consultations/index.d.ts +28 -0
  4. package/dist/consultations/index.js +60 -0
  5. package/dist/consultations/messages.cs.d.ts +149 -0
  6. package/dist/consultations/messages.cs.js +143 -0
  7. package/dist/consultations/messages.d.ts +34 -0
  8. package/dist/consultations/messages.en.d.ts +143 -0
  9. package/dist/consultations/messages.en.js +141 -0
  10. package/dist/consultations/messages.js +48 -0
  11. package/dist/consultations/outcome.d.ts +121 -0
  12. package/dist/consultations/outcome.js +161 -0
  13. package/dist/consultations/public-config.d.ts +71 -0
  14. package/dist/consultations/public-config.js +104 -0
  15. package/dist/consultations/reader.d.ts +83 -0
  16. package/dist/consultations/reader.js +128 -0
  17. package/dist/consultations/routes.d.ts +214 -0
  18. package/dist/consultations/routes.js +149 -0
  19. package/dist/consultations/server/client-ip.d.ts +50 -0
  20. package/dist/consultations/server/client-ip.js +44 -0
  21. package/dist/consultations/server/contact.d.ts +23 -0
  22. package/dist/consultations/server/contact.js +138 -0
  23. package/dist/consultations/server/context.d.ts +246 -0
  24. package/dist/consultations/server/context.js +152 -0
  25. package/dist/consultations/server/cookie.d.ts +60 -0
  26. package/dist/consultations/server/cookie.js +57 -0
  27. package/dist/consultations/server/env.d.ts +20 -0
  28. package/dist/consultations/server/env.js +35 -0
  29. package/dist/consultations/server/http.d.ts +59 -0
  30. package/dist/consultations/server/http.js +64 -0
  31. package/dist/consultations/server/index.d.ts +37 -0
  32. package/dist/consultations/server/index.js +19 -0
  33. package/dist/consultations/server/origin.d.ts +39 -0
  34. package/dist/consultations/server/origin.js +31 -0
  35. package/dist/consultations/server/server.d.ts +106 -0
  36. package/dist/consultations/server/server.js +122 -0
  37. package/dist/consultations/server/session.d.ts +38 -0
  38. package/dist/consultations/server/session.js +210 -0
  39. package/dist/consultations/server/transport.d.ts +69 -0
  40. package/dist/consultations/server/transport.js +117 -0
  41. package/dist/consultations/server/turnstile.d.ts +44 -0
  42. package/dist/consultations/server/turnstile.js +31 -0
  43. package/dist/consultations/site.d.ts +100 -0
  44. package/dist/consultations/site.js +60 -0
  45. package/dist/consultations/submit-new.d.ts +103 -0
  46. package/dist/consultations/submit-new.js +72 -0
  47. package/dist/core/auth.d.ts +2 -2
  48. package/dist/core/client.d.ts +25 -4
  49. package/dist/core/client.js +35 -30
  50. package/dist/core/consultation-adapter.d.ts +2 -2
  51. package/dist/core/consultations.d.ts +1 -1
  52. package/dist/core/errors.d.ts +1 -1
  53. package/dist/core/errors.js +16 -15
  54. package/dist/core/index.d.ts +31 -31
  55. package/dist/core/index.js +35 -34
  56. package/dist/core/markdown.d.ts +1 -1
  57. package/dist/core/queries.d.ts +4 -1
  58. package/dist/core/queries.js +131 -86
  59. package/dist/core/review/format.d.ts +1 -1
  60. package/dist/core/review/index.d.ts +2 -2
  61. package/dist/core/seo.d.ts +1 -1
  62. package/dist/core/translations/cs.json.js +1 -1
  63. package/dist/core/translations/en.json.js +1 -1
  64. package/dist/core/types.d.ts +50 -1
  65. package/dist/core/view-model.d.ts +12 -2
  66. package/dist/core/view-model.js +40 -34
  67. package/dist/{packages/tripmap-core/node_modules → node_modules}/pmtiles/dist/esm/index.js +1 -1
  68. package/dist/nuxt/composables/useAsyncKb.d.ts +4 -4
  69. package/dist/nuxt/index.d.ts +1 -1
  70. package/dist/packages/mdx-render-vue/dist/composables/useGallery.js +12 -11
  71. package/dist/packages/mdx-render-vue/dist/composables/useTripMap.js +16 -16
  72. package/dist/packages/mdx-render-vue/dist/edit/TripMapEdit.vue.js +1 -1
  73. package/dist/packages/mdx-render-vue/dist/registry.js +21 -22
  74. package/dist/packages/mdx-render-vue/dist/render/alert/Alert.vue2.js +1 -1
  75. package/dist/packages/mdx-render-vue/dist/render/badge/Badge.vue2.js +1 -1
  76. package/dist/packages/mdx-render-vue/dist/render/button/Button.vue2.js +1 -1
  77. package/dist/packages/mdx-render-vue/dist/render/callout/CalloutDefault.vue.js +1 -1
  78. package/dist/packages/mdx-render-vue/dist/render/callout/CalloutMinimal.vue.js +1 -1
  79. package/dist/packages/mdx-render-vue/dist/render/tripmap/TripMapDefault.vue.js +2 -2
  80. package/dist/packages/tripmap-core/dist/engine.js +3 -3
  81. package/dist/packages/tripmap-core/dist/generated/maplibre-worker.bundle.js +1 -1
  82. package/dist/react/KbMdxContent.d.ts +1 -1
  83. package/dist/react/KbMdxContent.js +7 -8
  84. package/dist/react/context.d.ts +4 -4
  85. package/dist/react/hooks/useImageRenderer.d.ts +1 -1
  86. package/dist/react/hooks/useKbClient.d.ts +1 -1
  87. package/dist/react/hooks/useKbContext.d.ts +1 -1
  88. package/dist/react/hooks/useKbI18n.d.ts +1 -1
  89. package/dist/react/hooks/useKbLanguage.d.ts +1 -1
  90. package/dist/react/hooks/useKbSearch.d.ts +1 -1
  91. package/dist/react/hooks/useMdxContent.d.ts +1 -1
  92. package/dist/react/index.d.ts +15 -15
  93. package/dist/react/provider.d.ts +2 -2
  94. package/dist/react/server/index.d.ts +2 -2
  95. package/dist/vue/components/KbAccessGate.vue.d.ts +4 -1
  96. package/dist/vue/components/KbAccessGate.vue.js +42 -32
  97. package/dist/vue/components/KbArticleCard.vue.d.ts +3 -1
  98. package/dist/vue/components/KbArticleCard.vue.js +67 -39
  99. package/dist/vue/components/KbMdxContent.vue2.js +6 -7
  100. package/dist/vue/composables/useArticles.d.ts +1 -1
  101. package/dist/vue/composables/useImageRenderer.d.ts +1 -1
  102. package/dist/vue/composables/useKbAuth.d.ts +1 -1
  103. package/dist/vue/composables/useKbClient.d.ts +1 -1
  104. package/dist/vue/composables/useKbComments.d.ts +1 -1
  105. package/dist/vue/composables/useKbI18n.d.ts +1 -1
  106. package/dist/vue/composables/useKbLanguage.d.ts +1 -1
  107. package/dist/vue/composables/useNavigation.d.ts +1 -1
  108. package/dist/vue/composables/useSearch.d.ts +1 -1
  109. package/dist/vue/composables/useTags.d.ts +1 -1
  110. package/dist/vue/index.d.ts +19 -19
  111. package/dist/vue/plugin.d.ts +4 -4
  112. package/package.json +15 -5
  113. package/src/consultations/channel-text.ts +168 -0
  114. package/src/consultations/index.ts +87 -0
  115. package/src/consultations/messages.cs.ts +175 -0
  116. package/src/consultations/messages.en.ts +171 -0
  117. package/src/consultations/messages.ts +91 -0
  118. package/src/consultations/outcome.ts +278 -0
  119. package/src/consultations/public-config.ts +246 -0
  120. package/src/consultations/reader.ts +281 -0
  121. package/src/consultations/routes.ts +341 -0
  122. package/src/consultations/server/client-ip.ts +106 -0
  123. package/src/consultations/server/contact.ts +267 -0
  124. package/src/consultations/server/context.ts +403 -0
  125. package/src/consultations/server/cookie.ts +129 -0
  126. package/src/consultations/server/env.ts +66 -0
  127. package/src/consultations/server/http.ts +148 -0
  128. package/src/consultations/server/index.ts +55 -0
  129. package/src/consultations/server/origin.ts +71 -0
  130. package/src/consultations/server/server.ts +322 -0
  131. package/src/consultations/server/session.ts +414 -0
  132. package/src/consultations/server/transport.ts +196 -0
  133. package/src/consultations/server/turnstile.ts +98 -0
  134. package/src/consultations/site.ts +183 -0
  135. package/src/consultations/submit-new.ts +266 -0
  136. package/src/core/auth.ts +1 -1
  137. package/src/core/client.ts +32 -1
  138. package/src/core/errors.ts +5 -2
  139. package/src/core/index.ts +3 -0
  140. package/src/core/queries.ts +56 -0
  141. package/src/core/translations/cs.json +2 -1
  142. package/src/core/translations/en.json +2 -1
  143. package/src/core/types.ts +51 -0
  144. package/src/core/view-model.ts +18 -0
  145. package/src/vue/components/KbAccessGate.vue +14 -1
  146. package/src/vue/components/KbArticleCard.vue +25 -0
  147. package/dist/_virtual/constants.js +0 -4
  148. package/dist/_virtual/index.js +0 -2
  149. package/dist/_virtual/index2.js +0 -4
  150. package/dist/_virtual/index3.js +0 -2
  151. package/dist/_virtual/re.js +0 -4
  152. package/dist/node_modules/@braintree/sanitize-url/dist/constants.js +0 -8
  153. package/dist/node_modules/@braintree/sanitize-url/dist/index.js +0 -60
  154. package/dist/node_modules/dompurify/dist/purify.es.js +0 -662
  155. package/dist/node_modules/semver/classes/comparator.js +0 -56
  156. package/dist/node_modules/semver/classes/range.js +0 -148
  157. package/dist/node_modules/semver/classes/semver.js +0 -169
  158. package/dist/node_modules/semver/functions/clean.js +0 -14
  159. package/dist/node_modules/semver/functions/cmp.js +0 -39
  160. package/dist/node_modules/semver/functions/coerce.js +0 -33
  161. package/dist/node_modules/semver/functions/compare-build.js +0 -14
  162. package/dist/node_modules/semver/functions/compare-loose.js +0 -11
  163. package/dist/node_modules/semver/functions/compare.js +0 -11
  164. package/dist/node_modules/semver/functions/diff.js +0 -24
  165. package/dist/node_modules/semver/functions/eq.js +0 -11
  166. package/dist/node_modules/semver/functions/gt.js +0 -11
  167. package/dist/node_modules/semver/functions/gte.js +0 -11
  168. package/dist/node_modules/semver/functions/inc.js +0 -21
  169. package/dist/node_modules/semver/functions/lt.js +0 -11
  170. package/dist/node_modules/semver/functions/lte.js +0 -11
  171. package/dist/node_modules/semver/functions/major.js +0 -11
  172. package/dist/node_modules/semver/functions/minor.js +0 -11
  173. package/dist/node_modules/semver/functions/neq.js +0 -11
  174. package/dist/node_modules/semver/functions/parse.js +0 -21
  175. package/dist/node_modules/semver/functions/patch.js +0 -11
  176. package/dist/node_modules/semver/functions/prerelease.js +0 -14
  177. package/dist/node_modules/semver/functions/rcompare.js +0 -11
  178. package/dist/node_modules/semver/functions/rsort.js +0 -11
  179. package/dist/node_modules/semver/functions/satisfies.js +0 -18
  180. package/dist/node_modules/semver/functions/sort.js +0 -11
  181. package/dist/node_modules/semver/functions/valid.js +0 -14
  182. package/dist/node_modules/semver/index.js +0 -97
  183. package/dist/node_modules/semver/internal/constants.js +0 -28
  184. package/dist/node_modules/semver/internal/debug.js +0 -8
  185. package/dist/node_modules/semver/internal/identifiers.js +0 -18
  186. package/dist/node_modules/semver/internal/lrucache.js +0 -32
  187. package/dist/node_modules/semver/internal/parse-options.js +0 -10
  188. package/dist/node_modules/semver/internal/re.js +0 -32
  189. package/dist/node_modules/semver/ranges/gtr.js +0 -11
  190. package/dist/node_modules/semver/ranges/intersects.js +0 -11
  191. package/dist/node_modules/semver/ranges/ltr.js +0 -11
  192. package/dist/node_modules/semver/ranges/max-satisfying.js +0 -22
  193. package/dist/node_modules/semver/ranges/min-satisfying.js +0 -22
  194. package/dist/node_modules/semver/ranges/min-version.js +0 -42
  195. package/dist/node_modules/semver/ranges/outside.js +0 -44
  196. package/dist/node_modules/semver/ranges/simplify.js +0 -24
  197. package/dist/node_modules/semver/ranges/subset.js +0 -94
  198. package/dist/node_modules/semver/ranges/to-comparators.js +0 -11
  199. package/dist/node_modules/semver/ranges/valid.js +0 -17
  200. package/dist/packages/mdx-schema/dist/composables/useMdxParsing.js +0 -389
  201. package/dist/packages/mdx-schema/dist/metadata/index.js +0 -526
  202. package/dist/packages/mdx-schema/dist/prepareProps.js +0 -46
  203. package/dist/packages/mdx-schema/dist/styles/index.js +0 -147
  204. package/dist/packages/mdx-schema/dist/tripmap.js +0 -101
  205. package/dist/packages/mdx-schema/dist/types/index.js +0 -26
  206. package/dist/packages/sanitize/dist/html.js +0 -89
  207. /package/dist/{packages/tripmap-core/node_modules → node_modules}/maplibre-gl/dist/maplibre-gl-shared.js +0 -0
  208. /package/dist/{packages/tripmap-core/node_modules → node_modules}/maplibre-gl/dist/maplibre-gl.js +0 -0
@@ -0,0 +1,129 @@
1
+ /**
2
+ * The session cookie of a reader who opened a magic link.
3
+ *
4
+ * `__Host-` is enforced by the browser: only with `Secure`, only `Path=/`, no
5
+ * `Domain` — so no sister host can read, overwrite or plant it. `HttpOnly`: the
6
+ * session is a bearer capability (whoever holds it reads the question) and must
7
+ * never reach page JavaScript. `SameSite=Lax`: it comes along with a click from
8
+ * the mail client, never with a cross-site POST.
9
+ *
10
+ * Clearing a cookie is a full `Set-Cookie` with `Max-Age=0` and EVERY attribute.
11
+ * A clear without `Secure` and `Path=/` (Next's `cookies().delete()`) is a
12
+ * different cookie as far as the browser is concerned — it is ignored and the
13
+ * session stays.
14
+ */
15
+
16
+ import { CONSULTATION_SECRET_RE } from '../index'
17
+ import type { ConsultationHttp } from './http'
18
+
19
+ /** The default name of the session cookie. */
20
+ export const CONSULTATION_SESSION_COOKIE = '__Host-kb_consult'
21
+
22
+ /** A configurable cookie name must keep the `__Host-` prefix. */
23
+ export const CONSULTATION_COOKIE_NAME_RE = /^__Host-[A-Za-z0-9_]+$/
24
+
25
+ /** Upper bound on the cookie's life: 12 h, even when the KB keeps the session longer. */
26
+ export const CONSULTATION_SESSION_COOKIE_MAX_S = 12 * 60 * 60
27
+
28
+ /** Lower bound: clock skew between the KB and the blog must not make a cookie that is gone at once. */
29
+ export const CONSULTATION_SESSION_COOKIE_MIN_S = 60
30
+
31
+ /** A cookie exactly as the consultation pages set it; the attributes are fixed by the type. */
32
+ export interface ConsultationCookie {
33
+ name: string
34
+ value: string
35
+ /** Seconds; 0 clears the cookie. */
36
+ maxAge: number
37
+ path: '/'
38
+ httpOnly: true
39
+ secure: true
40
+ sameSite: 'lax'
41
+ }
42
+
43
+ /** RFC 6265 cookie-octets (no whitespace, quote, comma, semicolon or backslash). */
44
+ const COOKIE_VALUE_RE = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/
45
+
46
+ /** The session cookie; `Max-Age` = clamp(expiresAt − now, 60 s, 12 h). The KB decides validity; the cookie only carries it. */
47
+ export function sessionCookie(
48
+ name: string,
49
+ session: string,
50
+ expiresAt: string | null | undefined,
51
+ now: number,
52
+ ): ConsultationCookie {
53
+ const at = typeof expiresAt === 'string' ? Date.parse(expiresAt) : Number.NaN
54
+ const remaining = Number.isNaN(at) ? CONSULTATION_SESSION_COOKIE_MAX_S : Math.floor((at - now) / 1000)
55
+ const maxAge = Math.max(CONSULTATION_SESSION_COOKIE_MIN_S, Math.min(remaining, CONSULTATION_SESSION_COOKIE_MAX_S))
56
+ return { name, value: session, maxAge, path: '/', httpOnly: true, secure: true, sameSite: 'lax' }
57
+ }
58
+
59
+ /** The cookie that removes the session from the browser. */
60
+ export function clearedCookie(name: string): ConsultationCookie {
61
+ return { name, value: '', maxAge: 0, path: '/', httpOnly: true, secure: true, sameSite: 'lax' }
62
+ }
63
+
64
+ /**
65
+ * `Set-Cookie` value for a consultation cookie. The attributes are always
66
+ * written from the fixed set, whatever the object says. Throws on a name
67
+ * without `__Host-`, a value that is not cookie-safe or a bad `Max-Age` — a
68
+ * programming error; the message never quotes the value (it is a session).
69
+ */
70
+ export function serializeConsultationCookie(c: ConsultationCookie): string {
71
+ if (typeof c?.name !== 'string' || !CONSULTATION_COOKIE_NAME_RE.test(c.name)) {
72
+ throw new TypeError('[blogmcp-sdk] consultation cookie name must match ^__Host-[A-Za-z0-9_]+$')
73
+ }
74
+ if (typeof c.value !== 'string' || !COOKIE_VALUE_RE.test(c.value)) {
75
+ throw new TypeError('[blogmcp-sdk] consultation cookie value is not a valid cookie value')
76
+ }
77
+ if (!Number.isInteger(c.maxAge) || c.maxAge < 0) {
78
+ throw new TypeError('[blogmcp-sdk] consultation cookie maxAge must be a non-negative integer')
79
+ }
80
+ return `${c.name}=${c.value}; Max-Age=${c.maxAge}; Path=/; HttpOnly; Secure; SameSite=Lax`
81
+ }
82
+
83
+ /**
84
+ * The `Cookie` request header without the consultation cookie — for a blog's
85
+ * `/api` proxy, so the session never travels on to the KB (or into its logs).
86
+ * The name is matched case-insensitively (browsers apply the `__Host-` prefix
87
+ * rules case-insensitively), every other cookie is kept in order.
88
+ */
89
+ export function stripConsultationCookie(cookieHeader: string, name: string = CONSULTATION_SESSION_COOKIE): string {
90
+ if (typeof cookieHeader !== 'string' || cookieHeader === '') return ''
91
+ const target = name.toLowerCase()
92
+ return cookieHeader
93
+ .split(';')
94
+ .map((part) => part.trim())
95
+ .filter((part) => {
96
+ if (part === '') return false
97
+ const eq = part.indexOf('=')
98
+ const key = (eq < 0 ? part : part.slice(0, eq)).trim().toLowerCase()
99
+ return key !== target
100
+ })
101
+ .join('; ')
102
+ }
103
+
104
+ /** The value of cookie `name` in a `Cookie` header (the first one), or null. */
105
+ export function cookieFromHeader(cookieHeader: string | null | undefined, name: string): string | null {
106
+ if (typeof cookieHeader !== 'string' || cookieHeader === '') return null
107
+ for (const part of cookieHeader.split(';')) {
108
+ const eq = part.indexOf('=')
109
+ if (eq < 0) continue
110
+ if (part.slice(0, eq).trim() !== name) continue
111
+ return part.slice(eq + 1).trim()
112
+ }
113
+ return null
114
+ }
115
+
116
+ /**
117
+ * The session from the request's cookie, or null. A value of any other shape
118
+ * than the KB's 43-char base64url secret is not a session at all and never
119
+ * goes to the KB.
120
+ */
121
+ export function readSessionCookie(http: Pick<ConsultationHttp, 'cookie'>, name: string): string | null {
122
+ let value: string | null
123
+ try {
124
+ value = http.cookie(name)
125
+ } catch {
126
+ return null
127
+ }
128
+ return typeof value === 'string' && CONSULTATION_SECRET_RE.test(value) ? value : null
129
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The consultation server's configuration from the environment — the same
3
+ * names for the managed blog (chart) and a headless kit:
4
+ *
5
+ * {prefix}CONSULTATIONS_READER_PROXY_KEY the PUBLIC reader-proxy service key
6
+ * {prefix}CONSULTATIONS_ADAPTER_KEY the contact form's adapter key
7
+ * {prefix}CONSULTATIONS_CLIENT_IP_HEADER the edge IP header (unset: cf-connecting-ip; empty: none)
8
+ * {prefix}CONSULTATIONS_TURNSTILE_SITE_KEY \ Turnstile on the contact form
9
+ * {prefix}CONSULTATIONS_TURNSTILE_SECRET_KEY / (both, or neither)
10
+ * KB_MANAGED_BLOG_URLS, SITE_URL, NUXT_PUBLIC_SITE_URL the blog's own URLs (their union)
11
+ *
12
+ * `prefix` is `''` for Next and `'NUXT_'` for Nuxt (whose runtime config reads
13
+ * `NUXT_*`). The keys are never PUBLIC: a `NEXT_PUBLIC_CONSULTATIONS_*` or
14
+ * `NUXT_PUBLIC_CONSULTATIONS_*` variable would be bundled into page
15
+ * JavaScript, so its mere presence throws — before anything reads it.
16
+ */
17
+
18
+ import { parseSiteUrls } from '../index'
19
+ import type { ConsultationServerConfig } from './server'
20
+
21
+ const PUBLIC_PREFIXES = ['NEXT_PUBLIC_CONSULTATIONS_', 'NUXT_PUBLIC_CONSULTATIONS_'] as const
22
+
23
+ function value(env: Record<string, string | undefined>, name: string): string | undefined {
24
+ const v = env[name]
25
+ return typeof v === 'string' ? v : undefined
26
+ }
27
+
28
+ function key(env: Record<string, string | undefined>, name: string): string | null {
29
+ const v = value(env, name)?.trim()
30
+ return v ? v : null
31
+ }
32
+
33
+ export function consultationServerEnv(
34
+ env: Record<string, string | undefined>,
35
+ o: { prefix?: '' | 'NUXT_' } = {},
36
+ ): Omit<ConsultationServerConfig, 'kbApiUrl'> {
37
+ for (const name of Object.keys(env ?? {})) {
38
+ const v = env[name]
39
+ if (typeof v === 'string' && v !== '' && PUBLIC_PREFIXES.some((p) => name.startsWith(p))) {
40
+ // The name only — never the value.
41
+ throw new Error(
42
+ `[blogmcp-sdk] ${name} is set — consultation keys are never PUBLIC (a *_PUBLIC_* variable ends up in page ` +
43
+ 'JavaScript). Rename it without PUBLIC_ and rotate the key.',
44
+ )
45
+ }
46
+ }
47
+
48
+ const p = o.prefix === 'NUXT_' ? 'NUXT_' : ''
49
+ const siteKey = key(env, `${p}CONSULTATIONS_TURNSTILE_SITE_KEY`)
50
+ const secretKey = key(env, `${p}CONSULTATIONS_TURNSTILE_SECRET_KEY`)
51
+ if ((siteKey === null) !== (secretKey === null)) {
52
+ console.warn(
53
+ `[consultations] only one of ${p}CONSULTATIONS_TURNSTILE_SITE_KEY / _SECRET_KEY is set — the contact form runs without Turnstile.`,
54
+ )
55
+ }
56
+ const clientIpHeader = value(env, `${p}CONSULTATIONS_CLIENT_IP_HEADER`)
57
+
58
+ return {
59
+ siteUrls: parseSiteUrls(value(env, 'KB_MANAGED_BLOG_URLS'), value(env, 'SITE_URL'), value(env, 'NUXT_PUBLIC_SITE_URL')),
60
+ readerProxyKey: key(env, `${p}CONSULTATIONS_READER_PROXY_KEY`),
61
+ adapterKey: key(env, `${p}CONSULTATIONS_ADAPTER_KEY`),
62
+ // Unset: the default edge header. Set but empty: none (a deployment not fronted by Cloudflare).
63
+ ...(clientIpHeader !== undefined ? { clientIpHeader: clientIpHeader.trim() } : {}),
64
+ turnstile: siteKey && secretKey ? { siteKey, secretKey } : null,
65
+ }
66
+ }
@@ -0,0 +1,148 @@
1
+ /**
2
+ * The one request/response seam between the consultation handlers and a
3
+ * framework. A Nitro (h3) event, a Next server action or route handler, or a
4
+ * plain Web `Request` each become a `ConsultationHttp` in a few lines; the
5
+ * handlers answer with a `ConsultationResponse` the framework writes out.
6
+ *
7
+ * `fromWebRequest` is the ready-made adapter for anything that speaks Web
8
+ * `Request`/`Response` (Next route handlers, Nitro's `toWebRequest`, workers).
9
+ */
10
+
11
+ import { cookieFromHeader, serializeConsultationCookie, type ConsultationCookie } from './cookie'
12
+
13
+ export interface ConsultationHttp {
14
+ /** The request method, upper case. A server action is always `'POST'`. */
15
+ method: string
16
+ /** A request header, case-insensitive; null when absent. */
17
+ header(name: string): string | null
18
+ /** A request cookie; null when absent. */
19
+ cookie(name: string): string | null
20
+ /**
21
+ * Queue a `Set-Cookie`. May be a no-op where cookies cannot be set (a Next
22
+ * Server Component) — the handlers only ever clear a cookie there, best effort.
23
+ */
24
+ setCookie(c: ConsultationCookie): void
25
+ /**
26
+ * The posted form: urlencoded or multipart, string fields only; null when the
27
+ * body is not a form (or is too large, or malformed). Called at most once.
28
+ *
29
+ * An adapter MUST enforce what `fromWebRequest` enforces: only
30
+ * `application/x-www-form-urlencoded` and `multipart/form-data`, at most
31
+ * 64 KB (stop reading past it and answer null), files dropped. Extra fields
32
+ * (Next's `$ACTION_*`, a blog's own) may stay: the handlers read only their
33
+ * own field names.
34
+ */
35
+ form(): Promise<Record<string, string> | null>
36
+ /** Optional: the framework's own idea of the client IP. Still validated as exactly one IP. */
37
+ clientIp?(): string | null
38
+ }
39
+
40
+ /** What a handler answers; `Set-Cookie` travels separately, through `ConsultationHttp.setCookie`. */
41
+ export interface ConsultationResponse<B> {
42
+ status: number
43
+ headers: Record<string, string>
44
+ /** JSON; `null` means no body at all (a 204, or a 200 with nothing to say). */
45
+ body: B
46
+ }
47
+
48
+ export interface FromWebRequestOptions {
49
+ /** Largest accepted form body in bytes (default 65 536); a larger one reads as "no form". */
50
+ maxBodyBytes?: number
51
+ }
52
+
53
+ const DEFAULT_MAX_BODY_BYTES = 65_536
54
+
55
+ /** Statuses a `Response` may not carry a body with. */
56
+ const NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304])
57
+
58
+ /** Fields of a posted form, string values only (files are dropped); a repeated field keeps its last value. */
59
+ export function stringFields(entries: Iterable<[string, unknown]>): Record<string, string> {
60
+ const out: Record<string, string> = Object.create(null)
61
+ for (const [key, value] of entries) {
62
+ if (typeof value === 'string') out[key] = value
63
+ }
64
+ return out
65
+ }
66
+
67
+ /** The media type of a `Content-Type` header, lower case, without parameters. */
68
+ function mediaType(contentType: string | null): string {
69
+ return (contentType ?? '').split(';')[0]!.trim().toLowerCase()
70
+ }
71
+
72
+ /**
73
+ * The request body as a stream that errors once it grows past `max` bytes (the
74
+ * rest is never read; the source is cancelled). Null when the declared length
75
+ * is already too large.
76
+ */
77
+ function limitedBody(req: Request, max: number): ReadableStream | '' | null {
78
+ const declared = Number(req.headers.get('content-length'))
79
+ if (Number.isFinite(declared) && declared > max) return null
80
+ if (!req.body) return ''
81
+ let size = 0
82
+ return req.body.pipeThrough(
83
+ new TransformStream({
84
+ transform(chunk: Uint8Array, controller) {
85
+ size += chunk.byteLength
86
+ if (size > max) controller.error(new Error('form body too large'))
87
+ else controller.enqueue(chunk)
88
+ },
89
+ }),
90
+ )
91
+ }
92
+
93
+ async function parseForm(req: Request, max: number): Promise<Record<string, string> | null> {
94
+ const contentType = req.headers.get('content-type')
95
+ const type = mediaType(contentType)
96
+ if (type !== 'application/x-www-form-urlencoded' && type !== 'multipart/form-data') return null
97
+ try {
98
+ const body = limitedBody(req, max)
99
+ if (body === null) return null
100
+ const limited = new Response(body, { headers: { 'content-type': contentType! } })
101
+ if (type === 'application/x-www-form-urlencoded') {
102
+ return stringFields(new URLSearchParams(await limited.text()))
103
+ }
104
+ const form = await limited.formData()
105
+ return stringFields(form as unknown as Iterable<[string, unknown]>)
106
+ } catch {
107
+ return null
108
+ }
109
+ }
110
+
111
+ /**
112
+ * A `ConsultationHttp` over a Web `Request`, and `respond` to turn a handler's
113
+ * answer into a `Response` (JSON body, the handler's headers, every queued
114
+ * `Set-Cookie`). Only urlencoded or multipart bodies up to `maxBodyBytes` are
115
+ * read as forms.
116
+ */
117
+ export function fromWebRequest(
118
+ req: Request,
119
+ o: FromWebRequestOptions = {},
120
+ ): { http: ConsultationHttp; respond<B>(r: ConsultationResponse<B>): Response } {
121
+ const max = Math.max(0, o.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES)
122
+ const cookies: string[] = []
123
+ let form: Promise<Record<string, string> | null> | null = null
124
+
125
+ const http: ConsultationHttp = {
126
+ method: req.method.toUpperCase(),
127
+ header: (name) => req.headers.get(name),
128
+ cookie: (name) => cookieFromHeader(req.headers.get('cookie'), name),
129
+ setCookie: (c) => {
130
+ cookies.push(serializeConsultationCookie(c))
131
+ },
132
+ // Memoised: the body stream can be read only once.
133
+ form: () => (form ??= parseForm(req, max)),
134
+ }
135
+
136
+ return {
137
+ http,
138
+ respond<B>(r: ConsultationResponse<B>): Response {
139
+ const headers = new Headers(r.headers)
140
+ for (const cookie of cookies) headers.append('Set-Cookie', cookie)
141
+ if (r.body === null || r.body === undefined || NULL_BODY_STATUSES.has(r.status)) {
142
+ return new Response(null, { status: r.status, headers })
143
+ }
144
+ headers.set('Content-Type', 'application/json; charset=utf-8')
145
+ return new Response(JSON.stringify(r.body), { status: r.status, headers })
146
+ },
147
+ }
148
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * `@blogmcp/sdk/consultations/server` — everything of the reader consultation
3
+ * pages that touches a key, a session, a cookie, a reader's IP or Turnstile
4
+ * (docs/internal/reader-consultations.md; the F5 plan §3).
5
+ *
6
+ * SERVER-ONLY: `createConsultationServer` throws when a global `window`
7
+ * exists. Runtime-neutral otherwise — Web `fetch`, `URL`, `crypto`,
8
+ * `AbortSignal.timeout`, no `node:*` — so it runs in Nitro on Bun or Node and
9
+ * in Next on Node.
10
+ *
11
+ * The browser-safe half (routes, codes, messages, the new-question flow) is
12
+ * `@blogmcp/sdk/consultations`.
13
+ *
14
+ * ```ts
15
+ * // Next (App Router): lib/consultations.server.ts
16
+ * import 'server-only'
17
+ * export const consultations = createConsultationServer({
18
+ * kbApiUrl: process.env.KB_API_URL!, ...consultationServerEnv(process.env) })
19
+ * // app/api/consultations/access/route.ts
20
+ * export async function POST(req: Request) {
21
+ * const { http, respond } = fromWebRequest(req)
22
+ * return respond(await consultations.handleAccess(http))
23
+ * }
24
+ * ```
25
+ */
26
+
27
+ export { createConsultationServer } from './server'
28
+ export type { ConsultationServer, ConsultationServerConfig } from './server'
29
+ export type {
30
+ ConsultationFeature,
31
+ ConsultationPageGate,
32
+ SessionPageState,
33
+ AccessResult,
34
+ SessionActionResult,
35
+ ForgetResult,
36
+ AttachResult,
37
+ RequestLinkResult,
38
+ ContactPageState,
39
+ ContactResult,
40
+ } from './context'
41
+
42
+ export { consultationServerEnv } from './env'
43
+
44
+ export { fromWebRequest } from './http'
45
+ export type { ConsultationHttp, ConsultationResponse, FromWebRequestOptions } from './http'
46
+
47
+ export { CONSULTATION_SESSION_COOKIE, serializeConsultationCookie, stripConsultationCookie } from './cookie'
48
+ export type { ConsultationCookie } from './cookie'
49
+
50
+ export { clientIpFrom } from './client-ip'
51
+
52
+ export { isAllowedOrigin } from './origin'
53
+
54
+ export { verifyTurnstile, TURNSTILE_VERIFY_URL } from './turnstile'
55
+ export type { TurnstileVerdict, VerifyTurnstileOptions } from './turnstile'
@@ -0,0 +1,71 @@
1
+ /**
2
+ * CSRF check for every consultation POST: did the request come from one of
3
+ * this blog's own pages? Exported so a blog's `/api` proxy applies the very
4
+ * same rule (`isAllowedOrigin(http, consultations.allowedOrigins())`) instead
5
+ * of a copy.
6
+ *
7
+ * The session cookie is `SameSite=Lax`, which stops a cross-SITE POST by
8
+ * itself. But "site" is the registrable domain: every tenant of a shared
9
+ * domain (`evil.blogmcp.ai` next to `tenant.blogmcp.ai`) is same-site and its
10
+ * pages send the cookie along. `Origin` compares the whole origin, and
11
+ * `Sec-Fetch-Site` (when the browser sends it) must say `same-origin` — so a
12
+ * sister host is stopped here, not by the cookie. `__Host-` stops the other
13
+ * half of that attack: a sister host cannot plant (toss) a cookie with
14
+ * `Domain=.blogmcp.ai` under our name.
15
+ *
16
+ * The allowlist is the origins of the blog's own site URLs plus explicit
17
+ * extras. Nothing is derived from the request: not `Host`, not
18
+ * `X-Forwarded-Host`, not `X-Forwarded-Proto` (behind a TLS-terminating proxy
19
+ * the request URL says `http://`, and trusting it once let a page served on
20
+ * plain `http://` by a network attacker pass the check).
21
+ *
22
+ * A missing `Origin` and the opaque `Origin: null` are refused. Browsers send
23
+ * `Origin` on every POST; the blog's pages answer with `Referrer-Policy:
24
+ * same-origin` (never `no-referrer`, which makes a plain form POST send
25
+ * `Origin: null` even to its own site).
26
+ */
27
+
28
+ import type { ConsultationHttp } from './http'
29
+
30
+ /** The origin of an absolute http(s) URL, or null. */
31
+ export function originOf(value: unknown): string | null {
32
+ if (typeof value !== 'string' || value.trim() === '') return null
33
+ try {
34
+ const url = new URL(value.trim())
35
+ return url.protocol === 'https:' || url.protocol === 'http:' ? url.origin : null
36
+ } catch {
37
+ return null
38
+ }
39
+ }
40
+
41
+ /** The allowed origins: every site URL's origin plus the explicit extras, deduplicated (junk entries are skipped). */
42
+ export function siteOrigins(siteUrls: readonly string[], extra: readonly string[] = []): readonly string[] {
43
+ const origins: string[] = []
44
+ for (const value of [...siteUrls, ...extra]) {
45
+ const origin = originOf(value)
46
+ if (origin && !origins.includes(origin)) origins.push(origin)
47
+ }
48
+ return Object.freeze(origins)
49
+ }
50
+
51
+ /**
52
+ * True when the request carries an `Origin` that is exactly one of `allowed`
53
+ * (not `null`) and, if present, `Sec-Fetch-Site: same-origin`. Browsers
54
+ * serialise `Origin` canonically (lower-case host, no default port, punycode),
55
+ * so the comparison is exact; `allowed` holds origins as `URL.origin` writes
56
+ * them (`ConsultationServer.allowedOrigins()`).
57
+ */
58
+ export function isAllowedOrigin(http: Pick<ConsultationHttp, 'header'>, allowed: readonly string[]): boolean {
59
+ let origin: string | null
60
+ let fetchSite: string | null
61
+ try {
62
+ origin = http.header('origin')
63
+ fetchSite = http.header('sec-fetch-site')
64
+ } catch {
65
+ return false
66
+ }
67
+ if (typeof origin !== 'string' || origin === '' || origin === 'null') return false
68
+ if (!Array.isArray(allowed) || !allowed.includes(origin)) return false
69
+ if (fetchSite !== null && fetchSite !== undefined && fetchSite.trim().toLowerCase() !== 'same-origin') return false
70
+ return true
71
+ }