nuxt-kirby 4.0.0 โ†’ 4.1.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/README.md CHANGED
@@ -2,19 +2,19 @@
2
2
 
3
3
  # Nuxt Kirby
4
4
 
5
- [Nuxt](https://nuxt.com) module to interact with [Kirby CMS](https://getkirby.com) with support for [Kirby's Query Language](https://github.com/getkirby/kql) API.
5
+ [Kirby CMS](https://getkirby.com) data in [Nuxt](https://nuxt.com), via [KQL](https://github.com/getkirby/kql) or the REST API.
6
6
 
7
7
  - [โœจ  Release Notes](https://github.com/johannschopplich/nuxt-kirby/releases)
8
8
  - [๐Ÿ“–  Read the documentation](https://nuxt-kirby.byjohann.dev)
9
9
 
10
10
  ## Features
11
11
 
12
- - ๐Ÿ”’ Protected Kirby credentials when sending queries
12
+ - ๐Ÿ”’ Protected Kirby credentials on every request
13
13
  - ๐Ÿชข Supports token-based authentication with the [Kirby Headless plugin](https://kirby.tools/docs/headless/getting-started/) (recommended)
14
- - ๐Ÿฑ Handle requests just like with the [`useFetch`](https://nuxt.com/docs/getting-started/data-fetching) composable
14
+ - ๐Ÿฑ Handle requests just like with the [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch) composable
15
15
  - ๐Ÿฆฆ [Multiple starter kits](https://nuxt-kirby.byjohann.dev/essentials/starter-kits) available
16
16
  - ๐Ÿ—ƒ Cached query responses
17
- - ๐Ÿคน No CORS issues!
17
+ - ๐Ÿคน No CORS issues
18
18
  - ๐Ÿฆพ Strongly typed
19
19
 
20
20
  ## Setup
package/dist/module.d.mts CHANGED
@@ -36,17 +36,32 @@ interface ModuleOptions {
36
36
  password: string;
37
37
  };
38
38
  /**
39
- * Send client-side requests instead of using the server-side proxy.
39
+ * Send queries straight from the browser instead of through the server-side proxy.
40
40
  *
41
41
  * @remarks
42
- * By default, data from Kirby is fetched safely with a server-side proxy.
43
- * If enabled, query requests will be sent directly from the client.
44
- * Note: This means your token or user credentials will be publicly visible.
45
- * If Nuxt SSR is disabled, this option is enabled by default.
42
+ * Leaving this off is what keeps your token out of the client bundle. Turn it on only for an
43
+ * instance whose credentials may be public, or one that needs none.
44
+ *
45
+ * If Nuxt SSR is disabled, this is enabled by default, because there is no server to proxy
46
+ * through.
46
47
  *
47
48
  * @default false
48
49
  */
49
50
  client?: boolean;
51
+ /**
52
+ * Forward the visitor's cookies to Kirby.
53
+ *
54
+ * @remarks
55
+ * A Kirby session lives in a cookie, so without this a logged-in visitor still receives the
56
+ * logged-out response. Turning it on skips the server-side cache, whether or not the visitor
57
+ * actually sent a cookie โ€“ one stored response is shared between all visitors.
58
+ *
59
+ * Individual calls override this through the `forwardCookies` option of `useKql`, `useKirbyData`,
60
+ * `$kql` and `$kirby`.
61
+ *
62
+ * @default false
63
+ */
64
+ forwardCookies?: boolean;
50
65
  /**
51
66
  * Prefetch custom KQL queries at build-time.
52
67
  *
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=4.0.0"
6
6
  },
7
- "version": "4.0.0",
7
+ "version": "4.1.1",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.3",
10
10
  "unbuild": "unknown"
package/dist/module.mjs CHANGED
@@ -79,6 +79,7 @@ const module$1 = defineNuxtModule({
79
79
  password: process.env.KIRBY_API_PASSWORD || ""
80
80
  },
81
81
  client: false,
82
+ forwardCookies: false,
82
83
  prefetch: {},
83
84
  server: {
84
85
  cache: false,
@@ -13,6 +13,14 @@ export type KirbyFetchOptions = Pick<NitroFetchOptions<string>, 'onRequest' | 'o
13
13
  * @default true
14
14
  */
15
15
  payloadCache?: boolean;
16
+ /**
17
+ * Forward the visitor's cookies to Kirby, overriding the module's `forwardCookies`.
18
+ *
19
+ * @remarks
20
+ * Such a request never reads from or writes to the server-side cache, since one stored response
21
+ * is shared between all visitors.
22
+ */
23
+ forwardCookies?: boolean;
16
24
  /**
17
25
  * Cache key, generated from the request options by default.
18
26
  */
@@ -9,7 +9,9 @@ export function $kirby(path, opts = {}) {
9
9
  opts.method,
10
10
  opts.query,
11
11
  opts.body,
12
- opts.language
12
+ opts.language,
13
+ opts.forwardCookies,
14
+ headersToObject(opts.headers)
13
15
  ])}`;
14
16
  return sendCachedRequest(key, payloadCache, () => sendKirbyRequest(path, { ...requestOptions, key }));
15
17
  }
@@ -22,6 +24,7 @@ export function sendKirbyRequest(path, opts) {
22
24
  body,
23
25
  language,
24
26
  key,
27
+ forwardCookies,
25
28
  ...fetchOptions
26
29
  } = opts;
27
30
  const sharedHeaders = {
@@ -35,7 +38,8 @@ export function sendKirbyRequest(path, opts) {
35
38
  method,
36
39
  query,
37
40
  body,
38
- headers: sharedHeaders
41
+ headers: sharedHeaders,
42
+ forwardCookies
39
43
  }
40
44
  };
41
45
  const _clientFetchOptions = {
@@ -46,7 +50,9 @@ export function sendKirbyRequest(path, opts) {
46
50
  ...sharedHeaders,
47
51
  ...createAuthHeader(kirby)
48
52
  },
49
- body
53
+ body,
54
+ // There is no proxy to forward anything here, so the browser has to attach the cookie itself.
55
+ credentials: forwardCookies ?? kirby.forwardCookies ? "include" : void 0
50
56
  };
51
57
  return useRequestFetch()(kirby.client ? path : buildApiProxyPath(key), {
52
58
  ...fetchOptions,
@@ -10,6 +10,14 @@ export type KqlOptions = Pick<NitroFetchOptions<string>, 'onRequest' | 'onReques
10
10
  * @default true
11
11
  */
12
12
  payloadCache?: boolean;
13
+ /**
14
+ * Forward the visitor's cookies to Kirby, overriding the module's `forwardCookies`.
15
+ *
16
+ * @remarks
17
+ * Such a request never reads from or writes to the server-side cache, since one stored response
18
+ * is shared between all visitors.
19
+ */
20
+ forwardCookies?: boolean;
13
21
  /**
14
22
  * Cache key, generated from the request options by default.
15
23
  */
@@ -4,7 +4,12 @@ import { sendCachedRequest } from "../cache.js";
4
4
  import { buildApiProxyPath, createAuthHeader, createLanguageHeader, headersToObject } from "../utils.js";
5
5
  export function $kql(query, opts = {}) {
6
6
  const { payloadCache = true, ...requestOptions } = opts;
7
- const key = opts.key || `$kql${hash([query, opts.language])}`;
7
+ const key = opts.key || `$kql${hash([
8
+ query,
9
+ opts.language,
10
+ opts.forwardCookies,
11
+ headersToObject(opts.headers)
12
+ ])}`;
8
13
  return sendCachedRequest(key, payloadCache, () => sendKqlRequest(query, { ...requestOptions, key }));
9
14
  }
10
15
  export function sendKqlRequest(query, opts) {
@@ -13,6 +18,7 @@ export function sendKqlRequest(query, opts) {
13
18
  headers,
14
19
  language,
15
20
  key,
21
+ forwardCookies,
16
22
  ...fetchOptions
17
23
  } = opts;
18
24
  const sharedHeaders = {
@@ -23,7 +29,8 @@ export function sendKqlRequest(query, opts) {
23
29
  method: "POST",
24
30
  body: {
25
31
  query,
26
- headers: sharedHeaders
32
+ headers: sharedHeaders,
33
+ forwardCookies
27
34
  }
28
35
  };
29
36
  const _clientFetchOptions = {
@@ -33,7 +40,9 @@ export function sendKqlRequest(query, opts) {
33
40
  ...sharedHeaders,
34
41
  ...createAuthHeader(kirby)
35
42
  },
36
- body: query
43
+ body: query,
44
+ // There is no proxy to forward anything here, so the browser has to attach the cookie itself.
45
+ credentials: forwardCookies ?? kirby.forwardCookies ? "include" : void 0
37
46
  };
38
47
  return useRequestFetch()(kirby.client ? kirby.kqlPath : buildApiProxyPath(key), {
39
48
  ...fetchOptions,
@@ -10,6 +10,14 @@ export type UseKirbyDataOptions<T> = Omit<AsyncDataOptions<T>, 'watch'> & Pick<N
10
10
  * reads it on the global-routes catch-all, but only for a path that names no language itself.
11
11
  */
12
12
  language?: MaybeRefOrGetter<string>;
13
+ /**
14
+ * Forward the visitor's cookies to Kirby, overriding the module's `forwardCookies`.
15
+ *
16
+ * @remarks
17
+ * Such a request never reads from or writes to the server-side cache, since one stored response
18
+ * is shared between all visitors.
19
+ */
20
+ forwardCookies?: boolean;
13
21
  /**
14
22
  * Watch an array of reactive sources and auto-refresh the fetch result when they change.
15
23
  * Path and language are watched by default. You can completely ignore reactive sources by using `watch: false`.
@@ -1,9 +1,10 @@
1
1
  import { hash } from "ohash";
2
2
  import { computed, toValue } from "vue";
3
3
  import { useFetch } from "#imports";
4
+ import { headersToObject } from "../utils.js";
4
5
  import { sendKirbyRequest } from "./$kirby.js";
5
6
  export function useKirbyData(path, opts = {}) {
6
- const { language, ...fetchOptions } = opts;
7
+ const { language, forwardCookies, ...fetchOptions } = opts;
7
8
  const _language = computed(() => toValue(language));
8
9
  const _path = computed(() => toValue(path).replace(/^\//, ""));
9
10
  const key = computed(() => `$kirby${hash([
@@ -11,7 +12,9 @@ export function useKirbyData(path, opts = {}) {
11
12
  _language.value,
12
13
  toValue(fetchOptions.query),
13
14
  toValue(fetchOptions.method),
14
- toValue(fetchOptions.body)
15
+ toValue(fetchOptions.body),
16
+ forwardCookies,
17
+ headersToObject(toValue(fetchOptions.headers))
15
18
  ])}`);
16
19
  if (!_path.value)
17
20
  console.warn("[nuxt-kirby] Empty Kirby path");
@@ -21,6 +24,7 @@ export function useKirbyData(path, opts = {}) {
21
24
  $fetch: ((_request, options) => sendKirbyRequest(_path.value, {
22
25
  ...options,
23
26
  language: _language.value,
27
+ forwardCookies,
24
28
  key: key.value
25
29
  }))
26
30
  });
@@ -7,6 +7,14 @@ export type UseKqlOptions<T> = Omit<AsyncDataOptions<T>, 'watch'> & Pick<NitroFe
7
7
  * Language code to fetch data for in multi-language Kirby setups.
8
8
  */
9
9
  language?: MaybeRefOrGetter<string>;
10
+ /**
11
+ * Forward the visitor's cookies to Kirby, overriding the module's `forwardCookies`.
12
+ *
13
+ * @remarks
14
+ * Such a request never reads from or writes to the server-side cache, since one stored response
15
+ * is shared between all visitors.
16
+ */
17
+ forwardCookies?: boolean;
10
18
  /**
11
19
  * Watch an array of reactive sources and auto-refresh the fetch result when they change.
12
20
  * Query and language are watched by default. You can completely ignore reactive sources by using `watch: false`.
@@ -1,12 +1,18 @@
1
1
  import { hash } from "ohash";
2
2
  import { computed, toValue } from "vue";
3
3
  import { useFetch } from "#imports";
4
+ import { headersToObject } from "../utils.js";
4
5
  import { sendKqlRequest } from "./$kql.js";
5
6
  export function useKql(query, opts = {}) {
6
- const { language, ...fetchOptions } = opts;
7
+ const { language, forwardCookies, ...fetchOptions } = opts;
7
8
  const _query = computed(() => toValue(query));
8
9
  const _language = computed(() => toValue(language));
9
- const key = computed(() => `$kql${hash([_query.value, _language.value])}`);
10
+ const key = computed(() => `$kql${hash([
11
+ _query.value,
12
+ _language.value,
13
+ forwardCookies,
14
+ headersToObject(toValue(fetchOptions.headers))
15
+ ])}`);
10
16
  if (Object.keys(_query.value).length === 0 || !_query.value.query)
11
17
  console.error("[nuxt-kirby] Empty KQL query");
12
18
  return useFetch(key, {
@@ -15,6 +21,7 @@ export function useKql(query, opts = {}) {
15
21
  $fetch: ((_request, options) => sendKqlRequest(_query.value, {
16
22
  ...options,
17
23
  language: _language.value,
24
+ forwardCookies,
18
25
  key: key.value
19
26
  }))
20
27
  });
@@ -1,10 +1,11 @@
1
1
  import { destr } from "destr";
2
- import { createError, defineEventHandler, getRouterParam, readBody, setResponseHeader, setResponseStatus, splitCookiesString } from "h3";
2
+ import { createError, defineEventHandler, getRequestHeader, getRouterParam, readBody, setResponseHeader, setResponseStatus, splitCookiesString } from "h3";
3
3
  import { defineCachedFunction } from "nitropack/runtime";
4
4
  import { hash } from "ohash";
5
5
  import { base64ToUint8Array, uint8ArrayToBase64, uint8ArrayToString } from "uint8array-extras";
6
6
  import { useRuntimeConfig } from "#imports";
7
- import { createAuthHeader } from "../utils.js";
7
+ import { createAuthHeader, headersToObject } from "../utils.js";
8
+ import { assertPathBelowBase } from "./path.js";
8
9
  const EXCLUDED_HEADERS = /* @__PURE__ */ new Set([
9
10
  // https://github.com/h3js/h3/blob/fe9800bbbe9bda2972cc5d11db7353f4ab70f0ba/src/utils/proxy.ts#L97
10
11
  "content-encoding",
@@ -19,9 +20,11 @@ async function fetchFromKirby(event, {
19
20
  path,
20
21
  headers,
21
22
  method,
22
- body
23
+ body,
24
+ forwardCookies
23
25
  }) {
24
26
  const kirby = useRuntimeConfig(event).kirby;
27
+ const cookie = forwardCookies ? getRequestHeader(event, "cookie") : void 0;
25
28
  const response = await globalThis.$fetch.raw(isQueryRequest ? kirby.kqlPath : path, {
26
29
  responseType: "arrayBuffer",
27
30
  ignoreResponseError: true,
@@ -36,6 +39,7 @@ async function fetchFromKirby(event, {
36
39
  },
37
40
  headers: {
38
41
  ...headers,
42
+ ...cookie ? { cookie } : {},
39
43
  ...createAuthHeader(kirby)
40
44
  }
41
45
  });
@@ -51,8 +55,14 @@ function createCachedFetcher(kirby) {
51
55
  // Nitro reads the event from the first argument only, and hands the cache write to
52
56
  // `event.waitUntil()` โ€“ without it an edge worker is torn down before the entry reaches storage.
53
57
  async (event, options) => {
54
- const { data, ...rest } = await fetchFromKirby(event, options);
55
- return { ...rest, data: uint8ArrayToBase64(data) };
58
+ const { data, headers, ...rest } = await fetchFromKirby(event, options);
59
+ return {
60
+ ...rest,
61
+ // A stored `set-cookie` would hand every later visitor on this key the session Kirby
62
+ // issued for the first one.
63
+ headers: headers.filter(([key]) => key !== "set-cookie"),
64
+ data: uint8ArrayToBase64(data)
65
+ };
56
66
  },
57
67
  {
58
68
  name: "nuxt-kirby",
@@ -67,7 +77,7 @@ function createCachedFetcher(kirby) {
67
77
  let cachedFetcher;
68
78
  export default defineEventHandler(async (event) => {
69
79
  const kirby = useRuntimeConfig(event).kirby;
70
- const body = await readBody(event);
80
+ const body = await readBody(event) ?? {};
71
81
  const key = decodeURIComponent(getRouterParam(event, "key"));
72
82
  const isQueryRequest = key.startsWith("$kql");
73
83
  if (isQueryRequest) {
@@ -78,21 +88,33 @@ export default defineEventHandler(async (event) => {
78
88
  });
79
89
  }
80
90
  } else {
81
- if (body.path && new URL(body.path, "http://localhost").origin !== "http://localhost") {
91
+ if (typeof body.path !== "string") {
82
92
  throw createError({
83
93
  statusCode: 400,
84
- statusMessage: "Absolute URLs are not allowed"
94
+ statusMessage: "Path must be a string"
85
95
  });
86
96
  }
97
+ assertPathBelowBase(body.path);
87
98
  }
99
+ let headers;
100
+ try {
101
+ headers = headersToObject(body.headers ?? void 0);
102
+ } catch {
103
+ throw createError({
104
+ statusCode: 400,
105
+ statusMessage: "Headers are invalid"
106
+ });
107
+ }
108
+ const forwardCookies = body.forwardCookies ?? kirby.forwardCookies;
88
109
  try {
89
110
  let response;
90
- if (kirby.server.cache) {
111
+ const request = { ...body, headers, isQueryRequest, forwardCookies };
112
+ if (kirby.server.cache && !forwardCookies) {
91
113
  cachedFetcher ??= createCachedFetcher(kirby);
92
- const cached = await cachedFetcher(event, { isQueryRequest, ...body });
114
+ const cached = await cachedFetcher(event, request);
93
115
  response = { ...cached, data: base64ToUint8Array(cached.data) };
94
116
  } else {
95
- response = await fetchFromKirby(event, { isQueryRequest, ...body });
117
+ response = await fetchFromKirby(event, request);
96
118
  }
97
119
  const dataArray = response.data;
98
120
  if (response.status >= 400 && response.status < 600) {
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Throws a 400 for a path that a URL parser or the server behind the Kirby URL could read as absolute
3
+ * or as climbing above it: a scheme, an authority, a tab or line break, or a `..` segment, also
4
+ * percent-encoded or with a `;` parameter.
5
+ */
6
+ export declare function assertPathBelowBase(path: string): void;
@@ -0,0 +1,10 @@
1
+ import { createError } from "h3";
2
+ export function assertPathBelowBase(path) {
3
+ const segments = path.split("?", 1)[0].replace(/%2e/gi, ".").replace(/%3b/gi, ";").split(/[/\\#]|%2f|%5c/i);
4
+ if (/[\t\n\r\u2028\u2029]/.test(path) || /^[^/?#]*:/.test(path) || /^[\s\u0000-\u001F]*(?:[/\\]\s*){2}/.test(path) || segments.some((segment) => /^\.\.(?:;|[\u0000-\u0020]*$)/.test(segment))) {
5
+ throw createError({
6
+ statusCode: 400,
7
+ statusMessage: "Path must stay below the Kirby URL"
8
+ });
9
+ }
10
+ }
@@ -4,6 +4,8 @@ export interface ServerFetchOptions extends Pick<NitroFetchOptions<string>, 'met
4
4
  /** A request carries one or the other: `query` for KQL, `path` for the REST API. */
5
5
  query?: Partial<KirbyQueryRequest>;
6
6
  path?: string;
7
+ /** Overrides the module's `forwardCookies` for this request. Absent leaves the decision to it. */
8
+ forwardCookies?: boolean;
7
9
  }
8
10
  export interface ServerFetchRequest extends ServerFetchOptions {
9
11
  isQueryRequest: boolean;
package/package.json CHANGED
@@ -1,9 +1,8 @@
1
1
  {
2
2
  "name": "nuxt-kirby",
3
3
  "type": "module",
4
- "version": "4.0.0",
5
- "packageManager": "pnpm@11.20.0",
6
- "description": "Kirby CMS integration for Nuxt with KQL support",
4
+ "version": "4.1.1",
5
+ "description": "Kirby CMS data in Nuxt, via KQL or the REST API",
7
6
  "author": "Johann Schopplich <hello@johannschopplich.com>",
8
7
  "license": "MIT",
9
8
  "homepage": "https://nuxt-kirby.byjohann.dev",
@@ -15,11 +14,11 @@
15
14
  "url": "https://github.com/johannschopplich/nuxt-kirby/issues"
16
15
  },
17
16
  "keywords": [
18
- "getkirby",
19
17
  "kirby",
20
- "kql",
18
+ "kirby-cms",
19
+ "getkirby",
21
20
  "nuxt",
22
- "query"
21
+ "kql"
23
22
  ],
24
23
  "sideEffects": false,
25
24
  "exports": {
@@ -33,25 +32,11 @@
33
32
  "files": [
34
33
  "dist"
35
34
  ],
36
- "scripts": {
37
- "prepack": "nuxt-module-build build",
38
- "dev": "nuxt dev playground",
39
- "dev:build": "nuxt build playground",
40
- "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt prepare playground && nuxt prepare test/fixture",
41
- "docs:dev": "pnpm --filter docs run dev",
42
- "docs:build": "pnpm --filter docs run build",
43
- "docs:preview": "pnpm --filter docs run preview",
44
- "lint": "eslint .",
45
- "lint:fix": "eslint . --fix",
46
- "test": "vitest",
47
- "test:types": "tsc --noEmit",
48
- "release": "bumpp"
49
- },
50
35
  "dependencies": {
51
36
  "@nuxt/kit": "^4.5.2",
52
37
  "defu": "^6.1.7",
53
38
  "destr": "^2.0.5",
54
- "kirby-types": "^1.6.0",
39
+ "kirby-types": "^1.8.1",
55
40
  "ofetch": "^1.5.1",
56
41
  "ohash": "^2.0.11",
57
42
  "pathe": "^2.0.3",
@@ -72,5 +57,18 @@
72
57
  "srvx": "^0.12.5",
73
58
  "typescript": "^6.0.3",
74
59
  "vitest": "^4.1.10"
60
+ },
61
+ "scripts": {
62
+ "dev": "nuxt dev playground",
63
+ "dev:build": "nuxt build playground",
64
+ "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt prepare playground && nuxt prepare test/fixture",
65
+ "docs:dev": "pnpm --filter docs run dev",
66
+ "docs:build": "pnpm --filter docs run build",
67
+ "docs:preview": "pnpm --filter docs run preview",
68
+ "lint": "eslint .",
69
+ "lint:fix": "eslint . --fix",
70
+ "test": "vitest",
71
+ "test:types": "tsc --noEmit",
72
+ "release": "bumpp"
75
73
  }
76
- }
74
+ }