@erxes/plugin-sdk 0.1.0-v2.1 → 0.1.0-v2.10
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/client.d.ts +219 -2
- package/dist/client.js +54 -22
- package/dist/filter.d.ts +67 -0
- package/dist/filter.js +205 -0
- package/dist/index.d.ts +58 -3
- package/dist/index.js +3 -2
- package/dist/jobs.d.ts +23 -0
- package/dist/jobs.js +18 -0
- package/dist/verify.d.ts +45 -23
- package/dist/verify.js +75 -5
- package/package.json +11 -3
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { PluginManifest, coreContract } from "@erxes/core-contract";
|
|
2
|
+
import { z } from "zod";
|
|
2
3
|
import { ContractRouterClient } from "@orpc/contract";
|
|
3
4
|
export type CoreClient = ContractRouterClient<typeof coreContract>;
|
|
4
5
|
export interface CoreClientOptions {
|
|
@@ -19,9 +20,225 @@ export declare const createCoreClient: (options: CoreClientOptions) => {
|
|
|
19
20
|
/** Declares the plugin's UI, API, scopes, permissions and events. Call at startup. */
|
|
20
21
|
registerManifest: (manifest: PluginManifest) => import("@orpc/client").ClientPromiseResult<{
|
|
21
22
|
ok: true;
|
|
22
|
-
},
|
|
23
|
+
}, import("@orpc/contract").ErrorFromErrorMap<import("@orpc/contract").MergedErrorMap<Record<never, never>, {
|
|
24
|
+
UNAUTHORIZED: {
|
|
25
|
+
status: number;
|
|
26
|
+
};
|
|
27
|
+
NOT_ALLOWED: {
|
|
28
|
+
status: number;
|
|
29
|
+
data: z.ZodOptional<z.ZodObject<{
|
|
30
|
+
permission: z.ZodString;
|
|
31
|
+
}, z.core.$strip>>;
|
|
32
|
+
};
|
|
33
|
+
PLUGIN_ONLY: {
|
|
34
|
+
status: number;
|
|
35
|
+
};
|
|
36
|
+
MEMBERS_ONLY: {
|
|
37
|
+
status: number;
|
|
38
|
+
};
|
|
39
|
+
ORG_REQUIRED: {
|
|
40
|
+
status: number;
|
|
41
|
+
};
|
|
42
|
+
SCOPE_REQUIRED: {
|
|
43
|
+
status: number;
|
|
44
|
+
};
|
|
45
|
+
SERVICE_TOKEN_REQUIRED: {
|
|
46
|
+
status: number;
|
|
47
|
+
};
|
|
48
|
+
ORGANIZATION_DISABLED: {
|
|
49
|
+
status: number;
|
|
50
|
+
data: z.ZodObject<{
|
|
51
|
+
manageUrl: z.ZodNullable<z.ZodString>;
|
|
52
|
+
}, z.core.$strip>;
|
|
53
|
+
};
|
|
54
|
+
NOT_IN_PLAN: {
|
|
55
|
+
status: number;
|
|
56
|
+
data: z.ZodOptional<z.ZodObject<{
|
|
57
|
+
manageUrl: z.ZodNullable<z.ZodString>;
|
|
58
|
+
}, z.core.$strip>>;
|
|
59
|
+
};
|
|
60
|
+
READ_ONLY: {
|
|
61
|
+
status: number;
|
|
62
|
+
};
|
|
63
|
+
TOO_MANY_REQUESTS: {
|
|
64
|
+
status: number;
|
|
65
|
+
};
|
|
66
|
+
INVALID_INPUT: {
|
|
67
|
+
status: number;
|
|
68
|
+
data: z.ZodObject<{
|
|
69
|
+
issues: z.ZodArray<z.ZodObject<{
|
|
70
|
+
path: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodInt]>>;
|
|
71
|
+
message: z.ZodString;
|
|
72
|
+
}, z.core.$strip>>;
|
|
73
|
+
}, z.core.$strip>;
|
|
74
|
+
};
|
|
75
|
+
NOT_FOUND: {
|
|
76
|
+
status: number;
|
|
77
|
+
};
|
|
78
|
+
TAKEN: {
|
|
79
|
+
status: number;
|
|
80
|
+
data: z.ZodObject<{
|
|
81
|
+
field: z.ZodString;
|
|
82
|
+
id: z.ZodOptional<z.ZodString>;
|
|
83
|
+
values: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
84
|
+
}, z.core.$strip>;
|
|
85
|
+
};
|
|
86
|
+
INVALID_CURSOR: {
|
|
87
|
+
status: number;
|
|
88
|
+
};
|
|
89
|
+
INVALID_REFERENCE: {
|
|
90
|
+
status: number;
|
|
91
|
+
data: z.ZodObject<{
|
|
92
|
+
field: z.ZodString;
|
|
93
|
+
}, z.core.$strip>;
|
|
94
|
+
};
|
|
95
|
+
INVALID_FILTER: {
|
|
96
|
+
status: number;
|
|
97
|
+
};
|
|
98
|
+
FILTER_TOO_SLOW: {
|
|
99
|
+
status: number;
|
|
100
|
+
};
|
|
101
|
+
CROSS_SITE: {
|
|
102
|
+
status: number;
|
|
103
|
+
};
|
|
104
|
+
DUPLICATE_PERMISSION_SET: {
|
|
105
|
+
status: number;
|
|
106
|
+
};
|
|
107
|
+
INVALID_CLIENT: {
|
|
108
|
+
status: number;
|
|
109
|
+
};
|
|
110
|
+
INVALID_SCHEDULE: {
|
|
111
|
+
status: number;
|
|
112
|
+
};
|
|
113
|
+
LIMIT_EXCEEDED: {
|
|
114
|
+
status: number;
|
|
115
|
+
};
|
|
116
|
+
NAMESPACE_REQUIRED: {
|
|
117
|
+
status: number;
|
|
118
|
+
};
|
|
119
|
+
NOT_INSTALLED: {
|
|
120
|
+
status: number;
|
|
121
|
+
};
|
|
122
|
+
PLUGIN_NOT_FOUND: {
|
|
123
|
+
status: number;
|
|
124
|
+
};
|
|
125
|
+
UNKNOWN_PERMISSION: {
|
|
126
|
+
status: number;
|
|
127
|
+
data: z.ZodObject<{
|
|
128
|
+
permissions: z.ZodArray<z.ZodString>;
|
|
129
|
+
}, z.core.$strip>;
|
|
130
|
+
};
|
|
131
|
+
}>>>;
|
|
23
132
|
/** Tells the plugin's open UIs that topics changed (needs `live:write`). */
|
|
24
133
|
signal: (orgId: string, topics: string[], userIds?: string[]) => import("@orpc/client").ClientPromiseResult<{
|
|
25
134
|
ok: true;
|
|
26
|
-
},
|
|
135
|
+
}, import("@orpc/contract").ErrorFromErrorMap<import("@orpc/contract").MergedErrorMap<Record<never, never>, {
|
|
136
|
+
UNAUTHORIZED: {
|
|
137
|
+
status: number;
|
|
138
|
+
};
|
|
139
|
+
NOT_ALLOWED: {
|
|
140
|
+
status: number;
|
|
141
|
+
data: z.ZodOptional<z.ZodObject<{
|
|
142
|
+
permission: z.ZodString;
|
|
143
|
+
}, z.core.$strip>>;
|
|
144
|
+
};
|
|
145
|
+
PLUGIN_ONLY: {
|
|
146
|
+
status: number;
|
|
147
|
+
};
|
|
148
|
+
MEMBERS_ONLY: {
|
|
149
|
+
status: number;
|
|
150
|
+
};
|
|
151
|
+
ORG_REQUIRED: {
|
|
152
|
+
status: number;
|
|
153
|
+
};
|
|
154
|
+
SCOPE_REQUIRED: {
|
|
155
|
+
status: number;
|
|
156
|
+
};
|
|
157
|
+
SERVICE_TOKEN_REQUIRED: {
|
|
158
|
+
status: number;
|
|
159
|
+
};
|
|
160
|
+
ORGANIZATION_DISABLED: {
|
|
161
|
+
status: number;
|
|
162
|
+
data: z.ZodObject<{
|
|
163
|
+
manageUrl: z.ZodNullable<z.ZodString>;
|
|
164
|
+
}, z.core.$strip>;
|
|
165
|
+
};
|
|
166
|
+
NOT_IN_PLAN: {
|
|
167
|
+
status: number;
|
|
168
|
+
data: z.ZodOptional<z.ZodObject<{
|
|
169
|
+
manageUrl: z.ZodNullable<z.ZodString>;
|
|
170
|
+
}, z.core.$strip>>;
|
|
171
|
+
};
|
|
172
|
+
READ_ONLY: {
|
|
173
|
+
status: number;
|
|
174
|
+
};
|
|
175
|
+
TOO_MANY_REQUESTS: {
|
|
176
|
+
status: number;
|
|
177
|
+
};
|
|
178
|
+
INVALID_INPUT: {
|
|
179
|
+
status: number;
|
|
180
|
+
data: z.ZodObject<{
|
|
181
|
+
issues: z.ZodArray<z.ZodObject<{
|
|
182
|
+
path: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodInt]>>;
|
|
183
|
+
message: z.ZodString;
|
|
184
|
+
}, z.core.$strip>>;
|
|
185
|
+
}, z.core.$strip>;
|
|
186
|
+
};
|
|
187
|
+
NOT_FOUND: {
|
|
188
|
+
status: number;
|
|
189
|
+
};
|
|
190
|
+
TAKEN: {
|
|
191
|
+
status: number;
|
|
192
|
+
data: z.ZodObject<{
|
|
193
|
+
field: z.ZodString;
|
|
194
|
+
id: z.ZodOptional<z.ZodString>;
|
|
195
|
+
values: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
196
|
+
}, z.core.$strip>;
|
|
197
|
+
};
|
|
198
|
+
INVALID_CURSOR: {
|
|
199
|
+
status: number;
|
|
200
|
+
};
|
|
201
|
+
INVALID_REFERENCE: {
|
|
202
|
+
status: number;
|
|
203
|
+
data: z.ZodObject<{
|
|
204
|
+
field: z.ZodString;
|
|
205
|
+
}, z.core.$strip>;
|
|
206
|
+
};
|
|
207
|
+
INVALID_FILTER: {
|
|
208
|
+
status: number;
|
|
209
|
+
};
|
|
210
|
+
FILTER_TOO_SLOW: {
|
|
211
|
+
status: number;
|
|
212
|
+
};
|
|
213
|
+
CROSS_SITE: {
|
|
214
|
+
status: number;
|
|
215
|
+
};
|
|
216
|
+
DUPLICATE_PERMISSION_SET: {
|
|
217
|
+
status: number;
|
|
218
|
+
};
|
|
219
|
+
INVALID_CLIENT: {
|
|
220
|
+
status: number;
|
|
221
|
+
};
|
|
222
|
+
INVALID_SCHEDULE: {
|
|
223
|
+
status: number;
|
|
224
|
+
};
|
|
225
|
+
LIMIT_EXCEEDED: {
|
|
226
|
+
status: number;
|
|
227
|
+
};
|
|
228
|
+
NAMESPACE_REQUIRED: {
|
|
229
|
+
status: number;
|
|
230
|
+
};
|
|
231
|
+
NOT_INSTALLED: {
|
|
232
|
+
status: number;
|
|
233
|
+
};
|
|
234
|
+
PLUGIN_NOT_FOUND: {
|
|
235
|
+
status: number;
|
|
236
|
+
};
|
|
237
|
+
UNKNOWN_PERMISSION: {
|
|
238
|
+
status: number;
|
|
239
|
+
data: z.ZodObject<{
|
|
240
|
+
permissions: z.ZodArray<z.ZodString>;
|
|
241
|
+
}, z.core.$strip>;
|
|
242
|
+
};
|
|
243
|
+
}>>>;
|
|
27
244
|
};
|
package/dist/client.js
CHANGED
|
@@ -20,21 +20,35 @@ const TokenAnswer = z.object({
|
|
|
20
20
|
code: z.string().optional(),
|
|
21
21
|
message: z.string().optional()
|
|
22
22
|
});
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
23
|
+
/** A cached token is replaced this long before it ends, so no call carries an expiring one. */
|
|
24
|
+
const RENEW_BEFORE_MS = 6e4;
|
|
25
|
+
/** The pause before the one retry of a token request that failed on core's side. */
|
|
26
|
+
const TOKEN_RETRY_MS = 500;
|
|
27
|
+
/** The plugin's core tokens, one per organisation (and one for the deployment), kept fresh. */
|
|
28
|
+
const pluginTokens = (options, fetcher, base) => {
|
|
26
29
|
const tokens = /* @__PURE__ */ new Map();
|
|
30
|
+
const askOnce = (org) => fetcher(`${base}${CORE_API_PREFIX}/plugins/token`, {
|
|
31
|
+
method: "POST",
|
|
32
|
+
headers: { "content-type": "application/json" },
|
|
33
|
+
body: JSON.stringify({
|
|
34
|
+
grant_type: "client_credentials",
|
|
35
|
+
client_id: options.plugin,
|
|
36
|
+
client_secret: options.clientSecret,
|
|
37
|
+
org
|
|
38
|
+
})
|
|
39
|
+
});
|
|
40
|
+
/** Core restarting or a network blip gets one more try; the second failure is the answer. */
|
|
41
|
+
const ask = async (org) => {
|
|
42
|
+
try {
|
|
43
|
+
const response = await askOnce(org);
|
|
44
|
+
if (response.status < 500) return response;
|
|
45
|
+
await response.body?.cancel();
|
|
46
|
+
} catch {}
|
|
47
|
+
await new Promise((resolve) => setTimeout(resolve, TOKEN_RETRY_MS));
|
|
48
|
+
return askOnce(org);
|
|
49
|
+
};
|
|
27
50
|
const requestToken = async (org) => {
|
|
28
|
-
const response = await
|
|
29
|
-
method: "POST",
|
|
30
|
-
headers: { "content-type": "application/json" },
|
|
31
|
-
body: JSON.stringify({
|
|
32
|
-
grant_type: "client_credentials",
|
|
33
|
-
client_id: options.plugin,
|
|
34
|
-
client_secret: options.clientSecret,
|
|
35
|
-
org
|
|
36
|
-
})
|
|
37
|
-
});
|
|
51
|
+
const response = await ask(org);
|
|
38
52
|
const body = TokenAnswer.safeParse(await response.json().catch(() => null)).data ?? {};
|
|
39
53
|
if (!response.ok || !body.access_token) throw new CoreTokenError(response.status, body.code ?? "TOKEN_FAILED", body.message ?? "Could not get a core token");
|
|
40
54
|
return {
|
|
@@ -42,29 +56,47 @@ const createCoreClient = (options) => {
|
|
|
42
56
|
expiresAt: Date.now() + (body.expires_in ?? 900) * 1e3
|
|
43
57
|
};
|
|
44
58
|
};
|
|
45
|
-
/**
|
|
46
|
-
|
|
59
|
+
/**
|
|
60
|
+
* The organisation's (or the deployment's) token, renewed a minute before it
|
|
61
|
+
* ends. `refused` is a token core just turned down: it is replaced once, for
|
|
62
|
+
* every call that failed with it at the same time.
|
|
63
|
+
*/
|
|
64
|
+
return async (org, refused) => {
|
|
47
65
|
const key = org ?? "";
|
|
48
66
|
const cached = tokens.get(key);
|
|
49
|
-
if (cached
|
|
67
|
+
if (cached) {
|
|
50
68
|
const value = await cached.catch(() => null);
|
|
51
|
-
if (value && value.expiresAt - Date.now() >
|
|
69
|
+
if (value && value.token !== refused && value.expiresAt - Date.now() > RENEW_BEFORE_MS) return value.token;
|
|
70
|
+
const renewing = tokens.get(key);
|
|
71
|
+
if (renewing && renewing !== cached) return (await renewing).token;
|
|
52
72
|
}
|
|
53
73
|
const request = requestToken(org);
|
|
54
74
|
tokens.set(key, request);
|
|
55
|
-
request.catch(() =>
|
|
75
|
+
request.catch(() => {
|
|
76
|
+
if (tokens.get(key) === request) tokens.delete(key);
|
|
77
|
+
});
|
|
56
78
|
return (await request).token;
|
|
57
79
|
};
|
|
80
|
+
};
|
|
81
|
+
const createCoreClient = (options) => {
|
|
82
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
83
|
+
const base = options.coreUrl.replace(/\/+$/, "");
|
|
84
|
+
const tokenFor = pluginTokens(options, fetcher, base);
|
|
58
85
|
const clientFor = (org) => createORPCClient(new OpenAPILink(coreRoutes, {
|
|
59
86
|
url: `${base}${CORE_API_PREFIX}`,
|
|
60
87
|
fetch: async (request, init) => {
|
|
61
|
-
const
|
|
88
|
+
const body = request.body ? await request.arrayBuffer() : void 0;
|
|
89
|
+
const send = (token) => {
|
|
62
90
|
const headers = new Headers(request.headers);
|
|
63
91
|
headers.set("authorization", `Bearer ${token}`);
|
|
64
|
-
return fetcher(new Request(request,
|
|
92
|
+
return fetcher(new Request(request, body ? {
|
|
93
|
+
headers,
|
|
94
|
+
body
|
|
95
|
+
} : { headers }), init);
|
|
65
96
|
};
|
|
66
|
-
const
|
|
67
|
-
|
|
97
|
+
const token = await tokenFor(org);
|
|
98
|
+
const response = await send(token);
|
|
99
|
+
return response.status === 401 ? send(await tokenFor(org, token)) : response;
|
|
68
100
|
}
|
|
69
101
|
}));
|
|
70
102
|
const orgClients = /* @__PURE__ */ new Map();
|
package/dist/filter.d.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A list's filter bar (erxes-ui's `ListFilter`) as SQL, the way core compiles its own lists:
|
|
3
|
+
*
|
|
4
|
+
* const FIELDS = {
|
|
5
|
+
* 'subject.name': { type: 'text', expr: tickets.name },
|
|
6
|
+
* 'subject.assigneeIds': { type: 'member', expr: tickets.assigneeIds, array: true },
|
|
7
|
+
* 'subject.tagIds': { type: 'tags', expr: tickets.tagIds },
|
|
8
|
+
* 'subject.createdAt': { type: 'date', expr: tickets.createdAt },
|
|
9
|
+
* } satisfies FilterFields;
|
|
10
|
+
*
|
|
11
|
+
* input: z.object({ filter: FilterParam.optional() }),
|
|
12
|
+
* .where(compileFilter(FIELDS, input.filter, { me: member.userId }))
|
|
13
|
+
*
|
|
14
|
+
* A rule on a path `fields` lacks, or with an operator or value its field can't take, throws
|
|
15
|
+
* core's 400 `INVALID_FILTER`.
|
|
16
|
+
*/
|
|
17
|
+
import { ConditionGroup, ConditionRule, FilterField } from "@erxes/core-contract";
|
|
18
|
+
import { ORPCError } from "@orpc/client";
|
|
19
|
+
import { z } from "zod";
|
|
20
|
+
import { Column, SQL } from "drizzle-orm";
|
|
21
|
+
/** A filter that doesn't fit its fields: core's 400 `INVALID_FILTER`. */
|
|
22
|
+
export declare const invalidFilter: (message: string) => ORPCError<"INVALID_FILTER", unknown>;
|
|
23
|
+
/** One field a list can be filtered by, as `ListFilter`'s field `type` says it compares. */
|
|
24
|
+
export interface FilterColumn {
|
|
25
|
+
/** `member`, `customer` and `company` hold ids of those records; "me" is a member. */
|
|
26
|
+
type: FilterField['type'];
|
|
27
|
+
/** The value as SQL: a column, or an expression over the list's table. */
|
|
28
|
+
expr: Column | SQL;
|
|
29
|
+
/** Named in errors; the path when absent. */
|
|
30
|
+
label?: string;
|
|
31
|
+
/** A `text[]` column, such as members or tag ids: "is" means "has". `tags` always is one. */
|
|
32
|
+
array?: boolean;
|
|
33
|
+
/** Only a day, no time: dates compare as dates, so an index on them applies. */
|
|
34
|
+
dateOnly?: boolean;
|
|
35
|
+
/** Text with a trigram index: "is" is an ILIKE without wildcards, so the index serves it. */
|
|
36
|
+
trigram?: boolean;
|
|
37
|
+
/** "Anniversary within" reads this month * 100 + day expression (a stored birthday's). */
|
|
38
|
+
monthDay?: SQL;
|
|
39
|
+
}
|
|
40
|
+
/** The fields a list can be filtered by, keyed by the rules' paths (`subject.<name>`). */
|
|
41
|
+
export type FilterFields = Record<string, FilterColumn>;
|
|
42
|
+
/** "Me" in a member rule: the member asking, if a member is. */
|
|
43
|
+
export interface FilterContext {
|
|
44
|
+
me?: string | null;
|
|
45
|
+
}
|
|
46
|
+
/** A list's `filter` query parameter: the condition group as JSON. */
|
|
47
|
+
export declare const FilterParam: z.ZodType<ConditionGroup, string>;
|
|
48
|
+
/** A text array parameter (a JS array in a template becomes a list of parameters, not one array). */
|
|
49
|
+
export declare const textArray: (values: string[]) => SQL<unknown>;
|
|
50
|
+
/** A LIKE pattern's text, where `%`, `_` and `\` match themselves. */
|
|
51
|
+
export declare const escapeLike: (value: string) => string;
|
|
52
|
+
export declare const text: (value: unknown) => string;
|
|
53
|
+
export declare const list: (value: unknown) => string[];
|
|
54
|
+
export declare const number: (value: unknown) => number;
|
|
55
|
+
/** Negative ops on a relation or a custom field: "none where …" rather than "one where not …". */
|
|
56
|
+
export declare const NEGATIVE: Partial<Record<ConditionRule['op'], ConditionRule['op']>>;
|
|
57
|
+
export declare const COMPARE: Partial<Record<ConditionRule['op'], string>>;
|
|
58
|
+
/** Date rules. Day-only values compare with days, so an index on them applies. */
|
|
59
|
+
export declare const compileDate: (x: SQL | Column, op: ConditionRule['op'], value: unknown, dateOnly: boolean, monthDay?: SQL) => SQL | undefined;
|
|
60
|
+
/** A rule's list of values, lower-cased, as a `text[]` parameter. */
|
|
61
|
+
export declare const lowerList: (value: unknown) => SQL<unknown>;
|
|
62
|
+
/** One rule on one field, or `INVALID_FILTER` when the field can't take its operator or value. */
|
|
63
|
+
export declare const compileColumn: (field: FilterColumn, path: string, rule: ConditionRule, context?: FilterContext) => SQL;
|
|
64
|
+
/** A condition group as SQL, each rule through `compileRule`: all of its rules, or any. */
|
|
65
|
+
export declare const compileGroup: (group: ConditionGroup, compileRule: (rule: ConditionRule) => SQL, depth?: number) => SQL | undefined;
|
|
66
|
+
/** A list's filter as one SQL condition on its table, or undefined when it has no rules. */
|
|
67
|
+
export declare const compileFilter: (fields: FilterFields, filter: ConditionGroup | null | undefined, context?: FilterContext) => SQL<unknown> | undefined;
|
package/dist/filter.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { ERRORS, RecordFilter } from "@erxes/core-contract";
|
|
2
|
+
import { ORPCError } from "@orpc/client";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { and, inArray, not, or, sql } from "drizzle-orm";
|
|
5
|
+
// src/filter.ts
|
|
6
|
+
/**
|
|
7
|
+
* A list's filter bar (erxes-ui's `ListFilter`) as SQL, the way core compiles its own lists:
|
|
8
|
+
*
|
|
9
|
+
* const FIELDS = {
|
|
10
|
+
* 'subject.name': { type: 'text', expr: tickets.name },
|
|
11
|
+
* 'subject.assigneeIds': { type: 'member', expr: tickets.assigneeIds, array: true },
|
|
12
|
+
* 'subject.tagIds': { type: 'tags', expr: tickets.tagIds },
|
|
13
|
+
* 'subject.createdAt': { type: 'date', expr: tickets.createdAt },
|
|
14
|
+
* } satisfies FilterFields;
|
|
15
|
+
*
|
|
16
|
+
* input: z.object({ filter: FilterParam.optional() }),
|
|
17
|
+
* .where(compileFilter(FIELDS, input.filter, { me: member.userId }))
|
|
18
|
+
*
|
|
19
|
+
* A rule on a path `fields` lacks, or with an operator or value its field can't take, throws
|
|
20
|
+
* core's 400 `INVALID_FILTER`.
|
|
21
|
+
*/
|
|
22
|
+
/** A filter that doesn't fit its fields: core's 400 `INVALID_FILTER`. */
|
|
23
|
+
const invalidFilter = (message) => new ORPCError("INVALID_FILTER", {
|
|
24
|
+
status: ERRORS.INVALID_FILTER.status,
|
|
25
|
+
message
|
|
26
|
+
});
|
|
27
|
+
/** A list's `filter` query parameter: the condition group as JSON. */
|
|
28
|
+
const FilterParam = z.string().transform((text, context) => {
|
|
29
|
+
try {
|
|
30
|
+
return JSON.parse(text);
|
|
31
|
+
} catch {
|
|
32
|
+
context.addIssue({
|
|
33
|
+
code: "custom",
|
|
34
|
+
message: "filter is not JSON"
|
|
35
|
+
});
|
|
36
|
+
return z.NEVER;
|
|
37
|
+
}
|
|
38
|
+
}).pipe(RecordFilter);
|
|
39
|
+
/** A text array parameter (a JS array in a template becomes a list of parameters, not one array). */
|
|
40
|
+
const textArray = (values) => sql`array[${sql.join(values.map((value) => sql`${value}`), sql`, `)}]::text[]`;
|
|
41
|
+
/** A LIKE pattern's text, where `%`, `_` and `\` match themselves. */
|
|
42
|
+
const escapeLike = (value) => value.replace(/[\\%_]/g, (char) => `\\${char}`);
|
|
43
|
+
const text = (value) => {
|
|
44
|
+
if (typeof value !== "string" && typeof value !== "number") throw invalidFilter("A text value is needed");
|
|
45
|
+
return String(value);
|
|
46
|
+
};
|
|
47
|
+
const list = (value) => {
|
|
48
|
+
if (!Array.isArray(value) || !value.length) throw invalidFilter("Choose at least one value");
|
|
49
|
+
return value.map(text);
|
|
50
|
+
};
|
|
51
|
+
const number = (value) => {
|
|
52
|
+
const n = typeof value === "number" ? value : Number(value);
|
|
53
|
+
if (!Number.isFinite(n)) throw invalidFilter("A number is needed");
|
|
54
|
+
return n;
|
|
55
|
+
};
|
|
56
|
+
/** `{ amount, unit }` of the relative date rules; anything else has no amount. */
|
|
57
|
+
const Span = z.object({
|
|
58
|
+
amount: z.unknown(),
|
|
59
|
+
unit: z.unknown()
|
|
60
|
+
}).partial();
|
|
61
|
+
const spanOf = (value) => Span.safeParse(value).data ?? {};
|
|
62
|
+
const interval = (value) => {
|
|
63
|
+
const { amount, unit } = spanOf(value);
|
|
64
|
+
const n = number(amount);
|
|
65
|
+
if (n < 0 || n > 3650) throw invalidFilter("Between 0 and 3650");
|
|
66
|
+
return unit === "months" ? sql`make_interval(months => ${n}::int)` : unit === "weeks" ? sql`make_interval(weeks => ${n}::int)` : sql`make_interval(days => ${n}::int)`;
|
|
67
|
+
};
|
|
68
|
+
/** Negative ops on a relation or a custom field: "none where …" rather than "one where not …". */
|
|
69
|
+
const NEGATIVE = {
|
|
70
|
+
neq: "eq",
|
|
71
|
+
not_contains: "contains",
|
|
72
|
+
not_in: "in",
|
|
73
|
+
not_exists: "exists"
|
|
74
|
+
};
|
|
75
|
+
const COMPARE = {
|
|
76
|
+
eq: "=",
|
|
77
|
+
neq: "<>",
|
|
78
|
+
gt: ">",
|
|
79
|
+
gte: ">=",
|
|
80
|
+
lt: "<",
|
|
81
|
+
lte: "<="
|
|
82
|
+
};
|
|
83
|
+
/** Month * 100 + day, as the stored birthday and the value index compute it. */
|
|
84
|
+
const monthDayOf = (day) => sql`((extract(month from ${day}) * 100 + extract(day from ${day}))::smallint)`;
|
|
85
|
+
/** "Within the next n days, any year", over a month-day expression; the window may run past 31 December. */
|
|
86
|
+
const anniversary = (monthDay, value) => {
|
|
87
|
+
const days = number(spanOf(value).amount);
|
|
88
|
+
if (days < 0 || days > 366) throw invalidFilter("Between 0 and 366 days");
|
|
89
|
+
const from = monthDayOf(sql`current_date`);
|
|
90
|
+
const to = monthDayOf(sql`(current_date + ${days}::int)`);
|
|
91
|
+
return sql`(case when ${to} >= ${from} then ${monthDay} between ${from} and ${to} else (${monthDay} >= ${from} or ${monthDay} <= ${to}) end)`;
|
|
92
|
+
};
|
|
93
|
+
/** Date rules. Day-only values compare with days, so an index on them applies. */
|
|
94
|
+
const compileDate = (x, op, value, dateOnly, monthDay) => {
|
|
95
|
+
const today = dateOnly ? sql`current_date` : sql`now()`;
|
|
96
|
+
const shift = (sign) => dateOnly ? sql`(current_date ${sql.raw(sign)} ${interval(value)})::date` : sql`now() ${sql.raw(sign)} ${interval(value)}`;
|
|
97
|
+
const cast = sql.raw(dateOnly ? "date" : "timestamptz");
|
|
98
|
+
const start = () => sql`${text(value)}::date::${cast}`;
|
|
99
|
+
const end = () => sql`(${text(value)}::date + 1)::${cast}`;
|
|
100
|
+
const on = () => dateOnly ? sql`${x} = ${start()}` : sql`(${x} >= ${start()} and ${x} < ${end()})`;
|
|
101
|
+
switch (op) {
|
|
102
|
+
case "eq": return on();
|
|
103
|
+
case "neq": return sql`(${x} is null or not ${on()})`;
|
|
104
|
+
case "lt": return sql`${x} < ${start()}`;
|
|
105
|
+
case "gte": return sql`${x} >= ${start()}`;
|
|
106
|
+
case "lte": return dateOnly ? sql`${x} <= ${start()}` : sql`${x} < ${end()}`;
|
|
107
|
+
case "gt": return dateOnly ? sql`${x} > ${start()}` : sql`${x} >= ${end()}`;
|
|
108
|
+
case "within_last": return sql`(${x} <= ${today} and ${x} >= ${shift("-")})`;
|
|
109
|
+
case "more_than_ago": return sql`${x} < ${shift("-")}`;
|
|
110
|
+
case "within_next": return sql`(${x} >= ${today} and ${x} <= ${shift("+")})`;
|
|
111
|
+
case "anniversary_within": return sql`(${x} is not null and ${anniversary(monthDay ?? monthDayOf(x), value)})`;
|
|
112
|
+
default: return;
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
/** A `text[]` column: "is" and "contains" mean it has the value, "is any of" that it has one of them. */
|
|
116
|
+
const compileArray = (x, values, rule) => {
|
|
117
|
+
switch (rule.op) {
|
|
118
|
+
case "eq":
|
|
119
|
+
case "contains": return sql`${x} @> ${textArray(values(rule.value))}`;
|
|
120
|
+
case "neq":
|
|
121
|
+
case "not_contains": return sql`not (${x} @> ${textArray(values(rule.value))})`;
|
|
122
|
+
case "in": return sql`${x} && ${textArray(list(rule.value).flatMap(values))}`;
|
|
123
|
+
case "not_in": return sql`not (${x} && ${textArray(list(rule.value).flatMap(values))})`;
|
|
124
|
+
default: return;
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
/** A member id; "me" is the member asking. */
|
|
128
|
+
const memberId = (value, { me }) => {
|
|
129
|
+
if (value !== "me") return text(value);
|
|
130
|
+
if (!me) throw invalidFilter("“me” is a member; this caller is not one");
|
|
131
|
+
return me;
|
|
132
|
+
};
|
|
133
|
+
const ID_TYPES = /* @__PURE__ */ new Set([
|
|
134
|
+
"member",
|
|
135
|
+
"customer",
|
|
136
|
+
"company"
|
|
137
|
+
]);
|
|
138
|
+
/** The fields whose values are record ids: a member's, customer's or company's. */
|
|
139
|
+
const isId = (field) => ID_TYPES.has(field.type);
|
|
140
|
+
/** A rule's value as an id of `field`'s records; only a member field reads "me". */
|
|
141
|
+
const idOf = (field, value, context) => field.type === "member" ? memberId(value, context) : text(value);
|
|
142
|
+
const compileId = (field, rule, context) => {
|
|
143
|
+
const x = field.expr;
|
|
144
|
+
const id = (value) => idOf(field, value, context);
|
|
145
|
+
switch (rule.op) {
|
|
146
|
+
case "eq": return sql`${x} = ${id(rule.value)}`;
|
|
147
|
+
case "neq": return sql`(${x} is null or ${x} <> ${id(rule.value)})`;
|
|
148
|
+
case "in": return inArray(sql`${x}`, list(rule.value).map(id));
|
|
149
|
+
case "not_in": return sql`(${x} is null or not ${inArray(sql`${x}`, list(rule.value).map(id))})`;
|
|
150
|
+
default: return;
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
/** A rule's list of values, lower-cased, as a `text[]` parameter. */
|
|
154
|
+
const lowerList = (value) => textArray(list(value).map((item) => item.toLowerCase()));
|
|
155
|
+
const compileText = (field, rule) => {
|
|
156
|
+
const x = field.expr;
|
|
157
|
+
const is = (value) => field.trigram ? sql`${x} ilike ${escapeLike(value)}` : sql`lower(${x}) = lower(${value})`;
|
|
158
|
+
switch (rule.op) {
|
|
159
|
+
case "eq": return is(text(rule.value));
|
|
160
|
+
case "neq": return sql`(${x} is null or not ${is(text(rule.value))})`;
|
|
161
|
+
case "contains": return sql`${x} ilike ${`%${escapeLike(text(rule.value))}%`}`;
|
|
162
|
+
case "not_contains": return sql`(${x} is null or ${x} not ilike ${`%${escapeLike(text(rule.value))}%`})`;
|
|
163
|
+
case "starts_with": return sql`${x} ilike ${`${escapeLike(text(rule.value))}%`}`;
|
|
164
|
+
case "in": return sql`lower(${x}) = any(${lowerList(rule.value)})`;
|
|
165
|
+
case "not_in": return sql`(${x} is null or not (lower(${x}) = any(${lowerList(rule.value)})))`;
|
|
166
|
+
default: return;
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
const compileNumber = (x, rule) => {
|
|
170
|
+
if (rule.op === "neq") return sql`(${x} is null or ${x} <> ${number(rule.value)})`;
|
|
171
|
+
const compare = COMPARE[rule.op];
|
|
172
|
+
return compare ? sql`${x} ${sql.raw(compare)} ${number(rule.value)}` : void 0;
|
|
173
|
+
};
|
|
174
|
+
const compileBoolean = (x, rule) => {
|
|
175
|
+
if (rule.op !== "eq") return void 0;
|
|
176
|
+
return rule.value === true || rule.value === "true" ? sql`${x} is true` : sql`${x} is not true`;
|
|
177
|
+
};
|
|
178
|
+
const isArray = (field) => field.array === true || field.type === "tags";
|
|
179
|
+
/** One rule on one field, or `INVALID_FILTER` when the field can't take its operator or value. */
|
|
180
|
+
const compileColumn = (field, path, rule, context = {}) => {
|
|
181
|
+
const x = field.expr;
|
|
182
|
+
const { op } = rule;
|
|
183
|
+
if (op === "exists") return isArray(field) ? sql`cardinality(${x}) > 0` : field.type === "text" ? sql`coalesce(${x}, '') <> ''` : sql`${x} is not null`;
|
|
184
|
+
if (op === "not_exists") return not(compileColumn(field, path, {
|
|
185
|
+
...rule,
|
|
186
|
+
op: "exists"
|
|
187
|
+
}, context));
|
|
188
|
+
const compiled = isArray(field) ? compileArray(x, (value) => [idOf(field, value, context)], rule) : field.type === "number" ? compileNumber(x, rule) : field.type === "date" ? compileDate(x, op, rule.value, Boolean(field.dateOnly), field.monthDay) : isId(field) ? compileId(field, rule, context) : field.type === "boolean" ? compileBoolean(x, rule) : field.type === "select" || field.type === "text" ? compileText(field, rule) : void 0;
|
|
189
|
+
if (!compiled) throw invalidFilter(`“${field.label ?? path}” can't use “${op}”`);
|
|
190
|
+
return compiled;
|
|
191
|
+
};
|
|
192
|
+
/** A condition group as SQL, each rule through `compileRule`: all of its rules, or any. */
|
|
193
|
+
const compileGroup = (group, compileRule, depth = 1) => {
|
|
194
|
+
if (depth > 3) throw invalidFilter("At most three levels of groups");
|
|
195
|
+
const parts = group.rules.map((rule) => "match" in rule ? compileGroup(rule, compileRule, depth + 1) : compileRule(rule)).filter((part) => Boolean(part));
|
|
196
|
+
if (!parts.length) return void 0;
|
|
197
|
+
return group.match === "all" ? and(...parts) : or(...parts);
|
|
198
|
+
};
|
|
199
|
+
/** A list's filter as one SQL condition on its table, or undefined when it has no rules. */
|
|
200
|
+
const compileFilter = (fields, filter, context = {}) => filter ? compileGroup(filter, (rule) => {
|
|
201
|
+
const field = fields[rule.path];
|
|
202
|
+
if (!field) throw invalidFilter(`Unknown field: ${rule.path}`);
|
|
203
|
+
return compileColumn(field, rule.path, rule, context);
|
|
204
|
+
}) : void 0;
|
|
205
|
+
export { COMPARE, FilterParam, NEGATIVE, compileColumn, compileDate, compileFilter, compileGroup, escapeLike, invalidFilter, list, lowerList, number, text, textArray };
|
package/dist/index.d.ts
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* Payments (scopes `payments:write`, `payments:read`; subscribe to `core.payment.*`):
|
|
11
11
|
*
|
|
12
12
|
* const invoice = await core.forOrg(orgId).payments.createInvoice({
|
|
13
|
-
* amount: 150000, description: 'Order #12',
|
|
13
|
+
* amount: 150000, description: 'Order #12', referenceType: 'order', referenceId: order.id,
|
|
14
14
|
* metadata: { orderId: order.id }, dedupeKey: `order:${order.id}`,
|
|
15
15
|
* }); // show invoice.payment.qrImage / links to the payer
|
|
16
16
|
* app.post('/events', express.text({ type: '*\/*' }), async (req, res) => {
|
|
@@ -29,6 +29,19 @@
|
|
|
29
29
|
* // An invoice may list what it pays for; `plugin` names another plugin's line (it gets the events):
|
|
30
30
|
* // lines: [{ productId, quantity: 1, unitPrice: 150000 }, { name: 'Delivery', quantity: 1, unitPrice: 10000, plugin: 'tms' }]
|
|
31
31
|
*
|
|
32
|
+
* Fields on customers and companies (rollups; scope `fields:write`): declare them in the manifest,
|
|
33
|
+
* then write their values. Members see them read-only and filter by them; no timeline entry or event.
|
|
34
|
+
*
|
|
35
|
+
* fields: [{ code: 'total_spent', contentType: 'customer', label: 'Total spent', type: 'number' }],
|
|
36
|
+
* await core.forOrg(orgId).fields.setPluginValues({
|
|
37
|
+
* contentType: 'customer', values: [{ recordId: customerId, code: 'total_spent', value: 150000 }],
|
|
38
|
+
* }); // → { written, skipped }; up to 500, value null clears
|
|
39
|
+
*
|
|
40
|
+
* Segments (scope `views:read`): a shared view members built in core is the audience.
|
|
41
|
+
*
|
|
42
|
+
* const { data } = await core.forOrg(orgId).views.list({ recordType: 'customer' }); // shared only
|
|
43
|
+
* const { recordIds } = await core.forOrg(orgId).views.matches({ viewId, recordIds: [customerId] });
|
|
44
|
+
*
|
|
32
45
|
* Customers (a shop, tracking, booking): core signs them in; the plugin never builds sign-up or
|
|
33
46
|
* sign-in. Declare `customerApp: { origins: ['https://{subdomain}.shop.example.com'] }` in the
|
|
34
47
|
* manifest. The app's own form makes two calls to core: `POST /core/v1/customer-auth/code`
|
|
@@ -50,11 +63,53 @@
|
|
|
50
63
|
* if (!member.canChange()) throw new Error('HR is read-only: buy it again on erxes.io');
|
|
51
64
|
* // server-side jobs: await core.forOrg(orgId).saas.pluginPlan() → { tier, access }
|
|
52
65
|
*
|
|
66
|
+
* Jobs (plugins on core's database): declare them in the manifest, queue them in the
|
|
67
|
+
* plugin's own transaction, and serve each at `<api.url>/jobs/<name>`. Core retries
|
|
68
|
+
* until the route answers 2xx (`retry`: attempts in all, the first wait and the
|
|
69
|
+
* longest, in seconds; default 8, 30 s, 6 h). A `cron` (UTC) job runs once per
|
|
70
|
+
* organisation that has the plugin.
|
|
71
|
+
*
|
|
72
|
+
* jobs: [{ name: 'mail.sync', retry: { attempts: 5, delay: 60, maxDelay: 3600 } },
|
|
73
|
+
* { name: 'sla.check', cron: '*\/5 * * * *' }],
|
|
74
|
+
* await enqueueJob(tx, { orgId, name: 'mail.sync', payload: { accountId }, dedupeKey: accountId });
|
|
75
|
+
* app.post('/api/jobs/:name', express.text({ type: '*\/*' }), async (req, res) => {
|
|
76
|
+
* const job = await verifyCoreJob(req.headers.authorization, req.body, { coreUrl, plugin: 'frontline' });
|
|
77
|
+
* await JOBS[job.name](job); // { jobId, orgId, name, attempt, payload }; may repeat
|
|
78
|
+
* res.sendStatus(204);
|
|
79
|
+
* });
|
|
80
|
+
*
|
|
81
|
+
* A timeline whose records not every member may read declares `recordAccess: true`; core asks the
|
|
82
|
+
* plugin before a member reads or notes on one, and anything but `{ allowed: true }` within 5 s is no:
|
|
83
|
+
*
|
|
84
|
+
* timelines: [{ type: 'frontline.ticket', label: 'Ticket', recordAccess: true }],
|
|
85
|
+
* app.post('/api/timelines/access', express.text({ type: '*\/*' }), async (req, res) => {
|
|
86
|
+
* const check = await verifyCoreAccessCheck(req.headers.authorization, req.body, { coreUrl, plugin: 'frontline' });
|
|
87
|
+
* res.json({ allowed: await canRead(check.orgId, check.userId, check.id) }); // check.type too
|
|
88
|
+
* });
|
|
89
|
+
*
|
|
90
|
+
* Callers outside erxes (a webhook, a redirect after an app install) reach the plugin through
|
|
91
|
+
* core, at `<coreUrl>/core/v1/plugins/<name>/public/<orgId>/<path>`, for a path under one of the
|
|
92
|
+
* manifest's `publicPaths`. Core forwards them to `<api.url>/public/<path>` with a token naming
|
|
93
|
+
* the organisation, and passes the answer's status, type and redirect back:
|
|
94
|
+
*
|
|
95
|
+
* publicPaths: ['/github/webhook'],
|
|
96
|
+
* app.all('/api/public/*path', express.text({ type: '*\/*' }), async (req, res) => {
|
|
97
|
+
* const { orgId } = await verifyPublicCall(req.headers.authorization, req.body ?? '', { coreUrl, plugin: 'operation' });
|
|
98
|
+
* // anyone can call: check the sender's own signature (X-Hub-Signature-256) before acting
|
|
99
|
+
* });
|
|
100
|
+
*
|
|
101
|
+
* List filters (erxes-ui's `ListFilter`): `@erxes/plugin-sdk/filter` compiles the bar's condition
|
|
102
|
+
* group to SQL on a map of paths to columns, with core's operators and its 400 `INVALID_FILTER`:
|
|
103
|
+
*
|
|
104
|
+
* const FIELDS = { 'subject.name': { type: 'text', expr: tickets.name } } satisfies FilterFields;
|
|
105
|
+
* .where(compileFilter(FIELDS, input.filter, { me: member.userId })) // filter: FilterParam
|
|
106
|
+
*
|
|
53
107
|
* The client secret is only ever sent to `POST /plugins/token`; API calls use
|
|
54
108
|
* 15-minute tokens, fetched and renewed here. Plugins on core's database can
|
|
55
109
|
* also call `core_publish_event()`, `core_record_audit()` and
|
|
56
110
|
* `core_live_signal()` inside their own transactions.
|
|
57
111
|
*/
|
|
58
112
|
import { CoreClient, CoreClientOptions, CoreTokenError, createCoreClient } from "./client.js";
|
|
59
|
-
import {
|
|
60
|
-
|
|
113
|
+
import { JobInput, enqueueJob } from "./jobs.js";
|
|
114
|
+
import { CoreCall, CustomerSignIn, DeliveredEvent, ErxesSignIn, PluginMember, PublicCall, bearerOf, verifyCoreAccessCheck, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession, verifyPublicCall } from "./verify.js";
|
|
115
|
+
export { CoreCall, CoreClient, CoreClientOptions, CoreTokenError, CustomerSignIn, DeliveredEvent, ErxesSignIn, JobInput, PluginMember, PublicCall, bearerOf, createCoreClient, enqueueJob, verifyCoreAccessCheck, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession, verifyPublicCall };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import { CoreTokenError, createCoreClient } from "./client.js";
|
|
2
|
-
import {
|
|
3
|
-
|
|
2
|
+
import { enqueueJob } from "./jobs.js";
|
|
3
|
+
import { DeliveredEvent, bearerOf, verifyCoreAccessCheck, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession, verifyPublicCall } from "./verify.js";
|
|
4
|
+
export { CoreTokenError, DeliveredEvent, bearerOf, createCoreClient, enqueueJob, verifyCoreAccessCheck, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession, verifyPublicCall };
|
package/dist/jobs.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { SQL } from "drizzle-orm";
|
|
2
|
+
/** A transaction on core's database, as the plugin's own role (Drizzle's `tx`). */
|
|
3
|
+
interface Transaction {
|
|
4
|
+
execute(query: SQL): PromiseLike<unknown>;
|
|
5
|
+
}
|
|
6
|
+
export interface JobInput {
|
|
7
|
+
orgId: string;
|
|
8
|
+
/** A job the manifest's `jobs` declares. */
|
|
9
|
+
name: string;
|
|
10
|
+
payload?: Record<string, unknown>;
|
|
11
|
+
/** Run no earlier than this. */
|
|
12
|
+
runAt?: Date;
|
|
13
|
+
/** One queued or running job per key: queueing it again adds nothing. */
|
|
14
|
+
dedupeKey?: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Queues one of the plugin's jobs in its own transaction (`core_enqueue_job`),
|
|
18
|
+
* so the job exists only if the transaction commits. Core then POSTs it to
|
|
19
|
+
* `<api.url>/jobs/<name>` until the plugin answers 2xx. The database refuses a
|
|
20
|
+
* name the manifest doesn't declare and an organisation without the plugin.
|
|
21
|
+
*/
|
|
22
|
+
export declare const enqueueJob: (tx: Transaction, job: JobInput) => Promise<void>;
|
|
23
|
+
export {};
|
package/dist/jobs.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { sql } from "drizzle-orm";
|
|
2
|
+
// src/jobs.ts
|
|
3
|
+
/**
|
|
4
|
+
* Queues one of the plugin's jobs in its own transaction (`core_enqueue_job`),
|
|
5
|
+
* so the job exists only if the transaction commits. Core then POSTs it to
|
|
6
|
+
* `<api.url>/jobs/<name>` until the plugin answers 2xx. The database refuses a
|
|
7
|
+
* name the manifest doesn't declare and an organisation without the plugin.
|
|
8
|
+
*/
|
|
9
|
+
const enqueueJob = async (tx, job) => {
|
|
10
|
+
await tx.execute(sql`select core_enqueue_job(
|
|
11
|
+
${job.orgId},
|
|
12
|
+
${job.name},
|
|
13
|
+
${JSON.stringify(job.payload ?? {})}::jsonb,
|
|
14
|
+
${job.runAt?.toISOString() ?? null}::timestamptz,
|
|
15
|
+
${job.dedupeKey ?? null}
|
|
16
|
+
)`);
|
|
17
|
+
};
|
|
18
|
+
export { enqueueJob };
|
package/dist/verify.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PluginAccess, PluginTier } from "@erxes/core-contract";
|
|
1
|
+
import { PluginAccess, PluginJobDelivery, PluginTier, RecordAccessCheck } from "@erxes/core-contract";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
/** The signed-in member a plugin UI calls the plugin's API for. */
|
|
4
4
|
export interface PluginMember {
|
|
@@ -52,31 +52,23 @@ export declare const DeliveredEvent: z.ZodObject<{
|
|
|
52
52
|
source: z.ZodString;
|
|
53
53
|
type: z.ZodString;
|
|
54
54
|
version: z.ZodInt;
|
|
55
|
+
subjectType: z.ZodNullable<z.ZodEnum<{
|
|
56
|
+
company: "company";
|
|
57
|
+
customer: "customer";
|
|
58
|
+
}>>;
|
|
59
|
+
subjectId: z.ZodNullable<z.ZodString>;
|
|
60
|
+
entityType: z.ZodNullable<z.ZodString>;
|
|
61
|
+
entityId: z.ZodNullable<z.ZodString>;
|
|
62
|
+
actorType: z.ZodEnum<{
|
|
63
|
+
customer: "customer";
|
|
64
|
+
plugin: "plugin";
|
|
65
|
+
system: "system";
|
|
66
|
+
user: "user";
|
|
67
|
+
}>;
|
|
68
|
+
actorId: z.ZodNullable<z.ZodString>;
|
|
55
69
|
payload: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
56
70
|
summary: z.ZodNullable<z.ZodString>;
|
|
57
71
|
link: z.ZodNullable<z.ZodString>;
|
|
58
|
-
subject: z.ZodNullable<z.ZodObject<{
|
|
59
|
-
type: z.ZodEnum<{
|
|
60
|
-
company: "company";
|
|
61
|
-
customer: "customer";
|
|
62
|
-
}>;
|
|
63
|
-
id: z.ZodString;
|
|
64
|
-
}, z.core.$strip>>;
|
|
65
|
-
entity: z.ZodNullable<z.ZodObject<{
|
|
66
|
-
type: z.ZodString;
|
|
67
|
-
id: z.ZodString;
|
|
68
|
-
}, z.core.$strip>>;
|
|
69
|
-
actor: z.ZodObject<{
|
|
70
|
-
type: z.ZodEnum<{
|
|
71
|
-
customer: "customer";
|
|
72
|
-
plugin: "plugin";
|
|
73
|
-
system: "system";
|
|
74
|
-
user: "user";
|
|
75
|
-
}>;
|
|
76
|
-
id: z.ZodNullable<z.ZodString>;
|
|
77
|
-
name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
78
|
-
avatarUrl: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
79
|
-
}, z.core.$strip>;
|
|
80
72
|
occurredAt: z.ZodISODateTime;
|
|
81
73
|
createdAt: z.ZodISODateTime;
|
|
82
74
|
}, {
|
|
@@ -135,4 +127,34 @@ export declare const verifyCustomerToken: (authorization: string | undefined | n
|
|
|
135
127
|
* once, and act on the totals in the payload, not on arrival order.
|
|
136
128
|
*/
|
|
137
129
|
export declare const verifyCoreEvent: (authorization: string | undefined | null, rawBody: string, options: VerifyOptions) => Promise<DeliveredEvent>;
|
|
130
|
+
/** A call from outside erxes that core forwarded to the plugin's `/public` route. */
|
|
131
|
+
export interface PublicCall {
|
|
132
|
+
/** The organisation the caller's address named, which has the plugin installed. */
|
|
133
|
+
orgId: string;
|
|
134
|
+
/** Core's id for this call. */
|
|
135
|
+
callId: string;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Verifies a call core forwarded to `<api.url>/public/<path>` (one of the manifest's
|
|
139
|
+
* `publicPaths`) and returns its organisation: the token is core's, for this plugin, at most a
|
|
140
|
+
* minute old, and signs this exact body (its raw text, or its bytes from `express.raw` for one
|
|
141
|
+
* that isn't text; '' without one). Throws if not. The caller is anyone on the internet: check
|
|
142
|
+
* what they send (a webhook's signature).
|
|
143
|
+
*/
|
|
144
|
+
export declare const verifyPublicCall: (authorization: string | undefined | null, rawBody: string | Uint8Array<ArrayBuffer>, options: VerifyOptions) => Promise<PublicCall>;
|
|
145
|
+
/**
|
|
146
|
+
* Verifies one attempt of a job core POSTed to `<api.url>/jobs/<name>` and
|
|
147
|
+
* returns it: the token is core's, for this plugin, unexpired, and signs this
|
|
148
|
+
* exact body (pass the raw body text). Throws if anything is off. Answer 2xx
|
|
149
|
+
* when done; anything else retries. A job can run more than once: the
|
|
150
|
+
* `Idempotency-Key` header is its `jobId`.
|
|
151
|
+
*/
|
|
152
|
+
export declare const verifyCoreJob: (authorization: string | undefined | null, rawBody: string, options: VerifyOptions) => Promise<PluginJobDelivery>;
|
|
153
|
+
/**
|
|
154
|
+
* Verifies core's question for a timeline with `recordAccess` (`POST <api.url>/timelines/access`)
|
|
155
|
+
* and returns it: may `userId` read record `id` of timeline `type`? The token is core's, for this
|
|
156
|
+
* plugin, unexpired, and signs this exact body (pass the raw body text). Answer
|
|
157
|
+
* `{ "allowed": true }` or `{ "allowed": false }` within 5 seconds; anything else is no.
|
|
158
|
+
*/
|
|
159
|
+
export declare const verifyCoreAccessCheck: (authorization: string | undefined | null, rawBody: string, options: VerifyOptions) => Promise<RecordAccessCheck>;
|
|
138
160
|
export {};
|
package/dist/verify.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CORE_API_PREFIX, CoreEvent, PluginAccess, PluginTier } from "@erxes/core-contract";
|
|
1
|
+
import { CORE_API_PREFIX, CoreEvent, PluginAccess, PluginJobDelivery, PluginTier, RecordAccessCheck } from "@erxes/core-contract";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
4
4
|
// src/verify.ts
|
|
@@ -14,6 +14,11 @@ const DeliveredEvent = z.object({
|
|
|
14
14
|
})
|
|
15
15
|
});
|
|
16
16
|
const jwksByCore = /* @__PURE__ */ new Map();
|
|
17
|
+
/**
|
|
18
|
+
* The plugin's server clock may run a little ahead of core's: a token core
|
|
19
|
+
* just issued, or one a member's browser renews 30 s before it ends, still passes.
|
|
20
|
+
*/
|
|
21
|
+
const CLOCK_TOLERANCE_SECONDS = 60;
|
|
17
22
|
/** A token core signed (its public keys), for this plugin (or `audience`), of this kind, unexpired; its claims parsed. */
|
|
18
23
|
const verifyCoreToken = async (token, options, typ, claims, audience = options.plugin) => {
|
|
19
24
|
const base = options.coreUrl.replace(/\/+$/, "");
|
|
@@ -27,7 +32,8 @@ const verifyCoreToken = async (token, options, typ, claims, audience = options.p
|
|
|
27
32
|
issuer: "erxes-core",
|
|
28
33
|
audience,
|
|
29
34
|
typ,
|
|
30
|
-
algorithms: ["ES256"]
|
|
35
|
+
algorithms: ["ES256"],
|
|
36
|
+
clockTolerance: CLOCK_TOLERANCE_SECONDS
|
|
31
37
|
});
|
|
32
38
|
const parsed = claims.safeParse(payload);
|
|
33
39
|
if (!parsed.success) throw new Error(`not an erxes ${typ} token`);
|
|
@@ -122,8 +128,9 @@ const verifyCustomerToken = async (authorization, options) => {
|
|
|
122
128
|
if (!token) throw new Error("no customer token");
|
|
123
129
|
return verifyCoreToken(token, options, "customer+jwt", CustomerClaims, "erxes-customer");
|
|
124
130
|
};
|
|
125
|
-
|
|
126
|
-
|
|
131
|
+
/** A body's SHA-256, base64url: text as UTF-8, or its bytes as they came. */
|
|
132
|
+
const sha256 = async (body) => {
|
|
133
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", typeof body === "string" ? new TextEncoder().encode(body) : body));
|
|
127
134
|
return btoa(String.fromCharCode(...digest)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
128
135
|
};
|
|
129
136
|
const EventClaims = z.object({
|
|
@@ -147,4 +154,67 @@ const verifyCoreEvent = async (authorization, rawBody, options) => {
|
|
|
147
154
|
if (event.id !== claims.event || event.organizationId !== claims.org) throw new Error("the event does not match the token");
|
|
148
155
|
return event;
|
|
149
156
|
};
|
|
150
|
-
|
|
157
|
+
const PublicClaims = z.object({
|
|
158
|
+
sha: z.string(),
|
|
159
|
+
public: z.string(),
|
|
160
|
+
org: z.string()
|
|
161
|
+
});
|
|
162
|
+
/**
|
|
163
|
+
* Verifies a call core forwarded to `<api.url>/public/<path>` (one of the manifest's
|
|
164
|
+
* `publicPaths`) and returns its organisation: the token is core's, for this plugin, at most a
|
|
165
|
+
* minute old, and signs this exact body (its raw text, or its bytes from `express.raw` for one
|
|
166
|
+
* that isn't text; '' without one). Throws if not. The caller is anyone on the internet: check
|
|
167
|
+
* what they send (a webhook's signature).
|
|
168
|
+
*/
|
|
169
|
+
const verifyPublicCall = async (authorization, rawBody, options) => {
|
|
170
|
+
const token = bearerOf(authorization);
|
|
171
|
+
if (!token) throw new Error("no core token");
|
|
172
|
+
const claims = await verifyCoreToken(token, options, "erxes-core-public+jwt", PublicClaims);
|
|
173
|
+
if (claims.sha !== await sha256(rawBody)) throw new Error("the body does not match the token");
|
|
174
|
+
return {
|
|
175
|
+
orgId: claims.org,
|
|
176
|
+
callId: claims.public
|
|
177
|
+
};
|
|
178
|
+
};
|
|
179
|
+
const JobClaims = z.object({
|
|
180
|
+
sha: z.string(),
|
|
181
|
+
job: z.string(),
|
|
182
|
+
org: z.string()
|
|
183
|
+
});
|
|
184
|
+
/**
|
|
185
|
+
* Verifies one attempt of a job core POSTed to `<api.url>/jobs/<name>` and
|
|
186
|
+
* returns it: the token is core's, for this plugin, unexpired, and signs this
|
|
187
|
+
* exact body (pass the raw body text). Throws if anything is off. Answer 2xx
|
|
188
|
+
* when done; anything else retries. A job can run more than once: the
|
|
189
|
+
* `Idempotency-Key` header is its `jobId`.
|
|
190
|
+
*/
|
|
191
|
+
const verifyCoreJob = async (authorization, rawBody, options) => {
|
|
192
|
+
const token = bearerOf(authorization);
|
|
193
|
+
if (!token) throw new Error("no core token");
|
|
194
|
+
const claims = await verifyCoreToken(token, options, "erxes-core-job+jwt", JobClaims);
|
|
195
|
+
if (claims.sha !== await sha256(rawBody)) throw new Error("the body does not match the token");
|
|
196
|
+
const job = PluginJobDelivery.parse(JSON.parse(rawBody));
|
|
197
|
+
if (job.jobId !== claims.job || job.orgId !== claims.org) throw new Error("the job does not match the token");
|
|
198
|
+
return job;
|
|
199
|
+
};
|
|
200
|
+
const AccessClaims = z.object({
|
|
201
|
+
sha: z.string(),
|
|
202
|
+
access: z.string(),
|
|
203
|
+
org: z.string()
|
|
204
|
+
});
|
|
205
|
+
/**
|
|
206
|
+
* Verifies core's question for a timeline with `recordAccess` (`POST <api.url>/timelines/access`)
|
|
207
|
+
* and returns it: may `userId` read record `id` of timeline `type`? The token is core's, for this
|
|
208
|
+
* plugin, unexpired, and signs this exact body (pass the raw body text). Answer
|
|
209
|
+
* `{ "allowed": true }` or `{ "allowed": false }` within 5 seconds; anything else is no.
|
|
210
|
+
*/
|
|
211
|
+
const verifyCoreAccessCheck = async (authorization, rawBody, options) => {
|
|
212
|
+
const token = bearerOf(authorization);
|
|
213
|
+
if (!token) throw new Error("no core token");
|
|
214
|
+
const claims = await verifyCoreToken(token, options, "erxes-core-access+jwt", AccessClaims);
|
|
215
|
+
if (claims.sha !== await sha256(rawBody)) throw new Error("the body does not match the token");
|
|
216
|
+
const check = RecordAccessCheck.parse(JSON.parse(rawBody));
|
|
217
|
+
if (check.orgId !== claims.org) throw new Error("the check does not match the token");
|
|
218
|
+
return check;
|
|
219
|
+
};
|
|
220
|
+
export { DeliveredEvent, bearerOf, verifyCoreAccessCheck, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession, verifyPublicCall };
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@erxes/plugin-sdk",
|
|
3
|
-
"version": "0.1.0-v2.
|
|
3
|
+
"version": "0.1.0-v2.10",
|
|
4
4
|
"private": false,
|
|
5
|
-
"description": "For erxes plugin servers: a typed core client with automatic plugin tokens,
|
|
5
|
+
"description": "For erxes plugin servers: a typed core client with automatic plugin tokens, verification of members' plugin session tokens and of core's deliveries, and plugin jobs",
|
|
6
6
|
"license": "AGPL-3.0-only",
|
|
7
7
|
"repository": {
|
|
8
8
|
"type": "git",
|
|
@@ -17,6 +17,8 @@
|
|
|
17
17
|
"exports": {
|
|
18
18
|
".": "./dist/index.js",
|
|
19
19
|
"./client": "./dist/client.js",
|
|
20
|
+
"./filter": "./dist/filter.js",
|
|
21
|
+
"./jobs": "./dist/jobs.js",
|
|
20
22
|
"./verify": "./dist/verify.js",
|
|
21
23
|
"./package.json": "./package.json"
|
|
22
24
|
},
|
|
@@ -31,7 +33,13 @@
|
|
|
31
33
|
"@orpc/openapi-client": "1.16.2",
|
|
32
34
|
"jose": "^6.2.17",
|
|
33
35
|
"zod": "^4.6.7",
|
|
34
|
-
"@erxes/core-contract": "0.1.0-v2.
|
|
36
|
+
"@erxes/core-contract": "0.1.0-v2.11"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"drizzle-orm": "0.45.4"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"drizzle-orm": "0.45.4"
|
|
35
43
|
},
|
|
36
44
|
"scripts": {
|
|
37
45
|
"build": "tsdown"
|