Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion packages/astro/src/__tests__/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});

Expand Down
1 change: 1 addition & 0 deletions packages/astro/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 1 addition & 3 deletions packages/dappfence/src/core/__tests__/logger.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

Expand Down
59 changes: 57 additions & 2 deletions packages/dappfence/src/core/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,64 @@ export const MSG = {

export const SYNC_TAG_TELEMETRY = 'dappfence-sync-tag-telemetry';

export const MODE = {
/**
* 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 = 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',
DENY: 'deny',
});
/** @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',
PERSONAL_SIGN_ALT: 'personal-sign-alt',
});
/** @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.
Expand Down Expand Up @@ -196,3 +250,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 */
24 changes: 15 additions & 9 deletions packages/dappfence/src/core/crypto.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,21 +51,27 @@ 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<len>" || 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
* @param {string} signature - Hex-encoded 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 }));
}
51 changes: 36 additions & 15 deletions packages/dappfence/src/sw/__tests__/manifest-loader.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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([])),
},
Expand Down Expand Up @@ -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(/^sha256-[A-Za-z0-9+/]{43}=$/);
expect(appStore.trustedManifestStore.addLatest).toHaveBeenCalledWith({
appVersion: result.appVersion,
signedEnvelope: { pay: VALID_PAYLOAD, sig: 'sig' },
manifest: normalizeManifestData(VALID_PAYLOAD),
});
});
});

Expand Down Expand Up @@ -266,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', () => {
Expand Down
Loading
Loading