vidspotai-shared 1.0.146 → 1.0.148

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 (67) hide show
  1. package/lib/globals/plans.d.ts +17 -0
  2. package/lib/globals/plans.d.ts.map +1 -1
  3. package/lib/globals/plans.js +11 -1
  4. package/lib/globals/types.d.ts +2 -1
  5. package/lib/globals/types.d.ts.map +1 -1
  6. package/lib/globals/types.js +5 -0
  7. package/lib/models/agent.model.d.ts +6 -0
  8. package/lib/models/agent.model.d.ts.map +1 -1
  9. package/lib/models/demoVideoProject.model.d.ts +6 -0
  10. package/lib/models/demoVideoProject.model.d.ts.map +1 -1
  11. package/lib/models/image.model.d.ts +6 -0
  12. package/lib/models/image.model.d.ts.map +1 -1
  13. package/lib/models/musicJob.model.d.ts +6 -0
  14. package/lib/models/musicJob.model.d.ts.map +1 -1
  15. package/lib/models/upscale.model.d.ts +6 -0
  16. package/lib/models/upscale.model.d.ts.map +1 -1
  17. package/lib/models/user.model.d.ts +68 -1
  18. package/lib/models/user.model.d.ts.map +1 -1
  19. package/lib/models/video.model.d.ts +43 -0
  20. package/lib/models/video.model.d.ts.map +1 -1
  21. package/lib/models/videoTool.model.d.ts +6 -0
  22. package/lib/models/videoTool.model.d.ts.map +1 -1
  23. package/lib/services/accountStatus/index.d.ts +35 -0
  24. package/lib/services/accountStatus/index.d.ts.map +1 -1
  25. package/lib/services/accountStatus/index.js +54 -0
  26. package/lib/services/agent/repair/engine.d.ts.map +1 -1
  27. package/lib/services/agent/repair/engine.js +18 -0
  28. package/lib/services/agent/repair/strategies/llmRepair.strategy.d.ts.map +1 -1
  29. package/lib/services/agent/repair/strategies/llmRepair.strategy.js +20 -8
  30. package/lib/services/bullmq.service.d.ts +18 -1
  31. package/lib/services/bullmq.service.d.ts.map +1 -1
  32. package/lib/services/bullmq.service.js +13 -0
  33. package/lib/services/credit.service.d.ts +61 -1
  34. package/lib/services/credit.service.d.ts.map +1 -1
  35. package/lib/services/credit.service.js +124 -52
  36. package/lib/services/credits/grant.d.ts +105 -0
  37. package/lib/services/credits/grant.d.ts.map +1 -0
  38. package/lib/services/credits/grant.js +129 -0
  39. package/lib/services/demo/demoPrefill.d.ts.map +1 -1
  40. package/lib/services/demo/demoPrefill.js +101 -84
  41. package/lib/services/index.d.ts +1 -0
  42. package/lib/services/index.d.ts.map +1 -1
  43. package/lib/services/index.js +1 -0
  44. package/lib/services/moderation/generationModeration.service.d.ts +52 -0
  45. package/lib/services/moderation/generationModeration.service.d.ts.map +1 -0
  46. package/lib/services/moderation/generationModeration.service.js +260 -0
  47. package/lib/services/moderation/index.d.ts +4 -0
  48. package/lib/services/moderation/index.d.ts.map +1 -1
  49. package/lib/services/moderation/index.js +14 -1
  50. package/lib/services/moderation/moderationStrike.service.d.ts +67 -0
  51. package/lib/services/moderation/moderationStrike.service.d.ts.map +1 -0
  52. package/lib/services/moderation/moderationStrike.service.js +134 -0
  53. package/lib/services/rateLimiter/index.d.ts +1 -0
  54. package/lib/services/rateLimiter/index.d.ts.map +1 -1
  55. package/lib/services/rateLimiter/index.js +1 -0
  56. package/lib/services/rateLimiter/userRateLimiter.service.d.ts +55 -0
  57. package/lib/services/rateLimiter/userRateLimiter.service.d.ts.map +1 -0
  58. package/lib/services/rateLimiter/userRateLimiter.service.js +220 -0
  59. package/lib/services/trialGuard/trialSignals.d.ts.map +1 -1
  60. package/lib/services/trialGuard/trialSignals.js +15 -0
  61. package/lib/utils/index.d.ts +1 -0
  62. package/lib/utils/index.d.ts.map +1 -1
  63. package/lib/utils/index.js +1 -0
  64. package/lib/utils/ssrfGuard.d.ts +59 -0
  65. package/lib/utils/ssrfGuard.d.ts.map +1 -0
  66. package/lib/utils/ssrfGuard.js +253 -0
  67. package/package.json +1 -1
@@ -0,0 +1,220 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.consumeRateLimit = consumeRateLimit;
4
+ exports.consumeQuota = consumeQuota;
5
+ const logger_1 = require("../../utils/logger");
6
+ const bullmq_service_1 = require("../bullmq.service");
7
+ const REDIS_TIMEOUT_MS = 300;
8
+ const KEY_PREFIX = "apirl:";
9
+ /**
10
+ * Atomic check-then-increment across N windows. KEYS = one per window,
11
+ * ARGV = [max_1, ttl_1, max_2, ttl_2, ...]. Returns {1,0,-1} when consumed or
12
+ * {0, ttlSec, windowIdx} for the first exhausted window (nothing incremented).
13
+ */
14
+ const CONSUME_SCRIPT = `
15
+ for i = 1, #KEYS do
16
+ local max = tonumber(ARGV[(i - 1) * 2 + 1])
17
+ local cur = tonumber(redis.call('GET', KEYS[i]) or '0')
18
+ if cur >= max then
19
+ local ttl = redis.call('TTL', KEYS[i])
20
+ if ttl < 0 then ttl = tonumber(ARGV[(i - 1) * 2 + 2]) end
21
+ return { 0, ttl, i - 1 }
22
+ end
23
+ end
24
+ for i = 1, #KEYS do
25
+ local n = redis.call('INCR', KEYS[i])
26
+ if n == 1 then
27
+ redis.call('EXPIRE', KEYS[i], tonumber(ARGV[(i - 1) * 2 + 2]))
28
+ end
29
+ end
30
+ return { 1, 0, -1 }
31
+ `;
32
+ // ── In-memory fallback ─────────────────────────────────────────────────────
33
+ const memory = new Map();
34
+ const MEMORY_MAX_KEYS = 20000;
35
+ function consumeMemory(keys, windows, nowMs) {
36
+ if (memory.size > MEMORY_MAX_KEYS) {
37
+ for (const [k, v] of memory)
38
+ if (v.resetAt <= nowMs)
39
+ memory.delete(k);
40
+ if (memory.size > MEMORY_MAX_KEYS)
41
+ memory.clear();
42
+ }
43
+ for (let i = 0; i < keys.length; i++) {
44
+ const entry = memory.get(keys[i]);
45
+ const w = windows[i];
46
+ if (entry && entry.resetAt > nowMs && entry.count >= w.max) {
47
+ return {
48
+ allowed: false,
49
+ retryAfterSec: Math.max(1, Math.ceil((entry.resetAt - nowMs) / 1000)),
50
+ exceeded: w,
51
+ backend: "memory",
52
+ };
53
+ }
54
+ }
55
+ for (let i = 0; i < keys.length; i++) {
56
+ const k = keys[i];
57
+ const w = windows[i];
58
+ const entry = memory.get(k);
59
+ if (!entry || entry.resetAt <= nowMs) {
60
+ memory.set(k, { count: 1, resetAt: windowEndMs(w, nowMs) });
61
+ }
62
+ else {
63
+ entry.count++;
64
+ }
65
+ }
66
+ return { allowed: true, retryAfterSec: 0, backend: "memory" };
67
+ }
68
+ function windowEndMs(w, nowMs) {
69
+ const lenMs = w.windowSec * 1000;
70
+ return (Math.floor(nowMs / lenMs) + 1) * lenMs;
71
+ }
72
+ function windowKey(bucket, subject, w, nowMs) {
73
+ const idx = Math.floor(nowMs / (w.windowSec * 1000));
74
+ return `${KEY_PREFIX}${bucket}:${subject}:${w.windowSec}:${idx}`;
75
+ }
76
+ let lastRedisWarnAt = 0;
77
+ /**
78
+ * Consume one request for `subject` (uid or `ip:<addr>`) in `bucket`
79
+ * (logical endpoint group) against every window. Never throws.
80
+ */
81
+ async function consumeRateLimit(bucket, subject, windows) {
82
+ const active = windows.filter((w) => w.max > 0 && w.windowSec > 0);
83
+ if (!active.length)
84
+ return { allowed: true, retryAfterSec: 0, backend: "memory" };
85
+ const nowMs = Date.now();
86
+ const keys = active.map((w) => windowKey(bucket, subject, w, nowMs));
87
+ let conn;
88
+ try {
89
+ conn = bullmq_service_1.bullmq.getSharedRedisConnection();
90
+ }
91
+ catch {
92
+ conn = undefined;
93
+ }
94
+ if (conn) {
95
+ const args = [];
96
+ for (const w of active)
97
+ args.push(String(w.max), String(w.windowSec + 5));
98
+ try {
99
+ const raw = (await Promise.race([
100
+ conn.eval(CONSUME_SCRIPT, keys.length, ...keys, ...args),
101
+ new Promise((_, reject) => setTimeout(() => reject(new Error("rate limiter redis timeout")), REDIS_TIMEOUT_MS)),
102
+ ]));
103
+ const [ok, ttl, idx] = raw;
104
+ if (ok === 1)
105
+ return { allowed: true, retryAfterSec: 0, backend: "redis" };
106
+ return {
107
+ allowed: false,
108
+ retryAfterSec: Math.max(1, Number(ttl) || 1),
109
+ exceeded: active[Number(idx)] ?? active[0],
110
+ backend: "redis",
111
+ };
112
+ }
113
+ catch (err) {
114
+ const now = Date.now();
115
+ if (now - lastRedisWarnAt > 60000) {
116
+ lastRedisWarnAt = now;
117
+ logger_1.logger.warn("userRateLimiter: Redis unavailable — falling back to in-memory", {
118
+ err: err instanceof Error ? err.message : String(err),
119
+ });
120
+ }
121
+ }
122
+ }
123
+ return consumeMemory(keys, active, nowMs);
124
+ }
125
+ /**
126
+ * KEYS = one per meter, ARGV = [cost_1, max_1, ..., ttl]. Rejects (and
127
+ * increments nothing) if ANY meter would exceed its max; else INCRBY all.
128
+ */
129
+ const QUOTA_SCRIPT = `
130
+ local ttl = tonumber(ARGV[#ARGV])
131
+ for i = 1, #KEYS do
132
+ local cost = tonumber(ARGV[(i - 1) * 2 + 1])
133
+ local max = tonumber(ARGV[(i - 1) * 2 + 2])
134
+ local cur = tonumber(redis.call('GET', KEYS[i]) or '0')
135
+ if cur + cost > max then
136
+ local t = redis.call('TTL', KEYS[i])
137
+ if t < 0 then t = ttl end
138
+ return { 0, t, i - 1 }
139
+ end
140
+ end
141
+ for i = 1, #KEYS do
142
+ local n = redis.call('INCRBY', KEYS[i], tonumber(ARGV[(i - 1) * 2 + 1]))
143
+ if n == tonumber(ARGV[(i - 1) * 2 + 1]) then
144
+ redis.call('EXPIRE', KEYS[i], ttl)
145
+ end
146
+ end
147
+ return { 1, 0, -1 }
148
+ `;
149
+ /**
150
+ * Consume `cost` from each meter of a fixed window (2026-11-25, upload quota).
151
+ * Same Redis/in-memory fail-open behaviour as consumeRateLimit. Never throws.
152
+ */
153
+ async function consumeQuota(bucket, subject, windowSec, meters) {
154
+ const active = meters.filter((m) => m.max > 0 && m.cost >= 0);
155
+ if (!active.length || windowSec <= 0)
156
+ return { allowed: true, retryAfterSec: 0, backend: "memory" };
157
+ const nowMs = Date.now();
158
+ const idx = Math.floor(nowMs / (windowSec * 1000));
159
+ const keys = active.map((m) => `${KEY_PREFIX}q:${bucket}:${subject}:${m.name}:${windowSec}:${idx}`);
160
+ let conn;
161
+ try {
162
+ conn = bullmq_service_1.bullmq.getSharedRedisConnection();
163
+ }
164
+ catch {
165
+ conn = undefined;
166
+ }
167
+ if (conn) {
168
+ const args = [];
169
+ for (const m of active)
170
+ args.push(String(Math.ceil(m.cost)), String(m.max));
171
+ args.push(String(windowSec + 5));
172
+ try {
173
+ const raw = (await Promise.race([
174
+ conn.eval(QUOTA_SCRIPT, keys.length, ...keys, ...args),
175
+ new Promise((_, reject) => setTimeout(() => reject(new Error("quota redis timeout")), REDIS_TIMEOUT_MS)),
176
+ ]));
177
+ const [ok, ttl, i] = raw;
178
+ if (ok === 1)
179
+ return { allowed: true, retryAfterSec: 0, backend: "redis" };
180
+ return {
181
+ allowed: false,
182
+ retryAfterSec: Math.max(1, Number(ttl) || 1),
183
+ exceeded: active[Number(i)] ?? active[0],
184
+ backend: "redis",
185
+ };
186
+ }
187
+ catch (err) {
188
+ const now = Date.now();
189
+ if (now - lastRedisWarnAt > 60000) {
190
+ lastRedisWarnAt = now;
191
+ logger_1.logger.warn("userRateLimiter: Redis unavailable for quota — falling back to in-memory", {
192
+ err: err instanceof Error ? err.message : String(err),
193
+ });
194
+ }
195
+ }
196
+ }
197
+ // In-memory fallback (per instance).
198
+ const resetAt = (idx + 1) * windowSec * 1000;
199
+ for (let i = 0; i < keys.length; i++) {
200
+ const entry = memory.get(keys[i]);
201
+ const cur = entry && entry.resetAt > nowMs ? entry.count : 0;
202
+ if (cur + active[i].cost > active[i].max) {
203
+ return {
204
+ allowed: false,
205
+ retryAfterSec: Math.max(1, Math.ceil((resetAt - nowMs) / 1000)),
206
+ exceeded: active[i],
207
+ backend: "memory",
208
+ };
209
+ }
210
+ }
211
+ for (let i = 0; i < keys.length; i++) {
212
+ const k = keys[i];
213
+ const entry = memory.get(k);
214
+ if (!entry || entry.resetAt <= nowMs)
215
+ memory.set(k, { count: active[i].cost, resetAt });
216
+ else
217
+ entry.count += active[i].cost;
218
+ }
219
+ return { allowed: true, retryAfterSec: 0,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C,MAAM,GAAG,SAAS,CAIpB;AAKD,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAE/D;AAED,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAElE;AAOD,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,cAAc,CAAC;IACrB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,wBAAgB,SAAS,CAAC,OAAO,EAAE,YAAY,GAAG,QAAQ,EAAE,CAY3D;AASD;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE;IAClC,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,YAAY,CAAC;IACtB,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,aAAa,GAAG,SAAS,CAAC,CAAC;IACjD,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,GAAG,aAAa,CAyBhB;AAED,6EAA6E;AAC7E,wBAAgB,SAAS,CACvB,GAAG,EAAE,aAAa,GAAG,SAAS,EAC9B,IAAI,EAAE,cAAc,EACpB,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,GACV,aAAa,CASf"}
@@ -21,6 +21,15 @@ exports.TRIAL_CLAIM_EVENTS_CAP = 20;
21
21
  // auto-generated per lab session (seen abusing trials 2026-10-05).
22
22
  const EXTRA_BLOCKED_DOMAINS = ["qwiklabs.net"];
23
23
  const GMAIL_DOMAINS = new Set(["gmail.com", "googlemail.com"]);
24
+ // 2026-11-25: Microsoft consumer mail. outlook.com / hotmail.com / live.com
25
+ // (+ country variants and msn.com) are all front-ends of one consumer
26
+ // account system, and a person can hold the same local part on several of
27
+ // them as aliases of ONE mailbox. Folding them into one key costs at worst a
28
+ // rare false positive (two different people owning name@hotmail and
29
+ // name@outlook) — acceptable for a free-trial guard, which then just shows a
30
+ // normal paid Checkout. Dots are NOT folded: Microsoft treats them as
31
+ // significant. `+tag` folding already applies to every domain (below).
32
+ const MICROSOFT_CONSUMER_DOMAIN_RE = /^(outlook|hotmail|live|msn|windowslive|passport)\.[a-z.]{2,}$/;
24
33
  function normalizeEmail(raw) {
25
34
  const email = raw.trim().toLowerCase();
26
35
  const at = email.lastIndexOf("@");
@@ -28,11 +37,17 @@ function normalizeEmail(raw) {
28
37
  return undefined;
29
38
  let local = email.slice(0, at);
30
39
  let domain = email.slice(at + 1);
40
+ // +tag sub-addressing is folded for EVERY domain (Gmail, Outlook, Fastmail,
41
+ // iCloud, Proton, most self-hosted servers).
31
42
  local = local.split("+")[0] ?? "";
32
43
  if (GMAIL_DOMAINS.has(domain)) {
44
+ // googlemail.com → gmail.com, dots ignored by Gmail.
33
45
  local = local.replace(/\./g, "");
34
46
  domain = "gmail.com";
35
47
  }
48
+ else if (MICROSOFT_CONSUMER_DOMAIN_RE.test(domain)) {
49
+ domain = "outlook.com";
50
+ }
36
51
  return local ? `${local}@${domain}` : undefined;
37
52
  }
38
53
  function blockedDomains() {
@@ -7,4 +7,5 @@ export * from "./renderTier";
7
7
  export * from "./socialEntitlements";
8
8
  export * from "./ttsUtils";
9
9
  export * from "./outreachTemplate";
10
+ export * from "./ssrfGuard";
10
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC;AACnC,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,eAAe,CAAC;AAC9B,cAAc,UAAU,CAAC;AACzB,cAAc,cAAc,CAAC;AAC7B,cAAc,sBAAsB,CAAC;AACrC,cAAc,YAAY,CAAC;AAC3B,cAAc,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC;AACnC,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,eAAe,CAAC;AAC9B,cAAc,UAAU,CAAC;AACzB,cAAc,cAAc,CAAC;AAC7B,cAAc,sBAAsB,CAAC;AACrC,cAAc,YAAY,CAAC;AAC3B,cAAc,oBAAoB,CAAC;AACnC,cAAc,aAAa,CAAC"}
@@ -23,3 +23,4 @@ __exportStar(require("./renderTier"), exports);
23
23
  __exportStar(require("./socialEntitlements"), exports);
24
24
  __exportStar(require("./ttsUtils"), exports);
25
25
  __exportStar(require("./outreachTemplate"), exports);
26
+ __exportStar(require("./ssrfGuard"), exports);
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Reusable SSRF guard (extracted 2026-11-25 from services/demo/demoPrefill.ts).
3
+ *
4
+ * WHY (2026-11-25): several worker/API surfaces fetch or browse to a URL a
5
+ * user typed — the demo website capture/record (headless Chrome), the
6
+ * browser-session remote control, video-tool input downloads and outreach
7
+ * webhook delivery. Those run inside Railway / GCP where 169.254.169.254
8
+ * (metadata), *.railway.internal (Redis, internal services) and loopback are
9
+ * one hop away. Every such surface must call `assertPublicUrl` on the initial
10
+ * URL AND on every redirect / subresource it lets through, because DNS can
11
+ * change between the check and the request.
12
+ */
13
+ export type SsrfBlockReason = "invalid_url" | "blocked_protocol" | "blocked_host" | "unresolvable";
14
+ export declare class SsrfBlockedError extends Error {
15
+ readonly reason: SsrfBlockReason;
16
+ constructor(reason: SsrfBlockReason, message: string);
17
+ }
18
+ /**
19
+ * True for any address we must never connect to on a user's behalf: loopback,
20
+ * RFC1918, link-local (incl. cloud metadata 169.254.169.254), CGNAT (Railway's
21
+ * private network lives in 100.64/10 + fd00::/8), multicast/reserved, ULA,
22
+ * and IPv4-mapped/NAT64 forms of all of those. Non-IP input ⇒ true (unsafe).
23
+ */
24
+ export declare function isPrivateAddress(ip: string): boolean;
25
+ /** Hostnames that are internal by name — rejected before any DNS lookup. */
26
+ export declare function isBlockedHostname(hostname: string): boolean;
27
+ export interface AssertPublicUrlOptions {
28
+ /** Allowed URL protocols. Default http: + https:. */
29
+ protocols?: ReadonlyArray<string>;
30
+ }
31
+ /**
32
+ * Validate that a URL is a public http(s) target: parseable, allowed
33
+ * protocol, no credentials-in-URL tricks on internal names, not an internal
34
+ * hostname, and EVERY address it resolves to is public. Throws
35
+ * SsrfBlockedError otherwise; returns the parsed URL on success.
36
+ *
37
+ * Note: this is a check-then-connect guard (a DNS-rebinding window exists
38
+ * between the lookup and the caller's own connect). Callers that follow
39
+ * redirects or load subresources must re-run it per hop/request.
40
+ */
41
+ export declare function assertPublicUrl(raw: string, opts?: AssertPublicUrlOptions): Promise<URL>;
42
+ /** Boolean form of assertPublicUrl — never throws. */
43
+ export declare function isPublicUrl(raw: string, opts?: AssertPublicUrlOptions): Promise<boolean>;
44
+ /**
45
+ * Synchronous pre-check usable without DNS (e.g. inside a browser request
46
+ * interceptor before the async check, or in a zod refine): false when the URL
47
+ * is unparseable, a non-http(s) scheme, an internal hostname, or a private IP
48
+ * literal. Public-looking hostnames return true — pair with assertPublicUrl
49
+ * for the DNS half.
50
+ */
51
+ export declare function isSyntacticallyPublicUrl(raw: string, opts?: AssertPublicUrlOptions): boolean;
52
+ /**
53
+ * Per-host DNS verdict cache for request interception in headless browsers,
54
+ * where a page can issue hundreds of subresource requests to the same few
55
+ * hosts. TTL is short so a rebinding host can't ride a stale "public" verdict
56
+ * for long.
57
+ */
58
+ export declare function createHostVerdictCache(ttlMs?: number): (rawUrl: string) => Promise<boolean>;
59
+ //# sourceMappingURL=ssrfGuard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssrfGuard.d.ts","sourceRoot":"","sources":["../../src/utils/ssrfGuard.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;GAWG;AAEH,MAAM,MAAM,eAAe,GAAG,aAAa,GAAG,kBAAkB,GAAG,cAAc,GAAG,cAAc,CAAC;AAEnG,qBAAa,gBAAiB,SAAQ,KAAK;aAEvB,MAAM,EAAE,eAAe;gBAAvB,MAAM,EAAE,eAAe,EACvC,OAAO,EAAE,MAAM;CAKlB;AAoCD;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CA0CpD;AAED,4EAA4E;AAC5E,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAY3D;AAED,MAAM,WAAW,sBAAsB;IACrC,qDAAqD;IACrD,SAAS,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;CACnC;AAED;;;;;;;;;GASG;AACH,wBAAsB,eAAe,CACnC,GAAG,EAAE,MAAM,EACX,IAAI,GAAE,sBAA2B,GAChC,OAAO,CAAC,GAAG,CAAC,CA+Bd;AAED,sDAAsD;AACtD,wBAAsB,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,sBAAsB,GAAG,OAAO,CAAC,OAAO,CAAC,CAO9F;AAED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,GAAE,sBAA2B,GAAG,OAAO,CAahG;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,SAAS,GAAG,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CA0B3F"}
@@ -0,0 +1,253 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SsrfBlockedError = void 0;
4
+ exports.isPrivateAddress = isPrivateAddress;
5
+ exports.isBlockedHostname = isBlockedHostname;
6
+ exports.assertPublicUrl = assertPublicUrl;
7
+ exports.isPublicUrl = isPublicUrl;
8
+ exports.isSyntacticallyPublicUrl = isSyntacticallyPublicUrl;
9
+ exports.createHostVerdictCache = createHostVerdictCache;
10
+ const promises_1 = require("dns/promises");
11
+ const net_1 = require("net");
12
+ class SsrfBlockedError extends Error {
13
+ constructor(reason, message) {
14
+ super(message);
15
+ this.reason = reason;
16
+ this.name = "SsrfBlockedError";
17
+ }
18
+ }
19
+ exports.SsrfBlockedError = SsrfBlockedError;
20
+ /** Parse a dotted-quad into its 4 octets, or null. */
21
+ function parseIpv4(ip) {
22
+ const p = ip.split(".").map(Number);
23
+ if (p.length !== 4 || p.some((n) => Number.isNaN(n) || n < 0 || n > 255))
24
+ return null;
25
+ return p;
26
+ }
27
+ /** Expand an IPv6 literal into 8 16-bit groups (handles `::` and a trailing v4). */
28
+ function expandIpv6(ip) {
29
+ let s = ip.toLowerCase();
30
+ const pct = s.indexOf("%");
31
+ if (pct >= 0)
32
+ s = s.slice(0, pct); // drop zone id
33
+ // Trailing embedded IPv4 (::ffff:1.2.3.4) → two hex groups.
34
+ const v4 = s.match(/(\d+\.\d+\.\d+\.\d+)$/);
35
+ if (v4?.[1]) {
36
+ const o = parseIpv4(v4[1]);
37
+ if (!o)
38
+ return null;
39
+ const hi = ((o[0] << 8) | o[1]).toString(16);
40
+ const lo = ((o[2] << 8) | o[3]).toString(16);
41
+ s = s.slice(0, s.length - v4[1].length) + `${hi}:${lo}`;
42
+ }
43
+ const halves = s.split("::");
44
+ if (halves.length > 2)
45
+ return null;
46
+ const head = halves[0] ? halves[0].split(":") : [];
47
+ const tail = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
48
+ const missing = 8 - head.length - tail.length;
49
+ if (halves.length === 1 && missing !== 0)
50
+ return null;
51
+ if (missing < 0)
52
+ return null;
53
+ const groups = [...head, ...Array(halves.length === 2 ? missing : 0).fill("0"), ...tail];
54
+ const nums = groups.map((g) => parseInt(g, 16));
55
+ if (nums.length !== 8 || nums.some((n) => Number.isNaN(n) || n < 0 || n > 0xffff))
56
+ return null;
57
+ return nums;
58
+ }
59
+ /**
60
+ * True for any address we must never connect to on a user's behalf: loopback,
61
+ * RFC1918, link-local (incl. cloud metadata 169.254.169.254), CGNAT (Railway's
62
+ * private network lives in 100.64/10 + fd00::/8), multicast/reserved, ULA,
63
+ * and IPv4-mapped/NAT64 forms of all of those. Non-IP input ⇒ true (unsafe).
64
+ */
65
+ function isPrivateAddress(ip) {
66
+ const v = (0, net_1.isIP)(ip);
67
+ if (v === 4) {
68
+ const p = parseIpv4(ip);
69
+ if (!p)
70
+ return true;
71
+ const a = p[0];
72
+ const b = p[1];
73
+ if (a === 10)
74
+ return true; // 10.0.0.0/8
75
+ if (a === 127)
76
+ return true; // loopback
77
+ if (a === 0)
78
+ return true; // "this" network
79
+ if (a === 169 && b === 254)
80
+ return true; // link-local incl. 169.254.169.254
81
+ if (a === 172 && b >= 16 && b <= 31)
82
+ return true; // 172.16.0.0/12
83
+ if (a === 192 && b === 168)
84
+ return true; // 192.168.0.0/16
85
+ if (a === 192 && b === 0 && p[2] === 0)
86
+ return true; // 192.0.0.0/24 IETF
87
+ if (a === 100 && b >= 64 && b <= 127)
88
+ return true; // CGNAT 100.64.0.0/10
89
+ if (a === 198 && (b === 18 || b === 19))
90
+ return true; // benchmarking
91
+ if (a >= 224)
92
+ return true; // multicast / reserved / broadcast
93
+ return false;
94
+ }
95
+ if (v === 6) {
96
+ const g = expandIpv6(ip);
97
+ if (!g)
98
+ return true;
99
+ if (g.every((n) => n === 0))
100
+ return true; // ::
101
+ if (g.slice(0, 7).every((n) => n === 0) && g[7] === 1)
102
+ return true; // ::1
103
+ const first = g[0];
104
+ if ((first & 0xfe00) === 0xfc00)
105
+ return true; // ULA fc00::/7
106
+ if ((first & 0xffc0) === 0xfe80)
107
+ return true; // link-local fe80::/10
108
+ if ((first & 0xffc0) === 0xfec0)
109
+ return true; // site-local (deprecated)
110
+ if ((first & 0xff00) === 0xff00)
111
+ return true; // multicast
112
+ const toV4 = (hi, lo) => `${hi >> 8}.${hi & 0xff}.${lo >> 8}.${lo & 0xff}`;
113
+ // IPv4-mapped ::ffff:a.b.c.d and IPv4-compatible ::a.b.c.d
114
+ if (g.slice(0, 5).every((n) => n === 0) && (g[5] === 0xffff || g[5] === 0)) {
115
+ return isPrivateAddress(toV4(g[6], g[7]));
116
+ }
117
+ // NAT64 64:ff9b::/96
118
+ if (first === 0x64 && g[1] === 0xff9b && g.slice(2, 6).every((n) => n === 0)) {
119
+ return isPrivateAddress(toV4(g[6], g[7]));
120
+ }
121
+ return false;
122
+ }
123
+ return true; // not an IP literal ⇒ treat as unsafe
124
+ }
125
+ /** Hostnames that are internal by name — rejected before any DNS lookup. */
126
+ function isBlockedHostname(hostname) {
127
+ const h = hostname.replace(/^\[|\]$/g, "").replace(/\.$/, "").toLowerCase();
128
+ if (!h)
129
+ return true;
130
+ return (h === "localhost" ||
131
+ h.endsWith(".localhost") ||
132
+ h.endsWith(".local") ||
133
+ h.endsWith(".internal") || // *.railway.internal, metadata.google.internal
134
+ h.endsWith(".localdomain") ||
135
+ h === "metadata" ||
136
+ h === "metadata.google.internal");
137
+ }
138
+ /**
139
+ * Validate that a URL is a public http(s) target: parseable, allowed
140
+ * protocol, no credentials-in-URL tricks on internal names, not an internal
141
+ * hostname, and EVERY address it resolves to is public. Throws
142
+ * SsrfBlockedError otherwise; returns the parsed URL on success.
143
+ *
144
+ * Note: this is a check-then-connect guard (a DNS-rebinding window exists
145
+ * between the lookup and the caller's own connect). Callers that follow
146
+ * redirects or load subresources must re-run it per hop/request.
147
+ */
148
+ async function assertPublicUrl(raw, opts = {}) {
149
+ const protocols = opts.protocols ?? ["http:", "https:"];
150
+ let url;
151
+ try {
152
+ url = new URL(raw);
153
+ }
154
+ catch {
155
+ throw new SsrfBlockedError("invalid_url", "That doesn't look like a valid URL.");
156
+ }
157
+ if (!protocols.includes(url.protocol)) {
158
+ throw new SsrfBlockedError("blocked_protocol", "That URL scheme isn't supported.");
159
+ }
160
+ const host = url.hostname.replace(/^\[|\]$/g, "");
161
+ if (isBlockedHostname(host)) {
162
+ throw new SsrfBlockedError("blocked_host", "That host isn't reachable.");
163
+ }
164
+ if ((0, net_1.isIP)(host)) {
165
+ if (isPrivateAddress(host)) {
166
+ throw new SsrfBlockedError("blocked_host", "That host isn't reachable.");
167
+ }
168
+ return url;
169
+ }
170
+ let addresses;
171
+ try {
172
+ addresses = await (0, promises_1.lookup)(host, { all: true });
173
+ }
174
+ catch {
175
+ throw new SsrfBlockedError("unresolvable", "We couldn't reach that site.");
176
+ }
177
+ if (addresses.length === 0 || addresses.some((a) => isPrivateAddress(a.address))) {
178
+ throw new SsrfBlockedError("blocked_host", "That host isn't reachable.");
179
+ }
180
+ return url;
181
+ }
182
+ /** Boolean form of assertPublicUrl — never throws. */
183
+ async function isPublicUrl(raw, opts) {
184
+ try {
185
+ await assertPublicUrl(raw, opts);
186
+ return true;
187
+ }
188
+ catch {
189
+ return false;
190
+ }
191
+ }
192
+ /**
193
+ * Synchronous pre-check usable without DNS (e.g. inside a browser request
194
+ * interceptor before the async check, or in a zod refine): false when the URL
195
+ * is unparseable, a non-http(s) scheme, an internal hostname, or a private IP
196
+ * literal. Public-looking hostnames return true — pair with assertPublicUrl
197
+ * for the DNS half.
198
+ */
199
+ function isSyntacticallyPublicUrl(raw, opts = {}) {
200
+ const protocols = opts.protocols ?? ["http:", "https:"];
201
+ let url;
202
+ try {
203
+ url = new URL(raw);
204
+ }
205
+ catch {
206
+ return false;
207
+ }
208
+ if (!protocols.includes(url.protocol))
209
+ return false;
210
+ const host = url.hostname.replace(/^\[|\]$/g, "");
211
+ if (isBlockedHostname(host))
212
+ return false;
213
+ if ((0, net_1.isIP)(host) && isPrivateAddress(host))
214
+ return false;
215
+ return true;
216
+ }
217
+ /**
218
+ * Per-host DNS verdict cache for request interception in headless browsers,
219
+ * where a page can issue hundreds of subresource requests to the same few
220
+ * hosts. TTL is short so a rebinding host can't ride a stale "public" verdict
221
+ * for long.
222
+ */
223
+ function createHostVerdictCache(ttlMs = 30000) {
224
+ const cache = new Map();
225
+ return async (rawUrl) => {
226
+ let url;
227
+ try {
228
+ url = new URL(rawUrl);
229
+ }
230
+ catch {
231
+ return false;
232
+ }
233
+ // Non-network schemes a page legitimately uses for inline content.
234
+ if (url.protocol === "data:" || url.protocol === "blob:" || url.protocol === "about:") {
235
+ return true;
236
+ }
237
+ if (url.protocol !== "http:" && url.protocol !== "https:" && url.protocol !== "ws:" && url.protocol !== "wss:") {
238
+ return false;
239
+ }
240
+ const key = url.hostname.toLowerCase();
241
+ const hit = cache.get(key);
242
+ if (hit && Date.now() - hit.at < ttlMs)
243
+ return hit.ok;
244
+ const probe = new URL(rawUrl);
245
+ if (probe.protocol === "ws:")
246
+ probe.protocol = "http:";
247
+ if (probe.protocol === "wss:")
248
+ probe.protocol = "https:";
249
+ const ok = await isPublicUrl(probe.toString());
250
+ cache.set(key, { ok, at: Date.now() });
251
+ return ok;
252
+ };
253
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vidspotai-shared",
3
- "version": "1.0.146",
3
+ "version": "1.0.148",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "exports": {