@basaltkit/api-keys-ui 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Machize Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # @basaltkit/api-keys-ui
2
+
3
+ Self-contained HTML page to **manage API keys** for [`@basaltkit/auth`](https://www.npmjs.com/package/@basaltkit/auth): create (shows the key **once**), list and revoke — **zero dependencies, no build step**. You need this module when you want to give users a screen to manage their API keys without building the UI from scratch.
4
+
5
+ ## What this module solves
6
+
7
+ `@basaltkit/auth` already exposes the `POST/GET /apikeys` and `DELETE /apikeys/:id` routes (the plaintext key only appears on creation). This module is the **UI** on top of them: a page that lists the keys, lets you create a new one (revealing the secret once, with a copy button) and revoke existing ones.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ pnpm add @basaltkit/api-keys-ui
13
+ ```
14
+
15
+ Depends on `@basaltkit/core` and `@basaltkit/fastify`. Requires your app to mount the API key routes from `@basaltkit/auth` (`apiKeysPlugin` + `apiKeyRoutes`).
16
+
17
+ ## Getting started in 5 minutes
18
+
19
+ ```ts
20
+ import { createApp } from '@basaltkit/core'
21
+ import { authPlugin, authRoutes, apiKeysPlugin, apiKeyRoutes, MemoryUserSource } from '@basaltkit/auth'
22
+ import { apiKeysUiRoutes } from '@basaltkit/api-keys-ui'
23
+ import { fastifyPlugin } from '@basaltkit/fastify'
24
+
25
+ const app = await createApp({
26
+ plugins: [
27
+ authPlugin({ users: new MemoryUserSource(), secret: process.env.JWT_SECRET! }),
28
+ apiKeysPlugin(),
29
+ fastifyPlugin({
30
+ routes: [
31
+ ...authRoutes(),
32
+ ...apiKeyRoutes(), // POST/GET /apikeys, DELETE /apikeys/:id
33
+ ...apiKeysUiRoutes(), // GET /apikeys/ui ← the page
34
+ ],
35
+ }),
36
+ ],
37
+ }).boot()
38
+ ```
39
+
40
+ Open **`/apikeys/ui`** (authenticated) and the user can create, view and revoke their keys.
41
+
42
+ ## How it works
43
+
44
+ The page is served by `GET /apikeys/ui` (requires login). In the browser, it calls the JSON routes with `credentials: 'same-origin'`, so it assumes the user's session is already authenticated against `${apiBase}/apikeys`. When creating a key, it reveals the secret **once** (with a warning and a copy button) — after that only the prefix is visible, as required by `@basaltkit/auth`'s security model.
45
+
46
+ ## API reference
47
+
48
+ ### `apiKeysUiRoutes({ path?, apiBase?, title? })`
49
+
50
+ Returns the route that serves the page. `path` (default `/apikeys/ui`), `apiBase` (where the JSON routes are, default same-origin), `title`.
51
+
52
+ ### `apiKeysPageHtml({ apiBase?, title? })`
53
+
54
+ Returns the page's HTML as a string — use it directly if you want to serve it your own way (or on another framework).
55
+
56
+ ## How it connects to other modules
57
+
58
+ - **`@basaltkit/auth`** — provides the API key routes this page consumes (`apiKeysPlugin` + `apiKeyRoutes`).
59
+ - **`@basaltkit/permissions`** — add a *guard* to the page route if you want to restrict who can see it.
@@ -0,0 +1,27 @@
1
+ import { BasaltRoute } from '@basaltkit/fastify';
2
+
3
+ interface ApiKeysPageOptions {
4
+ /** Base path where the API-key JSON routes are mounted. Default '' (same origin). */
5
+ apiBase?: string;
6
+ title?: string;
7
+ }
8
+ /**
9
+ * A self-contained HTML page (no dependencies, no build) to manage API keys by
10
+ * calling `@basaltkit/auth`'s routes: `GET/POST /apikeys` and `DELETE /apikeys/:id`.
11
+ * Serve it from a route (see `apiKeysUiRoutes`). The page assumes the browser is
12
+ * already authenticated (session cookie) for those routes.
13
+ */
14
+ declare function apiKeysPageHtml(options?: ApiKeysPageOptions): string;
15
+
16
+ interface ApiKeysUiOptions extends ApiKeysPageOptions {
17
+ /** Where to mount the page. Default `/apikeys/ui`. */
18
+ path?: string;
19
+ }
20
+ /**
21
+ * Serves the API-keys management page at `GET /apikeys/ui` (requires a
22
+ * logged-in user). Pair with `@basaltkit/auth`'s `apiKeyRoutes()`, which provides
23
+ * the JSON endpoints the page calls.
24
+ */
25
+ declare function apiKeysUiRoutes(options?: ApiKeysUiOptions): BasaltRoute[];
26
+
27
+ export { type ApiKeysPageOptions, type ApiKeysUiOptions, apiKeysPageHtml, apiKeysUiRoutes };
package/dist/index.js ADDED
@@ -0,0 +1,122 @@
1
+ // src/html.ts
2
+ function apiKeysPageHtml(options = {}) {
3
+ const apiBase = options.apiBase ?? "";
4
+ const title = options.title ?? "API keys";
5
+ return `<!doctype html>
6
+ <html lang="en">
7
+ <head>
8
+ <meta charset="utf-8" />
9
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
10
+ <title>${title}</title>
11
+ <style>
12
+ :root { color-scheme: light dark; --bd: #8884; --accent: #4f46e5; --danger: #dc2626; --ok: #16a34a; }
13
+ body { font: 14px/1.5 system-ui, sans-serif; margin: 0; padding: 2rem 1.5rem; max-width: 820px; margin-inline: auto; }
14
+ h1 { font-size: 1.4rem; margin: 0 0 1.25rem; }
15
+ .card { border: 1px solid var(--bd); border-radius: 10px; padding: 1rem 1.25rem; margin-bottom: 1.25rem; }
16
+ form { display: flex; gap: .5rem; flex-wrap: wrap; align-items: end; }
17
+ label { display: flex; flex-direction: column; gap: .25rem; font-size: .8rem; opacity: .8; }
18
+ input { padding: .45rem .6rem; border: 1px solid var(--bd); border-radius: 7px; background: transparent; color: inherit; min-width: 12rem; }
19
+ button { padding: .45rem .9rem; border: 1px solid var(--bd); border-radius: 7px; cursor: pointer; background: transparent; color: inherit; font: inherit; }
20
+ button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
21
+ button.link { border: none; color: var(--danger); padding: .2rem .4rem; }
22
+ table { width: 100%; border-collapse: collapse; }
23
+ th, td { text-align: left; padding: .55rem .5rem; border-bottom: 1px solid var(--bd); }
24
+ th { font-size: .75rem; text-transform: uppercase; letter-spacing: .04em; opacity: .6; }
25
+ code { font-family: ui-monospace, monospace; }
26
+ .muted { opacity: .55; }
27
+ .reveal { border: 1px solid var(--ok); background: #16a34a18; border-radius: 8px; padding: .75rem 1rem; margin-top: .75rem; display: none; }
28
+ .reveal code { word-break: break-all; }
29
+ .empty { padding: 1rem; text-align: center; }
30
+ </style>
31
+ </head>
32
+ <body>
33
+ <h1>${title}</h1>
34
+
35
+ <div class="card">
36
+ <form id="create">
37
+ <label>Name<input name="name" placeholder="CI pipeline" required /></label>
38
+ <label>Scopes (comma-separated)<input name="scopes" placeholder="read, write" /></label>
39
+ <button class="primary" type="submit">Create key</button>
40
+ </form>
41
+ <div class="reveal" id="reveal">
42
+ <div>Copy your new key now \u2014 it won't be shown again:</div>
43
+ <div style="margin-top:.4rem;display:flex;gap:.5rem;align-items:center">
44
+ <code id="newkey"></code><button id="copy" type="button">Copy</button>
45
+ </div>
46
+ </div>
47
+ </div>
48
+
49
+ <table>
50
+ <thead><tr><th>Prefix</th><th>Scopes</th><th>Last used</th><th></th></tr></thead>
51
+ <tbody id="rows"></tbody>
52
+ </table>
53
+
54
+ <script>
55
+ const API = ${JSON.stringify(apiBase)};
56
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>]/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;'}[c]));
57
+ const opts = { credentials: 'same-origin', headers: { 'content-type': 'application/json' } };
58
+
59
+ async function list() {
60
+ const keys = await fetch(API + '/apikeys', opts).then((r) => r.json());
61
+ const rows = document.getElementById('rows');
62
+ if (!Array.isArray(keys) || keys.length === 0) {
63
+ rows.innerHTML = '<tr><td colspan="4" class="empty muted">No API keys yet.</td></tr>';
64
+ return;
65
+ }
66
+ rows.innerHTML = keys.map((k) =>
67
+ '<tr><td><code>' + esc(k.prefix) + '\u2026</code></td>' +
68
+ '<td>' + esc((k.scopes || []).join(', ')) + '</td>' +
69
+ '<td class="muted">' + (k.lastUsedAt ? new Date(k.lastUsedAt).toLocaleString() : 'never') + '</td>' +
70
+ '<td><button class="link" data-id="' + esc(k.id) + '">Revoke</button></td></tr>').join('');
71
+ for (const b of rows.querySelectorAll('button[data-id]')) {
72
+ b.addEventListener('click', async () => {
73
+ if (!confirm('Revoke this key? Any client using it will stop working.')) return;
74
+ await fetch(API + '/apikeys/' + b.dataset.id, { ...opts, method: 'DELETE' });
75
+ list();
76
+ });
77
+ }
78
+ }
79
+
80
+ document.getElementById('create').addEventListener('submit', async (e) => {
81
+ e.preventDefault();
82
+ const f = new FormData(e.target);
83
+ const scopes = String(f.get('scopes') || '').split(',').map((s) => s.trim()).filter(Boolean);
84
+ const body = JSON.stringify({ name: f.get('name'), ...(scopes.length ? { scopes } : {}) });
85
+ const created = await fetch(API + '/apikeys', { ...opts, method: 'POST', body }).then((r) => r.json());
86
+ if (created && created.key) {
87
+ document.getElementById('newkey').textContent = created.key;
88
+ document.getElementById('reveal').style.display = 'block';
89
+ }
90
+ e.target.reset();
91
+ list();
92
+ });
93
+
94
+ document.getElementById('copy').addEventListener('click', () => {
95
+ navigator.clipboard && navigator.clipboard.writeText(document.getElementById('newkey').textContent);
96
+ });
97
+
98
+ list();
99
+ </script>
100
+ </body>
101
+ </html>`;
102
+ }
103
+
104
+ // src/plugin.ts
105
+ import { route } from "@basaltkit/fastify";
106
+ function apiKeysUiRoutes(options = {}) {
107
+ const html = apiKeysPageHtml(options);
108
+ return [
109
+ route({
110
+ method: "GET",
111
+ url: options.path ?? "/apikeys/ui",
112
+ meta: { auth: true },
113
+ async handler({ reply }) {
114
+ return reply.header("content-type", "text/html; charset=utf-8").send(html);
115
+ }
116
+ })
117
+ ];
118
+ }
119
+ export {
120
+ apiKeysPageHtml,
121
+ apiKeysUiRoutes
122
+ };
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@basaltkit/api-keys-ui",
3
+ "version": "1.0.0",
4
+ "description": "A self-contained HTML page to manage @basaltkit/auth API keys: create (show once), list and revoke — zero dependencies, no build.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js"
11
+ }
12
+ },
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "dependencies": {
17
+ "@basaltkit/fastify": "^1.0.0",
18
+ "@basaltkit/core": "^1.0.0"
19
+ },
20
+ "devDependencies": {
21
+ "@types/node": "^22.15.0",
22
+ "tsup": "^8.4.0",
23
+ "typescript": "^5.8.0",
24
+ "vitest": "^3.1.0",
25
+ "zod": "^3.24.0",
26
+ "@basaltkit/tenancy": "^1.0.0",
27
+ "@basaltkit/tsconfig": "^0.24.0",
28
+ "@basaltkit/auth": "^1.0.0"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/Zebedeu/basalt.git",
36
+ "directory": "packages/api-keys-ui"
37
+ },
38
+ "homepage": "https://github.com/Zebedeu/basalt/tree/main/packages/api-keys-ui#readme",
39
+ "bugs": "https://github.com/Zebedeu/basalt/issues",
40
+ "keywords": [
41
+ "basalt",
42
+ "typescript",
43
+ "saas",
44
+ "api-keys",
45
+ "ui"
46
+ ],
47
+ "scripts": {
48
+ "build": "tsup src/index.ts --format esm --dts --clean",
49
+ "test": "vitest run",
50
+ "typecheck": "tsc --noEmit"
51
+ }
52
+ }