@dexmond/sdk 3.2.0 → 3.3.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/index.d.ts CHANGED
@@ -99,3 +99,12 @@ export class DexmondClient {
99
99
  };
100
100
  }
101
101
  export default DexmondClient;
102
+
103
+ export {
104
+ DexmondGuardError,
105
+ guardOpenAIMessages,
106
+ createExpressGuard,
107
+ wrapNextHandler,
108
+ createVercelAiMiddleware,
109
+ type DexmondGuardOptions,
110
+ } from './middleware.js';
package/index.mjs CHANGED
@@ -205,3 +205,11 @@ export class DexmondClient {
205
205
  }
206
206
 
207
207
  export default DexmondClient;
208
+
209
+ export {
210
+ DexmondGuardError,
211
+ guardOpenAIMessages,
212
+ createExpressGuard,
213
+ wrapNextHandler,
214
+ createVercelAiMiddleware,
215
+ } from './middleware.mjs';
@@ -0,0 +1,46 @@
1
+ import type { DexmondClient } from './index.js';
2
+
3
+ export interface DexmondGuardOptions {
4
+ mode?: 'block' | 'redact' | 'audit';
5
+ riskThreshold?: number;
6
+ checkPrompt?: boolean;
7
+ checkDlp?: boolean;
8
+ redactPii?: boolean;
9
+ blockOnSecrets?: boolean;
10
+ redactOutput?: boolean;
11
+ failOpen?: boolean;
12
+ roles?: string[];
13
+ extractText?: (req: any) => string;
14
+ }
15
+
16
+ export class DexmondGuardError extends Error {
17
+ statusCode: number;
18
+ details: Record<string, any>;
19
+ constructor(message: string, details?: Record<string, any>);
20
+ }
21
+
22
+ export function guardOpenAIMessages<T extends { role: string; content: any }>(
23
+ client: DexmondClient,
24
+ messages: T[],
25
+ options?: DexmondGuardOptions
26
+ ): Promise<{ allowed: boolean; messages: T[]; riskScore: number; findings: any[] }>;
27
+
28
+ export function createExpressGuard(
29
+ client: DexmondClient,
30
+ options?: DexmondGuardOptions
31
+ ): (req: any, res: any, next: (err?: any) => void) => Promise<void>;
32
+
33
+ export function wrapNextHandler(
34
+ client: DexmondClient,
35
+ handler: (request: Request, context?: any) => Promise<Response> | Response,
36
+ options?: DexmondGuardOptions
37
+ ): (request: Request, context?: any) => Promise<Response>;
38
+
39
+ export function createVercelAiMiddleware(
40
+ client: DexmondClient,
41
+ options?: DexmondGuardOptions
42
+ ): {
43
+ middlewareVersion: 'v1';
44
+ transformParams: (args: { params: any }) => Promise<any>;
45
+ wrapGenerate: (args: { doGenerate: () => Promise<any> }) => Promise<any>;
46
+ };
package/middleware.mjs ADDED
@@ -0,0 +1,246 @@
1
+ /**
2
+ * @dexmond/sdk/middleware — Zero-dependency AI & Web Security Middleware
3
+ * Works with Express, Next.js App Router, Vercel AI SDK (wrapLanguageModel), and OpenAI/Anthropic chat messages.
4
+ */
5
+
6
+ export class DexmondGuardError extends Error {
7
+ constructor(message, details = {}) {
8
+ super(message);
9
+ this.name = 'DexmondGuardError';
10
+ this.statusCode = 400;
11
+ this.details = details;
12
+ }
13
+ }
14
+
15
+ function extractResponseData(resp) {
16
+ if (!resp || typeof resp !== 'object') return {};
17
+ return resp.data && typeof resp.data === 'object' ? resp.data : resp;
18
+ }
19
+
20
+ async function runGuardText(client, text, opts = {}) {
21
+ const mode = opts.mode || 'block'; // 'block' | 'redact' | 'audit'
22
+ const riskThreshold = typeof opts.riskThreshold === 'number' ? opts.riskThreshold : 60;
23
+ const checkPrompt = opts.checkPrompt !== false;
24
+ const checkDlp = opts.checkDlp !== false;
25
+ const includePii = opts.redactPii !== false;
26
+
27
+ const result = {
28
+ allowed: true,
29
+ text: String(text ?? ''),
30
+ promptRiskScore: 0,
31
+ promptVerdict: 'clean',
32
+ dlpFindings: [],
33
+ blockedReason: null,
34
+ };
35
+
36
+ if (!result.text.trim()) return result;
37
+
38
+ if (checkPrompt) {
39
+ const pg = extractResponseData(await client.shield.promptGuard(result.text));
40
+ result.promptRiskScore = Number(pg.risk_score || 0);
41
+ result.promptVerdict = pg.verdict || (result.promptRiskScore >= riskThreshold ? 'block' : 'allow');
42
+ if (result.promptRiskScore >= riskThreshold) {
43
+ result.blockedReason = `Prompt injection detected (risk_score=${result.promptRiskScore}, verdict=${result.promptVerdict})`;
44
+ if (mode === 'block') {
45
+ result.allowed = false;
46
+ return result;
47
+ }
48
+ }
49
+ }
50
+
51
+ if (checkDlp) {
52
+ const dlp = extractResponseData(await client.shield.dlpScan(result.text, { include_pii: includePii }));
53
+ result.dlpFindings = Array.isArray(dlp.findings) ? dlp.findings : [];
54
+ const hasCriticalSecret = result.dlpFindings.some((f) => f && (f.severity === 'critical' || f.severity === 'high'));
55
+ if (typeof dlp.redacted_text === 'string' && result.dlpFindings.length > 0 && (mode === 'redact' || opts.redactPii !== false)) {
56
+ result.text = dlp.redacted_text;
57
+ }
58
+ if (hasCriticalSecret && mode === 'block' && opts.blockOnSecrets !== false) {
59
+ result.allowed = false;
60
+ result.blockedReason = result.blockedReason || `Sensitive credentials detected (${result.dlpFindings.length} finding(s))`;
61
+ }
62
+ }
63
+
64
+ return result;
65
+ }
66
+
67
+ /**
68
+ * Drop-in OpenAI / Anthropic / LiteLLM chat messages pre-flight guard.
69
+ */
70
+ export async function guardOpenAIMessages(client, messages, options = {}) {
71
+ const mode = options.mode || 'block';
72
+ const roles = new Set(options.roles || ['user', 'tool']);
73
+ const guarded = [];
74
+ let maxRiskScore = 0;
75
+ const findings = [];
76
+
77
+ for (const msg of Array.isArray(messages) ? messages : []) {
78
+ if (!msg || !roles.has(msg.role) || typeof msg.content !== 'string') {
79
+ guarded.push(msg);
80
+ continue;
81
+ }
82
+ const r = await runGuardText(client, msg.content, options);
83
+ maxRiskScore = Math.max(maxRiskScore, r.promptRiskScore);
84
+ if (r.dlpFindings.length) findings.push(...r.dlpFindings);
85
+ if (!r.allowed && mode === 'block') {
86
+ throw new DexmondGuardError(r.blockedReason || 'Blocked by Dexmond Guard', {
87
+ riskScore: r.promptRiskScore,
88
+ verdict: r.promptVerdict,
89
+ findings: r.dlpFindings,
90
+ });
91
+ }
92
+ guarded.push({ ...msg, content: r.text });
93
+ }
94
+
95
+ return { allowed: true, messages: guarded, riskScore: maxRiskScore, findings };
96
+ }
97
+
98
+ /**
99
+ * Drop-in Express / Connect middleware for /api/chat, /api/completions, or form endpoints.
100
+ */
101
+ export function createExpressGuard(client, options = {}) {
102
+ const mode = options.mode || 'block';
103
+ const extractText =
104
+ typeof options.extractText === 'function'
105
+ ? options.extractText
106
+ : (req) => {
107
+ const b = req?.body;
108
+ if (typeof b === 'string') return b;
109
+ if (b && typeof b.prompt === 'string') return b.prompt;
110
+ if (b && typeof b.message === 'string') return b.message;
111
+ if (b && typeof b.text === 'string') return b.text;
112
+ if (b && Array.isArray(b.messages)) {
113
+ return b.messages
114
+ .filter((m) => m && (m.role === 'user' || m.role === 'tool') && typeof m.content === 'string')
115
+ .map((m) => m.content)
116
+ .join('\n');
117
+ }
118
+ return '';
119
+ };
120
+
121
+ return async function dexmondExpressGuard(req, res, next) {
122
+ try {
123
+ const text = extractText(req);
124
+ const report = await runGuardText(client, text, options);
125
+ req.dexmondGuard = report;
126
+
127
+ if (!report.allowed && mode === 'block') {
128
+ return res.status(400).json({
129
+ ok: false,
130
+ error: report.blockedReason || 'Request blocked by Dexmond Security Guard',
131
+ risk_score: report.promptRiskScore,
132
+ dlp_findings: report.dlpFindings.length,
133
+ });
134
+ }
135
+
136
+ if (mode === 'redact' && req.body && typeof req.body === 'object') {
137
+ if (typeof req.body.prompt === 'string') req.body.prompt = report.text;
138
+ else if (typeof req.body.message === 'string') req.body.message = report.text;
139
+ else if (typeof req.body.text === 'string') req.body.text = report.text;
140
+ }
141
+
142
+ return next();
143
+ } catch (err) {
144
+ if (options.failOpen) return next();
145
+ return next(err);
146
+ }
147
+ };
148
+ }
149
+
150
+ /**
151
+ * Next.js App Router / Web Fetch Request handler wrapper.
152
+ */
153
+ export function wrapNextHandler(client, handler, options = {}) {
154
+ const mode = options.mode || 'block';
155
+ return async function dexmondNextHandler(request, context) {
156
+ const cloned = request.clone();
157
+ let rawBody = '';
158
+ try {
159
+ rawBody = await cloned.text();
160
+ } catch (_) {
161
+ rawBody = '';
162
+ }
163
+ let textToScan = rawBody;
164
+ try {
165
+ const parsed = JSON.parse(rawBody);
166
+ if (parsed && typeof parsed === 'object') {
167
+ if (typeof parsed.prompt === 'string') textToScan = parsed.prompt;
168
+ else if (typeof parsed.message === 'string') textToScan = parsed.message;
169
+ else if (Array.isArray(parsed.messages)) {
170
+ textToScan = parsed.messages
171
+ .filter((m) => m && typeof m.content === 'string')
172
+ .map((m) => m.content)
173
+ .join('\n');
174
+ }
175
+ }
176
+ } catch (_) {}
177
+
178
+ const report = await runGuardText(client, textToScan, options);
179
+ if (!report.allowed && mode === 'block') {
180
+ return new Response(
181
+ JSON.stringify({
182
+ ok: false,
183
+ error: report.blockedReason || 'Request blocked by Dexmond Guard',
184
+ risk_score: report.promptRiskScore,
185
+ dlp_findings: report.dlpFindings.length,
186
+ }),
187
+ { status: 400, headers: { 'content-type': 'application/json' } }
188
+ );
189
+ }
190
+
191
+ return handler(request, { ...(context || {}), dexmondGuard: report });
192
+ };
193
+ }
194
+
195
+ /**
196
+ * Vercel AI SDK `wrapLanguageModel` compatible middleware (transformParams + wrapGenerate).
197
+ */
198
+ export function createVercelAiMiddleware(client, options = {}) {
199
+ return {
200
+ middlewareVersion: 'v1',
201
+ async transformParams({ params }) {
202
+ if (!params || !Array.isArray(params.prompt)) return params;
203
+ const nextPrompt = [];
204
+ for (const item of params.prompt) {
205
+ if (!item || item.role !== 'user') {
206
+ nextPrompt.push(item);
207
+ continue;
208
+ }
209
+ if (typeof item.content === 'string') {
210
+ const r = await runGuardText(client, item.content, options);
211
+ if (!r.allowed && (options.mode || 'block') === 'block') {
212
+ throw new DexmondGuardError(r.blockedReason || 'Blocked by Dexmond Vercel AI Guard', r);
213
+ }
214
+ nextPrompt.push({ ...item, content: r.text });
215
+ } else if (Array.isArray(item.content)) {
216
+ const nextParts = [];
217
+ for (const part of item.content) {
218
+ if (part && part.type === 'text' && typeof part.text === 'string') {
219
+ const r = await runGuardText(client, part.text, options);
220
+ if (!r.allowed && (options.mode || 'block') === 'block') {
221
+ throw new DexmondGuardError(r.blockedReason || 'Blocked by Dexmond Vercel AI Guard', r);
222
+ }
223
+ nextParts.push({ ...part, text: r.text });
224
+ } else {
225
+ nextParts.push(part);
226
+ }
227
+ }
228
+ nextPrompt.push({ ...item, content: nextParts });
229
+ } else {
230
+ nextPrompt.push(item);
231
+ }
232
+ }
233
+ return { ...params, prompt: nextPrompt };
234
+ },
235
+ async wrapGenerate({ doGenerate }) {
236
+ const result = await doGenerate();
237
+ if (options.redactOutput !== false && result && typeof result.text === 'string' && result.text.trim()) {
238
+ const dlp = extractResponseData(await client.shield.dlpScan(result.text, { include_pii: options.redactPii !== false }));
239
+ if (typeof dlp.redacted_text === 'string' && (dlp.finding_count || 0) > 0) {
240
+ return { ...result, text: dlp.redacted_text };
241
+ }
242
+ }
243
+ return result;
244
+ },
245
+ };
246
+ }
package/package.json CHANGED
@@ -1,16 +1,28 @@
1
1
  {
2
2
  "name": "@dexmond/sdk",
3
- "version": "3.2.0",
4
- "description": "Official zero-dependency JavaScript/TypeScript SDK and CLI for the Dexmond Commercial API Platform (62-detector DLP + entropy, Prompt Guard v2, 29.7k+ live malware IOCs, SQL/RLS auditor, EU GDPR/AI Act screener, APK audit, CypherNight crypto & orbital physics).",
3
+ "version": "3.3.0",
4
+ "description": "Official zero-dependency JavaScript/TypeScript SDK, CLI & AI/Web Middleware (Express, Next.js, Vercel AI SDK) for the Dexmond Commercial API Platform.",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
7
7
  "types": "./index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./index.d.ts",
11
+ "import": "./index.mjs"
12
+ },
13
+ "./middleware": {
14
+ "types": "./middleware.d.ts",
15
+ "import": "./middleware.mjs"
16
+ }
17
+ },
8
18
  "bin": {
9
19
  "dexmond": "./bin/dexmond.mjs"
10
20
  },
11
21
  "files": [
12
22
  "index.mjs",
13
23
  "index.d.ts",
24
+ "middleware.mjs",
25
+ "middleware.d.ts",
14
26
  "bin/",
15
27
  "README.md",
16
28
  "LICENSE"
@@ -38,10 +50,10 @@
38
50
  "homepage": "https://dexmond.com/integrations.html",
39
51
  "repository": {
40
52
  "type": "git",
41
- "url": "https://github.com/Dexmond-Technologies/DEXMONDWEBSiTE.git",
42
- "directory": "sdk/js"
53
+ "url": "https://github.com/Dexmond-Technologies/dexmond-sdk.git",
54
+ "directory": "packages/sdk"
43
55
  },
44
56
  "bugs": {
45
- "url": "https://github.com/Dexmond-Technologies/dexmond-cookbook/issues"
57
+ "url": "https://github.com/Dexmond-Technologies/dexmond-sdk/issues"
46
58
  }
47
59
  }