attribute_builders.mjs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /**
  2. * @license
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. import '../environment/dev';
  6. import { createAttributePrefix } from '../internals/attribute_impl';
  7. import { assertIsTemplateObject } from '../internals/string_literal';
  8. import { SECURITY_SENSITIVE_ATTRIBUTES } from './sensitive_attributes';
  9. /**
  10. * Creates a SafeAttributePrefix object from a template literal with no
  11. * interpolations for attributes that share a common prefix guaranteed to be not
  12. * security sensitive.
  13. *
  14. * The template literal is a prefix that makes it obvious this attribute is not
  15. * security sensitive. If it doesn't, this function will throw.
  16. */
  17. export function safeAttrPrefix(templ) {
  18. if (process.env.NODE_ENV !== 'production') {
  19. assertIsTemplateObject(templ, true, 'safeAttr is a template literal tag function ' +
  20. 'and should be called using the tagged template syntax. ' +
  21. 'For example, safeAttr`foo`;');
  22. }
  23. const attrPrefix = templ[0].toLowerCase();
  24. if (process.env.NODE_ENV !== 'production') {
  25. if (attrPrefix.indexOf('on') === 0 || 'on'.indexOf(attrPrefix) === 0) {
  26. throw new Error(`Prefix '${templ[0]}' does not guarantee the attribute ` +
  27. `to be safe as it is also a prefix for event handler attributes` +
  28. `Please use 'addEventListener' to set event handlers.`);
  29. }
  30. SECURITY_SENSITIVE_ATTRIBUTES.forEach(sensitiveAttr => {
  31. if (sensitiveAttr.indexOf(attrPrefix) === 0) {
  32. throw new Error(`Prefix '${templ[0]}' does not guarantee the attribute ` +
  33. `to be safe as it is also a prefix for ` +
  34. `the security sensitive attribute '${sensitiveAttr}'. ` +
  35. `Please use native or safe DOM APIs to set the attribute.`);
  36. }
  37. });
  38. }
  39. return createAttributePrefix(attrPrefix);
  40. }