Debian Codegraph @

tpl/internal/go_templates/htmltemplate/js.go

raw
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package template
6
7 import (
8 "bytes"
9 "encoding/json"
10 "fmt"
11 htmltemplate "html/template"
12 "reflect"
13 "regexp"
14 "strings"
15 "unicode/utf8"
16 )
17
18 // jsWhitespace contains all of the JS whitespace characters, as defined
19 // by the \s character class.
20 // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes.
21 const jsWhitespace = "\f\n\r\t\v\u0020\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff"
22
23 // nextJSCtx returns the context that determines whether a slash after the
24 // given run of tokens starts a regular expression instead of a division
25 // operator: / or /=.
26 //
27 // This assumes that the token run does not include any string tokens, comment
28 // tokens, regular expression literal tokens, or division operators.
29 //
30 // This fails on some valid but nonsensical JavaScript programs like
31 // "x = ++/foo/i" which is quite different than "x++/foo/i", but is not known to
32 // fail on any known useful programs. It is based on the draft
33 // JavaScript 2.0 lexical grammar and requires one token of lookbehind:
34 // https://www.mozilla.org/js/language/js20-2000-07/rationale/syntax.html
35 func nextJSCtx(s []byte, preceding jsCtx) jsCtx {
36 // Trim all JS whitespace characters
37 s = bytes.TrimRight(s, jsWhitespace)
38 if len(s) == 0 {
39 return preceding
40 }
41
42 // All cases below are in the single-byte UTF-8 group.
43 switch c, n := s[len(s)-1], len(s); c {
44 case '+', '-':
45 // ++ and -- are not regexp preceders, but + and - are whether
46 // they are used as infix or prefix operators.
47 start := n - 1
48 // Count the number of adjacent dashes or pluses.
49 for start > 0 && s[start-1] == c {
50 start--
51 }
52 if (n-start)&1 == 1 {
53 // Reached for trailing minus signs since "---" is the
54 // same as "-- -".
55 return jsCtxRegexp
56 }
57 return jsCtxDivOp
58 case '.':
59 // Handle "42."
60 if n != 1 && '0' <= s[n-2] && s[n-2] <= '9' {
61 return jsCtxDivOp
62 }
63 return jsCtxRegexp
64 // Suffixes for all punctuators from section 7.7 of the language spec
65 // that only end binary operators not handled above.
66 case ',', '<', '>', '=', '*', '%', '&', '|', '^', '?':
67 return jsCtxRegexp
68 // Suffixes for all punctuators from section 7.7 of the language spec
69 // that are prefix operators not handled above.
70 case '!', '~':
71 return jsCtxRegexp
72 // Matches all the punctuators from section 7.7 of the language spec
73 // that are open brackets not handled above.
74 case '(', '[':
75 return jsCtxRegexp
76 // Matches all the punctuators from section 7.7 of the language spec
77 // that precede expression starts.
78 case ':', ';', '{':
79 return jsCtxRegexp
80 // CAVEAT: the close punctuators ('}', ']', ')') precede div ops and
81 // are handled in the default except for '}' which can precede a
82 // division op as in
83 // ({ valueOf: function () { return 42 } } / 2
84 // which is valid, but, in practice, developers don't divide object
85 // literals, so our heuristic works well for code like
86 // function () { ... } /foo/.test(x) && sideEffect();
87 // The ')' punctuator can precede a regular expression as in
88 // if (b) /foo/.test(x) && ...
89 // but this is much less likely than
90 // (a + b) / c
91 case '}':
92 return jsCtxRegexp
93 default:
94 // Look for an IdentifierName and see if it is a keyword that
95 // can precede a regular expression.
96 j := n
97 for j > 0 && isJSIdentPart(rune(s[j-1])) {
98 j--
99 }
100 if regexpPrecederKeywords[string(s[j:])] {
101 return jsCtxRegexp
102 }
103 }
104 // Otherwise is a punctuator not listed above, or
105 // a string which precedes a div op, or an identifier
106 // which precedes a div op.
107 return jsCtxDivOp
108 }
109
110 // regexpPrecederKeywords is a set of reserved JS keywords that can precede a
111 // regular expression in JS source.
112 var regexpPrecederKeywords = map[string]bool{
113 "break": true,
114 "case": true,
115 "continue": true,
116 "delete": true,
117 "do": true,
118 "else": true,
119 "finally": true,
120 "in": true,
121 "instanceof": true,
122 "return": true,
123 "throw": true,
124 "try": true,
125 "typeof": true,
126 "void": true,
127 }
128
129 var jsonMarshalType = reflect.TypeFor[json.Marshaler]()
130
131 // indirectToJSONMarshaler returns the value, after dereferencing as many times
132 // as necessary to reach the base type (or nil) or an implementation of json.Marshal.
133 func indirectToJSONMarshaler(a any) any {
134 // text/template now supports passing untyped nil as a func call
135 // argument, so we must support it. Otherwise we'd panic below, as one
136 // cannot call the Type or Interface methods on an invalid
137 // reflect.Value. See golang.org/issue/18716.
138 if a == nil {
139 return nil
140 }
141
142 v := reflect.ValueOf(a)
143 for !v.Type().Implements(jsonMarshalType) && v.Kind() == reflect.Pointer && !v.IsNil() {
144 v = v.Elem()
145 }
146 return v.Interface()
147 }
148
149 var scriptTagRe = regexp.MustCompile("(?i)<(/?)script")
150
151 // jsValEscaper escapes its inputs to a JS Expression (section 11.14) that has
152 // neither side-effects nor free variables outside (NaN, Infinity).
153 func jsValEscaper(args ...any) string {
154 var a any
155 if len(args) == 1 {
156 a = indirectToJSONMarshaler(args[0])
157 switch t := a.(type) {
158 case htmltemplate.JS:
159 return string(t)
160 case htmltemplate.JSStr:
161 // TODO: normalize quotes.
162 return `"` + string(t) + `"`
163 case json.Marshaler:
164 // Do not treat as a Stringer.
165 case fmt.Stringer:
166 a = t.String()
167 }
168 } else {
169 for i, arg := range args {
170 args[i] = indirectToJSONMarshaler(arg)
171 }
172 a = fmt.Sprint(args...)
173 }
174 // TODO: detect cycles before calling Marshal which loops infinitely on
175 // cyclic data. This may be an unacceptable DoS risk.
176 b, err := json.Marshal(a)
177 if err != nil {
178 // While the standard JSON marshaler does not include user controlled
179 // information in the error message, if a type has a MarshalJSON method,
180 // the content of the error message is not guaranteed. Since we insert
181 // the error into the template, as part of a comment, we attempt to
182 // prevent the error from either terminating the comment, or the script
183 // block itself.
184 //
185 // In particular we:
186 // * replace "*/" comment end tokens with "* /", which does not
187 // terminate the comment
188 // * replace "<script" and "</script" with "\x3Cscript" and "\x3C/script"
189 // (case insensitively), and "<!--" with "\x3C!--", which prevents
190 // confusing script block termination semantics
191 //
192 // We also put a space before the comment so that if it is flush against
193 // a division operator it is not turned into a line comment:
194 // x/{{y}}
195 // turning into
196 // x//* error marshaling y:
197 // second line of error message */null
198 errStr := err.Error()
199 errStr = string(scriptTagRe.ReplaceAll([]byte(errStr), []byte(`\x3C${1}script`)))
200 errStr = strings.ReplaceAll(errStr, "*/", "* /")
201 errStr = strings.ReplaceAll(errStr, "<!--", `\x3C!--`)
202 return fmt.Sprintf(" /* %s */null ", errStr)
203 }
204
205 // TODO: maybe post-process output to prevent it from containing
206 // "<!--", "-->", "<![CDATA[", "]]>", or "</script"
207 // in case custom marshalers produce output containing those.
208 // Note: Do not use \x escaping to save bytes because it is not JSON compatible and this escaper
209 // supports ld+json content-type.
210 if len(b) == 0 {
211 // In, `x=y/{{.}}*z` a json.Marshaler that produces "" should
212 // not cause the output `x=y/*z`.
213 return " null "
214 }
215 first, _ := utf8.DecodeRune(b)
216 last, _ := utf8.DecodeLastRune(b)
217 var buf strings.Builder
218 // Prevent IdentifierNames and NumericLiterals from running into
219 // keywords: in, instanceof, typeof, void
220 pad := isJSIdentPart(first) || isJSIdentPart(last)
221 if pad {
222 buf.WriteByte(' ')
223 }
224 written := 0
225 // Make sure that json.Marshal escapes codepoints U+2028 & U+2029
226 // so it falls within the subset of JSON which is valid JS.
227 for i := 0; i < len(b); {
228 rune, n := utf8.DecodeRune(b[i:])
229 repl := ""
230 if rune == 0x2028 {
231 repl = `\u2028`
232 } else if rune == 0x2029 {
233 repl = `\u2029`
234 }
235 if repl != "" {
236 buf.Write(b[written:i])
237 buf.WriteString(repl)
238 written = i + n
239 }
240 i += n
241 }
242 if buf.Len() != 0 {
243 buf.Write(b[written:])
244 if pad {
245 buf.WriteByte(' ')
246 }
247 return buf.String()
248 }
249 return string(b)
250 }
251
252 // jsStrEscaper produces a string that can be included between quotes in
253 // JavaScript source, in JavaScript embedded in an HTML5 <script> element,
254 // or in an HTML5 event handler attribute such as onclick.
255 func jsStrEscaper(args ...any) string {
256 s, t := stringify(args...)
257 if t == contentTypeJSStr {
258 return replace(s, jsStrNormReplacementTable)
259 }
260 return replace(s, jsStrReplacementTable)
261 }
262
263 func jsTmplLitEscaper(args ...any) string {
264 s, _ := stringify(args...)
265 return replace(s, jsBqStrReplacementTable)
266 }
267
268 // jsRegexpEscaper behaves like jsStrEscaper but escapes regular expression
269 // specials so the result is treated literally when included in a regular
270 // expression literal. /foo{{.X}}bar/ matches the string "foo" followed by
271 // the literal text of {{.X}} followed by the string "bar".
272 func jsRegexpEscaper(args ...any) string {
273 s, _ := stringify(args...)
274 s = replace(s, jsRegexpReplacementTable)
275 if s == "" {
276 // /{{.X}}/ should not produce a line comment when .X == "".
277 return "(?:)"
278 }
279 return s
280 }
281
282 // replace replaces each rune r of s with replacementTable[r], provided that
283 // r < len(replacementTable). If replacementTable[r] is the empty string then
284 // no replacement is made.
285 // It also replaces runes U+2028 and U+2029 with the raw strings `\u2028` and
286 // `\u2029`.
287 func replace(s string, replacementTable []string) string {
288 var b strings.Builder
289 r, w, written := rune(0), 0, 0
290 for i := 0; i < len(s); i += w {
291 // See comment in htmlEscaper.
292 r, w = utf8.DecodeRuneInString(s[i:])
293 var repl string
294 switch {
295 case int(r) < len(lowUnicodeReplacementTable):
296 repl = lowUnicodeReplacementTable[r]
297 case int(r) < len(replacementTable) && replacementTable[r] != "":
298 repl = replacementTable[r]
299 case r == '\u2028':
300 repl = `\u2028`
301 case r == '\u2029':
302 repl = `\u2029`
303 default:
304 continue
305 }
306 if written == 0 {
307 b.Grow(len(s))
308 }
309 b.WriteString(s[written:i])
310 b.WriteString(repl)
311 written = i + w
312 }
313 if written == 0 {
314 return s
315 }
316 b.WriteString(s[written:])
317 return b.String()
318 }
319
320 var lowUnicodeReplacementTable = []string{
321 0: `\u0000`, 1: `\u0001`, 2: `\u0002`, 3: `\u0003`, 4: `\u0004`, 5: `\u0005`, 6: `\u0006`,
322 '\a': `\u0007`,
323 '\b': `\u0008`,
324 '\t': `\t`,
325 '\n': `\n`,
326 '\v': `\u000b`, // "\v" == "v" on IE 6.
327 '\f': `\f`,
328 '\r': `\r`,
329 0xe: `\u000e`, 0xf: `\u000f`, 0x10: `\u0010`, 0x11: `\u0011`, 0x12: `\u0012`, 0x13: `\u0013`,
330 0x14: `\u0014`, 0x15: `\u0015`, 0x16: `\u0016`, 0x17: `\u0017`, 0x18: `\u0018`, 0x19: `\u0019`,
331 0x1a: `\u001a`, 0x1b: `\u001b`, 0x1c: `\u001c`, 0x1d: `\u001d`, 0x1e: `\u001e`, 0x1f: `\u001f`,
332 }
333
334 var jsStrReplacementTable = []string{
335 0: `\u0000`,
336 '\t': `\t`,
337 '\n': `\n`,
338 '\v': `\u000b`, // "\v" == "v" on IE 6.
339 '\f': `\f`,
340 '\r': `\r`,
341 // Encode HTML specials as hex so the output can be embedded
342 // in HTML attributes without further encoding.
343 '"': `\u0022`,
344 '`': `\u0060`,
345 '&': `\u0026`,
346 '\'': `\u0027`,
347 '+': `\u002b`,
348 '/': `\/`,
349 '<': `\u003c`,
350 '>': `\u003e`,
351 '\\': `\\`,
352 }
353
354 // jsBqStrReplacementTable is like jsStrReplacementTable except it also contains
355 // the special characters for JS template literals: $, {, and }.
356 var jsBqStrReplacementTable = []string{
357 0: `\u0000`,
358 '\t': `\t`,
359 '\n': `\n`,
360 '\v': `\u000b`, // "\v" == "v" on IE 6.
361 '\f': `\f`,
362 '\r': `\r`,
363 // Encode HTML specials as hex so the output can be embedded
364 // in HTML attributes without further encoding.
365 '"': `\u0022`,
366 '`': `\u0060`,
367 '&': `\u0026`,
368 '\'': `\u0027`,
369 '+': `\u002b`,
370 '/': `\/`,
371 '<': `\u003c`,
372 '>': `\u003e`,
373 '\\': `\\`,
374 '$': `\u0024`,
375 '{': `\u007b`,
376 '}': `\u007d`,
377 }
378
379 // jsStrNormReplacementTable is like jsStrReplacementTable but does not
380 // overencode existing escapes since this table has no entry for `\`.
381 var jsStrNormReplacementTable = []string{
382 0: `\u0000`,
383 '\t': `\t`,
384 '\n': `\n`,
385 '\v': `\u000b`, // "\v" == "v" on IE 6.
386 '\f': `\f`,
387 '\r': `\r`,
388 // Encode HTML specials as hex so the output can be embedded
389 // in HTML attributes without further encoding.
390 '"': `\u0022`,
391 '&': `\u0026`,
392 '\'': `\u0027`,
393 '`': `\u0060`,
394 '+': `\u002b`,
395 '/': `\/`,
396 '<': `\u003c`,
397 '>': `\u003e`,
398 }
399 var jsRegexpReplacementTable = []string{
400 0: `\u0000`,
401 '\t': `\t`,
402 '\n': `\n`,
403 '\v': `\u000b`, // "\v" == "v" on IE 6.
404 '\f': `\f`,
405 '\r': `\r`,
406 // Encode HTML specials as hex so the output can be embedded
407 // in HTML attributes without further encoding.
408 '"': `\u0022`,
409 '$': `\$`,
410 '&': `\u0026`,
411 '\'': `\u0027`,
412 '(': `\(`,
413 ')': `\)`,
414 '*': `\*`,
415 '+': `\u002b`,
416 '-': `\-`,
417 '.': `\.`,
418 '/': `\/`,
419 '<': `\u003c`,
420 '>': `\u003e`,
421 '?': `\?`,
422 '[': `\[`,
423 '\\': `\\`,
424 ']': `\]`,
425 '^': `\^`,
426 '{': `\{`,
427 '|': `\|`,
428 '}': `\}`,
429 }
430
431 // isJSIdentPart reports whether the given rune is a JS identifier part.
432 // It does not handle all the non-Latin letters, joiners, and combining marks,
433 // but it does handle every codepoint that can occur in a numeric literal or
434 // a keyword.
435 func isJSIdentPart(r rune) bool {
436 switch {
437 case r == '$':
438 return true
439 case '0' <= r && r <= '9':
440 return true
441 case 'A' <= r && r <= 'Z':
442 return true
443 case r == '_':
444 return true
445 case 'a' <= r && r <= 'z':
446 return true
447 }
448 return false
449 }
450
451 // isJSType reports whether the given MIME type should be considered JavaScript.
452 //
453 // It is used to determine whether a script tag with a type attribute is a javascript container.
454 func isJSType(mimeType string) bool {
455 // per
456 // https://www.w3.org/TR/html5/scripting-1.html#attr-script-type
457 // https://tools.ietf.org/html/rfc7231#section-3.1.1
458 // https://tools.ietf.org/html/rfc4329#section-3
459 // https://www.ietf.org/rfc/rfc4627.txt
460 // discard parameters
461 mimeType, _, _ = strings.Cut(mimeType, ";")
462 mimeType = strings.ToLower(mimeType)
463 mimeType = strings.TrimSpace(mimeType)
464 switch mimeType {
465 case
466 "",
467 "application/ecmascript",
468 "application/javascript",
469 "application/json",
470 "application/ld+json",
471 "application/x-ecmascript",
472 "application/x-javascript",
473 "module",
474 "text/ecmascript",
475 "text/javascript",
476 "text/javascript1.0",
477 "text/javascript1.1",
478 "text/javascript1.2",
479 "text/javascript1.3",
480 "text/javascript1.4",
481 "text/javascript1.5",
482 "text/jscript",
483 "text/livescript",
484 "text/x-ecmascript",
485 "text/x-javascript":
486 return true
487 default:
488 return false
489 }
490 }