modkit-server 0.0.0-stage → 1.0.0-beta.2
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/README.md +23 -2
- package/dist/adapters/classifiers.d.ts +45 -0
- package/dist/adapters/classifiers.d.ts.map +1 -0
- package/dist/adapters/classifiers.js +293 -0
- package/dist/adapters/classifiers.js.map +1 -0
- package/dist/adapters/notifiers.d.ts +34 -0
- package/dist/adapters/notifiers.d.ts.map +1 -0
- package/dist/adapters/notifiers.js +114 -0
- package/dist/adapters/notifiers.js.map +1 -0
- package/dist/adapters/storage.d.ts +15 -0
- package/dist/adapters/storage.d.ts.map +1 -0
- package/dist/adapters/storage.js +77 -0
- package/dist/adapters/storage.js.map +1 -0
- package/dist/auth.d.ts +43 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +260 -0
- package/dist/auth.js.map +1 -0
- package/dist/cli.d.ts +18 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +306 -0
- package/dist/cli.js.map +1 -0
- package/dist/conformance.d.ts +21 -0
- package/dist/conformance.d.ts.map +1 -0
- package/dist/conformance.js +188 -0
- package/dist/conformance.js.map +1 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +18 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -0
- package/dist/memoryStore.d.ts +6 -0
- package/dist/memoryStore.d.ts.map +1 -0
- package/dist/memoryStore.js +332 -0
- package/dist/memoryStore.js.map +1 -0
- package/dist/postgresStore.d.ts +20 -0
- package/dist/postgresStore.d.ts.map +1 -0
- package/dist/postgresStore.js +457 -0
- package/dist/postgresStore.js.map +1 -0
- package/dist/server.d.ts +37 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +322 -0
- package/dist/server.js.map +1 -0
- package/dist/store.d.ts +131 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +19 -0
- package/dist/store.js.map +1 -0
- package/migrations/001_modkit_v1.sql +168 -0
- package/package.json +55 -4
package/README.md
CHANGED
|
@@ -1,3 +1,24 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `modkit-server`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Self-hosted HTTP `/v1` server handler, Postgres store, multimodal classifiers (OpenAI / AWS Rekognition), notification sinks (Slack / Email), and operator CLI for ModKit.
|
|
4
|
+
|
|
5
|
+
## Operator CLI (`npx modkit-server`)
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
# Copy 001_modkit_v1.sql into your Supabase migrations directory
|
|
9
|
+
npx modkit-server migrations copy ./supabase/migrations
|
|
10
|
+
|
|
11
|
+
# List open user reports
|
|
12
|
+
npx modkit-server reports list --db "$DATABASE_URL" --status open
|
|
13
|
+
|
|
14
|
+
# Resolve a report within the 24-hour App Store SLA (remove | dismiss | ban)
|
|
15
|
+
npx modkit-server reports resolve <report-id> --action remove --note "Removed objectionable photo" --db "$DATABASE_URL"
|
|
16
|
+
|
|
17
|
+
# Manage global user bans directly
|
|
18
|
+
npx modkit-server bans add <user-id> --reason "Repeated violations" --db "$DATABASE_URL"
|
|
19
|
+
npx modkit-server bans remove <user-id> --db "$DATABASE_URL"
|
|
20
|
+
npx modkit-server bans list --db "$DATABASE_URL"
|
|
21
|
+
|
|
22
|
+
# Run end-to-end HTTP /v1 conformance checks against a deployed server
|
|
23
|
+
npx modkit-server conformance --server "https://your-project.supabase.co/functions/v1/modkit" --token "$TEST_USER_JWT" --webhook-secret "$MODKIT_WEBHOOK_SECRET"
|
|
24
|
+
```
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
export interface ModKitClassificationInput {
|
|
2
|
+
targetType?: string | undefined;
|
|
3
|
+
targetId?: string | undefined;
|
|
4
|
+
authorId?: string | undefined;
|
|
5
|
+
text?: string | undefined;
|
|
6
|
+
imageUrls?: string[] | undefined;
|
|
7
|
+
}
|
|
8
|
+
export interface ModKitClassificationResult {
|
|
9
|
+
provider: string;
|
|
10
|
+
flagged: boolean;
|
|
11
|
+
categories: Record<string, boolean>;
|
|
12
|
+
scores: Record<string, number>;
|
|
13
|
+
}
|
|
14
|
+
export interface ModKitClassifier {
|
|
15
|
+
readonly name: string;
|
|
16
|
+
classify(input: ModKitClassificationInput): Promise<ModKitClassificationResult>;
|
|
17
|
+
}
|
|
18
|
+
export interface OpenAIClassifierOptions {
|
|
19
|
+
apiKey: string;
|
|
20
|
+
model?: string | undefined;
|
|
21
|
+
endpoint?: string | undefined;
|
|
22
|
+
fetchImpl?: typeof globalThis.fetch | undefined;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Multimodal content moderation classifier backed by OpenAI's `/v1/moderations` endpoint
|
|
26
|
+
* (`omni-moderation-latest`), supporting both text and image URLs/data-URIs.
|
|
27
|
+
*/
|
|
28
|
+
export declare function openAIClassifier(options: OpenAIClassifierOptions): ModKitClassifier;
|
|
29
|
+
export interface RekognitionClassifierOptions {
|
|
30
|
+
region: string;
|
|
31
|
+
accessKeyId: string;
|
|
32
|
+
secretAccessKey: string;
|
|
33
|
+
sessionToken?: string | undefined;
|
|
34
|
+
minConfidence?: number | undefined;
|
|
35
|
+
endpoint?: string | undefined;
|
|
36
|
+
fetchImpl?: typeof globalThis.fetch | undefined;
|
|
37
|
+
now?: (() => Date) | undefined;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Image moderation classifier backed by AWS Rekognition `DetectModerationLabels`.
|
|
41
|
+
* Downloads each image URL (or decodes `data:` URIs), signs the AWS SigV4 request,
|
|
42
|
+
* and aggregates moderation labels and confidence scores.
|
|
43
|
+
*/
|
|
44
|
+
export declare function rekognitionClassifier(options: RekognitionClassifierOptions): ModKitClassifier;
|
|
45
|
+
//# sourceMappingURL=classifiers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"classifiers.d.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ClC,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC7B,SAAS,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,GAAG,SAAS,CAAA;IAC/C,GAAG,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAA;CAC/B;AAYD;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,4BAA4B,GAAG,gBAAgB,CAoH7F"}
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
import { createHash, createHmac } from 'node:crypto';
|
|
3
|
+
import { ModKitError } from '../errors.js';
|
|
4
|
+
/**
|
|
5
|
+
* Multimodal content moderation classifier backed by OpenAI's `/v1/moderations` endpoint
|
|
6
|
+
* (`omni-moderation-latest`), supporting both text and image URLs/data-URIs.
|
|
7
|
+
*/
|
|
8
|
+
export function openAIClassifier(options) {
|
|
9
|
+
const apiKey = options.apiKey.trim();
|
|
10
|
+
if (!apiKey) {
|
|
11
|
+
throw new Error('openAIClassifier requires a non-empty apiKey.');
|
|
12
|
+
}
|
|
13
|
+
const model = options.model ?? 'omni-moderation-latest';
|
|
14
|
+
const endpoint = options.endpoint ?? 'https://api.openai.com/v1/moderations';
|
|
15
|
+
const fetchFn = options.fetchImpl ?? globalThis.fetch;
|
|
16
|
+
return {
|
|
17
|
+
name: 'openai',
|
|
18
|
+
async classify(input) {
|
|
19
|
+
const text = input.text?.trim() ?? '';
|
|
20
|
+
const imageUrls = (input.imageUrls ?? []).map((u) => u.trim()).filter((u) => u.length > 0);
|
|
21
|
+
const batches = [];
|
|
22
|
+
if (imageUrls.length === 0) {
|
|
23
|
+
if (text.length > 0) {
|
|
24
|
+
batches.push([{ type: 'text', text }]);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
for (let i = 0; i < imageUrls.length; i++) {
|
|
29
|
+
const imagePart = {
|
|
30
|
+
type: 'image_url',
|
|
31
|
+
image_url: { url: imageUrls[i] },
|
|
32
|
+
};
|
|
33
|
+
if (i === 0 && text.length > 0) {
|
|
34
|
+
batches.push([{ type: 'text', text }, imagePart]);
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
batches.push([imagePart]);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (batches.length === 0) {
|
|
42
|
+
return {
|
|
43
|
+
provider: 'openai',
|
|
44
|
+
flagged: false,
|
|
45
|
+
categories: {},
|
|
46
|
+
scores: {},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
const payloads = await Promise.all(batches.map(async (parts) => {
|
|
50
|
+
let response;
|
|
51
|
+
try {
|
|
52
|
+
response = await fetchFn(endpoint, {
|
|
53
|
+
method: 'POST',
|
|
54
|
+
headers: {
|
|
55
|
+
authorization: `Bearer ${apiKey}`,
|
|
56
|
+
'content-type': 'application/json',
|
|
57
|
+
},
|
|
58
|
+
body: JSON.stringify({
|
|
59
|
+
model,
|
|
60
|
+
input: parts,
|
|
61
|
+
}),
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
const reason = error instanceof Error ? error.message : 'network error';
|
|
66
|
+
throw new ModKitError(502, 'classifier_error', `OpenAI moderation request failed: ${reason}`);
|
|
67
|
+
}
|
|
68
|
+
if (!response.ok) {
|
|
69
|
+
let errorBody = '';
|
|
70
|
+
try {
|
|
71
|
+
errorBody = (await response.text()).trim();
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
// Ignore failure reading error body
|
|
75
|
+
}
|
|
76
|
+
const detailSuffix = errorBody ? `: ${errorBody}` : '.';
|
|
77
|
+
throw new ModKitError(502, 'classifier_error', `OpenAI moderation API failed with status ${response.status}${detailSuffix}`);
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
return (await response.json());
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
throw new ModKitError(502, 'classifier_error', 'OpenAI moderation API returned invalid JSON.');
|
|
84
|
+
}
|
|
85
|
+
}));
|
|
86
|
+
let flagged = false;
|
|
87
|
+
const categories = {};
|
|
88
|
+
const scores = {};
|
|
89
|
+
for (const payload of payloads) {
|
|
90
|
+
const results = Array.isArray(payload.results) ? payload.results : [];
|
|
91
|
+
for (const result of results) {
|
|
92
|
+
if (result.flagged) {
|
|
93
|
+
flagged = true;
|
|
94
|
+
}
|
|
95
|
+
if (result.categories && typeof result.categories === 'object') {
|
|
96
|
+
for (const [key, val] of Object.entries(result.categories)) {
|
|
97
|
+
const isTrue = Boolean(val);
|
|
98
|
+
categories[key] = Boolean(categories[key] || isTrue);
|
|
99
|
+
if (isTrue) {
|
|
100
|
+
flagged = true;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (result.category_scores && typeof result.category_scores === 'object') {
|
|
105
|
+
for (const [key, val] of Object.entries(result.category_scores)) {
|
|
106
|
+
const numericScore = typeof val === 'number' && Number.isFinite(val) ? val : 0;
|
|
107
|
+
scores[key] = Math.max(scores[key] ?? 0, numericScore);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
provider: 'openai',
|
|
114
|
+
flagged,
|
|
115
|
+
categories,
|
|
116
|
+
scores,
|
|
117
|
+
};
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Image moderation classifier backed by AWS Rekognition `DetectModerationLabels`.
|
|
123
|
+
* Downloads each image URL (or decodes `data:` URIs), signs the AWS SigV4 request,
|
|
124
|
+
* and aggregates moderation labels and confidence scores.
|
|
125
|
+
*/
|
|
126
|
+
export function rekognitionClassifier(options) {
|
|
127
|
+
const region = options.region.trim();
|
|
128
|
+
const accessKeyId = options.accessKeyId.trim();
|
|
129
|
+
const secretAccessKey = options.secretAccessKey.trim();
|
|
130
|
+
if (!region || !accessKeyId || !secretAccessKey) {
|
|
131
|
+
throw new Error('rekognitionClassifier requires non-empty region, accessKeyId, and secretAccessKey.');
|
|
132
|
+
}
|
|
133
|
+
const minConfidence = options.minConfidence ?? 60;
|
|
134
|
+
const endpoint = options.endpoint ?? `https://rekognition.${region}.amazonaws.com/`;
|
|
135
|
+
const fetchFn = options.fetchImpl ?? globalThis.fetch;
|
|
136
|
+
const nowFn = options.now ?? (() => new Date());
|
|
137
|
+
return {
|
|
138
|
+
name: 'rekognition',
|
|
139
|
+
async classify(input) {
|
|
140
|
+
const imageUrls = (input.imageUrls ?? []).map((u) => u.trim()).filter(Boolean);
|
|
141
|
+
if (imageUrls.length === 0) {
|
|
142
|
+
return {
|
|
143
|
+
provider: 'rekognition',
|
|
144
|
+
flagged: false,
|
|
145
|
+
categories: {},
|
|
146
|
+
scores: {},
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
let flagged = false;
|
|
150
|
+
const categories = {};
|
|
151
|
+
const scores = {};
|
|
152
|
+
for (const imageUrl of imageUrls) {
|
|
153
|
+
const base64Bytes = await fetchImageAsBase64(imageUrl, fetchFn);
|
|
154
|
+
const requestBody = JSON.stringify({
|
|
155
|
+
Image: { Bytes: base64Bytes },
|
|
156
|
+
MinConfidence: minConfidence,
|
|
157
|
+
});
|
|
158
|
+
const signedHeaders = signAwsSigV4({
|
|
159
|
+
method: 'POST',
|
|
160
|
+
url: endpoint,
|
|
161
|
+
region,
|
|
162
|
+
service: 'rekognition',
|
|
163
|
+
accessKeyId,
|
|
164
|
+
secretAccessKey,
|
|
165
|
+
sessionToken: options.sessionToken,
|
|
166
|
+
target: 'RekognitionService.DetectModerationLabels',
|
|
167
|
+
contentType: 'application/x-amz-json-1.1',
|
|
168
|
+
body: requestBody,
|
|
169
|
+
now: nowFn(),
|
|
170
|
+
});
|
|
171
|
+
let response;
|
|
172
|
+
try {
|
|
173
|
+
response = await fetchFn(endpoint, {
|
|
174
|
+
method: 'POST',
|
|
175
|
+
headers: signedHeaders,
|
|
176
|
+
body: requestBody,
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
const reason = error instanceof Error ? error.message : 'network error';
|
|
181
|
+
throw new ModKitError(502, 'classifier_error', `AWS Rekognition request failed: ${reason}`);
|
|
182
|
+
}
|
|
183
|
+
if (!response.ok) {
|
|
184
|
+
throw new ModKitError(502, 'classifier_error', `AWS Rekognition DetectModerationLabels failed with status ${response.status}.`);
|
|
185
|
+
}
|
|
186
|
+
let payload;
|
|
187
|
+
try {
|
|
188
|
+
payload = (await response.json());
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
throw new ModKitError(502, 'classifier_error', 'AWS Rekognition returned invalid JSON.');
|
|
192
|
+
}
|
|
193
|
+
const labels = Array.isArray(payload.ModerationLabels) ? payload.ModerationLabels : [];
|
|
194
|
+
for (const label of labels) {
|
|
195
|
+
const rawName = label.Name?.trim();
|
|
196
|
+
if (!rawName)
|
|
197
|
+
continue;
|
|
198
|
+
const confidence = typeof label.Confidence === 'number' && Number.isFinite(label.Confidence)
|
|
199
|
+
? label.Confidence
|
|
200
|
+
: 0;
|
|
201
|
+
const normalizedKey = rawName.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '');
|
|
202
|
+
const normalizedScore = Number((confidence / 100).toFixed(4));
|
|
203
|
+
scores[normalizedKey] = Math.max(scores[normalizedKey] ?? 0, normalizedScore);
|
|
204
|
+
if (confidence >= minConfidence) {
|
|
205
|
+
categories[normalizedKey] = true;
|
|
206
|
+
flagged = true;
|
|
207
|
+
}
|
|
208
|
+
else if (!(normalizedKey in categories)) {
|
|
209
|
+
categories[normalizedKey] = false;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
provider: 'rekognition',
|
|
215
|
+
flagged,
|
|
216
|
+
categories,
|
|
217
|
+
scores,
|
|
218
|
+
};
|
|
219
|
+
},
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
async function fetchImageAsBase64(imageUrl, fetchFn) {
|
|
223
|
+
if (imageUrl.startsWith('data:')) {
|
|
224
|
+
const commaIdx = imageUrl.indexOf(',');
|
|
225
|
+
if (commaIdx === -1) {
|
|
226
|
+
throw new ModKitError(400, 'invalid_image_url', 'Invalid data URI provided to classifier.');
|
|
227
|
+
}
|
|
228
|
+
return imageUrl.slice(commaIdx + 1);
|
|
229
|
+
}
|
|
230
|
+
let response;
|
|
231
|
+
try {
|
|
232
|
+
response = await fetchFn(imageUrl);
|
|
233
|
+
}
|
|
234
|
+
catch (error) {
|
|
235
|
+
const reason = error instanceof Error ? error.message : 'network error';
|
|
236
|
+
throw new ModKitError(502, 'classifier_image_fetch_error', `Failed to fetch image for Rekognition classification: ${reason}`);
|
|
237
|
+
}
|
|
238
|
+
if (!response.ok) {
|
|
239
|
+
throw new ModKitError(502, 'classifier_image_fetch_error', `Failed to fetch image for Rekognition classification (status ${response.status}).`);
|
|
240
|
+
}
|
|
241
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
242
|
+
return Buffer.from(arrayBuffer).toString('base64');
|
|
243
|
+
}
|
|
244
|
+
function sha256Hex(data) {
|
|
245
|
+
return createHash('sha256').update(data, 'utf8').digest('hex');
|
|
246
|
+
}
|
|
247
|
+
function hmacSha256(key, data) {
|
|
248
|
+
return createHmac('sha256', key).update(data, 'utf8').digest();
|
|
249
|
+
}
|
|
250
|
+
function signAwsSigV4(input) {
|
|
251
|
+
const parsedUrl = new URL(input.url);
|
|
252
|
+
const amzDate = input.now.toISOString().replace(/[:-]|\.\d{3}/g, '');
|
|
253
|
+
const dateStamp = amzDate.slice(0, 8);
|
|
254
|
+
const payloadHash = sha256Hex(input.body);
|
|
255
|
+
const headerMap = {
|
|
256
|
+
'content-type': input.contentType,
|
|
257
|
+
host: parsedUrl.host,
|
|
258
|
+
'x-amz-date': amzDate,
|
|
259
|
+
'x-amz-target': input.target,
|
|
260
|
+
};
|
|
261
|
+
if (input.sessionToken) {
|
|
262
|
+
headerMap['x-amz-security-token'] = input.sessionToken;
|
|
263
|
+
}
|
|
264
|
+
const sortedHeaderKeys = Object.keys(headerMap).sort();
|
|
265
|
+
const canonicalHeaders = sortedHeaderKeys.map((k) => `${k}:${headerMap[k]}\n`).join('');
|
|
266
|
+
const signedHeaders = sortedHeaderKeys.join(';');
|
|
267
|
+
const canonicalRequest = [
|
|
268
|
+
input.method,
|
|
269
|
+
parsedUrl.pathname || '/',
|
|
270
|
+
parsedUrl.searchParams.toString(),
|
|
271
|
+
canonicalHeaders,
|
|
272
|
+
signedHeaders,
|
|
273
|
+
payloadHash,
|
|
274
|
+
].join('\n');
|
|
275
|
+
const credentialScope = `${dateStamp}/${input.region}/${input.service}/aws4_request`;
|
|
276
|
+
const stringToSign = [
|
|
277
|
+
'AWS4-HMAC-SHA256',
|
|
278
|
+
amzDate,
|
|
279
|
+
credentialScope,
|
|
280
|
+
sha256Hex(canonicalRequest),
|
|
281
|
+
].join('\n');
|
|
282
|
+
const kDate = hmacSha256(`AWS4${input.secretAccessKey}`, dateStamp);
|
|
283
|
+
const kRegion = hmacSha256(kDate, input.region);
|
|
284
|
+
const kService = hmacSha256(kRegion, input.service);
|
|
285
|
+
const kSigning = hmacSha256(kService, 'aws4_request');
|
|
286
|
+
const signature = createHmac('sha256', kSigning).update(stringToSign, 'utf8').digest('hex');
|
|
287
|
+
const authorization = `AWS4-HMAC-SHA256 Credential=${input.accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
|
|
288
|
+
return {
|
|
289
|
+
...headerMap,
|
|
290
|
+
authorization,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
//# sourceMappingURL=classifiers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"classifiers.js","sourceRoot":"","sources":["../../src/adapters/classifiers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,UAAU,E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|
+
export interface ModKitReportAlertEvent {
|
|
3
|
+
kind: 'report_submitted';
|
|
4
|
+
report: ModKitReportRecord;
|
|
5
|
+
}
|
|
6
|
+
export interface ModKitClassifierRejectedAlertEvent {
|
|
7
|
+
kind: 'content_rejected';
|
|
8
|
+
item: ModKitItemRecord;
|
|
9
|
+
}
|
|
10
|
+
export type ModKitAlertEvent = ModKitReportAlertEvent | ModKitClassifierRejectedAlertEvent;
|
|
11
|
+
export interface ModKitNotifier {
|
|
12
|
+
readonly name: string;
|
|
13
|
+
notify(event: ModKitAlertEvent): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
export interface SlackNotifierOptions {
|
|
16
|
+
webhookUrl: string;
|
|
17
|
+
fetchImpl?: typeof globalThis.fetch | undefined;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Slack Incoming Webhook notification adapter for immediate report and moderation alerts.
|
|
21
|
+
*/
|
|
22
|
+
export declare function slackNotifier(options: SlackNotifierOptions): ModKitNotifier;
|
|
23
|
+
export interface EmailNotifierOptions {
|
|
24
|
+
apiKey: string;
|
|
25
|
+
from: string;
|
|
26
|
+
to: string | string[];
|
|
27
|
+
endpoint?: string | undefined;
|
|
28
|
+
fetchImpl?: typeof globalThis.fetch | undefined;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Resend-compatible HTTP email notification adapter for immediate report and moderation alerts.
|
|
32
|
+
*/
|
|
33
|
+
export declare function emailNotifier(options: EmailNotifierOptions): ModKitNotifier;
|
|
34
|
+
//# sourceMappingURL=notifiers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"notifiers.d.ts","sourceRoot":"","sources":["../../src/adapters/notifiers.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAEvE,MAAM,WAAW,sBAAsB;IACrC,IAAI,EAAE,kBAAkB,CAAA;IACxB,MAAM,EAAE,kBAAkB,CAAA;CAC3B;AAED,MAAM,WAAW,kCAAkC;IACjD,IAAI,EAAE,kBAAkB,CAAA;IACxB,IAAI,EAAE,gBAAgB,CAAA;CACvB;AAED,MAAM,MAAM,gBAAgB,GAAG,sBAAsB,GAAG,kCAAkC,CAAA;AAE1F,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,MAAM,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAC/C;AAED,MAAM,WAAW,oBAAoB;IACnC,UAAU,EAAE,MAAM,CAAA;IAClB,SAAS,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,GAAG,SAAS,CAAA;CAChD;AA0CD;;GAEG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,cAAc,CAuC3E;AAED,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,MAAM,CAAA;IACZ,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;IACrB,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC7B,SAAS,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,GAAG,SAAS,CAAA;CAChD;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,cAAc,CAgD3E"}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { ModKitError } from '../errors.js';
|
|
2
|
+
function formatAlertSummary(event) {
|
|
3
|
+
if (event.kind === 'report_submitted') {
|
|
4
|
+
const r = event.report;
|
|
5
|
+
const lines = [
|
|
6
|
+
`🚨 *[ModKit] User Content Report (${r.reason})*`,
|
|
7
|
+
`• *Report ID:* \`${r.id}\``,
|
|
8
|
+
`• *Target:* \`${r.target_type}/${r.target_id}\``,
|
|
9
|
+
`• *Author:* \`${r.target_author_id ?? 'unknown'}\``,
|
|
10
|
+
`• *Reporter:* \`${r.reporter_id}\``,
|
|
11
|
+
...(r.details ? [`• *Details:* ${r.details}`] : []),
|
|
12
|
+
`• *Created At:* ${r.created_at}`,
|
|
13
|
+
`• *Triage SLA:* Action required within 24 hours (\`npx modkit-server reports resolve ${r.id} --action remove|dismiss|ban\`)`,
|
|
14
|
+
];
|
|
15
|
+
return {
|
|
16
|
+
subject: `[ModKit] Content Report (${r.reason}): ${r.target_type}/${r.target_id}`,
|
|
17
|
+
text: lines.join('\n'),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
const item = event.item;
|
|
21
|
+
const triggeredCategories = Object.entries(item.classifier_categories)
|
|
22
|
+
.filter(([, flagged]) => flagged)
|
|
23
|
+
.map(([cat]) => cat);
|
|
24
|
+
const lines = [
|
|
25
|
+
`🛑 *[ModKit] Automated Classifier Rejected Content*`,
|
|
26
|
+
`• *Target:* \`${item.target_type}/${item.target_id}\``,
|
|
27
|
+
`• *Author:* \`${item.author_id}\``,
|
|
28
|
+
`• *Provider:* \`${item.classifier_provider ?? 'unknown'}\``,
|
|
29
|
+
`• *Categories:* ${triggeredCategories.length > 0 ? triggeredCategories.join(', ') : 'flagged'}`,
|
|
30
|
+
`• *Updated At:* ${item.updated_at}`,
|
|
31
|
+
];
|
|
32
|
+
return {
|
|
33
|
+
subject: `[ModKit] Classifier Rejected: ${item.target_type}/${item.target_id}`,
|
|
34
|
+
text: lines.join('\n'),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Slack Incoming Webhook notification adapter for immediate report and moderation alerts.
|
|
39
|
+
*/
|
|
40
|
+
export function slackNotifier(options) {
|
|
41
|
+
const webhookUrl = options.webhookUrl.trim();
|
|
42
|
+
if (!webhookUrl) {
|
|
43
|
+
throw new Error('slackNotifier requires a non-empty webhookUrl.');
|
|
44
|
+
}
|
|
45
|
+
const fetchFn = options.fetchImpl ?? globalThis.fetch;
|
|
46
|
+
return {
|
|
47
|
+
name: 'slack',
|
|
48
|
+
async notify(event) {
|
|
49
|
+
const { text } = formatAlertSummary(event);
|
|
50
|
+
let response;
|
|
51
|
+
try {
|
|
52
|
+
response = await fetchFn(webhookUrl, {
|
|
53
|
+
method: 'POST',
|
|
54
|
+
headers: {
|
|
55
|
+
'content-type': 'application/json',
|
|
56
|
+
},
|
|
57
|
+
body: JSON.stringify({ text }),
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
const reason = error instanceof Error ? error.message : 'network error';
|
|
62
|
+
throw new ModKitError(502, 'notifier_error', `Slack webhook notification failed: ${reason}`);
|
|
63
|
+
}
|
|
64
|
+
if (!response.ok) {
|
|
65
|
+
throw new ModKitError(502, 'notifier_error', `Slack webhook returned status ${response.status}.`);
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Resend-compatible HTTP email notification adapter for immediate report and moderation alerts.
|
|
72
|
+
*/
|
|
73
|
+
export function emailNotifier(options) {
|
|
74
|
+
const apiKey = options.apiKey.trim();
|
|
75
|
+
const from = options.from.trim();
|
|
76
|
+
const recipients = (Array.isArray(options.to) ? options.to : [options.to])
|
|
77
|
+
.map((addr) => addr.trim())
|
|
78
|
+
.filter(Boolean);
|
|
79
|
+
if (!apiKey || !from || recipients.length === 0) {
|
|
80
|
+
throw new Error('emailNotifier requires non-empty apiKey, from, and to recipient(s).');
|
|
81
|
+
}
|
|
82
|
+
const endpoint = options.endpoint ?? 'https://api.resend.com/emails';
|
|
83
|
+
const fetchFn = options.fetchImpl ?? globalThis.fetch;
|
|
84
|
+
return {
|
|
85
|
+
name: 'email',
|
|
86
|
+
async notify(event) {
|
|
87
|
+
const { subject, text } = formatAlertSummary(event);
|
|
88
|
+
let response;
|
|
89
|
+
try {
|
|
90
|
+
response = await fetchFn(endpoint, {
|
|
91
|
+
method: 'POST',
|
|
92
|
+
headers: {
|
|
93
|
+
authorization: `Bearer ${apiKey}`,
|
|
94
|
+
'content-type': 'application/json',
|
|
95
|
+
},
|
|
96
|
+
body: JSON.stringify({
|
|
97
|
+
from,
|
|
98
|
+
to: recipients,
|
|
99
|
+
subject,
|
|
100
|
+
text,
|
|
101
|
+
}),
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
const reason = error instanceof Error ? error.message : 'network error';
|
|
106
|
+
throw new ModKitError(502, 'notifier_error', `Email notification request failed: ${reason}`);
|
|
107
|
+
}
|
|
108
|
+
if (!response.ok) {
|
|
109
|
+
throw new ModKitError(502, 'notifier_error', `Email notification API returned status ${response.status}.`);
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
//# sourceMappingURL=notifiers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"notifiers.js","sourceRoot":"","sources":["../../src/adapters/notifiers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAyB1C,SAAS,kBAAkB,CAAC,KAAuB;IAIjD,IAAI,KAAK,CAAC,IAAI,KAAK,kBAAkB,EAAE,CAAC;QACtC,MAAM,CAAC,GAAG,KAAK,CAAC,MAAM,CAAA;QACtB,MAAM,KAAK,GAAG;YACZ,qCAAqC,CAAC,CAAC,MAAM,IAAI;YACjD,oBAAoB,CAAC,CAAC,EAAE,IAAI;YAC5B,iBAAiB,CAAC,CAAC,WAAW,IAAI,CAAC,CAAC,SAAS,IAAI;YACjD,iBAAiB,CAAC,CAAC,gBAAgB,IAAI,SAAS,IAAI;YACpD,mBAAmB,CAAC,CAAC,WAAW,IAAI;YACpC,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;YACnD,mBAAmB,CAAC,CAAC,UAAU,EAAE;YACjC,wFAAwF,CAAC,CAAC,EAAE,iCAAiC;SA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gBACjB,MAAM,IAAI,WAAW,CACnB,GAAG,EACH,gBAAgB,EAChB,0CAA0C,QAAQ,CAAC,MAAM,GAAG,CAC7D,CAAA;YACH,CAAC;QACH,CAAC;KACF,CAAA;AACH,CAAC"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface SupabaseStorageOptions {
|
|
2
|
+
url: string;
|
|
3
|
+
serviceRoleKey: string;
|
|
4
|
+
bucket: string;
|
|
5
|
+
fetchImpl?: typeof globalThis.fetch | undefined;
|
|
6
|
+
}
|
|
7
|
+
export interface SupabaseStorageHelper {
|
|
8
|
+
createSignedReadUrl(key: string, expiresInSeconds?: number): Promise<string>;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Helper for generating short-lived signed read URLs from a private Supabase Storage bucket
|
|
12
|
+
* so moderation classifiers (OpenAI / Rekognition) can inspect newly uploaded images.
|
|
13
|
+
*/
|
|
14
|
+
export declare function supabaseStorage(options: SupabaseStorageOptions): SupabaseStorageHelper;
|
|
15
|
+
//# sourceMappingURL=storage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../../src/adapters/storage.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,sBAAsB;IACrC,GAAG,EAAE,MAAM,CAAA;IACX,cAAc,EAAE,MAAM,CAAA;IACtB,MAAM,EAAE,MAAM,CAAA;IACd,SAAS,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,GAAG,SAAS,CAAA;CAChD;AAED,MAAM,WAAW,qBAAqB;IACpC,mBAAmB,CAAC,GAAG,EAAE,MAAM,EAAE,gBAAgB,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;CAC7E;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,qBAAqB,CAyEtF"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { ModKitError } from '../errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* Helper for generating short-lived signed read URLs from a private Supabase Storage bucket
|
|
4
|
+
* so moderation classifiers (OpenAI / Rekognition) can inspect newly uploaded images.
|
|
5
|
+
*/
|
|
6
|
+
export function supabaseStorage(options) {
|
|
7
|
+
const baseUrl = options.url.trim().replace(/\/+$/, '');
|
|
8
|
+
const serviceRoleKey = options.serviceRoleKey.trim();
|
|
9
|
+
const bucket = options.bucket.trim();
|
|
10
|
+
if (!baseUrl || !serviceRoleKey || !bucket) {
|
|
11
|
+
throw new Error('supabaseStorage requires non-empty url, serviceRoleKey, and bucket.');
|
|
12
|
+
}
|
|
13
|
+
const fetchFn = options.fetchImpl ?? globalThis.fetch;
|
|
14
|
+
return {
|
|
15
|
+
async createSignedReadUrl(key, expiresInSeconds = 300) {
|
|
16
|
+
const encodedKey = encodeStorageKey(key);
|
|
17
|
+
const endpoint = `${baseUrl}/storage/v1/object/sign/${encodeURIComponent(bucket)}/${encodedKey}`;
|
|
18
|
+
let response;
|
|
19
|
+
try {
|
|
20
|
+
response = await fetchFn(endpoint, {
|
|
21
|
+
method: 'POST',
|
|
22
|
+
headers: {
|
|
23
|
+
authorization: `Bearer ${serviceRoleKey}`,
|
|
24
|
+
apikey: serviceRoleKey,
|
|
25
|
+
'content-type': 'application/json',
|
|
26
|
+
},
|
|
27
|
+
body: JSON.stringify({ expiresIn: expiresInSeconds }),
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
const reason = error instanceof Error ? error.message : 'network error';
|
|
32
|
+
throw new ModKitError(502, 'storage_error', `Supabase storage sign request failed: ${reason}`);
|
|
33
|
+
}
|
|
34
|
+
if (!response.ok) {
|
|
35
|
+
throw new ModKitError(502, 'storage_error', `Supabase storage sign failed with status ${response.status}.`);
|
|
36
|
+
}
|
|
37
|
+
let payload;
|
|
38
|
+
try {
|
|
39
|
+
payload = (await response.json());
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
throw new ModKitError(502, 'storage_error', 'Supabase storage sign returned invalid JSON.');
|
|
43
|
+
}
|
|
44
|
+
const rawUrl = payload.signedURL ?? payload.signedUrl ?? payload.url;
|
|
45
|
+
if (!rawUrl || typeof rawUrl !== 'string') {
|
|
46
|
+
throw new ModKitError(502, 'storage_error', 'Supabase storage sign response did not include signedURL.');
|
|
47
|
+
}
|
|
48
|
+
return normalizeSupabaseSignedUrl(baseUrl, rawUrl);
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function normalizeSupabaseSignedUrl(baseUrl, rawUrl) {
|
|
53
|
+
if (rawUrl.startsWith('http://') || rawUrl.startsWith('https://')) {
|
|
54
|
+
return rawUrl;
|
|
55
|
+
}
|
|
56
|
+
if (rawUrl.startsWith('/storage/v1/')) {
|
|
57
|
+
return `${baseUrl}${rawUrl}`;
|
|
58
|
+
}
|
|
59
|
+
if (rawUrl.startsWith('/object/')) {
|
|
60
|
+
return `${baseUrl}/storage/v1${rawUrl}`;
|
|
61
|
+
}
|
|
62
|
+
return `${baseUrl}/${rawUrl.replace(/^\/+/, '')}`;
|
|
63
|
+
}
|
|
64
|
+
function encodeStorageKey(key) {
|
|
65
|
+
const normalizedKey = key.replace(/^\/+/, '');
|
|
66
|
+
if (!normalizedKey || normalizedKey.endsWith('/')) {
|
|
67
|
+
throw new ModKitError(400, 'invalid_storage_key', 'Storage key must be a non-empty object path.');
|
|
68
|
+
}
|
|
69
|
+
const segments = normalizedKey.split('/');
|
|
70
|
+
for (const segment of segments) {
|
|
71
|
+
if (!segment || segment === '.' || segment === '..') {
|
|
72
|
+
throw new ModKitError(400, 'invalid_storage_key', 'Storage key must not contain empty or dot path segments.');
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return segments.map((segment) => encodeURIComponent(segment)).join('/');
|
|
76
|
+
}
|
|
77
|
+
//# sourceMappingURL=storage.js.map
|