@capybara-hq/plugin-sdk 0.1.0-rc.2 → 0.1.0-rc.20

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 (104) hide show
  1. package/README.md +1 -1
  2. package/agent-docs/agent-templates.md +59 -0
  3. package/agent-docs/concepts.md +63 -0
  4. package/agent-docs/connector-templates.md +48 -0
  5. package/agent-docs/extension-points/channel.md +15 -0
  6. package/agent-docs/extension-points/config-source.md +15 -0
  7. package/agent-docs/extension-points/connector.md +15 -0
  8. package/agent-docs/extension-points/context.md +15 -0
  9. package/agent-docs/extension-points/counter.md +15 -0
  10. package/agent-docs/extension-points/directory.md +15 -0
  11. package/agent-docs/extension-points/file-preview.md +15 -0
  12. package/agent-docs/extension-points/identity-source.md +15 -0
  13. package/agent-docs/extension-points/model-provider.md +15 -0
  14. package/agent-docs/extension-points/object-store.md +15 -0
  15. package/agent-docs/extension-points/sandbox.md +15 -0
  16. package/agent-docs/extension-points/secret-store.md +15 -0
  17. package/agent-docs/extension-points/web-fetch.md +15 -0
  18. package/agent-docs/extension-points/web-search.md +15 -0
  19. package/agent-docs/extensions.md +88 -0
  20. package/agent-docs/plugin-format.md +100 -0
  21. package/agent-docs/setup.md +46 -0
  22. package/agent-docs/skills.md +44 -0
  23. package/agent-docs/tool-naming.md +21 -0
  24. package/dist/agent-template.d.ts +96 -2
  25. package/dist/agent-template.js +381 -3
  26. package/dist/bootstrap.d.ts +15 -1
  27. package/dist/bootstrap.js +17 -1
  28. package/dist/cards.d.ts +39 -5
  29. package/dist/cards.js +70 -11
  30. package/dist/channel.d.ts +20 -1
  31. package/dist/client-css.d.ts +36 -0
  32. package/dist/client-css.js +326 -0
  33. package/dist/client-section.d.ts +35 -0
  34. package/dist/client-section.js +133 -0
  35. package/dist/config-ui.d.ts +24 -1
  36. package/dist/config-ui.js +89 -11
  37. package/dist/connector-auth.d.ts +2 -0
  38. package/dist/connector-auth.js +15 -0
  39. package/dist/context.d.ts +40 -0
  40. package/dist/context.js +2 -0
  41. package/dist/ctx.d.ts +86 -4
  42. package/dist/define-extension.d.ts +5 -1
  43. package/dist/define-extension.js +1 -0
  44. package/dist/dev-hosts.d.ts +6 -0
  45. package/dist/dev-hosts.js +48 -0
  46. package/dist/device-protocol.d.ts +260 -0
  47. package/dist/device-protocol.js +496 -0
  48. package/dist/directory.d.ts +11 -2
  49. package/dist/extension-point.d.ts +6 -0
  50. package/dist/extension-point.js +19 -14
  51. package/dist/file-preview.d.ts +9 -1
  52. package/dist/hooks.d.ts +111 -15
  53. package/dist/hooks.js +5 -0
  54. package/dist/index.d.ts +18 -1
  55. package/dist/index.js +18 -1
  56. package/dist/marketplace.d.ts +55 -2
  57. package/dist/marketplace.js +73 -3
  58. package/dist/model.d.ts +60 -2
  59. package/dist/model.js +22 -0
  60. package/dist/org-access.d.ts +27 -0
  61. package/dist/org-access.js +35 -0
  62. package/dist/permissions.d.ts +33 -8
  63. package/dist/permissions.js +89 -22
  64. package/dist/plugin-manifest.d.ts +60 -7
  65. package/dist/plugin-manifest.js +178 -7
  66. package/dist/sandbox.d.ts +239 -62
  67. package/dist/sandbox.js +99 -14
  68. package/dist/setup-check.d.ts +115 -0
  69. package/dist/setup-check.js +142 -0
  70. package/dist/setup-guide-parse.d.ts +121 -0
  71. package/dist/setup-guide-parse.js +350 -0
  72. package/dist/setup-guide-render.d.ts +45 -0
  73. package/dist/setup-guide-render.js +351 -0
  74. package/dist/setup-guide.d.ts +94 -0
  75. package/dist/setup-guide.js +336 -0
  76. package/dist/skill-invocation.d.ts +9 -5
  77. package/dist/skill-invocation.js +18 -8
  78. package/dist/skill.d.ts +23 -3
  79. package/dist/skill.js +31 -6
  80. package/dist/theme-assets.d.ts +39 -0
  81. package/dist/theme-assets.js +449 -0
  82. package/dist/theme-readability.d.ts +37 -0
  83. package/dist/theme-readability.js +145 -0
  84. package/dist/theme-tokens.generated.d.ts +275 -0
  85. package/dist/theme-tokens.generated.js +172 -0
  86. package/dist/theme.d.ts +152 -0
  87. package/dist/theme.js +392 -0
  88. package/dist/tool.d.ts +26 -3
  89. package/dist/tool.js +8 -0
  90. package/dist/ui-parts.d.ts +23 -0
  91. package/dist/ui-parts.js +337 -0
  92. package/dist/ui-resolve.d.ts +40 -0
  93. package/dist/ui-resolve.js +54 -0
  94. package/dist/ui-slots.d.ts +55 -0
  95. package/dist/ui-slots.js +247 -0
  96. package/dist/ui.d.ts +143 -37
  97. package/dist/ui.js +65 -5
  98. package/dist/web.d.ts +30 -5
  99. package/package.json +10 -2
  100. package/schemas/bootstrap.v1.schema.json +6 -0
  101. package/schemas/connector-template.v1.schema.json +3 -0
  102. package/schemas/marketplace.v1.schema.json +50 -0
  103. package/schemas/plugin.v1.schema.json +144 -7
  104. package/schemas/theme.v1.schema.json +225 -0
package/dist/cards.d.ts CHANGED
@@ -10,10 +10,25 @@ export type ChannelCard = {
10
10
  toolName: string;
11
11
  appName?: string;
12
12
  agentName: string;
13
+ /**
14
+ * One line saying what the call does, as the web shows it: the tool's confirmation summary
15
+ * (e.g. a Platform operation's), else the tool's title and key argument; may be empty.
16
+ * Never the raw call input (it may hold a whole prompt, and a group sees the card); the
17
+ * full input is behind `webUrl`. Plain text written by the kernel from model-controlled
18
+ * values: render it as text, never as markup. The name is kept from when it held the input.
19
+ */
13
20
  inputPreview: string;
14
21
  scopes: ("once" | "session" | "always")[];
22
+ /**
23
+ * The kernel's names for the scopes when they mean something other than the default (a
24
+ * network ask: `once` = "Allow this time", `always` = "Always allow on this device"). Plain
25
+ * text, 1 to 40 characters; a channel that does not know the field renders its default
26
+ * scope labels. Kernel-written, never model-controlled.
27
+ */
28
+ scopeLabels?: Partial<Record<"once" | "session" | "always", string>>;
15
29
  expiresAt: string;
16
- state: "pending" | "approved" | "denied" | "expired" | "cancelled";
30
+ /** `skipped`: the person sent a message instead of deciding (the run went on with it). */
31
+ state: "pending" | "approved" | "denied" | "expired" | "cancelled" | "skipped";
17
32
  decidedBy?: string;
18
33
  /** A denied approval: the reason the person gave (plain text, never formatted). */
19
34
  denyReason?: string;
@@ -23,9 +38,17 @@ export type ChannelCard = {
23
38
  kind: "question";
24
39
  id: string;
25
40
  form: InputForm;
26
- state: "pending" | "answered" | "expired" | "cancelled";
41
+ /** `skipped`: the person sent a message instead of answering (the run went on with it). */
42
+ state: "pending" | "answered" | "skipped" | "expired" | "cancelled";
27
43
  answerSummary?: string;
28
44
  webUrl: string;
45
+ /**
46
+ * The person may answer by replying with text instead (pending cards only): `plain` in a DM
47
+ * (any reply reaches the agent), `mention` in a group thread (the reply must mention the bot;
48
+ * the kernel ignores group messages without it). Absent: only the card's own controls work
49
+ * (a sub-agent's question). Render the hint with {@link questionTextReplyHint}.
50
+ */
51
+ textReply?: "plain" | "mention";
29
52
  } | {
30
53
  kind: "connect";
31
54
  appName: string;
@@ -49,14 +72,25 @@ export interface OutboundMessage {
49
72
  cards?: ChannelCard[];
50
73
  }
51
74
  /**
52
- * 提问能否在 IM 内直接作答:仅当表单恰有一个枚举字段(单选 ≤ 5 项 / 多选 ≤ 10 项)且不允许「其他」时为真;
53
- * 否则卡片只给网页链接。
75
+ * Whether IM can draw the question's controls: exactly one enum field (single choice ≤ 5 options /
76
+ * multi-select ≤ 10). A field with `allowOther` qualifies only when the card has `textReply`
77
+ * (pass `{ textReply: card.textReply !== undefined }`): the Other path is then a plain reply, so
78
+ * never draw an Other button. Otherwise the card only links to the web.
54
79
  */
55
- export declare function questionRenderableInline(form: InputForm): boolean;
80
+ export declare function questionRenderableInline(form: InputForm, opts?: {
81
+ textReply?: boolean;
82
+ }): boolean;
56
83
  /** 校验卡片结构,返回问题列表(空 = 合法)。 */
57
84
  export declare function validateChannelCard(card: unknown): string[];
58
85
  /** A UI locale. */
59
86
  export type Locale = "zh" | "en";
87
+ /** The hint line of a pending question card with `textReply`, as {@link renderCardAsText} writes it. */
88
+ export declare function questionTextReplyHint(mode: "plain" | "mention", locale: Locale): string;
89
+ /**
90
+ * The label of a question card's state, as {@link renderCardAsText} writes it. A state this SDK
91
+ * does not know (a newer kernel) returns the state itself, never `undefined`.
92
+ */
93
+ export declare function questionStateLabel(state: string, locale: Locale): string;
60
94
  /**
61
95
  * 不支持卡片的渠道的统一退回文本(含链接);固定话术按 locale 取 zh / en。结果是 Markdown(放进
62
96
  * `OutboundMessage.text`,由渠道插件转换):模型可控的字段放在代码里(见 `asCode`),不会产生链接。
package/dist/cards.js CHANGED
@@ -3,14 +3,16 @@ import { isHttpUrl } from "./url.js";
3
3
  const MAX_INLINE_SINGLE = 5;
4
4
  const MAX_INLINE_MULTI = 10;
5
5
  /**
6
- * 提问能否在 IM 内直接作答:仅当表单恰有一个枚举字段(单选 ≤ 5 项 / 多选 ≤ 10 项)且不允许「其他」时为真;
7
- * 否则卡片只给网页链接。
6
+ * Whether IM can draw the question's controls: exactly one enum field (single choice ≤ 5 options /
7
+ * multi-select ≤ 10). A field with `allowOther` qualifies only when the card has `textReply`
8
+ * (pass `{ textReply: card.textReply !== undefined }`): the Other path is then a plain reply, so
9
+ * never draw an Other button. Otherwise the card only links to the web.
8
10
  */
9
- export function questionRenderableInline(form) {
11
+ export function questionRenderableInline(form, opts) {
10
12
  if (form.fields.length !== 1)
11
13
  return false;
12
14
  const f = form.fields[0];
13
- if (!f || f.allowOther)
15
+ if (!f || (f.allowOther && opts?.textReply !== true))
14
16
  return false;
15
17
  if (f.schema.type !== "string" || !("enum" in f.schema))
16
18
  return false;
@@ -19,8 +21,17 @@ export function questionRenderableInline(form) {
19
21
  }
20
22
  const KINDS = ["approval", "question", "connect", "bind"];
21
23
  const SCOPES = ["once", "session", "always"];
22
- const APPROVAL_STATES = ["pending", "approved", "denied", "expired", "cancelled"];
23
- const QUESTION_STATES = ["pending", "answered", "expired", "cancelled"];
24
+ const APPROVAL_STATES = [
25
+ "pending",
26
+ "approved",
27
+ "denied",
28
+ "expired",
29
+ "cancelled",
30
+ "skipped",
31
+ ];
32
+ const MAX_SCOPE_LABEL = 40;
33
+ const QUESTION_STATES = ["pending", "answered", "skipped", "expired", "cancelled"];
34
+ const TEXT_REPLY = ["plain", "mention"];
24
35
  const ISO_8601 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
25
36
  const list = (xs) => xs.map((x) => JSON.stringify(x)).join(", ");
26
37
  /** 校验卡片结构,返回问题列表(空 = 合法)。 */
@@ -58,6 +69,16 @@ export function validateChannelCard(card) {
58
69
  new Set(s).size !== s.length ||
59
70
  s.some((x) => !SCOPES.includes(x)))
60
71
  out.push(`scopes must be a non-empty array of ${list(SCOPES)} without duplicates`);
72
+ const labels = c.scopeLabels;
73
+ if (labels !== undefined &&
74
+ (typeof labels !== "object" ||
75
+ labels === null ||
76
+ Array.isArray(labels) ||
77
+ Object.entries(labels).some(([k, v]) => !SCOPES.includes(k) ||
78
+ typeof v !== "string" ||
79
+ v.length === 0 ||
80
+ v.length > MAX_SCOPE_LABEL)))
81
+ out.push(`scopeLabels must map ${list(SCOPES)} to strings of 1 to ${MAX_SCOPE_LABEL} characters`);
61
82
  if (typeof c.expiresAt !== "string" ||
62
83
  !ISO_8601.test(c.expiresAt) ||
63
84
  Number.isNaN(Date.parse(c.expiresAt)))
@@ -74,6 +95,8 @@ export function validateChannelCard(card) {
74
95
  url("webUrl");
75
96
  if (c.answerSummary !== undefined && typeof c.answerSummary !== "string")
76
97
  out.push("answerSummary must be a string");
98
+ if (c.textReply !== undefined)
99
+ oneOf("textReply", TEXT_REPLY);
77
100
  // 不能在 IM 内作答的表单(见 questionRenderableInline)同样合法:渠道只渲染网页链接。
78
101
  for (const p of validateInputForm(c.form))
79
102
  out.push(`form: ${p}`);
@@ -92,7 +115,7 @@ export function validateChannelCard(card) {
92
115
  }
93
116
  }
94
117
  /**
95
- * 把模型可控的值(审批标题、输入预览、提问标题、回答摘要)放进代码里,退回文本里它们不会变成链接、强调或 HTML:
118
+ * 把模型可控的值(审批标题、调用摘要、提问标题、回答摘要)放进代码里,退回文本里它们不会变成链接、强调或 HTML:
96
119
  * 单行用行内代码,多行用围栏代码块(以换行开头),分隔符都比值里最长的反引号串更长(CommonMark 6.1 / 4.5)。
97
120
  * 选代码而不是给标点加反斜杠:代码是 CommonMark / GFM 里唯一保证内容按原样显示的写法(反斜杠挡不住 GFM 的裸网址
98
121
  * 自动链接,各渠道转换器对反斜杠的处理也不一致)。
@@ -119,7 +142,7 @@ const TEXT = {
119
142
  connect: (app) => `[Connect] ${app} needs to be connected.`,
120
143
  tool: "Tool",
121
144
  agent: "Agent",
122
- input: "Input",
145
+ summary: "Summary",
123
146
  status: "Status",
124
147
  reason: "Reason",
125
148
  expires: "Expires",
@@ -128,19 +151,27 @@ const TEXT = {
128
151
  answerOnWeb: "Answer on the web",
129
152
  details: "Details",
130
153
  connectLink: "Connect",
154
+ options: "Options",
155
+ scopes: { once: "Once", session: "This session", always: "Always" },
131
156
  approvalStates: {
132
157
  pending: "Pending",
133
158
  approved: "Approved",
134
159
  denied: "Denied",
135
160
  expired: "Expired",
136
161
  cancelled: "Cancelled",
162
+ skipped: "Skipped",
137
163
  },
138
164
  questionStates: {
139
165
  pending: "Pending",
140
166
  answered: "Answered",
167
+ skipped: "Skipped (replied instead)",
141
168
  expired: "Expired",
142
169
  cancelled: "Cancelled",
143
170
  },
171
+ textReply: {
172
+ plain: "You can also just reply with text",
173
+ mention: "You can also reply in this thread, mentioning me",
174
+ },
144
175
  },
145
176
  zh: {
146
177
  sep: ":",
@@ -149,7 +180,7 @@ const TEXT = {
149
180
  connect: (app) => `【连接】需要连接 ${app}。`,
150
181
  tool: "工具",
151
182
  agent: "Agent",
152
- input: "输入",
183
+ summary: "摘要",
153
184
  status: "状态",
154
185
  reason: "原因",
155
186
  expires: "过期时间",
@@ -158,21 +189,41 @@ const TEXT = {
158
189
  answerOnWeb: "到网页上回答",
159
190
  details: "详情",
160
191
  connectLink: "连接",
192
+ options: "选项",
193
+ scopes: { once: "这次", session: "本会话", always: "一直" },
161
194
  approvalStates: {
162
195
  pending: "待审批",
163
196
  approved: "已批准",
164
197
  denied: "已拒绝",
165
198
  expired: "已过期",
166
199
  cancelled: "已取消",
200
+ skipped: "已跳过",
167
201
  },
168
202
  questionStates: {
169
203
  pending: "待回答",
170
204
  answered: "已回答",
205
+ skipped: "已跳过(已直接回复)",
171
206
  expired: "已过期",
172
207
  cancelled: "已取消",
173
208
  },
209
+ textReply: {
210
+ plain: "也可以直接回复文字",
211
+ mention: "也可以在本话题 @我 回复文字",
212
+ },
174
213
  },
175
214
  };
215
+ /** The hint line of a pending question card with `textReply`, as {@link renderCardAsText} writes it. */
216
+ export function questionTextReplyHint(mode, locale) {
217
+ return (TEXT[locale] ?? TEXT.en).textReply[mode];
218
+ }
219
+ /**
220
+ * The label of a question card's state, as {@link renderCardAsText} writes it. A state this SDK
221
+ * does not know (a newer kernel) returns the state itself, never `undefined`.
222
+ */
223
+ export function questionStateLabel(state, locale) {
224
+ const states = (TEXT[locale] ?? TEXT.en).questionStates;
225
+ return states[state] ?? state;
226
+ }
176
227
  /**
177
228
  * 不支持卡片的渠道的统一退回文本(含链接);固定话术按 locale 取 zh / en。结果是 Markdown(放进
178
229
  * `OutboundMessage.text`,由渠道插件转换):模型可控的字段放在代码里(见 `asCode`),不会产生链接。
@@ -187,11 +238,17 @@ export function renderCardAsText(card, locale) {
187
238
  withCode(t.approval, asCode(card.title)),
188
239
  line(t.tool, card.appName ? `${card.appName} / ${card.toolName}` : card.toolName),
189
240
  line(t.agent, card.agentName),
190
- line(t.input, asCode(card.inputPreview)),
241
+ ...(card.inputPreview !== "" ? [line(t.summary, asCode(card.inputPreview))] : []),
191
242
  line(t.status, card.decidedBy ? `${state} (${card.decidedBy})` : state),
192
243
  ];
193
244
  if (card.state === "denied" && card.denyReason)
194
245
  lines.push(line(t.reason, asCode(card.denyReason)));
246
+ // the scopes are listed only when the kernel named them (a network ask): the default
247
+ // approval text stays as it was
248
+ if (card.state === "pending" && card.scopeLabels) {
249
+ const labels = card.scopes.map((s) => card.scopeLabels?.[s] ?? t.scopes[s]);
250
+ lines.push(line(t.options, labels.join(" / ")));
251
+ }
195
252
  if (card.state === "pending")
196
253
  lines.push(line(t.expires, card.expiresAt), line(t.approveOnWeb, card.webUrl));
197
254
  else
@@ -202,11 +259,13 @@ export function renderCardAsText(card, locale) {
202
259
  const title = typeof card.form.title === "string" ? card.form.title : card.form.title[locale];
203
260
  const lines = [
204
261
  withCode(t.question, asCode(title)),
205
- line(t.status, t.questionStates[card.state]),
262
+ line(t.status, questionStateLabel(card.state, locale)),
206
263
  ];
207
264
  if (card.answerSummary)
208
265
  lines.push(line(t.answer, asCode(card.answerSummary)));
209
266
  lines.push(line(card.state === "pending" ? t.answerOnWeb : t.details, card.webUrl));
267
+ if (card.state === "pending" && card.textReply !== undefined)
268
+ lines.push(questionTextReplyHint(card.textReply, locale));
210
269
  return lines.join("\n");
211
270
  }
212
271
  case "connect":
package/dist/channel.d.ts CHANGED
@@ -21,6 +21,21 @@ export interface InboundSender {
21
21
  tenantId: string;
22
22
  displayName?: string;
23
23
  avatarUrl?: string;
24
+ /**
25
+ * The sender's time zone on the platform, an IANA name (`Asia/Shanghai`; Slack `users.info`
26
+ * `user.tz`), when the platform gives one. Include it on `message` events when you can get it
27
+ * within the acknowledgement deadline (cache it per user); leave it out otherwise. It wins over
28
+ * the person's account setting and the org default for the run's date and zone (run context
29
+ * spec §3.4); a name the kernel does not know is ignored.
30
+ */
31
+ timeZone?: string;
32
+ /**
33
+ * The sender's language on the platform: `zh` / `en` or a BCP 47 tag (`zh-CN`, `en-US`; Slack
34
+ * `users.info` with `include_locale=true`, `user.locale`), when the platform gives one. The
35
+ * kernel normalizes it (`zh` and `zh-*` are Chinese, any other tag English); it wins over the
36
+ * person's latest web UI language and the org default (run context spec §3.4).
37
+ */
38
+ locale?: string;
24
39
  }
25
40
  /**
26
41
  * 渠道交给内核的入站事件。插件的约定:
@@ -76,7 +91,11 @@ export interface ChannelSendArgs {
76
91
  */
77
92
  message: OutboundMessage;
78
93
  signal: AbortSignal;
79
- /** 连接所属组织的界面语言:插件自己渲染的文案(卡片按钮、降级文本里的固定词)按它选择。 */
94
+ /**
95
+ * The recipient's language (the sender's platform language, else their latest web language,
96
+ * else the org's): the wording the extension renders itself (card buttons, fixed words in the
97
+ * text fallback) follows it.
98
+ */
80
99
  locale: Locale;
81
100
  /**
82
101
  * 幂等键(可选):不超过 40 个 `[A-Za-z0-9_-]` 字符,同一条逻辑消息的每次重试(崩溃后其他副本续投、
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The client stylesheet rule (client extensions spec §4.1, §7.2): one function both sides run, so
3
+ * a stylesheet that packs cleanly imports cleanly. `capybara-plugin pack` wraps every file in
4
+ * `@layer extensions { … }` ({@link wrapClientCss}) and checks the wrapped text; the kernel checks
5
+ * the stored bytes again at import, because a tgz can be written by hand. A file must be one
6
+ * `@layer extensions` block, may not `@import`, and a URL may name only an asset of the plugin
7
+ * (`../assets/<path>`, a file of `client.assets`), a `data:` URL or a `#fragment`. Any other URL,
8
+ * relative ones included, is refused: the stylesheet is served from
9
+ * `/api/v1/client/<plugin>/<build>/styles/`, so `../../../../…` would reach the kernel's own
10
+ * routes with the viewer's cookies.
11
+ *
12
+ * Two passes, both must pass:
13
+ * - a plain-text pass over the escape-decoded file (`cssRemoteProblem`);
14
+ * - a tokenizer that follows the CSS Syntax tokenization (comments, strings, escapes, url tokens)
15
+ * closely enough that every brace it skips is one a browser skips too: the file must start with
16
+ * `@layer extensions {` and the block that opens must close at the file's last character, so no
17
+ * rule lands outside the layer. Every `url(…)` (token or string) is checked after decoding
18
+ * escapes, and an `@import` at-keyword is refused however it is spelled.
19
+ *
20
+ * Two rules close the spellings a plain string check would miss:
21
+ * - URLs are trimmed with CSS whitespace only (space, tab, LF, CR, FF), and a file holding any other
22
+ * whitespace, a zero-width character (U+200B-U+200D, U+2060) or U+FEFF anywhere, escaped or not,
23
+ * is refused: JavaScript's `trim()` strips an NBSP that CSS and the URL parser keep, so
24
+ * `url("\a0 data:/../../v1")` would pass as `data:` and resolve to `/api/v1`;
25
+ * - functions that turn a plain string (or a `var()`) into a URL or reach outside the stylesheet are
26
+ * refused outright: `image-set(var(--u) 1x)` takes its URL from a custom property no string check
27
+ * can see. Plugins write `url(../assets/x)` directly.
28
+ */
29
+ /** A stylesheet as the packer stores it: wrapped in `@layer extensions { … }` (spec §4.1). */
30
+ export declare function wrapClientCss(css: string): string;
31
+ /**
32
+ * The problem of a client stylesheet as stored (see the file header), or undefined when it is one
33
+ * `@layer extensions` block with no `@import` and every URL a `#fragment`, a `data:` URL or one of
34
+ * the plugin's `assets` (paths relative to `assets/`).
35
+ */
36
+ export declare function clientCssProblem(css: string, assets: ReadonlySet<string>): string | undefined;
@@ -0,0 +1,326 @@
1
+ /**
2
+ * The client stylesheet rule (client extensions spec §4.1, §7.2): one function both sides run, so
3
+ * a stylesheet that packs cleanly imports cleanly. `capybara-plugin pack` wraps every file in
4
+ * `@layer extensions { … }` ({@link wrapClientCss}) and checks the wrapped text; the kernel checks
5
+ * the stored bytes again at import, because a tgz can be written by hand. A file must be one
6
+ * `@layer extensions` block, may not `@import`, and a URL may name only an asset of the plugin
7
+ * (`../assets/<path>`, a file of `client.assets`), a `data:` URL or a `#fragment`. Any other URL,
8
+ * relative ones included, is refused: the stylesheet is served from
9
+ * `/api/v1/client/<plugin>/<build>/styles/`, so `../../../../…` would reach the kernel's own
10
+ * routes with the viewer's cookies.
11
+ *
12
+ * Two passes, both must pass:
13
+ * - a plain-text pass over the escape-decoded file (`cssRemoteProblem`);
14
+ * - a tokenizer that follows the CSS Syntax tokenization (comments, strings, escapes, url tokens)
15
+ * closely enough that every brace it skips is one a browser skips too: the file must start with
16
+ * `@layer extensions {` and the block that opens must close at the file's last character, so no
17
+ * rule lands outside the layer. Every `url(…)` (token or string) is checked after decoding
18
+ * escapes, and an `@import` at-keyword is refused however it is spelled.
19
+ *
20
+ * Two rules close the spellings a plain string check would miss:
21
+ * - URLs are trimmed with CSS whitespace only (space, tab, LF, CR, FF), and a file holding any other
22
+ * whitespace, a zero-width character (U+200B-U+200D, U+2060) or U+FEFF anywhere, escaped or not,
23
+ * is refused: JavaScript's `trim()` strips an NBSP that CSS and the URL parser keep, so
24
+ * `url("\a0 data:/../../v1")` would pass as `data:` and resolve to `/api/v1`;
25
+ * - functions that turn a plain string (or a `var()`) into a URL or reach outside the stylesheet are
26
+ * refused outright: `image-set(var(--u) 1x)` takes its URL from a custom property no string check
27
+ * can see. Plugins write `url(../assets/x)` directly.
28
+ */
29
+ /** A stylesheet as the packer stores it: wrapped in `@layer extensions { … }` (spec §4.1). */
30
+ export function wrapClientCss(css) {
31
+ return `@layer extensions {\n${css.trimEnd()}\n}\n`;
32
+ }
33
+ /** CSS whitespace (CSS Syntax §4.2): only these are trimmed from a URL. */
34
+ const CSS_SPACE = "[ \\t\\n\\r\\f]";
35
+ const CSS_TRIM = new RegExp(`^${CSS_SPACE}+|${CSS_SPACE}+$`, "g");
36
+ const cssTrim = (s) => s.replace(CSS_TRIM, "");
37
+ /** Whitespace other than CSS's, zero-width characters and U+FEFF: refused anywhere in a file. */
38
+ const INVISIBLE_RE = /[\u0085\u00a0\u1680\u180e\u2000-\u200d\u2028\u2029\u202f\u205f\u2060\u3000\ufeff]/;
39
+ const INVISIBLE_REFUSED = "the stylesheet contains non-ASCII whitespace, a zero-width character or U+FEFF; use plain spaces";
40
+ /**
41
+ * Functions refused in a client stylesheet (case-insensitive, escapes decoded): they take URLs from
42
+ * plain strings or `var()` (`image-set`, `cross-fade`, `src`, `image`), or reach outside it
43
+ * (`element`, `paint`).
44
+ */
45
+ const REFUSED_FUNCTIONS = new Set([
46
+ "image-set",
47
+ "-webkit-image-set",
48
+ "cross-fade",
49
+ "-webkit-cross-fade",
50
+ "element",
51
+ "-moz-element",
52
+ "paint",
53
+ "src",
54
+ "image",
55
+ ]);
56
+ const REFUSED_FUNCTION_RE = /(?<![A-Za-z0-9_-])(-webkit-image-set|image-set|-webkit-cross-fade|cross-fade|-moz-element|element|paint|src|image)\(/i;
57
+ const functionRefused = (name) => `${name}() is not allowed in a client stylesheet; use url(../assets/<file>) directly`;
58
+ /**
59
+ * The plain-text pass, escapes decoded first: no invisible characters (see the file header), no {@link REFUSED_FUNCTIONS}, no
60
+ * `@import`, and every `url()` is {@link cssUrlProblem}-free. `assets` are the plugin's asset paths
61
+ * relative to `assets/` (`a.png`, `fx/boot.ogg`). Returns the problem, or undefined.
62
+ */
63
+ function cssRemoteProblem(css, assets) {
64
+ const bare = css
65
+ .replace(/\/\*[\s\S]*?\*\//g, "")
66
+ .replace(/\\([0-9a-f]{1,6})[ \t\n]?|\\([^\n])/gi, (_m, hex, ch) => {
67
+ if (hex === undefined)
68
+ return ch ?? "";
69
+ const cp = Number.parseInt(hex, 16);
70
+ return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : "�";
71
+ });
72
+ if (INVISIBLE_RE.test(css) || INVISIBLE_RE.test(bare))
73
+ return INVISIBLE_REFUSED;
74
+ const fn = REFUSED_FUNCTION_RE.exec(bare);
75
+ if (fn !== null)
76
+ return functionRefused(fn[1].toLowerCase());
77
+ if (/@import\b/i.test(bare))
78
+ return IMPORT_REFUSED;
79
+ for (const m of bare.matchAll(/url\([ \t\n\r\f]*(["']?)([^)"']*)\1[ \t\n\r\f]*\)/gi)) {
80
+ const problem = cssUrlProblem(cssTrim(m[2] ?? ""), assets);
81
+ if (problem !== undefined)
82
+ return problem;
83
+ }
84
+ return undefined;
85
+ }
86
+ const IMPORT_REFUSED = "@import is not allowed (a remote stylesheet is not integrity-pinned); inline the rules";
87
+ /** How a stylesheet names one of the plugin's assets (it is served from `styles/`). */
88
+ const ASSETS_URL = "../assets/";
89
+ /**
90
+ * The problem of one URL of a stylesheet (escapes decoded, CSS whitespace trimmed), or undefined
91
+ * when it is a `#fragment`, a `data:` URL or `../assets/<path>` naming one of `assets` exactly.
92
+ */
93
+ function cssUrlProblem(u, assets) {
94
+ if (u.startsWith("#") || /^data:/i.test(u))
95
+ return undefined;
96
+ if (u.startsWith(ASSETS_URL) && assets.has(u.slice(ASSETS_URL.length)))
97
+ return undefined;
98
+ return `url(${u}) is not allowed; use ../assets/<a file of client/assets>, a data: URL or a #fragment`;
99
+ }
100
+ const WRAP_RE = /^@layer extensions \{/;
101
+ const isNewline = (c) => c === "\n" || c === "\r" || c === "\f";
102
+ const isWhitespace = (c) => c === " " || c === "\t" || isNewline(c);
103
+ const isHex = (c) => c !== undefined && /^[0-9a-f]$/i.test(c);
104
+ /** A name code point (CSS Syntax §4.2): letters, digits, `-`, `_`, anything non-ASCII. */
105
+ const isNameChar = (c) => c !== undefined && (/^[A-Za-z0-9_-]$/.test(c) || c.codePointAt(0) >= 0x80);
106
+ class CssProblem extends Error {
107
+ }
108
+ /** Tokenizes `css` from `start`; see the file header. */
109
+ class Scanner {
110
+ css;
111
+ assets;
112
+ i;
113
+ /** Open `{` blocks; the layer block is the first. */
114
+ depth = 1;
115
+ /** Open function / parenthesis names ("" for a plain `(` or `[`), innermost last. */
116
+ fns = [];
117
+ constructor(css, start, assets) {
118
+ this.css = css;
119
+ this.assets = assets;
120
+ this.i = start;
121
+ }
122
+ run() {
123
+ const s = this.css;
124
+ while (this.i < s.length) {
125
+ const c = s[this.i];
126
+ if (c === "/" && s[this.i + 1] === "*") {
127
+ const end = s.indexOf("*/", this.i + 2);
128
+ if (end < 0)
129
+ throw new CssProblem("a comment is not closed");
130
+ this.i = end + 2;
131
+ }
132
+ else if (c === '"' || c === "'") {
133
+ const value = this.string(c);
134
+ if (this.fns[this.fns.length - 1] === "url") {
135
+ const problem = cssUrlProblem(cssTrim(value), this.assets);
136
+ if (problem !== undefined)
137
+ throw new CssProblem(problem);
138
+ }
139
+ }
140
+ else if (c === "@") {
141
+ this.i++;
142
+ if (this.startsName()) {
143
+ if (this.name().toLowerCase() === "import")
144
+ throw new CssProblem(IMPORT_REFUSED);
145
+ }
146
+ }
147
+ else if (c === "#") {
148
+ this.i++;
149
+ if (this.startsName())
150
+ this.name();
151
+ }
152
+ else if (this.startsName()) {
153
+ const name = this.name().toLowerCase();
154
+ if (s[this.i] === "(") {
155
+ this.i++;
156
+ if (REFUSED_FUNCTIONS.has(name))
157
+ throw new CssProblem(functionRefused(name));
158
+ if (name === "url" && !this.quoteAfterWhitespace())
159
+ this.urlToken();
160
+ else
161
+ this.fns.push(name);
162
+ }
163
+ }
164
+ else if (c === "(" || c === "[") {
165
+ this.fns.push("");
166
+ this.i++;
167
+ }
168
+ else if (c === ")" || c === "]") {
169
+ this.fns.pop();
170
+ this.i++;
171
+ }
172
+ else if (c === "{") {
173
+ this.depth++;
174
+ this.i++;
175
+ }
176
+ else if (c === "}") {
177
+ this.depth--;
178
+ this.i++;
179
+ if (this.depth === 0) {
180
+ if (cssTrim(s.slice(this.i)) !== "") {
181
+ throw new CssProblem("a rule is outside @layer extensions; the whole file must be one @layer extensions block");
182
+ }
183
+ return;
184
+ }
185
+ }
186
+ else {
187
+ this.i++;
188
+ }
189
+ }
190
+ throw new CssProblem("the @layer extensions block is not closed");
191
+ }
192
+ /** Whether a name starts here: a name code point or a valid escape. */
193
+ startsName() {
194
+ const s = this.css;
195
+ const c = s[this.i];
196
+ return isNameChar(c) || (c === "\\" && this.i + 1 < s.length && !isNewline(s[this.i + 1]));
197
+ }
198
+ /** A valid escape at `this.i` (the backslash); returns the decoded character. */
199
+ escape() {
200
+ const s = this.css;
201
+ this.i++; // the backslash
202
+ if (isHex(s[this.i])) {
203
+ let hex = "";
204
+ while (hex.length < 6 && isHex(s[this.i]))
205
+ hex += s[this.i++];
206
+ if (s[this.i] === "\r" && s[this.i + 1] === "\n")
207
+ this.i += 2;
208
+ else if (isWhitespace(s[this.i]))
209
+ this.i++;
210
+ const cp = Number.parseInt(hex, 16);
211
+ return cp > 0 && cp <= 0x10ffff && (cp < 0xd800 || cp > 0xdfff)
212
+ ? String.fromCodePoint(cp)
213
+ : "�";
214
+ }
215
+ const cp = s.codePointAt(this.i);
216
+ if (cp === undefined)
217
+ return "�";
218
+ const ch = String.fromCodePoint(cp);
219
+ this.i += ch.length;
220
+ return ch;
221
+ }
222
+ /** Consumes a name (name code points and valid escapes), decoded. */
223
+ name() {
224
+ const s = this.css;
225
+ let out = "";
226
+ while (this.i < s.length) {
227
+ const c = s[this.i];
228
+ if (isNameChar(c)) {
229
+ out += c;
230
+ this.i++;
231
+ }
232
+ else if (c === "\\" && this.i + 1 < s.length && !isNewline(s[this.i + 1])) {
233
+ out += this.escape();
234
+ }
235
+ else
236
+ break;
237
+ }
238
+ return out;
239
+ }
240
+ /** A string from its opening quote; an unescaped newline or the end of the file refuses. */
241
+ string(quote) {
242
+ const s = this.css;
243
+ this.i++;
244
+ let out = "";
245
+ while (this.i < s.length) {
246
+ const c = s[this.i];
247
+ if (c === quote) {
248
+ this.i++;
249
+ return out;
250
+ }
251
+ if (isNewline(c))
252
+ throw new CssProblem("a string is not closed on its line");
253
+ if (c === "\\") {
254
+ const next = s[this.i + 1];
255
+ if (next === undefined)
256
+ break;
257
+ if (isNewline(next)) {
258
+ this.i += next === "\r" && s[this.i + 2] === "\n" ? 3 : 2;
259
+ }
260
+ else
261
+ out += this.escape();
262
+ }
263
+ else {
264
+ out += c;
265
+ this.i++;
266
+ }
267
+ }
268
+ throw new CssProblem("a string is not closed");
269
+ }
270
+ /** After `url(`: whether the argument is a string (then `url(` is an ordinary function). */
271
+ quoteAfterWhitespace() {
272
+ const s = this.css;
273
+ let j = this.i;
274
+ while (isWhitespace(s[j]))
275
+ j++;
276
+ return s[j] === '"' || s[j] === "'";
277
+ }
278
+ /**
279
+ * An unquoted url token after `url(`: everything up to the first unescaped `)` (a bad url, with a
280
+ * quote or `(` inside, ends there too), escapes decoded; the URL is checked.
281
+ */
282
+ urlToken() {
283
+ const s = this.css;
284
+ let out = "";
285
+ while (this.i < s.length) {
286
+ const c = s[this.i];
287
+ if (c === ")") {
288
+ this.i++;
289
+ const problem = cssUrlProblem(cssTrim(out), this.assets);
290
+ if (problem !== undefined)
291
+ throw new CssProblem(problem);
292
+ return;
293
+ }
294
+ if (c === "\\" && this.i + 1 < s.length && !isNewline(s[this.i + 1]))
295
+ out += this.escape();
296
+ else {
297
+ out += c;
298
+ this.i++;
299
+ }
300
+ }
301
+ throw new CssProblem("a url( is not closed");
302
+ }
303
+ }
304
+ /**
305
+ * The problem of a client stylesheet as stored (see the file header), or undefined when it is one
306
+ * `@layer extensions` block with no `@import` and every URL a `#fragment`, a `data:` URL or one of
307
+ * the plugin's `assets` (paths relative to `assets/`).
308
+ */
309
+ export function clientCssProblem(css, assets) {
310
+ const remote = cssRemoteProblem(css, assets);
311
+ if (remote !== undefined)
312
+ return remote;
313
+ const wrap = WRAP_RE.exec(css);
314
+ if (wrap === null) {
315
+ return "the file must start with @layer extensions { (capybara-plugin pack wraps every stylesheet)";
316
+ }
317
+ try {
318
+ new Scanner(css, wrap[0].length, assets).run();
319
+ }
320
+ catch (e) {
321
+ if (e instanceof CssProblem)
322
+ return e.message;
323
+ throw e;
324
+ }
325
+ return undefined;
326
+ }