@blogmcp/sdk 0.6.1 → 0.7.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 (137) 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/auth.js +21 -21
  49. package/dist/core/client.d.ts +25 -4
  50. package/dist/core/client.js +35 -30
  51. package/dist/core/consultation-adapter.d.ts +2 -2
  52. package/dist/core/consultations.d.ts +1 -1
  53. package/dist/core/errors.d.ts +1 -1
  54. package/dist/core/errors.js +16 -15
  55. package/dist/core/index.d.ts +31 -31
  56. package/dist/core/index.js +35 -34
  57. package/dist/core/markdown.d.ts +1 -1
  58. package/dist/core/queries.d.ts +4 -1
  59. package/dist/core/queries.js +131 -86
  60. package/dist/core/review/format.d.ts +1 -1
  61. package/dist/core/review/index.d.ts +2 -2
  62. package/dist/core/seo.d.ts +1 -1
  63. package/dist/core/translations/cs.json.js +1 -1
  64. package/dist/core/translations/en.json.js +1 -1
  65. package/dist/core/types.d.ts +50 -1
  66. package/dist/core/view-model.d.ts +12 -2
  67. package/dist/core/view-model.js +40 -34
  68. package/dist/{packages/tripmap-core/node_modules → node_modules}/pmtiles/dist/esm/index.js +1 -1
  69. package/dist/nuxt/composables/useAsyncKb.d.ts +4 -4
  70. package/dist/nuxt/index.d.ts +1 -1
  71. package/dist/packages/tripmap-core/dist/engine.js +3 -3
  72. package/dist/packages/tripmap-core/dist/generated/maplibre-worker.bundle.js +1 -1
  73. package/dist/react/KbMdxContent.d.ts +1 -1
  74. package/dist/react/context.d.ts +4 -4
  75. package/dist/react/hooks/useImageRenderer.d.ts +1 -1
  76. package/dist/react/hooks/useKbClient.d.ts +1 -1
  77. package/dist/react/hooks/useKbContext.d.ts +1 -1
  78. package/dist/react/hooks/useKbI18n.d.ts +1 -1
  79. package/dist/react/hooks/useKbLanguage.d.ts +1 -1
  80. package/dist/react/hooks/useKbSearch.d.ts +1 -1
  81. package/dist/react/hooks/useMdxContent.d.ts +1 -1
  82. package/dist/react/index.d.ts +15 -15
  83. package/dist/react/provider.d.ts +2 -2
  84. package/dist/react/server/index.d.ts +2 -2
  85. package/dist/vue/components/KbAccessGate.vue.d.ts +4 -1
  86. package/dist/vue/components/KbAccessGate.vue.js +42 -32
  87. package/dist/vue/components/KbArticleCard.vue.d.ts +3 -1
  88. package/dist/vue/components/KbArticleCard.vue.js +67 -39
  89. package/dist/vue/composables/useArticles.d.ts +1 -1
  90. package/dist/vue/composables/useImageRenderer.d.ts +1 -1
  91. package/dist/vue/composables/useKbAuth.d.ts +1 -1
  92. package/dist/vue/composables/useKbClient.d.ts +1 -1
  93. package/dist/vue/composables/useKbComments.d.ts +1 -1
  94. package/dist/vue/composables/useKbI18n.d.ts +1 -1
  95. package/dist/vue/composables/useKbLanguage.d.ts +1 -1
  96. package/dist/vue/composables/useNavigation.d.ts +1 -1
  97. package/dist/vue/composables/useSearch.d.ts +1 -1
  98. package/dist/vue/composables/useTags.d.ts +1 -1
  99. package/dist/vue/index.d.ts +19 -19
  100. package/dist/vue/plugin.d.ts +4 -4
  101. package/package.json +15 -5
  102. package/src/consultations/channel-text.ts +168 -0
  103. package/src/consultations/index.ts +87 -0
  104. package/src/consultations/messages.cs.ts +175 -0
  105. package/src/consultations/messages.en.ts +171 -0
  106. package/src/consultations/messages.ts +91 -0
  107. package/src/consultations/outcome.ts +278 -0
  108. package/src/consultations/public-config.ts +246 -0
  109. package/src/consultations/reader.ts +281 -0
  110. package/src/consultations/routes.ts +341 -0
  111. package/src/consultations/server/client-ip.ts +106 -0
  112. package/src/consultations/server/contact.ts +267 -0
  113. package/src/consultations/server/context.ts +403 -0
  114. package/src/consultations/server/cookie.ts +129 -0
  115. package/src/consultations/server/env.ts +66 -0
  116. package/src/consultations/server/http.ts +148 -0
  117. package/src/consultations/server/index.ts +55 -0
  118. package/src/consultations/server/origin.ts +71 -0
  119. package/src/consultations/server/server.ts +322 -0
  120. package/src/consultations/server/session.ts +414 -0
  121. package/src/consultations/server/transport.ts +196 -0
  122. package/src/consultations/server/turnstile.ts +98 -0
  123. package/src/consultations/site.ts +183 -0
  124. package/src/consultations/submit-new.ts +266 -0
  125. package/src/core/auth.ts +5 -1
  126. package/src/core/client.ts +32 -1
  127. package/src/core/errors.ts +5 -2
  128. package/src/core/index.ts +3 -0
  129. package/src/core/queries.ts +56 -0
  130. package/src/core/translations/cs.json +2 -1
  131. package/src/core/translations/en.json +2 -1
  132. package/src/core/types.ts +51 -0
  133. package/src/core/view-model.ts +18 -0
  134. package/src/vue/components/KbAccessGate.vue +14 -1
  135. package/src/vue/components/KbArticleCard.vue +25 -0
  136. /package/dist/{packages/tripmap-core/node_modules → node_modules}/maplibre-gl/dist/maplibre-gl-shared.js +0 -0
  137. /package/dist/{packages/tripmap-core/node_modules → node_modules}/maplibre-gl/dist/maplibre-gl.js +0 -0
@@ -0,0 +1,341 @@
1
+ /**
2
+ * Reader consultation pages — where they live, what their forms post, and the
3
+ * shapes the KB accepts (docs/internal/reader-consultations.md §7.4, §8.1).
4
+ *
5
+ * The route constants are router-relative: a blog mounted under `/blog` in
6
+ * production prepends its own base. Two of them are the KB's own
7
+ * (`MANAGED_BLOG_READER_LINK_PATH` / `_THREAD_PATH` in the KB's
8
+ * managed-blog.ts): the KB builds the links in its notice e-mails from them,
9
+ * so a drift test pins them — a blog page under another path would receive
10
+ * every e-mailed link as a 404.
11
+ *
12
+ * The patterns mirror the KB's validators (drift-tested as well). They are
13
+ * checked BEFORE any KB call, so a malformed value costs neither a request nor
14
+ * a unit of the reader's quota.
15
+ *
16
+ * Browser-safe: nothing here takes a key, and nothing imports `node:*`.
17
+ */
18
+
19
+ /** The reader pages (router-relative). */
20
+ export const CONSULTATION_ROUTES = {
21
+ /** The magic-link landing page; the token travels in the fragment (`#t=`), never in the path or query. */
22
+ open: '/consultation/open',
23
+ /** The thread an anonymous reader's session cookie opens (no id in the URL, ever). */
24
+ session: '/consultation',
25
+ /** Ask for a fresh link by e-mail address. */
26
+ newLink: '/consultation/new-link',
27
+ /** A signed-in reader's list ("My consultations"). */
28
+ account: '/my-consultations',
29
+ /** A signed-in reader asks a new question (KB channel `web`). */
30
+ accountNew: '/my-consultations/new',
31
+ /** One of the signed-in reader's threads; build it with `accountThreadPath(id)`. */
32
+ accountThread: '/my-consultations/:id',
33
+ /** The anonymous contact form (KB channel `contact_form`). */
34
+ contact: '/contact',
35
+ } as const
36
+
37
+ /** The JSON endpoints the reader pages post to from JavaScript (router-relative). */
38
+ export const CONSULTATION_API_PATHS = {
39
+ /** Exchange the link token for the session cookie (`intent=exchange&token=…`). */
40
+ access: '/api/consultations/access',
41
+ /** Move the session's thread to the signed-in reader's account. */
42
+ attach: '/api/consultations/attach',
43
+ /** Drop the session cookie. */
44
+ forget: '/api/consultations/forget',
45
+ } as const
46
+
47
+ /** Where the KB points an e-mailed link (== KB `MANAGED_BLOG_READER_LINK_PATH`). */
48
+ export const CONSULTATION_KB_READER_LINK_PATH = '/consultation/open#t={token}'
49
+
50
+ /** Where the KB points a signed-in reader's thread (== KB `MANAGED_BLOG_READER_THREAD_PATH`). */
51
+ export const CONSULTATION_KB_READER_THREAD_PATH = '/my-consultations/{id}'
52
+
53
+ /** A link token and a session value: 32 random bytes, base64url (== KB `SECRET_RE`). */
54
+ export const CONSULTATION_SECRET_RE = /^[A-Za-z0-9_-]{43}$/
55
+
56
+ /** An idempotency key of one reader action; a UUID fits (== KB `CLIENT_REQUEST_RE`). */
57
+ export const CLIENT_REQUEST_ID_RE = /^[A-Za-z0-9._:-]{1,64}$/
58
+
59
+ /** A legal text version (== KB `VERSION_RE`; stricter than the drhoubicka storefront's `{1,64}`). */
60
+ export const LEGAL_VERSION_RE = /^[A-Za-z0-9._-]{1,40}$/
61
+
62
+ /** A consultation id (the KB's thread UUID). Anything else is "not found" without asking the KB. */
63
+ export const CONSULTATION_ID_RE = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i
64
+
65
+ /** A locale: `cs`, `en`, `pt-BR` (== the KB's locale / language pattern). */
66
+ export const LOCALE_RE = /^[a-z]{2}(-[A-Za-z0-9]{2,8})?$/
67
+
68
+ /** The longest reader message the KB takes (== KB `READER_BODY_MAX`): a reply in a thread. */
69
+ export const READER_BODY_MAX = 5000
70
+
71
+ /** The longest NEW question on the account page. The KB would take 5000; the form keeps questions short. */
72
+ export const NEW_QUESTION_BODY_MAX = 2000
73
+
74
+ /** The longest contact-form message. */
75
+ export const CONTACT_MESSAGE_MAX = 2000
76
+
77
+ /** The longest name the contact form takes (the KB would take 255; the server refuses more than this). */
78
+ export const CONTACT_NAME_MAX = 100
79
+
80
+ /** The longest reader e-mail address accepted (the RFC 5321 path limit). */
81
+ export const READER_EMAIL_MAX = 254
82
+
83
+ /**
84
+ * The Turnstile action the contact form's widget declares (`data-action`) and the
85
+ * server expects when it verifies the token — one constant, so the two never drift.
86
+ */
87
+ export const CONSULTATION_TURNSTILE_ACTION = 'consultation_contact'
88
+
89
+ /** The KB's own address check. */
90
+ const READER_EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
91
+
92
+ /**
93
+ * Whether `value` is an address the server takes for a new link or the contact
94
+ * form — the same check it runs, so a page can show the field error before posting.
95
+ */
96
+ export function isReaderEmail(value: string): boolean {
97
+ return typeof value === 'string' && value.length <= READER_EMAIL_MAX && READER_EMAIL_RE.test(value)
98
+ }
99
+
100
+ /**
101
+ * The fields the new-question form (`/my-consultations/new`) posts.
102
+ *
103
+ * `legalMode` says what the page SHOWED: `consent` (the text with an unticked
104
+ * box), `notice` (the text, no box) or `covered` (no text: the reader's
105
+ * consent already covers new questions). `legalVersion` and `legalLocale`
106
+ * carry the shown text's version and locale; with `covered` they are ignored.
107
+ * `consent` is the checkbox, posted only when ticked, with the value `on`.
108
+ */
109
+ export const NEW_QUESTION_FIELDS = {
110
+ body: 'body',
111
+ clientRequestId: 'clientRequestId',
112
+ legalMode: 'legalMode',
113
+ legalVersion: 'legalVersion',
114
+ legalLocale: 'legalLocale',
115
+ consent: 'consent',
116
+ } as const
117
+
118
+ /**
119
+ * The fields of the session page's forms (`/consultation`) and of the access
120
+ * endpoint. `intent` is one of `CONSULTATION_INTENTS`: `reply` (with `body`
121
+ * and `clientRequestId`), `erase`, `logout` on the page; `exchange` (with
122
+ * `token`) on `CONSULTATION_API_PATHS.access`.
123
+ */
124
+ export const SESSION_FIELDS = {
125
+ intent: 'intent',
126
+ body: 'body',
127
+ clientRequestId: 'clientRequestId',
128
+ token: 'token',
129
+ } as const
130
+
131
+ /** The values of the `intent` field. */
132
+ export const CONSULTATION_INTENTS = {
133
+ exchange: 'exchange',
134
+ reply: 'reply',
135
+ erase: 'erase',
136
+ logout: 'logout',
137
+ } as const
138
+
139
+ /** The fields of the new-link form (`/consultation/new-link`). `website` is the honeypot: left empty by people. */
140
+ export const NEW_LINK_FIELDS = {
141
+ email: 'email',
142
+ honeypot: 'website',
143
+ } as const
144
+
145
+ /**
146
+ * The fields of the contact form (`/contact`). `messageId` is the idempotency
147
+ * key the page was rendered with; `legalMode` / `legalVersion` /
148
+ * `legalLocale` name the text the form showed, and `consent` is the checkbox
149
+ * in consent mode (`on` when ticked). `website` is the honeypot and
150
+ * `cf-turnstile-response` the Turnstile widget's own field.
151
+ */
152
+ export const CONTACT_FIELDS = {
153
+ name: 'name',
154
+ email: 'email',
155
+ message: 'message',
156
+ messageId: 'messageId',
157
+ legalMode: 'legalMode',
158
+ legalVersion: 'legalVersion',
159
+ legalLocale: 'legalLocale',
160
+ consent: 'consent',
161
+ honeypot: 'website',
162
+ turnstile: 'cf-turnstile-response',
163
+ } as const
164
+
165
+ /**
166
+ * The path of one of the signed-in reader's threads. A value that is not a
167
+ * consultation id links to the list instead: no path is ever built from
168
+ * arbitrary text (a redirect after a create, a link in the list).
169
+ */
170
+ export function accountThreadPath(id: string): string {
171
+ return typeof id === 'string' && CONSULTATION_ID_RE.test(id)
172
+ ? CONSULTATION_ROUTES.accountThread.replace(':id', id.toLowerCase())
173
+ : CONSULTATION_ROUTES.account
174
+ }
175
+
176
+ /**
177
+ * A reader message as the KB should get it: line breaks as `\n`, trimmed,
178
+ * 1..`max` characters, no NUL.
179
+ *
180
+ * A native form POST (before hydration, without JavaScript) sends every line
181
+ * break as CRLF — two characters — while the textarea's `maxLength` and a page
182
+ * counter count one. Without the normalisation a text that fit into the field
183
+ * would come back "too long", and without JavaScript there is no counter to
184
+ * show what to cut.
185
+ *
186
+ * A failure carries the typed text back for the form (line breaks normalised,
187
+ * NOT trimmed): the reader gets their text back to fix, never an empty field
188
+ * — and never a silently shortened one, which would pass on the next attempt
189
+ * without its end. Only a text over twice the limit (a hand-made POST, not a
190
+ * textarea) is cut, to bound the response.
191
+ */
192
+ export function normalizeBody(
193
+ raw: unknown,
194
+ max: number,
195
+ ): { ok: true; body: string } | { ok: false; code: 'invalid' | 'tooLong'; body: string } {
196
+ if (typeof raw !== 'string') return { ok: false, code: 'invalid', body: '' }
197
+ const typed = raw.replace(/\r\n?/g, '\n')
198
+ const echo = typed.slice(0, 2 * Math.max(max, READER_BODY_MAX))
199
+ const body = typed.trim()
200
+ if (body === '' || body.includes('\u0000')) return { ok: false, code: 'invalid', body: echo }
201
+ if (body.length > max) return { ok: false, code: 'tooLong', body: echo }
202
+ return { ok: true, body }
203
+ }
204
+
205
+ /**
206
+ * A fresh idempotency key for one reader action (a UUID). Mint it when the
207
+ * form is rendered and send the SAME key again on a retry: the KB answers a
208
+ * replay as the stored write (`duplicate`) instead of writing twice.
209
+ *
210
+ * `crypto.randomUUID` exists only in secure contexts; a blog opened over plain
211
+ * http on a LAN address (a phone during development) gets a v4 UUID from
212
+ * `crypto.getRandomValues`, which exists everywhere.
213
+ */
214
+ export function newClientRequestId(): string {
215
+ const c = globalThis.crypto
216
+ if (typeof c?.randomUUID === 'function') return c.randomUUID()
217
+ const bytes = c.getRandomValues(new Uint8Array(16))
218
+ // `?? 0` only for consumers compiling with noUncheckedIndexedAccess: the array has 16 bytes.
219
+ bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40
220
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80
221
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
222
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
223
+ }
224
+
225
+ /**
226
+ * The link token in a URL fragment (`#t=<token>`), or null.
227
+ *
228
+ * Nothing else is read from the fragment, and only the KB's exact token shape
229
+ * is accepted. A truncated link from a mail client or an appended tracking
230
+ * parameter is "the link has no access code", never a token that goes to the
231
+ * KB.
232
+ */
233
+ export function tokenFromHash(hash: string): string | null {
234
+ const match = /^#t=([^&]*)/.exec(typeof hash === 'string' ? hash : '')
235
+ const token = match?.[1] ?? ''
236
+ return CONSULTATION_SECRET_RE.test(token) ? token : null
237
+ }
238
+
239
+ /** The token each window's address bar carried, read once (the fragment is gone after the first read). */
240
+ const linkTokens = new WeakMap<Window, string | null>()
241
+
242
+ function browserWindow(): Window {
243
+ if (typeof window === 'undefined') {
244
+ throw new Error(
245
+ '[blogmcp-sdk] readLinkToken reads the address bar — call it in the browser ' +
246
+ '(onMounted / useEffect), never while rendering on the server',
247
+ )
248
+ }
249
+ return window
250
+ }
251
+
252
+ /** A plain object — a router's state record — not an array, a class instance or null. */
253
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
254
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
255
+ const proto = Object.getPrototypeOf(value)
256
+ return proto === Object.prototype || proto === null
257
+ }
258
+
259
+ /**
260
+ * `value` without the link's fragment: cut at the `#` where it starts. The
261
+ * fragment is found as the address bar showed it (`hash`) and, for a valid
262
+ * token, by the token itself wherever it stands — no copy of it survives.
263
+ */
264
+ function withoutFragment(value: string, hash: string, token: string | null): string {
265
+ let out = value
266
+ const at = hash ? out.indexOf(hash) : -1
267
+ if (at >= 0) out = out.slice(0, at)
268
+ if (token !== null) {
269
+ for (let i = out.indexOf(token); i >= 0; i = out.indexOf(token)) {
270
+ const fragment = out.lastIndexOf('#', i)
271
+ out = fragment >= 0 ? out.slice(0, fragment) : out.slice(0, i) + out.slice(i + token.length)
272
+ }
273
+ }
274
+ return out
275
+ }
276
+
277
+ /**
278
+ * The router's history state without any copy of the link's fragment.
279
+ * vue-router keeps the full URL, fragment included, in `history.state.current`
280
+ * (and in `back` / `forward`); a token left there stays readable by any script
281
+ * on the page and is kept in the back-forward cache. A SHALLOW copy: only
282
+ * top-level string values change; every other key and value (vue-router's
283
+ * `position` and `scroll`, Next's internals) stays as it is, and a state that
284
+ * is not a plain object is kept as it is.
285
+ */
286
+ function scrubbedState(state: unknown, hash: string, token: string | null): unknown {
287
+ if (!isPlainRecord(state)) return state
288
+ let changed = false
289
+ const copy: Record<string, unknown> = { ...state }
290
+ for (const [key, value] of Object.entries(copy)) {
291
+ if (typeof value !== 'string') continue
292
+ const clean = withoutFragment(value, hash, token)
293
+ if (clean !== value) {
294
+ copy[key] = clean
295
+ changed = true
296
+ }
297
+ }
298
+ return changed ? copy : state
299
+ }
300
+
301
+ /**
302
+ * The link token of the magic-link page, read from the address bar and then
303
+ * removed from it — from the URL and from the router's copy in
304
+ * `history.state`.
305
+ *
306
+ * The token is a bearer capability: left in the address bar it would end up
307
+ * in the history, in a bookmark, in a copied link. So the first call strips
308
+ * the fragment with `history.replaceState`, keeping the query string and the
309
+ * router's state (the routers keep their bookkeeping there; `null` would break
310
+ * their back navigation) — minus every copy of the fragment in it.
311
+ *
312
+ * The token is remembered per window: a second call — React StrictMode runs
313
+ * mount effects twice, Vue remounts a page — finds an address bar that is
314
+ * already clean and would otherwise answer "the link has no access code". A
315
+ * later call touches the address bar only for a new link (`#t=…` pasted into
316
+ * the same tab, whose valid token then replaces the remembered one), never for
317
+ * an anchor the page set itself.
318
+ *
319
+ * ⚠️ A router may also keep the old URL in its own memory: vue-router writes
320
+ * its last known location into the next entry's `state.back` on the next
321
+ * `push`. In a vue-router app, follow this with `router.replace({ hash: '' })`
322
+ * (or navigate away with `replace`), so the router forgets the fragment too.
323
+ *
324
+ * Send the token to the KB only on an explicit gesture (a button), never on
325
+ * load: mail scanners and link previews open links but do not press buttons,
326
+ * and the KB allows only a few exchanges per token.
327
+ */
328
+ export function readLinkToken(win: Window = browserWindow()): string | null {
329
+ const hash = win.location.hash
330
+ const fresh = tokenFromHash(hash)
331
+ const first = !linkTokens.has(win)
332
+ if (hash && (first || hash.startsWith('#t='))) {
333
+ win.history.replaceState(
334
+ scrubbedState(win.history.state, hash, fresh),
335
+ '',
336
+ win.location.pathname + win.location.search,
337
+ )
338
+ }
339
+ if (first || fresh !== null) linkTokens.set(win, fresh)
340
+ return linkTokens.get(win) ?? null
341
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The reader's IP, forwarded to the KB as `X-Blogmcp-Client-Ip`.
3
+ *
4
+ * kb-api believes that header from the blog's credentialed calls (the
5
+ * reader-proxy service key, the reader's own JWT, the adapter key), so the
6
+ * value IS the bucket its per-IP quotas count in. On the anonymous paths —
7
+ * link exchange 30/h, link requests 10/h, session posts 60/h, contact ingest —
8
+ * that cap is the only per-requester limit. It is used to bucket quotas and
9
+ * never for access decisions.
10
+ *
11
+ * Order (reader-consultations F5 §3.4):
12
+ * 1. The adapter's own `clientIp()` (e.g. h3's `getRequestIP`), or the
13
+ * configured edge header (default `cf-connecting-ip`; Cloudflare OVERWRITES
14
+ * it on every proxied request) — when it holds exactly one valid IP.
15
+ * 2. Otherwise the RIGHTMOST `X-Forwarded-For` hop: the one the proxy directly
16
+ * in front of us appended from its own peer address.
17
+ * 3. Otherwise null (the header is then not sent at all).
18
+ *
19
+ * ⚠️ Never the LEFTMOST hop: it is whatever the client sent (Cloudflare and
20
+ * most reverse proxies APPEND to a client-supplied `X-Forwarded-For`). Reading
21
+ * it let `curl -H "X-Forwarded-For: 10.0.$i.1"` in a loop get a fresh KB bucket
22
+ * per request, and fill somebody else's bucket on purpose. An unparseable
23
+ * rightmost hop is null, never "the next one to the left". `X-Real-IP` is
24
+ * never read: depending on the proxy it can echo a header the client sent.
25
+ *
26
+ * Validation is pure JS (no `node:net`, so the entry runs on any runtime) and
27
+ * never looser than kb-api's `net.isIP`: whatever this accepts, kb-api accepts
28
+ * (a parity test holds that). IPv4 is a strict dotted quad; IPv6 goes through
29
+ * the WHATWG URL parser; zone ids (`fe80::1%eth0`) and lists are rejected.
30
+ */
31
+
32
+ import type { ConsultationHttp } from './http'
33
+
34
+ /** The edge header read when the server config names none. */
35
+ export const DEFAULT_CLIENT_IP_HEADER = 'cf-connecting-ip'
36
+
37
+ /** The header kb-api reads the forwarded reader IP from. */
38
+ export const KB_CLIENT_IP_HEADER = 'X-Blogmcp-Client-Ip'
39
+
40
+ const IPV4_OCTET = '(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)'
41
+ const IPV4_RE = new RegExp(`^${IPV4_OCTET}(?:\\.${IPV4_OCTET}){3}$`)
42
+ /** The characters an IPv6 literal can have (an embedded IPv4 tail included); 45 = its longest form. */
43
+ const IPV6_CHARS_RE = /^[0-9A-Fa-f:.]{2,45}$/
44
+
45
+ /** An HTTP header name (RFC 9110 token). */
46
+ const HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/
47
+
48
+ /** True for one IPv4 or IPv6 address, as kb-api's `net.isIP` would accept it (no zone id, no list). */
49
+ export function isIpAddress(value: string): boolean {
50
+ if (IPV4_RE.test(value)) return true
51
+ if (!value.includes(':') || !IPV6_CHARS_RE.test(value)) return false
52
+ try {
53
+ // The URL parser implements the full IPv6 grammar ("::" once, at most 8
54
+ // groups, an IPv4 tail without leading zeros) and throws on anything else.
55
+ new URL(`http://[${value}]/`)
56
+ return true
57
+ } catch {
58
+ return false
59
+ }
60
+ }
61
+
62
+ /** One valid IP from a raw value (trimmed), else null. */
63
+ export function singleIp(value: unknown): string | null {
64
+ if (typeof value !== 'string') return null
65
+ const candidate = value.trim()
66
+ return candidate !== '' && isIpAddress(candidate) ? candidate : null
67
+ }
68
+
69
+ /** True for a usable header name ('' means "no edge header"). */
70
+ export function isHeaderName(name: string): boolean {
71
+ return HEADER_NAME_RE.test(name)
72
+ }
73
+
74
+ /**
75
+ * The reader's IP for the KB's per-IP quotas, or null when nothing
76
+ * trustworthy is available. `header` names the edge header (default
77
+ * `cf-connecting-ip`; `''` = none, for deployments not fronted by Cloudflare,
78
+ * where every client writes that header itself).
79
+ */
80
+ export function clientIpFrom(
81
+ http: Pick<ConsultationHttp, 'header' | 'clientIp'>,
82
+ o: { header?: string } = {},
83
+ ): string | null {
84
+ const own = typeof http.clientIp === 'function' ? singleIp(safely(() => http.clientIp!())) : null
85
+ if (own) return own
86
+
87
+ const name = (o.header ?? DEFAULT_CLIENT_IP_HEADER).trim()
88
+ if (name !== '' && isHeaderName(name)) {
89
+ const fromEdge = singleIp(safely(() => http.header(name)))
90
+ if (fromEdge) return fromEdge
91
+ }
92
+
93
+ const xff = safely(() => http.header('x-forwarded-for'))
94
+ if (typeof xff !== 'string' || xff.trim() === '') return null
95
+ // Rightmost hop only; never walk further left.
96
+ return singleIp(xff.split(',').at(-1))
97
+ }
98
+
99
+ /** An adapter callback that throws counts as "no value" (the IP is best effort). */
100
+ function safely<T>(read: () => T): T | null {
101
+ try {
102
+ return read()
103
+ } catch {
104
+ return null
105
+ }
106
+ }