@erxes/plugin-sdk 0.1.0-v2.22 → 0.1.0-v2.25

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 CHANGED
@@ -15,8 +15,14 @@ export declare class CoreTokenError extends Error {
15
15
  constructor(status: number, code: string, message: string);
16
16
  }
17
17
  export declare const createCoreClient: (options: CoreClientOptions) => {
18
- /** The core API acting in one organisation (that installed the plugin). */
19
- forOrg(orgId: string): CoreClient;
18
+ forOrg: (orgId: string) => CoreClient;
19
+ /**
20
+ * Another plugin's API, read for an organisation: `fetchPlugin(orgId, 'sales', '/v1/deals/x')`
21
+ * requests `<sales api.url>/v1/deals/x` with a 5-minute token core issued for the reads the
22
+ * manifest's `pluginReads` asks and the owner approved, and returns the Response. Throws
23
+ * `PluginCallError` when core refuses the token (`READ_NOT_APPROVED`, `PLUGIN_NOT_INSTALLED`).
24
+ */
25
+ fetchPlugin: (orgId: string, plugin: string, path: string, init?: RequestInit) => Promise<Response>;
20
26
  /** Declares the plugin's UI, API, scopes, permissions and events. Call at startup. */
21
27
  registerManifest: (manifest: PluginManifest) => import("@orpc/client").ClientPromiseResult<{
22
28
  ok: true;
package/dist/client.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { pluginCalls } from "./pluginCalls.js";
1
2
  import { CORE_API_PREFIX } from "@erxes/core-contract";
2
3
  import { coreRoutes } from "@erxes/core-contract/routes";
3
4
  import { createORPCClient } from "@orpc/client";
@@ -100,15 +101,23 @@ const createCoreClient = (options) => {
100
101
  }
101
102
  }));
102
103
  const orgClients = /* @__PURE__ */ new Map();
104
+ /** The core API acting in one organisation (that installed the plugin). */
105
+ const forOrg = (orgId) => {
106
+ const known = orgClients.get(orgId);
107
+ if (known) return known;
108
+ const client = clientFor(orgId);
109
+ orgClients.set(orgId, client);
110
+ return client;
111
+ };
103
112
  return {
104
- /** The core API acting in one organisation (that installed the plugin). */
105
- forOrg(orgId) {
106
- const known = orgClients.get(orgId);
107
- if (known) return known;
108
- const client = clientFor(orgId);
109
- orgClients.set(orgId, client);
110
- return client;
111
- },
113
+ forOrg,
114
+ /**
115
+ * Another plugin's API, read for an organisation: `fetchPlugin(orgId, 'sales', '/v1/deals/x')`
116
+ * requests `<sales api.url>/v1/deals/x` with a 5-minute token core issued for the reads the
117
+ * manifest's `pluginReads` asks and the owner approved, and returns the Response. Throws
118
+ * `PluginCallError` when core refuses the token (`READ_NOT_APPROVED`, `PLUGIN_NOT_INSTALLED`).
119
+ */
120
+ fetchPlugin: pluginCalls(forOrg, fetcher),
112
121
  /** Declares the plugin's UI, API, scopes, permissions and events. Call at startup. */
113
122
  registerManifest: (manifest) => clientFor().plugins.registerManifest(manifest),
114
123
  /** Tells the plugin's open UIs that topics changed (needs `live:write`). */
package/dist/filter.d.ts CHANGED
@@ -22,7 +22,7 @@ import { Column, SQL } from "drizzle-orm";
22
22
  export declare const invalidFilter: (message: string) => ORPCError<"INVALID_FILTER", unknown>;
23
23
  /** One field a list can be filtered by, as `ListFilter`'s field `type` says it compares. */
24
24
  export interface FilterColumn {
25
- /** `member`, `customer` and `company` hold ids of those records; "me" is a member. */
25
+ /** `member`, `customer`, `company` and `product` hold ids of those records; "me" is a member. */
26
26
  type: FilterField['type'];
27
27
  /** The value as SQL: a column, or an expression over the list's table. */
28
28
  expr: Column | SQL;
package/dist/filter.js CHANGED
@@ -133,9 +133,10 @@ const memberId = (value, { me }) => {
133
133
  const ID_TYPES = /* @__PURE__ */ new Set([
134
134
  "member",
135
135
  "customer",
136
- "company"
136
+ "company",
137
+ "product"
137
138
  ]);
138
- /** The fields whose values are record ids: a member's, customer's or company's. */
139
+ /** The fields whose values are record ids: a member's, customer's, company's or product's. */
139
140
  const isId = (field) => ID_TYPES.has(field.type);
140
141
  /** A rule's value as an id of `field`'s records; only a member field reads "me". */
141
142
  const idOf = (field, value, context) => field.type === "member" ? memberId(value, context) : text(value);
package/dist/index.d.ts CHANGED
@@ -128,6 +128,22 @@
128
128
  * app.use('/api/v1', member check, (req, res, next) => rest.handle(req, res, { prefix: '/api/v1', context }));
129
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
130
  *
131
+ * Another plugin's API (accounting reading sales' deals when sales' events arrive, which carry
132
+ * only ids and totals): name it in the manifest's `pluginReads`. Each organisation's owner
133
+ * approves it like a new scope, and it works where both plugins are installed. Core issues a
134
+ * 5-minute token for that plugin's API with the approved permissions its manifest declares:
135
+ *
136
+ * pluginReads: [{ plugin: 'sales', permissions: ['sales.deal.view'], reason: 'Post deals to the ledger' }],
137
+ * const response = await core.fetchPlugin(orgId, 'sales', `/v1/deals/${dealId}`); // <sales api.url>/v1/deals/…
138
+ * // a refused token throws PluginCallError: code READ_NOT_APPROVED, PLUGIN_NOT_INSTALLED, PLUGIN_UNREACHABLE, NOT_IN_PLAN
139
+ *
140
+ * The plugin being read accepts the token beside members' sessions on `/api/rpc/*` and
141
+ * `/api/v1/*`, so its `reads(...)` procedures serve it as they are:
142
+ *
143
+ * const options = { coreUrl, plugin: 'sales' };
144
+ * const member = await verifyPluginSession(token, options).catch(() => verifyPluginCall(token, options));
145
+ * // a call: userId 'plugin:accounting', plugin 'accounting', role 'plugin', can() only the approved permissions
146
+ *
131
147
  * The client secret is only ever sent to `POST /plugins/token`; API calls use
132
148
  * 15-minute tokens, fetched and renewed here. Plugins on core's database can
133
149
  * also call `core_publish_event()`, `core_record_audit()` and
@@ -135,5 +151,6 @@
135
151
  */
136
152
  import { CoreClient, CoreClientOptions, CoreTokenError, createCoreClient } from "./client.js";
137
153
  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 };
154
+ import { PluginCallError } from "./pluginCalls.js";
155
+ import { CoreCall, CustomerSignIn, DeliveredEvent, ErxesSignIn, PluginCall, PluginMember, PublicCall, bearerOf, verifyCoreAccessCheck, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginCall, verifyPluginSession, verifyPublicCall } from "./verify.js";
156
+ export { CoreCall, CoreClient, CoreClientOptions, CoreTokenError, CustomerSignIn, DeliveredEvent, ErxesSignIn, JobInput, PluginCall, PluginCallError, PluginMember, PublicCall, bearerOf, createCoreClient, enqueueJob, verifyCoreAccessCheck, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginCall, verifyPluginSession, verifyPublicCall };
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { CoreTokenError, createCoreClient } from "./client.js";
2
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 };
3
+ import { PluginCallError } from "./pluginCalls.js";
4
+ import { DeliveredEvent, bearerOf, verifyCoreAccessCheck, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginCall, verifyPluginSession, verifyPublicCall } from "./verify.js";
5
+ export { CoreTokenError, DeliveredEvent, PluginCallError, bearerOf, createCoreClient, enqueueJob, verifyCoreAccessCheck, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginCall, verifyPluginSession, verifyPublicCall };
@@ -0,0 +1,21 @@
1
+ import { coreContract } from "@erxes/core-contract";
2
+ import { ContractRouterClient } from "@orpc/contract";
3
+ type CoreClient = ContractRouterClient<typeof coreContract>;
4
+ /**
5
+ * Core refused a token to read another plugin's API. `code`: `READ_NOT_APPROVED` (the manifest's
6
+ * `pluginReads` doesn't name it, or the owner hasn't approved it), `PLUGIN_NOT_INSTALLED` (not in
7
+ * this organisation), `PLUGIN_UNREACHABLE` (it has no API address), `NOT_IN_PLAN`, or another of
8
+ * core's codes.
9
+ */
10
+ export declare class PluginCallError extends Error {
11
+ readonly status: number;
12
+ readonly code: string;
13
+ constructor(status: number, code: string, message: string);
14
+ }
15
+ /**
16
+ * `fetchPlugin(orgId, plugin, path, init)`: the other plugin's API at `<its api.url><path>` with
17
+ * a call token from core, cached per organisation and plugin. A 401 gets one more try with a new
18
+ * token, so send a body that can go twice (text or bytes, not a stream).
19
+ */
20
+ export declare const pluginCalls: (clientFor: (orgId: string) => CoreClient, fetcher: typeof globalThis.fetch) => (orgId: string, plugin: string, path: string, init?: RequestInit) => Promise<Response>;
21
+ export {};
@@ -0,0 +1,71 @@
1
+ import { z } from "zod";
2
+ // src/pluginCalls.ts
3
+ /**
4
+ * Core refused a token to read another plugin's API. `code`: `READ_NOT_APPROVED` (the manifest's
5
+ * `pluginReads` doesn't name it, or the owner hasn't approved it), `PLUGIN_NOT_INSTALLED` (not in
6
+ * this organisation), `PLUGIN_UNREACHABLE` (it has no API address), `NOT_IN_PLAN`, or another of
7
+ * core's codes.
8
+ */
9
+ var PluginCallError = class extends Error {
10
+ status;
11
+ code;
12
+ constructor(status, code, message) {
13
+ super(message);
14
+ this.status = status;
15
+ this.code = code;
16
+ }
17
+ };
18
+ /** A cached call token is replaced this long before it ends (they last 5 minutes). */
19
+ const RENEW_BEFORE_MS = 3e4;
20
+ /** Core's answer to a refused token request, as the oRPC client throws it. */
21
+ const Refusal = z.object({
22
+ status: z.number(),
23
+ code: z.string(),
24
+ message: z.string()
25
+ });
26
+ const asCallError = (error) => {
27
+ const refusal = Refusal.safeParse(error);
28
+ return refusal.success ? new PluginCallError(refusal.data.status, refusal.data.code, refusal.data.message) : error;
29
+ };
30
+ /**
31
+ * `fetchPlugin(orgId, plugin, path, init)`: the other plugin's API at `<its api.url><path>` with
32
+ * a call token from core, cached per organisation and plugin. A 401 gets one more try with a new
33
+ * token, so send a body that can go twice (text or bytes, not a stream).
34
+ */
35
+ const pluginCalls = (clientFor, fetcher) => {
36
+ const tokens = /* @__PURE__ */ new Map();
37
+ const tokenFor = async (orgId, plugin, refused) => {
38
+ const key = `${orgId}/${plugin}`;
39
+ const cached = tokens.get(key);
40
+ if (cached) {
41
+ const value = await cached.catch(() => null);
42
+ if (value && value.token !== refused && Date.parse(value.expiresAt) - Date.now() > RENEW_BEFORE_MS) return value;
43
+ const renewing = tokens.get(key);
44
+ if (renewing && renewing !== cached) return renewing;
45
+ }
46
+ const request = clientFor(orgId).plugins.callToken({ name: plugin }).catch((error) => {
47
+ throw asCallError(error);
48
+ });
49
+ tokens.set(key, request);
50
+ request.catch(() => {
51
+ if (tokens.get(key) === request) tokens.delete(key);
52
+ });
53
+ return request;
54
+ };
55
+ return async (orgId, plugin, path, init = {}) => {
56
+ const send = (call) => {
57
+ const headers = new Headers(init.headers);
58
+ headers.set("authorization", `Bearer ${call.token}`);
59
+ return fetcher(`${call.apiUrl.replace(/\/+$/, "")}${path}`, {
60
+ ...init,
61
+ headers
62
+ });
63
+ };
64
+ const call = await tokenFor(orgId, plugin);
65
+ const response = await send(call);
66
+ if (response.status !== 401) return response;
67
+ await response.body?.cancel();
68
+ return send(await tokenFor(orgId, plugin, call.token));
69
+ };
70
+ };
71
+ export { PluginCallError, pluginCalls };
package/dist/verify.d.ts CHANGED
@@ -87,6 +87,22 @@ interface VerifyOptions {
87
87
  * plugin, unexpired. Throws if not.
88
88
  */
89
89
  export declare const verifyPluginSession: (token: string, options: VerifyOptions) => Promise<PluginMember>;
90
+ /**
91
+ * Another plugin reading this plugin's API for an organisation (its manifest's `pluginReads`,
92
+ * approved by the owner). It passes for a member: `userId` is `plugin:<name>`, `role` `plugin`,
93
+ * and `can()` holds only for the approved permissions, so `reads(...)` procedures serve it as they
94
+ * are.
95
+ */
96
+ export interface PluginCall extends PluginMember {
97
+ /** The calling plugin (`accounting`). */
98
+ plugin: string;
99
+ }
100
+ /**
101
+ * Verifies a token core issued for another plugin to call this plugin's API (`Authorization:
102
+ * Bearer …` from `core.fetchPlugin`): issued by core, for this plugin, unexpired (5 minutes).
103
+ * Throws if not.
104
+ */
105
+ export declare const verifyPluginCall: (token: string, options: VerifyOptions) => Promise<PluginCall>;
90
106
  /** The bearer token of a request's `Authorization` header, if any. */
91
107
  export declare const bearerOf: (authorization: string | undefined | null) => string | null;
92
108
  /**
package/dist/verify.js CHANGED
@@ -64,6 +64,30 @@ const SessionClaims = z.object({
64
64
  * plugin, unexpired. Throws if not.
65
65
  */
66
66
  const verifyPluginSession = async (token, options) => member(await verifyCoreToken(token, options, "erxes-plugin-session+jwt", SessionClaims));
67
+ const PluginCallClaims = z.object({
68
+ sub: z.string().startsWith("plugin:"),
69
+ org: z.string().min(1),
70
+ plugin: z.string().min(1),
71
+ permissions: z.array(z.string()),
72
+ tier: Tier,
73
+ access: PluginAccess
74
+ });
75
+ /**
76
+ * Verifies a token core issued for another plugin to call this plugin's API (`Authorization:
77
+ * Bearer …` from `core.fetchPlugin`): issued by core, for this plugin, unexpired (5 minutes).
78
+ * Throws if not.
79
+ */
80
+ const verifyPluginCall = async (token, options) => {
81
+ const claims = await verifyCoreToken(token, options, "erxes-plugin-call+jwt", PluginCallClaims);
82
+ if (claims.sub !== `plugin:${claims.plugin}`) throw new Error("not an erxes plugin call token");
83
+ return {
84
+ ...member({
85
+ ...claims,
86
+ role: "plugin"
87
+ }),
88
+ plugin: claims.plugin
89
+ };
90
+ };
67
91
  /** The bearer token of a request's `Authorization` header, if any. */
68
92
  const bearerOf = (authorization) => authorization?.startsWith("Bearer ") ? authorization.slice(7).trim() || null : null;
69
93
  const CallClaims = z.object({
@@ -217,4 +241,4 @@ const verifyCoreAccessCheck = async (authorization, rawBody, options) => {
217
241
  if (check.orgId !== claims.org) throw new Error("the check does not match the token");
218
242
  return check;
219
243
  };
220
- export { DeliveredEvent, bearerOf, verifyCoreAccessCheck, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession, verifyPublicCall };
244
+ export { DeliveredEvent, bearerOf, verifyCoreAccessCheck, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginCall, verifyPluginSession, verifyPublicCall };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@erxes/plugin-sdk",
3
- "version": "0.1.0-v2.22",
3
+ "version": "0.1.0-v2.25",
4
4
  "private": false,
5
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",
@@ -20,6 +20,7 @@
20
20
  "./filter": "./dist/filter.js",
21
21
  "./jobs": "./dist/jobs.js",
22
22
  "./openapi": "./dist/openapi.js",
23
+ "./pluginCalls": "./dist/pluginCalls.js",
23
24
  "./verify": "./dist/verify.js",
24
25
  "./package.json": "./package.json"
25
26
  },
@@ -36,7 +37,7 @@
36
37
  "@orpc/zod": "1.16.2",
37
38
  "jose": "^6.2.17",
38
39
  "zod": "^4.6.7",
39
- "@erxes/core-contract": "0.1.0-v2.23"
40
+ "@erxes/core-contract": "0.1.0-v2.26"
40
41
  },
41
42
  "devDependencies": {
42
43
  "drizzle-orm": "0.45.4"