@erxes/plugin-sdk 0.0.0-stage → 0.1.0-v2.1
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 +89 -0
- package/dist/index.d.ts +60 -0
- package/dist/index.js +3 -0
- package/dist/verify.d.ts +138 -0
- package/dist/verify.js +150 -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,89 @@
|
|
|
1
|
+
import { CORE_API_PREFIX } from "@erxes/core-contract";
|
|
2
|
+
import { coreRoutes } from "@erxes/core-contract/routes";
|
|
3
|
+
import { createORPCClient } from "@orpc/client";
|
|
4
|
+
import { OpenAPILink } from "@orpc/openapi-client/fetch";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
// src/client.ts
|
|
7
|
+
var CoreTokenError = class extends Error {
|
|
8
|
+
status;
|
|
9
|
+
code;
|
|
10
|
+
constructor(status, code, message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.status = status;
|
|
13
|
+
this.code = code;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
/** `POST /plugins/token`'s answer: a token, or an error's code and message. */
|
|
17
|
+
const TokenAnswer = z.object({
|
|
18
|
+
access_token: z.string().optional(),
|
|
19
|
+
expires_in: z.number().optional(),
|
|
20
|
+
code: z.string().optional(),
|
|
21
|
+
message: z.string().optional()
|
|
22
|
+
});
|
|
23
|
+
const createCoreClient = (options) => {
|
|
24
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
25
|
+
const base = options.coreUrl.replace(/\/+$/, "");
|
|
26
|
+
const tokens = /* @__PURE__ */ new Map();
|
|
27
|
+
const requestToken = async (org) => {
|
|
28
|
+
const response = await fetcher(`${base}${CORE_API_PREFIX}/plugins/token`, {
|
|
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
|
+
});
|
|
38
|
+
const body = TokenAnswer.safeParse(await response.json().catch(() => null)).data ?? {};
|
|
39
|
+
if (!response.ok || !body.access_token) throw new CoreTokenError(response.status, body.code ?? "TOKEN_FAILED", body.message ?? "Could not get a core token");
|
|
40
|
+
return {
|
|
41
|
+
token: body.access_token,
|
|
42
|
+
expiresAt: Date.now() + (body.expires_in ?? 900) * 1e3
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
/** A token for the organisation (or the deployment), renewed a minute before it ends. */
|
|
46
|
+
const tokenFor = async (org, fresh = false) => {
|
|
47
|
+
const key = org ?? "";
|
|
48
|
+
const cached = tokens.get(key);
|
|
49
|
+
if (cached && !fresh) {
|
|
50
|
+
const value = await cached.catch(() => null);
|
|
51
|
+
if (value && value.expiresAt - Date.now() > 6e4) return value.token;
|
|
52
|
+
}
|
|
53
|
+
const request = requestToken(org);
|
|
54
|
+
tokens.set(key, request);
|
|
55
|
+
request.catch(() => tokens.delete(key));
|
|
56
|
+
return (await request).token;
|
|
57
|
+
};
|
|
58
|
+
const clientFor = (org) => createORPCClient(new OpenAPILink(coreRoutes, {
|
|
59
|
+
url: `${base}${CORE_API_PREFIX}`,
|
|
60
|
+
fetch: async (request, init) => {
|
|
61
|
+
const send = async (token) => {
|
|
62
|
+
const headers = new Headers(request.headers);
|
|
63
|
+
headers.set("authorization", `Bearer ${token}`);
|
|
64
|
+
return fetcher(new Request(request, { headers }), init);
|
|
65
|
+
};
|
|
66
|
+
const response = await send(await tokenFor(org));
|
|
67
|
+
return response.status === 401 ? send(await tokenFor(org, true)) : response;
|
|
68
|
+
}
|
|
69
|
+
}));
|
|
70
|
+
const orgClients = /* @__PURE__ */ new Map();
|
|
71
|
+
return {
|
|
72
|
+
/** The core API acting in one organisation (that installed the plugin). */
|
|
73
|
+
forOrg(orgId) {
|
|
74
|
+
const known = orgClients.get(orgId);
|
|
75
|
+
if (known) return known;
|
|
76
|
+
const client = clientFor(orgId);
|
|
77
|
+
orgClients.set(orgId, client);
|
|
78
|
+
return client;
|
|
79
|
+
},
|
|
80
|
+
/** Declares the plugin's UI, API, scopes, permissions and events. Call at startup. */
|
|
81
|
+
registerManifest: (manifest) => clientFor().plugins.registerManifest(manifest),
|
|
82
|
+
/** Tells the plugin's open UIs that topics changed (needs `live:write`). */
|
|
83
|
+
signal: (orgId, topics, userIds) => clientFor(orgId).plugins.signal({
|
|
84
|
+
topics,
|
|
85
|
+
userIds
|
|
86
|
+
})
|
|
87
|
+
};
|
|
88
|
+
};
|
|
89
|
+
export { CoreTokenError, createCoreClient };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
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
|
+
* Customers (a shop, tracking, booking): core signs them in; the plugin never builds sign-up or
|
|
33
|
+
* sign-in. Declare `customerApp: { origins: ['https://{subdomain}.shop.example.com'] }` in the
|
|
34
|
+
* manifest. The app's own form makes two calls to core: `POST /core/v1/customer-auth/code`
|
|
35
|
+
* `{ clientId, kind, value }` sends a code, `POST /core/v1/customer-auth/sign-in` with the code
|
|
36
|
+
* returns `{ accessToken, refreshToken, expiresIn, customer }`; `/customer-auth/refresh` renews
|
|
37
|
+
* them. Serve customers under `/customer/*`, keyed by the customer id:
|
|
38
|
+
*
|
|
39
|
+
* app.use('/customer', async (req, res, next) => {
|
|
40
|
+
* req.customer = await verifyCustomerToken(req.headers.authorization, { coreUrl })
|
|
41
|
+
* .catch(() => null); // { orgId, customerId, clientId }
|
|
42
|
+
* return req.customer ? next() : res.sendStatus(401);
|
|
43
|
+
* });
|
|
44
|
+
* app.get('/customer/orders', (req) => orders.list(req.customer.orgId, req.customer.customerId));
|
|
45
|
+
*
|
|
46
|
+
* Tiers on SaaS (erxes.io: free / plus / pro; self-hosted: pro, full):
|
|
47
|
+
*
|
|
48
|
+
* const member = await verifyPluginSession(token, { coreUrl, plugin: 'hr' });
|
|
49
|
+
* if (member.tier === 'free' && employees >= 20) throw new Error('Upgrade to Plus for more employees');
|
|
50
|
+
* if (!member.canChange()) throw new Error('HR is read-only: buy it again on erxes.io');
|
|
51
|
+
* // server-side jobs: await core.forOrg(orgId).saas.pluginPlan() → { tier, access }
|
|
52
|
+
*
|
|
53
|
+
* The client secret is only ever sent to `POST /plugins/token`; API calls use
|
|
54
|
+
* 15-minute tokens, fetched and renewed here. Plugins on core's database can
|
|
55
|
+
* also call `core_publish_event()`, `core_record_audit()` and
|
|
56
|
+
* `core_live_signal()` inside their own transactions.
|
|
57
|
+
*/
|
|
58
|
+
import { CoreClient, CoreClientOptions, CoreTokenError, createCoreClient } from "./client.js";
|
|
59
|
+
import { CoreCall, CustomerSignIn, DeliveredEvent, ErxesSignIn, PluginMember, bearerOf, verifyCoreCall, verifyCoreEvent, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession } from "./verify.js";
|
|
60
|
+
export { CoreCall, CoreClient, CoreClientOptions, CoreTokenError, CustomerSignIn, DeliveredEvent, ErxesSignIn, PluginMember, bearerOf, createCoreClient, verifyCoreCall, verifyCoreEvent, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { CoreTokenError, createCoreClient } from "./client.js";
|
|
2
|
+
import { DeliveredEvent, bearerOf, verifyCoreCall, verifyCoreEvent, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession } from "./verify.js";
|
|
3
|
+
export { CoreTokenError, DeliveredEvent, bearerOf, createCoreClient, verifyCoreCall, verifyCoreEvent, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession };
|
package/dist/verify.d.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { PluginAccess, PluginTier } from "@erxes/core-contract";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
/** The signed-in member a plugin UI calls the plugin's API for. */
|
|
4
|
+
export interface PluginMember {
|
|
5
|
+
userId: string;
|
|
6
|
+
orgId: string;
|
|
7
|
+
/** `owner`, `admin`, `member` or a custom role key. */
|
|
8
|
+
role: string;
|
|
9
|
+
/** The member's actions in this plugin (from its manifest's `permissions`). */
|
|
10
|
+
permissions: string[];
|
|
11
|
+
/** `member.can('hr.leave.approve')` */
|
|
12
|
+
can(action: string): boolean;
|
|
13
|
+
/**
|
|
14
|
+
* The plugin's tier in this organisation on erxes.io (`free`, `plus`,
|
|
15
|
+
* `pro`): gate paid features with it. Self-hosted: `pro`.
|
|
16
|
+
*/
|
|
17
|
+
tier: PluginTier | null;
|
|
18
|
+
/**
|
|
19
|
+
* `full`, `warning` (payment retrying / ending at period end: still
|
|
20
|
+
* works), `read_only` (left the plan: let them read and export, refuse
|
|
21
|
+
* changes). Self-hosted: `full`.
|
|
22
|
+
*/
|
|
23
|
+
access: PluginAccess;
|
|
24
|
+
/** `member.canChange()`: false while read-only. */
|
|
25
|
+
canChange(): boolean;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* A member signed into a plugin's own app with "Sign in with erxes". Access
|
|
29
|
+
* tokens carry no plan, so `tier` is null and `access` is `off`: ask core
|
|
30
|
+
* (`saas.pluginPlan`) before gating on them.
|
|
31
|
+
*/
|
|
32
|
+
export interface ErxesSignIn extends PluginMember {
|
|
33
|
+
scope: string[];
|
|
34
|
+
}
|
|
35
|
+
/** Who is calling a plugin's automation action: core, for an automation's run. */
|
|
36
|
+
export interface CoreCall {
|
|
37
|
+
orgId: string;
|
|
38
|
+
/** The member the automation acts as. */
|
|
39
|
+
userId: string;
|
|
40
|
+
automationId: string;
|
|
41
|
+
runId: string;
|
|
42
|
+
stepId: string;
|
|
43
|
+
}
|
|
44
|
+
/** An event core delivered to the plugin's `<api.url>/events` (from its manifest's `subscriptions`). */
|
|
45
|
+
export declare const DeliveredEvent: z.ZodObject<{
|
|
46
|
+
id: z.ZodString;
|
|
47
|
+
type: z.ZodString;
|
|
48
|
+
organizationId: z.ZodString;
|
|
49
|
+
createdAt: z.ZodString;
|
|
50
|
+
data: z.ZodObject<{
|
|
51
|
+
id: z.ZodString;
|
|
52
|
+
source: z.ZodString;
|
|
53
|
+
type: z.ZodString;
|
|
54
|
+
version: z.ZodInt;
|
|
55
|
+
payload: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
56
|
+
summary: z.ZodNullable<z.ZodString>;
|
|
57
|
+
link: z.ZodNullable<z.ZodString>;
|
|
58
|
+
subject: z.ZodNullable<z.ZodObject<{
|
|
59
|
+
type: z.ZodEnum<{
|
|
60
|
+
company: "company";
|
|
61
|
+
customer: "customer";
|
|
62
|
+
}>;
|
|
63
|
+
id: z.ZodString;
|
|
64
|
+
}, z.core.$strip>>;
|
|
65
|
+
entity: z.ZodNullable<z.ZodObject<{
|
|
66
|
+
type: z.ZodString;
|
|
67
|
+
id: z.ZodString;
|
|
68
|
+
}, z.core.$strip>>;
|
|
69
|
+
actor: z.ZodObject<{
|
|
70
|
+
type: z.ZodEnum<{
|
|
71
|
+
customer: "customer";
|
|
72
|
+
plugin: "plugin";
|
|
73
|
+
system: "system";
|
|
74
|
+
user: "user";
|
|
75
|
+
}>;
|
|
76
|
+
id: z.ZodNullable<z.ZodString>;
|
|
77
|
+
name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
78
|
+
avatarUrl: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
79
|
+
}, z.core.$strip>;
|
|
80
|
+
occurredAt: z.ZodISODateTime;
|
|
81
|
+
createdAt: z.ZodISODateTime;
|
|
82
|
+
}, {
|
|
83
|
+
out: {};
|
|
84
|
+
in: {};
|
|
85
|
+
}>;
|
|
86
|
+
}, z.core.$strip>;
|
|
87
|
+
export type DeliveredEvent = z.infer<typeof DeliveredEvent>;
|
|
88
|
+
interface VerifyOptions {
|
|
89
|
+
coreUrl: string;
|
|
90
|
+
plugin: string;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Verifies a member's plugin session token (`Authorization: Bearer …` from
|
|
94
|
+
* erxes-ui's `pluginFetch`) with core's public keys: issued by core, for this
|
|
95
|
+
* plugin, unexpired. Throws if not.
|
|
96
|
+
*/
|
|
97
|
+
export declare const verifyPluginSession: (token: string, options: VerifyOptions) => Promise<PluginMember>;
|
|
98
|
+
/** The bearer token of a request's `Authorization` header, if any. */
|
|
99
|
+
export declare const bearerOf: (authorization: string | undefined | null) => string | null;
|
|
100
|
+
/**
|
|
101
|
+
* Verifies the token core sends with an automation action
|
|
102
|
+
* (`POST <api.url>/automations/actions/<type>`): issued by core, for this
|
|
103
|
+
* plugin, unexpired. A retried call carries the same `Idempotency-Key` header
|
|
104
|
+
* (`<run>:<step>`): record it with the action's effect so a retry does nothing twice.
|
|
105
|
+
*/
|
|
106
|
+
export declare const verifyCoreCall: (token: string, options: VerifyOptions) => Promise<CoreCall>;
|
|
107
|
+
/**
|
|
108
|
+
* Verifies an access token from "Sign in with erxes" (OAuth 2.1, PKCE) for the
|
|
109
|
+
* plugin's own app: issued by core, for this client (the plugin), unexpired.
|
|
110
|
+
* Discovery: `<coreUrl>/core/v1/.well-known/openid-configuration`.
|
|
111
|
+
*/
|
|
112
|
+
export declare const verifyErxesAccessToken: (token: string, options: VerifyOptions) => Promise<ErxesSignIn>;
|
|
113
|
+
/** A customer signed in through core (`/customer-auth`), calling a plugin's `/customer/*` routes. */
|
|
114
|
+
export interface CustomerSignIn {
|
|
115
|
+
orgId: string;
|
|
116
|
+
customerId: string;
|
|
117
|
+
/** The plugin whose app the customer signed in to (any app of the organisation may call). */
|
|
118
|
+
clientId: string;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Verifies a customer's access token from the `Authorization` header with
|
|
122
|
+
* core's public keys: issued by core for customers, unexpired. Key the
|
|
123
|
+
* customer's data by `orgId` and `customerId`. Signing out reaches plugins
|
|
124
|
+
* when the token expires (15 minutes); ask core (`GET /customer/me` with the
|
|
125
|
+
* same token) where that matters. Throws if not valid.
|
|
126
|
+
*/
|
|
127
|
+
export declare const verifyCustomerToken: (authorization: string | undefined | null, options: {
|
|
128
|
+
coreUrl: string;
|
|
129
|
+
}) => Promise<CustomerSignIn>;
|
|
130
|
+
/**
|
|
131
|
+
* Verifies an event delivery and returns the event: the `Authorization`
|
|
132
|
+
* token is core's, for this plugin, unexpired, and signs this exact body
|
|
133
|
+
* (pass the raw body text, not parsed JSON). Throws if anything is off.
|
|
134
|
+
* Deliveries can repeat and arrive out of order: handle each `event.id`
|
|
135
|
+
* once, and act on the totals in the payload, not on arrival order.
|
|
136
|
+
*/
|
|
137
|
+
export declare const verifyCoreEvent: (authorization: string | undefined | null, rawBody: string, options: VerifyOptions) => Promise<DeliveredEvent>;
|
|
138
|
+
export {};
|
package/dist/verify.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { CORE_API_PREFIX, CoreEvent, PluginAccess, PluginTier } 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.extend({
|
|
12
|
+
occurredAt: z.iso.datetime(),
|
|
13
|
+
createdAt: z.iso.datetime()
|
|
14
|
+
})
|
|
15
|
+
});
|
|
16
|
+
const jwksByCore = /* @__PURE__ */ new Map();
|
|
17
|
+
/** A token core signed (its public keys), for this plugin (or `audience`), of this kind, unexpired; its claims parsed. */
|
|
18
|
+
const verifyCoreToken = async (token, options, typ, claims, audience = options.plugin) => {
|
|
19
|
+
const base = options.coreUrl.replace(/\/+$/, "");
|
|
20
|
+
let jwks = jwksByCore.get(base);
|
|
21
|
+
if (!jwks) {
|
|
22
|
+
jwks = createRemoteJWKSet(new URL(`${base}${CORE_API_PREFIX}/.well-known/jwks.json`));
|
|
23
|
+
jwksByCore.set(base, jwks);
|
|
24
|
+
}
|
|
25
|
+
if (!audience) throw new Error("no audience to check the token for");
|
|
26
|
+
const { payload } = await jwtVerify(token, jwks, {
|
|
27
|
+
issuer: "erxes-core",
|
|
28
|
+
audience,
|
|
29
|
+
typ,
|
|
30
|
+
algorithms: ["ES256"]
|
|
31
|
+
});
|
|
32
|
+
const parsed = claims.safeParse(payload);
|
|
33
|
+
if (!parsed.success) throw new Error(`not an erxes ${typ} token`);
|
|
34
|
+
return parsed.data;
|
|
35
|
+
};
|
|
36
|
+
const Tier = PluginTier.nullable();
|
|
37
|
+
const member = (claims) => ({
|
|
38
|
+
userId: claims.sub,
|
|
39
|
+
orgId: claims.org,
|
|
40
|
+
role: claims.role,
|
|
41
|
+
permissions: claims.permissions,
|
|
42
|
+
can: (action) => claims.role === "owner" || claims.permissions.includes(action),
|
|
43
|
+
tier: claims.tier,
|
|
44
|
+
access: claims.access,
|
|
45
|
+
canChange: () => claims.access === "full" || claims.access === "warning"
|
|
46
|
+
});
|
|
47
|
+
const SessionClaims = z.object({
|
|
48
|
+
sub: z.string().min(1),
|
|
49
|
+
org: z.string(),
|
|
50
|
+
role: z.string(),
|
|
51
|
+
permissions: z.array(z.string()),
|
|
52
|
+
tier: Tier,
|
|
53
|
+
access: PluginAccess
|
|
54
|
+
});
|
|
55
|
+
/**
|
|
56
|
+
* Verifies a member's plugin session token (`Authorization: Bearer …` from
|
|
57
|
+
* erxes-ui's `pluginFetch`) with core's public keys: issued by core, for this
|
|
58
|
+
* plugin, unexpired. Throws if not.
|
|
59
|
+
*/
|
|
60
|
+
const verifyPluginSession = async (token, options) => member(await verifyCoreToken(token, options, "erxes-plugin-session+jwt", SessionClaims));
|
|
61
|
+
/** The bearer token of a request's `Authorization` header, if any. */
|
|
62
|
+
const bearerOf = (authorization) => authorization?.startsWith("Bearer ") ? authorization.slice(7).trim() || null : null;
|
|
63
|
+
const CallClaims = z.object({
|
|
64
|
+
org: z.string(),
|
|
65
|
+
user: z.string(),
|
|
66
|
+
automation: z.string(),
|
|
67
|
+
run: z.string(),
|
|
68
|
+
step: z.string()
|
|
69
|
+
}).transform((claims) => ({
|
|
70
|
+
orgId: claims.org,
|
|
71
|
+
userId: claims.user,
|
|
72
|
+
automationId: claims.automation,
|
|
73
|
+
runId: claims.run,
|
|
74
|
+
stepId: claims.step
|
|
75
|
+
}));
|
|
76
|
+
/**
|
|
77
|
+
* Verifies the token core sends with an automation action
|
|
78
|
+
* (`POST <api.url>/automations/actions/<type>`): issued by core, for this
|
|
79
|
+
* plugin, unexpired. A retried call carries the same `Idempotency-Key` header
|
|
80
|
+
* (`<run>:<step>`): record it with the action's effect so a retry does nothing twice.
|
|
81
|
+
*/
|
|
82
|
+
const verifyCoreCall = (token, options) => verifyCoreToken(token, options, "erxes-core-call+jwt", CallClaims);
|
|
83
|
+
const AccessTokenClaims = z.object({
|
|
84
|
+
sub: z.string().min(1),
|
|
85
|
+
org: z.string(),
|
|
86
|
+
role: z.string(),
|
|
87
|
+
permissions: z.array(z.string()),
|
|
88
|
+
tier: Tier.default(null),
|
|
89
|
+
access: PluginAccess.default("off"),
|
|
90
|
+
scope: z.string().transform((scope) => scope.split(" "))
|
|
91
|
+
});
|
|
92
|
+
/**
|
|
93
|
+
* Verifies an access token from "Sign in with erxes" (OAuth 2.1, PKCE) for the
|
|
94
|
+
* plugin's own app: issued by core, for this client (the plugin), unexpired.
|
|
95
|
+
* Discovery: `<coreUrl>/core/v1/.well-known/openid-configuration`.
|
|
96
|
+
*/
|
|
97
|
+
const verifyErxesAccessToken = async (token, options) => {
|
|
98
|
+
const claims = await verifyCoreToken(token, options, "at+jwt", AccessTokenClaims);
|
|
99
|
+
return {
|
|
100
|
+
...member(claims),
|
|
101
|
+
scope: claims.scope
|
|
102
|
+
};
|
|
103
|
+
};
|
|
104
|
+
const CustomerClaims = z.object({
|
|
105
|
+
sub: z.string().min(1),
|
|
106
|
+
org: z.string().min(1),
|
|
107
|
+
client_id: z.string()
|
|
108
|
+
}).transform((claims) => ({
|
|
109
|
+
orgId: claims.org,
|
|
110
|
+
customerId: claims.sub,
|
|
111
|
+
clientId: claims.client_id
|
|
112
|
+
}));
|
|
113
|
+
/**
|
|
114
|
+
* Verifies a customer's access token from the `Authorization` header with
|
|
115
|
+
* core's public keys: issued by core for customers, unexpired. Key the
|
|
116
|
+
* customer's data by `orgId` and `customerId`. Signing out reaches plugins
|
|
117
|
+
* when the token expires (15 minutes); ask core (`GET /customer/me` with the
|
|
118
|
+
* same token) where that matters. Throws if not valid.
|
|
119
|
+
*/
|
|
120
|
+
const verifyCustomerToken = async (authorization, options) => {
|
|
121
|
+
const token = bearerOf(authorization);
|
|
122
|
+
if (!token) throw new Error("no customer token");
|
|
123
|
+
return verifyCoreToken(token, options, "customer+jwt", CustomerClaims, "erxes-customer");
|
|
124
|
+
};
|
|
125
|
+
const sha256 = async (text) => {
|
|
126
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
|
|
127
|
+
return btoa(String.fromCharCode(...digest)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
128
|
+
};
|
|
129
|
+
const EventClaims = z.object({
|
|
130
|
+
sha: z.string(),
|
|
131
|
+
event: z.string(),
|
|
132
|
+
org: z.string()
|
|
133
|
+
});
|
|
134
|
+
/**
|
|
135
|
+
* Verifies an event delivery and returns the event: the `Authorization`
|
|
136
|
+
* token is core's, for this plugin, unexpired, and signs this exact body
|
|
137
|
+
* (pass the raw body text, not parsed JSON). Throws if anything is off.
|
|
138
|
+
* Deliveries can repeat and arrive out of order: handle each `event.id`
|
|
139
|
+
* once, and act on the totals in the payload, not on arrival order.
|
|
140
|
+
*/
|
|
141
|
+
const verifyCoreEvent = async (authorization, rawBody, options) => {
|
|
142
|
+
const token = bearerOf(authorization);
|
|
143
|
+
if (!token) throw new Error("no core token");
|
|
144
|
+
const claims = await verifyCoreToken(token, options, "erxes-core-event+jwt", EventClaims);
|
|
145
|
+
if (claims.sha !== await sha256(rawBody)) throw new Error("the body does not match the token");
|
|
146
|
+
const event = DeliveredEvent.parse(JSON.parse(rawBody));
|
|
147
|
+
if (event.id !== claims.event || event.organizationId !== claims.org) throw new Error("the event does not match the token");
|
|
148
|
+
return event;
|
|
149
|
+
};
|
|
150
|
+
export { DeliveredEvent, bearerOf, verifyCoreCall, verifyCoreEvent, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession };
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@erxes/plugin-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.1.0-v2.1",
|
|
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": "^6.2.17",
|
|
33
|
+
"zod": "^4.6.7",
|
|
34
|
+
"@erxes/core-contract": "0.1.0-v2.1"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "tsdown"
|
|
38
|
+
}
|
|
6
39
|
}
|
package/README.md
DELETED