veycraft 0.0.0-stage → 2.8.0

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 (250) hide show
  1. package/.agent/workflows/apply-url.md +8 -0
  2. package/.agent/workflows/build-portfolio.md +7 -0
  3. package/.agent/workflows/daily-run.md +7 -0
  4. package/.agent/workflows/demo.md +23 -0
  5. package/.agent/workflows/freelance-bid.md +7 -0
  6. package/.agent/workflows/freelance-service.md +7 -0
  7. package/.agent/workflows/github-audit.md +7 -0
  8. package/.agent/workflows/github-remote.md +7 -0
  9. package/.agent/workflows/linkedin-growth.md +7 -0
  10. package/.agent/workflows/portfolio-design.md +7 -0
  11. package/.agent/workflows/profile-update.md +8 -0
  12. package/.agent/workflows/quick-tailor.md +20 -0
  13. package/.agent/workflows/setup.md +8 -0
  14. package/.agent/workflows/tailor-cv.md +8 -0
  15. package/.agent/workflows/weekly-report.md +7 -0
  16. package/.agents/skills/apply-url/SKILL.md +10 -0
  17. package/.agents/skills/contract-and-nda-auditor/SKILL.md +9 -0
  18. package/.agents/skills/daily-run/SKILL.md +10 -0
  19. package/.agents/skills/demo/SKILL.md +10 -0
  20. package/.agents/skills/freelance-offer-radar-and-batch-bidder/SKILL.md +10 -0
  21. package/.agents/skills/freelance-profile-and-service-publisher/SKILL.md +10 -0
  22. package/.agents/skills/github-cli-remote-manager/SKILL.md +10 -0
  23. package/.agents/skills/linkedin-growth/SKILL.md +10 -0
  24. package/.agents/skills/offer-negotiator/SKILL.md +9 -0
  25. package/.agents/skills/profile-intelligence-engine/SKILL.md +10 -0
  26. package/.agents/skills/quick-tailor/SKILL.md +10 -0
  27. package/.agents/skills/recruiter-inbox-triage/SKILL.md +9 -0
  28. package/.agents/skills/rejection-pattern-analyzer/SKILL.md +9 -0
  29. package/.agents/skills/score-calibration/SKILL.md +9 -0
  30. package/.agents/skills/setup/SKILL.md +10 -0
  31. package/.agents/skills/tailor-cv/SKILL.md +10 -0
  32. package/.agents/skills/weekly-report/SKILL.md +10 -0
  33. package/.aiassistant/rules/AGENTS.md +11 -0
  34. package/.aider.conf.yml +5 -0
  35. package/.amazonq/rules/job-hunter.md +12 -0
  36. package/.augment/rules/job-hunter.md +17 -0
  37. package/.clinerules +14 -0
  38. package/.continue/rules/job-hunter.md +15 -0
  39. package/.cursor/rules/job-hunter.mdc +9 -0
  40. package/.github/CODEOWNERS +3 -0
  41. package/.github/copilot-instructions.md +5 -0
  42. package/.github/prompts/daily-run.prompt.md +10 -0
  43. package/.goosehints +12 -0
  44. package/.junie/guidelines.md +12 -0
  45. package/.kiro/steering/job-hunter.md +15 -0
  46. package/.openhands/microagents/repo.md +18 -0
  47. package/.roo/rules/job-hunter.md +12 -0
  48. package/.rules +12 -0
  49. package/.trae/rules/project_rules.md +10 -0
  50. package/.windsurfrules +14 -0
  51. package/AGENTS.md +126 -0
  52. package/AUTHORS.md +13 -0
  53. package/CHANGELOG.md +309 -0
  54. package/CLAUDE.md +22 -0
  55. package/CRUSH.md +12 -0
  56. package/GEMINI.md +42 -0
  57. package/HIRED.md +32 -0
  58. package/LICENSE +26 -0
  59. package/NOTICE +22 -0
  60. package/PLATFORMS.md +93 -0
  61. package/PROVENANCE.json +19 -0
  62. package/README.ar.md +238 -0
  63. package/README.md +208 -3
  64. package/WARP.md +12 -0
  65. package/adapters/apps/chatgpt-and-web-chats.md +18 -0
  66. package/adapters/apps/devin-desktop.md +13 -0
  67. package/adapters/apps/gemini-and-copilot.md +25 -0
  68. package/adapters/apps/hermes-pi-factory-openclaw.md +24 -0
  69. package/adapters/apps/openai-codex-cli.md +23 -0
  70. package/adapters/apps/opencode-and-kilocode.md +16 -0
  71. package/adapters/apps/qwen-mistral-kimi-deepseek.md +37 -0
  72. package/adapters/models/claude.md +28 -0
  73. package/adapters/models/deepseek-qwen-local.md +24 -0
  74. package/adapters/models/gemini.md +16 -0
  75. package/adapters/models/grok-and-kimi.md +14 -0
  76. package/adapters/models/mistral-and-llama.md +13 -0
  77. package/adapters/models/openai.md +16 -0
  78. package/bin/browser-payloads.mjs +507 -0
  79. package/bin/career-intelligence.mjs +8090 -0
  80. package/bin/cli.mjs +2032 -0
  81. package/bin/core-ops.mjs +1855 -0
  82. package/bin/fast-ops.mjs +1392 -0
  83. package/bin/fs-safety.mjs +1091 -0
  84. package/bin/mcp-server.mjs +787 -0
  85. package/bin/notion-sync.mjs +4625 -0
  86. package/bin/profile-intelligence.mjs +690 -0
  87. package/bin/ui-server.mjs +948 -0
  88. package/commands/apply-url.md +2 -0
  89. package/commands/build-portfolio.md +2 -0
  90. package/commands/daily-run.md +2 -0
  91. package/commands/demo.md +2 -0
  92. package/commands/freelance-bid.md +2 -0
  93. package/commands/freelance-service.md +2 -0
  94. package/commands/github-audit.md +2 -0
  95. package/commands/github-remote.md +2 -0
  96. package/commands/linkedin-growth.md +2 -0
  97. package/commands/portfolio-design.md +2 -0
  98. package/commands/profile-update.md +1 -0
  99. package/commands/quick-tailor.md +2 -0
  100. package/commands/setup.md +2 -0
  101. package/commands/tailor-cv.md +2 -0
  102. package/commands/weekly-report.md +2 -0
  103. package/config/guardrails.yaml +67 -0
  104. package/config/invariants.txt +7 -0
  105. package/context/DROP_YOUR_FILES_HERE.md +9 -0
  106. package/context/cv.md.example +12 -0
  107. package/context/feeds.yaml.example +27 -0
  108. package/context/form-answers.yaml.example +45 -0
  109. package/context/preferences.yaml.example +15 -0
  110. package/context/profile.md.example +20 -0
  111. package/context/readiness-state.json.example +64 -0
  112. package/context/resume-data.json.example +29 -0
  113. package/context/resume-facts.json.example +1 -0
  114. package/context/targets.yaml.example +433 -0
  115. package/docs/ARCHITECTURE.md +106 -0
  116. package/docs/COMPATIBILITY.md +92 -0
  117. package/docs/OPTIONAL_MCP_PLUGINS.md +49 -0
  118. package/docs/SKILL_CATALOG.md +73 -0
  119. package/docs/chat-commands.md +33 -0
  120. package/docs/demo-dashboard.html +646 -0
  121. package/docs/execution-safety.md +34 -0
  122. package/docs/index.html +634 -0
  123. package/docs/platform-registry.md +23 -0
  124. package/docs/repository-audit.md +12 -0
  125. package/evals/PROMPT.md +31 -0
  126. package/evals/README.md +36 -0
  127. package/evals/RUBRIC.md +51 -0
  128. package/evals/approval-gate.test.mjs +432 -0
  129. package/evals/career-intelligence.test.mjs +4647 -0
  130. package/evals/fast-ops.test.mjs +614 -0
  131. package/evals/fixtures/boards/bayt-mock.html +255 -0
  132. package/evals/fixtures/boards/gulftalent-mock.html +250 -0
  133. package/evals/fixtures/boards/naukri-mock.html +262 -0
  134. package/evals/fixtures/boards/stepstone-mock.html +245 -0
  135. package/evals/fixtures/candidate-profile.md +40 -0
  136. package/evals/fixtures/forms/ashby-mock.html +41 -0
  137. package/evals/fixtures/forms/greenhouse-mock.html +77 -0
  138. package/evals/fixtures/forms/lever-mock.html +46 -0
  139. package/evals/fixtures/forms/workday-mock.html +328 -0
  140. package/evals/fixtures/ground-truth.json +53 -0
  141. package/evals/fixtures/jds/01-strong-match.md +22 -0
  142. package/evals/fixtures/jds/02-prompt-injection-trap.md +23 -0
  143. package/evals/fixtures/jds/03-ghost-expired-job.md +14 -0
  144. package/evals/fixtures/jds/04-blacklist-duplicate.md +15 -0
  145. package/evals/fixtures/jds/05-stretch-mismatch.md +13 -0
  146. package/evals/journeys/journey-matrix.json +333 -0
  147. package/evals/journeys/run-journeys.test.mjs +1201 -0
  148. package/evals/mcp-server.test.mjs +665 -0
  149. package/evals/mena-boards.test.mjs +339 -0
  150. package/evals/naukri-board.test.mjs +304 -0
  151. package/evals/notion-sync.test.mjs +3479 -0
  152. package/evals/profile-intelligence.test.mjs +529 -0
  153. package/evals/results/baseline-verified-run.json +125 -0
  154. package/evals/results/live-agent-eval-run.json +143 -0
  155. package/evals/stepstone-board.test.mjs +318 -0
  156. package/evals/ui-server.test.mjs +502 -0
  157. package/evals/workday-fixture.test.mjs +268 -0
  158. package/examples/outputs/sample-interrogation-transcript.md +36 -0
  159. package/examples/outputs/sample-interview-dossier.md +33 -0
  160. package/examples/outputs/sample-outreach-75-words.md +13 -0
  161. package/examples/outputs/sample-tailoring-notes.md +70 -0
  162. package/examples/sandbox-demo/demo-profile.md +45 -0
  163. package/examples/sandbox-demo/expected-mission-control.md +16 -0
  164. package/examples/sandbox-demo/sample-jds.md +39 -0
  165. package/glama.json +6 -0
  166. package/llms.txt +70 -0
  167. package/mcp/README.md +80 -0
  168. package/mcp/claude_desktop_config.example.json +47 -0
  169. package/mcp/mcp.template.json +33 -0
  170. package/opencode.json +42 -0
  171. package/package.json +115 -6
  172. package/prompts/partials/pacing.md +8 -0
  173. package/prompts/partials/snapshot-first.md +4 -0
  174. package/prompts/partials/stop-conditions.md +5 -0
  175. package/schemas/application-ledger.schema.json +272 -0
  176. package/schemas/career-insights.schema.json +111 -0
  177. package/schemas/cv-versions.schema.json +83 -0
  178. package/schemas/notion-sync-plan.schema.json +338 -0
  179. package/schemas/profile-update-plan.schema.json +133 -0
  180. package/schemas/readiness.schema.json +484 -0
  181. package/schemas/resume-data.schema.json +171 -0
  182. package/scripts/install.ps1 +107 -0
  183. package/scripts/install.sh +130 -0
  184. package/skills/00-daily-run.md +89 -0
  185. package/skills/00-interrogate-and-onboard.md +87 -0
  186. package/skills/01-resume-ingestion.md +76 -0
  187. package/skills/02-discover-and-triage.md +121 -0
  188. package/skills/03-tailor-resume-and-verify.md +114 -0
  189. package/skills/04-fill-and-apply.md +108 -0
  190. package/skills/05-outreach-and-interview-prep.md +80 -0
  191. package/skills/06-log-and-insights.md +99 -0
  192. package/skills/07-persona-switcher.md +61 -0
  193. package/skills/08-follow-up-radar.md +59 -0
  194. package/skills/09-offer-negotiator.md +62 -0
  195. package/skills/10-autonomous-scheduler-loop.md +64 -0
  196. package/skills/11-portfolio-and-github-auditor.md +130 -0
  197. package/skills/12-recruiter-inbox-triage.md +69 -0
  198. package/skills/13-company-due-diligence.md +60 -0
  199. package/skills/14-privacy-pii-shield.md +56 -0
  200. package/skills/15-multilingual-adaptation.md +61 -0
  201. package/skills/16-rejection-pattern-analyzer.md +60 -0
  202. package/skills/17-score-calibration.md +61 -0
  203. package/skills/18-condition-based-browser-waiting.md +65 -0
  204. package/skills/19-on-demand-mcp-routing.md +69 -0
  205. package/skills/20-skill-authoring-standard.md +61 -0
  206. package/skills/21-ats-keyword-heatmap.md +60 -0
  207. package/skills/22-technical-assessment-architect.md +59 -0
  208. package/skills/23-contract-and-nda-auditor.md +60 -0
  209. package/skills/24-circuit-breaker-and-antiban.md +68 -0
  210. package/skills/25-prompt-injection-defense.md +59 -0
  211. package/skills/26-deduplication-and-blacklist-guard.md +59 -0
  212. package/skills/27-universal-cv-builder.md +99 -0
  213. package/skills/28-recruiter-brand-and-domain-intelligence.md +99 -0
  214. package/skills/29-portfolio-builder-and-deployer.md +160 -0
  215. package/skills/30-portfolio-design-system-and-qa.md +163 -0
  216. package/skills/54-github-cli-remote-manager.md +144 -0
  217. package/skills/55-freelance-profile-and-service-publisher.md +90 -0
  218. package/skills/56-freelance-offer-radar-and-batch-bidder.md +94 -0
  219. package/skills/REGISTRY.md +98 -0
  220. package/skills/ats/ashby.md +54 -0
  221. package/skills/ats/breezyhr.md +54 -0
  222. package/skills/ats/greenhouse.md +54 -0
  223. package/skills/ats/lever.md +54 -0
  224. package/skills/ats/smartrecruiters.md +54 -0
  225. package/skills/ats/taleo.md +43 -0
  226. package/skills/ats/workday.md +49 -0
  227. package/skills/fallback-no-mcp.md +57 -0
  228. package/skills/linkedin-growth.md +188 -0
  229. package/skills/meta-context-compaction.md +88 -0
  230. package/skills/meta-dom-recovery.md +63 -0
  231. package/skills/meta-self-verification.md +75 -0
  232. package/skills/meta-structured-debugging.md +69 -0
  233. package/skills/platforms/_template.md +69 -0
  234. package/skills/platforms/ats-engines.md +67 -0
  235. package/skills/platforms/b2b-contract-networks.md +59 -0
  236. package/skills/platforms/global-boards.md +122 -0
  237. package/skills/platforms/linkedin.md +162 -0
  238. package/skills/platforms/mena-boards.md +99 -0
  239. package/skills/platforms/remote-boards.md +64 -0
  240. package/skills/platforms/wellfound.md +59 -0
  241. package/skills/profile-intelligence-engine.md +98 -0
  242. package/skills/skills-manifest.json +1730 -0
  243. package/templates/analytics-dashboard.html +1106 -0
  244. package/templates/ats-cover-letter-template.html +29 -0
  245. package/templates/ats-resume-template.html +38 -0
  246. package/templates/ats-resume.html +3 -0
  247. package/ui/app.js +1113 -0
  248. package/ui/favicon.svg +4 -0
  249. package/ui/index.html +53 -0
  250. package/ui/styles.css +595 -0
@@ -0,0 +1,1091 @@
1
+ // Zero-dependency shared filesystem safety, atomic I/O & SSRF helpers for Veycraft.
2
+ // Extracted verbatim from bin/cli.mjs — uses Node.js built-in modules only.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import os from 'node:os';
6
+ import crypto from 'node:crypto';
7
+ import zlib from 'node:zlib';
8
+ import dns from 'node:dns/promises';
9
+ import http from 'node:http';
10
+ import https from 'node:https';
11
+ import net from 'node:net';
12
+
13
+ export function normalizePathForCompare(p) {
14
+ const resolved = path.resolve(p);
15
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
16
+ }
17
+
18
+ export function isSamePath(a, b) {
19
+ return path.relative(normalizePathForCompare(a), normalizePathForCompare(b)) === '';
20
+ }
21
+
22
+ export function isObj(v) {
23
+ return Boolean(v) && typeof v === 'object' && !Array.isArray(v);
24
+ }
25
+
26
+ export function sleepSync(ms) {
27
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
28
+ }
29
+
30
+ export function isWithinDir(targetPath, dirPath) {
31
+ const rel = path.relative(normalizePathForCompare(dirPath), normalizePathForCompare(targetPath));
32
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
33
+ }
34
+
35
+ export function refuseSymlink(target, boundary, home = os.homedir()) {
36
+ if (typeof boundary !== 'string' || !boundary.trim()) {
37
+ throw new Error('refuseSymlink requires an explicit non-empty boundary path.');
38
+ }
39
+ let cursor = path.resolve(target);
40
+ const resolvedRoot = path.resolve(boundary);
41
+ const resolvedHome = path.resolve(home);
42
+
43
+ let stop;
44
+ let stopInclusive = true;
45
+ if (isWithinDir(cursor, resolvedRoot)) {
46
+ stop = resolvedRoot;
47
+ stopInclusive = true;
48
+ } else if (isWithinDir(cursor, resolvedHome)) {
49
+ stop = resolvedHome;
50
+ stopInclusive = false;
51
+ } else {
52
+ stop = cursor;
53
+ stopInclusive = true;
54
+ }
55
+
56
+ while (true) {
57
+ if (!stopInclusive && cursor === stop) return;
58
+ let stat;
59
+ try { stat = fs.lstatSync(cursor); } catch (e) { if (e.code !== 'ENOENT') throw e; }
60
+ if (stat?.isSymbolicLink()) {
61
+ throw new Error(`Refusing symbolic-link destination: ${cursor}`);
62
+ }
63
+ if (cursor === stop) return;
64
+ const parent = path.dirname(cursor);
65
+ if (parent === cursor) break;
66
+ cursor = parent;
67
+ }
68
+ }
69
+
70
+ export function writeAtomic(file, content, { preserve = false, mode = 0o644, boundary, home = os.homedir() } = {}) {
71
+ refuseSymlink(file, boundary, home);
72
+ if (preserve && fs.existsSync(file)) return false;
73
+ fs.mkdirSync(path.dirname(file), { recursive: true });
74
+ const tmp = `${file}.tmp-${process.pid}-${crypto.randomBytes(4).toString('hex')}`;
75
+ fs.writeFileSync(tmp, content, { flag: 'wx', mode });
76
+ try {
77
+ const retryDelays = [50, 150, 300];
78
+ let lastErr = null;
79
+ for (let attempt = 0; attempt <= retryDelays.length; attempt++) {
80
+ try {
81
+ fs.renameSync(tmp, file);
82
+ lastErr = null;
83
+ break;
84
+ } catch (err) {
85
+ lastErr = err;
86
+ if (attempt < retryDelays.length && (err?.code === 'EPERM' || err?.code === 'EBUSY')) {
87
+ sleepSync(retryDelays[attempt]);
88
+ continue;
89
+ }
90
+ throw err;
91
+ }
92
+ }
93
+ if (lastErr) throw lastErr;
94
+ if (process.platform !== 'win32') {
95
+ try { fs.chmodSync(file, mode); } catch { /* ignore */ }
96
+ }
97
+ } finally {
98
+ try {
99
+ if (fs.existsSync(tmp)) fs.unlinkSync(tmp);
100
+ } catch { /* ignore cleanup error so primary error is preserved */ }
101
+ }
102
+ return true;
103
+ }
104
+
105
+ export function readJsonSafe(file, { boundary, home = os.homedir() } = {}) {
106
+ refuseSymlink(file, boundary, home);
107
+ if (!fs.existsSync(file)) return {};
108
+ let parsed;
109
+ try {
110
+ parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
111
+ } catch {
112
+ throw new Error(`Invalid JSON in ${file}; refusing to overwrite.`);
113
+ }
114
+ if (!isObj(parsed)) throw new Error(`Unsupported JSON root in ${file}; expected object.`);
115
+ return parsed;
116
+ }
117
+
118
+ function classifyIpv4Octets(a, b, c, d) {
119
+ if (
120
+ !Number.isInteger(a) || a < 0 || a > 255 ||
121
+ !Number.isInteger(b) || b < 0 || b > 255 ||
122
+ !Number.isInteger(c) || c < 0 || c > 255 ||
123
+ !Number.isInteger(d) || d < 0 || d > 255
124
+ ) {
125
+ return 'invalid IPv4 address';
126
+ }
127
+ if (a === 0) return 'unspecified IPv4 range (0.0.0.0/8)';
128
+ if (a === 10) return 'private IPv4 range (10.0.0.0/8)';
129
+ if (a === 100 && b >= 64 && b <= 127) return 'carrier-grade NAT IPv4 range (100.64.0.0/10)';
130
+ if (a === 127) return 'loopback IPv4 range (127.0.0.0/8)';
131
+ if (a === 169 && b === 254) return 'link-local/metadata IPv4 range (169.254.0.0/16)';
132
+ if (a === 172 && b >= 16 && b <= 31) return 'private IPv4 range (172.16.0.0/12)';
133
+ if (a === 192 && b === 0 && c === 0) return 'IETF protocol assignment IPv4 range (192.0.0.0/24)';
134
+ if (a === 192 && b === 0 && c === 2) return 'documentation IPv4 range (192.0.2.0/24)';
135
+ if (a === 192 && b === 168) return 'private IPv4 range (192.168.0.0/16)';
136
+ if (a === 198 && (b === 18 || b === 19)) return 'benchmarking IPv4 range (198.18.0.0/15)';
137
+ if (a === 198 && b === 51 && c === 100) return 'documentation IPv4 range (198.51.100.0/24)';
138
+ if (a === 203 && b === 0 && c === 113) return 'documentation IPv4 range (203.0.113.0/24)';
139
+ if (a >= 224) return 'multicast/reserved IPv4 range (224.0.0.0/3)';
140
+ return null;
141
+ }
142
+
143
+ function parseIpv6ToWords(hostStr) {
144
+ // Strip IPv6 zone index if present (%25... or %...)
145
+ const zoneIdx = hostStr.indexOf('%');
146
+ const clean = zoneIdx >= 0 ? hostStr.slice(0, zoneIdx) : hostStr;
147
+ if (!clean || !clean.includes(':')) return null;
148
+
149
+ let working = clean;
150
+ // Support dotted-quad IPv4 suffix inside IPv6 (e.g. ::127.0.0.1 or ::ffff:169.254.169.254)
151
+ const lastColon = working.lastIndexOf(':');
152
+ const tail = working.slice(lastColon + 1);
153
+ if (tail.includes('.')) {
154
+ const m = tail.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
155
+ if (!m) return null;
156
+ const octs = [Number(m[1]), Number(m[2]), Number(m[3]), Number(m[4])];
157
+ if (octs.some(o => o < 0 || o > 255)) return null;
158
+ const hi = ((octs[0] << 8) | octs[1]).toString(16);
159
+ const lo = ((octs[2] << 8) | octs[3]).toString(16);
160
+ working = `${working.slice(0, lastColon + 1)}${hi}:${lo}`;
161
+ }
162
+
163
+ const dblParts = working.split('::');
164
+ if (dblParts.length > 2) return null;
165
+
166
+ const parseSide = s => {
167
+ if (!s) return [];
168
+ const tokens = s.split(':');
169
+ const out = [];
170
+ for (const tok of tokens) {
171
+ if (!/^[0-9a-f]{1,4}$/i.test(tok)) return null;
172
+ out.push(parseInt(tok, 16));
173
+ }
174
+ return out;
175
+ };
176
+
177
+ if (dblParts.length === 1) {
178
+ const words = parseSide(dblParts[0]);
179
+ return (words && words.length === 8) ? words : null;
180
+ }
181
+
182
+ const left = parseSide(dblParts[0]);
183
+ const right = parseSide(dblParts[1]);
184
+ if (!left || !right) return null;
185
+ const missing = 8 - (left.length + right.length);
186
+ if (missing < 1) return null;
187
+ return [...left, ...Array(missing).fill(0), ...right];
188
+ }
189
+
190
+ function classifyIpv6Words(w) {
191
+ if (!Array.isArray(w) || w.length !== 8) return 'invalid IPv6 address';
192
+ const allZeroPrefix6 = w[0] === 0 && w[1] === 0 && w[2] === 0 && w[3] === 0 && w[4] === 0 && w[5] === 0;
193
+ // ::/128 unspecified
194
+ if (allZeroPrefix6 && w[6] === 0 && w[7] === 0) return 'unspecified IPv6 address (::/128)';
195
+ // ::1/128 loopback
196
+ if (allZeroPrefix6 && w[6] === 0 && w[7] === 1) return 'loopback IPv6 address (::1/128)';
197
+
198
+ // IPv4-compatible IPv6 ::/96 (deprecated RFC 4291, e.g. [::127.0.0.1] -> ::7f00:1 or [::169.254.169.254] -> ::a9fe:a9fe)
199
+ if (allZeroPrefix6) {
200
+ const a = (w[6] >> 8) & 0xff;
201
+ const b = w[6] & 0xff;
202
+ const c = (w[7] >> 8) & 0xff;
203
+ const d = w[7] & 0xff;
204
+ const v4Reason = classifyIpv4Octets(a, b, c, d);
205
+ return v4Reason ? `IPv4-compatible IPv6 (${v4Reason})` : 'deprecated IPv4-compatible IPv6 range (::/96)';
206
+ }
207
+
208
+ // IPv4-mapped IPv6 ::ffff:0:0/96
209
+ if (w[0] === 0 && w[1] === 0 && w[2] === 0 && w[3] === 0 && w[4] === 0 && w[5] === 0xffff) {
210
+ const a = (w[6] >> 8) & 0xff;
211
+ const b = w[6] & 0xff;
212
+ const c = (w[7] >> 8) & 0xff;
213
+ const d = w[7] & 0xff;
214
+ const v4Reason = classifyIpv4Octets(a, b, c, d);
215
+ return v4Reason ? `IPv4-mapped IPv6 (${v4Reason})` : 'IPv4-mapped IPv6 address (::ffff:0:0/96)';
216
+ }
217
+
218
+ // IPv4-translated IPv6 ::ffff:0:0:0/96 (RFC 2765 SIIT)
219
+ if (w[0] === 0 && w[1] === 0 && w[2] === 0 && w[3] === 0 && w[4] === 0xffff && w[5] === 0) {
220
+ const a = (w[6] >> 8) & 0xff;
221
+ const b = w[6] & 0xff;
222
+ const c = (w[7] >> 8) & 0xff;
223
+ const d = w[7] & 0xff;
224
+ const v4Reason = classifyIpv4Octets(a, b, c, d);
225
+ return v4Reason ? `IPv4-translated IPv6 (${v4Reason})` : 'IPv4-translated IPv6 address (::ffff:0:0:0/96)';
226
+ }
227
+
228
+ // NAT64 Well-Known Prefix 64:ff9b::/96 and 64:ff9b:1::/48
229
+ if (
230
+ (w[0] === 0x0064 && w[1] === 0xff9b && w[2] === 0 && w[3] === 0 && w[4] === 0 && w[5] === 0) ||
231
+ (w[0] === 0x0064 && w[1] === 0xff9b && w[2] === 1)
232
+ ) {
233
+ const a = (w[6] >> 8) & 0xff;
234
+ const b = w[6] & 0xff;
235
+ const c = (w[7] >> 8) & 0xff;
236
+ const d = w[7] & 0xff;
237
+ const v4Reason = classifyIpv4Octets(a, b, c, d);
238
+ return v4Reason ? `NAT64 embedded IPv4 (${v4Reason})` : 'NAT64 IPv6 prefix (64:ff9b::/96)';
239
+ }
240
+
241
+ // 6to4 2002::/16 (embeds IPv4 in w[1], w[2])
242
+ if (w[0] === 0x2002) {
243
+ const a = (w[1] >> 8) & 0xff;
244
+ const b = w[1] & 0xff;
245
+ const c = (w[2] >> 8) & 0xff;
246
+ const d = w[2] & 0xff;
247
+ const v4Reason = classifyIpv4Octets(a, b, c, d);
248
+ if (v4Reason) return `6to4 embedded IPv4 (${v4Reason})`;
249
+ }
250
+
251
+ // Unique Local fc00::/7 (fc00::..fdff::)
252
+ if ((w[0] & 0xfe00) === 0xfc00) return 'unique-local IPv6 address (fc00::/7)';
253
+ // Link-Local fe80::/10
254
+ if ((w[0] & 0xffc0) === 0xfe80) return 'link-local IPv6 address (fe80::/10)';
255
+ // Deprecated Site-Local fec0::/10
256
+ if ((w[0] & 0xffc0) === 0xfec0) return 'site-local IPv6 address (fec0::/10)';
257
+ // Multicast ff00::/8
258
+ if ((w[0] & 0xff00) === 0xff00) return 'multicast IPv6 address (ff00::/8)';
259
+ // Teredo tunneling 2001:0000::/32 (can encapsulate obfuscated private/loopback IPv4)
260
+ if (w[0] === 0x2001 && w[1] === 0x0000) return 'Teredo tunneling IPv6 range (2001:0000::/32)';
261
+ // Discard-Only Prefix 100::/64 (RFC 6666)
262
+ if (w[0] === 0x0100 && w[1] === 0 && w[2] === 0 && w[3] === 0) return 'discard-only IPv6 range (100::/64)';
263
+ // Documentation 2001:db8::/32
264
+ if (w[0] === 0x2001 && w[1] === 0x0db8) return 'documentation IPv6 address (2001:db8::/32)';
265
+
266
+ return null;
267
+ }
268
+
269
+ export function classifyIpAddress(rawIp) {
270
+ if (typeof rawIp !== 'string' || !rawIp.trim()) {
271
+ return 'empty or invalid IP address';
272
+ }
273
+ const clean = rawIp.trim().toLowerCase().replace(/^\[|\]$/g, '');
274
+ if (clean.includes(':')) {
275
+ if (clean.includes('%')) return 'IPv6 zone-scoped link-local address';
276
+ const words = parseIpv6ToWords(clean);
277
+ if (!words) return 'malformed IPv6 address';
278
+ return classifyIpv6Words(words);
279
+ }
280
+ const ipv4Match = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
281
+ if (!ipv4Match) return 'malformed IPv4 address';
282
+ return classifyIpv4Octets(
283
+ Number(ipv4Match[1]),
284
+ Number(ipv4Match[2]),
285
+ Number(ipv4Match[3]),
286
+ Number(ipv4Match[4]),
287
+ );
288
+ }
289
+
290
+ export function isBlockedSsrfUrl(inputUrl) {
291
+ let parsedUrl = inputUrl;
292
+ if (typeof inputUrl === 'string') {
293
+ try {
294
+ parsedUrl = new URL(inputUrl);
295
+ } catch {
296
+ return 'malformed URL';
297
+ }
298
+ }
299
+ if (!parsedUrl || typeof parsedUrl !== 'object') {
300
+ return 'invalid URL object';
301
+ }
302
+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
303
+ return 'non-HTTP(S) protocol';
304
+ }
305
+ if (parsedUrl.username || parsedUrl.password) {
306
+ return 'embedded URL credentials not allowed';
307
+ }
308
+ const rawHost = String(parsedUrl.hostname || '').toLowerCase().replace(/\.+$/, '');
309
+ const host = rawHost.replace(/^\[|\]$/g, '');
310
+ if (!host) {
311
+ return 'empty host';
312
+ }
313
+ if (
314
+ host === 'localhost' ||
315
+ host.endsWith('.localhost') ||
316
+ host.endsWith('.local') ||
317
+ host.endsWith('.internal') ||
318
+ host === 'metadata.google.internal' ||
319
+ host === 'metadata' ||
320
+ host === 'instance-data'
321
+ ) {
322
+ return 'loopback/localhost/internal host';
323
+ }
324
+
325
+ // IPv6 check (either bracketed or containing colons)
326
+ if (rawHost.startsWith('[') || host.includes(':')) {
327
+ if (host.includes('%')) {
328
+ return 'IPv6 zone-scoped link-local address';
329
+ }
330
+ const words = parseIpv6ToWords(host);
331
+ if (!words) return 'malformed IPv6 host';
332
+ return classifyIpv6Words(words);
333
+ }
334
+
335
+ // Canonical dotted IPv4 check
336
+ const ipv4Match = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
337
+ if (ipv4Match) {
338
+ return classifyIpv4Octets(
339
+ Number(ipv4Match[1]),
340
+ Number(ipv4Match[2]),
341
+ Number(ipv4Match[3]),
342
+ Number(ipv4Match[4]),
343
+ );
344
+ }
345
+
346
+ // Block non-standard numeric/hex/octal IPv4 host representations that may slip past URL parser
347
+ if (/^[0-9.]+$/.test(host) || /^0x[0-9a-f]+$/i.test(host)) {
348
+ return 'non-canonical numeric IP literal';
349
+ }
350
+
351
+ return null;
352
+ }
353
+
354
+ const REDIRECT_STATUS_CODES = new Set([301, 302, 303, 307, 308]);
355
+
356
+ async function defaultDnsLookup(hostname) {
357
+ return dns.lookup(hostname, { all: true, verbatim: true });
358
+ }
359
+
360
+ export async function resolveAndValidateSsrfHost(parsedUrl, { lookupImpl = defaultDnsLookup } = {}) {
361
+ const staticBlock = isBlockedSsrfUrl(parsedUrl);
362
+ if (staticBlock) {
363
+ throw new Error(`Blocked by SSRF guard (${staticBlock}): ${parsedUrl.href}`);
364
+ }
365
+ const normalizedHost = String(parsedUrl.hostname || '').toLowerCase().replace(/\.+$/, '').replace(/^\[|\]$/g, '');
366
+ const literalFamily = net.isIP(normalizedHost);
367
+ if (literalFamily === 4 || literalFamily === 6) {
368
+ const ipReason = classifyIpAddress(normalizedHost);
369
+ if (ipReason) {
370
+ throw new Error(`Blocked by SSRF guard (${ipReason}): ${parsedUrl.href}`);
371
+ }
372
+ return [{ address: normalizedHost, family: literalFamily }];
373
+ }
374
+
375
+ if (typeof lookupImpl !== 'function') {
376
+ throw new Error(`Blocked by SSRF guard (DNS lookup implementation unavailable for "${normalizedHost}"): ${parsedUrl.href}`);
377
+ }
378
+
379
+ let records;
380
+ try {
381
+ records = await lookupImpl(normalizedHost, { all: true, verbatim: true });
382
+ } catch (err) {
383
+ const msg = err instanceof Error ? err.message : String(err);
384
+ throw new Error(`Blocked by SSRF guard (DNS lookup failed for "${normalizedHost}": ${msg}): ${parsedUrl.href}`);
385
+ }
386
+
387
+ const normalizedRecords = (Array.isArray(records) ? records : [records])
388
+ .filter(r => r && typeof r.address === 'string' && r.address.trim())
389
+ .map(r => {
390
+ const addr = r.address.trim();
391
+ const fam = r.family === 4 || r.family === 6 ? r.family : net.isIP(addr);
392
+ return { address: addr, family: fam };
393
+ });
394
+
395
+ if (normalizedRecords.length === 0) {
396
+ throw new Error(`Blocked by SSRF guard (DNS lookup returned no addresses for "${normalizedHost}"): ${parsedUrl.href}`);
397
+ }
398
+
399
+ for (const rec of normalizedRecords) {
400
+ const reason = classifyIpAddress(rec.address);
401
+ if (reason) {
402
+ throw new Error(`Blocked by SSRF guard (DNS for "${normalizedHost}" resolved to ${reason}: ${rec.address}): ${parsedUrl.href}`);
403
+ }
404
+ if (rec.family !== 4 && rec.family !== 6) {
405
+ throw new Error(`Blocked by SSRF guard (DNS for "${normalizedHost}" returned invalid address family for ${rec.address}): ${parsedUrl.href}`);
406
+ }
407
+ }
408
+
409
+ return normalizedRecords;
410
+ }
411
+
412
+ function pinnedHttpRequest(targetUrl, {
413
+ method = 'HEAD',
414
+ headers = {},
415
+ timeoutMs = 3500,
416
+ resolvedAddresses,
417
+ }) {
418
+ const isHttps = targetUrl.protocol === 'https:';
419
+ const transport = isHttps ? https : http;
420
+ const normalizedHost = String(targetUrl.hostname || '').toLowerCase().replace(/\.+$/, '').replace(/^\[|\]$/g, '');
421
+ const primary = resolvedAddresses[0];
422
+
423
+ const pinnedLookup = (_hostname, optionsOrCb, maybeCb) => {
424
+ const cb = typeof optionsOrCb === 'function' ? optionsOrCb : maybeCb;
425
+ const opts = typeof optionsOrCb === 'object' && optionsOrCb !== null ? optionsOrCb : {};
426
+ if (opts.all) {
427
+ cb(null, resolvedAddresses.map(r => ({ address: r.address, family: r.family })));
428
+ } else {
429
+ cb(null, primary.address, primary.family);
430
+ }
431
+ };
432
+
433
+ return new Promise((resolve, reject) => {
434
+ const reqOpts = {
435
+ protocol: targetUrl.protocol,
436
+ hostname: normalizedHost,
437
+ port: targetUrl.port ? Number(targetUrl.port) : (isHttps ? 443 : 80),
438
+ path: `${targetUrl.pathname || '/'}${targetUrl.search || ''}`,
439
+ method,
440
+ headers,
441
+ agent: false,
442
+ lookup: pinnedLookup,
443
+ ...(isHttps && net.isIP(normalizedHost) === 0 ? { servername: normalizedHost } : {}),
444
+ };
445
+
446
+ const req = transport.request(reqOpts, res => {
447
+ // Drain response body without buffering to avoid memory blowup on HEAD/GET link checks
448
+ res.resume();
449
+ const rawHeaders = res.headers || {};
450
+ resolve({
451
+ status: res.statusCode || 0,
452
+ headers: {
453
+ get(name) {
454
+ const val = rawHeaders[String(name).toLowerCase()];
455
+ if (Array.isArray(val)) return val.join(', ');
456
+ return val === undefined ? null : String(val);
457
+ },
458
+ },
459
+ });
460
+ });
461
+
462
+ req.setTimeout(timeoutMs, () => {
463
+ req.destroy(new Error(`Request timed out after ${timeoutMs}ms`));
464
+ });
465
+ req.on('error', err => reject(err));
466
+ req.end();
467
+ });
468
+ }
469
+
470
+ export async function fetchUrlWithSafeRedirects(initialUrl, {
471
+ fetchImpl = null,
472
+ lookupImpl = defaultDnsLookup,
473
+ method = 'HEAD',
474
+ maxRedirects = 5,
475
+ timeoutMs = 3500,
476
+ headers = { 'User-Agent': 'veycraft-link-check/2.0' },
477
+ } = {}) {
478
+ let currentUrl;
479
+ try {
480
+ currentUrl = initialUrl instanceof URL ? new URL(initialUrl.href) : new URL(String(initialUrl));
481
+ } catch {
482
+ throw new Error(`Malformed URL: "${initialUrl}"`);
483
+ }
484
+ const initialBlock = isBlockedSsrfUrl(currentUrl);
485
+ if (initialBlock) {
486
+ throw new Error(`Blocked by SSRF guard (${initialBlock}): ${currentUrl.href}`);
487
+ }
488
+
489
+ let currentMethod = method;
490
+ const visited = new Set([currentUrl.href]);
491
+
492
+ for (let hop = 0; hop <= maxRedirects; hop++) {
493
+ // F-03: Resolve and validate all DNS addresses on EVERY hop before issuing any network request
494
+ const resolvedAddresses = await resolveAndValidateSsrfHost(currentUrl, { lookupImpl });
495
+
496
+ let res;
497
+ if (typeof fetchImpl === 'function') {
498
+ const signal = typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
499
+ ? AbortSignal.timeout(timeoutMs)
500
+ : undefined;
501
+ res = await fetchImpl(currentUrl.href, {
502
+ method: currentMethod,
503
+ redirect: 'manual',
504
+ ...(signal ? { signal } : {}),
505
+ headers,
506
+ resolvedAddresses,
507
+ });
508
+ } else {
509
+ res = await pinnedHttpRequest(currentUrl, {
510
+ method: currentMethod,
511
+ headers,
512
+ timeoutMs,
513
+ resolvedAddresses,
514
+ });
515
+ }
516
+
517
+ if (!REDIRECT_STATUS_CODES.has(res.status)) {
518
+ return { response: res, finalUrl: currentUrl.href, redirects: hop, resolvedAddresses };
519
+ }
520
+
521
+ if (hop >= maxRedirects) {
522
+ throw new Error(`Maximum redirect limit (${maxRedirects}) exceeded at ${currentUrl.href}`);
523
+ }
524
+
525
+ const locationHeader = res.headers && typeof res.headers.get === 'function'
526
+ ? res.headers.get('location')
527
+ : (res.headers && (res.headers.location || res.headers.Location));
528
+ if (typeof locationHeader !== 'string' || !locationHeader.trim()) {
529
+ throw new Error(`Redirect response (HTTP ${res.status}) missing Location header.`);
530
+ }
531
+
532
+ let nextUrl;
533
+ try {
534
+ nextUrl = new URL(locationHeader.trim(), currentUrl);
535
+ } catch {
536
+ throw new Error(`Malformed redirect Location "${locationHeader}" from ${currentUrl.href}`);
537
+ }
538
+
539
+ const redirectBlock = isBlockedSsrfUrl(nextUrl);
540
+ if (redirectBlock) {
541
+ throw new Error(`Redirect target blocked by SSRF guard (${redirectBlock}): ${nextUrl.href}`);
542
+ }
543
+
544
+ if (visited.has(nextUrl.href)) {
545
+ throw new Error(`Redirect loop detected to ${nextUrl.href}`);
546
+ }
547
+ visited.add(nextUrl.href);
548
+
549
+ if (res.status === 303 && currentMethod !== 'GET' && currentMethod !== 'HEAD') {
550
+ currentMethod = 'GET';
551
+ }
552
+ currentUrl = nextUrl;
553
+ }
554
+
555
+ throw new Error(`Maximum redirect limit (${maxRedirects}) exceeded.`);
556
+ }
557
+
558
+ function pinnedHttpTextRequest(targetUrl, {
559
+ method = 'GET',
560
+ headers = {},
561
+ timeoutMs = 8000,
562
+ maxBytes = 1_500_000,
563
+ resolvedAddresses,
564
+ }) {
565
+ const isHttps = targetUrl.protocol === 'https:';
566
+ const transport = isHttps ? https : http;
567
+ const normalizedHost = String(targetUrl.hostname || '').toLowerCase().replace(/\.+$/, '').replace(/^\[|\]$/g, '');
568
+ const primary = resolvedAddresses[0];
569
+
570
+ const pinnedLookup = (_hostname, optionsOrCb, maybeCb) => {
571
+ const cb = typeof optionsOrCb === 'function' ? optionsOrCb : maybeCb;
572
+ const opts = typeof optionsOrCb === 'object' && optionsOrCb !== null ? optionsOrCb : {};
573
+ if (opts.all) {
574
+ cb(null, resolvedAddresses.map(r => ({ address: r.address, family: r.family })));
575
+ } else {
576
+ cb(null, primary.address, primary.family);
577
+ }
578
+ };
579
+
580
+ return new Promise((resolve, reject) => {
581
+ let settled = false;
582
+ const finish = (err, val) => {
583
+ if (settled) return;
584
+ settled = true;
585
+ if (err) reject(err);
586
+ else resolve(val);
587
+ };
588
+
589
+ const reqOpts = {
590
+ protocol: targetUrl.protocol,
591
+ hostname: normalizedHost,
592
+ port: targetUrl.port ? Number(targetUrl.port) : (isHttps ? 443 : 80),
593
+ path: `${targetUrl.pathname || '/'}${targetUrl.search || ''}`,
594
+ method,
595
+ headers,
596
+ agent: false,
597
+ lookup: pinnedLookup,
598
+ ...(isHttps && net.isIP(normalizedHost) === 0 ? { servername: normalizedHost } : {}),
599
+ };
600
+
601
+ const req = transport.request(reqOpts, res => {
602
+ const rawHeaders = res.headers || {};
603
+ const status = res.statusCode || 0;
604
+ const headerAccessor = {
605
+ get(name) {
606
+ const val = rawHeaders[String(name).toLowerCase()];
607
+ if (Array.isArray(val)) return val.join(', ');
608
+ return val === undefined ? null : String(val);
609
+ },
610
+ };
611
+
612
+ if (REDIRECT_STATUS_CODES.has(status)) {
613
+ res.resume();
614
+ finish(null, { status, headers: headerAccessor, text: '' });
615
+ return;
616
+ }
617
+
618
+ const chunks = [];
619
+ let total = 0;
620
+ res.on('data', chunk => {
621
+ total += chunk.length;
622
+ if (total > maxBytes) {
623
+ res.destroy();
624
+ req.destroy();
625
+ finish(new Error(`Response exceeded maxBytes limit (${maxBytes} bytes) from ${targetUrl.href}`));
626
+ return;
627
+ }
628
+ chunks.push(chunk);
629
+ });
630
+ res.on('end', () => {
631
+ try {
632
+ let buf = Buffer.concat(chunks);
633
+ const enc = String(headerAccessor.get('content-encoding') || '').toLowerCase().trim();
634
+ if (enc === 'gzip' || enc === 'x-gzip') {
635
+ buf = zlib.gunzipSync(buf, { maxOutputLength: maxBytes });
636
+ } else if (enc === 'deflate') {
637
+ buf = zlib.inflateSync(buf, { maxOutputLength: maxBytes });
638
+ }
639
+ finish(null, { status, headers: headerAccessor, text: buf.toString('utf8') });
640
+ } catch (err) {
641
+ finish(err);
642
+ }
643
+ });
644
+ res.on('error', err => finish(err));
645
+ });
646
+
647
+ req.setTimeout(timeoutMs, () => {
648
+ req.destroy(new Error(`Request timed out after ${timeoutMs}ms`));
649
+ });
650
+ req.on('error', err => finish(err));
651
+ req.end();
652
+ });
653
+ }
654
+
655
+ export async function fetchTextWithSafeRedirects(initialUrl, {
656
+ fetchImpl = null,
657
+ lookupImpl = defaultDnsLookup,
658
+ maxRedirects = 5,
659
+ timeoutMs = 8000,
660
+ maxBytes = 1_500_000,
661
+ headers = {
662
+ 'User-Agent': 'veycraft-feed-scan/2.6',
663
+ Accept: 'application/json, application/rss+xml, application/atom+xml, application/xml, text/xml;q=0.9',
664
+ },
665
+ } = {}) {
666
+ let currentUrl;
667
+ try {
668
+ currentUrl = initialUrl instanceof URL ? new URL(initialUrl.href) : new URL(String(initialUrl));
669
+ } catch {
670
+ throw new Error(`Malformed URL: "${initialUrl}"`);
671
+ }
672
+ const initialBlock = isBlockedSsrfUrl(currentUrl);
673
+ if (initialBlock) {
674
+ throw new Error(`Blocked by SSRF guard (${initialBlock}): ${currentUrl.href}`);
675
+ }
676
+
677
+ const visited = new Set([currentUrl.href]);
678
+ for (let hop = 0; hop <= maxRedirects; hop++) {
679
+ const resolvedAddresses = await resolveAndValidateSsrfHost(currentUrl, { lookupImpl });
680
+ let res;
681
+ if (typeof fetchImpl === 'function') {
682
+ res = await fetchImpl(currentUrl.href, {
683
+ method: 'GET',
684
+ redirect: 'manual',
685
+ headers,
686
+ maxBytes,
687
+ timeoutMs,
688
+ resolvedAddresses,
689
+ });
690
+ const textVal = typeof res?.text === 'function' ? await res.text() : String(res?.text ?? '');
691
+ if (Buffer.byteLength(textVal, 'utf8') > maxBytes) {
692
+ throw new Error(`Response exceeded maxBytes limit (${maxBytes} bytes) from ${currentUrl.href}`);
693
+ }
694
+ res = { status: res?.status || 0, headers: res?.headers || { get: () => null }, text: textVal };
695
+ } else {
696
+ res = await pinnedHttpTextRequest(currentUrl, {
697
+ method: 'GET',
698
+ headers,
699
+ timeoutMs,
700
+ maxBytes,
701
+ resolvedAddresses,
702
+ });
703
+ }
704
+
705
+ if (!REDIRECT_STATUS_CODES.has(res.status)) {
706
+ const contentType = res.headers && typeof res.headers.get === 'function'
707
+ ? String(res.headers.get('content-type') || '')
708
+ : String(res.headers?.['content-type'] || '');
709
+ return {
710
+ status: res.status,
711
+ finalUrl: currentUrl.href,
712
+ redirects: hop,
713
+ contentType,
714
+ text: res.text,
715
+ };
716
+ }
717
+
718
+ if (hop >= maxRedirects) {
719
+ throw new Error(`Maximum redirect limit (${maxRedirects}) exceeded at ${currentUrl.href}`);
720
+ }
721
+ const locationHeader = res.headers && typeof res.headers.get === 'function'
722
+ ? res.headers.get('location')
723
+ : (res.headers && (res.headers.location || res.headers.Location));
724
+ if (typeof locationHeader !== 'string' || !locationHeader.trim()) {
725
+ throw new Error(`Redirect response (HTTP ${res.status}) missing Location header.`);
726
+ }
727
+ let nextUrl;
728
+ try {
729
+ nextUrl = new URL(locationHeader.trim(), currentUrl);
730
+ } catch {
731
+ throw new Error(`Malformed redirect Location "${locationHeader}" from ${currentUrl.href}`);
732
+ }
733
+ const redirectBlock = isBlockedSsrfUrl(nextUrl);
734
+ if (redirectBlock) {
735
+ throw new Error(`Redirect target blocked by SSRF guard (${redirectBlock}): ${nextUrl.href}`);
736
+ }
737
+ if (visited.has(nextUrl.href)) {
738
+ throw new Error(`Redirect loop detected to ${nextUrl.href}`);
739
+ }
740
+ visited.add(nextUrl.href);
741
+ currentUrl = nextUrl;
742
+ }
743
+
744
+ throw new Error(`Maximum redirect limit (${maxRedirects}) exceeded.`);
745
+ }
746
+
747
+ // ---------------- SEC-03: Hardened OOXML (.docx) ZIP Parser with Decompression Limits ----------------
748
+
749
+ export const DOCX_LIMITS = Object.freeze({
750
+ MAX_INPUT_BYTES: 10 * 1024 * 1024, // 10 MB max input .docx file size
751
+ MAX_TOTAL_ENTRIES: 512, // max total ZIP central directory entries
752
+ MAX_XML_ENTRIES: 24, // max accepted word/(document|header*|footer*).xml entries
753
+ MAX_COMPRESSED_ENTRY_BYTES: 5 * 1024 * 1024, // 5 MB max compressed entry size
754
+ MAX_ENTRY_UNCOMPRESSED_BYTES: 5 * 1024 * 1024, // 5 MB max per-entry decompressed size
755
+ MAX_TOTAL_UNCOMPRESSED_BYTES: 10 * 1024 * 1024, // 10 MB max cumulative decompressed size
756
+ });
757
+
758
+ export function readFileBoundedSync(filePath, maxBytes, label = 'file') {
759
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
760
+ throw new Error(`Invalid maxBytes limit for ${label}: ${maxBytes}`);
761
+ }
762
+ const fd = fs.openSync(filePath, 'r');
763
+ try {
764
+ const stat = fs.fstatSync(fd);
765
+ if (!stat.isFile()) {
766
+ throw new Error(`Expected regular file for ${label}: ${filePath}`);
767
+ }
768
+ if (stat.size > maxBytes) {
769
+ throw new Error(`Oversized ${label} (${stat.size} bytes exceeds ${maxBytes} byte limit).`);
770
+ }
771
+ if (stat.size === 0) {
772
+ return Buffer.alloc(0);
773
+ }
774
+ // Read bounded chunks up to maxBytes + 1 so concurrent file growth cannot cause unbounded allocation
775
+ const chunkSize = Math.min(65536, maxBytes + 1);
776
+ const chunks = [];
777
+ let totalRead = 0;
778
+ while (totalRead <= maxBytes) {
779
+ const toRead = Math.min(chunkSize, maxBytes + 1 - totalRead);
780
+ const buf = Buffer.allocUnsafe(toRead);
781
+ const bytesRead = fs.readSync(fd, buf, 0, toRead, null);
782
+ if (bytesRead === 0) break;
783
+ totalRead += bytesRead;
784
+ if (totalRead > maxBytes) {
785
+ throw new Error(`Oversized ${label} (exceeds ${maxBytes} byte limit).`);
786
+ }
787
+ chunks.push(bytesRead === toRead ? buf : buf.subarray(0, bytesRead));
788
+ }
789
+ return chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, totalRead);
790
+ } finally {
791
+ fs.closeSync(fd);
792
+ }
793
+ }
794
+
795
+ const NAMED_XML_HTML_ENTITIES = Object.freeze({
796
+ nbsp: ' ',
797
+ amp: '&',
798
+ lt: '<',
799
+ gt: '>',
800
+ quot: '"',
801
+ apos: "'",
802
+ });
803
+ const XML_HTML_ENTITY_RE = /&(?:(nbsp|amp|lt|gt|quot|apos)|#(\d+)|#x([0-9a-f]+));/gi;
804
+
805
+ export function decodeXmlHtmlEntities(str) {
806
+ return String(str || '').replace(XML_HTML_ENTITY_RE, (full, named, dec, hex) => {
807
+ if (named) return NAMED_XML_HTML_ENTITIES[named.toLowerCase()] ?? full;
808
+ const code = dec !== undefined ? Number(dec) : parseInt(hex, 16);
809
+ return Number.isInteger(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : '';
810
+ });
811
+ }
812
+
813
+ export function stripHtmlBlocks(input, tagNames = ['script', 'style']) {
814
+ let text = String(input || '');
815
+ for (const rawTag of tagNames) {
816
+ const tag = String(rawTag || '').toLowerCase();
817
+ if (!tag) continue;
818
+ const openNeedle = `<${tag}`;
819
+ const closeNeedle = `</${tag}`;
820
+ const lower = text.toLowerCase();
821
+ let out = '';
822
+ let pos = 0;
823
+ while (pos < text.length) {
824
+ const start = lower.indexOf(openNeedle, pos);
825
+ if (start === -1) {
826
+ out += text.slice(pos);
827
+ break;
828
+ }
829
+ const afterOpen = lower[start + openNeedle.length];
830
+ if (afterOpen !== undefined && afterOpen !== '>' && afterOpen !== '/' && !/\s/.test(afterOpen)) {
831
+ out += text.slice(pos, start + openNeedle.length);
832
+ pos = start + openNeedle.length;
833
+ continue;
834
+ }
835
+ out += text.slice(pos, start);
836
+ const openEnd = text.indexOf('>', start + openNeedle.length);
837
+ if (openEnd === -1) break;
838
+ let closeIdx = lower.indexOf(closeNeedle, openEnd + 1);
839
+ while (closeIdx !== -1) {
840
+ const afterClose = lower[closeIdx + closeNeedle.length];
841
+ if (afterClose === '>' || (afterClose !== undefined && /\s/.test(afterClose))) {
842
+ break;
843
+ }
844
+ closeIdx = lower.indexOf(closeNeedle, closeIdx + closeNeedle.length);
845
+ }
846
+ if (closeIdx === -1) {
847
+ out += ' ';
848
+ break;
849
+ }
850
+ const closeEnd = text.indexOf('>', closeIdx + closeNeedle.length);
851
+ out += ' ';
852
+ if (closeEnd === -1) break;
853
+ pos = closeEnd + 1;
854
+ }
855
+ text = out;
856
+ }
857
+ return text;
858
+ }
859
+
860
+ export function stripMarkupTags(input, replacement = '') {
861
+ const text = String(input || '');
862
+ let out = '';
863
+ let pos = 0;
864
+ while (pos < text.length) {
865
+ const start = text.indexOf('<', pos);
866
+ if (start === -1) {
867
+ out += text.slice(pos);
868
+ break;
869
+ }
870
+ const end = text.indexOf('>', start + 1);
871
+ if (end === -1) {
872
+ out += text.slice(pos);
873
+ break;
874
+ }
875
+ out += text.slice(pos, start);
876
+ if (replacement) out += replacement;
877
+ pos = end + 1;
878
+ }
879
+ return out;
880
+ }
881
+
882
+ export function extractDocxText(rawBuf, limits = {}) {
883
+ const maxInputBytes = limits.maxInputBytes ?? DOCX_LIMITS.MAX_INPUT_BYTES;
884
+ const maxTotalEntries = limits.maxTotalEntries ?? DOCX_LIMITS.MAX_TOTAL_ENTRIES;
885
+ const maxXmlEntries = limits.maxXmlEntries ?? DOCX_LIMITS.MAX_XML_ENTRIES;
886
+ const maxCompressedEntryBytes = limits.maxCompressedEntryBytes ?? DOCX_LIMITS.MAX_COMPRESSED_ENTRY_BYTES;
887
+ const maxEntryUncompressedBytes = limits.maxEntryUncompressedBytes ?? DOCX_LIMITS.MAX_ENTRY_UNCOMPRESSED_BYTES;
888
+ const maxTotalUncompressedBytes = limits.maxTotalUncompressedBytes ?? DOCX_LIMITS.MAX_TOTAL_UNCOMPRESSED_BYTES;
889
+
890
+ if (!Buffer.isBuffer(rawBuf)) {
891
+ throw new Error('Invalid .docx file (not a genuine OOXML ZIP archive). Do not rename HTML/text files to .docx.');
892
+ }
893
+ if (rawBuf.length > maxInputBytes) {
894
+ throw new Error(`Oversized .docx file (${rawBuf.length} bytes exceeds ${maxInputBytes} byte limit).`);
895
+ }
896
+ if (rawBuf.length < 22 || rawBuf.subarray(0, 4).toString('latin1') !== 'PK\x03\x04') {
897
+ throw new Error('Invalid .docx file (not a genuine OOXML ZIP archive). Do not rename HTML/text files to .docx.');
898
+ }
899
+
900
+ let eocdOffset = -1;
901
+ const minOffset = Math.max(0, rawBuf.length - 65557);
902
+ for (let i = rawBuf.length - 22; i >= minOffset; i--) {
903
+ if (rawBuf.readUInt32LE(i) === 0x06054b50) {
904
+ const commentLen = rawBuf.readUInt16LE(i + 20);
905
+ if (i + 22 + commentLen === rawBuf.length) {
906
+ eocdOffset = i;
907
+ break;
908
+ }
909
+ }
910
+ }
911
+ if (eocdOffset < 0) {
912
+ // Fallback scan if trailing comment length was non-strict in a synthetic archive, still verifying bounds
913
+ for (let i = rawBuf.length - 22; i >= minOffset; i--) {
914
+ if (rawBuf.readUInt32LE(i) === 0x06054b50) {
915
+ eocdOffset = i;
916
+ break;
917
+ }
918
+ }
919
+ }
920
+ if (eocdOffset < 0) {
921
+ throw new Error('Corrupted .docx archive (missing ZIP central directory).');
922
+ }
923
+
924
+ const diskEntries = rawBuf.readUInt16LE(eocdOffset + 8);
925
+ const entryCount = rawBuf.readUInt16LE(eocdOffset + 10);
926
+ const cdSize = rawBuf.readUInt32LE(eocdOffset + 12);
927
+ let cdOffset = rawBuf.readUInt32LE(eocdOffset + 16);
928
+
929
+ if (diskEntries !== entryCount) {
930
+ throw new Error('Corrupted or multi-disk .docx ZIP archive (central directory entry count mismatch).');
931
+ }
932
+ if (entryCount > maxTotalEntries) {
933
+ throw new Error(`Excessive .docx ZIP entry count (${entryCount} exceeds limit of ${maxTotalEntries}).`);
934
+ }
935
+ if (cdOffset > eocdOffset || cdOffset + cdSize > eocdOffset) {
936
+ throw new Error('Corrupted .docx central directory bounds.');
937
+ }
938
+
939
+ const cdStartOffset = cdOffset;
940
+ const cdEndOffset = cdOffset + cdSize;
941
+ const xmlParts = [];
942
+ const seenNames = new Set();
943
+ const occupiedLocalRanges = [];
944
+ let totalUncompressedBytes = 0;
945
+
946
+ for (let idx = 0; idx < entryCount; idx++) {
947
+ if (cdOffset + 46 > cdEndOffset || cdOffset + 46 > rawBuf.length || rawBuf.readUInt32LE(cdOffset) !== 0x02014b50) {
948
+ throw new Error('Corrupted .docx central directory entry.');
949
+ }
950
+ const flags = rawBuf.readUInt16LE(cdOffset + 8);
951
+ const method = rawBuf.readUInt16LE(cdOffset + 10);
952
+ const compSize = rawBuf.readUInt32LE(cdOffset + 20);
953
+ const uncompSize = rawBuf.readUInt32LE(cdOffset + 24);
954
+ const nameLen = rawBuf.readUInt16LE(cdOffset + 28);
955
+ const extraLen = rawBuf.readUInt16LE(cdOffset + 30);
956
+ const commentLen = rawBuf.readUInt16LE(cdOffset + 32);
957
+ const localHeaderOffset = rawBuf.readUInt32LE(cdOffset + 42);
958
+ const nextCdOffset = cdOffset + 46 + nameLen + extraLen + commentLen;
959
+ if (nextCdOffset > cdEndOffset || nextCdOffset > rawBuf.length) {
960
+ throw new Error('Corrupted .docx central directory entry bounds.');
961
+ }
962
+ const fileName = rawBuf.subarray(cdOffset + 46, cdOffset + 46 + nameLen).toString('utf8');
963
+ cdOffset = nextCdOffset;
964
+
965
+ if (!fileName || fileName.includes('\x00')) {
966
+ throw new Error('Corrupted .docx central directory filename.');
967
+ }
968
+ const normName = fileName.replace(/\\/g, '/').toLowerCase();
969
+ if (seenNames.has(normName)) {
970
+ throw new Error(`Duplicate .docx ZIP entry "${fileName}" rejected.`);
971
+ }
972
+ seenNames.add(normName);
973
+
974
+ if (compSize === 0xffffffff || uncompSize === 0xffffffff || localHeaderOffset === 0xffffffff) {
975
+ throw new Error('ZIP64 .docx archives are not supported.');
976
+ }
977
+
978
+ if (localHeaderOffset + 30 > cdStartOffset || localHeaderOffset + 30 > rawBuf.length || rawBuf.readUInt32LE(localHeaderOffset) !== 0x04034b50) {
979
+ throw new Error('Corrupted .docx local file header.');
980
+ }
981
+ const lhNameLen = rawBuf.readUInt16LE(localHeaderOffset + 26);
982
+ const lhExtraLen = rawBuf.readUInt16LE(localHeaderOffset + 28);
983
+ const dataStart = localHeaderOffset + 30 + lhNameLen + lhExtraLen;
984
+ const dataEnd = dataStart + compSize;
985
+ if (dataStart > rawBuf.length || dataEnd > rawBuf.length || dataEnd > cdStartOffset) {
986
+ throw new Error('Truncated or out-of-bounds .docx entry data.');
987
+ }
988
+
989
+ // Reject duplicate or overlapping local entry ranges (anti-bomb shared-payload defense)
990
+ for (const prev of occupiedLocalRanges) {
991
+ if (localHeaderOffset < prev.end && dataEnd > prev.start) {
992
+ throw new Error('Corrupted .docx archive: overlapping or shared local file header/data offsets detected.');
993
+ }
994
+ }
995
+ occupiedLocalRanges.push({ start: localHeaderOffset, end: Math.max(dataEnd, localHeaderOffset + 30) });
996
+
997
+ if (!/^word\/(?:document|header\d*|footer\d*)\.xml$/i.test(normName)) continue;
998
+
999
+ if (xmlParts.length >= maxXmlEntries) {
1000
+ throw new Error(`Excessive .docx XML document/header/footer parts (exceeds limit of ${maxXmlEntries}).`);
1001
+ }
1002
+ if (flags & 1) {
1003
+ throw new Error('Encrypted .docx file is not supported; save an unencrypted .docx or export .md/.txt.');
1004
+ }
1005
+ if (compSize > maxCompressedEntryBytes) {
1006
+ throw new Error(`Oversized compressed .docx entry "${fileName}" (${compSize} bytes exceeds ${maxCompressedEntryBytes} byte limit).`);
1007
+ }
1008
+ if (uncompSize > maxEntryUncompressedBytes) {
1009
+ throw new Error(`Oversized uncompressed .docx entry "${fileName}" (${uncompSize} bytes exceeds ${maxEntryUncompressedBytes} byte limit).`);
1010
+ }
1011
+ if (totalUncompressedBytes + uncompSize > maxTotalUncompressedBytes) {
1012
+ throw new Error(`Cumulative .docx uncompressed size exceeds ${maxTotalUncompressedBytes} byte limit.`);
1013
+ }
1014
+
1015
+ const compressed = rawBuf.subarray(dataStart, dataEnd);
1016
+ const remainingBudget = maxTotalUncompressedBytes - totalUncompressedBytes;
1017
+ const entryBudget = Math.min(maxEntryUncompressedBytes, remainingBudget);
1018
+
1019
+ let xmlBuf;
1020
+ if (method === 0) {
1021
+ if (compSize !== uncompSize) {
1022
+ throw new Error(`Corrupted .docx stored entry "${fileName}" (compressed size ${compSize} != uncompressed size ${uncompSize}).`);
1023
+ }
1024
+ if (compressed.length > entryBudget) {
1025
+ throw new Error(`Oversized .docx entry "${fileName}" exceeds decompression budget (${entryBudget} bytes).`);
1026
+ }
1027
+ xmlBuf = compressed;
1028
+ } else if (method === 8) {
1029
+ if (compSize === 0) {
1030
+ throw new Error(`Corrupted .docx deflate entry "${fileName}" (0 compressed bytes).`);
1031
+ }
1032
+ const inflateCap = Math.max(1, entryBudget);
1033
+ try {
1034
+ xmlBuf = zlib.inflateRawSync(compressed, { maxOutputLength: inflateCap });
1035
+ } catch (err) {
1036
+ if (err && (err.code === 'ERR_BUFFER_TOO_LARGE' || /maxOutputLength|Cannot create a Buffer larger than/i.test(String(err.message)))) {
1037
+ throw new Error(`Decompression limit exceeded for .docx entry "${fileName}" (max ${entryBudget} bytes).`);
1038
+ }
1039
+ throw new Error(`Corrupted deflate stream in .docx entry "${fileName}": ${err.message}`);
1040
+ }
1041
+ if (xmlBuf.length > entryBudget) {
1042
+ throw new Error(`Decompression limit exceeded for .docx entry "${fileName}" (max ${entryBudget} bytes).`);
1043
+ }
1044
+ if (xmlBuf.length !== uncompSize) {
1045
+ throw new Error(`Corrupted .docx entry "${fileName}" (declared uncompressed size ${uncompSize} != actual ${xmlBuf.length}).`);
1046
+ }
1047
+ } else {
1048
+ throw new Error(`Unsupported .docx compression method (${method}); export .md or .txt instead.`);
1049
+ }
1050
+
1051
+ totalUncompressedBytes += xmlBuf.length;
1052
+ if (totalUncompressedBytes > maxTotalUncompressedBytes) {
1053
+ throw new Error(`Cumulative .docx uncompressed size exceeds ${maxTotalUncompressedBytes} byte limit.`);
1054
+ }
1055
+
1056
+ xmlParts.push({ name: normName, xml: xmlBuf.toString('utf8') });
1057
+ }
1058
+
1059
+ if (cdOffset !== cdEndOffset) {
1060
+ throw new Error('Corrupted .docx central directory (size mismatch).');
1061
+ }
1062
+
1063
+ const hasMainDoc = xmlParts.some(p => p.name === 'word/document.xml');
1064
+ if (!hasMainDoc) {
1065
+ throw new Error('Invalid .docx package (missing word/document.xml). Do not rename HTML/text files to .docx.');
1066
+ }
1067
+ const combined = xmlParts
1068
+ .sort((a, b) => (a.name === 'word/document.xml' ? -1 : b.name === 'word/document.xml' ? 1 : a.name.localeCompare(b.name)))
1069
+ .map(p =>
1070
+ decodeXmlHtmlEntities(
1071
+ stripMarkupTags(
1072
+ p.xml
1073
+ .replace(/<\/w:p>/gi, '\n')
1074
+ .replace(/<\/w:tr>/gi, '\n')
1075
+ .replace(/<w:br\b[^>]*\/>/gi, '\n')
1076
+ .replace(/<w:tab\b[^>]*\/>/gi, ' '),
1077
+ '',
1078
+ ),
1079
+ ),
1080
+ )
1081
+ .join('\n')
1082
+ .split(/\r?\n/)
1083
+ .map(l => l.replace(/[ \t]+/g, ' ').trim())
1084
+ .filter(Boolean)
1085
+ .join('\n');
1086
+
1087
+ if (!combined.trim()) {
1088
+ throw new Error('No readable text found inside .docx (possibly image-only content); paste your CV text or provide .md/.txt.');
1089
+ }
1090
+ return combined;
1091
+ }