Skip to content

Commit

Permalink
feat(message-compiler): export html tag checking (#1359)
Browse files Browse the repository at this point in the history
* feat(message-compiler): export html tag checking

* fix: lint warnings
  • Loading branch information
kazupon committed Mar 22, 2023
1 parent 03664f4 commit 0de0f9c
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 9 deletions.
21 changes: 13 additions & 8 deletions packages/core-base/src/compile.ts
@@ -1,17 +1,17 @@
import { warn, format, isBoolean } from '@intlify/shared'
import { baseCompile, defaultOnError } from '@intlify/message-compiler'
import {
baseCompile,
defaultOnError,
detectHtmlTag
} from '@intlify/message-compiler'

import type { CompileOptions, CompileError } from '@intlify/message-compiler'
import type { MessageFunction, MessageFunctions } from './runtime'

const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/
const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`

function checkHtmlMessage(source: string, options: CompileOptions): void {
const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true
if (warnHtmlMessage && RE_HTML_TAG.test(source)) {
function checkHtmlMessage(source: string, warnHtmlMessage?: boolean): void {
if (warnHtmlMessage && detectHtmlTag(source)) {
warn(format(WARN_MESSAGE, { source }))
}
}
Expand All @@ -37,7 +37,12 @@ export function compileToFunction<T = string>(
return (() => source) as MessageFunction<T>
} else {
// check HTML message
__DEV__ && checkHtmlMessage(source, options)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const warnHtmlMessage = isBoolean((options as any).warnHtmlMessage)
? // eslint-disable-next-line @typescript-eslint/no-explicit-any
(options as any).warnHtmlMessage
: true
__DEV__ && checkHtmlMessage(source, warnHtmlMessage)

// check caches
const onCacheKey = options.onCacheKey || defaultOnCacheKey
Expand Down
5 changes: 5 additions & 0 deletions packages/message-compiler/src/helpers.ts
Expand Up @@ -8,3 +8,8 @@ export const enum HelperNameMap {
INTERPOLATE = 'interpolate',
NORMALIZE = 'normalize'
}

const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/

export const detectHtmlTag = (source: string): boolean =>
RE_HTML_TAG.test(source)
1 change: 0 additions & 1 deletion packages/message-compiler/src/options.ts
Expand Up @@ -31,7 +31,6 @@ export interface CodeGenOptions {
}

export type CompileOptions = {
warnHtmlMessage?: boolean
onCacheKey?: CompileCacheKeyHandler
} & TransformOptions &
CodeGenOptions &
Expand Down

0 comments on commit 0de0f9c

Please sign in to comment.