index.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. "use strict";
  2. const punycode = require("punycode");
  3. const regexes = require("./lib/regexes.js");
  4. const mappingTable = require("./lib/mappingTable.json");
  5. const { STATUS_MAPPING } = require("./lib/statusMapping.js");
  6. function containsNonASCII(str) {
  7. return /[^\x00-\x7F]/.test(str);
  8. }
  9. function findStatus(val, { useSTD3ASCIIRules }) {
  10. let start = 0;
  11. let end = mappingTable.length - 1;
  12. while (start <= end) {
  13. const mid = Math.floor((start + end) / 2);
  14. const target = mappingTable[mid];
  15. const min = Array.isArray(target[0]) ? target[0][0] : target[0];
  16. const max = Array.isArray(target[0]) ? target[0][1] : target[0];
  17. if (min <= val && max >= val) {
  18. if (useSTD3ASCIIRules &&
  19. (target[1] === STATUS_MAPPING.disallowed_STD3_valid || target[1] === STATUS_MAPPING.disallowed_STD3_mapped)) {
  20. return [STATUS_MAPPING.disallowed, ...target.slice(2)];
  21. } else if (target[1] === STATUS_MAPPING.disallowed_STD3_valid) {
  22. return [STATUS_MAPPING.valid, ...target.slice(2)];
  23. } else if (target[1] === STATUS_MAPPING.disallowed_STD3_mapped) {
  24. return [STATUS_MAPPING.mapped, ...target.slice(2)];
  25. }
  26. return target.slice(1);
  27. } else if (min > val) {
  28. end = mid - 1;
  29. } else {
  30. start = mid + 1;
  31. }
  32. }
  33. return null;
  34. }
  35. function mapChars(domainName, { useSTD3ASCIIRules, processingOption }) {
  36. let hasError = false;
  37. let processed = "";
  38. for (const ch of domainName) {
  39. const [status, mapping] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules });
  40. switch (status) {
  41. case STATUS_MAPPING.disallowed:
  42. hasError = true;
  43. processed += ch;
  44. break;
  45. case STATUS_MAPPING.ignored:
  46. break;
  47. case STATUS_MAPPING.mapped:
  48. processed += mapping;
  49. break;
  50. case STATUS_MAPPING.deviation:
  51. if (processingOption === "transitional") {
  52. processed += mapping;
  53. } else {
  54. processed += ch;
  55. }
  56. break;
  57. case STATUS_MAPPING.valid:
  58. processed += ch;
  59. break;
  60. }
  61. }
  62. return {
  63. string: processed,
  64. error: hasError
  65. };
  66. }
  67. function validateLabel(label, { checkHyphens, checkBidi, checkJoiners, processingOption, useSTD3ASCIIRules }) {
  68. if (label.normalize("NFC") !== label) {
  69. return false;
  70. }
  71. const codePoints = Array.from(label);
  72. if (checkHyphens) {
  73. if ((codePoints[2] === "-" && codePoints[3] === "-") ||
  74. (label.startsWith("-") || label.endsWith("-"))) {
  75. return false;
  76. }
  77. }
  78. if (label.includes(".") ||
  79. (codePoints.length > 0 && regexes.combiningMarks.test(codePoints[0]))) {
  80. return false;
  81. }
  82. for (const ch of codePoints) {
  83. const [status] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules });
  84. if ((processingOption === "transitional" && status !== STATUS_MAPPING.valid) ||
  85. (processingOption === "nontransitional" &&
  86. status !== STATUS_MAPPING.valid && status !== STATUS_MAPPING.deviation)) {
  87. return false;
  88. }
  89. }
  90. // https://tools.ietf.org/html/rfc5892#appendix-A
  91. if (checkJoiners) {
  92. let last = 0;
  93. for (const [i, ch] of codePoints.entries()) {
  94. if (ch === "\u200C" || ch === "\u200D") {
  95. if (i > 0) {
  96. if (regexes.combiningClassVirama.test(codePoints[i - 1])) {
  97. continue;
  98. }
  99. if (ch === "\u200C") {
  100. // TODO: make this more efficient
  101. const next = codePoints.indexOf("\u200C", i + 1);
  102. const test = next < 0 ? codePoints.slice(last) : codePoints.slice(last, next);
  103. if (regexes.validZWNJ.test(test.join(""))) {
  104. last = i + 1;
  105. continue;
  106. }
  107. }
  108. }
  109. return false;
  110. }
  111. }
  112. }
  113. // https://tools.ietf.org/html/rfc5893#section-2
  114. if (checkBidi) {
  115. let rtl;
  116. // 1
  117. if (regexes.bidiS1LTR.test(codePoints[0])) {
  118. rtl = false;
  119. } else if (regexes.bidiS1RTL.test(codePoints[0])) {
  120. rtl = true;
  121. } else {
  122. return false;
  123. }
  124. if (rtl) {
  125. // 2-4
  126. if (!regexes.bidiS2.test(label) ||
  127. !regexes.bidiS3.test(label) ||
  128. (regexes.bidiS4EN.test(label) && regexes.bidiS4AN.test(label))) {
  129. return false;
  130. }
  131. } else if (!regexes.bidiS5.test(label) ||
  132. !regexes.bidiS6.test(label)) { // 5-6
  133. return false;
  134. }
  135. }
  136. return true;
  137. }
  138. function isBidiDomain(labels) {
  139. const domain = labels.map(label => {
  140. if (label.startsWith("xn--")) {
  141. try {
  142. return punycode.decode(label.substring(4));
  143. } catch (err) {
  144. return "";
  145. }
  146. }
  147. return label;
  148. }).join(".");
  149. return regexes.bidiDomain.test(domain);
  150. }
  151. function processing(domainName, options) {
  152. const { processingOption } = options;
  153. // 1. Map.
  154. let { string, error } = mapChars(domainName, options);
  155. // 2. Normalize.
  156. string = string.normalize("NFC");
  157. // 3. Break.
  158. const labels = string.split(".");
  159. const isBidi = isBidiDomain(labels);
  160. // 4. Convert/Validate.
  161. for (const [i, origLabel] of labels.entries()) {
  162. let label = origLabel;
  163. let curProcessing = processingOption;
  164. if (label.startsWith("xn--")) {
  165. try {
  166. label = punycode.decode(label.substring(4));
  167. labels[i] = label;
  168. } catch (err) {
  169. error = true;
  170. continue;
  171. }
  172. curProcessing = "nontransitional";
  173. }
  174. // No need to validate if we already know there is an error.
  175. if (error) {
  176. continue;
  177. }
  178. const validation = validateLabel(label, Object.assign({}, options, {
  179. processingOption: curProcessing,
  180. checkBidi: options.checkBidi && isBidi
  181. }));
  182. if (!validation) {
  183. error = true;
  184. }
  185. }
  186. return {
  187. string: labels.join("."),
  188. error
  189. };
  190. }
  191. function toASCII(domainName, {
  192. checkHyphens = false,
  193. checkBidi = false,
  194. checkJoiners = false,
  195. useSTD3ASCIIRules = false,
  196. processingOption = "nontransitional",
  197. verifyDNSLength = false
  198. } = {}) {
  199. if (processingOption !== "transitional" && processingOption !== "nontransitional") {
  200. throw new RangeError("processingOption must be either transitional or nontransitional");
  201. }
  202. const result = processing(domainName, {
  203. processingOption,
  204. checkHyphens,
  205. checkBidi,
  206. checkJoiners,
  207. useSTD3ASCIIRules
  208. });
  209. let labels = result.string.split(".");
  210. labels = labels.map(l => {
  211. if (containsNonASCII(l)) {
  212. try {
  213. return "xn--" + punycode.encode(l);
  214. } catch (e) {
  215. result.error = true;
  216. }
  217. }
  218. return l;
  219. });
  220. if (verifyDNSLength) {
  221. const total = labels.join(".").length;
  222. if (total > 253 || total === 0) {
  223. result.error = true;
  224. }
  225. for (let i = 0; i < labels.length; ++i) {
  226. if (labels[i].length > 63 || labels[i].length === 0) {
  227. result.error = true;
  228. break;
  229. }
  230. }
  231. }
  232. if (result.error) {
  233. return null;
  234. }
  235. return labels.join(".");
  236. }
  237. function toUnicode(domainName, {
  238. checkHyphens = false,
  239. checkBidi = false,
  240. checkJoiners = false,
  241. useSTD3ASCIIRules = false,
  242. processingOption = "nontransitional"
  243. } = {}) {
  244. const result = processing(domainName, {
  245. processingOption,
  246. checkHyphens,
  247. checkBidi,
  248. checkJoiners,
  249. useSTD3ASCIIRules
  250. });
  251. return {
  252. domain: result.string,
  253. error: result.error
  254. };
  255. }
  256. module.exports = {
  257. toASCII,
  258. toUnicode
  259. };