@capybara-hq/testing 0.1.0-rc.17 → 0.1.0-rc.19

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.
@@ -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", () => { });
@@ -169,8 +171,8 @@ const fastImportPath = (path) => /^"|[\n"\\]/.test(path)
169
171
  ? `"${path.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`
170
172
  : path;
171
173
  /**
172
- * A fake git host: bare repos in a temp dir, served read-only by the system `git http-backend`
173
- * (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
174
176
  * (`uploadpack.allowReachableSHA1InWant`, as GitHub does). Needs `git` on PATH.
175
177
  *
176
178
  * Spawning git is what these tests spend their time on, and it slows down most under load, so the
@@ -178,26 +180,66 @@ const fastImportPath = (path) => /^"|[\n"\\]/.test(path)
178
180
  * `git fast-import`, and a ref advertisement (`GET …/info/refs`) is answered by http-backend once per
179
181
  * repo state, then repeated until the next commit to that repo.
180
182
  */
181
- export async function startFakeGitServer() {
183
+ export async function startFakeGitServer(options = {}) {
182
184
  const root = await mkdtemp(join(tmpdir(), "capybara-fake-git-"));
183
185
  const requests = [];
184
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")}`;
185
192
  /** Ref advertisements by repo, then by request (path, query and `Git-Protocol`). */
186
193
  const advertised = new Map();
187
194
  /** Bumped by every commit to a repo: an answer read before the commit is not kept. */
188
195
  const generation = new Map();
189
- 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];
190
198
  const server = createServer((req, res) => {
191
- const r = { method: req.method ?? "GET", path: req.url ?? "/" };
192
- 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") {
193
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;
194
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
+ }
195
230
  if (redirect !== null) {
196
231
  res.writeHead(302, { location: redirect }).end();
197
232
  return;
198
233
  }
199
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
200
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
+ }
201
243
  if (repo === undefined) {
202
244
  serveCgi(root, req, res);
203
245
  return;
@@ -225,6 +267,13 @@ export async function startFakeGitServer() {
225
267
  });
226
268
  await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
227
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
+ };
228
277
  const repoDir = async (repo) => {
229
278
  if (!REPO_RE.test(repo))
230
279
  throw new Error(`invalid fake repo name: ${repo}`);
@@ -307,19 +356,36 @@ export async function startFakeGitServer() {
307
356
  advertised.delete(repo);
308
357
  return sha;
309
358
  };
310
- return {
359
+ const fake = {
311
360
  url: (repo) => `http://127.0.0.1:${port}/${repo}.git`,
312
361
  commit,
313
362
  setRedirect: (l) => {
314
363
  redirect = l;
315
364
  },
316
- requests,
317
- stop: async () => {
318
- await new Promise((resolve) => {
319
- server.closeAllConnections();
320
- server.close(() => resolve());
321
- });
322
- await rm(root, { recursive: true, force: true });
365
+ failNext: (status, body = "") => {
366
+ nextFail = { status, body };
367
+ },
368
+ redirectNext: (l) => {
369
+ nextRedirect = l;
323
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,
324
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;
325
391
  }
package/dist/index.d.ts CHANGED
@@ -9,7 +9,7 @@ export { createDualReplicaHarness, type DualReplicaOptions, type ExtraReplicaHan
9
9
  export { assertExtensionSecretsReachable, extensionDeploymentSecretValues, } from "./extension-config.js";
10
10
  export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, type FakeChannelCheckCall, type FakeChannelFailMatch, type FakeChannelPost, type FakeChannelSent, type FakeChannelServer, type FakeChannelServerOptions, type FakeChannelStream, type FakeChannelUser, type FakeDirectoryBook, type FakeSenderProfile, fakeCardAction, fakeDirectoryMember, fakeDm, fakeGroupMessage, fakeWebhookChallenge, fakeWebhookEvents, signFakeWebhook, startFakeChannelServer, } from "./fake-channel.js";
11
11
  export { type FakeE2BCall, type FakeE2BMatch, type FakeE2BOptions, type FakeE2BSandbox, type FakeE2BServer, startFakeE2B, } from "./fake-e2b.js";
12
- export { type FakeGitCommitOptions, type FakeGitRequest, type FakeGitServer, startFakeGitServer, } from "./fake-git-server.js";
12
+ export { type FakeGitCommitOptions, type FakeGitRequest, type FakeGitServer, type FakeGitServerOptions, startFakeGitServer, } from "./fake-git-server.js";
13
13
  export { encryptLarkWebhook, type FakeLarkAck, type FakeLarkApi, type FakeLarkButton, type FakeLarkCall, type FakeLarkDepartment, type FakeLarkFailure, type FakeLarkMessage, type FakeLarkOptions, type FakeLarkServer, type FakeLarkUser, findLarkButton, larkCardAction, larkMessageEvent, signLarkWebhook, startFakeLark, } from "./fake-lark.js";
14
14
  export { type FakeMarketplace, type FakeMarketplaceRequest, startFakeMarketplace, } from "./fake-marketplace.js";
15
15
  export { type FakeMcpCallInfo, type FakeMcpHandlerContext, type FakeMcpPrompt, type FakeMcpRequest, type FakeMcpResource, FakeMcpRpcError, type FakeMcpServer, type FakeMcpServerOptions, type FakeMcpTool, startFakeMcpServer, } from "./fake-mcp-server.js";
@@ -10,7 +10,7 @@ export default defineExtension({
10
10
  version: "0.1.0",
11
11
  sdk: "^0.1.0-rc.0",
12
12
  provides: ["counter@1"],
13
- permissions: { http: [{ method: "GET", path: "/ping" }] },
13
+ permissions: { http: [{ method: "GET", path: "/ping", access: "public" }] },
14
14
  setup(ctx) {
15
15
  const pong = "pong from fake-dep-provider";
16
16
  ctx.provide("counter@1", { ping: () => pong });
@@ -11,7 +11,7 @@ export default defineExtension({
11
11
  sdk: "^0.1.0-rc.0",
12
12
  provides: [],
13
13
  requires: ["counter@1"],
14
- permissions: { http: [{ method: "GET", path: "/ping" }] },
14
+ permissions: { http: [{ method: "GET", path: "/ping", access: "public" }] },
15
15
  setup(ctx) {
16
16
  ctx.http.route("GET", "/ping", async () => {
17
17
  const impl = ctx.extensionPoints.list<{ ping(): string }>("counter@1")[0]?.impl;
@@ -1,27 +1,27 @@
1
- import { defineExtension, EMBED_PROTOCOL, type OrgEmbedClaims } from "@capybara-hq/plugin-sdk";
1
+ import { defineExtension, EMBED_PROTOCOL, type RouteCaller } from "@capybara-hq/plugin-sdk";
2
2
  import { z } from "zod";
3
3
 
4
4
  /**
5
5
  * Test fake of an embed extension (`ui.embeds`): the kernel side of embedded apps (token issue and
6
6
  * verification, the `/plugin-ui` proxy, `ctx.bus` across replicas) without the official board.
7
7
  * - embeds `panel` (org page, `/ui/panel`) and `panel-conv` (conversation tab, `/ui/panel-conv`);
8
- * both pages are static HTML loading the static script `/ui/panel.js`; none of them needs a
9
- * token. The script speaks the host's message bridge (`capybara-embed/1`): on `init` it fetches
8
+ * both pages are static HTML loading the static script `/ui/panel.js`; all three are `public`
9
+ * GET routes (an iframe navigation carries no token). The script speaks the host's message bridge (`capybara-embed/1`): on `init` it fetches
10
10
  * `claims` with the token it was given, shows `<contribution> <orgId>` in `#status` and posts a
11
11
  * `toast` "fake-embed ready" to the host (a failed fetch shows `error <status>`), then reads the
12
12
  * `/ui/events` stream with the token: `ready` sets `data-live="1"` on the body, each `event`
13
13
  * shows its text in `#event`;
14
- * - every data route checks `Authorization: Bearer <embed token>` with `ctx.ui.verifyEmbedToken`
15
- * (401 otherwise); identity comes only from the claims;
16
- * - `GET /ui/claims` returns the verified claims;
14
+ * - every data route is an `embed` route: the kernel checks the embed token (`Authorization: Bearer`
15
+ * or `?token=`) and hands the handler the caller; identity comes only from `caller` (an org-scope
16
+ * caller, 401 otherwise);
17
+ * - `GET /ui/claims` returns the caller;
17
18
  * - `POST /ui/events` `{ text }` publishes `{ conversationId, text }` on the bus topic
18
19
  * `events.<orgId>` (202);
19
20
  * - `GET /ui/events` is an SSE stream: `ready` first, then an `event` for each message in the
20
21
  * token's scope (its conversation, or org-wide messages for a page token); it ends when the
21
- * client disconnects or the token expires.
22
+ * client disconnects or the token expires (`caller.exp`).
22
23
  */
23
24
 
24
- const BEARER_RE = /^Bearer ([A-Za-z0-9._-]{1,4096})$/;
25
25
  const EventBody = z.object({ text: z.string().min(1).max(200) });
26
26
 
27
27
  const PAGE = `<!doctype html><html><head><meta charset="utf-8"><title>Fake embed</title><script src="./panel.js"></script></head><body><p>fake-embed</p><p id="status">waiting</p><p id="event"></p></body></html>`;
@@ -110,22 +110,19 @@ export default defineExtension({
110
110
  ],
111
111
  permissions: {
112
112
  http: [
113
- { method: "GET", path: "/ui/panel" },
114
- { method: "GET", path: "/ui/panel-conv" },
115
- { method: "GET", path: "/ui/panel.js" },
116
- { method: "GET", path: "/ui/claims" },
117
- { method: "POST", path: "/ui/events" },
118
- { method: "GET", path: "/ui/events" },
113
+ { method: "GET", path: "/ui/panel", access: "public" },
114
+ { method: "GET", path: "/ui/panel-conv", access: "public" },
115
+ { method: "GET", path: "/ui/panel.js", access: "public" },
116
+ { method: "GET", path: "/ui/claims", access: "embed" },
117
+ { method: "POST", path: "/ui/events", access: "embed" },
118
+ { method: "GET", path: "/ui/events", access: "embed" },
119
119
  ],
120
120
  ui: { embeds: ["panel", "panel-conv"] },
121
121
  },
122
122
  setup(ctx) {
123
- /** An org-scope token's claims (every contribution here is in an org slot), or null. */
124
- const auth = async (req: Request): Promise<OrgEmbedClaims | null> => {
125
- const m = BEARER_RE.exec(req.headers.get("authorization") ?? "");
126
- const claims = m?.[1] === undefined ? null : await ctx.ui.verifyEmbedToken(m[1]);
127
- return claims?.scope === "org" ? claims : null;
128
- };
123
+ /** The org-scope embed caller (every contribution here is in an org slot), or null. */
124
+ const auth = (caller: RouteCaller) =>
125
+ caller.access === "embed" && caller.scope === "org" ? caller : null;
129
126
  const page = async () =>
130
127
  new Response(PAGE, { headers: { "content-type": "text/html; charset=utf-8" } });
131
128
  ctx.http.route("GET", "/ui/panel", page);
@@ -137,13 +134,13 @@ export default defineExtension({
137
134
  new Response(SCRIPT, { headers: { "content-type": "text/javascript; charset=utf-8" } }),
138
135
  );
139
136
 
140
- ctx.http.route("GET", "/ui/claims", async (req) => {
141
- const claims = await auth(req);
137
+ ctx.http.route("GET", "/ui/claims", async (_req, caller) => {
138
+ const claims = auth(caller);
142
139
  return claims ? json(200, claims) : unauthorized();
143
140
  });
144
141
 
145
- ctx.http.route("POST", "/ui/events", async (req) => {
146
- const claims = await auth(req);
142
+ ctx.http.route("POST", "/ui/events", async (req, caller) => {
143
+ const claims = auth(caller);
147
144
  if (!claims) return unauthorized();
148
145
  const body = EventBody.safeParse(await req.json().catch(() => undefined));
149
146
  if (!body.success) {
@@ -156,9 +153,10 @@ export default defineExtension({
156
153
  return json(202, { published: true });
157
154
  });
158
155
 
159
- ctx.http.route("GET", "/ui/events", async (req) => {
160
- const claims = await auth(req);
156
+ ctx.http.route("GET", "/ui/events", async (req, caller) => {
157
+ const claims = auth(caller);
161
158
  if (!claims) return unauthorized();
159
+ // ends when the client disconnects or the token expires (`caller.exp`)
162
160
  const done = AbortSignal.any([
163
161
  req.signal,
164
162
  AbortSignal.timeout(Math.max(1, claims.exp * 1000 - Date.now())),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/testing",
3
- "version": "0.1.0-rc.17",
3
+ "version": "0.1.0-rc.19",
4
4
  "description": "Test helpers for Capybara: test containers, dual-replica harness and fake third-party servers",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -47,18 +47,18 @@
47
47
  "tsx": "^4.23.15",
48
48
  "ws": "^8.22.0",
49
49
  "zod": "^4.6.7",
50
- "@capybara-hq/kernel": "^0.1.0-rc.25"
50
+ "@capybara-hq/kernel": "^0.1.0-rc.32"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/pg": "^8.23.1",
54
54
  "@types/ws": "^8.18.2",
55
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.19",
56
- "@capybara-hq/plugin-client": "^0.1.0-rc.4"
55
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.23",
56
+ "@capybara-hq/plugin-client": "^0.1.0-rc.5"
57
57
  },
58
58
  "peerDependencies": {
59
59
  "vitest": "^5.0.5",
60
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.19",
61
- "@capybara-hq/plugin-tools": "^0.1.0-rc.13"
60
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.23",
61
+ "@capybara-hq/plugin-tools": "^0.1.0-rc.15"
62
62
  },
63
63
  "peerDependenciesMeta": {
64
64
  "@capybara-hq/plugin-tools": {