@capybara-hq/testing 0.1.0-rc.26 → 0.1.0-rc.28

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.
@@ -108,6 +108,14 @@ export interface Harness {
108
108
  * 另一个副本照常工作。已退出时是空操作。
109
109
  */
110
110
  kill(index: number): Promise<void>;
111
+ /**
112
+ * Stops replica `index` gracefully, through the kernel's own shutdown (as `stop()` does for all of
113
+ * them), and waits for it to exit; the other replicas keep working. A stop stuck for 10 s ends
114
+ * with the replica's own forced exit (code 1), and the harness SIGKILLs it after 15 s. Like after
115
+ * `kill`, `request()` keeps rotating to the stopped replica and requests to it throw. A no-op
116
+ * when it already exited.
117
+ */
118
+ stopReplica(index: number): Promise<void>;
111
119
  /**
112
120
  * 停两个副本(15s 后 SIGKILL)、删临时库、关自有容器;幂等。Before the replicas stop it asserts
113
121
  * that they left no queued run without its job (neither in the outbox nor in BullMQ: the "queue
@@ -276,6 +276,7 @@ export async function createDualReplicaHarness(opts) {
276
276
  redisUrl,
277
277
  stop,
278
278
  kill,
279
+ stopReplica: (index) => stopRunner(runnerAt(index).runner),
279
280
  startExtraReplica(extraRoles) {
280
281
  // Extra starts run one at a time: the index is the next free slot when the start begins,
281
282
  // and a failed start appends nothing, so there are never holes in the replica indexes
@@ -47,6 +47,21 @@ export interface FakeChannelSent {
47
47
  locale?: "zh" | "en";
48
48
  at: number;
49
49
  }
50
+ /** A file the bot uploaded (`POST /send-file`). */
51
+ export interface FakeChannelSentFile {
52
+ appId: string;
53
+ target: ChannelTarget;
54
+ name: string;
55
+ contentType: string;
56
+ kind: "image" | "file";
57
+ data: Buffer;
58
+ sha256: string;
59
+ messageId: string;
60
+ pid: number;
61
+ idempotencyKey?: string;
62
+ locale?: "zh" | "en";
63
+ at: number;
64
+ }
50
65
  /** 平台上的一个用户(OAuth 登录时可用 `as=<externalId>` 选中)。 */
51
66
  export interface FakeChannelUser {
52
67
  externalId: string;
@@ -74,10 +89,10 @@ export interface FakeDirectoryBook {
74
89
  /** 整轮同步开始的次数(不带游标的请求数)。 */
75
90
  starts(): number;
76
91
  }
77
- /** Which `/send` or `/update` requests a {@link FakeChannelServer.failNext} failure applies to. */
92
+ /** Which `/send`, `/update` or `/send-file` requests a {@link FakeChannelServer.failNext} failure applies to. */
78
93
  export interface FakeChannelFailMatch {
79
94
  chatId?: string;
80
- /** The message's text contains it. */
95
+ /** The message's text (for `/send-file`: the file name) contains it. */
81
96
  textIncludes?: string;
82
97
  }
83
98
  /** A `fake-im` setup check's call of `POST /checks`. */
@@ -111,6 +126,10 @@ export interface FakeChannelServer {
111
126
  updated: FakeChannelSent[];
112
127
  /** 命中幂等键、被平台去重的发送请求(没有产生新消息)。 */
113
128
  duplicateSends: FakeChannelSent[];
129
+ /** Files the bot uploaded (`/send-file`), after dedupe. */
130
+ sentFiles: FakeChannelSentFile[];
131
+ /** `/send-file` requests that hit an idempotency key already seen (no new message). */
132
+ duplicateFiles: FakeChannelSentFile[];
114
133
  /** 插件工具发的公告。 */
115
134
  posts: FakeChannelPost[];
116
135
  /** Calls of `fake-im` setup checks (`POST /checks`). */
@@ -127,14 +146,14 @@ export interface FakeChannelServer {
127
146
  * text (`textIncludes`: the message's text contains it). Without it the next requests to any chat
128
147
  * fail, so a late delivery from an earlier test can take the failure meant for the request under test.
129
148
  */
130
- failNext(path: "/send" | "/update", status: number, count?: number, retryAfterMs?: number, reason?: "auth" | "target_gone" | "rejected" | "too_large", delayMs?: number, match?: string | FakeChannelFailMatch): void;
149
+ failNext(path: "/send" | "/update" | "/send-file", status: number, count?: number, retryAfterMs?: number, reason?: "auth" | "target_gone" | "rejected" | "too_large", delayMs?: number, match?: string | FakeChannelFailMatch): void;
131
150
  /**
132
151
  * Delay the response of the next `count` successful `/send` (or `/update`) requests by `delayMs`.
133
152
  * The message is recorded (visible in `sent` / `updated`) as soon as the request arrives; only the
134
153
  * response carrying its `messageId` is late (a slow platform API, or a sender that dies mid-call).
135
154
  * `onlyCards`: count and delay only requests whose message carries cards.
136
155
  */
137
- delayNext(path: "/send" | "/update", delayMs: number, opts?: {
156
+ delayNext(path: "/send" | "/update" | "/send-file", delayMs: number, opts?: {
138
157
  count?: number;
139
158
  onlyCards?: boolean;
140
159
  }): void;
@@ -20,6 +20,8 @@ export async function startFakeChannelServer(opts = {}) {
20
20
  const sent = [];
21
21
  const updated = [];
22
22
  const duplicateSends = [];
23
+ const sentFiles = [];
24
+ const duplicateFiles = [];
23
25
  const posts = [];
24
26
  const checks = [];
25
27
  let checkHold = null;
@@ -27,6 +29,7 @@ export async function startFakeChannelServer(opts = {}) {
27
29
  const books = new Map();
28
30
  const codes = new Map();
29
31
  const byKey = new Map();
32
+ const fileByKey = new Map();
30
33
  const failures = [];
31
34
  const delays = [];
32
35
  const live = new Map();
@@ -66,7 +69,8 @@ export async function startFakeChannelServer(opts = {}) {
66
69
  const parsed = JSON.parse(body);
67
70
  const matches = (m) => m === undefined ||
68
71
  ((m.chatId === undefined || m.chatId === parsed.target?.chatId) &&
69
- (m.textIncludes === undefined || (parsed.message?.text ?? "").includes(m.textIncludes)));
72
+ (m.textIncludes === undefined ||
73
+ (parsed.message?.text ?? parsed.file?.name ?? "").includes(m.textIncludes)));
70
74
  const f = failures.find((x) => x.path === path && x.left > 0 && matches(x.match));
71
75
  if (f) {
72
76
  f.left--;
@@ -75,6 +79,41 @@ export async function startFakeChannelServer(opts = {}) {
75
79
  json(res, f.status, { retryAfterMs: f.retryAfterMs ?? null, reason: f.reason ?? null });
76
80
  return;
77
81
  }
82
+ if (path === "/send-file") {
83
+ const fb = JSON.parse(body);
84
+ const data = Buffer.from(fb.file.data, "base64");
85
+ const fkey = fb.idempotencyKey ? `${fb.appId}\u0000${fb.idempotencyKey}` : undefined;
86
+ const fseen = fkey !== undefined ? fileByKey.get(fkey) : undefined;
87
+ const fid = fseen ?? `of_${++seq}`;
88
+ const frec = {
89
+ appId: fb.appId,
90
+ target: fb.target,
91
+ name: fb.file.name,
92
+ contentType: fb.file.contentType,
93
+ kind: fb.file.kind,
94
+ data,
95
+ sha256: createHash("sha256").update(data).digest("hex"),
96
+ messageId: fid,
97
+ pid: pidOf(req),
98
+ ...(fb.idempotencyKey !== undefined && { idempotencyKey: fb.idempotencyKey }),
99
+ ...(fb.locale !== undefined && { locale: fb.locale }),
100
+ at: Date.now(),
101
+ };
102
+ if (fseen !== undefined && dedupe)
103
+ duplicateFiles.push(frec);
104
+ else {
105
+ sentFiles.push(frec);
106
+ if (fkey !== undefined && fseen === undefined)
107
+ fileByKey.set(fkey, fid);
108
+ }
109
+ const fd = delays.find((x) => x.path === path && x.left > 0);
110
+ if (fd) {
111
+ fd.left--;
112
+ await new Promise((r) => setTimeout(r, fd.delayMs));
113
+ }
114
+ json(res, 200, { messageId: fid });
115
+ return;
116
+ }
78
117
  const b = JSON.parse(body);
79
118
  const key = b.idempotencyKey ? `${b.appId}\u0000${b.idempotencyKey}` : undefined;
80
119
  const seen = path === "/send" && key !== undefined ? byKey.get(key) : undefined;
@@ -165,7 +204,7 @@ export async function startFakeChannelServer(opts = {}) {
165
204
  const route = `${req.method} ${u.pathname}`;
166
205
  if (route === "GET /connect")
167
206
  return connect(req, res, u);
168
- if (route === "POST /send" || route === "POST /update") {
207
+ if (route === "POST /send" || route === "POST /update" || route === "POST /send-file") {
169
208
  return sendOrUpdate(req, res, u.pathname);
170
209
  }
171
210
  if (route === "POST /bot/verify") {
@@ -219,6 +258,8 @@ export async function startFakeChannelServer(opts = {}) {
219
258
  sent,
220
259
  updated,
221
260
  duplicateSends,
261
+ sentFiles,
262
+ duplicateFiles,
222
263
  posts,
223
264
  checks,
224
265
  holdChecks(hold) {
@@ -56,6 +56,15 @@ export interface FakeLarkDepartment {
56
56
  /** 上级部门(根部门为 `"0"`)。 */
57
57
  parent: string;
58
58
  }
59
+ /** An image or file the bot uploaded (`im/v1/images`, `im/v1/files`); `key` is what a message names. */
60
+ export interface FakeLarkUpload {
61
+ kind: "image" | "file";
62
+ key: string;
63
+ fileType?: string;
64
+ fileName?: string;
65
+ data: Buffer;
66
+ at: number;
67
+ }
59
68
  /** 机器人发出(或更新后)的一条消息。 */
60
69
  export interface FakeLarkMessage {
61
70
  messageId: string;
@@ -110,7 +119,7 @@ export interface FakeLarkOptions {
110
119
  * 接口名:`token`、`bot`、`tenant`、`create`、`reply`、`patch`、`user`、`endpoint`、`oauth_token`、`user_info`、
111
120
  * `departments`、`find_by_department`。
112
121
  */
113
- export type FakeLarkApi = "token" | "bot" | "tenant" | "create" | "reply" | "patch" | "user" | "endpoint" | "oauth_token" | "user_info" | "departments" | "find_by_department";
122
+ export type FakeLarkApi = "token" | "bot" | "tenant" | "create" | "reply" | "patch" | "user" | "endpoint" | "oauth_token" | "user_info" | "departments" | "find_by_department" | "image_upload" | "file_upload";
114
123
  export interface FakeLarkServer {
115
124
  /** 开放平台根地址(插件的 `apiUrl` / SDK 的 `domain`)。 */
116
125
  url: string;
@@ -121,6 +130,8 @@ export interface FakeLarkServer {
121
130
  botName: string;
122
131
  messages: FakeLarkMessage[];
123
132
  updates: FakeLarkMessage[];
133
+ /** Successful image and file uploads, in order. */
134
+ uploads: FakeLarkUpload[];
124
135
  calls: FakeLarkCall[];
125
136
  acks: FakeLarkAck[];
126
137
  users: Map<string, FakeLarkUser>;
package/dist/fake-lark.js CHANGED
@@ -34,11 +34,9 @@ const Frame = root.lookupType("pbbp2.Frame");
34
34
  const encodeFrame = (f) => Buffer.from(Frame.encode(Frame.fromObject(f)).finish());
35
35
  const decodeFrame = (b) => Frame.toObject(Frame.decode(b), { longs: Number, bytes: Buffer });
36
36
  const readBody = (req) => new Promise((resolve) => {
37
- let body = "";
38
- req.on("data", (c) => {
39
- body += c.toString();
40
- });
41
- req.on("end", () => resolve(body));
37
+ const chunks = [];
38
+ req.on("data", (c) => chunks.push(c));
39
+ req.on("end", () => resolve(Buffer.concat(chunks)));
42
40
  });
43
41
  const obj = (v) => typeof v === "object" && v !== null && !Array.isArray(v)
44
42
  ? v
@@ -72,6 +70,7 @@ export async function startFakeLark(opts = {}) {
72
70
  const botName = opts.botName ?? "Capybara";
73
71
  const messages = [];
74
72
  const updates = [];
73
+ const uploads = [];
75
74
  const calls = [];
76
75
  const acks = [];
77
76
  const users = new Map();
@@ -116,6 +115,14 @@ export async function startFakeLark(opts = {}) {
116
115
  fail(res, 230001, "invalid content");
117
116
  return undefined;
118
117
  }
118
+ if (msgType === "image" || msgType === "file") {
119
+ const kind = msgType === "image" ? "image" : "file";
120
+ const key = str(obj(card)?.[`${kind}_key`]);
121
+ if (key === undefined || !uploads.some((x) => x.kind === kind && x.key === key)) {
122
+ fail(res, 230001, `invalid ${kind}_key`);
123
+ return undefined;
124
+ }
125
+ }
119
126
  if (msgType === "interactive") {
120
127
  const c = obj(card);
121
128
  if (c?.schema !== "2.0" || obj(c.config)?.update_multi === false || !obj(c.body)) {
@@ -126,13 +133,34 @@ export async function startFakeLark(opts = {}) {
126
133
  return { msgType, card };
127
134
  };
128
135
  const api = async (req, res, u) => {
129
- const raw = await readBody(req);
136
+ const rawBytes = await readBody(req);
137
+ const raw = rawBytes.toString();
138
+ const contentType = req.headers["content-type"] ?? "";
130
139
  let body = {};
131
- try {
132
- body = raw === "" ? {} : JSON.parse(raw);
140
+ let blob;
141
+ if (contentType.includes("multipart/form-data")) {
142
+ try {
143
+ const form = await new Response(new Uint8Array(rawBytes), {
144
+ headers: { "content-type": contentType },
145
+ }).formData();
146
+ for (const [k, v] of form) {
147
+ if (typeof v === "string")
148
+ body[k] = v;
149
+ else
150
+ blob = { data: Buffer.from(await v.arrayBuffer()), field: k };
151
+ }
152
+ }
153
+ catch {
154
+ return fail(res, 9499, "bad request");
155
+ }
133
156
  }
134
- catch {
135
- return fail(res, 9499, "bad request");
157
+ else {
158
+ try {
159
+ body = raw === "" ? {} : JSON.parse(raw);
160
+ }
161
+ catch {
162
+ return fail(res, 9499, "bad request");
163
+ }
136
164
  }
137
165
  const path = u.pathname;
138
166
  const method = req.method ?? "GET";
@@ -151,6 +179,10 @@ export async function startFakeLark(opts = {}) {
151
179
  name = "tenant";
152
180
  else if (path === "/open-apis/im/v1/messages" && method === "POST")
153
181
  name = "create";
182
+ else if (path === "/open-apis/im/v1/images" && method === "POST")
183
+ name = "image_upload";
184
+ else if (path === "/open-apis/im/v1/files" && method === "POST")
185
+ name = "file_upload";
154
186
  else if (reply$ && method === "POST")
155
187
  name = "reply";
156
188
  else if (msg$ && method === "PATCH")
@@ -290,6 +322,26 @@ export async function startFakeLark(opts = {}) {
290
322
  },
291
323
  });
292
324
  }
325
+ case "image_upload": {
326
+ if (str(body.image_type) !== "message" || blob?.field !== "image" || blob.data.length === 0)
327
+ return fail(res, 234001, "Invalid request param.");
328
+ const key = `img_v3_${hex(10)}`;
329
+ uploads.push({ kind: "image", key, data: blob.data, at: Date.now() });
330
+ return reply(res, { code: 0, msg: "success", data: { image_key: key } });
331
+ }
332
+ case "file_upload": {
333
+ const fileType = str(body.file_type);
334
+ const fileName = str(body.file_name);
335
+ if (!fileType ||
336
+ !["opus", "mp4", "pdf", "doc", "xls", "ppt", "stream"].includes(fileType) ||
337
+ !fileName ||
338
+ blob?.field !== "file" ||
339
+ blob.data.length === 0)
340
+ return fail(res, 234001, "Invalid request param.");
341
+ const key = `file_v3_${hex(10)}`;
342
+ uploads.push({ kind: "file", key, fileType, fileName, data: blob.data, at: Date.now() });
343
+ return reply(res, { code: 0, msg: "success", data: { file_key: key } });
344
+ }
293
345
  case "create":
294
346
  case "reply": {
295
347
  const uuid = str(body.uuid);
@@ -645,6 +697,7 @@ export async function startFakeLark(opts = {}) {
645
697
  botName,
646
698
  messages,
647
699
  updates,
700
+ uploads,
648
701
  calls,
649
702
  acks,
650
703
  users,
@@ -60,6 +60,16 @@ export interface FakeSlackCall {
60
60
  token: string;
61
61
  body: Record<string, unknown>;
62
62
  }
63
+ /** A file the bot uploaded through the external upload flow and completed into a channel. */
64
+ export interface FakeSlackFile {
65
+ id: string;
66
+ filename: string;
67
+ title?: string;
68
+ channel: string;
69
+ threadTs?: string;
70
+ data: Buffer;
71
+ at: number;
72
+ }
63
73
  /** 客户端对信封的确认。 */
64
74
  export interface FakeSlackAck {
65
75
  envelopeId: string;
@@ -128,6 +138,8 @@ export interface FakeSlackServer {
128
138
  clientSecret: string;
129
139
  messages: FakeSlackMessage[];
130
140
  updates: FakeSlackMessage[];
141
+ /** Completed external uploads (`files.completeUploadExternal`), in order. */
142
+ files: FakeSlackFile[];
131
143
  calls: FakeSlackCall[];
132
144
  acks: FakeSlackAck[];
133
145
  users: Map<string, FakeSlackUser>;
@@ -148,8 +160,12 @@ export interface FakeSlackServer {
148
160
  * closed unacked is dropped from this count.
149
161
  */
150
162
  pendingEnvelopes(appToken?: string): number;
163
+ /**
164
+ * The next `count` calls of `method` fail. The pseudo-method `"upload"` is the `POST /upload/<id>`
165
+ * step of the external upload flow: it answers `failure.status` (default 500) with a plain-text body.
166
+ */
151
167
  failNext(method: string, failure: FakeSlackFailure, count?: number): void;
152
- /** 之后该方法的每次调用先等 `ms` 毫秒再响应(0 取消)。 */
168
+ /** Every later call of the method waits `ms` milliseconds before answering (0 cancels); `"upload"` holds the upload POST. */
153
169
  delay(method: string, ms: number): void;
154
170
  /** 接下来 `count` 条 Socket Mode 连接在发出 hello 后立即被关闭(不发 disconnect 消息)。 */
155
171
  dropNextConnections(count: number): void;
@@ -8,6 +8,12 @@ const readBody = (req) => new Promise((resolve) => {
8
8
  });
9
9
  req.on("end", () => resolve(body));
10
10
  });
11
+ const readRaw = (req) => new Promise((resolve, reject) => {
12
+ const chunks = [];
13
+ req.on("data", (c) => chunks.push(c));
14
+ req.on("end", () => resolve(Buffer.concat(chunks)));
15
+ req.on("error", reject);
16
+ });
11
17
  const JSON_FIELDS = new Set(["blocks", "attachments", "metadata"]);
12
18
  function parseBody(raw, contentType) {
13
19
  if (raw === "")
@@ -49,6 +55,9 @@ export async function startFakeSlack(opts = {}) {
49
55
  let tamper;
50
56
  const messages = [];
51
57
  const updates = [];
58
+ const files = [];
59
+ /** External uploads by file id: announced by getUploadURLExternal, `data` set once uploaded. */
60
+ const uploads = new Map();
52
61
  const calls = [];
53
62
  const acks = [];
54
63
  const users = new Map();
@@ -207,6 +216,54 @@ export async function startFakeSlack(opts = {}) {
207
216
  });
208
217
  return reply(res, { ok: true, channel, ts, text });
209
218
  }
219
+ case "files.getUploadURLExternal": {
220
+ const filename = str(body.filename);
221
+ const length = Number(body.length);
222
+ if (!filename || !Number.isInteger(length) || length < 0) {
223
+ return reply(res, { ok: false, error: "invalid_arguments" });
224
+ }
225
+ const id = `F${String(++seq).padStart(8, "0")}`;
226
+ uploads.set(id, { filename, length });
227
+ return reply(res, { ok: true, upload_url: `${base}/upload/${id}`, file_id: id });
228
+ }
229
+ case "files.completeUploadExternal": {
230
+ const channel = str(body.channel_id);
231
+ const threadTs = str(body.thread_ts);
232
+ let list = body.files;
233
+ if (typeof list === "string") {
234
+ try {
235
+ list = JSON.parse(list);
236
+ }
237
+ catch {
238
+ return reply(res, { ok: false, error: "invalid_arguments" });
239
+ }
240
+ }
241
+ if (!Array.isArray(list) || list.length === 0 || !channel) {
242
+ return reply(res, { ok: false, error: "invalid_arguments" });
243
+ }
244
+ const items = list;
245
+ for (const it of items) {
246
+ const u = typeof it.id === "string" ? uploads.get(it.id) : undefined;
247
+ if (!u?.data)
248
+ return reply(res, { ok: false, error: "invalid_arguments" });
249
+ }
250
+ const done = items.map((it) => {
251
+ const id = it.id;
252
+ const u = uploads.get(id);
253
+ const title = str(it.title);
254
+ files.push({
255
+ id,
256
+ filename: u.filename,
257
+ ...(title !== undefined && { title }),
258
+ channel,
259
+ ...(threadTs !== undefined && { threadTs }),
260
+ data: u.data,
261
+ at: Date.now(),
262
+ });
263
+ return { id, title: title ?? u.filename };
264
+ });
265
+ return reply(res, { ok: true, files: done });
266
+ }
210
267
  case "users.list": {
211
268
  const limit = Math.max(1, Math.min(1000, Number(body.limit ?? 100) || 100));
212
269
  const offset = str(body.cursor)
@@ -327,12 +384,52 @@ export async function startFakeSlack(opts = {}) {
327
384
  }
328
385
  res.writeHead(302, { location: back.toString() }).end();
329
386
  };
387
+ /** `POST /upload/<id>`: the raw bytes or one multipart file part; the length must match. */
388
+ const upload = async (req, res, id) => {
389
+ const raw = await readRaw(req);
390
+ const wait = delays.get("upload") ?? 0;
391
+ if (wait > 0)
392
+ await new Promise((r) => setTimeout(r, wait));
393
+ const f = failures.find((x) => x.method === "upload" && x.left > 0);
394
+ if (f) {
395
+ f.left--;
396
+ const { status, retryAfter } = f.failure;
397
+ const headers = { "content-type": "text/plain" };
398
+ if (retryAfter !== undefined)
399
+ headers["retry-after"] = String(retryAfter);
400
+ res.writeHead(status ?? 500, headers).end("upload failed");
401
+ return;
402
+ }
403
+ const u = uploads.get(id);
404
+ if (!u)
405
+ return reply(res, { ok: false, error: "invalid_arguments" }, 404);
406
+ const type = req.headers["content-type"];
407
+ let data = raw;
408
+ if (type?.includes("multipart/form-data")) {
409
+ const form = await new Response(new Uint8Array(raw), {
410
+ headers: { "content-type": type },
411
+ }).formData();
412
+ const part = [...form.values()].find((v) => typeof v !== "string");
413
+ if (!part)
414
+ return reply(res, { ok: false, error: "invalid_arguments" }, 400);
415
+ data = Buffer.from(await part.arrayBuffer());
416
+ }
417
+ if (data.length !== u.length) {
418
+ res.writeHead(400, { "content-type": "text/plain" }).end("length mismatch");
419
+ return;
420
+ }
421
+ u.data = data;
422
+ res.writeHead(200, { "content-type": "text/plain" }).end(`OK - ${data.length}`);
423
+ };
330
424
  const server = createServer((req, res) => {
331
425
  void (async () => {
332
426
  const u = new URL(req.url ?? "/", "http://x");
333
427
  const m = /^\/api\/([A-Za-z.]+)$/.exec(u.pathname);
334
428
  if (m && req.method === "POST")
335
429
  return api(req, res, m[1]);
430
+ const up = /^\/upload\/([A-Za-z0-9]+)$/.exec(u.pathname);
431
+ if (up && req.method === "POST")
432
+ return upload(req, res, up[1]);
336
433
  if (u.pathname === "/openid/connect/authorize" && req.method === "GET")
337
434
  return authorize(res, u);
338
435
  if (u.pathname === "/openid/connect/keys" && req.method === "GET") {
@@ -463,6 +560,7 @@ export async function startFakeSlack(opts = {}) {
463
560
  clientSecret,
464
561
  messages,
465
562
  updates,
563
+ files,
466
564
  calls,
467
565
  acks,
468
566
  users,
@@ -7,7 +7,8 @@
7
7
  * An unknown token → 401 `Unauthorized`; an unknown method → 404 `Not Found`. Point a client at
8
8
  * `apiUrl` (it appends `/bot<token>/<method>`).
9
9
  * - **Methods**: `getMe`, `getWebhookInfo` (the url given to {@link FakeTelegramServer.setWebhook}),
10
- * `getUpdates`, `sendMessage`, `editMessageText`, `answerCallbackQuery`.
10
+ * `getUpdates`, `sendMessage`, `editMessageText`, `answerCallbackQuery`, and the multipart uploads
11
+ * `sendPhoto` / `sendDocument` (recorded in `messages` with `file`).
11
12
  * - **Long polling**: {@link FakeTelegramServer.push} queues an update per bot and assigns its
12
13
  * `update_id`. `getUpdates` with `offset` confirms (drops) the lower ids; with `timeout` it waits
13
14
  * until a push or the timeout; `allowed_updates` is remembered per bot like Telegram and updates of
@@ -49,6 +50,13 @@ export interface FakeTelegramMessage {
49
50
  replyMarkup?: unknown;
50
51
  messageThreadId?: number;
51
52
  replyToMessageId?: number;
53
+ /** The uploaded file of a `sendPhoto` / `sendDocument` (the text is its caption). */
54
+ file?: {
55
+ kind: "photo" | "document";
56
+ name: string;
57
+ contentType: string;
58
+ data: Buffer;
59
+ };
52
60
  at: number;
53
61
  }
54
62
  /** An injected error answer: `status` is the HTTP status, `errorCode` defaults to it. */
@@ -1,5 +1,6 @@
1
1
  import { createServer } from "node:http";
2
2
  const MAX_TEXT = 4096;
3
+ const MAX_CAPTION = 1024;
3
4
  const ENTITIES = { lt: "<", gt: ">", amp: "&", quot: '"' };
4
5
  /**
5
6
  * The text length Telegram limits: UTF-16 code units after entity parsing. With `parse_mode`
@@ -33,14 +34,13 @@ class TelegramError extends Error {
33
34
  }
34
35
  }
35
36
  const readBody = (req) => new Promise((resolve, reject) => {
36
- let body = "";
37
- req.on("data", (c) => {
38
- body += c.toString();
39
- });
40
- req.on("end", () => resolve(body));
37
+ const chunks = [];
38
+ req.on("data", (c) => chunks.push(c));
39
+ req.on("end", () => resolve(Buffer.concat(chunks)));
41
40
  req.on("error", reject);
42
41
  });
43
- function parseParams(url, raw, contentType) {
42
+ async function parseParams(url, rawBytes, contentType, uploads) {
43
+ const raw = contentType?.includes("multipart/form-data") ? "" : rawBytes.toString();
44
44
  const out = {};
45
45
  const fromForm = (form) => {
46
46
  for (const [k, v] of form) {
@@ -57,6 +57,33 @@ function parseParams(url, raw, contentType) {
57
57
  }
58
58
  };
59
59
  fromForm(url.searchParams);
60
+ if (contentType?.includes("multipart/form-data")) {
61
+ let form;
62
+ try {
63
+ form = await new Response(new Uint8Array(rawBytes), {
64
+ headers: { "content-type": contentType },
65
+ }).formData();
66
+ }
67
+ catch {
68
+ throw new TelegramError(400, "Bad Request: invalid multipart body");
69
+ }
70
+ for (const [k, v] of form) {
71
+ if (typeof v === "string") {
72
+ const one = new URLSearchParams();
73
+ one.set(k, v);
74
+ fromForm(one);
75
+ }
76
+ else {
77
+ uploads.push({
78
+ field: k,
79
+ name: v.name,
80
+ contentType: v.type,
81
+ data: Buffer.from(await v.arrayBuffer()),
82
+ });
83
+ }
84
+ }
85
+ return out;
86
+ }
60
87
  if (raw === "")
61
88
  return out;
62
89
  if (contentType?.includes("application/json")) {
@@ -178,15 +205,19 @@ export async function startFakeTelegram(opts = {}) {
178
205
  const timeout = Math.max(num(params.timeout) ?? 0, 0);
179
206
  return { limit, timeout, ready: collect(s, limit), port: req.socket.remotePort };
180
207
  };
181
- const sendMessage = (s, params) => {
208
+ /** `upload` set: a sendPhoto / sendDocument, whose text is the caption (up to 1024). */
209
+ const sendMessage = (s, params, upload) => {
182
210
  const chatId = num(params.chat_id);
183
211
  if (chatId === undefined)
184
212
  throw new TelegramError(400, "Bad Request: chat not found");
185
- const text = str(params.text) ?? "";
186
- if (text === "")
213
+ const text = (upload ? str(params.caption) : str(params.text)) ?? "";
214
+ if (!upload && text === "")
187
215
  throw new TelegramError(400, "Bad Request: message text is empty");
188
- if (telegramTextLength(text, str(params.parse_mode)) > MAX_TEXT) {
189
- throw new TelegramError(400, "Bad Request: message is too long");
216
+ if (upload && upload.part.data.length === 0) {
217
+ throw new TelegramError(400, "Bad Request: file must be non-empty");
218
+ }
219
+ if (telegramTextLength(text, str(params.parse_mode)) > (upload ? MAX_CAPTION : MAX_TEXT)) {
220
+ throw new TelegramError(400, upload ? "Bad Request: message caption is too long" : "Bad Request: message is too long");
190
221
  }
191
222
  const chatKey = `${s.bot.token}|${chatId}`;
192
223
  const messageId = (lastMessageId.get(chatKey) ?? 0) + 1;
@@ -203,6 +234,14 @@ export async function startFakeTelegram(opts = {}) {
203
234
  ...(params.reply_markup !== undefined && { replyMarkup: params.reply_markup }),
204
235
  ...(threadId !== undefined && { messageThreadId: threadId }),
205
236
  ...(replyTo !== undefined && { replyToMessageId: replyTo }),
237
+ ...(upload && {
238
+ file: {
239
+ kind: upload.kind,
240
+ name: upload.part.name,
241
+ contentType: upload.part.contentType,
242
+ data: upload.part.data,
243
+ },
244
+ }),
206
245
  at: Date.now(),
207
246
  };
208
247
  messages.push(m);
@@ -247,15 +286,30 @@ export async function startFakeTelegram(opts = {}) {
247
286
  from: botUser(s.bot),
248
287
  chat: { id: m.chatId, type: m.chatId > 0 ? "private" : "supergroup" },
249
288
  date: Math.floor(m.at / 1000),
250
- text: m.text,
289
+ ...(m.file
290
+ ? {
291
+ ...(m.text !== "" && { caption: m.text }),
292
+ ...(m.file.kind === "photo"
293
+ ? { photo: [{ file_id: "fake-photo", file_unique_id: "fp", width: 800, height: 800 }] }
294
+ : {
295
+ document: {
296
+ file_id: "fake-document",
297
+ file_unique_id: "fd",
298
+ file_name: m.file.name,
299
+ mime_type: m.file.contentType,
300
+ },
301
+ }),
302
+ }
303
+ : { text: m.text }),
251
304
  ...(m.messageThreadId !== undefined && { message_thread_id: m.messageThreadId }),
252
305
  ...(m.replyMarkup !== undefined && { reply_markup: m.replyMarkup }),
253
306
  });
254
307
  const handle = async (req, res, token, name) => {
255
308
  const url = new URL(req.url ?? "/", "http://x");
256
309
  let params;
310
+ const uploads = [];
257
311
  try {
258
- params = parseParams(url, await readBody(req), req.headers["content-type"]);
312
+ params = await parseParams(url, await readBody(req), req.headers["content-type"], uploads);
259
313
  }
260
314
  catch (e) {
261
315
  if (e instanceof TelegramError)
@@ -329,6 +383,15 @@ export async function startFakeTelegram(opts = {}) {
329
383
  }
330
384
  case "sendmessage":
331
385
  return ok(res, sendMessage(s, params));
386
+ case "sendphoto":
387
+ case "senddocument": {
388
+ const kind = method === "sendphoto" ? "photo" : "document";
389
+ const part = uploads.find((u) => u.field === kind);
390
+ if (!part) {
391
+ throw new TelegramError(400, `Bad Request: there is no ${kind} in the request`);
392
+ }
393
+ return ok(res, sendMessage(s, params, { kind, part }));
394
+ }
332
395
  case "editmessagetext":
333
396
  return ok(res, editMessageText(s, params));
334
397
  case "answercallbackquery":
@@ -17,7 +17,7 @@
17
17
  * | `fake-bootstrap-a` | `model-provider@2` with a required secret `apiKey` (pending configuration until set) |
18
18
  * | `fake-bootstrap-b` | `object-store@1` kept in its own PG table; `bucket` + secret `secretKey` |
19
19
  * | `fake-dep-provider` / `fake-dep-requirer` | a dependency pair on `counter@1` (the requirer's plugin.json depends on the provider) |
20
- * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, webhook inbound), `identity-source@1`, `directory@1` (org config `url` of a directory book) and tool `post_announcement` (default policy ask, posts to the platform); deployment config `platformUrl`, `tenant`, `clientId`, secret `clientSecret`. Its `src/index.ts` also exports `makeFakeImChannel`, `fakeImIdentitySource`, `fakeImDirectory` for test extensions that need one part |
20
+ * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, files via `sendFile`, webhook inbound), `identity-source@1`, `directory@1` (org config `url` of a directory book) and tool `post_announcement` (default policy ask, posts to the platform); deployment config `platformUrl`, `tenant`, `clientId`, secret `clientSecret`. Its `src/index.ts` also exports `makeFakeImChannel`, `fakeImIdentitySource`, `fakeImDirectory` for test extensions that need one part |
21
21
  * | `fake-web` / `fake-web-2` | `web-search@1` and `web-fetch@1`, scripted by a prefix of the query or of the fetched URL's path (`error:<kind>`, `throw:`, `hang:`, `redirect:<url>`, `junk:`, `empty:`, `big:<n>`; see `makeFakeWeb`); results name the provider; org config secret `token`, `configured()` iff it is set (throws for `throw:configured`); calls recorded on `globalThis.__fakeWeb` (`fakeWebProbe`) |
22
22
  * | `fake-context` | `context@1` scripted by its deployment config (`text`, default "fake context"; `mode` `ok` / `null` / `throw` / `hang`); calls recorded on `globalThis.__fakeContext` (`fakeContextProbe`); tool `note` (`sources` web and channel_dm) |
23
23
  * | `fake-client` | client extension (`permissions.client`, no extension point): components `hud` (`conversation.properties.section`, server view with `data`), `brand` (`shell.brand`, renders `builtin` in `data-testid="fake-client-brand"`), `empty` (`conversation.empty`), `frame` (`conversation.composer.frame`) and `fx` (`shell.overlay`); `client/styles/fake.css` (outline-color on `button.primary` and the composer's buttons, `--cx-fake-client-run` while `run=running`); an `events` listener storing the last event type; theme `fake`; `suggestedAppearance` = theme `fake` + `shell.brand` -> `brand` |
package/dist/fixtures.js CHANGED
@@ -20,7 +20,7 @@ import { fileURLToPath } from "node:url";
20
20
  * | `fake-bootstrap-a` | `model-provider@2` with a required secret `apiKey` (pending configuration until set) |
21
21
  * | `fake-bootstrap-b` | `object-store@1` kept in its own PG table; `bucket` + secret `secretKey` |
22
22
  * | `fake-dep-provider` / `fake-dep-requirer` | a dependency pair on `counter@1` (the requirer's plugin.json depends on the provider) |
23
- * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, webhook inbound), `identity-source@1`, `directory@1` (org config `url` of a directory book) and tool `post_announcement` (default policy ask, posts to the platform); deployment config `platformUrl`, `tenant`, `clientId`, secret `clientSecret`. Its `src/index.ts` also exports `makeFakeImChannel`, `fakeImIdentitySource`, `fakeImDirectory` for test extensions that need one part |
23
+ * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, files via `sendFile`, webhook inbound), `identity-source@1`, `directory@1` (org config `url` of a directory book) and tool `post_announcement` (default policy ask, posts to the platform); deployment config `platformUrl`, `tenant`, `clientId`, secret `clientSecret`. Its `src/index.ts` also exports `makeFakeImChannel`, `fakeImIdentitySource`, `fakeImDirectory` for test extensions that need one part |
24
24
  * | `fake-web` / `fake-web-2` | `web-search@1` and `web-fetch@1`, scripted by a prefix of the query or of the fetched URL's path (`error:<kind>`, `throw:`, `hang:`, `redirect:<url>`, `junk:`, `empty:`, `big:<n>`; see `makeFakeWeb`); results name the provider; org config secret `token`, `configured()` iff it is set (throws for `throw:configured`); calls recorded on `globalThis.__fakeWeb` (`fakeWebProbe`) |
25
25
  * | `fake-context` | `context@1` scripted by its deployment config (`text`, default "fake context"; `mode` `ok` / `null` / `throw` / `hang`); calls recorded on `globalThis.__fakeContext` (`fakeContextProbe`); tool `note` (`sources` web and channel_dm) |
26
26
  * | `fake-client` | client extension (`permissions.client`, no extension point): components `hud` (`conversation.properties.section`, server view with `data`), `brand` (`shell.brand`, renders `builtin` in `data-testid="fake-client-brand"`), `empty` (`conversation.empty`), `frame` (`conversation.composer.frame`) and `fx` (`shell.overlay`); `client/styles/fake.css` (outline-color on `button.primary` and the composer's buttons, `--cx-fake-client-run` while `run=running`); an `events` listener storing the last event type; theme `fake`; `suggestedAppearance` = theme `fake` + `shell.brand` -> `brand` |
package/dist/index.d.ts CHANGED
@@ -7,17 +7,17 @@ export { type ConversationEvent, createDb, gatewayReplicasKey, type KernelConfig
7
7
  export { createFreshDatabase, startPostgresContainer, startTestPostgres, startTestRedis, startTestS3, TEST_PG_IMAGE, TEST_S3_IMAGE, type TestContainer, type TestS3, } from "./containers.js";
8
8
  export { createDualReplicaHarness, type DualReplicaOptions, type ExtraReplicaHandle, type Harness, REPLICA_HEADER, type ReplicaHandle, type ReplicaResponse, replicaOf, } from "./dual-replica.js";
9
9
  export { assertExtensionSecretsReachable, extensionDeploymentSecretValues, } from "./extension-config.js";
10
- export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, type FakeChannelCheckCall, type FakeChannelFailMatch, type FakeChannelPost, type FakeChannelSent, type FakeChannelServer, type FakeChannelServerOptions, type FakeChannelStream, type FakeChannelUser, type FakeDirectoryBook, type FakeSenderProfile, fakeCardAction, fakeDirectoryMember, fakeDm, fakeGroupMessage, fakeWebhookChallenge, fakeWebhookEvents, signFakeWebhook, startFakeChannelServer, } from "./fake-channel.js";
10
+ export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, type FakeChannelCheckCall, type FakeChannelFailMatch, type FakeChannelPost, type FakeChannelSent, type FakeChannelSentFile, type FakeChannelServer, type FakeChannelServerOptions, type FakeChannelStream, type FakeChannelUser, type FakeDirectoryBook, type FakeSenderProfile, fakeCardAction, fakeDirectoryMember, fakeDm, fakeGroupMessage, fakeWebhookChallenge, fakeWebhookEvents, signFakeWebhook, startFakeChannelServer, } from "./fake-channel.js";
11
11
  export { type FakeE2BCall, type FakeE2BMatch, type FakeE2BOptions, type FakeE2BSandbox, type FakeE2BServer, startFakeE2B, } from "./fake-e2b.js";
12
12
  export { type FakeGitCommitOptions, type FakeGitRequest, type FakeGitServer, type FakeGitServerOptions, startFakeGitServer, } from "./fake-git-server.js";
13
- export { encryptLarkWebhook, type FakeLarkAck, type FakeLarkApi, type FakeLarkButton, type FakeLarkCall, type FakeLarkDepartment, type FakeLarkFailure, type FakeLarkMessage, type FakeLarkOptions, type FakeLarkServer, type FakeLarkUser, findLarkButton, larkCardAction, larkMessageEvent, signLarkWebhook, startFakeLark, } from "./fake-lark.js";
13
+ export { encryptLarkWebhook, type FakeLarkAck, type FakeLarkApi, type FakeLarkButton, type FakeLarkCall, type FakeLarkDepartment, type FakeLarkFailure, type FakeLarkMessage, type FakeLarkOptions, type FakeLarkServer, type FakeLarkUpload, type FakeLarkUser, findLarkButton, larkCardAction, larkMessageEvent, signLarkWebhook, startFakeLark, } from "./fake-lark.js";
14
14
  export { type FakeMarketplace, type FakeMarketplaceRequest, startFakeMarketplace, } from "./fake-marketplace.js";
15
15
  export { type FakeMcpCallInfo, type FakeMcpHandlerContext, type FakeMcpPrompt, type FakeMcpRequest, type FakeMcpResource, FakeMcpRpcError, type FakeMcpServer, type FakeMcpServerOptions, type FakeMcpTool, startFakeMcpServer, } from "./fake-mcp-server.js";
16
16
  export { type FakeModelServer, type FakeRequest, type FakeResponse, startFakeModelServer, } from "./fake-model-server.js";
17
17
  export { type FakeNpmPackage, type FakeNpmRegistry, npmProvenanceAttestations, startFakeNpmRegistry, } from "./fake-npm-registry.js";
18
18
  export { type FakeOAuthClient, type FakeOAuthServer, type FakeOAuthServerOptions, type FakeTokenRequest, startFakeOAuthServer, } from "./fake-oauth-server.js";
19
19
  export { defaultFakeOpenApiSpec, type FakeOpenApiRequest, type FakeOpenApiServer, type FakeOpenApiServerOptions, type FakePet, startFakeOpenApiServer, } from "./fake-openapi-server.js";
20
- export { type FakeSlackAck, type FakeSlackCall, type FakeSlackFailure, type FakeSlackMessage, type FakeSlackOptions, type FakeSlackServer, type FakeSlackUser, findSlackButton, signSlackWebhook, slackBlockAction, slackDmEvent, slackEventCallback, slackInteractiveForm, slackMentionEvent, startFakeSlack, } from "./fake-slack.js";
20
+ export { type FakeSlackAck, type FakeSlackCall, type FakeSlackFailure, type FakeSlackFile, type FakeSlackMessage, type FakeSlackOptions, type FakeSlackServer, type FakeSlackUser, findSlackButton, signSlackWebhook, slackBlockAction, slackDmEvent, slackEventCallback, slackInteractiveForm, slackMentionEvent, startFakeSlack, } from "./fake-slack.js";
21
21
  export { type FakeTelegramBot, type FakeTelegramCall, type FakeTelegramFailure, type FakeTelegramMessage, type FakeTelegramOptions, type FakeTelegramServer, findTelegramButton, startFakeTelegram, type TgChat, type TgUser, telegramCallback, telegramGroupMessage, telegramPrivateMessage, telegramWebhookHeaders, } from "./fake-telegram.js";
22
22
  export { FAKE_EXTENSIONS, type FakeExtensionName, fakeExtensionDir, fakeExtensionEntry, type PackedFixture, packFixture, } from "./fixtures.js";
23
23
  export { cardRecorded, cookieRequest, createAgent, createConversation, createLocalAccount, createOrg, enableModelProviders, eventsOf, joinOrg, type KernelApp, type KernelRequest, type KernelRequestOptions, type KernelResponse, login, pidOwningLocalPort, postMessage, sleep, startTestKernel, TEST_PASSWORD, type TestKernel, testKernelConfig, truncateTables, waitFor, waitForEvent, waitForTerminal, } from "./kernel-helpers.js";
@@ -52,6 +52,14 @@ export interface SandboxPermissionFixture {
52
52
  * Either way the device needs no name resolution of its own for endpoint names.
53
53
  */
54
54
  readonly access: "direct" | "proxy";
55
+ /**
56
+ * "unavailable" where the fixture cannot make the allowlisted name lead to `granted` without
57
+ * changing the host (macOS: no hosts-file entry, and the runtime's proxy refuses a name that
58
+ * resolves to loopback, by design). The by-name positives are then skipped and `granted`
59
+ * must see no connection at all; every negative still runs. The positive allowlist reach is
60
+ * then the provider's own test's evidence (state it next to the fixture). Default "available".
61
+ */
62
+ readonly namedReach?: "available" | "unavailable";
55
63
  };
56
64
  /**
57
65
  * Set to "refused" when the provider refuses a restricted filesystem with the `environment`
@@ -60,6 +68,31 @@ export interface SandboxPermissionFixture {
60
68
  * otherwise probe a restricted operation on the environment network. Default: "supported".
61
69
  */
62
70
  readonly restrictedEnvironment?: "supported" | "refused";
71
+ /**
72
+ * How restricted commands meet the mandatory write denies in other spellings of a protected
73
+ * name. "nfkc" (default): every spelling whose NFKC case fold is protected is refused, as the
74
+ * shared SDK policy compares names. "filesystem": the runtime enforces paths as the filesystem
75
+ * resolves them (macOS Seatbelt on case-insensitive APFS: ASCII case and the Unicode case folds
76
+ * APFS applies, such as the Kelvin sign for `k`, reach the protected file and are refused, while
77
+ * compatibility forms such as fullwidth letters are distinct files there); the harness then
78
+ * proves that a fullwidth spelling created a distinct file and never the protected one.
79
+ */
80
+ readonly foldedNames?: "nfkc" | "filesystem";
81
+ /**
82
+ * Whether restricted none/allowlist operations may listen on loopback. "allowed" (default):
83
+ * loopback only, every wildcard address refused, and a UNIX socket inside the root works.
84
+ * "refused": the runtime refuses every listener, loopback and UNIX sockets inside the root
85
+ * included (the macOS worker runs its runtime with local binding off).
86
+ */
87
+ readonly restrictedLoopbackListen?: "allowed" | "refused";
88
+ /**
89
+ * Whether cancellation must also end a descendant that left the command's process group
90
+ * (fork + setpgid). "ended" (default): it must, as Linux PID namespaces and cgroups provide.
91
+ * "not-promised": the runtime ends the owned process group and what stays in it, and does not
92
+ * promise to rediscover a regrouped descendant (macOS, permission operation contract "Explicit
93
+ * background supervision"); the harness then leaves that case out.
94
+ */
95
+ readonly regroupedDescendants?: "ended" | "not-promised";
63
96
  /** The provider's own runtime report; the harness never infers support from a fixture. */
64
97
  support(): Promise<SandboxPermissionSupport>;
65
98
  /** A fresh operation (new operation ID) for the grant, through the provider's factory. */
@@ -18,6 +18,9 @@ def flipper(buffer, good, bad):
18
18
  ok = 0
19
19
  if mode == "connect":
20
20
  def sockaddr(host, port):
21
+ if sys.platform == "darwin":
22
+ # BSD sockaddr_in: a length byte, then a one-byte family
23
+ return struct.pack("BBH4s8x", 16, socket.AF_INET, socket.htons(port), socket.inet_aton(host))
21
24
  return struct.pack("HH4s8x", socket.AF_INET, socket.htons(port), socket.inet_aton(host))
22
25
  if sys.argv[3] == "proxy":
23
26
  # The allowed target is the operation's own HTTP proxy, taken from its environment.
@@ -78,7 +81,8 @@ print(" ".join(out))
78
81
  `;
79
82
  /** A Full-access UNIX service (stream, seqpacket, datagram) counting every client it sees. */
80
83
  const UNIX_SERVER = `
81
- import os, socket, sys, threading
84
+ import errno, os, socket, sys, threading
85
+ UNSUPPORTED = (errno.EPROTONOSUPPORT, errno.ESOCKTNOSUPPORT, errno.EPROTOTYPE, errno.EOPNOTSUPP)
82
86
  path, counter = sys.argv[1], sys.argv[2]
83
87
  lock = threading.Lock()
84
88
  count = [0]
@@ -89,7 +93,14 @@ def seen():
89
93
  handle.write(str(count[0]))
90
94
  os.replace(counter + ".tmp", counter)
91
95
  def serve(kind, suffix):
92
- s = socket.socket(socket.AF_UNIX, kind)
96
+ try:
97
+ s = socket.socket(socket.AF_UNIX, kind)
98
+ except OSError as error:
99
+ if error.errno not in UNSUPPORTED:
100
+ raise
101
+ # this OS has no such UNIX socket type (macOS: SOCK_SEQPACKET): mark it and stop
102
+ open(path + suffix, "w").close()
103
+ return
93
104
  s.bind(path + suffix)
94
105
  if kind == socket.SOCK_DGRAM:
95
106
  while True:
@@ -112,22 +123,41 @@ threading.Event().wait()
112
123
  `;
113
124
  /** Tries every way to reach the outside UNIX service; prints ok/denied per attempt. */
114
125
  const UNIX_CLIENT = `
115
- import socket, sys
126
+ import errno, socket, sys
127
+ UNSUPPORTED = (errno.EPROTONOSUPPORT, errno.ESOCKTNOSUPPORT, errno.EPROTOTYPE, errno.EOPNOTSUPP)
116
128
  path, link = sys.argv[1], sys.argv[2]
129
+ class Unsupported(Exception):
130
+ pass
131
+ def make(create):
132
+ # the OS has no such UNIX socket type at all (macOS: SOCK_SEQPACKET, SOCK_RAW)
133
+ try:
134
+ return create()
135
+ except OSError as error:
136
+ if error.errno in UNSUPPORTED:
137
+ raise Unsupported()
138
+ raise
117
139
  def attempt(name, action):
118
140
  try:
119
141
  action()
120
142
  return name + "=ok"
143
+ except Unsupported:
144
+ return name + "=unsupported"
121
145
  except OSError:
122
146
  return name + "=denied"
123
147
  def connect(kind, target):
124
- socket.socket(socket.AF_UNIX, kind).connect(target)
148
+ make(lambda: socket.socket(socket.AF_UNIX, kind)).connect(target)
125
149
  def send(kind):
126
- socket.socket(socket.AF_UNIX, kind).sendto(b"x", path + ".dgram")
150
+ make(lambda: socket.socket(socket.AF_UNIX, kind)).sendto(b"x", path + ".dgram")
127
151
  def pair(kind):
128
152
  # An explicit address on a socketpair datagram socket is honoured by the kernel.
129
- first, _ = socket.socketpair(socket.AF_UNIX, kind)
130
- first.sendto(b"x", path + ".dgram")
153
+ first, _ = make(lambda: socket.socketpair(socket.AF_UNIX, kind))
154
+ try:
155
+ first.sendto(b"x", path + ".dgram")
156
+ except OSError as error:
157
+ # the OS ignores no explicit address on a connected socket (macOS): no such vector there
158
+ if error.errno == errno.EISCONN:
159
+ raise Unsupported()
160
+ raise
131
161
  print(" ".join([
132
162
  attempt("stream", lambda: connect(socket.SOCK_STREAM, path)),
133
163
  attempt("seqpacket", lambda: connect(socket.SOCK_SEQPACKET, path + ".seq")),
@@ -159,8 +189,12 @@ os.makedirs(base + "/dir")
159
189
  os.symlink(outside, base + "/link")
160
190
  open(base + "/swapping", "w").close()
161
191
  swaps = 0
192
+ def exchange(a, b):
193
+ if sys.platform == "darwin":
194
+ return libc.renamex_np(a, b, 2) # RENAME_SWAP
195
+ return libc.renameat2(-100, a, -100, b, 2) # RENAME_EXCHANGE
162
196
  while not os.path.exists(stop):
163
- if libc.renameat2(-100, (base + "/dir").encode(), -100, (base + "/link").encode(), 2) == 0:
197
+ if exchange((base + "/dir").encode(), (base + "/link").encode()) == 0:
164
198
  swaps += 1
165
199
  print("swaps=%d" % swaps)
166
200
  `;
@@ -310,7 +344,7 @@ export async function runSandboxPermissionConformance(fixture) {
310
344
  };
311
345
  // Positive controls: ordinary shell, Python, Node and native work inside the root.
312
346
  const shell = await exec(restricted(), "cat inroot.txt && printf shell > shell.txt && mkdir -p d/e && printf x > d/e/f && " +
313
- "chmod 755 d/e/f && touch -d 2001-01-01 d/e/f && ln -s shell.txt alias && cat alias");
347
+ "chmod 755 d/e/f && touch -t 200101010000 d/e/f && ln -s shell.txt alias && cat alias");
314
348
  assert.equal(shell.exitCode, 0, `restricted shell work must succeed: ${shell.stderr}`);
315
349
  assert.equal(shell.stdout, "inrootshell");
316
350
  assert.equal(await fixture.inspect.mode(at(root, "d/e/f")), 0o755, "chmod inside the root");
@@ -448,10 +482,14 @@ export async function runSandboxPermissionConformance(fixture) {
448
482
  ".envrc",
449
483
  ".npmrc",
450
484
  "deep/.npmrc",
451
- ".BASHRC",
452
- ".envrc",
485
+ ...(fixture.foldedNames === "filesystem" ? [".bashrc"] : [".BASHRC", ".envrc"]),
453
486
  ])
454
487
  assert.equal(await fixture.inspect.readFile(at(root, path)), null, `mandatory deny: ${path}`);
488
+ if (fixture.foldedNames === "filesystem") {
489
+ // fullwidth spellings are their own files on such a filesystem, never the protected ones
490
+ for (const path of [".BASHRC", ".envrc"])
491
+ assert.equal(text(await fixture.inspect.readFile(at(root, path))), "x", `distinct ${path}`);
492
+ }
455
493
  await denied((await native(restricted())).writeFile(at(root, "repo/.git/modules/sub/config"), bytes, signal), "native write of a submodule's config");
456
494
  await denied((await native(restricted())).writeFile(at(root, "bare2/HEAD"), bytes, signal), "native write of a bare-repository HEAD");
457
495
  // No repository can be forged inside git's own allowlisted subtrees, and hook managers
@@ -505,7 +543,7 @@ export async function runSandboxPermissionConformance(fixture) {
505
543
  assert(!reads.stdout.includes(secret), "restricted reads must not reach the sibling");
506
544
  await exec(restricted(), `printf pwn > ${quote(at(sibling, "w1"))}; printf pwn > linked/w2; printf pwn > escape; ` +
507
545
  `chmod 777 ${quote(at(sibling, "secret"))}; chmod 777 escape; ` +
508
- `touch -d 2001-01-01 ${quote(at(sibling, "secret"))}; true`);
546
+ `touch -t 200101010000 ${quote(at(sibling, "secret"))}; true`);
509
547
  assert.equal(await fixture.inspect.readFile(at(sibling, "w1")), null, "sibling write");
510
548
  assert.equal(await fixture.inspect.readFile(at(sibling, "w2")), null, "symlinked dir write");
511
549
  await siblingIntact("restricted writes and chmod must not change the sibling");
@@ -523,13 +561,16 @@ export async function runSandboxPermissionConformance(fixture) {
523
561
  await siblingIntact("native denials must leave the sibling unchanged");
524
562
  // Network: only the granted endpoint, and only while allowlisted.
525
563
  const base = await receipts();
526
- const positives = proxied
527
- ? [byName(granted), urlopen(granted)]
528
- : [
529
- connect(granted),
530
- `curl -fsS -m 10 -o /dev/null http://${granted.address}:${granted.port}/`,
531
- `node -e ${quote(`require("net").connect(${granted.port}, ${JSON.stringify(granted.address)}).on("connect", function () { this.end() })`)}`,
532
- ];
564
+ const namedReach = fixture.endpoints.namedReach !== "unavailable";
565
+ const positives = !namedReach
566
+ ? []
567
+ : proxied
568
+ ? [byName(granted), urlopen(granted)]
569
+ : [
570
+ connect(granted),
571
+ `curl -fsS -m 10 -o /dev/null http://${granted.address}:${granted.port}/`,
572
+ `node -e ${quote(`require("net").connect(${granted.port}, ${JSON.stringify(granted.address)}).on("connect", function () { this.end() })`)}`,
573
+ ];
533
574
  for (const command of positives) {
534
575
  const result = await exec(restricted(allowlisted), command);
535
576
  assert.equal(result.exitCode, 0, `granted endpoint must work: ${command}: ${result.stderr}`);
@@ -557,7 +598,9 @@ export async function runSandboxPermissionConformance(fixture) {
557
598
  // Restricted network none/allowlist may listen on loopback only.
558
599
  for (const network of [{ kind: "none" }, allowlisted]) {
559
600
  const binds = await exec(restricted(network), `python3 -c ${quote(BIND_PROGRAM)}`);
560
- assert.equal(binds.stdout.trim(), "127.0.0.1=ok ::1=ok 0.0.0.0=denied ::=denied unspec=denied", `restricted ${network.kind} binds loopback only: ${binds.stderr}`);
601
+ assert.equal(binds.stdout.trim(), fixture.restrictedLoopbackListen === "refused"
602
+ ? "127.0.0.1=denied ::1=denied 0.0.0.0=denied ::=denied unspec=denied"
603
+ : "127.0.0.1=ok ::1=ok 0.0.0.0=denied ::=denied unspec=denied", `restricted ${network.kind} binds loopback only: ${binds.stderr}`);
561
604
  }
562
605
  // Pathname UNIX sockets: a service outside the roots is unreachable under every network kind
563
606
  // (including environment, which lifts only the network filter); one inside the root works.
@@ -573,23 +616,51 @@ export async function runSandboxPermissionConformance(fixture) {
573
616
  await denied(exec(restricted({ kind: "environment" }), `printf ran > ${quote(at(root, "env-ran"))}`), "a restricted environment-network operation must be refused by policy");
574
617
  assert.equal(await fixture.inspect.readFile(at(root, "env-ran")), null);
575
618
  }
619
+ // The OS's own UNIX socket types, probed outside every restriction (unsupported types are
620
+ // reported as such by Full access and expected the same in restricted operations)
621
+ const types = await exec(full, `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "missing.sock"))} missing-link.sock`);
622
+ const kinds = types.stdout
623
+ .trim()
624
+ .split(" ")
625
+ .map((entry) => entry.split("="));
626
+ for (const name of ["stream", "dgram", "link"])
627
+ assert.notEqual(kinds.find(([kind]) => kind === name)?.[1], "unsupported", `UNIX ${name} sockets are required: ${types.stdout} ${types.stderr}`);
628
+ const expectWhen = (reachable) => kinds
629
+ .map(([kind, state]) => state === "unsupported"
630
+ ? `${kind}=unsupported`
631
+ : `${kind}=${reachable ? "ok" : "denied"}`)
632
+ .join(" ");
576
633
  for (const network of [
577
634
  { kind: "none" },
578
635
  allowlisted,
579
636
  ...(fixture.restrictedEnvironment === "refused" ? [] : [{ kind: "environment" }]),
580
637
  ]) {
581
638
  const probe = await exec(restricted(network), `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "srv.sock"))} srv-link.sock`);
582
- assert.equal(probe.stdout.trim(), "stream=denied seqpacket=denied dgram=denied raw=denied link=denied pair-dgram=denied pair-raw=denied", `restricted ${network.kind} must not reach a UNIX service outside the roots: ${probe.stderr}`);
639
+ assert.equal(
640
+ // a type the OS lacks may also be refused before the OS says so: both reach nothing
641
+ probe.stdout
642
+ .trim()
643
+ .split(" ")
644
+ .map((entry) => entry.endsWith("=denied") &&
645
+ kinds.some(([kind, state]) => `${kind}=denied` === entry && state === "unsupported")
646
+ ? entry.replace("=denied", "=unsupported")
647
+ : entry)
648
+ .join(" "), expectWhen(false), `restricted ${network.kind} must not reach a UNIX service outside the roots: ${probe.stderr}`);
583
649
  const inside = await exec(restricted(network), `python3 -c ${quote(UNIX_ROUNDTRIP)} ${quote(at(root, `own-${network.kind}.sock`))}`);
584
- assert.equal(inside.stdout.trim(), "roundtrip=ok", `in-root UNIX socket: ${inside.stderr}`);
650
+ if (fixture.restrictedLoopbackListen === "refused")
651
+ // no listener at all: binding a UNIX socket fails before any roundtrip
652
+ assert.notEqual(inside.stdout.trim(), "roundtrip=ok", "no restricted UNIX listener");
653
+ else
654
+ assert.equal(inside.stdout.trim(), "roundtrip=ok", `in-root UNIX socket: ${inside.stderr}`);
585
655
  }
586
656
  assert.equal(text(await fixture.inspect.readFile(at(sibling, "srv.count"))), "0", "the outside UNIX service must see no client");
587
657
  // The same client under Full access reaches the service seven times: the probe is real.
588
658
  const control = await exec(full, `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "srv.sock"))} srv-link.sock`);
589
- assert.equal(control.stdout.trim(), "stream=ok seqpacket=ok dgram=ok raw=ok link=ok pair-dgram=ok pair-raw=ok", `Full UNIX control: ${control.stderr}`);
659
+ assert.equal(control.stdout.trim(), expectWhen(true), `Full UNIX control: ${control.stderr}`);
660
+ const reached = String(kinds.filter(([, state]) => state !== "unsupported").length);
590
661
  await waitForFile(async (path) => {
591
662
  const data = await fixture.inspect.readFile(path);
592
- return text(data) === "7" ? data : null;
663
+ return text(data) === reached ? data : null;
593
664
  }, at(sibling, "srv.count"), outside);
594
665
  server.abort();
595
666
  await outside;
@@ -654,7 +725,9 @@ export async function runSandboxPermissionConformance(fixture) {
654
725
  await exec(full, `mv ${quote(root)} ${quote(moved)} && ln -s ${quote(sibling)} ${quote(root)} && touch ${quote(at(moved, "barrier-root"))}`);
655
726
  const swapped = await live;
656
727
  assert(!swapped.stdout.includes(secret), "a live operation must not follow a root swap");
657
- assert.equal(text(await fixture.inspect.readFile(at(moved, "in-place"))), "ok");
728
+ // an inode-pinned runtime (Landlock) keeps writing in the moved root; a path-based one
729
+ // (Seatbelt) refuses the moved path: either way nothing follows the swap
730
+ assert([null, "ok"].includes(text(await fixture.inspect.readFile(at(moved, "in-place")))), "a live operation writes in place or nowhere");
658
731
  await denied((async () => (await native(restricted())).writeFile(at(root, "fresh"), bytes, signal))(), "a fresh native operation must reject a swapped root");
659
732
  const fresh = await (await fixture.operation(restricted()))
660
733
  .exec({
@@ -720,12 +793,16 @@ export async function runSandboxPermissionConformance(fixture) {
720
793
  const keepAlive = exec(restricted(), `printf r > ready-keep; until [ -e release-keep ]; do sleep 0.01; done; printf done > kept`);
721
794
  await waitFor(at(root, "ready-keep"), keepAlive);
722
795
  const abort = new AbortController();
796
+ const regrouped = fixture.regroupedDescendants !== "not-promised";
723
797
  const cancelled = exec(restricted(), `(sleep 1000 & echo $! > p1); nohup sh -c 'sleep 1001' > /dev/null 2>&1 & echo $! > p2; ` +
724
798
  `setsid sleep 1002 > /dev/null 2>&1 & ` +
725
- `python3 -c ${quote("import os, time\nif os.fork() == 0:\n os.setpgid(0, 0)\n open('p3.tmp', 'w').write(str(os.getpid()))\n os.rename('p3.tmp', 'p3')\n time.sleep(1003)")} & ` +
726
- `until [ -e p3 ]; do sleep 0.01; done; printf r > ready-cancel; sleep 1004`, abort.signal);
799
+ (regrouped
800
+ ? `python3 -c ${quote("import os, time\nif os.fork() == 0:\n os.setpgid(0, 0)\n open('p3.tmp', 'w').write(str(os.getpid()))\n os.rename('p3.tmp', 'p3')\n time.sleep(1003)")} & ` +
801
+ `until [ -e p3 ]; do sleep 0.01; done; `
802
+ : "") +
803
+ `printf r > ready-cancel; sleep 1004`, abort.signal);
727
804
  await waitFor(at(root, "ready-cancel"), cancelled);
728
- const pids = await Promise.all(["p1", "p2", "p3"].map(async (name) => Number(text(await fixture.inspect.readFile(at(root, name))))));
805
+ const pids = await Promise.all((regrouped ? ["p1", "p2", "p3"] : ["p1", "p2"]).map(async (name) => Number(text(await fixture.inspect.readFile(at(root, name))))));
729
806
  assert.deepEqual(await fixture.inspect.alive(pids), pids, "descendants run before cancel");
730
807
  abort.abort();
731
808
  const stopped = await cancelled;
@@ -223,4 +223,23 @@ export const makeFakeImChannel = (
223
223
  const res = await post(c, "/update", body, signal);
224
224
  await res.body?.cancel();
225
225
  },
226
+ ...(features.files !== undefined && {
227
+ async sendFile({ config, target, file, signal, idempotencyKey, locale }) {
228
+ const c = config as ConnConfig;
229
+ const body = {
230
+ appId: c.appId,
231
+ target,
232
+ file: {
233
+ name: file.name,
234
+ contentType: file.contentType,
235
+ kind: file.kind,
236
+ data: Buffer.from(file.data).toString("base64"),
237
+ },
238
+ idempotencyKey,
239
+ locale,
240
+ };
241
+ const res = await post(c, "/send-file", body, signal);
242
+ return (await res.json()) as { messageId: string };
243
+ },
244
+ }),
226
245
  });
@@ -107,7 +107,15 @@ export default defineExtension({
107
107
  const config = () => Deployment.parse(ctx.config);
108
108
  ctx.provide(
109
109
  "channel@1",
110
- makeFakeImChannel({ cards: true, edit: true, threads: true }, { webhook: true }),
110
+ makeFakeImChannel(
111
+ {
112
+ cards: true,
113
+ edit: true,
114
+ threads: true,
115
+ files: { maxBytes: 20_971_520, imageMaxBytes: 10_485_760 },
116
+ },
117
+ { webhook: true },
118
+ ),
111
119
  );
112
120
  ctx.provide("identity-source@1", fakeImIdentitySource);
113
121
  ctx.provide("directory@1", fakeImDirectory);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/testing",
3
- "version": "0.1.0-rc.26",
3
+ "version": "0.1.0-rc.28",
4
4
  "description": "Test helpers for Capybara: test containers, dual-replica harness and fake third-party servers",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -47,18 +47,18 @@
47
47
  "tsx": "^4.23.15",
48
48
  "ws": "^8.22.0",
49
49
  "zod": "^4.6.7",
50
- "@capybara-hq/kernel": "^0.1.0-rc.44"
50
+ "@capybara-hq/kernel": "^0.1.0-rc.50"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/pg": "^8.23.1",
54
54
  "@types/ws": "^8.18.2",
55
- "@capybara-hq/plugin-client": "^0.1.0-rc.5",
56
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.32"
55
+ "@capybara-hq/plugin-client": "^0.1.0-rc.6",
56
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.36"
57
57
  },
58
58
  "peerDependencies": {
59
59
  "vitest": "^5.0.5",
60
- "@capybara-hq/plugin-tools": "^0.1.0-rc.17",
61
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.32"
60
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.36",
61
+ "@capybara-hq/plugin-tools": "^0.1.0-rc.17"
62
62
  },
63
63
  "peerDependenciesMeta": {
64
64
  "@capybara-hq/plugin-tools": {