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.
- package/lib/globals/plans.d.ts +17 -0
- package/lib/globals/plans.d.ts.map +1 -1
- package/lib/globals/plans.js +11 -1
- package/lib/globals/types.d.ts +6 -2
- package/lib/globals/types.d.ts.map +1 -1
- package/lib/globals/types.js +11 -0
- package/lib/models/agent.model.d.ts +6 -0
- package/lib/models/agent.model.d.ts.map +1 -1
- package/lib/models/demoVideoProject.model.d.ts +6 -0
- package/lib/models/demoVideoProject.model.d.ts.map +1 -1
- package/lib/models/image.model.d.ts +6 -0
- package/lib/models/image.model.d.ts.map +1 -1
- package/lib/models/musicJob.model.d.ts +6 -0
- package/lib/models/musicJob.model.d.ts.map +1 -1
- package/lib/models/social.model.d.ts +7 -2
- package/lib/models/social.model.d.ts.map +1 -1
- package/lib/models/upscale.model.d.ts +6 -0
- package/lib/models/upscale.model.d.ts.map +1 -1
- package/lib/models/user.model.d.ts +68 -1
- package/lib/models/user.model.d.ts.map +1 -1
- package/lib/models/video.model.d.ts +43 -0
- package/lib/models/video.model.d.ts.map +1 -1
- package/lib/models/videoTool.model.d.ts +6 -0
- package/lib/models/videoTool.model.d.ts.map +1 -1
- package/lib/schemas/social.schema.d.ts +9 -0
- package/lib/schemas/social.schema.d.ts.map +1 -1
- package/lib/schemas/social.schema.js +6 -1
- package/lib/services/accountStatus/index.d.ts +35 -0
- package/lib/services/accountStatus/index.d.ts.map +1 -1
- package/lib/services/accountStatus/index.js +54 -0
- package/lib/services/agent/repair/engine.d.ts.map +1 -1
- package/lib/services/agent/repair/engine.js +18 -0
- package/lib/services/agent/repair/strategies/llmRepair.strategy.d.ts.map +1 -1
- package/lib/services/agent/repair/strategies/llmRepair.strategy.js +20 -8
- package/lib/services/bullmq.service.d.ts +18 -1
- package/lib/services/bullmq.service.d.ts.map +1 -1
- package/lib/services/bullmq.service.js +13 -0
- package/lib/services/credit.service.d.ts +61 -1
- package/lib/services/credit.service.d.ts.map +1 -1
- package/lib/services/credit.service.js +124 -52
- package/lib/services/credits/grant.d.ts +105 -0
- package/lib/services/credits/grant.d.ts.map +1 -0
- package/lib/services/credits/grant.js +129 -0
- package/lib/services/demo/demoPrefill.d.ts.map +1 -1
- package/lib/services/demo/demoPrefill.js +101 -84
- package/lib/services/index.d.ts +1 -0
- package/lib/services/index.d.ts.map +1 -1
- package/lib/services/index.js +1 -0
- package/lib/services/moderation/generationModeration.service.d.ts +52 -0
- package/lib/services/moderation/generationModeration.service.d.ts.map +1 -0
- package/lib/services/moderation/generationModeration.service.js +260 -0
- package/lib/services/moderation/index.d.ts +4 -0
- package/lib/services/moderation/index.d.ts.map +1 -1
- package/lib/services/moderation/index.js +14 -1
- package/lib/services/moderation/moderationStrike.service.d.ts +67 -0
- package/lib/services/moderation/moderationStrike.service.d.ts.map +1 -0
- package/lib/services/moderation/moderationStrike.service.js +134 -0
- package/lib/services/rateLimiter/index.d.ts +1 -0
- package/lib/services/rateLimiter/index.d.ts.map +1 -1
- package/lib/services/rateLimiter/index.js +1 -0
- package/lib/services/rateLimiter/userRateLimiter.service.d.ts +55 -0
- package/lib/services/rateLimiter/userRateLimiter.service.d.ts.map +1 -0
- package/lib/services/rateLimiter/userRateLimiter.service.js +220 -0
- package/lib/services/socialOAuth/youtube.oauth.d.ts +1 -1
- package/lib/services/socialOAuth/youtube.oauth.d.ts.map +1 -1
- package/lib/services/socialOAuth/youtube.oauth.js +15 -7
- package/lib/services/socialPublish/types.d.ts +31 -0
- package/lib/services/socialPublish/types.d.ts.map +1 -1
- package/lib/services/socialPublish/types.js +17 -0
- package/lib/services/socialPublish/youtube.publish.d.ts +12 -1
- package/lib/services/socialPublish/youtube.publish.d.ts.map +1 -1
- package/lib/services/socialPublish/youtube.publish.js +95 -0
- package/lib/services/trialGuard/trialSignals.d.ts.map +1 -1
- package/lib/services/trialGuard/trialSignals.js +15 -0
- package/lib/utils/index.d.ts +1 -0
- package/lib/utils/index.d.ts.map +1 -1
- package/lib/utils/index.js +1 -0
- package/lib/utils/ssrfGuard.d.ts +59 -0
- package/lib/utils/ssrfGuard.d.ts.map +1 -0
- package/lib/utils/ssrfGuard.js +253 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"social.schema.d.ts","sourceRoot":"","sources":["../../src/schemas/social.schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAEnD;;;;GAIG;AAEH,eAAO,MAAM,oBAAoB,mCAAgC,CAAC;AAElE,qFAAqF;AACrF,eAAO,MAAM,yBAAyB;;;;;;iBAmBpC,CAAC;AAEH,wCAAwC;AACxC,eAAO,MAAM,0BAA0B;;;;;;;;;;;;;;iBAoBnC,CAAC;AAEL,6EAA6E;AAC7E,eAAO,MAAM,sBAAsB;;iBAEjC,CAAC;AAEH,gFAAgF;AAChF,eAAO,MAAM,uBAAuB;;;;;;;;iBAKlC,CAAC;AAEH,6EAA6E;AAC7E,eAAO,MAAM,sBAAsB;;iBAGjC,CAAC;AAEH;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B;;;;;;iBAWrC,CAAC;AAEH;;;;;GAKG;AACH,eAAO,MAAM,4BAA4B;;;;;;iBAWvC,CAAC;AAEH,gEAAgE;AAChE,eAAO,MAAM,0BAA0B;;;iBAKrC,CAAC;AAEH,MAAM,MAAM,wBAAwB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,yBAAyB,CAAC,CAAC;AACjF,MAAM,MAAM,yBAAyB,GAAG,CAAC,CAAC,KAAK,CAC7C,OAAO,0BAA0B,CAClC,CAAC;AACF,MAAM,MAAM,yBAAyB,GAAG,CAAC,CAAC,KAAK,CAC7C,OAAO,0BAA0B,CAClC,CAAC;AACF,MAAM,MAAM,qBAAqB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAC3E,MAAM,MAAM,sBAAsB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAC;AAC7E,MAAM,MAAM,qBAAqB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAC3E,MAAM,MAAM,yBAAyB,GAAG,CAAC,CAAC,KAAK,CAC7C,OAAO,0BAA0B,CAClC,CAAC;AACF,MAAM,MAAM,2BAA2B,GAAG,CAAC,CAAC,KAAK,CAC/C,OAAO,4BAA4B,CACpC,CAAC"}
|
|
1
|
+
{"version":3,"file":"social.schema.d.ts","sourceRoot":"","sources":["../../src/schemas/social.schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAEnD;;;;GAIG;AAEH,eAAO,MAAM,oBAAoB,mCAAgC,CAAC;AAElE,qFAAqF;AACrF,eAAO,MAAM,yBAAyB;;;;;;iBAmBpC,CAAC;AAEH,wCAAwC;AACxC,eAAO,MAAM,0BAA0B;;;;;;;;;;;;;;iBAoBnC,CAAC;AAEL,uFAAuF;AACvF,eAAO,MAAM,0BAA0B;;;;;;;iBAGrC,CAAC;AAEH,6EAA6E;AAC7E,eAAO,MAAM,sBAAsB;;iBAEjC,CAAC;AAEH,gFAAgF;AAChF,eAAO,MAAM,uBAAuB;;;;;;;;iBAKlC,CAAC;AAEH,6EAA6E;AAC7E,eAAO,MAAM,sBAAsB;;iBAGjC,CAAC;AAEH;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B;;;;;;iBAWrC,CAAC;AAEH;;;;;GAKG;AACH,eAAO,MAAM,4BAA4B;;;;;;iBAWvC,CAAC;AAEH,gEAAgE;AAChE,eAAO,MAAM,0BAA0B;;;iBAKrC,CAAC;AAEH,MAAM,MAAM,wBAAwB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,yBAAyB,CAAC,CAAC;AACjF,MAAM,MAAM,yBAAyB,GAAG,CAAC,CAAC,KAAK,CAC7C,OAAO,0BAA0B,CAClC,CAAC;AACF,MAAM,MAAM,yBAAyB,GAAG,CAAC,CAAC,KAAK,CAC7C,OAAO,0BAA0B,CAClC,CAAC;AACF,MAAM,MAAM,qBAAqB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAC3E,MAAM,MAAM,sBAAsB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAC;AAC7E,MAAM,MAAM,qBAAqB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAC3E,MAAM,MAAM,yBAAyB,GAAG,CAAC,CAAC,KAAK,CAC7C,OAAO,0BAA0B,CAClC,CAAC;AACF,MAAM,MAAM,2BAA2B,GAAG,CAAC,CAAC,KAAK,CAC/C,OAAO,4BAA4B,CACpC,CAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SocialConnectRequestSchema = exports.SocialHookScoreRequestSchema = exports.SocialSuggestRequestSchema = exports.SocialInboxDraftSchema = exports.SocialInboxUpdateSchema = exports.SocialInboxReplySchema = exports.SocialPublishRequestSchema = exports.SocialPublishTargetSchema = exports.SocialProviderSchema = void 0;
|
|
3
|
+
exports.SocialConnectRequestSchema = exports.SocialHookScoreRequestSchema = exports.SocialSuggestRequestSchema = exports.SocialInboxDraftSchema = exports.SocialInboxUpdateSchema = exports.SocialInboxReplySchema = exports.SocialPostVisibilitySchema = exports.SocialPublishRequestSchema = exports.SocialPublishTargetSchema = exports.SocialProviderSchema = void 0;
|
|
4
4
|
const zod_1 = require("zod");
|
|
5
5
|
const types_1 = require("../globals/types");
|
|
6
6
|
/**
|
|
@@ -52,6 +52,11 @@ exports.SocialPublishRequestSchema = zod_1.z
|
|
|
52
52
|
message: "Either videoJobId or mediaUrl is required",
|
|
53
53
|
path: ["videoJobId"],
|
|
54
54
|
});
|
|
55
|
+
/** Body for PATCH /v1/social/posts/:id/visibility — change one target's visibility. */
|
|
56
|
+
exports.SocialPostVisibilitySchema = zod_1.z.object({
|
|
57
|
+
socialAccountId: zod_1.z.string().min(1),
|
|
58
|
+
privacy: zod_1.z.enum(["public", "unlisted", "private"]),
|
|
59
|
+
});
|
|
55
60
|
/** Body for POST /v1/social/inbox/:id/reply — reply to a comment/mention. */
|
|
56
61
|
exports.SocialInboxReplySchema = zod_1.z.object({
|
|
57
62
|
message: zod_1.z.string().min(1).max(2000),
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { IUserModel } from "../../models/user.model";
|
|
1
2
|
/**
|
|
2
3
|
* True when the user deleted their account (see IUserModel.deletedAt). Used
|
|
3
4
|
* by surfaces that act for a user without a signed-in request — public share
|
|
@@ -6,4 +7,38 @@
|
|
|
6
7
|
* A missing user doc also counts as deleted.
|
|
7
8
|
*/
|
|
8
9
|
export declare function isUserAccountDeleted(uid: string | null | undefined): Promise<boolean>;
|
|
10
|
+
/** The subset of the user doc the block check reads. */
|
|
11
|
+
export type AccountBlockFields = Pick<IUserModel, "blockedAt">;
|
|
12
|
+
/**
|
|
13
|
+
* Pure check on an already-loaded user doc. Keyed off `blockedAt` ALONE
|
|
14
|
+
* (2026-11-25): the moderation strike code writes blockedAt/blockedReason
|
|
15
|
+
* directly on the user doc, without going through the admin endpoint, so no
|
|
16
|
+
* other flag (Auth `disabled`, a status enum) may be required for the block to
|
|
17
|
+
* take effect. Any truthy value — Timestamp, epoch number, serverTimestamp
|
|
18
|
+
* sentinel — counts.
|
|
19
|
+
*/
|
|
20
|
+
export declare function isUserDocBlocked(user: AccountBlockFields | null | undefined): boolean;
|
|
21
|
+
/**
|
|
22
|
+
* True when the account is blocked. Accepts a loaded user doc (no read) or a
|
|
23
|
+
* uid (one Firestore read). A missing user doc is NOT "blocked" — pair with
|
|
24
|
+
* isUserAccountDeleted / isUserAccountUsable for that.
|
|
25
|
+
*/
|
|
26
|
+
export declare function isUserBlocked(userOrUid: AccountBlockFields | string | null | undefined): Promise<boolean>;
|
|
27
|
+
export type AccountUnusableReason = "account_deleted" | "account_blocked";
|
|
28
|
+
/**
|
|
29
|
+
* Single read that answers "may this uid act / be served?" — not deleted (doc
|
|
30
|
+
* exists, no deletedAt) and not blocked. Returns the reason when unusable so
|
|
31
|
+
* callers can surface the right code.
|
|
32
|
+
*/
|
|
33
|
+
export declare function getAccountUnusableReason(uid: string | null | undefined, opts?: {
|
|
34
|
+
/**
|
|
35
|
+
* Treat a MISSING user doc as deleted (default true). The worker gate
|
|
36
|
+
* passes false: a payload userId with no doc may be a system / service
|
|
37
|
+
* id, and failing that job outright (no refund) is worse than running it
|
|
38
|
+
* (review 2026-11-25). Soft-deleted accounts keep their doc + deletedAt.
|
|
39
|
+
*/
|
|
40
|
+
missingIsDeleted?: boolean;
|
|
41
|
+
}): Promise<AccountUnusableReason | null>;
|
|
42
|
+
/** True when the account is neither deleted (incl. missing doc) nor blocked. */
|
|
43
|
+
export declare function isUserAccountUsable(uid: string | null | undefined): Promise<boolean>;
|
|
9
44
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/services/accountStatus/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/services/accountStatus/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAE1D;;;;;;GAMG;AACH,wBAAsB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC,CAI3F;AAED,wDAAwD;AACxD,MAAM,MAAM,kBAAkB,GAAG,IAAI,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;AAE/D;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,kBAAkB,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAIrF;AAED;;;;GAIG;AACH,wBAAsB,aAAa,CACjC,SAAS,EAAE,kBAAkB,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,GACxD,OAAO,CAAC,OAAO,CAAC,CAKlB;AAED,MAAM,MAAM,qBAAqB,GAAG,iBAAiB,GAAG,iBAAiB,CAAC;AAE1E;;;;GAIG;AACH,wBAAsB,wBAAwB,CAC5C,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAC9B,IAAI,GAAE;IACJ;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CACvB,GACL,OAAO,CAAC,qBAAqB,GAAG,IAAI,CAAC,CAOvC;AAED,gFAAgF;AAChF,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC,CAG1F"}
|
|
@@ -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":"
|
|
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;
|
|
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 (
|
|
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.
|
|
95
|
-
|
|
96
|
-
"
|
|
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
|
-
//
|
|
138
|
-
//
|
|
139
|
-
|
|
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,
|
|
1
|
+
{"version":3,"file":"bullmq.service.d.ts","sourceRoot":"","sources":["../../src/services/bullmq.service.ts"],"names":[],"mappings":"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"}
|
|
@@ -93,6 +93,18 @@ class BullMQService {
|
|
|
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?:
|
|
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":"
|
|
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
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
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
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
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
|
+
}
|