@nullplatform/ui-plugin-sdk 0.19.0 → 0.19.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.
@@ -0,0 +1,237 @@
1
+ import { isApiRequestAllowed, normalizePath } from './allowlist.js';
2
+ /**
3
+ * Plugin documents (contracts 6 to 8): a `document` contribution is a JSON view in the SDUI vocabulary that the host
4
+ * draws with no plugin code running. This module holds the plugin profile's first cut: which node types a document may
5
+ * use, and the rule every read obeys. The full shape of each node is `@nullplatform/sdui-spec`'s to check, and the
6
+ * caller passes the spec in (`assertDocumentVocabulary`) until it is published, so the SDK depends on no renderer.
7
+ */
8
+ /**
9
+ * The plugin profile per vocabulary line (contract 7, proposal to validate with the SDUI owners): the node types a
10
+ * plugin document of that line may use. Within a line the list only grows, so a document published once keeps
11
+ * drawing; a change that would break one opens a new line. A document declares its line in its root (`vocabulary`),
12
+ * the `VOCABULARY_LINE` of `@nullplatform/sdui-spec`.
13
+ *
14
+ * Line 1, the first cut: layouts, labels, read controls, collections drawn as tables and navigation. Left out until
15
+ * the profile grows: `Definition` and `Reference` (the server expands them), `Page`, `Outlet`, `Slot`,
16
+ * `Categorization` and `Category` (routing and placement are the host's), and `Component` (another plugin's code).
17
+ */
18
+ export const DOCUMENT_PROFILES = {
19
+ 1: ['VerticalLayout', 'HorizontalLayout', 'GridLayout', 'Group', 'Label', 'Control', 'Collection', 'Action'],
20
+ };
21
+ /** The line documents are written in today; the API accepts every line in `DOCUMENT_PROFILES`. */
22
+ export const DOCUMENT_VOCABULARY_LINE = 1;
23
+ /** Node types of the current line's profile. */
24
+ export const DOCUMENT_NODE_TYPES = DOCUMENT_PROFILES[DOCUMENT_VOCABULARY_LINE];
25
+ export class DocumentError extends Error {
26
+ constructor(message) {
27
+ super(message);
28
+ this.name = 'DocumentError';
29
+ }
30
+ }
31
+ /**
32
+ * Keys that write, ask with a body, or need the server, anywhere in the document: a draft and its checks, pickers
33
+ * (`choices` reads candidates as a form), steps after an action, `rule` (expressions over the data, not in this
34
+ * cut), and what only the server writes (`contributions`, `release`).
35
+ */
36
+ const OUT_OF_CUT_KEYS = new Set(['draft', 'body', 'validate', 'choices', 'then', 'rule', 'contributes', 'contributions', 'release']);
37
+ /** One `{{ … }}` placeholder that is a singular path into the context (`$.url.params.id`), never an expression. */
38
+ const PLACEHOLDER = /^\{\{\s*(\$(?:\.[A-Za-z_][A-Za-z0-9_]*|\[[0-9]+\])+)\s*\}\}$/;
39
+ /** A literal path segment: characters an API path or a host route is written with, nothing a browser would drop. */
40
+ const LITERAL_SEGMENT = /^[A-Za-z0-9_~-][A-Za-z0-9_.~-]*$/;
41
+ /**
42
+ * Whitespace, control characters and backslashes anywhere in a url: a browser strips tabs and newlines and reads a
43
+ * backslash as a slash, so `/\t/evil.example.com` would become another site.
44
+ */
45
+ const UNSAFE_CHARACTERS = /[\s\\\u0000-\u001f\u007f]/;
46
+ /** A query parameter's name: a field, or a field with an operator (`name:contains`), as `sdui-spec` names them. */
47
+ const QUERY_PARAM = /^[a-z_][a-z0-9_.]*(:[a-z_]+)?$/;
48
+ /**
49
+ * What a placeholder segment becomes for the permission check: a pattern segment `{param}` matches it, a literal one
50
+ * can't, since no API path segment is written with braces.
51
+ */
52
+ const HOLE = '{{}}';
53
+ const isPlainObject = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
54
+ /**
55
+ * Parses a read url of a plugin document: a public API path, each placeholder a whole segment or a whole query value.
56
+ * Throws a `DocumentError` saying what to write instead.
57
+ */
58
+ function parseRead(url, where) {
59
+ if (/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('//')) {
60
+ throw new DocumentError(`${where}: "${url}" names a host; a document reads public API paths such as "/application/{{ $.url.params.id }}"`);
61
+ }
62
+ if (!url.startsWith('/'))
63
+ throw new DocumentError(`${where}: "${url}" must start with "/" (a public API path)`);
64
+ if (UNSAFE_CHARACTERS.test(url.replace(/\{\{[^}]*\}\}/g, ''))) {
65
+ throw new DocumentError(`${where}: "${url}" has whitespace, a control character or a backslash`);
66
+ }
67
+ const [path, query] = url.split(/\?(.*)/s, 2);
68
+ const segments = path.split('/').slice(1).map((segment) => {
69
+ if (segment.includes('{') || segment.includes('}')) {
70
+ if (PLACEHOLDER.test(segment))
71
+ return null;
72
+ throw new DocumentError(`${where}: "${url}": a placeholder takes a whole path segment and is a path into the context, such as {{ $.url.params.id }}`);
73
+ }
74
+ if (!LITERAL_SEGMENT.test(segment) || segment === '..') {
75
+ throw new DocumentError(`${where}: "${url}" has an empty, relative or encoded segment, or one with characters outside A-Z, a-z, 0-9 and _ . ~ -`);
76
+ }
77
+ return segment;
78
+ });
79
+ for (const pair of query ? query.split('&') : []) {
80
+ const [name, value = ''] = pair.split(/=(.*)/s, 2);
81
+ if (!QUERY_PARAM.test(name))
82
+ throw new DocumentError(`${where}: "${url}": "${name}" is not a query parameter name`);
83
+ if ((value.includes('{') || value.includes('}')) && !PLACEHOLDER.test(value)) {
84
+ throw new DocumentError(`${where}: "${url}": a placeholder takes a whole query value and is a path into the context`);
85
+ }
86
+ }
87
+ return { segments };
88
+ }
89
+ const asPath = (read, hole) => '/' + read.segments.map((segment, index) => segment ?? hole(index)).join('/');
90
+ /** Checks one read against the plugin's `permissions.api`, with the runtime's own matcher. */
91
+ function assertCovered(read, url, permissions, where) {
92
+ if (isApiRequestAllowed(permissions, 'GET', asPath(read, () => HOLE)))
93
+ return;
94
+ const suggested = asPath(read, (index) => `{param${index}}`);
95
+ const hint = read.segments[0] === 'v1' ? ' Paths are relative to the public API root, without "/v1".' : '';
96
+ throw new DocumentError(`${where}: GET ${url} is not covered by permissions.api; declare { "method": "GET", "path": "${suggested}" } or a pattern that covers it.${hint}`);
97
+ }
98
+ function checkText(value, where) {
99
+ if (isPlainObject(value) && 'i18n' in value)
100
+ throw new DocumentError(`${where}: translatable texts ({ "i18n": … }) are not in the first cut; write the text`);
101
+ }
102
+ /**
103
+ * Walks every value of a node's options: each `url` is a read the plugin declared, a `schema` given as a url too,
104
+ * `method` is only GET, and nothing that writes or needs the server.
105
+ */
106
+ function checkOptions(value, where, visit) {
107
+ if (Array.isArray(value)) {
108
+ value.forEach((item, index) => checkOptions(item, `${where}[${index}]`, visit));
109
+ return;
110
+ }
111
+ if (!isPlainObject(value))
112
+ return;
113
+ checkText(value, where);
114
+ for (const [key, child] of Object.entries(value)) {
115
+ const at = `${where}.${key}`;
116
+ if (OUT_OF_CUT_KEYS.has(key))
117
+ throw new DocumentError(`${at} is not in the first cut of plugin documents (read-only, resolved shape)`);
118
+ if (key === 'method' && child !== 'GET')
119
+ throw new DocumentError(`${at}: a document only reads (GET)`);
120
+ if (key === 'kind' && child !== 'navigate')
121
+ throw new DocumentError(`${at}: "${String(child)}" is not in the first cut; an action only navigates`);
122
+ if (key === 'to')
123
+ throw new DocumentError(`${at}: "to" is a page the server turns into a link; a document is drawn as written, so write the host path in "href"`);
124
+ if (key === 'href') {
125
+ if (typeof child !== 'string')
126
+ throw new DocumentError(`${at} must be a string`);
127
+ // A host path, built like a read: never a scheme or a second slash (another site, a script), never `..`, only
128
+ // safe characters. A placeholder fills one segment; the renderer refuses a filled-in link that is not a path
129
+ // of this origin (sdui-engine's `isRootRelativeHref`).
130
+ parseRead(child, at);
131
+ continue;
132
+ }
133
+ if (key === 'url' || (key === 'schema' && typeof child === 'string' && child.startsWith('/'))) {
134
+ if (typeof child !== 'string')
135
+ throw new DocumentError(`${at} must be a string`);
136
+ visit(child, at);
137
+ continue;
138
+ }
139
+ checkOptions(child, at, visit);
140
+ }
141
+ }
142
+ function checkNode(node, where, types, visit) {
143
+ if (!isPlainObject(node))
144
+ throw new DocumentError(`${where} must be an object`);
145
+ const type = node.type;
146
+ if (typeof type !== 'string' || !types.includes(type)) {
147
+ throw new DocumentError(`${where}: node type "${String(type)}" is not in the first cut (${types.join(', ')})`);
148
+ }
149
+ const at = `${where}(${type})`;
150
+ for (const key of Object.keys(node)) {
151
+ if (OUT_OF_CUT_KEYS.has(key))
152
+ throw new DocumentError(`${at}.${key} is not in the first cut of plugin documents (read-only, resolved shape)`);
153
+ }
154
+ checkText(node.label, `${at}.label`);
155
+ const options = node.options;
156
+ if (options !== undefined && !isPlainObject(options))
157
+ throw new DocumentError(`${at}.options must be an object`);
158
+ if (type === 'Collection' && options?.format !== 'table')
159
+ throw new DocumentError(`${at}: a collection is drawn as a table (options.format "table") in the first cut`);
160
+ if (type === 'Action' && options?.kind !== 'navigate')
161
+ throw new DocumentError(`${at}: an action only navigates (options.kind "navigate") in the first cut`);
162
+ checkOptions(options, `${at}.options`, visit);
163
+ if (node.elements !== undefined) {
164
+ if (!Array.isArray(node.elements))
165
+ throw new DocumentError(`${at}.elements must be an array`);
166
+ node.elements.forEach((child, index) => checkNode(child, `${at}.elements[${index}]`, types, visit));
167
+ }
168
+ }
169
+ /** Every read url of a document that already passed `validatePluginDocument`, in document order. */
170
+ function readsOf(document, permissions) {
171
+ const reads = [];
172
+ const types = DOCUMENT_PROFILES[document.vocabulary] ?? [];
173
+ checkNode(document, 'document', types, (url, where) => {
174
+ const read = parseRead(url, where);
175
+ assertCovered(read, url, permissions, where);
176
+ reads.push(read);
177
+ });
178
+ return reads;
179
+ }
180
+ /**
181
+ * Validates an untrusted plugin document against the first cut of the plugin profile and the plugin's
182
+ * `permissions.api` (contract 8): every read is a public API path, GET, covered by a declared permission, with its
183
+ * placeholders as whole segments. Throws a `DocumentError` describing the first problem.
184
+ */
185
+ export function validatePluginDocument(input, permissions) {
186
+ if (!isPlainObject(input))
187
+ throw new DocumentError('A document must be a JSON object');
188
+ if (typeof input.vocabulary !== 'number' || !(input.vocabulary in DOCUMENT_PROFILES)) {
189
+ throw new DocumentError(`A document declares its vocabulary line in its root: "vocabulary": ${DOCUMENT_VOCABULARY_LINE} (accepted: ${Object.keys(DOCUMENT_PROFILES).join(', ')})`);
190
+ }
191
+ readsOf(input, permissions);
192
+ return input;
193
+ }
194
+ /**
195
+ * Checks a document against the vocabulary itself (contract 6): a node as the server would answer it, the shape SDUI's
196
+ * renderer draws (ids are uuids, links are `href`, options closed per type). `vocabulary` is the plugin document's own
197
+ * envelope key, so it is set aside first. A line newer than the vocabulary's is refused. Run it after
198
+ * `validatePluginDocument`; throws a `DocumentError` naming up to five problems.
199
+ */
200
+ export function assertDocumentVocabulary(document, vocabulary) {
201
+ const { vocabulary: line, ...node } = document;
202
+ if (line > vocabulary.line) {
203
+ throw new DocumentError(`The document's vocabulary line ${line} is newer than this platform's (${vocabulary.line})`);
204
+ }
205
+ const parsed = vocabulary.node.safeParse(node);
206
+ if (parsed.success)
207
+ return;
208
+ const issues = (parsed.error?.issues ?? [])
209
+ .slice(0, 5)
210
+ .map((issue) => `${issue.path.length ? '/' + issue.path.map(String).join('/') : '/'}: ${issue.message}`);
211
+ throw new DocumentError(`The document is not a view the renderer draws: ${issues.join('; ')}`);
212
+ }
213
+ /**
214
+ * Builds the check for the reads the renderer asks for while drawing a document: a read is allowed when it is a GET,
215
+ * the interpolated url's path matches one of the document's read urls (each placeholder exactly one segment) and
216
+ * `permissions.api` covers it. Query strings are never part of the decision, as with widgets. The document is walked
217
+ * once, here, and not on every read; a document whose reads don't pass allows none.
218
+ */
219
+ export function documentReadCheck(document, permissions) {
220
+ let reads;
221
+ try {
222
+ reads = readsOf(document, permissions);
223
+ }
224
+ catch {
225
+ reads = [];
226
+ }
227
+ return (method, url) => {
228
+ if (method.toUpperCase() !== 'GET')
229
+ return false;
230
+ const [path] = url.split('?', 1);
231
+ const requested = normalizePath(path);
232
+ if (!requested || !isApiRequestAllowed(permissions, 'GET', path))
233
+ return false;
234
+ return reads.some((read) => read.segments.length === requested.length &&
235
+ read.segments.every((segment, index) => (segment === null ? requested[index].length > 0 : segment === requested[index])));
236
+ };
237
+ }
@@ -1,8 +1,8 @@
1
- export { PROTOCOL_VERSION, validateManifest, validatePublishableManifest, unnamedContributions, contributionId, RESERVED_PLUGIN_ID, isSectionSlot, ManifestError, type PluginManifest, type Contribution, type ApiPermission, type HttpPermission, type HttpMethod, } from './manifest.js';
1
+ export { PROTOCOL_VERSION, validateManifest, validatePublishableManifest, validateAuthoredApiPermissions, unnamedContributions, contributionId, RESERVED_PLUGIN_ID, isSectionSlot, ManifestError, type PluginManifest, type Contribution, type ApiPermission, type HttpPermission, type HttpMethod, } from './manifest.js';
2
2
  export { PLACE_ROOTS, missingContext, contextSatisfies, readPlaceRoots, type PlaceRoot } from './context.js';
3
3
  export { pageOf, layoutConflicts, type LayoutConflict } from './layout.js';
4
4
  export { PAGE_AREAS, REQUIRED_PAGE_AREA, MIN_PAGE_AREA_WIDTH, pageTemplateProblems, isPageTemplateDefinition, type PageArea, type PageTemplateBreakpoint, type PageTemplateDefinition, type PageTemplateResponsive, type PageTemplateTracks, } from './pageTemplate.js';
5
- export { isApiRequestAllowed, isHttpRequestAllowed, isRequestAllowed, normalizePath, canonicalizePath } from './allowlist.js';
5
+ export { isApiRequestAllowed, isHttpRequestAllowed, isRequestAllowed, isReservedApiRequest, normalizePath, canonicalizePath } from './allowlist.js';
6
6
  export { matchFixture, type Fixtures, type FixtureMatch } from './fixtures.js';
7
7
  export { CONTEXT_ROOTS, extractRoots, validateWhen, evaluateWhen, rolloutIncludes, WhenError, type WhenQuery, type ContextRoot, type Rollout, } from './when.js';
8
8
  export { PLUGIN_STORAGE_ORIGIN, validateStorageUrl, resolveAssetUrl } from './storage.js';
@@ -1,8 +1,8 @@
1
- export { PROTOCOL_VERSION, validateManifest, validatePublishableManifest, unnamedContributions, contributionId, RESERVED_PLUGIN_ID, isSectionSlot, ManifestError, } from './manifest.js';
1
+ export { PROTOCOL_VERSION, validateManifest, validatePublishableManifest, validateAuthoredApiPermissions, unnamedContributions, contributionId, RESERVED_PLUGIN_ID, isSectionSlot, ManifestError, } from './manifest.js';
2
2
  export { PLACE_ROOTS, missingContext, contextSatisfies, readPlaceRoots } from './context.js';
3
3
  export { pageOf, layoutConflicts } from './layout.js';
4
4
  export { PAGE_AREAS, REQUIRED_PAGE_AREA, MIN_PAGE_AREA_WIDTH, pageTemplateProblems, isPageTemplateDefinition, } from './pageTemplate.js';
5
- export { isApiRequestAllowed, isHttpRequestAllowed, isRequestAllowed, normalizePath, canonicalizePath } from './allowlist.js';
5
+ export { isApiRequestAllowed, isHttpRequestAllowed, isRequestAllowed, isReservedApiRequest, normalizePath, canonicalizePath } from './allowlist.js';
6
6
  export { matchFixture } from './fixtures.js';
7
7
  export { CONTEXT_ROOTS, extractRoots, validateWhen, evaluateWhen, rolloutIncludes, WhenError, } from './when.js';
8
8
  export { PLUGIN_STORAGE_ORIGIN, validateStorageUrl, resolveAssetUrl } from './storage.js';
@@ -76,6 +76,15 @@ export declare function contributionId(contribution: {
76
76
  * it before the build is pushed. Revisions published before keep working: hosts name them with `contributionId`.
77
77
  */
78
78
  export declare function validatePublishableManifest(input: unknown): PluginManifest;
79
+ /**
80
+ * What a manifest's `permissions.api` must meet where the manifest is written: at publish and in developer mode, never
81
+ * where a stored revision is read. Each path names its resource, so a reviewer reading the manifest sees what the
82
+ * plugin calls, and none names an operation no plugin may call (`isReservedApiRequest`). A revision published before
83
+ * these rules keeps loading, and the call itself is refused (`isApiRequestAllowed`), so a page loses one call, not
84
+ * the whole plugin. A placeholder deeper in the path can still cover a reserved operation (`POST /catalog/{kind}/{type}`):
85
+ * that too is refused at call time, on the path actually requested.
86
+ */
87
+ export declare function validateAuthoredApiPermissions(manifest: PluginManifest): PluginManifest;
79
88
  /**
80
89
  * Contributions that go by their widget for lack of an `id`. Publishable, but renaming the widget would rename the
81
90
  * block, its flag and its place in layouts, so the CLI warns about them.
@@ -1,6 +1,7 @@
1
1
  import { validateWhen, WhenError } from './when.js';
2
2
  import { isFieldPath, isHostTopic, isTopicName, topicOwner } from './topics.js';
3
3
  import { PLACE_ROOTS, readPlaceRoots } from './context.js';
4
+ import { isReservedApiRequest } from './allowlist.js';
4
5
  export const PROTOCOL_VERSION = 1;
5
6
  export class ManifestError extends Error {
6
7
  constructor(message) {
@@ -93,7 +94,8 @@ export function validateManifest(input) {
93
94
  permissions.api = rawPermissions.api.map((raw, index) => {
94
95
  const p = (raw ?? {});
95
96
  const where = `permissions.api[${index}]`;
96
- return { method: readMethod(p.method, where), path: readPath(p.path, where) };
97
+ const method = readMethod(p.method, where);
98
+ return { method, path: readPath(p.path, where) };
97
99
  });
98
100
  }
99
101
  if (rawPermissions.http !== undefined) {
@@ -205,6 +207,27 @@ export function validatePublishableManifest(input) {
205
207
  });
206
208
  return manifest;
207
209
  }
210
+ /**
211
+ * What a manifest's `permissions.api` must meet where the manifest is written: at publish and in developer mode, never
212
+ * where a stored revision is read. Each path names its resource, so a reviewer reading the manifest sees what the
213
+ * plugin calls, and none names an operation no plugin may call (`isReservedApiRequest`). A revision published before
214
+ * these rules keeps loading, and the call itself is refused (`isApiRequestAllowed`), so a page loses one call, not
215
+ * the whole plugin. A placeholder deeper in the path can still cover a reserved operation (`POST /catalog/{kind}/{type}`):
216
+ * that too is refused at call time, on the path actually requested.
217
+ */
218
+ export function validateAuthoredApiPermissions(manifest) {
219
+ (manifest.permissions?.api ?? []).forEach(({ method, path }, index) => {
220
+ const where = `permissions.api[${index}]`;
221
+ const [resource] = path.slice(1).split('/');
222
+ if (resource.startsWith('{') && resource.endsWith('}')) {
223
+ throw new ManifestError(`${where}.path must name its resource: "${resource}" cannot be the first segment`);
224
+ }
225
+ if (isReservedApiRequest(method, path)) {
226
+ throw new ManifestError(`${where}: plugins may not ${method === '*' ? 'call' : method} ${path}: it is reserved, because a plugin acts with the rights of whoever views it`);
227
+ }
228
+ });
229
+ return manifest;
230
+ }
208
231
  /**
209
232
  * Contributions that go by their widget for lack of an `id`. Publishable, but renaming the widget would rename the
210
233
  * block, its flag and its place in layouts, so the CLI warns about them.
@@ -4,6 +4,7 @@ exports.isRequestAllowed = void 0;
4
4
  exports.normalizePath = normalizePath;
5
5
  exports.canonicalizePath = canonicalizePath;
6
6
  exports.pathMatches = pathMatches;
7
+ exports.isReservedApiRequest = isReservedApiRequest;
7
8
  exports.isApiRequestAllowed = isApiRequestAllowed;
8
9
  exports.isHttpRequestAllowed = isHttpRequestAllowed;
9
10
  /** Splits a path into segments; rejects traversal, empty segments and query/hash fragments. */
@@ -49,6 +50,81 @@ function pathMatches(pattern, requestSegments) {
49
50
  return segment === requestSegments[index];
50
51
  });
51
52
  }
53
+ // A plugin call runs with the token of whoever is looking at the page, so a manifest that names
54
+ // one of these would act with an administrator's rights for every administrator who opens it.
55
+ // Each entry is a path prefix: it reserves that path and everything under it.
56
+ const RESERVED_FOR_EVERY_METHOD = [
57
+ // Credentials.
58
+ ['api_key'],
59
+ ['pat'],
60
+ ['token'],
61
+ ];
62
+ const RESERVED_FOR_WRITES = [
63
+ // Who may do what.
64
+ ['authz'],
65
+ ['user'],
66
+ // Which code an organization runs.
67
+ ['packages'],
68
+ ['package_revision'],
69
+ ['package_installations'],
70
+ ['artifacts'],
71
+ ['artifact_revision'],
72
+ ['plugin_bundles'],
73
+ // Catalog lake ingest: it adds entities to the catalog.
74
+ ['catalog', 'lake'],
75
+ ];
76
+ // Writes under a prefix reserved for writes that a plugin may still make. Each is exact: one
77
+ // method, never `*` (which would cover the other writes too), and one path, never a prefix, where
78
+ // `{id}` matches one segment.
79
+ const ALLOWED_UNDER_RESERVED = [
80
+ // Asks whether the viewer may do something; it grants nothing.
81
+ ['POST', '/authz/check'],
82
+ // What the authz backoffice (nullplatform/frontend-authz-backoffice) writes. Allowed for now,
83
+ // to every plugin: nothing yet tells a platform plugin from a customer's (BAC-3552).
84
+ ['POST', '/authz/role'],
85
+ ['PATCH', '/authz/role/{id}'],
86
+ ['POST', '/authz/role/{id}/action'],
87
+ ['POST', '/authz/action'],
88
+ ['PATCH', '/authz/action/{id}'],
89
+ ['POST', '/authz/action_group'],
90
+ ['PATCH', '/authz/action_group/{id}'],
91
+ ['DELETE', '/authz/action_group/{id}'],
92
+ ['POST', '/authz/role_hierarchy'],
93
+ ['DELETE', '/authz/role_hierarchy/{id}'],
94
+ ['POST', '/authz/role_action_modifier'],
95
+ ['DELETE', '/authz/role_action_modifier/{id}'],
96
+ ];
97
+ // `*` counts as a write: a permission declared with it covers the writes too.
98
+ const WRITE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE', '*']);
99
+ function startsWith(segments, prefix) {
100
+ return prefix.length <= segments.length && prefix.every((segment, index) => segments[index].toLowerCase() === segment);
101
+ }
102
+ function isAllowedUnderReserved(verb, segments) {
103
+ return ALLOWED_UNDER_RESERVED.some(([method, path]) => {
104
+ const pattern = path.split('/').slice(1);
105
+ return (method === verb &&
106
+ pattern.length === segments.length &&
107
+ pattern.every((segment, index) => (segment === '{id}' ? segments[index].length > 0 : segments[index].toLowerCase() === segment)));
108
+ });
109
+ }
110
+ function isReservedSegments(method, segments) {
111
+ if (RESERVED_FOR_EVERY_METHOD.some((prefix) => startsWith(segments, prefix)))
112
+ return true;
113
+ const verb = method.toUpperCase();
114
+ if (!WRITE_METHODS.has(verb))
115
+ return false;
116
+ if (isAllowedUnderReserved(verb, segments))
117
+ return false;
118
+ return RESERVED_FOR_WRITES.some((prefix) => startsWith(segments, prefix));
119
+ }
120
+ /**
121
+ * True when no plugin may call `method` on `path`, whatever its manifest declares. A path that
122
+ * does not normalize is not reserved: `isApiRequestAllowed` already refuses it.
123
+ */
124
+ function isReservedApiRequest(method, path) {
125
+ const segments = normalizePath(path);
126
+ return segments !== null && isReservedSegments(method, segments);
127
+ }
52
128
  /**
53
129
  * Decides whether a plugin API request (a nullplatform public API path) is covered
54
130
  * by its declared `permissions.api`. Query strings are never part of the decision.
@@ -60,6 +136,9 @@ function isApiRequestAllowed(permissions, method, path) {
60
136
  const requestSegments = normalizePath(path);
61
137
  if (!requestSegments)
62
138
  return false;
139
+ // Checked on the request, not on the declared patterns, so a placeholder cannot reach one.
140
+ if (isReservedSegments(requestMethod, requestSegments))
141
+ return false;
63
142
  return permissions.some((permission) => (permission.method === '*' || permission.method === requestMethod) && pathMatches(permission.path, requestSegments));
64
143
  }
65
144
  /** @deprecated use `isApiRequestAllowed`. */