@erxes/plugin-sdk 0.0.0-stage → 0.1.0-v2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.d.ts +27 -0
- package/dist/client.js +88 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.js +3 -0
- package/dist/verify.d.ts +115 -0
- package/dist/verify.js +136 -0
- package/package.json +36 -3
- package/README.md +0 -3
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { PluginManifest, coreContract } from "@erxes/core-contract";
|
|
2
|
+
import { ContractRouterClient } from "@orpc/contract";
|
|
3
|
+
export type CoreClient = ContractRouterClient<typeof coreContract>;
|
|
4
|
+
export interface CoreClientOptions {
|
|
5
|
+
/** Core's address, e.g. `https://acme.erxes.io` (without `/core/v1`). */
|
|
6
|
+
coreUrl: string;
|
|
7
|
+
plugin: string;
|
|
8
|
+
clientSecret: string;
|
|
9
|
+
fetch?: typeof globalThis.fetch;
|
|
10
|
+
}
|
|
11
|
+
export declare class CoreTokenError extends Error {
|
|
12
|
+
readonly status: number;
|
|
13
|
+
readonly code: string;
|
|
14
|
+
constructor(status: number, code: string, message: string);
|
|
15
|
+
}
|
|
16
|
+
export declare const createCoreClient: (options: CoreClientOptions) => {
|
|
17
|
+
/** The core API acting in one organisation (that installed the plugin). */
|
|
18
|
+
forOrg(orgId: string): CoreClient;
|
|
19
|
+
/** Declares the plugin's UI, API, scopes, permissions and events. Call at startup. */
|
|
20
|
+
registerManifest: (manifest: PluginManifest) => import("@orpc/client").ClientPromiseResult<{
|
|
21
|
+
ok: true;
|
|
22
|
+
}, Error>;
|
|
23
|
+
/** Tells the plugin's open UIs that topics changed (needs `live:write`). */
|
|
24
|
+
signal: (orgId: string, topics: string[], userIds?: string[]) => import("@orpc/client").ClientPromiseResult<{
|
|
25
|
+
ok: true;
|
|
26
|
+
}, Error>;
|
|
27
|
+
};
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { CORE_API_PREFIX, coreContract } from "@erxes/core-contract";
|
|
2
|
+
import { createORPCClient } from "@orpc/client";
|
|
3
|
+
import { OpenAPILink } from "@orpc/openapi-client/fetch";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
// src/client.ts
|
|
6
|
+
var CoreTokenError = class extends Error {
|
|
7
|
+
status;
|
|
8
|
+
code;
|
|
9
|
+
constructor(status, code, message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.status = status;
|
|
12
|
+
this.code = code;
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
/** `POST /plugins/token`'s answer: a token, or an error's code and message. */
|
|
16
|
+
const TokenAnswer = z.object({
|
|
17
|
+
access_token: z.string().optional(),
|
|
18
|
+
expires_in: z.number().optional(),
|
|
19
|
+
code: z.string().optional(),
|
|
20
|
+
message: z.string().optional()
|
|
21
|
+
}).catch({});
|
|
22
|
+
const createCoreClient = (options) => {
|
|
23
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
24
|
+
const base = options.coreUrl.replace(/\/+$/, "");
|
|
25
|
+
const tokens = /* @__PURE__ */ new Map();
|
|
26
|
+
const requestToken = async (org) => {
|
|
27
|
+
const response = await fetcher(`${base}${CORE_API_PREFIX}/plugins/token`, {
|
|
28
|
+
method: "POST",
|
|
29
|
+
headers: { "content-type": "application/json" },
|
|
30
|
+
body: JSON.stringify({
|
|
31
|
+
grant_type: "client_credentials",
|
|
32
|
+
client_id: options.plugin,
|
|
33
|
+
client_secret: options.clientSecret,
|
|
34
|
+
org
|
|
35
|
+
})
|
|
36
|
+
});
|
|
37
|
+
const body = TokenAnswer.parse(await response.json().catch(() => ({})));
|
|
38
|
+
if (!response.ok || !body.access_token) throw new CoreTokenError(response.status, body.code ?? "TOKEN_FAILED", body.message ?? "Could not get a core token");
|
|
39
|
+
return {
|
|
40
|
+
token: body.access_token,
|
|
41
|
+
expiresAt: Date.now() + (body.expires_in ?? 900) * 1e3
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
/** A token for the organisation (or the deployment), renewed a minute before it ends. */
|
|
45
|
+
const tokenFor = async (org, fresh = false) => {
|
|
46
|
+
const key = org ?? "";
|
|
47
|
+
const cached = tokens.get(key);
|
|
48
|
+
if (cached && !fresh) {
|
|
49
|
+
const value = await cached.catch(() => null);
|
|
50
|
+
if (value && value.expiresAt - Date.now() > 6e4) return value.token;
|
|
51
|
+
}
|
|
52
|
+
const request = requestToken(org);
|
|
53
|
+
tokens.set(key, request);
|
|
54
|
+
request.catch(() => tokens.delete(key));
|
|
55
|
+
return (await request).token;
|
|
56
|
+
};
|
|
57
|
+
const clientFor = (org) => createORPCClient(new OpenAPILink(coreContract, {
|
|
58
|
+
url: `${base}${CORE_API_PREFIX}`,
|
|
59
|
+
fetch: async (request, init) => {
|
|
60
|
+
const send = async (token) => {
|
|
61
|
+
const headers = new Headers(request.headers);
|
|
62
|
+
headers.set("authorization", `Bearer ${token}`);
|
|
63
|
+
return fetcher(new Request(request, { headers }), init);
|
|
64
|
+
};
|
|
65
|
+
const response = await send(await tokenFor(org));
|
|
66
|
+
return response.status === 401 ? send(await tokenFor(org, true)) : response;
|
|
67
|
+
}
|
|
68
|
+
}));
|
|
69
|
+
const orgClients = /* @__PURE__ */ new Map();
|
|
70
|
+
return {
|
|
71
|
+
/** The core API acting in one organisation (that installed the plugin). */
|
|
72
|
+
forOrg(orgId) {
|
|
73
|
+
const known = orgClients.get(orgId);
|
|
74
|
+
if (known) return known;
|
|
75
|
+
const client = clientFor(orgId);
|
|
76
|
+
orgClients.set(orgId, client);
|
|
77
|
+
return client;
|
|
78
|
+
},
|
|
79
|
+
/** Declares the plugin's UI, API, scopes, permissions and events. Call at startup. */
|
|
80
|
+
registerManifest: (manifest) => clientFor().plugins.registerManifest(manifest),
|
|
81
|
+
/** Tells the plugin's open UIs that topics changed (needs `live:write`). */
|
|
82
|
+
signal: (orgId, topics, userIds) => clientFor(orgId).plugins.signal({
|
|
83
|
+
topics,
|
|
84
|
+
userIds
|
|
85
|
+
})
|
|
86
|
+
};
|
|
87
|
+
};
|
|
88
|
+
export { CoreTokenError, createCoreClient };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* For plugin servers (`hr`, `ecom`, …):
|
|
3
|
+
*
|
|
4
|
+
* const core = createCoreClient({ coreUrl, plugin: 'hr', clientSecret });
|
|
5
|
+
* await core.registerManifest({ title: 'HR', version: '1.0.0', scopes: ['notifications:write'] });
|
|
6
|
+
* await core.forOrg(orgId).notifications.create({ userIds, kind: 'hr.leave.requested', title });
|
|
7
|
+
*
|
|
8
|
+
* const member = await verifyPluginSession(token, { coreUrl, plugin: 'hr' });
|
|
9
|
+
*
|
|
10
|
+
* Payments (scopes `payments:write`, `payments:read`; subscribe to `core.payment.*`):
|
|
11
|
+
*
|
|
12
|
+
* const invoice = await core.forOrg(orgId).payments.createInvoice({
|
|
13
|
+
* amount: 150000, description: 'Order #12', reference: { type: 'order', id: order.id },
|
|
14
|
+
* metadata: { orderId: order.id }, dedupeKey: `order:${order.id}`,
|
|
15
|
+
* }); // show invoice.payment.qrImage / links to the payer
|
|
16
|
+
* app.post('/events', express.text({ type: '*\/*' }), async (req, res) => {
|
|
17
|
+
* const event = await verifyCoreEvent(req.headers.authorization, req.body, { coreUrl, plugin: 'ecom' });
|
|
18
|
+
* if (event.type === 'core.payment.paid') await markOrderPaid(event.data.payload.metadata.orderId);
|
|
19
|
+
* res.sendStatus(204); // anything but 2xx is retried; handle each event id once
|
|
20
|
+
* });
|
|
21
|
+
* await core.forOrg(orgId).payments.refund({ id: invoice.id, reason: 'Out of stock' });
|
|
22
|
+
*
|
|
23
|
+
* Products (scopes `products:read`, `products:write`): one catalog per organisation, shared by plugins.
|
|
24
|
+
* Prices are integers in the organisation's currency's smallest unit (`organizations.current()`).
|
|
25
|
+
*
|
|
26
|
+
* const mine = await core.forOrg(orgId).products.list({}); // the ones this plugin uses
|
|
27
|
+
* const found = await core.forOrg(orgId).products.list({ search: 'phone', all: true });
|
|
28
|
+
* await core.forOrg(orgId).products.use({ ids: [found.data[0].id], used: true });
|
|
29
|
+
* // An invoice may list what it pays for; `plugin` names another plugin's line (it gets the events):
|
|
30
|
+
* // lines: [{ productId, quantity: 1, unitPrice: 150000 }, { name: 'Delivery', quantity: 1, unitPrice: 10000, plugin: 'tms' }]
|
|
31
|
+
*
|
|
32
|
+
* Tiers on SaaS (erxes.io: free / plus / pro; self-hosted: pro, full):
|
|
33
|
+
*
|
|
34
|
+
* const member = await verifyPluginSession(token, { coreUrl, plugin: 'hr' });
|
|
35
|
+
* if (member.tier === 'free' && employees >= 20) throw new Error('Upgrade to Plus for more employees');
|
|
36
|
+
* if (!member.canChange()) throw new Error('HR is read-only: buy it again on erxes.io');
|
|
37
|
+
* // server-side jobs: await core.forOrg(orgId).saas.pluginPlan() → { tier, access }
|
|
38
|
+
*
|
|
39
|
+
* The client secret is only ever sent to `POST /plugins/token`; API calls use
|
|
40
|
+
* 15-minute tokens, fetched and renewed here. Plugins on core's database can
|
|
41
|
+
* also call `core_publish_event()`, `core_record_audit()` and
|
|
42
|
+
* `core_live_signal()` inside their own transactions.
|
|
43
|
+
*/
|
|
44
|
+
import { CoreClient, CoreClientOptions, CoreTokenError, createCoreClient } from "./client.js";
|
|
45
|
+
import { CoreCall, DeliveredEvent, ErxesSignIn, PluginMember, bearerOf, verifyCoreCall, verifyCoreEvent, verifyErxesAccessToken, verifyPluginSession } from "./verify.js";
|
|
46
|
+
export { CoreCall, CoreClient, CoreClientOptions, CoreTokenError, DeliveredEvent, ErxesSignIn, PluginMember, bearerOf, createCoreClient, verifyCoreCall, verifyCoreEvent, verifyErxesAccessToken, verifyPluginSession };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { CoreTokenError, createCoreClient } from "./client.js";
|
|
2
|
+
import { DeliveredEvent, bearerOf, verifyCoreCall, verifyCoreEvent, verifyErxesAccessToken, verifyPluginSession } from "./verify.js";
|
|
3
|
+
export { CoreTokenError, DeliveredEvent, bearerOf, createCoreClient, verifyCoreCall, verifyCoreEvent, verifyErxesAccessToken, verifyPluginSession };
|
package/dist/verify.d.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/** The signed-in member a plugin UI calls the plugin's API for. */
|
|
3
|
+
export interface PluginMember {
|
|
4
|
+
userId: string;
|
|
5
|
+
orgId: string;
|
|
6
|
+
/** `owner`, `admin`, `member` or a custom role key. */
|
|
7
|
+
role: string;
|
|
8
|
+
/** The member's actions in this plugin (from its manifest's `permissions`). */
|
|
9
|
+
permissions: string[];
|
|
10
|
+
/** `member.can('hr.leave.approve')` */
|
|
11
|
+
can(action: string): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* The plugin's tier in this organisation on erxes.io (`free`, `plus`,
|
|
14
|
+
* `pro`): gate paid features with it. Self-hosted: `pro`.
|
|
15
|
+
*/
|
|
16
|
+
tier: 'free' | 'plus' | 'pro' | null;
|
|
17
|
+
/**
|
|
18
|
+
* `full`, `warning` (payment retrying / ending at period end: still
|
|
19
|
+
* works), `read_only` (left the plan: let them read and export, refuse
|
|
20
|
+
* changes). Self-hosted: `full`.
|
|
21
|
+
*/
|
|
22
|
+
access: 'full' | 'warning' | 'read_only' | 'off';
|
|
23
|
+
/** `member.canChange()`: false while read-only. */
|
|
24
|
+
canChange(): boolean;
|
|
25
|
+
}
|
|
26
|
+
/** A member signed into a plugin's own app with "Sign in with erxes". */
|
|
27
|
+
export interface ErxesSignIn extends PluginMember {
|
|
28
|
+
scope: string[];
|
|
29
|
+
}
|
|
30
|
+
/** Who is calling a plugin's automation action: core, for an automation's run. */
|
|
31
|
+
export interface CoreCall {
|
|
32
|
+
orgId: string;
|
|
33
|
+
/** The member the automation acts as. */
|
|
34
|
+
userId: string;
|
|
35
|
+
automationId: string;
|
|
36
|
+
runId: string;
|
|
37
|
+
stepId: string;
|
|
38
|
+
}
|
|
39
|
+
/** An event core delivered to the plugin's `<api.url>/events` (from its manifest's `subscriptions`). */
|
|
40
|
+
export declare const DeliveredEvent: z.ZodObject<{
|
|
41
|
+
id: z.ZodString;
|
|
42
|
+
type: z.ZodString;
|
|
43
|
+
organizationId: z.ZodString;
|
|
44
|
+
createdAt: z.ZodString;
|
|
45
|
+
data: z.ZodObject<{
|
|
46
|
+
id: z.ZodString;
|
|
47
|
+
source: z.ZodString;
|
|
48
|
+
type: z.ZodString;
|
|
49
|
+
version: z.ZodInt;
|
|
50
|
+
payload: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
51
|
+
summary: z.ZodNullable<z.ZodString>;
|
|
52
|
+
link: z.ZodNullable<z.ZodString>;
|
|
53
|
+
occurredAt: z.ZodISODateTime;
|
|
54
|
+
createdAt: z.ZodISODateTime;
|
|
55
|
+
subject: z.ZodNullable<z.ZodObject<{
|
|
56
|
+
type: z.ZodEnum<{
|
|
57
|
+
company: "company";
|
|
58
|
+
customer: "customer";
|
|
59
|
+
}>;
|
|
60
|
+
id: z.ZodString;
|
|
61
|
+
}, z.core.$strip>>;
|
|
62
|
+
entity: z.ZodNullable<z.ZodObject<{
|
|
63
|
+
type: z.ZodString;
|
|
64
|
+
id: z.ZodString;
|
|
65
|
+
}, z.core.$strip>>;
|
|
66
|
+
actor: z.ZodObject<{
|
|
67
|
+
type: z.ZodEnum<{
|
|
68
|
+
plugin: "plugin";
|
|
69
|
+
system: "system";
|
|
70
|
+
user: "user";
|
|
71
|
+
}>;
|
|
72
|
+
id: z.ZodNullable<z.ZodString>;
|
|
73
|
+
name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
74
|
+
avatarUrl: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
75
|
+
}, z.core.$strip>;
|
|
76
|
+
}, {
|
|
77
|
+
out: {};
|
|
78
|
+
in: {};
|
|
79
|
+
}>;
|
|
80
|
+
}, z.core.$strip>;
|
|
81
|
+
export type DeliveredEvent = z.infer<typeof DeliveredEvent>;
|
|
82
|
+
interface VerifyOptions {
|
|
83
|
+
coreUrl: string;
|
|
84
|
+
plugin: string;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Verifies a member's plugin session token (`Authorization: Bearer …` from
|
|
88
|
+
* erxes-ui's `pluginFetch`) with core's public keys: issued by core, for this
|
|
89
|
+
* plugin, unexpired. Throws if not.
|
|
90
|
+
*/
|
|
91
|
+
export declare const verifyPluginSession: (token: string, options: VerifyOptions) => Promise<PluginMember>;
|
|
92
|
+
/** The bearer token of a request's `Authorization` header, if any. */
|
|
93
|
+
export declare const bearerOf: (authorization: string | undefined | null) => string | null;
|
|
94
|
+
/**
|
|
95
|
+
* Verifies the token core sends with an automation action
|
|
96
|
+
* (`POST <api.url>/automations/actions/<type>`): issued by core, for this
|
|
97
|
+
* plugin, unexpired. A retried call carries the same `Idempotency-Key` header
|
|
98
|
+
* (`<run>:<step>`): record it with the action's effect so a retry does nothing twice.
|
|
99
|
+
*/
|
|
100
|
+
export declare const verifyCoreCall: (token: string, options: VerifyOptions) => Promise<CoreCall>;
|
|
101
|
+
/**
|
|
102
|
+
* Verifies an access token from "Sign in with erxes" (OAuth 2.1, PKCE) for the
|
|
103
|
+
* plugin's own app: issued by core, for this client (the plugin), unexpired.
|
|
104
|
+
* Discovery: `<coreUrl>/core/v1/.well-known/openid-configuration`.
|
|
105
|
+
*/
|
|
106
|
+
export declare const verifyErxesAccessToken: (token: string, options: VerifyOptions) => Promise<ErxesSignIn>;
|
|
107
|
+
/**
|
|
108
|
+
* Verifies an event delivery and returns the event: the `Authorization`
|
|
109
|
+
* token is core's, for this plugin, unexpired, and signs this exact body
|
|
110
|
+
* (pass the raw body text, not parsed JSON). Throws if anything is off.
|
|
111
|
+
* Deliveries can repeat and arrive out of order: handle each `event.id`
|
|
112
|
+
* once, and act on the totals in the payload, not on arrival order.
|
|
113
|
+
*/
|
|
114
|
+
export declare const verifyCoreEvent: (authorization: string | undefined | null, rawBody: string, options: VerifyOptions) => Promise<DeliveredEvent>;
|
|
115
|
+
export {};
|
package/dist/verify.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { CORE_API_PREFIX, CoreEvent } from "@erxes/core-contract";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
4
|
+
// src/verify.ts
|
|
5
|
+
/** An event core delivered to the plugin's `<api.url>/events` (from its manifest's `subscriptions`). */
|
|
6
|
+
const DeliveredEvent = z.object({
|
|
7
|
+
id: z.string(),
|
|
8
|
+
type: z.string(),
|
|
9
|
+
organizationId: z.string(),
|
|
10
|
+
createdAt: z.string(),
|
|
11
|
+
data: CoreEvent
|
|
12
|
+
});
|
|
13
|
+
const jwksByCore = /* @__PURE__ */ new Map();
|
|
14
|
+
/** A token core signed (its public keys), for this plugin, of this kind, unexpired; its claims parsed. */
|
|
15
|
+
const verifyCoreToken = async (token, options, typ, claims) => {
|
|
16
|
+
const base = options.coreUrl.replace(/\/+$/, "");
|
|
17
|
+
let jwks = jwksByCore.get(base);
|
|
18
|
+
if (!jwks) {
|
|
19
|
+
jwks = createRemoteJWKSet(new URL(`${base}${CORE_API_PREFIX}/.well-known/jwks.json`));
|
|
20
|
+
jwksByCore.set(base, jwks);
|
|
21
|
+
}
|
|
22
|
+
const { payload } = await jwtVerify(token, jwks, {
|
|
23
|
+
issuer: "erxes-core",
|
|
24
|
+
audience: options.plugin,
|
|
25
|
+
typ,
|
|
26
|
+
algorithms: ["ES256"]
|
|
27
|
+
});
|
|
28
|
+
const parsed = claims.safeParse(payload);
|
|
29
|
+
if (!parsed.success) throw new Error(`not an erxes ${typ} token`);
|
|
30
|
+
return parsed.data;
|
|
31
|
+
};
|
|
32
|
+
const Tier = z.enum([
|
|
33
|
+
"free",
|
|
34
|
+
"plus",
|
|
35
|
+
"pro"
|
|
36
|
+
]);
|
|
37
|
+
const Access = z.enum([
|
|
38
|
+
"full",
|
|
39
|
+
"warning",
|
|
40
|
+
"read_only",
|
|
41
|
+
"off"
|
|
42
|
+
]);
|
|
43
|
+
const Strings = z.array(z.unknown()).transform((items) => items.filter((item) => typeof item === "string"));
|
|
44
|
+
const member = (claims) => ({
|
|
45
|
+
userId: claims.sub,
|
|
46
|
+
orgId: claims.org,
|
|
47
|
+
role: claims.role,
|
|
48
|
+
permissions: claims.permissions,
|
|
49
|
+
can: (action) => claims.role === "owner" || claims.permissions.includes(action),
|
|
50
|
+
tier: claims.tier,
|
|
51
|
+
access: claims.access,
|
|
52
|
+
canChange: () => claims.access === "full" || claims.access === "warning"
|
|
53
|
+
});
|
|
54
|
+
const SessionClaims = z.object({
|
|
55
|
+
sub: z.string().min(1),
|
|
56
|
+
org: z.string(),
|
|
57
|
+
role: z.string(),
|
|
58
|
+
permissions: Strings,
|
|
59
|
+
tier: z.union([Tier, z.null()]).catch("pro"),
|
|
60
|
+
access: Access.catch("full")
|
|
61
|
+
});
|
|
62
|
+
/**
|
|
63
|
+
* Verifies a member's plugin session token (`Authorization: Bearer …` from
|
|
64
|
+
* erxes-ui's `pluginFetch`) with core's public keys: issued by core, for this
|
|
65
|
+
* plugin, unexpired. Throws if not.
|
|
66
|
+
*/
|
|
67
|
+
const verifyPluginSession = async (token, options) => member(await verifyCoreToken(token, options, "erxes-plugin-session+jwt", SessionClaims));
|
|
68
|
+
/** The bearer token of a request's `Authorization` header, if any. */
|
|
69
|
+
const bearerOf = (authorization) => authorization?.startsWith("Bearer ") ? authorization.slice(7).trim() || null : null;
|
|
70
|
+
const CallClaims = z.object({
|
|
71
|
+
org: z.string(),
|
|
72
|
+
user: z.string(),
|
|
73
|
+
automation: z.string(),
|
|
74
|
+
run: z.string(),
|
|
75
|
+
step: z.string()
|
|
76
|
+
}).transform((claims) => ({
|
|
77
|
+
orgId: claims.org,
|
|
78
|
+
userId: claims.user,
|
|
79
|
+
automationId: claims.automation,
|
|
80
|
+
runId: claims.run,
|
|
81
|
+
stepId: claims.step
|
|
82
|
+
}));
|
|
83
|
+
/**
|
|
84
|
+
* Verifies the token core sends with an automation action
|
|
85
|
+
* (`POST <api.url>/automations/actions/<type>`): issued by core, for this
|
|
86
|
+
* plugin, unexpired. A retried call carries the same `Idempotency-Key` header
|
|
87
|
+
* (`<run>:<step>`): record it with the action's effect so a retry does nothing twice.
|
|
88
|
+
*/
|
|
89
|
+
const verifyCoreCall = (token, options) => verifyCoreToken(token, options, "erxes-core-call+jwt", CallClaims);
|
|
90
|
+
const AccessTokenClaims = z.object({
|
|
91
|
+
sub: z.string().min(1),
|
|
92
|
+
org: z.string(),
|
|
93
|
+
role: z.string().catch("member"),
|
|
94
|
+
permissions: Strings.catch([]),
|
|
95
|
+
tier: Tier.catch("pro"),
|
|
96
|
+
access: Access.catch("full"),
|
|
97
|
+
scope: z.string().transform((scope) => scope.split(" ")).catch([])
|
|
98
|
+
});
|
|
99
|
+
/**
|
|
100
|
+
* Verifies an access token from "Sign in with erxes" (OAuth 2.1, PKCE) for the
|
|
101
|
+
* plugin's own app: issued by core, for this client (the plugin), unexpired.
|
|
102
|
+
* Discovery: `<coreUrl>/core/v1/.well-known/openid-configuration`.
|
|
103
|
+
*/
|
|
104
|
+
const verifyErxesAccessToken = async (token, options) => {
|
|
105
|
+
const claims = await verifyCoreToken(token, options, "at+jwt", AccessTokenClaims);
|
|
106
|
+
return {
|
|
107
|
+
...member(claims),
|
|
108
|
+
scope: claims.scope
|
|
109
|
+
};
|
|
110
|
+
};
|
|
111
|
+
const sha256 = async (text) => {
|
|
112
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
|
|
113
|
+
return btoa(String.fromCharCode(...digest)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
114
|
+
};
|
|
115
|
+
const EventClaims = z.object({
|
|
116
|
+
sha: z.string(),
|
|
117
|
+
event: z.string(),
|
|
118
|
+
org: z.string()
|
|
119
|
+
});
|
|
120
|
+
/**
|
|
121
|
+
* Verifies an event delivery and returns the event: the `Authorization`
|
|
122
|
+
* token is core's, for this plugin, unexpired, and signs this exact body
|
|
123
|
+
* (pass the raw body text, not parsed JSON). Throws if anything is off.
|
|
124
|
+
* Deliveries can repeat and arrive out of order: handle each `event.id`
|
|
125
|
+
* once, and act on the totals in the payload, not on arrival order.
|
|
126
|
+
*/
|
|
127
|
+
const verifyCoreEvent = async (authorization, rawBody, options) => {
|
|
128
|
+
const token = bearerOf(authorization);
|
|
129
|
+
if (!token) throw new Error("no core token");
|
|
130
|
+
const claims = await verifyCoreToken(token, options, "erxes-core-event+jwt", EventClaims);
|
|
131
|
+
if (claims.sha !== await sha256(rawBody)) throw new Error("the body does not match the token");
|
|
132
|
+
const event = DeliveredEvent.parse(JSON.parse(rawBody));
|
|
133
|
+
if (event.id !== claims.event || event.organizationId !== claims.org) throw new Error("the event does not match the token");
|
|
134
|
+
return event;
|
|
135
|
+
};
|
|
136
|
+
export { DeliveredEvent, bearerOf, verifyCoreCall, verifyCoreEvent, verifyErxesAccessToken, verifyPluginSession };
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@erxes/plugin-sdk",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.1.0-v2.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"description": "For erxes plugin servers: a typed core client with automatic plugin tokens, and verification of members' plugin session tokens",
|
|
6
|
+
"license": "AGPL-3.0-only",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/erxes/erxes.git",
|
|
10
|
+
"directory": "packages/plugin-sdk"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"dist"
|
|
14
|
+
],
|
|
15
|
+
"type": "module",
|
|
16
|
+
"sideEffects": false,
|
|
17
|
+
"exports": {
|
|
18
|
+
".": "./dist/index.js",
|
|
19
|
+
"./client": "./dist/client.js",
|
|
20
|
+
"./verify": "./dist/verify.js",
|
|
21
|
+
"./package.json": "./package.json"
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public",
|
|
25
|
+
"provenance": true,
|
|
26
|
+
"tag": "v2-next"
|
|
27
|
+
},
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@orpc/client": "1.16.2",
|
|
30
|
+
"@orpc/contract": "1.16.2",
|
|
31
|
+
"@orpc/openapi-client": "1.16.2",
|
|
32
|
+
"jose": "^5.9.6",
|
|
33
|
+
"zod": "^4.6.7",
|
|
34
|
+
"@erxes/core-contract": "0.1.0-v2.0"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "tsdown"
|
|
38
|
+
}
|
|
6
39
|
}
|
package/README.md
DELETED