@lbdudc/linea-plugin-sdk 0.0.0-stage → 1.0.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/index.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ export const HOST_API_VERSION: string;
2
+ export function verifyEventSignature(secret: string, rawBody: string | Buffer, header: string | string[] | undefined): boolean;
3
+ export function signEvent(secret: string, rawBody: string | Buffer): string;
4
+ export function serviceClient(options: { baseUrl: string; key: string; fetchFn?: typeof fetch }): {
5
+ request(path: string, options: { actAs: string; method?: string; body?: unknown; headers?: Record<string, string>; signal?: AbortSignal }): Promise<any>;
6
+ get(path: string, options: { actAs: string }): Promise<any>;
7
+ post(path: string, body: unknown, options: { actAs: string }): Promise<any>;
8
+ };
9
+ export function healthStatus(extra?: Record<string, unknown>): { status: 'ok' } & Record<string, unknown>;
10
+ export function readBody(request: import('node:http').IncomingMessage, limit?: number): Promise<Buffer>;
11
+
12
+ /** `ctx`: what the host gives `register(ctx)` of a plugin's `server` entry. */
13
+ export interface PluginContext {
14
+ id: string;
15
+ dir: string;
16
+ isEnabled(): boolean;
17
+ settings(): Record<string, any>;
18
+ onSettingsChange(fn: (fresh: Record<string, any>, previous: Record<string, any>) => void | Promise<void>): void;
19
+ router(): import('express').Router;
20
+ alias(prefix: string | RegExp, base?: string | ((match: RegExpExecArray) => string)): void;
21
+ events: { on(name: string, listener: (...args: any[]) => void): void };
22
+ services: {
23
+ requireAuth: import('express').RequestHandler; requireAdmin: import('express').RequestHandler; asyncHandler: Function;
24
+ rateLimit: Function; handleValidationErrors: import('express').RequestHandler; errors: Record<string, any>; userRepository: any;
25
+ };
26
+ }
27
+
28
+ /** `ui`: what the host gives `register(ui)` of a plugin's `client` entry. */
29
+ export interface PluginUi {
30
+ plugin: string;
31
+ router: any;
32
+ info: { id: string; version: string; web: string | null; settings: Record<string, any> };
33
+ settings: Record<string, any>;
34
+ api: import('axios').AxiosInstance;
35
+ addNav(item: { id: string; icon?: string; label: string | Record<string, string>; to?: string | object; href?: string; activeFor?: string[] }): void;
36
+ addRoute(route: { path: string; component: any; name?: string; props?: any }): void;
37
+ addPages(pages: { path: string; shell: any; children: { path: string; name?: string; component: any }[] }): void;
38
+ addSlot(name: 'line.tabs' | 'product.tabs' | 'featureModel.strip' | 'featureModel.actions' | 'featureModel.panels' | 'line.create.fields' | 'dashboard.widgets', component: any, options?: { id?: string; when?: (context: any) => boolean; order?: number }): void;
39
+ addI18n(messages: Record<string, any>, options?: { keepExisting?: boolean }): void;
40
+ }
package/index.js ADDED
@@ -0,0 +1,61 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+
3
+ /** The version of the plugin interface (`requires.hostApi`) this SDK was written for. */
4
+ export const HOST_API_VERSION = '1.0.0';
5
+
6
+ /**
7
+ * Checks the `X-Linea-Signature` header of an event LINEA sent to `remote.events`: `sha256=<hex>`, the HMAC-SHA256 of the *raw* body
8
+ * keyed by `EVENT_WEBHOOK_SECRET`. Check the bytes you received, not a re-serialised JSON.
9
+ */
10
+ export const verifyEventSignature = (secret, rawBody, header) => {
11
+ if (!secret || !header) return false;
12
+ const expected = Buffer.from(`sha256=${createHmac('sha256', secret).update(rawBody).digest('hex')}`);
13
+ const given = Buffer.from(String(header));
14
+ return expected.length === given.length && timingSafeEqual(expected, given);
15
+ };
16
+
17
+ /** Signs a body the way LINEA does (for tests of a receiver). */
18
+ export const signEvent = (secret, rawBody) => `sha256=${createHmac('sha256', secret).update(rawBody).digest('hex')}`;
19
+
20
+ /**
21
+ * A client for LINEA's API from the service of a plugin: `Authorization: Service <key>` and `X-Act-As: <username>` (the person it acts for
22
+ * must have logged in to LINEA once). `key` is the value of the plugin's `serviceKey` setting.
23
+ */
24
+ export const serviceClient = ({ baseUrl, key, fetchFn = globalThis.fetch }) => {
25
+ if (!baseUrl || !key) throw new Error('serviceClient needs baseUrl and key');
26
+ const request = async (path, { actAs, method = 'GET', body, headers = {}, signal = AbortSignal.timeout(10_000) } = {}) => {
27
+ if (!actAs) throw new Error('serviceClient: say who it acts as (actAs)');
28
+ // (a path with a leading slash replaces any path in `baseUrl`: give LINEA's address without one, or a path without it)
29
+ const response = await fetchFn(new URL(path, baseUrl), {
30
+ method,
31
+ headers: { ...headers, Authorization: `Service ${key}`, 'X-Act-As': actAs, ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
32
+ body: body === undefined ? undefined : JSON.stringify(body),
33
+ signal,
34
+ });
35
+ const text = await response.text();
36
+ let data = text;
37
+ try { data = text ? JSON.parse(text) : null; } catch { /* not JSON: keep the text */ }
38
+ if (!response.ok) throw Object.assign(new Error(`LINEA answered ${response.status} to ${method} ${path}`), { status: response.status, data });
39
+ return data;
40
+ };
41
+ return { request, get: (path, options) => request(path, options), post: (path, body, options) => request(path, { ...options, method: 'POST', body }) };
42
+ };
43
+
44
+ /**
45
+ * The answer to LINEA's health check (`remote.health`): any 2xx means up. Use it as a `node:http` handler body, or in Express:
46
+ * `app.get('/health', (req, res) => res.status(200).json(healthStatus({ version })))`.
47
+ */
48
+ export const healthStatus = (extra = {}) => ({ status: 'ok', ...extra });
49
+
50
+ /** Reads the raw body of a `node:http` request (needed to check a signature). */
51
+ export const readBody = (request, limit = 1_000_000) => new Promise((resolve, reject) => {
52
+ const chunks = [];
53
+ let size = 0;
54
+ request.on('data', (chunk) => {
55
+ size += chunk.length;
56
+ if (size > limit) { reject(Object.assign(new Error('body too large'), { status: 413 })); request.destroy(); return; }
57
+ chunks.push(chunk);
58
+ });
59
+ request.on('end', () => resolve(Buffer.concat(chunks)));
60
+ request.on('error', reject);
61
+ });
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@lbdudc/linea-plugin-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Helpers for writing LINEA plugins: the contract of the host (see docs/linea/plugins.md), with no dependencies",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "types": "index.d.ts",
8
+ "files": [
9
+ "index.js",
10
+ "index.d.ts"
11
+ ],
12
+ "engines": {
13
+ "node": ">=18"
14
+ },
15
+ "license": "Apache-2.0",
16
+ "author": "Laboratorio de Bases de Datos (LBD) - Universidade da Coruña",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/lbdudc/linea.git",
20
+ "directory": "packages/sdk"
21
+ },
22
+ "homepage": "https://github.com/lbdudc/linea/tree/main/packages/sdk",
23
+ "bugs": {
24
+ "url": "https://github.com/lbdudc/linea/issues"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public",
28
+ "provenance": true
29
+ }
30
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.