vidspotai-shared 1.0.147 → 1.0.149

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 (81) 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 +6 -2
  5. package/lib/globals/types.d.ts.map +1 -1
  6. package/lib/globals/types.js +11 -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/social.model.d.ts +7 -2
  16. package/lib/models/social.model.d.ts.map +1 -1
  17. package/lib/models/upscale.model.d.ts +6 -0
  18. package/lib/models/upscale.model.d.ts.map +1 -1
  19. package/lib/models/user.model.d.ts +68 -1
  20. package/lib/models/user.model.d.ts.map +1 -1
  21. package/lib/models/video.model.d.ts +43 -0
  22. package/lib/models/video.model.d.ts.map +1 -1
  23. package/lib/models/videoTool.model.d.ts +6 -0
  24. package/lib/models/videoTool.model.d.ts.map +1 -1
  25. package/lib/schemas/social.schema.d.ts +9 -0
  26. package/lib/schemas/social.schema.d.ts.map +1 -1
  27. package/lib/schemas/social.schema.js +6 -1
  28. package/lib/services/accountStatus/index.d.ts +35 -0
  29. package/lib/services/accountStatus/index.d.ts.map +1 -1
  30. package/lib/services/accountStatus/index.js +54 -0
  31. package/lib/services/agent/repair/engine.d.ts.map +1 -1
  32. package/lib/services/agent/repair/engine.js +18 -0
  33. package/lib/services/agent/repair/strategies/llmRepair.strategy.d.ts.map +1 -1
  34. package/lib/services/agent/repair/strategies/llmRepair.strategy.js +20 -8
  35. package/lib/services/bullmq.service.d.ts +18 -1
  36. package/lib/services/bullmq.service.d.ts.map +1 -1
  37. package/lib/services/bullmq.service.js +13 -0
  38. package/lib/services/credit.service.d.ts +61 -1
  39. package/lib/services/credit.service.d.ts.map +1 -1
  40. package/lib/services/credit.service.js +124 -52
  41. package/lib/services/credits/grant.d.ts +105 -0
  42. package/lib/services/credits/grant.d.ts.map +1 -0
  43. package/lib/services/credits/grant.js +129 -0
  44. package/lib/services/demo/demoPrefill.d.ts.map +1 -1
  45. package/lib/services/demo/demoPrefill.js +101 -84
  46. package/lib/services/index.d.ts +1 -0
  47. package/lib/services/index.d.ts.map +1 -1
  48. package/lib/services/index.js +1 -0
  49. package/lib/services/moderation/generationModeration.service.d.ts +52 -0
  50. package/lib/services/moderation/generationModeration.service.d.ts.map +1 -0
  51. package/lib/services/moderation/generationModeration.service.js +260 -0
  52. package/lib/services/moderation/index.d.ts +4 -0
  53. package/lib/services/moderation/index.d.ts.map +1 -1
  54. package/lib/services/moderation/index.js +14 -1
  55. package/lib/services/moderation/moderationStrike.service.d.ts +67 -0
  56. package/lib/services/moderation/moderationStrike.service.d.ts.map +1 -0
  57. package/lib/services/moderation/moderationStrike.service.js +134 -0
  58. package/lib/services/rateLimiter/index.d.ts +1 -0
  59. package/lib/services/rateLimiter/index.d.ts.map +1 -1
  60. package/lib/services/rateLimiter/index.js +1 -0
  61. package/lib/services/rateLimiter/userRateLimiter.service.d.ts +55 -0
  62. package/lib/services/rateLimiter/userRateLimiter.service.d.ts.map +1 -0
  63. package/lib/services/rateLimiter/userRateLimiter.service.js +220 -0
  64. package/lib/services/socialOAuth/youtube.oauth.d.ts +1 -1
  65. package/lib/services/socialOAuth/youtube.oauth.d.ts.map +1 -1
  66. package/lib/services/socialOAuth/youtube.oauth.js +15 -7
  67. package/lib/services/socialPublish/types.d.ts +31 -0
  68. package/lib/services/socialPublish/types.d.ts.map +1 -1
  69. package/lib/services/socialPublish/types.js +17 -0
  70. package/lib/services/socialPublish/youtube.publish.d.ts +12 -1
  71. package/lib/services/socialPublish/youtube.publish.d.ts.map +1 -1
  72. package/lib/services/socialPublish/youtube.publish.js +95 -0
  73. package/lib/services/trialGuard/trialSignals.d.ts.map +1 -1
  74. package/lib/services/trialGuard/trialSignals.js +15 -0
  75. package/lib/utils/index.d.ts +1 -0
  76. package/lib/utils/index.d.ts.map +1 -1
  77. package/lib/utils/index.js +1 -0
  78. package/lib/utils/ssrfGuard.d.ts +59 -0
  79. package/lib/utils/ssrfGuard.d.ts.map +1 -0
  80. package/lib/utils/ssrfGuard.js +253 -0
  81. 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, backend: "memory" };
220
+ }
@@ -4,7 +4,7 @@ export declare class YouTubeOAuthProvider implements ISocialOAuthProvider {
4
4
  readonly provider = ESocialProvider.YOUTUBE;
5
5
  private clientId;
6
6
  private clientSecret;
7
- getAuthUrl({ state, redirectUri, requestBusinessScopes, }: AuthUrlParams): string;
7
+ getAuthUrl({ state, redirectUri }: AuthUrlParams): string;
8
8
  exchangeCode({ code, redirectUri, }: ExchangeCodeParams): Promise<ConnectResult>;
9
9
  refresh(refreshToken: string): Promise<OAuthTokens>;
10
10
  revoke(token: string): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"youtube.oauth.d.ts","sourceRoot":"","sources":["../../../src/services/socialOAuth/youtube.oauth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAE1E,OAAO,EACL,aAAa,EACb,aAAa,EACb,kBAAkB,EAClB,oBAAoB,EACpB,WAAW,EACZ,MAAM,SAAS,CAAC;AAoDjB,qBAAa,oBAAqB,YAAW,oBAAoB;IAC/D,QAAQ,CAAC,QAAQ,2BAA2B;IAE5C,OAAO,CAAC,QAAQ;IAMhB,OAAO,CAAC,YAAY;IAOpB,UAAU,CAAC,EACT,KAAK,EACL,WAAW,EACX,qBAAqB,GACtB,EAAE,aAAa,GAAG,MAAM;IAiBnB,YAAY,CAAC,EACjB,IAAI,EACJ,WAAW,GACZ,EAAE,kBAAkB,GAAG,OAAO,CAAC,aAAa,CAAC;IAiBxC,OAAO,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IAiBnD,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;YAc5B,SAAS;IAmBvB,OAAO,CAAC,QAAQ;YAUF,cAAc;CAwB7B"}
1
+ {"version":3,"file":"youtube.oauth.d.ts","sourceRoot":"","sources":["../../../src/services/socialOAuth/youtube.oauth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAE1E,OAAO,EACL,aAAa,EACb,aAAa,EACb,kBAAkB,EAClB,oBAAoB,EACpB,WAAW,EACZ,MAAM,SAAS,CAAC;AA4DjB,qBAAa,oBAAqB,YAAW,oBAAoB;IAC/D,QAAQ,CAAC,QAAQ,2BAA2B;IAE5C,OAAO,CAAC,QAAQ;IAMhB,OAAO,CAAC,YAAY;IAOpB,UAAU,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE,aAAa,GAAG,MAAM;IAoBnD,YAAY,CAAC,EACjB,IAAI,EACJ,WAAW,GACZ,EAAE,kBAAkB,GAAG,OAAO,CAAC,aAAa,CAAC;IAiBxC,OAAO,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IAiBnD,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;YAc5B,SAAS;IAmBvB,OAAO,CAAC,QAAQ;YAUF,cAAc;CAwB7B"}
@@ -21,14 +21,19 @@ const AUTH_ENDPOINT = "https://accounts.google.com/o/oauth2/v2/auth";
21
21
  const TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token";
22
22
  const REVOKE_ENDPOINT = "https://oauth2.googleapis.com/revoke";
23
23
  const CHANNELS_ENDPOINT = "https://www.googleapis.com/youtube/v3/channels?part=snippet&mine=true";
24
- /** Scopes needed to upload + read analytics + manage comments. */
24
+ /**
25
+ * Scopes every connection gets: upload, read analytics, and manage the videos
26
+ * we published. `youtube.force-ssl` is in the base set (since 2026-11-28)
27
+ * because `videos.delete` / `videos.update` — "Delete from YouTube" and
28
+ * "Change visibility" on the Posts tab — are rejected with the upload scope
29
+ * alone. It also covers comment list/insert/moderate (premium engage).
30
+ */
25
31
  const BASE_SCOPES = [
26
32
  "https://www.googleapis.com/auth/youtube.upload",
27
33
  "https://www.googleapis.com/auth/youtube.readonly",
28
34
  "https://www.googleapis.com/auth/yt-analytics.readonly",
35
+ "https://www.googleapis.com/auth/youtube.force-ssl",
29
36
  ];
30
- /** force-ssl is required for comment list/insert/moderate (premium engage). */
31
- const COMMENT_SCOPES = ["https://www.googleapis.com/auth/youtube.force-ssl"];
32
37
  class YouTubeOAuthProvider {
33
38
  constructor() {
34
39
  this.provider = types_1.ESocialProvider.YOUTUBE;
@@ -45,10 +50,13 @@ class YouTubeOAuthProvider {
45
50
  throw new Error("YouTubeOAuth: GOOGLE_OAUTH_CLIENT_SECRET not set");
46
51
  return secret;
47
52
  }
48
- getAuthUrl({ state, redirectUri, requestBusinessScopes, }) {
49
- const scopes = requestBusinessScopes
50
- ? [...BASE_SCOPES, ...COMMENT_SCOPES]
51
- : BASE_SCOPES;
53
+ getAuthUrl({ state, redirectUri }) {
54
+ // REMOVED 2026-11-28: business connections no longer add scopes on top —
55
+ // every YouTube connection requests the same set (see BASE_SCOPES).
56
+ // const scopes = requestBusinessScopes
57
+ // ? [...BASE_SCOPES, ...COMMENT_SCOPES]
58
+ // : BASE_SCOPES;
59
+ const scopes = BASE_SCOPES;
52
60
  const params = new URLSearchParams({
53
61
  client_id: this.clientId(),
54
62
  redirect_uri: redirectUri,
@@ -41,7 +41,38 @@ export interface PublishResult {
41
41
  publishedUrl?: string;
42
42
  }
43
43
  export interface ISocialPublisher {
44
+ /**
45
+ * Remove a published post from the platform. Optional — only implemented
46
+ * where the platform API allows it. Must be idempotent: an already-gone post
47
+ * resolves (not throws) so a retried delete converges.
48
+ */
49
+ deletePost?(input: ManagePostInput): Promise<void>;
50
+ /** Change a published post's visibility. Optional, as above. */
51
+ updatePrivacy?(input: UpdatePrivacyInput): Promise<void>;
44
52
  readonly provider: ESocialProvider;
45
53
  publish(input: PublishInput): Promise<PublishResult>;
46
54
  }
55
+ /** Visibility values the cross-platform UI offers (YouTube's native set). */
56
+ export declare const SOCIAL_VISIBILITIES: readonly ["public", "unlisted", "private"];
57
+ export type SocialVisibility = (typeof SOCIAL_VISIBILITIES)[number];
58
+ /** Addresses one already-published post on a platform. */
59
+ export interface ManagePostInput {
60
+ /** Cleartext access token (from getValidAccessToken — never persisted here). */
61
+ accessToken: string;
62
+ /** Provider's post id (YT video id / IG media id / …). */
63
+ providerPostId: string;
64
+ }
65
+ export interface UpdatePrivacyInput extends ManagePostInput {
66
+ privacy: SocialVisibility;
67
+ }
68
+ /**
69
+ * Thrown by post-management calls when the stored grant lacks the scope the
70
+ * action needs (e.g. a YouTube channel connected before `youtube.force-ssl`
71
+ * was requested). The API maps this to SOCIAL_RECONNECT_REQUIRED so the UI can
72
+ * send the user back through the connect flow instead of showing a raw 403.
73
+ */
74
+ export declare class SocialScopeError extends Error {
75
+ readonly provider: string;
76
+ constructor(provider: string, message: string);
77
+ }
47
78
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/services/socialPublish/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;;;GAKG;AAEH,MAAM,WAAW,YAAY;IAC3B,yEAAyE;IACzE,WAAW,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,MAAM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Q,CAAC,EAAE,MAAM,EAAE,CAAC;CACrB;AAED,MAAM,WAAW,aAAa;IAC5B,sCAAsC;IACtC,cAAc,EAAE,MAAM,CAAC;IACvB,kEAAkE;IAClE,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,gBAAgB;IAC/B;;;;OAIG;IACH,UAAU,CAAC,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACnD,gEAAgE;IAChE,aAAa,CAAC,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACzD,QAAQ,CAAC,QAAQ,EAAE,eAAe,CAAC;IACnC,OAAO,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;CACtD;AAED,6EAA6E;AAC7E,eAAO,MAAM,mBAAmB,4CAA6C,CAAC;AAC9E,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,mBAAmB,CAAC,CAAC,MAAM,CAAC,CAAC;AAEpE,0DAA0D;AAC1D,MAAM,WAAW,eAAe;IAC9B,gFAAgF;IAChF,WAAW,EAAE,MAAM,CAAC;IACpB,0DAA0D;IAC1D,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,kBAAmB,SAAQ,eAAe;IACzD,OAAO,EAAE,gBAAgB,CAAC;CAC3B;AAED;;;;;GAKG;AACH,qBAAa,gBAAiB,SAAQ,KAAK;IAEvC,QAAQ,CAAC,QAAQ,EAAE,MAAM;gBAAhB,QAAQ,EAAE,MAAM,EACzB,OAAO,EAAE,MAAM;CAKlB"}
@@ -1,2 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SocialScopeError = exports.SOCIAL_VISIBILITIES = void 0;
4
+ /** Visibility values the cross-platform UI offers (YouTube's native set). */
5
+ exports.SOCIAL_VISIBILITIES = ["public", "unlisted", "private"];
6
+ /**
7
+ * Thrown by post-management calls when the stored grant lacks the scope the
8
+ * action needs (e.g. a YouTube channel connected before `youtube.force-ssl`
9
+ * was requested). The API maps this to SOCIAL_RECONNECT_REQUIRED so the UI can
10
+ * send the user back through the connect flow instead of showing a raw 403.
11
+ */
12
+ class SocialScopeError extends Error {
13
+ constructor(provider, message) {
14
+ super(message);
15
+ this.provider = provider;
16
+ this.name = "SocialScopeError";
17
+ }
18
+ }
19
+ exports.SocialScopeError = SocialScopeError;
@@ -1,8 +1,19 @@
1
1
  import { ESocialProvider } from "../../globals/types";
2
- import { ISocialPublisher, PublishInput, PublishResult } from "./types";
2
+ import { ISocialPublisher, ManagePostInput, PublishInput, PublishResult, UpdatePrivacyInput } from "./types";
3
3
  export declare class YouTubePublisher implements ISocialPublisher {
4
4
  readonly provider = ESocialProvider.YOUTUBE;
5
5
  publish(input: PublishInput): Promise<PublishResult>;
6
+ /**
7
+ * `videos.delete`. Needs the `youtube.force-ssl` (or `youtube`) scope — the
8
+ * upload scope alone cannot delete. A 404 means it is already gone → success.
9
+ */
10
+ deletePost(input: ManagePostInput): Promise<void>;
11
+ /**
12
+ * `videos.update` (part=status). Update REPLACES the whole part, so read the
13
+ * current status first and write it back with only privacyStatus changed —
14
+ * otherwise made-for-kids / embeddable / license silently reset.
15
+ */
16
+ updatePrivacy(input: UpdatePrivacyInput): Promise<void>;
6
17
  private resolvePrivacy;
7
18
  private buildDescription;
8
19
  }
@@ -1 +1 @@
1
- {"version":3,"file":"youtube.publish.d.ts","sourceRoot":"","sources":["../../../src/services/socialPublish/youtube.publish.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AA0BxE,qBAAa,gBAAiB,YAAW,gBAAgB;IACvD,QAAQ,CAAC,QAAQ,2BAA2B;IAEtC,OAAO,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,aAAa,CAAC;IA+E1D,OAAO,CAAC,cAAc;IAOtB,OAAO,CAAC,gBAAgB;CAUzB"}
1
+ {"version":3,"file":"youtube.publish.d.ts","sourceRoot":"","sources":["../../../src/services/socialPublish/youtube.publish.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,YAAY,EACZ,aAAa,EAEb,kBAAkB,EACnB,MAAM,SAAS,CAAC;AA+EjB,qBAAa,gBAAiB,YAAW,gBAAgB;IACvD,QAAQ,CAAC,QAAQ,2BAA2B;IAEtC,OAAO,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,aAAa,CAAC;IA+E1D;;;OAGG;IACG,UAAU,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IA2BvD;;;;OAIG;IACG,aAAa,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;IA4D7D,OAAO,CAAC,cAAc;IAOtB,OAAO,CAAC,gBAAgB;CAUzB"}
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.YouTubePublisher = void 0;
4
4
  const types_1 = require("../../globals/types");
5
5
  const logger_1 = require("../../utils/logger");
6
+ const types_2 = require("./types");
6
7
  /**
7
8
  * YouTube publisher — uploads a video via the Data API `videos.insert` resumable
8
9
  * endpoint and sets visibility / native scheduling. Phase 1. See SOCIAL_SUITE_PLAN.md.
@@ -19,6 +20,28 @@ const logger_1 = require("../../utils/logger");
19
20
  * short-form; switch to chunked upload if we publish very large long-form files.
20
21
  */
21
22
  const RESUMABLE_INIT = "https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status";
23
+ const VIDEOS_API = "https://www.googleapis.com/youtube/v3/videos";
24
+ /** Reasons Google returns when the token is valid but lacks the needed scope. */
25
+ const SCOPE_REASONS = new Set([
26
+ "insufficientPermissions",
27
+ "ACCESS_TOKEN_SCOPE_INSUFFICIENT",
28
+ ]);
29
+ function isScopeError(status, error) {
30
+ if (status !== 403 || !error)
31
+ return false;
32
+ const reasons = [...(error.errors ?? []), ...(error.details ?? [])].map((e) => e.reason ?? "");
33
+ return (reasons.some((r) => SCOPE_REASONS.has(r)) ||
34
+ /insufficient (authentication )?(scopes|permission)/i.test(error.message ?? ""));
35
+ }
36
+ async function readApiError(resp) {
37
+ try {
38
+ const body = (await resp.json());
39
+ return body.error ?? {};
40
+ }
41
+ catch {
42
+ return {};
43
+ }
44
+ }
22
45
  class YouTubePublisher {
23
46
  constructor() {
24
47
  this.provider = types_1.ESocialProvider.YOUTUBE;
@@ -87,6 +110,78 @@ class YouTubePublisher {
87
110
  publishedUrl: `https://www.youtube.com/watch?v=${result.id}`,
88
111
  };
89
112
  }
113
+ /**
114
+ * `videos.delete`. Needs the `youtube.force-ssl` (or `youtube`) scope — the
115
+ * upload scope alone cannot delete. A 404 means it is already gone → success.
116
+ */
117
+ async deletePost(input) {
118
+ const resp = await fetch(`${VIDEOS_API}?id=${encodeURIComponent(input.providerPostId)}`, {
119
+ method: "DELETE",
120
+ headers: { Authorization: `Bearer ${input.accessToken}` },
121
+ });
122
+ if (resp.ok || resp.status === 404) {
123
+ logger_1.logger.info("YouTubePublisher: deleted", {
124
+ videoId: input.providerPostId,
125
+ alreadyGone: resp.status === 404,
126
+ });
127
+ return;
128
+ }
129
+ const error = await readApiError(resp);
130
+ if (isScopeError(resp.status, error)) {
131
+ throw new types_2.SocialScopeError(this.provider, "YouTube connection lacks permission to delete videos");
132
+ }
133
+ throw new Error(`YouTubePublisher: delete failed ${resp.status} ${error.message ?? ""}`);
134
+ }
135
+ /**
136
+ * `videos.update` (part=status). Update REPLACES the whole part, so read the
137
+ * current status first and write it back with only privacyStatus changed —
138
+ * otherwise made-for-kids / embeddable / license silently reset.
139
+ */
140
+ async updatePrivacy(input) {
141
+ const headers = { Authorization: `Bearer ${input.accessToken}` };
142
+ const id = encodeURIComponent(input.providerPostId);
143
+ const listResp = await fetch(`${VIDEOS_API}?part=status&id=${id}`, {
144
+ headers,
145
+ });
146
+ const list = (await listResp.json());
147
+ if (!listResp.ok) {
148
+ throw new Error(`YouTubePublisher: status read failed ${listResp.status} ${list.error?.message ?? ""}`);
149
+ }
150
+ const current = list.items?.[0]?.status;
151
+ if (!current) {
152
+ throw new Error("YouTubePublisher: video not found on YouTube");
153
+ }
154
+ const status = {
155
+ privacyStatus: input.privacy,
156
+ embeddable: current.embeddable,
157
+ license: current.license,
158
+ publicStatsViewable: current.publicStatsViewable,
159
+ selfDeclaredMadeForKids: current.selfDeclaredMadeForKids,
160
+ containsSyntheticMedia: current.containsSyntheticMedia,
161
+ // publishAt is only valid while private (a pending scheduled release);
162
+ // keep it then, drop it when the user makes the video visible now.
163
+ ...(input.privacy === "private" && current.publishAt
164
+ ? { publishAt: current.publishAt }
165
+ : {}),
166
+ };
167
+ const resp = await fetch(`${VIDEOS_API}?part=status`, {
168
+ method: "PUT",
169
+ headers: { ...headers, "Content-Type": "application/json" },
170
+ body: JSON.stringify({ id: input.providerPostId, status }),
171
+ });
172
+ if (resp.ok) {
173
+ logger_1.logger.info("YouTubePublisher: visibility updated", {
174
+ videoId: input.providerPostId,
175
+ privacy: input.privacy,
176
+ });
177
+ return;
178
+ }
179
+ const error = await readApiError(resp);
180
+ if (isScopeError(resp.status, error)) {
181
+ throw new types_2.SocialScopeError(this.provider, "YouTube connection lacks permission to change video visibility");
182
+ }
183
+ throw new Error(`YouTubePublisher: visibility update failed ${resp.status} ${error.message ?? ""}`);
184
+ }
90
185
  resolvePrivacy(input) {
91
186
  // Native scheduling requires private until publishAt fires.
92
187
  if (input.scheduledAt)
@@ -1 +1 @@
1
- {"version":3,"file":"trialSignals.d.ts","sourceRoot":"","sources":["../../../src/services/trialGuard/trialSignals.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,MAAM,MAAM,cAAc,GAAG,QAAQ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,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"}