sandcms 0.6.3 → 0.8.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 +15 -11
- package/dist/admin/Account.svelte +2 -0
- package/dist/admin/Admin.svelte +21 -6
- package/dist/admin/AssetAttachment.svelte +9 -6
- package/dist/admin/AssetAttachment.svelte.d.ts +3 -1
- package/dist/admin/BlueprintFields.svelte +0 -3
- package/dist/admin/BlueprintFields.svelte.d.ts +0 -1
- package/dist/admin/Editor.svelte +5 -10
- package/dist/admin/Fields.svelte +2 -8
- package/dist/admin/Fields.svelte.d.ts +0 -1
- package/dist/admin/Gallery.svelte +221 -80
- package/dist/admin/Gallery.svelte.d.ts +0 -1
- package/dist/admin/Inbox.svelte +3 -2
- package/dist/admin/LinkField.svelte +0 -3
- package/dist/admin/LinkField.svelte.d.ts +0 -1
- package/dist/admin/MediaLibrary.svelte +10 -7
- package/dist/admin/MediaPicker.svelte +43 -35
- package/dist/admin/MediaPicker.svelte.d.ts +0 -1
- package/dist/admin/Navigation.svelte +13 -2
- package/dist/admin/Pages.svelte +195 -0
- package/dist/admin/Pages.svelte.d.ts +7 -0
- package/dist/admin/Shell.svelte +27 -5
- package/dist/admin/SortableList.svelte +82 -61
- package/dist/admin/SortableList.svelte.d.ts +3 -1
- package/dist/admin/ThemePicker.svelte +72 -0
- package/dist/admin/ThemePicker.svelte.d.ts +18 -0
- package/dist/admin/UploadButton.svelte +2 -1
- package/dist/admin/UploadProgress.svelte +24 -0
- package/dist/admin/UploadProgress.svelte.d.ts +7 -0
- package/dist/admin/Users.svelte +8 -3
- package/dist/admin/client.d.ts +3 -670
- package/dist/admin/client.js +2 -1
- package/dist/admin/components/ui/alert/alert.svelte.d.ts +3 -13
- package/dist/admin/components/ui/attachment/attachment-media.svelte.d.ts +3 -13
- package/dist/admin/components/ui/attachment/attachment.svelte.d.ts +6 -26
- package/dist/admin/components/ui/badge/badge.svelte.d.ts +7 -25
- package/dist/admin/components/ui/button/button.svelte.d.ts +15 -53
- package/dist/admin/components/ui/toggle/toggle.svelte.d.ts +6 -26
- package/dist/admin/generated/admin.css +823 -115
- package/dist/admin/navigation.d.ts +9 -0
- package/dist/admin/navigation.js +20 -1
- package/dist/admin/theme-context.d.ts +7 -0
- package/dist/admin/theme-context.js +3 -0
- package/dist/admin/theme.d.ts +7 -0
- package/dist/admin/theme.js +14 -0
- package/dist/admin/types.d.ts +3 -1
- package/dist/admin/uploads.d.ts +8 -1
- package/dist/admin/uploads.js +94 -16
- package/dist/blueprints/files.js +1 -0
- package/dist/blueprints/labels.d.ts +6 -0
- package/dist/blueprints/labels.js +14 -0
- package/dist/blueprints/load.js +16 -2
- package/dist/blueprints/types.d.ts +4 -1
- package/dist/cli/admin.d.ts +39 -0
- package/dist/cli/admin.js +95 -0
- package/dist/cli/backup.js +4 -4
- package/dist/cli/doctor.d.ts +10 -1
- package/dist/cli/doctor.js +98 -33
- package/dist/cli/email-test.d.ts +3 -0
- package/dist/cli/email-test.js +20 -0
- package/dist/cli/files.d.ts +2 -6
- package/dist/cli/files.js +12 -2
- package/dist/cli/index.js +401 -95
- package/dist/cli/rebaseline.d.ts +10 -0
- package/dist/cli/rebaseline.js +117 -0
- package/dist/cli/scaffold.js +8 -8
- package/dist/cli/setup.js +16 -26
- package/dist/cli/upgrade.js +34 -7
- package/dist/env.d.ts +26 -2
- package/dist/env.js +48 -6
- package/dist/notification-fields.js +2 -1
- package/dist/server/admin-load.d.ts +85 -5
- package/dist/server/admin-load.js +26 -1
- package/dist/server/api-access.d.ts +4 -0
- package/dist/server/api-access.js +15 -2
- package/dist/server/api-keys.d.ts +96 -0
- package/dist/server/api-keys.js +115 -0
- package/dist/server/api-pagination.d.ts +3 -0
- package/dist/server/api.js +21 -63
- package/dist/server/auth.d.ts +10 -9
- package/dist/server/cms.d.ts +63 -21
- package/dist/server/cms.js +64 -7
- package/dist/server/db/auto-migrate.d.ts +0 -4
- package/dist/server/db/auto-migrate.js +12 -3
- package/dist/server/db/legacy.d.ts +13 -0
- package/dist/server/db/legacy.js +60 -0
- package/dist/server/db/migration-data.js +2 -34
- package/dist/server/db/migrations/{0000_foundation.sql → 0000_baseline.sql} +120 -4
- package/dist/server/db/migrations/meta/0000_snapshot.json +578 -3
- package/dist/server/db/migrations/meta/_journal.json +2 -58
- package/dist/server/db/schema.d.ts +119 -2
- package/dist/server/db/schema.js +23 -9
- package/dist/server/db/store.d.ts +25 -2
- package/dist/server/db/store.js +90 -26
- package/dist/server/forms.js +2 -1
- package/dist/server/hooks.js +155 -81
- package/dist/server/media/contracts.d.ts +115 -0
- package/dist/server/media/contracts.js +12 -0
- package/dist/server/media/deletions.d.ts +2 -1
- package/dist/server/media/deletions.js +3 -3
- package/dist/server/media/delivery.js +7 -11
- package/dist/server/media/processor-child.d.ts +2 -0
- package/dist/server/media/processor-child.js +236 -0
- package/dist/server/media/processor.d.ts +51 -0
- package/dist/server/media/processor.js +135 -0
- package/dist/server/media/render-math.d.ts +24 -0
- package/dist/server/media/render-math.js +50 -0
- package/dist/server/media/runner.d.ts +30 -1
- package/dist/server/media/runner.js +418 -165
- package/dist/server/media/service.d.ts +53 -11
- package/dist/server/media/service.js +307 -98
- package/dist/server/media/storage.d.ts +5 -0
- package/dist/server/media/storage.js +279 -0
- package/dist/server/media/upload-ticket.d.ts +12 -0
- package/dist/server/media/upload-ticket.js +35 -0
- package/dist/server/media/verify.d.ts +64 -0
- package/dist/server/media/verify.js +201 -0
- package/dist/server/platform/http.d.ts +27 -0
- package/dist/server/platform/http.js +77 -0
- package/dist/server/platform/index.d.ts +52 -0
- package/dist/server/platform/index.js +98 -0
- package/dist/server/platform/snapshots.d.ts +18 -0
- package/dist/server/platform/snapshots.js +110 -0
- package/dist/server/platform/volume.d.ts +20 -0
- package/dist/server/platform/volume.js +60 -0
- package/docs/acceptance.md +7 -5
- package/docs/api.md +56 -4
- package/docs/cloudflare.md +26 -152
- package/docs/content.md +20 -5
- package/docs/deployment.md +222 -57
- package/docs/email.md +6 -0
- package/docs/forms.md +2 -2
- package/docs/media.md +94 -21
- package/docs/package.md +21 -18
- package/docs/plans/0.7-self-hosted.md +264 -0
- package/docs/releases.md +37 -1
- package/docs/upgrades.md +72 -9
- package/package.json +37 -44
- package/templates/Dockerfile +32 -0
- package/templates/integration.ts +26 -5
- package/templates/openship.json +9 -0
- package/templates/railpack.json +1 -1
- package/templates/sandcms/blueprints/files/image.yaml +1 -1
- package/templates/sandcms/config.yaml +1 -1
- package/dist/cli/cloudflare.d.ts +0 -8
- package/dist/cli/cloudflare.js +0 -135
- package/dist/server/db/migrations/0001_independent_password_resets.sql +0 -3
- package/dist/server/db/migrations/0002_email_failure_reason.sql +0 -1
- package/dist/server/db/migrations/0003_direct_r2_uploads.sql +0 -10
- package/dist/server/db/migrations/0004_agent_api_keys.sql +0 -38
- package/dist/server/db/migrations/0005_api_retention_and_pagination.sql +0 -3
- package/dist/server/db/migrations/0006_durable_media_deletion.sql +0 -7
- package/dist/server/db/migrations/0007_content_and_job_indexes.sql +0 -2
- package/dist/server/db/migrations/0008_search_text_cache.sql +0 -45
- package/dist/server/db/migrations/meta/0001_snapshot.json +0 -1197
- package/dist/server/db/migrations/meta/0002_snapshot.json +0 -1204
- package/dist/server/db/migrations/meta/0003_snapshot.json +0 -1281
- package/dist/server/db/migrations/meta/0004_snapshot.json +0 -1546
- package/dist/server/db/migrations/meta/0005_snapshot.json +0 -1572
- package/dist/server/db/migrations/meta/0006_snapshot.json +0 -1627
- package/dist/server/db/migrations/meta/0007_snapshot.json +0 -1643
- package/dist/server/db/migrations/meta/0008_snapshot.json +0 -1711
- package/dist/worker/index.d.ts +0 -10
- package/dist/worker/index.js +0 -460
- package/dist/worker/local.d.ts +0 -5
- package/dist/worker/local.js +0 -57
- package/dist/worker/source.d.ts +0 -2
- package/dist/worker/source.js +0 -31
- package/dist/worker/uploads.d.ts +0 -22
- package/dist/worker/uploads.js +0 -48
- package/templates/sandcms/worker/index.ts +0 -1
- package/templates/sandcms/worker/local.ts +0 -1
- package/templates/sandcms/worker/wrangler.jsonc +0 -6
- /package/dist/{worker → server/media}/svg.d.ts +0 -0
- /package/dist/{worker → server/media}/svg.js +0 -0
|
@@ -4,6 +4,7 @@ import { and, asc, count, desc, eq, inArray, sql } from 'drizzle-orm';
|
|
|
4
4
|
import { requireUser } from './auth.js';
|
|
5
5
|
import { documents, references, submissions, user } from './db/schema.js';
|
|
6
6
|
import { blueprintIcon } from './blueprint-icons.js';
|
|
7
|
+
import { parseTheme, themeCookie } from '../admin/theme.js';
|
|
7
8
|
const entryBlueprintIds = (cms) => cms.definition.blueprints.filter((b) => b.kind !== 'form').map((b) => b.id);
|
|
8
9
|
const formBlueprintIds = (cms) => cms.definition.blueprints.filter((b) => b.kind === 'form').map((b) => b.id);
|
|
9
10
|
// Matches String(draft.title ?? 'Untitled') without parsing every draft in JS.
|
|
@@ -37,6 +38,20 @@ export function relationLabels(cms) {
|
|
|
37
38
|
relations[row.blueprint].push({ id: row.id, label: titleLabel(row) });
|
|
38
39
|
return relations;
|
|
39
40
|
}
|
|
41
|
+
/** The newest document of every page blueprint, without creating missing singletons. */
|
|
42
|
+
export function pageEntries(cms) {
|
|
43
|
+
const ids = cms.definition.blueprints.filter((b) => b.kind === 'page').map((b) => b.id);
|
|
44
|
+
if (!ids.length)
|
|
45
|
+
return [];
|
|
46
|
+
const seen = new Set();
|
|
47
|
+
return cms.store.db
|
|
48
|
+
.select()
|
|
49
|
+
.from(documents)
|
|
50
|
+
.where(inArray(documents.blueprint, ids))
|
|
51
|
+
.orderBy(desc(documents.updatedAt), asc(documents.id))
|
|
52
|
+
.all()
|
|
53
|
+
.filter((entry) => !seen.has(entry.blueprint) && !!seen.add(entry.blueprint));
|
|
54
|
+
}
|
|
40
55
|
/** Content references grouped by media id; every requested asset id gets an array. */
|
|
41
56
|
export function mediaUsages(cms, assetIds) {
|
|
42
57
|
const usages = Object.fromEntries(assetIds.map((id) => [id, []]));
|
|
@@ -98,6 +113,11 @@ export function dashboardData(cms, mediaCount) {
|
|
|
98
113
|
};
|
|
99
114
|
}
|
|
100
115
|
export async function adminLoad(cms, event) {
|
|
116
|
+
// Rendered on the admin root during SSR so the chosen theme paints without a flash.
|
|
117
|
+
const theme = parseTheme(event.cookies.get(themeCookie));
|
|
118
|
+
return { ...(await screenLoad(cms, event)), theme };
|
|
119
|
+
}
|
|
120
|
+
async function screenLoad(cms, event) {
|
|
101
121
|
const session = await cms.auth.api.getSession({ headers: event.request.headers }), path = event.params.path ?? '';
|
|
102
122
|
// Preserve notification links through sign-in, accepting only local form paths.
|
|
103
123
|
const requestedNext = event.url.searchParams.get('next') ?? '';
|
|
@@ -124,12 +144,12 @@ export async function adminLoad(cms, event) {
|
|
|
124
144
|
screen: screen || 'dashboard',
|
|
125
145
|
user: session.user,
|
|
126
146
|
site: cms.definition.config.name,
|
|
147
|
+
logo: cms.definition.config.logo,
|
|
127
148
|
blueprints: cms.definition.blueprints.map((blueprint) => ({
|
|
128
149
|
...blueprint,
|
|
129
150
|
navigationIcon: blueprintIcon(blueprint)
|
|
130
151
|
})),
|
|
131
152
|
emailEnabled: cms.email.enabled,
|
|
132
|
-
workerUrl: cms.media.workerUrl,
|
|
133
153
|
mediaVersion: cms.media.version,
|
|
134
154
|
fileBlueprints: fileBlueprints(cms.definition),
|
|
135
155
|
defaultFileBlueprint: getFileBlueprint(cms.definition).id
|
|
@@ -159,6 +179,11 @@ export async function adminLoad(cms, event) {
|
|
|
159
179
|
relations
|
|
160
180
|
};
|
|
161
181
|
}
|
|
182
|
+
if (screen === 'pages') {
|
|
183
|
+
if (key)
|
|
184
|
+
error(404, 'Page not found');
|
|
185
|
+
return { ...base, entries: pageEntries(cms) };
|
|
186
|
+
}
|
|
162
187
|
if (screen === 'media')
|
|
163
188
|
return {
|
|
164
189
|
...base,
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { CMS } from './cms.js';
|
|
2
|
+
/** Chunk endpoint of a chunked upload (`media/upload/{id}`), relative to `/api/cms/`. */
|
|
3
|
+
export declare const uploadChunkRoute: (path: string) => boolean;
|
|
2
4
|
export declare function apiKeyRoute(path: string, method: string): boolean;
|
|
3
5
|
export declare function apiPrincipal(cms: CMS, request: Request, path: string): Promise<{
|
|
4
6
|
user: {
|
|
@@ -29,3 +31,5 @@ export declare function apiPrincipal(cms: CMS, request: Request, path: string):
|
|
|
29
31
|
};
|
|
30
32
|
keyId: null;
|
|
31
33
|
}>;
|
|
34
|
+
/** User ID of the caller: the API key owner, or the signed-in admin/editor (with the origin check for writes). */
|
|
35
|
+
export declare function principalUserId(cms: CMS, request: Request, path: string): Promise<string>;
|
|
@@ -14,8 +14,13 @@ const writes = new Set([
|
|
|
14
14
|
'media/retry',
|
|
15
15
|
'media/delete'
|
|
16
16
|
]);
|
|
17
|
+
const chunkRoute = /^media\/upload\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
18
|
+
/** Chunk endpoint of a chunked upload (`media/upload/{id}`), relative to `/api/cms/`. */
|
|
19
|
+
export const uploadChunkRoute = (path) => chunkRoute.test(path);
|
|
17
20
|
export function apiKeyRoute(path, method) {
|
|
18
|
-
return (method === 'GET' && reads.has(path)) ||
|
|
21
|
+
return ((method === 'GET' && reads.has(path)) ||
|
|
22
|
+
(method === 'POST' && writes.has(path)) ||
|
|
23
|
+
((method === 'PUT' || method === 'GET') && uploadChunkRoute(path)));
|
|
19
24
|
}
|
|
20
25
|
export async function apiPrincipal(cms, request, path) {
|
|
21
26
|
// An explicitly supplied credential never falls back to a browser cookie.
|
|
@@ -30,7 +35,8 @@ export async function apiPrincipal(cms, request, path) {
|
|
|
30
35
|
}
|
|
31
36
|
if (!apiKeyRoute(path, request.method))
|
|
32
37
|
error(403, 'API keys can only access content and media');
|
|
33
|
-
|
|
38
|
+
// Chunk status (GET) belongs to an upload, so it needs the same write permission as PUT.
|
|
39
|
+
const action = request.method === 'GET' && !uploadChunkRoute(path) ? 'read' : 'write';
|
|
34
40
|
if (!result.key.permissions?.cms?.includes(action))
|
|
35
41
|
error(403, 'API key permission denied');
|
|
36
42
|
const owner = cms.store.db.select().from(user).where(eq(user.id, result.key.referenceId)).get();
|
|
@@ -50,3 +56,10 @@ export async function apiPrincipal(cms, request, path) {
|
|
|
50
56
|
error(403, 'Change your temporary password first');
|
|
51
57
|
return { user: session.user, keyId: null };
|
|
52
58
|
}
|
|
59
|
+
/** User ID of the caller: the API key owner, or the signed-in admin/editor (with the origin check for writes). */
|
|
60
|
+
export async function principalUserId(cms, request, path) {
|
|
61
|
+
const { user } = await apiPrincipal(cms, request, path);
|
|
62
|
+
if (!['admin', 'editor'].includes(user.role ?? ''))
|
|
63
|
+
error(403, 'You cannot access the CMS');
|
|
64
|
+
return user.id;
|
|
65
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { Auth } from './auth.js';
|
|
2
|
+
import type { Store } from './db/store.js';
|
|
3
|
+
export type KeyScope = 'read' | 'write';
|
|
4
|
+
/** An invalid key request; HTTP callers map it to 400. */
|
|
5
|
+
export declare class KeyRequestError extends Error {
|
|
6
|
+
}
|
|
7
|
+
/** Validates a key request; the lifetime defaults to 7 days for write keys and 30 for read keys. */
|
|
8
|
+
export declare function keyRequest(input: {
|
|
9
|
+
name?: unknown;
|
|
10
|
+
scope?: unknown;
|
|
11
|
+
expiresIn?: unknown;
|
|
12
|
+
}): {
|
|
13
|
+
name: string;
|
|
14
|
+
scope: KeyScope;
|
|
15
|
+
expiresIn: number;
|
|
16
|
+
};
|
|
17
|
+
export declare function issueApiKey(auth: Auth, userId: string, request: {
|
|
18
|
+
name: string;
|
|
19
|
+
scope: KeyScope;
|
|
20
|
+
expiresIn: number;
|
|
21
|
+
}): Promise<{
|
|
22
|
+
key: string;
|
|
23
|
+
metadata: any;
|
|
24
|
+
permissions: any;
|
|
25
|
+
id: string;
|
|
26
|
+
configId: string;
|
|
27
|
+
name: string | null;
|
|
28
|
+
start: string | null;
|
|
29
|
+
prefix: string | null;
|
|
30
|
+
referenceId: string;
|
|
31
|
+
refillInterval: number | null;
|
|
32
|
+
refillAmount: number | null;
|
|
33
|
+
lastRefillAt: Date | null;
|
|
34
|
+
enabled: boolean;
|
|
35
|
+
rateLimitEnabled: boolean;
|
|
36
|
+
rateLimitTimeWindow: number | null;
|
|
37
|
+
rateLimitMax: number | null;
|
|
38
|
+
requestCount: number;
|
|
39
|
+
remaining: number | null;
|
|
40
|
+
lastRequest: Date | null;
|
|
41
|
+
expiresAt: Date | null;
|
|
42
|
+
createdAt: Date;
|
|
43
|
+
updatedAt: Date;
|
|
44
|
+
}>;
|
|
45
|
+
/** Sanitized keys of every account, newest first. Secrets are never stored in plain text. */
|
|
46
|
+
export declare function listApiKeys(store: Store): {
|
|
47
|
+
permissions: {
|
|
48
|
+
cms?: string[];
|
|
49
|
+
} | null;
|
|
50
|
+
id: string;
|
|
51
|
+
name: string | null;
|
|
52
|
+
start: string | null;
|
|
53
|
+
prefix: string | null;
|
|
54
|
+
expiresAt: Date | null;
|
|
55
|
+
lastRequest: Date | null;
|
|
56
|
+
enabled: boolean | null;
|
|
57
|
+
referenceId: string;
|
|
58
|
+
owner: string;
|
|
59
|
+
}[];
|
|
60
|
+
/** Deletes a key and audits the revocation. Returns false when no such key exists. */
|
|
61
|
+
export declare function revokeApiKey(store: Store, id: string, actor: string): boolean;
|
|
62
|
+
/**
|
|
63
|
+
* Operator path for `sandcms key create`: issues a key for an existing admin or editor without a
|
|
64
|
+
* browser session. Anyone who can run the CLI against the database can already reset passwords.
|
|
65
|
+
*/
|
|
66
|
+
export declare function createOperatorKey(auth: Auth, store: Store, input: {
|
|
67
|
+
email: string;
|
|
68
|
+
name: unknown;
|
|
69
|
+
scope: unknown;
|
|
70
|
+
days?: unknown;
|
|
71
|
+
}): Promise<{
|
|
72
|
+
scope: KeyScope;
|
|
73
|
+
owner: string;
|
|
74
|
+
key: string;
|
|
75
|
+
metadata: any;
|
|
76
|
+
permissions: any;
|
|
77
|
+
id: string;
|
|
78
|
+
configId: string;
|
|
79
|
+
name: string | null;
|
|
80
|
+
start: string | null;
|
|
81
|
+
prefix: string | null;
|
|
82
|
+
referenceId: string;
|
|
83
|
+
refillInterval: number | null;
|
|
84
|
+
refillAmount: number | null;
|
|
85
|
+
lastRefillAt: Date | null;
|
|
86
|
+
enabled: boolean;
|
|
87
|
+
rateLimitEnabled: boolean;
|
|
88
|
+
rateLimitTimeWindow: number | null;
|
|
89
|
+
rateLimitMax: number | null;
|
|
90
|
+
requestCount: number;
|
|
91
|
+
remaining: number | null;
|
|
92
|
+
lastRequest: Date | null;
|
|
93
|
+
expiresAt: Date | null;
|
|
94
|
+
createdAt: Date;
|
|
95
|
+
updatedAt: Date;
|
|
96
|
+
}>;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { desc, eq } from 'drizzle-orm';
|
|
2
|
+
import { apikey, audit, user } from './db/schema.js';
|
|
3
|
+
/** An invalid key request; HTTP callers map it to 400. */
|
|
4
|
+
export class KeyRequestError extends Error {
|
|
5
|
+
}
|
|
6
|
+
const day = 60 * 60 * 24;
|
|
7
|
+
/** Validates a key request; the lifetime defaults to 7 days for write keys and 30 for read keys. */
|
|
8
|
+
export function keyRequest(input) {
|
|
9
|
+
const { name, scope } = input;
|
|
10
|
+
if (scope !== 'read' && scope !== 'write')
|
|
11
|
+
throw new KeyRequestError('Scope must be read or write');
|
|
12
|
+
if (typeof name !== 'string' || !name.trim() || name.length > 100)
|
|
13
|
+
throw new KeyRequestError('Use a key name with 1–100 characters');
|
|
14
|
+
const expiresIn = input.expiresIn ?? day * (scope === 'write' ? 7 : 30);
|
|
15
|
+
if (typeof expiresIn !== 'number' ||
|
|
16
|
+
!Number.isInteger(expiresIn) ||
|
|
17
|
+
expiresIn < day ||
|
|
18
|
+
expiresIn > day * 365)
|
|
19
|
+
throw new KeyRequestError('expiresIn must be between 1 and 365 days, in seconds');
|
|
20
|
+
return { name: name.trim(), scope: scope, expiresIn };
|
|
21
|
+
}
|
|
22
|
+
export function issueApiKey(auth, userId, request) {
|
|
23
|
+
return auth.api.createApiKey({
|
|
24
|
+
body: {
|
|
25
|
+
userId,
|
|
26
|
+
name: request.name,
|
|
27
|
+
expiresIn: request.expiresIn,
|
|
28
|
+
permissions: { cms: request.scope === 'write' ? ['read', 'write'] : ['read'] }
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
/** Sanitized keys of every account, newest first. Secrets are never stored in plain text. */
|
|
33
|
+
export function listApiKeys(store) {
|
|
34
|
+
return store.db
|
|
35
|
+
.select({
|
|
36
|
+
id: apikey.id,
|
|
37
|
+
name: apikey.name,
|
|
38
|
+
start: apikey.start,
|
|
39
|
+
prefix: apikey.prefix,
|
|
40
|
+
expiresAt: apikey.expiresAt,
|
|
41
|
+
lastRequest: apikey.lastRequest,
|
|
42
|
+
enabled: apikey.enabled,
|
|
43
|
+
referenceId: apikey.referenceId,
|
|
44
|
+
owner: user.email,
|
|
45
|
+
permissions: apikey.permissions
|
|
46
|
+
})
|
|
47
|
+
.from(apikey)
|
|
48
|
+
.innerJoin(user, eq(user.id, apikey.referenceId))
|
|
49
|
+
.orderBy(desc(apikey.createdAt), desc(apikey.id))
|
|
50
|
+
.all()
|
|
51
|
+
.map((key) => ({
|
|
52
|
+
...key,
|
|
53
|
+
permissions: (key.permissions ? JSON.parse(key.permissions) : null)
|
|
54
|
+
}));
|
|
55
|
+
}
|
|
56
|
+
/** Deletes a key and audits the revocation. Returns false when no such key exists. */
|
|
57
|
+
export function revokeApiKey(store, id, actor) {
|
|
58
|
+
return store.db.transaction((tx) => {
|
|
59
|
+
const revoked = tx
|
|
60
|
+
.delete(apikey)
|
|
61
|
+
.where(eq(apikey.id, id))
|
|
62
|
+
.returning({ referenceId: apikey.referenceId })
|
|
63
|
+
.get();
|
|
64
|
+
if (!revoked)
|
|
65
|
+
return false;
|
|
66
|
+
tx.insert(audit)
|
|
67
|
+
.values({
|
|
68
|
+
id: crypto.randomUUID(),
|
|
69
|
+
actor,
|
|
70
|
+
action: 'apikey.revoke',
|
|
71
|
+
detail: { keyId: id, ownerId: revoked.referenceId },
|
|
72
|
+
createdAt: Date.now()
|
|
73
|
+
})
|
|
74
|
+
.run();
|
|
75
|
+
return true;
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Operator path for `sandcms key create`: issues a key for an existing admin or editor without a
|
|
80
|
+
* browser session. Anyone who can run the CLI against the database can already reset passwords.
|
|
81
|
+
*/
|
|
82
|
+
export async function createOperatorKey(auth, store, input) {
|
|
83
|
+
const days = input.days === undefined ? undefined : Number(input.days);
|
|
84
|
+
if (days !== undefined && !Number.isInteger(days))
|
|
85
|
+
throw new KeyRequestError('--days must be a whole number from 1 to 365');
|
|
86
|
+
const request = keyRequest({
|
|
87
|
+
name: input.name,
|
|
88
|
+
scope: input.scope,
|
|
89
|
+
expiresIn: days === undefined ? undefined : days * day
|
|
90
|
+
});
|
|
91
|
+
const owner = store.db
|
|
92
|
+
.select()
|
|
93
|
+
.from(user)
|
|
94
|
+
.where(eq(user.email, input.email.trim().toLowerCase()))
|
|
95
|
+
.get();
|
|
96
|
+
if (!owner)
|
|
97
|
+
throw new Error('User not found');
|
|
98
|
+
if (!['admin', 'editor'].includes(owner.role ?? ''))
|
|
99
|
+
throw new Error('Key owners must be admins or editors');
|
|
100
|
+
// The API rejects keys whose owner still has a temporary password; fail before issuing one.
|
|
101
|
+
if (owner.mustChangePassword)
|
|
102
|
+
throw new Error('This account still has a temporary password. Sign in and change it before creating a key.');
|
|
103
|
+
const created = await issueApiKey(auth, owner.id, request);
|
|
104
|
+
store.db
|
|
105
|
+
.insert(audit)
|
|
106
|
+
.values({
|
|
107
|
+
id: crypto.randomUUID(),
|
|
108
|
+
actor: 'operator',
|
|
109
|
+
action: 'apikey.create',
|
|
110
|
+
detail: { keyId: created.id, ownerId: owner.id, scope: request.scope },
|
|
111
|
+
createdAt: Date.now()
|
|
112
|
+
})
|
|
113
|
+
.run();
|
|
114
|
+
return { ...created, scope: request.scope, owner: owner.email };
|
|
115
|
+
}
|
|
@@ -31,6 +31,9 @@ export declare function mediaPage(cms: CMS, params: URLSearchParams): {
|
|
|
31
31
|
error: string | null;
|
|
32
32
|
createdAt: number;
|
|
33
33
|
searchText: string | null;
|
|
34
|
+
width: number | null;
|
|
35
|
+
height: number | null;
|
|
36
|
+
uploadAttempt: string | null;
|
|
34
37
|
}[];
|
|
35
38
|
nextCursor: string | null;
|
|
36
39
|
};
|
package/dist/server/api.js
CHANGED
|
@@ -4,11 +4,13 @@ import { rateLimit } from './forms.js';
|
|
|
4
4
|
import { createUser, deleteUser } from './auth.js';
|
|
5
5
|
import { boundedJson, clientAddress } from './request.js';
|
|
6
6
|
import { apiPrincipal } from './api-access.js';
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
7
|
+
import { issueApiKey, keyRequest, KeyRequestError, listApiKeys, revokeApiKey } from './api-keys.js';
|
|
8
|
+
import { apiRequests, audit } from './db/schema.js';
|
|
9
|
+
import { eq, lt } from 'drizzle-orm';
|
|
9
10
|
import { contentPage, mediaPage } from './api-pagination.js';
|
|
10
11
|
import { globalSearch } from './search.js';
|
|
11
12
|
import { ValidationError } from '../blueprints/validate.js';
|
|
13
|
+
import { MediaRequestError } from './media/contracts.js';
|
|
12
14
|
const replayRetention = 48 * 60 * 60 * 1000;
|
|
13
15
|
const lastPruned = new WeakMap();
|
|
14
16
|
function orderedJson(value) {
|
|
@@ -82,29 +84,7 @@ export async function apiHandler(cms, event) {
|
|
|
82
84
|
case 'keys/list':
|
|
83
85
|
if (session.user.role !== 'admin')
|
|
84
86
|
error(403, 'Only admins can manage API keys');
|
|
85
|
-
return json({
|
|
86
|
-
apiKeys: cms.store.db
|
|
87
|
-
.select({
|
|
88
|
-
id: apikey.id,
|
|
89
|
-
name: apikey.name,
|
|
90
|
-
start: apikey.start,
|
|
91
|
-
prefix: apikey.prefix,
|
|
92
|
-
expiresAt: apikey.expiresAt,
|
|
93
|
-
lastRequest: apikey.lastRequest,
|
|
94
|
-
enabled: apikey.enabled,
|
|
95
|
-
referenceId: apikey.referenceId,
|
|
96
|
-
owner: user.email,
|
|
97
|
-
permissions: apikey.permissions
|
|
98
|
-
})
|
|
99
|
-
.from(apikey)
|
|
100
|
-
.innerJoin(user, eq(user.id, apikey.referenceId))
|
|
101
|
-
.orderBy(desc(apikey.createdAt), desc(apikey.id))
|
|
102
|
-
.all()
|
|
103
|
-
.map((key) => ({
|
|
104
|
-
...key,
|
|
105
|
-
permissions: key.permissions ? JSON.parse(key.permissions) : null
|
|
106
|
-
}))
|
|
107
|
-
});
|
|
87
|
+
return json({ apiKeys: listApiKeys(cms.store) });
|
|
108
88
|
}
|
|
109
89
|
}
|
|
110
90
|
if (event.request.method === 'GET' && path.startsWith('forms/') && path.endsWith('/export')) {
|
|
@@ -220,46 +200,22 @@ export async function apiHandler(cms, event) {
|
|
|
220
200
|
case 'keys/create': {
|
|
221
201
|
if (session.user.role !== 'admin')
|
|
222
202
|
error(403, 'Only admins can manage API keys');
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
return json(await cms.auth.api.createApiKey({
|
|
234
|
-
body: {
|
|
235
|
-
userId: session.user.id,
|
|
236
|
-
name: body.name.trim(),
|
|
237
|
-
expiresIn,
|
|
238
|
-
permissions: { cms: body.scope === 'write' ? ['read', 'write'] : ['read'] }
|
|
239
|
-
}
|
|
240
|
-
}));
|
|
203
|
+
let request;
|
|
204
|
+
try {
|
|
205
|
+
request = keyRequest(body);
|
|
206
|
+
}
|
|
207
|
+
catch (e) {
|
|
208
|
+
if (e instanceof KeyRequestError)
|
|
209
|
+
error(400, e.message);
|
|
210
|
+
throw e;
|
|
211
|
+
}
|
|
212
|
+
return json(await issueApiKey(cms.auth, session.user.id, request));
|
|
241
213
|
}
|
|
242
214
|
case 'keys/delete': {
|
|
243
215
|
if (session.user.role !== 'admin')
|
|
244
216
|
error(403, 'Only admins can manage API keys');
|
|
245
|
-
cms.store.
|
|
246
|
-
|
|
247
|
-
.delete(apikey)
|
|
248
|
-
.where(eq(apikey.id, id))
|
|
249
|
-
.returning({ referenceId: apikey.referenceId })
|
|
250
|
-
.get();
|
|
251
|
-
if (!revoked)
|
|
252
|
-
error(404, 'API key not found');
|
|
253
|
-
tx.insert(audit)
|
|
254
|
-
.values({
|
|
255
|
-
id: crypto.randomUUID(),
|
|
256
|
-
actor: session.user.id,
|
|
257
|
-
action: 'apikey.revoke',
|
|
258
|
-
detail: { keyId: id, ownerId: revoked.referenceId },
|
|
259
|
-
createdAt: Date.now()
|
|
260
|
-
})
|
|
261
|
-
.run();
|
|
262
|
-
});
|
|
217
|
+
if (!revokeApiKey(cms.store, id, session.user.id))
|
|
218
|
+
error(404, 'API key not found');
|
|
263
219
|
return json({ success: true });
|
|
264
220
|
}
|
|
265
221
|
case 'media/upload':
|
|
@@ -269,9 +225,9 @@ export async function apiHandler(cms, event) {
|
|
|
269
225
|
name: body.name,
|
|
270
226
|
type: body.type,
|
|
271
227
|
size: body.size
|
|
272
|
-
}, blueprint || undefined));
|
|
228
|
+
}, blueprint || undefined, { userId: session.user.id }));
|
|
273
229
|
case 'media/upload/complete':
|
|
274
|
-
return json(cms.media.completeUpload(id));
|
|
230
|
+
return json(await cms.media.completeUpload(id));
|
|
275
231
|
case 'media/update':
|
|
276
232
|
cms.media.updateMetadata(id, body.metadata);
|
|
277
233
|
break;
|
|
@@ -331,6 +287,8 @@ export async function apiHandler(cms, event) {
|
|
|
331
287
|
return json({ ok: true });
|
|
332
288
|
}
|
|
333
289
|
catch (e) {
|
|
290
|
+
if (e instanceof MediaRequestError)
|
|
291
|
+
return json({ error: e.message }, { status: e.status });
|
|
334
292
|
if (e && typeof e === 'object' && 'status' in e)
|
|
335
293
|
throw e;
|
|
336
294
|
return json({
|
package/dist/server/auth.d.ts
CHANGED
|
@@ -56,21 +56,22 @@ export declare function createAuth(store: Store, options: AuthOptions): import("
|
|
|
56
56
|
plugins: [{
|
|
57
57
|
id: "two-factor";
|
|
58
58
|
version: string;
|
|
59
|
+
shouldRequireTwoFactor: (ctx: import("better-auth").GenericEndpointContext) => Promise<boolean>;
|
|
59
60
|
endpoints: {
|
|
60
61
|
enableTwoFactor: import("better-auth").StrictEndpoint<"/two-factor/enable", {
|
|
61
62
|
method: "POST";
|
|
62
63
|
body: import("better-auth").ZodObject<{
|
|
63
64
|
password: import("better-auth").ZodOptional<import("better-auth").ZodString>;
|
|
64
65
|
method: import("better-auth").ZodDefault<import("better-auth").ZodEnum<{
|
|
65
|
-
otp: "otp";
|
|
66
66
|
totp: "totp";
|
|
67
|
+
otp: "otp";
|
|
67
68
|
}>>;
|
|
68
69
|
issuer: import("better-auth").ZodOptional<import("better-auth").ZodString>;
|
|
69
70
|
}, import("zod/v4/core").$strip> | import("better-auth").ZodObject<{
|
|
70
71
|
password: import("better-auth").ZodString;
|
|
71
72
|
method: import("better-auth").ZodDefault<import("better-auth").ZodEnum<{
|
|
72
|
-
otp: "otp";
|
|
73
73
|
totp: "totp";
|
|
74
|
+
otp: "otp";
|
|
74
75
|
}>>;
|
|
75
76
|
issuer: import("better-auth").ZodOptional<import("better-auth").ZodString>;
|
|
76
77
|
}, import("zod/v4/core").$strip>;
|
|
@@ -298,7 +299,7 @@ export declare function createAuth(store: Store, options: AuthOptions): import("
|
|
|
298
299
|
};
|
|
299
300
|
}, {
|
|
300
301
|
token: string | undefined;
|
|
301
|
-
user: (
|
|
302
|
+
user: ({
|
|
302
303
|
id: string;
|
|
303
304
|
createdAt: Date;
|
|
304
305
|
updatedAt: Date;
|
|
@@ -306,7 +307,7 @@ export declare function createAuth(store: Store, options: AuthOptions): import("
|
|
|
306
307
|
emailVerified: boolean;
|
|
307
308
|
name: string;
|
|
308
309
|
image?: string | null | undefined;
|
|
309
|
-
}) | import("better-auth/plugins").UserWithTwoFactor;
|
|
310
|
+
} & Record<string, any>) | import("better-auth/plugins").UserWithTwoFactor;
|
|
310
311
|
}>;
|
|
311
312
|
generateBackupCodes: import("better-auth").StrictEndpoint<"/two-factor/generate-backup-codes", {
|
|
312
313
|
method: "POST";
|
|
@@ -493,7 +494,7 @@ export declare function createAuth(store: Store, options: AuthOptions): import("
|
|
|
493
494
|
user: import("better-auth/plugins").UserWithTwoFactor;
|
|
494
495
|
} | {
|
|
495
496
|
token: string;
|
|
496
|
-
user:
|
|
497
|
+
user: {
|
|
497
498
|
id: string;
|
|
498
499
|
createdAt: Date;
|
|
499
500
|
updatedAt: Date;
|
|
@@ -501,7 +502,7 @@ export declare function createAuth(store: Store, options: AuthOptions): import("
|
|
|
501
502
|
emailVerified: boolean;
|
|
502
503
|
name: string;
|
|
503
504
|
image?: string | null | undefined;
|
|
504
|
-
}
|
|
505
|
+
} & Record<string, any>;
|
|
505
506
|
}>;
|
|
506
507
|
generateTOTP: import("better-auth").StrictEndpoint<string, {
|
|
507
508
|
method: "POST";
|
|
@@ -624,7 +625,7 @@ export declare function createAuth(store: Store, options: AuthOptions): import("
|
|
|
624
625
|
user: import("better-auth/plugins").UserWithTwoFactor;
|
|
625
626
|
} | {
|
|
626
627
|
token: string;
|
|
627
|
-
user:
|
|
628
|
+
user: {
|
|
628
629
|
id: string;
|
|
629
630
|
createdAt: Date;
|
|
630
631
|
updatedAt: Date;
|
|
@@ -632,7 +633,7 @@ export declare function createAuth(store: Store, options: AuthOptions): import("
|
|
|
632
633
|
emailVerified: boolean;
|
|
633
634
|
name: string;
|
|
634
635
|
image?: string | null | undefined;
|
|
635
|
-
}
|
|
636
|
+
} & Record<string, any>;
|
|
636
637
|
}>;
|
|
637
638
|
};
|
|
638
639
|
options: NoInfer<{
|
|
@@ -859,7 +860,7 @@ export declare function createAuth(store: Store, options: AuthOptions): import("
|
|
|
859
860
|
} | null) => void;
|
|
860
861
|
socialProviders: import("better-auth").OAuthProvider[];
|
|
861
862
|
authCookies: import("better-auth").BetterAuthCookies;
|
|
862
|
-
logger: ReturnType<
|
|
863
|
+
logger: ReturnType<typeof import("better-auth").createLogger>;
|
|
863
864
|
rateLimit: {
|
|
864
865
|
enabled: boolean;
|
|
865
866
|
window: number;
|