@erxes/plugin-sdk 0.1.0-v2.2 → 0.1.0-v2.20
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 +24 -0
- package/dist/client.js +54 -22
- package/dist/filter.d.ts +67 -0
- package/dist/filter.js +205 -0
- package/dist/index.d.ts +81 -2
- package/dist/index.js +3 -2
- package/dist/jobs.d.ts +23 -0
- package/dist/jobs.js +18 -0
- package/dist/openapi.d.ts +37 -0
- package/dist/openapi.js +74 -0
- package/dist/verify.d.ts +31 -1
- package/dist/verify.js +75 -5
- package/package.json +14 -3
package/dist/client.d.ts
CHANGED
|
@@ -101,9 +101,15 @@ export declare const createCoreClient: (options: CoreClientOptions) => {
|
|
|
101
101
|
CROSS_SITE: {
|
|
102
102
|
status: number;
|
|
103
103
|
};
|
|
104
|
+
DUPLICATE_PERMISSION_SET: {
|
|
105
|
+
status: number;
|
|
106
|
+
};
|
|
104
107
|
INVALID_CLIENT: {
|
|
105
108
|
status: number;
|
|
106
109
|
};
|
|
110
|
+
INVALID_SCHEDULE: {
|
|
111
|
+
status: number;
|
|
112
|
+
};
|
|
107
113
|
LIMIT_EXCEEDED: {
|
|
108
114
|
status: number;
|
|
109
115
|
};
|
|
@@ -116,6 +122,12 @@ export declare const createCoreClient: (options: CoreClientOptions) => {
|
|
|
116
122
|
PLUGIN_NOT_FOUND: {
|
|
117
123
|
status: number;
|
|
118
124
|
};
|
|
125
|
+
UNKNOWN_PERMISSION: {
|
|
126
|
+
status: number;
|
|
127
|
+
data: z.ZodObject<{
|
|
128
|
+
permissions: z.ZodArray<z.ZodString>;
|
|
129
|
+
}, z.core.$strip>;
|
|
130
|
+
};
|
|
119
131
|
}>>>;
|
|
120
132
|
/** Tells the plugin's open UIs that topics changed (needs `live:write`). */
|
|
121
133
|
signal: (orgId: string, topics: string[], userIds?: string[]) => import("@orpc/client").ClientPromiseResult<{
|
|
@@ -201,9 +213,15 @@ export declare const createCoreClient: (options: CoreClientOptions) => {
|
|
|
201
213
|
CROSS_SITE: {
|
|
202
214
|
status: number;
|
|
203
215
|
};
|
|
216
|
+
DUPLICATE_PERMISSION_SET: {
|
|
217
|
+
status: number;
|
|
218
|
+
};
|
|
204
219
|
INVALID_CLIENT: {
|
|
205
220
|
status: number;
|
|
206
221
|
};
|
|
222
|
+
INVALID_SCHEDULE: {
|
|
223
|
+
status: number;
|
|
224
|
+
};
|
|
207
225
|
LIMIT_EXCEEDED: {
|
|
208
226
|
status: number;
|
|
209
227
|
};
|
|
@@ -216,5 +234,11 @@ export declare const createCoreClient: (options: CoreClientOptions) => {
|
|
|
216
234
|
PLUGIN_NOT_FOUND: {
|
|
217
235
|
status: number;
|
|
218
236
|
};
|
|
237
|
+
UNKNOWN_PERMISSION: {
|
|
238
|
+
status: number;
|
|
239
|
+
data: z.ZodObject<{
|
|
240
|
+
permissions: z.ZodArray<z.ZodString>;
|
|
241
|
+
}, z.core.$strip>;
|
|
242
|
+
};
|
|
219
243
|
}>>>;
|
|
220
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
|
@@ -29,6 +29,35 @@
|
|
|
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
|
+
* Team members who don't sign in (scope `users:write`): people a plugin keeps on the team for its own app
|
|
33
|
+
* (HR's employees). They take no seat and never sign in to erxes; a plugin adds them and changes
|
|
34
|
+
* their profile, never a member who signs in.
|
|
35
|
+
*
|
|
36
|
+
* const worker = await core.forOrg(orgId).users.add({ fullName, employeeId, phone });
|
|
37
|
+
*
|
|
38
|
+
* Branches and departments (scopes `units:read`, `units:write`; subscribe to `core.unit.*`): core's,
|
|
39
|
+
* shared by plugins. Keep a read-only copy for your own visibility queries and refresh it whenever
|
|
40
|
+
* a `core.unit.*` event arrives (the event names the unit in `entityId`); bring your old units in
|
|
41
|
+
* once with `units.import`, which keeps their ids and answers where each one went. Each unit has a
|
|
42
|
+
* `typeId`, one of the organisation's `unitTypes` of its kind (Branch and Department to start);
|
|
43
|
+
* bring your own types first with `unitTypes.import` and name them on the units you import.
|
|
44
|
+
*
|
|
45
|
+
* const { data } = await core.forOrg(orgId).units.list({}); // every unit, parents first, with memberIds
|
|
46
|
+
* const { ids } = await core.forOrg(orgId).units.import({ units: [{ id, kind: 'branch', name, memberIds }] });
|
|
47
|
+
*
|
|
48
|
+
* Fields on customers and companies (rollups; scope `fields:write`): declare them in the manifest,
|
|
49
|
+
* then write their values. Members see them read-only and filter by them; no timeline entry or event.
|
|
50
|
+
*
|
|
51
|
+
* fields: [{ code: 'total_spent', contentType: 'customer', label: 'Total spent', type: 'number' }],
|
|
52
|
+
* await core.forOrg(orgId).fields.setPluginValues({
|
|
53
|
+
* contentType: 'customer', values: [{ recordId: customerId, code: 'total_spent', value: 150000 }],
|
|
54
|
+
* }); // → { written, skipped }; up to 500, value null clears
|
|
55
|
+
*
|
|
56
|
+
* Segments (scope `views:read`): a shared view members built in core is the audience.
|
|
57
|
+
*
|
|
58
|
+
* const { data } = await core.forOrg(orgId).views.list({ recordType: 'customer' }); // shared only
|
|
59
|
+
* const { recordIds } = await core.forOrg(orgId).views.matches({ viewId, recordIds: [customerId] });
|
|
60
|
+
*
|
|
32
61
|
* Customers (a shop, tracking, booking): core signs them in; the plugin never builds sign-up or
|
|
33
62
|
* sign-in. Declare `customerApp: { origins: ['https://{subdomain}.shop.example.com'] }` in the
|
|
34
63
|
* manifest. The app's own form makes two calls to core: `POST /core/v1/customer-auth/code`
|
|
@@ -50,11 +79,61 @@
|
|
|
50
79
|
* if (!member.canChange()) throw new Error('HR is read-only: buy it again on erxes.io');
|
|
51
80
|
* // server-side jobs: await core.forOrg(orgId).saas.pluginPlan() → { tier, access }
|
|
52
81
|
*
|
|
82
|
+
* Jobs (plugins on core's database): declare them in the manifest, queue them in the
|
|
83
|
+
* plugin's own transaction, and serve each at `<api.url>/jobs/<name>`. Core retries
|
|
84
|
+
* until the route answers 2xx (`retry`: attempts in all, the first wait and the
|
|
85
|
+
* longest, in seconds; default 8, 30 s, 6 h). A `cron` (UTC) job runs once per
|
|
86
|
+
* organisation that has the plugin.
|
|
87
|
+
*
|
|
88
|
+
* jobs: [{ name: 'mail.sync', retry: { attempts: 5, delay: 60, maxDelay: 3600 } },
|
|
89
|
+
* { name: 'sla.check', cron: '*\/5 * * * *' }],
|
|
90
|
+
* await enqueueJob(tx, { orgId, name: 'mail.sync', payload: { accountId }, dedupeKey: accountId });
|
|
91
|
+
* app.post('/api/jobs/:name', express.text({ type: '*\/*' }), async (req, res) => {
|
|
92
|
+
* const job = await verifyCoreJob(req.headers.authorization, req.body, { coreUrl, plugin: 'frontline' });
|
|
93
|
+
* await JOBS[job.name](job); // { jobId, orgId, name, attempt, payload }; may repeat
|
|
94
|
+
* res.sendStatus(204);
|
|
95
|
+
* });
|
|
96
|
+
*
|
|
97
|
+
* A timeline whose records not every member may read declares `recordAccess: true`; core asks the
|
|
98
|
+
* plugin before a member reads or notes on one, and anything but `{ allowed: true }` within 5 s is no:
|
|
99
|
+
*
|
|
100
|
+
* timelines: [{ type: 'frontline.ticket', label: 'Ticket', recordAccess: true }],
|
|
101
|
+
* app.post('/api/timelines/access', express.text({ type: '*\/*' }), async (req, res) => {
|
|
102
|
+
* const check = await verifyCoreAccessCheck(req.headers.authorization, req.body, { coreUrl, plugin: 'frontline' });
|
|
103
|
+
* res.json({ allowed: await canRead(check.orgId, check.userId, check.id) }); // check.type too
|
|
104
|
+
* });
|
|
105
|
+
*
|
|
106
|
+
* Callers outside erxes (a webhook, a redirect after an app install) reach the plugin through
|
|
107
|
+
* core, at `<coreUrl>/core/v1/plugins/<name>/public/<orgId>/<path>`, for a path under one of the
|
|
108
|
+
* manifest's `publicPaths`. Core forwards them to `<api.url>/public/<path>` with a token naming
|
|
109
|
+
* the organisation, and passes the answer's status, type and redirect back:
|
|
110
|
+
*
|
|
111
|
+
* publicPaths: ['/github/webhook'],
|
|
112
|
+
* app.all('/api/public/*path', express.text({ type: '*\/*' }), async (req, res) => {
|
|
113
|
+
* const { orgId } = await verifyPublicCall(req.headers.authorization, req.body ?? '', { coreUrl, plugin: 'operation' });
|
|
114
|
+
* // anyone can call: check the sender's own signature (X-Hub-Signature-256) before acting
|
|
115
|
+
* });
|
|
116
|
+
*
|
|
117
|
+
* List filters (erxes-ui's `ListFilter`): `@erxes/plugin-sdk/filter` compiles the bar's condition
|
|
118
|
+
* group to SQL on a map of paths to columns, with core's operators and its 400 `INVALID_FILTER`:
|
|
119
|
+
*
|
|
120
|
+
* const FIELDS = { 'subject.name': { type: 'text', expr: tickets.name } } satisfies FilterFields;
|
|
121
|
+
* .where(compileFilter(FIELDS, input.filter, { me: member.userId })) // filter: FilterParam
|
|
122
|
+
*
|
|
123
|
+
* API reference: `@erxes/plugin-sdk/openapi` documents the plugin's routes, served as REST beside
|
|
124
|
+
* the RPC handler. The manifest's `api.docs` lists one document per audience (`member`, and
|
|
125
|
+
* `employee`, `customer` or `website` for routes those call), and Settings › Developer shows them:
|
|
126
|
+
*
|
|
127
|
+
* api: { url: `${publicUrl}/api`, docs: [{ audience: 'member', path: '/openapi/member.json' }] },
|
|
128
|
+
* app.use('/api/v1', member check, (req, res, next) => rest.handle(req, res, { prefix: '/api/v1', context }));
|
|
129
|
+
* app.get('/api/openapi/member.json', async (_req, res) => res.json(await pluginOpenApi(router, { plugin, audience: 'member', title, version, server: `${publicUrl}/api`, prefix: '/v1' })));
|
|
130
|
+
*
|
|
53
131
|
* The client secret is only ever sent to `POST /plugins/token`; API calls use
|
|
54
132
|
* 15-minute tokens, fetched and renewed here. Plugins on core's database can
|
|
55
133
|
* also call `core_publish_event()`, `core_record_audit()` and
|
|
56
134
|
* `core_live_signal()` inside their own transactions.
|
|
57
135
|
*/
|
|
58
136
|
import { CoreClient, CoreClientOptions, CoreTokenError, createCoreClient } from "./client.js";
|
|
59
|
-
import {
|
|
60
|
-
|
|
137
|
+
import { JobInput, enqueueJob } from "./jobs.js";
|
|
138
|
+
import { CoreCall, CustomerSignIn, DeliveredEvent, ErxesSignIn, PluginMember, PublicCall, bearerOf, verifyCoreAccessCheck, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession, verifyPublicCall } from "./verify.js";
|
|
139
|
+
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 };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { PluginApiAudience } from "@erxes/core-contract";
|
|
2
|
+
import { OpenAPI, OpenAPIGenerator } from "@orpc/openapi";
|
|
3
|
+
/** What `OpenAPIGenerator` documents: a router or a contract. */
|
|
4
|
+
type Documented = Parameters<OpenAPIGenerator['generate']>[0];
|
|
5
|
+
export interface PluginOpenApiOptions {
|
|
6
|
+
/** The plugin's name, as registered (`sales`). */
|
|
7
|
+
plugin: string;
|
|
8
|
+
/** Who calls these routes, which decides how they sign in (the manifest's `api.docs`). */
|
|
9
|
+
audience: PluginApiAudience;
|
|
10
|
+
title: string;
|
|
11
|
+
version: string;
|
|
12
|
+
description?: string;
|
|
13
|
+
/**
|
|
14
|
+
* The address the document's paths start from, which "try it" calls: the manifest's
|
|
15
|
+
* `api.url` (`${publicUrl}/api`) for routes under it, or the plugin's public URL for routes
|
|
16
|
+
* outside it (a website's `/public/v1`, customers' `/customer`).
|
|
17
|
+
*/
|
|
18
|
+
server: string;
|
|
19
|
+
/**
|
|
20
|
+
* Where the REST routes are mounted under `server` (`/v1`, for an `OpenAPIHandler` with
|
|
21
|
+
* prefix `<api path>/v1`): every path in the document starts with it.
|
|
22
|
+
*/
|
|
23
|
+
prefix: `/${string}`;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* One OpenAPI document of a plugin's REST routes, for Settings › Developer › API reference:
|
|
27
|
+
* serve it at its path in the manifest's `api.docs` (`/openapi/member.json` under `api.url`).
|
|
28
|
+
* Each audience signs in its own way (`securityOf`), and the document says how.
|
|
29
|
+
*
|
|
30
|
+
* const rest = new OpenAPIHandler(router); // mounted at `<api path>/v1`, like the RPC handler
|
|
31
|
+
* const doc = pluginOpenApi(router, {
|
|
32
|
+
* plugin: 'sales', audience: 'member', title, version, server: `${publicUrl}/api`, prefix: '/v1',
|
|
33
|
+
* });
|
|
34
|
+
* app.get('/api/openapi/member.json', async (_req, res) => res.json(await doc));
|
|
35
|
+
*/
|
|
36
|
+
export declare const pluginOpenApi: (router: Documented, { plugin, audience, title, version, description, server, prefix }: PluginOpenApiOptions) => Promise<OpenAPI.Document>;
|
|
37
|
+
export {};
|
package/dist/openapi.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { CORE_API_PREFIX, CUSTOMER_TOKEN_SCHEME, EMPLOYEE_TOKEN_SCHEME, PLUGIN_SESSION_SCHEME, WEBSITE_KEY_SCHEME } from "@erxes/core-contract";
|
|
2
|
+
import { OpenAPIGenerator } from "@orpc/openapi";
|
|
3
|
+
import { ZodToJsonSchemaConverter } from "@orpc/zod/zod4";
|
|
4
|
+
// src/openapi.ts
|
|
5
|
+
const BEARER = {
|
|
6
|
+
type: "http",
|
|
7
|
+
scheme: "bearer",
|
|
8
|
+
bearerFormat: "JWT"
|
|
9
|
+
};
|
|
10
|
+
const customerToken = {
|
|
11
|
+
...BEARER,
|
|
12
|
+
description: `A customer's access token from core: \`POST ${CORE_API_PREFIX}/customer-auth/sign-in\` returns it (core's Customer API documents the sign-in).`
|
|
13
|
+
};
|
|
14
|
+
/** How each audience signs in, for the document's security schemes. */
|
|
15
|
+
const securityOf = (plugin, audience) => {
|
|
16
|
+
if (audience === "member") return {
|
|
17
|
+
components: { securitySchemes: { [PLUGIN_SESSION_SCHEME]: {
|
|
18
|
+
...BEARER,
|
|
19
|
+
description: `A member's 5-minute session token for this plugin: \`POST ${CORE_API_PREFIX}/plugins/${plugin}/session\` on core with an API key (Settings › Developer › API keys) returns it.`
|
|
20
|
+
} } },
|
|
21
|
+
security: [{ [PLUGIN_SESSION_SCHEME]: [] }]
|
|
22
|
+
};
|
|
23
|
+
if (audience === "employee") return {
|
|
24
|
+
components: { securitySchemes: { [EMPLOYEE_TOKEN_SCHEME]: {
|
|
25
|
+
...BEARER,
|
|
26
|
+
description: "An employee's access token, from this plugin's own sign-in in this document (employees sign in to the plugin's app, not to erxes)."
|
|
27
|
+
} } },
|
|
28
|
+
security: [{ [EMPLOYEE_TOKEN_SCHEME]: [] }]
|
|
29
|
+
};
|
|
30
|
+
if (audience === "customer") return {
|
|
31
|
+
components: { securitySchemes: { [CUSTOMER_TOKEN_SCHEME]: customerToken } },
|
|
32
|
+
security: [{ [CUSTOMER_TOKEN_SCHEME]: [] }]
|
|
33
|
+
};
|
|
34
|
+
return {
|
|
35
|
+
components: { securitySchemes: {
|
|
36
|
+
[WEBSITE_KEY_SCHEME]: {
|
|
37
|
+
type: "apiKey",
|
|
38
|
+
in: "header",
|
|
39
|
+
name: "x-api-key",
|
|
40
|
+
description: "The website's key, from the plugin's settings. Keep it on the server."
|
|
41
|
+
},
|
|
42
|
+
[CUSTOMER_TOKEN_SCHEME]: customerToken
|
|
43
|
+
} },
|
|
44
|
+
security: [{ [WEBSITE_KEY_SCHEME]: [] }, {
|
|
45
|
+
[WEBSITE_KEY_SCHEME]: [],
|
|
46
|
+
[CUSTOMER_TOKEN_SCHEME]: []
|
|
47
|
+
}]
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* One OpenAPI document of a plugin's REST routes, for Settings › Developer › API reference:
|
|
52
|
+
* serve it at its path in the manifest's `api.docs` (`/openapi/member.json` under `api.url`).
|
|
53
|
+
* Each audience signs in its own way (`securityOf`), and the document says how.
|
|
54
|
+
*
|
|
55
|
+
* const rest = new OpenAPIHandler(router); // mounted at `<api path>/v1`, like the RPC handler
|
|
56
|
+
* const doc = pluginOpenApi(router, {
|
|
57
|
+
* plugin: 'sales', audience: 'member', title, version, server: `${publicUrl}/api`, prefix: '/v1',
|
|
58
|
+
* });
|
|
59
|
+
* app.get('/api/openapi/member.json', async (_req, res) => res.json(await doc));
|
|
60
|
+
*/
|
|
61
|
+
const pluginOpenApi = async (router, { plugin, audience, title, version, description, server, prefix }) => {
|
|
62
|
+
const doc = await new OpenAPIGenerator({ schemaConverters: [new ZodToJsonSchemaConverter()] }).generate(router, {
|
|
63
|
+
info: {
|
|
64
|
+
title,
|
|
65
|
+
version,
|
|
66
|
+
description
|
|
67
|
+
},
|
|
68
|
+
servers: [{ url: server }],
|
|
69
|
+
...securityOf(plugin, audience)
|
|
70
|
+
});
|
|
71
|
+
doc.paths = Object.fromEntries(Object.entries(doc.paths ?? {}).map(([path, item]) => [`${prefix}${path}`, item]));
|
|
72
|
+
return doc;
|
|
73
|
+
};
|
|
74
|
+
export { pluginOpenApi };
|
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 {
|
|
@@ -127,4 +127,34 @@ export declare const verifyCustomerToken: (authorization: string | undefined | n
|
|
|
127
127
|
* once, and act on the totals in the payload, not on arrival order.
|
|
128
128
|
*/
|
|
129
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>;
|
|
130
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.20",
|
|
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,9 @@
|
|
|
17
17
|
"exports": {
|
|
18
18
|
".": "./dist/index.js",
|
|
19
19
|
"./client": "./dist/client.js",
|
|
20
|
+
"./filter": "./dist/filter.js",
|
|
21
|
+
"./jobs": "./dist/jobs.js",
|
|
22
|
+
"./openapi": "./dist/openapi.js",
|
|
20
23
|
"./verify": "./dist/verify.js",
|
|
21
24
|
"./package.json": "./package.json"
|
|
22
25
|
},
|
|
@@ -28,10 +31,18 @@
|
|
|
28
31
|
"dependencies": {
|
|
29
32
|
"@orpc/client": "1.16.2",
|
|
30
33
|
"@orpc/contract": "1.16.2",
|
|
34
|
+
"@orpc/openapi": "1.16.2",
|
|
31
35
|
"@orpc/openapi-client": "1.16.2",
|
|
36
|
+
"@orpc/zod": "1.16.2",
|
|
32
37
|
"jose": "^6.2.17",
|
|
33
38
|
"zod": "^4.6.7",
|
|
34
|
-
"@erxes/core-contract": "0.1.0-v2.
|
|
39
|
+
"@erxes/core-contract": "0.1.0-v2.21"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"drizzle-orm": "0.45.4"
|
|
43
|
+
},
|
|
44
|
+
"peerDependencies": {
|
|
45
|
+
"drizzle-orm": "0.45.4"
|
|
35
46
|
},
|
|
36
47
|
"scripts": {
|
|
37
48
|
"build": "tsdown"
|