diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 37e4bd4..83bad44 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -3,5 +3,6 @@ "packages/storage": "1.0.0", "packages/ops": "1.0.0", "packages/auth-client": "1.1.1", - "packages/legal": "1.0.0" + "packages/legal": "1.0.0", + "packages/e2e": "0.0.0" } diff --git a/AGENTS.md b/AGENTS.md index a1b0e8c..7bf0d43 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,6 +11,7 @@ packages/storage @lumorphia/storage オブジェクトストレージの境界 packages/ops @lumorphia/ops 運用の土台。入口は logger (pino、Node 専用)、notify (Discord)、sentry (伏せ字、ブラウザでも動く) packages/auth-client @lumorphia/auth-client OIDC のログイン・claim・ログアウト。DB はサービスのアダプターで受ける packages/legal @lumorphia/legal 規約とプライバシーポリシーの本文の読み取りと表示、同意した版と今の版の比較 (ブラウザでも動く) +packages/e2e @lumorphia/e2e サービスの E2E の土台。Lumorphia アカウントの発行元のふり、E2E 専用の TLS、Playwright の helper (ADR-0010) tooling/ リポジトリ全体の決まりのテスト (依存の向き、公開する package.json) docs/adr/ 設計判断 ``` @@ -28,6 +29,7 @@ docs/adr/ 設計判断 - `auth-client` は認証の境界だけ。画像・ストレージ・運用の実装に依存しない - `legal` は画面でも本文を表示するので Node API を使わない。ファイルの読み込みと同意の記録の形はサービスが決める - キーの付け方 (`tmp/`、`posts/` など) はサービスが決める。`storage` は知らない +- `e2e` の発行元のふりは auth-client を import しない (同じ実装からトークンを作ると、ずれを見つけられない)。auth-client はテストからだけ使い、偽物が出すものを auth-client で確かめる (ADR-0010) ## ほかのリポジトリと共通の開発の道具 (ADR-0009) diff --git a/docs/adr/0009-shared-dev-tooling.md b/docs/adr/0009-shared-dev-tooling.md index 56a9b3b..3e6aabe 100644 --- a/docs/adr/0009-shared-dev-tooling.md +++ b/docs/adr/0009-shared-dev-tooling.md @@ -15,7 +15,7 @@ lumorphia/scenote の ADR-0006 で、開発の道具 (ESLint・TypeScript・Pret - **Renovate の共通の設定**を `renovate/default.json` に置く。各リポジトリは `"extends": ["local>lumorphia/platform//renovate/default"]` で読み、リポジトリだけの決まり (prismtone の postgres や transformers の上限など) と hostRules を自分の `renovate.json` に足す。Renovate は main の版を読む - **CI の再利用ワークフロー**を置く。`security.yml` (gitleaks で履歴全体、高リスクの脆弱性は警告、追加の検査) と `release.yml` (release-please と、版が上がったパッケージだけを GitHub Packages に公開。platform と umbra の形)。呼び出し側は `lumorphia/platform/.github/workflows/<名前>.yml@
# main` で固定し、Renovate が上げる。lint・テスト・E2E・Docker はリポジトリごとの違いが大きいので共通にしない - **Prettier・TypeScript・ESLint の基本の設定はパッケージにしない**。数行で、版を上げる手間のほうが大きい。新しいリポジトリは AGENTS.md の「手本」の一覧から写す -- **E2E の土台は、Scenote の骨組みと一緒に切り出す**。3 つ目の使い手が出たときのほうが、共通の形を決めやすい +- **E2E の土台は、Scenote の骨組みと一緒に切り出す**。3 つ目の使い手が出たときのほうが、共通の形を決めやすい (2026-10-12 追記: Scenote のログインの段に回し、ADR-0010 で `@lumorphia/e2e` にした) ## Consequences diff --git a/docs/adr/0010-e2e-package.md b/docs/adr/0010-e2e-package.md new file mode 100644 index 0000000..07a4ed9 --- /dev/null +++ b/docs/adr/0010-e2e-package.md @@ -0,0 +1,54 @@ +# ADR-0010: E2E の土台を @lumorphia/e2e にし、偽の発行元は auth-client で確かめる + +| 項目 | 内容 | +| -------- | ---------- | +| Status | Accepted | +| Date | 2026-10-12 | +| Deciders | t1nyb0x | + +## Context + +ADR-0009 は「E2E の土台は Scenote の骨組みと一緒に切り出す」とした。Scenote の骨組み (scenote ADR-0008) の時点で共有できたのは、CSP の違反を見張る fixture、hydration を待つ helper、開発の証明書のスクリプトで、どれも数十行だった。切り出す価値が大きいのは、prismtone の `e2e/mock-lumorphia.ts` (Lumorphia アカウントの発行元のふり) と `e2e/tls.ts` (E2E 専用の CA) で、Scenote がこれを使うのはログインの段 (S4) になる。scenote ADR-0008 で、切り出しを S4 に回した。 + +偽の発行元は、サービスの E2E が本物の accounts と同じ形で通るためのもの。prismtone の版は、本物の accounts とつないで初めて「ID トークンに email が入らない」ことが分かり、偽物も直した (platform#24)。偽物が auth-client や accounts とずれても、偽物を相手にした E2E は緑のまま通る。 + +## Decision + +- `@lumorphia/e2e` を作り、入口を 3 つに分ける + - `./tls`: E2E 専用の CA と 127.0.0.1・localhost の証明書 (`ensureE2eTls`)、Chromium に証明書を信頼させる公開鍵のハッシュ (`certificateSpki`) + - `./mock-issuer`: 発行元のふり (`startMockIssuer`)。discovery・JWKS・認可・token・UserInfo・end-session、accounts の `/api/characters`、サービスが足す API (`extraRoutes`。prismtone の引き継ぎの完了など)。テストからの操作で、認可の code、back-channel logout、退会の知らせ (送り直しを含む) を出す。アプリに届かないときは 502 と理由を返す (応答しないまま止まらない)。bin の `lumorphia-mock-issuer` は環境変数で起動し、Playwright の webServer から使う + - `./playwright`: CSP の違反を見張る `test`、`approveLumorphia`、back-channel logout と退会の知らせを送る helper、`lumorphiaUser` +- **認可の画面は、偽の発行元が自分で承認する**。承認する利用者は、テストが発行元のオリジンの Cookie に置く (`approveLumorphia`)。prismtone の形 (`page.route` で認可の要求を受け、`route.fetch` でアプリの 302 をたどる) は、`route.fetch` が Node から送るので Chromium の `--host-resolver-rules` が効かず、`*.lumorphia.test` で動くサービス (Scenote) では使えなかった。Cookie はブラウザのコンテキストごとなので、並列のテストでも混ざらない +- **偽の発行元が出すものは、auth-client そのもので確かめる** (`getUserInfo`、`createLogoutTokenVerifier`、`createAccountEventVerifier`)。auth-client を変えて偽物とずれたら、このリポジトリのテストが落ちる +- **偽の発行元のコードは auth-client を import しない** (ESLint が止める)。同じ実装からトークンを作ると、ずれをテストで見つけられない。auth-client はテストからだけ使う +- サービスごとの偽物 (Discord・Google の OAuth、Misskey、Mastodon、Lodestone) は切り出さない。使うのは accounts と prismtone の旧ログインだけで、Scenote は使わない +- 開発の証明書 (`*.lumorphia.test`、各サービスの `scripts/dev-certs.sh`) も切り出さない。シェルの数十行で、Caddy の compose と一緒に読むほうが分かりやすい +- Scenote から使い始める。prismtone と accounts の載せ替えは、それぞれの都合で行う + +## Consequences + +### 良い点 + +- 偽の発行元が 1 つになり、auth-client と食い違わないことを CI が確かめる +- Facetia は、`startMockIssuer` と `approveLumorphia` を並べるだけでログインの E2E を始められる + +### 悪い点・受け入れるリスク + +- 本物の accounts とのずれ (auth-client が確かめていないもの) は残る。気づいたら偽物と auth-client の両方を直す +- E2E の土台の変更でも版を上げることになる。サービスは devDependencies に固定して入れる + +### 追従して必要になること + +- prismtone と accounts の `e2e/mock-lumorphia.ts`・`e2e/tls.ts` を載せ替える (それぞれの PR で) +- ADR-0009 の E2E の土台の行は、この ADR で置き換える + +## Alternatives + +- prismtone の偽物をそのまま写す: 引き継ぎなど prismtone だけの口が混ざり、3 つ目の写しになる +- 本物の accounts を E2E で立てる: accounts の DB とビルドが要り、サービスの E2E が重くなる。偽物を auth-client で確かめるほうが軽い + +## References + +- ADR-0005、ADR-0006、ADR-0009 +- lumorphia/scenote ADR-0008 +- lumorphia/prismtone `e2e/mock-lumorphia.ts`、`e2e/tls.ts`、`e2e/lumorphia.ts` diff --git a/docs/adr/README.md b/docs/adr/README.md index 3a07735..ccde9e5 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -16,5 +16,6 @@ | [0008](0008-legal-package.md) | 規約の本文と同意の版の比較を @lumorphia/legal にまとめる | | [0009](0009-shared-dev-tooling.md) | 開発の道具は Renovate の共通の設定と CI の再利用ワークフローだけを共通にする | +| [0010](0010-e2e-package.md) | E2E の土台を @lumorphia/e2e にし、偽の発行元は auth-client で確かめる | 本文中の「prismtone ADR-NNNN」は lumorphia/prismtone の ADR を指す。 diff --git a/eslint.config.js b/eslint.config.js index 9752ac5..3fa913d 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -116,6 +116,24 @@ export default tseslint.config( storage, ops, opsSentry, + // 発行元のふりは auth-client と別に作る。同じ実装からトークンを作ると、食い違いをテストで見つけられない + { + files: ["packages/e2e/**/*.ts"], + ignores: ["packages/e2e/**/*.test.ts"], + ...restrict([ + SERVICES, + UMBRA, + DEEP, + { + group: ["@lumorphia/auth-client", "@lumorphia/auth-client/*"], + message: "e2e は auth-client の前に立つ偽物。auth-client はテストからだけ使う", + }, + ]), + }, + { + files: ["packages/e2e/**/*.test.ts"], + ...restrict([SERVICES, UMBRA, DEEP]), + }, // 規約の本文は画面でも表示するので、ブラウザで動く形に保つ { files: ["packages/legal/**/*.ts"], diff --git a/packages/e2e/package.json b/packages/e2e/package.json new file mode 100644 index 0000000..121285b --- /dev/null +++ b/packages/e2e/package.json @@ -0,0 +1,64 @@ +{ + "name": "@lumorphia/e2e", + "version": "0.0.0", + "description": "サービスの E2E の土台。Lumorphia アカウントの発行元のふり、E2E 専用の TLS、Playwright の helper と CSP の見張り", + "license": "AGPL-3.0-only", + "repository": { + "type": "git", + "url": "git+https://github.com/lumorphia/platform.git", + "directory": "packages/e2e" + }, + "publishConfig": { + "registry": "https://npm.pkg.github.com" + }, + "type": "module", + "exports": { + "./tls": { + "source": "./src/tls.ts", + "types": "./dist/tls.d.ts", + "default": "./dist/tls.js" + }, + "./mock-issuer": { + "source": "./src/mock-issuer.ts", + "types": "./dist/mock-issuer.d.ts", + "default": "./dist/mock-issuer.js" + }, + "./playwright": { + "source": "./src/playwright.ts", + "types": "./dist/playwright.d.ts", + "default": "./dist/playwright.js" + } + }, + "bin": { + "lumorphia-mock-issuer": "./dist/bin/mock-issuer.js" + }, + "scripts": { + "build": "rm -rf dist && tsc -p tsconfig.build.json", + "typecheck": "tsc -p tsconfig.json", + "test": "vitest run", + "prepack": "cp ../../LICENSE LICENSE", + "postpack": "rm -f LICENSE" + }, + "files": [ + "dist", + "src", + "!src/**/*.test.ts", + "!src/test-setup.ts" + ], + "dependencies": { + "jose": "6.2.12" + }, + "peerDependencies": { + "@playwright/test": "^1.63.0" + }, + "peerDependenciesMeta": { + "@playwright/test": { + "optional": true + } + }, + "devDependencies": { + "@lumorphia/auth-client": "workspace:*", + "@playwright/test": "^1.63.0", + "better-auth": "1.7.7" + } +} diff --git a/packages/e2e/src/bin/mock-issuer.ts b/packages/e2e/src/bin/mock-issuer.ts new file mode 100644 index 0000000..0ad2359 --- /dev/null +++ b/packages/e2e/src/bin/mock-issuer.ts @@ -0,0 +1,9 @@ +#!/usr/bin/env node +// Playwright の webServer から起こす発行元のふり。設定は環境変数 (../env.ts) +import { mockIssuerOptionsFromEnv } from "../env.ts"; +import { startMockIssuer } from "../mock-issuer.ts"; + +const mock = await startMockIssuer(mockIssuerOptionsFromEnv(process.env)); +console.log(`mock Lumorphia issuer: ${mock.issuer} (control ${mock.controlUrl})`); +for (const signal of ["SIGINT", "SIGTERM"] as const) + process.once(signal, () => void mock.close().then(() => process.exit(0))); diff --git a/packages/e2e/src/env.test.ts b/packages/e2e/src/env.test.ts new file mode 100644 index 0000000..d284979 --- /dev/null +++ b/packages/e2e/src/env.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from "vitest"; +import { mockIssuerOptionsFromEnv } from "./env.ts"; + +const base = { + LUMORPHIA_CLIENT_ID: "test-client", + LUMORPHIA_SERVICE: "scenote", + MOCK_LUMORPHIA_CERT: "/tls/cert.pem", + MOCK_LUMORPHIA_KEY: "/tls/key.pem", + APP_BASE_URL: "https://127.0.0.1:3445", +}; + +describe("mockIssuerOptionsFromEnv", () => { + it("reads the client, the service, the certificate and the app", () => { + expect(mockIssuerOptionsFromEnv(base)).toMatchObject({ + clientId: "test-client", + service: "scenote", + tls: { cert: "/tls/cert.pem", key: "/tls/key.pem" }, + appBaseUrl: "https://127.0.0.1:3445", + }); + }); + + it("uses the ports prismtone has used when none are given", () => { + expect(mockIssuerOptionsFromEnv(base)).toMatchObject({ port: 3404, controlPort: 3405 }); + }); + + it("takes the ports from the environment", () => { + const options = mockIssuerOptionsFromEnv({ + ...base, + MOCK_LUMORPHIA_PORT: "3504", + MOCK_LUMORPHIA_CONTROL_PORT: "3505", + }); + expect(options).toMatchObject({ port: 3504, controlPort: 3505 }); + }); + + it("takes the origins end-session may send the browser back to", () => { + const options = mockIssuerOptionsFromEnv({ + ...base, + POST_LOGOUT_REDIRECT_ORIGINS: "https://scenote.lumorphia.test:3445,https://127.0.0.1:3445", + }); + expect(options.postLogoutRedirectOrigins).toEqual([ + "https://scenote.lumorphia.test:3445", + "https://127.0.0.1:3445", + ]); + }); + + it("refuses to start without a certificate", () => { + expect(() => mockIssuerOptionsFromEnv({ ...base, MOCK_LUMORPHIA_CERT: undefined })).toThrow( + /MOCK_LUMORPHIA_CERT/, + ); + }); + + it("refuses a service it does not know", () => { + expect(() => mockIssuerOptionsFromEnv({ ...base, LUMORPHIA_SERVICE: "other" })).toThrow( + /LUMORPHIA_SERVICE/, + ); + }); +}); diff --git a/packages/e2e/src/env.ts b/packages/e2e/src/env.ts new file mode 100644 index 0000000..4294bfa --- /dev/null +++ b/packages/e2e/src/env.ts @@ -0,0 +1,34 @@ +import type { LumorphiaServiceName, MockIssuerOptions } from "./mock-issuer.ts"; + +const SERVICES: readonly LumorphiaServiceName[] = ["prismtone", "scenote", "facetia"]; + +const required = (env: Record, name: string): string => { + const value = env[name]; + if (!value) throw new Error(`${name} が要る`); + return value; +}; + +/** + * bin (lumorphia-mock-issuer) が環境変数から起動の設定を作る。Playwright の webServer の env で渡す。 + * ポートの既定は lumorphia/prismtone で使ってきた 3404 (発行元) と 3405 (操作) + */ +export function mockIssuerOptionsFromEnv( + env: Record, +): MockIssuerOptions { + const service = required(env, "LUMORPHIA_SERVICE"); + if (!SERVICES.includes(service as LumorphiaServiceName)) + throw new Error(`LUMORPHIA_SERVICE は ${SERVICES.join(" / ")} のどれか`); + return { + clientId: required(env, "LUMORPHIA_CLIENT_ID"), + service: service as LumorphiaServiceName, + tls: { cert: required(env, "MOCK_LUMORPHIA_CERT"), key: required(env, "MOCK_LUMORPHIA_KEY") }, + appBaseUrl: required(env, "APP_BASE_URL"), + port: Number(env.MOCK_LUMORPHIA_PORT ?? 3404), + controlPort: Number(env.MOCK_LUMORPHIA_CONTROL_PORT ?? 3405), + ...(env.POST_LOGOUT_REDIRECT_ORIGINS + ? { postLogoutRedirectOrigins: env.POST_LOGOUT_REDIRECT_ORIGINS.split(",") } + : {}), + ...(env.BACKCHANNEL_LOGOUT_PATH ? { backchannelLogoutPath: env.BACKCHANNEL_LOGOUT_PATH } : {}), + ...(env.ACCOUNT_EVENTS_PATH ? { accountEventsPath: env.ACCOUNT_EVENTS_PATH } : {}), + }; +} diff --git a/packages/e2e/src/mock-issuer.test.ts b/packages/e2e/src/mock-issuer.test.ts new file mode 100644 index 0000000..b03292e --- /dev/null +++ b/packages/e2e/src/mock-issuer.test.ts @@ -0,0 +1,362 @@ +import { createServer, type Server } from "node:http"; +import { randomUUID } from "node:crypto"; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { + createAccountEventVerifier, + createLogoutTokenVerifier, + createLumorphiaOAuthConfig, +} from "@lumorphia/auth-client"; +import { + E2E_USER_COOKIE, + encodeE2eUser, + startMockIssuer, + type MockIssuer, + type MockLumorphiaUser, +} from "./mock-issuer.ts"; + +// 発行元のふりが出すものを、サービスが使う auth-client そのもので確かめる。auth-client と食い違えば、 +// サービスの E2E が本物の accounts と違う形で通ってしまう + +const CLIENT_ID = "test-e2e-client"; + +/** サービスのアプリのふり。発行元のふりが送る back-channel logout と退会の知らせを受け取る */ +let app: Server; +let appBaseUrl: string; +let received: { path: string; body: URLSearchParams }[] = []; +let appStatus = 204; +let mock: MockIssuer; + +const user = (overrides: Partial = {}): MockLumorphiaUser => ({ + sub: randomUUID(), + sid: `test-sid-${randomUUID()}`, + handle: "test_handle", + name: "テスト_利用者", + ...overrides, +}); + +async function control(path: string, body: unknown) { + const res = await fetch(`${mock.controlUrl}${path}`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + }); + return { status: res.status, body: (await res.json()) as Record }; +} + +async function authorize(u: MockLumorphiaUser, nonce = "test-nonce") { + const { body } = await control("/_e2e/authorize", { nonce, user: u }); + return body.code as string; +} + +async function exchange(code: string, clientId = CLIENT_ID) { + const res = await fetch(`${mock.issuer}/oauth2/token`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ grant_type: "authorization_code", code, client_id: clientId }), + }); + return { status: res.status, body: (await res.json()) as Record }; +} + +beforeAll(async () => { + app = createServer((req, res) => { + let raw = ""; + req.on("data", (chunk) => (raw += chunk)); + req.on("end", () => { + received = [...received, { path: req.url ?? "", body: new URLSearchParams(raw) }]; + res.writeHead(appStatus).end(); + }); + }); + await new Promise((resolve) => app.listen(0, "127.0.0.1", resolve)); + const address = app.address(); + appBaseUrl = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}`; + mock = await startMockIssuer({ + clientId: CLIENT_ID, + service: "scenote", + tls: { + cert: process.env.LUMORPHIA_E2E_TEST_CERT!, + key: process.env.LUMORPHIA_E2E_TEST_KEY!, + }, + appBaseUrl, + extraRoutes: async (request) => + request.path === "/api/test/echo" + ? { status: 200, body: { sub: request.user?.sub ?? null } } + : null, + }); +}); + +afterAll(async () => { + await mock.close(); + await new Promise((resolve) => app.close(resolve)); +}); + +beforeEach(() => { + received = []; + appStatus = 204; +}); + +describe("discovery", () => { + it("serves the issuer under /api/auth like the real accounts", async () => { + expect(mock.issuer).toMatch(/^https:\/\/127\.0\.0\.1:\d+\/api\/auth$/); + }); + + it("advertises the endpoints the services use", async () => { + const res = await fetch(`${mock.issuer}/.well-known/openid-configuration`); + expect(await res.json()).toMatchObject({ + issuer: mock.issuer, + token_endpoint: `${mock.issuer}/oauth2/token`, + userinfo_endpoint: `${mock.issuer}/oauth2/userinfo`, + end_session_endpoint: `${mock.issuer}/oauth2/end-session`, + jwks_uri: `${mock.issuer}/jwks`, + }); + }); +}); + +describe("login", () => { + it("logs in through auth-client's getUserInfo with the authorized user", async () => { + const u = user({ picture: "https://img.example.invalid/a.webp" }); + const { body } = await exchange(await authorize(u)); + const config = createLumorphiaOAuthConfig({ + issuer: mock.issuer, + clientId: CLIENT_ID, + clientSecret: "test-secret", + }); + const info = await config.getUserInfo!({ + idToken: body.id_token, + accessToken: body.access_token, + }); + expect(info).toMatchObject({ + sub: u.sub, + name: u.name, + image: u.picture, + emailVerified: true, + "https://lumorphia.com/handle": u.handle, + }); + }); + + it("hands auth-client the sid of the Lumorphia session", async () => { + const u = user(); + const { body } = await exchange(await authorize(u)); + let sid: string | null = null; + const config = createLumorphiaOAuthConfig({ + issuer: mock.issuer, + clientId: CLIENT_ID, + clientSecret: "test-secret", + onVerifiedLogin: (login) => { + sid = login.sid; + }, + }); + await config.getUserInfo!({ idToken: body.id_token, accessToken: body.access_token }); + expect(sid).toBe(u.sid); + }); + + it("puts the nonce of the authorization request into the ID token", async () => { + const { body } = await exchange(await authorize(user(), "test-nonce-2")); + const payload = JSON.parse(Buffer.from(body.id_token!.split(".")[1]!, "base64url").toString()); + expect(payload.nonce).toBe("test-nonce-2"); + }); + + it("accepts a code only once", async () => { + const code = await authorize(user()); + await exchange(code); + expect((await exchange(code)).status).toBe(400); + }); + + it("refuses a code for another client", async () => { + expect((await exchange(await authorize(user()), "test-other-client")).status).toBe(400); + }); + + it("refuses UserInfo without a token it issued", async () => { + const res = await fetch(`${mock.issuer}/oauth2/userinfo`, { + headers: { authorization: "Bearer test-unknown" }, + }); + expect(res.status).toBe(401); + }); +}); + +describe("authorization endpoint", () => { + const authorizeAs = (u: MockLumorphiaUser | null, params: Record = defaults()) => + fetch(`${mock.issuer}/oauth2/authorize?${new URLSearchParams(params)}`, { + redirect: "manual", + headers: u ? { cookie: `${E2E_USER_COOKIE}=${encodeE2eUser(u)}` } : {}, + }); + // appBaseUrl は beforeAll で決まるので、テストの中で組み立てる + const defaults = () => ({ + client_id: CLIENT_ID, + redirect_uri: `${appBaseUrl}/api/auth/callback/lumorphia`, + state: "test-state", + nonce: "test-nonce", + }); + + it("approves the user in the cookie and sends the browser back with a code", async () => { + const res = await authorizeAs(user()); + const back = new URL(res.headers.get("location")!); + expect(back.origin + back.pathname).toBe(defaults().redirect_uri); + expect(back.searchParams.get("state")).toBe("test-state"); + expect(back.searchParams.get("code")).toBeTruthy(); + }); + + it("issues a code for that user with the nonce of the request", async () => { + const u = user(); + const res = await authorizeAs(u); + const code = new URL(res.headers.get("location")!).searchParams.get("code")!; + const { body } = await exchange(code); + const payload = JSON.parse(Buffer.from(body.id_token!.split(".")[1]!, "base64url").toString()); + expect(payload).toMatchObject({ sub: u.sub, nonce: "test-nonce" }); + }); + + it("refuses without a user to approve", async () => { + expect((await authorizeAs(null)).status).toBe(400); + }); + + it("refuses another client", async () => { + expect((await authorizeAs(user(), { ...defaults(), client_id: "test-other" })).status).toBe( + 400, + ); + }); + + it("refuses a broken redirect URI instead of hanging", async () => { + expect((await authorizeAs(user(), { ...defaults(), redirect_uri: "not a url" })).status).toBe( + 400, + ); + }); +}); + +describe("end-session", () => { + const endSession = (params: Record) => + fetch(`${mock.issuer}/oauth2/end-session?${new URLSearchParams(params)}`, { + redirect: "manual", + }); + + it("sends the browser back to the service with the state", async () => { + const res = await endSession({ + client_id: CLIENT_ID, + post_logout_redirect_uri: `${appBaseUrl}/api/lumorphia/signed-out`, + state: "test-state", + }); + expect(res.status).toBe(302); + expect(res.headers.get("location")).toBe( + `${appBaseUrl}/api/lumorphia/signed-out?state=test-state`, + ); + }); + + it("refuses to send the browser to another site", async () => { + const res = await endSession({ + client_id: CLIENT_ID, + post_logout_redirect_uri: "https://evil.example/", + state: "test-state", + }); + expect(res.status).toBe(400); + }); +}); + +describe("accounts API", () => { + it("returns the user's characters to the access token", async () => { + const characters = [{ id: "test-character", lodestoneId: "1", name: "Test Chara" }]; + const { body } = await exchange(await authorize(user({ characters }))); + const res = await fetch(`${mock.issuer.replace(/\/api\/auth$/, "")}/api/characters`, { + headers: { authorization: `Bearer ${body.access_token}` }, + }); + expect(await res.json()).toEqual({ characters }); + }); + + it("answers routes the service adds, with the user of the access token", async () => { + const u = user(); + const { body } = await exchange(await authorize(u)); + const res = await fetch(`${mock.issuer.replace(/\/api\/auth$/, "")}/api/test/echo`, { + headers: { authorization: `Bearer ${body.access_token}` }, + }); + expect(await res.json()).toEqual({ sub: u.sub }); + }); + + it("answers an unknown path with 404", async () => { + const res = await fetch(`${mock.issuer.replace(/\/api\/auth$/, "")}/api/test/nope`); + expect(res.status).toBe(404); + }); +}); + +describe("back-channel logout", () => { + it("sends the app a Logout Token that auth-client accepts", async () => { + const u = user(); + await control("/_e2e/backchannel-logout", { sub: u.sub, sid: u.sid }); + const [sent] = received; + expect(sent?.path).toBe("/api/lumorphia/backchannel-logout"); + const verify = createLogoutTokenVerifier({ issuer: mock.issuer, clientId: CLIENT_ID }); + expect(await verify(sent!.body.get("logout_token")!)).toMatchObject({ + sub: u.sub, + sid: u.sid, + }); + }); + + it("tells the test when the app cannot be reached, instead of hanging", async () => { + const lost = await startMockIssuer({ + clientId: CLIENT_ID, + service: "scenote", + tls: { + cert: process.env.LUMORPHIA_E2E_TEST_CERT!, + key: process.env.LUMORPHIA_E2E_TEST_KEY!, + }, + appBaseUrl: "http://127.0.0.1:1", + }); + try { + const res = await fetch(`${lost.controlUrl}/_e2e/backchannel-logout`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ sub: "test-sub", sid: "test-sid" }), + }); + expect(res.status).toBe(502); + expect(((await res.json()) as { error: string }).error).toMatch(/app_unreachable/); + } finally { + await lost.close(); + } + }); + + it("reports the status the app answered with", async () => { + appStatus = 400; + const u = user(); + const { body } = await control("/_e2e/backchannel-logout", { sub: u.sub, sid: u.sid }); + expect(body).toEqual({ status: 400 }); + }); +}); + +describe("account events", () => { + const verify = () => + createAccountEventVerifier({ issuer: mock.issuer, clientId: CLIENT_ID, service: "scenote" }); + + it("sends a deletion with the 30 day recovery deadline that auth-client accepts", async () => { + const sub = randomUUID(); + await control("/_e2e/account-event", { sub, state: "deleted" }); + const [sent] = received; + expect(sent?.path).toBe("/api/lumorphia/account-events"); + const event = await verify()(sent!.body.get("event_token")!); + expect(event).toMatchObject({ sub, state: "deleted", scope: "account", service: "scenote" }); + expect(Date.parse(event.recoverUntil!) - Date.parse(event.deletedAt!)).toBe(30 * 86_400_000); + }); + + it("sends a recovery without a deadline", async () => { + const sub = randomUUID(); + await control("/_e2e/account-event", { sub, state: "active", scope: "service" }); + const event = await verify()(received[0]!.body.get("event_token")!); + expect(event).toMatchObject({ state: "active", scope: "service", deletedAt: null }); + }); + + it("raises the revision for each event of the same user", async () => { + const sub = randomUUID(); + await control("/_e2e/account-event", { sub, state: "deleted" }); + await control("/_e2e/account-event", { sub, state: "active" }); + const [first, second] = await Promise.all( + received.map((r) => verify()(r.body.get("event_token")!)), + ); + expect([first?.revision, second?.revision]).toEqual([1, 2]); + }); + + it("can send the same event twice, as accounts does when it retries", async () => { + const sub = randomUUID(); + const { body } = await control("/_e2e/account-event", { sub, state: "purged" }); + await control("/_e2e/account-event", { sub, resend: body.eventId }); + const [first, second] = await Promise.all( + received.map((r) => verify()(r.body.get("event_token")!)), + ); + expect(second?.eventId).toBe(first?.eventId); + expect(second?.revision).toBe(first?.revision); + }); +}); diff --git a/packages/e2e/src/mock-issuer.ts b/packages/e2e/src/mock-issuer.ts new file mode 100644 index 0000000..1fc9515 --- /dev/null +++ b/packages/e2e/src/mock-issuer.ts @@ -0,0 +1,368 @@ +import { randomUUID } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { + createServer as createHttpServer, + type IncomingMessage, + type Server, + type ServerResponse, +} from "node:http"; +import { createServer as createHttpsServer } from "node:https"; +import type { AddressInfo } from "node:net"; +import { exportJWK, generateKeyPair, SignJWT } from "jose"; + +/** + * E2E 用の Lumorphia アカウントの発行元のふり (lumorphia/prismtone の e2e/mock-lumorphia.ts から)。 + * - https (`port`): サービスのサーバーが叩く discovery・JWKS・token・UserInfo と、accounts の API + * (`/api/characters`、サービスが足す `extraRoutes`)。証明書は ./tls.ts + * - http (`controlPort`): テストからの操作。認可画面はブラウザ側で spec が受け (./playwright.ts)、ここに + * nonce と利用者を渡して code をもらう。back-channel logout と退会の知らせもここから送らせる + * + * 本物の accounts (Better Auth 1.7.7) に合わせ、email などの標準の claim は ID トークンに入れず UserInfo でだけ返す + */ + +export interface MockLumorphiaUser { + readonly sub: string; + /** Lumorphia のセッション。ID トークンの sid と back-channel logout に使う */ + readonly sid: string; + readonly handle: string; + readonly name: string; + readonly picture?: string | null; + readonly identities?: readonly { readonly provider: string; readonly id: string }[]; + /** accounts の GET /api/characters が返すキャラクター。形はそのまま返す */ + readonly characters?: readonly unknown[]; +} + +export type LumorphiaServiceName = "prismtone" | "scenote" | "facetia"; + +/** サービスが足す accounts の API (`/api/...`)。null を返すと 404 */ +export type MockIssuerRoute = (request: { + readonly method: string; + readonly path: string; + readonly searchParams: URLSearchParams; + readonly body: string; + /** Authorization の access token の利用者。無ければ null */ + readonly user: MockLumorphiaUser | null; +}) => Promise<{ readonly status: number; readonly body: unknown } | null>; + +export interface MockIssuerOptions { + readonly clientId: string; + /** 退会の知らせの宛先のサービス (auth-client の createAccountEventVerifier と揃える) */ + readonly service: LumorphiaServiceName; + /** https の証明書と鍵のファイル */ + readonly tls: { readonly cert: string; readonly key: string }; + /** back-channel logout と退会の知らせを送る先 (サービスのアプリ) */ + readonly appBaseUrl: string; + /** 0 なら空いているポート */ + readonly port?: number; + readonly controlPort?: number; + /** + * end-session から戻してよいオリジン。既定は appBaseUrl のオリジン。ブラウザが開くホスト名 + * (`https://scenote.lumorphia.test:3445` など) が appBaseUrl と違うときに渡す + */ + readonly postLogoutRedirectOrigins?: readonly string[]; + readonly backchannelLogoutPath?: string; + readonly accountEventsPath?: string; + readonly extraRoutes?: MockIssuerRoute; +} + +export interface MockIssuer { + /** `https://127.0.0.1:/api/auth` */ + readonly issuer: string; + /** `http://127.0.0.1:` */ + readonly controlUrl: string; + close(): Promise; +} + +type LifecycleState = "active" | "deleted" | "purged"; +type Lifecycle = { + service: LumorphiaServiceName; + revision: number; + state: LifecycleState; + scope: "account" | "service"; + occurredAt: string; + deletedAt: string | null; + recoverUntil: string | null; +}; + +const RECOVERY_MS = 30 * 86_400_000; + +class AppUnreachable extends Error {} + +/** + * 認可の口 (GET /oauth2/authorize) で承認する利用者を渡す Cookie。発行元のオリジンに置く (./playwright.ts)。 + * ブラウザのコンテキストごとに持つので、並列のテストでも混ざらない + */ +export const E2E_USER_COOKIE = "lumorphia_e2e_user"; + +export function encodeE2eUser(user: MockLumorphiaUser): string { + return Buffer.from(JSON.stringify(user)).toString("base64url"); +} + +const cookieValue = (req: IncomingMessage, name: string): string | null => { + for (const part of (req.headers.cookie ?? "").split(";")) { + const [key, ...rest] = part.trim().split("="); + if (key === name) return rest.join("="); + } + return null; +}; + +const json = (res: ServerResponse, status: number, body: unknown) => { + res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" }); + res.end(JSON.stringify(body)); +}; + +const readBody = (req: IncomingMessage) => + new Promise((resolve, reject) => { + let body = ""; + req.on("data", (chunk) => (body += chunk)); + req.on("end", () => resolve(body)); + req.on("error", reject); + }); + +const listen = (server: Server, port: number) => + new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(port, "127.0.0.1", () => resolve((server.address() as AddressInfo).port)); + }); + +const close = (server: Server) => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }); + +const bearer = (req: IncomingMessage) => (req.headers.authorization ?? "").replace(/^Bearer /, ""); + +/** ID トークンと UserInfo に共通の Lumorphia の claim */ +const lumorphiaClaims = (u: MockLumorphiaUser) => ({ + sub: u.sub, + "https://lumorphia.com/handle": u.handle, + "https://lumorphia.com/legacy_pending": [], + "https://lumorphia.com/identities": u.identities ?? [], +}); + +export async function startMockIssuer(options: MockIssuerOptions): Promise { + const backchannelLogoutPath = + options.backchannelLogoutPath ?? "/api/lumorphia/backchannel-logout"; + const accountEventsPath = options.accountEventsPath ?? "/api/lumorphia/account-events"; + const postLogoutOrigins = new Set( + (options.postLogoutRedirectOrigins ?? [options.appBaseUrl]).map((url) => new URL(url).origin), + ); + const keys = await generateKeyPair("EdDSA"); + const kid = "e2e-key"; + const jwk = { ...(await exportJWK(keys.publicKey)), kid, alg: "EdDSA" }; + // code と access token から、認可したときの利用者と nonce を引く + const codes = new Map(); + const tokens = new Map(); + // 退会の知らせ。送り直しのために eventId から引けるようにし、revision は利用者ごとに数える + const events = new Map(); + const revisions = new Map(); + let issuer = ""; + + const sign = (payload: Record, typ: string) => + new SignJWT(payload) + .setProtectedHeader({ alg: "EdDSA", kid, typ }) + .setIssuer(issuer) + .setAudience(options.clientId) + .setIssuedAt(); + + const postToApp = async (path: string, form: Record) => { + try { + const res = await fetch(new URL(path, options.appBaseUrl), { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams(form).toString(), + }); + return res.status; + } catch (error) { + // アプリに届かない (証明書を信頼していない、起動していない)。テストに理由を返す + const cause = error instanceof Error && error.cause instanceof Error ? error.cause : error; + throw new AppUnreachable(cause instanceof Error ? cause.message : String(cause)); + } + }; + + const sendAccountEvent = async (eventId: string) => { + const event = events.get(eventId)!; + const token = await sign({ lifecycle: event.lifecycle }, "lumorphia-account-event+jwt") + .setSubject(event.sub) + .setJti(eventId) + .setExpirationTime("2m") + .sign(keys.privateKey); + return postToApp(accountEventsPath, { event_token: token }); + }; + + const issuerServer = createHttpsServer( + { cert: readFileSync(options.tls.cert), key: readFileSync(options.tls.key) }, + async (req, res) => { + const url = new URL(req.url ?? "/", issuer); + if (url.pathname === "/api/auth/.well-known/openid-configuration") + return json(res, 200, { + issuer, + authorization_endpoint: `${issuer}/oauth2/authorize`, + token_endpoint: `${issuer}/oauth2/token`, + userinfo_endpoint: `${issuer}/oauth2/userinfo`, + end_session_endpoint: `${issuer}/oauth2/end-session`, + jwks_uri: `${issuer}/jwks`, + id_token_signing_alg_values_supported: ["EdDSA"], + }); + if (url.pathname === "/api/auth/jwks") return json(res, 200, { keys: [jwk] }); + // 認可の画面のふり。Cookie の利用者をそのまま承認し、code を付けて戻す (同意の画面は出さない。 + // 自社クライアントは accounts でも同意を省く) + if (url.pathname === "/api/auth/oauth2/authorize" && req.method === "GET") { + const encoded = cookieValue(req, E2E_USER_COOKIE); + const redirectUri = url.searchParams.get("redirect_uri"); + if ( + !encoded || + !redirectUri || + !URL.canParse(redirectUri) || + url.searchParams.get("client_id") !== options.clientId + ) + return json(res, 400, { error: "invalid_request" }); + const user = JSON.parse(Buffer.from(encoded, "base64url").toString()) as MockLumorphiaUser; + const code = randomUUID(); + codes.set(code, { user, nonce: url.searchParams.get("nonce") ?? "" }); + const back = new URL(redirectUri); + back.searchParams.set("code", code); + const state = url.searchParams.get("state"); + if (state) back.searchParams.set("state", state); + res.writeHead(302, { location: back.href, "cache-control": "no-store" }); + return res.end(); + } + // accounts のログアウト。確認の画面は出さず、登録した戻り先へ state を付けて戻す + if (url.pathname === "/api/auth/oauth2/end-session") { + const back = url.searchParams.get("post_logout_redirect_uri"); + if (!back || !URL.canParse(back) || !postLogoutOrigins.has(new URL(back).origin)) + return json(res, 400, { error: "invalid_request" }); + const location = new URL(back); + const state = url.searchParams.get("state"); + if (state) location.searchParams.set("state", state); + res.writeHead(302, { location: location.href, "cache-control": "no-store" }); + return res.end(); + } + if (url.pathname === "/api/auth/oauth2/token" && req.method === "POST") { + const form = new URLSearchParams(await readBody(req)); + const code = form.get("code") ?? ""; + const grant = codes.get(code); + if (!grant || form.get("client_id") !== options.clientId) + return json(res, 400, { error: "invalid_grant" }); + codes.delete(code); + const accessToken = randomUUID(); + tokens.set(accessToken, grant.user); + const idToken = await sign( + { ...lumorphiaClaims(grant.user), sid: grant.user.sid, nonce: grant.nonce }, + "JWT", + ) + .setExpirationTime("5m") + .sign(keys.privateKey); + return json(res, 200, { + access_token: accessToken, + token_type: "Bearer", + expires_in: 300, + id_token: idToken, + }); + } + if (url.pathname === "/api/auth/oauth2/userinfo") { + const u = tokens.get(bearer(req)); + if (!u) return json(res, 401, { error: "invalid_token" }); + return json(res, 200, { + ...lumorphiaClaims(u), + email: `${u.handle}@example.invalid`, + email_verified: true, + name: u.name, + ...(u.picture ? { picture: u.picture } : {}), + }); + } + const u = tokens.get(bearer(req)) ?? null; + if (url.pathname === "/api/characters" && req.method === "GET") { + if (!u) return json(res, 401, { error: "invalid_token" }); + return json(res, 200, { characters: u.characters ?? [] }); + } + const extra = await options.extraRoutes?.({ + method: req.method ?? "GET", + path: url.pathname, + searchParams: url.searchParams, + body: await readBody(req), + user: u, + }); + if (extra) return json(res, extra.status, extra.body); + return json(res, 404, { error: "not_found" }); + }, + ); + + const controlServer = createHttpServer((req, res) => { + control(req, res).catch((error: unknown) => { + if (error instanceof AppUnreachable) + return json(res, 502, { error: `app_unreachable: ${error.message}` }); + return json(res, 500, { error: error instanceof Error ? error.message : String(error) }); + }); + }); + + const control = async (req: IncomingMessage, res: ServerResponse) => { + const url = new URL(req.url ?? "/", "http://127.0.0.1"); + if (url.pathname === "/health") return json(res, 200, { ok: true }); + if (req.method !== "POST") return json(res, 404, { error: "not_found" }); + const body = JSON.parse((await readBody(req)) || "{}") as Record; + // 認可画面のふり: { nonce, user } で code を返す + if (url.pathname === "/_e2e/authorize") { + const code = randomUUID(); + codes.set(code, { user: body.user as MockLumorphiaUser, nonce: String(body.nonce) }); + return json(res, 200, { code }); + } + // accounts の back-channel logout: { sub, sid } で Logout Token を送り、アプリの応答の状態を返す + if (url.pathname === "/_e2e/backchannel-logout") { + const token = await sign( + { sid: body.sid, events: { "http://schemas.openid.net/event/backchannel-logout": {} } }, + "logout+jwt", + ) + .setSubject(String(body.sub)) + .setJti(randomUUID()) + .setExpirationTime("2m") + .sign(keys.privateKey); + return json(res, 200, { + status: await postToApp(backchannelLogoutPath, { logout_token: token }), + }); + } + // accounts の退会の知らせ: { sub, state, scope? } で新しい知らせを、{ sub, resend: eventId } で同じ知らせを送り直す + if (url.pathname === "/_e2e/account-event") { + if (typeof body.resend === "string") { + if (!events.has(body.resend)) return json(res, 404, { error: "unknown_event" }); + return json(res, 200, { + eventId: body.resend, + status: await sendAccountEvent(body.resend), + }); + } + const sub = String(body.sub); + const state = body.state as LifecycleState; + const now = new Date(); + const revision = (revisions.get(sub) ?? 0) + 1; + revisions.set(sub, revision); + const eventId = randomUUID(); + events.set(eventId, { + sub, + lifecycle: { + service: options.service, + revision, + state, + scope: body.scope === "service" ? "service" : "account", + occurredAt: now.toISOString(), + deletedAt: state === "deleted" ? now.toISOString() : null, + recoverUntil: + state === "deleted" ? new Date(now.getTime() + RECOVERY_MS).toISOString() : null, + }, + }); + return json(res, 200, { eventId, status: await sendAccountEvent(eventId) }); + } + return json(res, 404, { error: "not_found" }); + }; + + const port = await listen(issuerServer, options.port ?? 0); + issuer = `https://127.0.0.1:${port}/api/auth`; + const controlPort = await listen(controlServer, options.controlPort ?? 0); + return { + issuer, + controlUrl: `http://127.0.0.1:${controlPort}`, + close: async () => { + await Promise.all([close(issuerServer), close(controlServer)]); + }, + }; +} diff --git a/packages/e2e/src/playwright.ts b/packages/e2e/src/playwright.ts new file mode 100644 index 0000000..a4c2dc4 --- /dev/null +++ b/packages/e2e/src/playwright.ts @@ -0,0 +1,91 @@ +import { expect, test as base, type Page } from "@playwright/test"; +import { E2E_USER_COOKIE, encodeE2eUser, type MockLumorphiaUser } from "./mock-issuer.ts"; + +export { lumorphiaUser } from "./users.ts"; +export type { MockLumorphiaUser } from "./mock-issuer.ts"; + +/** 発行元のふり (./mock-issuer.ts) の場所。サービスの playwright.config.ts と揃える */ +export interface MockIssuerLocation { + /** `https://127.0.0.1:/api/auth` */ + readonly issuer: string; + /** `http://127.0.0.1:` */ + readonly controlUrl: string; +} + +/** + * 全 E2E 共通の test。CSP の違反を見張り、テストの終わりに 0 件であることを確かめる (lumorphia/prismtone と同じ)。 + * 違反はブラウザが console にエラーとして出すので、コンテキストの console を集める。 + * browser.newContext() で作った別のコンテキストは見ない + */ +export const test = base.extend<{ cspViolations: string[] }>({ + cspViolations: [ + async ({ context }, use) => { + const violations: string[] = []; + context.on("console", (msg) => { + const text = msg.text(); + if (/Content Security Policy|Refused to/i.test(text)) violations.push(text); + }); + await use(violations); + expect(violations, "CSP の違反が console に出た").toEqual([]); + }, + { auto: true }, + ], +}); + +export { expect }; + +/** + * Lumorphia の認可画面のふり。発行元のふりの認可の口 (./mock-issuer.ts) が承認する利用者を、発行元のオリジンの + * Cookie に置く。ブラウザは本物と同じく認可へ移り、code を持って callback へ戻ってくる。もう一度呼ぶと、 + * 次のログインからその利用者になる。 + * `page.route` と `route.fetch` を使わないのは、route.fetch が Node から送るので Chromium の + * `--host-resolver-rules` (`*.lumorphia.test`) が効かず、302 の先も page.route に渡らないため + */ +export async function approveLumorphia( + page: Page, + user: MockLumorphiaUser, + location: MockIssuerLocation, +): Promise { + await page.context().addCookies([ + { + name: E2E_USER_COOKIE, + value: encodeE2eUser(user), + url: new URL(location.issuer).origin, + secure: true, + sameSite: "None", + }, + ]); +} + +/** accounts の back-channel logout のふり。アプリが返した HTTP の状態を返す */ +export async function sendBackchannelLogout( + page: Page, + user: MockLumorphiaUser, + location: MockIssuerLocation, +): Promise { + const res = await page.request.post(`${location.controlUrl}/_e2e/backchannel-logout`, { + data: { sub: user.sub, sid: user.sid }, + }); + return ((await res.json()) as { status: number }).status; +} + +/** + * accounts の退会の知らせのふり。`resend` に前の eventId を渡すと同じ知らせを送り直す。 + * eventId とアプリが返した HTTP の状態を返す + */ +export async function sendAccountEvent( + page: Page, + event: + | { + readonly sub: string; + readonly state: "active" | "deleted" | "purged"; + readonly scope?: "account" | "service"; + } + | { readonly sub: string; readonly resend: string }, + location: MockIssuerLocation, +): Promise<{ eventId: string; status: number }> { + const res = await page.request.post(`${location.controlUrl}/_e2e/account-event`, { + data: event, + }); + return (await res.json()) as { eventId: string; status: number }; +} diff --git a/packages/e2e/src/test-setup.ts b/packages/e2e/src/test-setup.ts new file mode 100644 index 0000000..216f40f --- /dev/null +++ b/packages/e2e/src/test-setup.ts @@ -0,0 +1,17 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { ensureE2eTls } from "./tls.ts"; + +/** + * テストの Worker を起こす前に、発行元のふり (https) の CA を作って信頼させる。NODE_EXTRA_CA_CERTS は + * プロセスの起動時にしか読まれないので、ここで設定して Worker (子プロセス) に引き継ぐ + */ +export default function setup() { + const dir = mkdtempSync(join(tmpdir(), "lumorphia-e2e-test-")); + const tls = ensureE2eTls(dir); + process.env.NODE_EXTRA_CA_CERTS = tls.ca; + process.env.LUMORPHIA_E2E_TEST_CERT = tls.cert; + process.env.LUMORPHIA_E2E_TEST_KEY = tls.key; + return () => rmSync(dir, { recursive: true, force: true }); +} diff --git a/packages/e2e/src/tls.test.ts b/packages/e2e/src/tls.test.ts new file mode 100644 index 0000000..edbf060 --- /dev/null +++ b/packages/e2e/src/tls.test.ts @@ -0,0 +1,60 @@ +import { X509Certificate } from "node:crypto"; +import { mkdtemp, readFile, rm, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { certificateSpki, ensureE2eTls } from "./tls.ts"; + +let dir: string; +let paths: { ca: string; cert: string; key: string }; + +beforeAll(async () => { + dir = await mkdtemp(join(tmpdir(), "lumorphia-e2e-tls-")); + paths = ensureE2eTls(dir); +}); + +afterAll(async () => { + await rm(dir, { recursive: true, force: true }); +}); + +describe("ensureE2eTls", () => { + it("issues a server certificate signed by its own CA", async () => { + const ca = new X509Certificate(await readFile(paths.ca)); + const cert = new X509Certificate(await readFile(paths.cert)); + expect(cert.verify(ca.publicKey)).toBe(true); + }); + + it("covers 127.0.0.1 and localhost", async () => { + const cert = new X509Certificate(await readFile(paths.cert)); + expect(cert.subjectAltName).toContain("IP Address:127.0.0.1"); + expect(cert.subjectAltName).toContain("DNS:localhost"); + }); + + it("keeps the certificate under the 398 days browsers accept", async () => { + const cert = new X509Certificate(await readFile(paths.cert)); + const days = (Date.parse(cert.validTo) - Date.parse(cert.validFrom)) / 86_400_000; + expect(days).toBeLessThanOrEqual(398); + }); + + it("does not issue again when the files are already there", async () => { + const before = (await stat(paths.cert)).mtimeMs; + expect(ensureE2eTls(dir)).toEqual(paths); + expect((await stat(paths.cert)).mtimeMs).toBe(before); + }); + + it("leaves only the CA, the certificate and its key behind", async () => { + const { readdir } = await import("node:fs/promises"); + expect((await readdir(dir)).sort()).toEqual(["ca-key.pem", "ca.pem", "cert.pem", "key.pem"]); + }); +}); + +describe("certificateSpki", () => { + it("hashes the public key the way Chromium's spki list expects", async () => { + const spki = certificateSpki(paths.cert); + expect(spki).toMatch(/^[A-Za-z0-9+/]{43}=$/); + }); + + it("gives the same hash for the same certificate", () => { + expect(certificateSpki(paths.cert)).toBe(certificateSpki(paths.cert)); + }); +}); diff --git a/packages/e2e/src/tls.ts b/packages/e2e/src/tls.ts new file mode 100644 index 0000000..e8693c8 --- /dev/null +++ b/packages/e2e/src/tls.ts @@ -0,0 +1,101 @@ +import { execFileSync } from "node:child_process"; +import { createHash, X509Certificate } from "node:crypto"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +export interface E2eTlsPaths { + readonly ca: string; + readonly cert: string; + readonly key: string; +} + +/** + * E2E 専用の CA と、127.0.0.1・localhost のサーバー証明書を `dir` に作る (lumorphia/prismtone の e2e/tls.ts から)。 + * auth-client は発行元に https を求めるので、発行元のふり (mock-issuer) に使う。サービスのアプリは + * NODE_EXTRA_CA_CERTS でこの CA を信頼する。開発の CA (`*.lumorphia.test`) とは分ける。 + * 3 つのファイルが揃っていれば作り直さない。openssl が要る + */ +export function ensureE2eTls(dir: string): E2eTlsPaths { + const paths = { ca: join(dir, "ca.pem"), cert: join(dir, "cert.pem"), key: join(dir, "key.pem") }; + if (existsSync(paths.ca) && existsSync(paths.cert) && existsSync(paths.key)) return paths; + mkdirSync(dir, { recursive: true }); + const caKey = join(dir, "ca-key.pem"); + const csr = join(dir, "cert.csr"); + const ext = join(dir, "cert.ext"); + const openssl = (args: readonly string[]) => execFileSync("openssl", args, { stdio: "ignore" }); + openssl([ + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-keyout", + caKey, + "-out", + paths.ca, + "-days", + "3650", + "-subj", + "/CN=Lumorphia E2E CA", + "-addext", + "basicConstraints=critical,CA:TRUE", + "-addext", + "keyUsage=critical,keyCertSign,cRLSign", + ]); + openssl([ + "req", + "-newkey", + "rsa:2048", + "-nodes", + "-keyout", + paths.key, + "-out", + csr, + "-subj", + "/CN=127.0.0.1", + ]); + writeFileSync( + ext, + [ + "basicConstraints=CA:FALSE", + "keyUsage=critical,digitalSignature,keyEncipherment", + "extendedKeyUsage=serverAuth", + "subjectAltName=IP:127.0.0.1,DNS:localhost", + ].join("\n"), + ); + // ブラウザは 398 日より長いサーバー証明書を拒む + openssl([ + "x509", + "-req", + "-in", + csr, + "-CA", + paths.ca, + "-CAkey", + caKey, + "-CAcreateserial", + "-out", + paths.cert, + "-days", + "397", + "-extfile", + ext, + ]); + rmSync(csr); + rmSync(ext); + rmSync(join(dir, "ca.srl"), { force: true }); + return paths; +} + +/** + * 証明書の公開鍵 (SPKI) の SHA-256 (base64)。Chromium の `--ignore-certificate-errors-spki-list` に渡すと、 + * その鍵の証明書だけを信頼する。ignoreHTTPSErrors は接続のたびに証明書のエラーを通るので、読み込みが + * ときどき net::ERR_TOO_MANY_RETRIES で落ちる (lumorphia/accounts で起きた) + */ +export function certificateSpki(certPath: string): string { + const spki = new X509Certificate(readFileSync(certPath)).publicKey.export({ + type: "spki", + format: "der", + }); + return createHash("sha256").update(spki).digest("base64"); +} diff --git a/packages/e2e/src/users.test.ts b/packages/e2e/src/users.test.ts new file mode 100644 index 0000000..71ec99b --- /dev/null +++ b/packages/e2e/src/users.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from "vitest"; +import { lumorphiaUser } from "./users.ts"; + +describe("lumorphiaUser", () => { + it("gives each test its own user", () => { + const [a, b] = [lumorphiaUser(), lumorphiaUser()]; + expect(a.sub).not.toBe(b.sub); + expect(a.sid).not.toBe(b.sid); + expect(a.handle).not.toBe(b.handle); + }); + + it("makes a handle accounts would accept", () => { + expect(lumorphiaUser().handle).toMatch(/^[a-z0-9_]{3,20}$/); + }); + + it("names the user so it stands out from real ones", () => { + expect(lumorphiaUser().name).toMatch(/^テスト_/); + }); + + it("lets the test choose any field", () => { + expect(lumorphiaUser({ name: "テスト_別名" }).name).toBe("テスト_別名"); + }); +}); diff --git a/packages/e2e/src/users.ts b/packages/e2e/src/users.ts new file mode 100644 index 0000000..f9042d7 --- /dev/null +++ b/packages/e2e/src/users.ts @@ -0,0 +1,16 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import type { MockLumorphiaUser } from "./mock-issuer.ts"; + +/** + * テストごとに別の Lumorphia の利用者を作る。handle は accounts の決まり (英小文字・数字・_、3〜20 文字) で、 + * サービスの中でも一意になる。名前は「テスト_」で始め、手元の画面で本物と見分ける + */ +export function lumorphiaUser(overrides: Partial = {}): MockLumorphiaUser { + return { + sub: randomUUID(), + sid: `e2e-sid-${randomUUID()}`, + handle: `lm_${randomBytes(5).toString("hex")}`, + name: "テスト_ルモルフィア", + ...overrides, + }; +} diff --git a/packages/e2e/tsconfig.build.json b/packages/e2e/tsconfig.build.json new file mode 100644 index 0000000..83c42b0 --- /dev/null +++ b/packages/e2e/tsconfig.build.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "rootDir": "src", + "outDir": "dist" + }, + "exclude": ["src/**/*.test.ts", "src/test-setup.ts"] +} diff --git a/packages/e2e/tsconfig.json b/packages/e2e/tsconfig.json new file mode 100644 index 0000000..bf5a36d --- /dev/null +++ b/packages/e2e/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src/**/*"] +} diff --git a/packages/e2e/vitest.config.ts b/packages/e2e/vitest.config.ts new file mode 100644 index 0000000..2d0027c --- /dev/null +++ b/packages/e2e/vitest.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from "vitest/config"; +import { readPlatformSource } from "../../vitest.source.ts"; +export default defineConfig({ + ...readPlatformSource, + // 発行元のふりは https。テストの CA を作り、Worker を起こす前に NODE_EXTRA_CA_CERTS で信頼させる + test: { name: "e2e", include: ["src/**/*.test.ts"], globalSetup: ["src/test-setup.ts"] }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2521d79..27f65ab 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -204,6 +204,22 @@ importers: specifier: 1.7.7 version: 1.7.7(vitest@5.0.3) + packages/e2e: + dependencies: + jose: + specifier: 6.2.12 + version: 6.2.12 + devDependencies: + '@lumorphia/auth-client': + specifier: workspace:* + version: link:../auth-client + '@playwright/test': + specifier: ^1.63.0 + version: 1.64.0 + better-auth: + specifier: 1.7.7 + version: 1.7.7(vitest@5.0.3) + packages/legal: dependencies: marked: @@ -670,6 +686,11 @@ packages: '@pinojs/redact@0.4.0': resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==} + '@playwright/test@1.64.0': + resolution: {integrity: sha512-oTN9FNYuN6bqQMwiho6jJKLCG2/QOYCixGXuCjRmzOq23eODeukuY2XiAVoVpAECbuezMt1MHQjAiQxK8F+Y+g==} + engines: {node: '>=20'} + hasBin: true + '@rolldown/binding-android-arm-eabi@1.2.12': resolution: {integrity: sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==} engines: {node: ^20.19.0 || >=22.12.0} @@ -1354,6 +1375,16 @@ packages: resolution: {integrity: sha512-bk1ZMTwG/Vymx+zPoa28MhNzucFvXJWp3csrSuxuHPSMeUettaCoQ5Jvg07mtC4JGNpcfTwz41oVCnNgBK9+vA==} hasBin: true + playwright-core@1.64.0: + resolution: {integrity: sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==} + engines: {node: '>=20'} + hasBin: true + + playwright@1.64.0: + resolution: {integrity: sha512-kVzTnYFYEyQ9RGzBjNCd2+yEqWmVbxl3AHPynv3qQ6JTjv4a+kwRcnqQwIpuP3NnrnIrE/Q6wWAIAvMfIE2/Yg==} + engines: {node: '>=20'} + hasBin: true + postcss@8.5.29: resolution: {integrity: sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==} engines: {node: ^10 || ^12 || >=14} @@ -2042,6 +2073,10 @@ snapshots: '@pinojs/redact@0.4.0': {} + '@playwright/test@1.64.0': + dependencies: + playwright: 1.64.0 + '@rolldown/binding-android-arm-eabi@1.2.12': optional: true @@ -2638,6 +2673,12 @@ snapshots: sonic-boom: 4.2.1 thread-stream: 4.2.0 + playwright-core@1.64.0: {} + + playwright@1.64.0: + dependencies: + playwright-core: 1.64.0 + postcss@8.5.29: dependencies: nanoid: 3.3.19 diff --git a/release-please-config.json b/release-please-config.json index 119f73f..bc7e6db 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -66,6 +66,10 @@ "packages/legal": { "component": "legal", "package-name": "@lumorphia/legal" + }, + "packages/e2e": { + "component": "e2e", + "package-name": "@lumorphia/e2e" } } } diff --git a/tooling/eslint-boundaries.test.ts b/tooling/eslint-boundaries.test.ts index abeb36a..b8d3a74 100644 --- a/tooling/eslint-boundaries.test.ts +++ b/tooling/eslint-boundaries.test.ts @@ -88,4 +88,22 @@ describe("eslint boundaries", () => { // 画面でも本文を表示するので、ブラウザで動く形に保つ expect(await restricted(file, 'import "node:fs";')).toBe(true); }); + + it("keeps e2e free of the services and the private umbra", async () => { + const file = "packages/e2e/src/x.ts"; + expect(await restricted(file, 'import "@scenote/core";')).toBe(true); + expect(await restricted(file, 'import "@lumorphia/moderation";')).toBe(true); + }); + + it("keeps the mock issuer apart from the auth-client it stands in front of", async () => { + // 同じ実装からトークンを作ると、食い違いをテストで見つけられない。auth-client はテストからだけ使う + expect(await restricted("packages/e2e/src/x.ts", 'import "@lumorphia/auth-client";')).toBe( + true, + ); + }); + + it("lets the e2e tests check the mock issuer with auth-client", async () => { + const code = 'import "@lumorphia/auth-client";'; + expect(await restricted("packages/e2e/src/x.test.ts", code)).toBe(false); + }); }); diff --git a/tooling/packages.test.ts b/tooling/packages.test.ts index d41947d..6d10be2 100644 --- a/tooling/packages.test.ts +++ b/tooling/packages.test.ts @@ -8,7 +8,7 @@ const read = (path: string) => version: string; }; -const PACKAGES = ["media", "storage", "ops", "auth-client", "legal"] as const; +const PACKAGES = ["media", "storage", "ops", "auth-client", "legal", "e2e"] as const; const manifest = read(".release-please-manifest.json") as unknown as Record; const config = read("release-please-config.json") as unknown as { packages: Record;