@erxes/plugin-sdk 0.1.0-v2.4 → 0.1.0-v2.6
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 +6 -0
- package/dist/client.js +54 -22
- package/dist/index.d.ts +18 -2
- package/dist/index.js +3 -2
- package/dist/jobs.d.ts +23 -0
- package/dist/jobs.js +18 -0
- package/dist/verify.d.ts +9 -1
- package/dist/verify.js +30 -3
- package/package.json +10 -3
package/dist/client.d.ts
CHANGED
|
@@ -107,6 +107,9 @@ export declare const createCoreClient: (options: CoreClientOptions) => {
|
|
|
107
107
|
INVALID_CLIENT: {
|
|
108
108
|
status: number;
|
|
109
109
|
};
|
|
110
|
+
INVALID_SCHEDULE: {
|
|
111
|
+
status: number;
|
|
112
|
+
};
|
|
110
113
|
LIMIT_EXCEEDED: {
|
|
111
114
|
status: number;
|
|
112
115
|
};
|
|
@@ -216,6 +219,9 @@ export declare const createCoreClient: (options: CoreClientOptions) => {
|
|
|
216
219
|
INVALID_CLIENT: {
|
|
217
220
|
status: number;
|
|
218
221
|
};
|
|
222
|
+
INVALID_SCHEDULE: {
|
|
223
|
+
status: number;
|
|
224
|
+
};
|
|
219
225
|
LIMIT_EXCEEDED: {
|
|
220
226
|
status: number;
|
|
221
227
|
};
|
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/index.d.ts
CHANGED
|
@@ -50,11 +50,27 @@
|
|
|
50
50
|
* if (!member.canChange()) throw new Error('HR is read-only: buy it again on erxes.io');
|
|
51
51
|
* // server-side jobs: await core.forOrg(orgId).saas.pluginPlan() → { tier, access }
|
|
52
52
|
*
|
|
53
|
+
* Jobs (plugins on core's database): declare them in the manifest, queue them in the
|
|
54
|
+
* plugin's own transaction, and serve each at `<api.url>/jobs/<name>`. Core retries
|
|
55
|
+
* until the route answers 2xx (`retry`: attempts in all, the first wait and the
|
|
56
|
+
* longest, in seconds; default 8, 30 s, 6 h). A `cron` (UTC) job runs once per
|
|
57
|
+
* organisation that has the plugin.
|
|
58
|
+
*
|
|
59
|
+
* jobs: [{ name: 'mail.sync', retry: { attempts: 5, delay: 60, maxDelay: 3600 } },
|
|
60
|
+
* { name: 'sla.check', cron: '*\/5 * * * *' }],
|
|
61
|
+
* await enqueueJob(tx, { orgId, name: 'mail.sync', payload: { accountId }, dedupeKey: accountId });
|
|
62
|
+
* app.post('/api/jobs/:name', express.text({ type: '*\/*' }), async (req, res) => {
|
|
63
|
+
* const job = await verifyCoreJob(req.headers.authorization, req.body, { coreUrl, plugin: 'frontline' });
|
|
64
|
+
* await JOBS[job.name](job); // { jobId, orgId, name, attempt, payload }; may repeat
|
|
65
|
+
* res.sendStatus(204);
|
|
66
|
+
* });
|
|
67
|
+
*
|
|
53
68
|
* The client secret is only ever sent to `POST /plugins/token`; API calls use
|
|
54
69
|
* 15-minute tokens, fetched and renewed here. Plugins on core's database can
|
|
55
70
|
* also call `core_publish_event()`, `core_record_audit()` and
|
|
56
71
|
* `core_live_signal()` inside their own transactions.
|
|
57
72
|
*/
|
|
58
73
|
import { CoreClient, CoreClientOptions, CoreTokenError, createCoreClient } from "./client.js";
|
|
59
|
-
import {
|
|
60
|
-
|
|
74
|
+
import { JobInput, enqueueJob } from "./jobs.js";
|
|
75
|
+
import { CoreCall, CustomerSignIn, DeliveredEvent, ErxesSignIn, PluginMember, bearerOf, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession } from "./verify.js";
|
|
76
|
+
export { CoreCall, CoreClient, CoreClientOptions, CoreTokenError, CustomerSignIn, DeliveredEvent, ErxesSignIn, JobInput, PluginMember, bearerOf, createCoreClient, enqueueJob, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession };
|
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, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession } from "./verify.js";
|
|
4
|
+
export { CoreTokenError, DeliveredEvent, bearerOf, createCoreClient, enqueueJob, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession };
|
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 } 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,12 @@ 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
|
+
/**
|
|
131
|
+
* Verifies one attempt of a job core POSTed to `<api.url>/jobs/<name>` and
|
|
132
|
+
* returns it: the token is core's, for this plugin, unexpired, and signs this
|
|
133
|
+
* exact body (pass the raw body text). Throws if anything is off. Answer 2xx
|
|
134
|
+
* when done; anything else retries. A job can run more than once: the
|
|
135
|
+
* `Idempotency-Key` header is its `jobId`.
|
|
136
|
+
*/
|
|
137
|
+
export declare const verifyCoreJob: (authorization: string | undefined | null, rawBody: string, options: VerifyOptions) => Promise<PluginJobDelivery>;
|
|
130
138
|
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 } 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`);
|
|
@@ -147,4 +153,25 @@ const verifyCoreEvent = async (authorization, rawBody, options) => {
|
|
|
147
153
|
if (event.id !== claims.event || event.organizationId !== claims.org) throw new Error("the event does not match the token");
|
|
148
154
|
return event;
|
|
149
155
|
};
|
|
150
|
-
|
|
156
|
+
const JobClaims = z.object({
|
|
157
|
+
sha: z.string(),
|
|
158
|
+
job: z.string(),
|
|
159
|
+
org: z.string()
|
|
160
|
+
});
|
|
161
|
+
/**
|
|
162
|
+
* Verifies one attempt of a job core POSTed to `<api.url>/jobs/<name>` and
|
|
163
|
+
* returns it: the token is core's, for this plugin, unexpired, and signs this
|
|
164
|
+
* exact body (pass the raw body text). Throws if anything is off. Answer 2xx
|
|
165
|
+
* when done; anything else retries. A job can run more than once: the
|
|
166
|
+
* `Idempotency-Key` header is its `jobId`.
|
|
167
|
+
*/
|
|
168
|
+
const verifyCoreJob = async (authorization, rawBody, options) => {
|
|
169
|
+
const token = bearerOf(authorization);
|
|
170
|
+
if (!token) throw new Error("no core token");
|
|
171
|
+
const claims = await verifyCoreToken(token, options, "erxes-core-job+jwt", JobClaims);
|
|
172
|
+
if (claims.sha !== await sha256(rawBody)) throw new Error("the body does not match the token");
|
|
173
|
+
const job = PluginJobDelivery.parse(JSON.parse(rawBody));
|
|
174
|
+
if (job.jobId !== claims.job || job.orgId !== claims.org) throw new Error("the job does not match the token");
|
|
175
|
+
return job;
|
|
176
|
+
};
|
|
177
|
+
export { DeliveredEvent, bearerOf, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession };
|
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.6",
|
|
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,7 @@
|
|
|
17
17
|
"exports": {
|
|
18
18
|
".": "./dist/index.js",
|
|
19
19
|
"./client": "./dist/client.js",
|
|
20
|
+
"./jobs": "./dist/jobs.js",
|
|
20
21
|
"./verify": "./dist/verify.js",
|
|
21
22
|
"./package.json": "./package.json"
|
|
22
23
|
},
|
|
@@ -31,7 +32,13 @@
|
|
|
31
32
|
"@orpc/openapi-client": "1.16.2",
|
|
32
33
|
"jose": "^6.2.17",
|
|
33
34
|
"zod": "^4.6.7",
|
|
34
|
-
"@erxes/core-contract": "0.1.0-v2.
|
|
35
|
+
"@erxes/core-contract": "0.1.0-v2.7"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"drizzle-orm": "0.45.4"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"drizzle-orm": "0.45.4"
|
|
35
42
|
},
|
|
36
43
|
"scripts": {
|
|
37
44
|
"build": "tsdown"
|