@nullplatform/ui-plugin-sdk 0.2.0 → 0.5.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.
@@ -3,11 +3,11 @@ import "./polyfill.js";
3
3
  * React components a plugin renders with. Each one maps to a catalog element;
4
4
  * the host decides how it looks.
5
5
  */
6
- import '@remote-dom/react/polyfill';
7
- import { createRemoteComponent } from '@remote-dom/react';
8
- import { createElement } from 'react';
9
- import { CATALOG_BY_TAG } from './catalog.js';
10
- import { defineCatalogElements } from './elements.js';
6
+ import "@remote-dom/react/polyfill";
7
+ import { createRemoteComponent } from "@remote-dom/react";
8
+ import { createElement } from "react";
9
+ import { CATALOG_BY_TAG, } from "./catalog.js";
10
+ import { defineCatalogElements } from "./elements.js";
11
11
  const elements = defineCatalogElements();
12
12
  function component(tag) {
13
13
  const spec = CATALOG_BY_TAG.get(tag);
@@ -16,7 +16,9 @@ function component(tag) {
16
16
  const eventProps = {};
17
17
  for (const [event, prop] of Object.entries(spec.events))
18
18
  eventProps[prop] = { event };
19
- const Remote = createRemoteComponent(tag, elements.get(tag), { eventProps: eventProps });
19
+ const Remote = createRemoteComponent(tag, elements.get(tag), {
20
+ eventProps: eventProps,
21
+ });
20
22
  const handlerProps = Object.values(spec.events);
21
23
  if (handlerProps.length === 0)
22
24
  return Remote;
@@ -25,9 +27,11 @@ function component(tag) {
25
27
  const mapped = { ...props };
26
28
  for (const prop of handlerProps) {
27
29
  const handler = props[prop];
28
- if (typeof handler === 'function') {
30
+ if (typeof handler === "function") {
29
31
  mapped[prop] = (event) => {
30
- const detail = event && typeof event === 'object' && 'detail' in event ? event.detail : event;
32
+ const detail = event && typeof event === "object" && "detail" in event
33
+ ? event.detail
34
+ : event;
31
35
  return handler(detail);
32
36
  };
33
37
  }
@@ -37,21 +41,38 @@ function component(tag) {
37
41
  Wrapped.displayName = spec.component;
38
42
  return Wrapped;
39
43
  }
40
- export const Image = component('np-image');
41
- export const Card = component('np-card');
42
- export const Stack = component('np-stack');
43
- export const Text = component('np-text');
44
- export const Button = component('np-button');
45
- export const Chip = component('np-chip');
46
- export const Link = component('np-link');
47
- export const Table = component('np-table');
48
- export const Skeleton = component('np-skeleton');
49
- export const Empty = component('np-empty');
50
- export const Alert = component('np-alert');
51
- export const Icon = component('np-icon');
52
- export const Divider = component('np-divider');
53
- export const Markdown = component('np-markdown');
54
- export const Code = component('np-code');
44
+ export const TextField = component("np-text-field");
45
+ export const Select = component("np-select");
46
+ export const Switch = component("np-switch");
47
+ export const NetworkGraph = component("np-network-graph");
48
+ export const Image = component("np-image");
49
+ export const Card = component("np-card");
50
+ export const Stack = component("np-stack");
51
+ export const Text = component("np-text");
52
+ export const Button = component("np-button");
53
+ export const Chip = component("np-chip");
54
+ export const Link = component("np-link");
55
+ export const Table = component("np-table");
56
+ export const Skeleton = component("np-skeleton");
57
+ export const Empty = component("np-empty");
58
+ export const Alert = component("np-alert");
59
+ export const Icon = component("np-icon");
60
+ export const Divider = component("np-divider");
61
+ export const Markdown = component("np-markdown");
62
+ export const Code = component("np-code");
55
63
  /** Ego graph: the focus node in the center, what consumes it on the left, what it depends on on the right. */
56
- export const EgoGraph = component('np-ego-graph');
57
- export const Box = component('np-box');
64
+ export const EgoGraph = component("np-ego-graph");
65
+ export const Box = component("np-box");
66
+ /** Responsive grid: as many columns as fit `min` px, up to `columns`. */
67
+ export const Grid = component("np-grid");
68
+ /** Big number tile. `trend` draws the arrow; `tone` colors the delta (`positive` = good, whatever the direction). */
69
+ export const Metric = component("np-metric");
70
+ /** `area` fills under the line; off by default. */
71
+ export const Sparkline = component("np-sparkline");
72
+ /** Time series; `categories` are the x labels, one per value. */
73
+ export const LineChart = component("np-line-chart");
74
+ export const BarChart = component("np-bar-chart");
75
+ /** Part-to-whole ring; the center shows `total` or the formatted sum. */
76
+ export const Donut = component("np-donut");
77
+ /** Horizontal share bar, `value` in 0..1. */
78
+ export const ProgressBar = component("np-progress-bar");
@@ -1,6 +1,12 @@
1
1
  import type { ApiPermission, HttpPermission } from './manifest.js';
2
2
  /** Splits a path into segments; rejects traversal, empty segments and query/hash fragments. */
3
3
  export declare function normalizePath(path: string): string[] | null;
4
+ /**
5
+ * The one canonical spelling of a plugin path: decoded once, validated, re-encoded per segment.
6
+ * The allowlist decision and the request the host actually sends must both use this string, so
7
+ * that nothing downstream can resolve a path other than the authorized one.
8
+ */
9
+ export declare function canonicalizePath(path: string): string | null;
4
10
  /**
5
11
  * Decides whether a plugin API request (a nullplatform public API path) is covered
6
12
  * by its declared `permissions.api`. Query strings are never part of the decision.
@@ -14,8 +14,22 @@ export function normalizePath(path) {
14
14
  const segments = decoded.split('/').slice(1);
15
15
  if (segments.some((segment) => segment === '' || segment === '.' || segment === '..'))
16
16
  return null;
17
+ // A legitimately encoded path has no `%` left after one decode. One that still does is
18
+ // double-encoded, and would resolve to a different path in any component that decodes again
19
+ // than the one this allowlist just authorized.
20
+ if (segments.some((segment) => segment.includes('%')))
21
+ return null;
17
22
  return segments;
18
23
  }
24
+ /**
25
+ * The one canonical spelling of a plugin path: decoded once, validated, re-encoded per segment.
26
+ * The allowlist decision and the request the host actually sends must both use this string, so
27
+ * that nothing downstream can resolve a path other than the authorized one.
28
+ */
29
+ export function canonicalizePath(path) {
30
+ const segments = normalizePath(path);
31
+ return segments ? '/' + segments.map(encodeURIComponent).join('/') : null;
32
+ }
19
33
  /** `{param}` placeholders match exactly one non-empty segment. */
20
34
  function pathMatches(pattern, requestSegments) {
21
35
  const patternSegments = normalizePath(pattern);
@@ -1,4 +1,4 @@
1
1
  export { PROTOCOL_VERSION, validateManifest, isSectionSlot, ManifestError, type PluginManifest, type Contribution, type ApiPermission, type HttpPermission, type HttpMethod, } from './manifest.js';
2
- export { isApiRequestAllowed, isHttpRequestAllowed, isRequestAllowed, normalizePath } from './allowlist.js';
2
+ export { isApiRequestAllowed, isHttpRequestAllowed, isRequestAllowed, normalizePath, canonicalizePath } from './allowlist.js';
3
3
  export { CONTEXT_ROOTS, extractRoots, validateWhen, evaluateWhen, rolloutIncludes, WhenError, type WhenQuery, type ContextRoot, type Rollout, } from './when.js';
4
4
  export { PLUGIN_STORAGE_ORIGIN, validateStorageUrl, resolveAssetUrl } from './storage.js';
@@ -1,4 +1,4 @@
1
1
  export { PROTOCOL_VERSION, validateManifest, isSectionSlot, ManifestError, } from './manifest.js';
2
- export { isApiRequestAllowed, isHttpRequestAllowed, isRequestAllowed, normalizePath } from './allowlist.js';
2
+ export { isApiRequestAllowed, isHttpRequestAllowed, isRequestAllowed, normalizePath, canonicalizePath } from './allowlist.js';
3
3
  export { CONTEXT_ROOTS, extractRoots, validateWhen, evaluateWhen, rolloutIncludes, WhenError, } from './when.js';
4
4
  export { PLUGIN_STORAGE_ORIGIN, validateStorageUrl, resolveAssetUrl } from './storage.js';
@@ -1,7 +1,17 @@
1
1
  export type WhenQuery = Record<string, unknown>;
2
- /** Roots a condition may reference. The API knows how to load each one; anything else is rejected at write time. */
3
- export declare const CONTEXT_ROOTS: readonly ["nrn", "organization", "account", "namespace", "application", "scope", "deployment", "user"];
2
+ /**
3
+ * Roots a condition may reference. The API knows how to load each one; anything else is rejected at write time.
4
+ * `locale` and `route` are in the plugin context but are not roots: the platform resolves installations without
5
+ * knowing either, so a condition on them could only ever hold in developer mode.
6
+ */
7
+ export declare const CONTEXT_ROOTS: readonly ["nrn", "organization", "account", "namespace", "application", "user"];
4
8
  export type ContextRoot = (typeof CONTEXT_ROOTS)[number];
9
+ export declare const WHEN_LIMITS: {
10
+ readonly depth: 16;
11
+ readonly nodes: 512;
12
+ readonly array: 100;
13
+ readonly string: 1024;
14
+ };
5
15
  export declare class WhenError extends Error {
6
16
  constructor(message: string);
7
17
  }
@@ -4,10 +4,20 @@
4
4
  * the API (installations and manifests) and in the host (developer mode).
5
5
  */
6
6
  import sift from 'sift';
7
- /** Roots a condition may reference. The API knows how to load each one; anything else is rejected at write time. */
8
- export const CONTEXT_ROOTS = ['nrn', 'organization', 'account', 'namespace', 'application', 'scope', 'deployment', 'user'];
7
+ /**
8
+ * Roots a condition may reference. The API knows how to load each one; anything else is rejected at write time.
9
+ * `locale` and `route` are in the plugin context but are not roots: the platform resolves installations without
10
+ * knowing either, so a condition on them could only ever hold in developer mode.
11
+ */
12
+ export const CONTEXT_ROOTS = ['nrn', 'organization', 'account', 'namespace', 'application', 'user'];
13
+ /**
14
+ * In the plugin context, but not usable in a condition yet. Installations resolve for the application's NRN, so the
15
+ * platform never loads a scope or a deployment and a condition on either would silently never match.
16
+ */
17
+ const UNSUPPORTED_ROOTS = new Set(['scope', 'deployment']);
9
18
  /** Operators that would execute code or are meaningless outside MongoDB. */
10
- const FORBIDDEN_OPERATORS = new Set(['$where', '$function', '$expr', '$jsonSchema', '$text', '$accumulator']);
19
+ const ALLOWED_OPERATORS = new Set(['$eq', '$ne', '$gt', '$gte', '$lt', '$lte', '$in', '$nin', '$exists', '$size', '$all', '$elemMatch', '$not', '$and', '$or', '$nor', '$mod']);
20
+ export const WHEN_LIMITS = { depth: 16, nodes: 512, array: 100, string: 1024 };
11
21
  /** Logical operators whose operands are themselves queries against the same document. */
12
22
  const LOGICAL_LIST_OPERATORS = new Set(['$and', '$or', '$nor']);
13
23
  export class WhenError extends Error {
@@ -21,45 +31,71 @@ const rootOf = (field) => field.split('.')[0];
21
31
  /** Top-level roots referenced by a query (walks `$and` / `$or` / `$nor`; field operands are never roots). */
22
32
  export function extractRoots(when) {
23
33
  const roots = new Set();
24
- const walk = (query) => {
34
+ const pending = [when];
35
+ let visited = 0;
36
+ while (pending.length && visited++ < WHEN_LIMITS.nodes) {
37
+ const query = pending.pop();
25
38
  if (!isPlainObject(query))
26
- return;
39
+ continue;
27
40
  for (const [key, value] of Object.entries(query)) {
28
41
  if (key.startsWith('$')) {
29
42
  if (LOGICAL_LIST_OPERATORS.has(key) && Array.isArray(value))
30
- value.forEach(walk);
43
+ pending.push(...value.slice(0, WHEN_LIMITS.array));
31
44
  else if (key === '$not')
32
- walk(value);
33
- continue;
45
+ pending.push(value);
34
46
  }
35
- roots.add(rootOf(key));
47
+ else
48
+ roots.add(rootOf(key));
36
49
  }
37
- };
38
- walk(when);
50
+ }
39
51
  return [...roots];
40
52
  }
41
53
  /** Deep check for forbidden operators and non-JSON values (functions, symbols). */
42
- function assertSafe(value, path) {
43
- if (typeof value === 'function' || typeof value === 'symbol')
44
- throw new WhenError(`${path || 'when'} must be plain JSON`);
45
- if (Array.isArray(value)) {
46
- value.forEach((item, index) => assertSafe(item, `${path}[${index}]`));
47
- return;
48
- }
49
- if (!isPlainObject(value))
50
- return;
51
- for (const [key, item] of Object.entries(value)) {
52
- if (FORBIDDEN_OPERATORS.has(key))
53
- throw new WhenError(`Operator ${key} is not allowed`);
54
- assertSafe(item, path ? `${path}.${key}` : key);
55
- }
54
+ function assertSafe(input) {
55
+ let nodes = 0;
56
+ const seen = new WeakSet();
57
+ const walk = (value, depth) => {
58
+ if (++nodes > WHEN_LIMITS.nodes || depth > WHEN_LIMITS.depth)
59
+ throw new WhenError('when exceeds complexity limits');
60
+ if (typeof value === 'string') {
61
+ if (value.length > WHEN_LIMITS.string)
62
+ throw new WhenError('when string exceeds limit');
63
+ return;
64
+ }
65
+ if (value === null || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value)))
66
+ return;
67
+ if (typeof value !== 'object' || (!Array.isArray(value) && !isPlainObject(value)))
68
+ throw new WhenError('when must be plain JSON');
69
+ if (seen.has(value))
70
+ throw new WhenError('when must not contain cycles');
71
+ seen.add(value);
72
+ if (Array.isArray(value)) {
73
+ if (value.length > WHEN_LIMITS.array)
74
+ throw new WhenError('when array exceeds limit');
75
+ value.forEach(item => walk(item, depth + 1));
76
+ }
77
+ else {
78
+ for (const [key, item] of Object.entries(value)) {
79
+ if (key.length > WHEN_LIMITS.string || key.split('.').some(part => ['__proto__', 'prototype', 'constructor'].includes(part)))
80
+ throw new WhenError('Invalid when field');
81
+ if (key.startsWith('$') && !ALLOWED_OPERATORS.has(key))
82
+ throw new WhenError(`Operator ${key} is not allowed`);
83
+ walk(item, depth + 1);
84
+ }
85
+ }
86
+ seen.delete(value);
87
+ };
88
+ walk(input, 0);
56
89
  }
57
90
  /** Validates an untrusted condition: plain object, JSON only, no code operators, known roots. Returns it unchanged. */
58
91
  export function validateWhen(input) {
59
92
  if (!isPlainObject(input))
60
93
  throw new WhenError('when must be an object');
61
- assertSafe(input, '');
94
+ assertSafe(input);
62
95
  for (const root of extractRoots(input)) {
96
+ if (UNSUPPORTED_ROOTS.has(root)) {
97
+ throw new WhenError(`Context root "${root}" is not supported yet: plugins resolve for the application, so it would never match`);
98
+ }
63
99
  if (!CONTEXT_ROOTS.includes(root)) {
64
100
  throw new WhenError(`Unknown context root "${root}" (allowed: ${CONTEXT_ROOTS.join(', ')})`);
65
101
  }
@@ -71,7 +107,7 @@ export function evaluateWhen(when, context) {
71
107
  if (!when || Object.keys(when).length === 0)
72
108
  return true;
73
109
  try {
74
- return sift(when)(context ?? {});
110
+ return sift(validateWhen(when))(context ?? {});
75
111
  }
76
112
  catch {
77
113
  return false;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.isRequestAllowed = void 0;
4
4
  exports.normalizePath = normalizePath;
5
+ exports.canonicalizePath = canonicalizePath;
5
6
  exports.isApiRequestAllowed = isApiRequestAllowed;
6
7
  exports.isHttpRequestAllowed = isHttpRequestAllowed;
7
8
  /** Splits a path into segments; rejects traversal, empty segments and query/hash fragments. */
@@ -20,8 +21,22 @@ function normalizePath(path) {
20
21
  const segments = decoded.split('/').slice(1);
21
22
  if (segments.some((segment) => segment === '' || segment === '.' || segment === '..'))
22
23
  return null;
24
+ // A legitimately encoded path has no `%` left after one decode. One that still does is
25
+ // double-encoded, and would resolve to a different path in any component that decodes again
26
+ // than the one this allowlist just authorized.
27
+ if (segments.some((segment) => segment.includes('%')))
28
+ return null;
23
29
  return segments;
24
30
  }
31
+ /**
32
+ * The one canonical spelling of a plugin path: decoded once, validated, re-encoded per segment.
33
+ * The allowlist decision and the request the host actually sends must both use this string, so
34
+ * that nothing downstream can resolve a path other than the authorized one.
35
+ */
36
+ function canonicalizePath(path) {
37
+ const segments = normalizePath(path);
38
+ return segments ? '/' + segments.map(encodeURIComponent).join('/') : null;
39
+ }
25
40
  /** `{param}` placeholders match exactly one non-empty segment. */
26
41
  function pathMatches(pattern, requestSegments) {
27
42
  const patternSegments = normalizePath(pattern);
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resolveAssetUrl = exports.validateStorageUrl = exports.PLUGIN_STORAGE_ORIGIN = exports.WhenError = exports.rolloutIncludes = exports.evaluateWhen = exports.validateWhen = exports.extractRoots = exports.CONTEXT_ROOTS = exports.normalizePath = exports.isRequestAllowed = exports.isHttpRequestAllowed = exports.isApiRequestAllowed = exports.ManifestError = exports.isSectionSlot = exports.validateManifest = exports.PROTOCOL_VERSION = void 0;
3
+ exports.resolveAssetUrl = exports.validateStorageUrl = exports.PLUGIN_STORAGE_ORIGIN = exports.WhenError = exports.rolloutIncludes = exports.evaluateWhen = exports.validateWhen = exports.extractRoots = exports.CONTEXT_ROOTS = exports.canonicalizePath = exports.normalizePath = exports.isRequestAllowed = exports.isHttpRequestAllowed = exports.isApiRequestAllowed = exports.ManifestError = exports.isSectionSlot = exports.validateManifest = exports.PROTOCOL_VERSION = void 0;
4
4
  var manifest_1 = require("./manifest");
5
5
  Object.defineProperty(exports, "PROTOCOL_VERSION", { enumerable: true, get: function () { return manifest_1.PROTOCOL_VERSION; } });
6
6
  Object.defineProperty(exports, "validateManifest", { enumerable: true, get: function () { return manifest_1.validateManifest; } });
@@ -11,6 +11,7 @@ Object.defineProperty(exports, "isApiRequestAllowed", { enumerable: true, get: f
11
11
  Object.defineProperty(exports, "isHttpRequestAllowed", { enumerable: true, get: function () { return allowlist_1.isHttpRequestAllowed; } });
12
12
  Object.defineProperty(exports, "isRequestAllowed", { enumerable: true, get: function () { return allowlist_1.isRequestAllowed; } });
13
13
  Object.defineProperty(exports, "normalizePath", { enumerable: true, get: function () { return allowlist_1.normalizePath; } });
14
+ Object.defineProperty(exports, "canonicalizePath", { enumerable: true, get: function () { return allowlist_1.canonicalizePath; } });
14
15
  var when_1 = require("./when");
15
16
  Object.defineProperty(exports, "CONTEXT_ROOTS", { enumerable: true, get: function () { return when_1.CONTEXT_ROOTS; } });
16
17
  Object.defineProperty(exports, "extractRoots", { enumerable: true, get: function () { return when_1.extractRoots; } });
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.WhenError = exports.CONTEXT_ROOTS = void 0;
6
+ exports.WhenError = exports.WHEN_LIMITS = exports.CONTEXT_ROOTS = void 0;
7
7
  exports.extractRoots = extractRoots;
8
8
  exports.validateWhen = validateWhen;
9
9
  exports.evaluateWhen = evaluateWhen;
@@ -14,10 +14,20 @@ exports.rolloutIncludes = rolloutIncludes;
14
14
  * the API (installations and manifests) and in the host (developer mode).
15
15
  */
16
16
  const sift_1 = __importDefault(require("sift"));
17
- /** Roots a condition may reference. The API knows how to load each one; anything else is rejected at write time. */
18
- exports.CONTEXT_ROOTS = ['nrn', 'organization', 'account', 'namespace', 'application', 'scope', 'deployment', 'user'];
17
+ /**
18
+ * Roots a condition may reference. The API knows how to load each one; anything else is rejected at write time.
19
+ * `locale` and `route` are in the plugin context but are not roots: the platform resolves installations without
20
+ * knowing either, so a condition on them could only ever hold in developer mode.
21
+ */
22
+ exports.CONTEXT_ROOTS = ['nrn', 'organization', 'account', 'namespace', 'application', 'user'];
23
+ /**
24
+ * In the plugin context, but not usable in a condition yet. Installations resolve for the application's NRN, so the
25
+ * platform never loads a scope or a deployment and a condition on either would silently never match.
26
+ */
27
+ const UNSUPPORTED_ROOTS = new Set(['scope', 'deployment']);
19
28
  /** Operators that would execute code or are meaningless outside MongoDB. */
20
- const FORBIDDEN_OPERATORS = new Set(['$where', '$function', '$expr', '$jsonSchema', '$text', '$accumulator']);
29
+ const ALLOWED_OPERATORS = new Set(['$eq', '$ne', '$gt', '$gte', '$lt', '$lte', '$in', '$nin', '$exists', '$size', '$all', '$elemMatch', '$not', '$and', '$or', '$nor', '$mod']);
30
+ exports.WHEN_LIMITS = { depth: 16, nodes: 512, array: 100, string: 1024 };
21
31
  /** Logical operators whose operands are themselves queries against the same document. */
22
32
  const LOGICAL_LIST_OPERATORS = new Set(['$and', '$or', '$nor']);
23
33
  class WhenError extends Error {
@@ -32,45 +42,71 @@ const rootOf = (field) => field.split('.')[0];
32
42
  /** Top-level roots referenced by a query (walks `$and` / `$or` / `$nor`; field operands are never roots). */
33
43
  function extractRoots(when) {
34
44
  const roots = new Set();
35
- const walk = (query) => {
45
+ const pending = [when];
46
+ let visited = 0;
47
+ while (pending.length && visited++ < exports.WHEN_LIMITS.nodes) {
48
+ const query = pending.pop();
36
49
  if (!isPlainObject(query))
37
- return;
50
+ continue;
38
51
  for (const [key, value] of Object.entries(query)) {
39
52
  if (key.startsWith('$')) {
40
53
  if (LOGICAL_LIST_OPERATORS.has(key) && Array.isArray(value))
41
- value.forEach(walk);
54
+ pending.push(...value.slice(0, exports.WHEN_LIMITS.array));
42
55
  else if (key === '$not')
43
- walk(value);
44
- continue;
56
+ pending.push(value);
45
57
  }
46
- roots.add(rootOf(key));
58
+ else
59
+ roots.add(rootOf(key));
47
60
  }
48
- };
49
- walk(when);
61
+ }
50
62
  return [...roots];
51
63
  }
52
64
  /** Deep check for forbidden operators and non-JSON values (functions, symbols). */
53
- function assertSafe(value, path) {
54
- if (typeof value === 'function' || typeof value === 'symbol')
55
- throw new WhenError(`${path || 'when'} must be plain JSON`);
56
- if (Array.isArray(value)) {
57
- value.forEach((item, index) => assertSafe(item, `${path}[${index}]`));
58
- return;
59
- }
60
- if (!isPlainObject(value))
61
- return;
62
- for (const [key, item] of Object.entries(value)) {
63
- if (FORBIDDEN_OPERATORS.has(key))
64
- throw new WhenError(`Operator ${key} is not allowed`);
65
- assertSafe(item, path ? `${path}.${key}` : key);
66
- }
65
+ function assertSafe(input) {
66
+ let nodes = 0;
67
+ const seen = new WeakSet();
68
+ const walk = (value, depth) => {
69
+ if (++nodes > exports.WHEN_LIMITS.nodes || depth > exports.WHEN_LIMITS.depth)
70
+ throw new WhenError('when exceeds complexity limits');
71
+ if (typeof value === 'string') {
72
+ if (value.length > exports.WHEN_LIMITS.string)
73
+ throw new WhenError('when string exceeds limit');
74
+ return;
75
+ }
76
+ if (value === null || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value)))
77
+ return;
78
+ if (typeof value !== 'object' || (!Array.isArray(value) && !isPlainObject(value)))
79
+ throw new WhenError('when must be plain JSON');
80
+ if (seen.has(value))
81
+ throw new WhenError('when must not contain cycles');
82
+ seen.add(value);
83
+ if (Array.isArray(value)) {
84
+ if (value.length > exports.WHEN_LIMITS.array)
85
+ throw new WhenError('when array exceeds limit');
86
+ value.forEach(item => walk(item, depth + 1));
87
+ }
88
+ else {
89
+ for (const [key, item] of Object.entries(value)) {
90
+ if (key.length > exports.WHEN_LIMITS.string || key.split('.').some(part => ['__proto__', 'prototype', 'constructor'].includes(part)))
91
+ throw new WhenError('Invalid when field');
92
+ if (key.startsWith('$') && !ALLOWED_OPERATORS.has(key))
93
+ throw new WhenError(`Operator ${key} is not allowed`);
94
+ walk(item, depth + 1);
95
+ }
96
+ }
97
+ seen.delete(value);
98
+ };
99
+ walk(input, 0);
67
100
  }
68
101
  /** Validates an untrusted condition: plain object, JSON only, no code operators, known roots. Returns it unchanged. */
69
102
  function validateWhen(input) {
70
103
  if (!isPlainObject(input))
71
104
  throw new WhenError('when must be an object');
72
- assertSafe(input, '');
105
+ assertSafe(input);
73
106
  for (const root of extractRoots(input)) {
107
+ if (UNSUPPORTED_ROOTS.has(root)) {
108
+ throw new WhenError(`Context root "${root}" is not supported yet: plugins resolve for the application, so it would never match`);
109
+ }
74
110
  if (!exports.CONTEXT_ROOTS.includes(root)) {
75
111
  throw new WhenError(`Unknown context root "${root}" (allowed: ${exports.CONTEXT_ROOTS.join(', ')})`);
76
112
  }
@@ -82,7 +118,7 @@ function evaluateWhen(when, context) {
82
118
  if (!when || Object.keys(when).length === 0)
83
119
  return true;
84
120
  try {
85
- return (0, sift_1.default)(when)(context ?? {});
121
+ return (0, sift_1.default)(validateWhen(when))(context ?? {});
86
122
  }
87
123
  catch {
88
124
  return false;
@@ -10,6 +10,10 @@ export declare const PROTOCOL_VERSION = 1;
10
10
  export type FunctionToken = {
11
11
  $fn: string;
12
12
  };
13
+ /**
14
+ * Where the plugin is rendering. Identity only (ids, slugs, names): every plugin receives it whatever its
15
+ * permissions, so anything else about an entity goes through `api` with a declared permission.
16
+ */
13
17
  export interface PluginContext {
14
18
  organization?: {
15
19
  id: number | string;
@@ -31,6 +35,16 @@ export interface PluginContext {
31
35
  slug?: string;
32
36
  name?: string;
33
37
  };
38
+ /** Set on scope pages. Not usable in `when` yet (see `CONTEXT_ROOTS`). */
39
+ scope?: {
40
+ id: number | string;
41
+ slug?: string;
42
+ name?: string;
43
+ };
44
+ /** Set on deployment pages. Not usable in `when` yet (see `CONTEXT_ROOTS`). */
45
+ deployment?: {
46
+ id: number | string;
47
+ };
34
48
  nrn?: string;
35
49
  user?: {
36
50
  id: number | string;
@@ -128,6 +142,9 @@ export type HostMessage = {
128
142
  } | {
129
143
  type: 'unmount';
130
144
  mountId: string;
145
+ } | {
146
+ type: 'release-functions';
147
+ ids: string[];
131
148
  } | {
132
149
  type: 'context';
133
150
  context: PluginContext;
@@ -146,11 +163,14 @@ export type HostMessage = {
146
163
  export interface SerializedError {
147
164
  message: string;
148
165
  code?: string;
166
+ /** HTTP status, when the failure came from a request the host made for the plugin. */
167
+ status?: number;
149
168
  stack?: string;
150
169
  }
151
170
  export declare class BridgeError extends Error {
152
171
  code: string;
153
- constructor(message: string, code?: string);
172
+ status?: number;
173
+ constructor(message: string, code?: string, status?: number);
154
174
  }
155
175
  export declare function serializeError(error: unknown): SerializedError;
156
176
  export declare function deserializeError(error: SerializedError): BridgeError;
@@ -168,3 +188,7 @@ export declare function deserializeFunctions(value: unknown, resolve: (id: strin
168
188
  */
169
189
  export declare function toCloneable(value: unknown, seen?: WeakSet<object>): unknown;
170
190
  export declare function createIdGenerator(prefix: string): () => string;
191
+ /** Bound work before traversing data received from an untrusted worker. */
192
+ export declare function assertWireValue(value: unknown): void;
193
+ /** Deadline also covers custom adapters/loaders that ignore cancellation. */
194
+ export declare function withDeadline<T>(promise: Promise<T>, timeoutMs?: number, signal?: AbortSignal): Promise<T>;