@capybara-hq/testing 0.1.0-rc.3 → 0.1.0-rc.30

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 (92) hide show
  1. package/dist/containers.d.ts +7 -2
  2. package/dist/containers.js +7 -3
  3. package/dist/dual-replica.d.ts +15 -1
  4. package/dist/dual-replica.js +49 -0
  5. package/dist/fake-channel.d.ts +51 -3
  6. package/dist/fake-channel.js +71 -3
  7. package/dist/fake-e2b.d.ts +34 -0
  8. package/dist/fake-e2b.js +95 -1
  9. package/dist/fake-git-server.d.ts +32 -4
  10. package/dist/fake-git-server.js +87 -19
  11. package/dist/fake-lark.d.ts +12 -1
  12. package/dist/fake-lark.js +63 -10
  13. package/dist/fake-oauth-server.d.ts +16 -2
  14. package/dist/fake-oauth-server.js +21 -1
  15. package/dist/fake-slack.d.ts +17 -1
  16. package/dist/fake-slack.js +98 -0
  17. package/dist/fake-telegram.d.ts +173 -0
  18. package/dist/fake-telegram.js +632 -0
  19. package/dist/fixtures.d.ts +25 -7
  20. package/dist/fixtures.js +35 -7
  21. package/dist/index.d.ts +12 -8
  22. package/dist/index.js +8 -4
  23. package/dist/kernel-helpers.d.ts +16 -4
  24. package/dist/kernel-helpers.js +39 -4
  25. package/dist/media-samples.d.ts +2 -0
  26. package/dist/media-samples.js +2 -0
  27. package/dist/model-conformance.d.ts +15 -10
  28. package/dist/model-conformance.js +87 -14
  29. package/dist/push-conformance.d.ts +31 -0
  30. package/dist/push-conformance.js +160 -0
  31. package/dist/replica-runner.js +2 -0
  32. package/dist/sandbox-native-conformance.d.ts +31 -0
  33. package/dist/sandbox-native-conformance.js +153 -0
  34. package/dist/sandbox-permission-conformance.d.ts +307 -0
  35. package/dist/sandbox-permission-conformance.js +1475 -0
  36. package/fixtures/extensions/fake-client/.capybara-plugin/plugin.json +11 -0
  37. package/fixtures/extensions/fake-client/client/styles/fake.css +11 -0
  38. package/fixtures/extensions/fake-client/package.json +12 -0
  39. package/fixtures/extensions/fake-client/src/client.tsx +51 -0
  40. package/fixtures/extensions/fake-client/src/index.ts +43 -0
  41. package/fixtures/extensions/fake-client/themes/fake.json +11 -0
  42. package/fixtures/extensions/fake-client-broken/.capybara-plugin/plugin.json +7 -0
  43. package/fixtures/extensions/fake-client-broken/package.json +12 -0
  44. package/fixtures/extensions/fake-client-broken/src/client.tsx +22 -0
  45. package/fixtures/extensions/fake-client-broken/src/index.ts +27 -0
  46. package/fixtures/extensions/fake-config-form/.capybara-plugin/plugin.json +11 -0
  47. package/fixtures/extensions/fake-config-form/package.json +12 -0
  48. package/fixtures/extensions/fake-config-form/src/index.ts +205 -0
  49. package/fixtures/extensions/fake-connector/src/index.ts +41 -21
  50. package/fixtures/extensions/fake-context/.capybara-plugin/plugin.json +7 -0
  51. package/fixtures/extensions/fake-context/package.json +12 -0
  52. package/fixtures/extensions/fake-context/src/index.ts +81 -0
  53. package/fixtures/extensions/fake-dep-provider/src/index.ts +1 -1
  54. package/fixtures/extensions/fake-dep-requirer/src/index.ts +1 -1
  55. package/fixtures/extensions/fake-embed/src/index.ts +26 -26
  56. package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -1
  57. package/fixtures/extensions/fake-im/guides/fake-im-app.md +32 -0
  58. package/fixtures/extensions/fake-im/guides/fake-im-app.zh.md +32 -0
  59. package/fixtures/extensions/fake-im/src/channel.ts +22 -1
  60. package/fixtures/extensions/fake-im/src/checks.ts +94 -0
  61. package/fixtures/extensions/fake-im/src/index.ts +45 -2
  62. package/fixtures/extensions/fake-lifecycle/.capybara-plugin/plugin.json +7 -0
  63. package/fixtures/extensions/fake-lifecycle/migrations/0001_init.sql +16 -0
  64. package/fixtures/extensions/fake-lifecycle/package.json +12 -0
  65. package/fixtures/extensions/fake-lifecycle/src/index.ts +72 -0
  66. package/fixtures/extensions/fake-openapi/src/index.ts +46 -34
  67. package/fixtures/extensions/fake-push/.capybara-plugin/plugin.json +13 -0
  68. package/fixtures/extensions/fake-push/guides/fake-push-key.md +6 -0
  69. package/fixtures/extensions/fake-push/guides/fake-push-key.zh.md +6 -0
  70. package/fixtures/extensions/fake-push/migrations/0001_sends.sql +9 -0
  71. package/fixtures/extensions/fake-push/package.json +12 -0
  72. package/fixtures/extensions/fake-push/src/check.ts +40 -0
  73. package/fixtures/extensions/fake-push/src/index.ts +48 -0
  74. package/fixtures/extensions/fake-push/src/push.ts +103 -0
  75. package/fixtures/extensions/fake-storage-user/src/index.ts +1 -1
  76. package/fixtures/extensions/fake-tools-ui/skills/fake-notes/SKILL.md +1 -1
  77. package/fixtures/extensions/fake-tools-ui/src/index.ts +62 -3
  78. package/fixtures/extensions/fake-web/.capybara-plugin/plugin.json +7 -0
  79. package/fixtures/extensions/fake-web/package.json +12 -0
  80. package/fixtures/extensions/fake-web/src/index.ts +22 -0
  81. package/fixtures/extensions/fake-web/src/web.ts +183 -0
  82. package/fixtures/extensions/fake-web-2/.capybara-plugin/plugin.json +7 -0
  83. package/fixtures/extensions/fake-web-2/package.json +12 -0
  84. package/fixtures/extensions/fake-web-2/src/index.ts +16 -0
  85. package/fixtures/extensions/fake-web-2/src/web.ts +183 -0
  86. package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
  87. package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
  88. package/fixtures/plugins/fake-theme/logo.svg +1 -0
  89. package/fixtures/plugins/fake-theme/package.json +8 -0
  90. package/fixtures/plugins/fake-theme/themes/neon-grid.json +13 -0
  91. package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
  92. package/package.json +6 -5
@@ -3,8 +3,30 @@ export interface FakeGitRequest {
3
3
  method: string;
4
4
  /** Path and query, e.g. `/x.git/info/refs?service=git-upload-pack`. */
5
5
  path: string;
6
- /** The `Authorization` header. */
6
+ /** `git-upload-pack` or `git-receive-pack` for smart-HTTP requests. */
7
+ service?: string;
8
+ /** False when `requireBasic` is set and the request did not carry the matching Basic auth. */
9
+ authorized: boolean;
10
+ /**
11
+ * The `Authorization` header value; set unless `recordAuthorization: false` (the catalog tests
12
+ * assert on it; tests that handle real credentials pass false).
13
+ */
7
14
  authorization?: string;
15
+ /** Lower-case names of the request headers; values are never recorded (no credential in here). */
16
+ headerNames: string[];
17
+ }
18
+ export interface FakeGitServerOptions {
19
+ /** Repos (`owner/repo` or `repo`) created as bare repos at start. */
20
+ repos?: string[];
21
+ /** Seed each of `repos` with one commit on `main` so clones are not empty (default true). */
22
+ seed?: boolean;
23
+ /** Answers 401 (`WWW-Authenticate: Basic realm="fake"`) unless the request carries this Basic auth. */
24
+ /** Record each request's `Authorization` value in `requests` (default true, for tests of what a client sends; pass false to record names only). */
25
+ recordAuthorization?: boolean;
26
+ requireBasic?: {
27
+ username: string;
28
+ password: string;
29
+ };
8
30
  }
9
31
  /** Entries that are not regular files, for tests of refused trees. */
10
32
  export interface FakeGitCommitOptions {
@@ -40,13 +62,19 @@ export interface FakeGitServer {
40
62
  commit(repo: string, files: Record<string, string>, opts?: FakeGitCommitOptions): Promise<string>;
41
63
  /** Makes every request answer 302 to `location` (`null` restores it). */
42
64
  setRedirect(location: string | null): void;
65
+ /** The next request (only) answers `status` with `body`. */
66
+ failNext(status: number, body?: string): void;
67
+ /** The next request (only) answers 302 to `location`. */
68
+ redirectNext(location: string): void;
69
+ /** The sha `ref` (e.g. `refs/heads/main`) points at in the bare repo, or undefined. */
70
+ refOf(repo: string, ref: string): Promise<string | undefined>;
43
71
  /** The requests received, in order. */
44
72
  requests: FakeGitRequest[];
45
73
  stop(): Promise<void>;
46
74
  }
47
75
  /**
48
- * A fake git host: bare repos in a temp dir, served read-only by the system `git http-backend`
49
- * (smart HTTP, as CGI) over a loopback http server. Repos allow fetching any reachable commit by sha
76
+ * A fake git host: bare repos in a temp dir, served by the system `git http-backend`
77
+ * (smart HTTP, as CGI, pushes included) over a loopback http server. Repos allow fetching any reachable commit by sha
50
78
  * (`uploadpack.allowReachableSHA1InWant`, as GitHub does). Needs `git` on PATH.
51
79
  *
52
80
  * Spawning git is what these tests spend their time on, and it slows down most under load, so the
@@ -54,4 +82,4 @@ export interface FakeGitServer {
54
82
  * `git fast-import`, and a ref advertisement (`GET …/info/refs`) is answered by http-backend once per
55
83
  * repo state, then repeated until the next commit to that repo.
56
84
  */
57
- export declare function startFakeGitServer(): Promise<FakeGitServer>;
85
+ export declare function startFakeGitServer(options?: FakeGitServerOptions): Promise<FakeGitServer>;
@@ -4,7 +4,7 @@ import { appendFile, mkdtemp, readFile, rm } from "node:fs/promises";
4
4
  import { createServer } from "node:http";
5
5
  import { tmpdir } from "node:os";
6
6
  import { join, posix } from "node:path";
7
- const REPO_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
7
+ const REPO_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*(\/[A-Za-z0-9][A-Za-z0-9._-]*)?$/;
8
8
  /** Git runs with no user or system config, so a developer's settings never change the repos. */
9
9
  function gitEnv(extra = {}) {
10
10
  return {
@@ -56,7 +56,7 @@ function git(args, o = {}) {
56
56
  }
57
57
  });
58
58
  }
59
- /** Starts `git http-backend` as a CGI script for one request (smart HTTP, read-only). */
59
+ /** Starts `git http-backend` as a CGI script for one request (smart HTTP, push enabled). */
60
60
  function spawnCgi(root, req) {
61
61
  const url = new URL(req.url ?? "/", "http://127.0.0.1");
62
62
  const env = {
@@ -77,7 +77,9 @@ function spawnCgi(root, req) {
77
77
  const enc = req.headers["content-encoding"];
78
78
  if (typeof enc === "string")
79
79
  env.HTTP_CONTENT_ENCODING = enc;
80
- const p = spawn("git", ["http-backend"], { env: gitEnv(env) });
80
+ const p = spawn("git", ["-c", "http.receivepack=true", "http-backend"], {
81
+ env: gitEnv(env),
82
+ });
81
83
  // http-backend may exit without reading the whole body (a GET, or a request it refuses): the
82
84
  // write then fails with EPIPE. Its exit status and output decide the response, not the pipe.
83
85
  p.stdin.on("error", () => { });
@@ -129,8 +131,10 @@ function serveCgi(root, req, res) {
129
131
  res.writeHead(h.status, h.headers);
130
132
  res.write(head.subarray(h.bodyStart));
131
133
  });
134
+ // A child that could not be spawned emits 'error' and then 'close': only the first writes a head
135
+ // (a second writeHead throws ERR_HTTP_HEADERS_SENT, an uncaught exception).
132
136
  p.on("close", () => {
133
- if (!headDone)
137
+ if (!headDone && !res.headersSent)
134
138
  res.writeHead(502);
135
139
  res.end();
136
140
  });
@@ -167,8 +171,8 @@ const fastImportPath = (path) => /^"|[\n"\\]/.test(path)
167
171
  ? `"${path.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`
168
172
  : path;
169
173
  /**
170
- * A fake git host: bare repos in a temp dir, served read-only by the system `git http-backend`
171
- * (smart HTTP, as CGI) over a loopback http server. Repos allow fetching any reachable commit by sha
174
+ * A fake git host: bare repos in a temp dir, served by the system `git http-backend`
175
+ * (smart HTTP, as CGI, pushes included) over a loopback http server. Repos allow fetching any reachable commit by sha
172
176
  * (`uploadpack.allowReachableSHA1InWant`, as GitHub does). Needs `git` on PATH.
173
177
  *
174
178
  * Spawning git is what these tests spend their time on, and it slows down most under load, so the
@@ -176,26 +180,66 @@ const fastImportPath = (path) => /^"|[\n"\\]/.test(path)
176
180
  * `git fast-import`, and a ref advertisement (`GET …/info/refs`) is answered by http-backend once per
177
181
  * repo state, then repeated until the next commit to that repo.
178
182
  */
179
- export async function startFakeGitServer() {
183
+ export async function startFakeGitServer(options = {}) {
180
184
  const root = await mkdtemp(join(tmpdir(), "capybara-fake-git-"));
181
185
  const requests = [];
182
186
  let redirect = null;
187
+ let nextFail;
188
+ let nextRedirect;
189
+ const expectedBasic = options.requireBasic === undefined
190
+ ? undefined
191
+ : `Basic ${Buffer.from(`${options.requireBasic.username}:${options.requireBasic.password}`).toString("base64")}`;
183
192
  /** Ref advertisements by repo, then by request (path, query and `Git-Protocol`). */
184
193
  const advertised = new Map();
185
194
  /** Bumped by every commit to a repo: an answer read before the commit is not kept. */
186
195
  const generation = new Map();
187
- const repoOf = (pathname) => /^\/([^/]+)\.git\/info\/refs$/.exec(pathname)?.[1];
196
+ const repoOf = (pathname) => /^\/(.+)\.git\/info\/refs$/.exec(pathname)?.[1];
197
+ const pushedRepo = (pathname) => /^\/(.+)\.git\/git-receive-pack$/.exec(pathname)?.[1];
188
198
  const server = createServer((req, res) => {
189
- const r = { method: req.method ?? "GET", path: req.url ?? "/" };
190
- if (typeof req.headers.authorization === "string")
199
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
200
+ const authorized = expectedBasic === undefined || req.headers.authorization === expectedBasic;
201
+ const r = {
202
+ method: req.method ?? "GET",
203
+ path: req.url ?? "/",
204
+ authorized,
205
+ headerNames: Object.keys(req.headers),
206
+ };
207
+ if (options.recordAuthorization !== false && typeof req.headers.authorization === "string") {
191
208
  r.authorization = req.headers.authorization;
209
+ }
210
+ const service = url.searchParams.get("service") ?? /\/(git-(?:upload|receive)-pack)$/.exec(url.pathname)?.[1];
211
+ if (service !== undefined && service !== null)
212
+ r.service = service;
192
213
  requests.push(r);
214
+ if (nextFail !== undefined) {
215
+ const f = nextFail;
216
+ nextFail = undefined;
217
+ res.writeHead(f.status, { "content-type": "text/plain" }).end(f.body);
218
+ return;
219
+ }
220
+ if (nextRedirect !== undefined) {
221
+ const l = nextRedirect;
222
+ nextRedirect = undefined;
223
+ res.writeHead(302, { location: l }).end();
224
+ return;
225
+ }
226
+ if (!authorized) {
227
+ res.writeHead(401, { "www-authenticate": 'Basic realm="fake"' }).end();
228
+ return;
229
+ }
193
230
  if (redirect !== null) {
194
231
  res.writeHead(302, { location: redirect }).end();
195
232
  return;
196
233
  }
197
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
198
234
  const repo = req.method === "GET" ? repoOf(url.pathname) : undefined;
235
+ const pushed = pushedRepo(url.pathname);
236
+ if (pushed !== undefined) {
237
+ // a push moves refs: advertisements read before it are stale
238
+ res.on("close", () => {
239
+ generation.set(pushed, (generation.get(pushed) ?? 0) + 1);
240
+ advertised.delete(pushed);
241
+ });
242
+ }
199
243
  if (repo === undefined) {
200
244
  serveCgi(root, req, res);
201
245
  return;
@@ -223,6 +267,13 @@ export async function startFakeGitServer() {
223
267
  });
224
268
  await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
225
269
  const port = server.address().port;
270
+ const stopServer = async () => {
271
+ await new Promise((resolve) => {
272
+ server.closeAllConnections();
273
+ server.close(() => resolve());
274
+ });
275
+ await rm(root, { recursive: true, force: true });
276
+ };
226
277
  const repoDir = async (repo) => {
227
278
  if (!REPO_RE.test(repo))
228
279
  throw new Error(`invalid fake repo name: ${repo}`);
@@ -305,19 +356,36 @@ export async function startFakeGitServer() {
305
356
  advertised.delete(repo);
306
357
  return sha;
307
358
  };
308
- return {
359
+ const fake = {
309
360
  url: (repo) => `http://127.0.0.1:${port}/${repo}.git`,
310
361
  commit,
311
362
  setRedirect: (l) => {
312
363
  redirect = l;
313
364
  },
314
- requests,
315
- stop: async () => {
316
- await new Promise((resolve) => {
317
- server.closeAllConnections();
318
- server.close(() => resolve());
319
- });
320
- await rm(root, { recursive: true, force: true });
365
+ failNext: (status, body = "") => {
366
+ nextFail = { status, body };
367
+ },
368
+ redirectNext: (l) => {
369
+ nextRedirect = l;
321
370
  },
371
+ refOf: async (repo, ref) => {
372
+ const gitDir = await repoDir(repo);
373
+ return git(["rev-parse", "--verify", "--quiet", ref], { env: { GIT_DIR: gitDir } }).then((sha) => sha || undefined, () => undefined);
374
+ },
375
+ requests,
376
+ stop: stopServer,
322
377
  };
378
+ try {
379
+ for (const repo of options.repos ?? []) {
380
+ if (options.seed === false)
381
+ await repoDir(repo);
382
+ else
383
+ await commit(repo, { "README.md": "seed\n" });
384
+ }
385
+ }
386
+ catch (e) {
387
+ await stopServer();
388
+ throw e;
389
+ }
390
+ return fake;
323
391
  }
@@ -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,
@@ -19,6 +19,15 @@ export interface FakeOAuthServerOptions {
19
19
  scopesSupported?: string[];
20
20
  /** 元数据里的 `code_challenge_methods_supported`;null = 不声明。默认 `["S256"]`。 */
21
21
  pkceMethods?: string[] | null;
22
+ /**
23
+ * How the token endpoint answers. `"oauth"` (default): RFC 6749 (`token_type: "Bearer"`, errors
24
+ * as 400 / 401 `{ error }`). `"slack"`: like Slack's `oauth.v2.user.access`: success is
25
+ * `{ ok: true, token_type: "user", ... }`, every error is HTTP 200 `{ ok: false, error }` with
26
+ * Slack's codes where they differ (`invalid_code`, `invalid_refresh_token`, `invalid_client_id`).
27
+ */
28
+ dialect?: "oauth" | "slack";
29
+ /** The `token_type` of successful token responses (default: `Bearer`; `user` with dialect slack). */
30
+ tokenType?: string;
22
31
  }
23
32
  /** 令牌端点收到的一次请求(不含任何密钥)。 */
24
33
  export interface FakeTokenRequest {
@@ -28,8 +37,10 @@ export interface FakeTokenRequest {
28
37
  scope: string | undefined;
29
38
  /** 客户端认证方式:Basic 头、表单里的 client_secret、或只有 client_id。 */
30
39
  clientAuth: "basic" | "post" | "none";
31
- /** 本次响应的 HTTP 状态。 */
40
+ /** 本次响应的 HTTP 状态(dialect slack: errors are 200 too). */
32
41
  status: number;
42
+ /** The error code answered, if any (as sent: Slack's code with dialect slack). */
43
+ error?: string;
33
44
  }
34
45
  export interface FakeOAuthServer {
35
46
  /** issuer(`http://127.0.0.1:<port>`),也是各端点的基址。 */
@@ -45,7 +56,10 @@ export interface FakeOAuthServer {
45
56
  issuedSecrets(): string[];
46
57
  /** 作废全部 access token(refresh token 仍有效):资源服务随之返回 401。 */
47
58
  revokeAccessTokens(): void;
48
- /** 作废全部 refresh token:之后的刷新返回 `invalid_grant`。 */
59
+ /**
60
+ * 作废全部 refresh token:之后的刷新返回 `invalid_grant`(dialect slack: HTTP 200
61
+ * `{ ok: false, error: "invalid_refresh_token" }`)。
62
+ */
49
63
  revokeRefreshTokens(): void;
50
64
  /** 下一次授权请求以该 OAuth 错误回跳。 */
51
65
  denyNext(error: string, description?: string): void;
@@ -19,6 +19,16 @@ const json = (res, status, body) => {
19
19
  */
20
20
  export async function startFakeOAuthServer(opts = {}) {
21
21
  let dcr = opts.dcr ?? true;
22
+ const slack = opts.dialect === "slack";
23
+ const tokenType = opts.tokenType ?? (slack ? "user" : "Bearer");
24
+ /** RFC 6749 error code -> Slack's code for the same failure (dialect slack). */
25
+ const slackCode = (error, grantType) => {
26
+ if (error === "invalid_grant")
27
+ return grantType === "refresh_token" ? "invalid_refresh_token" : "invalid_code";
28
+ if (error === "invalid_client")
29
+ return "invalid_client_id";
30
+ return error;
31
+ };
22
32
  const ttl = opts.accessTokenTtl ?? 3600;
23
33
  const clients = new Map((opts.clients ?? []).map((c) => [
24
34
  c.clientId,
@@ -53,7 +63,11 @@ export async function startFakeOAuthServer(opts = {}) {
53
63
  const accessToken = rand("at_");
54
64
  access.set(accessToken, { expiresAt: ttl > 0 ? Date.now() + ttl * 1000 : null });
55
65
  secrets.add(accessToken);
56
- const body = { access_token: accessToken, token_type: "Bearer" };
66
+ const body = {
67
+ ...(slack && { ok: true }),
68
+ access_token: accessToken,
69
+ token_type: tokenType,
70
+ };
57
71
  if (ttl > 0)
58
72
  body.expires_in = ttl;
59
73
  if (scope !== undefined)
@@ -108,7 +122,13 @@ export async function startFakeOAuthServer(opts = {}) {
108
122
  return json(res, tokenFailures.status, tokenFailures.body ?? { message: "fake failure" });
109
123
  }
110
124
  const fail = (status, error) => {
125
+ if (slack) {
126
+ entry.status = 200;
127
+ entry.error = slackCode(error, grantType);
128
+ return json(res, 200, { ok: false, error: entry.error });
129
+ }
111
130
  entry.status = status;
131
+ entry.error = error;
112
132
  json(res, status, { error, error_description: `fake: ${error}` });
113
133
  };
114
134
  const client = authenticate(req, form);
@@ -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,