@blogmcp/sdk 0.6.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/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 +1 -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,414 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The anonymous reader's pages: the magic link (`/consultation/open` →
|
|
3
|
+
* `POST /api/consultations/access`), the thread its session opens
|
|
4
|
+
* (`/consultation`), dropping a session the KB no longer accepts
|
|
5
|
+
* (`POST /api/consultations/forget`), attaching that thread to an account, and
|
|
6
|
+
* asking for a fresh link (`/consultation/new-link`). A port of the drhoubicka
|
|
7
|
+
* storefront's `/dotaz*` routes, generalised.
|
|
8
|
+
*
|
|
9
|
+
* Every handler runs in the same order: 1. method, 2. the gate (`dark` → 404
|
|
10
|
+
* `disabled`, `unknown` → 503 `unavailable` with `Retry-After: 30`), 3. the
|
|
11
|
+
* Origin check, 4. the form, 5. the KB call. Nothing here throws.
|
|
12
|
+
*
|
|
13
|
+
* Credentials: the session calls go out with the blog's reader-proxy key and
|
|
14
|
+
* the reader's IP (the key is what makes kb-api believe the IP). Attaching
|
|
15
|
+
* goes out with the reader's own JWT — never the proxy key. The link token
|
|
16
|
+
* and the session only ever travel in a request body to the KB, and the
|
|
17
|
+
* session back to the browser only in `Set-Cookie`.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import type { ReaderConsultation } from '../../core/types'
|
|
21
|
+
import {
|
|
22
|
+
CLIENT_REQUEST_ID_RE,
|
|
23
|
+
CONSULTATION_SECRET_RE,
|
|
24
|
+
NEW_LINK_FIELDS,
|
|
25
|
+
READER_BODY_MAX,
|
|
26
|
+
SESSION_FIELDS,
|
|
27
|
+
consultationOutcomeOf,
|
|
28
|
+
isReaderEmail,
|
|
29
|
+
normalizeBody,
|
|
30
|
+
type ConsultationUiCode,
|
|
31
|
+
} from '../index'
|
|
32
|
+
import {
|
|
33
|
+
GET_ONLY,
|
|
34
|
+
POST_ONLY,
|
|
35
|
+
blogKeyFailure,
|
|
36
|
+
fieldOf,
|
|
37
|
+
freshKey,
|
|
38
|
+
gate,
|
|
39
|
+
isGet,
|
|
40
|
+
isPost,
|
|
41
|
+
kbClient,
|
|
42
|
+
kbFailureOf,
|
|
43
|
+
logFailure,
|
|
44
|
+
readForm,
|
|
45
|
+
readerIp,
|
|
46
|
+
respond,
|
|
47
|
+
statusOf,
|
|
48
|
+
withRetry,
|
|
49
|
+
type AccessResult,
|
|
50
|
+
type AttachResult,
|
|
51
|
+
type ForgetResult,
|
|
52
|
+
type KbFailure,
|
|
53
|
+
type RequestLinkResult,
|
|
54
|
+
type ServerContext,
|
|
55
|
+
type SessionActionResult,
|
|
56
|
+
type SessionPageState,
|
|
57
|
+
} from './context'
|
|
58
|
+
import { clearedCookie, readSessionCookie, sessionCookie } from './cookie'
|
|
59
|
+
import type { ConsultationHttp, ConsultationResponse } from './http'
|
|
60
|
+
import { isAllowedOrigin } from './origin'
|
|
61
|
+
|
|
62
|
+
/** A JWT: three base64url parts. Checked before it goes anywhere. */
|
|
63
|
+
const JWT_RE = /^[\w-]+\.[\w-]+\.[\w-]+$/
|
|
64
|
+
const JWT_MAX = 4096
|
|
65
|
+
|
|
66
|
+
/** The intents of the session page's forms. */
|
|
67
|
+
const SESSION_INTENTS = new Set(['reply', 'erase', 'logout'])
|
|
68
|
+
|
|
69
|
+
/** `Authorization: Bearer <token>` → the token, or null. */
|
|
70
|
+
export function bearerToken(http: Pick<ConsultationHttp, 'header'>): string | null {
|
|
71
|
+
let header: string | null
|
|
72
|
+
try {
|
|
73
|
+
header = http.header('authorization')
|
|
74
|
+
} catch {
|
|
75
|
+
return null
|
|
76
|
+
}
|
|
77
|
+
const match = typeof header === 'string' ? /^Bearer\s+(\S+)\s*$/i.exec(header) : null
|
|
78
|
+
return match ? match[1]! : null
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** True for a plausible reader address (what the KB would take) — the shared entry's `isReaderEmail`. */
|
|
82
|
+
export const isEmailAddress: (value: string) => boolean = isReaderEmail
|
|
83
|
+
|
|
84
|
+
/** Clears the session cookie; best effort (a Next Server Component cannot set cookies). */
|
|
85
|
+
function clearSession(ctx: ServerContext, http: ConsultationHttp): void {
|
|
86
|
+
try {
|
|
87
|
+
http.setCookie(clearedCookie(ctx.cookieName))
|
|
88
|
+
} catch {
|
|
89
|
+
// The cookie then expires on its own (Max-Age ≤ 12 h); the KB already refuses the session.
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** A mutation result (`{success, code}`) → null on success, else the failure. */
|
|
94
|
+
function mutationFailure(result: unknown): KbFailure | null {
|
|
95
|
+
const r = result as { success?: unknown; code?: unknown } | null | undefined
|
|
96
|
+
if (r && typeof r === 'object' && r.success === true) return null
|
|
97
|
+
if (!r || typeof r !== 'object' || typeof r.success !== 'boolean') {
|
|
98
|
+
return { code: 'unavailable', kbCode: null, status: null }
|
|
99
|
+
}
|
|
100
|
+
const kbCode = typeof r.code === 'string' ? r.code : null
|
|
101
|
+
return { code: consultationOutcomeOf(kbCode), kbCode, status: null }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Runs one KB call made with the blog's reader-proxy key and turns any throw into a failure. */
|
|
105
|
+
async function viaProxy<T>(
|
|
106
|
+
ctx: ServerContext,
|
|
107
|
+
op: string,
|
|
108
|
+
clientIp: string | null,
|
|
109
|
+
call: (client: NonNullable<ReturnType<typeof kbClient>>) => Promise<T>,
|
|
110
|
+
): Promise<{ ok: true; value: T } | { ok: false; failure: KbFailure }> {
|
|
111
|
+
const client = kbClient(ctx, { token: ctx.proxyKey, clientIp })
|
|
112
|
+
if (!client) {
|
|
113
|
+
const failure: KbFailure = { code: 'unavailable', kbCode: null, status: null }
|
|
114
|
+
logFailure(ctx, op, failure)
|
|
115
|
+
return { ok: false, failure }
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
return { ok: true, value: await call(client) }
|
|
119
|
+
} catch (err) {
|
|
120
|
+
const failure = blogKeyFailure(kbFailureOf(err))
|
|
121
|
+
logFailure(ctx, op, failure)
|
|
122
|
+
return { ok: false, failure }
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function isThread(value: unknown): value is ReaderConsultation {
|
|
127
|
+
const v = value as Partial<ReaderConsultation> | null
|
|
128
|
+
return !!v && typeof v === 'object' && typeof v.id === 'string' && Array.isArray(v.messages)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ───────────────────────── GET /consultation ─────────────────────────
|
|
132
|
+
|
|
133
|
+
export async function loadSession(ctx: ServerContext, http: ConsultationHttp): Promise<ConsultationResponse<SessionPageState>> {
|
|
134
|
+
const error = (code: ConsultationUiCode, retryAfterS?: number, allow?: string) =>
|
|
135
|
+
respond<SessionPageState>(statusOf(code), withRetry({ state: 'error' as const, error: code }, retryAfterS), {
|
|
136
|
+
retryAfterS,
|
|
137
|
+
allow,
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
if (!isGet(http)) return error('method', undefined, GET_ONLY)
|
|
141
|
+
const g = await gate(ctx, 'magicLink')
|
|
142
|
+
if (!g.ok) return error(g.code, g.retryAfterS)
|
|
143
|
+
|
|
144
|
+
const session = readSessionCookie(http, ctx.cookieName)
|
|
145
|
+
if (!session) return respond<SessionPageState>(200, { state: 'none' })
|
|
146
|
+
|
|
147
|
+
const result = await viaProxy(ctx, 'bySession', readerIp(ctx, http), (c) => c.consultationSession.get(session))
|
|
148
|
+
if (!result.ok) {
|
|
149
|
+
if (result.failure.code === 'expired') {
|
|
150
|
+
clearSession(ctx, http)
|
|
151
|
+
return respond<SessionPageState>(200, { state: 'expired' })
|
|
152
|
+
}
|
|
153
|
+
return error(result.failure.code, result.failure.retryAfterS)
|
|
154
|
+
}
|
|
155
|
+
if (!isThread(result.value)) {
|
|
156
|
+
logFailure(ctx, 'bySession', { code: 'unavailable', kbCode: null, status: null })
|
|
157
|
+
return error('unavailable')
|
|
158
|
+
}
|
|
159
|
+
return respond<SessionPageState>(200, { state: 'open', consultation: result.value, clientRequestId: freshKey(ctx) })
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// ───────────────────────── POST /api/consultations/access ─────────────────────────
|
|
163
|
+
|
|
164
|
+
export async function handleAccess(ctx: ServerContext, http: ConsultationHttp): Promise<ConsultationResponse<AccessResult>> {
|
|
165
|
+
const fail = (code: ConsultationUiCode, retryAfterS?: number, allow?: string) =>
|
|
166
|
+
respond<AccessResult>(statusOf(code), withRetry({ success: false as const, error: code }, retryAfterS), {
|
|
167
|
+
retryAfterS,
|
|
168
|
+
allow,
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
if (!isPost(http)) return fail('method', undefined, POST_ONLY)
|
|
172
|
+
const g = await gate(ctx, 'magicLink')
|
|
173
|
+
if (!g.ok) return fail(g.code, g.retryAfterS)
|
|
174
|
+
if (!isAllowedOrigin(http, ctx.origins)) return fail('origin')
|
|
175
|
+
|
|
176
|
+
const fields = await readForm(http)
|
|
177
|
+
if (!fields || fieldOf(fields, SESSION_FIELDS.intent) !== 'exchange') return fail('invalid')
|
|
178
|
+
const token = fieldOf(fields, SESSION_FIELDS.token)
|
|
179
|
+
// A token of the wrong shape costs neither a request nor the reader's quota.
|
|
180
|
+
if (typeof token !== 'string' || !CONSULTATION_SECRET_RE.test(token)) return fail('invalid')
|
|
181
|
+
|
|
182
|
+
const result = await viaProxy(ctx, 'exchange', readerIp(ctx, http), (c) => c.consultationSession.exchange(token))
|
|
183
|
+
if (!result.ok) return fail(result.failure.code, result.failure.retryAfterS)
|
|
184
|
+
const refused = mutationFailure(result.value)
|
|
185
|
+
if (refused) {
|
|
186
|
+
const failure = blogKeyFailure(refused)
|
|
187
|
+
logFailure(ctx, 'exchange', failure)
|
|
188
|
+
return fail(failure.code)
|
|
189
|
+
}
|
|
190
|
+
const session = result.value.session
|
|
191
|
+
if (typeof session !== 'string' || !CONSULTATION_SECRET_RE.test(session)) {
|
|
192
|
+
// The KB said yes but handed no usable session: nothing to put in a cookie.
|
|
193
|
+
logFailure(ctx, 'exchange', { code: 'unavailable', kbCode: null, status: null })
|
|
194
|
+
return fail('unavailable')
|
|
195
|
+
}
|
|
196
|
+
try {
|
|
197
|
+
http.setCookie(sessionCookie(ctx.cookieName, session, result.value.expiresAt, ctx.now()))
|
|
198
|
+
} catch {
|
|
199
|
+
logFailure(ctx, 'exchange', { code: 'unavailable', kbCode: null, status: null })
|
|
200
|
+
return fail('unavailable')
|
|
201
|
+
}
|
|
202
|
+
return respond<AccessResult>(200, { success: true })
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ───────────────────────── POST /api/consultations/forget ─────────────────────────
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Drop a session cookie the KB no longer accepts. The session page's loader
|
|
209
|
+
* clears such a cookie itself where the framework lets it; a Next Server
|
|
210
|
+
* Component cannot, so its page calls this endpoint instead. It asks the KB
|
|
211
|
+
* exactly what `loadSession` asks and clears the cookie ONLY on an expired or
|
|
212
|
+
* invalid session: a session that is still valid stays, so this can never
|
|
213
|
+
* close a fresh session the reader opened in another tab. Never thread data.
|
|
214
|
+
*/
|
|
215
|
+
export async function handleForget(ctx: ServerContext, http: ConsultationHttp): Promise<ConsultationResponse<ForgetResult>> {
|
|
216
|
+
const fail = (code: ConsultationUiCode, retryAfterS?: number, allow?: string) =>
|
|
217
|
+
respond<ForgetResult>(statusOf(code), withRetry({ success: false as const, error: code }, retryAfterS), {
|
|
218
|
+
retryAfterS,
|
|
219
|
+
allow,
|
|
220
|
+
})
|
|
221
|
+
|
|
222
|
+
if (!isPost(http)) return fail('method', undefined, POST_ONLY)
|
|
223
|
+
const g = await gate(ctx, 'magicLink')
|
|
224
|
+
if (!g.ok) return fail(g.code, g.retryAfterS)
|
|
225
|
+
if (!isAllowedOrigin(http, ctx.origins)) return fail('origin')
|
|
226
|
+
|
|
227
|
+
const session = readSessionCookie(http, ctx.cookieName)
|
|
228
|
+
if (!session) return respond<ForgetResult>(204, null)
|
|
229
|
+
|
|
230
|
+
const result = await viaProxy(ctx, 'forget', readerIp(ctx, http), (c) => c.consultationSession.get(session))
|
|
231
|
+
if (result.ok) {
|
|
232
|
+
if (isThread(result.value)) return respond<ForgetResult>(200, null)
|
|
233
|
+
logFailure(ctx, 'forget', { code: 'unavailable', kbCode: null, status: null })
|
|
234
|
+
return fail('unavailable')
|
|
235
|
+
}
|
|
236
|
+
if (result.failure.code === 'expired') {
|
|
237
|
+
clearSession(ctx, http)
|
|
238
|
+
return fail('expired')
|
|
239
|
+
}
|
|
240
|
+
return fail(result.failure.code, result.failure.retryAfterS)
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// ───────────────────────── POST /consultation ─────────────────────────
|
|
244
|
+
|
|
245
|
+
/** The body and key of a failed reply, for the form: the reader's own text, never lost. */
|
|
246
|
+
type ReplyEcho = { body: string; clientRequestId: string }
|
|
247
|
+
|
|
248
|
+
export async function handleSessionAction(
|
|
249
|
+
ctx: ServerContext,
|
|
250
|
+
http: ConsultationHttp,
|
|
251
|
+
): Promise<ConsultationResponse<SessionActionResult>> {
|
|
252
|
+
const fail = (code: ConsultationUiCode, o: { retryAfterS?: number; allow?: string; echo?: ReplyEcho } = {}) =>
|
|
253
|
+
respond<SessionActionResult>(
|
|
254
|
+
statusOf(code),
|
|
255
|
+
withRetry({ success: false as const, error: code, ...(o.echo ?? {}) }, o.retryAfterS),
|
|
256
|
+
{ retryAfterS: o.retryAfterS, allow: o.allow },
|
|
257
|
+
)
|
|
258
|
+
const loggedOut = () => {
|
|
259
|
+
clearSession(ctx, http)
|
|
260
|
+
return respond<SessionActionResult>(200, { success: true, done: 'loggedOut' })
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
if (!isPost(http)) return fail('method', { allow: POST_ONLY })
|
|
264
|
+
const g = await gate(ctx, 'magicLink')
|
|
265
|
+
if (!g.ok && g.code === 'disabled') return fail('disabled')
|
|
266
|
+
|
|
267
|
+
const originOk = isAllowedOrigin(http, ctx.origins)
|
|
268
|
+
if (g.ok && !originOk) return fail('origin')
|
|
269
|
+
const fields = originOk ? await readForm(http) : null
|
|
270
|
+
const intent = fields ? fieldOf(fields, SESSION_FIELDS.intent) : undefined
|
|
271
|
+
|
|
272
|
+
// The KB cannot be asked (`unknown`). Signing out must still work — it only drops the cookie —
|
|
273
|
+
// and a reply keeps the reader's text; everything else is the gate's 503.
|
|
274
|
+
if (!g.ok) {
|
|
275
|
+
if (fields && intent === 'logout') return loggedOut()
|
|
276
|
+
return fail(g.code, { retryAfterS: g.retryAfterS, echo: fields && intent === 'reply' ? replyEcho(ctx, fields) : undefined })
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
if (!fields || typeof intent !== 'string' || !SESSION_INTENTS.has(intent)) return fail('invalid')
|
|
280
|
+
const clientIp = readerIp(ctx, http)
|
|
281
|
+
const session = readSessionCookie(http, ctx.cookieName)
|
|
282
|
+
|
|
283
|
+
if (intent === 'logout') {
|
|
284
|
+
// The KB's answer is not read: a session the KB does not know, or cannot close now, expires
|
|
285
|
+
// on its own. The cookie goes ALWAYS — signing out must not depend on the KB being up.
|
|
286
|
+
if (session) await viaProxy(ctx, 'closeSession', clientIp, (c) => c.consultationSession.close(session))
|
|
287
|
+
return loggedOut()
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (intent === 'reply') {
|
|
291
|
+
const echo = replyEcho(ctx, fields)
|
|
292
|
+
const body = normalizeBody(fieldOf(fields, SESSION_FIELDS.body), READER_BODY_MAX)
|
|
293
|
+
if (!body.ok) return fail(body.code, { echo })
|
|
294
|
+
const key = fieldOf(fields, SESSION_FIELDS.clientRequestId)
|
|
295
|
+
if (typeof key !== 'string' || !CLIENT_REQUEST_ID_RE.test(key)) return fail('invalid', { echo })
|
|
296
|
+
if (!session) return fail('expired', { echo })
|
|
297
|
+
|
|
298
|
+
const result = await viaProxy(ctx, 'postBySession', clientIp, (c) =>
|
|
299
|
+
c.consultationSession.post(session, { body: body.body, clientRequestId: key }),
|
|
300
|
+
)
|
|
301
|
+
const failure = result.ok ? mutationFailure(result.value) : result.failure
|
|
302
|
+
if (!failure) return respond<SessionActionResult>(200, { success: true, done: 'posted' })
|
|
303
|
+
const f = result.ok ? blogKeyFailure(failure) : failure
|
|
304
|
+
if (result.ok) logFailure(ctx, 'postBySession', f)
|
|
305
|
+
if (f.code === 'expired') clearSession(ctx, http)
|
|
306
|
+
// IDEMPOTENCY_CONFLICT: the first attempt most likely went through — a NEW key for the next one.
|
|
307
|
+
const nextKey = f.code === 'conflict' ? freshKey(ctx) : key
|
|
308
|
+
return fail(f.code, { retryAfterS: f.retryAfterS, echo: { body: echo.body, clientRequestId: nextKey } })
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// erase
|
|
312
|
+
if (!session) return fail('expired')
|
|
313
|
+
const result = await viaProxy(ctx, 'erasureBySession', clientIp, (c) => c.consultationSession.requestErasure(session))
|
|
314
|
+
const failure = result.ok ? mutationFailure(result.value) : result.failure
|
|
315
|
+
if (!failure) {
|
|
316
|
+
// The KB revoked the thread's sessions; the cookie would only linger.
|
|
317
|
+
clearSession(ctx, http)
|
|
318
|
+
return respond<SessionActionResult>(200, { success: true, done: 'erased' })
|
|
319
|
+
}
|
|
320
|
+
const f = result.ok ? blogKeyFailure(failure) : failure
|
|
321
|
+
if (result.ok) logFailure(ctx, 'erasureBySession', f)
|
|
322
|
+
if (f.code === 'expired') clearSession(ctx, http)
|
|
323
|
+
return fail(f.code, { retryAfterS: f.retryAfterS })
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** What a failed reply hands back: the typed text (normalised) and the posted key, or a fresh one if it was malformed. */
|
|
327
|
+
function replyEcho(ctx: ServerContext, fields: Record<string, string>): ReplyEcho {
|
|
328
|
+
const typed = normalizeBody(fieldOf(fields, SESSION_FIELDS.body), READER_BODY_MAX)
|
|
329
|
+
const key = fieldOf(fields, SESSION_FIELDS.clientRequestId)
|
|
330
|
+
return {
|
|
331
|
+
body: typed.body,
|
|
332
|
+
clientRequestId: typeof key === 'string' && CLIENT_REQUEST_ID_RE.test(key) ? key : freshKey(ctx),
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// ───────────────────────── POST /api/consultations/attach ─────────────────────────
|
|
337
|
+
|
|
338
|
+
export async function handleAttach(ctx: ServerContext, http: ConsultationHttp): Promise<ConsultationResponse<AttachResult>> {
|
|
339
|
+
const fail = (code: ConsultationUiCode, retryAfterS?: number, allow?: string) =>
|
|
340
|
+
respond<AttachResult>(statusOf(code), withRetry({ success: false as const, error: code }, retryAfterS), {
|
|
341
|
+
retryAfterS,
|
|
342
|
+
allow,
|
|
343
|
+
})
|
|
344
|
+
|
|
345
|
+
if (!isPost(http)) return fail('method', undefined, POST_ONLY)
|
|
346
|
+
const g = await gate(ctx, 'magicLink')
|
|
347
|
+
if (!g.ok) return fail(g.code, g.retryAfterS)
|
|
348
|
+
if (!isAllowedOrigin(http, ctx.origins)) return fail('origin')
|
|
349
|
+
|
|
350
|
+
const session = readSessionCookie(http, ctx.cookieName)
|
|
351
|
+
if (!session) return fail('expired')
|
|
352
|
+
let jwt: string | null
|
|
353
|
+
try {
|
|
354
|
+
jwt = ctx.readerToken(http)
|
|
355
|
+
} catch {
|
|
356
|
+
jwt = null
|
|
357
|
+
}
|
|
358
|
+
// No reader, or not a token at all: sign in first. Nothing reaches the KB.
|
|
359
|
+
if (typeof jwt !== 'string' || jwt.length > JWT_MAX || !JWT_RE.test(jwt)) return fail('auth')
|
|
360
|
+
|
|
361
|
+
// The reader's OWN identity: the proxy key must never stand in for it here.
|
|
362
|
+
const client = kbClient(ctx, { token: jwt, clientIp: readerIp(ctx, http) })
|
|
363
|
+
if (!client) {
|
|
364
|
+
logFailure(ctx, 'attach', { code: 'unavailable', kbCode: null, status: null })
|
|
365
|
+
return fail('unavailable')
|
|
366
|
+
}
|
|
367
|
+
let failure: KbFailure | null
|
|
368
|
+
try {
|
|
369
|
+
failure = mutationFailure(await client.consultationSession.attach(session))
|
|
370
|
+
} catch (err) {
|
|
371
|
+
failure = kbFailureOf(err)
|
|
372
|
+
}
|
|
373
|
+
if (!failure) {
|
|
374
|
+
// The KB revoked the sessions: the thread now lives in the reader's account.
|
|
375
|
+
clearSession(ctx, http)
|
|
376
|
+
return respond<AttachResult>(200, { success: true, done: 'attached' })
|
|
377
|
+
}
|
|
378
|
+
logFailure(ctx, 'attach', failure)
|
|
379
|
+
if (failure.code === 'expired') clearSession(ctx, http)
|
|
380
|
+
return fail(failure.code, failure.retryAfterS)
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// ───────────────────────── POST /consultation/new-link ─────────────────────────
|
|
384
|
+
|
|
385
|
+
export async function handleRequestLink(
|
|
386
|
+
ctx: ServerContext,
|
|
387
|
+
http: ConsultationHttp,
|
|
388
|
+
): Promise<ConsultationResponse<RequestLinkResult>> {
|
|
389
|
+
const fail = (code: ConsultationUiCode, retryAfterS?: number, allow?: string) =>
|
|
390
|
+
respond<RequestLinkResult>(statusOf(code), withRetry({ done: false as const, error: code }, retryAfterS), {
|
|
391
|
+
retryAfterS,
|
|
392
|
+
allow,
|
|
393
|
+
})
|
|
394
|
+
const done = () => respond<RequestLinkResult>(200, { done: true })
|
|
395
|
+
|
|
396
|
+
if (!isPost(http)) return fail('method', undefined, POST_ONLY)
|
|
397
|
+
const g = await gate(ctx, 'newLink')
|
|
398
|
+
if (!g.ok) return fail(g.code, g.retryAfterS)
|
|
399
|
+
if (!isAllowedOrigin(http, ctx.origins)) return fail('origin')
|
|
400
|
+
|
|
401
|
+
const fields = await readForm(http)
|
|
402
|
+
if (!fields) return fail('invalid')
|
|
403
|
+
// A filled honeypot: the same answer as always, and nothing goes to the KB.
|
|
404
|
+
const honeypot = fieldOf(fields, NEW_LINK_FIELDS.honeypot)
|
|
405
|
+
if (typeof honeypot === 'string' && honeypot !== '') return done()
|
|
406
|
+
const email = (fieldOf(fields, NEW_LINK_FIELDS.email) ?? '').trim()
|
|
407
|
+
// A typo is worth telling (it reveals nothing about who wrote in).
|
|
408
|
+
if (!isEmailAddress(email)) return fail('invalid')
|
|
409
|
+
|
|
410
|
+
// The answer is deliberately NOT read: an outage and a success end in the same sentence.
|
|
411
|
+
// A failure is logged (code and status only, never the address).
|
|
412
|
+
await viaProxy(ctx, 'requestLink', readerIp(ctx, http), (c) => c.consultationSession.requestLink(email))
|
|
413
|
+
return done()
|
|
414
|
+
}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How the consultation server talks to kb-api: a status-checking GraphQL
|
|
3
|
+
* transport and the per-request clients built on it.
|
|
4
|
+
*
|
|
5
|
+
* Why not the SDK's default fetcher: it never looks at the HTTP status. kb-api's
|
|
6
|
+
* rate limiter answers 429 with a JSON body that has no `errors`, so the default
|
|
7
|
+
* transport hands back `undefined` and a reader page shows "not found" where the
|
|
8
|
+
* truth is "the KB is busy, retry in N seconds". Here every way the KB can fail
|
|
9
|
+
* to answer — network, timeout, HTTP 5xx or 429 without a code, a body that is
|
|
10
|
+
* not JSON — is a `ConsultationTransportError` with the status and the
|
|
11
|
+
* `Retry-After`, which the handlers turn into `unavailable` (503). A GraphQL
|
|
12
|
+
* `errors` answer is left to the SDK client, which throws `KbGraphQLError` with
|
|
13
|
+
* the code.
|
|
14
|
+
*
|
|
15
|
+
* Every request: `redirect: 'error'` (following a redirect would re-send the key
|
|
16
|
+
* to wherever it points), `cache: 'no-store'` (a reader's thread must never sit
|
|
17
|
+
* in a fetch cache — Next's data cache included) and a timeout.
|
|
18
|
+
*
|
|
19
|
+
* Clients are built per request: the credential and the reader's IP differ per
|
|
20
|
+
* call, so a module-level client would carry one reader's identity into
|
|
21
|
+
* another's request.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { createKbClient, type KbClient } from '../../core/client'
|
|
25
|
+
import type { Fetcher } from '../../core/client-types'
|
|
26
|
+
import { createConsultationAdapterClient, type ConsultationAdapterClient } from '../../core/consultation-adapter'
|
|
27
|
+
import { ConsultationTransportError } from '../index'
|
|
28
|
+
import { KB_CLIENT_IP_HEADER } from './client-ip'
|
|
29
|
+
|
|
30
|
+
/** A key or token that is safe as an HTTP header value (visible ASCII, no whitespace). */
|
|
31
|
+
export const HEADER_TOKEN_RE = /^[\x21-\x7E]+$/
|
|
32
|
+
|
|
33
|
+
/** The longest wait the KB may ask for that is passed on to a reader (seconds). */
|
|
34
|
+
const RETRY_AFTER_MAX_S = 600
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The kb-api base URL (`http://kb-api:5070`, `https://tenant.example/api`)
|
|
38
|
+
* without a trailing slash, or null when it is not an absolute http(s) URL
|
|
39
|
+
* without a query or fragment.
|
|
40
|
+
*/
|
|
41
|
+
export function kbApiBase(value: unknown): string | null {
|
|
42
|
+
if (typeof value !== 'string' || value.trim() === '') return null
|
|
43
|
+
try {
|
|
44
|
+
const url = new URL(value.trim())
|
|
45
|
+
if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.search || url.hash) return null
|
|
46
|
+
return url.origin + url.pathname.replace(/\/+$/, '')
|
|
47
|
+
} catch {
|
|
48
|
+
return null
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Seconds until a retry can succeed: `Retry-After` (seconds or an HTTP date),
|
|
54
|
+
* else the `reset` of the draft-7 `RateLimit` header kb-api's limiter sends
|
|
55
|
+
* (`limit=200, remaining=0, reset=37`). Null when neither says.
|
|
56
|
+
*/
|
|
57
|
+
export function retryAfterSeconds(headers: Pick<Headers, 'get'>, now: number = Date.now()): number | null {
|
|
58
|
+
let seconds: number | null = null
|
|
59
|
+
const retryAfter = headers.get('retry-after')?.trim()
|
|
60
|
+
if (retryAfter) {
|
|
61
|
+
if (/^\d+$/.test(retryAfter)) seconds = Number(retryAfter)
|
|
62
|
+
else {
|
|
63
|
+
const at = Date.parse(retryAfter)
|
|
64
|
+
if (!Number.isNaN(at)) seconds = Math.max(0, Math.ceil((at - now) / 1000))
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (seconds === null) {
|
|
68
|
+
const reset = /(?:^|[\s,;])reset=(\d+)/.exec(headers.get('ratelimit') ?? '')
|
|
69
|
+
if (reset) seconds = Number(reset[1])
|
|
70
|
+
}
|
|
71
|
+
return seconds === null ? null : Math.min(seconds, RETRY_AFTER_MAX_S)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
75
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** A GraphQL error answer the SDK should see (and throw as `KbGraphQLError` with its code). */
|
|
79
|
+
function isGraphQLErrorAnswer(body: unknown, status: number): boolean {
|
|
80
|
+
if (!isRecord(body) || !Array.isArray(body.errors) || body.errors.length === 0) return false
|
|
81
|
+
// A request error (400 validation, 401 …) is the API's own answer. A 429 / 5xx is the KB being
|
|
82
|
+
// unable to answer — unless it names the reader's quota, which the page reports as such.
|
|
83
|
+
if (status >= 400 && status < 500 && status !== 429) return true
|
|
84
|
+
return body.errors.some(
|
|
85
|
+
(e) => isRecord(e) && isRecord(e.extensions) && e.extensions.code === 'QUOTA_EXCEEDED',
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface KbTransportOptions {
|
|
90
|
+
/** The kb-api base URL, already normalised (`kbApiBase`). */
|
|
91
|
+
base: string
|
|
92
|
+
/** Resolved per call, so a test spy or a framework-patched global fetch is honoured. */
|
|
93
|
+
fetch: () => typeof fetch
|
|
94
|
+
timeoutMs: number
|
|
95
|
+
now: () => number
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The status-checking GraphQL transport (see the module doc). */
|
|
99
|
+
export function createKbFetcher(o: KbTransportOptions): Fetcher {
|
|
100
|
+
return async (url, init) => {
|
|
101
|
+
let res: Response
|
|
102
|
+
try {
|
|
103
|
+
res = await o.fetch()(url, {
|
|
104
|
+
method: init.method,
|
|
105
|
+
headers: init.headers,
|
|
106
|
+
body: init.body,
|
|
107
|
+
redirect: 'error',
|
|
108
|
+
cache: 'no-store',
|
|
109
|
+
signal: AbortSignal.timeout(o.timeoutMs),
|
|
110
|
+
})
|
|
111
|
+
} catch {
|
|
112
|
+
// The cause is dropped on purpose: a fetch header error quotes the header value (a key).
|
|
113
|
+
throw new ConsultationTransportError('KB request failed (network error or timeout)')
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
let text: string
|
|
117
|
+
try {
|
|
118
|
+
text = await res.text()
|
|
119
|
+
} catch {
|
|
120
|
+
throw new ConsultationTransportError(`KB answered HTTP ${res.status} with an unreadable body`, {
|
|
121
|
+
status: res.status,
|
|
122
|
+
})
|
|
123
|
+
}
|
|
124
|
+
let body: unknown
|
|
125
|
+
try {
|
|
126
|
+
body = JSON.parse(text)
|
|
127
|
+
} catch {
|
|
128
|
+
body = undefined
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (!res.ok) {
|
|
132
|
+
if (isGraphQLErrorAnswer(body, res.status)) return body as Awaited<ReturnType<Fetcher>>
|
|
133
|
+
throw new ConsultationTransportError(`KB answered HTTP ${res.status}`, {
|
|
134
|
+
status: res.status,
|
|
135
|
+
retryAfterS: retryAfterSeconds(res.headers, o.now()),
|
|
136
|
+
})
|
|
137
|
+
}
|
|
138
|
+
if (!isRecord(body)) {
|
|
139
|
+
throw new ConsultationTransportError('KB answered with a body that is not a GraphQL response', {
|
|
140
|
+
status: res.status,
|
|
141
|
+
})
|
|
142
|
+
}
|
|
143
|
+
return body as Awaited<ReturnType<Fetcher>>
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** A token storage that always answers the same credential (and ignores writes). */
|
|
148
|
+
function fixedToken(token: string | null) {
|
|
149
|
+
return { getToken: () => token, setToken: () => {}, removeToken: () => {} }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export interface KbTransport {
|
|
153
|
+
/**
|
|
154
|
+
* A GraphQL client for one call: `token` goes into `Authorization` (the
|
|
155
|
+
* reader-proxy key, or a reader's JWT), `clientIp` into
|
|
156
|
+
* `X-Blogmcp-Client-Ip` (omitted when null).
|
|
157
|
+
*/
|
|
158
|
+
graphql(o: { token: string | null; clientIp: string | null }): KbClient
|
|
159
|
+
/**
|
|
160
|
+
* The adapter client for one ingest, and the `Retry-After` of its last
|
|
161
|
+
* response (the adapter client does not keep it).
|
|
162
|
+
*/
|
|
163
|
+
adapter(apiKey: string): { client: ConsultationAdapterClient; retryAfterS(): number | null }
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function createKbTransport(o: KbTransportOptions): KbTransport {
|
|
167
|
+
const fetcher = createKbFetcher(o)
|
|
168
|
+
const endpoint = `${o.base}/graphql`
|
|
169
|
+
|
|
170
|
+
return {
|
|
171
|
+
graphql: ({ token, clientIp }) =>
|
|
172
|
+
createKbClient({
|
|
173
|
+
endpoint,
|
|
174
|
+
isServer: true,
|
|
175
|
+
fetcher,
|
|
176
|
+
tokenStorage: fixedToken(token),
|
|
177
|
+
headers: clientIp ? { [KB_CLIENT_IP_HEADER]: clientIp } : undefined,
|
|
178
|
+
}),
|
|
179
|
+
|
|
180
|
+
adapter: (apiKey) => {
|
|
181
|
+
let retryAfterS: number | null = null
|
|
182
|
+
const adapterFetch: typeof fetch = async (input, init) => {
|
|
183
|
+
const res = await o.fetch()(input, { ...init, cache: 'no-store' })
|
|
184
|
+
retryAfterS = res.ok ? null : retryAfterSeconds(res.headers, o.now())
|
|
185
|
+
return res
|
|
186
|
+
}
|
|
187
|
+
const client = createConsultationAdapterClient({
|
|
188
|
+
baseUrl: o.base,
|
|
189
|
+
apiKey,
|
|
190
|
+
fetch: adapterFetch,
|
|
191
|
+
timeoutMs: o.timeoutMs,
|
|
192
|
+
})
|
|
193
|
+
return { client, retryAfterS: () => retryAfterS }
|
|
194
|
+
},
|
|
195
|
+
}
|
|
196
|
+
}
|