@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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createHash, randomBytes } from "node:crypto";
|
|
1
|
+
import { createHash, createSign, generateKeyPairSync, randomBytes, } from "node:crypto";
|
|
2
2
|
import { createServer } from "node:http";
|
|
3
3
|
const b64url = (b) => b.toString("base64url");
|
|
4
4
|
const rand = (prefix) => `${prefix}${b64url(randomBytes(18))}`;
|
|
@@ -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,
|
|
@@ -35,8 +45,39 @@ export async function startFakeOAuthServer(opts = {}) {
|
|
|
35
45
|
let tokenFailures;
|
|
36
46
|
let forgedIss;
|
|
37
47
|
let issuer = "";
|
|
48
|
+
const oidc = opts.oidc;
|
|
49
|
+
const signing = oidc ? generateKeyPairSync("rsa", { modulusLength: 2048 }) : undefined;
|
|
50
|
+
const foreign = oidc ? generateKeyPairSync("rsa", { modulusLength: 2048 }) : undefined;
|
|
51
|
+
const kid = "fake-oidc-key-1";
|
|
52
|
+
const logins = [];
|
|
53
|
+
let tamper;
|
|
54
|
+
let forgedIdTokenIss;
|
|
55
|
+
const signJwt = (claims, key, keyId) => {
|
|
56
|
+
const b64 = (o) => b64url(Buffer.from(JSON.stringify(o)));
|
|
57
|
+
const input = `${b64({ alg: "RS256", typ: "JWT", kid: keyId })}.${b64(claims)}`;
|
|
58
|
+
return `${input}.${createSign("RSA-SHA256").update(input).sign(key).toString("base64url")}`;
|
|
59
|
+
};
|
|
60
|
+
// Precedence, lowest to highest: the server's claims (an `issNext` value replaces its `iss`), the
|
|
61
|
+
// dequeued login's claims, then `tamperNextIdToken`'s claims.
|
|
62
|
+
const idToken = (clientId, nonce) => {
|
|
63
|
+
const now = Math.floor(Date.now() / 1000);
|
|
64
|
+
const claims = {
|
|
65
|
+
iss: forgedIdTokenIss ?? oidc?.issuer ?? issuer,
|
|
66
|
+
aud: clientId,
|
|
67
|
+
azp: clientId,
|
|
68
|
+
iat: now,
|
|
69
|
+
exp: now + 3600,
|
|
70
|
+
...(nonce !== undefined && { nonce }),
|
|
71
|
+
...(logins.shift() ?? { sub: "fake-sub-1" }),
|
|
72
|
+
};
|
|
73
|
+
forgedIdTokenIss = undefined;
|
|
74
|
+
const t = tamper;
|
|
75
|
+
tamper = undefined;
|
|
76
|
+
Object.assign(claims, t?.claims);
|
|
77
|
+
return signJwt(claims, (t?.foreignKey ? foreign : signing)?.privateKey, t?.kid ?? kid);
|
|
78
|
+
};
|
|
38
79
|
const metadata = () => ({
|
|
39
|
-
issuer,
|
|
80
|
+
issuer: oidc?.issuer ?? issuer,
|
|
40
81
|
authorization_endpoint: `${issuer}/authorize`,
|
|
41
82
|
token_endpoint: `${issuer}/token`,
|
|
42
83
|
...(dcr && { registration_endpoint: `${issuer}/register` }),
|
|
@@ -53,7 +94,11 @@ export async function startFakeOAuthServer(opts = {}) {
|
|
|
53
94
|
const accessToken = rand("at_");
|
|
54
95
|
access.set(accessToken, { expiresAt: ttl > 0 ? Date.now() + ttl * 1000 : null });
|
|
55
96
|
secrets.add(accessToken);
|
|
56
|
-
const body = {
|
|
97
|
+
const body = {
|
|
98
|
+
...(slack && { ok: true }),
|
|
99
|
+
access_token: accessToken,
|
|
100
|
+
token_type: tokenType,
|
|
101
|
+
};
|
|
57
102
|
if (ttl > 0)
|
|
58
103
|
body.expires_in = ttl;
|
|
59
104
|
if (scope !== undefined)
|
|
@@ -94,6 +139,7 @@ export async function startFakeOAuthServer(opts = {}) {
|
|
|
94
139
|
clientId: undefined,
|
|
95
140
|
resource: form.get("resource") ?? undefined,
|
|
96
141
|
scope: form.get("scope") ?? undefined,
|
|
142
|
+
paramNames: [...new Set(form.keys())],
|
|
97
143
|
clientAuth: req.headers.authorization?.startsWith("Basic ")
|
|
98
144
|
? "basic"
|
|
99
145
|
: form.has("client_secret")
|
|
@@ -108,7 +154,13 @@ export async function startFakeOAuthServer(opts = {}) {
|
|
|
108
154
|
return json(res, tokenFailures.status, tokenFailures.body ?? { message: "fake failure" });
|
|
109
155
|
}
|
|
110
156
|
const fail = (status, error) => {
|
|
157
|
+
if (slack) {
|
|
158
|
+
entry.status = 200;
|
|
159
|
+
entry.error = slackCode(error, grantType);
|
|
160
|
+
return json(res, 200, { ok: false, error: entry.error });
|
|
161
|
+
}
|
|
111
162
|
entry.status = status;
|
|
163
|
+
entry.error = error;
|
|
112
164
|
json(res, status, { error, error_description: `fake: ${error}` });
|
|
113
165
|
};
|
|
114
166
|
const client = authenticate(req, form);
|
|
@@ -130,7 +182,13 @@ export async function startFakeOAuthServer(opts = {}) {
|
|
|
130
182
|
if (grant.resource !== undefined && form.get("resource") !== grant.resource) {
|
|
131
183
|
return fail(400, "invalid_target");
|
|
132
184
|
}
|
|
133
|
-
|
|
185
|
+
const body = issue(client.clientId, grant.scope, grant.allowRefresh);
|
|
186
|
+
if (oidc) {
|
|
187
|
+
const jwt = idToken(client.clientId, grant.nonce);
|
|
188
|
+
secrets.add(jwt);
|
|
189
|
+
body.id_token = jwt;
|
|
190
|
+
}
|
|
191
|
+
return json(res, 200, body);
|
|
134
192
|
}
|
|
135
193
|
if (grantType === "refresh_token") {
|
|
136
194
|
const rt = form.get("refresh_token") ?? "";
|
|
@@ -185,6 +243,8 @@ export async function startFakeOAuthServer(opts = {}) {
|
|
|
185
243
|
challenge,
|
|
186
244
|
scope: q.get("scope") ?? undefined,
|
|
187
245
|
resource: q.get("resource") ?? undefined,
|
|
246
|
+
nonce: q.get("nonce") ?? undefined,
|
|
247
|
+
allowRefresh: Object.entries(opts.refreshTokenOnlyWith ?? {}).every(([k, v]) => q.get(k) === v),
|
|
188
248
|
});
|
|
189
249
|
back.searchParams.set("code", code);
|
|
190
250
|
}
|
|
@@ -228,7 +288,18 @@ export async function startFakeOAuthServer(opts = {}) {
|
|
|
228
288
|
if (req.method === "GET" && path === "/.well-known/openid-configuration") {
|
|
229
289
|
if (opts.metadata !== "openid")
|
|
230
290
|
return json(res, 404, { error: "not_found" });
|
|
231
|
-
return json(res, 200, {
|
|
291
|
+
return json(res, 200, {
|
|
292
|
+
...metadata(),
|
|
293
|
+
subject_types_supported: ["public"],
|
|
294
|
+
...(oidc && {
|
|
295
|
+
jwks_uri: `${issuer}/jwks`,
|
|
296
|
+
id_token_signing_alg_values_supported: ["RS256"],
|
|
297
|
+
}),
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
if (req.method === "GET" && path === "/jwks" && signing) {
|
|
301
|
+
const jwk = signing.publicKey.export({ format: "jwk" });
|
|
302
|
+
return json(res, 200, { keys: [{ ...jwk, kid, alg: "RS256", use: "sig" }] });
|
|
232
303
|
}
|
|
233
304
|
if (req.method === "GET" && path === "/authorize")
|
|
234
305
|
return authorize(url, res);
|
|
@@ -254,6 +325,7 @@ export async function startFakeOAuthServer(opts = {}) {
|
|
|
254
325
|
issuer = `http://127.0.0.1:${port}`;
|
|
255
326
|
return {
|
|
256
327
|
issuer,
|
|
328
|
+
jwksUrl: `${issuer}/jwks`,
|
|
257
329
|
tokenRequests,
|
|
258
330
|
registrations,
|
|
259
331
|
authorizeRequests,
|
|
@@ -270,6 +342,15 @@ export async function startFakeOAuthServer(opts = {}) {
|
|
|
270
342
|
forgeIssNext: (iss) => {
|
|
271
343
|
forgedIss = iss;
|
|
272
344
|
},
|
|
345
|
+
queueLogin: (claims) => {
|
|
346
|
+
logins.push(claims);
|
|
347
|
+
},
|
|
348
|
+
tamperNextIdToken: (claims, o) => {
|
|
349
|
+
tamper = { claims, ...o };
|
|
350
|
+
},
|
|
351
|
+
issNext: (iss) => {
|
|
352
|
+
forgedIdTokenIss = iss;
|
|
353
|
+
},
|
|
273
354
|
denyNext: (error, description) => {
|
|
274
355
|
deny = { error, description };
|
|
275
356
|
},
|
package/dist/fake-slack.d.ts
CHANGED
|
@@ -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
|
-
/**
|
|
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;
|
package/dist/fake-slack.js
CHANGED
|
@@ -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,
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A programmable fake Telegram Bot API (for the Telegram channel plugin's tests).
|
|
3
|
+
*
|
|
4
|
+
* - **Routing**: `GET|POST /bot<token>/<method>` (method names are case-insensitive, like Telegram);
|
|
5
|
+
* parameters come from the query string and a JSON or form-urlencoded body. Every answer is the
|
|
6
|
+
* Bot API envelope: `{ ok: true, result }` or `{ ok: false, error_code, description, parameters? }`.
|
|
7
|
+
* An unknown token → 401 `Unauthorized`; an unknown method → 404 `Not Found`. Point a client at
|
|
8
|
+
* `apiUrl` (it appends `/bot<token>/<method>`).
|
|
9
|
+
* - **Methods**: `getMe`, `getWebhookInfo` (the url given to {@link FakeTelegramServer.setWebhook}),
|
|
10
|
+
* `getUpdates`, `sendMessage`, `editMessageText`, `answerCallbackQuery`, and the multipart uploads
|
|
11
|
+
* `sendPhoto` / `sendDocument` (recorded in `messages` with `file`).
|
|
12
|
+
* - **Long polling**: {@link FakeTelegramServer.push} queues an update per bot and assigns its
|
|
13
|
+
* `update_id`. `getUpdates` with `offset` confirms (drops) the lower ids; with `timeout` it waits
|
|
14
|
+
* until a push or the timeout; `allowed_updates` is remembered per bot like Telegram and updates of
|
|
15
|
+
* other types are dropped. While a webhook is set `getUpdates` answers 409; a second concurrent
|
|
16
|
+
* `getUpdates` for the same token ends the earlier one with 409 "Conflict: terminated by other
|
|
17
|
+
* getUpdates request", as Telegram does.
|
|
18
|
+
* - **Several bots**: {@link FakeTelegramOptions.bots}; each token has its own queue, offset, webhook
|
|
19
|
+
* and pollers.
|
|
20
|
+
* - **Failures**: {@link FakeTelegramServer.failNext} answers a method with an error envelope
|
|
21
|
+
* (`parameters.retry_after` / `migrate_to_chat_id`), {@link FakeTelegramServer.delay} holds it.
|
|
22
|
+
*
|
|
23
|
+
* Records: `messages` (sendMessage), `edits` (successful editMessageText), `calls` (every call with
|
|
24
|
+
* a known token), `callbackAnswers` (answerCallbackQuery ids).
|
|
25
|
+
*/
|
|
26
|
+
export interface FakeTelegramBot {
|
|
27
|
+
/** `<id>:<secret>`, as BotFather issues it. */
|
|
28
|
+
token: string;
|
|
29
|
+
id: number;
|
|
30
|
+
username: string;
|
|
31
|
+
firstName?: string;
|
|
32
|
+
/** getMe `can_read_all_group_messages` (privacy mode off); default false. */
|
|
33
|
+
canReadAllGroupMessages?: boolean;
|
|
34
|
+
/** getMe `has_topics_enabled` (forum topics in private chats); default false. */
|
|
35
|
+
hasTopicsEnabled?: boolean;
|
|
36
|
+
}
|
|
37
|
+
/** One Bot API call with a known token (parameters merged from query string and body). */
|
|
38
|
+
export interface FakeTelegramCall {
|
|
39
|
+
method: string;
|
|
40
|
+
token: string;
|
|
41
|
+
params: Record<string, unknown>;
|
|
42
|
+
at: number;
|
|
43
|
+
}
|
|
44
|
+
/** A message the bot sent (`sendMessage`) or an edit of one (`editMessageText`). */
|
|
45
|
+
export interface FakeTelegramMessage {
|
|
46
|
+
chatId: number;
|
|
47
|
+
messageId: number;
|
|
48
|
+
text: string;
|
|
49
|
+
parseMode?: string;
|
|
50
|
+
replyMarkup?: unknown;
|
|
51
|
+
messageThreadId?: number;
|
|
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
|
+
};
|
|
60
|
+
at: number;
|
|
61
|
+
}
|
|
62
|
+
/** An injected error answer: `status` is the HTTP status, `errorCode` defaults to it. */
|
|
63
|
+
export interface FakeTelegramFailure {
|
|
64
|
+
status: number;
|
|
65
|
+
errorCode?: number;
|
|
66
|
+
description: string;
|
|
67
|
+
retryAfter?: number;
|
|
68
|
+
migrateToChatId?: number;
|
|
69
|
+
}
|
|
70
|
+
export interface FakeTelegramOptions {
|
|
71
|
+
/** The bots this fake serves; default one bot (`123456:fake-telegram-token`, `capybara_bot`). */
|
|
72
|
+
bots?: FakeTelegramBot[];
|
|
73
|
+
}
|
|
74
|
+
export interface FakeTelegramServer {
|
|
75
|
+
url: string;
|
|
76
|
+
/** Same as `url`: the client appends `/bot<token>/<method>`. */
|
|
77
|
+
apiUrl: string;
|
|
78
|
+
/** The first bot (the default for every `token?` argument). */
|
|
79
|
+
bot: FakeTelegramBot;
|
|
80
|
+
bots: FakeTelegramBot[];
|
|
81
|
+
/** sendMessage results, in order. */
|
|
82
|
+
messages: FakeTelegramMessage[];
|
|
83
|
+
/** Successful editMessageText calls, in order (markup-only edits are recorded too). */
|
|
84
|
+
edits: FakeTelegramMessage[];
|
|
85
|
+
calls: FakeTelegramCall[];
|
|
86
|
+
/** answerCallbackQuery `callback_query_id`s, in order. */
|
|
87
|
+
callbackAnswers: string[];
|
|
88
|
+
/** Queues an update for the bot, assigns its `update_id` and returns it; wakes a long poll. */
|
|
89
|
+
push(update: Record<string, unknown>, token?: string): number;
|
|
90
|
+
/** The highest offset passed to getUpdates (0 before any). */
|
|
91
|
+
confirmedOffset(token?: string): number;
|
|
92
|
+
/** Updates pushed and not yet confirmed. */
|
|
93
|
+
pending(token?: string): number;
|
|
94
|
+
/** In-flight getUpdates requests. */
|
|
95
|
+
activePollers(token?: string): number;
|
|
96
|
+
/**
|
|
97
|
+
* The peak number of overlapping getUpdates requests: a request that arrives while another is in
|
|
98
|
+
* flight counts as concurrent with it, although it ends the earlier one with 409.
|
|
99
|
+
*/
|
|
100
|
+
maxConcurrentPollers(token?: string): number;
|
|
101
|
+
/**
|
|
102
|
+
* The client TCP ports of the in-flight getUpdates requests; dual-replica tests map them to the
|
|
103
|
+
* replica process holding the poll.
|
|
104
|
+
*/
|
|
105
|
+
pollerPeerPorts(token?: string): number[];
|
|
106
|
+
/** Sets (or clears with null) the webhook getWebhookInfo reports; while set, getUpdates is 409. */
|
|
107
|
+
setWebhook(url: string | null, token?: string): void;
|
|
108
|
+
/** The next `count` (default 1) calls of `method` answer with `failure`. */
|
|
109
|
+
failNext(method: string, failure: FakeTelegramFailure, count?: number): void;
|
|
110
|
+
/** Every later call of `method` waits `ms` before answering (0 cancels). */
|
|
111
|
+
delay(method: string, ms: number): void;
|
|
112
|
+
close(): Promise<void>;
|
|
113
|
+
}
|
|
114
|
+
export type TgUser = {
|
|
115
|
+
id: number;
|
|
116
|
+
first_name: string;
|
|
117
|
+
last_name?: string;
|
|
118
|
+
username?: string;
|
|
119
|
+
is_bot?: boolean;
|
|
120
|
+
};
|
|
121
|
+
export type TgChat = {
|
|
122
|
+
id: number;
|
|
123
|
+
type: "private" | "group" | "supergroup";
|
|
124
|
+
title?: string;
|
|
125
|
+
is_forum?: boolean;
|
|
126
|
+
};
|
|
127
|
+
/** Starts the fake Telegram Bot API (listens on a random 127.0.0.1 port). */
|
|
128
|
+
export declare function startFakeTelegram(opts?: FakeTelegramOptions): Promise<FakeTelegramServer>;
|
|
129
|
+
/** An update with a private (direct) message from `from`. */
|
|
130
|
+
export declare function telegramPrivateMessage(from: TgUser, text: string, o?: {
|
|
131
|
+
messageId?: number;
|
|
132
|
+
date?: number;
|
|
133
|
+
}): Record<string, unknown>;
|
|
134
|
+
/**
|
|
135
|
+
* An update with a group message. `mention` (with or without `@`) adds a `mention` entity at its
|
|
136
|
+
* UTF-16 offset, prefixing `@<mention> ` when the text lacks it; `replyTo` sets `reply_to_message`
|
|
137
|
+
* (from the bot when `fromBot` is given); `messageThreadId` sets the thread, with
|
|
138
|
+
* `is_topic_message` defaulting to the chat's `is_forum`; `caption` turns the message into a photo
|
|
139
|
+
* whose caption carries the text and entities.
|
|
140
|
+
*/
|
|
141
|
+
export declare function telegramGroupMessage(chat: TgChat, from: TgUser, text: string, o?: {
|
|
142
|
+
messageId?: number;
|
|
143
|
+
mention?: string;
|
|
144
|
+
replyTo?: {
|
|
145
|
+
messageId: number;
|
|
146
|
+
fromBot?: FakeTelegramBot;
|
|
147
|
+
text?: string;
|
|
148
|
+
};
|
|
149
|
+
messageThreadId?: number;
|
|
150
|
+
isTopicMessage?: boolean;
|
|
151
|
+
caption?: boolean;
|
|
152
|
+
}): Record<string, unknown>;
|
|
153
|
+
/** An update with a callback query: `from` pressed an inline button with `data` on a bot message. */
|
|
154
|
+
export declare function telegramCallback(from: TgUser, message: {
|
|
155
|
+
chatId: number;
|
|
156
|
+
messageId: number;
|
|
157
|
+
chatType?: string;
|
|
158
|
+
messageThreadId?: number;
|
|
159
|
+
}, data: string, o?: {
|
|
160
|
+
id?: string;
|
|
161
|
+
}): Record<string, unknown>;
|
|
162
|
+
/** Finds an inline keyboard button in a `reply_markup` (object or JSON string). */
|
|
163
|
+
export declare function findTelegramButton(replyMarkup: unknown, pred: (b: {
|
|
164
|
+
text: string;
|
|
165
|
+
callback_data?: string;
|
|
166
|
+
url?: string;
|
|
167
|
+
}) => boolean): {
|
|
168
|
+
text: string;
|
|
169
|
+
callback_data?: string;
|
|
170
|
+
url?: string;
|
|
171
|
+
} | undefined;
|
|
172
|
+
/** The headers Telegram sends to a webhook set with `secret_token`. */
|
|
173
|
+
export declare function telegramWebhookHeaders(secret: string): Record<string, string>;
|