|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google LLC All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.io/license |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * @fileoverview |
| 11 | + * A module to facilitate use of a Trusted Types policy internally within |
| 12 | + * Angular Material. It lazily constructs the Trusted Types policy, providing |
| 13 | + * helper utilities for promoting strings to Trusted Types. When Trusted Types |
| 14 | + * are not available, strings are used as a fallback. |
| 15 | + * @security All use of this module is security-sensitive and should go through |
| 16 | + * security review. |
| 17 | + */ |
| 18 | + |
| 19 | +export declare interface TrustedHTML { |
| 20 | + __brand__: 'TrustedHTML'; |
| 21 | +} |
| 22 | + |
| 23 | +export declare interface TrustedTypePolicyFactory { |
| 24 | + createPolicy(policyName: string, policyOptions: { |
| 25 | + createHTML?: (input: string) => string, |
| 26 | + }): TrustedTypePolicy; |
| 27 | +} |
| 28 | + |
| 29 | +export declare interface TrustedTypePolicy { |
| 30 | + createHTML(input: string): TrustedHTML; |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * The Trusted Types policy, or null if Trusted Types are not |
| 35 | + * enabled/supported, or undefined if the policy has not been created yet. |
| 36 | + */ |
| 37 | +let policy: TrustedTypePolicy|null|undefined; |
| 38 | + |
| 39 | +/** |
| 40 | + * Returns the Trusted Types policy, or null if Trusted Types are not |
| 41 | + * enabled/supported. The first call to this function will create the policy. |
| 42 | + */ |
| 43 | +function getPolicy(): TrustedTypePolicy|null { |
| 44 | + if (policy === undefined) { |
| 45 | + policy = null; |
| 46 | + if (typeof window !== 'undefined') { |
| 47 | + const ttWindow = window as unknown as {trustedTypes?: TrustedTypePolicyFactory}; |
| 48 | + if (ttWindow.trustedTypes !== undefined) { |
| 49 | + policy = ttWindow.trustedTypes.createPolicy('angular#material', { |
| 50 | + createHTML: (s: string) => s, |
| 51 | + }); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + return policy; |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * Unsafely promote a string to a TrustedHTML, falling back to strings when |
| 60 | + * Trusted Types are not available. |
| 61 | + * @security This is a security-sensitive function; any use of this function |
| 62 | + * must go through security review. In particular, it must be assured that the |
| 63 | + * provided string will never cause an XSS vulnerability if used in a context |
| 64 | + * that will be interpreted as HTML by a browser, e.g. when assigning to |
| 65 | + * element.innerHTML. |
| 66 | + */ |
| 67 | +export function trustedHTMLFromString(html: string): TrustedHTML { |
| 68 | + return getPolicy()?.createHTML(html) || html as unknown as TrustedHTML; |
| 69 | +} |
0 commit comments