plugin-document-understanding 1.1.8 → 1.1.9
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/dist/externalVersion.js +6 -6
- package/dist/server/actions.js +1 -1
- package/dist/server/plugin.js +11 -10
- package/dist/server/services/DocumentUnderstandingService.js +24 -5
- package/dist/server/services/PipelineExecutor.js +8 -32
- package/package.json +1 -1
- package/src/server/__tests__/document-understanding-service.test.ts +71 -0
- package/src/server/__tests__/pipeline-executor.test.ts +23 -1
- package/src/server/actions.ts +1 -1
- package/src/server/plugin.ts +15 -15
- package/src/server/services/DocumentUnderstandingService.ts +26 -6
- package/src/server/services/PipelineExecutor.ts +8 -33
- package/src/server/types.ts +5 -0
package/dist/externalVersion.js
CHANGED
|
@@ -8,14 +8,14 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
module.exports = {
|
|
11
|
-
"@nocobase/client": "2.1.
|
|
12
|
-
"@nocobase/flow-engine": "2.1.
|
|
13
|
-
"@nocobase/client-v2": "2.1.
|
|
14
|
-
"@nocobase/actions": "2.1.
|
|
15
|
-
"@nocobase/server": "2.1.
|
|
11
|
+
"@nocobase/client": "2.1.34",
|
|
12
|
+
"@nocobase/flow-engine": "2.1.34",
|
|
13
|
+
"@nocobase/client-v2": "2.1.34",
|
|
14
|
+
"@nocobase/actions": "2.1.34",
|
|
15
|
+
"@nocobase/server": "2.1.34",
|
|
16
16
|
"react": "18.2.0",
|
|
17
17
|
"antd": "5.24.2",
|
|
18
18
|
"@ant-design/icons": "5.6.1",
|
|
19
|
-
"@nocobase/database": "2.1.
|
|
19
|
+
"@nocobase/database": "2.1.34",
|
|
20
20
|
"axios": "1.18.1"
|
|
21
21
|
};
|
package/dist/server/actions.js
CHANGED
|
@@ -34,7 +34,7 @@ const defineActions = (plugin) => {
|
|
|
34
34
|
const service = plugin.service;
|
|
35
35
|
return {
|
|
36
36
|
async getConfig(ctx, next) {
|
|
37
|
-
ctx.body = await service.
|
|
37
|
+
ctx.body = await service.getConfigForClient();
|
|
38
38
|
await next();
|
|
39
39
|
},
|
|
40
40
|
async updateConfig(ctx, next) {
|
package/dist/server/plugin.js
CHANGED
|
@@ -47,19 +47,12 @@ class PluginDocumentUnderstandingServer extends import_server.Plugin {
|
|
|
47
47
|
async afterAdd() {
|
|
48
48
|
}
|
|
49
49
|
async beforeLoad() {
|
|
50
|
-
}
|
|
51
|
-
async load() {
|
|
52
50
|
await this.db.import({
|
|
53
51
|
directory: (0, import_path.resolve)(__dirname, "collections")
|
|
54
52
|
});
|
|
53
|
+
}
|
|
54
|
+
async load() {
|
|
55
55
|
this.service = new import_DocumentUnderstandingService.DocumentUnderstandingService(this.app, this.db);
|
|
56
|
-
this.app.on("afterStart", async () => {
|
|
57
|
-
try {
|
|
58
|
-
await this.service.initialize({ recoverJobs: true });
|
|
59
|
-
} catch (err) {
|
|
60
|
-
this.app.logger.warn("Document Understanding plugin not configured yet, skip init.", err);
|
|
61
|
-
}
|
|
62
|
-
});
|
|
63
56
|
this.registerActions();
|
|
64
57
|
this.registerAITools();
|
|
65
58
|
this.app.on("afterStart", this.registerAIToolsAfterStart);
|
|
@@ -115,6 +108,13 @@ class PluginDocumentUnderstandingServer extends import_server.Plugin {
|
|
|
115
108
|
this.app.logger.warn("Document Understanding: Failed to register AI tools, continue without it.", err);
|
|
116
109
|
}
|
|
117
110
|
}
|
|
111
|
+
async afterStart() {
|
|
112
|
+
try {
|
|
113
|
+
await this.service.initialize({ recoverJobs: true });
|
|
114
|
+
} catch (err) {
|
|
115
|
+
this.app.logger.warn("Document Understanding plugin not configured yet, skip init.", err);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
118
|
async install() {
|
|
119
119
|
}
|
|
120
120
|
async afterEnable() {
|
|
@@ -124,9 +124,10 @@ class PluginDocumentUnderstandingServer extends import_server.Plugin {
|
|
|
124
124
|
async remove() {
|
|
125
125
|
}
|
|
126
126
|
async beforeStop() {
|
|
127
|
-
var _a, _b, _c, _d;
|
|
127
|
+
var _a, _b, _c, _d, _e;
|
|
128
128
|
(_b = (_a = this.app).off) == null ? void 0 : _b.call(_a, "afterStart", this.registerAIToolsAfterStart);
|
|
129
129
|
(_d = (_c = this.app).removeListener) == null ? void 0 : _d.call(_c, "afterStart", this.registerAIToolsAfterStart);
|
|
130
|
+
(_e = this.service) == null ? void 0 : _e.destroy();
|
|
130
131
|
const runtimeState = this.app;
|
|
131
132
|
if (runtimeState.documentUnderstandingService === this.service) {
|
|
132
133
|
runtimeState.documentUnderstandingService = void 0;
|
|
@@ -124,14 +124,31 @@ class DocumentUnderstandingService {
|
|
|
124
124
|
async getConfig() {
|
|
125
125
|
return this.ensureConfig();
|
|
126
126
|
}
|
|
127
|
+
async getConfigForClient() {
|
|
128
|
+
const { authKey, webhookSecret, ...config } = await this.ensureConfig();
|
|
129
|
+
return {
|
|
130
|
+
...config,
|
|
131
|
+
hasAuthKey: Boolean(authKey),
|
|
132
|
+
hasWebhookSecret: Boolean(webhookSecret)
|
|
133
|
+
};
|
|
134
|
+
}
|
|
127
135
|
async updateConfig(data) {
|
|
128
136
|
const configRepo = this.db.getRepository("doc_understanding_config");
|
|
129
137
|
const conf = await configRepo.findOne();
|
|
130
138
|
if (conf) {
|
|
131
|
-
|
|
139
|
+
const values = { ...data };
|
|
140
|
+
if (!values.authKey) delete values.authKey;
|
|
141
|
+
if (!values.webhookSecret) delete values.webhookSecret;
|
|
142
|
+
await configRepo.update({ filterByTk: conf.id, values });
|
|
132
143
|
}
|
|
133
144
|
await this.initialize();
|
|
134
145
|
}
|
|
146
|
+
destroy() {
|
|
147
|
+
var _a;
|
|
148
|
+
(_a = this.jobManager) == null ? void 0 : _a.destroy();
|
|
149
|
+
this.initialized = false;
|
|
150
|
+
this.startupRecoveryCompleted = false;
|
|
151
|
+
}
|
|
135
152
|
async listEndpoints() {
|
|
136
153
|
await this.ensureInitialized();
|
|
137
154
|
return this.db.getRepository("doc_understanding_endpoints").find({ sort: "sortOrder" });
|
|
@@ -203,14 +220,16 @@ class DocumentUnderstandingService {
|
|
|
203
220
|
const job = await this.pipelineExecutor.execute(pipelineId, input, files, userId);
|
|
204
221
|
return { jobId: job.id };
|
|
205
222
|
}
|
|
206
|
-
async getJobStatus(jobId) {
|
|
207
|
-
const
|
|
223
|
+
async getJobStatus(jobId, userId) {
|
|
224
|
+
const filter = userId ? { id: jobId, createdById: userId } : { id: jobId };
|
|
225
|
+
const job = await this.db.getRepository("doc_understanding_jobs").findOne({ filter });
|
|
208
226
|
if (!job) throw new Error("Job not found");
|
|
209
227
|
return job;
|
|
210
228
|
}
|
|
211
|
-
async listJobs(filters) {
|
|
229
|
+
async listJobs(filters, userId) {
|
|
230
|
+
const filter = userId ? { ...filters || {}, createdById: userId } : filters;
|
|
212
231
|
return this.db.getRepository("doc_understanding_jobs").find({
|
|
213
|
-
filter
|
|
232
|
+
filter,
|
|
214
233
|
sort: ["-createdAt"]
|
|
215
234
|
});
|
|
216
235
|
}
|
|
@@ -42,7 +42,6 @@ __export(PipelineExecutor_exports, {
|
|
|
42
42
|
module.exports = __toCommonJS(PipelineExecutor_exports);
|
|
43
43
|
var import_fs = require("fs");
|
|
44
44
|
var import_path = require("path");
|
|
45
|
-
var import_axios = __toESM(require("axios"));
|
|
46
45
|
var import_mime_types = __toESM(require("mime-types"));
|
|
47
46
|
const UPLOAD_ROOTS = [(0, import_path.resolve)(process.cwd(), "storage", "uploads")];
|
|
48
47
|
const isInsidePath = (basePath, targetPath) => targetPath === basePath || targetPath.startsWith(`${basePath}${import_path.sep}`);
|
|
@@ -92,7 +91,7 @@ class PipelineExecutor {
|
|
|
92
91
|
this.logger = logger;
|
|
93
92
|
}
|
|
94
93
|
async resolveFile(urlOrPath, fieldName = "file") {
|
|
95
|
-
var _a, _b;
|
|
94
|
+
var _a, _b, _c, _d;
|
|
96
95
|
if (!urlOrPath || typeof urlOrPath !== "string") return null;
|
|
97
96
|
try {
|
|
98
97
|
const localPath = resolveUploadFilePath(urlOrPath);
|
|
@@ -107,39 +106,11 @@ class PipelineExecutor {
|
|
|
107
106
|
};
|
|
108
107
|
}
|
|
109
108
|
if (urlOrPath.startsWith("http://") || urlOrPath.startsWith("https://")) {
|
|
110
|
-
|
|
111
|
-
const buffer = Buffer.from(response.data);
|
|
112
|
-
let filename = "file";
|
|
113
|
-
const disposition = response.headers["content-disposition"];
|
|
114
|
-
if (disposition && disposition.includes("filename=")) {
|
|
115
|
-
const match = disposition.match(/filename="?([^";]+)"?/);
|
|
116
|
-
if (match == null ? void 0 : match[1]) {
|
|
117
|
-
filename = match[1];
|
|
118
|
-
}
|
|
119
|
-
} else {
|
|
120
|
-
const base = (0, import_path.basename)(new URL(urlOrPath).pathname);
|
|
121
|
-
if (base && base.includes(".")) {
|
|
122
|
-
filename = base;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
const contentType = response.headers["content-type"] || "application/octet-stream";
|
|
126
|
-
const mimeType = contentType.split(";")[0].trim();
|
|
127
|
-
if (!filename.includes(".")) {
|
|
128
|
-
const extension = import_mime_types.default.extension(mimeType);
|
|
129
|
-
if (extension) {
|
|
130
|
-
filename = `${filename}.${extension}`;
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
return {
|
|
134
|
-
fieldName,
|
|
135
|
-
buffer,
|
|
136
|
-
filename,
|
|
137
|
-
mimeType
|
|
138
|
-
};
|
|
109
|
+
(_b = (_a = this.logger).warn) == null ? void 0 : _b.call(_a, "Ignoring remote file URL; use a NocoBase upload URL instead.");
|
|
139
110
|
}
|
|
140
111
|
} catch (err) {
|
|
141
112
|
const message = err instanceof Error ? err.message : String(err);
|
|
142
|
-
(
|
|
113
|
+
(_d = (_c = this.logger).warn) == null ? void 0 : _d.call(_c, `Failed to resolve file input: ${message}`);
|
|
143
114
|
}
|
|
144
115
|
return null;
|
|
145
116
|
}
|
|
@@ -151,6 +122,7 @@ class PipelineExecutor {
|
|
|
151
122
|
appends: ["steps", "steps.endpoint"]
|
|
152
123
|
});
|
|
153
124
|
if (!pipeline) throw new Error(`Pipeline ${pipelineId} not found`);
|
|
125
|
+
if (!pipeline.enabled) throw new Error(`Pipeline ${pipelineId} is disabled`);
|
|
154
126
|
const job = await jobsRepo.create({
|
|
155
127
|
values: {
|
|
156
128
|
pipelineId,
|
|
@@ -232,6 +204,7 @@ class PipelineExecutor {
|
|
|
232
204
|
return job;
|
|
233
205
|
}
|
|
234
206
|
async runSteps(job, steps, context, startFromOrder = 1) {
|
|
207
|
+
var _a;
|
|
235
208
|
const jobsRepo = this.db.getRepository("doc_understanding_jobs");
|
|
236
209
|
let currentOrder = startFromOrder;
|
|
237
210
|
try {
|
|
@@ -244,6 +217,9 @@ class PipelineExecutor {
|
|
|
244
217
|
if (!this.evaluateCondition(step.condition, context)) {
|
|
245
218
|
continue;
|
|
246
219
|
}
|
|
220
|
+
if (!((_a = step.endpoint) == null ? void 0 : _a.enabled)) {
|
|
221
|
+
throw new Error(`Endpoint for step ${step.name} is disabled`);
|
|
222
|
+
}
|
|
247
223
|
const mappedBody = this.resolveMapping(step.inputMapping || {}, context);
|
|
248
224
|
let retries = step.onError === "retry" ? step.retryCount || 0 : 0;
|
|
249
225
|
let success = false;
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"displayName": "Document Understanding",
|
|
4
4
|
"displayName.zh-CN": "文档理解",
|
|
5
5
|
"description": "Configure external document processing endpoints, chain them into pipelines, and expose enabled pipelines as AI tools.",
|
|
6
|
-
"version": "1.1.
|
|
6
|
+
"version": "1.1.9",
|
|
7
7
|
"license": "Apache-2.0",
|
|
8
8
|
"main": "dist/server/index.js",
|
|
9
9
|
"files": [
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { DocumentUnderstandingService } from '../services/DocumentUnderstandingService';
|
|
2
|
+
|
|
3
|
+
describe('DocumentUnderstandingService configuration exposure', () => {
|
|
4
|
+
const config = {
|
|
5
|
+
id: 1,
|
|
6
|
+
baseUrl: 'https://processor.example.com',
|
|
7
|
+
authType: 'bearer',
|
|
8
|
+
authKey: 'super-secret-token',
|
|
9
|
+
webhookSecret: 'webhook-secret',
|
|
10
|
+
defaultTimeout: 30000,
|
|
11
|
+
defaultRetries: 2,
|
|
12
|
+
pollInterval: 5000,
|
|
13
|
+
pollTimeout: 300000,
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
it('does not expose stored secrets to a browser caller', async () => {
|
|
17
|
+
const db = {
|
|
18
|
+
getRepository: () => ({ findOne: vi.fn().mockResolvedValue(config) }),
|
|
19
|
+
};
|
|
20
|
+
const service = new DocumentUnderstandingService({ logger: {} } as never, db as never);
|
|
21
|
+
|
|
22
|
+
await expect(service.getConfigForClient()).resolves.toEqual({
|
|
23
|
+
id: 1,
|
|
24
|
+
baseUrl: 'https://processor.example.com',
|
|
25
|
+
authType: 'bearer',
|
|
26
|
+
authHeaderName: undefined,
|
|
27
|
+
defaultTimeout: 30000,
|
|
28
|
+
defaultRetries: 2,
|
|
29
|
+
pollInterval: 5000,
|
|
30
|
+
pollTimeout: 300000,
|
|
31
|
+
hasAuthKey: true,
|
|
32
|
+
hasWebhookSecret: true,
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('keeps existing secrets when an update omits them', async () => {
|
|
37
|
+
const update = vi.fn().mockResolvedValue(undefined);
|
|
38
|
+
const db = {
|
|
39
|
+
getRepository: () => ({ findOne: vi.fn().mockResolvedValue(config), update }),
|
|
40
|
+
};
|
|
41
|
+
const service = new DocumentUnderstandingService({ logger: {} } as never, db as never);
|
|
42
|
+
|
|
43
|
+
await service.updateConfig({ baseUrl: 'https://new-processor.example.com', authKey: '' });
|
|
44
|
+
|
|
45
|
+
expect(update).toHaveBeenCalledWith({
|
|
46
|
+
filterByTk: 1,
|
|
47
|
+
values: { baseUrl: 'https://new-processor.example.com' },
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
function createExecutor(pipeline: Record<string, unknown>) {
|
|
53
|
+
const jobsRepo = { create: vi.fn() };
|
|
54
|
+
const db = {
|
|
55
|
+
getRepository: vi.fn((name: string) =>
|
|
56
|
+
name === 'doc_understanding_pipelines' ? { findOne: vi.fn().mockResolvedValue(pipeline) } : jobsRepo,
|
|
57
|
+
),
|
|
58
|
+
};
|
|
59
|
+
return { db, jobsRepo };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
describe('Pipeline execution guards', () => {
|
|
63
|
+
it('rejects a disabled pipeline before creating a job', async () => {
|
|
64
|
+
const { db, jobsRepo } = createExecutor({ id: 1, enabled: false, steps: [] });
|
|
65
|
+
const { PipelineExecutor } = await import('../services/PipelineExecutor');
|
|
66
|
+
const executor = new PipelineExecutor(db as never, {} as never, {} as never, { error: vi.fn() });
|
|
67
|
+
|
|
68
|
+
await expect(executor.execute(1, {})).rejects.toThrow('disabled');
|
|
69
|
+
expect(jobsRepo.create).not.toHaveBeenCalled();
|
|
70
|
+
});
|
|
71
|
+
});
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { mkdirSync, rmSync, writeFileSync } from 'fs';
|
|
2
2
|
import { resolve } from 'path';
|
|
3
|
-
import
|
|
3
|
+
import axios from 'axios';
|
|
4
|
+
import { AsyncJobManager } from '../services/AsyncJobManager';
|
|
5
|
+
import { ExternalApiClient } from '../services/ExternalApiClient';
|
|
6
|
+
import { PipelineExecutor, resolveUploadFilePath } from '../services/PipelineExecutor';
|
|
4
7
|
|
|
5
8
|
describe('PipelineExecutor upload path resolution', () => {
|
|
6
9
|
const uploadsRoot = resolve(process.cwd(), 'storage', 'uploads');
|
|
@@ -30,4 +33,23 @@ describe('PipelineExecutor upload path resolution', () => {
|
|
|
30
33
|
it('maps upload URLs by pathname only', () => {
|
|
31
34
|
expect(resolveUploadFilePath('https://example.com/uploads/du-test/sample.txt?token=secret')).toBe(samplePath);
|
|
32
35
|
});
|
|
36
|
+
|
|
37
|
+
it('does not resolve arbitrary remote URLs as upload files', () => {
|
|
38
|
+
expect(resolveUploadFilePath('https://evil.example/private.pdf')).toBeNull();
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
describe('PipelineExecutor remote file handling', () => {
|
|
43
|
+
it('does not fetch arbitrary remote URLs', async () => {
|
|
44
|
+
const getSpy = vi.spyOn(axios, 'get');
|
|
45
|
+
const executor = new PipelineExecutor(
|
|
46
|
+
{ getRepository: vi.fn() } as never,
|
|
47
|
+
{} as ExternalApiClient,
|
|
48
|
+
{} as AsyncJobManager,
|
|
49
|
+
{ error: vi.fn(), warn: vi.fn() },
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
await expect((executor as any).resolveFile('https://evil.example/private.pdf')).resolves.toBeNull();
|
|
53
|
+
expect(getSpy).not.toHaveBeenCalled();
|
|
54
|
+
});
|
|
33
55
|
});
|
package/src/server/actions.ts
CHANGED
|
@@ -36,7 +36,7 @@ export const defineActions = (plugin: DocumentUnderstandingPluginLike) => {
|
|
|
36
36
|
|
|
37
37
|
return {
|
|
38
38
|
async getConfig(ctx: Context, next: () => Promise<any>) {
|
|
39
|
-
ctx.body = await service.
|
|
39
|
+
ctx.body = await service.getConfigForClient();
|
|
40
40
|
await next();
|
|
41
41
|
},
|
|
42
42
|
|
package/src/server/plugin.ts
CHANGED
|
@@ -29,27 +29,18 @@ export class PluginDocumentUnderstandingServer extends Plugin {
|
|
|
29
29
|
|
|
30
30
|
async afterAdd() {}
|
|
31
31
|
|
|
32
|
-
async beforeLoad() {
|
|
33
|
-
|
|
34
|
-
async load() {
|
|
35
|
-
// 1. Import collections
|
|
32
|
+
async beforeLoad() {
|
|
36
33
|
await this.db.import({
|
|
37
34
|
directory: resolve(__dirname, 'collections'),
|
|
38
35
|
});
|
|
36
|
+
}
|
|
39
37
|
|
|
40
|
-
|
|
38
|
+
async load() {
|
|
39
|
+
// Collections are imported in beforeLoad so database metadata exists before
|
|
40
|
+
// resources and runtime services are registered.
|
|
41
41
|
this.service = new DocumentUnderstandingService(this.app, this.db);
|
|
42
42
|
|
|
43
|
-
//
|
|
44
|
-
this.app.on('afterStart', async () => {
|
|
45
|
-
try {
|
|
46
|
-
await this.service.initialize({ recoverJobs: true });
|
|
47
|
-
} catch (err) {
|
|
48
|
-
this.app.logger.warn('Document Understanding plugin not configured yet, skip init.', err);
|
|
49
|
-
}
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
// 3. Register REST actions
|
|
43
|
+
// Register REST actions
|
|
53
44
|
this.registerActions();
|
|
54
45
|
|
|
55
46
|
// 4. Register AI tool (graceful)
|
|
@@ -113,6 +104,14 @@ export class PluginDocumentUnderstandingServer extends Plugin {
|
|
|
113
104
|
}
|
|
114
105
|
}
|
|
115
106
|
|
|
107
|
+
async afterStart() {
|
|
108
|
+
try {
|
|
109
|
+
await this.service.initialize({ recoverJobs: true });
|
|
110
|
+
} catch (err) {
|
|
111
|
+
this.app.logger.warn('Document Understanding plugin not configured yet, skip init.', err);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
116
115
|
async install() {}
|
|
117
116
|
|
|
118
117
|
async afterEnable() {}
|
|
@@ -124,6 +123,7 @@ export class PluginDocumentUnderstandingServer extends Plugin {
|
|
|
124
123
|
async beforeStop() {
|
|
125
124
|
this.app.off?.('afterStart', this.registerAIToolsAfterStart);
|
|
126
125
|
this.app.removeListener?.('afterStart', this.registerAIToolsAfterStart);
|
|
126
|
+
this.service?.destroy();
|
|
127
127
|
const runtimeState = this.app as typeof this.app & DocumentToolRuntimeState;
|
|
128
128
|
if (runtimeState.documentUnderstandingService === this.service) {
|
|
129
129
|
runtimeState.documentUnderstandingService = undefined;
|
|
@@ -4,7 +4,7 @@ import { Database, Repository } from '@nocobase/database';
|
|
|
4
4
|
import { ExternalApiClient, FileInput } from './ExternalApiClient';
|
|
5
5
|
import { AsyncJobManager } from './AsyncJobManager';
|
|
6
6
|
import { PipelineExecutor } from './PipelineExecutor';
|
|
7
|
-
import { ServiceConfig, EndpointDef, PipelineDef, JobState } from '../types';
|
|
7
|
+
import { ClientServiceConfig, ServiceConfig, EndpointDef, PipelineDef, JobState } from '../types';
|
|
8
8
|
|
|
9
9
|
export class DocumentUnderstandingService {
|
|
10
10
|
private app: Application;
|
|
@@ -101,16 +101,34 @@ export class DocumentUnderstandingService {
|
|
|
101
101
|
return this.ensureConfig();
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
+
async getConfigForClient(): Promise<ClientServiceConfig> {
|
|
105
|
+
const { authKey, webhookSecret, ...config } = await this.ensureConfig();
|
|
106
|
+
return {
|
|
107
|
+
...config,
|
|
108
|
+
hasAuthKey: Boolean(authKey),
|
|
109
|
+
hasWebhookSecret: Boolean(webhookSecret),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
104
113
|
async updateConfig(data: Partial<ServiceConfig>): Promise<void> {
|
|
105
114
|
const configRepo = this.db.getRepository<any>('doc_understanding_config');
|
|
106
115
|
const conf = await configRepo.findOne();
|
|
107
116
|
if (conf) {
|
|
108
|
-
|
|
117
|
+
const values = { ...data };
|
|
118
|
+
if (!values.authKey) delete values.authKey;
|
|
119
|
+
if (!values.webhookSecret) delete values.webhookSecret;
|
|
120
|
+
await configRepo.update({ filterByTk: conf.id, values });
|
|
109
121
|
}
|
|
110
122
|
// Reinitialize to pick up new config
|
|
111
123
|
await this.initialize();
|
|
112
124
|
}
|
|
113
125
|
|
|
126
|
+
destroy(): void {
|
|
127
|
+
this.jobManager?.destroy();
|
|
128
|
+
this.initialized = false;
|
|
129
|
+
this.startupRecoveryCompleted = false;
|
|
130
|
+
}
|
|
131
|
+
|
|
114
132
|
async listEndpoints(): Promise<EndpointDef[]> {
|
|
115
133
|
await this.ensureInitialized();
|
|
116
134
|
return this.db.getRepository<any>('doc_understanding_endpoints').find({ sort: 'sortOrder' });
|
|
@@ -200,15 +218,17 @@ export class DocumentUnderstandingService {
|
|
|
200
218
|
return { jobId: job.id };
|
|
201
219
|
}
|
|
202
220
|
|
|
203
|
-
async getJobStatus(jobId: number): Promise<JobState> {
|
|
204
|
-
const
|
|
221
|
+
async getJobStatus(jobId: number, userId?: number): Promise<JobState> {
|
|
222
|
+
const filter = userId ? { id: jobId, createdById: userId } : { id: jobId };
|
|
223
|
+
const job = await this.db.getRepository<any>('doc_understanding_jobs').findOne({ filter });
|
|
205
224
|
if (!job) throw new Error('Job not found');
|
|
206
225
|
return job;
|
|
207
226
|
}
|
|
208
227
|
|
|
209
|
-
async listJobs(filters?:
|
|
228
|
+
async listJobs(filters?: Record<string, unknown>, userId?: number): Promise<JobState[]> {
|
|
229
|
+
const filter = userId ? { ...(filters || {}), createdById: userId } : filters;
|
|
210
230
|
return this.db.getRepository<any>('doc_understanding_jobs').find({
|
|
211
|
-
filter
|
|
231
|
+
filter,
|
|
212
232
|
sort: ['-createdAt'],
|
|
213
233
|
});
|
|
214
234
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { existsSync, realpathSync, readFileSync, statSync } from 'fs';
|
|
2
2
|
import { basename, resolve, sep } from 'path';
|
|
3
3
|
import { Database } from '@nocobase/database';
|
|
4
|
-
import axios from 'axios';
|
|
5
4
|
import mime from 'mime-types';
|
|
6
5
|
import { ExternalApiClient, FileInput } from './ExternalApiClient';
|
|
7
6
|
import { AsyncJobManager } from './AsyncJobManager';
|
|
@@ -100,39 +99,10 @@ export class PipelineExecutor {
|
|
|
100
99
|
};
|
|
101
100
|
}
|
|
102
101
|
|
|
102
|
+
// Only files in NocoBase's upload storage are accepted. Fetching arbitrary
|
|
103
|
+
// HTTP(S) URLs here would turn a user/AI-provided value into an SSRF primitive.
|
|
103
104
|
if (urlOrPath.startsWith('http://') || urlOrPath.startsWith('https://')) {
|
|
104
|
-
|
|
105
|
-
const buffer = Buffer.from(response.data);
|
|
106
|
-
|
|
107
|
-
let filename = 'file';
|
|
108
|
-
const disposition = response.headers['content-disposition'];
|
|
109
|
-
if (disposition && disposition.includes('filename=')) {
|
|
110
|
-
const match = disposition.match(/filename="?([^";]+)"?/);
|
|
111
|
-
if (match?.[1]) {
|
|
112
|
-
filename = match[1];
|
|
113
|
-
}
|
|
114
|
-
} else {
|
|
115
|
-
const base = basename(new URL(urlOrPath).pathname);
|
|
116
|
-
if (base && base.includes('.')) {
|
|
117
|
-
filename = base;
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
const contentType = response.headers['content-type'] || 'application/octet-stream';
|
|
122
|
-
const mimeType = contentType.split(';')[0].trim();
|
|
123
|
-
if (!filename.includes('.')) {
|
|
124
|
-
const extension = mime.extension(mimeType);
|
|
125
|
-
if (extension) {
|
|
126
|
-
filename = `${filename}.${extension}`;
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
return {
|
|
131
|
-
fieldName,
|
|
132
|
-
buffer,
|
|
133
|
-
filename,
|
|
134
|
-
mimeType,
|
|
135
|
-
};
|
|
105
|
+
this.logger.warn?.('Ignoring remote file URL; use a NocoBase upload URL instead.');
|
|
136
106
|
}
|
|
137
107
|
} catch (err) {
|
|
138
108
|
const message = err instanceof Error ? err.message : String(err);
|
|
@@ -157,6 +127,7 @@ export class PipelineExecutor {
|
|
|
157
127
|
});
|
|
158
128
|
|
|
159
129
|
if (!pipeline) throw new Error(`Pipeline ${pipelineId} not found`);
|
|
130
|
+
if (!pipeline.enabled) throw new Error(`Pipeline ${pipelineId} is disabled`);
|
|
160
131
|
|
|
161
132
|
// Create Job
|
|
162
133
|
const job = await jobsRepo.create({
|
|
@@ -282,6 +253,10 @@ export class PipelineExecutor {
|
|
|
282
253
|
continue; // Skip step
|
|
283
254
|
}
|
|
284
255
|
|
|
256
|
+
if (!step.endpoint?.enabled) {
|
|
257
|
+
throw new Error(`Endpoint for step ${step.name} is disabled`);
|
|
258
|
+
}
|
|
259
|
+
|
|
285
260
|
const mappedBody = this.resolveMapping(step.inputMapping || {}, context);
|
|
286
261
|
let retries = step.onError === 'retry' ? step.retryCount || 0 : 0;
|
|
287
262
|
let success = false;
|
package/src/server/types.ts
CHANGED
|
@@ -11,6 +11,11 @@ export interface ServiceConfig {
|
|
|
11
11
|
webhookSecret?: string;
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
+
export type ClientServiceConfig = Omit<ServiceConfig, 'authKey' | 'webhookSecret'> & {
|
|
15
|
+
hasAuthKey: boolean;
|
|
16
|
+
hasWebhookSecret: boolean;
|
|
17
|
+
};
|
|
18
|
+
|
|
14
19
|
export interface EndpointDef {
|
|
15
20
|
id: number;
|
|
16
21
|
name: string;
|