@blogmcp/sdk 0.1.3 → 0.2.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.
@@ -33,6 +33,13 @@ export interface KbClientConfig {
33
33
  tokenStorage?: TokenStorage;
34
34
  /** Whether currently running on server (for endpoint selection). Defaults to false. */
35
35
  isServer?: boolean;
36
+ /**
37
+ * Extra headers sent with every request (e.g. `X-Blogmcp-Client-Ip` from a
38
+ * trusted server proxy). The protocol-critical pair is protected:
39
+ * `Content-Type` and `Authorization` (from tokenStorage) always win over
40
+ * anything in this bag.
41
+ */
42
+ headers?: Record<string, string>;
36
43
  }
37
44
  /** Generates HTML for images in markdown content. Pluggable for IPX, Cloudinary, etc. */
38
45
  export type ImageHtmlRenderer = (href: string, alt: string, title?: string | null) => string;
@@ -1,4 +1,4 @@
1
- import { UPDATE_MY_PROFILE as i, ARTICLE_VERSION as A, UPDATE_MY_REPORT_SETTINGS as S, MY_REPORT_SETTINGS as _, CHANGE_PASSWORD as I, RESEND_VERIFICATION as l, RESET_PASSWORD as R, FORGOT_PASSWORD as c, VERIFY_EMAIL as d, REGISTER as N, LOGIN as O, DELETE_COMMENT as C, UPDATE_COMMENT as L, CREATE_COMMENT as u, GET_COMMENT as h, ARTICLE_COMMENTS as p, GET_TRANSLATION as g, ARTICLE_TRANSLATIONS as G, KB_NAVIGATION as m, KB_LANGUAGES as M, LOCALIZED_TAGS as P, ACCESSIBLE_TAGS as y, GET_KB_CONTEXT as D, SEARCH_KNOWLEDGE_BASE as f, ARTICLE_ALIAS_TARGET as w, ARTICLE_WITH_TRANSLATION_BY_ID as B, ARTICLE_WITH_TRANSLATION as v, ACCESSIBLE_ARTICLES as W } from "./queries.js";
1
+ import { UPDATE_MY_PROFILE as A, ARTICLE_VERSION as i, UPDATE_MY_REPORT_SETTINGS as S, MY_REPORT_SETTINGS as _, CHANGE_PASSWORD as I, RESEND_VERIFICATION as l, RESET_PASSWORD as R, FORGOT_PASSWORD as d, VERIFY_EMAIL as N, REGISTER as O, LOGIN as c, DELETE_COMMENT as C, UPDATE_COMMENT as L, CREATE_COMMENT as h, GET_COMMENT as u, ARTICLE_COMMENTS as p, GET_TRANSLATION as G, ARTICLE_TRANSLATIONS as g, KB_NAVIGATION as m, KB_LANGUAGES as M, LOCALIZED_TAGS as P, ACCESSIBLE_TAGS as y, GET_KB_CONTEXT as D, SEARCH_KNOWLEDGE_BASE as f, ARTICLE_ALIAS_TARGET as w, ARTICLE_WITH_TRANSLATION_BY_ID as B, ARTICLE_WITH_TRANSLATION as v, ACCESSIBLE_ARTICLES as W } from "./queries.js";
2
2
  import { createMemoryTokenStorage as K } from "./auth.js";
3
3
  function k() {
4
4
  return async (n, o) => (await fetch(n, {
@@ -9,6 +9,7 @@ function k() {
9
9
  }
10
10
  async function x(n, o, a) {
11
11
  const E = {
12
+ ...n.headers ?? {},
12
13
  "Content-Type": "application/json"
13
14
  }, s = n.tokenStorage.getToken();
14
15
  s && (E.Authorization = `Bearer ${s}`);
@@ -22,7 +23,7 @@ async function x(n, o, a) {
22
23
  return t.data;
23
24
  }
24
25
  function Y(n) {
25
- const o = n.fetcher || k(), a = n.tokenStorage || K(), s = { endpoint: n.isServer && n.serverEndpoint ? n.serverEndpoint : n.endpoint, fetcher: o, tokenStorage: a };
26
+ const o = n.fetcher || k(), a = n.tokenStorage || K(), s = { endpoint: n.isServer && n.serverEndpoint ? n.serverEndpoint : n.endpoint, fetcher: o, tokenStorage: a, headers: n.headers };
26
27
  function t(e, r) {
27
28
  return x(s, e, r);
28
29
  }
@@ -32,7 +33,7 @@ function Y(n) {
32
33
  getWithTranslation: (e, r) => t(v, { filename: e, languageCode: r }),
33
34
  getWithTranslationById: (e, r) => t(B, { id: e, languageCode: r }),
34
35
  resolveAlias: (e) => t(w, { filename: e }),
35
- getVersion: (e, r) => t(A, { versionId: e, previewKey: r?.previewKey ?? null })
36
+ getVersion: (e, r) => t(i, { versionId: e, previewKey: r?.previewKey ?? null })
36
37
  },
37
38
  search: {
38
39
  query: (e) => t(f, e),
@@ -49,25 +50,25 @@ function Y(n) {
49
50
  get: (e) => t(m, e ?? {})
50
51
  },
51
52
  translations: {
52
- list: (e) => t(G, { sourceFilename: e }),
53
- get: (e, r) => t(g, { sourceFilename: e, languageCode: r })
53
+ list: (e) => t(g, { sourceFilename: e }),
54
+ get: (e, r) => t(G, { sourceFilename: e, languageCode: r })
54
55
  },
55
56
  comments: {
56
57
  list: (e, r) => t(p, { articleId: e, languageCode: r }),
57
- get: (e, r) => t(h, { commentId: e, languageCode: r }),
58
- create: (e) => t(u, e),
58
+ get: (e, r) => t(u, { commentId: e, languageCode: r }),
59
+ create: (e) => t(h, e),
59
60
  update: (e, r) => t(L, { commentId: e, content: r }),
60
61
  delete: (e) => t(C, { commentId: e })
61
62
  },
62
63
  auth: {
63
- login: (e, r) => t(O, { email: e, password: r }),
64
- register: (e, r, T) => t(N, { email: e, password: r, name: T }),
65
- verifyEmail: (e) => t(d, { token: e }),
66
- forgotPassword: (e) => t(c, { email: e }),
64
+ login: (e, r) => t(c, { email: e, password: r }),
65
+ register: (e, r, T) => t(O, { email: e, password: r, name: T }),
66
+ verifyEmail: (e) => t(N, { token: e }),
67
+ forgotPassword: (e) => t(d, { email: e }),
67
68
  resetPassword: (e, r) => t(R, { token: e, password: r }),
68
69
  resendVerification: (e) => t(l, { email: e }),
69
70
  changePassword: (e, r) => t(I, { currentPassword: e, newPassword: r }),
70
- updateProfile: (e) => t(i, {
71
+ updateProfile: (e) => t(A, {
71
72
  name: e.name ?? null,
72
73
  email: e.email ?? null
73
74
  })
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Delegated identity for headless storefronts ("external login").
3
+ *
4
+ * A trusted storefront server that has ALREADY authenticated its own user
5
+ * (a Vendure customer, a Shopify account, any bring-your-own-login) exchanges
6
+ * its internal `kb_*` API key plus the user's email/name for a short-lived,
7
+ * user-scoped KB JWT via `POST {api}/auth/delegated-token`. Requests made with
8
+ * that token author comments and feedback as a real per-user KB identity —
9
+ * ownership, edit/delete-own, and quotas all apply per end user instead of
10
+ * collapsing onto the shared service key.
11
+ *
12
+ * The minted token is deliberately narrow: `accessLevel: 'public'` always and
13
+ * `scope: 'delegated'` (profile/password mutations are rejected server-side).
14
+ *
15
+ * SERVER-ONLY: `createDelegatedTokenMinter` throws when called in a browser
16
+ * context — the internal key must never ship in a client bundle. Keep usage
17
+ * inside server-only modules (e.g. React Router `*.server.ts`, Nuxt server
18
+ * routes).
19
+ */
20
+ export interface DelegatedTokenMinterConfig {
21
+ /**
22
+ * Full URL of the delegated-token endpoint, e.g.
23
+ * `${BLOGMCP_API_URL}/api/auth/delegated-token`.
24
+ */
25
+ endpoint: string;
26
+ /** Internal-access `kb_*` API key. Server-side secret. */
27
+ internalKey: string;
28
+ /**
29
+ * Refresh a cached token this many ms before its expiry. Default 5 minutes
30
+ * (clamped to a non-negative value).
31
+ */
32
+ ttlSkewMs?: number;
33
+ /** Custom fetch implementation (tests / non-global-fetch runtimes). */
34
+ fetchImpl?: typeof fetch;
35
+ }
36
+ export interface DelegatedMintInput {
37
+ /** End-user email as verified by the delegating storefront. */
38
+ email: string;
39
+ /** Display name shown as the comment author (e.g. "Jana N."). */
40
+ name?: string;
41
+ /**
42
+ * Stable caller-side user reference, e.g. `vendure:customer:42`. Stored for
43
+ * audit on the kb user row and used as the cache key (falls back to the
44
+ * normalized email when omitted).
45
+ */
46
+ externalRef?: string;
47
+ }
48
+ export interface DelegatedIdentity {
49
+ /** Short-lived user-scoped KB JWT — send as `Authorization: Bearer <token>`. */
50
+ token: string;
51
+ /** The kb user id the token acts as (matches `Comment.userId`). */
52
+ kbUserId: string;
53
+ email: string;
54
+ name: string | null;
55
+ /** True when this mint created the kb user row (first visit). */
56
+ created: boolean;
57
+ /** Epoch ms when the token expires. */
58
+ expiresAt: number;
59
+ }
60
+ /** Thrown on a non-2xx or malformed response from the delegated-token endpoint. */
61
+ export declare class DelegatedTokenError extends Error {
62
+ readonly status: number;
63
+ constructor(status: number, message: string);
64
+ }
65
+ export interface DelegatedTokenMinter {
66
+ /**
67
+ * Return a fresh identity for the given end user. Cached per
68
+ * `externalRef` (or normalized email) until close to expiry; concurrent
69
+ * mints for the same user share one request.
70
+ */
71
+ mint(input: DelegatedMintInput): Promise<DelegatedIdentity>;
72
+ /**
73
+ * Drop a cached identity — pass the cache key (the `externalRef`, or the
74
+ * normalized email when no ref was used) or nothing to clear all.
75
+ */
76
+ invalidate(key?: string): void;
77
+ }
78
+ export declare function createDelegatedTokenMinter(config: DelegatedTokenMinterConfig): DelegatedTokenMinter;
@@ -0,0 +1,79 @@
1
+ class m extends Error {
2
+ status;
3
+ constructor(l, d) {
4
+ super(d), this.name = "DelegatedTokenError", this.status = l;
5
+ }
6
+ }
7
+ const p = 300 * 1e3, k = 1024;
8
+ function u(n) {
9
+ return n.toLowerCase().trim();
10
+ }
11
+ function y(n) {
12
+ if (typeof window < "u" && typeof window.document < "u")
13
+ throw new Error(
14
+ "[blogmcp-sdk] createDelegatedTokenMinter is server-only — it holds an internal API key that must never reach the browser."
15
+ );
16
+ if (!n.endpoint) throw new Error("[blogmcp-sdk] delegated-token endpoint is required");
17
+ if (!n.internalKey) throw new Error("[blogmcp-sdk] internalKey is required");
18
+ const l = Math.max(0, n.ttlSkewMs ?? p), d = n.fetchImpl ?? globalThis.fetch, o = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map();
19
+ async function w(t) {
20
+ const r = await d(n.endpoint, {
21
+ method: "POST",
22
+ headers: {
23
+ "Content-Type": "application/json",
24
+ Authorization: `Bearer ${n.internalKey}`
25
+ },
26
+ body: JSON.stringify({
27
+ email: t.email,
28
+ name: t.name,
29
+ externalRef: t.externalRef
30
+ })
31
+ });
32
+ if (!r.ok) {
33
+ let s = `delegated-token request failed with status ${r.status}`;
34
+ try {
35
+ const a = await r.json();
36
+ a?.error && (s = a.error);
37
+ } catch {
38
+ }
39
+ throw new m(r.status, s);
40
+ }
41
+ const e = await r.json();
42
+ if (typeof e?.token != "string" || typeof e.expiresIn != "number" || typeof e.user?.id != "string")
43
+ throw new m(r.status, "delegated-token response is malformed");
44
+ return {
45
+ token: e.token,
46
+ kbUserId: e.user.id,
47
+ email: e.user.email ?? u(t.email),
48
+ name: e.user.name ?? null,
49
+ created: e.user.created === !0,
50
+ expiresAt: Date.now() + e.expiresIn * 1e3
51
+ };
52
+ }
53
+ return {
54
+ async mint(t) {
55
+ if (!t?.email) throw new Error("[blogmcp-sdk] mint() requires an email");
56
+ const r = t.externalRef ?? u(t.email), e = o.get(r);
57
+ if (e && e.expiresAt - Date.now() > l)
58
+ return e;
59
+ const s = c.get(r);
60
+ if (s) return s;
61
+ if (o.size >= k) {
62
+ const i = Date.now();
63
+ for (const [f, h] of o)
64
+ h.expiresAt <= i && o.delete(f);
65
+ }
66
+ const a = w(t).then((i) => (o.set(r, i), i)).finally(() => {
67
+ c.delete(r);
68
+ });
69
+ return c.set(r, a), a;
70
+ },
71
+ invalidate(t) {
72
+ t === void 0 ? o.clear() : o.delete(t);
73
+ }
74
+ };
75
+ }
76
+ export {
77
+ m as DelegatedTokenError,
78
+ y as createDelegatedTokenMinter
79
+ };
@@ -7,6 +7,8 @@ export type { NavNode, NavNodeType, NavBadge, NavGroupLink, NavNextPrev, FlatNav
7
7
  export { navWalk, findNavNode, navBreadcrumbs, navSiblings, navSubtree, navNextPrev, isNavigable, flattenNav, } from './navigation';
8
8
  export type { AuthManager } from './auth';
9
9
  export { createAuthManager, createMemoryTokenStorage, createLocalStorageTokenStorage, decodeJwtUser, hasAccessLevel, } from './auth';
10
+ export { createDelegatedTokenMinter, DelegatedTokenError, } from './delegated-identity';
11
+ export type { DelegatedTokenMinter, DelegatedTokenMinterConfig, DelegatedMintInput, DelegatedIdentity, } from './delegated-identity';
10
12
  export { stripLeadingH1, generateDescription } from './article-seo';
11
13
  export { createMarkedInstance, defaultImageHtml, parseMarkdownSafe } from './markdown';
12
14
  export type { CreateMarkedOptions } from './markdown';
@@ -1,67 +1,70 @@
1
1
  import { ACCESS_LEVEL_ORDER as t } from "./types.js";
2
- import { createKbClient as s } from "./client.js";
3
- import { findNavNode as n, flattenNav as i, isNavigable as m, navBreadcrumbs as p, navNextPrev as f, navSiblings as c, navSubtree as d, navWalk as x } from "./navigation.js";
4
- import { createAuthManager as b, createLocalStorageTokenStorage as u, createMemoryTokenStorage as v, decodeJwtUser as S, hasAccessLevel as T } from "./auth.js";
5
- import { generateDescription as h, stripLeadingH1 as A } from "./article-seo.js";
6
- import { createMarkedInstance as k, defaultImageHtml as M, parseMarkdownSafe as N } from "./markdown.js";
7
- import { deepMerge as I } from "./blog-config.js";
8
- import { retryWithBackoff as E } from "./retry.js";
9
- import { buildThemeCssVars as R, darkenColor as w, hexToHsl as y, hexToRgb as B, hslToRgb as K, lightenColor as U, rgbTriplet as V } from "./theme.js";
10
- import { buildArticleSeo as _, buildHomeSeo as q, buildListPageSeo as z, localizedHref as J, pageUrl as O, stripLocalePrefix as j } from "./seo.js";
11
- import { buildArticleListItem as G, formatArticleDate as Q, resolveArticleAccessLevel as X, toIsoDate as Y } from "./view-model.js";
12
- import { createKbI18n as $, mergeTranslations as ee } from "./i18n.js";
2
+ import { createKbClient as l } from "./client.js";
3
+ import { findNavNode as s, flattenNav as i, isNavigable as m, navBreadcrumbs as p, navNextPrev as f, navSiblings as c, navSubtree as d, navWalk as x } from "./navigation.js";
4
+ import { createAuthManager as b, createLocalStorageTokenStorage as u, createMemoryTokenStorage as v, decodeJwtUser as T, hasAccessLevel as S } from "./auth.js";
5
+ import { DelegatedTokenError as L, createDelegatedTokenMinter as h } from "./delegated-identity.js";
6
+ import { generateDescription as C, stripLeadingH1 as M } from "./article-seo.js";
7
+ import { createMarkedInstance as N, defaultImageHtml as E, parseMarkdownSafe as H } from "./markdown.js";
8
+ import { deepMerge as P } from "./blog-config.js";
9
+ import { retryWithBackoff as w } from "./retry.js";
10
+ import { buildThemeCssVars as B, darkenColor as K, hexToHsl as U, hexToRgb as V, hslToRgb as W, lightenColor as _, rgbTriplet as q } from "./theme.js";
11
+ import { buildArticleSeo as J, buildHomeSeo as O, buildListPageSeo as j, localizedHref as F, pageUrl as G, stripLocalePrefix as Q } from "./seo.js";
12
+ import { buildArticleListItem as Y, formatArticleDate as Z, resolveArticleAccessLevel as $, toIsoDate as ee } from "./view-model.js";
13
+ import { createKbI18n as oe, mergeTranslations as te } from "./i18n.js";
13
14
  import * as e from "./queries.js";
14
- import { prepareProps as oe } from "../packages/mdx-schema/dist/prepareProps.js";
15
- import { componentMetadata as ae, getComponentMetadata as se, getComponentNames as le } from "../packages/mdx-schema/dist/metadata/index.js";
16
- import { default as ie } from "./translations/cs.json.js";
17
- import { default as pe } from "./translations/en.json.js";
15
+ import { prepareProps as le } from "../packages/mdx-schema/dist/prepareProps.js";
16
+ import { componentMetadata as se, getComponentMetadata as ie, getComponentNames as me } from "../packages/mdx-schema/dist/metadata/index.js";
17
+ import { default as fe } from "./translations/cs.json.js";
18
+ import { default as de } from "./translations/en.json.js";
18
19
  export {
19
20
  t as ACCESS_LEVEL_ORDER,
20
- G as buildArticleListItem,
21
- _ as buildArticleSeo,
22
- q as buildHomeSeo,
23
- z as buildListPageSeo,
24
- R as buildThemeCssVars,
25
- ae as componentMetadata,
21
+ L as DelegatedTokenError,
22
+ Y as buildArticleListItem,
23
+ J as buildArticleSeo,
24
+ O as buildHomeSeo,
25
+ j as buildListPageSeo,
26
+ B as buildThemeCssVars,
27
+ se as componentMetadata,
26
28
  b as createAuthManager,
27
- s as createKbClient,
28
- $ as createKbI18n,
29
+ h as createDelegatedTokenMinter,
30
+ l as createKbClient,
31
+ oe as createKbI18n,
29
32
  u as createLocalStorageTokenStorage,
30
- k as createMarkedInstance,
33
+ N as createMarkedInstance,
31
34
  v as createMemoryTokenStorage,
32
- ie as csTranslations,
33
- w as darkenColor,
34
- S as decodeJwtUser,
35
- I as deepMerge,
36
- M as defaultImageHtml,
37
- pe as enTranslations,
38
- n as findNavNode,
35
+ fe as csTranslations,
36
+ K as darkenColor,
37
+ T as decodeJwtUser,
38
+ P as deepMerge,
39
+ E as defaultImageHtml,
40
+ de as enTranslations,
41
+ s as findNavNode,
39
42
  i as flattenNav,
40
- Q as formatArticleDate,
41
- h as generateDescription,
42
- se as getComponentMetadata,
43
- le as getComponentNames,
44
- T as hasAccessLevel,
45
- y as hexToHsl,
46
- B as hexToRgb,
47
- K as hslToRgb,
43
+ Z as formatArticleDate,
44
+ C as generateDescription,
45
+ ie as getComponentMetadata,
46
+ me as getComponentNames,
47
+ S as hasAccessLevel,
48
+ U as hexToHsl,
49
+ V as hexToRgb,
50
+ W as hslToRgb,
48
51
  m as isNavigable,
49
- U as lightenColor,
50
- J as localizedHref,
51
- ee as mergeTranslations,
52
+ _ as lightenColor,
53
+ F as localizedHref,
54
+ te as mergeTranslations,
52
55
  p as navBreadcrumbs,
53
56
  f as navNextPrev,
54
57
  c as navSiblings,
55
58
  d as navSubtree,
56
59
  x as navWalk,
57
- O as pageUrl,
58
- N as parseMarkdownSafe,
59
- oe as prepareProps,
60
+ G as pageUrl,
61
+ H as parseMarkdownSafe,
62
+ le as prepareProps,
60
63
  e as queries,
61
- X as resolveArticleAccessLevel,
62
- E as retryWithBackoff,
63
- V as rgbTriplet,
64
- A as stripLeadingH1,
65
- j as stripLocalePrefix,
66
- Y as toIsoDate
64
+ $ as resolveArticleAccessLevel,
65
+ w as retryWithBackoff,
66
+ q as rgbTriplet,
67
+ M as stripLeadingH1,
68
+ Q as stripLocalePrefix,
69
+ ee as toIsoDate
67
70
  };
@@ -8,7 +8,7 @@ var o, m;
8
8
  function S() {
9
9
  if (m) return o;
10
10
  m = 1;
11
- const t = Symbol("SemVer ANY");
11
+ const t = /* @__PURE__ */ Symbol("SemVer ANY");
12
12
  class i {
13
13
  static get ANY() {
14
14
  return t;
@@ -1,5 +1,5 @@
1
1
  import { inject as m } from "vue";
2
- const o = Symbol("ImgComponent");
2
+ const o = /* @__PURE__ */ Symbol("ImgComponent");
3
3
  function n() {
4
4
  return m(o, "img");
5
5
  }
@@ -1,6 +1,6 @@
1
1
  function s(...n) {
2
2
  const o = n.length === 1 ? n[0] : n[1];
3
- (n.length === 2 ? n[0] : !0) && process.env.NODE_ENV !== "production" && console.warn(o);
3
+ (n.length !== 2 || n[0]) && process.env.NODE_ENV !== "production" && console.warn(o);
4
4
  }
5
5
  function c(...n) {
6
6
  const o = n.length === 1 ? n[0] : n[1];
@@ -2,7 +2,7 @@ import { createKbClient as K } from "../core/client.js";
2
2
  import { createLocalStorageTokenStorage as c, createMemoryTokenStorage as i, createAuthManager as l } from "../core/auth.js";
3
3
  import { createKbI18n as b } from "../core/i18n.js";
4
4
  import { defaultImageHtml as d } from "../core/markdown.js";
5
- const s = Symbol("KbClient"), E = Symbol("KbAuth"), S = Symbol("KbI18n"), _ = Symbol("KbImageRenderer"), R = {
5
+ const s = /* @__PURE__ */ Symbol("KbClient"), E = /* @__PURE__ */ Symbol("KbAuth"), S = /* @__PURE__ */ Symbol("KbI18n"), _ = /* @__PURE__ */ Symbol("KbImageRenderer"), R = {
6
6
  install(o, e) {
7
7
  const t = e.tokenStorage || (typeof window < "u" ? c() : i()), r = K({ ...e, tokenStorage: t }), n = l(t), a = e.i18n || b(e.locale || "en"), m = e.imageRenderer || d;
8
8
  o.provide(s, r), o.provide(E, n), o.provide(S, a), o.provide(_, m);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blogmcp/sdk",
3
- "version": "0.1.3",
3
+ "version": "0.2.1",
4
4
  "description": "Headless SDK for Knowledge Base blog — core client, Vue composables, Nuxt adapter",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -61,8 +61,8 @@
61
61
  }
62
62
  },
63
63
  "dependencies": {
64
- "@blogmcp/mdx-schema": "^0.1.3",
65
- "@blogmcp/sanitize": "^0.1.3",
64
+ "@blogmcp/mdx-schema": "^0.2.1",
65
+ "@blogmcp/sanitize": "^0.2.1",
66
66
  "marked": "^15.0.7"
67
67
  },
68
68
  "optionalDependencies": {
@@ -34,6 +34,13 @@ export interface KbClientConfig {
34
34
  tokenStorage?: TokenStorage
35
35
  /** Whether currently running on server (for endpoint selection). Defaults to false. */
36
36
  isServer?: boolean
37
+ /**
38
+ * Extra headers sent with every request (e.g. `X-Blogmcp-Client-Ip` from a
39
+ * trusted server proxy). The protocol-critical pair is protected:
40
+ * `Content-Type` and `Authorization` (from tokenStorage) always win over
41
+ * anything in this bag.
42
+ */
43
+ headers?: Record<string, string>
37
44
  }
38
45
 
39
46
  /** Generates HTML for images in markdown content. Pluggable for IPX, Cloudinary, etc. */
@@ -44,11 +44,19 @@ function createDefaultFetcher(): Fetcher {
44
44
 
45
45
  /** Execute a GraphQL query and return typed data */
46
46
  async function executeGraphQL<T>(
47
- config: { endpoint: string; fetcher: Fetcher; tokenStorage: TokenStorage },
47
+ config: {
48
+ endpoint: string
49
+ fetcher: Fetcher
50
+ tokenStorage: TokenStorage
51
+ headers?: Record<string, string>
52
+ },
48
53
  query: string,
49
54
  variables?: Record<string, unknown>,
50
55
  ): Promise<T> {
56
+ // Extra headers first; the protocol-critical pair (Content-Type,
57
+ // Authorization) is applied after so a headers bag can never displace them.
51
58
  const headers: Record<string, string> = {
59
+ ...(config.headers ?? {}),
52
60
  'Content-Type': 'application/json',
53
61
  }
54
62
 
@@ -239,7 +247,7 @@ export function createKbClient(config: KbClientConfig): KbClient {
239
247
  ? config.serverEndpoint
240
248
  : config.endpoint
241
249
 
242
- const ctx = { endpoint, fetcher, tokenStorage }
250
+ const ctx = { endpoint, fetcher, tokenStorage, headers: config.headers }
243
251
 
244
252
  function exec<T>(query: string, variables?: Record<string, unknown>) {
245
253
  return executeGraphQL<T>(ctx, query, variables)
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Delegated identity for headless storefronts ("external login").
3
+ *
4
+ * A trusted storefront server that has ALREADY authenticated its own user
5
+ * (a Vendure customer, a Shopify account, any bring-your-own-login) exchanges
6
+ * its internal `kb_*` API key plus the user's email/name for a short-lived,
7
+ * user-scoped KB JWT via `POST {api}/auth/delegated-token`. Requests made with
8
+ * that token author comments and feedback as a real per-user KB identity —
9
+ * ownership, edit/delete-own, and quotas all apply per end user instead of
10
+ * collapsing onto the shared service key.
11
+ *
12
+ * The minted token is deliberately narrow: `accessLevel: 'public'` always and
13
+ * `scope: 'delegated'` (profile/password mutations are rejected server-side).
14
+ *
15
+ * SERVER-ONLY: `createDelegatedTokenMinter` throws when called in a browser
16
+ * context — the internal key must never ship in a client bundle. Keep usage
17
+ * inside server-only modules (e.g. React Router `*.server.ts`, Nuxt server
18
+ * routes).
19
+ */
20
+
21
+ export interface DelegatedTokenMinterConfig {
22
+ /**
23
+ * Full URL of the delegated-token endpoint, e.g.
24
+ * `${BLOGMCP_API_URL}/api/auth/delegated-token`.
25
+ */
26
+ endpoint: string
27
+ /** Internal-access `kb_*` API key. Server-side secret. */
28
+ internalKey: string
29
+ /**
30
+ * Refresh a cached token this many ms before its expiry. Default 5 minutes
31
+ * (clamped to a non-negative value).
32
+ */
33
+ ttlSkewMs?: number
34
+ /** Custom fetch implementation (tests / non-global-fetch runtimes). */
35
+ fetchImpl?: typeof fetch
36
+ }
37
+
38
+ export interface DelegatedMintInput {
39
+ /** End-user email as verified by the delegating storefront. */
40
+ email: string
41
+ /** Display name shown as the comment author (e.g. "Jana N."). */
42
+ name?: string
43
+ /**
44
+ * Stable caller-side user reference, e.g. `vendure:customer:42`. Stored for
45
+ * audit on the kb user row and used as the cache key (falls back to the
46
+ * normalized email when omitted).
47
+ */
48
+ externalRef?: string
49
+ }
50
+
51
+ export interface DelegatedIdentity {
52
+ /** Short-lived user-scoped KB JWT — send as `Authorization: Bearer <token>`. */
53
+ token: string
54
+ /** The kb user id the token acts as (matches `Comment.userId`). */
55
+ kbUserId: string
56
+ email: string
57
+ name: string | null
58
+ /** True when this mint created the kb user row (first visit). */
59
+ created: boolean
60
+ /** Epoch ms when the token expires. */
61
+ expiresAt: number
62
+ }
63
+
64
+ /** Thrown on a non-2xx or malformed response from the delegated-token endpoint. */
65
+ export class DelegatedTokenError extends Error {
66
+ readonly status: number
67
+
68
+ constructor(status: number, message: string) {
69
+ super(message)
70
+ this.name = 'DelegatedTokenError'
71
+ this.status = status
72
+ }
73
+ }
74
+
75
+ export interface DelegatedTokenMinter {
76
+ /**
77
+ * Return a fresh identity for the given end user. Cached per
78
+ * `externalRef` (or normalized email) until close to expiry; concurrent
79
+ * mints for the same user share one request.
80
+ */
81
+ mint(input: DelegatedMintInput): Promise<DelegatedIdentity>
82
+ /**
83
+ * Drop a cached identity — pass the cache key (the `externalRef`, or the
84
+ * normalized email when no ref was used) or nothing to clear all.
85
+ */
86
+ invalidate(key?: string): void
87
+ }
88
+
89
+ const DEFAULT_TTL_SKEW_MS = 5 * 60 * 1000
90
+
91
+ /**
92
+ * Cache-size threshold that triggers a sweep of expired identities. Without
93
+ * it, one entry per distinct end user would accumulate for the lifetime of
94
+ * the server process (unbounded heap growth on large storefronts). Entries
95
+ * are tiny, so the sweep is deliberately lazy — amortized into mint() rather
96
+ * than a timer.
97
+ */
98
+ const CACHE_SWEEP_THRESHOLD = 1024
99
+
100
+ interface DelegatedTokenResponse {
101
+ token: string
102
+ /** Token lifetime in seconds. */
103
+ expiresIn: number
104
+ user: { id: string; email: string; name: string | null; created: boolean }
105
+ }
106
+
107
+ function normalizeEmail(email: string): string {
108
+ return email.toLowerCase().trim()
109
+ }
110
+
111
+ export function createDelegatedTokenMinter(
112
+ config: DelegatedTokenMinterConfig,
113
+ ): DelegatedTokenMinter {
114
+ if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {
115
+ throw new Error(
116
+ '[blogmcp-sdk] createDelegatedTokenMinter is server-only — it holds an ' +
117
+ 'internal API key that must never reach the browser.',
118
+ )
119
+ }
120
+ if (!config.endpoint) throw new Error('[blogmcp-sdk] delegated-token endpoint is required')
121
+ if (!config.internalKey) throw new Error('[blogmcp-sdk] internalKey is required')
122
+
123
+ const ttlSkewMs = Math.max(0, config.ttlSkewMs ?? DEFAULT_TTL_SKEW_MS)
124
+ const fetchImpl = config.fetchImpl ?? globalThis.fetch
125
+ const cache = new Map<string, DelegatedIdentity>()
126
+ const inFlight = new Map<string, Promise<DelegatedIdentity>>()
127
+
128
+ async function requestToken(input: DelegatedMintInput): Promise<DelegatedIdentity> {
129
+ const res = await fetchImpl(config.endpoint, {
130
+ method: 'POST',
131
+ headers: {
132
+ 'Content-Type': 'application/json',
133
+ Authorization: `Bearer ${config.internalKey}`,
134
+ },
135
+ body: JSON.stringify({
136
+ email: input.email,
137
+ name: input.name,
138
+ externalRef: input.externalRef,
139
+ }),
140
+ })
141
+
142
+ if (!res.ok) {
143
+ let message = `delegated-token request failed with status ${res.status}`
144
+ try {
145
+ const body = (await res.json()) as { error?: string }
146
+ if (body?.error) message = body.error
147
+ } catch {
148
+ // Non-JSON error body — keep the status message.
149
+ }
150
+ throw new DelegatedTokenError(res.status, message)
151
+ }
152
+
153
+ const body = (await res.json()) as Partial<DelegatedTokenResponse>
154
+ if (
155
+ typeof body?.token !== 'string' ||
156
+ typeof body.expiresIn !== 'number' ||
157
+ typeof body.user?.id !== 'string'
158
+ ) {
159
+ throw new DelegatedTokenError(res.status, 'delegated-token response is malformed')
160
+ }
161
+
162
+ return {
163
+ token: body.token,
164
+ kbUserId: body.user.id,
165
+ email: body.user.email ?? normalizeEmail(input.email),
166
+ name: body.user.name ?? null,
167
+ created: body.user.created === true,
168
+ expiresAt: Date.now() + body.expiresIn * 1000,
169
+ }
170
+ }
171
+
172
+ return {
173
+ async mint(input: DelegatedMintInput): Promise<DelegatedIdentity> {
174
+ if (!input?.email) throw new Error('[blogmcp-sdk] mint() requires an email')
175
+ const key = input.externalRef ?? normalizeEmail(input.email)
176
+
177
+ const cached = cache.get(key)
178
+ if (cached && cached.expiresAt - Date.now() > ttlSkewMs) {
179
+ return cached
180
+ }
181
+
182
+ const pending = inFlight.get(key)
183
+ if (pending) return pending
184
+
185
+ // Lazy eviction: once the cache is large, drop everything already
186
+ // expired so long-lived processes don't pin one entry per user forever.
187
+ if (cache.size >= CACHE_SWEEP_THRESHOLD) {
188
+ const now = Date.now()
189
+ for (const [k, v] of cache) {
190
+ if (v.expiresAt <= now) cache.delete(k)
191
+ }
192
+ }
193
+
194
+ const promise = requestToken(input)
195
+ .then((identity) => {
196
+ cache.set(key, identity)
197
+ return identity
198
+ })
199
+ .finally(() => {
200
+ inFlight.delete(key)
201
+ })
202
+ inFlight.set(key, promise)
203
+ return promise
204
+ },
205
+
206
+ invalidate(key?: string): void {
207
+ if (key === undefined) {
208
+ cache.clear()
209
+ } else {
210
+ cache.delete(key)
211
+ }
212
+ },
213
+ }
214
+ }
package/src/core/index.ts CHANGED
@@ -65,6 +65,18 @@ export {
65
65
  hasAccessLevel,
66
66
  } from './auth'
67
67
 
68
+ // Delegated identity (server-only — headless storefront "external login")
69
+ export {
70
+ createDelegatedTokenMinter,
71
+ DelegatedTokenError,
72
+ } from './delegated-identity'
73
+ export type {
74
+ DelegatedTokenMinter,
75
+ DelegatedTokenMinterConfig,
76
+ DelegatedMintInput,
77
+ DelegatedIdentity,
78
+ } from './delegated-identity'
79
+
68
80
  // Content utilities
69
81
  export { stripLeadingH1, generateDescription } from './article-seo'
70
82
  export { createMarkedInstance, defaultImageHtml, parseMarkdownSafe } from './markdown'