@abyss-project/probe 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/.eslintrc.js +32 -0
  2. package/.prettierrc +5 -0
  3. package/README.md +4 -14
  4. package/dist/api/index.d.ts +4 -0
  5. package/dist/api/index.js +4 -0
  6. package/dist/api/index.js.map +1 -1
  7. package/dist/api/probe-scan.api.d.ts +4 -6
  8. package/dist/api/probe-scan.api.js +34 -30
  9. package/dist/api/probe-scan.api.js.map +1 -1
  10. package/dist/api/probe-scan.api.test.js +27 -7
  11. package/dist/api/probe-scan.api.test.js.map +1 -1
  12. package/dist/api/probe-scan.application.api.d.ts +7 -0
  13. package/dist/api/probe-scan.application.api.js +40 -0
  14. package/dist/api/probe-scan.application.api.js.map +1 -0
  15. package/dist/api/probe-scan.application.api.test.d.ts +1 -0
  16. package/dist/api/probe-scan.application.api.test.js +51 -0
  17. package/dist/api/probe-scan.application.api.test.js.map +1 -0
  18. package/dist/api/probe-usage.api.d.ts +2 -0
  19. package/dist/api/probe-usage.api.js +24 -0
  20. package/dist/api/probe-usage.api.js.map +1 -0
  21. package/dist/api/probe-usage.application.api.d.ts +2 -0
  22. package/dist/api/probe-usage.application.api.js +12 -0
  23. package/dist/api/probe-usage.application.api.js.map +1 -0
  24. package/dist/api/probe-webhook.api.d.ts +3 -1
  25. package/dist/api/probe-webhook.api.js +28 -8
  26. package/dist/api/probe-webhook.api.js.map +1 -1
  27. package/dist/api/probe-webhook.api.test.js +17 -7
  28. package/dist/api/probe-webhook.api.test.js.map +1 -1
  29. package/dist/api/probe-webhook.application.api.d.ts +6 -0
  30. package/dist/api/probe-webhook.application.api.js +27 -0
  31. package/dist/api/probe-webhook.application.api.js.map +1 -0
  32. package/dist/api/probe-webhook.application.api.test.d.ts +1 -0
  33. package/dist/api/probe-webhook.application.api.test.js +43 -0
  34. package/dist/api/probe-webhook.application.api.test.js.map +1 -0
  35. package/dist/constants/index.d.ts +1 -0
  36. package/dist/{types/interface/models/probe-scan.model.js → constants/index.js} +1 -1
  37. package/dist/constants/index.js.map +1 -0
  38. package/dist/index.d.ts +42 -9
  39. package/dist/index.js +65 -20
  40. package/dist/index.js.map +1 -1
  41. package/dist/types/enum/api-error.enum.d.ts +15 -1
  42. package/dist/types/enum/api-error.enum.js +14 -0
  43. package/dist/types/enum/api-error.enum.js.map +1 -1
  44. package/dist/types/index.d.ts +1 -1
  45. package/dist/types/index.js +1 -1
  46. package/dist/types/index.js.map +1 -1
  47. package/dist/types/interface/api/requests/index.d.ts +1 -0
  48. package/dist/types/interface/api/requests/index.js +1 -0
  49. package/dist/types/interface/api/requests/index.js.map +1 -1
  50. package/dist/types/interface/api/requests/probe-usage.request.d.ts +3 -0
  51. package/dist/types/interface/{models/probe-webhook.model.js → api/requests/probe-usage.request.js} +1 -1
  52. package/dist/types/interface/api/requests/probe-usage.request.js.map +1 -0
  53. package/dist/types/interface/api/requests/probe-webhook.request.d.ts +8 -0
  54. package/dist/types/interface/api/responses/index.d.ts +1 -0
  55. package/dist/types/interface/api/responses/index.js +1 -0
  56. package/dist/types/interface/api/responses/index.js.map +1 -1
  57. package/dist/types/interface/api/responses/probe-scan.response.d.ts +1 -0
  58. package/dist/types/interface/api/responses/probe-usage.response.d.ts +7 -0
  59. package/dist/types/interface/api/responses/probe-usage.response.js +3 -0
  60. package/dist/types/interface/api/responses/probe-usage.response.js.map +1 -0
  61. package/dist/types/interface/api/responses/probe-webhook.response.d.ts +5 -2
  62. package/dist/types/interface/index.d.ts +0 -1
  63. package/dist/types/interface/index.js +0 -1
  64. package/dist/types/interface/index.js.map +1 -1
  65. package/dist/types/interface/models/index.d.ts +3 -2
  66. package/dist/types/interface/models/index.js +3 -2
  67. package/dist/types/interface/models/index.js.map +1 -1
  68. package/dist/types/interface/models/{probe-scan.model.d.ts → probe-scan.dto.d.ts} +8 -0
  69. package/dist/types/interface/models/probe-scan.dto.js +3 -0
  70. package/dist/types/interface/models/probe-scan.dto.js.map +1 -0
  71. package/dist/types/interface/models/probe-webhook-delivery.dto.d.ts +19 -0
  72. package/dist/types/interface/models/probe-webhook-delivery.dto.js.map +1 -0
  73. package/dist/types/interface/models/{probe-webhook.model.d.ts → probe-webhook.dto.d.ts} +1 -3
  74. package/dist/types/interface/models/probe-webhook.dto.js +3 -0
  75. package/dist/types/interface/models/probe-webhook.dto.js.map +1 -0
  76. package/dist/types/tests/probe.dto.test.js +39 -2
  77. package/dist/types/tests/probe.dto.test.js.map +1 -1
  78. package/dist/utils/enum.utils.d.ts +1 -0
  79. package/dist/utils/enum.utils.js +3 -0
  80. package/dist/utils/enum.utils.js.map +1 -0
  81. package/dist/utils/error.utils.d.ts +15 -0
  82. package/dist/utils/error.utils.js +25 -0
  83. package/dist/utils/error.utils.js.map +1 -0
  84. package/dist/utils/index.d.ts +3 -1
  85. package/dist/utils/index.js +3 -1
  86. package/dist/utils/index.js.map +1 -1
  87. package/dist/utils/probe-scan-cost.utils.d.ts +5 -0
  88. package/dist/utils/probe-scan-cost.utils.js +21 -0
  89. package/dist/utils/probe-scan-cost.utils.js.map +1 -0
  90. package/dist/utils/probe-webhook-signature.utils.d.ts +0 -2
  91. package/dist/utils/probe-webhook-signature.utils.js +1 -2
  92. package/dist/utils/probe-webhook-signature.utils.js.map +1 -1
  93. package/package.json +24 -14
  94. package/src/api/index.ts +6 -0
  95. package/src/api/probe-scan.api.test.ts +47 -0
  96. package/src/api/probe-scan.api.ts +203 -0
  97. package/src/api/probe-scan.application.api.test.ts +35 -0
  98. package/src/api/probe-scan.application.api.ts +157 -0
  99. package/src/api/probe-usage.api.ts +47 -0
  100. package/src/api/probe-usage.application.api.ts +25 -0
  101. package/src/api/probe-webhook.api.test.ts +17 -0
  102. package/src/api/probe-webhook.api.ts +119 -0
  103. package/src/api/probe-webhook.application.api.test.ts +18 -0
  104. package/src/api/probe-webhook.application.api.ts +141 -0
  105. package/src/constants/index.ts +1 -0
  106. package/src/index.ts +205 -0
  107. package/src/types/enum/api-error.enum.ts +33 -0
  108. package/src/types/enum/index.ts +2 -0
  109. package/src/types/enum/probe-scan.enum.ts +44 -0
  110. package/src/types/index.ts +2 -0
  111. package/src/types/interface/api/index.ts +5 -0
  112. package/src/types/interface/api/requests/index.ts +3 -0
  113. package/src/types/interface/api/requests/probe-scan.request.ts +54 -0
  114. package/src/types/interface/api/requests/probe-usage.request.ts +7 -0
  115. package/src/types/interface/api/requests/probe-webhook.request.ts +33 -0
  116. package/src/types/interface/api/responses/index.ts +3 -0
  117. package/src/types/interface/api/responses/probe-scan.response.ts +45 -0
  118. package/src/types/interface/api/responses/probe-usage.response.ts +25 -0
  119. package/src/types/interface/api/responses/probe-webhook.response.ts +24 -0
  120. package/src/types/interface/api/type-message/api-error.ts +7 -0
  121. package/src/types/interface/api/type-message/base-paginate.ts +11 -0
  122. package/src/types/interface/api/type-message/response.ts +6 -0
  123. package/src/types/interface/index.ts +2 -0
  124. package/src/types/interface/models/index.ts +3 -0
  125. package/src/types/interface/models/probe-scan.dto.ts +67 -0
  126. package/src/types/interface/models/probe-webhook-delivery.dto.ts +73 -0
  127. package/src/types/interface/models/probe-webhook.dto.ts +29 -0
  128. package/src/types/tests/probe.dto.test.ts +156 -0
  129. package/src/utils/enum.utils.ts +1 -0
  130. package/src/utils/error.utils.ts +30 -0
  131. package/src/utils/index.ts +4 -0
  132. package/src/utils/probe-scan-cost.utils.ts +101 -0
  133. package/src/utils/probe-webhook-signature.utils.ts +56 -0
  134. package/tsconfig.check.json +15 -0
  135. package/dist/types/interface/dto/index.d.ts +0 -1
  136. package/dist/types/interface/dto/index.js +0 -18
  137. package/dist/types/interface/dto/index.js.map +0 -1
  138. package/dist/types/interface/dto/probe-webhook-delivery.dto.d.ts +0 -7
  139. package/dist/types/interface/dto/probe-webhook-delivery.dto.js.map +0 -1
  140. package/dist/types/interface/models/probe-scan.model.js.map +0 -1
  141. package/dist/types/interface/models/probe-webhook.model.js.map +0 -1
  142. package/dist/utils/http.utils.d.ts +0 -3
  143. package/dist/utils/http.utils.js +0 -20
  144. package/dist/utils/http.utils.js.map +0 -1
  145. /package/dist/types/interface/{dto → models}/probe-webhook-delivery.dto.js +0 -0
@@ -0,0 +1,73 @@
1
+ import { ProbeScanVerdict } from '../../enum';
2
+
3
+ // Mirrors apps/api/src/services/probe-webhook-delivery.service.ts's
4
+ // ProbeWebhookPayload EXACTLY (same field set, same JSON.stringify'd body a
5
+ // receiver's raw request body will deserialize into) — this is the payload
6
+ // AbyssProbe POSTs to every registered webhook's `callbackUrl` (and to a
7
+ // scan's own per-request `callbackUrl`, see probe-scan docs) once an ASYNC
8
+ // scan reaches a verdict (`status: DONE`).
9
+ //
10
+ // `verdict` is typed as the concrete enum here (not `string` like the
11
+ // server's internal type) because delivery only ever happens on a DONE scan,
12
+ // where the verdict is always set — see dispatchProbeScanWebhooks's guard.
13
+
14
+ /**
15
+ * Body of a webhook delivery, signed via HMAC-SHA256 of
16
+ * `JSON.stringify(payload)` — see {@link PROBE_WEBHOOK_SIGNATURE_HEADER} and
17
+ * {@link verifyProbeWebhookSignature} (this package's root / utils).
18
+ */
19
+ export interface IProbeWebhookDeliveryPayload {
20
+ scanId: string;
21
+ /** Free-form caller reference, echoed back verbatim (see IProbeScanHistoryItem#context). */
22
+ context: Record<string, unknown> | null;
23
+ verdict: ProbeScanVerdict;
24
+ /** [] when clean. */
25
+ viruses: string[];
26
+ /**
27
+ * `ACCOUNT_AV_SCAN_UNITS` this scan consumed (WS5-1). Delivery only ever
28
+ * happens on a DONE scan, where the cost is always already computed and
29
+ * billed — see {@link IProbeScanHistoryItem#costUnits}.
30
+ */
31
+ costUnits: number | null;
32
+ }
33
+
34
+ // ─── Delivery HISTORY (WS5-6) ────────────────
35
+ //
36
+ // The interface above is the PAYLOAD a webhook receiver gets POSTed. This
37
+ // section is a DIFFERENT concept: the persisted AUDIT ROW AbyssProbe keeps
38
+ // of its OWN delivery attempts (one row per attempt — mirrors
39
+ // apps/api/src/database/models/probe-webhook-delivery.model.ts EXACTLY,
40
+ // itself modelled after this package's own extraction-webhook
41
+ // delivery-history shape, trimmed to AbyssProbe's simpler
42
+ // one-attempt-per-row reality — see that model's header comment). Read via
43
+ // `GET /webhook/:webhookId/deliveries` (`sdk.probe.webhook.listDeliveries`).
44
+
45
+ /**
46
+ * One persisted delivery-attempt row, as returned (paginated) by
47
+ * `GET /webhook/:webhookId/deliveries`.
48
+ */
49
+ export interface IProbeWebhookDelivery {
50
+ id: string;
51
+ /**
52
+ * The registered webhook this delivery targeted. null for a delivery to a
53
+ * scan's own ad-hoc per-request `callbackUrl` that matched no registered
54
+ * webhook (see the server model's own doc comment) — such a row is never
55
+ * reachable via this webhook-scoped endpoint in practice (there is no
56
+ * webhookId to query it under), but the field stays nullable to mirror the
57
+ * server column's real type.
58
+ */
59
+ webhookId: string | null;
60
+ /** The scan whose verdict this delivery carried. */
61
+ scanId: string;
62
+ /** The exact URL this attempt POSTed to. */
63
+ url: string;
64
+ /** HTTP status code received. null when the request never got a response (network error / timeout / abort). */
65
+ statusCode: number | null;
66
+ /** true only for a 2xx response. */
67
+ success: boolean;
68
+ /** When this attempt was made. */
69
+ attemptedAt: Date;
70
+ /** Failure reason (HTTP non-2xx status, or the caught network/timeout error's message). null on success. */
71
+ error: string | null;
72
+ createdAt: Date;
73
+ }
@@ -0,0 +1,29 @@
1
+ // Mirrors apps/api/src/api/controllers/probe-webhook.controller.ts's local
2
+ // WebhookResponseData. Public shape of a registered `probe_webhooks` row —
3
+ // never echoes the internal ownership columns
4
+ // (userId/organizationId/applicationId), same discipline as the scan models.
5
+ //
6
+ // WS5-7 (AbyssProbe UX rework): `secret` is ALWAYS re-displayable now —
7
+ // returned on every read (GET /webhook list, and PATCH /webhook/:id), not
8
+ // just once on create. Mirrors how AbyssExtract's own webhook model
9
+ // (`IExtractionWebhookDelivery`'s sibling `ExtractionWebhook` — see
10
+ // apps/api/src/database/models/extraction-webhook.model.ts /
11
+ // extraction-webhook.controller.ts) has always exposed its
12
+ // `webhookSecret` column on every response, never a once-only reveal. This
13
+ // lets a consumer (e.g. abyss-storage's own webhook registration) read its
14
+ // secret back at any time instead of relying on a log-once bootstrap.
15
+
16
+ export interface IProbeWebhook {
17
+ id: string;
18
+ /** HTTPS endpoint the verdict is POSTed to. */
19
+ callbackUrl: string;
20
+ /**
21
+ * Server-generated HMAC-SHA256 signing secret. Re-displayable: returned on
22
+ * every read (list/create/update), not once-only — see this interface's
23
+ * own header note (WS5-7).
24
+ */
25
+ secret: string;
26
+ /** Disabled webhooks are skipped by dispatch (soft-off, not deleted). */
27
+ active: boolean;
28
+ createdAt: Date;
29
+ }
@@ -0,0 +1,156 @@
1
+ // Type-level compile test for AbyssProbe's DTO/response shapes — asserts
2
+ // they match the server contract (probe-scan.controller.ts /
3
+ // probe-webhook.controller.ts / probe-usage.controller.ts /
4
+ // probe-webhook-delivery.service.ts) at compile time: any incompatible
5
+ // rename/removal on either side fails `npm run build` here. No jest runner
6
+ // in this SDK package; compile guard only (mirrors
7
+ // ../api/extraction-plan-preset.api.test.ts). Run: npx tsc --noEmit.
8
+
9
+ import {
10
+ ProbeScanVerdict,
11
+ ProbeScanMode,
12
+ ProbeScanStatus,
13
+ IProbeScanDetail,
14
+ IProbeScanHistoryItem,
15
+ IProbeWebhook,
16
+ IProbeWebhookDelivery,
17
+ IProbeWebhookDeliveryPayload,
18
+ IScanSyncData,
19
+ IScanAsyncData,
20
+ IUpdateProbeWebhookBody,
21
+ IProbeUsageData,
22
+ } from '..';
23
+ // estimateProbeScanCost lives in src/utils/ (a SIBLING of src/types/, not
24
+ // re-exported by the types barrel this file otherwise imports from) — see
25
+ // probe-scan-cost.utils.ts's own header comment for why it is a plain
26
+ // top-level export rather than a `sdk.probe.*` method.
27
+ import { estimateProbeScanCost } from '../../utils';
28
+
29
+ // Enum exhaustiveness: fails to compile if a member is added/removed/renamed
30
+ // here without updating this file — a cheap drift guard for values
31
+ // transported verbatim over the wire (this SDK does not control the
32
+ // server's enum, so a silent value drift is exactly what this must catch).
33
+ const _verdicts: Record<ProbeScanVerdict, true> = { clean: true, infected: true };
34
+ const _modes: Record<ProbeScanMode, true> = { sync: true, async: true };
35
+ const _statuses: Record<ProbeScanStatus, true> = {
36
+ queued: true,
37
+ scanning: true,
38
+ done: true,
39
+ error: true,
40
+ };
41
+
42
+ // GET /scan/:scanId — WS5-4: full metadata parity with IProbeScanHistoryItem
43
+ // (fileName/fileSize/mimeType/mode/startedAt/finishedAt/costUnits).
44
+ const _scanDetail: IProbeScanDetail = {
45
+ scanId: 's1',
46
+ status: ProbeScanStatus.DONE,
47
+ verdict: ProbeScanVerdict.CLEAN,
48
+ viruses: [],
49
+ context: null,
50
+ fileName: 'invoice.pdf',
51
+ fileSize: 1024,
52
+ mimeType: 'application/pdf',
53
+ mode: ProbeScanMode.SYNC,
54
+ startedAt: new Date(),
55
+ finishedAt: new Date(),
56
+ costUnits: 3,
57
+ };
58
+
59
+ // GET /scan history row — WS5-1: costUnits added.
60
+ const _historyItem: IProbeScanHistoryItem = {
61
+ scanId: 's1',
62
+ fileName: 'invoice.pdf',
63
+ fileSize: 1024,
64
+ mimeType: 'application/pdf',
65
+ verdict: ProbeScanVerdict.INFECTED,
66
+ viruses: ['Eicar-Test-Signature'],
67
+ mode: ProbeScanMode.ASYNC,
68
+ status: ProbeScanStatus.DONE,
69
+ context: { applicationFileId: 'af1' },
70
+ startedAt: new Date(),
71
+ finishedAt: new Date(),
72
+ costUnits: 1,
73
+ createdAt: new Date(),
74
+ };
75
+
76
+ // POST /scan — sync (200) / async (202) data shapes. WS5-1: costUnits added to the sync shape (always known/billed by the time a 200 is returned).
77
+ const _scanSyncData: IScanSyncData = {
78
+ scanId: 's1',
79
+ verdict: ProbeScanVerdict.CLEAN,
80
+ viruses: [],
81
+ costUnits: 3,
82
+ };
83
+ const _scanAsyncData: IScanAsyncData = { scanId: 's1', status: ProbeScanStatus.QUEUED };
84
+
85
+ // Webhook subscription — WS5-7: secret is now ALWAYS present (list/create/
86
+ // update) and the create response returns IProbeWebhook.
87
+ const _webhook: IProbeWebhook = {
88
+ id: 'w1',
89
+ callbackUrl: 'https://example.com/hook',
90
+ secret: 'shh',
91
+ active: true,
92
+ createdAt: new Date(),
93
+ };
94
+
95
+ // PATCH /webhook/:webhookId body (WS5-5) — every field optional (at least one required server-side).
96
+ const _updateBody: IUpdateProbeWebhookBody = { active: false };
97
+ const _updateBody2: IUpdateProbeWebhookBody = { callbackUrl: 'https://example.com/hook2' };
98
+
99
+ // Webhook delivery payload — the exact body signed by x-probe-signature
100
+ // (see verifyProbeWebhookSignature). WS5-1: costUnits added.
101
+ const _deliveryPayload: IProbeWebhookDeliveryPayload = {
102
+ scanId: 's1',
103
+ context: null,
104
+ verdict: ProbeScanVerdict.INFECTED,
105
+ viruses: ['Eicar-Test-Signature'],
106
+ costUnits: 5,
107
+ };
108
+
109
+ // GET /webhook/:webhookId/deliveries row (WS5-6) — a persisted delivery-attempt.
110
+ const _deliveryRecord: IProbeWebhookDelivery = {
111
+ id: 'd1',
112
+ webhookId: 'w1',
113
+ scanId: 's1',
114
+ url: 'https://example.com/hook',
115
+ statusCode: 200,
116
+ success: true,
117
+ attemptedAt: new Date(),
118
+ error: null,
119
+ createdAt: new Date(),
120
+ };
121
+ // webhookId is nullable (ad-hoc per-request callbackUrl with no matching registration).
122
+ const _deliveryRecordAdHoc: IProbeWebhookDelivery = { ..._deliveryRecord, webhookId: null };
123
+
124
+ // GET /usage data shape (WS5-3).
125
+ const _usage: IProbeUsageData = { used: 10, limit: 1000, remaining: 990 };
126
+ // -1 is the established "unlimited" sentinel (see estimateProbeScanCost's
127
+ // server-side counterpart, utils/billing-emit.util.ts#UNLIMITED_EXPIRY_DAYS).
128
+ const _usageUnlimited: IProbeUsageData = { used: 10, limit: -1, remaining: -1 };
129
+
130
+ // estimateProbeScanCost (WS5-2) — pure shared cost model, ASYNC must cost
131
+ // strictly less than SYNC for the same size (the scanner UI's "background
132
+ // analysis saves tokens" tooltip depends on this). A one-byte compile-time
133
+ // smoke check; the full behavioural suite lives in probe-scan-cost.utils.test.ts.
134
+ const _asyncCost: number = estimateProbeScanCost(5 * 1024 * 1024, ProbeScanMode.ASYNC);
135
+ const _syncCost: number = estimateProbeScanCost(5 * 1024 * 1024, ProbeScanMode.SYNC);
136
+ if (_asyncCost >= _syncCost) {
137
+ throw new Error('estimateProbeScanCost: ASYNC must cost strictly less than SYNC');
138
+ }
139
+
140
+ void _verdicts;
141
+ void _modes;
142
+ void _statuses;
143
+ void _scanDetail;
144
+ void _historyItem;
145
+ void _scanSyncData;
146
+ void _scanAsyncData;
147
+ void _webhook;
148
+ void _updateBody;
149
+ void _updateBody2;
150
+ void _deliveryPayload;
151
+ void _deliveryRecord;
152
+ void _deliveryRecordAdHoc;
153
+ void _usage;
154
+ void _usageUnlimited;
155
+
156
+ export {};
@@ -0,0 +1 @@
1
+ export type ValueOf<T> = T[keyof T];
@@ -0,0 +1,30 @@
1
+ import { Code, ErrorType } from '../types';
2
+
3
+ type ErrorParams = { code: Code; type: ErrorType; message?: string };
4
+
5
+ export class ServiceException extends Error {
6
+ private readonly code: Code;
7
+
8
+ private readonly type: ErrorType;
9
+
10
+ getCode(): Code {
11
+ return this.code;
12
+ }
13
+
14
+ getType(): ErrorType {
15
+ return this.type;
16
+ }
17
+
18
+ constructor(params: ErrorParams) {
19
+ super(params.message);
20
+ this.code = params.code;
21
+ this.type = params.type;
22
+ }
23
+ }
24
+
25
+ export const handleError = (error: Error | ErrorParams, _params?: ErrorParams): Error => {
26
+ if (error instanceof Error) {
27
+ return error;
28
+ }
29
+ return new ServiceException(error);
30
+ };
@@ -0,0 +1,4 @@
1
+ export * from './error.utils';
2
+ export * from './enum.utils';
3
+ export * from './probe-webhook-signature.utils';
4
+ export * from './probe-scan-cost.utils';
@@ -0,0 +1,101 @@
1
+ // ──────────────────────────────────────────────
2
+ // AbyssProbe scan cost model — pure, shared (client + server, no endpoint).
3
+ //
4
+ // Ported from abyss-storage's OWN weighted AV-scan cost model
5
+ // (`apps/api/src/services/av-scan-usage.ts#computeAvScanCost`, introduced in
6
+ // storage commit 317e4a0 "wire the weighted AV-scan quota", since made dead
7
+ // code there by the AV v3 Phase 3b-2 hand-off — "storage never bills —
8
+ // AbyssProbe does" — but the FORMULA itself is exactly what AbyssProbe's own
9
+ // weighted billing needs, so it is ported here verbatim rather than
10
+ // reinvented):
11
+ //
12
+ // cost = round( (BASE + K_MB * ceil(sizeOctet / 1 MiB)) * MODE_WEIGHT[mode] )
13
+ //
14
+ // ASYNC costs LESS than SYNC (MODE_WEIGHT.async=1 < MODE_WEIGHT.sync=3) — a
15
+ // synchronous scan holds the caller's request (and an engine worker) until
16
+ // the verdict and cannot be batched/load-balanced, so it costs more than an
17
+ // asynchronous (queued) scan of the SAME bytes. This is the numeric backing
18
+ // for the scanner UI's "l'analyse en arrière-plan économise des tokens"
19
+ // tooltip (WS1).
20
+ //
21
+ // PURE + DETERMINISTIC + no I/O: this is the SINGLE source of truth for
22
+ // AbyssProbe's scan cost, used on BOTH sides of the wire —
23
+ // - server (apps/api/src/services/probe-scan.service.ts): the REAL cost
24
+ // billed via recordProbeScanUsage and persisted on probe_scans.costUnits
25
+ // once a scan reaches a verdict (DONE).
26
+ // - client (the AbyssProbe UI, or any external caller): a cost PREVIEW
27
+ // before scanning — call this with the picked file's size and the
28
+ // intended mode to show the estimated token cost, matching exactly what
29
+ // the server will bill (no separate "estimate" formula to drift out of
30
+ // sync with the real one — same function, same constants, both sides).
31
+ //
32
+ // Deliberately NOT exposed as an HTTP endpoint (no `POST /scan/estimate`):
33
+ // the whole point of a pure function is that the client can compute it
34
+ // locally, instantly, with zero round-trip — see this package's root README
35
+ // note on `sdk.probe.*`'s HTTP-call-only convention; a helper like this one
36
+ // (and `verifyProbeWebhookSignature` before it) is instead a plain top-level
37
+ // export, not a `sdk.probe.*` method.
38
+ // ──────────────────────────────────────────────
39
+
40
+ import { ProbeScanMode } from '../types';
41
+
42
+ /** Flat floor every scanned file pays (the "one scan" cost). Tunable. */
43
+ export const PROBE_SCAN_COST_BASE = 1;
44
+
45
+ /** Additional units per (ceil'd) mebibyte of scanned bytes. Tunable. */
46
+ export const PROBE_SCAN_COST_K_MB = 1;
47
+
48
+ /**
49
+ * Per-mode cost multiplier. A synchronous scan blocks the caller's request
50
+ * (and an engine worker) until the verdict and cannot be queued/batched, so
51
+ * it costs strictly MORE than an asynchronous scan of the same bytes —
52
+ * ASYNC < SYNC is a load-bearing invariant relied on by the scanner UI's
53
+ * "background analysis saves tokens" messaging (WS1). Tunable, but this
54
+ * ordering must never be inverted.
55
+ */
56
+ export const PROBE_SCAN_COST_MODE_WEIGHT: Record<ProbeScanMode, number> = {
57
+ [ProbeScanMode.ASYNC]: 1,
58
+ [ProbeScanMode.SYNC]: 3,
59
+ };
60
+
61
+ /** One mebibyte, the unit the per-MB term is quantised to. */
62
+ const ONE_MB = 1024 * 1024;
63
+
64
+ /**
65
+ * Weighted cost of one AbyssProbe scan, in `ACCOUNT_AV_SCAN_UNITS` ("tokens"
66
+ * in the UI). Pure + deterministic — same inputs always produce the same
67
+ * output, no I/O, safe to call from a browser or a server.
68
+ *
69
+ * Returns `0` for a non-finite / non-positive `sizeOctet` (nothing to scan,
70
+ * nothing to bill) rather than throwing — a defensive, never-crash contract
71
+ * appropriate for a client-side cost preview that might run ahead of full
72
+ * input validation (e.g. while a file is still being selected).
73
+ *
74
+ * `mode` defaults to the (cheaper) ASYNC weight when given an unrecognised
75
+ * value, mirroring the ported formula's own `MODE_WEIGHT[mode] ?? MODE_WEIGHT.async`
76
+ * fallback — never silently the MORE expensive weight.
77
+ *
78
+ * `mode`'s type is widened to `| 'sync' | 'async'` alongside the enum
79
+ * itself, NOT just `ProbeScanMode`: apps/api's own server-side
80
+ * `database/probe-scan.enum.ts#ProbeScanMode` is a SEPARATE TypeScript enum
81
+ * declaration (kept server-local — see that file's header comment on why —
82
+ * with the identical 'sync'/'async' runtime values, so the wire format never
83
+ * drifts). TypeScript string enums are nominal: a same-valued member of that
84
+ * OTHER enum is not directly assignable to THIS package's `ProbeScanMode`
85
+ * parameter type, but IS assignable to a plain string-literal type matching
86
+ * its value — so the server can call this exact function (`scan.mode`,
87
+ * `estimateProbeScanCost`'s whole reason for living being ONE shared formula
88
+ * on both sides of the wire, see this file's header comment) without a cast.
89
+ */
90
+ export const estimateProbeScanCost = (
91
+ sizeOctet: number,
92
+ mode: ProbeScanMode | 'sync' | 'async',
93
+ ): number => {
94
+ if (!Number.isFinite(sizeOctet) || sizeOctet <= 0) {
95
+ return 0;
96
+ }
97
+ const megabytes = Math.ceil(sizeOctet / ONE_MB);
98
+ const weight =
99
+ PROBE_SCAN_COST_MODE_WEIGHT[mode] ?? PROBE_SCAN_COST_MODE_WEIGHT[ProbeScanMode.ASYNC];
100
+ return Math.round((PROBE_SCAN_COST_BASE + PROBE_SCAN_COST_K_MB * megabytes) * weight);
101
+ };
@@ -0,0 +1,56 @@
1
+ // ──────────────────────────────────────────────
2
+ // AbyssProbe webhook signature verification (helper for RECEIVERS of a
3
+ // webhook delivery — the abyss-main UI/abyss-storage/any external
4
+ // integrator that registered a callbackUrl).
5
+ //
6
+ // Mirrors this package's own extraction-webhook.utils.ts
7
+ // (verifyExtractionWebhook) — the same package's own precedent for this
8
+ // exact problem — adapted to AbyssProbe's actual wire format: the signature
9
+ // header (see PROBE_WEBHOOK_SIGNATURE_HEADER in this package's root index)
10
+ // carries the RAW hex HMAC digest with no `sha256=` prefix (unlike
11
+ // the extraction signature header `x-rcb-signature: sha256=<hex>`) — see
12
+ // apps/api/src/services/probe-webhook-delivery.service.ts's `sign()`.
13
+ //
14
+ // Lazy-requires `crypto` so the SDK stays browser-compatible when this
15
+ // utility is never invoked (a browser page is never the receiving end of a
16
+ // server-to-server webhook).
17
+ // ──────────────────────────────────────────────
18
+
19
+ export interface VerifyProbeWebhookSignatureInput {
20
+ /** The exact bytes/string the receiver's HTTP framework handed it — must be the RAW body, not a re-serialized JSON.parse/stringify round trip (whitespace/key-order would change the HMAC). */
21
+ rawBody: string | Buffer;
22
+ /** The incoming `x-probe-signature` header value. */
23
+ signatureHeader: string | undefined;
24
+ /** This webhook registration's secret (re-displayable on IProbeWebhook). */
25
+ secret: string;
26
+ }
27
+
28
+ /**
29
+ * Recompute the HMAC-SHA256 of `rawBody` with `secret` and constant-time
30
+ * compare it against `signatureHeader`. Returns `false` (never throws) for
31
+ * any malformed input — a hostile/truncated header must not crash the
32
+ * receiver.
33
+ */
34
+ export function verifyProbeWebhookSignature(input: VerifyProbeWebhookSignatureInput): boolean {
35
+ if (!input.signatureHeader || !input.secret) return false;
36
+
37
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
38
+ const crypto = require('crypto');
39
+ const computed: string = crypto
40
+ .createHmac('sha256', input.secret)
41
+ .update(input.rawBody)
42
+ .digest('hex');
43
+
44
+ if (input.signatureHeader.length !== computed.length) return false;
45
+
46
+ try {
47
+ return crypto.timingSafeEqual(
48
+ Buffer.from(input.signatureHeader, 'hex'),
49
+ Buffer.from(computed, 'hex'),
50
+ );
51
+ } catch {
52
+ // Buffer.from(..., 'hex') on a non-hex string yields a shorter buffer,
53
+ // which would otherwise make timingSafeEqual throw on a length mismatch.
54
+ return false;
55
+ }
56
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ // Perimetre de VERIFICATION, distinct de celui du build.
3
+ //
4
+ // `tsconfig.json` exclut `src/**/*.spec.ts` parce qu'il sert a emettre `dist/`, ou une spec
5
+ // n'a rien a faire. Mais eslint s'appuie sur ce meme fichier via `parserOptions.project` :
6
+ // les cinq specs du paquet sortaient donc en « Parsing error: that TSConfig does not include
7
+ // this file », mesure du 2026-09-09, et n'etaient lintees par personne.
8
+ //
9
+ // Ce fichier sert uniquement a eslint. Il n'emet rien et ne change pas ce que `build` produit.
10
+ "extends": "./tsconfig.json",
11
+ "compilerOptions": {
12
+ "noEmit": true
13
+ },
14
+ "exclude": ["./dist/**/*"]
15
+ }
@@ -1 +0,0 @@
1
- export * from './probe-webhook-delivery.dto';
@@ -1,18 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./probe-webhook-delivery.dto"), exports);
18
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/types/interface/dto/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,+DAA6C"}
@@ -1,7 +0,0 @@
1
- import { ProbeScanVerdict } from '../../enum';
2
- export interface IProbeWebhookDeliveryPayload {
3
- scanId: string;
4
- context: Record<string, unknown> | null;
5
- verdict: ProbeScanVerdict;
6
- viruses: string[];
7
- }
@@ -1 +0,0 @@
1
- {"version":3,"file":"probe-webhook-delivery.dto.js","sourceRoot":"","sources":["../../../../src/types/interface/dto/probe-webhook-delivery.dto.ts"],"names":[],"mappings":""}
@@ -1 +0,0 @@
1
- {"version":3,"file":"probe-scan.model.js","sourceRoot":"","sources":["../../../../src/types/interface/models/probe-scan.model.ts"],"names":[],"mappings":""}
@@ -1 +0,0 @@
1
- {"version":3,"file":"probe-webhook.model.js","sourceRoot":"","sources":["../../../../src/types/interface/models/probe-webhook.model.ts"],"names":[],"mappings":""}
@@ -1,3 +0,0 @@
1
- export declare const API_KEY_HEADER = "abyss-api-key";
2
- export declare function authHeader(apiKey?: string): Record<string, string>;
3
- export declare function serializeProbeQuery<T extends object>(query: T): Record<string, unknown>;
@@ -1,20 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.serializeProbeQuery = exports.authHeader = exports.API_KEY_HEADER = void 0;
4
- exports.API_KEY_HEADER = 'abyss-api-key';
5
- function authHeader(apiKey) {
6
- return apiKey ? { [exports.API_KEY_HEADER]: apiKey } : {};
7
- }
8
- exports.authHeader = authHeader;
9
- function serializeProbeQuery(query) {
10
- const out = {};
11
- for (const [key, value] of Object.entries(query)) {
12
- if (value === undefined || value === null)
13
- continue;
14
- const wireKey = key === 'organizationId' ? 'organization_id' : key;
15
- out[wireKey] = value instanceof Date ? value.toISOString() : value;
16
- }
17
- return out;
18
- }
19
- exports.serializeProbeQuery = serializeProbeQuery;
20
- //# sourceMappingURL=http.utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"http.utils.js","sourceRoot":"","sources":["../../src/utils/http.utils.ts"],"names":[],"mappings":";;;AAQa,QAAA,cAAc,GAAG,eAAe,CAAC;AAS9C,SAAgB,UAAU,CAAC,MAAe;IACxC,OAAO,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,sBAAc,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AACpD,CAAC;AAFD,gCAEC;AASD,SAAgB,mBAAmB,CAAmB,KAAQ;IAC5D,MAAM,GAAG,GAA4B,EAAE,CAAC;IACxC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAgC,CAAC,EAAE,CAAC;QAC5E,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI;YAAE,SAAS;QACpD,MAAM,OAAO,GAAG,GAAG,KAAK,gBAAgB,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,GAAG,CAAC;QACnE,GAAG,CAAC,OAAO,CAAC,GAAG,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;IACrE,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AARD,kDAQC"}