@adea-ai/app-framework 0.27.0 → 0.28.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 +177 -15
- package/dist/app/create-application.d.ts +2 -0
- package/dist/app/create-application.js +6 -0
- package/dist/app/service-registry.js +4 -0
- package/dist/appearance/custom-theme-import.js +43 -7
- package/dist/appearance/custom-theme-library.d.ts +2 -0
- package/dist/appearance/custom-theme-library.js +5 -1
- package/dist/appearance/theme-record-adapter.js +4 -2
- package/dist/appearance/theme-registry.js +7 -1
- package/dist/cli/create-application-cli.js +4 -2
- package/dist/cli/update-helper-cli.js +28 -6
- package/dist/desktop/client-asset-manifest.d.ts +47 -0
- package/dist/desktop/client-asset-manifest.js +114 -0
- package/dist/desktop/client-asset-stream.d.ts +10 -0
- package/dist/desktop/client-asset-stream.js +138 -33
- package/dist/desktop/client-assets.d.ts +20 -0
- package/dist/desktop/client-assets.js +132 -22
- package/dist/desktop/client-response-lifecycle.d.ts +22 -0
- package/dist/desktop/client-response-lifecycle.js +233 -0
- package/dist/desktop/desktop-host.d.ts +40 -2
- package/dist/desktop/desktop-host.js +159 -9
- package/dist/framework-source.json +1 -1
- package/dist/installer/command-artifact.d.ts +4 -2
- package/dist/installer/command-artifact.js +119 -19
- package/dist/installer/linux-process-group.d.ts +13 -0
- package/dist/installer/linux-process-group.js +58 -0
- package/dist/native/darwin-sync.d.ts +7 -0
- package/dist/native/darwin-sync.js +43 -0
- package/dist/native/desktop-build-hook.js +7 -0
- package/dist/native/directory-exchange.d.ts +10 -0
- package/dist/native/directory-exchange.js +90 -0
- package/dist/native/electrobun-source-patch.d.ts +5 -0
- package/dist/native/electrobun-source-patch.js +19 -1
- package/dist/native/posix-launcher-build.d.ts +24 -0
- package/dist/native/posix-launcher-build.js +232 -0
- package/dist/native/posix-tree-removal.d.ts +36 -0
- package/dist/native/posix-tree-removal.js +425 -0
- package/dist/update-helper.bundle.js +1483 -105
- package/dist/updates/channel-update-manager.d.ts +5 -0
- package/dist/updates/channel-update-manager.js +13 -1
- package/dist/updates/desktop-updater.d.ts +78 -2
- package/dist/updates/desktop-updater.js +320 -37
- package/dist/updates/launch-environment.d.ts +2 -0
- package/dist/updates/launch-environment.js +4 -0
- package/dist/updates/native-file-lock.d.ts +15 -0
- package/dist/updates/native-file-lock.js +189 -0
- package/dist/updates/packaged-launch-admission.d.ts +13 -0
- package/dist/updates/packaged-launch-admission.js +45 -0
- package/dist/updates/packaged-release-config.d.ts +18 -0
- package/dist/updates/packaged-release-config.js +60 -0
- package/dist/updates/packaged-update-startup.d.ts +44 -0
- package/dist/updates/packaged-update-startup.js +81 -0
- package/dist/updates/update-arm.d.ts +9 -8
- package/dist/updates/update-arm.js +227 -62
- package/dist/updates/update-cleanup-error.d.ts +23 -0
- package/dist/updates/update-cleanup-error.js +65 -0
- package/dist/updates/update-download-cleanup.d.ts +11 -0
- package/dist/updates/update-download-cleanup.js +112 -2
- package/dist/updates/update-download-lock.d.ts +20 -0
- package/dist/updates/update-download-lock.js +73 -0
- package/dist/updates/update-download.d.ts +2 -0
- package/dist/updates/update-download.js +7 -3
- package/dist/updates/update-generation-lease.d.ts +6 -0
- package/dist/updates/update-generation-lease.js +14 -0
- package/dist/updates/update-helper.d.ts +11 -2
- package/dist/updates/update-helper.js +322 -13
- package/dist/updates/update-inherited-launch-lease.d.ts +22 -0
- package/dist/updates/update-inherited-launch-lease.js +58 -0
- package/dist/updates/update-instance-lease.d.ts +15 -0
- package/dist/updates/update-instance-lease.js +25 -0
- package/dist/updates/update-launch-gate.d.ts +137 -0
- package/dist/updates/update-launch-gate.js +617 -0
- package/dist/updates/update-launch.js +3 -1
- package/dist/updates/update-lock.d.ts +12 -0
- package/dist/updates/update-lock.js +18 -0
- package/dist/updates/update-manager.d.ts +2 -0
- package/dist/updates/update-manager.js +9 -2
- package/dist/updates/update-marker.d.ts +7 -0
- package/dist/updates/update-marker.js +62 -0
- package/dist/updates/update-preflight-error.d.ts +7 -0
- package/dist/updates/update-preflight-error.js +11 -0
- package/dist/updates/update-process-fence.d.ts +4 -0
- package/dist/updates/update-process-fence.js +85 -73
- package/dist/updates/update-process-liveness.d.ts +2 -0
- package/dist/updates/update-process-liveness.js +11 -0
- package/dist/updates/update-resume.d.ts +37 -3
- package/dist/updates/update-resume.js +839 -23
- package/dist/updates/update-retention-marker.d.ts +67 -0
- package/dist/updates/update-retention-marker.js +165 -0
- package/dist/updates/update-retention-plan.d.ts +25 -0
- package/dist/updates/update-retention-plan.js +54 -0
- package/dist/updates/update-retention-sync.d.ts +34 -0
- package/dist/updates/update-retention-sync.js +83 -0
- package/dist/updates/update-retirement.d.ts +205 -0
- package/dist/updates/update-retirement.js +1485 -0
- package/dist/updates/update-shutdown.d.ts +16 -4
- package/dist/updates/update-shutdown.js +133 -8
- package/dist/updates/update-state-store.d.ts +58 -0
- package/dist/updates/update-state-store.js +139 -0
- package/dist/updates/update-swap-stage.d.ts +1 -1
- package/dist/updates/update-swap-stage.js +85 -14
- package/dist/updates/update-swap.d.ts +45 -2
- package/dist/updates/update-swap.js +207 -17
- package/package.json +31 -1
- package/src/appearance/custom-theme-import.ts +96 -14
- package/src/appearance/custom-theme-library.ts +5 -0
- package/src/appearance/theme-record-adapter.ts +15 -6
- package/src/appearance/theme-registry.ts +8 -1
- package/src/desktop/client-asset-manifest.ts +207 -0
- package/src/desktop/client-asset-stream.ts +193 -32
- package/src/desktop/client-assets.ts +210 -19
- package/src/desktop/client-response-lifecycle.ts +305 -0
- package/src/native/electrobun-posix-launch-lease.patch +398 -0
- package/templates/application/README.md +50 -0
- package/templates/application/electrobun.config.ts +5 -1
- package/templates/application/scripts/build-desktop.ts +4 -0
- package/templates/application/src/bun/index.ts +173 -16
- package/templates/application/vite.config.ts +112 -6
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { posix } from "node:path";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
// src/desktop/client-asset-manifest.ts
|
|
4
|
+
var CLIENT_ASSET_MANIFEST_FILE = "client-assets-manifest.json";
|
|
5
|
+
var CLIENT_ASSET_ASSET_PATTERN = "assets/[name]-[hash][extname]";
|
|
6
|
+
var CLIENT_ASSET_CHUNK_PATTERN = "assets/[name]-[hash].js";
|
|
7
|
+
var FORMAT = "adea-client-assets-v1";
|
|
8
|
+
/** Build a cache allowlist from Vite's actual output bundle and explicit Rollup names. */
|
|
9
|
+
function createClientAssetManifest(bundle, output, namingEvidence) {
|
|
10
|
+
if ([
|
|
11
|
+
output.assetFileNames,
|
|
12
|
+
output.chunkFileNames,
|
|
13
|
+
output.entryFileNames
|
|
14
|
+
].some((pattern) => typeof pattern !== "string" || !pattern.includes("[hash]"))) throw new Error("Client asset caching requires explicit [hash] output names");
|
|
15
|
+
const assets = [];
|
|
16
|
+
const paths = /* @__PURE__ */ new Set();
|
|
17
|
+
const outputEvidenceCounts = /* @__PURE__ */ new Map();
|
|
18
|
+
for (const item of Object.values(bundle)) {
|
|
19
|
+
const evidence = item.type === "asset" ? clientAssetAssetEvidenceKey(item) : clientAssetChunkEvidenceKey(item);
|
|
20
|
+
outputEvidenceCounts.set(evidence, (outputEvidenceCounts.get(evidence) ?? 0) + 1);
|
|
21
|
+
}
|
|
22
|
+
for (const item of Object.values(bundle)) {
|
|
23
|
+
if (item.fileName.toLowerCase().endsWith(".html") || item.fileName.toLowerCase().endsWith(".map")) continue;
|
|
24
|
+
if (!item.fileName.startsWith("assets/")) continue;
|
|
25
|
+
const pattern = item.type === "asset" ? output.assetFileNames : item.isEntry ? output.entryFileNames : output.chunkFileNames;
|
|
26
|
+
const evidence = item.type === "asset" ? clientAssetAssetEvidenceKey(item) : clientAssetChunkEvidenceKey(item);
|
|
27
|
+
if (namingEvidence.get(evidence) !== 1 || outputEvidenceCounts.get(evidence) !== 1 || !matchesConfiguredHashedName(item, pattern)) continue;
|
|
28
|
+
const path = `/${item.fileName}`;
|
|
29
|
+
if (paths.has(path)) throw new Error("Duplicate client asset manifest path");
|
|
30
|
+
paths.add(path);
|
|
31
|
+
assets.push({
|
|
32
|
+
path,
|
|
33
|
+
sha256: createHash("sha256").update(item.type === "chunk" ? item.code : item.source).digest("hex")
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
const sortedAssets = [...assets];
|
|
37
|
+
sortedAssets.sort((left, right) => left.path.localeCompare(right.path));
|
|
38
|
+
return {
|
|
39
|
+
format: FORMAT,
|
|
40
|
+
assets: sortedAssets
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/** Evidence keys for Rollup naming callbacks; explicit `fileName` outputs never call them. */
|
|
44
|
+
function clientAssetChunkEvidenceKey(chunk) {
|
|
45
|
+
const moduleIds = [...chunk.moduleIds ?? []];
|
|
46
|
+
moduleIds.sort();
|
|
47
|
+
return `chunk:${JSON.stringify([
|
|
48
|
+
chunk.name,
|
|
49
|
+
chunk.isEntry,
|
|
50
|
+
chunk.facadeModuleId ?? null,
|
|
51
|
+
moduleIds
|
|
52
|
+
])}`;
|
|
53
|
+
}
|
|
54
|
+
function clientAssetAssetEvidenceKey(asset) {
|
|
55
|
+
return `asset:${JSON.stringify([asset.name ?? null])}`;
|
|
56
|
+
}
|
|
57
|
+
/** Parse a complete manifest. Any malformed or duplicate entry disables the whole allowlist. */
|
|
58
|
+
function parseClientAssetManifest(input) {
|
|
59
|
+
let value = input;
|
|
60
|
+
if (typeof value === "string") try {
|
|
61
|
+
value = JSON.parse(value);
|
|
62
|
+
} catch {
|
|
63
|
+
return /* @__PURE__ */ new Map();
|
|
64
|
+
}
|
|
65
|
+
if (!value || typeof value !== "object" || value.format !== FORMAT || !Array.isArray(value.assets) || value.assets.length > 1e4) return /* @__PURE__ */ new Map();
|
|
66
|
+
const entries = /* @__PURE__ */ new Map();
|
|
67
|
+
for (const asset of value.assets) {
|
|
68
|
+
if (!asset || typeof asset !== "object") return /* @__PURE__ */ new Map();
|
|
69
|
+
const { path, sha256 } = asset;
|
|
70
|
+
if (typeof path !== "string" || typeof sha256 !== "string" || !isImmutableClientAssetPath(path) || !/^[a-f0-9]{64}$/.test(sha256) || entries.has(path)) return /* @__PURE__ */ new Map();
|
|
71
|
+
entries.set(path, sha256);
|
|
72
|
+
}
|
|
73
|
+
return entries;
|
|
74
|
+
}
|
|
75
|
+
/** Snapshot a caller-provided allowlist and reject it as a whole if any entry is invalid. */
|
|
76
|
+
function snapshotClientAssetAllowlist(value) {
|
|
77
|
+
if (value === void 0) return /* @__PURE__ */ new Map();
|
|
78
|
+
try {
|
|
79
|
+
const assets = [];
|
|
80
|
+
for (const [path, sha256] of value) {
|
|
81
|
+
if (assets.length === 1e4) return /* @__PURE__ */ new Map();
|
|
82
|
+
assets.push({
|
|
83
|
+
path,
|
|
84
|
+
sha256
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
return parseClientAssetManifest({
|
|
88
|
+
format: FORMAT,
|
|
89
|
+
assets
|
|
90
|
+
});
|
|
91
|
+
} catch {
|
|
92
|
+
return /* @__PURE__ */ new Map();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function isImmutableClientAssetPath(path) {
|
|
96
|
+
if (!path.startsWith("/assets/") || path.includes("\\") || path.includes("\0") || path.includes("%") || path.includes("?") || path.includes("#") || path.endsWith("/") || path.toLowerCase().endsWith(".map") || path.toLowerCase().endsWith(".html") || posix.normalize(path) !== path) return false;
|
|
97
|
+
return !path.slice(1).split("/").some((part) => part === "." || part === ".." || part === "");
|
|
98
|
+
}
|
|
99
|
+
/** Match only filenames produced by the supported explicit [name]-[hash] patterns. */
|
|
100
|
+
function matchesConfiguredHashedName(item, pattern) {
|
|
101
|
+
const name = item.name;
|
|
102
|
+
if (!name || name.includes("/") || name.includes("\\")) return false;
|
|
103
|
+
const prefix = `assets/${item.type === "chunk" ? name : name.replace(/\.[^.]+$/, "")}-`;
|
|
104
|
+
const suffix = item.type === "chunk" ? ".js" : extname$1(name);
|
|
105
|
+
if (pattern !== (item.type === "chunk" ? "assets/[name]-[hash].js" : "assets/[name]-[hash][extname]") || !suffix) return false;
|
|
106
|
+
if (!item.fileName.startsWith(prefix) || !item.fileName.endsWith(suffix)) return false;
|
|
107
|
+
const hash = item.fileName.slice(prefix.length, -suffix.length);
|
|
108
|
+
return hash.length > 0 && !hash.includes("/") && !hash.includes(".");
|
|
109
|
+
}
|
|
110
|
+
function extname$1(value) {
|
|
111
|
+
const index = value.lastIndexOf(".");
|
|
112
|
+
return index <= 0 ? "" : value.slice(index);
|
|
113
|
+
}
|
|
114
|
+
export { CLIENT_ASSET_ASSET_PATTERN, CLIENT_ASSET_CHUNK_PATTERN, CLIENT_ASSET_MANIFEST_FILE, clientAssetAssetEvidenceKey, clientAssetChunkEvidenceKey, createClientAssetManifest, parseClientAssetManifest, snapshotClientAssetAllowlist };
|
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
import type { Stats } from 'node:fs';
|
|
2
2
|
import { type FileHandle } from 'node:fs/promises';
|
|
3
|
+
export type ClientAssetVerificationCache = {
|
|
4
|
+
has(path: string, metadata: Stats, sha256: string): boolean;
|
|
5
|
+
remember(path: string, metadata: Stats, sha256: string): void;
|
|
6
|
+
};
|
|
7
|
+
/** Share concurrent checks only for the same cache, file identity, and expected digest. */
|
|
8
|
+
export declare function verifyClientAssetCached(cache: ClientAssetVerificationCache, path: string, metadata: Stats, sha256: string, verify: () => Promise<boolean>): Promise<boolean>;
|
|
9
|
+
/** Keep successful content checks only while the file identity remains unchanged. */
|
|
10
|
+
export declare function createClientAssetVerificationCache(maxEntries?: number): ClientAssetVerificationCache;
|
|
3
11
|
type AssetFile = Pick<FileHandle, 'close' | 'stat' | 'read'>;
|
|
4
12
|
type OpenAsset = (path: string, flags: 'r') => Promise<AssetFile>;
|
|
5
13
|
/**
|
|
@@ -7,4 +15,6 @@ type OpenAsset = (path: string, flags: 'r') => Promise<AssetFile>;
|
|
|
7
15
|
* fail the stream, and a read error can surface after response headers have been sent.
|
|
8
16
|
*/
|
|
9
17
|
export declare function createClientAssetStream(path: string, expected: Stats, openAsset?: OpenAsset): ReadableStream<Uint8Array>;
|
|
18
|
+
/** Verify an opted-in asset before sending immutable cache headers without buffering it. */
|
|
19
|
+
export declare function verifyClientAssetDigest(path: string, expected: Stats, expectedSha256: string, openAsset?: OpenAsset): Promise<boolean>;
|
|
10
20
|
export {};
|
|
@@ -1,10 +1,74 @@
|
|
|
1
1
|
import { open } from "node:fs/promises";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
2
3
|
import { Buffer } from "node:buffer";
|
|
3
4
|
// src/desktop/client-asset-stream.ts
|
|
4
5
|
var FILE_CHUNK_BYTES = 65536;
|
|
5
6
|
function sameFile(expected, actual) {
|
|
6
7
|
return actual.isFile() && expected.dev === actual.dev && expected.ino === actual.ino && expected.size === actual.size && expected.mtimeMs === actual.mtimeMs && expected.ctimeMs === actual.ctimeMs;
|
|
7
8
|
}
|
|
9
|
+
var pendingVerifications = /* @__PURE__ */ new WeakMap();
|
|
10
|
+
/** Share concurrent checks only for the same cache, file identity, and expected digest. */
|
|
11
|
+
async function verifyClientAssetCached(cache, path, metadata, sha256, verify) {
|
|
12
|
+
if (cache.has(path, metadata, sha256)) return true;
|
|
13
|
+
let pending = pendingVerifications.get(cache);
|
|
14
|
+
if (!pending) {
|
|
15
|
+
pending = /* @__PURE__ */ new Map();
|
|
16
|
+
pendingVerifications.set(cache, pending);
|
|
17
|
+
}
|
|
18
|
+
const key = JSON.stringify([
|
|
19
|
+
path,
|
|
20
|
+
metadata.dev,
|
|
21
|
+
metadata.ino,
|
|
22
|
+
metadata.size,
|
|
23
|
+
metadata.mtimeMs,
|
|
24
|
+
metadata.ctimeMs,
|
|
25
|
+
sha256
|
|
26
|
+
]);
|
|
27
|
+
const existing = pending.get(key);
|
|
28
|
+
if (existing) return existing;
|
|
29
|
+
const tasks = pending;
|
|
30
|
+
const task = Promise.resolve().then(verify).then((matched) => {
|
|
31
|
+
if (matched) cache.remember(path, metadata, sha256);
|
|
32
|
+
return matched;
|
|
33
|
+
}).finally(() => {
|
|
34
|
+
tasks.delete(key);
|
|
35
|
+
if (tasks.size === 0) pendingVerifications.delete(cache);
|
|
36
|
+
});
|
|
37
|
+
tasks.set(key, task);
|
|
38
|
+
return task;
|
|
39
|
+
}
|
|
40
|
+
/** Keep successful content checks only while the file identity remains unchanged. */
|
|
41
|
+
function createClientAssetVerificationCache(maxEntries = 256) {
|
|
42
|
+
if (!Number.isInteger(maxEntries) || maxEntries < 1 || maxEntries > 1e4) throw new Error("Invalid client asset verification cache size");
|
|
43
|
+
const entries = /* @__PURE__ */ new Map();
|
|
44
|
+
const sameIdentity = (expected, actual, sha256) => actual.isFile() && expected.dev === actual.dev && expected.ino === actual.ino && expected.size === actual.size && expected.mtimeMs === actual.mtimeMs && expected.ctimeMs === actual.ctimeMs && expected.sha256 === sha256;
|
|
45
|
+
return {
|
|
46
|
+
has(path, metadata, sha256) {
|
|
47
|
+
const entry = entries.get(path);
|
|
48
|
+
if (!entry) return false;
|
|
49
|
+
if (!sameIdentity(entry, metadata, sha256)) {
|
|
50
|
+
entries.delete(path);
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
entries.delete(path);
|
|
54
|
+
entries.set(path, entry);
|
|
55
|
+
return true;
|
|
56
|
+
},
|
|
57
|
+
remember(path, metadata, sha256) {
|
|
58
|
+
if (!metadata.isFile() || !/^[a-f0-9]{64}$/.test(sha256)) return;
|
|
59
|
+
entries.delete(path);
|
|
60
|
+
entries.set(path, {
|
|
61
|
+
dev: metadata.dev,
|
|
62
|
+
ino: metadata.ino,
|
|
63
|
+
size: metadata.size,
|
|
64
|
+
mtimeMs: metadata.mtimeMs,
|
|
65
|
+
ctimeMs: metadata.ctimeMs,
|
|
66
|
+
sha256
|
|
67
|
+
});
|
|
68
|
+
while (entries.size > maxEntries) entries.delete(entries.keys().next().value);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
}
|
|
8
72
|
/**
|
|
9
73
|
* Stream an immutable bundled asset. This is not a snapshot: detected file changes
|
|
10
74
|
* fail the stream, and a read error can surface after response headers have been sent.
|
|
@@ -13,6 +77,9 @@ function createClientAssetStream(path, expected, openAsset = open) {
|
|
|
13
77
|
let file;
|
|
14
78
|
let opening;
|
|
15
79
|
let closing;
|
|
80
|
+
let pulling;
|
|
81
|
+
let closeFailed = false;
|
|
82
|
+
let closeFailure;
|
|
16
83
|
let cancelled = false;
|
|
17
84
|
let offset = 0;
|
|
18
85
|
const close = () => {
|
|
@@ -20,7 +87,11 @@ function createClientAssetStream(path, expected, openAsset = open) {
|
|
|
20
87
|
const current = file;
|
|
21
88
|
file = void 0;
|
|
22
89
|
if (!current) return Promise.resolve();
|
|
23
|
-
const pending = current.close()
|
|
90
|
+
const pending = current.close().catch((error) => {
|
|
91
|
+
closeFailed = true;
|
|
92
|
+
closeFailure = error;
|
|
93
|
+
throw error;
|
|
94
|
+
});
|
|
24
95
|
closing = pending;
|
|
25
96
|
const clear = () => {
|
|
26
97
|
if (closing === pending) closing = void 0;
|
|
@@ -34,7 +105,13 @@ function createClientAssetStream(path, expected, openAsset = open) {
|
|
|
34
105
|
const pending = (async () => {
|
|
35
106
|
const opened = await openAsset(path, "r");
|
|
36
107
|
if (cancelled) {
|
|
37
|
-
|
|
108
|
+
try {
|
|
109
|
+
await opened.close();
|
|
110
|
+
} catch (error) {
|
|
111
|
+
closeFailed = true;
|
|
112
|
+
closeFailure = error;
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
38
115
|
return;
|
|
39
116
|
}
|
|
40
117
|
file = opened;
|
|
@@ -51,47 +128,75 @@ function createClientAssetStream(path, expected, openAsset = open) {
|
|
|
51
128
|
return pending;
|
|
52
129
|
};
|
|
53
130
|
return new ReadableStream({
|
|
54
|
-
|
|
131
|
+
pull(controller) {
|
|
55
132
|
if (cancelled) return;
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const current = file;
|
|
60
|
-
if (!current) return;
|
|
61
|
-
if (offset === expected.size) {
|
|
62
|
-
const actual = await current.stat();
|
|
133
|
+
const pending = (async () => {
|
|
134
|
+
try {
|
|
135
|
+
await ensureOpen();
|
|
63
136
|
if (cancelled) return;
|
|
64
|
-
|
|
65
|
-
|
|
137
|
+
const current = file;
|
|
138
|
+
if (!current) return;
|
|
139
|
+
if (offset === expected.size) {
|
|
140
|
+
const actual = await current.stat();
|
|
141
|
+
if (cancelled) return;
|
|
142
|
+
if (!sameFile(expected, actual)) throw new Error("Client asset changed during request");
|
|
143
|
+
await close();
|
|
144
|
+
if (cancelled) return;
|
|
145
|
+
controller.close();
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const buffer = Buffer.allocUnsafe(Math.min(FILE_CHUNK_BYTES, expected.size - offset));
|
|
149
|
+
const { bytesRead } = await current.read(buffer, 0, buffer.length, offset);
|
|
66
150
|
if (cancelled) return;
|
|
67
|
-
|
|
68
|
-
|
|
151
|
+
if (!bytesRead) throw new Error("Client asset changed during request");
|
|
152
|
+
offset += bytesRead;
|
|
153
|
+
if (offset === expected.size) {
|
|
154
|
+
const actual = await current.stat();
|
|
155
|
+
if (cancelled) return;
|
|
156
|
+
if (!sameFile(expected, actual)) throw new Error("Client asset changed during request");
|
|
157
|
+
await close();
|
|
158
|
+
if (cancelled) return;
|
|
159
|
+
controller.enqueue(buffer.subarray(0, bytesRead));
|
|
160
|
+
controller.close();
|
|
161
|
+
} else controller.enqueue(buffer.subarray(0, bytesRead));
|
|
162
|
+
} catch (error) {
|
|
163
|
+
await close().catch(() => {});
|
|
164
|
+
if (!cancelled) controller.error(error);
|
|
69
165
|
}
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
if (offset === expected.size) {
|
|
76
|
-
const actual = await current.stat();
|
|
77
|
-
if (cancelled) return;
|
|
78
|
-
if (!sameFile(expected, actual)) throw new Error("Client asset changed during request");
|
|
79
|
-
await close();
|
|
80
|
-
if (cancelled) return;
|
|
81
|
-
controller.enqueue(buffer.subarray(0, bytesRead));
|
|
82
|
-
controller.close();
|
|
83
|
-
} else controller.enqueue(buffer.subarray(0, bytesRead));
|
|
84
|
-
} catch (error) {
|
|
85
|
-
await close().catch(() => {});
|
|
86
|
-
if (!cancelled) controller.error(error);
|
|
87
|
-
}
|
|
166
|
+
})().finally(() => {
|
|
167
|
+
if (pulling === pending) pulling = void 0;
|
|
168
|
+
});
|
|
169
|
+
pulling = pending;
|
|
170
|
+
return pending;
|
|
88
171
|
},
|
|
89
172
|
async cancel() {
|
|
90
173
|
cancelled = true;
|
|
91
174
|
const pending = opening;
|
|
92
175
|
if (pending) await pending.catch(() => {});
|
|
176
|
+
const activePull = pulling;
|
|
177
|
+
if (activePull) await activePull.catch(() => {});
|
|
93
178
|
await close();
|
|
179
|
+
if (closeFailed) throw closeFailure;
|
|
94
180
|
}
|
|
95
181
|
}, { highWaterMark: 0 });
|
|
96
182
|
}
|
|
97
|
-
|
|
183
|
+
/** Verify an opted-in asset before sending immutable cache headers without buffering it. */
|
|
184
|
+
async function verifyClientAssetDigest(path, expected, expectedSha256, openAsset = open) {
|
|
185
|
+
const file = await openAsset(path, "r");
|
|
186
|
+
try {
|
|
187
|
+
if (!sameFile(expected, await file.stat())) return false;
|
|
188
|
+
const hash = createHash("sha256");
|
|
189
|
+
const buffer = Buffer.allocUnsafe(FILE_CHUNK_BYTES);
|
|
190
|
+
let offset = 0;
|
|
191
|
+
while (offset < expected.size) {
|
|
192
|
+
const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, expected.size - offset), offset);
|
|
193
|
+
if (!bytesRead) return false;
|
|
194
|
+
hash.update(buffer.subarray(0, bytesRead));
|
|
195
|
+
offset += bytesRead;
|
|
196
|
+
}
|
|
197
|
+
return sameFile(expected, await file.stat()) && hash.digest("hex") === expectedSha256;
|
|
198
|
+
} finally {
|
|
199
|
+
await file.close();
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
export { createClientAssetStream, createClientAssetVerificationCache, verifyClientAssetCached, verifyClientAssetDigest };
|
|
@@ -1,9 +1,29 @@
|
|
|
1
|
+
import { type ClientAssetVerificationCache } from './client-asset-stream';
|
|
2
|
+
export { createClientAssetVerificationCache, type ClientAssetVerificationCache, } from './client-asset-stream';
|
|
3
|
+
export { CLIENT_ASSET_ASSET_PATTERN, CLIENT_ASSET_CHUNK_PATTERN, CLIENT_ASSET_MANIFEST_FILE, clientAssetAssetEvidenceKey, clientAssetChunkEvidenceKey, createClientAssetManifest, parseClientAssetManifest, snapshotClientAssetAllowlist, type ClientAssetManifest, } from './client-asset-manifest';
|
|
1
4
|
export type ClientOptions = {
|
|
2
5
|
root: string;
|
|
3
6
|
deniedPaths?: readonly string[];
|
|
4
7
|
transformHtml?: (html: string, request: Request) => string;
|
|
5
8
|
/** Stream GET bodies instead of buffered snapshots. Use only for immutable asset roots. */
|
|
6
9
|
streamAssets?: boolean;
|
|
10
|
+
/** Explicit URL path to SHA-256 allowlist from a generated client asset manifest. */
|
|
11
|
+
immutableAssets?: ReadonlyMap<string, string>;
|
|
12
|
+
/** Bounded, host-lifetime cache of successful checks for unchanged immutable files. */
|
|
13
|
+
verificationCache?: ClientAssetVerificationCache;
|
|
7
14
|
};
|
|
15
|
+
/** A caller-owned, immutable client root kept available for the resolver's lifetime. */
|
|
16
|
+
export type RetainedClientAssetRoot = Readonly<{
|
|
17
|
+
root: string;
|
|
18
|
+
immutableAssets: ReadonlyMap<string, string>;
|
|
19
|
+
}>;
|
|
20
|
+
/**
|
|
21
|
+
* Resolve current assets first, then explicitly retained, content-verified assets.
|
|
22
|
+
* The caller owns every retained root and must keep it immutable and available
|
|
23
|
+
* until the host and every response body using it have stopped.
|
|
24
|
+
*/
|
|
25
|
+
export declare function createClientAssetResolver(options: ClientOptions, retained?: readonly RetainedClientAssetRoot[]): (request: Request) => Promise<Response>;
|
|
26
|
+
/** Missing or invalid manifests disable immutable caching without disrupting the app. */
|
|
27
|
+
export declare function loadClientAssetManifest(path: string): Promise<ReadonlyMap<string, string>>;
|
|
8
28
|
/** Serve a bundled SPA without resolving links outside its root. */
|
|
9
29
|
export declare function serveClient(request: Request, options: ClientOptions): Promise<Response>;
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { CLIENT_ASSET_ASSET_PATTERN, CLIENT_ASSET_CHUNK_PATTERN, CLIENT_ASSET_MANIFEST_FILE, clientAssetAssetEvidenceKey, clientAssetChunkEvidenceKey, createClientAssetManifest, parseClientAssetManifest, snapshotClientAssetAllowlist } from "./client-asset-manifest.js";
|
|
2
|
+
import { createClientAssetStream, createClientAssetVerificationCache, verifyClientAssetCached, verifyClientAssetDigest } from "./client-asset-stream.js";
|
|
3
|
+
import { open, readFile, realpath, stat } from "node:fs/promises";
|
|
3
4
|
import { extname, join, posix, relative, resolve, sep } from "node:path";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
4
6
|
// src/desktop/client-assets.ts
|
|
5
7
|
var MIME = {
|
|
6
8
|
".html": "text/html",
|
|
@@ -10,6 +12,12 @@ var MIME = {
|
|
|
10
12
|
".svg": "image/svg+xml",
|
|
11
13
|
".json": "application/json",
|
|
12
14
|
".png": "image/png",
|
|
15
|
+
".jpg": "image/jpeg",
|
|
16
|
+
".jpeg": "image/jpeg",
|
|
17
|
+
".gif": "image/gif",
|
|
18
|
+
".webp": "image/webp",
|
|
19
|
+
".avif": "image/avif",
|
|
20
|
+
".webmanifest": "application/manifest+json",
|
|
13
21
|
".ico": "image/x-icon",
|
|
14
22
|
".woff2": "font/woff2",
|
|
15
23
|
".wasm": "application/wasm"
|
|
@@ -18,8 +26,102 @@ var unavailable = (status = 404) => new Response(null, {
|
|
|
18
26
|
status,
|
|
19
27
|
headers: { "cache-control": "no-store" }
|
|
20
28
|
});
|
|
29
|
+
var IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable";
|
|
30
|
+
function clientPath(request) {
|
|
31
|
+
try {
|
|
32
|
+
const path = posix.normalize("/" + decodeURIComponent(new URL(request.url).pathname).replaceAll("\\", "/"));
|
|
33
|
+
return path.includes("\0") ? void 0 : path;
|
|
34
|
+
} catch {
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Resolve current assets first, then explicitly retained, content-verified assets.
|
|
40
|
+
* The caller owns every retained root and must keep it immutable and available
|
|
41
|
+
* until the host and every response body using it have stopped.
|
|
42
|
+
*/
|
|
43
|
+
function createClientAssetResolver(options, retained = []) {
|
|
44
|
+
if (!Array.isArray(retained) || retained.length > 32) throw new Error("Invalid retained client asset roots");
|
|
45
|
+
const primaryAssets = new Map(snapshotClientAssetAllowlist(options.immutableAssets));
|
|
46
|
+
const candidates = /* @__PURE__ */ new Map();
|
|
47
|
+
for (const item of retained) {
|
|
48
|
+
if (!item || typeof item.root !== "string" || !item.root) throw new Error("Invalid retained client asset root");
|
|
49
|
+
const assets = snapshotClientAssetAllowlist(item.immutableAssets);
|
|
50
|
+
const candidate = {
|
|
51
|
+
root: item.root,
|
|
52
|
+
assets
|
|
53
|
+
};
|
|
54
|
+
for (const [path, digest] of assets) {
|
|
55
|
+
const existing = primaryAssets.get(path);
|
|
56
|
+
if (existing !== void 0 && existing !== digest) throw new Error("Conflicting retained client asset digest");
|
|
57
|
+
primaryAssets.set(path, digest);
|
|
58
|
+
const roots = candidates.get(path) ?? [];
|
|
59
|
+
roots.push(candidate);
|
|
60
|
+
candidates.set(path, roots);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const primary = {
|
|
64
|
+
...options,
|
|
65
|
+
immutableAssets: primaryAssets,
|
|
66
|
+
...options.deniedPaths ? { deniedPaths: [...options.deniedPaths] } : {}
|
|
67
|
+
};
|
|
68
|
+
if (!candidates.size) return (request) => serveClient(request, primary);
|
|
69
|
+
return async (request) => {
|
|
70
|
+
const path = clientPath(request);
|
|
71
|
+
const roots = path && (request.method === "GET" || request.method === "HEAD") ? candidates.get(path) : void 0;
|
|
72
|
+
if (!roots) return serveClient(request, primary);
|
|
73
|
+
const resolveRetained = async () => {
|
|
74
|
+
for (const candidate of roots) {
|
|
75
|
+
let previous;
|
|
76
|
+
try {
|
|
77
|
+
previous = await serveClient(request, {
|
|
78
|
+
...primary,
|
|
79
|
+
root: candidate.root,
|
|
80
|
+
immutableAssets: candidate.assets
|
|
81
|
+
});
|
|
82
|
+
} catch {
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (previous.status === 200 && previous.headers.get("cache-control") === IMMUTABLE_CACHE_CONTROL) return previous;
|
|
86
|
+
await previous.body?.cancel();
|
|
87
|
+
}
|
|
88
|
+
return unavailable();
|
|
89
|
+
};
|
|
90
|
+
let activeRootMissing = false;
|
|
91
|
+
const response = await serveClientInternal(request, primary, async () => {
|
|
92
|
+
activeRootMissing = true;
|
|
93
|
+
return resolveRetained();
|
|
94
|
+
});
|
|
95
|
+
if (activeRootMissing) return response;
|
|
96
|
+
if (response.status !== 404) {
|
|
97
|
+
if (response.status !== 200 || response.headers.get("cache-control") === IMMUTABLE_CACHE_CONTROL) return response;
|
|
98
|
+
await response.body?.cancel();
|
|
99
|
+
return unavailable();
|
|
100
|
+
}
|
|
101
|
+
return resolveRetained();
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
async function matchesManifestDigest(path, metadata, sha256, verificationCache) {
|
|
105
|
+
try {
|
|
106
|
+
const verify = () => verifyClientAssetDigest(path, metadata, sha256);
|
|
107
|
+
return verificationCache ? await verifyClientAssetCached(verificationCache, path, metadata, sha256, verify) : await verify();
|
|
108
|
+
} catch {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/** Missing or invalid manifests disable immutable caching without disrupting the app. */
|
|
113
|
+
async function loadClientAssetManifest(path) {
|
|
114
|
+
try {
|
|
115
|
+
return parseClientAssetManifest(await readFile(path, "utf8"));
|
|
116
|
+
} catch {
|
|
117
|
+
return /* @__PURE__ */ new Map();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
21
120
|
/** Serve a bundled SPA without resolving links outside its root. */
|
|
22
121
|
async function serveClient(request, options) {
|
|
122
|
+
return serveClientInternal(request, options);
|
|
123
|
+
}
|
|
124
|
+
async function serveClientInternal(request, options, onMissingRoot) {
|
|
23
125
|
if (request.method !== "GET" && request.method !== "HEAD") return new Response(null, {
|
|
24
126
|
status: 405,
|
|
25
127
|
headers: {
|
|
@@ -27,20 +129,21 @@ async function serveClient(request, options) {
|
|
|
27
129
|
"cache-control": "no-store"
|
|
28
130
|
}
|
|
29
131
|
});
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
logical = posix.normalize("/" + decodeURIComponent(new URL(request.url).pathname).replaceAll("\\", "/"));
|
|
33
|
-
} catch {
|
|
34
|
-
return unavailable();
|
|
35
|
-
}
|
|
36
|
-
if (logical.includes("\0")) return unavailable();
|
|
132
|
+
const logical = clientPath(request);
|
|
133
|
+
if (logical === void 0) return unavailable();
|
|
37
134
|
const denied = (path) => (options.deniedPaths ?? []).some((item) => {
|
|
38
135
|
const prefix = posix.normalize("/" + item.replaceAll("\\", "/")).toLowerCase().replace(/\/$/, "") || "/";
|
|
39
136
|
const folded = path.toLowerCase();
|
|
40
137
|
return prefix === "/" || folded === prefix || folded.startsWith(prefix + "/");
|
|
41
138
|
});
|
|
42
139
|
if (denied(logical)) return unavailable();
|
|
43
|
-
|
|
140
|
+
let root;
|
|
141
|
+
try {
|
|
142
|
+
root = await realpath(options.root);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
if (onMissingRoot && error.code === "ENOENT") return onMissingRoot();
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
44
147
|
let filePath = resolve(root, "." + logical);
|
|
45
148
|
const inside = (path) => path === root || path.startsWith(root + sep);
|
|
46
149
|
if (!inside(filePath)) return unavailable(403);
|
|
@@ -62,33 +165,40 @@ async function serveClient(request, options) {
|
|
|
62
165
|
if (denied("/" + relative(root, physical).replaceAll("\\", "/"))) return unavailable();
|
|
63
166
|
const extension = extname(physical).toLowerCase();
|
|
64
167
|
const contentType = MIME[extension] ?? "application/octet-stream";
|
|
168
|
+
const configuredSha256 = options.immutableAssets?.get(logical);
|
|
169
|
+
const immutableSha256 = extension !== ".html" && extension !== ".map" && typeof configuredSha256 === "string" && /^[a-f0-9]{64}$/.test(configuredSha256) ? configuredSha256 : void 0;
|
|
65
170
|
if (request.method === "HEAD" && !(extension === ".html" && options.transformHtml)) {
|
|
66
171
|
const file = await open(physical, "r");
|
|
67
|
-
let
|
|
172
|
+
let fileMetadata;
|
|
68
173
|
try {
|
|
69
|
-
|
|
174
|
+
fileMetadata = await file.stat();
|
|
70
175
|
if (!fileMetadata.isFile()) return unavailable();
|
|
71
|
-
size = fileMetadata.size;
|
|
72
176
|
} finally {
|
|
73
177
|
await file.close();
|
|
74
178
|
}
|
|
179
|
+
const cacheVerified = immutableSha256 !== void 0 && await matchesManifestDigest(physical, fileMetadata, immutableSha256, options.verificationCache);
|
|
75
180
|
return new Response(null, { headers: {
|
|
76
181
|
"content-type": contentType,
|
|
77
|
-
"content-length": String(size),
|
|
78
|
-
"cache-control": "no-store"
|
|
182
|
+
"content-length": String(fileMetadata.size),
|
|
183
|
+
"cache-control": cacheVerified ? IMMUTABLE_CACHE_CONTROL : "no-store"
|
|
184
|
+
} });
|
|
185
|
+
}
|
|
186
|
+
if (options.streamAssets === true && request.method === "GET" && !(extension === ".html" && options.transformHtml)) {
|
|
187
|
+
const cacheVerified = immutableSha256 !== void 0 && await matchesManifestDigest(physical, metadata, immutableSha256, options.verificationCache);
|
|
188
|
+
return new Response(createClientAssetStream(physical, metadata), { headers: {
|
|
189
|
+
"content-type": contentType,
|
|
190
|
+
"cache-control": cacheVerified ? IMMUTABLE_CACHE_CONTROL : "no-store",
|
|
191
|
+
"content-length": String(metadata.size)
|
|
79
192
|
} });
|
|
80
193
|
}
|
|
81
|
-
if (options.streamAssets === true && request.method === "GET" && !(extension === ".html" && options.transformHtml)) return new Response(createClientAssetStream(physical, metadata), { headers: {
|
|
82
|
-
"content-type": contentType,
|
|
83
|
-
"cache-control": "no-store",
|
|
84
|
-
"content-length": String(metadata.size)
|
|
85
|
-
} });
|
|
86
194
|
let body = new Uint8Array(await Bun.file(physical).arrayBuffer());
|
|
87
195
|
if (extension === ".html" && options.transformHtml) body = new TextEncoder().encode(options.transformHtml(new TextDecoder().decode(body), request));
|
|
196
|
+
const cacheVerified = immutableSha256 !== void 0 && createHash("sha256").update(body).digest("hex") === immutableSha256;
|
|
88
197
|
return new Response(request.method === "HEAD" ? null : body, { headers: {
|
|
89
198
|
"content-type": contentType,
|
|
90
|
-
"cache-control": "no-store",
|
|
199
|
+
"cache-control": cacheVerified ? IMMUTABLE_CACHE_CONTROL : "no-store",
|
|
200
|
+
...cacheVerified && request.method === "GET" ? { "content-length": String(body.byteLength) } : {},
|
|
91
201
|
...request.method === "HEAD" ? { "content-length": String(body.byteLength) } : {}
|
|
92
202
|
} });
|
|
93
203
|
}
|
|
94
|
-
export { serveClient };
|
|
204
|
+
export { CLIENT_ASSET_ASSET_PATTERN, CLIENT_ASSET_CHUNK_PATTERN, CLIENT_ASSET_MANIFEST_FILE, clientAssetAssetEvidenceKey, clientAssetChunkEvidenceKey, createClientAssetManifest, createClientAssetResolver, createClientAssetVerificationCache, loadClientAssetManifest, parseClientAssetManifest, serveClient, snapshotClientAssetAllowlist };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** A request was admitted after the response lifecycle had started draining. */
|
|
2
|
+
export declare class ClientResponseLifecycleClosedError extends Error {
|
|
3
|
+
constructor();
|
|
4
|
+
}
|
|
5
|
+
export type ClientResponseLifecycleTracker = Readonly<{
|
|
6
|
+
/** Run an asset handler while registering it synchronously for shutdown drain. */
|
|
7
|
+
handle(factory: () => Response | PromiseLike<Response>): Promise<Response>;
|
|
8
|
+
/** Pause admission and wait for current handlers and response bodies to finish naturally. */
|
|
9
|
+
quiesce(): Promise<void>;
|
|
10
|
+
/** Resume admission after an aborted shutdown that has not started stopping the host. */
|
|
11
|
+
resume(): void;
|
|
12
|
+
/** Stop admission, cancel outstanding response bodies, and await all cleanup. */
|
|
13
|
+
stopAndDrain(reason?: unknown): Promise<void>;
|
|
14
|
+
readonly accepting: boolean;
|
|
15
|
+
}>;
|
|
16
|
+
/**
|
|
17
|
+
* Tracks async asset handlers and the response bodies they create. The response
|
|
18
|
+
* body returned from `handle` remains owned by its caller for normal reads; this
|
|
19
|
+
* tracker keeps a reader so shutdown can cancel it even while the body is locked
|
|
20
|
+
* by the host's response writer.
|
|
21
|
+
*/
|
|
22
|
+
export declare function createClientResponseLifecycleTracker(): ClientResponseLifecycleTracker;
|