@perkyzz/emvb 1.0.0 → 1.2.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.
Files changed (142) hide show
  1. package/README.md +9 -0
  2. package/THIRD_PARTY_NOTICES.md +1 -0
  3. package/package.json +10 -9
  4. package/src/admin/agents-api.ts +5 -1
  5. package/src/admin/bulk-api.ts +67 -0
  6. package/src/admin/content-api.ts +39 -6
  7. package/src/admin/copy-rich-text.ts +119 -0
  8. package/src/admin/dialog-tab-wrap.ts +78 -0
  9. package/src/admin/editor/A11yCopilot.tsx +2 -0
  10. package/src/admin/editor/Editor.tsx +24 -7
  11. package/src/admin/editor/ScheduleDialog.tsx +167 -0
  12. package/src/admin/editor/Timeline.tsx +6 -2
  13. package/src/admin/editor/TopBar.tsx +60 -8
  14. package/src/admin/editor/canvas/CanvasFrame.tsx +7 -2
  15. package/src/admin/editor/canvas/DeviceBar.tsx +22 -9
  16. package/src/admin/editor/canvas/canvas-scale.ts +3 -3
  17. package/src/admin/editor/canvas/use-canvas-session.ts +2 -2
  18. package/src/admin/editor/dnd/new-element.ts +68 -0
  19. package/src/admin/editor/editor-chrome.tsx +16 -5
  20. package/src/admin/editor/editor-commands.ts +10 -4
  21. package/src/admin/editor/editor-css.ts +2 -1
  22. package/src/admin/editor/element-chrome.ts +22 -0
  23. package/src/admin/editor/panels/ElementPanel.tsx +34 -17
  24. package/src/admin/editor/panels/SettingsPanel.tsx +2 -2
  25. package/src/admin/editor/panels/settings/DraftTextField.tsx +33 -1
  26. package/src/admin/editor/panels/settings/EffectsControls.tsx +79 -1
  27. package/src/admin/editor/panels/settings/FieldBindControl.tsx +6 -1
  28. package/src/admin/editor/panels/settings/FieldControl.tsx +10 -1
  29. package/src/admin/editor/panels/settings/IconControls.tsx +11 -0
  30. package/src/admin/editor/panels/settings/IconPicker.tsx +4 -1
  31. package/src/admin/editor/panels/settings/ItemList.tsx +36 -2
  32. package/src/admin/editor/panels/settings/LengthRow.tsx +36 -3
  33. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +18 -0
  34. package/src/admin/editor/panels/settings/StyleRow.tsx +7 -0
  35. package/src/admin/editor/panels/settings/advanced-rules.ts +3 -0
  36. package/src/admin/editor/panels/settings/length-units.ts +15 -3
  37. package/src/admin/editor/panels/settings/style-sections.ts +1 -0
  38. package/src/admin/editor/panels/style-target.ts +17 -4
  39. package/src/admin/editor/section-templates.ts +26 -4
  40. package/src/admin/editor/store.ts +15 -3
  41. package/src/admin/editor/useEditorCommands.ts +7 -5
  42. package/src/admin/editor/useEditorData.ts +4 -0
  43. package/src/admin/editor/useNodeActions.ts +4 -2
  44. package/src/admin/editor/useSave.ts +47 -3
  45. package/src/admin/export-api.ts +238 -0
  46. package/src/admin/index.tsx +6 -1
  47. package/src/admin/menus-api.ts +113 -0
  48. package/src/admin/pages/ExportDialog.tsx +395 -0
  49. package/src/admin/pages/ImportElementorDialog.tsx +25 -1
  50. package/src/admin/pages/PageList.tsx +67 -2
  51. package/src/admin/pages/ThemePartList.tsx +37 -1
  52. package/src/admin/pages/bulk.tsx +303 -0
  53. package/src/admin/search.ts +20 -0
  54. package/src/admin/theme-api.ts +4 -0
  55. package/src/admin/ui.ts +11 -2
  56. package/src/admin/widgets/CanvasField.tsx +8 -0
  57. package/src/admin/widgets/ConvertToRichText.tsx +136 -0
  58. package/src/admin/widgets/ExportEntryHtml.tsx +92 -0
  59. package/src/admin/widgets/convert-body.ts +73 -2
  60. package/src/astro/EmVBPage.astro +3 -0
  61. package/src/astro/render.ts +47 -22
  62. package/src/astro/request-data.ts +3 -0
  63. package/src/astro/resolve-theme.ts +88 -51
  64. package/src/astro/tabs/runtime.ts +16 -6
  65. package/src/astro/visitor.ts +23 -4
  66. package/src/astro/widgets/EmVBAlertsRuntime.astro +8 -0
  67. package/src/astro/widgets/EmVBCarouselRuntime.astro +8 -0
  68. package/src/astro/widgets/EmVBLightboxRuntime.astro +8 -0
  69. package/src/astro/widgets/EmVBWidgetRuntimes.astro +19 -0
  70. package/src/astro/widgets/alerts.ts +37 -0
  71. package/src/astro/widgets/carousel.ts +167 -0
  72. package/src/astro/widgets/index.ts +1 -0
  73. package/src/astro/widgets/lightbox.ts +123 -0
  74. package/src/constants.ts +1 -1
  75. package/src/core/a11y/audit.ts +103 -3
  76. package/src/core/arrange.ts +57 -1
  77. package/src/core/bounded-array.ts +16 -13
  78. package/src/core/contract.ts +26 -3
  79. package/src/core/css/generate.ts +83 -21
  80. package/src/core/css/scope.ts +10 -2
  81. package/src/core/css/trace.ts +33 -8
  82. package/src/core/design/classes.ts +25 -5
  83. package/src/core/design/devices.ts +78 -2
  84. package/src/core/design/variables.ts +14 -1
  85. package/src/core/elements/icon-svg.ts +135 -0
  86. package/src/core/elements/index.ts +33 -127
  87. package/src/core/elements/widgets.ts +907 -0
  88. package/src/core/export/runtimes.generated.ts +12 -0
  89. package/src/core/export/site.ts +579 -0
  90. package/src/core/export/zip.ts +95 -0
  91. package/src/core/extensions/schema.ts +2 -1
  92. package/src/core/geo-trust.ts +18 -0
  93. package/src/core/history/diff.ts +25 -0
  94. package/src/core/icons/social.generated.ts +29 -0
  95. package/src/core/image-edit/schema.ts +2 -1
  96. package/src/core/import/elementor/atomic.ts +22 -9
  97. package/src/core/import/elementor/context.ts +18 -0
  98. package/src/core/import/elementor/index.ts +72 -11
  99. package/src/core/import/elementor/style.ts +21 -1
  100. package/src/core/import/elementor/widgets.ts +394 -133
  101. package/src/core/index.ts +14 -0
  102. package/src/core/issue-cap.ts +19 -0
  103. package/src/core/json-schema.ts +8 -1
  104. package/src/core/limits.ts +6 -0
  105. package/src/core/loop-collections.ts +33 -0
  106. package/src/core/perf/meter.ts +37 -19
  107. package/src/core/portable-text-export.ts +243 -0
  108. package/src/core/proposals.ts +8 -2
  109. package/src/core/public-attributes.ts +30 -0
  110. package/src/core/render/index.ts +115 -13
  111. package/src/core/render/tabs.ts +18 -11
  112. package/src/core/render/vnode.ts +44 -6
  113. package/src/core/sanitize/css.ts +26 -0
  114. package/src/core/sanitize/svg-upload.ts +276 -23
  115. package/src/core/sanitize/svg.ts +3 -3
  116. package/src/core/schema/descriptors.ts +4 -0
  117. package/src/core/schema/design.ts +8 -7
  118. package/src/core/schema/layout.ts +406 -18
  119. package/src/core/schema/style.ts +49 -1
  120. package/src/core/search-text.ts +70 -0
  121. package/src/core/shadowing-ids.ts +41 -0
  122. package/src/core/theme/conditions.ts +2 -1
  123. package/src/core/theme/float.ts +1 -0
  124. package/src/core/theme/parse-doc.ts +10 -5
  125. package/src/core/theme/popup-rules.ts +16 -0
  126. package/src/core/theme/triggers.ts +3 -2
  127. package/src/core/validate.ts +3 -2
  128. package/src/index.ts +23 -2
  129. package/src/mcp/ports.ts +18 -7
  130. package/src/mcp/proposals.ts +36 -11
  131. package/src/mcp/read.ts +2 -3
  132. package/src/mcp/tools.ts +1 -1
  133. package/src/server/agent-settings.ts +12 -1
  134. package/src/server/hooks.ts +41 -6
  135. package/src/server/icon-routes.ts +52 -12
  136. package/src/server/mcp-routes.ts +11 -5
  137. package/src/server/plugin.ts +27 -2
  138. package/src/server/presence.ts +5 -1
  139. package/src/server/proposals.ts +16 -4
  140. package/src/server/requests.ts +60 -11
  141. package/src/server/site-origin.ts +13 -0
  142. package/src/server/targets.ts +26 -0
@@ -24,16 +24,40 @@ type IconStore = {
24
24
  query(options?: {
25
25
  orderBy?: Record<string, "asc" | "desc">;
26
26
  limit?: number;
27
- }): Promise<{ items: Array<{ id: string; data: UploadedIcon }>; hasMore: boolean }>;
27
+ cursor?: string;
28
+ }): Promise<{
29
+ items: Array<{ id: string; data: UploadedIcon }>;
30
+ hasMore: boolean;
31
+ cursor?: string;
32
+ }>;
28
33
  };
29
34
 
30
35
  const store = (ctx: RouteContext<unknown>) => ctx.storage["icons"] as unknown as IconStore;
31
36
 
32
37
  /**
33
- * The uploads the picker lists, and the most My uploads holds (W-535): past it the oldest
34
- * uploads dropped off the list and could no longer be seen or deleted.
38
+ * The most My uploads holds, and the uploads the picker lists (W-535; 500 since W-972). EmDash
39
+ * returns plugin storage 100 rows at a time, so the list is read page by page.
35
40
  */
36
- export const UPLOAD_LIST_LIMIT = 100;
41
+ export const UPLOAD_LIST_LIMIT = 500;
42
+ const STORAGE_PAGE = 100;
43
+
44
+ /** Every upload, newest first, up to the limit, following EmDash's storage cursor (W-972). */
45
+ async function allUploads(ctx: RouteContext<unknown>) {
46
+ const items: Array<{ id: string; data: UploadedIcon }> = [];
47
+ let cursor: string | undefined;
48
+ for (let page = 0; page < UPLOAD_LIST_LIMIT / STORAGE_PAGE; page += 1) {
49
+ // oxlint-disable-next-line no-await-in-loop -- each page needs the previous page's cursor
50
+ const result = await store(ctx).query({
51
+ orderBy: { uploadedAt: "desc" },
52
+ limit: STORAGE_PAGE,
53
+ ...(cursor ? { cursor } : {}),
54
+ });
55
+ items.push(...result.items);
56
+ if (!result.hasMore || !result.cursor) break;
57
+ cursor = result.cursor;
58
+ }
59
+ return items.slice(0, UPLOAD_LIST_LIMIT);
60
+ }
37
61
 
38
62
  /** An icon's label as typed: trimmed and capped (W-655: a rename may hold a slash, as in "AC/DC"). */
39
63
  // W-656: control characters become spaces and invisible or direction-changing marks go, so a
@@ -75,11 +99,7 @@ export function publicUploadedIcon(id: string, data: UploadedIcon): UploadedIcon
75
99
  export const iconsRoute: PluginRoute = {
76
100
  permission: "content:edit_any",
77
101
  handler: async (ctx) => {
78
- const page = await store(ctx).query({
79
- orderBy: { uploadedAt: "desc" },
80
- limit: UPLOAD_LIST_LIMIT,
81
- });
82
- const items = page.items.flatMap(({ id, data }) => {
102
+ const items = (await allUploads(ctx)).flatMap(({ id, data }) => {
83
103
  const item = publicUploadedIcon(id, data);
84
104
  return item ? [item] : [];
85
105
  });
@@ -100,15 +120,27 @@ export const iconUploadRoute: PluginRoute<z.infer<typeof UploadInput>> = {
100
120
  handler: async (ctx) => {
101
121
  const prepared = prepareUploadedSvg(ctx.input.svg);
102
122
  if (!prepared.ok) throw new PluginRouteError("INVALID_SVG", prepared.message, 422);
103
- const held = await store(ctx).query({ limit: UPLOAD_LIST_LIMIT });
104
- if (held.items.length >= UPLOAD_LIST_LIMIT) {
123
+ const held = await allUploads(ctx);
124
+ // W-972: the same SVG uploaded again (twice at once from two tabs, or later) is the icon
125
+ // already in My uploads; the check runs on the sanitized markup, so it is the same drawing.
126
+ const same = held.find(({ data }) => data.svg === prepared.svg);
127
+ if (same) {
128
+ return {
129
+ item: { id: same.id, ...same.data },
130
+ imagesLeftOut: prepared.imagesLeftOut,
131
+ duplicate: true,
132
+ };
133
+ }
134
+ if (held.length >= UPLOAD_LIST_LIMIT) {
105
135
  throw new PluginRouteError(
106
136
  "UPLOADS_FULL",
107
137
  `My uploads holds up to ${UPLOAD_LIST_LIMIT} icons. Delete one you no longer use, then upload again.`,
108
138
  409,
109
139
  );
110
140
  }
111
- const id = crypto.randomUUID().replaceAll("-", "").slice(0, 16);
141
+ // W-972: the id is the drawing's hash, so two uploads of the same SVG at the same moment
142
+ // land on one row instead of two.
143
+ const id = await svgId(prepared.svg);
112
144
  const item: UploadedIcon = {
113
145
  name: uploadName(ctx.input.name),
114
146
  svg: prepared.svg,
@@ -119,6 +151,14 @@ export const iconUploadRoute: PluginRoute<z.infer<typeof UploadInput>> = {
119
151
  },
120
152
  };
121
153
 
154
+ /** The first 16 hex digits of the SHA-256 of the sanitized markup. */
155
+ async function svgId(svg: string): Promise<string> {
156
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(svg));
157
+ return [...new Uint8Array(digest).slice(0, 8)]
158
+ .map((b) => b.toString(16).padStart(2, "0"))
159
+ .join("");
160
+ }
161
+
122
162
  const IdInput = z.object({
123
163
  id: z.string().regex(/^[0-9a-f]{16}$/, "Unknown icon"),
124
164
  });
@@ -12,6 +12,7 @@ import { callerKey, hitRateLimit, type RateStore } from "../mcp/rate-limit.ts";
12
12
  import { runTool, type ToolDef } from "../mcp/tools.ts";
13
13
  import { publishDesignDraft, readDesign, writeDesignDraft } from "./design-routes.ts";
14
14
  import { appendAgentLog, readAgentSettings } from "./agent-settings.ts";
15
+ import { trustedOrigin } from "./site-origin.ts";
15
16
 
16
17
  type Item = {
17
18
  id: string;
@@ -76,18 +77,23 @@ const FORMS_DEFINITION = "/_emdash/api/plugins/emdash-forms/definition";
76
77
  /**
77
78
  * W-511: form fields for describe_page's required-field warnings, from the forms plugin's public
78
79
  * definition route on this site. A plugin route has no in-process handle on another plugin, so
79
- * this is a same-origin request with a short timeout; a form it can't read is left out.
80
+ * this is a request with a short timeout; a form it can't read is left out. S-05 (W-995): the
81
+ * request goes only to the configured site origin and follows no redirect; without a configured
82
+ * origin there are no warnings.
80
83
  */
81
- async function loadFormFieldsFromSite(
82
- origin: string,
84
+ export async function loadFormFieldsFromSite(
85
+ origin: string | undefined,
83
86
  formIds: readonly string[],
87
+ fetcher: typeof fetch = fetch,
84
88
  ): Promise<Map<string, RequiredFieldInfo[]>> {
85
89
  const found = new Map<string, RequiredFieldInfo[]>();
90
+ if (!origin) return found;
86
91
  await Promise.all(
87
92
  formIds.slice(0, 20).map(async (id) => {
88
93
  try {
89
- const response = await fetch(new URL(FORMS_DEFINITION, origin), {
94
+ const response = await fetcher(new URL(FORMS_DEFINITION, origin), {
90
95
  method: "POST",
96
+ redirect: "error",
91
97
  headers: { "content-type": "application/json" },
92
98
  body: JSON.stringify({ id }),
93
99
  signal: AbortSignal.timeout(3000),
@@ -148,7 +154,7 @@ function pluginPorts(ctx: RouteContext<unknown>): EmvbPorts {
148
154
  collection: PAGES_COLLECTION,
149
155
  id,
150
156
  }),
151
- formFields: (formIds) => loadFormFieldsFromSite(ctx.request.url, formIds),
157
+ formFields: (formIds) => loadFormFieldsFromSite(trustedOrigin(ctx.site?.url), formIds),
152
158
  async rateLimit(cls) {
153
159
  await hitRateLimit(
154
160
  ctx.kv as unknown as RateStore,
@@ -1,3 +1,5 @@
1
+ import { setLoopCollections } from "../core/loop-collections.ts";
2
+ import { setGeoTrust } from "../core/geo-trust.ts";
1
3
  import {
2
4
  proposalCreateRoute,
3
5
  proposalGetRoute,
@@ -36,17 +38,30 @@ import { manifestsFromOptions } from "../core/extensions/index.ts";
36
38
  import { TOOLS } from "../mcp/tools.ts";
37
39
  import { mcpRoutes, mcpToolConfig } from "./mcp-routes.ts";
38
40
 
41
+ /** W-1005: the name and description EmDash 1.5 shows for the plugin. */
42
+ export const PLUGIN_META = {
43
+ displayName: "EmVB",
44
+ description: "Visual page builder: pages, theme parts and site styles, edited on a live canvas.",
45
+ };
46
+
39
47
  export function createPlugin(
40
48
  options: {
41
49
  canvasStyles?: unknown;
42
50
  canvasCollections?: unknown;
43
51
  extensions?: unknown;
52
+ trustGeoHeaders?: unknown;
53
+ loopCollections?: unknown;
44
54
  } = {},
45
55
  ) {
56
+ setGeoTrust(options.trustGeoHeaders);
57
+ setLoopCollections(options.loopCollections);
46
58
  const canvasStyles = canvasStyleUrls(options.canvasStyles);
47
59
  const canvasCollections = canvasCollectionSlugs(options.canvasCollections);
48
60
  const extensions = manifestsFromOptions(options.extensions);
49
61
  return definePlugin({
62
+ // W-1005: EmDash 1.5 shows these on its plugins screen; 1.4 ignores them. Spread from a
63
+ // constant because 1.4's types don't list them.
64
+ ...PLUGIN_META,
50
65
  id: PLUGIN_ID,
51
66
  version: PLUGIN_VERSION,
52
67
  capabilities: [
@@ -57,6 +72,8 @@ export function createPlugin(
57
72
  "content:publish",
58
73
  "content:revisions:read",
59
74
  "hooks.content-policy:register",
75
+ // W-991 (S-04): check every co-editor EmDash 1.5 lists in a save's `editedBy`.
76
+ "users:read",
60
77
  ],
61
78
  // W-239: uploaded SVG icons (EmDash's media library refuses SVG by default).
62
79
  storage: {
@@ -95,12 +112,20 @@ export function createPlugin(
95
112
  ],
96
113
  },
97
114
  routes: {
115
+ // S-12 (W-1001): the public check says the plugin is loaded, not which version (a version
116
+ // tells an attacker which advisories apply); editors read it from `version`.
98
117
  health: {
99
118
  public: true,
100
- handler: async () => ({ ok: true, plugin: PLUGIN_ID, version: PLUGIN_VERSION }),
119
+ handler: async () => ({ ok: true, plugin: PLUGIN_ID }),
120
+ },
121
+ version: {
122
+ permission: "content:edit_any",
123
+ handler: async () => ({ plugin: PLUGIN_ID, version: PLUGIN_VERSION }),
101
124
  },
102
- // W-327: what the editor needs from the host's `emvb()` options.
125
+ // W-327: what the editor needs from the host's `emvb()` options. S-12 (W-1001): without a
126
+ // permission the route was admin-only, so an editor's canvas lacked the site's styles.
103
127
  "editor/config": {
128
+ permission: "content:edit_any",
104
129
  handler: async () => ({
105
130
  canvasStyles,
106
131
  canvasCollections,
@@ -1,4 +1,5 @@
1
- import type { PluginRoute, RouteContext } from "emdash";
1
+ import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
2
+ import { isEmvbTarget } from "./targets.ts";
2
3
  import { z } from "zod";
3
4
  import { isRecord } from "../core/record.ts";
4
5
  import { ProposalTarget } from "../core/proposals.ts";
@@ -70,6 +71,9 @@ export const presenceRoute: PluginRoute<z.infer<typeof PresenceInput>> = {
70
71
  input: PresenceInput,
71
72
  handler: async (ctx: RouteContext<z.infer<typeof PresenceInput>>) => {
72
73
  const userId = ctx.user?.id;
74
+ // S-09 (W-998): a lease only for an entry that exists; closing never needs the check.
75
+ if (ctx.input.open && !(await isEmvbTarget(ctx, ctx.input.target)))
76
+ throw new PluginRouteError("NOT_FOUND", "No such page.", 404);
73
77
  if (userId) {
74
78
  await setPresence(ctx.kv as unknown as Kv, ctx.input.target, userId, ctx.input.open);
75
79
  }
@@ -39,7 +39,14 @@ function readRecord(raw: unknown): { ok: true; record: ProposalRecord } | Propos
39
39
  }
40
40
  const read = readProposal(raw.proposal);
41
41
  return read.ok
42
- ? { ok: true, record: { proposal: read.proposal, createdAt: raw.createdAt } }
42
+ ? {
43
+ ok: true,
44
+ record: {
45
+ proposal: read.proposal,
46
+ createdAt: raw.createdAt,
47
+ ...(typeof raw.createdBy === "string" ? { createdBy: raw.createdBy } : {}),
48
+ },
49
+ }
43
50
  : read;
44
51
  }
45
52
 
@@ -71,7 +78,7 @@ export function proposalsPort(
71
78
  }
72
79
  return items;
73
80
  },
74
- create: (raw) =>
81
+ create: (raw, createdBy) =>
75
82
  queued("proposals", async () => {
76
83
  const read = readProposal(raw);
77
84
  if (!read.ok) return read;
@@ -114,7 +121,11 @@ export function proposalsPort(
114
121
  const rechecked = applyProposal(latest, read.proposal);
115
122
  if (!rechecked.ok) return rechecked;
116
123
  const id = crypto.randomUUID().replaceAll("-", "").slice(0, 16);
117
- const record = { proposal: read.proposal, createdAt: new Date().toISOString() };
124
+ const record: ProposalRecord = {
125
+ proposal: read.proposal,
126
+ createdAt: new Date().toISOString(),
127
+ ...(createdBy ? { createdBy } : {}),
128
+ };
118
129
  await store.put(id, record);
119
130
  return { ok: true, id, record };
120
131
  }),
@@ -191,7 +202,8 @@ const CreateInput = z.strictObject({ proposal: z.unknown() });
191
202
  export const proposalCreateRoute: PluginRoute<z.infer<typeof CreateInput>> = {
192
203
  permission: "content:edit_any",
193
204
  input: CreateInput,
194
- handler: async (ctx) => unwrap(await proposalPortOf(ctx).create(ctx.input.proposal)),
205
+ handler: async (ctx) =>
206
+ unwrap(await proposalPortOf(ctx).create(ctx.input.proposal, ctx.user?.id ?? null)),
195
207
  };
196
208
  const WithdrawInput = IdInput.extend({
197
209
  /** W-933: the person's review, when the editor closes a proposal it decided. */
@@ -5,12 +5,17 @@ import { ProposalTarget } from "../core/proposals.ts";
5
5
  import { isRecord } from "../core/record.ts";
6
6
  import type { AgentRequest, RequestsPort } from "../mcp/ports.ts";
7
7
  import { queued } from "../mcp/queue.ts";
8
+ import { isEmvbTarget } from "./targets.ts";
8
9
 
9
10
  /**
10
11
  * W-931 prompt relay (D-063: bring-your-own agent). A person writes a request in the editor's
11
12
  * Agent tab; their own agent reads it with get_requests and answers with propose_changes. Nothing
12
13
  * here calls a model or holds a key. Requests are the person's words for their agent: they are
13
14
  * shown back as plain text and never reach a page.
15
+ *
16
+ * W-990 (S-01): a request is private to its author. Only an agent signed in as that person (its
17
+ * token) reads it, answers it or sees it listed; a row without an author goes to nobody. Any
18
+ * editor's text reached whoever ran `emvb-mcp watch` before, as if they had written it.
14
19
  */
15
20
 
16
21
  const COLLECTION = "emvb_requests";
@@ -18,12 +23,19 @@ const ID = /^[0-9a-f]{16}$/;
18
23
  /** Requests older than this are no longer offered to agents. */
19
24
  const REQUEST_TTL_MS = 24 * 3_600_000;
20
25
  const SEEN_KEY = "relay:seen";
26
+ /** S-09 (W-998): open requests one person may have across the site. */
27
+ const MAX_OPEN_REQUESTS_PER_USER = 20;
28
+ /** Expired requests deleted per new request. */
29
+ const PURGE_BATCH = 50;
30
+ /** EmDash's admin role: may cancel anyone's request. */
31
+ const ADMIN_ROLE = 50;
21
32
 
22
33
  type Target = z.infer<typeof ProposalTarget>;
23
34
  type Stored = {
24
35
  target: Target;
25
36
  prompt: string;
26
37
  createdAt: string;
38
+ /** The author; a row without one (written before W-990 by a signed-out call) goes to nobody. */
27
39
  userId: string | null;
28
40
  status: "open" | "answered";
29
41
  proposalId?: string;
@@ -74,6 +86,7 @@ const nextCreatedAt = (nowMs: number) => {
74
86
  };
75
87
 
76
88
  const sameTarget = (a: Target, b: Target) => a.collection === b.collection && a.id === b.id;
89
+ const ownedBy = (s: Stored, userId: string | null) => userId !== null && s.userId === userId;
77
90
 
78
91
  /** Same per-isolate write queue pattern as proposals; `now` is injectable for tests. */
79
92
  export function requestsPort(store: Store, kv: Kv, now: () => number = Date.now): RequestsPort {
@@ -88,14 +101,14 @@ export function requestsPort(store: Store, kv: Kv, now: () => number = Date.now)
88
101
  };
89
102
  const live = (s: Stored) => now() - Date.parse(s.createdAt) < REQUEST_TTL_MS;
90
103
  return {
91
- async list(target) {
104
+ async list(target, userId) {
92
105
  return (await all())
93
- .filter((r) => sameTarget(r.stored.target, target))
106
+ .filter((r) => ownedBy(r.stored, userId) && sameTarget(r.stored.target, target))
94
107
  .map((r) => toRequest(r.id, r.stored));
95
108
  },
96
- async open(target) {
109
+ async open(userId, target) {
97
110
  return (await all())
98
- .filter((r) => r.stored.status === "open" && live(r.stored))
111
+ .filter((r) => r.stored.status === "open" && live(r.stored) && ownedBy(r.stored, userId))
99
112
  .filter((r) => !target || sameTarget(r.stored.target, target))
100
113
  .map((r) => toRequest(r.id, r.stored))
101
114
  .toSorted((a, b) => a.createdAt.localeCompare(b.createdAt));
@@ -109,9 +122,26 @@ export function requestsPort(store: Store, kv: Kv, now: () => number = Date.now)
109
122
  ok: false as const,
110
123
  reason: `Keep a request under ${MAX_REQUEST_PROMPT} characters.`,
111
124
  };
112
- const open = (await all()).filter(
125
+ if (userId === null)
126
+ return { ok: false as const, reason: "Sign in to write a request for your agent." };
127
+ const rows = await all();
128
+ // S-09 (W-998): expired requests are deleted as new ones come in, a few at a time.
129
+ const expired = rows.filter((r) => !live(r.stored)).slice(0, PURGE_BATCH);
130
+ await Promise.all(expired.map((r) => store.delete(r.id)));
131
+ const mine = rows.filter(
132
+ (r) => r.stored.status === "open" && live(r.stored) && ownedBy(r.stored, userId),
133
+ );
134
+ if (mine.length >= MAX_OPEN_REQUESTS_PER_USER)
135
+ return {
136
+ ok: false as const,
137
+ reason: `You already have ${MAX_OPEN_REQUESTS_PER_USER} requests waiting. Cancel one or wait for answers.`,
138
+ };
139
+ const open = rows.filter(
113
140
  (r) =>
114
- r.stored.status === "open" && live(r.stored) && sameTarget(r.stored.target, target),
141
+ r.stored.status === "open" &&
142
+ live(r.stored) &&
143
+ ownedBy(r.stored, userId) &&
144
+ sameTarget(r.stored.target, target),
115
145
  );
116
146
  if (open.length >= MAX_OPEN_REQUESTS_PER_PAGE)
117
147
  return {
@@ -129,12 +159,25 @@ export function requestsPort(store: Store, kv: Kv, now: () => number = Date.now)
129
159
  await store.put(id, stored);
130
160
  return { ok: true as const, request: toRequest(id, stored) };
131
161
  }),
132
- cancel: (id) => queued("requests", async () => ID.test(id) && (await store.delete(id))),
133
- answer: (id, target, proposalId) =>
162
+ cancel: (id, userId, isAdmin) =>
163
+ queued("requests", async () => {
164
+ if (!ID.test(id)) return false;
165
+ const stored = read(await store.get(id));
166
+ // S-01: the author or an admin; anyone else sees no such request.
167
+ if (!stored || !(isAdmin || ownedBy(stored, userId))) return false;
168
+ return store.delete(id);
169
+ }),
170
+ answer: (id, target, proposalId, userId) =>
134
171
  queued("requests", async () => {
135
172
  if (!ID.test(id)) return false;
136
173
  const stored = read(await store.get(id));
137
- if (!stored || stored.status !== "open" || !sameTarget(stored.target, target)) return false;
174
+ if (
175
+ !stored ||
176
+ stored.status !== "open" ||
177
+ !ownedBy(stored, userId) ||
178
+ !sameTarget(stored.target, target)
179
+ )
180
+ return false;
138
181
  await store.put(id, {
139
182
  ...stored,
140
183
  status: "answered",
@@ -162,7 +205,10 @@ export const requestsRoute: PluginRoute<z.infer<typeof ProposalTarget>> = {
162
205
  input: ProposalTarget,
163
206
  handler: async (ctx) => {
164
207
  const port = requestsPortOf(ctx);
165
- return { items: await port.list(ctx.input), agentSeenAt: await port.lastSeen() };
208
+ return {
209
+ items: await port.list(ctx.input, ctx.user?.id ?? null),
210
+ agentSeenAt: await port.lastSeen(),
211
+ };
166
212
  },
167
213
  };
168
214
 
@@ -174,6 +220,8 @@ export const requestCreateRoute: PluginRoute<z.infer<typeof CreateInput>> = {
174
220
  permission: "content:edit_any",
175
221
  input: CreateInput,
176
222
  handler: async (ctx) => {
223
+ if (!(await isEmvbTarget(ctx, ctx.input.target)))
224
+ throw new PluginRouteError("NOT_FOUND", "No such page.", 404);
177
225
  const made = await requestsPortOf(ctx).create(
178
226
  ctx.input.target,
179
227
  ctx.input.prompt,
@@ -189,7 +237,8 @@ export const requestCancelRoute: PluginRoute<z.infer<typeof IdInput>> = {
189
237
  permission: "content:edit_any",
190
238
  input: IdInput,
191
239
  handler: async (ctx) => {
192
- if (!(await requestsPortOf(ctx).cancel(ctx.input.id)))
240
+ const isAdmin = Number(ctx.user?.role ?? 0) >= ADMIN_ROLE;
241
+ if (!(await requestsPortOf(ctx).cancel(ctx.input.id, ctx.user?.id ?? null, isAdmin)))
193
242
  throw new PluginRouteError("NOT_FOUND", "No such request.", 404);
194
243
  return { id: ctx.input.id };
195
244
  },
@@ -0,0 +1,13 @@
1
+ /**
2
+ * S-05 (W-995): the site's own origin from its configuration (EmDash's site URL setting), never
3
+ * from the request: the Host header is the caller's to choose. Undefined when none is set.
4
+ */
5
+ export function trustedOrigin(siteUrl: unknown): string | undefined {
6
+ if (typeof siteUrl !== "string" || !siteUrl) return undefined;
7
+ try {
8
+ const url = new URL(siteUrl);
9
+ return url.protocol === "https:" || url.protocol === "http:" ? url.origin : undefined;
10
+ } catch {
11
+ return undefined;
12
+ }
13
+ }
@@ -0,0 +1,26 @@
1
+ import type { PluginContext, RouteContext } from "emdash";
2
+ import type { z } from "zod";
3
+ import { PAGES_COLLECTION, THEME_PARTS_COLLECTION } from "../constants.ts";
4
+ import type { ProposalTarget } from "../core/proposals.ts";
5
+ import { canvasFieldSlugs } from "./hooks.ts";
6
+
7
+ /**
8
+ * S-09 (W-998): a request or an editor presence may name only an entry that exists in an EmVB
9
+ * collection or in a collection with an emvb:canvas field. Routes took any slug and id, so junk
10
+ * targets filled storage and hid real requests.
11
+ */
12
+ export async function isEmvbTarget(
13
+ ctx: RouteContext<unknown>,
14
+ target: z.infer<typeof ProposalTarget>,
15
+ ): Promise<boolean> {
16
+ const owned =
17
+ target.collection === PAGES_COLLECTION || target.collection === THEME_PARTS_COLLECTION;
18
+ if (!owned) {
19
+ const slugs = await canvasFieldSlugs(ctx as unknown as PluginContext, target.collection).catch(
20
+ () => [],
21
+ );
22
+ if (slugs.length === 0) return false;
23
+ }
24
+ const found = await ctx.content?.get(target.collection, target.id).catch(() => null);
25
+ return Boolean(found);
26
+ }