@glw907/cairn-cms 0.14.0 → 0.17.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/dist/auth/crypto.d.ts +8 -2
- package/dist/auth/crypto.d.ts.map +1 -1
- package/dist/auth/crypto.js +12 -2
- package/dist/auth/store.d.ts +2 -0
- package/dist/auth/store.d.ts.map +1 -1
- package/dist/auth/store.js +17 -5
- package/dist/components/EditPage.svelte +4 -6
- package/dist/components/EditPage.svelte.d.ts +1 -1
- package/dist/components/EditPage.svelte.d.ts.map +1 -1
- package/dist/delivery/content-index.d.ts.map +1 -1
- package/dist/delivery/content-index.js +11 -9
- package/dist/delivery/feeds.d.ts +1 -1
- package/dist/delivery/feeds.d.ts.map +1 -1
- package/dist/delivery/feeds.js +31 -16
- package/dist/delivery/site-indexes.d.ts.map +1 -1
- package/dist/delivery/site-indexes.js +9 -1
- package/dist/env.d.ts.map +1 -1
- package/dist/env.js +14 -0
- package/dist/github/signing.d.ts +12 -0
- package/dist/github/signing.d.ts.map +1 -1
- package/dist/github/signing.js +22 -0
- package/dist/render/pipeline.d.ts +10 -0
- package/dist/render/pipeline.d.ts.map +1 -1
- package/dist/render/pipeline.js +15 -1
- package/dist/render/sanitize-schema.d.ts +20 -0
- package/dist/render/sanitize-schema.d.ts.map +1 -0
- package/dist/render/sanitize-schema.js +48 -0
- package/dist/sveltekit/auth-routes.d.ts.map +1 -1
- package/dist/sveltekit/auth-routes.js +29 -11
- package/dist/sveltekit/content-routes.js +2 -2
- package/dist/sveltekit/guard.d.ts +1 -1
- package/dist/sveltekit/guard.d.ts.map +1 -1
- package/dist/sveltekit/guard.js +25 -10
- package/dist/sveltekit/nav-routes.js +2 -2
- package/dist/sveltekit/public-routes.js +1 -1
- package/dist/sveltekit/types.d.ts +6 -0
- package/dist/sveltekit/types.d.ts.map +1 -1
- package/package.json +3 -2
- package/src/lib/auth/crypto.ts +14 -2
- package/src/lib/auth/store.ts +18 -5
- package/src/lib/components/EditPage.svelte +4 -6
- package/src/lib/delivery/content-index.ts +12 -9
- package/src/lib/delivery/feeds.ts +34 -19
- package/src/lib/delivery/site-indexes.ts +13 -1
- package/src/lib/env.ts +13 -0
- package/src/lib/github/signing.ts +32 -0
- package/src/lib/render/pipeline.ts +25 -1
- package/src/lib/render/sanitize-schema.ts +57 -0
- package/src/lib/sveltekit/auth-routes.ts +30 -11
- package/src/lib/sveltekit/content-routes.ts +2 -2
- package/src/lib/sveltekit/guard.ts +25 -10
- package/src/lib/sveltekit/nav-routes.ts +2 -2
- package/src/lib/sveltekit/public-routes.ts +1 -1
- package/src/lib/sveltekit/types.ts +5 -1
- package/dist/render/sanitize.d.ts +0 -8
- package/dist/render/sanitize.d.ts.map +0 -1
- package/dist/render/sanitize.js +0 -26
- package/src/lib/render/sanitize.ts +0 -27
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
// against a sink. The confirm-load, confirm, and logout handlers arrive in Task 6.
|
|
4
4
|
import { redirect } from '@sveltejs/kit';
|
|
5
5
|
import { requireOrigin, requireDb } from '../env.js';
|
|
6
|
-
import { generateToken, generateSessionId, hashToken, TOKEN_TTL_MS, SESSION_TTL_MS,
|
|
7
|
-
import { findEditor, issueToken, consumeToken, createSession, deleteSession } from '../auth/store.js';
|
|
6
|
+
import { generateToken, generateSessionId, hashToken, TOKEN_TTL_MS, SESSION_TTL_MS, SEND_COOLDOWN_MS, sessionCookieName, } from '../auth/crypto.js';
|
|
7
|
+
import { findEditor, issueToken, consumeToken, createSession, deleteSession, recentlyIssued } from '../auth/store.js';
|
|
8
8
|
import { buildMagicLinkMessage, cloudflareSend } from '../email.js';
|
|
9
9
|
export function createAuthRoutes(config) {
|
|
10
10
|
const send = config.send ?? cloudflareSend;
|
|
@@ -21,11 +21,27 @@ export function createAuthRoutes(config) {
|
|
|
21
21
|
const email = String(form.get('email') ?? '').trim().toLowerCase();
|
|
22
22
|
const editor = email ? await findEditor(db, email) : null;
|
|
23
23
|
if (editor) {
|
|
24
|
-
const token = generateToken();
|
|
25
24
|
const now = Date.now();
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
25
|
+
// Per-email cooldown: skip the reissue and send when a token for this email was issued within
|
|
26
|
+
// the window, so the endpoint cannot flood an editor's inbox. The response is unchanged, so
|
|
27
|
+
// the non-leak property holds.
|
|
28
|
+
if (!(await recentlyIssued(db, email, now - SEND_COOLDOWN_MS))) {
|
|
29
|
+
const token = generateToken();
|
|
30
|
+
await issueToken(db, email, await hashToken(token), now + TOKEN_TTL_MS, now);
|
|
31
|
+
const link = `${origin}/admin/auth/confirm?token=${encodeURIComponent(token)}`;
|
|
32
|
+
// The token row is the security-critical write the email depends on, so it is awaited. The
|
|
33
|
+
// send is a post-response side effect, handed to waitUntil so a slow email provider does not
|
|
34
|
+
// hold the response. An absent waitUntil (local dev, tests) falls back to await. A send
|
|
35
|
+
// failure is logged so observability survives a backgrounded send.
|
|
36
|
+
const sending = send(env, buildMagicLinkMessage({ to: email, branding: config.branding, link })).catch((err) => console.error('cairn: magic-link send failed', err));
|
|
37
|
+
// adapter-cloudflare exposes the ExecutionContext as platform.ctx; platform.context is a
|
|
38
|
+
// deprecated alias kept as a fallback so an adapter that drops it keeps backgrounding.
|
|
39
|
+
const ctx = event.platform?.ctx ?? event.platform?.context;
|
|
40
|
+
if (ctx?.waitUntil)
|
|
41
|
+
ctx.waitUntil(sending);
|
|
42
|
+
else
|
|
43
|
+
await sending;
|
|
44
|
+
}
|
|
29
45
|
}
|
|
30
46
|
return { sent: true };
|
|
31
47
|
}
|
|
@@ -62,11 +78,12 @@ export function createAuthRoutes(config) {
|
|
|
62
78
|
throw redirect(303, '/admin/login?error=expired');
|
|
63
79
|
const id = generateSessionId();
|
|
64
80
|
await createSession(db, id, email, now + SESSION_TTL_MS, now);
|
|
65
|
-
event.
|
|
81
|
+
const secure = event.url.protocol === 'https:';
|
|
82
|
+
event.cookies.set(sessionCookieName(secure), id, {
|
|
66
83
|
path: '/',
|
|
67
84
|
httpOnly: true,
|
|
68
|
-
//
|
|
69
|
-
secure
|
|
85
|
+
// __Host- needs Secure unconditionally on https; local http dev drops the prefix and Secure.
|
|
86
|
+
secure,
|
|
70
87
|
sameSite: 'lax',
|
|
71
88
|
maxAge: Math.floor(SESSION_TTL_MS / 1000),
|
|
72
89
|
});
|
|
@@ -75,10 +92,11 @@ export function createAuthRoutes(config) {
|
|
|
75
92
|
/** POST /admin/auth/logout. Deletes the session row and clears the cookie. */
|
|
76
93
|
async function logoutAction(event) {
|
|
77
94
|
const db = requireDb(event.platform?.env ?? {});
|
|
78
|
-
const
|
|
95
|
+
const name = sessionCookieName(event.url.protocol === 'https:');
|
|
96
|
+
const id = event.cookies.get(name);
|
|
79
97
|
if (id)
|
|
80
98
|
await deleteSession(db, id);
|
|
81
|
-
event.cookies.delete(
|
|
99
|
+
event.cookies.delete(name, { path: '/' });
|
|
82
100
|
throw redirect(303, '/admin/login');
|
|
83
101
|
}
|
|
84
102
|
return { loginLoad, requestAction, confirmLoad, confirmAction, logoutAction };
|
|
@@ -8,7 +8,7 @@ import { frontmatterFromForm, parseMarkdown, dateInputValue, serializeMarkdown }
|
|
|
8
8
|
import { isValidId, slugify, filenameFromId, composeDatedId } from '../content/ids.js';
|
|
9
9
|
import { appCredentials } from '../github/credentials.js';
|
|
10
10
|
import { listMarkdown, readRaw, commitFile } from '../github/repo.js';
|
|
11
|
-
import {
|
|
11
|
+
import { cachedInstallationToken } from '../github/signing.js';
|
|
12
12
|
import { CommitConflictError } from '../github/types.js';
|
|
13
13
|
/** The signed-in editor the guard resolved, or a login redirect. Kept local to decouple event shapes. */
|
|
14
14
|
function sessionOf(event) {
|
|
@@ -25,7 +25,7 @@ function conceptOf(runtime, params) {
|
|
|
25
25
|
return concept;
|
|
26
26
|
}
|
|
27
27
|
export function createContentRoutes(runtime, deps = {}) {
|
|
28
|
-
const mintToken = deps.mintToken ?? ((env) =>
|
|
28
|
+
const mintToken = deps.mintToken ?? ((env) => cachedInstallationToken(appCredentials(runtime.backend, env)));
|
|
29
29
|
/** Layout load for every admin page: the nav, the user, and the active path. */
|
|
30
30
|
function layoutLoad(event) {
|
|
31
31
|
const editor = sessionOf(event);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Editor } from '../auth/types.js';
|
|
2
2
|
import type { HandleInput, RequestContext } from './types.js';
|
|
3
|
-
/** The SvelteKit `Handle` that guards `/admin
|
|
3
|
+
/** The SvelteKit `Handle` that guards `/admin/**` and hardens admin responses. */
|
|
4
4
|
export declare function createAuthGuard(): ({ event, resolve }: HandleInput) => Promise<Response>;
|
|
5
5
|
/** For a protected load/action: the session the guard already resolved, or a login redirect. */
|
|
6
6
|
export declare function requireSession(event: RequestContext): Editor;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"guard.d.ts","sourceRoot":"","sources":["../../src/lib/sveltekit/guard.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"guard.d.ts","sourceRoot":"","sources":["../../src/lib/sveltekit/guard.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAwB9D,kFAAkF;AAClF,wBAAgB,eAAe,KACA,oBAAoB,WAAW,KAAG,OAAO,CAAC,QAAQ,CAAC,CAcjF;AAED,gGAAgG;AAChG,wBAAgB,cAAc,CAAC,KAAK,EAAE,cAAc,GAAG,MAAM,CAI5D;AAED,2EAA2E;AAC3E,wBAAgB,YAAY,CAAC,KAAK,EAAE,cAAc,GAAG,MAAM,CAI1D"}
|
package/dist/sveltekit/guard.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// stays free of a site's App.* ambient types.
|
|
4
4
|
import { redirect, error } from '@sveltejs/kit';
|
|
5
5
|
import { resolveSession } from '../auth/store.js';
|
|
6
|
-
import {
|
|
6
|
+
import { sessionCookieName } from '../auth/crypto.js';
|
|
7
7
|
/** The login page and the auth endpoints are public; everything else under /admin is gated. */
|
|
8
8
|
function isPublicAdminPath(pathname) {
|
|
9
9
|
return pathname === '/admin/login' || pathname.startsWith('/admin/auth/');
|
|
@@ -11,20 +11,35 @@ function isPublicAdminPath(pathname) {
|
|
|
11
11
|
function isAdminPath(pathname) {
|
|
12
12
|
return pathname === '/admin' || pathname.startsWith('/admin/');
|
|
13
13
|
}
|
|
14
|
-
/**
|
|
14
|
+
/**
|
|
15
|
+
* Attach the baseline security headers to an admin response. No full CSP; see the auth-hardening
|
|
16
|
+
* design. frame-ancestors is the modern clickjacking control and the one CSP directive included.
|
|
17
|
+
*/
|
|
18
|
+
function applySecurityHeaders(headers) {
|
|
19
|
+
headers.set('X-Content-Type-Options', 'nosniff');
|
|
20
|
+
headers.set('X-Frame-Options', 'DENY');
|
|
21
|
+
headers.set('Content-Security-Policy', "frame-ancestors 'none'");
|
|
22
|
+
headers.set('Referrer-Policy', 'no-referrer');
|
|
23
|
+
headers.set('Strict-Transport-Security', 'max-age=63072000; includeSubDomains');
|
|
24
|
+
headers.set('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
|
|
25
|
+
}
|
|
26
|
+
/** The SvelteKit `Handle` that guards `/admin/**` and hardens admin responses. */
|
|
15
27
|
export function createAuthGuard() {
|
|
16
28
|
return async function handle({ event, resolve }) {
|
|
17
29
|
const { pathname } = event.url;
|
|
18
|
-
if (!isAdminPath(pathname)
|
|
30
|
+
if (!isAdminPath(pathname))
|
|
19
31
|
return resolve(event);
|
|
32
|
+
if (!isPublicAdminPath(pathname)) {
|
|
33
|
+
const env = event.platform?.env ?? {};
|
|
34
|
+
const id = event.cookies.get(sessionCookieName(event.url.protocol === 'https:'));
|
|
35
|
+
const editor = id && env.AUTH_DB ? await resolveSession(env.AUTH_DB, id, Date.now()) : null;
|
|
36
|
+
if (!editor)
|
|
37
|
+
throw redirect(303, '/admin/login');
|
|
38
|
+
event.locals.editor = editor;
|
|
20
39
|
}
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
if (!editor)
|
|
25
|
-
throw redirect(303, '/admin/login');
|
|
26
|
-
event.locals.editor = editor;
|
|
27
|
-
return resolve(event);
|
|
40
|
+
const response = await resolve(event);
|
|
41
|
+
applySecurityHeaders(response.headers);
|
|
42
|
+
return response;
|
|
28
43
|
};
|
|
29
44
|
}
|
|
30
45
|
/** For a protected load/action: the session the guard already resolved, or a login redirect. */
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// and commit paths are unit-testable against a fetch double with an injected token.
|
|
4
4
|
import { redirect, error } from '@sveltejs/kit';
|
|
5
5
|
import { appCredentials } from '../github/credentials.js';
|
|
6
|
-
import {
|
|
6
|
+
import { cachedInstallationToken } from '../github/signing.js';
|
|
7
7
|
import { listMarkdown, readRaw, commitFile } from '../github/repo.js';
|
|
8
8
|
import { CommitConflictError } from '../github/types.js';
|
|
9
9
|
import { parseSiteConfig, extractMenu, validateNavTree, setMenu } from '../nav/site-config.js';
|
|
@@ -19,7 +19,7 @@ function isConflict(err) {
|
|
|
19
19
|
return err instanceof CommitConflictError || err?.name === 'CommitConflictError';
|
|
20
20
|
}
|
|
21
21
|
export function createNavRoutes(runtime, deps = {}) {
|
|
22
|
-
const mintToken = deps.mintToken ?? ((env) =>
|
|
22
|
+
const mintToken = deps.mintToken ?? ((env) => cachedInstallationToken(appCredentials(runtime.backend, env)));
|
|
23
23
|
/** List page-like concepts (routable, not dated) for the URL picker. Best-effort per concept. */
|
|
24
24
|
async function pageOptions(token) {
|
|
25
25
|
const pageConcepts = runtime.concepts.filter((c) => c.routing.routable && !c.routing.dated);
|
|
@@ -38,7 +38,7 @@ export function createPublicRoutes(deps) {
|
|
|
38
38
|
...(image ? { image } : {}),
|
|
39
39
|
...(fields.robots ? { robots: fields.robots } : {}),
|
|
40
40
|
...(fields.author ? { author: fields.author } : {}),
|
|
41
|
-
feeds,
|
|
41
|
+
...(entry.date ? { feeds } : {}),
|
|
42
42
|
});
|
|
43
43
|
return { entry, html: await render(entry.body, { stagger: true }), canonicalUrl, seo, newer, older };
|
|
44
44
|
}
|
|
@@ -22,6 +22,12 @@ export interface RequestContext {
|
|
|
22
22
|
};
|
|
23
23
|
platform?: {
|
|
24
24
|
env?: AuthEnv;
|
|
25
|
+
ctx?: {
|
|
26
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
27
|
+
};
|
|
28
|
+
context?: {
|
|
29
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
30
|
+
};
|
|
25
31
|
};
|
|
26
32
|
setHeaders(headers: Record<string, string>): void;
|
|
27
33
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/lib/sveltekit/types.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAExD,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,QAAQ,CAAC,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;IACrC,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,SAAS;IACxB,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IACtC,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAC/D,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;CACpD;AAED,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,GAAG,CAAC;IACT,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,SAAS,CAAC;IACnB,MAAM,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC;IACnC,QAAQ,CAAC,EAAE;
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/lib/sveltekit/types.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAExD,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,QAAQ,CAAC,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;IACrC,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,SAAS;IACxB,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IACtC,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAC/D,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;CACpD;AAED,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,GAAG,CAAC;IACT,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,SAAS,CAAC;IACnB,MAAM,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC;IACnC,QAAQ,CAAC,EAAE;QACT,GAAG,CAAC,EAAE,OAAO,CAAC;QACd,GAAG,CAAC,EAAE;YAAE,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI,CAAA;SAAE,CAAC;QACrD,OAAO,CAAC,EAAE;YAAE,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI,CAAA;SAAE,CAAC;KAC1D,CAAC;IAGF,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAAC;CACnD;AAED,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,cAAc,CAAC;IACtB,OAAO,CAAC,KAAK,EAAE,cAAc,GAAG,OAAO,CAAC,QAAQ,CAAC,GAAG,QAAQ,CAAC;CAC9D"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@glw907/cairn-cms",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.0",
|
|
4
4
|
"description": "Embedded, magic-link, GitHub-committing CMS for SvelteKit/Cloudflare sites.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": [
|
|
@@ -73,11 +73,12 @@
|
|
|
73
73
|
"@types/hast": "^3.0.4",
|
|
74
74
|
"@types/mdast": "^4.0.4",
|
|
75
75
|
"codemirror": "^6.0.2",
|
|
76
|
-
"dompurify": "^3.4.7",
|
|
77
76
|
"gray-matter": "^4",
|
|
77
|
+
"hast-util-sanitize": "^5.0.2",
|
|
78
78
|
"hastscript": "^9.0.1",
|
|
79
79
|
"mdast-util-directive": "^3.1.0",
|
|
80
80
|
"rehype-raw": "^7.0.0",
|
|
81
|
+
"rehype-sanitize": "^6.0.0",
|
|
81
82
|
"rehype-slug": "^6.0.0",
|
|
82
83
|
"rehype-stringify": "^10.0.1",
|
|
83
84
|
"remark-directive": "^4.0.0",
|
package/src/lib/auth/crypto.ts
CHANGED
|
@@ -2,8 +2,17 @@
|
|
|
2
2
|
// code runs unchanged in workerd. The store keeps only the hash of a token, never the
|
|
3
3
|
// token itself (spec 7.1).
|
|
4
4
|
|
|
5
|
-
/** The session cookie name. */
|
|
6
|
-
|
|
5
|
+
/** The base session cookie name, prefixed with __Host- when the cookie is Secure. */
|
|
6
|
+
const COOKIE_BASE = 'cairn_session';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The session cookie name. On https the cookie is Secure and takes the __Host- prefix, which
|
|
10
|
+
* binds it to the origin (the browser enforces Secure, Path=/, and no Domain). On local http
|
|
11
|
+
* dev the prefix is dropped, since __Host- requires Secure and the dev cookie cannot set it.
|
|
12
|
+
*/
|
|
13
|
+
export function sessionCookieName(secure: boolean): string {
|
|
14
|
+
return secure ? `__Host-${COOKIE_BASE}` : COOKIE_BASE;
|
|
15
|
+
}
|
|
7
16
|
|
|
8
17
|
/** Magic-link tokens live 10 minutes. */
|
|
9
18
|
export const TOKEN_TTL_MS = 10 * 60 * 1000;
|
|
@@ -11,6 +20,9 @@ export const TOKEN_TTL_MS = 10 * 60 * 1000;
|
|
|
11
20
|
/** Sessions live 30 days. */
|
|
12
21
|
export const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
13
22
|
|
|
23
|
+
/** A magic link is sent at most once per email per minute, to throttle inbox flooding. */
|
|
24
|
+
export const SEND_COOLDOWN_MS = 60 * 1000;
|
|
25
|
+
|
|
14
26
|
function randomBase64Url(byteLength = 32): string {
|
|
15
27
|
const bytes = new Uint8Array(byteLength);
|
|
16
28
|
crypto.getRandomValues(bytes);
|
package/src/lib/auth/store.ts
CHANGED
|
@@ -28,13 +28,23 @@ export async function issueToken(
|
|
|
28
28
|
now: number,
|
|
29
29
|
): Promise<void> {
|
|
30
30
|
await db.batch([
|
|
31
|
-
|
|
31
|
+
// Replace this email's prior token, and sweep any expired token while here (no cron needed).
|
|
32
|
+
db.prepare('DELETE FROM magic_token WHERE email = ? OR expires_at <= ?').bind(email, now),
|
|
32
33
|
db
|
|
33
34
|
.prepare('INSERT INTO magic_token (token_hash, email, expires_at, created_at) VALUES (?, ?, ?, ?)')
|
|
34
35
|
.bind(tokenHash, email, expiresAt, now),
|
|
35
36
|
]);
|
|
36
37
|
}
|
|
37
38
|
|
|
39
|
+
/** True when a magic-link token for this email was issued at or after `since`, for the send cooldown. */
|
|
40
|
+
export async function recentlyIssued(db: D1Database, email: string, since: number): Promise<boolean> {
|
|
41
|
+
const row = await db
|
|
42
|
+
.prepare('SELECT 1 AS one FROM magic_token WHERE email = ? AND created_at >= ? LIMIT 1')
|
|
43
|
+
.bind(email, since)
|
|
44
|
+
.first<{ one: number }>();
|
|
45
|
+
return row != null;
|
|
46
|
+
}
|
|
47
|
+
|
|
38
48
|
/**
|
|
39
49
|
* Consume a token in one atomic statement. A returned email means the token was present and
|
|
40
50
|
* unexpired and is now gone, so the link is single-use by construction on strongly-consistent D1.
|
|
@@ -55,10 +65,13 @@ export async function createSession(
|
|
|
55
65
|
expiresAt: number,
|
|
56
66
|
now: number,
|
|
57
67
|
): Promise<void> {
|
|
58
|
-
await db
|
|
59
|
-
|
|
60
|
-
.
|
|
61
|
-
|
|
68
|
+
await db.batch([
|
|
69
|
+
// Sweep expired sessions on login, so abandoned rows do not accumulate (no cron needed).
|
|
70
|
+
db.prepare('DELETE FROM session WHERE expires_at <= ?').bind(now),
|
|
71
|
+
db
|
|
72
|
+
.prepare('INSERT INTO session (id, email, expires_at, created_at) VALUES (?, ?, ?, ?)')
|
|
73
|
+
.bind(id, email, expiresAt, now),
|
|
74
|
+
]);
|
|
62
75
|
}
|
|
63
76
|
|
|
64
77
|
/**
|
|
@@ -12,14 +12,13 @@ markdown editor and a live, design-accurate preview. The whole surface is one fo
|
|
|
12
12
|
import type { IconSet } from '../render/glyph.js';
|
|
13
13
|
import type { EditData } from '../sveltekit/content-routes.js';
|
|
14
14
|
import type { TextareaField, TagsField, FreeTagsField } from '../content/types.js';
|
|
15
|
-
import { sanitizePreviewHtml } from '../render/sanitize.js';
|
|
16
15
|
|
|
17
16
|
interface Props {
|
|
18
17
|
/** The edit load's data, plus the site name for the heading. */
|
|
19
18
|
data: EditData & { siteName: string };
|
|
20
19
|
/** The site's component registry, for the insert palette. */
|
|
21
20
|
registry?: ComponentRegistry;
|
|
22
|
-
/** The site's design-accurate render pipeline; the preview pane
|
|
21
|
+
/** The site's design-accurate render pipeline; the preview pane renders its output, which the floored pipeline already sanitized. */
|
|
23
22
|
render?: (md: string, opts?: { stagger?: boolean }) => string | Promise<string>;
|
|
24
23
|
/** The site's icon set, for the guided form's icon fields. */
|
|
25
24
|
icons?: IconSet;
|
|
@@ -46,8 +45,8 @@ markdown editor and a live, design-accurate preview. The whole surface is one fo
|
|
|
46
45
|
localStorage.setItem(PREVIEW_KEY, showPreview ? '1' : '0');
|
|
47
46
|
}
|
|
48
47
|
|
|
49
|
-
// Render the design-accurate preview as the body changes, debounced
|
|
50
|
-
//
|
|
48
|
+
// Render the design-accurate preview as the body changes, debounced. The site's render is the
|
|
49
|
+
// floored engine pipeline, so its output is already sanitized; the preview mirrors the page.
|
|
51
50
|
// previewRun is a plain counter (not reactive state) used as a latest-wins guard: if a slow earlier
|
|
52
51
|
// async render call resolves after a newer one has started, the stale result is discarded.
|
|
53
52
|
let previewRun = 0;
|
|
@@ -58,8 +57,7 @@ markdown editor and a live, design-accurate preview. The whole surface is one fo
|
|
|
58
57
|
const handle = setTimeout(async () => {
|
|
59
58
|
try {
|
|
60
59
|
const html = await render(md);
|
|
61
|
-
|
|
62
|
-
if (run === previewRun) previewHtml = safe;
|
|
60
|
+
if (run === previewRun) previewHtml = html;
|
|
63
61
|
} catch {
|
|
64
62
|
if (run === previewRun) previewHtml = '';
|
|
65
63
|
}
|
|
@@ -84,18 +84,21 @@ export function createContentIndex<F = Record<string, unknown>>(
|
|
|
84
84
|
descriptor: ConceptDescriptor,
|
|
85
85
|
): ContentIndex<F> {
|
|
86
86
|
const problems: ContentProblem[] = [];
|
|
87
|
-
const entries: ContentEntry<F>[] =
|
|
87
|
+
const entries: ContentEntry<F>[] = [];
|
|
88
|
+
for (const file of files) {
|
|
88
89
|
const id = idFromFilename(basename(file.path));
|
|
89
90
|
const slug = slugFromId(id, descriptor.routing.dated ? descriptor.datePrefix : null);
|
|
90
91
|
const { frontmatter: raw, body } = parseMarkdown(file.raw);
|
|
91
92
|
const date = asDate(raw.date);
|
|
92
93
|
const draft = raw.draft === true;
|
|
93
|
-
// Validate once at build.
|
|
94
|
-
//
|
|
95
|
-
// failure is recorded, not thrown, so the query surface does not explode on construction.
|
|
94
|
+
// Validate once at build. A failure is recorded for the site gate and excluded from the typed
|
|
95
|
+
// read, so every readable entry's frontmatter is the validator's normalized output, never raw.
|
|
96
96
|
const result = descriptor.validate(raw, body);
|
|
97
|
-
if (!result.ok)
|
|
98
|
-
|
|
97
|
+
if (!result.ok) {
|
|
98
|
+
problems.push({ id, draft, errors: result.errors });
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
entries.push({
|
|
99
102
|
id,
|
|
100
103
|
slug,
|
|
101
104
|
permalink: permalink(descriptor, { id, slug, date }),
|
|
@@ -106,10 +109,10 @@ export function createContentIndex<F = Record<string, unknown>>(
|
|
|
106
109
|
excerpt: deriveExcerpt(body, { description: asString(raw.description) }),
|
|
107
110
|
wordCount: wordCount(body),
|
|
108
111
|
draft,
|
|
109
|
-
frontmatter:
|
|
112
|
+
frontmatter: result.data as F,
|
|
110
113
|
body,
|
|
111
|
-
};
|
|
112
|
-
}
|
|
114
|
+
});
|
|
115
|
+
}
|
|
113
116
|
|
|
114
117
|
// Dated concepts sort newest-first; undated concepts (Pages) sort by title.
|
|
115
118
|
const sorted = [...entries].sort((a, b) =>
|
|
@@ -17,7 +17,7 @@ export interface FeedChannel {
|
|
|
17
17
|
export interface FeedItem {
|
|
18
18
|
title: string;
|
|
19
19
|
url: string;
|
|
20
|
-
date
|
|
20
|
+
date?: string;
|
|
21
21
|
updated?: string;
|
|
22
22
|
summary: string;
|
|
23
23
|
contentHtml?: string;
|
|
@@ -37,14 +37,22 @@ function cdataSafe(value: string): string {
|
|
|
37
37
|
return value.replace(/]]>/g, ']]]]><![CDATA[>');
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
/**
|
|
41
|
-
|
|
42
|
-
|
|
40
|
+
/** Parse a YYYY-MM-DD (or ISO) string as a UTC instant. Returns undefined for an absent or
|
|
41
|
+
* unparseable date, so a feed omits the date field rather than emit Invalid Date or throw. */
|
|
42
|
+
function parseFeedDate(date?: string): Date | undefined {
|
|
43
|
+
if (!date) return undefined;
|
|
44
|
+
const at = new Date(`${date.slice(0, 10)}T00:00:00.000Z`);
|
|
45
|
+
return Number.isNaN(at.getTime()) ? undefined : at;
|
|
43
46
|
}
|
|
44
47
|
|
|
45
|
-
/** Format a
|
|
46
|
-
function
|
|
47
|
-
return
|
|
48
|
+
/** Format a date as an RFC-822 string in UTC, as RSS wants, or undefined when it cannot parse. */
|
|
49
|
+
function rfc822(date?: string): string | undefined {
|
|
50
|
+
return parseFeedDate(date)?.toUTCString();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Format a date as an ISO-8601 instant in UTC, or undefined when it cannot parse. */
|
|
54
|
+
function iso(date?: string): string | undefined {
|
|
55
|
+
return parseFeedDate(date)?.toISOString();
|
|
48
56
|
}
|
|
49
57
|
|
|
50
58
|
/** Build an RSS 2.0 document. */
|
|
@@ -52,17 +60,20 @@ export function buildRssFeed(channel: FeedChannel, items: FeedItem[]): string {
|
|
|
52
60
|
const entries = items
|
|
53
61
|
.map((item) => {
|
|
54
62
|
const content = item.contentHtml ?? item.summary;
|
|
63
|
+
const pubDate = rfc822(item.date);
|
|
55
64
|
return [
|
|
56
65
|
' <item>',
|
|
57
66
|
` <title>${escapeXml(item.title)}</title>`,
|
|
58
67
|
` <link>${escapeXml(item.url)}</link>`,
|
|
59
68
|
` <guid isPermaLink="true">${escapeXml(item.url)}</guid>`,
|
|
60
|
-
` <pubDate>${
|
|
69
|
+
pubDate ? ` <pubDate>${pubDate}</pubDate>` : '',
|
|
61
70
|
` <description>${escapeXml(item.summary)}</description>`,
|
|
62
71
|
// CDATA cannot contain `]]>`, so split that one sequence rather than escape the body.
|
|
63
72
|
` <content:encoded><![CDATA[${cdataSafe(content)}]]></content:encoded>`,
|
|
64
73
|
' </item>',
|
|
65
|
-
]
|
|
74
|
+
]
|
|
75
|
+
.filter((line) => line !== '')
|
|
76
|
+
.join('\n');
|
|
66
77
|
})
|
|
67
78
|
.join('\n');
|
|
68
79
|
|
|
@@ -95,16 +106,20 @@ export function buildJsonFeed(channel: FeedChannel, items: FeedItem[]): string {
|
|
|
95
106
|
feed_url: channel.feedUrl,
|
|
96
107
|
...(channel.language ? { language: channel.language } : {}),
|
|
97
108
|
...(channel.author ? { authors: [channel.author] } : {}),
|
|
98
|
-
items: items.map((item) =>
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
109
|
+
items: items.map((item) => {
|
|
110
|
+
const datePublished = iso(item.date);
|
|
111
|
+
const dateModified = iso(item.updated);
|
|
112
|
+
return {
|
|
113
|
+
id: item.url,
|
|
114
|
+
url: item.url,
|
|
115
|
+
title: item.title,
|
|
116
|
+
summary: item.summary,
|
|
117
|
+
...(datePublished ? { date_published: datePublished } : {}),
|
|
118
|
+
...(dateModified ? { date_modified: dateModified } : {}),
|
|
119
|
+
...(item.contentHtml ? { content_html: item.contentHtml } : { content_text: item.summary }),
|
|
120
|
+
...(item.tags && item.tags.length ? { tags: item.tags } : {}),
|
|
121
|
+
};
|
|
122
|
+
}),
|
|
108
123
|
},
|
|
109
124
|
null,
|
|
110
125
|
2,
|
|
@@ -39,10 +39,22 @@ export function createSiteIndexes<const A extends CairnAdapter>(
|
|
|
39
39
|
opts: { validate?: boolean } = {},
|
|
40
40
|
): SiteIndexes<A> {
|
|
41
41
|
const descriptors = siteDescriptors(adapter, config);
|
|
42
|
+
const globRecord = globs as Record<string, Record<string, string> | undefined>;
|
|
42
43
|
const byConcept: Record<string, ContentIndex> = {};
|
|
43
44
|
const conceptIndexes: ConceptIndex[] = [];
|
|
44
45
|
for (const descriptor of descriptors) {
|
|
45
|
-
|
|
46
|
+
if (descriptor.id === 'site') {
|
|
47
|
+
throw new Error(
|
|
48
|
+
'createSiteIndexes: a concept cannot be named "site", which is the reserved cross-concept resolver key',
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
if (!Object.prototype.hasOwnProperty.call(globRecord, descriptor.id)) {
|
|
52
|
+
const passed = Object.keys(globRecord);
|
|
53
|
+
throw new Error(
|
|
54
|
+
`createSiteIndexes: no glob passed for concept "${descriptor.id}"; pass its import.meta.glob (an empty {} for an intentionally empty concept). Globs passed: ${passed.length ? passed.join(', ') : '(none)'}`,
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
const record = globRecord[descriptor.id] ?? {};
|
|
46
58
|
const index = createContentIndex(fromGlob(record), descriptor);
|
|
47
59
|
byConcept[descriptor.id] = index;
|
|
48
60
|
conceptIndexes.push({ descriptor, index });
|
package/src/lib/env.ts
CHANGED
|
@@ -13,6 +13,19 @@ export function requireOrigin(env: { PUBLIC_ORIGIN?: string }): string {
|
|
|
13
13
|
if (!origin) {
|
|
14
14
|
throw new Error('PUBLIC_ORIGIN is not configured');
|
|
15
15
|
}
|
|
16
|
+
let hostname: string;
|
|
17
|
+
try {
|
|
18
|
+
hostname = new URL(origin).hostname;
|
|
19
|
+
} catch {
|
|
20
|
+
throw new Error(`PUBLIC_ORIGIN is not a valid URL, got ${origin}`);
|
|
21
|
+
}
|
|
22
|
+
// The magic-link origin must be https in production so the link and the __Host- cookie are
|
|
23
|
+
// origin-bound. http is allowed only for local dev on localhost or 127.0.0.1, matched exactly so
|
|
24
|
+
// a lookalike host like localhost.example.com cannot skip the https requirement.
|
|
25
|
+
const isLocal = hostname === 'localhost' || hostname === '127.0.0.1';
|
|
26
|
+
if (!origin.startsWith('https://') && !isLocal) {
|
|
27
|
+
throw new Error(`PUBLIC_ORIGIN must be https in production, got ${origin}`);
|
|
28
|
+
}
|
|
16
29
|
return origin;
|
|
17
30
|
}
|
|
18
31
|
|
|
@@ -79,6 +79,38 @@ export async function installationToken(creds: AppCredentials): Promise<string>
|
|
|
79
79
|
return ((await res.json()) as { token: string }).token;
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
interface CachedToken {
|
|
83
|
+
token: string;
|
|
84
|
+
expiresAt: number;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Build an installation-token cache. A module-global instance memoizes the minted token per
|
|
89
|
+
* installation for most of its one-hour life, so a warm Worker isolate reuses it across requests
|
|
90
|
+
* instead of re-signing and re-calling GitHub on every list and commit. A cold isolate re-mints,
|
|
91
|
+
* which is always safe. This mirrors the default of @octokit/auth-app, which caches installation
|
|
92
|
+
* tokens in memory and returns them until expiry. The TTL stays under GitHub's documented one-hour
|
|
93
|
+
* lifetime, so a fixed margin avoids parsing the API expiry. `mint` and `now` are injected so the
|
|
94
|
+
* cache is testable with no network call and no real clock.
|
|
95
|
+
*/
|
|
96
|
+
export function createInstallationTokenCache(
|
|
97
|
+
mint: (creds: AppCredentials) => Promise<string> = installationToken,
|
|
98
|
+
now: () => number = () => Date.now(),
|
|
99
|
+
ttlMs = 55 * 60 * 1000,
|
|
100
|
+
): (creds: AppCredentials) => Promise<string> {
|
|
101
|
+
const cache = new Map<string, CachedToken>();
|
|
102
|
+
return async function get(creds: AppCredentials): Promise<string> {
|
|
103
|
+
const hit = cache.get(creds.installationId);
|
|
104
|
+
if (hit && hit.expiresAt > now()) return hit.token;
|
|
105
|
+
const token = await mint(creds);
|
|
106
|
+
cache.set(creds.installationId, { token, expiresAt: now() + ttlMs });
|
|
107
|
+
return token;
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The shared installation-token cache, one instance per Worker isolate. */
|
|
112
|
+
export const cachedInstallationToken = createInstallationTokenCache();
|
|
113
|
+
|
|
82
114
|
/**
|
|
83
115
|
* Deploy-time self-test for the App signer: sign a dummy JWT with the configured key. It
|
|
84
116
|
* exercises the brittle PKCS#1-to-PKCS#8 conversion and the Web Crypto import and sign with
|
|
@@ -6,6 +6,9 @@ import remarkRehype from 'remark-rehype';
|
|
|
6
6
|
import rehypeRaw from 'rehype-raw';
|
|
7
7
|
import rehypeSlug from 'rehype-slug';
|
|
8
8
|
import rehypeStringify from 'rehype-stringify';
|
|
9
|
+
import rehypeSanitize from 'rehype-sanitize';
|
|
10
|
+
import type { Schema } from 'hast-util-sanitize';
|
|
11
|
+
import { buildSanitizeSchema, rehypeAnchorRel } from './sanitize-schema.js';
|
|
9
12
|
import { remarkDirectiveStamp } from './remark-directives.js';
|
|
10
13
|
import { rehypeDispatch } from './rehype-dispatch.js';
|
|
11
14
|
import type { ComponentRegistry } from './registry.js';
|
|
@@ -15,6 +18,15 @@ export interface RendererOptions {
|
|
|
15
18
|
* CSS can drive an entrance-cascade delay off it. Omit for no stagger. The ordinal
|
|
16
19
|
* is inert, so a consumer's sanitize floor can keep `data-rise` and drop `style`. */
|
|
17
20
|
stagger?: boolean;
|
|
21
|
+
/** Extend the sanitize allowlist. Receives cairn's default schema (defaultSchema plus the
|
|
22
|
+
* directive markers and the common benign tags) and returns the schema to use. Add to the
|
|
23
|
+
* allowlist for the benign HTML a site's content needs; start from the argument so the
|
|
24
|
+
* dangerous strip is preserved. */
|
|
25
|
+
sanitizeSchema?: (defaults: Schema) => Schema;
|
|
26
|
+
/** Developer-only escape hatch: disable the sanitize floor entirely. This reintroduces the XSS
|
|
27
|
+
* vector the floor closes, so it is only for a site whose content is fully developer-controlled.
|
|
28
|
+
* It is a code-level adapter decision, never an editor-facing setting. */
|
|
29
|
+
unsafeDisableSanitize?: boolean;
|
|
18
30
|
}
|
|
19
31
|
|
|
20
32
|
/** Compose a site's render pipeline from its component registry: directive syntax to
|
|
@@ -22,7 +34,19 @@ export interface RendererOptions {
|
|
|
22
34
|
* rehype plugin arrays (so the admin editor preview can reuse the exact same set). */
|
|
23
35
|
export function createRenderer(registry: ComponentRegistry, options: RendererOptions = {}) {
|
|
24
36
|
const remarkPlugins: PluggableList = [remarkDirective, [remarkDirectiveStamp, registry]];
|
|
25
|
-
|
|
37
|
+
// The sanitize floor runs after rehype-raw (so author raw HTML is parsed, then cleaned) and
|
|
38
|
+
// before the dispatch (so the site's trusted build() output and its inline SVG icons are never
|
|
39
|
+
// sanitized). The anchor-rel hardening runs last so it also covers component-built anchors.
|
|
40
|
+
const floor: PluggableList = options.unsafeDisableSanitize
|
|
41
|
+
? []
|
|
42
|
+
: [[rehypeSanitize, buildSanitizeSchema(registry, options.sanitizeSchema)]];
|
|
43
|
+
const rehypePlugins: PluggableList = [
|
|
44
|
+
rehypeRaw,
|
|
45
|
+
...floor,
|
|
46
|
+
[rehypeDispatch, registry, options.stagger],
|
|
47
|
+
rehypeSlug,
|
|
48
|
+
rehypeAnchorRel,
|
|
49
|
+
];
|
|
26
50
|
const processor = unified()
|
|
27
51
|
.use(remarkParse)
|
|
28
52
|
.use(remarkGfm)
|