@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,98 @@
1
+ /**
2
+ * Cloudflare Turnstile — server-side verification of the widget's token
3
+ * (`siteverify`). A port of the drhoubicka backend's verifier
4
+ * (`vendure-backend/src/common/turnstile.ts`).
5
+ *
6
+ * | status | ok | when |
7
+ * |---------------|-------|--------------------------------------------------------------|
8
+ * | `disabled` | true | no secret configured (dev, tests, or switched off on purpose) |
9
+ * | `unavailable` | true | Cloudflare did not answer (network, timeout, 5xx, bad body) |
10
+ * | `verified` | true | Cloudflare confirmed the token |
11
+ * | `rejected` | false | Cloudflare refused it, the token is missing or too long, or the widget's `action` differs |
12
+ *
13
+ * An outage is `ok` on purpose (fail-open, like the backend): a lost reader
14
+ * question is worse than a little more spam, which the honeypot and the KB's
15
+ * quotas still bound. The caller decides — the contact handler refuses on
16
+ * `unavailable` only with `turnstile.failOpen: false`. An attacker cannot
17
+ * cause the outage: they do not control whether Cloudflare answers.
18
+ *
19
+ * Never throws, and the verdict carries no detail: nothing here can put the
20
+ * secret (it is in the request body) or the token into a log.
21
+ */
22
+
23
+ import { singleIp } from './client-ip'
24
+
25
+ export const TURNSTILE_VERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'
26
+
27
+ /** A Turnstile token is at most 2048 characters (Cloudflare's docs); a longer one is refused unsent. */
28
+ export const TURNSTILE_MAX_TOKEN_LENGTH = 2048
29
+
30
+ const DEFAULT_TIMEOUT_MS = 5000
31
+
32
+ export type TurnstileVerdict =
33
+ | { ok: true; status: 'disabled' | 'verified' | 'unavailable' }
34
+ | { ok: false; status: 'rejected' }
35
+
36
+ export interface VerifyTurnstileOptions {
37
+ /** The widget's secret key. Empty or missing: verification is off (`disabled`). */
38
+ secret?: string | null
39
+ /** The reader's IP when known; sent as `remoteip` only when it is exactly one IP. */
40
+ remoteIp?: string | null
41
+ /** The widget's `action`. When Cloudflare reports one, it must match (a token from another form must not pass). */
42
+ expectedAction?: string
43
+ /** Default 5000 ms. */
44
+ timeoutMs?: number
45
+ /** Custom fetch (tests / runtimes without a global fetch). */
46
+ fetch?: typeof fetch
47
+ }
48
+
49
+ interface SiteverifyResponse {
50
+ success?: unknown
51
+ 'error-codes'?: unknown
52
+ action?: unknown
53
+ }
54
+
55
+ export async function verifyTurnstile(
56
+ token: string | null | undefined,
57
+ o: VerifyTurnstileOptions,
58
+ ): Promise<TurnstileVerdict> {
59
+ const secret = typeof o?.secret === 'string' ? o.secret.trim() : ''
60
+ if (!secret) return { ok: true, status: 'disabled' }
61
+
62
+ const response = typeof token === 'string' ? token.trim() : ''
63
+ if (!response || response.length > TURNSTILE_MAX_TOKEN_LENGTH) return { ok: false, status: 'rejected' }
64
+
65
+ const body = new URLSearchParams({ secret, response })
66
+ const remoteIp = singleIp(o.remoteIp)
67
+ if (remoteIp) body.set('remoteip', remoteIp)
68
+
69
+ let parsed: SiteverifyResponse
70
+ try {
71
+ const doFetch = o.fetch ?? globalThis.fetch
72
+ const res = await doFetch(TURNSTILE_VERIFY_URL, {
73
+ method: 'POST',
74
+ body,
75
+ signal: AbortSignal.timeout(o.timeoutMs ?? DEFAULT_TIMEOUT_MS),
76
+ // Following a redirect would re-send the secret to wherever it points.
77
+ redirect: 'error',
78
+ cache: 'no-store',
79
+ })
80
+ if (!res.ok) return { ok: true, status: 'unavailable' }
81
+ parsed = (await res.json()) as SiteverifyResponse
82
+ } catch {
83
+ return { ok: true, status: 'unavailable' }
84
+ }
85
+ if (parsed === null || typeof parsed !== 'object') return { ok: true, status: 'unavailable' }
86
+
87
+ if (parsed.success !== true) {
88
+ const codes = Array.isArray(parsed['error-codes']) ? parsed['error-codes'] : []
89
+ // `internal-error` is Cloudflare's own failure, not a verdict about the visitor.
90
+ if (codes.includes('internal-error')) return { ok: true, status: 'unavailable' }
91
+ return { ok: false, status: 'rejected' }
92
+ }
93
+
94
+ if (o.expectedAction && typeof parsed.action === 'string' && parsed.action !== '' && parsed.action !== o.expectedAction) {
95
+ return { ok: false, status: 'rejected' }
96
+ }
97
+ return { ok: true, status: 'verified' }
98
+ }
@@ -0,0 +1,183 @@
1
+ /**
2
+ * The reader-site gate: does THIS blog serve the reader consultation pages?
3
+ *
4
+ * A tenant has one reader site — the site the KB sends readers to from its
5
+ * notice e-mails (`kb_settings.reader_base_url`, public as
6
+ * `consultationPublicConfig.readerSiteUrl`). The pages are live on a blog
7
+ * only when:
8
+ *
9
+ * 1. the blog holds its reader-proxy key (without it every reader would
10
+ * share one per-IP quota bucket, and the session pages cannot work);
11
+ * 2. the KB can be asked (otherwise `unknown`: the pages answer 503 with
12
+ * `Retry-After`, never 404 and never live);
13
+ * 3. the reader site is set, and
14
+ * 4. it is this blog: `canonicalSiteUrl(readerSiteUrl)` is one of the
15
+ * blog's own canonical URLs (`siteUrls`).
16
+ *
17
+ * So a tenant whose reader site is its storefront (`https://shop.example`)
18
+ * keeps its managed blog (`https://shop.example/blog`) dark: a different path
19
+ * is a different site.
20
+ *
21
+ * The module switch closes only what creates content: the contact form and
22
+ * new questions. Switched off, the KB still lets a reader read their
23
+ * questions, open a link, erase a question and withdraw their consent,
24
+ * because privacy duties do not end with the feature
25
+ * (docs/internal/reader-consultations.md §5.6). The pages that do that stay
26
+ * live, but the site stops linking to them (`features.links`).
27
+ */
28
+
29
+ import type { ConsultationPublicConfig } from '../core/types'
30
+ import { CHANNEL_TEXT_DISABLED, CONSULTATION_CHANNELS, channelTextFrom, type ChannelText } from './channel-text'
31
+ import type { ConsultationOutcome } from './outcome'
32
+
33
+ /**
34
+ * The shape of a reader site the KB accepts (the DB CHECK on
35
+ * `reader_base_url`): https, or plain http only on localhost; no query string
36
+ * or fragment; none of `" ' < > \`. A copy of the KB's
37
+ * `READER_BASE_URL_PATTERN` (reader-base-url.ts); the parity test runs both.
38
+ */
39
+ const READER_BASE_URL_PATTERN =
40
+ /^(https:\/\/[^/?#\s"'<>\\]+|http:\/\/(localhost|127\.0\.0\.1)(:[0-9]+)?)(\/[^?#\s"'<>\\]*)?$/
41
+
42
+ /**
43
+ * A site URL in the KB's canonical reader-site form, or null when it could not
44
+ * be a reader site (empty, not https, a query string, credentials, …).
45
+ *
46
+ * The canonical form is the parsed origin (scheme and host lower-cased, IDN as
47
+ * punycode, default port dropped) plus the path, without trailing slashes:
48
+ * `https://Blog.Example:443/blog/` and `https://blog.example/blog` are the
49
+ * same site. It mirrors the KB's `canonicalReaderBaseUrl` exactly — a parity
50
+ * test runs both over the same vectors — because the KB compares and stores
51
+ * the reader site in this form.
52
+ */
53
+ export function canonicalSiteUrl(v: unknown): string | null {
54
+ if (typeof v !== 'string' || v === '') return null
55
+ const trimmed = v.trim()
56
+ if (/[\s"'<>\\]/.test(trimmed)) return null
57
+ // An empty "?" or "#" parses to search/hash '' — check the raw text too.
58
+ if (/[?#]/.test(trimmed)) return null
59
+ let parsed: URL
60
+ try {
61
+ parsed = new URL(trimmed)
62
+ } catch {
63
+ return null
64
+ }
65
+ const isLocalhost = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1'
66
+ if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && isLocalhost)) return null
67
+ if (parsed.username || parsed.password) return null
68
+ const canonical = `${parsed.origin}${parsed.pathname}`.replace(/\/+$/, '')
69
+ return READER_BASE_URL_PATTERN.test(canonical) ? canonical : null
70
+ }
71
+
72
+ /**
73
+ * The blog's own URLs, canonical and deduplicated, first occurrence first.
74
+ * Every argument may be a comma-separated list (`KB_MANAGED_BLOG_URLS`), a
75
+ * list of such strings, or empty; an entry that could not be a reader site is
76
+ * dropped. The union of the managed blog's list and a headless kit's
77
+ * `SITE_URL` is fine — both are this blog.
78
+ */
79
+ export function parseSiteUrls(...v: Array<string | string[] | null | undefined>): string[] {
80
+ const urls: string[] = []
81
+ for (const arg of v) {
82
+ for (const item of Array.isArray(arg) ? arg : [arg]) {
83
+ if (typeof item !== 'string') continue
84
+ for (const entry of item.split(',')) {
85
+ const url = canonicalSiteUrl(entry.trim())
86
+ if (url !== null && !urls.includes(url)) urls.push(url)
87
+ }
88
+ }
89
+ }
90
+ return urls
91
+ }
92
+
93
+ export interface ConsultationSiteStatus {
94
+ /** `live`: serve the pages; `dark`: 404 them; `unknown`: 503 with `Retry-After` (the KB could not be asked). */
95
+ state: 'live' | 'dark' | 'unknown'
96
+ /** Why — for logs and smoke tests only, never for readers. */
97
+ reason: 'ok' | 'module_off' | 'reader_site_unset' | 'other_reader_site' | 'reader_proxy_key_missing' | 'kb_unavailable'
98
+ features: {
99
+ /** `/consultation/open`, `/consultation` and the access / attach / forget endpoints. */
100
+ magicLink: boolean
101
+ /** `/consultation/new-link` — only when answers reach readers by e-mail. */
102
+ newLink: boolean
103
+ /** `/my-consultations` and `/my-consultations/:id`. (`/my-consultations/new` is decided per reader by `webAsk`.) */
104
+ account: boolean
105
+ /** `/contact` — e-mail notices, the blog's adapter key, and a usable `contact_form` text in this locale. */
106
+ contactForm: boolean
107
+ /**
108
+ * Link the pages from the site's menu and footer. Off while the module is
109
+ * off: the pages stay open for the questions readers already have (their
110
+ * e-mails link there), but the site offers consultations to nobody new.
111
+ * Not a page gate — menus and footers read it, `pageGate` does not.
112
+ */
113
+ links: boolean
114
+ }
115
+ /** The contact form's text; disabled whenever `features.contactForm` is off. */
116
+ contactText: ChannelText
117
+ }
118
+
119
+ const ALL_OFF = Object.freeze({ magicLink: false, newLink: false, account: false, contactForm: false, links: false })
120
+
121
+ function status(
122
+ state: ConsultationSiteStatus['state'],
123
+ reason: ConsultationSiteStatus['reason'],
124
+ features: ConsultationSiteStatus['features'] = ALL_OFF,
125
+ contactText: ChannelText = CHANNEL_TEXT_DISABLED,
126
+ ): ConsultationSiteStatus {
127
+ return Object.freeze({ state, reason, features: Object.freeze({ ...features }), contactText })
128
+ }
129
+
130
+ /**
131
+ * Whether this blog serves the reader pages, and which of them.
132
+ *
133
+ * | feature | module on | module off (`reason: module_off`) |
134
+ * |---------------|-----------------------------------------------|-----------------------------------|
135
+ * | `magicLink` | yes | yes |
136
+ * | `account` | yes | yes |
137
+ * | `newLink` | `emailNotices` | `emailNotices` |
138
+ * | `contactForm` | `emailNotices` ∧ adapter key ∧ a usable `contact_form` text | no |
139
+ * | `links` | yes | no |
140
+ *
141
+ * Both columns are `live`; everything else is `dark` or `unknown` with every
142
+ * feature off. `/my-consultations/new` is decided per reader by `webAsk`, and
143
+ * the KB closes it while the module is off.
144
+ *
145
+ * `cfg` is the public config outcome (`PublicConfigCache.get(locale)`); `site`
146
+ * describes the blog: its canonical URLs, whether its reader-proxy and adapter
147
+ * keys are configured (never the keys themselves), and the page locale.
148
+ */
149
+ export function readerSiteStatus(
150
+ cfg: ConsultationOutcome<ConsultationPublicConfig>,
151
+ site: { siteUrls: string[]; readerProxyKey: boolean; adapterKey: boolean; locale: string },
152
+ ): ConsultationSiteStatus {
153
+ // Local configuration first: a blog without its key is dark whether or not the KB answers.
154
+ if (site.readerProxyKey !== true) return status('dark', 'reader_proxy_key_missing')
155
+ if (!cfg || cfg.ok !== true) return status('unknown', 'kb_unavailable')
156
+ const config = cfg.value
157
+ // Whose pages these are comes before whether the module is on: a blog that is not the reader site
158
+ // serves nothing, on or off.
159
+ const readerSite = canonicalSiteUrl(config.readerSiteUrl)
160
+ if (readerSite === null) return status('dark', 'reader_site_unset')
161
+ const ours = new Set((Array.isArray(site.siteUrls) ? site.siteUrls : []).map(canonicalSiteUrl))
162
+ if (!ours.has(readerSite)) return status('dark', 'other_reader_site')
163
+
164
+ const emailNotices = config.emailNotices === true
165
+ if (config.enabled !== true) {
166
+ // Off: what a reader may still do with an existing question stays open (§5.6); nothing new is offered.
167
+ return status('live', 'module_off', {
168
+ magicLink: true,
169
+ account: true,
170
+ newLink: emailNotices,
171
+ contactForm: false,
172
+ links: false,
173
+ })
174
+ }
175
+ const text = channelTextFrom(config, CONSULTATION_CHANNELS.contactForm, site.locale)
176
+ const contactForm = emailNotices && site.adapterKey === true && text.enabled
177
+ return status(
178
+ 'live',
179
+ 'ok',
180
+ { magicLink: true, account: true, newLink: emailNotices, contactForm, links: true },
181
+ contactForm ? text : CHANNEL_TEXT_DISABLED,
182
+ )
183
+ }
@@ -0,0 +1,266 @@
1
+ /**
2
+ * The new-question form's submit (`/my-consultations/new`, KB channel `web`):
3
+ * the decision tree of the drhoubicka storefront's `account/dotazy.novy.tsx`
4
+ * action, framework-free. The page renders what `webAsk` offers; this checks
5
+ * what was posted and sends it — or says exactly why not, with what the form
6
+ * must show next.
7
+ *
8
+ * ## Consent belongs to the person, not to a question
9
+ *
10
+ * Given once, with a first question, it covers every later one until the
11
+ * reader withdraws it — or until the tenant publishes a consent text that asks
12
+ * everyone again. So the form showed one of three things (`legalMode`):
13
+ *
14
+ * - `consent`: the consent text and an UNTICKED box. Whoever consents,
15
+ * consents to the CURRENT text: the reader's status is fetched afresh and a
16
+ * stale version is refused before anything is created (`textChanged`, with
17
+ * the new text) — the KB would otherwise record a consent to a text that is
18
+ * no longer current (texts are append-only there; keeping them current is
19
+ * ours to do);
20
+ * - `notice`: the notice text, no box; the same freshness check;
21
+ * - `covered`: no text — the reader's consent covers new questions. Nothing
22
+ * is checked first (that would cost a KB call per submit); if the consent
23
+ * stopped covering meanwhile, the KB answers CONSENT_REQUIRED (or
24
+ * NOTICE_REQUIRED once the channel is in notice mode) and the form shows
25
+ * what applies now.
26
+ *
27
+ * ## A retry keeps the idempotency key
28
+ *
29
+ * A replay of the same question with the same `clientRequestId` comes back
30
+ * from the KB as the same thread (`duplicate`) — even when one attempt
31
+ * carried the consent and the other did not. A page that minted a new key for
32
+ * every render would turn a lost response (a timeout, a 5xx from a proxy) into
33
+ * a second thread. So every failure after the form was read carries the key
34
+ * for the NEXT attempt: the posted one (a fresh one when it was malformed and
35
+ * could not have stored anything). Only `conflict` gets a new key: under the
36
+ * posted one the KB already holds DIFFERENT content (the reader edited the
37
+ * text after a lost response), so the question most likely is stored already —
38
+ * the page says so and points to the list; whoever does not find it there
39
+ * sends it again, under the new key.
40
+ *
41
+ * Everything that can be decided without the KB comes first: an empty or too
42
+ * long question, a malformed field, an unticked box. Such an attempt costs
43
+ * neither a request nor quota. Every failure returns the typed text, so a
44
+ * plain form POST (no JavaScript) never loses it.
45
+ */
46
+
47
+ import type { WebAsk } from './channel-text'
48
+ import type { ConsultationUiCode } from './outcome'
49
+ import type { NewQuestion, ReaderConsultations } from './reader'
50
+ import {
51
+ CLIENT_REQUEST_ID_RE,
52
+ LEGAL_VERSION_RE,
53
+ LOCALE_RE,
54
+ NEW_QUESTION_BODY_MAX,
55
+ NEW_QUESTION_FIELDS,
56
+ READER_BODY_MAX,
57
+ newClientRequestId,
58
+ normalizeBody,
59
+ } from './routes'
60
+
61
+ /** What the form offers (`closed` is a 404, never a form). */
62
+ type ShownAsk = Exclude<WebAsk, { kind: 'closed' }>
63
+
64
+ export type NewQuestionResult =
65
+ | { ok: true; id: string; duplicate: boolean }
66
+ | {
67
+ ok: false
68
+ code: ConsultationUiCode
69
+ /** The reader's text back into the form (line breaks normalised, not trimmed). */
70
+ body: string
71
+ /**
72
+ * The key for the NEXT attempt: the posted one (a new one after
73
+ * `conflict`, or when the posted one was malformed). Absent only when
74
+ * the fields could not be read at all.
75
+ */
76
+ clientRequestId?: string
77
+ /** What the form shows now, whenever that is known (fresh from the KB, or what the page showed). */
78
+ ask?: ShownAsk
79
+ /** The reader confirmed (or saw) another text than the one that applies now: "we have updated the text". */
80
+ textChanged?: true
81
+ /**
82
+ * The reader sent without a consent because theirs covered new
83
+ * questions, and it no longer does (withdrawn in another window,
84
+ * lapsed): "your earlier consent is no longer valid". An active consent
85
+ * the tenant asks to renew is `textChanged` instead — "no longer valid"
86
+ * would be false.
87
+ */
88
+ consentNeeded?: true
89
+ /**
90
+ * The KB said the question needs a consent, and what applies now could
91
+ * not be read (an outage). The form stays as it was — but must not keep
92
+ * saying "your consent is valid".
93
+ */
94
+ consentUnknown?: true
95
+ }
96
+
97
+ type Failure = Extract<NewQuestionResult, { ok: false }>
98
+ type Extra = Omit<Failure, 'ok' | 'code' | 'body' | 'clientRequestId'>
99
+
100
+ type Legal = NewQuestion['legal']
101
+
102
+ /** Same text? (mode, version and locale — exactly what the KB records with the question) */
103
+ function sameText(a: Legal, b: Legal): boolean {
104
+ return !!a && !!b && a.mode === b.mode && a.version === b.version && a.locale === b.locale
105
+ }
106
+
107
+ type Parsed =
108
+ | { ok: true; body: string; clientRequestId: string; legalMode: 'covered' }
109
+ | { ok: true; body: string; clientRequestId: string; legalMode: 'consent' | 'notice'; version: string; locale: string; ticked: boolean }
110
+ | { ok: false; code: 'invalid' | 'tooLong' }
111
+
112
+ /**
113
+ * The posted fields → a checked submission, or why not. `tooLong` wins over
114
+ * other problems, so the reader learns what to fix in the text they wrote —
115
+ * except when the form's mode itself is unknown (not a form this page renders).
116
+ */
117
+ function parse(fields: Record<string, string | undefined>, max: number): Parsed {
118
+ const F = NEW_QUESTION_FIELDS
119
+ const legalMode = fields[F.legalMode]
120
+ if (legalMode !== 'consent' && legalMode !== 'notice' && legalMode !== 'covered') return { ok: false, code: 'invalid' }
121
+ const body = normalizeBody(fields[F.body], max)
122
+ if (!body.ok) return { ok: false, code: body.code }
123
+ const clientRequestId = fields[F.clientRequestId]
124
+ if (typeof clientRequestId !== 'string' || !CLIENT_REQUEST_ID_RE.test(clientRequestId)) return { ok: false, code: 'invalid' }
125
+ // A checkbox is posted only when ticked, with the value `on`; anything else is nonsense, not consent.
126
+ const consent = fields[F.consent]
127
+ if (consent !== undefined && consent !== 'on') return { ok: false, code: 'invalid' }
128
+ // No text was shown: a stray version is ignored, never compared.
129
+ if (legalMode === 'covered') return { ok: true, body: body.body, clientRequestId, legalMode }
130
+ const version = fields[F.legalVersion]
131
+ const locale = fields[F.legalLocale]
132
+ if (typeof version !== 'string' || !LEGAL_VERSION_RE.test(version)) return { ok: false, code: 'invalid' }
133
+ if (typeof locale !== 'string' || !LOCALE_RE.test(locale)) return { ok: false, code: 'invalid' }
134
+ return { ok: true, body: body.body, clientRequestId, legalMode, version, locale, ticked: consent === 'on' }
135
+ }
136
+
137
+ /**
138
+ * Checks and sends a new question. `fields` are the posted form fields
139
+ * (`NEW_QUESTION_FIELDS`), `locale` the page's language; `maxBody` the form's
140
+ * limit (default `NEW_QUESTION_BODY_MAX`; never above the KB's own). Never
141
+ * throws.
142
+ *
143
+ * On success redirect with 303 to `accountThreadPath(result.id)` — "back" and
144
+ * a reload then do not post again (and if they did, the same key answers with
145
+ * the same thread).
146
+ */
147
+ export async function submitNewConsultation(
148
+ reader: ReaderConsultations,
149
+ input: { locale: string; fields: Record<string, string | undefined> },
150
+ o: { maxBody?: number } = {},
151
+ ): Promise<NewQuestionResult> {
152
+ const fields = input?.fields && typeof input.fields === 'object' ? input.fields : {}
153
+ const locale = input?.locale
154
+ const max =
155
+ typeof o.maxBody === 'number' && Number.isFinite(o.maxBody)
156
+ ? Math.min(READER_BODY_MAX, Math.max(1, Math.floor(o.maxBody)))
157
+ : NEW_QUESTION_BODY_MAX
158
+
159
+ // The text back into the form after any failure: line breaks as the textarea counts them, the
160
+ // reader's own spacing kept (bounded like `normalizeBody`'s echo).
161
+ const typedRaw = fields[NEW_QUESTION_FIELDS.body]
162
+ const typedBody =
163
+ typeof typedRaw === 'string' ? typedRaw.replace(/\r\n?/g, '\n').slice(0, 2 * Math.max(max, READER_BODY_MAX)) : ''
164
+ // The key for the next attempt: the posted one when it is valid — a malformed one cannot have
165
+ // stored anything, so a fresh one.
166
+ const postedKey = fields[NEW_QUESTION_FIELDS.clientRequestId]
167
+ const retryKey = typeof postedKey === 'string' && CLIENT_REQUEST_ID_RE.test(postedKey) ? postedKey : newClientRequestId()
168
+
169
+ const fail = (code: ConsultationUiCode, extra: Extra = {}): NewQuestionResult => ({
170
+ ok: false,
171
+ code,
172
+ body: typedBody,
173
+ ...extra,
174
+ clientRequestId: retryKey,
175
+ })
176
+
177
+ try {
178
+ // Everything that needs no KB first.
179
+ const parsed = parse(fields, max)
180
+ if (!parsed.ok) return fail(parsed.code)
181
+ if (parsed.legalMode === 'consent' && !parsed.ticked) return fail('consent')
182
+
183
+ // What goes with the question (`legal`), and what the form offers after a failure (`shown`).
184
+ let legal: Legal
185
+ let shown: ShownAsk
186
+ if (parsed.legalMode === 'covered') {
187
+ // The page said "your consent is valid": no check first; the KB links the question to the
188
+ // reader's consent itself. The date is the page's to show — the action does not know it.
189
+ legal = null
190
+ shown = { kind: 'covered', givenAt: null }
191
+ } else {
192
+ // The page showed a text: the reader must have seen (and, for a consent, confirmed) the
193
+ // CURRENT one, in the page's language. Fresh, past the memo.
194
+ const status = await reader.webAsk(locale, { fresh: true })
195
+ if (!status.ok) return fail(status.code)
196
+ const now = status.value.ask
197
+ if (now.kind === 'closed') return fail('disabled')
198
+ if (now.kind === 'covered') {
199
+ // Covered meanwhile (given in another window — or this very question went through once and
200
+ // its answer was lost). A consent on top would be dropped by the KB; the question goes
201
+ // without it and under the SAME key, so a lost first attempt comes back as `duplicate`.
202
+ legal = null
203
+ shown = now
204
+ } else {
205
+ const current = { mode: now.legal.mode, version: now.legal.version, locale: now.legal.locale }
206
+ const posted = { mode: parsed.legalMode, version: parsed.version, locale: parsed.locale }
207
+ if (!sameText(current, posted)) {
208
+ // The key stays: had an earlier attempt with it gone through, the KB answers it as a
209
+ // duplicate (or `conflict`, "most likely stored") — never a second thread.
210
+ return fail('consent', { ask: now, textChanged: true })
211
+ }
212
+ legal = current
213
+ shown = now
214
+ }
215
+ }
216
+
217
+ const outcome = await reader.create({
218
+ body: parsed.body,
219
+ languageCode: locale,
220
+ legal,
221
+ clientRequestId: parsed.clientRequestId,
222
+ })
223
+ if (outcome.ok) return { ok: true, id: outcome.value.id, duplicate: outcome.value.duplicate }
224
+
225
+ if (outcome.code === 'consent') {
226
+ // The KB wants another legal text with the question than the one that went (CONSENT_* and
227
+ // NOTICE_*): the consent stopped covering (withdrawn in another window), the tenant asked
228
+ // everyone again, the channel switched to notice mode, or the text changed between the two
229
+ // calls. Show what applies now — the text and an unticked box, or the notice.
230
+ const again = await reader.webAsk(locale, { fresh: true })
231
+ if (!again.ok) {
232
+ // What applies now cannot be read. A text that was sent can be shown again (the reader
233
+ // confirms it, the KB decides). Without one the form stays as it was — the next attempt
234
+ // asks the KB — but it must not say "your consent is valid": the KB just said otherwise.
235
+ return legal
236
+ ? fail('consent', { ask: shown, textChanged: true })
237
+ : fail(again.code, { ask: shown, consentUnknown: true })
238
+ }
239
+ const now = again.value.ask
240
+ if (now.kind === 'closed') return fail('disabled')
241
+ // Covered again (given in another window): the next attempt goes through.
242
+ if (now.kind === 'covered') return fail('submit', { ask: now })
243
+ if (!legal) {
244
+ // "Your earlier consent is no longer valid" only for a reader who has none. One whose
245
+ // consent the tenant asks to renew, or whose channel switched to notice mode, gets "we
246
+ // have updated the text" — the page says below it why it asks again.
247
+ return fail(
248
+ 'consent',
249
+ now.kind === 'consent' && !now.renew ? { ask: now, consentNeeded: true } : { ask: now, textChanged: true },
250
+ )
251
+ }
252
+ // The plain "tick the box" only for a consent with the same text; the same notice refused by
253
+ // the KB is a contradiction — let the reader read it again and send (the KB decides).
254
+ return fail('consent', now.kind === 'consent' && sameText(legal, now.legal) ? { ask: now } : { ask: now, textChanged: true })
255
+ }
256
+ if (outcome.code === 'conflict') {
257
+ // The key holds a question with different content: "most likely stored already", and a NEW
258
+ // key — with the old one every further attempt would end the same way.
259
+ return { ok: false, code: 'conflict', body: typedBody, ask: shown, clientRequestId: newClientRequestId() }
260
+ }
261
+ return fail(outcome.code, { ask: shown })
262
+ } catch {
263
+ // Only a custom ReaderConsultations that throws gets here.
264
+ return fail('unavailable')
265
+ }
266
+ }
package/src/core/auth.ts CHANGED
@@ -27,7 +27,11 @@ export function decodeJwtUser(token: string): AuthUser | null {
27
27
  try {
28
28
  const parts = token.split('.')
29
29
  if (parts.length !== 3) return null
30
- const payload = JSON.parse(atob(parts[1]))
30
+ // base64url without padding, UTF-8 inside (RFC 7519): a bare atob threw on
31
+ // "-"/"_" and read non-ASCII names as Latin-1.
32
+ const b64 = parts[1]!.replace(/-/g, '+').replace(/_/g, '/')
33
+ const binary = atob(b64.padEnd(Math.ceil(b64.length / 4) * 4, '='))
34
+ const payload = JSON.parse(new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0))))
31
35
  return {
32
36
  id: payload.sub || payload.userId || '',
33
37
  email: payload.email || '',
@@ -9,6 +9,7 @@
9
9
  import type { KbClientConfig, Fetcher, TokenStorage } from './client-types'
10
10
  import type {
11
11
  Article,
12
+ ArticlePreview,
12
13
  ArticleWithTranslation,
13
14
  ArticleVersionContent,
14
15
  Tag,
@@ -101,6 +102,12 @@ export interface KbClient {
101
102
  tagMode?: 'all' | 'any'
102
103
  limit?: number
103
104
  offset?: number
105
+ /**
106
+ * Also list the published premium/partners articles the caller may not open but
107
+ * the tenant shows (its locked-article preview is title or excerpt), each flagged
108
+ * `locked` with its `access` tiers. Needs a KB API with the locked-article preview.
109
+ */
110
+ includeLocked?: boolean
104
111
  }): Promise<{
105
112
  accessibleKbArticles: { articles: Article[]; totalCount: number }
106
113
  }>
@@ -127,6 +134,23 @@ export interface KbClient {
127
134
  * extension), or null if the slug was never an alias. Backs the blog
128
135
  * 301-redirect after a rename.
129
136
  */
137
+ /**
138
+ * What a reader who may NOT open a published article sees of it: title,
139
+ * description, the tier that opens it and — when the tenant chose so — a plain-text
140
+ * excerpt. `{ articlePreview: null }` when the tenant hides locked articles, when the
141
+ * article is missing, internal-only or unpublished, and when the caller can open it
142
+ * (then `getWithTranslation` returns it). Call it after `getWithTranslation` came
143
+ * back null, to show a sign-in / upgrade gate instead of "not found".
144
+ */
145
+ getPreview(
146
+ filename: string,
147
+ languageCode: string,
148
+ ): Promise<{ articlePreview: ArticlePreview | null }>
149
+ /** `getPreview` by the article's IMMUTABLE id. */
150
+ getPreviewById(
151
+ id: string,
152
+ languageCode: string,
153
+ ): Promise<{ articlePreviewById: ArticlePreview | null }>
130
154
  resolveAlias(
131
155
  filename: string,
132
156
  ): Promise<{ articleAliasTarget: string | null }>
@@ -289,11 +313,18 @@ export function createKbClient(config: KbClientConfig): KbClient {
289
313
 
290
314
  return {
291
315
  articles: {
292
- list: (params) => exec(Q.ACCESSIBLE_ARTICLES, params),
316
+ list: (params) => {
317
+ const { includeLocked, ...variables } = params ?? {}
318
+ return exec(includeLocked ? Q.ACCESSIBLE_ARTICLES_WITH_LOCKED : Q.ACCESSIBLE_ARTICLES, variables)
319
+ },
293
320
  getWithTranslation: (filename, languageCode) =>
294
321
  exec(Q.ARTICLE_WITH_TRANSLATION, { filename, languageCode }),
295
322
  getWithTranslationById: (id, languageCode) =>
296
323
  exec(Q.ARTICLE_WITH_TRANSLATION_BY_ID, { id, languageCode }),
324
+ getPreview: (filename, languageCode) =>
325
+ exec(Q.ARTICLE_PREVIEW, { filename, languageCode }),
326
+ getPreviewById: (id, languageCode) =>
327
+ exec(Q.ARTICLE_PREVIEW_BY_ID, { id, languageCode }),
297
328
  resolveAlias: (filename) =>
298
329
  exec(Q.ARTICLE_ALIAS_TARGET, { filename }),
299
330
  getVersion: (versionId, opts) =>
@@ -42,6 +42,7 @@ export const CONSULTATION_ERROR_CODES = [
42
42
  'READER_PATH_MISSING',
43
43
  'TEXT_MISSING',
44
44
  'OPERATOR_MISSING',
45
+ 'MAIL_TRANSPORT_MISSING',
45
46
  'TEXT_VERSION_EXISTS',
46
47
  'CONTENT_ACCESS_ATTESTATION_REQUIRED',
47
48
  'AI_DRAFTS_DISABLED',
@@ -126,9 +127,11 @@ export class KbGraphQLError extends Error {
126
127
 
127
128
  constructor(errors: ReadonlyArray<RawGraphQLError | unknown>) {
128
129
  const entries = (errors.length > 0 ? errors : [undefined]).map(entryOf)
129
- super(entries[0].message)
130
+ // Never empty (the `[undefined]` fallback); `!` only for noUncheckedIndexedAccess consumers.
131
+ const first = entries[0]!
132
+ super(first.message)
130
133
  this.name = 'KbGraphQLError'
131
- this.code = entries[0].code
134
+ this.code = first.code
132
135
  this.errors = entries
133
136
  // Non-enumerable, so it stays out of serialised errors and of the .d.ts.
134
137
  Object.defineProperty(this, KB_GRAPHQL_ERROR_BRAND, { value: true })
package/src/core/index.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  // Types
2
2
  export type {
3
3
  Article,
4
+ ArticlePreview,
5
+ LockedPreviewMode,
4
6
  ArticleWithTranslation,
5
7
  ArticleVersionContent,
6
8
  MediaGeo,
@@ -188,6 +190,7 @@ export {
188
190
  toIsoDate,
189
191
  formatArticleDate,
190
192
  resolveArticleAccessLevel,
193
+ lockedRequiredAccess,
191
194
  buildArticleListItem,
192
195
  } from './view-model'
193
196
  export type { ArticleListItemVM, BuildArticleListItemOptions } from './view-model'