@astryxdesign/core 0.6.3-canary.f22695a → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/dist/Button/Button.d.ts.map +1 -1
  2. package/dist/Button/Button.js +28 -13
  3. package/dist/Chat/ChatLayout.d.ts +0 -19
  4. package/dist/Chat/ChatLayout.d.ts.map +1 -1
  5. package/dist/Chat/ChatLayout.js +0 -19
  6. package/dist/Chat/ChatLayoutScrollButton.d.ts.map +1 -1
  7. package/dist/Chat/ChatLayoutScrollButton.js +34 -44
  8. package/dist/Citation/Citation.d.ts +1 -1
  9. package/dist/Citation/Citation.d.ts.map +1 -1
  10. package/dist/Citation/Citation.js +2 -3
  11. package/dist/CodeBlock/highlightRanges.d.ts.map +1 -1
  12. package/dist/CodeBlock/highlightRanges.js +3 -14
  13. package/dist/Icon/Icon.d.ts +31 -6
  14. package/dist/Icon/Icon.d.ts.map +1 -1
  15. package/dist/Icon/Icon.js +71 -8
  16. package/dist/Link/useLinkComponent.d.ts +15 -5
  17. package/dist/Link/useLinkComponent.d.ts.map +1 -1
  18. package/dist/Link/useLinkComponent.js +51 -34
  19. package/dist/Markdown/Markdown.js +2 -2
  20. package/dist/Markdown/url.d.ts +0 -2
  21. package/dist/Markdown/url.d.ts.map +1 -1
  22. package/dist/Markdown/url.js +2 -8
  23. package/dist/PowerSearch/PowerSearchValueEditor.d.ts.map +1 -1
  24. package/dist/PowerSearch/PowerSearchValueEditor.js +0 -5
  25. package/dist/TopNav/TopNavMenu.d.ts +1 -1
  26. package/dist/TopNav/TopNavMenu.d.ts.map +1 -1
  27. package/dist/TopNav/TopNavMenu.js +2 -3
  28. package/dist/astryx.css +4 -2
  29. package/dist/hooks/useClickableContainer.d.ts +1 -10
  30. package/dist/hooks/useClickableContainer.d.ts.map +1 -1
  31. package/dist/hooks/useClickableContainer.js +4 -15
  32. package/dist/index.d.ts +0 -1
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +0 -3
  35. package/dist/theme/generateThemeRules.d.ts +7 -13
  36. package/dist/theme/generateThemeRules.d.ts.map +1 -1
  37. package/dist/theme/generateThemeRules.js +35 -131
  38. package/package.json +4 -9
  39. package/src/Button/Button.doc.mjs +5 -5
  40. package/src/Button/Button.tsx +13 -15
  41. package/src/Chat/ChatLayout.doc.mjs +4 -12
  42. package/src/Chat/ChatLayout.test.tsx +0 -28
  43. package/src/Chat/ChatLayout.tsx +0 -19
  44. package/src/Chat/ChatLayoutScrollButton.test.tsx +0 -31
  45. package/src/Chat/ChatLayoutScrollButton.tsx +14 -31
  46. package/src/Citation/Citation.doc.mjs +2 -2
  47. package/src/Citation/Citation.test.tsx +0 -17
  48. package/src/Citation/Citation.tsx +2 -4
  49. package/src/ClickableCard/ClickableCard.doc.mjs +2 -2
  50. package/src/CodeBlock/highlightRanges.test.ts +1 -143
  51. package/src/CodeBlock/highlightRanges.ts +5 -15
  52. package/src/Icon/Icon.doc.mjs +5 -7
  53. package/src/Icon/Icon.spec.md +40 -81
  54. package/src/Icon/Icon.test.tsx +3 -6
  55. package/src/Icon/Icon.tsx +68 -20
  56. package/src/IconButton/IconButton.doc.mjs +3 -3
  57. package/src/IconButton/IconButton.test.tsx +0 -40
  58. package/src/Item/Item.doc.mjs +2 -2
  59. package/src/Link/Link.doc.mjs +4 -6
  60. package/src/Link/LinkProvider.doc.mjs +2 -2
  61. package/src/Link/useLinkComponent.test.tsx +0 -333
  62. package/src/Link/useLinkComponent.ts +57 -29
  63. package/src/List/ListItem.doc.mjs +2 -2
  64. package/src/Markdown/Markdown.doc.mjs +2 -2
  65. package/src/Markdown/Markdown.spec.md +15 -19
  66. package/src/Markdown/Markdown.test.tsx +0 -52
  67. package/src/Markdown/Markdown.tsx +2 -2
  68. package/src/Markdown/parser.test.ts +0 -20
  69. package/src/Markdown/url.ts +3 -9
  70. package/src/PowerSearch/PowerSearchValueEditor.test.tsx +0 -51
  71. package/src/PowerSearch/PowerSearchValueEditor.tsx +0 -4
  72. package/src/Token/Token.doc.mjs +2 -2
  73. package/src/TopNav/TopNavMenu.doc.mjs +2 -2
  74. package/src/TopNav/TopNavMenu.test.tsx +0 -30
  75. package/src/TopNav/TopNavMenu.tsx +2 -7
  76. package/src/hooks/useClickableContainer.ts +4 -20
  77. package/src/index.ts +0 -3
  78. package/src/tailwind-theme.css +6 -0
  79. package/src/theme/Theme.test.tsx +0 -32
  80. package/src/theme/generateThemeRules.test.ts +2 -470
  81. package/src/theme/generateThemeRules.ts +51 -219
  82. package/src/theme/tokenValueCompat.test.ts +1 -4
  83. package/dist/Icon/IconDefaultSizeContext.d.ts +0 -4
  84. package/dist/Icon/IconDefaultSizeContext.d.ts.map +0 -1
  85. package/dist/Icon/IconDefaultSizeContext.js +0 -18
  86. package/dist/Icon/IconSize.stylex.d.ts +0 -65
  87. package/dist/Icon/IconSize.stylex.d.ts.map +0 -1
  88. package/dist/Icon/IconSize.stylex.js +0 -75
  89. package/dist/Timer/Timer.d.ts +0 -49
  90. package/dist/Timer/Timer.d.ts.map +0 -1
  91. package/dist/Timer/Timer.js +0 -158
  92. package/dist/Timer/index.d.ts +0 -9
  93. package/dist/Timer/index.d.ts.map +0 -1
  94. package/dist/Timer/index.js +0 -10
  95. package/dist/theme/declarationBoundary.d.ts +0 -17
  96. package/dist/theme/declarationBoundary.d.ts.map +0 -1
  97. package/dist/theme/declarationBoundary.js +0 -343
  98. package/dist/utils/safeUrl.d.ts +0 -11
  99. package/dist/utils/safeUrl.d.ts.map +0 -1
  100. package/dist/utils/safeUrl.js +0 -78
  101. package/src/Chat/ChatLayout.spec.md +0 -271
  102. package/src/Chat/ChatLayoutScrollButton.spec.md +0 -338
  103. package/src/Chat/__tests__/ChatLayoutScrollButton.a11y.chromium.spec.ts +0 -514
  104. package/src/Chat/__tests__/ChatLayoutScrollButtonSurface.a11y.chromium.spec.ts +0 -740
  105. package/src/Icon/IconDefaultSizeContext.ts +0 -23
  106. package/src/Icon/IconSize.stylex.ts +0 -70
  107. package/src/Link/__tests__/Link.navigation.a11y.chromium.spec.ts +0 -261
  108. package/src/Markdown/Markdown.renderBoundary.test.tsx +0 -72
  109. package/src/Timer/Timer.doc.mjs +0 -183
  110. package/src/Timer/Timer.spec.md +0 -215
  111. package/src/Timer/Timer.test.tsx +0 -302
  112. package/src/Timer/Timer.tsx +0 -258
  113. package/src/Timer/index.ts +0 -11
  114. package/src/hooks/useClickableContainer.test.tsx +0 -236
  115. package/src/theme/declarationBoundary.test.ts +0 -126
  116. package/src/theme/declarationBoundary.ts +0 -347
  117. package/src/utils/safeUrl.test.ts +0 -88
  118. package/src/utils/safeUrl.ts +0 -85
@@ -1,347 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- /**
4
- * @file Declaration boundary scanner
5
- *
6
- * Decides whether a consumer-supplied property name and value can be emitted
7
- * as exactly one CSS declaration, `name: value;`, without the value ending
8
- * the declaration early or swallowing what follows it. Theme definitions are
9
- * code, but apps assemble them from stored input (brand colors,
10
- * white-labeling), so the generated stylesheet must never extend beyond the
11
- * declarations it means to emit.
12
- *
13
- * The scanner follows the CSS Syntax Module Level 3 tokenizer for everything
14
- * that decides where a declaration ends: strings with backslash escapes and
15
- * line continuations, comments, `url()` with an unquoted body, escaped code
16
- * points outside strings, and `()`, `[]`, `{}` block nesting. Inside any of
17
- * those a `;` or a brace is inert, exactly as a browser reads it, so a `data:`
18
- * URI, `Gill\ Sans`, or a closed comment passes through byte-identically.
19
- * Only what a browser would read as the end of the declaration or rule is
20
- * rejected: an unnested `;`, `{` or `}`, an unbalanced closer, and anything
21
- * left open at the end of the value (a string, comment, block, or url whose
22
- * closer would then be the generator's own `;` or `}`). A `bad-string` or
23
- * `bad-url` token is rejected as well: the browser would discard the
24
- * declaration anyway, and a diagnostic beats a silent no-op.
25
- *
26
- * @input A property name or a declaration value as authored in a theme
27
- * @output `null` when it can be emitted, otherwise the reason it cannot
28
- * @position packages/core/src/theme/declarationBoundary.ts
29
- */
30
-
31
- /** Newline per CSS Syntax §4.2 (after preprocessing, CR and FF are newlines). */
32
- function isNewline(ch: string): boolean {
33
- return ch === '\n' || ch === '\r' || ch === '\f';
34
- }
35
-
36
- function isWhitespace(ch: string): boolean {
37
- return ch === ' ' || ch === '\t' || isNewline(ch);
38
- }
39
-
40
- function isHexDigit(ch: string): boolean {
41
- return /^[0-9a-fA-F]$/.test(ch);
42
- }
43
-
44
- /** Name-start code point: letter, underscore, or any non-ASCII code point. */
45
- function isNameStart(ch: string): boolean {
46
- return /^[A-Za-z_]$/.test(ch) || ch.charCodeAt(0) >= 0x80;
47
- }
48
-
49
- function isNameChar(ch: string): boolean {
50
- return isNameStart(ch) || /^[0-9-]$/.test(ch);
51
- }
52
-
53
- /** CSS Syntax §3.3 preprocessing, for scanning only; emitted bytes stay intact. */
54
- function preprocess(input: string): string {
55
- return input.replace(/\r\n?|\f/g, '\n').replace(/\0/g, '\uFFFD');
56
- }
57
-
58
- /** Non-printable code points make an unquoted url() a bad-url token. */
59
- // eslint-disable-next-line no-control-regex -- these code points are the subject
60
- const NON_PRINTABLE = /[\x01-\x08\x0b\x0e-\x1f\x7f]/;
61
-
62
- /** "Check if two code points are a valid escape" (§4.3.8). */
63
- function isValidEscape(input: string, pos: number): boolean {
64
- return (
65
- input[pos] === '\\' && pos + 1 < input.length && !isNewline(input[pos + 1])
66
- );
67
- }
68
-
69
- /** "Check if three code points would start an ident sequence" (§4.3.9). */
70
- function startsIdent(input: string, pos: number): boolean {
71
- const ch = input[pos];
72
- if (ch === '-') {
73
- const next = input[pos + 1];
74
- return (
75
- next !== undefined &&
76
- (next === '-' || isNameStart(next) || isValidEscape(input, pos + 1))
77
- );
78
- }
79
- if (ch === '\\') {
80
- return isValidEscape(input, pos);
81
- }
82
- return ch !== undefined && isNameStart(ch);
83
- }
84
-
85
- /**
86
- * "Consume an escaped code point" (§4.3.7), positioned after the backslash.
87
- * Returns the position after the escape. A hex escape takes up to six hex
88
- * digits plus one optional whitespace; anything else takes one code point.
89
- */
90
- function consumeEscape(input: string, pos: number): number {
91
- if (isHexDigit(input[pos])) {
92
- let end = pos;
93
- while (end < input.length && end - pos < 6 && isHexDigit(input[end])) {
94
- end++;
95
- }
96
- if (end < input.length && isWhitespace(input[end])) {
97
- end++;
98
- }
99
- return end;
100
- }
101
- // A surrogate pair is one code point.
102
- const code = input.codePointAt(pos) ?? 0;
103
- return pos + (code > 0xffff ? 2 : 1);
104
- }
105
-
106
- /**
107
- * "Consume an ident sequence" (§4.3.11) starting at `pos`. Returns the
108
- * position after it and the decoded name (escapes resolved, for the
109
- * case-insensitive `url` check; hex escapes decode to their code point).
110
- */
111
- function consumeIdent(input: string, pos: number): {end: number; name: string} {
112
- let name = '';
113
- let i = pos;
114
- while (i < input.length) {
115
- const ch = input[i];
116
- if (isNameChar(ch)) {
117
- name += ch;
118
- i++;
119
- } else if (isValidEscape(input, i)) {
120
- const end = consumeEscape(input, i + 1);
121
- if (isHexDigit(input[i + 1])) {
122
- const hex = input.slice(i + 1, end).trim();
123
- const code = parseInt(hex, 16);
124
- name +=
125
- code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)
126
- ? '\uFFFD'
127
- : String.fromCodePoint(code);
128
- } else {
129
- name += input.slice(i + 1, end);
130
- }
131
- i = end;
132
- } else {
133
- break;
134
- }
135
- }
136
- return {end: i, name};
137
- }
138
-
139
- /**
140
- * "Consume a string token" (§4.3.5), positioned at the opening quote.
141
- * Returns the position after the closing quote, or a rejection reason.
142
- */
143
- function consumeString(
144
- input: string,
145
- pos: number,
146
- ): {end: number} | {reason: string} {
147
- const quote = input[pos];
148
- let i = pos + 1;
149
- while (i < input.length) {
150
- const ch = input[i];
151
- if (ch === quote) {
152
- return {end: i + 1};
153
- }
154
- if (isNewline(ch)) {
155
- // A raw newline ends the string as a bad-string token; the browser
156
- // discards the declaration, so a diagnostic is more useful than
157
- // reasoning about where that leaves the next `;`.
158
- return {reason: 'a newline inside a quoted string makes a bad string'};
159
- }
160
- if (ch === '\\') {
161
- if (i + 1 >= input.length) {
162
- break;
163
- }
164
- // Escaped newline is a line continuation; any other escape consumes
165
- // the escaped code point (so `\"` never closes the string).
166
- i = isNewline(input[i + 1]) ? i + 2 : consumeEscape(input, i + 1);
167
- continue;
168
- }
169
- i++;
170
- }
171
- return {
172
- reason: `an unclosed ${quote} string would swallow the rest of the rule`,
173
- };
174
- }
175
-
176
- /**
177
- * "Consume a url token" (§4.3.6), positioned after `url(` and any leading
178
- * whitespace, with a non-quote next code point. Returns the position after
179
- * the closing `)`, or a rejection reason (bad-url or unclosed).
180
- */
181
- function consumeUrl(
182
- input: string,
183
- pos: number,
184
- ): {end: number} | {reason: string} {
185
- let i = pos;
186
- while (i < input.length) {
187
- const ch = input[i];
188
- if (ch === ')') {
189
- return {end: i + 1};
190
- }
191
- if (isWhitespace(ch)) {
192
- while (i < input.length && isWhitespace(input[i])) {
193
- i++;
194
- }
195
- if (i >= input.length) {
196
- break;
197
- }
198
- if (input[i] === ')') {
199
- return {end: i + 1};
200
- }
201
- return {reason: 'whitespace inside an unquoted url() makes a bad url'};
202
- }
203
- if (NON_PRINTABLE.test(ch)) {
204
- return {reason: 'a non-printable character inside url() makes a bad url'};
205
- }
206
- if (ch === '"' || ch === "'" || ch === '(') {
207
- return {
208
- reason: `"${ch}" inside an unquoted url() makes a bad url; quote the URL instead`,
209
- };
210
- }
211
- if (ch === '\\') {
212
- if (!isValidEscape(input, i)) {
213
- return {reason: 'a stray backslash inside url() makes a bad url'};
214
- }
215
- i = consumeEscape(input, i + 1);
216
- continue;
217
- }
218
- i++;
219
- }
220
- return {reason: 'an unclosed url( would swallow the rest of the rule'};
221
- }
222
-
223
- const CLOSER: Record<string, string> = {'(': ')', '[': ']', '{': '}'};
224
-
225
- /**
226
- * Why `value` cannot be emitted as the value of one declaration, or `null`
227
- * when it can. Valid CSS a browser keeps inside one declaration always
228
- * returns `null`; see the file header for the exact rules.
229
- */
230
- export function checkDeclarationValue(input: string): string | null {
231
- const value = preprocess(input);
232
- const open: string[] = [];
233
- let i = 0;
234
- while (i < value.length) {
235
- const ch = value[i];
236
-
237
- if (ch === '/' && value[i + 1] === '*') {
238
- const close = value.indexOf('*/', i + 2);
239
- if (close === -1) {
240
- return 'an unclosed /* comment would swallow the rest of the rule';
241
- }
242
- i = close + 2;
243
- continue;
244
- }
245
-
246
- if (ch === '"' || ch === "'") {
247
- const result = consumeString(value, i);
248
- if ('reason' in result) {
249
- return result.reason;
250
- }
251
- i = result.end;
252
- continue;
253
- }
254
-
255
- if (startsIdent(value, i)) {
256
- const ident = consumeIdent(value, i);
257
- i = ident.end;
258
- if (value[i] === '(' && ident.name.toLowerCase() === 'url') {
259
- let j = i + 1;
260
- while (j < value.length && isWhitespace(value[j])) {
261
- j++;
262
- }
263
- if (value[j] === '"' || value[j] === "'") {
264
- // `url("...")` is an ordinary function token; the string and the
265
- // closing paren are handled by the loop.
266
- open.push(')');
267
- i = i + 1;
268
- continue;
269
- }
270
- const result = consumeUrl(value, j);
271
- if ('reason' in result) {
272
- return result.reason;
273
- }
274
- i = result.end;
275
- }
276
- continue;
277
- }
278
-
279
- if (ch === '\\') {
280
- if (i + 1 >= value.length) {
281
- // `\` followed by the generator's own `;` would escape it.
282
- return 'a trailing backslash would escape the declaration terminator';
283
- }
284
- // `\` + newline is not an escape: the backslash is a delim and the
285
- // newline is whitespace. Anything else escapes the next code point.
286
- i = isNewline(value[i + 1]) ? i + 1 : consumeEscape(value, i + 1);
287
- continue;
288
- }
289
-
290
- if (ch === '(' || ch === '[' || ch === '{') {
291
- if (ch === '{' && open.length === 0) {
292
- return 'an unquoted "{" would open a nested block';
293
- }
294
- open.push(CLOSER[ch]);
295
- i++;
296
- continue;
297
- }
298
-
299
- if (ch === ')' || ch === ']' || ch === '}') {
300
- if (open.length === 0) {
301
- return ch === '}'
302
- ? 'an unquoted "}" would close the rule'
303
- : `an unbalanced "${ch}" has nothing to close`;
304
- }
305
- const expected = open.pop();
306
- if (expected !== ch) {
307
- return `"${ch}" does not close the open "${expected === ')' ? '(' : expected === ']' ? '[' : '{'}"`;
308
- }
309
- i++;
310
- continue;
311
- }
312
-
313
- if (ch === ';' && open.length === 0) {
314
- return 'an unquoted ";" would end the declaration';
315
- }
316
-
317
- i++;
318
- }
319
-
320
- if (open.length > 0) {
321
- const closer = open[open.length - 1];
322
- const opener = closer === ')' ? '(' : closer === ']' ? '[' : '{';
323
- return `an unclosed "${opener}" would swallow the rest of the rule`;
324
- }
325
- return null;
326
- }
327
-
328
- /**
329
- * Why `name` cannot be emitted as a declaration's property name, or `null`
330
- * when it can. A property name is one CSS ident sequence: a standard
331
- * property (`color`), a vendor-prefixed one (`-webkit-line-clamp`), or a
332
- * custom property (`--brand-accent`, `--_internal`). Escapes are allowed
333
- * because an ident allows them. Whether the name means anything to the
334
- * browser is not this check's concern; only that it cannot end the
335
- * declaration or leak a second one.
336
- */
337
- export function checkDeclarationName(input: string): string | null {
338
- const name = preprocess(input);
339
- if (name.length === 0 || !startsIdent(name, 0)) {
340
- return 'a property name must be a CSS identifier';
341
- }
342
- const {end} = consumeIdent(name, 0);
343
- if (end !== name.length) {
344
- return `a property name must be one CSS identifier; "${name[end]}" cannot appear in one`;
345
- }
346
- return null;
347
- }
@@ -1,88 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- import {describe, expect, it} from 'vitest';
4
- import {isSafeDestination, isSafeUrl, sanitizeUrl} from './safeUrl';
5
-
6
- // Expectations come from the navigation contract, not another policy helper.
7
- const accepted = [
8
- 'https://example.com/a?b=c#d',
9
- 'http://example.com',
10
- '//example.com/protocol-relative',
11
- '/relative/path',
12
- 'relative/path',
13
- '#fragment',
14
- 'mailto:a@example.com',
15
- 'tel:+1234567890',
16
- 'custom:open/document',
17
- 'data:image/png;base64,iVBORw0KGgo=',
18
- 'data:text/plain,download',
19
- ];
20
- const rejected = [
21
- 'javascript:alert(1)',
22
- 'JaVaScRiPt:alert(1)',
23
- ' javascript:alert(1)',
24
- 'vbscript:MsgBox(1)',
25
- 'data:text/html,<script>alert(1)</script>',
26
- 'DATA:TEXT/HTML;base64,PHNjcmlwdD4=',
27
- 'java\tscript:alert(1)',
28
- 'java\nscript:alert(1)',
29
- '\x00javascript:alert(1)',
30
- 'java\x7fscript:alert(1)',
31
- ];
32
-
33
- describe('navigation strings', () => {
34
- it.each(accepted)('accepts %s', url => {
35
- expect(isSafeUrl(url)).toBe(true);
36
- expect(isSafeDestination(url)).toBe(true);
37
- expect(sanitizeUrl(url)).toBe(url);
38
- });
39
- it.each(rejected)('rejects %s', url => {
40
- expect(isSafeUrl(url)).toBe(false);
41
- expect(isSafeDestination(url)).toBe(false);
42
- expect(sanitizeUrl(url)).toBeNull();
43
- });
44
- it('normalizes accepted strings only when requested', () => {
45
- expect(sanitizeUrl(' /docs\n')).toBe('/docs');
46
- expect(sanitizeUrl('/do\x00cs')).toBe('/docs');
47
- });
48
- });
49
-
50
- describe('structured destinations', () => {
51
- it.each([
52
- {pathname: '/docs', search: '?q=1', hash: '#a'},
53
- {href: 'https://example.com'},
54
- {protocol: 'https:', hostname: 'example.com', pathname: '/docs'},
55
- {protocol: 'custom', pathname: 'document'},
56
- {protocol: 'mailto:', pathname: 'a@example.com'},
57
- {protocol: 'data:', pathname: 'image/png;base64,aA=='},
58
- {search: '?page=2'},
59
- {hash: '#section'},
60
- {},
61
- new URL('https://example.com/docs'),
62
- undefined,
63
- null,
64
- ])('accepts supported destination %j', destination => {
65
- expect(isSafeDestination(destination)).toBe(true);
66
- });
67
- it.each([
68
- {pathname: 'javascript:alert(1)'},
69
- {pathname: 'java\x00script:alert(1)'},
70
- {href: 'vbscript:MsgBox(1)'},
71
- {pathname: '/ok', href: 'javascript:1'},
72
- {protocol: 'javascript:', pathname: 'alert(1)'},
73
- {protocol: 'javascript', pathname: 'alert(1)'},
74
- {protocol: ' JaVa\tsCrIpT ', pathname: 'alert(1)'},
75
- {protocol: 'vbscript', pathname: 'MsgBox(1)'},
76
- {protocol: 'data:', pathname: 'text/html,<b>x</b>'},
77
- {protocol: 'data', pathname: 'TEXT/HTML;base64,PGI+eDwvYj4='},
78
- {protocol: 'data:', host: 'text/', pathname: 'html,<b>x</b>'},
79
- {protocol: 'data:', hostname: 'text/html,<b>x</b>'},
80
- {href: '/safe', protocol: 'javascript:'},
81
- new URL('javascript:alert(1)'),
82
- {pathname: 42},
83
- {protocol: {toString: (): string => 'javascript:'}},
84
- 3,
85
- ])('rejects blocked or unsupported destination %j', destination => {
86
- expect(isSafeDestination(destination)).toBe(false);
87
- });
88
- });
@@ -1,85 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- /**
4
- * @file safeUrl.ts
5
- * @input Navigation strings or supported structured router destinations
6
- * @output The shared blocked-scheme decision, without rewriting accepted inputs
7
- * @position Core navigation policy; embedded-resource policy is separate
8
- */
9
-
10
- function normalizeUrl(url: string): string {
11
- // eslint-disable-next-line no-control-regex -- inspect schemes without browser-ignored controls
12
- return url.replace(/[\x00-\x1f\x7f]/g, '').trim();
13
- }
14
-
15
- /** Return a normalized navigation URL, or null for a blocked scheme. */
16
- export function sanitizeUrl(url: string): string | null {
17
- const normalized = normalizeUrl(url);
18
- const lower = normalized.toLowerCase();
19
- if (
20
- lower.startsWith('javascript:') ||
21
- lower.startsWith('vbscript:') ||
22
- lower.startsWith('data:text/html')
23
- ) {
24
- return null;
25
- }
26
- return normalized;
27
- }
28
-
29
- /** Inspect a navigation string without changing the value used by its sink. */
30
- export function isSafeUrl(url: string): boolean {
31
- return sanitizeUrl(url) !== null;
32
- }
33
-
34
- /**
35
- * Inspect React Router paths, Next.js URL objects, and URL instances without
36
- * serializing or replacing the object handed to the router. Search/query/hash
37
- * are route-relative data, not schemes. Absent destinations remain absent.
38
- */
39
- export function isSafeDestination(destination: unknown): boolean {
40
- if (destination == null) {
41
- return true;
42
- }
43
- if (typeof destination === 'string') {
44
- return isSafeUrl(destination);
45
- }
46
- if (typeof destination !== 'object') {
47
- return false;
48
- }
49
-
50
- const {pathname, href, protocol, host, hostname} = destination as {
51
- pathname?: unknown;
52
- href?: unknown;
53
- protocol?: unknown;
54
- host?: unknown;
55
- hostname?: unknown;
56
- };
57
- for (const field of [pathname, href, protocol, host, hostname]) {
58
- if (field != null && typeof field !== 'string') {
59
- return false;
60
- }
61
- }
62
- if (typeof pathname === 'string' && !isSafeUrl(pathname)) {
63
- return false;
64
- }
65
- if (typeof href === 'string' && !isSafeUrl(href)) {
66
- return false;
67
- }
68
- if (typeof protocol === 'string' && protocol !== '') {
69
- // URL-object formatters accept a protocol with or without its colon and
70
- // can assemble a data media type from the host and pathname fields.
71
- const normalizedProtocol = normalizeUrl(protocol);
72
- const prefix = normalizedProtocol.endsWith(':')
73
- ? normalizedProtocol
74
- : `${normalizedProtocol}:`;
75
- if (!isSafeUrl(prefix)) {
76
- return false;
77
- }
78
- const body = (host || hostname || '') as string;
79
- const path = typeof pathname === 'string' ? pathname : '';
80
- if (!isSafeUrl(`${prefix}${body}${path}`)) {
81
- return false;
82
- }
83
- }
84
- return true;
85
- }