@capybara-hq/testing 0.1.0-rc.4 → 0.1.0-rc.40
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.
- package/dist/containers.d.ts +7 -2
- package/dist/containers.js +7 -3
- package/dist/device-service-conformance.d.ts +38 -0
- package/dist/device-service-conformance.js +141 -0
- package/dist/dual-replica.d.ts +23 -1
- package/dist/dual-replica.js +53 -0
- package/dist/fake-channel.d.ts +44 -5
- package/dist/fake-channel.js +63 -2
- package/dist/fake-dial-in-machine.d.ts +150 -0
- package/dist/fake-dial-in-machine.js +367 -0
- package/dist/fake-e2b.d.ts +34 -0
- package/dist/fake-e2b.js +95 -1
- package/dist/fake-git-server.d.ts +32 -4
- package/dist/fake-git-server.js +87 -19
- package/dist/fake-lark.d.ts +12 -1
- package/dist/fake-lark.js +63 -10
- package/dist/fake-oauth-server.d.ts +62 -2
- package/dist/fake-oauth-server.js +86 -5
- package/dist/fake-slack.d.ts +17 -1
- package/dist/fake-slack.js +98 -0
- package/dist/fake-telegram.d.ts +173 -0
- package/dist/fake-telegram.js +632 -0
- package/dist/fixtures.d.ts +24 -8
- package/dist/fixtures.js +31 -8
- package/dist/index.d.ts +15 -9
- package/dist/index.js +10 -4
- package/dist/kernel-helpers.d.ts +16 -4
- package/dist/kernel-helpers.js +39 -4
- package/dist/media-samples.d.ts +2 -0
- package/dist/media-samples.js +2 -0
- package/dist/model-conformance.d.ts +15 -10
- package/dist/model-conformance.js +87 -14
- package/dist/push-conformance.d.ts +31 -0
- package/dist/push-conformance.js +160 -0
- package/dist/replica-runner.js +2 -0
- package/dist/sandbox-native-conformance.d.ts +31 -0
- package/dist/sandbox-native-conformance.js +153 -0
- package/dist/sandbox-permission-conformance.d.ts +310 -0
- package/dist/sandbox-permission-conformance.js +1491 -0
- package/fixtures/extensions/fake-bootstrap-a/src/index.ts +8 -4
- package/fixtures/extensions/fake-bootstrap-b/src/index.ts +8 -4
- package/fixtures/extensions/fake-client/.capybara-plugin/plugin.json +11 -0
- package/fixtures/extensions/fake-client/client/styles/fake.css +11 -0
- package/fixtures/extensions/fake-client/package.json +12 -0
- package/fixtures/extensions/fake-client/src/client.tsx +51 -0
- package/fixtures/extensions/fake-client/src/index.ts +43 -0
- package/fixtures/extensions/fake-client/themes/fake.json +11 -0
- package/fixtures/extensions/fake-client-broken/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-client-broken/package.json +12 -0
- package/fixtures/extensions/fake-client-broken/src/client.tsx +22 -0
- package/fixtures/extensions/fake-client-broken/src/index.ts +27 -0
- package/fixtures/extensions/fake-config-form/src/index.ts +52 -46
- package/fixtures/extensions/fake-connector/src/index.ts +64 -34
- package/fixtures/extensions/fake-context/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-context/package.json +12 -0
- package/fixtures/extensions/fake-context/src/index.ts +78 -0
- package/fixtures/extensions/fake-dep-provider/src/index.ts +1 -1
- package/fixtures/extensions/fake-dep-requirer/src/index.ts +1 -1
- package/fixtures/extensions/fake-embed/src/index.ts +26 -26
- package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -1
- package/fixtures/extensions/fake-im/guides/fake-im-app.md +32 -0
- package/fixtures/extensions/fake-im/guides/fake-im-app.zh.md +32 -0
- package/fixtures/extensions/fake-im/src/channel.ts +22 -1
- package/fixtures/extensions/fake-im/src/checks.ts +94 -0
- package/fixtures/extensions/fake-im/src/directory.ts +44 -20
- package/fixtures/extensions/fake-im/src/index.ts +59 -11
- package/fixtures/extensions/fake-lifecycle/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-lifecycle/migrations/0001_init.sql +16 -0
- package/fixtures/extensions/fake-lifecycle/package.json +12 -0
- package/fixtures/extensions/fake-lifecycle/src/index.ts +72 -0
- package/fixtures/extensions/fake-object-store/src/index.ts +12 -8
- package/fixtures/extensions/fake-openapi/src/index.ts +46 -34
- package/fixtures/extensions/fake-push/.capybara-plugin/plugin.json +13 -0
- package/fixtures/extensions/fake-push/guides/fake-push-key.md +6 -0
- package/fixtures/extensions/fake-push/guides/fake-push-key.zh.md +6 -0
- package/fixtures/extensions/fake-push/migrations/0001_sends.sql +9 -0
- package/fixtures/extensions/fake-push/package.json +12 -0
- package/fixtures/extensions/fake-push/src/check.ts +40 -0
- package/fixtures/extensions/fake-push/src/index.ts +56 -0
- package/fixtures/extensions/fake-push/src/push.ts +103 -0
- package/fixtures/extensions/fake-tools-ui/src/index.ts +61 -2
- package/fixtures/extensions/fake-web/src/index.ts +5 -4
- package/fixtures/extensions/fake-web/src/web.ts +11 -7
- package/fixtures/extensions/fake-web-2/src/index.ts +2 -2
- package/fixtures/extensions/fake-web-2/src/web.ts +11 -7
- package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
- package/fixtures/plugins/fake-theme/brand/app-512.png +0 -0
- package/fixtures/plugins/fake-theme/brand/app-mask-512.png +0 -0
- package/fixtures/plugins/fake-theme/brand/avatars/bot.svg +1 -0
- package/fixtures/plugins/fake-theme/brand/avatars/cat.png +0 -0
- package/fixtures/plugins/fake-theme/brand/illustration.svg +1 -0
- package/fixtures/plugins/fake-theme/brand/unnamed.svg +1 -0
- package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
- package/fixtures/plugins/fake-theme/logo.svg +1 -0
- package/fixtures/plugins/fake-theme/package.json +8 -0
- package/fixtures/plugins/fake-theme/themes/brand-kit.json +24 -0
- package/fixtures/plugins/fake-theme/themes/neon-grid.json +13 -0
- package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
- package/package.json +6 -5
package/dist/fake-e2b.js
CHANGED
|
@@ -84,6 +84,12 @@ export async function startFakeE2B(opts = {}) {
|
|
|
84
84
|
await chmod(join(shims, "setsid"), 0o755);
|
|
85
85
|
const sandboxes = new Map();
|
|
86
86
|
const procs = new Map();
|
|
87
|
+
const templates = new Map();
|
|
88
|
+
for (const alias of opts.templates ?? [])
|
|
89
|
+
templates.set(alias, { templateID: `t${randomBytes(6).toString("hex")}`, alias });
|
|
90
|
+
const buildMs = opts.templateBuildMs ?? 0;
|
|
91
|
+
const templateByRef = (ref) => templates.get(ref) ?? [...templates.values()].find((t) => t.templateID === ref);
|
|
92
|
+
const ready = (t) => t.readyAt !== undefined && Date.now() >= t.readyAt;
|
|
87
93
|
const calls = [];
|
|
88
94
|
const fails = [];
|
|
89
95
|
const reboots = new Map();
|
|
@@ -122,12 +128,13 @@ export async function startFakeE2B(opts = {}) {
|
|
|
122
128
|
};
|
|
123
129
|
const newSandbox = async (body) => {
|
|
124
130
|
const id = `i${randomBytes(9).toString("hex")}`;
|
|
131
|
+
const tpl = templateByRef(String(body.templateID));
|
|
125
132
|
const root = join(base, id);
|
|
126
133
|
for (const d of ROOT_DIRS)
|
|
127
134
|
await mkdir(join(root, d), { recursive: true });
|
|
128
135
|
const s = {
|
|
129
136
|
id,
|
|
130
|
-
templateID: String(body.templateID),
|
|
137
|
+
templateID: tpl?.templateID ?? String(body.templateID),
|
|
131
138
|
metadata: body.metadata ?? {},
|
|
132
139
|
state: "running",
|
|
133
140
|
timeout: typeof body.timeout === "number" ? body.timeout : 300,
|
|
@@ -160,6 +167,11 @@ export async function startFakeE2B(opts = {}) {
|
|
|
160
167
|
sendJson(res, 400, { code: 400, message: "templateID is required" });
|
|
161
168
|
return;
|
|
162
169
|
}
|
|
170
|
+
const tpl = templateByRef(body.templateID);
|
|
171
|
+
if (tpl?.buildID !== undefined && !ready(tpl)) {
|
|
172
|
+
sendJson(res, 404, { code: 404, message: `template '${body.templateID}' is not ready` });
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
163
175
|
const s = await newSandbox(body);
|
|
164
176
|
sendJson(res, 201, {
|
|
165
177
|
sandboxID: s.id,
|
|
@@ -235,9 +247,89 @@ export async function startFakeE2B(opts = {}) {
|
|
|
235
247
|
return;
|
|
236
248
|
}
|
|
237
249
|
s.state = "paused";
|
|
250
|
+
s.pausedWithMemory = body.memory !== false;
|
|
251
|
+
if (!s.pausedWithMemory) {
|
|
252
|
+
// filesystem-only snapshot: the processes are gone, the files stay
|
|
253
|
+
for (const p of procs.get(s.id) ?? [])
|
|
254
|
+
killGroup(p);
|
|
255
|
+
procs.delete(s.id);
|
|
256
|
+
}
|
|
238
257
|
sendJson(res, 204);
|
|
239
258
|
return;
|
|
240
259
|
}
|
|
260
|
+
if (method === "POST" && path === "/v3/templates") {
|
|
261
|
+
const name = typeof body.name === "string" ? body.name : "";
|
|
262
|
+
if (name === "") {
|
|
263
|
+
sendJson(res, 400, { code: 400, message: "name is required" });
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
const alias = name.split(":")[0];
|
|
267
|
+
const tags = Array.isArray(body.tags) ? body.tags : [];
|
|
268
|
+
const t = templates.get(alias) ?? {
|
|
269
|
+
templateID: `t${randomBytes(6).toString("hex")}`,
|
|
270
|
+
alias,
|
|
271
|
+
};
|
|
272
|
+
t.buildID = randomBytes(8).toString("hex");
|
|
273
|
+
t.readyAt = undefined;
|
|
274
|
+
t.image = undefined;
|
|
275
|
+
templates.set(alias, t);
|
|
276
|
+
sendJson(res, 202, {
|
|
277
|
+
templateID: t.templateID,
|
|
278
|
+
buildID: t.buildID,
|
|
279
|
+
names: [name],
|
|
280
|
+
aliases: [alias],
|
|
281
|
+
tags,
|
|
282
|
+
public: false,
|
|
283
|
+
});
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
m = /^\/templates\/([^/]+)\/files\/([^/]+)$/.exec(path);
|
|
287
|
+
if (m && method === "GET") {
|
|
288
|
+
sendJson(res, 200, { present: true });
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
m = /^\/v2\/templates\/([^/]+)\/builds\/([^/]+)$/.exec(path);
|
|
292
|
+
if (m && method === "POST") {
|
|
293
|
+
const t = templateByRef(m[1]);
|
|
294
|
+
if (!t || t.buildID !== m[2]) {
|
|
295
|
+
sendJson(res, 404, { code: 404, message: "build not found" });
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
if (typeof body.fromImage !== "string") {
|
|
299
|
+
sendJson(res, 400, { code: 400, message: "fromImage is required" });
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
t.image = body.fromImage;
|
|
303
|
+
t.readyAt = Date.now() + buildMs;
|
|
304
|
+
sendJson(res, 202);
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
m = /^\/templates\/([^/]+)\/builds\/([^/]+)\/status$/.exec(path);
|
|
308
|
+
if (m && method === "GET") {
|
|
309
|
+
const t = templateByRef(m[1]);
|
|
310
|
+
if (!t || t.buildID !== m[2]) {
|
|
311
|
+
sendJson(res, 404, { code: 404, message: "build not found" });
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
sendJson(res, 200, {
|
|
315
|
+
buildID: t.buildID,
|
|
316
|
+
templateID: t.templateID,
|
|
317
|
+
status: t.readyAt === undefined ? "waiting" : ready(t) ? "ready" : "building",
|
|
318
|
+
logEntries: [],
|
|
319
|
+
logs: [],
|
|
320
|
+
});
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
m = /^\/templates\/aliases\/([^/]+)$/.exec(path);
|
|
324
|
+
if (m && method === "GET") {
|
|
325
|
+
const t = templates.get(decodeURIComponent(m[1]));
|
|
326
|
+
if (!t) {
|
|
327
|
+
sendJson(res, 404, { code: 404, message: `template '${m[1]}' not found` });
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
sendJson(res, 200, { templateID: t.templateID, public: false });
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
241
333
|
m = /^\/sandboxes\/([^/]+)$/.exec(path);
|
|
242
334
|
if (m && method === "DELETE") {
|
|
243
335
|
if (!sandboxes.has(m[1]))
|
|
@@ -454,6 +546,7 @@ export async function startFakeE2B(opts = {}) {
|
|
|
454
546
|
url,
|
|
455
547
|
apiKey,
|
|
456
548
|
sandboxes,
|
|
549
|
+
templates,
|
|
457
550
|
calls,
|
|
458
551
|
failNext(match, status, message = `fake failure ${status}`, opts = {}) {
|
|
459
552
|
fails.push({ match, status, message, raw: opts.raw === true });
|
|
@@ -469,6 +562,7 @@ export async function startFakeE2B(opts = {}) {
|
|
|
469
562
|
hangs.push(match);
|
|
470
563
|
},
|
|
471
564
|
expire: destroy,
|
|
565
|
+
removeSandbox: destroy,
|
|
472
566
|
hostPath(id, sandboxPath) {
|
|
473
567
|
const s = sandboxes.get(id);
|
|
474
568
|
if (!s)
|
|
@@ -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
|
-
/**
|
|
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
|
|
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>;
|
package/dist/fake-git-server.js
CHANGED
|
@@ -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,
|
|
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"], {
|
|
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
|
|
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) => /^\/(
|
|
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
|
|
190
|
-
|
|
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
|
-
|
|
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
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
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
|
}
|
package/dist/fake-lark.d.ts
CHANGED
|
@@ -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
|
-
|
|
38
|
-
req.on("data", (c) =>
|
|
39
|
-
|
|
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
|
|
136
|
+
const rawBytes = await readBody(req);
|
|
137
|
+
const raw = rawBytes.toString();
|
|
138
|
+
const contentType = req.headers["content-type"] ?? "";
|
|
130
139
|
let body = {};
|
|
131
|
-
|
|
132
|
-
|
|
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
|
-
|
|
135
|
-
|
|
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,42 @@ 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;
|
|
31
|
+
/**
|
|
32
|
+
* OIDC mode: the code exchange also answers an RS256 `id_token`, the discovery document gains
|
|
33
|
+
* `jwks_uri`, and `GET /jwks` serves the public key. `issuer` overrides the `iss` claim and the
|
|
34
|
+
* `issuer` field of both discovery documents (default: the server's own origin).
|
|
35
|
+
*/
|
|
36
|
+
oidc?: {
|
|
37
|
+
issuer?: string;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* The code exchange returns a refresh token only when the authorize request carried every listed
|
|
41
|
+
* parameter with that value (e.g. `{ access_type: "offline" }`, like Google).
|
|
42
|
+
*/
|
|
43
|
+
refreshTokenOnlyWith?: Record<string, string>;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The claims of the next ID token (`oidc` mode). Any claim given here overrides the one the server
|
|
47
|
+
* sets itself (`iss`, `aud`, `azp`, `nonce`, `iat`, `exp`), including an `issNext` value. `iss`, `aud`, `azp`, `nonce`, `iat`, `exp` are set by the server. */
|
|
48
|
+
export interface FakeOidcClaims {
|
|
49
|
+
sub: string;
|
|
50
|
+
email?: string;
|
|
51
|
+
email_verified?: unknown;
|
|
52
|
+
hd?: string;
|
|
53
|
+
name?: string;
|
|
54
|
+
given_name?: string;
|
|
55
|
+
family_name?: string;
|
|
56
|
+
picture?: string;
|
|
57
|
+
[k: string]: unknown;
|
|
22
58
|
}
|
|
23
59
|
/** 令牌端点收到的一次请求(不含任何密钥)。 */
|
|
24
60
|
export interface FakeTokenRequest {
|
|
@@ -26,14 +62,20 @@ export interface FakeTokenRequest {
|
|
|
26
62
|
clientId: string | undefined;
|
|
27
63
|
resource: string | undefined;
|
|
28
64
|
scope: string | undefined;
|
|
65
|
+
/** The names of the form parameters sent (values are never recorded). */
|
|
66
|
+
paramNames: string[];
|
|
29
67
|
/** 客户端认证方式:Basic 头、表单里的 client_secret、或只有 client_id。 */
|
|
30
68
|
clientAuth: "basic" | "post" | "none";
|
|
31
|
-
/** 本次响应的 HTTP
|
|
69
|
+
/** 本次响应的 HTTP 状态(dialect slack: errors are 200 too). */
|
|
32
70
|
status: number;
|
|
71
|
+
/** The error code answered, if any (as sent: Slack's code with dialect slack). */
|
|
72
|
+
error?: string;
|
|
33
73
|
}
|
|
34
74
|
export interface FakeOAuthServer {
|
|
35
75
|
/** issuer(`http://127.0.0.1:<port>`),也是各端点的基址。 */
|
|
36
76
|
issuer: string;
|
|
77
|
+
/** `${issuer}/jwks` (served in `oidc` mode only). */
|
|
78
|
+
jwksUrl: string;
|
|
37
79
|
tokenRequests: FakeTokenRequest[];
|
|
38
80
|
/** DCR 注册请求体。 */
|
|
39
81
|
registrations: Record<string, unknown>[];
|
|
@@ -45,7 +87,10 @@ export interface FakeOAuthServer {
|
|
|
45
87
|
issuedSecrets(): string[];
|
|
46
88
|
/** 作废全部 access token(refresh token 仍有效):资源服务随之返回 401。 */
|
|
47
89
|
revokeAccessTokens(): void;
|
|
48
|
-
/**
|
|
90
|
+
/**
|
|
91
|
+
* 作废全部 refresh token:之后的刷新返回 `invalid_grant`(dialect slack: HTTP 200
|
|
92
|
+
* `{ ok: false, error: "invalid_refresh_token" }`)。
|
|
93
|
+
*/
|
|
49
94
|
revokeRefreshTokens(): void;
|
|
50
95
|
/** 下一次授权请求以该 OAuth 错误回跳。 */
|
|
51
96
|
denyNext(error: string, description?: string): void;
|
|
@@ -54,6 +99,21 @@ export interface FakeOAuthServer {
|
|
|
54
99
|
failTokenRequests(n: number, status: number, body?: unknown): void;
|
|
55
100
|
/** 下一次授权回跳的 RFC 9207 `iss` 改为该值(默认回跳带真实 issuer)。 */
|
|
56
101
|
forgeIssNext(iss: string): void;
|
|
102
|
+
/**
|
|
103
|
+
* The next code exchange logs in with these claims (queued, one per exchange). Only takes effect
|
|
104
|
+
* with `oidc`. The claims override any claim the server sets (`iss`, `aud`, `nonce`, ...).
|
|
105
|
+
*/
|
|
106
|
+
queueLogin(claims: FakeOidcClaims): void;
|
|
107
|
+
/**
|
|
108
|
+
* The next ID token carries these claims on top of the regular and queued ones (they win), signed with a
|
|
109
|
+
* key outside the JWKS (`foreignKey`) and/or a different `kid`.
|
|
110
|
+
*/
|
|
111
|
+
tamperNextIdToken(claims: Record<string, unknown>, o?: {
|
|
112
|
+
foreignKey?: boolean;
|
|
113
|
+
kid?: string;
|
|
114
|
+
}): void;
|
|
115
|
+
/** The next ID token's `iss` is this value (a queued or tampered `iss` still wins). Only takes effect with `oidc`. */
|
|
116
|
+
issNext(iss: string): void;
|
|
57
117
|
stop(): Promise<void>;
|
|
58
118
|
}
|
|
59
119
|
/**
|