Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { ImportMap } from '../model/import-map';
import { tryCreateTrustedScript } from './trusted-types';

export function appendImportMap(importMap: ImportMap) {
document.head.appendChild(
Object.assign(document.createElement('script'), {
type: 'importmap-shim',
innerHTML: JSON.stringify(importMap),
type: tryCreateTrustedScript('importmap-shim'),
textContent: tryCreateTrustedScript(JSON.stringify(importMap)),
}),
);
}
95 changes: 95 additions & 0 deletions libs/native-federation-runtime/src/lib/utils/trusted-types.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import {
afterEach,
beforeEach,
describe,
expect,
expectTypeOf,
it,
vi,
} from 'vitest';

type TryCreateTrustedScript = (string: string) => string | TrustedScript;

describe('tryCreateTrustedScript', () => {
let tryCreateTrustedScript: TryCreateTrustedScript | undefined;

beforeEach(async () => {
// Setup
vi.resetModules();
const mod = await import('./trusted-types');
tryCreateTrustedScript = mod.tryCreateTrustedScript;
});

afterEach(() => {
// Clean up
delete (globalThis as any).trustedTypes;
vi.resetModules();
});

it('returns input when trustedTypes is undefined', () => {
// Setup
(globalThis as any).trustedTypes = undefined;
const input = 'alert(1)';

// Execute
const result = tryCreateTrustedScript!(input);

// Assert
expectTypeOf(result as string).toExtend<string>();
expect(result).toBe(input);
});

it('returns input when trustedTypes is defined', () => {
// Setup
const input = 'alert(1)';

// Execute
const result = tryCreateTrustedScript!(input);

// Assert
expectTypeOf(result as TrustedScript).toExtend<TrustedScript>();
expect(result).toBe(input);
});

it('caches policy and only calls createPolicy once', () => {
// Setup
let createPolicyMock = vi.fn(() => ({
createScript: (s: string) => `CACHE:${s}`,
createHTML: (h: string) => h,
createScriptURL: (u: string) => u,
}));

(globalThis as any).trustedTypes = {
createPolicy: createPolicyMock,
};

// Execute
const result1 = tryCreateTrustedScript!('a=1');
const result2 = tryCreateTrustedScript!('b=2');

// Assert
expect(result1).toBe(`CACHE:a=1`);
expect(result2).toBe(`CACHE:b=2`);
expect(createPolicyMock).toHaveBeenCalledTimes(1);
});

it('falls back when createPolicy throws', () => {
// Setup
const createPolicyMock = vi.fn(() => {
throw new Error('policy exists');
});

(globalThis as any).trustedTypes = {
createPolicy: createPolicyMock,
};

const input = 'console.log("fallback")';
// Execute
const result = tryCreateTrustedScript!(input);

// Assert
expect(typeof result).toBe('string');
expect(result).toBe(input);
expect(createPolicyMock).toHaveBeenCalled();
});
});
30 changes: 30 additions & 0 deletions libs/native-federation-runtime/src/lib/utils/trusted-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { TrustedTypePolicy, TrustedTypePolicyFactory } from 'trusted-types';

const global: any = globalThis;

let policy: TrustedTypePolicy | null | undefined;

function createPolicy(): TrustedTypePolicy | null {
if (policy === undefined) {
policy = null;
if (global.trustedTypes) {
try {
policy = (global.trustedTypes as TrustedTypePolicyFactory).createPolicy(
'native-federation',
{
createHTML: (html: string) => html,
createScript: (script: string) => script,
createScriptURL: (url: string) => url,
},
);
} catch {
// trustedTypes.createPolicy may throw an exception if called with a name that is already registered, even in report-only mode.
}
}
}
return policy;
}

export function tryCreateTrustedScript(script: string): string | TrustedScript {
return createPolicy()?.createScript(script) ?? script;
}
8 changes: 8 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@
"@types/browser-sync": "^2.29.0",
"@types/jest": "^29.5.0",
"@types/node": "^24.9.0",
"@types/trusted-types": "^2.0.7",
"@typescript-eslint/eslint-plugin": "^8.46.0",
"@typescript-eslint/parser": "^8.46.0",
"@typescript-eslint/utils": "^8.46.0",
Expand Down