From ecfad7904e1b6b92926f78fe100a66574a2bae13 Mon Sep 17 00:00:00 2001 From: adji Date: Wed, 18 Nov 2026 15:21:49 -0300 Subject: [PATCH 1/6] feat(sw): retain signed envelope + derive appVersion in loader + server-requested manifest upload Store: - addLatest({appVersion, signedEnvelope, manifest}) takes caller-computed appVersion, drops the return value (caller has both inputs) - new getSignedEnvelope(appVersion) for server-requested re-POST - deleted createSyntheticAppVersion (moved to loader as deriveAppVersion) Loader: - deriveAppVersion(pay) hashes the raw signed payload, not the SW-normalized manifest, so a server with the same envelope can compute the same id - normalizeManifestData runs in the caller; store never reshapes input Event stream: - POST response header x-dappfence-request-manifest signals which appVersion the server wants a copy of; uploadManifestIfRequested re-POSTs the matching signedEnvelope best-effort (errors swallowed, doesn't affect primary POST) Also: new HEADER_REQUEST_MANIFEST constant. --- packages/dappfence/src/core/constants.js | 7 + .../src/sw/__tests__/manifest-loader.test.js | 24 ++-- .../src/sw/__tests__/manifest-store.test.js | 130 ++++++++---------- .../src/sw/__tests__/storage-index.test.js | 9 +- .../src/sw/manifest/manifest-loader.js | 22 ++- .../src/sw/storage/manifest-store.js | 54 ++++---- .../src/sw/telemetry/event-stream.js | 46 ++++++- 7 files changed, 171 insertions(+), 121 deletions(-) diff --git a/packages/dappfence/src/core/constants.js b/packages/dappfence/src/core/constants.js index 95e0c987..d3338724 100644 --- a/packages/dappfence/src/core/constants.js +++ b/packages/dappfence/src/core/constants.js @@ -35,6 +35,13 @@ export const MSG = { export const SYNC_TAG_TELEMETRY = 'dappfence-sync-tag-telemetry'; +/** + * Response header on a telemetry POST. Value is the appVersion the server + * wants a copy of; the SW uploads the matching stored signed envelope back + * to the same endpoint URL, best-effort (errors swallowed). + */ +export const HEADER_REQUEST_MANIFEST = 'x-dappfence-request-manifest'; + export const MODE = { REPORTING: 'reporting', // log to console and indexeddb PROTECTED: 'protected', // stop requests that are invalid diff --git a/packages/dappfence/src/sw/__tests__/manifest-loader.test.js b/packages/dappfence/src/sw/__tests__/manifest-loader.test.js index a399c681..3f9cbf28 100644 --- a/packages/dappfence/src/sw/__tests__/manifest-loader.test.js +++ b/packages/dappfence/src/sw/__tests__/manifest-loader.test.js @@ -11,7 +11,6 @@ import { verifyManifestSignature } from '../manifest/verification.js'; const MANIFEST_URL = 'https://example.com/manifest.json'; const VALID_PAYLOAD = { files: { '/app.js': 'sha256-abc' }, mode: 'protected' }; -const MANIFEST_INFO = { appVersion: 'v1', manifest: normalizeManifestData(VALID_PAYLOAD) }; function makeConfig(overrides = {}) { return { @@ -37,10 +36,10 @@ function makeSwContext({ }; } -function makeAppStore({ addLatestResult = MANIFEST_INFO } = {}) { +function makeAppStore() { return { trustedManifestStore: { - addLatest: vi.fn(() => Promise.resolve(addLatestResult)), + addLatest: vi.fn(() => Promise.resolve()), getLatest: vi.fn(() => Promise.resolve(undefined)), getAll: vi.fn(() => Promise.resolve([])), }, @@ -157,23 +156,20 @@ describe('fetchAndStoreManifest', () => { expect(result.fileKey).toBe('/manifest.json'); }); - it('normalizes the payload before handing it to the store', async () => { + it('derives appVersion from the signed payload and hands the triple to the store', async () => { verifyManifestSignature.mockReturnValue({ status: VERIFICATION_STATUS.MATCH, payload: VALID_PAYLOAD, }); - const appStore = makeAppStore({ - addLatestResult: { - appVersion: 'v-ok', - manifest: normalizeManifestData(VALID_PAYLOAD), - }, - }); + const appStore = makeAppStore(); const result = await makeLoader({ appStore }).fetchAndStoreManifest(); expect(result.status).toBe(VERIFICATION_STATUS.MATCH); - expect(result.appVersion).toBe('v-ok'); - expect(appStore.trustedManifestStore.addLatest).toHaveBeenCalledWith( - normalizeManifestData(VALID_PAYLOAD) - ); + expect(result.appVersion).toMatch(/^manifest-[A-Za-z0-9+/]{16}$/); + expect(appStore.trustedManifestStore.addLatest).toHaveBeenCalledWith({ + appVersion: result.appVersion, + signedEnvelope: { pay: VALID_PAYLOAD, sig: 'sig' }, + manifest: normalizeManifestData(VALID_PAYLOAD), + }); }); }); diff --git a/packages/dappfence/src/sw/__tests__/manifest-store.test.js b/packages/dappfence/src/sw/__tests__/manifest-store.test.js index cd52dc6b..4006ef42 100644 --- a/packages/dappfence/src/sw/__tests__/manifest-store.test.js +++ b/packages/dappfence/src/sw/__tests__/manifest-store.test.js @@ -2,6 +2,21 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { createManifestStore } from '../storage/manifest-store.js'; import { createInMemoryDb } from './helpers/in-memory-db.js'; +/** + * @param {string} appVersion + * @param {object} manifest + * @param {object} [signedEnvelope] + */ +const entry = ( + appVersion, + manifest, + signedEnvelope = { pay: manifest, sig: `sig-${appVersion}` } +) => ({ + appVersion, + manifest, + signedEnvelope, +}); + describe('createManifestStore', () => { let storage; @@ -11,93 +26,78 @@ describe('createManifestStore', () => { describe('trustedManifest', () => { it('returns undefined for unknown version', async () => { - const manifest = await storage.get('unknown'); - expect(manifest).toBeUndefined(); + expect(await storage.get('unknown')).toBeUndefined(); }); it('returns undefined from getLatest when nothing is stored', async () => { - const latest = await storage.getLatest(); - expect(latest).toBeUndefined(); - }); - - it('addLatest synthesizes a deterministic appVersion from manifest content', async () => { - const { appVersion } = await storage.addLatest({ - files: { '/a.js': 'h' }, - }); - expect(appVersion).toMatch(/^manifest-[A-Za-z0-9+/]{16}$/); - const dup = await storage.addLatest({ - files: { '/a.js': 'h' }, - }); - expect(dup.appVersion).toBe(appVersion); - const other = await storage.addLatest({ - files: { '/b.js': 'h2' }, - }); - expect(other.appVersion).not.toBe(appVersion); + expect(await storage.getLatest()).toBeUndefined(); }); it('addLatest stores a manifest retrievable by appVersion and via getLatest', async () => { - const manifestData = { files: { '/app.js': 'abc123', '/style.css': 'def456' } }; - const { appVersion } = await storage.addLatest(manifestData); + const manifest = { files: { '/app.js': 'abc123', '/style.css': 'def456' } }; + await storage.addLatest(entry('v-1', manifest)); - expect(await storage.get(appVersion)).toEqual(manifestData); + expect(await storage.get('v-1')).toEqual(manifest); expect(await storage.getLatest()).toEqual( expect.objectContaining({ - appVersion, - manifest: manifestData, + appVersion: 'v-1', + manifest, }) ); }); it('preserves mode, metadata, and other top-level manifest fields', async () => { - const manifestData = { + const manifest = { files: { '/app.js': 'abc' }, mode: 'reporting', metadata: { extensions: ['.js', '.wasm'] }, customField: { future: true }, }; - const { appVersion } = await storage.addLatest(manifestData); + await storage.addLatest(entry('v-1', manifest)); - expect(await storage.get(appVersion)).toEqual(manifestData); - expect((await storage.getLatest()).manifest).toEqual(manifestData); + expect(await storage.get('v-1')).toEqual(manifest); + expect((await storage.getLatest()).manifest).toEqual(manifest); }); it('getLatest returns the most recently added manifest', async () => { - await storage.addLatest({ files: { '/a.js': 'x' } }); - const second = await storage.addLatest({ - files: { '/b.js': 'y' }, - }); + await storage.addLatest(entry('v-1', { files: { '/a.js': 'x' } })); + await storage.addLatest(entry('v-2', { files: { '/b.js': 'y' } })); const latest = await storage.getLatest(); - expect(latest.appVersion).toBe(second.appVersion); + expect(latest.appVersion).toBe('v-2'); expect(latest.manifest).toEqual({ files: { '/b.js': 'y' } }); }); it('addLatest caps entries at 20 (safety bound)', async () => { const versions = []; for (let i = 1; i <= 25; i++) { - const { appVersion } = await storage.addLatest({ - files: { [`/f${i}.js`]: `h${i}` }, - }); - versions.push(appVersion); + const v = `v-${i}`; + await storage.addLatest(entry(v, { files: { [`/f${i}.js`]: `h${i}` } })); + versions.push(v); } - const all = await storage.getAll(); - expect(all).toHaveLength(20); + + expect(await storage.getAll()).toHaveLength(20); expect((await storage.getLatest()).appVersion).toBe(versions[24]); - // The five earliest additions should have been dropped by the cap. for (let i = 0; i < 5; i++) { expect(await storage.get(versions[i])).toBeUndefined(); } }); - it('re-adding an existing manifest dedups and promotes it to the front', async () => { - const a = await storage.addLatest({ files: { '/a.js': 'x' } }); - await storage.addLatest({ files: { '/b.js': 'y' } }); - const aAgain = await storage.addLatest({ - files: { '/a.js': 'x' }, - }); + it('re-adding an existing appVersion dedups and promotes it to the front', async () => { + await storage.addLatest(entry('v-a', { files: { '/a.js': 'x' } })); + await storage.addLatest(entry('v-b', { files: { '/b.js': 'y' } })); + await storage.addLatest(entry('v-a', { files: { '/a.js': 'x' } })); + + expect((await storage.getLatest()).appVersion).toBe('v-a'); + expect(await storage.getAll()).toHaveLength(2); + }); + + it('getSignedEnvelope returns the stored {pay, sig} envelope', async () => { + const signedEnvelope = { pay: { files: { '/a.js': 'h' } }, sig: '0xdeadbeef' }; + await storage.addLatest(entry('v-1', { files: { '/a.js': 'h' } }, signedEnvelope)); - expect(aAgain.appVersion).toBe(a.appVersion); - expect((await storage.getLatest()).appVersion).toBe(a.appVersion); + expect(await storage.getSignedEnvelope('v-1')).toEqual(signedEnvelope); + expect(await storage.getSignedEnvelope('unknown')).toBeUndefined(); }); describe('age-based pruning', () => { @@ -106,43 +106,33 @@ describe('createManifestStore', () => { it('prunes entries older than 24h on next addLatest', async () => { vi.setSystemTime(new Date('2026-01-01T00:00:00Z')); - const stale = await storage.addLatest({ - files: { '/old.js': 'gone' }, - }); - expect(await storage.get(stale.appVersion)).toBeDefined(); + await storage.addLatest(entry('v-stale', { files: { '/old.js': 'gone' } })); + expect(await storage.get('v-stale')).toBeDefined(); vi.setSystemTime(new Date('2026-01-02T00:00:01Z')); - const fresh = await storage.addLatest({ - files: { '/new.js': 'kept' }, - }); + await storage.addLatest(entry('v-fresh', { files: { '/new.js': 'kept' } })); - expect(await storage.get(stale.appVersion)).toBeUndefined(); - expect(await storage.get(fresh.appVersion)).toBeDefined(); + expect(await storage.get('v-stale')).toBeUndefined(); + expect(await storage.get('v-fresh')).toBeDefined(); }); it('does not prune entries younger than 24h', async () => { vi.setSystemTime(new Date('2026-01-01T00:00:00Z')); - const first = await storage.addLatest({ - files: { '/a.js': 'ha' }, - }); + await storage.addLatest(entry('v-first', { files: { '/a.js': 'ha' } })); vi.setSystemTime(new Date('2026-01-01T23:59:59Z')); - await storage.addLatest({ files: { '/b.js': 'hb' } }); + await storage.addLatest(entry('v-second', { files: { '/b.js': 'hb' } })); - expect(await storage.get(first.appVersion)).toBeDefined(); + expect(await storage.get('v-first')).toBeDefined(); }); }); it('getAll returns entries newest-first', async () => { - const a = await storage.addLatest({ files: { '/a.js': 'ha' } }); - const b = await storage.addLatest({ files: { '/b.js': 'hb' } }); - const c = await storage.addLatest({ files: { '/c.js': 'hc' } }); + await storage.addLatest(entry('v-a', { files: { '/a.js': 'ha' } })); + await storage.addLatest(entry('v-b', { files: { '/b.js': 'hb' } })); + await storage.addLatest(entry('v-c', { files: { '/c.js': 'hc' } })); const all = await storage.getAll(); - expect(all.map((e) => e.appVersion)).toEqual([ - c.appVersion, - b.appVersion, - a.appVersion, - ]); + expect(all.map((e) => e.appVersion)).toEqual(['v-c', 'v-b', 'v-a']); }); it('getAll returns an empty array when nothing is stored', async () => { diff --git a/packages/dappfence/src/sw/__tests__/storage-index.test.js b/packages/dappfence/src/sw/__tests__/storage-index.test.js index be447ea5..c174a2ad 100644 --- a/packages/dappfence/src/sw/__tests__/storage-index.test.js +++ b/packages/dappfence/src/sw/__tests__/storage-index.test.js @@ -26,11 +26,14 @@ describe('createAppStore', () => { it('manifest stores are functional', async () => { const appStore = createAppStoreFromDb(createInMemoryDb()); - const { appVersion } = await appStore.trustedManifestStore.addLatest({ - files: { '/a.js': 'h' }, + const manifest = { files: { '/a.js': 'h' } }; + await appStore.trustedManifestStore.addLatest({ + appVersion: 'v-1', + signedEnvelope: { pay: manifest, sig: '0x' }, + manifest, }); const latest = await appStore.trustedManifestStore.getLatest(); - expect(latest.appVersion).toBe(appVersion); + expect(latest.appVersion).toBe('v-1'); }); it('security store is functional', async () => { diff --git a/packages/dappfence/src/sw/manifest/manifest-loader.js b/packages/dappfence/src/sw/manifest/manifest-loader.js index 720cbe51..d496f538 100644 --- a/packages/dappfence/src/sw/manifest/manifest-loader.js +++ b/packages/dappfence/src/sw/manifest/manifest-loader.js @@ -6,6 +6,7 @@ */ import { ASSET_TYPE, MODE, VERIFICATION_STATUS } from '../../core/constants.js'; +import { calculateHash } from '../../core/crypto.js'; import { createSingleFlight, hasConfigManifest } from '../../core/utils.js'; import { toPathname, verifyManifestSignature } from './verification.js'; import { createLogger } from '../../core/logger.js'; @@ -14,6 +15,21 @@ import { validateMessages } from '../../messages/index.js'; /** @typedef {import('../../core/constants.js').AssetType} AssetType */ /** @typedef {import('../../core/constants.js').ManifestLoadReason} ManifestLoadReason */ +/** + * Deterministic appVersion from the signed manifest payload. Strips the + * `sha256-` encoding prefix before truncating, so the 16-char tail is pure + * entropy (~96 bits of base64). Hashes the raw pay (not the SW-normalized + * manifest) so a server with the same envelope can derive the same id. + * @param {object} pay - Raw signed payload (signatureResult.payload). + * @returns {Promise} + */ +const deriveAppVersion = async (pay) => { + const payStr = JSON.stringify(pay); + const hash = await calculateHash(new TextEncoder().encode(payStr)); + const rawHash = hash.replace(/^sha256-/, ''); + return `manifest-${rawHash.substring(0, 16)}`; +}; + /** * Loader output. `.status.isViolation` is the branch check at call sites; * producer code sets `manifest`/`appVersion` on MATCH and `reason` on @@ -302,9 +318,9 @@ export const createManifestLoader = ({ swContext, appStore, config }) => { if (signatureResult.status.isViolation) { return manifestResult(signatureResult); } - const { appVersion, manifest } = await trustedManifestStore.addLatest( - normalizeManifestData(signatureResult.payload) - ); + const appVersion = await deriveAppVersion(signatureResult.payload); + const manifest = normalizeManifestData(signatureResult.payload); + await trustedManifestStore.addLatest({ appVersion, signedEnvelope: json, manifest }); logger.setMinLevel(manifest.logsMinLevel ?? config.logsMinLevel ?? 'log'); logger.log( `Loaded manifest, app version: ${appVersion.substring(0, 12)}... (${Object.keys(manifest.files).length} files)` diff --git a/packages/dappfence/src/sw/storage/manifest-store.js b/packages/dappfence/src/sw/storage/manifest-store.js index 1babc5d2..579aebbe 100644 --- a/packages/dappfence/src/sw/storage/manifest-store.js +++ b/packages/dappfence/src/sw/storage/manifest-store.js @@ -6,8 +6,6 @@ * { db } interface, making it testable with in-memory backends. */ -import { calculateHash } from '../../core/crypto.js'; - // Trusted Manifest System constants const TRUSTED_MANIFEST_KEY = 'trusted-manifest'; @@ -17,35 +15,15 @@ const TRUSTED_MANIFEST_KEY = 'trusted-manifest'; const MAX_MANIFESTS = 20; const MAX_AGE_MS = 24 * 60 * 60 * 1000; -/** - * Synthesize a deterministic appVersion from manifest content. Strips the - * `sha256-` encoding prefix before truncating, so the 16-char tail is pure - * entropy (~96 bits of base64) rather than 9 payload chars after a fixed - * prefix. Same content -> same key, which is how to addLatest dedups. - */ -const createSyntheticAppVersion = async (manifestData) => { - const manifestStr = JSON.stringify(manifestData); - const manifestHash = await calculateHash(new TextEncoder().encode(manifestStr)); - const rawHash = manifestHash.replace(/^sha256-/, ''); - return `manifest-${rawHash.substring(0, 16)}`; -}; - /** * Create all manifest database operations with an injected database backend. * @param {import('./indexeddb.js').DbHandle} db */ export function createManifestStore(db) { /** - * Trusted Manifest database Operations - * - * Stored as a flat array `[{appVersion, manifest, storedAt}]`, newest first. - * The full manifest object is retained so consumers can read `mode`, - * `metadata`, and any future top-level fields. Callers pass in - * already-normalized manifests (see manifest-loader.normalizeManifestData); - * the store does not reshape input. - * - * `cachedList` mirrors the persisted array and is populated lazily on the - * first read, kept in sync by addLatest after its tx commits. + * Flat array `[{appVersion, signedEnvelope, manifest, storedAt}]`, newest + * first. `cachedList` mirrors the persisted array, populated lazily and + * kept in sync by addLatest after its tx commits. */ let cachedList = null; @@ -60,8 +38,15 @@ export function createManifestStore(db) { }; return { - async addLatest(manifest) { - const appVersion = await createSyntheticAppVersion(manifest); + /** + * @param {object} entry + * @param {string} entry.appVersion - Deterministic identity derived + * from the signed envelope by the caller. + * @param {object} entry.signedEnvelope - Raw `{pay, sig}` as received + * on the wire; retained for re-POST on server request. + * @param {object} entry.manifest - Normalized manifest for SW use. + */ + async addLatest({ appVersion, signedEnvelope, manifest }) { // Read-modify-write under a single transaction so concurrent // addLatest calls can't clobber each other's updates. let newList; @@ -69,13 +54,12 @@ export function createManifestStore(db) { const list = (await manifests.get(TRUSTED_MANIFEST_KEY)) || []; const now = Date.now(); const deduped = list.filter((m) => m.appVersion !== appVersion); - deduped.unshift({ appVersion, manifest, storedAt: now }); + deduped.unshift({ appVersion, signedEnvelope, manifest, storedAt: now }); const pruned = deduped.filter((m) => now - m.storedAt < MAX_AGE_MS); newList = pruned.slice(0, MAX_MANIFESTS); await manifests.put(newList, TRUSTED_MANIFEST_KEY); }); cachedList = newList; - return { appVersion, manifest }; }, async getLatest() { @@ -92,6 +76,18 @@ export function createManifestStore(db) { return entry?.manifest; }, + /** + * Returns the raw `{pay, sig}` envelope for the given appVersion, or + * undefined if we don't have it (never seen or aged out). + * @param {string} appVersion + * @returns {Promise} + */ + async getSignedEnvelope(appVersion) { + const list = await readList(); + const entry = list.find((m) => m.appVersion === appVersion); + return entry?.signedEnvelope; + }, + async getAll() { return readList(); }, diff --git a/packages/dappfence/src/sw/telemetry/event-stream.js b/packages/dappfence/src/sw/telemetry/event-stream.js index f96873a0..b0da33c6 100644 --- a/packages/dappfence/src/sw/telemetry/event-stream.js +++ b/packages/dappfence/src/sw/telemetry/event-stream.js @@ -1,5 +1,5 @@ import { createStreamDriver } from './stream-driver.js'; -import { VERIFICATION_STATUS_BY_NAME } from '../../core/constants.js'; +import { HEADER_REQUEST_MANIFEST, VERIFICATION_STATUS_BY_NAME } from '../../core/constants.js'; import { createLogger } from '../../core/logger.js'; /** @typedef {import('./stream-driver.js').TryToSendResult} TryToSendResult */ @@ -34,7 +34,8 @@ export function createEventStream({ swContext, appStore, manifestService, taskMa 'actualHash', ]; - const { telemetryBatchesStore, verificationResultsStore, settingsStore } = appStore; + const { telemetryBatchesStore, trustedManifestStore, verificationResultsStore, settingsStore } = + appStore; const name = 'events'; let maxEventsBytes; let selectVerdicts; @@ -95,6 +96,9 @@ export function createEventStream({ swContext, appStore, manifestService, taskMa body: JSON.stringify(envelope), signal: AbortSignal.timeout(POST_TIMEOUT_MS), }); + + await uploadManifestIfRequested(response); + if (!response?.ok) { logger.local.warn(`telemetry POST failed status=${response?.status ?? 0}`); return false; @@ -106,6 +110,44 @@ export function createEventStream({ swContext, appStore, manifestService, taskMa } } + /** + * Honor an `x-dappfence-request-manifest: ` response header + * by re-POSTing the matching stored `{pay, sig}` envelope to the same + * endpoint. Best-effort: any error (missing header, unknown appVersion, + * fetch failure) is swallowed — the primary POST's success is the only + * signal that matters to the caller. + * @param {Response | undefined} response + */ + async function uploadManifestIfRequested(response) { + try { + const appVersion = response?.headers?.get(HEADER_REQUEST_MANIFEST); + if (!appVersion) { + return; + } + const signedEnvelope = await trustedManifestStore.getSignedEnvelope(appVersion); + if (!signedEnvelope) { + logger.log( + `[${name}] server requested manifest ${appVersion}; not in store, skipping upload` + ); + return; + } + logger.log(`[${name}] server requested manifest ${appVersion}; uploading`); + await swContext.fetch(currentManifest.telemetryEndpoints?.events, { + method: 'POST', + keepalive: true, + mode: 'cors', + credentials: 'omit', + priority: 'low', + referrerPolicy: 'no-referrer', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(signedEnvelope), + signal: AbortSignal.timeout(POST_TIMEOUT_MS), + }); + } catch (err) { + logger.log(`[${name}] manifest upload threw (ignored):`, err); + } + } + /** * Dedup-aware event accumulator. Owns a Map and its serialized byte * footprint together so they can't drift. `tryAdd` is atomic: all events From b5d78a9dfda715f949237d6046ae9f05021edada Mon Sep 17 00:00:00 2001 From: adji Date: Wed, 2 Dec 2026 11:46:11 -0300 Subject: [PATCH 2/6] fix(sw/telemetry): fix envelopes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The SW logger buffers entries as {ts, level, args, count?} and log-stream was shipping them verbatim as envelope.logs. The Worker's sanitizer expects {ts, level, message, source?, context?, occurrenceCount?} and reads none of the SW's fields, so every log row arrived with an empty message column in df.mjs tail and lost its dedup count. Add formatArgs(args) and toWireEntry(entry) helpers in log-stream.js and map the drained batch through toWireEntry before buffering for POST. formatArgs flattens the args array to a single string (Errors render as "Name: message"; objects JSON.stringify with String() fallback for circular refs), joins with a space, and caps at 1024 chars with a trailing "..." marker — mirroring MAX_LOG_MESSAGE_BYTES on the Worker so we never ship bytes the server would discard. deriveAppVersion collapses to calculateHash(encode(JSON.stringify(pay))): same sha256- shape the codebase already uses for file hashes and SRI attributes, so appVersion is directly comparable with other hashes without reformatting. Drops the 96-bit truncation that earlier commits on this branch emitted (manifest-<16 base64 chars>) — full SHA-256 is cheap (~26 extra chars per envelope) and removes a birthday-collision concern on a content-addressed identity. --- .../src/sw/__tests__/manifest-loader.test.js | 2 +- .../src/sw/manifest/manifest-loader.js | 14 ++--- .../src/sw/telemetry/event-stream.js | 9 ++- .../dappfence/src/sw/telemetry/log-stream.js | 61 ++++++++++++++++++- .../test-app/test/common/sw-telemetry.spec.ts | 29 +++++---- 5 files changed, 94 insertions(+), 21 deletions(-) diff --git a/packages/dappfence/src/sw/__tests__/manifest-loader.test.js b/packages/dappfence/src/sw/__tests__/manifest-loader.test.js index 3f9cbf28..055c0c66 100644 --- a/packages/dappfence/src/sw/__tests__/manifest-loader.test.js +++ b/packages/dappfence/src/sw/__tests__/manifest-loader.test.js @@ -164,7 +164,7 @@ describe('fetchAndStoreManifest', () => { const appStore = makeAppStore(); const result = await makeLoader({ appStore }).fetchAndStoreManifest(); expect(result.status).toBe(VERIFICATION_STATUS.MATCH); - expect(result.appVersion).toMatch(/^manifest-[A-Za-z0-9+/]{16}$/); + expect(result.appVersion).toMatch(/^sha256-[A-Za-z0-9+/]{43}=$/); expect(appStore.trustedManifestStore.addLatest).toHaveBeenCalledWith({ appVersion: result.appVersion, signedEnvelope: { pay: VALID_PAYLOAD, sig: 'sig' }, diff --git a/packages/dappfence/src/sw/manifest/manifest-loader.js b/packages/dappfence/src/sw/manifest/manifest-loader.js index d496f538..60f78d8a 100644 --- a/packages/dappfence/src/sw/manifest/manifest-loader.js +++ b/packages/dappfence/src/sw/manifest/manifest-loader.js @@ -16,18 +16,18 @@ import { validateMessages } from '../../messages/index.js'; /** @typedef {import('../../core/constants.js').ManifestLoadReason} ManifestLoadReason */ /** - * Deterministic appVersion from the signed manifest payload. Strips the - * `sha256-` encoding prefix before truncating, so the 16-char tail is pure - * entropy (~96 bits of base64). Hashes the raw pay (not the SW-normalized - * manifest) so a server with the same envelope can derive the same id. + * Deterministic appVersion from the signed manifest payload: the SRI-formatted + * SHA-256 of `JSON.stringify(pay)`, i.e. `sha256-`. Hashes the raw pay + * (not the SW-normalized manifest) so a server with the same envelope derives + * the same id. Same `sha256-...` convention used elsewhere in the codebase + * (file hashes, SRI attributes), so appVersion is directly comparable without + * any reformatting dance. * @param {object} pay - Raw signed payload (signatureResult.payload). * @returns {Promise} */ const deriveAppVersion = async (pay) => { const payStr = JSON.stringify(pay); - const hash = await calculateHash(new TextEncoder().encode(payStr)); - const rawHash = hash.replace(/^sha256-/, ''); - return `manifest-${rawHash.substring(0, 16)}`; + return calculateHash(new TextEncoder().encode(payStr)); }; /** diff --git a/packages/dappfence/src/sw/telemetry/event-stream.js b/packages/dappfence/src/sw/telemetry/event-stream.js index b0da33c6..9bdbc37c 100644 --- a/packages/dappfence/src/sw/telemetry/event-stream.js +++ b/packages/dappfence/src/sw/telemetry/event-stream.js @@ -24,6 +24,7 @@ export function createEventStream({ swContext, appStore, manifestService, taskMa const KEEPALIVE_QUOTA_BYTES = 64 * 1024; const SENT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000; const CEILING_MS = 3000; + const MAX_APP_VERSION_LENGTH = 128; // Wire-visible only — internal verdict fields must not change dedup identity. const IDENTITY_FIELDS = [ 'assetType', @@ -124,6 +125,12 @@ export function createEventStream({ swContext, appStore, manifestService, taskMa if (!appVersion) { return; } + if (appVersion.length > MAX_APP_VERSION_LENGTH) { + logger.log( + `[${name}] request-manifest appVersion too long (${appVersion.length} chars); ignoring` + ); + return; + } const signedEnvelope = await trustedManifestStore.getSignedEnvelope(appVersion); if (!signedEnvelope) { logger.log( @@ -218,7 +225,7 @@ export function createEventStream({ swContext, appStore, manifestService, taskMa async function getMaxEventsBytes() { const installationTime = await settingsStore.getInstallationTime(); const envelope = renderEnvelope({ - appVersion: 'manifest-0123456789abcdef', // exact 25-char format + appVersion: `sha256-${'A'.repeat(43)}=`, // exact 51-char format installationTime, // real runtime value, stable per install origin: swContext.getLocationOrigin(), // real deployment value userAgent: swContext.getUserAgent(), // real browser session value diff --git a/packages/dappfence/src/sw/telemetry/log-stream.js b/packages/dappfence/src/sw/telemetry/log-stream.js index 69df1c9c..35e062ef 100644 --- a/packages/dappfence/src/sw/telemetry/log-stream.js +++ b/packages/dappfence/src/sw/telemetry/log-stream.js @@ -5,6 +5,65 @@ import { createLogger } from '../../core/logger.js'; const logger = createLogger(); +const MAX_MESSAGE_CHARS = 1024; +const TRUNC_SUFFIX = '...'; + +/** + * Flatten `args` into one string for the telemetry wire. Strings pass through; + * Errors render as `Name: message`; other non-primitives JSON.stringify + * (falling back to String()); then join with a single space. No timestamp + * prefix — `entry.ts` carries that as a separate field in the wire shape. + * Result is capped at `MAX_MESSAGE_CHARS` and marked with a trailing ellipsis + * when truncated, mirroring the Worker's `MAX_LOG_MESSAGE_BYTES` so we never + * ship bytes the server would discard. + * @param {unknown[]} args + * @returns {string} + */ +function formatArgs(args) { + const joined = args + .map((a) => { + if (typeof a === 'string') { + return a; + } + if (a instanceof Error) { + return `${a.name}: ${a.message}`; + } + if (a === null || typeof a !== 'object') { + return String(a); + } + try { + return JSON.stringify(a); + } catch { + return String(a); + } + }) + .join(' '); + + if (joined.length <= MAX_MESSAGE_CHARS) { + return joined; + } + return joined.slice(0, MAX_MESSAGE_CHARS - TRUNC_SUFFIX.length) + TRUNC_SUFFIX; +} + +/** + * Translate a logger buffer entry (`{ts, level, args, count?}`) to the Worker + * sanitizer's expected shape (`{ts, level, message, occurrenceCount?}`). The + * Worker drops `occurrenceCount` when <= 1, so we omit it unless dedup fired. + * @param {{ts: number, level: string, args: unknown[], count?: number}} entry + * @returns {{ts: number, level: string, message: string, occurrenceCount?: number}} + */ +function toWireEntry(entry) { + const wire = { + ts: entry.ts, + level: entry.level, + message: formatArgs(entry.args), + }; + if (entry.count !== undefined) { + wire.occurrenceCount = entry.count; + } + return wire; +} + /** * Logs telemetry stream — drains the logger's ring buffer, ships to * `manifest.telemetryEndpoints.logs`, and commits backoff. Unlike events, @@ -92,7 +151,7 @@ export function createLogStream({ swContext, appStore, manifestService, taskMana async function tryToSend(commitWhenDone) { const freshLogs = logger.getPendingLogs(); if (freshLogs.length > 0) { - pendingLogs = pendingLogs.concat(freshLogs); + pendingLogs = pendingLogs.concat(freshLogs.map(toWireEntry)); } if (pendingLogs.length > MAX_PENDING_LOGS) { diff --git a/packages/test-app/test/common/sw-telemetry.spec.ts b/packages/test-app/test/common/sw-telemetry.spec.ts index 4947516e..d3763e2a 100644 --- a/packages/test-app/test/common/sw-telemetry.spec.ts +++ b/packages/test-app/test/common/sw-telemetry.spec.ts @@ -361,24 +361,31 @@ test.describe('telemetry pipeline', () => { const envelopes = await listCapturesAt(swHelper, '/capture/logs'); const wireBodies = envelopes .flatMap((e) => e.logs) - .filter(({ args }) => typeof args[0] === 'string' && args[0].length > 0) - .flatMap(({ level, args, count = 1 }) => - Array(count).fill({ + .filter(({ message }) => typeof message === 'string' && message.length > 0) + .flatMap(({ level, message, occurrenceCount = 1 }) => + Array(occurrenceCount).fill({ type: level === 'warn' ? 'warning' : level, - body: args[0].replace(/^%c/, ''), + body: message.replace(/^%c/, ''), }) ); // With withDebugLog plugging the log-stream's own feedback loop, a quiet // SW produces no new entries after the final flush — so console and - // wire must be a 1:1 match (modulo the format transformation: wire body - // is args[0] alone, console body is the full space-joined args list). + // wire must be a 1:1 match. Both sinks receive the same args, but + // serialize non-primitive args differently: wire JSON.stringify's + // (`{"a":1}`) while Chromium's console inspector uses JS-literal format + // (`{a: 1}`). The two diverge at the first `{` / `[`, so compare only + // the leading primitive prefix — enough to confirm every console line + // maps to a wire entry at the right position with the right level. expect(consoleBodies).toHaveLength(wireBodies.length); - const consoleAlignedToWire = consoleBodies.map((m, i) => ({ - type: m.type, - body: m.body.slice(0, wireBodies[i].body.length), - })); - expect(consoleAlignedToWire).toEqual(wireBodies); + const labelPrefix = (s: string) => { + const idx = s.search(/[{[]/); + return idx === -1 ? s : s.slice(0, idx); + }; + for (let i = 0; i < consoleBodies.length; i++) { + expect(consoleBodies[i].type).toBe(wireBodies[i].type); + expect(labelPrefix(consoleBodies[i].body)).toBe(labelPrefix(wireBodies[i].body)); + } expect(envelopes.length).toBeGreaterThan(0); envelopes.forEach(expectValidShape); expect(wireBodies.length).toBeGreaterThan(0); From bc0de54df8326d4a199425e7bc92ccf1271b600a Mon Sep 17 00:00:00 2001 From: adji Date: Fri, 4 Dec 2026 08:31:15 -0300 Subject: [PATCH 3/6] feat(manifest-tools): strict build-time validator + shared enum constants MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Problem: the stringly-typed fields in a signed manifest — `mode`, `pathRules[].type`, `contentRules[].action.type`, `signatureType`, `logsMinLevel` were authored as ad-hoc string literals in build configs and dropped silently if misspelled: the loader's permissive normalizer would warn+fallback at runtime, but the signer happily produced the broken manifest and operators had no way to catch the typo before deploy. This change: 1. Extracts the stringly-typed values into frozen enums in `@dappfence/core/constants` (`MODE`, `PATH_RULE_TYPE`, `CONTENT_ACTION_TYPE`, `SIGNATURE_TYPE`, `LOG_LEVEL`), each with a matching JSDoc `@typedef`. These are the single source of truth for both the signer and the SW loader. 2. Adds `@dappfence/manifest-tools/validate` — a strict `assertValidManifestPayload` that throws on any unknown enum value, malformed sha256 hash, malformed URL, or type mismatch. Exposed via `./validate` subpath export so build tools can call it directly. 3. Wires `signManifest` to call the validator by default (with a `skipValidation: true` escape for tests that exercise malformed payloads on purpose). --- packages/dappfence/src/core/constants.js | 50 +++++- packages/manifest-tools/package.json | 3 +- packages/manifest-tools/src/build.js | 21 ++- packages/manifest-tools/src/validate.js | 193 +++++++++++++++++++++++ 4 files changed, 261 insertions(+), 6 deletions(-) create mode 100644 packages/manifest-tools/src/validate.js diff --git a/packages/dappfence/src/core/constants.js b/packages/dappfence/src/core/constants.js index d3338724..5ba6dde5 100644 --- a/packages/dappfence/src/core/constants.js +++ b/packages/dappfence/src/core/constants.js @@ -42,10 +42,55 @@ export const SYNC_TAG_TELEMETRY = 'dappfence-sync-tag-telemetry'; */ export const HEADER_REQUEST_MANIFEST = 'x-dappfence-request-manifest'; -export const MODE = { +export const MODE = Object.freeze({ REPORTING: 'reporting', // log to console and indexeddb PROTECTED: 'protected', // stop requests that are invalid -}; +}); +/** @typedef {typeof MODE[keyof typeof MODE]} Mode */ + +/** + * `pathRules[].type` values embedded verbatim in signed manifests. + * Changing a value is a breaking change — existing signed manifests would reject. + */ +export const PATH_RULE_TYPE = Object.freeze({ + DIRECTORY_INDEX: 'directory-index', + HTML_EXTENSION: 'html-extension', + ERROR_PAGE: 'error-page', +}); +/** @typedef {typeof PATH_RULE_TYPE[keyof typeof PATH_RULE_TYPE]} PathRuleType */ + +/** + * `contentRules[].action.type` values embedded verbatim in signed manifests. + * Changing a value is a breaking change — existing signed manifests would reject. + */ +export const CONTENT_ACTION_TYPE = Object.freeze({ + VERIFY: 'verify', + REWRITE: 'rewrite', + TRANSFORM: 'transform', + CSP: 'csp', + ALLOW: 'allow', +}); +/** @typedef {typeof CONTENT_ACTION_TYPE[keyof typeof CONTENT_ACTION_TYPE]} ContentActionType */ + +/** + * Manifest `signatureType` values. Each entry maps to a signature recovery + * implementation in sw/manifest/verification.js. + */ +export const SIGNATURE_TYPE = Object.freeze({ + NOBLE_SECP256K1_RECOVERED_ETH: 'noble-secp256k1-recovered-eth', +}); +/** @typedef {typeof SIGNATURE_TYPE[keyof typeof SIGNATURE_TYPE]} SignatureType */ + +/** + * Manifest `logsMinLevel` values. Caps SW-side log volume per client. + */ +export const LOG_LEVEL = Object.freeze({ + DEBUG: 'debug', + LOG: 'log', + WARN: 'warn', + ERROR: 'error', +}); +/** @typedef {typeof LOG_LEVEL[keyof typeof LOG_LEVEL]} LogLevel */ /** * Verification verdict for a single file or manifest. @@ -203,3 +248,4 @@ export const enforcesCsp = (destination) => CSP_ENFORCING_DESTINATIONS.has(desti export const TRANSFORM = Object.freeze({ NETLIFY_CDP: 'netlify-cdp', }); +/** @typedef {typeof TRANSFORM[keyof typeof TRANSFORM]} Transform */ diff --git a/packages/manifest-tools/package.json b/packages/manifest-tools/package.json index 0fa00d63..96f4bd19 100644 --- a/packages/manifest-tools/package.json +++ b/packages/manifest-tools/package.json @@ -13,7 +13,8 @@ "./crypto": "./src/crypto.js", "./manifest": "./src/manifest.js", "./inline-scripts": "./src/inline-scripts.js", - "./messages": "./src/messages.js" + "./messages": "./src/messages.js", + "./validate": "./src/validate.js" }, "bin": { "dappfence-manifest": "./src/cli.js" diff --git a/packages/manifest-tools/src/build.js b/packages/manifest-tools/src/build.js index 0e679f75..6bfb8b8c 100644 --- a/packages/manifest-tools/src/build.js +++ b/packages/manifest-tools/src/build.js @@ -4,6 +4,7 @@ */ import { createHash } from 'node:crypto'; import { readFileSync } from 'node:fs'; +import { SIGNATURE_TYPE } from '@dappfence/core/constants'; import { sign, ethereumAddress, @@ -12,6 +13,7 @@ import { keccak256, recoverSigner, } from './crypto.js'; +import { assertValidManifestPayload } from './validate.js'; /** * Signature types `signManifest` can actually produce. The SW's runtime @@ -25,7 +27,7 @@ import { * while the script tag declares a different type, and the SW rejects the * mismatch as an unsupported/invalid signature. */ -export const SUPPORTED_SIGNATURE_TYPES = ['noble-secp256k1-recovered-eth']; +export const SUPPORTED_SIGNATURE_TYPES = Object.values(SIGNATURE_TYPE); /** * Calculate SHA-256 hash of a file buffer or path. @@ -50,12 +52,25 @@ export function calculateStringHash(content) { /** * Sign a manifest payload and return the signed JSON string. + * + * Validates the payload shape against the DF enum set (MODE, PATH_RULE_TYPE, + * CONTENT_ACTION_TYPE, TRANSFORM, SIGNATURE_TYPE, LOG_LEVEL) and throws loud + * on any unknown value — a typo like `mode: 'PROTECTED'` fails the build + * instead of silently shipping a manifest the SW ignores. + * + * Unit tests that need to sign a partial/mocked payload may pass + * `{ skipValidation: true }` to bypass the check. + * * @param {object} manifestData - The manifest payload (e.g. { files: { ... }, metadata: { ... } }) * @param {object} keys * @param {string|Uint8Array} keys.secretKey - Hex string (with or without 0x) or raw bytes + * @param {boolean} [keys.skipValidation=false] - Opt out of schema validation (tests only) * @returns {{ pay: object, sig: string, identity: string, signatureType: string }} */ -export function signManifest(manifestData, { secretKey }) { +export function signManifest(manifestData, { secretKey, skipValidation = false }) { + if (!skipValidation) { + assertValidManifestPayload(manifestData); + } const skBytes = typeof secretKey === 'string' ? hexToBytes(secretKey.replace(/^0x/, '')) : secretKey; const pkBytes = getPublicKey(skBytes); @@ -67,7 +82,7 @@ export function signManifest(manifestData, { secretKey }) { pay: manifestData, sig, identity, - signatureType: 'noble-secp256k1-recovered-eth', + signatureType: SIGNATURE_TYPE.NOBLE_SECP256K1_RECOVERED_ETH, }; } diff --git a/packages/manifest-tools/src/validate.js b/packages/manifest-tools/src/validate.js new file mode 100644 index 00000000..fc8a1628 --- /dev/null +++ b/packages/manifest-tools/src/validate.js @@ -0,0 +1,193 @@ +/** + * Build-time manifest payload validator. + * + * Strict — throws `Error` on any unknown enum value, malformed file hash, + * malformed URL, or type mismatch. Called from `signManifest` by default so + * no caller can produce a signed manifest with fields the SW won't accept. + * + * Posture split (see docs/manifest-schema-validation.md): + * - manifest-tools here: STRICT — fail loud at build time. Typos = broken build. + * - sw/manifest-loader normalizeManifestData: PERMISSIVE — warn + fallback. + * SW cannot throw on a signed manifest at runtime without bricking + * every site DappFence protects. + * + * Both layers consume the same enum constants from `@dappfence/core/constants` + * so there is a single source of truth per field. + */ + +import { + MODE, + PATH_RULE_TYPE, + CONTENT_ACTION_TYPE, + TRANSFORM, + SIGNATURE_TYPE, + LOG_LEVEL, +} from '@dappfence/core/constants'; + +const SHA256_RE = /^sha256-[A-Za-z0-9+/=]+$/; + +function isValidManifestFilePath(p) { + if (p.startsWith('/')) { + return true; + } + if (p.startsWith('http://') || p.startsWith('https://')) { + try { + new URL(p); + return true; + } catch { + return false; + } + } + return false; +} + +/** + * Format a list of allowed values for an error message. + * @param {Record} enumObj + */ +function allowed(enumObj) { + return Object.values(enumObj) + .map((v) => JSON.stringify(v)) + .join(', '); +} + +/** + * Throw if `value` is not a member of the enum. No-op on `undefined`. + * @param {string} label - Dotted path like `manifest.mode` for the error message + * @param {unknown} value + * @param {Record} enumObj + */ +function assertEnum(label, value, enumObj) { + if (value === undefined) { + return; + } + if (!Object.values(enumObj).includes(value)) { + throw new Error( + `${label}: invalid value ${JSON.stringify(value)}. Expected one of: ${allowed(enumObj)}` + ); + } +} + +/** + * Validate `payload.files`: object mapping `/path` → `sha256-...` string. + * Accepts the array form (`[sha256-..., sha256-...]`) too — some manifests + * declare multiple known-good hashes per path for CDN-served assets. + * @param {unknown} files + */ +function validateFiles(files) { + if (files === undefined) { + return; + } + if (!files || typeof files !== 'object' || Array.isArray(files)) { + throw new Error(`manifest.files: expected object, got ${typeof files}`); + } + for (const [p, entry] of Object.entries(files)) { + if (typeof p !== 'string' || !isValidManifestFilePath(p)) { + throw new Error( + `manifest.files: path ${JSON.stringify(p)} must start with / or be an absolute http(s):// URL` + ); + } + const entries = Array.isArray(entry) ? entry : [entry]; + for (const hash of entries) { + if (typeof hash !== 'string' || !SHA256_RE.test(hash)) { + throw new Error( + `manifest.files[${JSON.stringify(p)}]: expected "sha256-..." string, got ${JSON.stringify(hash)}` + ); + } + } + } +} + +/** + * @param {unknown} rules + */ +function validatePathRules(rules) { + if (rules === undefined) { + return; + } + if (!Array.isArray(rules)) { + throw new Error(`manifest.pathRules: expected array, got ${typeof rules}`); + } + for (const [i, rule] of rules.entries()) { + if (!rule || typeof rule !== 'object') { + throw new Error(`manifest.pathRules[${i}]: expected object, got ${typeof rule}`); + } + assertEnum(`manifest.pathRules[${i}].type`, rule.type, PATH_RULE_TYPE); + } +} + +/** + * @param {unknown} rules + */ +function validateContentRules(rules) { + if (rules === undefined || rules === null) { + return; + } + if (!Array.isArray(rules)) { + throw new Error(`manifest.contentRules: expected array, got ${typeof rules}`); + } + for (const [i, rule] of rules.entries()) { + if (!rule || typeof rule !== 'object') { + throw new Error(`manifest.contentRules[${i}]: expected object, got ${typeof rule}`); + } + const action = rule.action; + if (!action || typeof action !== 'object') { + throw new Error( + `manifest.contentRules[${i}].action: expected object, got ${typeof action}` + ); + } + assertEnum(`manifest.contentRules[${i}].action.type`, action.type, CONTENT_ACTION_TYPE); + if (action.type === CONTENT_ACTION_TYPE.TRANSFORM) { + assertEnum( + `manifest.contentRules[${i}].action.transform`, + action.transform, + TRANSFORM + ); + } + } +} + +/** + * @param {string} label + * @param {unknown} value + */ +function assertUrlOrNull(label, value) { + if (value == null) { + return; + } + if (typeof value !== 'string') { + throw new Error(`${label}: expected string URL, got ${typeof value}`); + } + if (value.startsWith('/')) { + return; + } + try { + new URL(value); + } catch { + throw new Error(`${label}: not a valid URL: ${JSON.stringify(value)}`); + } +} + +/** + * Validate a full manifest payload (the thing you hand to `signManifest`). + * Throws `Error` on the first problem found. + * + * @param {object} payload + */ +export function assertValidManifestPayload(payload) { + if (!payload || typeof payload !== 'object') { + throw new Error('manifest: payload must be an object'); + } + + assertEnum('manifest.mode', payload.mode, MODE); + assertEnum('manifest.logsMinLevel', payload.logsMinLevel, LOG_LEVEL); + assertEnum('manifest.signatureType', payload.signatureType, SIGNATURE_TYPE); + + validateFiles(payload.files); + validatePathRules(payload.pathRules); + validateContentRules(payload.contentRules); + + assertUrlOrNull('manifest.csp.reportUri', payload.csp?.reportUri); + assertUrlOrNull('manifest.telemetry.eventsEndpoint', payload.telemetry?.eventsEndpoint); + assertUrlOrNull('manifest.telemetry.logsEndpoint', payload.telemetry?.logsEndpoint); +} From 2364f8a0743c9c45fcdeea78ce37deecb4dd1e2f Mon Sep 17 00:00:00 2001 From: adji Date: Fri, 4 Dec 2026 09:01:00 -0300 Subject: [PATCH 4/6] feat(manifest): thread enums + signatureType through SW and signer Wire the shared constants into the SW's manifest handling so string literals can't drift, and extend signManifest to honor the declared signatureType. --- packages/astro/src/__tests__/index.test.js | 8 ++- packages/astro/src/index.js | 1 + packages/dappfence/src/core/constants.js | 2 + packages/dappfence/src/core/crypto.js | 24 +++++---- .../src/sw/manifest/manifest-service.js | 6 +++ packages/dappfence/src/sw/manifest/rules.js | 16 +++--- .../src/sw/manifest/security-verifier.js | 15 +++--- .../dappfence/src/sw/manifest/verification.js | 6 +-- packages/manifest-tools/src/build.js | 49 ++++++++++++------- packages/manifest-tools/src/cli.js | 3 +- packages/manifest-tools/src/crypto.js | 20 ++++++-- packages/manifest-tools/src/manifest.js | 13 ++--- packages/manifest-tools/src/validate.js | 6 +-- packages/next/bin/dappfence-next.js | 2 + packages/next/src/__tests__/generate.test.js | 8 ++- packages/vite/src/__tests__/index.test.js | 8 ++- packages/vite/src/index.js | 1 + 17 files changed, 126 insertions(+), 62 deletions(-) diff --git a/packages/astro/src/__tests__/index.test.js b/packages/astro/src/__tests__/index.test.js index 008ceb10..10264c49 100644 --- a/packages/astro/src/__tests__/index.test.js +++ b/packages/astro/src/__tests__/index.test.js @@ -298,9 +298,15 @@ describe('conflicting secretKey sources', () => { describe('manifestSignatureType validation', () => { it('rejects a manifestSignatureType the build-time signer cannot produce', () => { + expect(() => + dappfence({ secretKey: SECRET_KEY, manifestSignatureType: 'unknown-scheme' }) + ).toThrow(/manifestSignatureType "unknown-scheme" is not supported/); + }); + + it('accepts personal-sign-alt now that signManifest produces it', () => { expect(() => dappfence({ secretKey: SECRET_KEY, manifestSignatureType: 'personal-sign-alt' }) - ).toThrow(/manifestSignatureType "personal-sign-alt" is not supported/); + ).not.toThrow(); }); }); diff --git a/packages/astro/src/index.js b/packages/astro/src/index.js index 02185fb2..32cbb790 100644 --- a/packages/astro/src/index.js +++ b/packages/astro/src/index.js @@ -388,6 +388,7 @@ export default function dappfence(options = {}) { // scriptSrc URL appears in the manifest. exclude: [...(opts.exclude || []), scriptSrcWebKey], secretKey, + signatureType: opts.manifestSignatureType, outDir, pages, routes: resolvedRoutes, diff --git a/packages/dappfence/src/core/constants.js b/packages/dappfence/src/core/constants.js index 5ba6dde5..751a20b8 100644 --- a/packages/dappfence/src/core/constants.js +++ b/packages/dappfence/src/core/constants.js @@ -69,6 +69,7 @@ export const CONTENT_ACTION_TYPE = Object.freeze({ TRANSFORM: 'transform', CSP: 'csp', ALLOW: 'allow', + DENY: 'deny', }); /** @typedef {typeof CONTENT_ACTION_TYPE[keyof typeof CONTENT_ACTION_TYPE]} ContentActionType */ @@ -78,6 +79,7 @@ export const CONTENT_ACTION_TYPE = Object.freeze({ */ export const SIGNATURE_TYPE = Object.freeze({ NOBLE_SECP256K1_RECOVERED_ETH: 'noble-secp256k1-recovered-eth', + PERSONAL_SIGN_ALT: 'personal-sign-alt', }); /** @typedef {typeof SIGNATURE_TYPE[keyof typeof SIGNATURE_TYPE]} SignatureType */ diff --git a/packages/dappfence/src/core/crypto.js b/packages/dappfence/src/core/crypto.js index e9a7794b..edc20887 100644 --- a/packages/dappfence/src/core/crypto.js +++ b/packages/dappfence/src/core/crypto.js @@ -51,6 +51,19 @@ export function recoverEthereumAddress(msg, signature) { return ethereumAddress(recoverPublicKey(sigBytes, msgHash, { prehash: false })); } +/** + * Wrap a keccak256 digest in the EIP-191 `personal_sign` envelope: + * keccak256("\x19Ethereum Signed Message:\n" || digest). Single + * source of truth for the prefix on the SW side — any verifier that + * handles a wallet eth_personalSign signature routes through this. + * @param {Uint8Array} msgHash - 32-byte keccak256 digest + * @returns {Uint8Array} + */ +export function applyPersonalSignPrefix(msgHash) { + const prefix = '\x19Ethereum Signed Message:\n'; + return keccak_256(etc.concatBytes(new TextEncoder().encode(prefix + msgHash.length), msgHash)); +} + /** * Recover Ethereum address from a wallet personal_sign message using the signature. * @param {Uint8Array} msg - The original message bytes @@ -58,14 +71,7 @@ export function recoverEthereumAddress(msg, signature) { * @returns {string} Recovered Ethereum address */ export function recoverPersonalSign(msg, signature) { - const msgHash = keccak_256(msg); + const msgHash = applyPersonalSignPrefix(keccak_256(msg)); const sigBytes = etc.hexToBytes(signature); - - // Message Hash - const prefix = '\x19Ethereum Signed Message:\n'; - // TextEncoder encodes to UTF-8. - const messageHash = keccak_256( - etc.concatBytes(new TextEncoder().encode(prefix + msgHash.length), msgHash) - ); - return ethereumAddress(recoverPublicKey(sigBytes, messageHash, { prehash: false })); + return ethereumAddress(recoverPublicKey(sigBytes, msgHash, { prehash: false })); } diff --git a/packages/dappfence/src/sw/manifest/manifest-service.js b/packages/dappfence/src/sw/manifest/manifest-service.js index dfa4161a..8b6c7ad8 100644 --- a/packages/dappfence/src/sw/manifest/manifest-service.js +++ b/packages/dappfence/src/sw/manifest/manifest-service.js @@ -14,8 +14,14 @@ import { import { createLogger } from '../../core/logger.js'; import { isRequestAllowed } from './rules.js'; +/** @typedef {import('../../core/constants.js').Mode} Mode */ + const logger = createLogger(); +/** + * @param {object} [manifest] + * @returns {Mode} + */ const getEffectiveMode = (manifest) => manifest?.mode || (isFeatureEnabled('default_to_protected_mode') ? MODE.PROTECTED : MODE.REPORTING); diff --git a/packages/dappfence/src/sw/manifest/rules.js b/packages/dappfence/src/sw/manifest/rules.js index 73fda413..68db29fc 100644 --- a/packages/dappfence/src/sw/manifest/rules.js +++ b/packages/dappfence/src/sw/manifest/rules.js @@ -5,8 +5,12 @@ // ── contentRules ───────────────────────────────────────────────────────────── +import { CONTENT_ACTION_TYPE, PATH_RULE_TYPE } from '../../core/constants.js'; import { decodePathname } from './verification.js'; +/** @typedef {import('../../core/constants.js').PathRuleType} PathRuleType */ +/** @typedef {import('../../core/constants.js').ContentActionType} ContentActionType */ + /** * @param {object|undefined} condition * @param {string} fileKey @@ -41,7 +45,7 @@ export const collectContentRuleActions = (fileKey, destination, contentRules = [ * Apply a single named pathRule type to a pathname and return the candidate key, * or null if the rule does not succeed (candidate not in files). * - * @param {object} rule + * @param {{ type: PathRuleType, match?: string, resolveAs?: string }} rule * @param {string} pathname * @param {object} files - manifest files map * @returns {string|null} @@ -54,7 +58,7 @@ const applyPathRule = (rule, pathname, files) => { const lastSegment = pathname.split('/').pop(); const hasExtension = lastSegment.includes('.'); - if (rule.type === 'directory-index') { + if (rule.type === PATH_RULE_TYPE.DIRECTORY_INDEX) { if (hasExtension) { return null; } @@ -63,7 +67,7 @@ const applyPathRule = (rule, pathname, files) => { return files[candidate] !== undefined ? candidate : null; } - if (rule.type === 'html-extension') { + if (rule.type === PATH_RULE_TYPE.HTML_EXTENSION) { if (hasExtension || pathname.endsWith('/')) { return null; } @@ -76,7 +80,7 @@ const applyPathRule = (rule, pathname, files) => { // Predicate: rule participates in normal key resolution (not an error-page fallback rule). const isApplicableRule = (pathname) => (r) => - r.type !== 'error-page' && + r.type !== PATH_RULE_TYPE.ERROR_PAGE && (!r.condition?.urlFilter || pathname.startsWith(r.condition.urlFilter)); // Predicate: rule is an error-page fallback matching the response status and request @@ -84,7 +88,7 @@ const isApplicableRule = (pathname) => (r) => // existing contentRule / files lookup decides byte-hash vs CSP-only vs unknown-key, // exactly like any normal navigation. Used as pathRules.find(isErrorPageRule(...)). const isErrorPageRule = (pathname, destination, status) => (r) => - r.type === 'error-page' && + r.type === PATH_RULE_TYPE.ERROR_PAGE && r.status === status && r.url && matchesCondition(r.condition, pathname, destination); @@ -163,6 +167,6 @@ export const isRequestAllowed = (req, locationHref, manifest) => { if (!manifest) return false; const key = resolveManifestKey(req, locationHref, manifest); return collectContentRuleActions(key, req.destination, manifest.contentRules).some( - (a) => a.type === 'allow' + (a) => a.type === CONTENT_ACTION_TYPE.ALLOW ); }; diff --git a/packages/dappfence/src/sw/manifest/security-verifier.js b/packages/dappfence/src/sw/manifest/security-verifier.js index 055835dc..4d1fa2ae 100644 --- a/packages/dappfence/src/sw/manifest/security-verifier.js +++ b/packages/dappfence/src/sw/manifest/security-verifier.js @@ -19,6 +19,7 @@ import { ASSET_TYPE, + CONTENT_ACTION_TYPE, enforcesCsp, isExecutableDestination, VERIFICATION_STATUS, @@ -46,24 +47,24 @@ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); const isRedirectStatus = (status) => REDIRECT_STATUSES.has(status); const ACTION_HANDLERS = { - allow: async (fileKey) => { + [CONTENT_ACTION_TYPE.ALLOW]: async (fileKey) => { logger.log(`⏭️ Skipping (allow): ${fileKey}`); return { status: VERIFICATION_STATUS.SKIPPED }; }, - deny: async (fileKey) => { + [CONTENT_ACTION_TYPE.DENY]: async (fileKey) => { logger.log(`❌ Denied by rule: ${fileKey}`); return { status: VERIFICATION_STATUS.DENIED_BY_RULE }; }, - rewrite: async (fileKey) => { + [CONTENT_ACTION_TYPE.REWRITE]: async (fileKey) => { logger.log(`↩️ Rewriting by rule: ${fileKey}`); return { status: VERIFICATION_STATUS.REWRITE }; }, - transform: handleTransform, - csp: async (fileKey) => { + [CONTENT_ACTION_TYPE.TRANSFORM]: handleTransform, + [CONTENT_ACTION_TYPE.CSP]: async (fileKey) => { logger.log(`⏭️ CSP-only (skip verify): ${fileKey}`); return { status: VERIFICATION_STATUS.CSP_PROTECTED }; }, - verify: async (fileKey, response, manifestInfo) => { + [CONTENT_ACTION_TYPE.VERIFY]: async (fileKey, response, manifestInfo) => { const hash = await response.calculateBodyHash(); if (hash.status) { return hash; @@ -455,7 +456,7 @@ export const securityVerifyAgainstManifest = async (req, response, manifestInfo, const { manifest } = manifestInfo; const fileKey = resolveManifestKey(req, locationHref, manifest, response); const actions = collectContentRuleActions(fileKey, req.destination, manifest?.contentRules); - const actionsToWalk = actions.length ? actions : [{ type: 'verify' }]; + const actionsToWalk = actions.length ? actions : [{ type: CONTENT_ACTION_TYPE.VERIFY }]; // Annotation needed because verdict() preserves literal types — without it // tsc would infer lastResult.status as the FILE_UNTRUSTED literal and flag // the SKIPPED comparison below as unreachable. diff --git a/packages/dappfence/src/sw/manifest/verification.js b/packages/dappfence/src/sw/manifest/verification.js index 4dcd6075..fcf1f77c 100644 --- a/packages/dappfence/src/sw/manifest/verification.js +++ b/packages/dappfence/src/sw/manifest/verification.js @@ -1,4 +1,4 @@ -import { ASSET_TYPE, VERIFICATION_STATUS } from '../../core/constants.js'; +import { ASSET_TYPE, SIGNATURE_TYPE, VERIFICATION_STATUS } from '../../core/constants.js'; import { recoverEthereumAddress, recoverPersonalSign } from '../../core/crypto.js'; import { createLogger } from '../../core/logger.js'; import { isFeatureEnabled } from '../../core/utils.js'; @@ -10,8 +10,8 @@ import { isFeatureEnabled } from '../../core/utils.js'; const logger = createLogger(); const MANIFEST_SIGNATURE_TYPES = { - 'noble-secp256k1-recovered-eth': recoverEthereumAddress, - 'personal-sign-alt': recoverPersonalSign, + [SIGNATURE_TYPE.NOBLE_SECP256K1_RECOVERED_ETH]: recoverEthereumAddress, + [SIGNATURE_TYPE.PERSONAL_SIGN_ALT]: recoverPersonalSign, }; /** diff --git a/packages/manifest-tools/src/build.js b/packages/manifest-tools/src/build.js index 6bfb8b8c..ccd3a39f 100644 --- a/packages/manifest-tools/src/build.js +++ b/packages/manifest-tools/src/build.js @@ -6,6 +6,7 @@ import { createHash } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { SIGNATURE_TYPE } from '@dappfence/core/constants'; import { + applyPersonalSignPrefix, sign, ethereumAddress, getPublicKey, @@ -16,16 +17,9 @@ import { import { assertValidManifestPayload } from './validate.js'; /** - * Signature types `signManifest` can actually produce. The SW's runtime - * verifier (`packages/dappfence/src/sw/manifest/verification.js`) recognizes - * more `manifestSignatureType` values than this build-time signer - * implements (e.g. `'personal-sign-alt'`, used only by test-app's - * interactive wallet-signing flow, which builds its manifest by hand rather - * than through `signManifest`). Every integration option that exposes - * `manifestSignatureType` must validate against this list — otherwise a - * manifest gets signed with `noble-secp256k1-recovered-eth` regardless, - * while the script tag declares a different type, and the SW rejects the - * mismatch as an unsupported/invalid signature. + * Signature types `signManifest` can produce. Mirrors the SW verifier's + * `MANIFEST_SIGNATURE_TYPES` so that the enum and the signer walk in lockstep: + * anything the SW verifies, `signManifest` can emit, and vice-versa. */ export const SUPPORTED_SIGNATURE_TYPES = Object.values(SIGNATURE_TYPE); @@ -58,16 +52,37 @@ export function calculateStringHash(content) { * on any unknown value — a typo like `mode: 'PROTECTED'` fails the build * instead of silently shipping a manifest the SW ignores. * + * `signatureType` selects which recovery scheme the signature targets. The + * NOBLE_SECP256K1_RECOVERED_ETH path signs the keccak256 of the JSON directly + * (matches `recoverEthereumAddress` in the SW). PERSONAL_SIGN_ALT wraps the + * digest in EIP-191's `"\x19Ethereum Signed Message:\n"` envelope before + * signing (matches `recoverPersonalSign`, what a wallet's eth_personalSign + * produces). + * * Unit tests that need to sign a partial/mocked payload may pass * `{ skipValidation: true }` to bypass the check. * * @param {object} manifestData - The manifest payload (e.g. { files: { ... }, metadata: { ... } }) * @param {object} keys * @param {string|Uint8Array} keys.secretKey - Hex string (with or without 0x) or raw bytes + * @param {string} [keys.signatureType] - A `SIGNATURE_TYPE` value (default NOBLE_SECP256K1_RECOVERED_ETH) * @param {boolean} [keys.skipValidation=false] - Opt out of schema validation (tests only) * @returns {{ pay: object, sig: string, identity: string, signatureType: string }} */ -export function signManifest(manifestData, { secretKey, skipValidation = false }) { +export function signManifest( + manifestData, + { + secretKey, + signatureType = SIGNATURE_TYPE.NOBLE_SECP256K1_RECOVERED_ETH, + skipValidation = false, + } +) { + if (!SUPPORTED_SIGNATURE_TYPES.includes(signatureType)) { + throw new Error( + `signManifest: unsupported signatureType ${JSON.stringify(signatureType)} ` + + `(supported: ${SUPPORTED_SIGNATURE_TYPES.join(', ')})` + ); + } if (!skipValidation) { assertValidManifestPayload(manifestData); } @@ -76,14 +91,12 @@ export function signManifest(manifestData, { secretKey, skipValidation = false } const pkBytes = getPublicKey(skBytes); const identity = ethereumAddress(pkBytes); const msg = new TextEncoder('utf-8').encode(JSON.stringify(manifestData, null, 2)); - const msgHash = keccak256(msg); + let msgHash = keccak256(msg); + if (signatureType === SIGNATURE_TYPE.PERSONAL_SIGN_ALT) { + msgHash = applyPersonalSignPrefix(msgHash); + } const sig = sign(msgHash, skBytes); - return { - pay: manifestData, - sig, - identity, - signatureType: SIGNATURE_TYPE.NOBLE_SECP256K1_RECOVERED_ETH, - }; + return { pay: manifestData, sig, identity, signatureType }; } /** diff --git a/packages/manifest-tools/src/cli.js b/packages/manifest-tools/src/cli.js index 4fc79e5d..e554580f 100755 --- a/packages/manifest-tools/src/cli.js +++ b/packages/manifest-tools/src/cli.js @@ -15,6 +15,7 @@ import { createHash } from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; +import { MODE } from '@dappfence/core/constants'; import { calculateFileHash, verifyManifest, deriveIdentity } from './build.js'; import { generateManifest, buildScriptAttrs, buildScriptTag } from './manifest.js'; import { loadMessages } from './messages.js'; @@ -81,7 +82,7 @@ async function cmdSign(dir, args) { const manifestPath = args['--out'] || 'integrity-manifest.json'; const scriptSrc = args['--script-src'] || '/dappfence.js'; const manifestUrl = args['--manifest-url'] || '/integrity-manifest.json'; - const mode = args['--mode'] || 'protected'; + const mode = args['--mode'] || MODE.PROTECTED; const noInject = '--no-inject' in args; const exclude = args['--exclude'] ? args['--exclude'].split(',') : []; const messagesDir = args['--messages'] || null; diff --git a/packages/manifest-tools/src/crypto.js b/packages/manifest-tools/src/crypto.js index 295e3aa2..aeaaed9a 100644 --- a/packages/manifest-tools/src/crypto.js +++ b/packages/manifest-tools/src/crypto.js @@ -35,12 +35,25 @@ export function recoverSigner(msgHash, signature) { return '0x' + secp.etc.bytesToHex(keccak.slice(-20)); } -export function recoverPersonalSign(msgHash, signature) { - const sigBytes = secp.etc.hexToBytes(signature); +/** + * Wrap a keccak256 digest in the EIP-191 `personal_sign` envelope: + * keccak256("\x19Ethereum Signed Message:\n" || digest). + * Single source of truth for the prefix — used by both `signManifest` + * (when producing PERSONAL_SIGN_ALT signatures) and `recoverPersonalSign` + * (when verifying them). + * @param {Uint8Array} msgHash - 32-byte keccak256 digest + * @returns {Uint8Array} + */ +export function applyPersonalSignPrefix(msgHash) { const prefix = '\x19Ethereum Signed Message:\n'; - const messageHash = keccak_256( + return keccak_256( secp.etc.concatBytes(new TextEncoder('utf-8').encode(prefix + msgHash.length), msgHash) ); +} + +export function recoverPersonalSign(msgHash, signature) { + const sigBytes = secp.etc.hexToBytes(signature); + const messageHash = applyPersonalSignPrefix(msgHash); const compressedPubKey = secp.recoverPublicKey(sigBytes, messageHash, { prehash: false }); const point = secp.Point.fromBytes(compressedPubKey); const keccak = keccak_256(point.toBytes(false).slice(1)); @@ -56,4 +69,5 @@ export function hexToBytes(hex) { } export const bytesToHex = secp.etc.bytesToHex; +export const concatBytes = secp.etc.concatBytes; export const keccak256 = keccak_256; diff --git a/packages/manifest-tools/src/manifest.js b/packages/manifest-tools/src/manifest.js index da32b8be..173a725b 100644 --- a/packages/manifest-tools/src/manifest.js +++ b/packages/manifest-tools/src/manifest.js @@ -5,7 +5,7 @@ import { promises as fs } from 'node:fs'; import path from 'node:path'; import { calculateFileHash, signManifest } from './build.js'; -import { TRANSFORM } from '@dappfence/core/constants'; +import { CONTENT_ACTION_TYPE, SIGNATURE_TYPE, TRANSFORM } from '@dappfence/core/constants'; import { extractInlineHashesFromHtml } from './inline-scripts.js'; import { assertValidMessages } from './messages.js'; @@ -122,15 +122,15 @@ export function buildNetlifyContentRules() { return [ { condition: { resourceTypes: ['document'] }, - action: { type: 'transform', transform: TRANSFORM.NETLIFY_CDP }, + action: { type: CONTENT_ACTION_TYPE.TRANSFORM, transform: TRANSFORM.NETLIFY_CDP }, }, { condition: { urlFilter: CDP_SCRIPT_PATH }, - action: { type: 'verify' }, + action: { type: CONTENT_ACTION_TYPE.VERIFY }, }, { condition: { urlFilter: CDP_SCRIPT_PATH }, - action: { type: 'rewrite' }, + action: { type: CONTENT_ACTION_TYPE.REWRITE }, }, ]; } @@ -178,7 +178,7 @@ export async function resolveNetlifyCdpHashes(logger) { export const SCRIPT_ATTRS_DEFAULTS = { scriptSrc: '/dappfence.js', manifestUrl: '/integrity-manifest.json', - manifestSignatureType: 'noble-secp256k1-recovered-eth', + manifestSignatureType: SIGNATURE_TYPE.NOBLE_SECP256K1_RECOVERED_ETH, }; export function buildScriptAttrs(opts = {}) { @@ -288,6 +288,7 @@ export async function generateManifest({ manifestPath, exclude, secretKey, + signatureType = SIGNATURE_TYPE.NOBLE_SECP256K1_RECOVERED_ETH, mode, pathRules, contentRules, @@ -399,7 +400,7 @@ export async function generateManifest({ let manifest; if (secretKey) { try { - manifest = signManifest(payload, { secretKey }); + manifest = signManifest(payload, { secretKey, signatureType }); logger.info('DappFence: manifest signed'); } catch (err) { logger.error(`DappFence: signing failed — ${err.message}`); diff --git a/packages/manifest-tools/src/validate.js b/packages/manifest-tools/src/validate.js index fc8a1628..95e2d016 100644 --- a/packages/manifest-tools/src/validate.js +++ b/packages/manifest-tools/src/validate.js @@ -138,11 +138,7 @@ function validateContentRules(rules) { } assertEnum(`manifest.contentRules[${i}].action.type`, action.type, CONTENT_ACTION_TYPE); if (action.type === CONTENT_ACTION_TYPE.TRANSFORM) { - assertEnum( - `manifest.contentRules[${i}].action.transform`, - action.transform, - TRANSFORM - ); + assertEnum(`manifest.contentRules[${i}].action.transform`, action.transform, TRANSFORM); } } } diff --git a/packages/next/bin/dappfence-next.js b/packages/next/bin/dappfence-next.js index 3d50b16d..f28bf0ca 100755 --- a/packages/next/bin/dappfence-next.js +++ b/packages/next/bin/dappfence-next.js @@ -193,6 +193,7 @@ async function runSSR(opts, projectRoot) { pathPrefix: basePath + '/_next/static', exclude: opts.exclude, secretKey, + signatureType: opts.manifestSignatureType, mode: opts.mode, pathRules: ssrPathRules, contentRules: [...cspRules, ...(isNetlify ? buildNetlifyContentRules() : [])], @@ -257,6 +258,7 @@ async function runStaticExport(opts, projectRoot) { manifestPath: opts.manifestPath, exclude: opts.exclude, secretKey, + signatureType: opts.manifestSignatureType, mode: opts.mode, pathRules: STATIC_EXPORT_PATH_RULES, contentRules: [...cspRules, ...(isNetlify ? buildNetlifyContentRules() : [])], diff --git a/packages/next/src/__tests__/generate.test.js b/packages/next/src/__tests__/generate.test.js index 9b278e28..165c7c93 100644 --- a/packages/next/src/__tests__/generate.test.js +++ b/packages/next/src/__tests__/generate.test.js @@ -508,10 +508,14 @@ describe('withDappfence', () => { }); it('rejects a manifestSignatureType the build-time signer cannot produce', () => { - expect(() => withDappfence({ manifestSignatureType: 'personal-sign-alt' })).toThrow( - /manifestSignatureType "personal-sign-alt" is not supported/ + expect(() => withDappfence({ manifestSignatureType: 'unknown-scheme' })).toThrow( + /manifestSignatureType "unknown-scheme" is not supported/ ); }); + + it('accepts personal-sign-alt now that signManifest produces it', () => { + expect(() => withDappfence({ manifestSignatureType: 'personal-sign-alt' })).not.toThrow(); + }); }); describe('DappfenceWebpackPlugin._copyDappfenceJs path containment', () => { diff --git a/packages/vite/src/__tests__/index.test.js b/packages/vite/src/__tests__/index.test.js index 9e553b47..c52602e6 100644 --- a/packages/vite/src/__tests__/index.test.js +++ b/packages/vite/src/__tests__/index.test.js @@ -40,9 +40,15 @@ describe('@dappfence/vite plugin shape', () => { }); it('rejects a manifestSignatureType the build-time signer cannot produce', () => { + expect(() => + dappfence({ secretKey: SECRET_KEY, manifestSignatureType: 'unknown-scheme' }) + ).toThrow(/manifestSignatureType "unknown-scheme" is not supported/); + }); + + it('accepts personal-sign-alt now that signManifest produces it', () => { expect(() => dappfence({ secretKey: SECRET_KEY, manifestSignatureType: 'personal-sign-alt' }) - ).toThrow(/manifestSignatureType "personal-sign-alt" is not supported/); + ).not.toThrow(); }); it('throws in configResolved when no secretKey is available', () => { diff --git a/packages/vite/src/index.js b/packages/vite/src/index.js index 836931e6..1666bf3a 100644 --- a/packages/vite/src/index.js +++ b/packages/vite/src/index.js @@ -217,6 +217,7 @@ export default function dappfence(options = {}) { manifestPath: opts.manifestPath, exclude: [...opts.exclude, scriptSrcWebKey], secretKey, + signatureType: opts.manifestSignatureType, mode: opts.mode, pathRules: opts.pathRules, contentRules: opts.contentRules, From 32d21ad94017a775c070a823eb4c3d2339b995fb Mon Sep 17 00:00:00 2001 From: adji Date: Fri, 4 Dec 2026 09:57:04 -0300 Subject: [PATCH 5/6] feat(sw/manifest-loader): permissive enum-based normalization MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mirrors the manifest-tools build-time validator on the SW side, but in permissive mode — the SW cannot throw at runtime without bricking every DF-protected site, so unknown values warn + drop + fall back instead of hard-failing. - `resolveMode` falls back to REPORTING on unknown/missing mode (log-only is the safer default when the integrator ships a typo). - `filterKnownPathRules` / `filterKnownContentRules` drop rules whose `type` / `action.type` isn't in the enum set, warning per drop. - `logsMinLevel` validation now uses Object.values(LOG_LEVEL) instead of an inline literal array — single source of truth with the enum. - Switch the "Resolved manifest from cache" line from logger.debug to logger.local.log; this one fires on every fetch during steady state and shouldn't flow through telemetry. --- .../src/sw/__tests__/manifest-loader.test.js | 27 +++++- .../src/sw/manifest/manifest-loader.js | 95 +++++++++++++++++-- 2 files changed, 115 insertions(+), 7 deletions(-) diff --git a/packages/dappfence/src/sw/__tests__/manifest-loader.test.js b/packages/dappfence/src/sw/__tests__/manifest-loader.test.js index 055c0c66..b96e83a9 100644 --- a/packages/dappfence/src/sw/__tests__/manifest-loader.test.js +++ b/packages/dappfence/src/sw/__tests__/manifest-loader.test.js @@ -262,7 +262,32 @@ describe('normalizeManifestData', () => { it('preserves pathRules', () => { const rules = [{ type: 'directory-index' }]; const result = normalizeManifestData({ files: {}, pathRules: rules }); - expect(result.pathRules).toBe(rules); + expect(result.pathRules).toEqual(rules); + }); + + it('drops pathRules with unknown type', () => { + const rules = [{ type: 'directory-index' }, { type: 'bogus-type' }]; + const result = normalizeManifestData({ files: {}, pathRules: rules }); + expect(result.pathRules).toEqual([{ type: 'directory-index' }]); + }); + + it('drops contentRules with unknown action.type', () => { + const rules = [ + { condition: {}, action: { type: 'verify' } }, + { condition: {}, action: { type: 'bogus-action' } }, + ]; + const result = normalizeManifestData({ files: {}, contentRules: rules }); + expect(result.contentRules).toEqual([{ condition: {}, action: { type: 'verify' } }]); + }); + + it('falls back to REPORTING on unknown mode (permissive)', () => { + const result = normalizeManifestData({ files: {}, mode: 'PROTECTED' }); + expect(result.mode).toBe('reporting'); + }); + + it('falls back to REPORTING when mode is missing', () => { + const result = normalizeManifestData({ files: {} }); + expect(result.mode).toBe('reporting'); }); it('returns a safe empty shape for non-objects', () => { diff --git a/packages/dappfence/src/sw/manifest/manifest-loader.js b/packages/dappfence/src/sw/manifest/manifest-loader.js index 60f78d8a..c239014e 100644 --- a/packages/dappfence/src/sw/manifest/manifest-loader.js +++ b/packages/dappfence/src/sw/manifest/manifest-loader.js @@ -5,7 +5,14 @@ * handoff. */ -import { ASSET_TYPE, MODE, VERIFICATION_STATUS } from '../../core/constants.js'; +import { + ASSET_TYPE, + CONTENT_ACTION_TYPE, + LOG_LEVEL, + MODE, + PATH_RULE_TYPE, + VERIFICATION_STATUS, +} from '../../core/constants.js'; import { calculateHash } from '../../core/crypto.js'; import { createSingleFlight, hasConfigManifest } from '../../core/utils.js'; import { toPathname, verifyManifestSignature } from './verification.js'; @@ -14,6 +21,7 @@ import { validateMessages } from '../../messages/index.js'; /** @typedef {import('../../core/constants.js').AssetType} AssetType */ /** @typedef {import('../../core/constants.js').ManifestLoadReason} ManifestLoadReason */ +/** @typedef {import('../../core/constants.js').Mode} Mode */ /** * Deterministic appVersion from the signed manifest payload: the SRI-formatted @@ -207,17 +215,17 @@ export const normalizeManifestData = (manifestData) => { const logsMinLevel = typeof manifestData?.logsMinLevel === 'string' && - ['debug', 'log', 'warn', 'error'].includes(manifestData.logsMinLevel) + Object.values(LOG_LEVEL).includes(manifestData.logsMinLevel) ? manifestData.logsMinLevel : null; return { ...(typeof manifestData === 'object' && manifestData !== null ? manifestData : {}), files: normalizedFiles, - pathRules: Array.isArray(manifestData?.pathRules) ? manifestData.pathRules : [], - contentRules: Array.isArray(manifestData?.contentRules) ? manifestData.contentRules : [], + pathRules: filterKnownPathRules(manifestData?.pathRules), + contentRules: filterKnownContentRules(manifestData?.contentRules), redirects: normalizeRedirects(manifestData?.redirects), - mode: manifestData?.mode ?? MODE.REPORTING, + mode: resolveMode(manifestData?.mode), csp, messages: normalizeMessages(manifestData?.messages), telemetry, @@ -225,6 +233,81 @@ export const normalizeManifestData = (manifestData) => { }; }; +/** + * Permissive mode resolver for the SW. Unknown values fall back to the + * safer REPORTING mode (log-only) and emit a warning so operators see the + * mismatch without losing their site. Throwing here would brick every + * DF-protected page whose manifest contains a typo. + * @param {unknown} value + * @returns {Mode} + */ +function resolveMode(value) { + if (value == null) { + return MODE.REPORTING; + } + if ( + typeof value === 'string' && + /** @type {string[]} */ (Object.values(MODE)).includes(value) + ) { + return /** @type {Mode} */ (value); + } + logger.warn( + `manifest.mode: unknown value ${JSON.stringify(value)}, falling back to ${MODE.REPORTING}. Expected one of: ${Object.values(MODE).join(', ')}.` + ); + return MODE.REPORTING; +} + +/** + * Drop rules with unrecognized `type`, warn on each drop. Known-type rules + * pass through untouched — their body-level fields (status, url, etc.) are + * validated by the rule handlers in rules.js. + * @param {unknown} rules + * @returns {Array} + */ +function filterKnownPathRules(rules) { + if (!Array.isArray(rules)) { + return []; + } + return rules.filter((rule, i) => { + if (!rule || typeof rule !== 'object') { + logger.warn(`manifest.pathRules[${i}]: not an object, skipping.`); + return false; + } + if (!Object.values(PATH_RULE_TYPE).includes(rule.type)) { + logger.warn( + `manifest.pathRules[${i}].type: unknown value ${JSON.stringify(rule.type)}, skipping. Expected one of: ${Object.values(PATH_RULE_TYPE).join(', ')}.` + ); + return false; + } + return true; + }); +} + +/** + * Drop contentRules with unrecognized `action.type` (or missing action); + * warn on each drop. Known-action rules pass through untouched. + * @param {unknown} rules + * @returns {Array} + */ +function filterKnownContentRules(rules) { + if (!Array.isArray(rules)) { + return []; + } + return rules.filter((rule, i) => { + if (!rule || typeof rule !== 'object' || !rule.action || typeof rule.action !== 'object') { + logger.warn(`manifest.contentRules[${i}]: missing or malformed action, skipping.`); + return false; + } + if (!Object.values(CONTENT_ACTION_TYPE).includes(rule.action.type)) { + logger.warn( + `manifest.contentRules[${i}].action.type: unknown value ${JSON.stringify(rule.action.type)}, skipping. Expected one of: ${Object.values(CONTENT_ACTION_TYPE).join(', ')}.` + ); + return false; + } + return true; + }); +} + /** * Integrator text overrides. manifest-tools already rejects bad entries at * build time; this re-checks so a hand-built manifest can only ever supply @@ -373,7 +456,7 @@ export const createManifestLoader = ({ swContext, appStore, config }) => { const resolveLatest = async () => { const cached = await trustedManifestStore.getLatest(); if (cached) { - logger.debug( + logger.local.log( `Resolved manifest from cache ${cached.appVersion} ${cached.manifest.mode}` ); return cached; From 4a31802e2eb62b16a07b69aaa1fa04431293c472 Mon Sep 17 00:00:00 2001 From: adji Date: Fri, 4 Dec 2026 15:56:31 -0300 Subject: [PATCH 6/6] test(sw/logger): fix flaky dedup timestamp assertion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The mid-test `getPendingLogs()` drain caused the second `log('a')` to start a fresh buffer entry, so `pending[0].ts` was a *new* `Date.now()` call separate from the captured `firstTs`. The assertion `pending[0].ts <= firstTs` only held when both calls landed in the same millisecond — flaky on CI under load (1 ms off). Drop the drain, log four times back-to-back, and keep the single `before <= ts` bound. The assertion no longer depends on sub-ms timing. Update count to 4 to match the new call count. --- packages/dappfence/src/core/__tests__/logger.test.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/dappfence/src/core/__tests__/logger.test.js b/packages/dappfence/src/core/__tests__/logger.test.js index 6d4d309b..0313288a 100644 --- a/packages/dappfence/src/core/__tests__/logger.test.js +++ b/packages/dappfence/src/core/__tests__/logger.test.js @@ -85,14 +85,12 @@ describe('createLogger — SW realm', () => { const logger = await freshLogger(); const before = Date.now(); logger.log('a'); - const firstTs = logger.getPendingLogs()[0].ts; logger.log('a'); logger.log('a'); logger.log('a'); const pending = logger.getPendingLogs(); expect(pending).toHaveLength(1); - expect(pending[0].count).toBe(3); - expect(pending[0].ts).toBeLessThanOrEqual(firstTs); + expect(pending[0].count).toBe(4); expect(pending[0].ts).toBeGreaterThanOrEqual(before); });