@capybara-hq/testing 0.1.0-rc.31 → 0.1.0-rc.32

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.
@@ -28,6 +28,33 @@ export interface FakeOAuthServerOptions {
28
28
  dialect?: "oauth" | "slack";
29
29
  /** The `token_type` of successful token responses (default: `Bearer`; `user` with dialect slack). */
30
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;
31
58
  }
32
59
  /** 令牌端点收到的一次请求(不含任何密钥)。 */
33
60
  export interface FakeTokenRequest {
@@ -45,6 +72,8 @@ export interface FakeTokenRequest {
45
72
  export interface FakeOAuthServer {
46
73
  /** issuer(`http://127.0.0.1:<port>`),也是各端点的基址。 */
47
74
  issuer: string;
75
+ /** `${issuer}/jwks` (served in `oidc` mode only). */
76
+ jwksUrl: string;
48
77
  tokenRequests: FakeTokenRequest[];
49
78
  /** DCR 注册请求体。 */
50
79
  registrations: Record<string, unknown>[];
@@ -68,6 +97,21 @@ export interface FakeOAuthServer {
68
97
  failTokenRequests(n: number, status: number, body?: unknown): void;
69
98
  /** 下一次授权回跳的 RFC 9207 `iss` 改为该值(默认回跳带真实 issuer)。 */
70
99
  forgeIssNext(iss: string): void;
100
+ /**
101
+ * The next code exchange logs in with these claims (queued, one per exchange). Only takes effect
102
+ * with `oidc`. The claims override any claim the server sets (`iss`, `aud`, `nonce`, ...).
103
+ */
104
+ queueLogin(claims: FakeOidcClaims): void;
105
+ /**
106
+ * The next ID token carries these claims on top of the regular and queued ones (they win), signed with a
107
+ * key outside the JWKS (`foreignKey`) and/or a different `kid`.
108
+ */
109
+ tamperNextIdToken(claims: Record<string, unknown>, o?: {
110
+ foreignKey?: boolean;
111
+ kid?: string;
112
+ }): void;
113
+ /** The next ID token's `iss` is this value (a queued or tampered `iss` still wins). Only takes effect with `oidc`. */
114
+ issNext(iss: string): void;
71
115
  stop(): Promise<void>;
72
116
  }
73
117
  /**
@@ -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))}`;
@@ -45,8 +45,39 @@ export async function startFakeOAuthServer(opts = {}) {
45
45
  let tokenFailures;
46
46
  let forgedIss;
47
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
+ };
48
79
  const metadata = () => ({
49
- issuer,
80
+ issuer: oidc?.issuer ?? issuer,
50
81
  authorization_endpoint: `${issuer}/authorize`,
51
82
  token_endpoint: `${issuer}/token`,
52
83
  ...(dcr && { registration_endpoint: `${issuer}/register` }),
@@ -150,7 +181,13 @@ export async function startFakeOAuthServer(opts = {}) {
150
181
  if (grant.resource !== undefined && form.get("resource") !== grant.resource) {
151
182
  return fail(400, "invalid_target");
152
183
  }
153
- return json(res, 200, issue(client.clientId, grant.scope, true));
184
+ const body = issue(client.clientId, grant.scope, grant.allowRefresh);
185
+ if (oidc) {
186
+ const jwt = idToken(client.clientId, grant.nonce);
187
+ secrets.add(jwt);
188
+ body.id_token = jwt;
189
+ }
190
+ return json(res, 200, body);
154
191
  }
155
192
  if (grantType === "refresh_token") {
156
193
  const rt = form.get("refresh_token") ?? "";
@@ -205,6 +242,8 @@ export async function startFakeOAuthServer(opts = {}) {
205
242
  challenge,
206
243
  scope: q.get("scope") ?? undefined,
207
244
  resource: q.get("resource") ?? undefined,
245
+ nonce: q.get("nonce") ?? undefined,
246
+ allowRefresh: Object.entries(opts.refreshTokenOnlyWith ?? {}).every(([k, v]) => q.get(k) === v),
208
247
  });
209
248
  back.searchParams.set("code", code);
210
249
  }
@@ -248,7 +287,18 @@ export async function startFakeOAuthServer(opts = {}) {
248
287
  if (req.method === "GET" && path === "/.well-known/openid-configuration") {
249
288
  if (opts.metadata !== "openid")
250
289
  return json(res, 404, { error: "not_found" });
251
- return json(res, 200, { ...metadata(), subject_types_supported: ["public"] });
290
+ return json(res, 200, {
291
+ ...metadata(),
292
+ subject_types_supported: ["public"],
293
+ ...(oidc && {
294
+ jwks_uri: `${issuer}/jwks`,
295
+ id_token_signing_alg_values_supported: ["RS256"],
296
+ }),
297
+ });
298
+ }
299
+ if (req.method === "GET" && path === "/jwks" && signing) {
300
+ const jwk = signing.publicKey.export({ format: "jwk" });
301
+ return json(res, 200, { keys: [{ ...jwk, kid, alg: "RS256", use: "sig" }] });
252
302
  }
253
303
  if (req.method === "GET" && path === "/authorize")
254
304
  return authorize(url, res);
@@ -274,6 +324,7 @@ export async function startFakeOAuthServer(opts = {}) {
274
324
  issuer = `http://127.0.0.1:${port}`;
275
325
  return {
276
326
  issuer,
327
+ jwksUrl: `${issuer}/jwks`,
277
328
  tokenRequests,
278
329
  registrations,
279
330
  authorizeRequests,
@@ -290,6 +341,15 @@ export async function startFakeOAuthServer(opts = {}) {
290
341
  forgeIssNext: (iss) => {
291
342
  forgedIss = iss;
292
343
  },
344
+ queueLogin: (claims) => {
345
+ logins.push(claims);
346
+ },
347
+ tamperNextIdToken: (claims, o) => {
348
+ tamper = { claims, ...o };
349
+ },
350
+ issNext: (iss) => {
351
+ forgedIdTokenIss = iss;
352
+ },
293
353
  denyNext: (error, description) => {
294
354
  deny = { error, description };
295
355
  },
@@ -32,7 +32,7 @@ export declare const FAKE_EXTENSIONS: readonly ["fake-connector", "fake-openapi"
32
32
  *
33
33
  * | name | provides / covers |
34
34
  * |---|---|
35
- * | `fake-theme` | themes `neon-grid` (dark only, wordmark, font `FakeSans`, logo) and `paper` (light and dark); passes `capybara-plugin check` |
35
+ * | `fake-theme` | themes `neon-grid` (dark only, wordmark, font `FakeSans`, logo) and `paper` (light and dark), and `brand-kit` (dark and light, every brand asset: logo, illustration, app icons, avatars `bot` and `cat`; `brand/unnamed.svg` is in the directory but named by no theme); passes `capybara-plugin check` |
36
36
  */
37
37
  export declare const FAKE_PLUGINS: readonly ["fake-theme"];
38
38
  /** The name of a fake plugin. */
package/dist/fixtures.js CHANGED
@@ -55,7 +55,7 @@ export const FAKE_EXTENSIONS = [
55
55
  *
56
56
  * | name | provides / covers |
57
57
  * |---|---|
58
- * | `fake-theme` | themes `neon-grid` (dark only, wordmark, font `FakeSans`, logo) and `paper` (light and dark); passes `capybara-plugin check` |
58
+ * | `fake-theme` | themes `neon-grid` (dark only, wordmark, font `FakeSans`, logo) and `paper` (light and dark), and `brand-kit` (dark and light, every brand asset: logo, illustration, app icons, avatars `bot` and `cat`; `brand/unnamed.svg` is in the directory but named by no theme); passes `capybara-plugin check` |
59
59
  */
60
60
  export const FAKE_PLUGINS = ["fake-theme"];
61
61
  /** `fixtures/extensions/` of this package (same path from `src/` and from `dist/`). */
package/dist/index.d.ts CHANGED
@@ -15,7 +15,7 @@ export { type FakeMarketplace, type FakeMarketplaceRequest, startFakeMarketplace
15
15
  export { type FakeMcpCallInfo, type FakeMcpHandlerContext, type FakeMcpPrompt, type FakeMcpRequest, type FakeMcpResource, FakeMcpRpcError, type FakeMcpServer, type FakeMcpServerOptions, type FakeMcpTool, startFakeMcpServer, } from "./fake-mcp-server.js";
16
16
  export { type FakeModelServer, type FakeRequest, type FakeResponse, startFakeModelServer, } from "./fake-model-server.js";
17
17
  export { type FakeNpmPackage, type FakeNpmRegistry, npmProvenanceAttestations, startFakeNpmRegistry, } from "./fake-npm-registry.js";
18
- export { type FakeOAuthClient, type FakeOAuthServer, type FakeOAuthServerOptions, type FakeTokenRequest, startFakeOAuthServer, } from "./fake-oauth-server.js";
18
+ export { type FakeOAuthClient, type FakeOAuthServer, type FakeOAuthServerOptions, type FakeOidcClaims, type FakeTokenRequest, startFakeOAuthServer, } from "./fake-oauth-server.js";
19
19
  export { defaultFakeOpenApiSpec, type FakeOpenApiRequest, type FakeOpenApiServer, type FakeOpenApiServerOptions, type FakePet, startFakeOpenApiServer, } from "./fake-openapi-server.js";
20
20
  export { type FakeSlackAck, type FakeSlackCall, type FakeSlackFailure, type FakeSlackFile, type FakeSlackMessage, type FakeSlackOptions, type FakeSlackServer, type FakeSlackUser, findSlackButton, signSlackWebhook, slackBlockAction, slackDmEvent, slackEventCallback, slackInteractiveForm, slackMentionEvent, startFakeSlack, } from "./fake-slack.js";
21
21
  export { type FakeTelegramBot, type FakeTelegramCall, type FakeTelegramFailure, type FakeTelegramMessage, type FakeTelegramOptions, type FakeTelegramServer, findTelegramButton, startFakeTelegram, type TgChat, type TgUser, telegramCallback, telegramGroupMessage, telegramPrivateMessage, telegramWebhookHeaders, } from "./fake-telegram.js";
@@ -3,5 +3,5 @@
3
3
  "name": "fake-theme",
4
4
  "version": "0.1.0",
5
5
  "publisher": "Capybara",
6
- "description": "Fixture: a declarative plugin with two themes and no extension"
6
+ "description": "Fixture: a declarative plugin with themes and no extension"
7
7
  }
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><title>Bot</title><rect width="32" height="32" fill="#2B6CB0"/><rect x="8" y="10" width="16" height="12" fill="#FFFFFF"/><circle cx="13" cy="16" r="2" fill="#2B6CB0"/><circle cx="19" cy="16" r="2" fill="#2B6CB0"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 80"><title>Brand kit illustration</title><rect width="120" height="80" fill="#2B6CB0"/><circle cx="60" cy="40" r="20" fill="#F6E05E"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><title>Unnamed</title><rect width="10" height="10" fill="#888888"/></svg>
@@ -2,7 +2,7 @@
2
2
  "name": "@capybara-hq/plugin-fake-theme",
3
3
  "version": "0.1.0",
4
4
  "private": true,
5
- "description": "Fixture: a declarative plugin with two themes and no extension",
5
+ "description": "Fixture: a declarative plugin with themes and no extension",
6
6
  "license": "Apache-2.0",
7
7
  "type": "module"
8
8
  }
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": { "en": "Brand Kit", "zh": "品牌套件" },
3
+ "schemes": {
4
+ "dark": {
5
+ "color": { "bg": "#05070D", "panel": "#0A0E18", "accent": "#63B3ED", "on-accent": "#05121F" }
6
+ },
7
+ "light": {
8
+ "color": { "bg": "#F7FAFC", "panel": "#FFFFFF", "accent": "#2B6CB0", "on-accent": "#FFFFFF" }
9
+ }
10
+ },
11
+ "logo": {
12
+ "mark": "./logo.svg",
13
+ "wordmark": "BRAND KIT",
14
+ "illustration": "./brand/illustration.svg",
15
+ "appIcon": "./brand/app-512.png",
16
+ "appIconMaskable": "./brand/app-mask-512.png"
17
+ },
18
+ "decoration": "none",
19
+ "avatars": [
20
+ { "id": "bot", "name": { "en": "Bot", "zh": "机器人" }, "file": "./brand/avatars/bot.svg" },
21
+ { "id": "cat", "name": { "en": "Cat", "zh": "猫" }, "file": "./brand/avatars/cat.png" }
22
+ ],
23
+ "hideAvatarPresets": ["capybara"]
24
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/testing",
3
- "version": "0.1.0-rc.31",
3
+ "version": "0.1.0-rc.32",
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.63"
50
+ "@capybara-hq/kernel": "^0.1.0-rc.66"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/pg": "^8.23.1",
54
54
  "@types/ws": "^8.18.2",
55
55
  "@capybara-hq/plugin-client": "^0.1.0-rc.7",
56
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.48"
56
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.50"
57
57
  },
58
58
  "peerDependencies": {
59
59
  "vitest": "^5.0.5",
60
- "@capybara-hq/plugin-tools": "^0.1.0-rc.18",
61
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.48"
60
+ "@capybara-hq/plugin-tools": "^0.1.0-rc.19",
61
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.50"
62
62
  },
63
63
  "peerDependenciesMeta": {
64
64
  "@capybara-hq/plugin-tools": {