nuxt-kirby 4.1.0 → 4.2.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/README.md CHANGED
@@ -19,19 +19,20 @@
19
19
 
20
20
  ## Setup
21
21
 
22
+ Add the module to a project on Nuxt 4 or later:
23
+
22
24
  ```bash
23
25
  npx nuxt module add kirby
24
26
  ```
25
27
 
26
28
  ## Basic Usage
27
29
 
28
- Add Nuxt Kirby to your Nuxt configuration:
30
+ Set your Kirby credentials in `.env`. This example uses basic authentication with the [KQL plugin](https://github.com/getkirby/kql); [Getting Started](https://nuxt-kirby.byjohann.dev/essentials/getting-started) sets up token authentication instead:
29
31
 
30
- ```ts
31
- // `nuxt.config.ts`
32
- export default defineNuxtConfig({
33
- modules: ['nuxt-kirby']
34
- })
32
+ ```ini
33
+ KIRBY_BASE_URL=https://kirby.example.com
34
+ KIRBY_API_USERNAME=your-username
35
+ KIRBY_API_PASSWORD=your-password
35
36
  ```
36
37
 
37
38
  And send queries in your template:
package/dist/module.d.mts CHANGED
@@ -42,10 +42,10 @@ interface ModuleOptions {
42
42
  * Leaving this off is what keeps your token out of the client bundle. Turn it on only for an
43
43
  * instance whose credentials may be public, or one that needs none.
44
44
  *
45
- * If Nuxt SSR is disabled, this is enabled by default, because there is no server to proxy
46
- * through.
45
+ * An explicit `false` holds even with SSR disabled; the default flips there because a
46
+ * client-rendered app often has no server to proxy through.
47
47
  *
48
- * @default false
48
+ * @default false, or true if Nuxt SSR is disabled
49
49
  */
50
50
  client?: boolean;
51
51
  /**
@@ -78,27 +78,27 @@ interface ModuleOptions {
78
78
  /**
79
79
  * Enable server-side caching of queries using the Nitro cache API.
80
80
  *
81
- * @see https://nitro.unjs.io/guide/cache
81
+ * @see https://v2.nitro.build/guide/cache
82
82
  */
83
83
  cache?: boolean;
84
84
  /**
85
85
  * Name of the storage mountpoint to use for caching.
86
86
  *
87
- * @see https://nitro.unjs.io/guide/cache
87
+ * @see https://v2.nitro.build/guide/cache
88
88
  * @default 'cache'
89
89
  */
90
90
  storage?: string;
91
91
  /**
92
92
  * Enable stale-while-revalidate behavior (cache is returned while it is being updated).
93
93
  *
94
- * @see https://nitro.unjs.io/guide/cache#options
94
+ * @see https://v2.nitro.build/guide/cache#options
95
95
  * @default false
96
96
  */
97
97
  swr?: boolean;
98
98
  /**
99
99
  * Number of seconds to cache the query response.
100
100
  *
101
- * @see https://nitro.unjs.io/guide/cache#options
101
+ * @see https://v2.nitro.build/guide/cache#options
102
102
  * @default 1
103
103
  */
104
104
  maxAge?: number;
package/dist/module.json CHANGED
@@ -4,9 +4,9 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=4.0.0"
6
6
  },
7
- "version": "4.1.0",
7
+ "version": "4.2.0",
8
8
  "builder": {
9
- "@nuxt/module-builder": "1.0.3",
9
+ "@nuxt/module-builder": "1.0.4",
10
10
  "unbuild": "unknown"
11
11
  }
12
12
  }
package/dist/module.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import process from 'node:process';
2
2
  import { useLogger, defineNuxtModule, createResolver, addServerHandler, addImports, addTemplate } from '@nuxt/kit';
3
3
  import { defu } from 'defu';
4
- import { join } from 'pathe';
4
+ import { join, relative } from 'pathe';
5
5
  import { pascalCase } from 'scule';
6
6
  import { withLeadingSlash } from 'ufo';
7
7
  import { ofetch } from 'ofetch';
@@ -78,7 +78,8 @@ const module$1 = defineNuxtModule({
78
78
  username: process.env.KIRBY_API_USERNAME || "",
79
79
  password: process.env.KIRBY_API_PASSWORD || ""
80
80
  },
81
- client: false,
81
+ // Left unset, so that an explicit `false` survives `ssr: false`.
82
+ client: void 0,
82
83
  forwardCookies: false,
83
84
  prefetch: {},
84
85
  server: {
@@ -98,21 +99,32 @@ const module$1 = defineNuxtModule({
98
99
  if (options.auth === "bearer" && !options.token)
99
100
  logger.error("Missing `KIRBY_API_TOKEN` environment variable for bearer authentication");
100
101
  options.kqlPath ||= options.auth === "bearer" ? "api/kql" : "api/query";
101
- if (!nuxt.options.ssr) {
102
- logger.info("Kirby requests are client-only because SSR is disabled");
103
- options.client = true;
102
+ if (options.client == null) {
103
+ options.client = !nuxt.options.ssr;
104
+ if (options.client)
105
+ logger.info("Kirby requests are client-only because SSR is disabled. Set `client: false` to keep them on the server proxy.");
104
106
  }
105
107
  if (options.server) {
106
108
  options.server.storage ||= "cache";
107
109
  options.server.storage = withLeadingSlash(options.server.storage);
108
110
  }
111
+ const { prefetch, ...runtimeOptions } = options;
109
112
  nuxt.options.runtimeConfig.kirby = defu(
110
113
  nuxt.options.runtimeConfig.kirby,
111
- options
114
+ runtimeOptions
112
115
  );
116
+ const publicOptions = options.client ? {
117
+ url: options.url,
118
+ kqlPath: options.kqlPath,
119
+ auth: options.auth,
120
+ ...options.auth === "bearer" && { token: options.token },
121
+ ...options.auth === "basic" && { credentials: options.credentials },
122
+ client: true,
123
+ forwardCookies: options.forwardCookies
124
+ } : { client: false };
113
125
  nuxt.options.runtimeConfig.public.kirby = defu(
114
126
  nuxt.options.runtimeConfig.public.kirby,
115
- options.client ? options : { client: false }
127
+ publicOptions
116
128
  );
117
129
  const { resolve } = createResolver(import.meta.url);
118
130
  nuxt.options.build.transpile.push(resolve("runtime"));
@@ -122,20 +134,24 @@ const module$1 = defineNuxtModule({
122
134
  method: "post"
123
135
  });
124
136
  addImports(
125
- ["$kirby", "$kql", "useKirbyData", "useKql"].map((name2) => ({
137
+ [
138
+ "$kirby",
139
+ "$kql",
140
+ "useKirbyData",
141
+ "useKql"
142
+ ].map((name2) => ({
126
143
  name: name2,
127
144
  from: resolve(`runtime/composables/${name2}`)
128
145
  }))
129
146
  );
130
147
  nuxt.hooks.hook("nitro:config", (config) => {
131
- config.externals ||= {};
132
- config.externals.inline ||= [];
133
- config.externals.inline.push(resolve("runtime/utils"));
134
148
  config.imports = defu(config.imports, {
135
- presets: [{
136
- from: resolve("runtime/server/imports"),
137
- imports: ["$kirby", "$kql"]
138
- }]
149
+ presets: [
150
+ {
151
+ from: resolve("runtime/server/imports"),
152
+ imports: ["$kirby", "$kql"]
153
+ }
154
+ ]
139
155
  });
140
156
  });
141
157
  nuxt.options.alias[`#${moduleName}`] = join(nuxt.options.buildDir, `module/${moduleName}`);
@@ -146,21 +162,26 @@ const module$1 = defineNuxtModule({
146
162
  getContents() {
147
163
  return `
148
164
  // Generated by ${moduleName}
149
- ${[...prefetchedQueries.entries()].map(([key, response]) => `
165
+ ${[
166
+ ...prefetchedQueries.entries()
167
+ ].map(([key, response]) => `
150
168
  export const ${key} = ${JSON.stringify(response?.result || null, void 0, 2)}
151
169
  `.trimStart()).join("") || `export {}
152
170
  `}`.trimStart();
153
171
  }
154
172
  });
173
+ const kirbyTypesPath = relative(join(nuxt.options.buildDir, "module"), resolve("runtime/kirby-types"));
155
174
  addTemplate({
156
175
  filename: `module/${moduleName}.d.ts`,
157
176
  write: true,
158
177
  getContents() {
159
178
  return `
160
179
  // Generated by ${moduleName}
161
- export type * from 'kirby-types'
180
+ export type * from ${JSON.stringify(kirbyTypesPath)}
162
181
 
163
- ${[...prefetchedQueries.entries()].map(([key, response]) => `
182
+ ${[
183
+ ...prefetchedQueries.entries()
184
+ ].map(([key, response]) => `
164
185
  export declare const ${key}: ${JSON.stringify(response?.result || null, void 0, 2)}
165
186
  export type ${pascalCase(key)} = typeof ${key}
166
187
  `.trimStart()).join("") || `export {}
@@ -1,8 +1,9 @@
1
1
  import { hash } from "ohash";
2
2
  import { useRequestFetch, useRuntimeConfig } from "#imports";
3
3
  import { sendCachedRequest } from "../cache.js";
4
+ import { assertPathBelowBase } from "../path.js";
4
5
  import { buildApiProxyPath, createAuthHeader, createLanguageHeader, headersToObject } from "../utils.js";
5
- export function $kirby(path, opts = {}) {
6
+ export async function $kirby(path, opts = {}) {
6
7
  const { payloadCache = true, ...requestOptions } = opts;
7
8
  const key = opts.key || `$kirby${hash([
8
9
  path,
@@ -27,6 +28,8 @@ export function sendKirbyRequest(path, opts) {
27
28
  forwardCookies,
28
29
  ...fetchOptions
29
30
  } = opts;
31
+ if (kirby.client)
32
+ assertPathBelowBase(path);
30
33
  const sharedHeaders = {
31
34
  ...headersToObject(headers),
32
35
  ...createLanguageHeader(language)
@@ -2,7 +2,7 @@ import { hash } from "ohash";
2
2
  import { useRequestFetch, useRuntimeConfig } from "#imports";
3
3
  import { sendCachedRequest } from "../cache.js";
4
4
  import { buildApiProxyPath, createAuthHeader, createLanguageHeader, headersToObject } from "../utils.js";
5
- export function $kql(query, opts = {}) {
5
+ export async function $kql(query, opts = {}) {
6
6
  const { payloadCache = true, ...requestOptions } = opts;
7
7
  const key = opts.key || `$kql${hash([
8
8
  query,
@@ -0,0 +1 @@
1
+ export type * from 'kirby-types';
File without changes
@@ -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,9 +4,20 @@ 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 { assertPathBelowBase } from "../path.js";
8
+ import { createAuthHeader, headersToObject } from "../utils.js";
8
9
  const EXCLUDED_HEADERS = /* @__PURE__ */ new Set([
9
- // https://github.com/h3js/h3/blob/fe9800bbbe9bda2972cc5d11db7353f4ab70f0ba/src/utils/proxy.ts#L97
10
+ // Headers that describe a single connection rather than the message, so they end at the proxy.
11
+ "connection",
12
+ "keep-alive",
13
+ "proxy-authenticate",
14
+ "proxy-authorization",
15
+ "proxy-connection",
16
+ "te",
17
+ "trailer",
18
+ "transfer-encoding",
19
+ "upgrade",
20
+ // The body arrives decoded, so its original encoding and length no longer apply.
10
21
  "content-encoding",
11
22
  "content-length",
12
23
  // Reduce information leakage.
@@ -45,7 +56,9 @@ async function fetchFromKirby(event, {
45
56
  return {
46
57
  status: response.status,
47
58
  statusText: response.statusText,
48
- headers: [...response.headers.entries()],
59
+ headers: [
60
+ ...response.headers.entries()
61
+ ],
49
62
  data: new Uint8Array(response._data ?? [])
50
63
  };
51
64
  }
@@ -76,7 +89,7 @@ function createCachedFetcher(kirby) {
76
89
  let cachedFetcher;
77
90
  export default defineEventHandler(async (event) => {
78
91
  const kirby = useRuntimeConfig(event).kirby;
79
- const body = await readBody(event);
92
+ const body = await readBody(event) ?? {};
80
93
  const key = decodeURIComponent(getRouterParam(event, "key"));
81
94
  const isQueryRequest = key.startsWith("$kql");
82
95
  if (isQueryRequest) {
@@ -87,21 +100,45 @@ export default defineEventHandler(async (event) => {
87
100
  });
88
101
  }
89
102
  } else {
90
- if (body.path && new URL(body.path, "http://localhost").origin !== "http://localhost") {
103
+ if (typeof body.path !== "string") {
91
104
  throw createError({
92
105
  statusCode: 400,
93
- statusMessage: "Absolute URLs are not allowed"
106
+ statusMessage: "Path must be a string"
94
107
  });
95
108
  }
109
+ if (body.method != null && typeof body.method !== "string") {
110
+ throw createError({
111
+ statusCode: 400,
112
+ statusMessage: "Method must be a string"
113
+ });
114
+ }
115
+ assertPathBelowBase(body.path);
116
+ }
117
+ let headers;
118
+ try {
119
+ headers = headersToObject(body.headers ?? void 0);
120
+ } catch {
121
+ throw createError({
122
+ statusCode: 400,
123
+ statusMessage: "Headers are invalid"
124
+ });
96
125
  }
97
126
  const forwardCookies = body.forwardCookies ?? kirby.forwardCookies;
98
127
  try {
99
128
  let response;
100
- const request = { isQueryRequest, ...body, forwardCookies };
129
+ const request = {
130
+ ...body,
131
+ headers,
132
+ isQueryRequest,
133
+ forwardCookies
134
+ };
101
135
  if (kirby.server.cache && !forwardCookies) {
102
136
  cachedFetcher ??= createCachedFetcher(kirby);
103
137
  const cached = await cachedFetcher(event, request);
104
- response = { ...cached, data: base64ToUint8Array(cached.data) };
138
+ response = {
139
+ ...cached,
140
+ data: base64ToUint8Array(cached.data)
141
+ };
105
142
  } else {
106
143
  response = await fetchFromKirby(event, request);
107
144
  }
@@ -1,8 +1,10 @@
1
1
  import { useRuntimeConfig } from "#imports";
2
+ import { assertPathBelowBase } from "../path.js";
2
3
  import { createAuthHeader, createLanguageHeader, headersToObject } from "../utils.js";
3
- export function $kirby(path, opts = {}) {
4
+ export async function $kirby(path, opts = {}) {
4
5
  const { headers, language, ...fetchOptions } = opts;
5
6
  const kirby = useRuntimeConfig().kirby;
7
+ assertPathBelowBase(path);
6
8
  return globalThis.$fetch(path, {
7
9
  ...fetchOptions,
8
10
  baseURL: kirby.url,
@@ -13,7 +15,7 @@ export function $kirby(path, opts = {}) {
13
15
  }
14
16
  });
15
17
  }
16
- export function $kql(query, opts = {}) {
18
+ export async function $kql(query, opts = {}) {
17
19
  const { headers, language, ...fetchOptions } = opts;
18
20
  const kirby = useRuntimeConfig().kirby;
19
21
  return globalThis.$fetch(kirby.kqlPath, {
@@ -1,5 +1,12 @@
1
1
  import type { KirbyQueryRequest } from 'kirby-types';
2
2
  import type { NitroFetchOptions } from 'nitropack';
3
+ import type { ModuleOptions } from '../module.js';
4
+ /** The module options without `prefetch`, which only the build reads. */
5
+ export type ServerKirbyConfig = Omit<Required<ModuleOptions>, 'prefetch'>;
6
+ /** The fields published in client mode; without it, only `client` is. */
7
+ export type PublicKirbyConfig = Pick<Required<ModuleOptions>, 'url' | 'kqlPath' | 'auth' | 'forwardCookies'> & Pick<ModuleOptions, 'token' | 'credentials'> & {
8
+ client: boolean;
9
+ };
3
10
  export interface ServerFetchOptions extends Pick<NitroFetchOptions<string>, 'method' | 'headers' | 'query' | 'body'> {
4
11
  /** A request carries one or the other: `query` for KQL, `path` for the REST API. */
5
12
  query?: Partial<KirbyQueryRequest>;
package/package.json CHANGED
@@ -1,8 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-kirby",
3
3
  "type": "module",
4
- "version": "4.1.0",
5
- "packageManager": "pnpm@11.20.0",
4
+ "version": "4.2.0",
6
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",
@@ -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,8 +32,34 @@
33
32
  "files": [
34
33
  "dist"
35
34
  ],
35
+ "dependencies": {
36
+ "@nuxt/kit": "^4.6.4",
37
+ "defu": "^6.1.7",
38
+ "destr": "^2.0.5",
39
+ "h3": "^1.15.11",
40
+ "kirby-types": "^1.8.2",
41
+ "ofetch": "^1.5.1",
42
+ "ohash": "^2.0.12",
43
+ "pathe": "^2.0.3",
44
+ "scule": "^1.3.0",
45
+ "ufo": "^1.6.4",
46
+ "uint8array-extras": "^1.6.0"
47
+ },
48
+ "devDependencies": {
49
+ "@antfu/eslint-config": "^10.0.0",
50
+ "@nuxt/module-builder": "^1.0.4",
51
+ "@nuxt/schema": "^4.6.4",
52
+ "@nuxt/test-utils": "^4.4.0",
53
+ "@types/node": "^26.6.6",
54
+ "bumpp": "^12.3.0",
55
+ "eslint": "^10.14.0",
56
+ "nuxt": "^4.6.4",
57
+ "playwright-core": "^1.65.0",
58
+ "srvx": "^1.0.8",
59
+ "typescript": "^6.0.3",
60
+ "vitest": "^5.1.0"
61
+ },
36
62
  "scripts": {
37
- "prepack": "nuxt-module-build build",
38
63
  "dev": "nuxt dev playground",
39
64
  "dev:build": "nuxt build playground",
40
65
  "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt prepare playground && nuxt prepare test/fixture",
@@ -46,31 +71,5 @@
46
71
  "test": "vitest",
47
72
  "test:types": "tsc --noEmit",
48
73
  "release": "bumpp"
49
- },
50
- "dependencies": {
51
- "@nuxt/kit": "^4.5.2",
52
- "defu": "^6.1.7",
53
- "destr": "^2.0.5",
54
- "kirby-types": "^1.6.0",
55
- "ofetch": "^1.5.1",
56
- "ohash": "^2.0.11",
57
- "pathe": "^2.0.3",
58
- "scule": "^1.3.0",
59
- "ufo": "^1.6.4",
60
- "uint8array-extras": "^1.5.0"
61
- },
62
- "devDependencies": {
63
- "@antfu/eslint-config": "^9.3.0",
64
- "@nuxt/module-builder": "^1.0.3",
65
- "@nuxt/schema": "^4.5.2",
66
- "@nuxt/test-utils": "^4.1.0",
67
- "@types/node": "^26.1.2",
68
- "bumpp": "^12.2.0",
69
- "eslint": "^10.8.0",
70
- "nuxt": "^4.5.2",
71
- "playwright-core": "^1.62.1",
72
- "srvx": "^0.12.5",
73
- "typescript": "^6.0.3",
74
- "vitest": "^4.1.10"
75
74
  }
76
- }
75
+ }