e2ed
Version:
E2E testing framework over Playwright
81 lines (80 loc) • 3.03 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.sanitizeJson = exports.sanitizeHtml = void 0;
exports.createSafeHtmlWithoutSanitize = createSafeHtmlWithoutSanitize;
exports.isSafeHtml = isSafeHtml;
exports.sanitizeValue = sanitizeValue;
const assertValueIsDefined_1 = require("./assertValueIsDefined");
const assertValueIsDefined = assertValueIsDefined_1.assertValueIsDefined;
/**
* Creates SafeHtml from string without sanitize.
* This base client function should not use scope variables (except other base functions).
* @internal
*/
function createSafeHtmlWithoutSanitize(stringParts, ...values) {
const key = Symbol.for('e2ed:SafeHtml:key');
const parts = [];
for (let index = 0; index < values.length; index += 1) {
const stringPart = stringParts[index];
assertValueIsDefined(stringPart);
const value = String(values[index]);
parts.push(stringPart, value);
}
const lastStringPart = stringParts.at(-1);
assertValueIsDefined(lastStringPart);
parts.push(lastStringPart);
const html = parts.join('');
// eslint-disable-next-line no-new-wrappers
const safeHtml = new String(html);
Object.defineProperty(safeHtml, key, { value: undefined });
return safeHtml;
}
/**
* Returns `true`, if value is `SafeHtml`, and `false` otherwise.
* This base client function should not use scope variables (except other base functions).
* @internal
*/
function isSafeHtml(value) {
const key = Symbol.for('e2ed:SafeHtml:key');
return typeof value === 'object' && value !== null && key in value;
}
/**
* Sanitizes arbitrary value.
* This base client function should not use scope variables (except other base functions).
* @internal
*/
function sanitizeValue(value) {
return String(value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
/**
* Sanitizes HTML code (simple protection against XSS attacks).
* This base client function should not use scope variables (except other base functions).
* @internal
*/
const sanitizeHtml = (stringParts, ...values) => {
const parts = [];
for (let index = 0; index < values.length; index += 1) {
const stringPart = stringParts[index];
assertValueIsDefined(stringPart);
const value = values[index];
const safeValue = isSafeHtml(value) ? String(value) : sanitizeValue(value);
parts.push(stringPart, safeValue);
}
const lastStringPart = stringParts.at(-1);
assertValueIsDefined(lastStringPart);
parts.push(lastStringPart);
const html = parts.join('');
return createSafeHtmlWithoutSanitize `${html}`;
};
exports.sanitizeHtml = sanitizeHtml;
/**
* Sanitizes JSON string (simple protection against XSS attacks).
* This base client function should not use scope variables (except other base functions).
* @internal
*/
const sanitizeJson = (json) => json.replace(/</g, '\\u003c');
exports.sanitizeJson = sanitizeJson;