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
@@ -1,6 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.isUserAccountDeleted = isUserAccountDeleted;
4
+ exports.isUserDocBlocked = isUserDocBlocked;
5
+ exports.isUserBlocked = isUserBlocked;
6
+ exports.getAccountUnusableReason = getAccountUnusableReason;
7
+ exports.isUserAccountUsable = isUserAccountUsable;
4
8
  const firestore_service_1 = require("../firestore.service");
5
9
  /**
6
10
  * True when the user deleted their account (see IUserModel.deletedAt). Used
@@ -15,3 +19,53 @@ async function isUserAccountDeleted(uid) {
15
19
  const user = await firestore_service_1.FirestoreService.getUserById(uid);
16
20
  return !user || Boolean(user.deletedAt);
17
21
  }
22
+ /**
23
+ * Pure check on an already-loaded user doc. Keyed off `blockedAt` ALONE
24
+ * (2026-11-25): the moderation strike code writes blockedAt/blockedReason
25
+ * directly on the user doc, without going through the admin endpoint, so no
26
+ * other flag (Auth `disabled`, a status enum) may be required for the block to
27
+ * take effect. Any truthy value — Timestamp, epoch number, serverTimestamp
28
+ * sentinel — counts.
29
+ */
30
+ function isUserDocBlocked(user) {
31
+ if (!user)
32
+ return false;
33
+ const v = user.blockedAt;
34
+ return v !== undefined && v !== null && v !== false && v !== 0;
35
+ }
36
+ /**
37
+ * True when the account is blocked. Accepts a loaded user doc (no read) or a
38
+ * uid (one Firestore read). A missing user doc is NOT "blocked" — pair with
39
+ * isUserAccountDeleted / isUserAccountUsable for that.
40
+ */
41
+ async function isUserBlocked(userOrUid) {
42
+ if (!userOrUid)
43
+ return false;
44
+ if (typeof userOrUid !== "string")
45
+ return isUserDocBlocked(userOrUid);
46
+ const user = await firestore_service_1.FirestoreService.getUserById(userOrUid);
47
+ return isUserDocBlocked(user);
48
+ }
49
+ /**
50
+ * Single read that answers "may this uid act / be served?" — not deleted (doc
51
+ * exists, no deletedAt) and not blocked. Returns the reason when unusable so
52
+ * callers can surface the right code.
53
+ */
54
+ async function getAccountUnusableReason(uid, opts = {}) {
55
+ if (!uid)
56
+ return null;
57
+ const user = await firestore_service_1.FirestoreService.getUserById(uid);
58
+ if (!user)
59
+ return opts.missingIsDeleted === false ? null : "account_deleted";
60
+ if (user.deletedAt)
61
+ return "account_deleted";
62
+ if (isUserDocBlocked(user))
63
+ return "account_blocked";
64
+ return null;
65
+ }
66
+ /** True when the account is neither deleted (incl. missing doc) nor blocked. */
67
+ async function isUserAccountUsable(uid) {
68
+ if (!uid)
69
+ return false;
70
+ return (await getAccountUnusableReason(uid)) === null;
71
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../../../src/services/agent/repair/engine.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE3D,OAAO,EAEL,aAAa,EAEb,cAAc,EACd,cAAc,EACd,mBAAmB,EACnB,oBAAoB,EACrB,MAAM,SAAS,CAAC;AAEjB;;;;;;;;;;;;;GAaG;AACH,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAmB;gBAElC,UAAU,EAAE,cAAc,EAAE;IAKxC,6EAA6E;IAC7E,IAAI,aAAa,IAAI,MAAM,EAAE,CAE5B;IAED;;;;OAIG;IACG,QAAQ,CAAC,EAAE,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC;IA2BjE;;;;;;;OAOG;IACG,aAAa,CAAC,CAAC,GAAG,OAAO,EAC7B,OAAO,EAAE,mBAAmB,EAC5B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC9B,GAAG,EAAE,WAAW,EAChB,IAAI,GAAE,oBAAyB,GAC9B,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;CAyF3B"}
1
+ {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../../../src/services/agent/repair/engine.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE3D,OAAO,EAEL,aAAa,EAEb,cAAc,EACd,cAAc,EACd,mBAAmB,EACnB,oBAAoB,EACrB,MAAM,SAAS,CAAC;AAEjB;;;;;;;;;;;;;GAaG;AACH,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAmB;gBAElC,UAAU,EAAE,cAAc,EAAE;IAKxC,6EAA6E;IAC7E,IAAI,aAAa,IAAI,MAAM,EAAE,CAE5B;IAED;;;;OAIG;IACG,QAAQ,CAAC,EAAE,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC;IA2BjE;;;;;;;OAOG;IACG,aAAa,CAAC,CAAC,GAAG,OAAO,EAC7B,OAAO,EAAE,mBAAmB,EAC5B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC9B,GAAG,EAAE,WAAW,EAChB,IAAI,GAAE,oBAAyB,GAC9B,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;CA2G3B"}
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RepairEngine = void 0;
4
4
  const logger_1 = require("../../../utils/logger");
5
+ const moderationStrike_service_1 = require("../../moderation/moderationStrike.service");
5
6
  const providerTaskCache_1 = require("../providerTaskCache");
6
7
  /**
7
8
  * RepairEngine — the generic, reactive, escalating retry brain.
@@ -86,6 +87,23 @@ class RepairEngine {
86
87
  log("repair_skip", { reason: "auth_class_terminal", toolName });
87
88
  break;
88
89
  }
90
+ // 2026-11-25: a content-moderation / safety block is terminal for the
91
+ // TOOL-level loop — rewording a blocked prompt until a provider accepts
92
+ // it is exactly the evasion the 2026-11 abuser relied on. The plan-level
93
+ // degrade ladder (stock-only for `safety`) or a scene failure takes over,
94
+ // and a sexual/NSFW-type rejection counts as a moderation strike.
95
+ if (failure.classification === "safety") {
96
+ log("repair_skip", { reason: "safety_class_terminal", toolName });
97
+ if (ctx.userId && (0, moderationStrike_service_1.isStrikeableProviderRejection)(failure.message)) {
98
+ await (0, moderationStrike_service_1.recordModerationStrike)(ctx.userId, "provider", {
99
+ surface: `agent.${toolName}`,
100
+ categories: [failure.code],
101
+ reason: failure.message.slice(0, 300),
102
+ jobId: ctx.agentRunId,
103
+ });
104
+ }
105
+ break;
106
+ }
89
107
  const rc = {
90
108
  toolName,
91
109
  input: currentInput,
@@ -1 +1 @@
1
- {"version":3,"file":"llmRepair.strategy.d.ts","sourceRoot":"","sources":["../../../../../src/services/agent/repair/strategies/llmRepair.strategy.ts"],"names":[],"mappings":"AAOA,OAAO,EAAiC,cAAc,EAAE,MAAM,UAAU,CAAC;AAyOzE,2EAA2E;AAC3E,eAAO,MAAM,uBAAuB,gBAAsC,CAAC;AAC3E,gEAAgE;AAChE,eAAO,MAAM,qBAAqB,gBAAoC,CAAC"}
1
+ {"version":3,"file":"llmRepair.strategy.d.ts","sourceRoot":"","sources":["../../../../../src/services/agent/repair/strategies/llmRepair.strategy.ts"],"names":[],"mappings":"AAOA,OAAO,EAAiC,cAAc,EAAE,MAAM,UAAU,CAAC;AAqPzE,2EAA2E;AAC3E,eAAO,MAAM,uBAAuB,gBAAsC,CAAC;AAC3E,gEAAgE;AAChE,eAAO,MAAM,qBAAqB,gBAAoC,CAAC"}
@@ -10,8 +10,8 @@ const toolRegistry_1 = require("../../toolRegistry");
10
10
  /**
11
11
  * Tiers 1 & 2 — the AGENTIC repair brain.
12
12
  *
13
- * When the deterministic micro-fix can't help (moderation block, an
14
- * unrecognised provider rejection, a request that no single param snap can
13
+ * When the deterministic micro-fix can't help (an
14
+ * unrecognised provider rejection — NOT a moderation block since 2026-11-25, a request that no single param snap can
15
15
  * satisfy), an LLM looks at the failure the way a human operator would: it
16
16
  * decides WHETHER the issue is fixable and HOW, then returns a reworked tool
17
17
  * input. Two scopes, registered as two strategies so the engine escalates
@@ -91,9 +91,12 @@ function systemPrompt(scope) {
91
91
  if (scope === "narrow") {
92
92
  return (common +
93
93
  " SCOPE: NARROW. Fix ONLY the specific thing the provider rejected. Do NOT change " +
94
- "`modelKey`. Do NOT change the overall approach. For a content-moderation/safety block, " +
95
- "minimally reword the prompt to remove the flagged element while keeping the scene's " +
96
- "meaning. If the issue cannot be fixed this narrowly, or the only narrow fix would " +
94
+ "`modelKey`. Do NOT change the overall approach. " +
95
+ // REMOVED FOR v1 — kept for reference (2026-11-25: safety blocks are never reworded)
96
+ // "For a content-moderation/safety block, " +
97
+ // "minimally reword the prompt to remove the flagged element while keeping the scene's " +
98
+ // "meaning. " +
99
+ "If the issue cannot be fixed this narrowly, or the only narrow fix would " +
97
100
  "SIGNIFICANTLY degrade quality, set fixable=false (a wider repair will be tried).");
98
101
  }
99
102
  return (common +
@@ -134,9 +137,18 @@ function makeLlmRepairStrategy(scope, rank) {
134
137
  name: `llm-repair-${scope}`,
135
138
  rank,
136
139
  applies(rc) {
137
- // The LLM can reason about any non-auth failure. Auth is a deploy bug,
138
- // already short-circuited by the engine, but guard here too.
139
- return rc.failure.classification !== "auth";
140
+ // REMOVED FOR v1 — kept for reference
141
+ // // The LLM can reason about any non-auth failure. Auth is a deploy bug,
142
+ // // already short-circuited by the engine, but guard here too.
143
+ // return rc.failure.classification !== "auth";
144
+ //
145
+ // 2026-11-25: never reword-and-resubmit a content-moderation / safety
146
+ // block. The LLM was effectively a jailbreak loop — it rewrote blocked
147
+ // prompts (incl. sexualized real-person requests) until a provider let
148
+ // one through. Safety failures now go to the plan-level degrade ladder
149
+ // (stock-only for `safety`, see recovery/degradeLadder.ts) or fail the
150
+ // scene, and the engine records a moderation strike.
151
+ return rc.failure.classification !== "auth" && rc.failure.classification !== "safety";
140
152
  },
141
153
  async propose(rc) {
142
154
  const caller = (0, llmCallerRegistry_1.getLlmCaller)();
@@ -1,5 +1,5 @@
1
1
  import { Job } from "bullmq";
2
- import { RedisOptions } from "ioredis";
2
+ import { Redis as RedisClient, RedisOptions } from "ioredis";
3
3
  export declare class EnqueueTimeoutError extends Error {
4
4
  constructor();
5
5
  }
@@ -43,6 +43,14 @@ declare class BullMQService {
43
43
  * for the connection it blocks on.
44
44
  */
45
45
  private getConnection;
46
+ /**
47
+ * 2026-11-25: expose the single shared connection for small non-blocking
48
+ * commands (the per-user API rate limiter) so Functions don't open a SECOND
49
+ * Redis client per instance — prod Redis has a ~30-client ceiling. Callers
50
+ * MUST race every command against their own timeout (offline queue +
51
+ * infinite retries, see pingRedis) and fail open.
52
+ */
53
+ getSharedRedisConnection(): RedisClient | undefined;
46
54
  /**
47
55
  * Lightweight Redis reachability probe. Callers must race this against their
48
56
  * own timeout — ioredis (offline queueing + infinite retryStrategy, see
@@ -91,6 +99,15 @@ declare class BullMQService {
91
99
  age?: number;
92
100
  count?: number;
93
101
  };
102
+ /**
103
+ * 2026-11-25 (credit audit H3): a REAL BullMQ job id — BullMQ ignores a
104
+ * second add() with the same id while the first job's hash exists, so a
105
+ * double-submitted request can't enqueue the same work twice. Kept
106
+ * separate from `jobId` (which, despite its name, has always been sent
107
+ * as the job NAME — changing that would silently start de-duplicating
108
+ * every existing caller). Must not be an integer or contain ':'.
109
+ */
110
+ dedupeJobId?: string;
94
111
  }): Promise<void>;
95
112
  /**
96
113
  * After an enqueue timeout, drop the (likely half-open) shared connection so
@@ -1 +1 @@
1
- {"version":3,"file":"bullmq.service.d.ts","sourceRoot":"","sources":["../../src/services/bullmq.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAiB,GAAG,EAAE,MAAM,QAAQ,CAAC;AAC5C,OAAgB,EAAwB,YAAY,EAAE,MAAM,SAAS,CAAC;AAOtE,qBAAa,mBAAoB,SAAQ,KAAK;;CAK7C;AAqBD,MAAM,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAc1C,UAAU,oBAAoB;IAC5B,YAAY,EAAE,YAAY,CAAC;IAC3B,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,cAAM,aAAa;IACjB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAgB;IACvC,OAAO,CAAC,MAAM,CAAiC;IAC/C,OAAO,CAAC,OAAO,CAAgB;IAC/B,OAAO,CAAC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QService {
93
93
  (0, redisOptions_1.attachRedisListeners)(this.connection, "BullMQ");
94
94
  return this.connection;
95
95
  }
96
+ /**
97
+ * 2026-11-25: expose the single shared connection for small non-blocking
98
+ * commands (the per-user API rate limiter) so Functions don't open a SECOND
99
+ * Redis client per instance — prod Redis has a ~30-client ceiling. Callers
100
+ * MUST race every command against their own timeout (offline queue +
101
+ * infinite retries, see pingRedis) and fail open.
102
+ */
103
+ getSharedRedisConnection() {
104
+ if (!this.redisOptions.host)
105
+ return undefined;
106
+ return this.getConnection();
107
+ }
96
108
  /**
97
109
  * Lightweight Redis reachability probe. Callers must race this against their
98
110
  * own timeout — ioredis (offline queueing + infinite retryStrategy, see
@@ -159,6 +171,7 @@ class BullMQService {
159
171
  await this.init();
160
172
  await this.getQueue(queueName).add(opts?.jobId || "default", data, {
161
173
  delay: opts?.delay,
174
+ ...(opts?.dedupeJobId ? { jobId: opts.dedupeJobId } : {}),
162
175
  attempts: opts?.attempts,
163
176
  backoff: opts?.backoff,
164
177
  // Auto-evict finished jobs so their hashes don't accumulate forever.
@@ -1,7 +1,67 @@
1
+ import { DocumentData, DocumentReference, Transaction, UpdateData } from "firebase-admin/firestore";
2
+ /**
3
+ * Which wallet a charge came from / a refund goes back to:
4
+ * - string -> that organization's pooled balance
5
+ * - null -> explicitly the user's PERSONAL balance
6
+ * - undefined -> legacy: re-derive from the user's *current* organizationId
7
+ *
8
+ * Before 2026-11-25 there was no way to say "personal" explicitly, so a job
9
+ * charged to the personal wallet was refunded into an org pool if the user
10
+ * had joined one since (M3 of the credit-ledger audit). Jobs now store the
11
+ * wallet they were charged from (`chargedOrgId`, string | null) and thread it
12
+ * into every refund.
13
+ */
14
+ export type TCreditWallet = string | null | undefined;
15
+ /** Plan returned by a `refundCreditsWithDocUpdate` decider. */
16
+ export interface ICreditDocRefundPlan {
17
+ /** Credits to hand back (0 = no balance change, patch still written). */
18
+ refund: number;
19
+ /** Wallet to refund into (see TCreditWallet). */
20
+ wallet?: TCreditWallet;
21
+ /** Fields written to the job doc in the SAME transaction as the refund. */
22
+ patch: UpdateData<DocumentData>;
23
+ }
1
24
  export declare class CreditService {
2
25
  static consumeCredits(userId: string, creditsToConsume: number): Promise<{
3
26
  chargedOrgId: string | null;
4
27
  }>;
5
- static refundCredits(userId: string, creditsToRefund: number, spentFromOrgId?: string): Promise<void>;
28
+ static refundCredits(userId: string, creditsToRefund: number, spentFromOrgId?: TCreditWallet): Promise<void>;
29
+ /**
30
+ * Refund + job-doc update in ONE transaction (2026-11-25 audit, M1/M2).
31
+ *
32
+ * `decide` receives the FRESH job doc (read inside the transaction) and
33
+ * returns how much to refund, to which wallet, and the patch to write —
34
+ * or null to do nothing (e.g. the run was already settled by another
35
+ * writer). Because the guard, the balance change and the settled-marker
36
+ * all commit together, a worker reconcile and the stuck-job reaper (or a
37
+ * retried enqueue-failure handler) can never both refund the same hold.
38
+ */
39
+ static refundCreditsWithDocUpdate(params: {
40
+ userId: string;
41
+ docRef: DocumentReference;
42
+ decide: (doc: DocumentData | undefined) => ICreditDocRefundPlan | null;
43
+ }): Promise<{
44
+ applied: boolean;
45
+ refunded: number;
46
+ }>;
47
+ /**
48
+ * Refund inside a caller's transaction. Performs all of its reads before
49
+ * any write, so callers must have finished THEIR reads before calling it
50
+ * and may only write afterwards (Firestore's reads-before-writes rule).
51
+ * Returns the credits actually handed back.
52
+ *
53
+ * `spentFromOrgId`: string = that org; null = personal (explicit);
54
+ * undefined = legacy re-derive from the user's current organizationId.
55
+ */
56
+ static refundInTx(tx: Transaction, userId: string, creditsToRefund: number, spentFromOrgId?: TCreditWallet): Promise<number>;
57
+ }
58
+ /** Minimal shape needed to reason about a video job's billing run. */
59
+ export interface IVideoJobCreditRunShape {
60
+ reprocessCount?: number;
61
+ creditsSettledRun?: number;
6
62
  }
63
+ /** The billing run currently open on a video job. */
64
+ export declare function videoJobCreditRun(job: IVideoJobCreditRunShape): number;
65
+ /** True when the CURRENT run's hold has already been settled. */
66
+ export declare function isVideoJobRunSettled(job: IVideoJobCreditRunShape): boolean;
7
67
  //# sourceMappingURL=credit.service.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"credit.service.d.ts","sourceRoot":"","sources":["../../src/services/credit.service.ts"],"names":[],"mappings":"AAcA,qBAAa,aAAa;WACX,cAAc,CACzB,MAAM,EAAE,MAAM,EACd,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC;QAAE,YAAY,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC;WAsI9B,aAAa,CACxB,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,MAAM,EACvB,cAAc,CAAC,EAAE,MAAM,GACtB,OAAO,CAAC,IAAI,CAAC;CAwEjB"}
1
+ {"version":3,"file":"credit.service.d.ts","sourceRoot":"","sources":["../../src/services/credit.service.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,iBAAiB,EAGjB,WAAW,EACX,UAAU,EACX,MAAM,0BAA0B,CAAC;AAclC;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;AAEtD,+DAA+D;AAC/D,MAAM,WAAW,oBAAoB;IACnC,yEAAyE;IACzE,MAAM,EAAE,MAAM,CAAC;IACf,iDAAiD;IACjD,MAAM,CAAC,EAAE,aAAa,CAAC;IACvB,2EAA2E;IAC3E,KAAK,EAAE,UAAU,CAAC,YAAY,CAAC,CAAC;CACjC;AAUD,qBAAa,aAAa;WACX,cAAc,CACzB,MAAM,EAAE,MAAM,EACd,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC;QAAE,YAAY,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC;WA+I9B,aAAa,CACxB,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,MAAM,EACvB,cAAc,CAAC,EAAE,aAAa,GAC7B,OAAO,CAAC,IAAI,CAAC;IAShB;;;;;;;;;OASG;WACU,0BAA0B,CAAC,MAAM,EAAE;QAC9C,MAAM,EAAE,MAAM,CAAC;QACf,MAAM,EAAE,iBAAiB,CAAC;QAC1B,MAAM,EAAE,CAAC,GAAG,EAAE,YAAY,GAAG,SAAS,KAAK,oBAAoB,GAAG,IAAI,CAAC;KACxE,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;IAenD;;;;;;;;OAQG;WACU,UAAU,CACrB,EAAE,EAAE,WAAW,EACf,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,MAAM,EACvB,cAAc,CAAC,EAAE,aAAa,GAC7B,OAAO,CAAC,MAAM,CAAC;CA4EnB;AAQD,sEAAsE;AACtE,MAAM,WAAW,uBAAuB;IACtC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,qDAAqD;AACrD,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,uBAAuB,GAAG,MAAM,CAEtE;AAED,iEAAiE;AACjE,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,uBAAuB,GAAG,OAAO,CAK1E"}
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CreditService = void 0;
4
+ exports.videoJobCreditRun = videoJobCreditRun;
5
+ exports.isVideoJobRunSettled = isVideoJobRunSettled;
4
6
  const firestore_1 = require("firebase-admin/firestore");
5
7
  const types_1 = require("../globals/types");
6
8
  const firebase_1 = require("../libs/firebase");
@@ -13,8 +15,16 @@ const notification_service_1 = require("./notification.service");
13
15
  // who linger near the threshold don't see daily spam.
14
16
  const CREDITS_LOW_THRESHOLD = 0.2;
15
17
  const CREDITS_LOW_THROTTLE_MS = 24 * 60 * 60 * 1000;
18
+ // Throws on a non-finite or negative amount — a NaN/negative "charge" would
19
+ // silently MINT credits (consumed + NaN, consumed - -n). 2026-11-25 audit (LOW).
20
+ function assertCreditAmount(amount, op) {
21
+ if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0) {
22
+ throw new Error(`INVALID_CREDIT_AMOUNT: ${op} got ${String(amount)}`);
23
+ }
24
+ }
16
25
  class CreditService {
17
26
  static async consumeCredits(userId, creditsToConsume) {
27
+ assertCreditAmount(creditsToConsume, "consumeCredits");
18
28
  // Capture the post-consume balance so we can fire CREDITS_LOW outside the
19
29
  // transaction (notification writes must not interleave with the credit
20
30
  // mutation — that would risk transaction abort + retry firing duplicate
@@ -85,6 +95,14 @@ class CreditService {
85
95
  }
86
96
  const consumed = data.credits?.consumed ?? 0;
87
97
  const total = data.credits?.total ?? 0;
98
+ // Debt gate (2026-11-25): an uncovered finalization overage is recorded
99
+ // as `credits.owed` instead of being forgiven. While it is unpaid, no
100
+ // new personal-wallet spend is allowed — otherwise going into debt is a
101
+ // free generation followed by business as usual. Billing pays `owed`
102
+ // off on the next grant/top-up. Zero-credit "charges" don't spend.
103
+ if (creditsToConsume > 0 && (data.credits?.owed ?? 0) > 0) {
104
+ throw new Error("OUTSTANDING_BALANCE");
105
+ }
88
106
  if (consumed + creditsToConsume > total) {
89
107
  throw new Error("INSUFFICIENT_CREDITS");
90
108
  }
@@ -131,65 +149,119 @@ class CreditService {
131
149
  return { chargedOrgId: postState.chargedOrgId };
132
150
  }
133
151
  static async refundCredits(userId, creditsToRefund, spentFromOrgId) {
152
+ assertCreditAmount(creditsToRefund, "refundCredits");
134
153
  if (creditsToRefund <= 0)
135
154
  return;
136
155
  await firebase_1.firestore.runTransaction(async (tx) => {
137
- const userRef = firestore_service_1.FirestoreService.usersCol.doc(userId);
138
- const snap = await tx.get(userRef);
139
- if (!snap.exists) {
140
- throw new Error("USER_NOT_FOUND");
141
- }
142
- // `spentFromOrgId` (from the job's `spentFrom` snapshot) takes priority
143
- // over the user's *current* organizationId — the active org may have
144
- // changed between the charge and this refund. Callers with no job-doc
145
- // concept (older refund sites) omit it and fall back to today's
146
- // re-derive-from-current-org behavior.
147
- const orgId = spentFromOrgId ?? snap.data()?.organizationId;
148
- if (orgId) {
149
- const orgRef = firestore_service_1.FirestoreService.organizationsCol.doc(orgId);
150
- const memberRef = firestore_service_1.FirestoreService.organizationMembersCol.doc((0, organization_model_1.organizationMemberDocId)(orgId, userId));
151
- const [orgSnap, memberSnap] = await Promise.all([
152
- tx.get(orgRef),
153
- tx.get(memberRef),
154
- ]);
155
- // Org/membership may have been deleted since the charge — swallow
156
- // like the personal path's own "can't go below 0" clamp; there's
157
- // nowhere left to refund to.
158
- if (!orgSnap.exists)
159
- return;
160
- const orgData = orgSnap.data();
161
- const orgConsumed = orgData?.credits?.consumed ?? 0;
162
- const orgTotal = orgData?.credits?.total ?? 0;
163
- const newOrgConsumed = Math.max(0, orgConsumed - creditsToRefund);
164
- tx.update(orgRef, { "credits.consumed": newOrgConsumed });
165
- const allocation = memberSnap.exists
166
- ? memberSnap.data()?.monthlyAllocation
167
- : undefined;
168
- if (orgData?.creditMode === "allocated" && allocation && memberSnap.exists) {
169
- const newMemberConsumed = Math.max(0, (allocation.consumed ?? 0) - creditsToRefund);
170
- tx.update(memberRef, {
171
- "monthlyAllocation.consumed": newMemberConsumed,
172
- });
173
- }
174
- const ledgerRef = firestore_service_1.FirestoreService.organizationCreditLedgerCol.doc();
175
- tx.set(ledgerRef, {
176
- id: ledgerRef.id,
177
- orgId,
178
- actorUid: userId,
179
- delta: creditsToRefund,
180
- reason: "refund",
181
- balanceAfter: orgTotal - newOrgConsumed,
182
- createdAt: firestore_1.FieldValue.serverTimestamp(),
156
+ await CreditService.refundInTx(tx, userId, creditsToRefund, spentFromOrgId);
157
+ });
158
+ }
159
+ /**
160
+ * Refund + job-doc update in ONE transaction (2026-11-25 audit, M1/M2).
161
+ *
162
+ * `decide` receives the FRESH job doc (read inside the transaction) and
163
+ * returns how much to refund, to which wallet, and the patch to write —
164
+ * or null to do nothing (e.g. the run was already settled by another
165
+ * writer). Because the guard, the balance change and the settled-marker
166
+ * all commit together, a worker reconcile and the stuck-job reaper (or a
167
+ * retried enqueue-failure handler) can never both refund the same hold.
168
+ */
169
+ static async refundCreditsWithDocUpdate(params) {
170
+ return firebase_1.firestore.runTransaction(async (tx) => {
171
+ const docSnap = await tx.get(params.docRef);
172
+ const plan = params.decide(docSnap.exists ? docSnap.data() : undefined);
173
+ if (!plan)
174
+ return { applied: false, refunded: 0 };
175
+ assertCreditAmount(plan.refund, "refundCreditsWithDocUpdate");
176
+ const refunded = plan.refund > 0
177
+ ? await CreditService.refundInTx(tx, params.userId, plan.refund, plan.wallet)
178
+ : 0;
179
+ if (docSnap.exists)
180
+ tx.update(params.docRef, plan.patch);
181
+ return { applied: true, refunded };
182
+ });
183
+ }
184
+ /**
185
+ * Refund inside a caller's transaction. Performs all of its reads before
186
+ * any write, so callers must have finished THEIR reads before calling it
187
+ * and may only write afterwards (Firestore's reads-before-writes rule).
188
+ * Returns the credits actually handed back.
189
+ *
190
+ * `spentFromOrgId`: string = that org; null = personal (explicit);
191
+ * undefined = legacy re-derive from the user's current organizationId.
192
+ */
193
+ static async refundInTx(tx, userId, creditsToRefund, spentFromOrgId) {
194
+ assertCreditAmount(creditsToRefund, "refundInTx");
195
+ if (creditsToRefund <= 0)
196
+ return 0;
197
+ const userRef = firestore_service_1.FirestoreService.usersCol.doc(userId);
198
+ const snap = await tx.get(userRef);
199
+ if (!snap.exists) {
200
+ throw new Error("USER_NOT_FOUND");
201
+ }
202
+ // `spentFromOrgId` (from the job's charge-time snapshot) takes priority
203
+ // over the user's *current* organizationId — the active org may have
204
+ // changed between the charge and this refund. `null` means the charge
205
+ // was personal (2026-11-25); only `undefined` (older refund sites with
206
+ // no snapshot) falls back to the re-derive-from-current-org behavior.
207
+ // const orgId = spentFromOrgId ?? snap.data()?.organizationId; // REMOVED FOR v1 — kept for reference (null could not mean "personal", 2026-11-25)
208
+ const orgId = spentFromOrgId === undefined
209
+ ? snap.data()?.organizationId
210
+ : (spentFromOrgId ?? undefined);
211
+ if (orgId) {
212
+ const orgRef = firestore_service_1.FirestoreService.organizationsCol.doc(orgId);
213
+ const memberRef = firestore_service_1.FirestoreService.organizationMembersCol.doc((0, organization_model_1.organizationMemberDocId)(orgId, userId));
214
+ const [orgSnap, memberSnap] = await Promise.all([
215
+ tx.get(orgRef),
216
+ tx.get(memberRef),
217
+ ]);
218
+ // Org/membership may have been deleted since the charge — swallow
219
+ // like the personal path's own "can't go below 0" clamp; there's
220
+ // nowhere left to refund to.
221
+ if (!orgSnap.exists)
222
+ return 0;
223
+ const orgData = orgSnap.data();
224
+ const orgConsumed = orgData?.credits?.consumed ?? 0;
225
+ const orgTotal = orgData?.credits?.total ?? 0;
226
+ const newOrgConsumed = Math.max(0, orgConsumed - creditsToRefund);
227
+ tx.update(orgRef, { "credits.consumed": newOrgConsumed });
228
+ const allocation = memberSnap.exists
229
+ ? memberSnap.data()?.monthlyAllocation
230
+ : undefined;
231
+ if (orgData?.creditMode === "allocated" && allocation && memberSnap.exists) {
232
+ const newMemberConsumed = Math.max(0, (allocation.consumed ?? 0) - creditsToRefund);
233
+ tx.update(memberRef, {
234
+ "monthlyAllocation.consumed": newMemberConsumed,
183
235
  });
184
- return;
185
236
  }
186
- const consumed = snap.data()?.credits?.consumed ?? 0;
187
- // Never let consumed go below 0
188
- const newConsumed = Math.max(0, consumed - creditsToRefund);
189
- tx.update(userRef, {
190
- "credits.consumed": newConsumed,
237
+ const ledgerRef = firestore_service_1.FirestoreService.organizationCreditLedgerCol.doc();
238
+ tx.set(ledgerRef, {
239
+ id: ledgerRef.id,
240
+ orgId,
241
+ actorUid: userId,
242
+ delta: creditsToRefund,
243
+ reason: "refund",
244
+ balanceAfter: orgTotal - newOrgConsumed,
245
+ createdAt: firestore_1.FieldValue.serverTimestamp(),
191
246
  });
247
+ return orgConsumed - newOrgConsumed;
248
+ }
249
+ const consumed = snap.data()?.credits?.consumed ?? 0;
250
+ // Never let consumed go below 0
251
+ const newConsumed = Math.max(0, consumed - creditsToRefund);
252
+ tx.update(userRef, {
253
+ "credits.consumed": newConsumed,
192
254
  });
255
+ return consumed - newConsumed;
193
256
  }
194
257
  }
195
258
  exports.CreditService = CreditService;
259
+ /** The billing run currently open on a video job. */
260
+ function videoJobCreditRun(job) {
261
+ return job.reprocessCount ?? 0;
262
+ }
263
+ /** True when the CURRENT run's hold has already been settled. */
264
+ function isVideoJobRunSettled(job) {
265
+ return (typeof job.creditsSettledRun === "number" &&
266
+ job.creditsSettledRun === videoJobCreditRun(job));
267
+ }
@@ -0,0 +1,105 @@
1
+ import type { DocumentData, DocumentReference, Transaction } from "firebase-admin/firestore";
2
+ /**
3
+ * Single source of truth for every credit GRANT and CLAWBACK on a user's
4
+ * personal balance (2026-11-25).
5
+ *
6
+ * Why this exists: grants used to be ad-hoc writes scattered across the
7
+ * invoice webhook (`total = P, consumed = 0`), the yearly refresh trigger
8
+ * (`consumed = 0`) and the trial path (`total += 10`). Two exploits came out
9
+ * of that:
10
+ * - `credits.owed` (credits a job really cost beyond the balance, written by
11
+ * the worker's finalization) was wiped by the next reset, so going into
12
+ * debt was free.
13
+ * - a plan reset threw away the paid-for top-up credits the user still had.
14
+ *
15
+ * Ledger fields (all on `users/{uid}.credits`):
16
+ * - total credits granted in the current period
17
+ * - consumed credits used against `total`
18
+ * - owed credits used but not paid for (debt). While > 0 the
19
+ * CreditService refuses new spending; every grant pays it
20
+ * off first.
21
+ * - topUpBalance how much of the remaining balance (total - consumed) came
22
+ * from pay-as-you-go top-ups. Never decremented on spend;
23
+ * instead it is clamped to the remaining balance, which
24
+ * means PLAN credits are considered spent first.
25
+ *
26
+ * Invariants kept by every function here:
27
+ * - 0 <= owed
28
+ * - 0 <= topUpBalance <= max(0, total - consumed)
29
+ * - total >= consumed is never violated by a grant or a clawback (a clawback
30
+ * pulls total down to consumed at most — `consumed > total` is treated as a
31
+ * corrupt account by the credit precheck).
32
+ */
33
+ export interface ICreditLedgerState {
34
+ total: number;
35
+ consumed: number;
36
+ owed: number;
37
+ topUpBalance: number;
38
+ }
39
+ export type CreditGrant =
40
+ /** Monthly/yearly plan period start: total = P + carried top-up, consumed reset. */
41
+ {
42
+ kind: "plan_reset";
43
+ planCredits: number;
44
+ }
45
+ /** Mid-period upgrade: add the positive difference in plan credits, no reset. */
46
+ | {
47
+ kind: "plan_delta";
48
+ credits: number;
49
+ }
50
+ /** Paid pay-as-you-go pack: adds to total AND to topUpBalance. */
51
+ | {
52
+ kind: "top_up";
53
+ credits: number;
54
+ }
55
+ /** Free grant (trial): adds to total, not counted as a paid top-up. */
56
+ | {
57
+ kind: "bonus";
58
+ credits: number;
59
+ };
60
+ export type CreditClawback =
61
+ /** Dispute: every unused credit, top-ups included, is revoked. */
62
+ {
63
+ kind: "revoke_all";
64
+ }
65
+ /** Subscription payment refunded: revoke unused PLAN credits, keep paid top-ups. */
66
+ | {
67
+ kind: "revoke_plan";
68
+ }
69
+ /** A top-up payment refunded/disputed: revoke up to `credits` of the unused balance. */
70
+ | {
71
+ kind: "revoke_top_up";
72
+ credits: number;
73
+ };
74
+ export interface ICreditChangeResult {
75
+ before: ICreditLedgerState;
76
+ after: ICreditLedgerState;
77
+ /** Owed credits this grant paid off. */
78
+ paidOwed: number;
79
+ /** Credits removed from the spendable balance (clawbacks only). */
80
+ revoked: number;
81
+ }
82
+ /** Reads a user doc's `credits` map defensively (missing fields → 0). */
83
+ export declare function readCreditState(userData: DocumentData | undefined): ICreditLedgerState;
84
+ /** Pure: the ledger after a grant. Unit-testable without Firestore. */
85
+ export declare function computeCreditGrant(before: ICreditLedgerState, grant: CreditGrant): ICreditChangeResult;
86
+ /** Pure: the ledger after a refund/dispute clawback. */
87
+ export declare function computeCreditClawback(before: ICreditLedgerState, clawback: CreditClawback): ICreditChangeResult;
88
+ /** Dot-path update for the ledger fields only (never clobbers `reserved`). */
89
+ export declare function creditStateUpdate(s: ICreditLedgerState): Record<string, number>;
90
+ /**
91
+ * Transactional grant. The caller passes the user doc's data if it already
92
+ * read it inside `tx` (Firestore requires all reads before writes); otherwise
93
+ * it is read here. `extra` is merged into the same `tx.update` (dot paths),
94
+ * so a grant and the subscription fields it belongs to commit atomically.
95
+ */
96
+ export declare function applyCreditGrantInTx(tx: Transaction, ref: DocumentReference, grant: CreditGrant, opts?: {
97
+ userData?: DocumentData;
98
+ extra?: Record<string, unknown>;
99
+ }): Promise<ICreditChangeResult>;
100
+ /** Transactional clawback; same read/write contract as applyCreditGrantInTx. */
101
+ export declare function applyCreditClawbackInTx(tx: Transaction, ref: DocumentReference, clawback: CreditClawback, opts?: {
102
+ userData?: DocumentData;
103
+ extra?: Record<string, unknown>;
104
+ }): Promise<ICreditChangeResult>;
105
+ //# sourceMappingURL=grant.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grant.d.ts","sourceRoot":"","sources":["../../../src/services/credits/grant.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,YAAY,EACZ,iBAAiB,EACjB,WAAW,EACZ,MAAM,0BAA0B,CAAC;AAElC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,MAAM,WAAW;AACrB,oFAAoF;AAClF;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE;AAC7C,iFAAiF;GAC/E;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE;AACzC,kEAAkE;GAChE;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE;AACrC,uEAAuE;GACrE;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAEvC,MAAM,MAAM,cAAc;AACxB,kEAAkE;AAChE;IAAE,IAAI,EAAE,YAAY,CAAA;CAAE;AACxB,oFAAoF;GAClF;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