@molecule/api-ai-moderation-pipeline 1.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.
- package/LICENSE +115 -0
- package/dist/browser-guard.d.ts +2 -0
- package/dist/browser-guard.d.ts.map +1 -0
- package/dist/browser-guard.js +18 -0
- package/dist/index.d.ts +47 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +46 -0
- package/dist/pipeline.d.ts +43 -0
- package/dist/pipeline.d.ts.map +1 -0
- package/dist/pipeline.js +230 -0
- package/dist/types.d.ts +84 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +1 -0
- package/package.json +45 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work.
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship.
|
|
43
|
+
|
|
44
|
+
"Contribution" shall mean any work of authorship, including the
|
|
45
|
+
original version of the Work and any modifications or additions
|
|
46
|
+
to that Work, that is intentionally submitted to the Licensor for
|
|
47
|
+
inclusion in the Work by the copyright owner or by an individual or
|
|
48
|
+
Legal Entity authorized to submit on behalf of the copyright owner.
|
|
49
|
+
|
|
50
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
51
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
52
|
+
subsequently incorporated within the Work.
|
|
53
|
+
|
|
54
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
55
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
56
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
57
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
58
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
59
|
+
Work and such Derivative Works in Source or Object form.
|
|
60
|
+
|
|
61
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
62
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
63
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
64
|
+
patent license to make, have made, use, offer to sell, sell, import,
|
|
65
|
+
and otherwise transfer the Work.
|
|
66
|
+
|
|
67
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
68
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
69
|
+
modifications, and in Source or Object form, provided that You
|
|
70
|
+
meet the following conditions:
|
|
71
|
+
|
|
72
|
+
(a) You must give any other recipients of the Work or
|
|
73
|
+
Derivative Works a copy of this License; and
|
|
74
|
+
|
|
75
|
+
(b) You must cause any modified files to carry prominent notices
|
|
76
|
+
stating that You changed the files; and
|
|
77
|
+
|
|
78
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
79
|
+
that You distribute, all copyright, patent, trademark, and
|
|
80
|
+
attribution notices from the Source form of the Work,
|
|
81
|
+
excluding those notices that do not pertain to any part of
|
|
82
|
+
the Derivative Works; and
|
|
83
|
+
|
|
84
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
85
|
+
distribution, then any Derivative Works that You distribute must
|
|
86
|
+
include a readable copy of the attribution notices contained
|
|
87
|
+
within such NOTICE file.
|
|
88
|
+
|
|
89
|
+
5. Submission of Contributions.
|
|
90
|
+
|
|
91
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
92
|
+
names, trademarks, service marks, or product names of the Licensor.
|
|
93
|
+
|
|
94
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
95
|
+
agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
|
|
96
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
|
|
97
|
+
|
|
98
|
+
8. Limitation of Liability. In no event and under no legal theory shall
|
|
99
|
+
any Contributor be liable to You for damages.
|
|
100
|
+
|
|
101
|
+
9. Accepting Warranty or Additional Liability.
|
|
102
|
+
|
|
103
|
+
Copyright 2026 Molecule Dev, Inc.
|
|
104
|
+
|
|
105
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
106
|
+
you may not use this file except in compliance with the License.
|
|
107
|
+
You may obtain a copy of the License at
|
|
108
|
+
|
|
109
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
110
|
+
|
|
111
|
+
Unless required by applicable law or agreed to in writing, software
|
|
112
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
113
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
114
|
+
See the License for the specific language governing permissions and
|
|
115
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser guard — `@molecule/api-ai-moderation-pipeline` is SERVER-ONLY.
|
|
3
|
+
*
|
|
4
|
+
* Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
|
|
5
|
+
* Evaluating a server package in a browser bundle is always an import-graph mistake
|
|
6
|
+
* (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
|
|
7
|
+
* ("Buffer is not defined") far from the culprit. Throwing here names the package and
|
|
8
|
+
* the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
|
|
9
|
+
* unaffected: the throw requires browser globals AND the absence of a node runtime.
|
|
10
|
+
*/
|
|
11
|
+
const g = globalThis;
|
|
12
|
+
if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
|
|
13
|
+
throw new Error('@molecule/api-ai-moderation-pipeline is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
|
|
14
|
+
'from server code (a server route/function or your API), or dynamic-import it inside ' +
|
|
15
|
+
'the server handler — never from components or shared client modules, and never ' +
|
|
16
|
+
'polyfill Buffer/process to silence this.');
|
|
17
|
+
}
|
|
18
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@molecule/api-ai-moderation-pipeline` — content moderation built on
|
|
3
|
+
* the bonded AI provider. Classify → policy-match → action → audit-log.
|
|
4
|
+
*
|
|
5
|
+
* Extracted from ai-content-moderator flagship.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { moderate, DEFAULT_POLICY } from '@molecule/api-ai-moderation-pipeline'
|
|
10
|
+
*
|
|
11
|
+
* const decision = await moderate({
|
|
12
|
+
* content: userComment,
|
|
13
|
+
* ownerId: userId,
|
|
14
|
+
* resource: { type: 'comment', id: commentId },
|
|
15
|
+
* })
|
|
16
|
+
* if (decision.action === 'block') return res.status(403).end()
|
|
17
|
+
* if (decision.action === 'flag') void notifyMods(decision)
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* @remarks
|
|
21
|
+
* Tables: `src/__setup__/moderation_audit_log.sql` creates
|
|
22
|
+
* `moderation_audit_log`. An mlcl-scaffolded API replays `__setup__/*.sql`
|
|
23
|
+
* automatically on migrate; anywhere else run it once. Audit writes are
|
|
24
|
+
* best-effort (a DB failure never blocks the moderation decision) but are NO
|
|
25
|
+
* LONGER silent: a failed write is logged via `logger.warn({ error })`, so a
|
|
26
|
+
* missing table surfaces in logs instead of vanishing.
|
|
27
|
+
*
|
|
28
|
+
* Requires a bonded `ai` chat provider (`@molecule/api-ai`) — `classify()` /
|
|
29
|
+
* `moderate()` throw if none is bonded (a misconfiguration, surfaced loudly).
|
|
30
|
+
*
|
|
31
|
+
* FAILS SAFE on classifier failure. When the classifier can't produce a signal
|
|
32
|
+
* — a provider error/timeout, an in-band `error` stream event, or malformed
|
|
33
|
+
* model output — `classify()` returns empty `scores` WITH `error` set, and
|
|
34
|
+
* `moderate()` routes per `policy.onError`, ALWAYS logging the failure via
|
|
35
|
+
* `logger.error({ error })`. `onError` defaults to `'flag'` (route to human
|
|
36
|
+
* review — never a silent allow); set `'block'` to fail closed or `'allow'` to
|
|
37
|
+
* explicitly opt into fail-open. The env var `MODERATION_ON_ERROR` overrides
|
|
38
|
+
* the default when a policy omits `onError`. Such decisions carry
|
|
39
|
+
* `errored: true`. Direct `classify()` callers (bypassing `moderate()`) MUST
|
|
40
|
+
* check `result.error` before trusting empty `scores`.
|
|
41
|
+
*
|
|
42
|
+
* @module
|
|
43
|
+
*/
|
|
44
|
+
export * from './browser-guard.js';
|
|
45
|
+
export * from './pipeline.js';
|
|
46
|
+
export * from './types.js';
|
|
47
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@molecule/api-ai-moderation-pipeline` — content moderation built on
|
|
3
|
+
* the bonded AI provider. Classify → policy-match → action → audit-log.
|
|
4
|
+
*
|
|
5
|
+
* Extracted from ai-content-moderator flagship.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { moderate, DEFAULT_POLICY } from '@molecule/api-ai-moderation-pipeline'
|
|
10
|
+
*
|
|
11
|
+
* const decision = await moderate({
|
|
12
|
+
* content: userComment,
|
|
13
|
+
* ownerId: userId,
|
|
14
|
+
* resource: { type: 'comment', id: commentId },
|
|
15
|
+
* })
|
|
16
|
+
* if (decision.action === 'block') return res.status(403).end()
|
|
17
|
+
* if (decision.action === 'flag') void notifyMods(decision)
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* @remarks
|
|
21
|
+
* Tables: `src/__setup__/moderation_audit_log.sql` creates
|
|
22
|
+
* `moderation_audit_log`. An mlcl-scaffolded API replays `__setup__/*.sql`
|
|
23
|
+
* automatically on migrate; anywhere else run it once. Audit writes are
|
|
24
|
+
* best-effort (a DB failure never blocks the moderation decision) but are NO
|
|
25
|
+
* LONGER silent: a failed write is logged via `logger.warn({ error })`, so a
|
|
26
|
+
* missing table surfaces in logs instead of vanishing.
|
|
27
|
+
*
|
|
28
|
+
* Requires a bonded `ai` chat provider (`@molecule/api-ai`) — `classify()` /
|
|
29
|
+
* `moderate()` throw if none is bonded (a misconfiguration, surfaced loudly).
|
|
30
|
+
*
|
|
31
|
+
* FAILS SAFE on classifier failure. When the classifier can't produce a signal
|
|
32
|
+
* — a provider error/timeout, an in-band `error` stream event, or malformed
|
|
33
|
+
* model output — `classify()` returns empty `scores` WITH `error` set, and
|
|
34
|
+
* `moderate()` routes per `policy.onError`, ALWAYS logging the failure via
|
|
35
|
+
* `logger.error({ error })`. `onError` defaults to `'flag'` (route to human
|
|
36
|
+
* review — never a silent allow); set `'block'` to fail closed or `'allow'` to
|
|
37
|
+
* explicitly opt into fail-open. The env var `MODERATION_ON_ERROR` overrides
|
|
38
|
+
* the default when a policy omits `onError`. Such decisions carry
|
|
39
|
+
* `errored: true`. Direct `classify()` callers (bypassing `moderate()`) MUST
|
|
40
|
+
* check `result.error` before trusting empty `scores`.
|
|
41
|
+
*
|
|
42
|
+
* @module
|
|
43
|
+
*/
|
|
44
|
+
export * from './browser-guard.js';
|
|
45
|
+
export * from './pipeline.js';
|
|
46
|
+
export * from './types.js';
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI content-moderation pipeline.
|
|
3
|
+
*
|
|
4
|
+
* Pipe content through:
|
|
5
|
+
* 1. AI classifier — scores categories
|
|
6
|
+
* 2. Policy matcher — checks thresholds
|
|
7
|
+
* 3. Action decision — allow / flag / block / redact
|
|
8
|
+
* 4. Audit log — records what was decided + why
|
|
9
|
+
*
|
|
10
|
+
* @module
|
|
11
|
+
*/
|
|
12
|
+
import type { ClassificationResult, ModerationDecision, ModerationPolicy, ModerationScore } from './types.js';
|
|
13
|
+
/** Default moderation policy applied when no explicit policy is provided. */
|
|
14
|
+
export declare const DEFAULT_POLICY: ModerationPolicy;
|
|
15
|
+
/**
|
|
16
|
+
* Classify content using the bonded AI provider.
|
|
17
|
+
*
|
|
18
|
+
* On a provider error/timeout, an in-band `error` stream event, or malformed
|
|
19
|
+
* model output, this resolves to empty `scores` with `error` set — it does NOT
|
|
20
|
+
* throw and does NOT fabricate a benign result. `moderate()` routes that
|
|
21
|
+
* failure per `policy.onError`; direct callers MUST check `result.error` before
|
|
22
|
+
* trusting an empty-scores result (an empty result with no `error` means the
|
|
23
|
+
* model genuinely scored everything at 0).
|
|
24
|
+
*
|
|
25
|
+
* @param content - The content to classify.
|
|
26
|
+
* @returns The classification result — scores + reasoning, or `error` on failure.
|
|
27
|
+
*/
|
|
28
|
+
export declare function classify(content: string): Promise<ClassificationResult>;
|
|
29
|
+
/** Apply a policy to classifier scores → moderation decision. */
|
|
30
|
+
export declare function applyPolicy(scores: ModerationScore[], reasoning: string, policy?: ModerationPolicy): ModerationDecision;
|
|
31
|
+
/** Full pipeline — classify + decide + audit. Returns the decision. */
|
|
32
|
+
export declare function moderate(opts: {
|
|
33
|
+
content: string;
|
|
34
|
+
policy?: ModerationPolicy;
|
|
35
|
+
ownerId?: string | null;
|
|
36
|
+
resource?: {
|
|
37
|
+
type: string;
|
|
38
|
+
id: string;
|
|
39
|
+
};
|
|
40
|
+
/** Whether to write the audit log row. Defaults to true. */
|
|
41
|
+
audit?: boolean;
|
|
42
|
+
}): Promise<ModerationDecision>;
|
|
43
|
+
//# sourceMappingURL=pipeline.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pipeline.d.ts","sourceRoot":"","sources":["../src/pipeline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAMH,OAAO,KAAK,EAEV,oBAAoB,EAEpB,kBAAkB,EAElB,gBAAgB,EAChB,eAAe,EAChB,MAAM,YAAY,CAAA;AAqCnB,6EAA6E;AAC7E,eAAO,MAAM,cAAc,EAAE,gBAe5B,CAAA;AAmBD;;;;;;;;;;;;GAYG;AACH,wBAAsB,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAkE7E;AAED,iEAAiE;AACjE,wBAAgB,WAAW,CACzB,MAAM,EAAE,eAAe,EAAE,EACzB,SAAS,EAAE,MAAM,EACjB,MAAM,GAAE,gBAAiC,GACxC,kBAAkB,CAqBpB;AAED,uEAAuE;AACvE,wBAAsB,QAAQ,CAAC,IAAI,EAAE;IACnC,OAAO,EAAE,MAAM,CAAA;IACf,MAAM,CAAC,EAAE,gBAAgB,CAAA;IACzB,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACvB,QAAQ,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAA;IACvC,4DAA4D;IAC5D,KAAK,CAAC,EAAE,OAAO,CAAA;CAChB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAsD9B"}
|
package/dist/pipeline.js
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI content-moderation pipeline.
|
|
3
|
+
*
|
|
4
|
+
* Pipe content through:
|
|
5
|
+
* 1. AI classifier — scores categories
|
|
6
|
+
* 2. Policy matcher — checks thresholds
|
|
7
|
+
* 3. Action decision — allow / flag / block / redact
|
|
8
|
+
* 4. Audit log — records what was decided + why
|
|
9
|
+
*
|
|
10
|
+
* @module
|
|
11
|
+
*/
|
|
12
|
+
import { requireProvider as requireAI } from '@molecule/api-ai';
|
|
13
|
+
import { create } from '@molecule/api-database';
|
|
14
|
+
import { logger } from '@molecule/api-logger';
|
|
15
|
+
const AUDIT_TABLE = 'moderation_audit_log';
|
|
16
|
+
/**
|
|
17
|
+
* Behavior when the classifier fails and no real moderation signal exists.
|
|
18
|
+
* `'flag'` (route to human review) is the safe default: a moderation control
|
|
19
|
+
* must NOT silently allow un-moderated content on a transient classifier blip,
|
|
20
|
+
* yet a hard `'block'` on every failure would break legitimate flows. The error
|
|
21
|
+
* is always logged; `'allow'` (fail-open) and `'block'` (fail-closed) are
|
|
22
|
+
* explicit opt-ins. See {@link ModerationPolicy.onError}.
|
|
23
|
+
*/
|
|
24
|
+
const DEFAULT_ON_ERROR = 'flag';
|
|
25
|
+
const CLASSIFY_PROMPT = `You are a content moderation classifier.
|
|
26
|
+
|
|
27
|
+
Score the following content from 0.0 (none) to 1.0 (extreme) for each category:
|
|
28
|
+
- hate (slurs, dehumanization)
|
|
29
|
+
- harassment (targeted abuse)
|
|
30
|
+
- sexual (explicit sexual content)
|
|
31
|
+
- self_harm (self-harm / suicide encouragement)
|
|
32
|
+
- violence (gore, threats of violence)
|
|
33
|
+
- illegal (illegal activity)
|
|
34
|
+
- spam (commercial spam, links, repetition)
|
|
35
|
+
- misinformation (knowingly false claims about real-world events)
|
|
36
|
+
- pii (personally identifiable information — emails, phone, address, SSN)
|
|
37
|
+
|
|
38
|
+
Respond with ONLY a JSON object mapping each category to its score and a brief reasoning string.
|
|
39
|
+
Format:
|
|
40
|
+
{
|
|
41
|
+
"scores": { "hate": 0.0, "harassment": 0.0, "sexual": 0.0, "self_harm": 0.0, "violence": 0.0, "illegal": 0.0, "spam": 0.0, "misinformation": 0.0, "pii": 0.0 },
|
|
42
|
+
"reasoning": "..."
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
Content:
|
|
46
|
+
{{CONTENT}}`;
|
|
47
|
+
/** Default moderation policy applied when no explicit policy is provided. */
|
|
48
|
+
export const DEFAULT_POLICY = {
|
|
49
|
+
thresholds: {
|
|
50
|
+
hate: 0.7,
|
|
51
|
+
harassment: 0.7,
|
|
52
|
+
sexual: 0.85,
|
|
53
|
+
self_harm: 0.6,
|
|
54
|
+
violence: 0.8,
|
|
55
|
+
illegal: 0.7,
|
|
56
|
+
spam: 0.9,
|
|
57
|
+
misinformation: 0.8,
|
|
58
|
+
pii: 0.7,
|
|
59
|
+
},
|
|
60
|
+
action: 'flag',
|
|
61
|
+
defaultAction: 'allow',
|
|
62
|
+
onError: 'flag',
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* Resolves the effective {@link ModerationErrorAction} from an explicit policy
|
|
66
|
+
* value, then the `MODERATION_ON_ERROR` env var, defaulting to
|
|
67
|
+
* {@link DEFAULT_ON_ERROR}. Only the exact strings `'allow'`/`'block'`/`'flag'`
|
|
68
|
+
* are honored; anything else falls through to the default.
|
|
69
|
+
*
|
|
70
|
+
* @param policy - The active moderation policy, if any.
|
|
71
|
+
* @returns The effective action to take on classifier failure.
|
|
72
|
+
*/
|
|
73
|
+
function resolveErrorAction(policy) {
|
|
74
|
+
if (policy?.onError)
|
|
75
|
+
return policy.onError;
|
|
76
|
+
const env = typeof process !== 'undefined' ? process.env?.MODERATION_ON_ERROR?.toLowerCase() : undefined;
|
|
77
|
+
if (env === 'allow' || env === 'block' || env === 'flag')
|
|
78
|
+
return env;
|
|
79
|
+
return DEFAULT_ON_ERROR;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Classify content using the bonded AI provider.
|
|
83
|
+
*
|
|
84
|
+
* On a provider error/timeout, an in-band `error` stream event, or malformed
|
|
85
|
+
* model output, this resolves to empty `scores` with `error` set — it does NOT
|
|
86
|
+
* throw and does NOT fabricate a benign result. `moderate()` routes that
|
|
87
|
+
* failure per `policy.onError`; direct callers MUST check `result.error` before
|
|
88
|
+
* trusting an empty-scores result (an empty result with no `error` means the
|
|
89
|
+
* model genuinely scored everything at 0).
|
|
90
|
+
*
|
|
91
|
+
* @param content - The content to classify.
|
|
92
|
+
* @returns The classification result — scores + reasoning, or `error` on failure.
|
|
93
|
+
*/
|
|
94
|
+
export async function classify(content) {
|
|
95
|
+
const ai = requireAI();
|
|
96
|
+
let raw = '';
|
|
97
|
+
let streamError = null;
|
|
98
|
+
try {
|
|
99
|
+
for await (const event of ai.chat({
|
|
100
|
+
messages: [{ role: 'user', content: CLASSIFY_PROMPT.replace('{{CONTENT}}', content) }],
|
|
101
|
+
temperature: 0,
|
|
102
|
+
})) {
|
|
103
|
+
// A ChatEvent's text payload is `content` (NOT `text`, which is the
|
|
104
|
+
// ContentBlock shape) — reading `event.text` accumulated nothing.
|
|
105
|
+
if (event.type === 'text')
|
|
106
|
+
raw += event.content;
|
|
107
|
+
else if (event.type === 'error') {
|
|
108
|
+
// In-band provider error — the classifier did not produce a usable
|
|
109
|
+
// signal. Capture it so the caller fails per policy, never silently.
|
|
110
|
+
streamError = new Error(event.message ?? 'AI provider returned an error event');
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
// The chat call/stream threw (connection error, timeout, aborted). Same as
|
|
116
|
+
// an in-band error: no usable signal — surface it, don't swallow it.
|
|
117
|
+
streamError = error instanceof Error ? error : new Error(String(error));
|
|
118
|
+
}
|
|
119
|
+
if (streamError) {
|
|
120
|
+
return {
|
|
121
|
+
scores: [],
|
|
122
|
+
reasoning: `classifier failed: ${streamError.message}`,
|
|
123
|
+
error: streamError,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
try {
|
|
127
|
+
// Extract the JSON object even when the model wraps it in prose and/or a
|
|
128
|
+
// markdown fence (LLMs commonly add "Here is the result:" or trailing
|
|
129
|
+
// remarks). Prefer fenced content, then slice first `{` to last `}` — a bare
|
|
130
|
+
// fence-strip fails on prose around the block.
|
|
131
|
+
const fenced = raw.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
|
132
|
+
const jsonBody = (fenced ? fenced[1] : raw).trim();
|
|
133
|
+
// Slice the outermost JSON value — object OR array — out of any prose.
|
|
134
|
+
const objAt = jsonBody.indexOf('{');
|
|
135
|
+
const arrAt = jsonBody.indexOf('[');
|
|
136
|
+
const useArray = arrAt >= 0 && (objAt < 0 || arrAt < objAt);
|
|
137
|
+
const valStart = useArray ? arrAt : objAt;
|
|
138
|
+
const valEnd = jsonBody.lastIndexOf(useArray ? ']' : '}');
|
|
139
|
+
const json = valStart >= 0 && valEnd > valStart ? jsonBody.slice(valStart, valEnd + 1) : jsonBody;
|
|
140
|
+
const parsed = JSON.parse(json);
|
|
141
|
+
const scores = Object.entries(parsed.scores).map(([category, score]) => ({
|
|
142
|
+
category: category,
|
|
143
|
+
score: Math.max(0, Math.min(1, Number(score) || 0)),
|
|
144
|
+
}));
|
|
145
|
+
return { scores, reasoning: parsed.reasoning ?? '' };
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
// The model returned non-JSON or structurally invalid output — there is no
|
|
149
|
+
// usable moderation signal. Return empty scores WITH `error` set so the
|
|
150
|
+
// pipeline routes per policy.onError instead of treating this as an allow.
|
|
151
|
+
return {
|
|
152
|
+
scores: [],
|
|
153
|
+
reasoning: 'classifier returned malformed JSON',
|
|
154
|
+
error: error instanceof Error ? error : new Error('classifier returned malformed JSON'),
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/** Apply a policy to classifier scores → moderation decision. */
|
|
159
|
+
export function applyPolicy(scores, reasoning, policy = DEFAULT_POLICY) {
|
|
160
|
+
let matched = null;
|
|
161
|
+
let maxOver = 0;
|
|
162
|
+
for (const s of scores) {
|
|
163
|
+
const threshold = policy.thresholds[s.category];
|
|
164
|
+
if (threshold === undefined)
|
|
165
|
+
continue;
|
|
166
|
+
if (s.score >= threshold) {
|
|
167
|
+
const over = s.score - threshold;
|
|
168
|
+
if (matched === null || over > maxOver) {
|
|
169
|
+
maxOver = over;
|
|
170
|
+
matched = s.category;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
action: matched ? policy.action : (policy.defaultAction ?? 'allow'),
|
|
176
|
+
scores,
|
|
177
|
+
reasoning,
|
|
178
|
+
matched_category: matched,
|
|
179
|
+
flagged: !!matched,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
/** Full pipeline — classify + decide + audit. Returns the decision. */
|
|
183
|
+
export async function moderate(opts) {
|
|
184
|
+
const policy = opts.policy ?? DEFAULT_POLICY;
|
|
185
|
+
const result = await classify(opts.content);
|
|
186
|
+
let decision;
|
|
187
|
+
if (result.error) {
|
|
188
|
+
// The classifier failed — there is NO real moderation signal. Route per
|
|
189
|
+
// policy.onError instead of silently allowing un-moderated content, and
|
|
190
|
+
// ALWAYS log the failure loudly (the real bug was swallowing it).
|
|
191
|
+
const onError = resolveErrorAction(policy);
|
|
192
|
+
logger.error(`[api-ai-moderation-pipeline] classifier failed; applying onError='${onError}' ` +
|
|
193
|
+
`(content ${onError === 'block' ? 'BLOCKED' : onError === 'flag' ? 'FLAGGED for review' : 'ALLOWED un-moderated'}). ` +
|
|
194
|
+
'Moderation is degraded until the classifier recovers.', { error: result.error });
|
|
195
|
+
decision = {
|
|
196
|
+
action: onError,
|
|
197
|
+
scores: result.scores,
|
|
198
|
+
reasoning: result.reasoning,
|
|
199
|
+
matched_category: null,
|
|
200
|
+
flagged: onError !== 'allow',
|
|
201
|
+
errored: true,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
decision = applyPolicy(result.scores, result.reasoning, policy);
|
|
206
|
+
}
|
|
207
|
+
if (opts.audit !== false) {
|
|
208
|
+
try {
|
|
209
|
+
await create(AUDIT_TABLE, {
|
|
210
|
+
owner_id: opts.ownerId ?? null,
|
|
211
|
+
content_excerpt: opts.content.slice(0, 500),
|
|
212
|
+
decision: decision.action,
|
|
213
|
+
matched_category: decision.matched_category,
|
|
214
|
+
scores: decision.scores,
|
|
215
|
+
reasoning: decision.reasoning,
|
|
216
|
+
resource_type: opts.resource?.type ?? null,
|
|
217
|
+
resource_id: opts.resource?.id ?? null,
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
// Audit is best-effort — a DB write failure must not block the moderation
|
|
222
|
+
// decision returned to the caller — but it must NEVER be silently dropped:
|
|
223
|
+
// an unwritten audit row is a lost compliance/security record, so warn
|
|
224
|
+
// with the error (the decision itself still stands).
|
|
225
|
+
logger.warn(`[api-ai-moderation-pipeline] audit-log write to '${AUDIT_TABLE}' failed; ` +
|
|
226
|
+
'the moderation decision still stands but no audit row was recorded.', { error });
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return decision;
|
|
230
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/** Content category assigned by the moderation pipeline. */
|
|
2
|
+
export type ModerationCategory = 'hate' | 'harassment' | 'sexual' | 'self_harm' | 'violence' | 'illegal' | 'spam' | 'misinformation' | 'pii' | 'safe';
|
|
3
|
+
/** Action the pipeline takes after evaluating content against policy. */
|
|
4
|
+
export type ModerationAction = 'allow' | 'flag' | 'block' | 'redact';
|
|
5
|
+
/**
|
|
6
|
+
* Action taken when the classifier itself FAILS to produce a usable signal —
|
|
7
|
+
* a provider error/timeout, an in-band `error` event, or malformed model output.
|
|
8
|
+
* There is no real moderation verdict in that case, so the pipeline routes per
|
|
9
|
+
* this policy instead of silently allowing un-moderated content.
|
|
10
|
+
*
|
|
11
|
+
* - `'flag'` — route to human review (safe default; never a silent allow).
|
|
12
|
+
* - `'block'` — fail closed (deny the content).
|
|
13
|
+
* - `'allow'` — explicit opt-in to fail OPEN (content passes un-moderated).
|
|
14
|
+
*/
|
|
15
|
+
export type ModerationErrorAction = 'allow' | 'flag' | 'block';
|
|
16
|
+
/** Per-category confidence score produced by a moderation classifier. */
|
|
17
|
+
export interface ModerationScore {
|
|
18
|
+
category: ModerationCategory;
|
|
19
|
+
/** 0..1 confidence. */
|
|
20
|
+
score: number;
|
|
21
|
+
}
|
|
22
|
+
/** Final verdict returned by the pipeline for a piece of content. */
|
|
23
|
+
export interface ModerationDecision {
|
|
24
|
+
action: ModerationAction;
|
|
25
|
+
scores: ModerationScore[];
|
|
26
|
+
reasoning: string;
|
|
27
|
+
/** Most severe matched category, if any. */
|
|
28
|
+
matched_category: ModerationCategory | null;
|
|
29
|
+
/** True if any non-safe category exceeded its policy threshold. */
|
|
30
|
+
flagged: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* True when this decision came from a classifier FAILURE routed through
|
|
33
|
+
* `policy.onError` (no real moderation signal), rather than a real verdict.
|
|
34
|
+
* Lets callers/audits distinguish a fail-safe `'flag'`/`'block'` from a
|
|
35
|
+
* genuine one. Absent (undefined) on normal decisions.
|
|
36
|
+
*/
|
|
37
|
+
errored?: boolean;
|
|
38
|
+
}
|
|
39
|
+
/** Result of a single classification attempt against the bonded AI provider. */
|
|
40
|
+
export interface ClassificationResult {
|
|
41
|
+
scores: ModerationScore[];
|
|
42
|
+
reasoning: string;
|
|
43
|
+
/**
|
|
44
|
+
* Set when the classifier FAILED to produce a usable signal — a provider
|
|
45
|
+
* error/timeout, an in-band `error` event, or malformed model output. When
|
|
46
|
+
* present, `scores` is empty; the pipeline routes per `policy.onError`
|
|
47
|
+
* instead of treating the empty scores as an allow. `moderate()` handles this
|
|
48
|
+
* for you; direct `classify()` callers MUST check `error` before trusting an
|
|
49
|
+
* empty-scores result.
|
|
50
|
+
*/
|
|
51
|
+
error?: Error;
|
|
52
|
+
}
|
|
53
|
+
/** Per-category thresholds and actions that govern moderation decisions. */
|
|
54
|
+
export interface ModerationPolicy {
|
|
55
|
+
/** Threshold per category — content above this score triggers the action. */
|
|
56
|
+
thresholds: Partial<Record<ModerationCategory, number>>;
|
|
57
|
+
/** What action to take when any threshold is exceeded. */
|
|
58
|
+
action: ModerationAction;
|
|
59
|
+
/** Default action when no threshold is exceeded. */
|
|
60
|
+
defaultAction?: ModerationAction;
|
|
61
|
+
/**
|
|
62
|
+
* What to do when classification FAILS (provider error/timeout or malformed
|
|
63
|
+
* output) — i.e. when there is no real moderation signal. Defaults to
|
|
64
|
+
* `'flag'` (route to human review) so a transient classifier blip never
|
|
65
|
+
* silently ALLOWS un-moderated content. Set `'allow'` to explicitly opt into
|
|
66
|
+
* fail-open, or `'block'` to fail closed. When omitted, the
|
|
67
|
+
* `MODERATION_ON_ERROR` env var is consulted, then falls back to `'flag'`.
|
|
68
|
+
*/
|
|
69
|
+
onError?: ModerationErrorAction;
|
|
70
|
+
}
|
|
71
|
+
/** Database row shape for a single moderation audit-log entry. */
|
|
72
|
+
export interface AuditLogRow {
|
|
73
|
+
id: string;
|
|
74
|
+
owner_id: string | null;
|
|
75
|
+
content_excerpt: string;
|
|
76
|
+
decision: ModerationAction;
|
|
77
|
+
matched_category: ModerationCategory | null;
|
|
78
|
+
scores: ModerationScore[];
|
|
79
|
+
reasoning: string;
|
|
80
|
+
resource_type: string | null;
|
|
81
|
+
resource_id: string | null;
|
|
82
|
+
created_at: string | Date;
|
|
83
|
+
}
|
|
84
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,MAAM,MAAM,kBAAkB,GAC1B,MAAM,GACN,YAAY,GACZ,QAAQ,GACR,WAAW,GACX,UAAU,GACV,SAAS,GACT,MAAM,GACN,gBAAgB,GAChB,KAAK,GACL,MAAM,CAAA;AAEV,yEAAyE;AACzE,MAAM,MAAM,gBAAgB,GAAG,OAAO,GAAG,MAAM,GAAG,OAAO,GAAG,QAAQ,CAAA;AAEpE;;;;;;;;;GASG;AACH,MAAM,MAAM,qBAAqB,GAAG,OAAO,GAAG,MAAM,GAAG,OAAO,CAAA;AAE9D,yEAAyE;AACzE,MAAM,WAAW,eAAe;IAC9B,QAAQ,EAAE,kBAAkB,CAAA;IAC5B,uBAAuB;IACvB,KAAK,EAAE,MAAM,CAAA;CACd;AAED,qEAAqE;AACrE,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,gBAAgB,CAAA;IACxB,MAAM,EAAE,eAAe,EAAE,CAAA;IACzB,SAAS,EAAE,MAAM,CAAA;IACjB,4CAA4C;IAC5C,gBAAgB,EAAE,kBAAkB,GAAG,IAAI,CAAA;IAC3C,mEAAmE;IACnE,OAAO,EAAE,OAAO,CAAA;IAChB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;CAClB;AAED,gFAAgF;AAChF,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,eAAe,EAAE,CAAA;IACzB,SAAS,EAAE,MAAM,CAAA;IACjB;;;;;;;OAOG;IACH,KAAK,CAAC,EAAE,KAAK,CAAA;CACd;AAED,4EAA4E;AAC5E,MAAM,WAAW,gBAAgB;IAC/B,6EAA6E;IAC7E,UAAU,EAAE,OAAO,CAAC,MAAM,CAAC,kBAAkB,EAAE,MAAM,CAAC,CAAC,CAAA;IACvD,0DAA0D;IAC1D,MAAM,EAAE,gBAAgB,CAAA;IACxB,oDAAoD;IACpD,aAAa,CAAC,EAAE,gBAAgB,CAAA;IAChC;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,qBAAqB,CAAA;CAChC;AAED,kEAAkE;AAClE,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAA;IACV,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;IACvB,eAAe,EAAE,MAAM,CAAA;IACvB,QAAQ,EAAE,gBAAgB,CAAA;IAC1B,gBAAgB,EAAE,kBAAkB,GAAG,IAAI,CAAA;IAC3C,MAAM,EAAE,eAAe,EAAE,CAAA;IACzB,SAAS,EAAE,MAAM,CAAA;IACjB,aAAa,EAAE,MAAM,GAAG,IAAI,CAAA;IAC5B,WAAW,EAAE,MAAM,GAAG,IAAI,CAAA;IAC1B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;CAC1B"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@molecule/api-ai-moderation-pipeline",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "AI content moderation pipeline — classify, policy-match, action, audit-log",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"build": "tsc",
|
|
10
|
+
"test": "vitest run",
|
|
11
|
+
"test:watch": "vitest"
|
|
12
|
+
},
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"import": "./dist/index.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist"
|
|
21
|
+
],
|
|
22
|
+
"keywords": [
|
|
23
|
+
"molecule",
|
|
24
|
+
"ai",
|
|
25
|
+
"moderation",
|
|
26
|
+
"ugc",
|
|
27
|
+
"content-policy",
|
|
28
|
+
"resource"
|
|
29
|
+
],
|
|
30
|
+
"license": "Apache-2.0",
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@molecule/api-logger": "1.0.0",
|
|
33
|
+
"@types/node": "26.1.2",
|
|
34
|
+
"typescript": "6.0.3",
|
|
35
|
+
"vitest": "4.1.10"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@molecule/api-bonds-default-express": "^1.0.0",
|
|
39
|
+
"@molecule/api-database": "^1.0.0",
|
|
40
|
+
"@molecule/api-i18n": "^1.0.0",
|
|
41
|
+
"@molecule/api-logger": "^1.0.0",
|
|
42
|
+
"@molecule/api-middleware-validation": "^1.0.0",
|
|
43
|
+
"@molecule/api-ai": "^1.0.0"
|
|
44
|
+
}
|
|
45
|
+
}
|