@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.
- package/dist/consultations/channel-text.d.ts +118 -0
- package/dist/consultations/channel-text.js +40 -0
- package/dist/consultations/index.d.ts +28 -0
- package/dist/consultations/index.js +60 -0
- package/dist/consultations/messages.cs.d.ts +149 -0
- package/dist/consultations/messages.cs.js +143 -0
- package/dist/consultations/messages.d.ts +34 -0
- package/dist/consultations/messages.en.d.ts +143 -0
- package/dist/consultations/messages.en.js +141 -0
- package/dist/consultations/messages.js +48 -0
- package/dist/consultations/outcome.d.ts +121 -0
- package/dist/consultations/outcome.js +161 -0
- package/dist/consultations/public-config.d.ts +71 -0
- package/dist/consultations/public-config.js +104 -0
- package/dist/consultations/reader.d.ts +83 -0
- package/dist/consultations/reader.js +128 -0
- package/dist/consultations/routes.d.ts +214 -0
- package/dist/consultations/routes.js +149 -0
- package/dist/consultations/server/client-ip.d.ts +50 -0
- package/dist/consultations/server/client-ip.js +44 -0
- package/dist/consultations/server/contact.d.ts +23 -0
- package/dist/consultations/server/contact.js +138 -0
- package/dist/consultations/server/context.d.ts +246 -0
- package/dist/consultations/server/context.js +152 -0
- package/dist/consultations/server/cookie.d.ts +60 -0
- package/dist/consultations/server/cookie.js +57 -0
- package/dist/consultations/server/env.d.ts +20 -0
- package/dist/consultations/server/env.js +35 -0
- package/dist/consultations/server/http.d.ts +59 -0
- package/dist/consultations/server/http.js +64 -0
- package/dist/consultations/server/index.d.ts +37 -0
- package/dist/consultations/server/index.js +19 -0
- package/dist/consultations/server/origin.d.ts +39 -0
- package/dist/consultations/server/origin.js +31 -0
- package/dist/consultations/server/server.d.ts +106 -0
- package/dist/consultations/server/server.js +122 -0
- package/dist/consultations/server/session.d.ts +38 -0
- package/dist/consultations/server/session.js +210 -0
- package/dist/consultations/server/transport.d.ts +69 -0
- package/dist/consultations/server/transport.js +117 -0
- package/dist/consultations/server/turnstile.d.ts +44 -0
- package/dist/consultations/server/turnstile.js +31 -0
- package/dist/consultations/site.d.ts +100 -0
- package/dist/consultations/site.js +60 -0
- package/dist/consultations/submit-new.d.ts +103 -0
- package/dist/consultations/submit-new.js +72 -0
- package/dist/core/auth.d.ts +2 -2
- package/dist/core/auth.js +21 -21
- package/dist/core/client.d.ts +25 -4
- package/dist/core/client.js +35 -30
- package/dist/core/consultation-adapter.d.ts +2 -2
- package/dist/core/consultations.d.ts +1 -1
- package/dist/core/errors.d.ts +1 -1
- package/dist/core/errors.js +16 -15
- package/dist/core/index.d.ts +31 -31
- package/dist/core/index.js +35 -34
- package/dist/core/markdown.d.ts +1 -1
- package/dist/core/queries.d.ts +4 -1
- package/dist/core/queries.js +131 -86
- package/dist/core/review/format.d.ts +1 -1
- package/dist/core/review/index.d.ts +2 -2
- package/dist/core/seo.d.ts +1 -1
- package/dist/core/translations/cs.json.js +1 -1
- package/dist/core/translations/en.json.js +1 -1
- package/dist/core/types.d.ts +50 -1
- package/dist/core/view-model.d.ts +12 -2
- package/dist/core/view-model.js +40 -34
- package/dist/{packages/tripmap-core/node_modules → node_modules}/pmtiles/dist/esm/index.js +1 -1
- package/dist/nuxt/composables/useAsyncKb.d.ts +4 -4
- package/dist/nuxt/index.d.ts +1 -1
- package/dist/packages/tripmap-core/dist/engine.js +3 -3
- package/dist/packages/tripmap-core/dist/generated/maplibre-worker.bundle.js +1 -1
- package/dist/react/KbMdxContent.d.ts +1 -1
- package/dist/react/context.d.ts +4 -4
- package/dist/react/hooks/useImageRenderer.d.ts +1 -1
- package/dist/react/hooks/useKbClient.d.ts +1 -1
- package/dist/react/hooks/useKbContext.d.ts +1 -1
- package/dist/react/hooks/useKbI18n.d.ts +1 -1
- package/dist/react/hooks/useKbLanguage.d.ts +1 -1
- package/dist/react/hooks/useKbSearch.d.ts +1 -1
- package/dist/react/hooks/useMdxContent.d.ts +1 -1
- package/dist/react/index.d.ts +15 -15
- package/dist/react/provider.d.ts +2 -2
- package/dist/react/server/index.d.ts +2 -2
- package/dist/vue/components/KbAccessGate.vue.d.ts +4 -1
- package/dist/vue/components/KbAccessGate.vue.js +42 -32
- package/dist/vue/components/KbArticleCard.vue.d.ts +3 -1
- package/dist/vue/components/KbArticleCard.vue.js +67 -39
- package/dist/vue/composables/useArticles.d.ts +1 -1
- package/dist/vue/composables/useImageRenderer.d.ts +1 -1
- package/dist/vue/composables/useKbAuth.d.ts +1 -1
- package/dist/vue/composables/useKbClient.d.ts +1 -1
- package/dist/vue/composables/useKbComments.d.ts +1 -1
- package/dist/vue/composables/useKbI18n.d.ts +1 -1
- package/dist/vue/composables/useKbLanguage.d.ts +1 -1
- package/dist/vue/composables/useNavigation.d.ts +1 -1
- package/dist/vue/composables/useSearch.d.ts +1 -1
- package/dist/vue/composables/useTags.d.ts +1 -1
- package/dist/vue/index.d.ts +19 -19
- package/dist/vue/plugin.d.ts +4 -4
- package/package.json +15 -5
- package/src/consultations/channel-text.ts +168 -0
- package/src/consultations/index.ts +87 -0
- package/src/consultations/messages.cs.ts +175 -0
- package/src/consultations/messages.en.ts +171 -0
- package/src/consultations/messages.ts +91 -0
- package/src/consultations/outcome.ts +278 -0
- package/src/consultations/public-config.ts +246 -0
- package/src/consultations/reader.ts +281 -0
- package/src/consultations/routes.ts +341 -0
- package/src/consultations/server/client-ip.ts +106 -0
- package/src/consultations/server/contact.ts +267 -0
- package/src/consultations/server/context.ts +403 -0
- package/src/consultations/server/cookie.ts +129 -0
- package/src/consultations/server/env.ts +66 -0
- package/src/consultations/server/http.ts +148 -0
- package/src/consultations/server/index.ts +55 -0
- package/src/consultations/server/origin.ts +71 -0
- package/src/consultations/server/server.ts +322 -0
- package/src/consultations/server/session.ts +414 -0
- package/src/consultations/server/transport.ts +196 -0
- package/src/consultations/server/turnstile.ts +98 -0
- package/src/consultations/site.ts +183 -0
- package/src/consultations/submit-new.ts +266 -0
- package/src/core/auth.ts +5 -1
- package/src/core/client.ts +32 -1
- package/src/core/errors.ts +5 -2
- package/src/core/index.ts +3 -0
- package/src/core/queries.ts +56 -0
- package/src/core/translations/cs.json +2 -1
- package/src/core/translations/en.json +2 -1
- package/src/core/types.ts +51 -0
- package/src/core/view-model.ts +18 -0
- package/src/vue/components/KbAccessGate.vue +14 -1
- package/src/vue/components/KbArticleCard.vue +25 -0
- /package/dist/{packages/tripmap-core/node_modules → node_modules}/maplibre-gl/dist/maplibre-gl-shared.js +0 -0
- /package/dist/{packages/tripmap-core/node_modules → node_modules}/maplibre-gl/dist/maplibre-gl.js +0 -0
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The anonymous contact form (`/contact`, KB channel `contact_form`): the
|
|
3
|
+
* reader's question becomes a thread in the KB through the blog's scoped
|
|
4
|
+
* adapter key (`consultations:ingest:contact_form`, no ref prefix). The reader
|
|
5
|
+
* gets the answer by e-mail with a magic link — so the form exists only while
|
|
6
|
+
* the KB sends e-mail notices (`emailNotices`) and the channel has a usable
|
|
7
|
+
* legal text in the page's language.
|
|
8
|
+
*
|
|
9
|
+
* Order: 1. method, 2. the gate, 3. Origin, 4. the form — honeypot (a filled
|
|
10
|
+
* one gets the ordinary answer and nothing is sent), Turnstile, the fields, the
|
|
11
|
+
* legal text the form showed (a consent box must be ticked, and in consent
|
|
12
|
+
* mode the text must still be the current one), 5. the ingest.
|
|
13
|
+
*
|
|
14
|
+
* Idempotency: the page renders a `messageId` (`blog-contact:<uuid>`) and
|
|
15
|
+
* posts it back. It is the ingest's `externalMessageId`, so a retry after a
|
|
16
|
+
* lost answer lands as a duplicate instead of a second thread: every failure
|
|
17
|
+
* hands back the SAME id, except `conflict` (the first attempt went through
|
|
18
|
+
* with other content), which hands back a new one.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { ConsultationIngestInput } from '../../core/types'
|
|
22
|
+
import { isConsultationAdapterError } from '../../core/consultation-adapter'
|
|
23
|
+
import {
|
|
24
|
+
CONTACT_FIELDS,
|
|
25
|
+
CONTACT_NAME_MAX,
|
|
26
|
+
LEGAL_VERSION_RE,
|
|
27
|
+
LOCALE_RE,
|
|
28
|
+
channelTextFrom,
|
|
29
|
+
consultationOutcomeOf,
|
|
30
|
+
normalizeBody,
|
|
31
|
+
type ConsultationUiCode,
|
|
32
|
+
type ShownLegalText,
|
|
33
|
+
} from '../index'
|
|
34
|
+
import {
|
|
35
|
+
CONTACT_FORM_CHANNEL,
|
|
36
|
+
GATE_RETRY_AFTER_S,
|
|
37
|
+
GET_ONLY,
|
|
38
|
+
POST_ONLY,
|
|
39
|
+
fieldOf,
|
|
40
|
+
freshKey,
|
|
41
|
+
gate,
|
|
42
|
+
isGet,
|
|
43
|
+
isPost,
|
|
44
|
+
logFailure,
|
|
45
|
+
readForm,
|
|
46
|
+
readerIp,
|
|
47
|
+
respond,
|
|
48
|
+
statusOf,
|
|
49
|
+
withRetry,
|
|
50
|
+
type ContactPageState,
|
|
51
|
+
type ContactResult,
|
|
52
|
+
type ServerContext,
|
|
53
|
+
} from './context'
|
|
54
|
+
import type { ConsultationHttp, ConsultationResponse } from './http'
|
|
55
|
+
import { isAllowedOrigin } from './origin'
|
|
56
|
+
import { isEmailAddress } from './session'
|
|
57
|
+
import { verifyTurnstile } from './turnstile'
|
|
58
|
+
|
|
59
|
+
/** The idempotency key of one contact form: `blog-contact:` + a request id. */
|
|
60
|
+
const MESSAGE_ID_PREFIX = 'blog-contact:'
|
|
61
|
+
/** The prefix plus a request id (`CLIENT_REQUEST_ID_RE`). */
|
|
62
|
+
const MESSAGE_ID_RE = /^blog-contact:[A-Za-z0-9._:-]{1,64}$/
|
|
63
|
+
|
|
64
|
+
/** The KB wants another legal text with the question than the one that went with it. */
|
|
65
|
+
const LEGAL_CODES: ReadonlySet<string> = new Set([
|
|
66
|
+
'NOTICE_REQUIRED',
|
|
67
|
+
'NOTICE_VERSION_UNKNOWN',
|
|
68
|
+
'CONSENT_REQUIRED',
|
|
69
|
+
'CONSENT_VERSION_UNKNOWN',
|
|
70
|
+
])
|
|
71
|
+
|
|
72
|
+
type Shown = { mode: 'notice' | 'consent'; version: string; locale: string }
|
|
73
|
+
|
|
74
|
+
function newMessageId(ctx: ServerContext): string {
|
|
75
|
+
return `${MESSAGE_ID_PREFIX}${freshKey(ctx)}`
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function sameText(current: ShownLegalText, shown: Shown): boolean {
|
|
79
|
+
return current.mode === shown.mode && current.version === shown.version && current.locale === shown.locale
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The contact form's text as the KB has it NOW (a fresh load that also refreshes the memo). */
|
|
83
|
+
async function currentText(
|
|
84
|
+
ctx: ServerContext,
|
|
85
|
+
locale: string,
|
|
86
|
+
): Promise<{ ok: true; text: ShownLegalText } | { ok: false; code: ConsultationUiCode; retryAfterS?: number }> {
|
|
87
|
+
const fresh = await ctx.publicConfig.get(locale, { fresh: true })
|
|
88
|
+
if (!fresh.ok) return { ok: false, code: 'unavailable', retryAfterS: fresh.retryAfterS ?? GATE_RETRY_AFTER_S }
|
|
89
|
+
const text = channelTextFrom(fresh.value, CONTACT_FORM_CHANNEL, locale)
|
|
90
|
+
return text.enabled ? { ok: true, text } : { ok: false, code: 'disabled' }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ───────────────────────── GET /contact ─────────────────────────
|
|
94
|
+
|
|
95
|
+
export async function loadContact(
|
|
96
|
+
ctx: ServerContext,
|
|
97
|
+
http: ConsultationHttp,
|
|
98
|
+
locale: string,
|
|
99
|
+
): Promise<ConsultationResponse<ContactPageState>> {
|
|
100
|
+
const error = (code: ConsultationUiCode, retryAfterS?: number, allow?: string) =>
|
|
101
|
+
respond<ContactPageState>(statusOf(code), withRetry({ state: 'error' as const, error: code }, retryAfterS), {
|
|
102
|
+
retryAfterS,
|
|
103
|
+
allow,
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
if (!isGet(http)) return error('method', undefined, GET_ONLY)
|
|
107
|
+
const g = await gate(ctx, 'contactForm', locale)
|
|
108
|
+
if (!g.ok) return error(g.code, g.retryAfterS)
|
|
109
|
+
const text = g.status.contactText
|
|
110
|
+
if (!text.enabled) return error('disabled')
|
|
111
|
+
return respond<ContactPageState>(200, {
|
|
112
|
+
state: 'open',
|
|
113
|
+
text,
|
|
114
|
+
messageId: newMessageId(ctx),
|
|
115
|
+
turnstileSiteKey: ctx.turnstile?.siteKey ?? null,
|
|
116
|
+
maxMessage: ctx.contactMessageMax,
|
|
117
|
+
})
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ───────────────────────── POST /contact ─────────────────────────
|
|
121
|
+
|
|
122
|
+
export async function handleContact(
|
|
123
|
+
ctx: ServerContext,
|
|
124
|
+
http: ConsultationHttp,
|
|
125
|
+
locale: string,
|
|
126
|
+
): Promise<ConsultationResponse<ContactResult>> {
|
|
127
|
+
// The key handed back with a failure: the posted one once it is known to be well-formed.
|
|
128
|
+
let messageId: string | null = null
|
|
129
|
+
const fail = (
|
|
130
|
+
code: ConsultationUiCode,
|
|
131
|
+
o: { retryAfterS?: number; allow?: string; text?: ShownLegalText; messageId?: string } = {},
|
|
132
|
+
) =>
|
|
133
|
+
respond<ContactResult>(
|
|
134
|
+
statusOf(code),
|
|
135
|
+
withRetry(
|
|
136
|
+
{
|
|
137
|
+
done: false as const,
|
|
138
|
+
error: code,
|
|
139
|
+
messageId: o.messageId ?? messageId ?? newMessageId(ctx),
|
|
140
|
+
...(o.text ? { textChanged: true as const, text: o.text } : {}),
|
|
141
|
+
},
|
|
142
|
+
o.retryAfterS,
|
|
143
|
+
),
|
|
144
|
+
{ retryAfterS: o.retryAfterS, allow: o.allow },
|
|
145
|
+
)
|
|
146
|
+
const stored = () => respond<ContactResult>(200, { done: 'stored' })
|
|
147
|
+
|
|
148
|
+
if (!isPost(http)) return fail('method', { allow: POST_ONLY })
|
|
149
|
+
const g = await gate(ctx, 'contactForm', locale)
|
|
150
|
+
if (!g.ok) return fail(g.code, { retryAfterS: g.retryAfterS })
|
|
151
|
+
if (!isAllowedOrigin(http, ctx.origins)) return fail('origin')
|
|
152
|
+
|
|
153
|
+
const fields = await readForm(http)
|
|
154
|
+
if (!fields) return fail('invalid')
|
|
155
|
+
const posted = fieldOf(fields, CONTACT_FIELDS.messageId)
|
|
156
|
+
if (typeof posted === 'string' && MESSAGE_ID_RE.test(posted)) messageId = posted
|
|
157
|
+
|
|
158
|
+
// A filled honeypot: the ordinary answer, and nothing is sent anywhere.
|
|
159
|
+
const honeypot = fieldOf(fields, CONTACT_FIELDS.honeypot)
|
|
160
|
+
if (typeof honeypot === 'string' && honeypot !== '') return stored()
|
|
161
|
+
|
|
162
|
+
const clientIp = readerIp(ctx, http)
|
|
163
|
+
if (ctx.turnstile) {
|
|
164
|
+
const verdict = await verifyTurnstile(fieldOf(fields, CONTACT_FIELDS.turnstile), {
|
|
165
|
+
secret: ctx.turnstile.secretKey,
|
|
166
|
+
remoteIp: clientIp,
|
|
167
|
+
expectedAction: ctx.turnstile.action,
|
|
168
|
+
fetch: ctx.fetch(),
|
|
169
|
+
})
|
|
170
|
+
if (!verdict.ok) return fail('captcha')
|
|
171
|
+
if (verdict.status === 'unavailable') {
|
|
172
|
+
logFailure(ctx, 'turnstile', { code: 'unavailable', kbCode: null, status: null })
|
|
173
|
+
if (!ctx.turnstile.failOpen) return fail('unavailable', { retryAfterS: GATE_RETRY_AFTER_S })
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Without its key a question cannot be retried safely: the page must render the form again.
|
|
178
|
+
if (messageId === null) return fail('invalid')
|
|
179
|
+
const name = (fieldOf(fields, CONTACT_FIELDS.name) ?? '').trim()
|
|
180
|
+
if (name.length > CONTACT_NAME_MAX) return fail('invalid')
|
|
181
|
+
const email = (fieldOf(fields, CONTACT_FIELDS.email) ?? '').trim()
|
|
182
|
+
if (!isEmailAddress(email)) return fail('invalid')
|
|
183
|
+
const message = normalizeBody(fieldOf(fields, CONTACT_FIELDS.message), ctx.contactMessageMax)
|
|
184
|
+
if (!message.ok) return fail(message.code)
|
|
185
|
+
|
|
186
|
+
// The legal text the form SHOWED goes with the question, exactly as shown.
|
|
187
|
+
const mode = fieldOf(fields, CONTACT_FIELDS.legalMode)
|
|
188
|
+
const version = fieldOf(fields, CONTACT_FIELDS.legalVersion)
|
|
189
|
+
const legalLocale = fieldOf(fields, CONTACT_FIELDS.legalLocale)
|
|
190
|
+
if (
|
|
191
|
+
(mode !== 'notice' && mode !== 'consent') ||
|
|
192
|
+
typeof version !== 'string' ||
|
|
193
|
+
!LEGAL_VERSION_RE.test(version) ||
|
|
194
|
+
typeof legalLocale !== 'string' ||
|
|
195
|
+
!LOCALE_RE.test(legalLocale)
|
|
196
|
+
) {
|
|
197
|
+
return fail('invalid')
|
|
198
|
+
}
|
|
199
|
+
const shown: Shown = { mode, version, locale: legalLocale }
|
|
200
|
+
if (mode === 'consent') {
|
|
201
|
+
if (fieldOf(fields, CONTACT_FIELDS.consent) !== 'on') return fail('consent')
|
|
202
|
+
// A consent is informed only for the text the reader read: it must still be the current one.
|
|
203
|
+
const current = await currentText(ctx, locale)
|
|
204
|
+
if (!current.ok) return fail(current.code, { retryAfterS: current.retryAfterS })
|
|
205
|
+
if (!sameText(current.text, shown)) return fail('consent', { text: current.text })
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const adapter = ctx.transport && ctx.adapterKey ? ctx.transport.adapter(ctx.adapterKey) : null
|
|
209
|
+
if (!adapter) {
|
|
210
|
+
logFailure(ctx, 'contactIngest', { code: 'unavailable', kbCode: null, status: null })
|
|
211
|
+
return fail('unavailable', { retryAfterS: GATE_RETRY_AFTER_S })
|
|
212
|
+
}
|
|
213
|
+
const legal = { version, locale: legalLocale }
|
|
214
|
+
const input: ConsultationIngestInput = {
|
|
215
|
+
channel: CONTACT_FORM_CHANNEL,
|
|
216
|
+
externalMessageId: messageId,
|
|
217
|
+
body: message.body,
|
|
218
|
+
languageCode: locale,
|
|
219
|
+
newThread: {
|
|
220
|
+
owner: { email },
|
|
221
|
+
...(name !== '' ? { displayName: name } : {}),
|
|
222
|
+
externalThreadRef: messageId,
|
|
223
|
+
...(mode === 'consent'
|
|
224
|
+
? { consent: { ...legal, givenAt: new Date(ctx.now()).toISOString() } }
|
|
225
|
+
: { notice: legal }),
|
|
226
|
+
},
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
try {
|
|
230
|
+
await adapter.client.ingest(input, clientIp ? { clientIp } : undefined)
|
|
231
|
+
return stored()
|
|
232
|
+
} catch (err) {
|
|
233
|
+
const retryAfterS = adapter.retryAfterS() ?? undefined
|
|
234
|
+
if (!isConsultationAdapterError(err)) {
|
|
235
|
+
logFailure(ctx, 'contactIngest', { code: 'unavailable', kbCode: null, status: null })
|
|
236
|
+
return fail('unavailable', { retryAfterS })
|
|
237
|
+
}
|
|
238
|
+
const code = err.code
|
|
239
|
+
const status = err.status === 0 ? null : err.status
|
|
240
|
+
if (code === 'QUOTA_EXCEEDED') return fail('quota', { retryAfterS })
|
|
241
|
+
// A revoked or wrong adapter key: the reader cannot fix that by signing in.
|
|
242
|
+
if (status === 401 || status === 403 || code === 'UNAUTHENTICATED' || code === 'FORBIDDEN') {
|
|
243
|
+
logFailure(ctx, 'contactIngest', { code: 'unavailable', kbCode: code, status })
|
|
244
|
+
return fail('unavailable', { retryAfterS })
|
|
245
|
+
}
|
|
246
|
+
// The same key with other content: the first attempt most likely went through. A NEW key.
|
|
247
|
+
if (code === 'IDEMPOTENCY_CONFLICT') return fail('conflict', { messageId: newMessageId(ctx) })
|
|
248
|
+
if (code !== null && LEGAL_CODES.has(code)) {
|
|
249
|
+
const current = await currentText(ctx, locale)
|
|
250
|
+
if (!current.ok) return fail(current.code, { retryAfterS: current.retryAfterS })
|
|
251
|
+
if (!sameText(current.text, shown)) return fail('consent', { text: current.text })
|
|
252
|
+
// The KB refused the very text it publishes: nothing the reader can change.
|
|
253
|
+
logFailure(ctx, 'contactIngest', { code: 'submit', kbCode: code, status })
|
|
254
|
+
return fail('submit')
|
|
255
|
+
}
|
|
256
|
+
if (code !== null) {
|
|
257
|
+
const ui = consultationOutcomeOf(code)
|
|
258
|
+
const outcome: ConsultationUiCode = ui === 'auth' ? 'unavailable' : ui
|
|
259
|
+
logFailure(ctx, 'contactIngest', { code: outcome, kbCode: code, status })
|
|
260
|
+
return fail(outcome, { retryAfterS: outcome === 'unavailable' ? retryAfterS : undefined })
|
|
261
|
+
}
|
|
262
|
+
// No code: network, timeout, HTTP 5xx / 429 without one, a malformed answer. The SAME key:
|
|
263
|
+
// a retry of a question the KB did store lands as a duplicate.
|
|
264
|
+
logFailure(ctx, 'contactIngest', { code: 'unavailable', kbCode: null, status })
|
|
265
|
+
return fail('unavailable', { retryAfterS })
|
|
266
|
+
}
|
|
267
|
+
}
|
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What every consultation handler shares: the resolved configuration, the
|
|
3
|
+
* gate, the response builders and the log hygiene. Internal to the server
|
|
4
|
+
* entry — the public surface is `createConsultationServer`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { KbClient } from '../../core/client'
|
|
8
|
+
import type { ReaderConsultation } from '../../core/types'
|
|
9
|
+
import {
|
|
10
|
+
CLIENT_REQUEST_ID_RE,
|
|
11
|
+
CONSULTATION_RESPONSE_HEADERS,
|
|
12
|
+
CONSULTATION_UI_HTTP_STATUS,
|
|
13
|
+
ConsultationTransportError,
|
|
14
|
+
LOCALE_RE,
|
|
15
|
+
consultationFailureOf,
|
|
16
|
+
newClientRequestId,
|
|
17
|
+
readerSiteStatus,
|
|
18
|
+
type ChannelText,
|
|
19
|
+
type ConsultationLogger,
|
|
20
|
+
type ConsultationOutcome,
|
|
21
|
+
type ConsultationSiteStatus,
|
|
22
|
+
type ConsultationUiCode,
|
|
23
|
+
type PublicConfigCache,
|
|
24
|
+
type ShownLegalText,
|
|
25
|
+
} from '../index'
|
|
26
|
+
import { isKbGraphQLError } from '../../core/errors'
|
|
27
|
+
import type { ConsultationPublicConfig } from '../../core/types'
|
|
28
|
+
import { clientIpFrom } from './client-ip'
|
|
29
|
+
import type { ConsultationHttp, ConsultationResponse } from './http'
|
|
30
|
+
import type { KbTransport } from './transport'
|
|
31
|
+
|
|
32
|
+
// ───────────────────────── public result shapes ─────────────────────────
|
|
33
|
+
|
|
34
|
+
/** A page the gate decides on (`ConsultationSiteStatus.features`; `links` is for menus and footers, never a gate). */
|
|
35
|
+
export type ConsultationFeature = Exclude<keyof ConsultationSiteStatus['features'], 'links'>
|
|
36
|
+
|
|
37
|
+
/** What a page loader answers when it only needs the gate: 200, 404 (dark) or 503 (the KB could not be asked). */
|
|
38
|
+
export interface ConsultationPageGate {
|
|
39
|
+
status: 200 | 404 | 503
|
|
40
|
+
headers: Record<string, string>
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** `loadSession` — the `/consultation` page. */
|
|
44
|
+
export type SessionPageState =
|
|
45
|
+
/** The thread the session opens; `clientRequestId` goes into the reply form as a hidden field. */
|
|
46
|
+
| { state: 'open'; consultation: ReaderConsultation; clientRequestId: string }
|
|
47
|
+
/** No session cookie: "open the link from your e-mail". No KB call was made. */
|
|
48
|
+
| { state: 'none' }
|
|
49
|
+
/** The KB no longer knows the session (the cookie was cleared): offer a new link. */
|
|
50
|
+
| { state: 'expired' }
|
|
51
|
+
| { state: 'error'; error: ConsultationUiCode; retryAfterS?: number }
|
|
52
|
+
|
|
53
|
+
/** `handleAccess` — `POST /api/consultations/access`. The session travels only in `Set-Cookie`. */
|
|
54
|
+
export type AccessResult = { success: true } | { success: false; error: ConsultationUiCode; retryAfterS?: number }
|
|
55
|
+
|
|
56
|
+
/** `handleSessionAction` — `POST /consultation` (`intent` = `reply` | `erase` | `logout`). */
|
|
57
|
+
export type SessionActionResult =
|
|
58
|
+
| { success: true; done: 'posted' | 'erased' | 'loggedOut' }
|
|
59
|
+
| {
|
|
60
|
+
success: false
|
|
61
|
+
error: ConsultationUiCode
|
|
62
|
+
retryAfterS?: number
|
|
63
|
+
/** A failed `reply`: the reader's own text back, for the form (line breaks normalised). */
|
|
64
|
+
body?: string
|
|
65
|
+
/** A failed `reply`: the key to post with the retry — the same one, or a NEW one after `conflict`. */
|
|
66
|
+
clientRequestId?: string
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* `handleForget` — `POST /api/consultations/forget`: drop a session cookie the
|
|
71
|
+
* KB no longer accepts (a Next Server Component can render "expired" but cannot
|
|
72
|
+
* clear the cookie). `null` body: 204 when there was no session, 200 when the
|
|
73
|
+
* session is still valid (the cookie is left alone — a fresh session opened in
|
|
74
|
+
* another tab is never closed from here). 410 after clearing an expired one.
|
|
75
|
+
* Never any thread data.
|
|
76
|
+
*/
|
|
77
|
+
export type ForgetResult = null | { success: false; error: ConsultationUiCode; retryAfterS?: number }
|
|
78
|
+
|
|
79
|
+
/** `handleAttach` — `POST /api/consultations/attach`. */
|
|
80
|
+
export type AttachResult =
|
|
81
|
+
| { success: true; done: 'attached' }
|
|
82
|
+
| { success: false; error: ConsultationUiCode; retryAfterS?: number }
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* `handleRequestLink` — `POST /consultation/new-link`. `done` whether or not
|
|
86
|
+
* the address ever wrote in and whether or not the KB answered: a different
|
|
87
|
+
* answer would tell a stranger who wrote to the team.
|
|
88
|
+
*/
|
|
89
|
+
export type RequestLinkResult = { done: true } | { done: false; error: ConsultationUiCode; retryAfterS?: number }
|
|
90
|
+
|
|
91
|
+
/** `loadContact` — the `/contact` page. */
|
|
92
|
+
export type ContactPageState =
|
|
93
|
+
| {
|
|
94
|
+
state: 'open'
|
|
95
|
+
/** The legal text the form shows (a consent text comes with an UNTICKED box). */
|
|
96
|
+
text: ShownLegalText
|
|
97
|
+
/** The idempotency key of this form; a hidden field, posted back as `messageId`. */
|
|
98
|
+
messageId: string
|
|
99
|
+
/** Render the Turnstile widget when set (`action` = the server's Turnstile action). */
|
|
100
|
+
turnstileSiteKey: string | null
|
|
101
|
+
/** The message field's `maxLength`. */
|
|
102
|
+
maxMessage: number
|
|
103
|
+
}
|
|
104
|
+
| { state: 'error'; error: ConsultationUiCode; retryAfterS?: number }
|
|
105
|
+
|
|
106
|
+
/** `handleContact` — `POST /contact`. */
|
|
107
|
+
export type ContactResult =
|
|
108
|
+
| { done: 'stored' }
|
|
109
|
+
| {
|
|
110
|
+
done: false
|
|
111
|
+
error: ConsultationUiCode
|
|
112
|
+
/**
|
|
113
|
+
* The key to post with the next attempt: the SAME one after an outage (a
|
|
114
|
+
* retry of a question the KB did store lands as a duplicate), a NEW one
|
|
115
|
+
* after `conflict`.
|
|
116
|
+
*/
|
|
117
|
+
messageId: string
|
|
118
|
+
/** The legal text changed since the form was rendered: show `text` (a consent box unticked again). */
|
|
119
|
+
textChanged?: true
|
|
120
|
+
text?: ShownLegalText
|
|
121
|
+
retryAfterS?: number
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ───────────────────────── context ─────────────────────────
|
|
125
|
+
|
|
126
|
+
export interface ResolvedTurnstile {
|
|
127
|
+
siteKey: string
|
|
128
|
+
secretKey: string
|
|
129
|
+
action: string
|
|
130
|
+
failOpen: boolean
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export interface ServerContext {
|
|
134
|
+
/** Null when `kbApiUrl` is unusable: every KB call is then an outage. */
|
|
135
|
+
transport: KbTransport | null
|
|
136
|
+
siteUrls: string[]
|
|
137
|
+
/** The Origin allowlist: the site URLs' origins plus the configured extras. */
|
|
138
|
+
origins: readonly string[]
|
|
139
|
+
proxyKey: string | null
|
|
140
|
+
adapterKey: string | null
|
|
141
|
+
clientIpHeader: string
|
|
142
|
+
cookieName: string
|
|
143
|
+
turnstile: ResolvedTurnstile | null
|
|
144
|
+
readerToken: (http: ConsultationHttp) => string | null
|
|
145
|
+
contactMessageMax: number
|
|
146
|
+
timeoutMs: number
|
|
147
|
+
fetch: () => typeof fetch
|
|
148
|
+
now: () => number
|
|
149
|
+
randomId: () => string
|
|
150
|
+
publicConfig: PublicConfigCache
|
|
151
|
+
logger: ConsultationLogger
|
|
152
|
+
/** One console warning per server instance and `key` — configuration problems, never reader data. */
|
|
153
|
+
warnOnce(key: string, message: string): void
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The locale the gate asks the KB in when a handler has no page locale (the gate reads no text). */
|
|
157
|
+
export const GATE_LOCALE = 'en'
|
|
158
|
+
|
|
159
|
+
/** How long a page that could not ask the KB tells the client to wait. */
|
|
160
|
+
export const GATE_RETRY_AFTER_S = 30
|
|
161
|
+
|
|
162
|
+
/** The KB channel of the contact form. */
|
|
163
|
+
export const CONTACT_FORM_CHANNEL = 'contact_form'
|
|
164
|
+
|
|
165
|
+
/** "Show no text" (a feature that is off). */
|
|
166
|
+
export const NO_TEXT: ChannelText = Object.freeze({ enabled: false })
|
|
167
|
+
|
|
168
|
+
/** The outcomes operators see in the log: outages and the unexpected. Everything else is an ordinary reader state. */
|
|
169
|
+
export function isLoggedOutcome(code: ConsultationUiCode): boolean {
|
|
170
|
+
return code === 'unavailable' || code === 'submit'
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** A ConsultationTransportError, also one from another copy of the SDK. */
|
|
174
|
+
export function isTransportError(err: unknown): err is ConsultationTransportError {
|
|
175
|
+
return (
|
|
176
|
+
err instanceof ConsultationTransportError ||
|
|
177
|
+
(err instanceof Error && err.name === 'ConsultationTransportError' && 'retryAfterS' in err)
|
|
178
|
+
)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** A KB code as it may appear in a log line; anything else (a proxy's text, a body) is `other`. */
|
|
182
|
+
const LOGGABLE_CODE_RE = /^[A-Z][A-Z0-9_]{0,63}$/
|
|
183
|
+
|
|
184
|
+
/** The default log line: `[consultations] op=… outcome=… kb_code=… status=…`. */
|
|
185
|
+
export const defaultConsultationLogger: ConsultationLogger = (e) => {
|
|
186
|
+
console.warn(
|
|
187
|
+
`[consultations] op=${e.op} outcome=${e.outcome} kb_code=${e.kbCode ?? 'none'} status=${e.status ?? 'none'}`,
|
|
188
|
+
)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Wraps a logger: only outages and the unexpected (`unavailable`, `submit`)
|
|
193
|
+
* reach it, with the KB code reduced to a code shape and the status to an
|
|
194
|
+
* integer. A throwing logger never breaks a handler.
|
|
195
|
+
*/
|
|
196
|
+
export function hygienicLogger(logger: ConsultationLogger): ConsultationLogger {
|
|
197
|
+
return (e) => {
|
|
198
|
+
if (!isLoggedOutcome(e.outcome)) return
|
|
199
|
+
const kbCode = typeof e.kbCode === 'string' ? (LOGGABLE_CODE_RE.test(e.kbCode) ? e.kbCode : 'other') : null
|
|
200
|
+
const status = typeof e.status === 'number' && Number.isInteger(e.status) ? e.status : null
|
|
201
|
+
try {
|
|
202
|
+
logger({ op: String(e.op).replace(/[^A-Za-z0-9_.-]/g, '').slice(0, 40), outcome: e.outcome, kbCode, status })
|
|
203
|
+
} catch {
|
|
204
|
+
// A logger that throws must not turn a handled failure into an unhandled one.
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// ───────────────────────── gate ─────────────────────────
|
|
210
|
+
|
|
211
|
+
const NO_KEY: ConsultationOutcome<ConsultationPublicConfig> = Object.freeze({ ok: false, code: 'unavailable' })
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Whether this blog serves the reader pages. The public config comes from the
|
|
215
|
+
* server's memo (identity-free: the proxy key, no reader IP, no JWT). Without
|
|
216
|
+
* the reader-proxy key the answer is `dark` and the KB is not asked at all. A
|
|
217
|
+
* locale the KB would not take never reaches it; the site-level features do
|
|
218
|
+
* not depend on the locale, and the contact form is off for it.
|
|
219
|
+
*
|
|
220
|
+
* `peek`: never wait for the KB — answer from the memo as it is (null when it
|
|
221
|
+
* holds nothing for the locale yet) and let a load run in the background, for
|
|
222
|
+
* menus and footers that must not hold a page up.
|
|
223
|
+
*/
|
|
224
|
+
export function siteStatusOf(ctx: ServerContext, locale: string): Promise<ConsultationSiteStatus>
|
|
225
|
+
export function siteStatusOf(ctx: ServerContext, locale: string, o: { peek: true }): Promise<ConsultationSiteStatus | null>
|
|
226
|
+
export async function siteStatusOf(
|
|
227
|
+
ctx: ServerContext,
|
|
228
|
+
locale: string,
|
|
229
|
+
o: { peek?: boolean } = {},
|
|
230
|
+
): Promise<ConsultationSiteStatus | null> {
|
|
231
|
+
const validLocale = typeof locale === 'string' && LOCALE_RE.test(locale)
|
|
232
|
+
const lookup = validLocale ? locale : GATE_LOCALE
|
|
233
|
+
const site = { siteUrls: ctx.siteUrls, readerProxyKey: ctx.proxyKey !== null, adapterKey: ctx.adapterKey !== null, locale: lookup }
|
|
234
|
+
if (ctx.proxyKey === null) {
|
|
235
|
+
ctx.warnOnce(
|
|
236
|
+
'proxy_key',
|
|
237
|
+
'[consultations] no reader-proxy key (CONSULTATIONS_READER_PROXY_KEY) — the reader consultation pages stay dark (404).',
|
|
238
|
+
)
|
|
239
|
+
return readerSiteStatus(NO_KEY, site)
|
|
240
|
+
}
|
|
241
|
+
let cfg: ConsultationOutcome<ConsultationPublicConfig>
|
|
242
|
+
if (o.peek) {
|
|
243
|
+
const memo = ctx.publicConfig.peek(lookup)
|
|
244
|
+
// Not awaited: the memo coalesces and reloads only what is missing or stale.
|
|
245
|
+
ctx.publicConfig.get(lookup).catch(() => {
|
|
246
|
+
ctx.warnOnce('peek_load', '[consultations] a background public-config load failed unexpectedly.')
|
|
247
|
+
})
|
|
248
|
+
if (!memo) return null
|
|
249
|
+
cfg = memo
|
|
250
|
+
} else {
|
|
251
|
+
cfg = await ctx.publicConfig.get(lookup)
|
|
252
|
+
}
|
|
253
|
+
const status = readerSiteStatus(cfg, site)
|
|
254
|
+
if (status.state === 'live' && ctx.adapterKey === null && cfg.ok && cfg.value.emailNotices) {
|
|
255
|
+
ctx.warnOnce(
|
|
256
|
+
'adapter_key',
|
|
257
|
+
'[consultations] no adapter key (CONSULTATIONS_ADAPTER_KEY) — the contact form stays off (404).',
|
|
258
|
+
)
|
|
259
|
+
}
|
|
260
|
+
if (!validLocale && status.features.contactForm) {
|
|
261
|
+
return Object.freeze({
|
|
262
|
+
...status,
|
|
263
|
+
features: Object.freeze({ ...status.features, contactForm: false }),
|
|
264
|
+
contactText: NO_TEXT,
|
|
265
|
+
})
|
|
266
|
+
}
|
|
267
|
+
return status
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export type GateResult =
|
|
271
|
+
| { ok: true; status: ConsultationSiteStatus }
|
|
272
|
+
| { ok: false; code: 'disabled' | 'unavailable'; retryAfterS?: number }
|
|
273
|
+
|
|
274
|
+
/** The gate of one feature: `dark` (or the feature off) → `disabled`; `unknown` → `unavailable` with `Retry-After: 30`. */
|
|
275
|
+
export async function gate(ctx: ServerContext, feature: ConsultationFeature, locale: string = GATE_LOCALE): Promise<GateResult> {
|
|
276
|
+
const status = await siteStatusOf(ctx, locale)
|
|
277
|
+
if (status.state === 'unknown') return { ok: false, code: 'unavailable', retryAfterS: GATE_RETRY_AFTER_S }
|
|
278
|
+
if (status.state !== 'live' || status.features[feature] !== true) return { ok: false, code: 'disabled' }
|
|
279
|
+
return { ok: true, status }
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// ───────────────────────── responses ─────────────────────────
|
|
283
|
+
|
|
284
|
+
/** Headers of a consultation response: the fixed set, plus `Retry-After` on 503 / a known wait. */
|
|
285
|
+
export function responseHeaders(
|
|
286
|
+
status: number,
|
|
287
|
+
extra: { retryAfterS?: number; allow?: string } = {},
|
|
288
|
+
): Record<string, string> {
|
|
289
|
+
const headers: Record<string, string> = { ...CONSULTATION_RESPONSE_HEADERS }
|
|
290
|
+
if (status === 503 || (status === 429 && extra.retryAfterS !== undefined)) {
|
|
291
|
+
headers['Retry-After'] = String(Math.max(1, extra.retryAfterS ?? GATE_RETRY_AFTER_S))
|
|
292
|
+
}
|
|
293
|
+
if (extra.allow) headers.Allow = extra.allow
|
|
294
|
+
return headers
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export function respond<B>(status: number, body: B, extra: { retryAfterS?: number; allow?: string } = {}): ConsultationResponse<B> {
|
|
298
|
+
return { status, headers: responseHeaders(status, extra), body }
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** HTTP status of a reader code. */
|
|
302
|
+
export function statusOf(code: ConsultationUiCode): number {
|
|
303
|
+
return CONSULTATION_UI_HTTP_STATUS[code] ?? 502
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** `retryAfterS` only when known (so the body carries no `undefined` member). */
|
|
307
|
+
export function withRetry<T extends object>(body: T, retryAfterS: number | undefined): T & { retryAfterS?: number } {
|
|
308
|
+
return retryAfterS === undefined ? body : { ...body, retryAfterS }
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// ───────────────────────── request helpers ─────────────────────────
|
|
312
|
+
|
|
313
|
+
export const POST_ONLY = 'POST'
|
|
314
|
+
export const GET_ONLY = 'GET, HEAD'
|
|
315
|
+
|
|
316
|
+
export function isPost(http: ConsultationHttp): boolean {
|
|
317
|
+
return typeof http.method === 'string' && http.method.toUpperCase() === 'POST'
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export function isGet(http: ConsultationHttp): boolean {
|
|
321
|
+
const m = typeof http.method === 'string' ? http.method.toUpperCase() : ''
|
|
322
|
+
return m === 'GET' || m === 'HEAD'
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** The posted form, or null (not a form, too large, malformed, or an adapter that throws). */
|
|
326
|
+
export async function readForm(http: ConsultationHttp): Promise<Record<string, string> | null> {
|
|
327
|
+
try {
|
|
328
|
+
const form = await http.form()
|
|
329
|
+
return form && typeof form === 'object' ? form : null
|
|
330
|
+
} catch {
|
|
331
|
+
return null
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** One posted string field (own property only). */
|
|
336
|
+
export function fieldOf(fields: Record<string, string>, name: string): string | undefined {
|
|
337
|
+
if (!Object.prototype.hasOwnProperty.call(fields, name)) return undefined
|
|
338
|
+
const value = fields[name]
|
|
339
|
+
return typeof value === 'string' ? value : undefined
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** The reader's IP for the KB's per-IP quotas; a request without one is announced once. */
|
|
343
|
+
export function readerIp(ctx: ServerContext, http: ConsultationHttp): string | null {
|
|
344
|
+
const ip = clientIpFrom(http, { header: ctx.clientIpHeader })
|
|
345
|
+
if (ip === null) {
|
|
346
|
+
ctx.warnOnce(
|
|
347
|
+
'client_ip',
|
|
348
|
+
'[consultations] a reader request without a client IP (no valid edge header or X-Forwarded-For) — ' +
|
|
349
|
+
"the KB's per-IP quotas count the blog server's own IP instead. Check CONSULTATIONS_CLIENT_IP_HEADER " +
|
|
350
|
+
'and the reverse-proxy configuration.',
|
|
351
|
+
)
|
|
352
|
+
}
|
|
353
|
+
return ip
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** A fresh idempotency key (the configured generator, when it yields a valid key). */
|
|
357
|
+
export function freshKey(ctx: ServerContext): string {
|
|
358
|
+
let id: unknown
|
|
359
|
+
try {
|
|
360
|
+
id = ctx.randomId()
|
|
361
|
+
} catch {
|
|
362
|
+
id = null
|
|
363
|
+
}
|
|
364
|
+
return typeof id === 'string' && CLIENT_REQUEST_ID_RE.test(id) ? id : newClientRequestId()
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// ───────────────────────── KB calls ─────────────────────────
|
|
368
|
+
|
|
369
|
+
/** A GraphQL client for one call, or null when no KB is configured. */
|
|
370
|
+
export function kbClient(ctx: ServerContext, o: { token: string | null; clientIp: string | null }): KbClient | null {
|
|
371
|
+
return ctx.transport ? ctx.transport.graphql(o) : null
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
export interface KbFailure {
|
|
375
|
+
code: ConsultationUiCode
|
|
376
|
+
retryAfterS?: number
|
|
377
|
+
kbCode: string | null
|
|
378
|
+
status: number | null
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** A thrown KB error → the reader's code plus what a log line may say about it. */
|
|
382
|
+
export function kbFailureOf(err: unknown): KbFailure {
|
|
383
|
+
const failure = consultationFailureOf(err)
|
|
384
|
+
return {
|
|
385
|
+
...failure,
|
|
386
|
+
kbCode: isKbGraphQLError(err) ? err.code : null,
|
|
387
|
+
status: isTransportError(err) ? err.status : null,
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* The reader cannot fix a credential the blog holds: an `auth` answer on a
|
|
393
|
+
* call made with the blog's own key (a revoked or wrong reader-proxy or
|
|
394
|
+
* adapter key) is an outage, never "sign in".
|
|
395
|
+
*/
|
|
396
|
+
export function blogKeyFailure(f: KbFailure): KbFailure {
|
|
397
|
+
return f.code === 'auth' ? { ...f, code: 'unavailable' } : f
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** Logs a failure (outages and the unexpected only; see `hygienicLogger`). */
|
|
401
|
+
export function logFailure(ctx: ServerContext, op: string, f: Pick<KbFailure, 'code' | 'kbCode' | 'status'>): void {
|
|
402
|
+
ctx.logger({ op, outcome: f.code, kbCode: f.kbCode, status: f.status })
|
|
403
|
+
}
|