Skip to content

Commit 163cfd1

Browse files
committed
fix(cli): allow the Console's blob: manifest in the document policy, and serve the e2e like the CLI
The Console links its branded web app manifest as a blob: URL, which default-src 'self' refused, so the served Console was not installable. The Playwright service-worker spec serves the build with the CLI's base tag, so routes stay inside the worker's scope. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QsR2jQhk3S1XeTLgXSkEMt
1 parent 9d765ec commit 163cfd1

4 files changed

Lines changed: 128 additions & 70 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@object-ui/mobile': patch
3+
'@object-ui/console': patch
4+
'@objectstack/cli': patch
5+
---
6+
7+
feat(console): the Console is an installable PWA on desktop, with an offline app shell and a Service Worker ready for Web Push
8+
9+
Clause-②: yes (widening)
10+
Metadata-protocol: none
11+
12+
The Console already injected a web app manifest, but nothing registered a Service Worker, so the installed app showed a browser error page on a cold start without network, and Web Push had no worker to reach. Under the CLI's content-security-policy the branded manifest was refused too, so the served Console was not installable at all.
13+
14+
- **`@object-ui/mobile` gains an `'app-shell'` worker strategy.** `getServiceWorkerSource({ strategy: 'app-shell', build })` writes a build-versioned shell worker: its cache is named after the scope and the build, and activation deletes the scope's caches of every other build. Requests under `apiPrefix` and every request outside the scope are network-only (the worker never answers them, never reads or writes the cache for them, so no data and no cookie is stored). Navigations are network-first with the precached HTML entry as the offline fallback; hashed `assets/` files are cache-first. `build` is required by `'app-shell'` and refused by `'offline-first'`. The default `'offline-first'` worker is byte-identical to before.
15+
- **`notifications: true`** adds `push` and `notificationclick` handlers. A click focuses or opens an app window at the payload's `route`, an in-app path relative to the scope; a route that is not an in-app path, or that climbs out of the scope, opens nothing. No push subscription is made.
16+
- **`cacheLoadedResources(worker)`** asks an `'app-shell'` worker to cache the files the page loaded before the worker controlled it, so the first visit's lazy chunks are there for an offline start. `SERVICE_WORKER_CACHE_URLS_MESSAGE` and `ServiceWorkerStrategy` are exported beside it.
17+
- **The Console registers it.** The build emits `service-worker.js` at its root (precache: the entry chunk, its static imports and their CSS), and the Console registers it under its own mount (`/_console/`), never the site root, in production builds. The next navigation after a deploy runs the new build. Inside the ObjectStack mobile shell no worker is registered, and one registered earlier in that WebView is removed. The generated manifest's `start_url`, `scope` and icon are absolute URLs under the mount.
18+
- **`@objectstack/cli`**: the Console document's policy adds `manifest-src 'self' blob:`, so the branded manifest loads and the Console is installable.

‎packages/cli/src/utils/console.content-security-policy.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,9 @@ describe('the console document is served with a nonce-based content-security-pol
157157
expect(policy.get('base-uri')).toEqual(["'self'"]);
158158
expect(policy.get('frame-ancestors')).toEqual(["'self'"]);
159159
expect(policy.get('connect-src')).toEqual(["'self'", 'https://demotiles.maplibre.org']);
160+
// The Console links its branded manifest as a `blob:` URL; without this
161+
// the browser refuses it and the Console is not installable (#29155).
162+
expect(policy.get('manifest-src')).toEqual(["'self'", 'blob:']);
160163
});
161164

162165
it('stamps every <script> in the served document with the nonce the header names', async () => {

‎packages/cli/src/utils/console.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -831,8 +831,14 @@ const DEFAULT_MAP_STYLE_ORIGIN = 'https://demotiles.maplibre.org';
831831
* stores; `readStorageUploadOrigin`), and the hosts an operator names in
832832
* `OS_CONSOLE_CSP_CONNECT_SRC`.
833833
* - `default-src 'self'` covers the rest the Console uses: the module workers
834-
* maplibre starts from its own file, the PWA manifest, and the same-origin
834+
* maplibre starts from its own file, its Service Worker, and the same-origin
835835
* frames (the Studio's live canvas). The build ships no web fonts.
836+
* - `manifest-src 'self' blob:`: the Console builds its web app manifest from
837+
* the runtime branding and links it as a `blob:` URL, so the installed app
838+
* carries the product's name and icon. Under `default-src 'self'` alone that
839+
* manifest is refused and the Console is not installable (objectstack#29155).
840+
* A `blob:` URL can only be minted by a script the page already runs, which
841+
* `script-src` governs.
836842
* - `object-src 'none'` and `base-uri 'self'`: no plugins, and only the
837843
* server's own `<base href>`.
838844
* - `frame-ancestors 'self'`, except on the public form page: the Console's
@@ -868,6 +874,7 @@ function consoleContentSecurityPolicy(input: {
868874
['style-src', "'self'", "'unsafe-inline'"],
869875
['img-src', "'self'", 'data:', 'blob:', 'https:'],
870876
['connect-src', ...new Set(connectSrc)],
877+
['manifest-src', "'self'", 'blob:'],
871878
['object-src', "'none'"],
872879
['base-uri', "'self'"],
873880
];

‎ui/e2e/console-service-worker.spec.ts‎

Lines changed: 99 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,79 @@ import { CONSOLE_BASE, waitForReactMount } from './helpers';
1212
* comes from the worker), and data calls fail visibly as offline: the
1313
* sign-in screen's "Cannot connect to server" panel, and a direct API
1414
* request rejects instead of answering from a cache.
15-
* 2. A new build is picked up within one navigation: a server that switches
16-
* to a "next" build (new document, new worker build id) serves that
17-
* document on the next navigation, and the new worker deletes the old
15+
* 2. A new build is picked up within one navigation: once the server switches
16+
* to a "next" build (new document, new worker build id), the next
17+
* navigation runs that document, and the new worker deletes the old
1818
* build's cache when it activates.
1919
*
20-
* Chromium only: `context.setOffline` and Cache Storage are measured there,
21-
* and the CI lane runs `--project=chromium`.
20+
* The build is served here the way the framework CLI serves it, not by
21+
* `vite preview`: the document carries `<base href>` for the mount, so the
22+
* router keeps every route under the worker's scope. Under `vite preview`
23+
* there is no `<base>`, the router's basename is `/`, and the app moves to
24+
* `/login`, outside the scope, where no worker of the Console can answer.
25+
*
26+
* Chromium only: the CI lane runs `--project=chromium`.
2227
*/
2328

2429
const CACHE_PREFIX = 'objectui-console::';
30+
const DIST = path.resolve(import.meta.dirname, '../apps/console/dist');
31+
32+
interface ConsoleServer {
33+
origin: string;
34+
/** The `service-worker.js` build id as emitted. */
35+
build: string;
36+
/** Switch to a "next" build: a marked document and a worker with a new build id. */
37+
deploy(): void;
38+
close(): Promise<void>;
39+
}
40+
41+
async function serveConsole(): Promise<ConsoleServer> {
42+
const index = fs.readFileSync(path.join(DIST, 'index.html'), 'utf8');
43+
const worker = fs.readFileSync(path.join(DIST, 'service-worker.js'), 'utf8');
44+
const build = /const BUILD = "([^"]+)";/.exec(worker)?.[1] ?? '';
45+
let next = false;
46+
47+
const server = http.createServer((req, res) => {
48+
const pathname = new URL(req.url ?? '/', 'http://localhost').pathname;
49+
if (!pathname.startsWith(`${CONSOLE_BASE}/`)) {
50+
res.writeHead(404).end();
51+
return;
52+
}
53+
const rel = pathname.slice(CONSOLE_BASE.length + 1);
54+
if (rel === 'service-worker.js') {
55+
const body = next ? worker.replace(`const BUILD = "${build}";`, `const BUILD = "${build}-next";`) : worker;
56+
res.writeHead(200, { 'content-type': 'text/javascript' }).end(body);
57+
return;
58+
}
59+
const file = path.join(DIST, rel);
60+
if (rel && file.startsWith(DIST) && fs.existsSync(file) && fs.statSync(file).isFile() && !rel.endsWith('.html')) {
61+
const type = file.endsWith('.js') ? 'text/javascript' : file.endsWith('.css') ? 'text/css' : 'application/octet-stream';
62+
res.writeHead(200, { 'content-type': type }).end(fs.readFileSync(file));
63+
return;
64+
}
65+
if (rel.startsWith('assets/')) {
66+
res.writeHead(404).end();
67+
return;
68+
}
69+
// The SPA document, with the `<base>` the CLI injects.
70+
const head = `<head>\n <base href="${CONSOLE_BASE}/">${next ? '<meta name="e2e-build" content="next">' : ''}`;
71+
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(index.replace('<head>', head));
72+
});
73+
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
74+
75+
return {
76+
origin: `http://127.0.0.1:${(server.address() as AddressInfo).port}`,
77+
build,
78+
deploy: () => {
79+
next = true;
80+
},
81+
close: () =>
82+
new Promise<void>((resolve) => {
83+
server.closeAllConnections();
84+
server.close(() => resolve());
85+
}),
86+
};
87+
}
2588

2689
/** Waits until the worker controls the page and holds every console file the page loaded. */
2790
async function waitForShellCached(page: Page) {
@@ -46,12 +109,22 @@ async function waitForShellCached(page: Page) {
46109
test.describe('Console service worker', () => {
47110
test.skip(({ browserName }) => browserName !== 'chromium', 'measured on chromium, the CI E2E project');
48111

112+
let server: ConsoleServer;
113+
test.beforeEach(async () => {
114+
server = await serveConsole();
115+
expect(server.build, 'the emitted worker names its build').toBeTruthy();
116+
});
117+
test.afterEach(async () => {
118+
await server.close();
119+
});
120+
49121
test('after one load, an offline reload shows the shell and data calls fail as offline', async ({
50122
page,
51123
context,
52124
}) => {
53-
await page.goto(`${CONSOLE_BASE}/`);
125+
await page.goto(`${server.origin}${CONSOLE_BASE}/`);
54126
await waitForReactMount(page);
127+
await expect(page).toHaveURL(new RegExp(`${CONSOLE_BASE}/`));
55128
await waitForShellCached(page);
56129

57130
await context.setOffline(true);
@@ -63,7 +136,7 @@ test.describe('Console service worker', () => {
63136
await expect(page.getByTestId('auth-server-unreachable')).toBeVisible({ timeout: 30_000 });
64137

65138
// The API is network-only: offline, a data call rejects instead of
66-
// answering from the worker's cache.
139+
// answering from the worker's cache, and nothing under /api/ was cached.
67140
const apiAnswer = await page.evaluate(() =>
68141
fetch('/api/v1/auth/get-session').then(
69142
(res) => `answered ${res.status}`,
@@ -87,67 +160,24 @@ test.describe('Console service worker', () => {
87160
});
88161

89162
test('a new build is picked up within one navigation, and its worker drops the old cache', async ({ page }) => {
90-
const dist = path.resolve(import.meta.dirname, '../apps/console/dist');
91-
const index = fs.readFileSync(path.join(dist, 'index.html'), 'utf8');
92-
const worker = fs.readFileSync(path.join(dist, 'service-worker.js'), 'utf8');
93-
const build = /const BUILD = "([^"]+)";/.exec(worker)?.[1];
94-
expect(build, 'the emitted worker names its build').toBeTruthy();
95-
96-
// A server for the same dist that can switch to a "next" build: a new
97-
// document and a worker with a new build id, the two things a deploy
98-
// changes for the browser.
99-
let next = false;
100-
const server = http.createServer((req, res) => {
101-
const pathname = new URL(req.url ?? '/', 'http://localhost').pathname;
102-
if (!pathname.startsWith(`${CONSOLE_BASE}/`)) {
103-
res.writeHead(404).end();
104-
return;
105-
}
106-
const rel = pathname.slice(CONSOLE_BASE.length + 1);
107-
if (rel === 'service-worker.js') {
108-
const body = next ? worker.replace(`const BUILD = "${build}";`, `const BUILD = "${build}-next";`) : worker;
109-
res.writeHead(200, { 'content-type': 'text/javascript', 'cache-control': 'no-cache' }).end(body);
110-
return;
111-
}
112-
const file = path.join(dist, rel);
113-
if (rel && file.startsWith(dist) && fs.existsSync(file) && fs.statSync(file).isFile()) {
114-
const type = file.endsWith('.js') ? 'text/javascript' : file.endsWith('.css') ? 'text/css' : 'application/octet-stream';
115-
res.writeHead(200, { 'content-type': type }).end(fs.readFileSync(file));
116-
return;
117-
}
118-
if (rel.startsWith('assets/')) {
119-
res.writeHead(404).end();
120-
return;
121-
}
122-
const html = next ? index.replace('<head>', '<head><meta name="e2e-build" content="next">') : index;
123-
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(html);
124-
});
125-
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
126-
const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
127-
128-
try {
129-
await page.goto(`${origin}${CONSOLE_BASE}/`);
130-
await waitForReactMount(page);
131-
await waitForShellCached(page);
132-
expect(await page.evaluate(() => caches.keys())).toContain(`${CACHE_PREFIX}${CONSOLE_BASE}/::${build}`);
133-
134-
// Deploy.
135-
next = true;
136-
await page.goto(`${origin}${CONSOLE_BASE}/login`);
137-
await expect(page.locator('meta[name="e2e-build"]')).toHaveAttribute('content', 'next');
138-
await waitForReactMount(page);
139-
140-
// The new worker installs, takes over and deletes the old build's cache.
141-
await page.waitForFunction(
142-
async ({ prefix, oldBuild }) => {
143-
const keys = (await caches.keys()).filter((key) => key.startsWith(prefix));
144-
return keys.length === 1 && keys[0].endsWith(`::${oldBuild}-next`);
145-
},
146-
{ prefix: CACHE_PREFIX, oldBuild: build },
147-
{ timeout: 30_000, polling: 250 },
148-
);
149-
} finally {
150-
await new Promise<void>((resolve) => server.close(() => resolve()));
151-
}
163+
await page.goto(`${server.origin}${CONSOLE_BASE}/`);
164+
await waitForReactMount(page);
165+
await waitForShellCached(page);
166+
expect(await page.evaluate(() => caches.keys())).toContain(`${CACHE_PREFIX}${CONSOLE_BASE}/::${server.build}`);
167+
168+
server.deploy();
169+
await page.goto(`${server.origin}${CONSOLE_BASE}/login`);
170+
await expect(page.locator('meta[name="e2e-build"]')).toHaveAttribute('content', 'next');
171+
await waitForReactMount(page);
172+
173+
// The new worker installs, takes over and deletes the old build's cache.
174+
await page.waitForFunction(
175+
async ({ prefix, build }) => {
176+
const keys = (await caches.keys()).filter((key) => key.startsWith(prefix));
177+
return keys.length === 1 && keys[0].endsWith(`::${build}-next`);
178+
},
179+
{ prefix: CACHE_PREFIX, build: server.build },
180+
{ timeout: 30_000, polling: 250 },
181+
);
152182
});
153183
});

0 commit comments

Comments
 (0)