inlaycms 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +462 -2
- package/assets/admin/admin.css +2 -0
- package/assets/admin/admin.js +1 -0
- package/assets/admin/editor.js +125 -0
- package/dist/adapters/admin/activity.d.ts +17 -0
- package/dist/adapters/admin/activity.js +59 -0
- package/dist/adapters/admin/assets.d.ts +14 -0
- package/dist/adapters/admin/assets.js +64 -0
- package/dist/adapters/admin/attention.d.ts +15 -0
- package/dist/adapters/admin/attention.js +34 -0
- package/dist/adapters/admin/context.d.ts +40 -0
- package/dist/adapters/admin/context.js +142 -0
- package/dist/adapters/admin/form/walk.d.ts +61 -0
- package/dist/adapters/admin/form/walk.js +565 -0
- package/dist/adapters/admin/pages.d.ts +38 -0
- package/dist/adapters/admin/pages.js +66 -0
- package/dist/adapters/admin/publish.d.ts +12 -0
- package/dist/adapters/admin/publish.js +195 -0
- package/dist/adapters/admin/routes.d.ts +47 -0
- package/dist/adapters/admin/routes.js +255 -0
- package/dist/adapters/admin/screens/backups.d.ts +11 -0
- package/dist/adapters/admin/screens/backups.js +223 -0
- package/dist/adapters/admin/screens/dashboard.d.ts +4 -0
- package/dist/adapters/admin/screens/dashboard.js +160 -0
- package/dist/adapters/admin/screens/editor.d.ts +67 -0
- package/dist/adapters/admin/screens/editor.js +416 -0
- package/dist/adapters/admin/screens/history.d.ts +4 -0
- package/dist/adapters/admin/screens/history.js +105 -0
- package/dist/adapters/admin/screens/lists.d.ts +4 -0
- package/dist/adapters/admin/screens/lists.js +297 -0
- package/dist/adapters/admin/screens/media.d.ts +20 -0
- package/dist/adapters/admin/screens/media.js +186 -0
- package/dist/adapters/admin/screens/pickers.d.ts +29 -0
- package/dist/adapters/admin/screens/pickers.js +134 -0
- package/dist/adapters/admin/screens/preview-pane.d.ts +10 -0
- package/dist/adapters/admin/screens/preview-pane.js +74 -0
- package/dist/adapters/admin/screens/redirects.d.ts +4 -0
- package/dist/adapters/admin/screens/redirects.js +137 -0
- package/dist/adapters/admin/screens/releases.d.ts +7 -0
- package/dist/adapters/admin/screens/releases.js +287 -0
- package/dist/adapters/admin/screens/search.d.ts +22 -0
- package/dist/adapters/admin/screens/search.js +113 -0
- package/dist/adapters/admin/screens/security.d.ts +4 -0
- package/dist/adapters/admin/screens/security.js +85 -0
- package/dist/adapters/admin/screens/users.d.ts +4 -0
- package/dist/adapters/admin/screens/users.js +330 -0
- package/dist/adapters/admin/theme.d.ts +1 -0
- package/dist/adapters/admin/theme.js +1 -0
- package/dist/adapters/admin/translations.d.ts +16 -0
- package/dist/adapters/admin/translations.js +23 -0
- package/dist/adapters/admin/upload.d.ts +8 -0
- package/dist/adapters/admin/upload.js +116 -0
- package/dist/adapters/admin/views/data-table.d.ts +82 -0
- package/dist/adapters/admin/views/data-table.js +117 -0
- package/dist/adapters/admin/views/icons.d.ts +48 -0
- package/dist/adapters/admin/views/icons.js +47 -0
- package/dist/adapters/admin/views/layout.d.ts +51 -0
- package/dist/adapters/admin/views/layout.js +145 -0
- package/dist/adapters/admin/views/sheet.d.ts +15 -0
- package/dist/adapters/admin/views/sheet.js +6 -0
- package/dist/adapters/admin/views/status.d.ts +32 -0
- package/dist/adapters/admin/views/status.js +74 -0
- package/dist/adapters/auth/handler.d.ts +10 -0
- package/dist/adapters/auth/handler.js +63 -0
- package/dist/adapters/auth/request.d.ts +8 -0
- package/dist/adapters/auth/request.js +14 -0
- package/dist/adapters/cli/bin.d.ts +2 -0
- package/dist/adapters/cli/bin.js +42 -0
- package/dist/adapters/cli/main.d.ts +7 -0
- package/dist/adapters/cli/main.js +982 -0
- package/dist/adapters/cli/remote.d.ts +52 -0
- package/dist/adapters/cli/remote.js +161 -0
- package/dist/adapters/mcp/agent-refs.d.ts +9 -0
- package/dist/adapters/mcp/agent-refs.js +25 -0
- package/dist/adapters/mcp/documents.d.ts +15 -0
- package/dist/adapters/mcp/documents.js +26 -0
- package/dist/adapters/mcp/fetch-url.d.ts +19 -0
- package/dist/adapters/mcp/fetch-url.js +244 -0
- package/dist/adapters/mcp/request-state.d.ts +15 -0
- package/dist/adapters/mcp/request-state.js +38 -0
- package/dist/adapters/mcp/results.d.ts +20 -0
- package/dist/adapters/mcp/results.js +61 -0
- package/dist/adapters/mcp/route.d.ts +34 -0
- package/dist/adapters/mcp/route.js +52 -0
- package/dist/adapters/mcp/server.d.ts +44 -0
- package/dist/adapters/mcp/server.js +49 -0
- package/dist/adapters/mcp/tools/history.d.ts +5 -0
- package/dist/adapters/mcp/tools/history.js +84 -0
- package/dist/adapters/mcp/tools/media.d.ts +5 -0
- package/dist/adapters/mcp/tools/media.js +102 -0
- package/dist/adapters/mcp/tools/publish.d.ts +5 -0
- package/dist/adapters/mcp/tools/publish.js +157 -0
- package/dist/adapters/mcp/tools/read.d.ts +5 -0
- package/dist/adapters/mcp/tools/read.js +279 -0
- package/dist/adapters/mcp/tools/redirects.d.ts +5 -0
- package/dist/adapters/mcp/tools/redirects.js +74 -0
- package/dist/adapters/mcp/tools/write.d.ts +5 -0
- package/dist/adapters/mcp/tools/write.js +304 -0
- package/dist/adapters/site/backup-schedule.d.ts +8 -0
- package/dist/adapters/site/backup-schedule.js +31 -0
- package/dist/adapters/site/cache.d.ts +29 -0
- package/dist/adapters/site/cache.js +63 -0
- package/dist/adapters/site/context.d.ts +29 -0
- package/dist/adapters/site/context.js +278 -0
- package/dist/adapters/site/head.d.ts +23 -0
- package/dist/adapters/site/head.js +44 -0
- package/dist/adapters/site/limiter.d.ts +17 -0
- package/dist/adapters/site/limiter.js +39 -0
- package/dist/adapters/site/lock.d.ts +30 -0
- package/dist/adapters/site/lock.js +143 -0
- package/dist/adapters/site/media-routes.d.ts +4 -0
- package/dist/adapters/site/media-routes.js +55 -0
- package/dist/adapters/site/plugin.d.ts +122 -0
- package/dist/adapters/site/plugin.js +436 -0
- package/dist/adapters/site/preview.d.ts +36 -0
- package/dist/adapters/site/preview.js +82 -0
- package/dist/adapters/site/public.d.ts +6 -0
- package/dist/adapters/site/public.js +87 -0
- package/dist/adapters/site/render.d.ts +45 -0
- package/dist/adapters/site/render.js +191 -0
- package/dist/adapters/site/routes.d.ts +17 -0
- package/dist/adapters/site/routes.js +125 -0
- package/dist/adapters/site/sitemap.d.ts +10 -0
- package/dist/adapters/site/sitemap.js +10 -0
- package/dist/adapters/web.d.ts +22 -0
- package/dist/adapters/web.js +75 -0
- package/dist/config.d.ts +21 -0
- package/dist/config.js +58 -0
- package/dist/core/agent/format.d.ts +62 -0
- package/dist/core/agent/format.js +211 -0
- package/dist/core/agent/schema.d.ts +6 -0
- package/dist/core/agent/schema.js +86 -0
- package/dist/core/archive.d.ts +12 -0
- package/dist/core/archive.js +72 -0
- package/dist/core/auth/auth.d.ts +4911 -0
- package/dist/core/auth/auth.js +61 -0
- package/dist/core/auth/roles.d.ts +10 -0
- package/dist/core/auth/roles.js +38 -0
- package/dist/core/auth/service.d.ts +118 -0
- package/dist/core/auth/service.js +424 -0
- package/dist/core/auth/upload-token.d.ts +8 -0
- package/dist/core/auth/upload-token.js +27 -0
- package/dist/core/backup/backup.d.ts +28 -0
- package/dist/core/backup/backup.js +126 -0
- package/dist/core/backup/restore.d.ts +41 -0
- package/dist/core/backup/restore.js +264 -0
- package/dist/core/backup/schedule.d.ts +12 -0
- package/dist/core/backup/schedule.js +29 -0
- package/dist/core/boot.d.ts +63 -0
- package/dist/core/boot.js +141 -0
- package/dist/core/check.d.ts +32 -0
- package/dist/core/check.js +111 -0
- package/dist/core/content/activity.d.ts +8 -0
- package/dist/core/content/activity.js +101 -0
- package/dist/core/content/delete.d.ts +5 -0
- package/dist/core/content/delete.js +100 -0
- package/dist/core/content/diff.d.ts +6 -0
- package/dist/core/content/diff.js +129 -0
- package/dist/core/content/dry-run.d.ts +24 -0
- package/dist/core/content/dry-run.js +69 -0
- package/dist/core/content/gaps.d.ts +25 -0
- package/dist/core/content/gaps.js +50 -0
- package/dist/core/content/hidden.d.ts +33 -0
- package/dist/core/content/hidden.js +103 -0
- package/dist/core/content/history.d.ts +15 -0
- package/dist/core/content/history.js +62 -0
- package/dist/core/content/patch.d.ts +40 -0
- package/dist/core/content/patch.js +287 -0
- package/dist/core/content/path.d.ts +6 -0
- package/dist/core/content/path.js +38 -0
- package/dist/core/content/publish.d.ts +26 -0
- package/dist/core/content/publish.js +211 -0
- package/dist/core/content/read.d.ts +99 -0
- package/dist/core/content/read.js +141 -0
- package/dist/core/content/reader.d.ts +37 -0
- package/dist/core/content/reader.js +195 -0
- package/dist/core/content/refs.d.ts +44 -0
- package/dist/core/content/refs.js +161 -0
- package/dist/core/content/release-migrations.d.ts +12 -0
- package/dist/core/content/release-migrations.js +154 -0
- package/dist/core/content/save.d.ts +25 -0
- package/dist/core/content/save.js +87 -0
- package/dist/core/content/schema.d.ts +22 -0
- package/dist/core/content/schema.js +127 -0
- package/dist/core/content/search.d.ts +8 -0
- package/dist/core/content/search.js +89 -0
- package/dist/core/content/shipped-input.d.ts +39 -0
- package/dist/core/content/shipped-input.js +221 -0
- package/dist/core/content/shipped.d.ts +112 -0
- package/dist/core/content/shipped.js +437 -0
- package/dist/core/content/slug.d.ts +23 -0
- package/dist/core/content/slug.js +182 -0
- package/dist/core/content/stats.d.ts +11 -0
- package/dist/core/content/stats.js +30 -0
- package/dist/core/content/translate.d.ts +3 -0
- package/dist/core/content/translate.js +68 -0
- package/dist/core/content/usages.d.ts +13 -0
- package/dist/core/content/usages.js +70 -0
- package/dist/core/content/validate.d.ts +21 -0
- package/dist/core/content/validate.js +124 -0
- package/dist/core/content/write.d.ts +10 -0
- package/dist/core/content/write.js +93 -0
- package/dist/core/core.d.ts +227 -0
- package/dist/core/core.js +251 -0
- package/dist/core/db/connection.d.ts +6 -0
- package/dist/core/db/connection.js +12 -0
- package/dist/core/db/migrate.d.ts +9 -0
- package/dist/core/db/migrate.js +42 -0
- package/dist/core/db/migrations/0001_content.d.ts +2 -0
- package/dist/core/db/migrations/0001_content.js +69 -0
- package/dist/core/db/migrations/0002_media.d.ts +2 -0
- package/dist/core/db/migrations/0002_media.js +26 -0
- package/dist/core/db/migrations/0003_redirects.d.ts +2 -0
- package/dist/core/db/migrations/0003_redirects.js +19 -0
- package/dist/core/db/migrations/0004_token_cutoffs.d.ts +3 -0
- package/dist/core/db/migrations/0004_token_cutoffs.js +8 -0
- package/dist/core/db/migrations/0005_site_lock.d.ts +3 -0
- package/dist/core/db/migrations/0005_site_lock.js +10 -0
- package/dist/core/db/migrations/0006_releases.d.ts +3 -0
- package/dist/core/db/migrations/0006_releases.js +34 -0
- package/dist/core/db/schema.d.ts +155 -0
- package/dist/core/db/schema.js +1 -0
- package/dist/core/errors.d.ts +27 -0
- package/dist/core/errors.js +15 -0
- package/dist/core/export/export.d.ts +17 -0
- package/dist/core/export/export.js +185 -0
- package/dist/core/export/format.d.ts +241 -0
- package/dist/core/export/format.js +106 -0
- package/dist/core/export/import.d.ts +54 -0
- package/dist/core/export/import.js +180 -0
- package/dist/core/export/read.d.ts +16 -0
- package/dist/core/export/read.js +234 -0
- package/dist/core/export/replace.d.ts +17 -0
- package/dist/core/export/replace.js +36 -0
- package/dist/core/export/report.d.ts +55 -0
- package/dist/core/export/report.js +50 -0
- package/dist/core/export/schema.d.ts +8 -0
- package/dist/core/export/schema.js +47 -0
- package/dist/core/export/stage.d.ts +25 -0
- package/dist/core/export/stage.js +192 -0
- package/dist/core/fields/builtins.d.ts +70 -0
- package/dist/core/fields/builtins.js +335 -0
- package/dist/core/fields/define.d.ts +86 -0
- package/dist/core/fields/define.js +34 -0
- package/dist/core/fields/walk.d.ts +49 -0
- package/dist/core/fields/walk.js +270 -0
- package/dist/core/fields/widgets.d.ts +27 -0
- package/dist/core/fields/widgets.js +330 -0
- package/dist/core/fields/zod-internals.d.ts +29 -0
- package/dist/core/fields/zod-internals.js +28 -0
- package/dist/core/media/detect.d.ts +5 -0
- package/dist/core/media/detect.js +66 -0
- package/dist/core/media/labels.d.ts +6 -0
- package/dist/core/media/labels.js +17 -0
- package/dist/core/media/library.d.ts +45 -0
- package/dist/core/media/library.js +239 -0
- package/dist/core/media/store.d.ts +11 -0
- package/dist/core/media/store.js +49 -0
- package/dist/core/media/variants.d.ts +10 -0
- package/dist/core/media/variants.js +59 -0
- package/dist/core/messages/en.d.ts +1278 -0
- package/dist/core/messages/en.js +1287 -0
- package/dist/core/messages/index.d.ts +7 -0
- package/dist/core/messages/index.js +14 -0
- package/dist/core/preview.d.ts +16 -0
- package/dist/core/preview.js +42 -0
- package/dist/core/redirects/collapse.d.ts +68 -0
- package/dist/core/redirects/collapse.js +153 -0
- package/dist/core/redirects/csv.d.ts +15 -0
- package/dist/core/redirects/csv.js +68 -0
- package/dist/core/redirects/redirects.d.ts +58 -0
- package/dist/core/redirects/redirects.js +545 -0
- package/dist/core/registry/content.d.ts +26 -0
- package/dist/core/registry/content.js +9 -0
- package/dist/core/registry/define.d.ts +145 -0
- package/dist/core/registry/define.js +41 -0
- package/dist/core/registry/migration.d.ts +44 -0
- package/dist/core/registry/migration.js +4 -0
- package/dist/core/registry/registry.d.ts +18 -0
- package/dist/core/registry/registry.js +255 -0
- package/dist/core/registry/render.d.ts +98 -0
- package/dist/core/registry/render.js +1 -0
- package/dist/core/registry/route.d.ts +42 -0
- package/dist/core/registry/route.js +3 -0
- package/dist/core/release/bundle.d.ts +21 -0
- package/dist/core/release/bundle.js +252 -0
- package/dist/core/release/keys.d.ts +11 -0
- package/dist/core/release/keys.js +60 -0
- package/dist/core/release/manifest.d.ts +103 -0
- package/dist/core/release/manifest.js +138 -0
- package/dist/core/release/pack.d.ts +20 -0
- package/dist/core/release/pack.js +97 -0
- package/dist/core/release/pointer.d.ts +19 -0
- package/dist/core/release/pointer.js +53 -0
- package/dist/core/release/read.d.ts +59 -0
- package/dist/core/release/read.js +256 -0
- package/dist/core/report.d.ts +31 -0
- package/dist/core/report.js +37 -0
- package/dist/core/richtext/html.d.ts +15 -0
- package/dist/core/richtext/html.js +81 -0
- package/dist/core/richtext/markdown.d.ts +19 -0
- package/dist/core/richtext/markdown.js +951 -0
- package/dist/core/richtext/schema.d.ts +98 -0
- package/dist/core/richtext/schema.js +275 -0
- package/dist/core/site/live.d.ts +56 -0
- package/dist/core/site/live.js +145 -0
- package/dist/core/site/paths.d.ts +15 -0
- package/dist/core/site/paths.js +64 -0
- package/dist/core/site/resolve.d.ts +9 -0
- package/dist/core/site/resolve.js +202 -0
- package/dist/core/site/sitemap.d.ts +11 -0
- package/dist/core/site/sitemap.js +24 -0
- package/dist/core/site-lock/site-lock.d.ts +21 -0
- package/dist/core/site-lock/site-lock.js +65 -0
- package/dist/core/site-lock/token.d.ts +7 -0
- package/dist/core/site-lock/token.js +24 -0
- package/dist/core/theme.d.ts +22 -0
- package/dist/core/theme.js +133 -0
- package/dist/core/types.d.ts +253 -0
- package/dist/core/types.js +1 -0
- package/dist/core/version.d.ts +1 -0
- package/dist/core/version.js +5 -0
- package/dist/host/activate.d.ts +53 -0
- package/dist/host/activate.js +162 -0
- package/dist/host/app.d.ts +46 -0
- package/dist/host/app.js +129 -0
- package/dist/host/bin.d.ts +5 -0
- package/dist/host/bin.js +8 -0
- package/dist/host/config.d.ts +36 -0
- package/dist/host/config.js +152 -0
- package/dist/host/dev.d.ts +10 -0
- package/dist/host/dev.js +293 -0
- package/dist/host/diff.d.ts +78 -0
- package/dist/host/diff.js +346 -0
- package/dist/host/hooks.d.ts +41 -0
- package/dist/host/hooks.js +49 -0
- package/dist/host/ipc.d.ts +123 -0
- package/dist/host/ipc.js +61 -0
- package/dist/host/preview-proxy.d.ts +24 -0
- package/dist/host/preview-proxy.js +154 -0
- package/dist/host/preview-worker.d.ts +42 -0
- package/dist/host/preview-worker.js +242 -0
- package/dist/host/primary.d.ts +38 -0
- package/dist/host/primary.js +357 -0
- package/dist/host/push.d.ts +125 -0
- package/dist/host/push.js +420 -0
- package/dist/host/serve.d.ts +16 -0
- package/dist/host/serve.js +150 -0
- package/dist/host/store.d.ts +48 -0
- package/dist/host/store.js +109 -0
- package/dist/host/worker.d.ts +67 -0
- package/dist/host/worker.js +310 -0
- package/dist/index.d.ts +47 -0
- package/dist/index.js +32 -0
- package/dist/jsx/html.d.ts +16 -0
- package/dist/jsx/html.js +65 -0
- package/dist/jsx/jsx-dev-runtime.d.ts +4 -0
- package/dist/jsx/jsx-dev-runtime.js +5 -0
- package/dist/jsx/jsx-runtime.d.ts +17 -0
- package/dist/jsx/jsx-runtime.js +41 -0
- package/dist/site.d.ts +17 -0
- package/dist/site.js +14 -0
- package/package.json +111 -3
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { apiKey } from '@better-auth/api-key';
|
|
2
|
+
import { mcp } from '@better-auth/mcp';
|
|
3
|
+
import { betterAuth } from 'better-auth';
|
|
4
|
+
import { createAccessControl } from 'better-auth/plugins/access';
|
|
5
|
+
import { admin } from 'better-auth/plugins/admin';
|
|
6
|
+
import { adminAc, defaultStatements } from 'better-auth/plugins/admin/access';
|
|
7
|
+
import { jwt } from 'better-auth/plugins/jwt';
|
|
8
|
+
import { hashPassword, verifyPassword } from 'better-auth/crypto';
|
|
9
|
+
export const AUTH_BASE_PATH = '/api/auth';
|
|
10
|
+
export const MCP_PATH = '/mcp';
|
|
11
|
+
let testPasswordHasher;
|
|
12
|
+
/**
|
|
13
|
+
* Tests only: replaces better-auth's scrypt (~60 ms a call) for every auth
|
|
14
|
+
* created afterwards. Deliberately not a plugin option, so a site can't
|
|
15
|
+
* weaken its password storage by accident.
|
|
16
|
+
*/
|
|
17
|
+
export function setTestPasswordHasher(hasher) {
|
|
18
|
+
testPasswordHasher = hasher;
|
|
19
|
+
}
|
|
20
|
+
/** The hasher for passwords Inlay stores itself: the test hasher when set, otherwise better-auth's scrypt. */
|
|
21
|
+
export function passwordHasher() {
|
|
22
|
+
return testPasswordHasher ?? { hash: hashPassword, verify: verifyPassword };
|
|
23
|
+
}
|
|
24
|
+
const ac = createAccessControl(defaultStatements);
|
|
25
|
+
const owner = ac.newRole({ ...adminAc.statements });
|
|
26
|
+
const editor = ac.newRole({ user: [], session: [] });
|
|
27
|
+
/**
|
|
28
|
+
* better-auth on the content database (plan decisions 3, 4, 6, 7, 8). It
|
|
29
|
+
* shares the core's single SQLite connection, so never call `auth.api.*`
|
|
30
|
+
* inside a Kysely transaction: it would wait for the connection forever.
|
|
31
|
+
*/
|
|
32
|
+
export function createAuth(opts) {
|
|
33
|
+
return betterAuth({
|
|
34
|
+
secret: opts.secret,
|
|
35
|
+
baseURL: opts.baseUrl,
|
|
36
|
+
basePath: AUTH_BASE_PATH,
|
|
37
|
+
trustedOrigins: [opts.baseUrl],
|
|
38
|
+
database: { db: opts.db, type: 'sqlite' },
|
|
39
|
+
emailAndPassword: {
|
|
40
|
+
enabled: true,
|
|
41
|
+
disableSignUp: true,
|
|
42
|
+
minPasswordLength: 10,
|
|
43
|
+
...(testPasswordHasher && { password: testPasswordHasher }),
|
|
44
|
+
},
|
|
45
|
+
rateLimit: { enabled: opts.rateLimit ?? true, storage: 'memory' },
|
|
46
|
+
advanced: { ipAddress: { ipAddressHeaders: ['x-inlay-client-ip'] }, database: { validateSchema: false } },
|
|
47
|
+
plugins: [
|
|
48
|
+
admin({ ac, roles: { owner, editor }, adminRoles: ['owner'], defaultRole: 'editor' }),
|
|
49
|
+
jwt(),
|
|
50
|
+
mcp({
|
|
51
|
+
resource: opts.baseUrl + MCP_PATH,
|
|
52
|
+
loginPage: '/admin/login',
|
|
53
|
+
consentPage: '/admin/consent',
|
|
54
|
+
allowDynamicClientRegistration: true,
|
|
55
|
+
allowUnauthenticatedClientRegistration: true,
|
|
56
|
+
clientRegistrationDefaultApplicationType: 'infer',
|
|
57
|
+
}),
|
|
58
|
+
apiKey({ rateLimit: { enabled: false } }),
|
|
59
|
+
],
|
|
60
|
+
});
|
|
61
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Actor, Ctx, RevisionSource, Role } from '../types.js';
|
|
2
|
+
export type Action = 'content.read' | 'content.write' | 'content.publish' | 'entry.delete' | 'entry.restore' | 'backup.create' | 'backup.read' | 'content.export' | 'content.import' | 'media.write' | 'redirects.write' | 'users.manage' | 'site.protect' | 'release.push' | 'release.activate' | 'release.manage';
|
|
3
|
+
export declare function can(role: Role, action: Action): boolean;
|
|
4
|
+
/** Whether an API key may push releases: its user is an owner now and the key was made with the `release:push` permission. */
|
|
5
|
+
export declare function canPush(actor: Actor, permissions: {
|
|
6
|
+
release?: string[];
|
|
7
|
+
}): boolean;
|
|
8
|
+
export declare function assertCan(ctx: Ctx, action: Action): void;
|
|
9
|
+
/** The context for work Inlay does itself (initial content, system changes, restores). */
|
|
10
|
+
export declare function systemCtx(source: RevisionSource): Ctx;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { InlayError } from '../errors.js';
|
|
2
|
+
import { t } from '../messages/index.js';
|
|
3
|
+
/** What only owners may do. */
|
|
4
|
+
const OWNER_ONLY = new Set([
|
|
5
|
+
'entry.restore',
|
|
6
|
+
'backup.create',
|
|
7
|
+
'backup.read',
|
|
8
|
+
'content.export',
|
|
9
|
+
'content.import',
|
|
10
|
+
'users.manage',
|
|
11
|
+
'site.protect',
|
|
12
|
+
'release.push',
|
|
13
|
+
'release.activate',
|
|
14
|
+
'release.manage',
|
|
15
|
+
]);
|
|
16
|
+
export function can(role, action) {
|
|
17
|
+
switch (role) {
|
|
18
|
+
case 'owner':
|
|
19
|
+
case 'system':
|
|
20
|
+
return true;
|
|
21
|
+
case 'editor':
|
|
22
|
+
return !OWNER_ONLY.has(action);
|
|
23
|
+
default:
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** Whether an API key may push releases: its user is an owner now and the key was made with the `release:push` permission. */
|
|
28
|
+
export function canPush(actor, permissions) {
|
|
29
|
+
return actor.role === 'owner' && can(actor.role, 'release.push') && (permissions.release ?? []).includes('push');
|
|
30
|
+
}
|
|
31
|
+
export function assertCan(ctx, action) {
|
|
32
|
+
if (!can(ctx.actor.role, action))
|
|
33
|
+
throw new InlayError('forbidden', 'error.forbidden');
|
|
34
|
+
}
|
|
35
|
+
/** The context for work Inlay does itself (initial content, system changes, restores). */
|
|
36
|
+
export function systemCtx(source) {
|
|
37
|
+
return { actor: { id: null, name: t('label.system'), role: 'system' }, source };
|
|
38
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import type { Actor } from '../types.js';
|
|
2
|
+
import { type AuthOptions, type InlayAuth } from './auth.js';
|
|
3
|
+
export type UserRole = 'owner' | 'editor';
|
|
4
|
+
export interface UserInput {
|
|
5
|
+
email: string;
|
|
6
|
+
name: string;
|
|
7
|
+
password: string;
|
|
8
|
+
}
|
|
9
|
+
export interface UserInfo {
|
|
10
|
+
id: string;
|
|
11
|
+
name: string;
|
|
12
|
+
email: string;
|
|
13
|
+
role: UserRole | null;
|
|
14
|
+
banned: boolean;
|
|
15
|
+
createdAt: string;
|
|
16
|
+
}
|
|
17
|
+
export interface ApiKeyInfo {
|
|
18
|
+
id: string;
|
|
19
|
+
name: string;
|
|
20
|
+
/** The first characters of the key, to tell keys apart. */
|
|
21
|
+
start: string | null;
|
|
22
|
+
createdAt: string;
|
|
23
|
+
lastUsedAt: string | null;
|
|
24
|
+
}
|
|
25
|
+
/** The caller of a request made with an API key, and what the key was made to allow beyond its user's role. */
|
|
26
|
+
export interface ApiKeyAuth {
|
|
27
|
+
actor: Actor;
|
|
28
|
+
/** `release` holds `'push'` for a push key (see `canPush`); empty otherwise. */
|
|
29
|
+
permissions: {
|
|
30
|
+
release: string[];
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
export interface ApiKeyOptions {
|
|
34
|
+
/** `release: ['push']` makes a push key; only an owner may have one. */
|
|
35
|
+
permissions?: {
|
|
36
|
+
release?: ['push'];
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/** An assistant (OAuth client) a user has allowed on the consent page. */
|
|
40
|
+
export interface AssistantInfo {
|
|
41
|
+
clientId: string;
|
|
42
|
+
/** The name the assistant registered itself under, or its client id when it gave none. */
|
|
43
|
+
name: string;
|
|
44
|
+
redirectUris: string[];
|
|
45
|
+
/** When the user first allowed it. */
|
|
46
|
+
connectedAt: string;
|
|
47
|
+
}
|
|
48
|
+
export interface BearerAuth {
|
|
49
|
+
actor: Actor;
|
|
50
|
+
/** The OAuth client the token was issued to (`azp`). */
|
|
51
|
+
clientId: string;
|
|
52
|
+
scopes: string[];
|
|
53
|
+
/** The token's `exp`, in seconds since the epoch (as MCP's `AuthInfo.expiresAt`). */
|
|
54
|
+
expiresAt: number;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Everything Inlay asks of better-auth. Adapters go through this and never
|
|
58
|
+
* query better-auth's tables or call `auth.api.*` themselves (except
|
|
59
|
+
* forwarding requests to `auth.handler`). None of these may be called inside
|
|
60
|
+
* a Kysely transaction: better-auth shares the single SQLite connection.
|
|
61
|
+
*/
|
|
62
|
+
export interface AuthService {
|
|
63
|
+
auth: InlayAuth;
|
|
64
|
+
/** better-auth's issuer for OAuth tokens: `baseUrl` + `AUTH_BASE_PATH`. */
|
|
65
|
+
issuer: string;
|
|
66
|
+
/** The MCP protected resource, `${baseUrl}/mcp`: the audience of its access tokens. */
|
|
67
|
+
resource: string;
|
|
68
|
+
migrationsPending(): Promise<boolean>;
|
|
69
|
+
migrate(): Promise<void>;
|
|
70
|
+
hasOwner(): Promise<boolean>;
|
|
71
|
+
/** Throws invalid_operation `error.ownerExists`, or validation with plain-language issues (email, password length). */
|
|
72
|
+
createOwner(input: UserInput): Promise<Actor>;
|
|
73
|
+
/** Creates an editor or owner; for tests and Phase 6. */
|
|
74
|
+
createUser(input: UserInput & {
|
|
75
|
+
role: UserRole;
|
|
76
|
+
}): Promise<Actor>;
|
|
77
|
+
/** The actor for a user who may use Inlay right now, read from their current row; `null` for unknown, banned or role-less users. */
|
|
78
|
+
actorForUser(userId: string): Promise<Actor | null>;
|
|
79
|
+
sessionActor(headers: Headers): Promise<Actor | null>;
|
|
80
|
+
/** Verifies an MCP OAuth access token (a JWT) in-process. Any failure gives `null`. */
|
|
81
|
+
bearerActor(token: string): Promise<BearerAuth | null>;
|
|
82
|
+
apiKeyActor(key: string): Promise<ApiKeyAuth | null>;
|
|
83
|
+
/**
|
|
84
|
+
* Returns the plaintext key; only its hash is stored. A blank or overlong name is a validation issue on `keyName`.
|
|
85
|
+
* Asking for a push key for anyone but an owner is forbidden.
|
|
86
|
+
*/
|
|
87
|
+
createApiKey(userId: string, name: string, opts?: ApiKeyOptions): Promise<string>;
|
|
88
|
+
oauthClient(clientId: string): Promise<{
|
|
89
|
+
name: string;
|
|
90
|
+
redirectUris: string[];
|
|
91
|
+
} | null>;
|
|
92
|
+
/** Every user, sorted by name. Owners only (`users.manage`), as are the next four. */
|
|
93
|
+
listUsers(actor: Actor): Promise<UserInfo[]>;
|
|
94
|
+
/** Validated as `createUser`; an email already in use is a validation issue on `email`. */
|
|
95
|
+
addUser(actor: Actor, input: UserInput & {
|
|
96
|
+
role: UserRole;
|
|
97
|
+
}): Promise<UserInfo>;
|
|
98
|
+
/** invalid_operation `error.lastOwner` when it would leave the site without an owner. */
|
|
99
|
+
setRole(actor: Actor, userId: string, role: UserRole): Promise<void>;
|
|
100
|
+
/** Sets a user's password and ends every way they were signed in: sessions, API keys and OAuth (assistant) tokens. */
|
|
101
|
+
setPassword(actor: Actor, userId: string, password: string): Promise<void>;
|
|
102
|
+
/** Deletes the account with its sessions and API keys. invalid_operation `error.removeSelf` or `error.lastOwner`. */
|
|
103
|
+
removeUser(actor: Actor, userId: string): Promise<void>;
|
|
104
|
+
/**
|
|
105
|
+
* Changes a user's own password. A wrong `current` is a validation issue on `current`. Ends the user's sessions,
|
|
106
|
+
* except the one `keep` (request headers) carries, so the page that asked stays signed in. Also ends the user's
|
|
107
|
+
* assistant (OAuth) tokens, but not their API keys.
|
|
108
|
+
*/
|
|
109
|
+
changePassword(userId: string, current: string, next: string, keep?: Headers): Promise<void>;
|
|
110
|
+
/** The user's API keys, newest first; never the keys themselves. */
|
|
111
|
+
listApiKeys(userId: string): Promise<ApiKeyInfo[]>;
|
|
112
|
+
/** not_found unless `keyId` is one of the user's own keys. */
|
|
113
|
+
deleteApiKey(userId: string, keyId: string): Promise<void>;
|
|
114
|
+
/** The assistants the user has allowed, newest first. These are approvals, not live tokens. */
|
|
115
|
+
listAssistants(userId: string): Promise<AssistantInfo[]>;
|
|
116
|
+
}
|
|
117
|
+
export declare const MIN_PASSWORD = 10;
|
|
118
|
+
export declare function createAuthService(opts: AuthOptions): AuthService;
|
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
import { APIError } from 'better-auth/api';
|
|
2
|
+
import { getMigrations } from 'better-auth/db/migration';
|
|
3
|
+
import { createLocalJWKSet, errors, jwtVerify } from 'jose';
|
|
4
|
+
import { sql } from 'kysely';
|
|
5
|
+
import { contentIssue } from '../content/validate.js';
|
|
6
|
+
import { InlayError } from '../errors.js';
|
|
7
|
+
import { t } from '../messages/index.js';
|
|
8
|
+
import { assertCan } from './roles.js';
|
|
9
|
+
import { AUTH_BASE_PATH, createAuth, MCP_PATH } from './auth.js';
|
|
10
|
+
/** The shortest time between two re-reads of the signing keys for an unknown `kid`. */
|
|
11
|
+
const JWKS_COOLDOWN_MS = 30_000;
|
|
12
|
+
export const MIN_PASSWORD = 10;
|
|
13
|
+
/** better-auth's default `maxPasswordLength`. */
|
|
14
|
+
const MAX_PASSWORD = 128;
|
|
15
|
+
/** The api-key plugin's default `maximumNameLength`. */
|
|
16
|
+
const MAX_KEY_NAME = 32;
|
|
17
|
+
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
18
|
+
const LABELS = {
|
|
19
|
+
email: 'label.user.email',
|
|
20
|
+
name: 'label.user.name',
|
|
21
|
+
password: 'label.user.password',
|
|
22
|
+
current: 'label.user.currentPassword',
|
|
23
|
+
keyName: 'label.apiKey.name',
|
|
24
|
+
};
|
|
25
|
+
function userIssue(at, code, messageId, params = {}) {
|
|
26
|
+
return contentIssue([at], [t(LABELS[at])], code, messageId, params);
|
|
27
|
+
}
|
|
28
|
+
function checkPassword(password) {
|
|
29
|
+
if (password.length < MIN_PASSWORD)
|
|
30
|
+
return [userIssue('password', 'too_short', 'issue.tooShort', { min: MIN_PASSWORD })];
|
|
31
|
+
if (password.length > MAX_PASSWORD)
|
|
32
|
+
return [userIssue('password', 'too_long', 'issue.tooLong', { max: MAX_PASSWORD })];
|
|
33
|
+
return [];
|
|
34
|
+
}
|
|
35
|
+
function checkUser(input) {
|
|
36
|
+
const issues = [];
|
|
37
|
+
if (!EMAIL.test(input.email.trim()))
|
|
38
|
+
issues.push(userIssue('email', 'invalid', 'issue.email'));
|
|
39
|
+
if (input.name.trim() === '')
|
|
40
|
+
issues.push(userIssue('name', 'required', 'issue.required'));
|
|
41
|
+
issues.push(...checkPassword(input.password));
|
|
42
|
+
return issues;
|
|
43
|
+
}
|
|
44
|
+
const invalid = (issues) => new InlayError('validation', 'error.validation', {}, { issues });
|
|
45
|
+
const isRole = (role) => role === 'owner' || role === 'editor';
|
|
46
|
+
/** More users or API keys than any site has; better-auth's adapter reads 100 rows unless told otherwise. */
|
|
47
|
+
const ALL = 100_000;
|
|
48
|
+
const iso = (value) => (value instanceof Date ? value.toISOString() : String(value));
|
|
49
|
+
const manage = (actor) => assertCan({ actor, source: 'admin' }, 'users.manage');
|
|
50
|
+
const userNotFound = () => new InlayError('not_found', 'error.userNotFound');
|
|
51
|
+
export function createAuthService(opts) {
|
|
52
|
+
const { db } = opts;
|
|
53
|
+
const auth = createAuth(opts);
|
|
54
|
+
const issuer = `${opts.baseUrl}${AUTH_BASE_PATH}`;
|
|
55
|
+
const resource = `${opts.baseUrl}${MCP_PATH}`;
|
|
56
|
+
// better-auth compares column types on every run and warns that its
|
|
57
|
+
// string[] columns are TEXT, which is how it stores them on SQLite.
|
|
58
|
+
const migrations = () => getMigrations({ ...auth.options, logger: { level: 'error' } });
|
|
59
|
+
async function actorForUser(userId) {
|
|
60
|
+
const row = await db
|
|
61
|
+
.selectFrom('user')
|
|
62
|
+
.select(['id', 'name', 'role', 'banned', 'banExpires'])
|
|
63
|
+
.where('id', '=', userId)
|
|
64
|
+
.executeTakeFirst();
|
|
65
|
+
if (!row || !isRole(row.role))
|
|
66
|
+
return null;
|
|
67
|
+
if (row.banned && !(row.banExpires !== null && Date.parse(row.banExpires) <= Date.now()))
|
|
68
|
+
return null;
|
|
69
|
+
return { id: row.id, name: row.name, role: row.role };
|
|
70
|
+
}
|
|
71
|
+
async function hasOwner() {
|
|
72
|
+
return (await db.selectFrom('user').select('id').where('role', '=', 'owner').executeTakeFirst()) !== undefined;
|
|
73
|
+
}
|
|
74
|
+
async function createUser(input) {
|
|
75
|
+
const issues = checkUser(input);
|
|
76
|
+
if (issues.length > 0)
|
|
77
|
+
throw invalid(issues);
|
|
78
|
+
try {
|
|
79
|
+
const { user } = await auth.api.createUser({
|
|
80
|
+
body: { email: input.email.trim(), name: input.name.trim(), password: input.password, role: input.role },
|
|
81
|
+
});
|
|
82
|
+
return { id: user.id, name: user.name, role: input.role };
|
|
83
|
+
}
|
|
84
|
+
catch (e) {
|
|
85
|
+
const code = e instanceof APIError ? e.body?.code : undefined;
|
|
86
|
+
if (typeof code === 'string' && code.startsWith('USER_ALREADY_EXISTS'))
|
|
87
|
+
throw invalid([userIssue('email', 'invalid', 'issue.emailTaken')]);
|
|
88
|
+
if (code === 'INVALID_EMAIL')
|
|
89
|
+
throw invalid([userIssue('email', 'invalid', 'issue.email')]);
|
|
90
|
+
throw e;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
// Serialises createOwner within this process, so two concurrent calls make one owner.
|
|
94
|
+
let ownerLock = Promise.resolve();
|
|
95
|
+
/**
|
|
96
|
+
* The lock can't see another process (`inlaycms create-owner` beside a running site), so once `actor` exists as
|
|
97
|
+
* an owner, it checks the database too. Of two owners made at once, the one inserted later (higher `rowid`)
|
|
98
|
+
* gives way: it deletes itself, with its account and sessions, and the call fails as if the other owner had
|
|
99
|
+
* come first. A process that sees only itself was inserted first, so exactly one owner remains.
|
|
100
|
+
*/
|
|
101
|
+
async function keepFirstOwner(actor) {
|
|
102
|
+
if (actor.id === null)
|
|
103
|
+
return actor;
|
|
104
|
+
const first = await db
|
|
105
|
+
.selectFrom('user')
|
|
106
|
+
.select('id')
|
|
107
|
+
.where('role', '=', 'owner')
|
|
108
|
+
.orderBy(sql `rowid`)
|
|
109
|
+
.executeTakeFirst();
|
|
110
|
+
if (first === undefined || first.id === actor.id)
|
|
111
|
+
return actor;
|
|
112
|
+
const { internalAdapter } = await auth.$context;
|
|
113
|
+
await internalAdapter.deleteUser(actor.id);
|
|
114
|
+
throw new InlayError('invalid_operation', 'error.ownerExists');
|
|
115
|
+
}
|
|
116
|
+
// Serialises role changes and removals within this process, so two at once can't both take away the last owner.
|
|
117
|
+
let usersLock = Promise.resolve();
|
|
118
|
+
function serially(work) {
|
|
119
|
+
const run = usersLock.then(work);
|
|
120
|
+
usersLock = run.catch(() => undefined);
|
|
121
|
+
return run;
|
|
122
|
+
}
|
|
123
|
+
/** Throws `error.lastOwner` unless an owner other than `userId` can still use the site. */
|
|
124
|
+
async function assertOtherOwner(userId) {
|
|
125
|
+
const other = await db
|
|
126
|
+
.selectFrom('user')
|
|
127
|
+
.select('id')
|
|
128
|
+
.where('role', '=', 'owner')
|
|
129
|
+
.where('id', '!=', userId)
|
|
130
|
+
.where((eb) => eb.or([eb('banned', 'is', null), eb('banned', '=', 0)]))
|
|
131
|
+
.executeTakeFirst();
|
|
132
|
+
if (other === undefined)
|
|
133
|
+
throw new InlayError('invalid_operation', 'error.lastOwner');
|
|
134
|
+
}
|
|
135
|
+
const userInfo = (user) => ({
|
|
136
|
+
id: user.id,
|
|
137
|
+
name: user.name,
|
|
138
|
+
email: user.email,
|
|
139
|
+
role: isRole(user.role) ? user.role : null,
|
|
140
|
+
banned: user.banned === true,
|
|
141
|
+
createdAt: iso(user.createdAt),
|
|
142
|
+
});
|
|
143
|
+
/**
|
|
144
|
+
* Ends every other way in for a user: the OAuth tokens better-auth stores (refresh tokens would mint new access
|
|
145
|
+
* tokens), and through the cutoff, the access tokens already handed out, which are JWTs checked without the
|
|
146
|
+
* database. API keys end too unless `apiKeys` is false.
|
|
147
|
+
*/
|
|
148
|
+
async function endTokens(userId, opts) {
|
|
149
|
+
const { adapter } = await auth.$context;
|
|
150
|
+
if (opts.apiKeys)
|
|
151
|
+
await adapter.deleteMany({ model: 'apikey', where: [{ field: 'referenceId', value: userId }] });
|
|
152
|
+
await adapter.deleteMany({ model: 'oauthRefreshToken', where: [{ field: 'userId', value: userId }] });
|
|
153
|
+
await adapter.deleteMany({ model: 'oauthAccessToken', where: [{ field: 'userId', value: userId }] });
|
|
154
|
+
const before = Math.floor(Date.now() / 1000);
|
|
155
|
+
await db
|
|
156
|
+
.insertInto('token_cutoffs')
|
|
157
|
+
.values({ user_id: userId, before })
|
|
158
|
+
.onConflict((oc) => oc.column('user_id').doUpdateSet({ before }))
|
|
159
|
+
.execute();
|
|
160
|
+
}
|
|
161
|
+
async function findUser(userId) {
|
|
162
|
+
const { internalAdapter } = await auth.$context;
|
|
163
|
+
const user = (await internalAdapter.findUserById(userId));
|
|
164
|
+
if (!user)
|
|
165
|
+
throw userNotFound();
|
|
166
|
+
return user;
|
|
167
|
+
}
|
|
168
|
+
async function findApiKeys(userId) {
|
|
169
|
+
const { adapter } = await auth.$context;
|
|
170
|
+
return adapter.findMany({ model: 'apikey', where: [{ field: 'referenceId', value: userId }], limit: ALL });
|
|
171
|
+
}
|
|
172
|
+
let keys = null;
|
|
173
|
+
/** When the keys were last read, or 0 when that read found none (so the first key ever made is picked up at once). */
|
|
174
|
+
let keysReadAt = 0;
|
|
175
|
+
const loadKeys = async () => {
|
|
176
|
+
const jwks = await auth.api.getJwks();
|
|
177
|
+
keysReadAt = jwks.keys.length > 0 ? Date.now() : 0;
|
|
178
|
+
return (keys = createLocalJWKSet(jwks));
|
|
179
|
+
};
|
|
180
|
+
// Keys come from the database, never over HTTP. An unknown kid re-reads them in case they rotated, but at most
|
|
181
|
+
// once per cooldown, so a stream of tokens with made-up kids can't make every request hit the database.
|
|
182
|
+
const getKey = async (header, token) => {
|
|
183
|
+
const current = keys ?? (await loadKeys());
|
|
184
|
+
try {
|
|
185
|
+
return await current(header, token);
|
|
186
|
+
}
|
|
187
|
+
catch (e) {
|
|
188
|
+
if (!(e instanceof errors.JWKSNoMatchingKey) || Date.now() - keysReadAt < JWKS_COOLDOWN_MS)
|
|
189
|
+
throw e;
|
|
190
|
+
return (await loadKeys())(header, token);
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
return {
|
|
194
|
+
auth,
|
|
195
|
+
issuer,
|
|
196
|
+
resource,
|
|
197
|
+
async migrationsPending() {
|
|
198
|
+
const { toBeCreated, toBeAdded } = await migrations();
|
|
199
|
+
return toBeCreated.length + toBeAdded.length > 0;
|
|
200
|
+
},
|
|
201
|
+
async migrate() {
|
|
202
|
+
await (await migrations()).runMigrations();
|
|
203
|
+
},
|
|
204
|
+
hasOwner,
|
|
205
|
+
createOwner(input) {
|
|
206
|
+
const run = ownerLock.then(async () => {
|
|
207
|
+
if (await hasOwner())
|
|
208
|
+
throw new InlayError('invalid_operation', 'error.ownerExists');
|
|
209
|
+
return keepFirstOwner(await createUser({ ...input, role: 'owner' }));
|
|
210
|
+
});
|
|
211
|
+
ownerLock = run.catch(() => undefined);
|
|
212
|
+
return run;
|
|
213
|
+
},
|
|
214
|
+
createUser,
|
|
215
|
+
actorForUser,
|
|
216
|
+
async sessionActor(headers) {
|
|
217
|
+
let session;
|
|
218
|
+
try {
|
|
219
|
+
session = await auth.api.getSession({ headers });
|
|
220
|
+
}
|
|
221
|
+
catch (e) {
|
|
222
|
+
if (e instanceof APIError)
|
|
223
|
+
return null;
|
|
224
|
+
throw e;
|
|
225
|
+
}
|
|
226
|
+
return session ? actorForUser(session.user.id) : null;
|
|
227
|
+
},
|
|
228
|
+
async bearerActor(token) {
|
|
229
|
+
let claims;
|
|
230
|
+
try {
|
|
231
|
+
const { payload } = await jwtVerify(token, getKey, { issuer, audience: resource, requiredClaims: ['sub', 'exp', 'iat'] });
|
|
232
|
+
const { sub, azp, scope, exp, iat } = payload;
|
|
233
|
+
if (typeof sub !== 'string' || typeof azp !== 'string' || typeof exp !== 'number' || typeof iat !== 'number')
|
|
234
|
+
return null;
|
|
235
|
+
claims = { sub, azp, scope, exp, iat };
|
|
236
|
+
}
|
|
237
|
+
catch (e) {
|
|
238
|
+
if (e instanceof errors.JOSEError)
|
|
239
|
+
return null;
|
|
240
|
+
throw e;
|
|
241
|
+
}
|
|
242
|
+
const cutoff = await db.selectFrom('token_cutoffs').select('before').where('user_id', '=', claims.sub).executeTakeFirst();
|
|
243
|
+
if (cutoff && claims.iat <= cutoff.before)
|
|
244
|
+
return null;
|
|
245
|
+
const actor = await actorForUser(claims.sub);
|
|
246
|
+
if (!actor)
|
|
247
|
+
return null;
|
|
248
|
+
const scopes = typeof claims.scope === 'string' ? claims.scope.split(' ').filter((s) => s !== '') : [];
|
|
249
|
+
return { actor, clientId: claims.azp, scopes, expiresAt: claims.exp };
|
|
250
|
+
},
|
|
251
|
+
async apiKeyActor(key) {
|
|
252
|
+
if (key === '')
|
|
253
|
+
return null;
|
|
254
|
+
let result;
|
|
255
|
+
try {
|
|
256
|
+
result = await auth.api.verifyApiKey({ body: { key } });
|
|
257
|
+
}
|
|
258
|
+
catch (e) {
|
|
259
|
+
if (e instanceof APIError)
|
|
260
|
+
return null;
|
|
261
|
+
throw e;
|
|
262
|
+
}
|
|
263
|
+
if (!result.valid || !result.key)
|
|
264
|
+
return null;
|
|
265
|
+
const actor = await actorForUser(result.key.referenceId);
|
|
266
|
+
if (!actor)
|
|
267
|
+
return null;
|
|
268
|
+
const release = result.key.permissions?.release;
|
|
269
|
+
return { actor, permissions: { release: Array.isArray(release) ? release.filter((p) => typeof p === 'string') : [] } };
|
|
270
|
+
},
|
|
271
|
+
async createApiKey(userId, name, opts = {}) {
|
|
272
|
+
const trimmed = name.trim();
|
|
273
|
+
if (trimmed === '')
|
|
274
|
+
throw invalid([userIssue('keyName', 'required', 'issue.required')]);
|
|
275
|
+
if (trimmed.length > MAX_KEY_NAME)
|
|
276
|
+
throw invalid([userIssue('keyName', 'too_long', 'issue.tooLong', { max: MAX_KEY_NAME })]);
|
|
277
|
+
const push = opts.permissions?.release?.includes('push') === true;
|
|
278
|
+
if (push && (await actorForUser(userId))?.role !== 'owner')
|
|
279
|
+
throw new InlayError('forbidden', 'error.forbidden');
|
|
280
|
+
const body = { userId, name: trimmed, ...(push && { permissions: { release: ['push'] } }) };
|
|
281
|
+
return (await auth.api.createApiKey({ body })).key;
|
|
282
|
+
},
|
|
283
|
+
async oauthClient(clientId) {
|
|
284
|
+
const row = await db.selectFrom('oauthClient').select(['name', 'redirectUris']).where('clientId', '=', clientId).executeTakeFirst();
|
|
285
|
+
if (!row)
|
|
286
|
+
return null;
|
|
287
|
+
const uris = JSON.parse(row.redirectUris);
|
|
288
|
+
const redirectUris = Array.isArray(uris) ? uris.filter((u) => typeof u === 'string') : [];
|
|
289
|
+
return { name: row.name ?? clientId, redirectUris };
|
|
290
|
+
},
|
|
291
|
+
async listUsers(actor) {
|
|
292
|
+
manage(actor);
|
|
293
|
+
const { internalAdapter } = await auth.$context;
|
|
294
|
+
const users = (await internalAdapter.listUsers(ALL));
|
|
295
|
+
return users.map(userInfo).sort((a, b) => a.name.localeCompare(b.name) || a.email.localeCompare(b.email));
|
|
296
|
+
},
|
|
297
|
+
async addUser(actor, input) {
|
|
298
|
+
manage(actor);
|
|
299
|
+
const { id } = await createUser(input);
|
|
300
|
+
return userInfo(await findUser(id));
|
|
301
|
+
},
|
|
302
|
+
async setRole(actor, userId, role) {
|
|
303
|
+
manage(actor);
|
|
304
|
+
return serially(async () => {
|
|
305
|
+
const user = await findUser(userId);
|
|
306
|
+
if (user.role === role)
|
|
307
|
+
return;
|
|
308
|
+
if (user.role === 'owner')
|
|
309
|
+
await assertOtherOwner(userId);
|
|
310
|
+
const { internalAdapter } = await auth.$context;
|
|
311
|
+
await internalAdapter.updateUser(userId, { role });
|
|
312
|
+
});
|
|
313
|
+
},
|
|
314
|
+
async setPassword(actor, userId, password) {
|
|
315
|
+
manage(actor);
|
|
316
|
+
const issues = checkPassword(password);
|
|
317
|
+
if (issues.length > 0)
|
|
318
|
+
throw invalid(issues);
|
|
319
|
+
const user = await findUser(userId);
|
|
320
|
+
const ctx = await auth.$context;
|
|
321
|
+
const hash = await ctx.password.hash(password);
|
|
322
|
+
// As better-auth's admin `setUserPassword`, which needs an admin session to call.
|
|
323
|
+
if (await ctx.internalAdapter.findCredentialAccount(userId))
|
|
324
|
+
await ctx.internalAdapter.updatePassword(userId, hash);
|
|
325
|
+
else
|
|
326
|
+
await ctx.internalAdapter.createAccount({ userId, providerId: 'credential', accountId: user.id, password: hash });
|
|
327
|
+
await ctx.internalAdapter.deleteUserSessions(userId);
|
|
328
|
+
// A reset is often for a password someone else may know, so every other way in ends too, API keys included.
|
|
329
|
+
await endTokens(userId, { apiKeys: true });
|
|
330
|
+
},
|
|
331
|
+
async removeUser(actor, userId) {
|
|
332
|
+
manage(actor);
|
|
333
|
+
if (userId === actor.id)
|
|
334
|
+
throw new InlayError('invalid_operation', 'error.removeSelf');
|
|
335
|
+
return serially(async () => {
|
|
336
|
+
const user = await findUser(userId);
|
|
337
|
+
if (user.role === 'owner')
|
|
338
|
+
await assertOtherOwner(userId);
|
|
339
|
+
const { adapter, internalAdapter } = await auth.$context;
|
|
340
|
+
// API keys point at their user without a foreign key, so they go first, by hand.
|
|
341
|
+
await adapter.deleteMany({ model: 'apikey', where: [{ field: 'referenceId', value: userId }] });
|
|
342
|
+
await internalAdapter.deleteUserSessions(userId);
|
|
343
|
+
// Also deletes the user's accounts; OAuth tokens and consents cascade. Revisions keep the author's name.
|
|
344
|
+
await internalAdapter.deleteUser(userId);
|
|
345
|
+
await db.deleteFrom('token_cutoffs').where('user_id', '=', userId).execute();
|
|
346
|
+
});
|
|
347
|
+
},
|
|
348
|
+
async changePassword(userId, current, next, keep) {
|
|
349
|
+
const ctx = await auth.$context;
|
|
350
|
+
const account = await ctx.internalAdapter.findCredentialAccount(userId);
|
|
351
|
+
const issues = [];
|
|
352
|
+
if (!account?.password || !(await ctx.password.verify({ hash: account.password, password: current }))) {
|
|
353
|
+
issues.push(userIssue('current', 'invalid', 'issue.wrongPassword'));
|
|
354
|
+
}
|
|
355
|
+
issues.push(...checkPassword(next));
|
|
356
|
+
if (issues.length > 0)
|
|
357
|
+
throw invalid(issues);
|
|
358
|
+
await ctx.internalAdapter.updatePassword(userId, await ctx.password.hash(next));
|
|
359
|
+
let kept;
|
|
360
|
+
if (keep) {
|
|
361
|
+
try {
|
|
362
|
+
const session = await auth.api.getSession({ headers: keep });
|
|
363
|
+
if (session?.user.id === userId)
|
|
364
|
+
kept = session.session.token;
|
|
365
|
+
}
|
|
366
|
+
catch (e) {
|
|
367
|
+
if (!(e instanceof APIError))
|
|
368
|
+
throw e;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
const sessions = await ctx.internalAdapter.listSessions(userId);
|
|
372
|
+
const others = sessions.map((s) => s.token).filter((token) => token !== kept);
|
|
373
|
+
if (others.length > 0)
|
|
374
|
+
await ctx.internalAdapter.deleteSessions(others);
|
|
375
|
+
await endTokens(userId, { apiKeys: false });
|
|
376
|
+
},
|
|
377
|
+
async listApiKeys(userId) {
|
|
378
|
+
const rows = await findApiKeys(userId);
|
|
379
|
+
return rows
|
|
380
|
+
.map((row) => ({
|
|
381
|
+
id: row.id,
|
|
382
|
+
name: row.name ?? '',
|
|
383
|
+
start: row.start,
|
|
384
|
+
createdAt: iso(row.createdAt),
|
|
385
|
+
lastUsedAt: row.lastRequest ? iso(row.lastRequest) : null,
|
|
386
|
+
}))
|
|
387
|
+
.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
388
|
+
},
|
|
389
|
+
async deleteApiKey(userId, keyId) {
|
|
390
|
+
const { adapter } = await auth.$context;
|
|
391
|
+
const key = await adapter.findOne({ model: 'apikey', where: [{ field: 'id', value: keyId }] });
|
|
392
|
+
if (!key || key.referenceId !== userId)
|
|
393
|
+
throw new InlayError('not_found', 'error.apiKeyNotFound');
|
|
394
|
+
await adapter.delete({ model: 'apikey', where: [{ field: 'id', value: keyId }] });
|
|
395
|
+
},
|
|
396
|
+
async listAssistants(userId) {
|
|
397
|
+
const { adapter } = await auth.$context;
|
|
398
|
+
const consents = await adapter.findMany({
|
|
399
|
+
model: 'oauthConsent',
|
|
400
|
+
where: [{ field: 'userId', value: userId }],
|
|
401
|
+
limit: ALL,
|
|
402
|
+
});
|
|
403
|
+
if (consents.length === 0)
|
|
404
|
+
return [];
|
|
405
|
+
const clients = await adapter.findMany({
|
|
406
|
+
model: 'oauthClient',
|
|
407
|
+
where: [{ field: 'clientId', operator: 'in', value: consents.map((c) => c.clientId) }],
|
|
408
|
+
limit: ALL,
|
|
409
|
+
});
|
|
410
|
+
const byId = new Map(clients.map((c) => [c.clientId, c]));
|
|
411
|
+
return consents
|
|
412
|
+
.map((consent) => {
|
|
413
|
+
const client = byId.get(consent.clientId);
|
|
414
|
+
return {
|
|
415
|
+
clientId: consent.clientId,
|
|
416
|
+
name: client?.name ?? consent.clientId,
|
|
417
|
+
redirectUris: client?.redirectUris ?? [],
|
|
418
|
+
connectedAt: iso(consent.createdAt),
|
|
419
|
+
};
|
|
420
|
+
})
|
|
421
|
+
.sort((a, b) => b.connectedAt.localeCompare(a.connectedAt));
|
|
422
|
+
},
|
|
423
|
+
};
|
|
424
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare const UPLOAD_TTL_MS = 3600000;
|
|
2
|
+
/** An upload link token for `userId`, valid for `UPLOAD_TTL_MS` from `now`: `u1.<userId base64url>.<expiry ms base36>.<HMAC-SHA256 base64url>`. */
|
|
3
|
+
export declare function createUploadToken(secret: string, userId: string, now: Date): string;
|
|
4
|
+
/** The token's user and expiry, or `null` if it's malformed, wasn't signed with `secret`, or has expired. */
|
|
5
|
+
export declare function verifyUploadToken(secret: string, token: string, now: Date): {
|
|
6
|
+
userId: string;
|
|
7
|
+
expiresAt: Date;
|
|
8
|
+
} | null;
|