@basaltkit/api-keys-ui 1.0.1 → 1.1.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
@@ -59,6 +59,16 @@ Returns the route that serves the page. `path` (default `/apikeys/ui`), `apiBase
59
59
 
60
60
  Returns the page's HTML as a string — use it directly if you want to serve it your own way (or on another framework).
61
61
 
62
+ ## Content-Security-Policy
63
+
64
+ The route sets a route-scoped CSP by default: everything locked down and the
65
+ page's inline script allowed only by sha256 hash (exported as `apiKeysPageCsp`). It
66
+ works under `securityPlugin`'s strict app-wide CSP — do not disable CSP
67
+ globally. Override with `csp: '…'` or opt out with `csp: false`; if you serve
68
+ the raw HTML string yourself, set the matching CSP header on that route.
69
+ Server-side inputs are HTML-escaped and embedded state cannot terminate the
70
+ script block.
71
+
62
72
  ## How it connects to other modules
63
73
 
64
74
  - **`@basaltkit/auth`** — provides the API key routes this page consumes (`apiKeysPlugin` + `apiKeyRoutes`).
package/dist/html.d.ts CHANGED
@@ -3,6 +3,13 @@ export interface ApiKeysPageOptions {
3
3
  apiBase?: string;
4
4
  title?: string;
5
5
  }
6
+ /**
7
+ * The Content-Security-Policy matching {@link apiKeysPageHtml}: everything
8
+ * locked down, the page's inline script allowed by sha256 hash. Served by
9
+ * default from `apiKeysUiRoutes` so the page works under `securityPlugin`
10
+ * without weakening the app-wide policy.
11
+ */
12
+ export declare function apiKeysPageCsp(options?: ApiKeysPageOptions): string;
6
13
  /**
7
14
  * A self-contained HTML page (no dependencies, no build) to manage API keys by
8
15
  * calling `@basaltkit/auth`'s routes: `GET/POST /apikeys` and `DELETE /apikeys/:id`.
package/dist/html.js CHANGED
@@ -1,3 +1,68 @@
1
+ import { escapeHtml, pageCsp, scriptJson } from '@basaltkit/http';
2
+ // The inline script, built separately so the page and its CSP hash (see
3
+ // apiKeysPageCsp) are computed from the exact same source text. Server-side
4
+ // state is embedded with scriptJson (a crafted value cannot terminate the
5
+ // script block); API responses are rendered client-side through esc(), whose
6
+ // charset includes quotes because the values land in quoted attributes.
7
+ const pageScript = (apiBase) => `
8
+ const API = ${scriptJson(apiBase)};
9
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
10
+ const opts = { credentials: 'same-origin', headers: { 'content-type': 'application/json' } };
11
+
12
+ async function list() {
13
+ const keys = await fetch(API + '/apikeys', opts).then((r) => r.json());
14
+ const rows = document.getElementById('rows');
15
+ if (!Array.isArray(keys) || keys.length === 0) {
16
+ rows.innerHTML = '<tr><td colspan="4" class="empty muted">No API keys yet.</td></tr>';
17
+ return;
18
+ }
19
+ rows.innerHTML = keys.map((k) =>
20
+ '<tr><td><code>' + esc(k.prefix) + '…</code></td>' +
21
+ '<td>' + esc((k.scopes || []).join(', ')) + '</td>' +
22
+ '<td class="muted">' + (k.lastUsedAt ? new Date(k.lastUsedAt).toLocaleString() : 'never') + '</td>' +
23
+ '<td><button class="link" data-id="' + esc(k.id) + '">Revoke</button></td></tr>').join('');
24
+ for (const b of rows.querySelectorAll('button[data-id]')) {
25
+ b.addEventListener('click', async () => {
26
+ if (!confirm('Revoke this key? Any client using it will stop working.')) return;
27
+ await fetch(API + '/apikeys/' + b.dataset.id, { ...opts, method: 'DELETE' });
28
+ list();
29
+ });
30
+ }
31
+ }
32
+
33
+ document.getElementById('create').addEventListener('submit', async (e) => {
34
+ e.preventDefault();
35
+ const f = new FormData(e.target);
36
+ const scopes = String(f.get('scopes') || '').split(',').map((s) => s.trim()).filter(Boolean);
37
+ const body = JSON.stringify({ name: f.get('name'), ...(scopes.length ? { scopes } : {}) });
38
+ const created = await fetch(API + '/apikeys', { ...opts, method: 'POST', body }).then((r) => r.json());
39
+ if (created && created.key) {
40
+ document.getElementById('newkey').textContent = created.key;
41
+ document.getElementById('reveal').style.display = 'block';
42
+ }
43
+ e.target.reset();
44
+ list();
45
+ });
46
+
47
+ document.getElementById('copy').addEventListener('click', () => {
48
+ navigator.clipboard && navigator.clipboard.writeText(document.getElementById('newkey').textContent);
49
+ });
50
+
51
+ list();
52
+ `;
53
+ /**
54
+ * The Content-Security-Policy matching {@link apiKeysPageHtml}: everything
55
+ * locked down, the page's inline script allowed by sha256 hash. Served by
56
+ * default from `apiKeysUiRoutes` so the page works under `securityPlugin`
57
+ * without weakening the app-wide policy.
58
+ */
59
+ export function apiKeysPageCsp(options = {}) {
60
+ const apiBase = options.apiBase ?? '';
61
+ return pageCsp({
62
+ scripts: [pageScript(apiBase)],
63
+ ...(/^https?:\/\//.test(apiBase) ? { connect: [new URL(apiBase).origin] } : {}),
64
+ });
65
+ }
1
66
  /**
2
67
  * A self-contained HTML page (no dependencies, no build) to manage API keys by
3
68
  * calling `@basaltkit/auth`'s routes: `GET/POST /apikeys` and `DELETE /apikeys/:id`.
@@ -6,7 +71,7 @@
6
71
  */
7
72
  export function apiKeysPageHtml(options = {}) {
8
73
  const apiBase = options.apiBase ?? '';
9
- const title = options.title ?? 'API keys';
74
+ const title = escapeHtml(options.title ?? 'API keys');
10
75
  return `<!doctype html>
11
76
  <html lang="en">
12
77
  <head>
@@ -56,52 +121,7 @@ export function apiKeysPageHtml(options = {}) {
56
121
  <tbody id="rows"></tbody>
57
122
  </table>
58
123
 
59
- <script>
60
- const API = ${JSON.stringify(apiBase)};
61
- const esc = (s) => String(s == null ? '' : s).replace(/[&<>]/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;'}[c]));
62
- const opts = { credentials: 'same-origin', headers: { 'content-type': 'application/json' } };
63
-
64
- async function list() {
65
- const keys = await fetch(API + '/apikeys', opts).then((r) => r.json());
66
- const rows = document.getElementById('rows');
67
- if (!Array.isArray(keys) || keys.length === 0) {
68
- rows.innerHTML = '<tr><td colspan="4" class="empty muted">No API keys yet.</td></tr>';
69
- return;
70
- }
71
- rows.innerHTML = keys.map((k) =>
72
- '<tr><td><code>' + esc(k.prefix) + '…</code></td>' +
73
- '<td>' + esc((k.scopes || []).join(', ')) + '</td>' +
74
- '<td class="muted">' + (k.lastUsedAt ? new Date(k.lastUsedAt).toLocaleString() : 'never') + '</td>' +
75
- '<td><button class="link" data-id="' + esc(k.id) + '">Revoke</button></td></tr>').join('');
76
- for (const b of rows.querySelectorAll('button[data-id]')) {
77
- b.addEventListener('click', async () => {
78
- if (!confirm('Revoke this key? Any client using it will stop working.')) return;
79
- await fetch(API + '/apikeys/' + b.dataset.id, { ...opts, method: 'DELETE' });
80
- list();
81
- });
82
- }
83
- }
84
-
85
- document.getElementById('create').addEventListener('submit', async (e) => {
86
- e.preventDefault();
87
- const f = new FormData(e.target);
88
- const scopes = String(f.get('scopes') || '').split(',').map((s) => s.trim()).filter(Boolean);
89
- const body = JSON.stringify({ name: f.get('name'), ...(scopes.length ? { scopes } : {}) });
90
- const created = await fetch(API + '/apikeys', { ...opts, method: 'POST', body }).then((r) => r.json());
91
- if (created && created.key) {
92
- document.getElementById('newkey').textContent = created.key;
93
- document.getElementById('reveal').style.display = 'block';
94
- }
95
- e.target.reset();
96
- list();
97
- });
98
-
99
- document.getElementById('copy').addEventListener('click', () => {
100
- navigator.clipboard && navigator.clipboard.writeText(document.getElementById('newkey').textContent);
101
- });
102
-
103
- list();
104
- </script>
124
+ <script>${pageScript(apiBase)}</script>
105
125
  </body>
106
126
  </html>`;
107
127
  }
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { apiKeysPageHtml, type ApiKeysPageOptions } from './html.js';
1
+ export { apiKeysPageCsp, apiKeysPageHtml, type ApiKeysPageOptions } from './html.js';
2
2
  export { apiKeysUiRoutes, type ApiKeysUiOptions } from './plugin.js';
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export { apiKeysPageHtml } from './html.js';
1
+ export { apiKeysPageCsp, apiKeysPageHtml } from './html.js';
2
2
  export { apiKeysUiRoutes } from './plugin.js';
package/dist/plugin.d.ts CHANGED
@@ -1,8 +1,15 @@
1
- import { type BasaltRoute } from '@basaltkit/fastify';
1
+ import { type BasaltRoute } from '@basaltkit/http';
2
2
  import { type ApiKeysPageOptions } from './html.js';
3
3
  export interface ApiKeysUiOptions extends ApiKeysPageOptions {
4
4
  /** Where to mount the page. Default `/apikeys/ui`. */
5
5
  path?: string;
6
+ /**
7
+ * Content-Security-Policy for the page. Default: the hash-locked
8
+ * {@link apiKeysPageCsp}, so the page works under `securityPlugin`'s strict
9
+ * app-wide CSP without weakening it. Pass a string to override, or `false`
10
+ * to send no route-scoped CSP at all.
11
+ */
12
+ csp?: string | false;
6
13
  }
7
14
  /**
8
15
  * Serves the API-keys management page at `GET /apikeys/ui` (requires a
package/dist/plugin.js CHANGED
@@ -1,5 +1,5 @@
1
- import { route } from '@basaltkit/fastify';
2
- import { apiKeysPageHtml } from './html.js';
1
+ import { route } from '@basaltkit/http';
2
+ import { apiKeysPageCsp, apiKeysPageHtml } from './html.js';
3
3
  /**
4
4
  * Serves the API-keys management page at `GET /apikeys/ui` (requires a
5
5
  * logged-in user). Pair with `@basaltkit/auth`'s `apiKeyRoutes()`, which provides
@@ -7,12 +7,15 @@ import { apiKeysPageHtml } from './html.js';
7
7
  */
8
8
  export function apiKeysUiRoutes(options = {}) {
9
9
  const html = apiKeysPageHtml(options);
10
+ const csp = options.csp === false ? undefined : (options.csp ?? apiKeysPageCsp(options));
10
11
  return [
11
12
  route({
12
13
  method: 'GET',
13
14
  url: options.path ?? '/apikeys/ui',
14
15
  meta: { auth: true },
15
16
  async handler({ reply }) {
17
+ if (csp !== undefined)
18
+ reply.header('content-security-policy', csp);
16
19
  return reply.header('content-type', 'text/html; charset=utf-8').send(html);
17
20
  },
18
21
  }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/api-keys-ui",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "description": "A self-contained HTML page to manage @basaltkit/auth API keys: create (show once), list and revoke — zero dependencies, no build.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -14,17 +14,18 @@
14
14
  "dist"
15
15
  ],
16
16
  "dependencies": {
17
- "@basaltkit/core": "^1.1.2",
18
- "@basaltkit/fastify": "^1.6.1"
17
+ "@basaltkit/core": "^1.3.0",
18
+ "@basaltkit/http": "^1.11.0"
19
19
  },
20
20
  "devDependencies": {
21
21
  "@types/node": "^26.3.0",
22
22
  "typescript": "^7.0.2",
23
23
  "vitest": "^4.1.11",
24
24
  "zod": "^3.24.0 || ^4.0.0",
25
- "@basaltkit/tsconfig": "^0.24.0",
26
- "@basaltkit/tenancy": "^1.3.3",
27
- "@basaltkit/auth": "^1.6.2"
25
+ "@basaltkit/auth": "^1.6.3",
26
+ "@basaltkit/fastify": "^1.7.0",
27
+ "@basaltkit/tenancy": "^1.4.0",
28
+ "@basaltkit/tsconfig": "^0.24.0"
28
29
  },
29
30
  "publishConfig": {
30
31
  "access": "public"