pem.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.pemConverter = exports.pem = void 0;
  4. exports.encode = encode;
  5. exports.encodeMany = encodeMany;
  6. exports.decode = decode;
  7. exports.find = find;
  8. exports.findAll = findAll;
  9. exports.decodeFirst = decodeFirst;
  10. exports.parse = parse;
  11. exports.format = format;
  12. const base64_js_1 = require("../encoding/base64.js");
  13. const LABEL_REGEX = /^[A-Z0-9][A-Z0-9 ._-]*[A-Z0-9]$/i;
  14. const PEM_BLOCK_REGEX = /-----BEGIN ([^-]+)-----([\s\S]*?)-----END \1-----/g;
  15. function assertLabel(label) {
  16. if (!LABEL_REGEX.test(label)) {
  17. throw new TypeError(`Invalid PEM label '${label}'`);
  18. }
  19. }
  20. function wrap(text, lineLength) {
  21. const result = [];
  22. for (let i = 0; i < text.length; i += lineLength) {
  23. result.push(text.slice(i, i + lineLength));
  24. }
  25. return result;
  26. }
  27. function parseBody(body) {
  28. const normalized = body.trim().replace(/\r\n/g, "\n");
  29. const lines = normalized.split("\n").map((line) => line.trim()).filter(Boolean);
  30. const headers = {};
  31. let index = 0;
  32. for (; index < lines.length; index++) {
  33. const line = lines[index];
  34. const separator = line.indexOf(":");
  35. if (separator <= 0) {
  36. break;
  37. }
  38. headers[line.slice(0, separator).trim()] = line.slice(separator + 1).trim();
  39. }
  40. return {
  41. headers: Object.keys(headers).length ? headers : undefined,
  42. base64Lines: lines.slice(index),
  43. base64Text: lines.slice(index).join(""),
  44. };
  45. }
  46. function detectNewline(text) {
  47. return /\r\n/.test(text) ? "\r\n" : "\n";
  48. }
  49. function collectBlocks(text, options = {}) {
  50. const blocks = [];
  51. const requestedLabel = options.label;
  52. let match;
  53. PEM_BLOCK_REGEX.lastIndex = 0;
  54. while ((match = PEM_BLOCK_REGEX.exec(text))) {
  55. const label = match[1].trim();
  56. if (requestedLabel && label !== requestedLabel) {
  57. continue;
  58. }
  59. assertLabel(label);
  60. const parsed = parseBody(match[2]);
  61. blocks.push({
  62. label,
  63. data: base64_js_1.base64.decode(parsed.base64Text),
  64. headers: parsed.headers,
  65. lineLength: parsed.base64Lines[0]?.length ?? 64,
  66. newline: detectNewline(match[0]),
  67. });
  68. }
  69. if (options.strict && blocks.length === 0) {
  70. throw new TypeError(requestedLabel
  71. ? `No PEM block with label '${requestedLabel}' was found`
  72. : "No PEM blocks were found");
  73. }
  74. return blocks;
  75. }
  76. function encode(label, data, options = {}) {
  77. assertLabel(label);
  78. const lineLength = options.lineLength ?? 64;
  79. if (!Number.isInteger(lineLength) || lineLength < 1) {
  80. throw new RangeError("PEM lineLength must be a positive integer");
  81. }
  82. const newline = options.newline ?? "\n";
  83. const lines = [`-----BEGIN ${label}-----`];
  84. if (options.headers) {
  85. for (const [name, value] of Object.entries(options.headers)) {
  86. lines.push(`${name}: ${value}`);
  87. }
  88. lines.push("");
  89. }
  90. lines.push(...wrap(base64_js_1.base64.encode(data), lineLength));
  91. lines.push(`-----END ${label}-----`);
  92. return `${lines.join(newline)}${newline}`;
  93. }
  94. function encodeMany(blocks, options = {}) {
  95. return blocks.map((block) => encode(block.label, block.data, { ...options, headers: block.headers ?? options.headers })).join("");
  96. }
  97. function decode(text, options = {}) {
  98. return collectBlocks(text, options).map(({ lineLength: _lineLength, newline: _newline, ...block }) => block);
  99. }
  100. function find(text, label) {
  101. return decode(text, { label })[0];
  102. }
  103. function findAll(text, label) {
  104. return decode(text, { label });
  105. }
  106. function decodeFirst(text, label) {
  107. const [block] = decode(text, { label, strict: true });
  108. return block.data;
  109. }
  110. function parse(text, options = {}) {
  111. const [block] = collectBlocks(text, { ...options, strict: true });
  112. const format = {
  113. label: block.label,
  114. headers: block.headers,
  115. lineLength: block.lineLength,
  116. newline: block.newline,
  117. };
  118. return {
  119. bytes: block.data,
  120. format,
  121. normalized: encode(block.label, block.data, format),
  122. };
  123. }
  124. function format(data, value) {
  125. return encode(value.label, data, value);
  126. }
  127. exports.pem = { decode, decodeFirst, encode, encodeMany, find, findAll, format, parse };
  128. exports.pemConverter = {
  129. name: "pem",
  130. encode: (data, options) => {
  131. if (!options?.label) {
  132. throw new TypeError("PEM label is required");
  133. }
  134. return encode(options.label, data, options);
  135. },
  136. decode: (text, options) => decodeFirst(text, options?.label),
  137. format,
  138. is: (text) => typeof text === "string" && /-----BEGIN [^-]+-----/.test(text),
  139. parse,
  140. };