@decocms/tanstack 8.0.0 → 8.4.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 +79 -0
- package/dist/draft.d.ts +33 -0
- package/dist/draft.d.ts.map +1 -0
- package/dist/draft.js +41 -0
- package/dist/draft.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/react/DecoDocument.d.ts +61 -0
- package/dist/react/DecoDocument.d.ts.map +1 -0
- package/dist/react/DecoDocument.js +96 -0
- package/dist/react/DecoDocument.js.map +1 -0
- package/dist/react/Image.d.ts +96 -0
- package/dist/react/Image.d.ts.map +1 -0
- package/dist/react/Image.js +79 -0
- package/dist/react/Image.js.map +1 -0
- package/dist/react/index.d.ts +7 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +7 -0
- package/dist/react/index.js.map +1 -0
- package/dist/react/pageValues.d.ts +10 -0
- package/dist/react/pageValues.d.ts.map +1 -0
- package/dist/react/pageValues.js +29 -0
- package/dist/react/pageValues.js.map +1 -0
- package/dist/react/scripts.d.ts +14 -0
- package/dist/react/scripts.d.ts.map +1 -0
- package/dist/react/scripts.js +96 -0
- package/dist/react/scripts.js.map +1 -0
- package/dist/router/index.d.ts +38 -0
- package/dist/router/index.d.ts.map +1 -0
- package/dist/router/index.js +60 -0
- package/dist/router/index.js.map +1 -0
- package/dist/scope/browser.d.ts +11 -0
- package/dist/scope/browser.d.ts.map +1 -0
- package/dist/scope/browser.js +8 -0
- package/dist/scope/browser.js.map +1 -0
- package/dist/scope/server.d.ts +13 -0
- package/dist/scope/server.d.ts.map +1 -0
- package/dist/scope/server.js +26 -0
- package/dist/scope/server.js.map +1 -0
- package/dist/server/index.d.ts +27 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +31 -0
- package/dist/server/index.js.map +1 -0
- package/dist/shared.d.ts +26 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +26 -0
- package/dist/shared.js.map +1 -0
- package/dist/start/index.d.ts +9 -0
- package/dist/start/index.d.ts.map +1 -0
- package/dist/start/index.js +33 -0
- package/dist/start/index.js.map +1 -0
- package/dist/studio.d.ts +28 -0
- package/dist/studio.d.ts.map +1 -0
- package/dist/studio.js +53 -0
- package/dist/studio.js.map +1 -0
- package/dist/vite/index.d.ts +15 -0
- package/dist/vite/index.d.ts.map +1 -0
- package/dist/vite/index.js +95 -0
- package/dist/vite/index.js.map +1 -0
- package/dist/worker/cacheProfiles.d.ts +43 -0
- package/dist/worker/cacheProfiles.d.ts.map +1 -0
- package/dist/worker/cacheProfiles.js +162 -0
- package/dist/worker/cacheProfiles.js.map +1 -0
- package/dist/worker/cookies.d.ts +20 -0
- package/dist/worker/cookies.d.ts.map +1 -0
- package/dist/worker/cookies.js +69 -0
- package/dist/worker/cookies.js.map +1 -0
- package/dist/worker/drafts.d.ts +59 -0
- package/dist/worker/drafts.d.ts.map +1 -0
- package/dist/worker/drafts.js +140 -0
- package/dist/worker/drafts.js.map +1 -0
- package/dist/worker/index.d.ts +107 -0
- package/dist/worker/index.d.ts.map +1 -0
- package/dist/worker/index.js +511 -0
- package/dist/worker/index.js.map +1 -0
- package/dist/worker/security.d.ts +14 -0
- package/dist/worker/security.d.ts.map +1 -0
- package/dist/worker/security.js +48 -0
- package/dist/worker/security.js.map +1 -0
- package/dist/worker/segment.d.ts +21 -0
- package/dist/worker/segment.d.ts.map +1 -0
- package/dist/worker/segment.js +43 -0
- package/dist/worker/segment.js.map +1 -0
- package/package.json +86 -31
- package/src/draft.ts +43 -0
- package/src/index.ts +8 -44
- package/src/react/DecoDocument.tsx +234 -0
- package/src/react/Image.tsx +213 -0
- package/src/react/index.ts +24 -0
- package/src/react/pageValues.ts +35 -0
- package/src/react/scripts.ts +98 -0
- package/src/router/index.ts +80 -0
- package/src/scope/browser.ts +18 -0
- package/src/scope/server.ts +37 -0
- package/src/server/index.ts +43 -0
- package/src/shared.ts +29 -0
- package/src/start/index.ts +31 -0
- package/src/studio.ts +52 -0
- package/src/vite/index.ts +105 -0
- package/src/worker/cacheProfiles.ts +180 -0
- package/src/worker/cookies.ts +65 -0
- package/src/worker/drafts.ts +157 -0
- package/src/worker/index.ts +648 -0
- package/src/worker/security.ts +63 -0
- package/src/worker/segment.ts +49 -0
- package/src/cms/kvBlockSource.test.ts +0 -82
- package/src/cms/kvBlockSource.ts +0 -68
- package/src/daemon/auth.ts +0 -204
- package/src/daemon/fs.ts +0 -238
- package/src/daemon/index.ts +0 -8
- package/src/daemon/middleware.ts +0 -156
- package/src/daemon/tunnel.ts +0 -129
- package/src/daemon/volumes.ts +0 -366
- package/src/daemon/watch.ts +0 -272
- package/src/hooks/DecoPageRenderer.tsx +0 -688
- package/src/hooks/DecoRootLayout.tsx +0 -111
- package/src/hooks/NavigationProgress.tsx +0 -21
- package/src/hooks/PreviewProviders.tsx +0 -26
- package/src/hooks/StableOutlet.tsx +0 -30
- package/src/hooks/index.ts +0 -9
- package/src/routes/adminRoutes.test.ts +0 -99
- package/src/routes/adminRoutes.ts +0 -153
- package/src/routes/cmsRoute.test.ts +0 -100
- package/src/routes/cmsRoute.ts +0 -944
- package/src/routes/components.tsx +0 -57
- package/src/routes/index.ts +0 -24
- package/src/routes/pageUrl.test.ts +0 -70
- package/src/routes/pageUrl.ts +0 -54
- package/src/routes/withSiteGlobals.test.ts +0 -206
- package/src/routes/withSiteGlobals.ts +0 -222
- package/src/sdk/cookiePassthrough.ts +0 -58
- package/src/sdk/createInvoke.ts +0 -77
- package/src/sdk/deferredSectionLoader.test.ts +0 -94
- package/src/sdk/deferredSectionLoader.ts +0 -46
- package/src/sdk/kvHydration.test.ts +0 -215
- package/src/sdk/kvHydration.ts +0 -193
- package/src/sdk/outboundHeaders.test.ts +0 -113
- package/src/sdk/outboundHeaders.ts +0 -81
- package/src/sdk/router.ts +0 -92
- package/src/sdk/useHydrated.ts +0 -19
- package/src/sdk/workerEntry.test.ts +0 -495
- package/src/sdk/workerEntry.ts +0 -2307
- package/src/setupFastDeploy.ts +0 -13
- package/src/vite/plugin-scaffold-gen.test.js +0 -106
- package/src/vite/plugin.js +0 -850
- package/src/vite/plugin.test.js +0 -113
- package/src/vite/plugin.test.ts +0 -52
- package/tsconfig.json +0 -7
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The headers every HTML response carries: v7's security headers, the site's
|
|
3
|
+
* Content-Security-Policy, and `frame-ancestors` so Deco Studio's site editor
|
|
4
|
+
* (and nothing else the site doesn't name) can show the page in its frame. No
|
|
5
|
+
* `X-Frame-Options`: `frame-ancestors` supersedes it and, unlike `SAMEORIGIN`,
|
|
6
|
+
* can allow Studio's origin.
|
|
7
|
+
*/
|
|
8
|
+
import { STUDIO_FRAME_ANCESTORS } from "../studio.ts";
|
|
9
|
+
|
|
10
|
+
export const SECURITY_HEADERS: Readonly<Record<string, string>> = {
|
|
11
|
+
"X-Content-Type-Options": "nosniff",
|
|
12
|
+
"Referrer-Policy": "strict-origin-when-cross-origin",
|
|
13
|
+
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
|
|
14
|
+
"X-XSS-Protection": "1; mode=block",
|
|
15
|
+
"Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
|
|
16
|
+
"Cross-Origin-Opener-Policy": "same-origin-allow-popups",
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** A Studio on this machine, in local development. */
|
|
20
|
+
const LOOPBACK_ANCESTORS = ["http://localhost:*", "http://127.0.0.1:*"];
|
|
21
|
+
|
|
22
|
+
export interface CspOptions {
|
|
23
|
+
/** The enforced policy's directives (`frame-ancestors` is added when they have none). */
|
|
24
|
+
enforce?: string | readonly string[];
|
|
25
|
+
/** Directives sent as `Content-Security-Policy-Report-Only`. */
|
|
26
|
+
reportOnly?: string | readonly string[];
|
|
27
|
+
/** More origins that may frame the site, besides Studio's (a marketing tool's editor). */
|
|
28
|
+
frameAncestors?: readonly string[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function directives(value: string | readonly string[] | undefined): string[] {
|
|
32
|
+
if (value === undefined) return [];
|
|
33
|
+
const list = typeof value === "string" ? value.split(";") : [...value];
|
|
34
|
+
return list.map((d) => d.trim()).filter(Boolean);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The `frame-ancestors` sources: Studio's, the site's own, and loopback in development. */
|
|
38
|
+
export function frameAncestors(csp: CspOptions | undefined, dev: boolean): string[] {
|
|
39
|
+
return [
|
|
40
|
+
...new Set([
|
|
41
|
+
...STUDIO_FRAME_ANCESTORS,
|
|
42
|
+
...(csp?.frameAncestors ?? []),
|
|
43
|
+
...(dev ? LOOPBACK_ANCESTORS : []),
|
|
44
|
+
]),
|
|
45
|
+
];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Every HTML response's security headers. */
|
|
49
|
+
export function htmlSecurityHeaders(
|
|
50
|
+
csp: CspOptions | undefined,
|
|
51
|
+
dev: boolean,
|
|
52
|
+
): Record<string, string> {
|
|
53
|
+
const enforce = directives(csp?.enforce);
|
|
54
|
+
if (!enforce.some((d) => /^frame-ancestors(\s|$)/i.test(d))) {
|
|
55
|
+
enforce.push(`frame-ancestors ${frameAncestors(csp, dev).join(" ")}`);
|
|
56
|
+
}
|
|
57
|
+
const reportOnly = directives(csp?.reportOnly);
|
|
58
|
+
return {
|
|
59
|
+
...SECURITY_HEADERS,
|
|
60
|
+
"Content-Security-Policy": enforce.join("; "),
|
|
61
|
+
...(reportOnly.length ? { "Content-Security-Policy-Report-Only": reportOnly.join("; ") } : {}),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What splits the edge cache: the device class, plus whatever the site's
|
|
3
|
+
* `segment` option adds (a region, a sales channel, an A/B cohort). Every part
|
|
4
|
+
* is in the cache key, and in the `__cseg` token the page hands to the browser,
|
|
5
|
+
* so the CDN can cache client-side navigation data under the same split.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export type Device = "mobile" | "tablet" | "desktop";
|
|
9
|
+
|
|
10
|
+
/** A cache split: part name to value. `device` is always present. */
|
|
11
|
+
export type Segment = Readonly<Record<string, string>>;
|
|
12
|
+
|
|
13
|
+
// v7's expressions (@decocms/blocks/sdk/detectDevice): tablets first, so
|
|
14
|
+
// `android(?!.*mobile)` takes Android tablets before the phone rule.
|
|
15
|
+
const MOBILE_RE = /mobile|android.*mobile|iphone|ipod|webos|blackberry|opera mini|iemobile/i;
|
|
16
|
+
const TABLET_RE = /ipad|tablet|kindle|silk|playbook|android(?!.*mobile)/i;
|
|
17
|
+
|
|
18
|
+
export function detectDevice(userAgent: string): Device {
|
|
19
|
+
if (TABLET_RE.test(userAgent)) return "tablet";
|
|
20
|
+
if (MOBILE_RE.test(userAgent)) return "mobile";
|
|
21
|
+
return "desktop";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const DEVICES: readonly Device[] = ["mobile", "tablet", "desktop"];
|
|
25
|
+
|
|
26
|
+
/** A segment as one stable string: parts sorted by name, values URL-encoded. */
|
|
27
|
+
export function segmentKey(segment: Segment): string {
|
|
28
|
+
return Object.keys(segment)
|
|
29
|
+
.filter((name) => segment[name] !== undefined && segment[name] !== "")
|
|
30
|
+
.sort()
|
|
31
|
+
.map((name) => `${name}=${encodeURIComponent(segment[name] as string)}`)
|
|
32
|
+
.join("|");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** DJB2 over UTF-16 code units, as 8 hex digits. */
|
|
36
|
+
export function djb2Hex(text: string): string {
|
|
37
|
+
let hash = 5381;
|
|
38
|
+
for (let i = 0; i < text.length; i++) hash = ((hash << 5) + hash + text.charCodeAt(i)) | 0;
|
|
39
|
+
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The `__cseg` token for a segment and cache version, or `null` when there is
|
|
44
|
+
* no version to bind it to (a dev build), so stale URLs can never match.
|
|
45
|
+
*/
|
|
46
|
+
export function segmentToken(segment: Segment, version: string): string | null {
|
|
47
|
+
if (!version || version === "dev") return null;
|
|
48
|
+
return djb2Hex(`${segmentKey(segment)}|${version}`);
|
|
49
|
+
}
|
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from "vitest";
|
|
2
|
-
import { computeRevision, type KVNamespace, revisionKey, snapshotKey } from "@decocms/blocks/cms";
|
|
3
|
-
import { KVBlockSource } from "./kvBlockSource";
|
|
4
|
-
|
|
5
|
-
const ID = "sha-abc123";
|
|
6
|
-
const SNAP = snapshotKey(ID);
|
|
7
|
-
const REV = revisionKey(ID);
|
|
8
|
-
|
|
9
|
-
function makeKV(initial: Record<string, string> = {}): KVNamespace {
|
|
10
|
-
const store = new Map<string, string>(Object.entries(initial));
|
|
11
|
-
return {
|
|
12
|
-
get: (k) => Promise.resolve(store.get(k) ?? null),
|
|
13
|
-
put: (k, v) => {
|
|
14
|
-
store.set(k, v);
|
|
15
|
-
return Promise.resolve();
|
|
16
|
-
},
|
|
17
|
-
delete: (k) => {
|
|
18
|
-
store.delete(k);
|
|
19
|
-
return Promise.resolve();
|
|
20
|
-
},
|
|
21
|
-
};
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
describe("KVBlockSource.loadSnapshot", () => {
|
|
25
|
-
it("returns null when the snapshot key is missing", async () => {
|
|
26
|
-
const src = new KVBlockSource(makeKV(), ID);
|
|
27
|
-
await expect(src.loadSnapshot()).resolves.toBeNull();
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
it("reads the key for its own deployment id, not another", async () => {
|
|
31
|
-
const blocks = { Site: { name: "x" } };
|
|
32
|
-
// Store under a DIFFERENT deployment id — this source must not see it.
|
|
33
|
-
const src = new KVBlockSource(
|
|
34
|
-
makeKV({ [snapshotKey("other-sha")]: JSON.stringify(blocks) }),
|
|
35
|
-
ID,
|
|
36
|
-
);
|
|
37
|
-
await expect(src.loadSnapshot()).resolves.toBeNull();
|
|
38
|
-
});
|
|
39
|
-
|
|
40
|
-
it("returns blocks with the stored revision", async () => {
|
|
41
|
-
const blocks = { Site: { name: "x" } };
|
|
42
|
-
const src = new KVBlockSource(
|
|
43
|
-
makeKV({
|
|
44
|
-
[SNAP]: JSON.stringify(blocks),
|
|
45
|
-
[REV]: "stored-rev",
|
|
46
|
-
}),
|
|
47
|
-
ID,
|
|
48
|
-
);
|
|
49
|
-
await expect(src.loadSnapshot()).resolves.toEqual({ blocks, revision: "stored-rev" });
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
it("recomputes the revision when only the snapshot is stored", async () => {
|
|
53
|
-
const blocks = { Site: { name: "x" } };
|
|
54
|
-
const src = new KVBlockSource(makeKV({ [SNAP]: JSON.stringify(blocks) }), ID);
|
|
55
|
-
await expect(src.loadSnapshot()).resolves.toEqual({
|
|
56
|
-
blocks,
|
|
57
|
-
revision: computeRevision(blocks),
|
|
58
|
-
});
|
|
59
|
-
});
|
|
60
|
-
|
|
61
|
-
it("throws on a non-object snapshot (treated as KV-unavailable by callers)", async () => {
|
|
62
|
-
const src = new KVBlockSource(makeKV({ [SNAP]: "[1,2,3]" }), ID);
|
|
63
|
-
await expect(src.loadSnapshot()).rejects.toThrow();
|
|
64
|
-
});
|
|
65
|
-
|
|
66
|
-
it("throws on malformed JSON", async () => {
|
|
67
|
-
const src = new KVBlockSource(makeKV({ [SNAP]: "{not json" }), ID);
|
|
68
|
-
await expect(src.loadSnapshot()).rejects.toThrow();
|
|
69
|
-
});
|
|
70
|
-
});
|
|
71
|
-
|
|
72
|
-
describe("KVBlockSource.getRevision", () => {
|
|
73
|
-
it("returns the stored revision", async () => {
|
|
74
|
-
const src = new KVBlockSource(makeKV({ [REV]: "r1" }), ID);
|
|
75
|
-
await expect(src.getRevision()).resolves.toBe("r1");
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
it("returns null when absent", async () => {
|
|
79
|
-
const src = new KVBlockSource(makeKV(), ID);
|
|
80
|
-
await expect(src.getRevision()).resolves.toBeNull();
|
|
81
|
-
});
|
|
82
|
-
});
|
package/src/cms/kvBlockSource.ts
DELETED
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* KVBlockSource — a `BlockSource` backed by a Cloudflare KV namespace, scoped
|
|
3
|
-
* to a single **deployment id**.
|
|
4
|
-
*
|
|
5
|
-
* Reads the whole decofile snapshot (`decofile:<id>`) and its revision
|
|
6
|
-
* (`index:revision:<id>`) from KV. Used by the runtime hydration path
|
|
7
|
-
* (`src/sdk/kvHydration.ts`) on cold start and during revision polling, and by
|
|
8
|
-
* the write-through path (`src/admin/decofile.ts`) which writes the same keys.
|
|
9
|
-
* Keying by deployment id means each running version only ever sees its own
|
|
10
|
-
* content — a rolling deploy can't feed new content to still-live old code.
|
|
11
|
-
*
|
|
12
|
-
* This class is intentionally thin — error handling (KV outages, JSON parse
|
|
13
|
-
* failures) is the caller's responsibility so the framework can fall back to
|
|
14
|
-
* the bundled snapshot. See `kvHydration.ts`.
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
import {
|
|
18
|
-
type BlockSnapshot,
|
|
19
|
-
type BlockSource,
|
|
20
|
-
computeRevision,
|
|
21
|
-
type KVNamespace,
|
|
22
|
-
revisionKey,
|
|
23
|
-
snapshotKey,
|
|
24
|
-
} from "@decocms/blocks/cms";
|
|
25
|
-
|
|
26
|
-
export class KVBlockSource implements BlockSource {
|
|
27
|
-
private readonly snapshotKey: string;
|
|
28
|
-
private readonly revisionKey: string;
|
|
29
|
-
|
|
30
|
-
constructor(
|
|
31
|
-
private readonly kv: KVNamespace,
|
|
32
|
-
/** Deployment id (git commit sha) this source is scoped to. */
|
|
33
|
-
deploymentId: string,
|
|
34
|
-
) {
|
|
35
|
-
this.snapshotKey = snapshotKey(deploymentId);
|
|
36
|
-
this.revisionKey = revisionKey(deploymentId);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Read and parse this deployment's full decofile snapshot from KV.
|
|
41
|
-
*
|
|
42
|
-
* Returns `null` when no snapshot is present (key missing) so the caller
|
|
43
|
-
* keeps whatever blocks are already in memory (the bundled fallback).
|
|
44
|
-
*
|
|
45
|
-
* The stored revision is preferred; if it's absent we recompute it from the
|
|
46
|
-
* blocks so the result is always self-consistent. A malformed snapshot
|
|
47
|
-
* (invalid JSON / non-object) throws — the caller treats that as "KV
|
|
48
|
-
* unavailable" and falls back.
|
|
49
|
-
*/
|
|
50
|
-
async loadSnapshot(): Promise<BlockSnapshot | null> {
|
|
51
|
-
const raw = await this.kv.get(this.snapshotKey);
|
|
52
|
-
if (raw === null) return null;
|
|
53
|
-
|
|
54
|
-
const parsed = JSON.parse(raw) as unknown;
|
|
55
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
56
|
-
throw new Error(`[CMS/KV] ${this.snapshotKey} is not a JSON object`);
|
|
57
|
-
}
|
|
58
|
-
const blocks = parsed as Record<string, unknown>;
|
|
59
|
-
|
|
60
|
-
const storedRevision = await this.kv.get(this.revisionKey);
|
|
61
|
-
return { blocks, revision: storedRevision ?? computeRevision(blocks) };
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/** Cheap revision probe for change detection (no full snapshot transfer). */
|
|
65
|
-
getRevision(): Promise<string | null> {
|
|
66
|
-
return this.kv.get(this.revisionKey);
|
|
67
|
-
}
|
|
68
|
-
}
|
package/src/daemon/auth.ts
DELETED
|
@@ -1,204 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* JWT verification for admin.deco.cx requests.
|
|
3
|
-
* Uses Web Crypto only — no external dependencies.
|
|
4
|
-
*
|
|
5
|
-
* Ported from: deco-cx/deco daemon/auth.ts + commons/jwt/*
|
|
6
|
-
*/
|
|
7
|
-
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
8
|
-
|
|
9
|
-
// ---------------------------------------------------------------------------
|
|
10
|
-
// Public key — same key used by all sites (from commons/jwt/trusted.ts)
|
|
11
|
-
// ---------------------------------------------------------------------------
|
|
12
|
-
|
|
13
|
-
const ADMIN_PUBLIC_KEY =
|
|
14
|
-
process.env.DECO_ADMIN_PUBLIC_KEY ??
|
|
15
|
-
"eyJrdHkiOiJSU0EiLCJhbGciOiJSUzI1NiIsIm4iOiJ1N0Y3UklDN19Zc3ljTFhEYlBvQ1pUQnM2elZ6VjVPWkhXQ0M4akFZeFdPUnByem9WNDJDQ1JBVkVOVjJldzk1MnJOX2FTMmR3WDlmVGRvdk9zWl9jX2RVRXctdGlPN3hJLXd0YkxsanNUbUhoNFpiYXU0aUVoa0o1VGNHc2VaelhFYXNOSEhHdUo4SzY3WHluRHJSX0h4Ym9kQ2YxNFFJTmc5QnJjT3FNQmQyMUl4eUctVVhQampBTnRDTlNici1rXzFKeTZxNmtPeVJ1ZmV2Mjl0djA4Ykh5WDJQenp5Tnp3RWpjY0lROWpmSFdMN0JXX2tzdFpOOXU3TUtSLWJ4bjlSM0FKMEpZTHdXR3VnZGpNdVpBRnk0dm5BUXZzTk5Cd3p2YnFzMnZNd0dDTnF1ZE1tVmFudlNzQTJKYkE3Q0JoazI5TkRFTXRtUS1wbmo1cUlYSlEiLCJlIjoiQVFBQiIsImtleV9vcHMiOlsidmVyaWZ5Il0sImV4dCI6dHJ1ZX0";
|
|
16
|
-
|
|
17
|
-
const BYPASS_JWT =
|
|
18
|
-
process.env.DANGEROUSLY_ALLOW_PUBLIC_ACCESS === "true";
|
|
19
|
-
|
|
20
|
-
// ---------------------------------------------------------------------------
|
|
21
|
-
// JWT types
|
|
22
|
-
// ---------------------------------------------------------------------------
|
|
23
|
-
|
|
24
|
-
export interface JwtPayload {
|
|
25
|
-
[key: string]: unknown;
|
|
26
|
-
iss?: string;
|
|
27
|
-
sub?: string;
|
|
28
|
-
aud?: string | string[];
|
|
29
|
-
exp?: number;
|
|
30
|
-
nbf?: number;
|
|
31
|
-
iat?: number;
|
|
32
|
-
jti?: string;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
// ---------------------------------------------------------------------------
|
|
36
|
-
// Crypto helpers — ported from commons/jwt/keys.ts
|
|
37
|
-
// ---------------------------------------------------------------------------
|
|
38
|
-
|
|
39
|
-
const ALG = "RSASSA-PKCS1-v1_5";
|
|
40
|
-
const HASH = "SHA-256";
|
|
41
|
-
|
|
42
|
-
function parseJWK(b64: string): JsonWebKey {
|
|
43
|
-
return JSON.parse(atob(b64));
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
let cachedKey: Promise<CryptoKey> | null = null;
|
|
47
|
-
|
|
48
|
-
function getAdminPublicKey(): Promise<CryptoKey> {
|
|
49
|
-
cachedKey ??= crypto.subtle.importKey(
|
|
50
|
-
"jwk",
|
|
51
|
-
parseJWK(ADMIN_PUBLIC_KEY),
|
|
52
|
-
{ name: ALG, hash: HASH },
|
|
53
|
-
false,
|
|
54
|
-
["verify"],
|
|
55
|
-
);
|
|
56
|
-
return cachedKey;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
// ---------------------------------------------------------------------------
|
|
60
|
-
// JWT verification — ported from commons/jwt/jwt.ts
|
|
61
|
-
// ---------------------------------------------------------------------------
|
|
62
|
-
|
|
63
|
-
function base64UrlDecode(str: string): Uint8Array {
|
|
64
|
-
const b64 = str.replace(/-/g, "+").replace(/_/g, "/");
|
|
65
|
-
const pad = b64.length % 4 === 0 ? "" : "=".repeat(4 - (b64.length % 4));
|
|
66
|
-
const binary = atob(b64 + pad);
|
|
67
|
-
const bytes = new Uint8Array(binary.length);
|
|
68
|
-
for (let i = 0; i < binary.length; i++) {
|
|
69
|
-
bytes[i] = binary.charCodeAt(i);
|
|
70
|
-
}
|
|
71
|
-
return bytes;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
export async function verifyAdminJwt(
|
|
75
|
-
token: string,
|
|
76
|
-
): Promise<JwtPayload | null> {
|
|
77
|
-
const parts = token.split(".");
|
|
78
|
-
if (parts.length !== 3) return null;
|
|
79
|
-
|
|
80
|
-
const [headerB64, payloadB64, signatureB64] = parts;
|
|
81
|
-
const signingInput = new TextEncoder().encode(
|
|
82
|
-
`${headerB64}.${payloadB64}`,
|
|
83
|
-
);
|
|
84
|
-
const signature = base64UrlDecode(signatureB64);
|
|
85
|
-
|
|
86
|
-
try {
|
|
87
|
-
const key = await getAdminPublicKey();
|
|
88
|
-
const valid = await crypto.subtle.verify(
|
|
89
|
-
ALG,
|
|
90
|
-
key,
|
|
91
|
-
new Uint8Array(signature),
|
|
92
|
-
new Uint8Array(signingInput),
|
|
93
|
-
);
|
|
94
|
-
if (!valid) return null;
|
|
95
|
-
} catch {
|
|
96
|
-
return null;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
try {
|
|
100
|
-
const payload: JwtPayload = JSON.parse(
|
|
101
|
-
new TextDecoder().decode(base64UrlDecode(payloadB64)),
|
|
102
|
-
);
|
|
103
|
-
return payload;
|
|
104
|
-
} catch {
|
|
105
|
-
return null;
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
// ---------------------------------------------------------------------------
|
|
110
|
-
// URN matching — ported from commons/jwt/engine.ts
|
|
111
|
-
// ---------------------------------------------------------------------------
|
|
112
|
-
|
|
113
|
-
function matchPart(urnPart: string, otherPart: string): boolean {
|
|
114
|
-
return urnPart === "*" || otherPart === urnPart;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
function matchParts(urn: string[], resource: string[]): boolean {
|
|
118
|
-
return urn.every((part, idx) => matchPart(part, resource[idx]));
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
function matches(urnParts: string[]) {
|
|
122
|
-
return (resourceUrn: string) => {
|
|
123
|
-
const resourceParts = resourceUrn.split(":");
|
|
124
|
-
if (resourceParts.length > urnParts.length) return false;
|
|
125
|
-
const lastIdx = resourceParts.length - 1;
|
|
126
|
-
return resourceParts.every((part, idx) => {
|
|
127
|
-
if (part === "*") return true;
|
|
128
|
-
if (lastIdx === idx) {
|
|
129
|
-
return matchParts(part.split("/"), urnParts[idx].split("/"));
|
|
130
|
-
}
|
|
131
|
-
return part === urnParts[idx];
|
|
132
|
-
});
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
export function tokenIsValid(site: string, jwt: JwtPayload): boolean {
|
|
137
|
-
const { iss, sub, exp } = jwt;
|
|
138
|
-
if (!iss || !sub) return false;
|
|
139
|
-
if (exp && exp * 1000 <= Date.now()) return false;
|
|
140
|
-
const siteUrn = `urn:deco:site:*:${site}:deployment/*`;
|
|
141
|
-
return matches(sub.split(":"))(siteUrn);
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
// ---------------------------------------------------------------------------
|
|
145
|
-
// Auth middleware for Connect (Vite dev server)
|
|
146
|
-
// ---------------------------------------------------------------------------
|
|
147
|
-
|
|
148
|
-
function extractToken(req: IncomingMessage): string | null {
|
|
149
|
-
const auth = req.headers.authorization;
|
|
150
|
-
if (auth) {
|
|
151
|
-
const parts = auth.split(/\s+/);
|
|
152
|
-
if (parts.length === 2) return parts[1];
|
|
153
|
-
}
|
|
154
|
-
// Fallback: ?token= query param
|
|
155
|
-
try {
|
|
156
|
-
const url = new URL(req.url ?? "/", "http://localhost");
|
|
157
|
-
const t = url.searchParams.get("token");
|
|
158
|
-
if (t) return t;
|
|
159
|
-
} catch {
|
|
160
|
-
// ignore
|
|
161
|
-
}
|
|
162
|
-
return null;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
export type NextFn = () => void;
|
|
166
|
-
|
|
167
|
-
/**
|
|
168
|
-
* Returns a Connect-style middleware that verifies JWT on every request.
|
|
169
|
-
* If invalid, responds 401/403. If valid (or bypass enabled), calls next().
|
|
170
|
-
*/
|
|
171
|
-
export function createAuthMiddleware(site: string) {
|
|
172
|
-
return async (
|
|
173
|
-
req: IncomingMessage,
|
|
174
|
-
res: ServerResponse,
|
|
175
|
-
next: NextFn,
|
|
176
|
-
): Promise<void> => {
|
|
177
|
-
if (BYPASS_JWT) {
|
|
178
|
-
next();
|
|
179
|
-
return;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
const token = extractToken(req);
|
|
183
|
-
if (!token) {
|
|
184
|
-
res.writeHead(401);
|
|
185
|
-
res.end();
|
|
186
|
-
return;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
const jwt = await verifyAdminJwt(token);
|
|
190
|
-
if (!jwt) {
|
|
191
|
-
res.writeHead(401);
|
|
192
|
-
res.end();
|
|
193
|
-
return;
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
if (!tokenIsValid(site, jwt)) {
|
|
197
|
-
res.writeHead(403);
|
|
198
|
-
res.end();
|
|
199
|
-
return;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
next();
|
|
203
|
-
};
|
|
204
|
-
}
|