Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
test(forge): cover the creation endpoints, enhance prompt cleanup and the GitHub token connect
nirholasbc6904c6137c
diff --git a/tests/api/forge-creation-endpoints.test.js b/tests/api/forge-creation-endpoints.test.jsnew file mode 100644index 000000000..8deeffbcf--- /dev/null+++ b/tests/api/forge-creation-endpoints.test.js@@ -0,0 +1,326 @@+// Tests for the four durable-creation endpoints that had no direct coverage:+// api/forge-creation.js, api/forge-categorize.js, api/forge-feedback.js and+// api/forge-comments.js.+//+// All four are the ownership-scoped half of the /forge flywheel, and each one+// answers on a boundary that is easy to get wrong and impossible to notice from+// the UI: a share-link read that must stay public, a write that must be scoped+// to the browser that forged the row, and a comment thread whose 405 has to tell+// a client which methods it may use. The forge store is stubbed at the module+// boundary so these assert the handlers' own contracts, not Postgres.++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { Readable } from 'node:stream';++const storeEnabled = vi.fn(() => true);+const getPublicCreation = vi.fn(async () => ({ id: 'c1', model_category: 'item', glb_url: 'https://cdn.example/a.glb' }));+const listRelated = vi.fn(async () => [{ id: 'c2' }]);+const recordCreationView = vi.fn(async () => true);+const deleteCreation = vi.fn(async () => 'deleted');+const setForgeCategory = vi.fn(async () => true);+const recordFeedback = vi.fn(async () => true);+const hashClient = vi.fn((raw) => `hashed:${raw ?? 'anon'}`);++vi.mock('../../api/_lib/forge-store.js', () => ({+ MODEL_CATEGORIES: ['avatar', 'accessory', 'item', 'scene', 'creature', 'vehicle', 'other'],+ forgeStoreEnabled: (...a) => storeEnabled(...a),+ getPublicCreation: (...a) => getPublicCreation(...a),+ listRelated: (...a) => listRelated(...a),+ recordCreationView: (...a) => recordCreationView(...a),+ deleteCreation: (...a) => deleteCreation(...a),+ setForgeCategory: (...a) => setForgeCategory(...a),+ recordFeedback: (...a) => recordFeedback(...a),+ hashClient: (...a) => hashClient(...a),+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ mcp3dStatus: vi.fn(async () => ({ success: true })),+ publicIp: vi.fn(async () => ({ success: true })),+ authIp: vi.fn(async () => ({ success: true })),+ },+ clientIp: vi.fn(() => '203.0.113.7'),+}));++// forge-comments talks to Postgres and the session layer directly. Stub both so+// the dispatch + auth contracts are the only thing under test.+vi.mock('../../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => null),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));+vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));+vi.mock('../../api/_lib/feed.js', () => ({ publishUserEvent: vi.fn() }));+vi.mock('../../api/_lib/display-name-safety.js', () => ({ containsHateSlur: vi.fn(() => false) }));++const creationHandler = (await import('../../api/forge-creation.js')).default;+const categorizeHandler = (await import('../../api/forge-categorize.js')).default;+const feedbackHandler = (await import('../../api/forge-feedback.js')).default;+const commentsHandler = (await import('../../api/forge-comments.js')).default;++const UUID = '19a208e7-ad6b-48b0-b7e0-1a752a54f222';++function mkReq({ method = 'GET', url = '/', headers = {}, body = null } = {}) {+ const payload = body == null ? '' : typeof body === 'string' ? body : JSON.stringify(body);+ const stream = Readable.from(payload ? [Buffer.from(payload, 'utf8')] : []);+ stream.method = method;+ stream.url = url;+ stream.headers = { 'content-type': 'application/json', ...headers };+ return stream;+}++function mkRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ setHeader(k, v) {+ this.headers[String(k).toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[String(k).toLowerCase()];+ },+ end(chunk) {+ if (chunk !== undefined) this.body += String(chunk);+ this.writableEnded = true;+ },+ };+}++const parsed = (res) => JSON.parse(res.body || '{}');++beforeEach(() => {+ vi.clearAllMocks();+ storeEnabled.mockReturnValue(true);+ getPublicCreation.mockResolvedValue({ id: 'c1', model_category: 'item', glb_url: 'https://cdn.example/a.glb' });+ deleteCreation.mockResolvedValue('deleted');+ hashClient.mockImplementation((raw) => `hashed:${raw ?? 'anon'}`);+});++describe('GET /api/forge-creation', () => {+ it('serves a stored creation to a share-link visitor who sends no client header', async () => {+ const res = mkRes();+ await creationHandler(mkReq({ url: `/api/forge-creation?id=${UUID}` }), res);+ expect(res.statusCode).toBe(200);+ expect(parsed(res).creation.id).toBe('c1');+ // A share-link recipient forged nothing, so the read must not be voter-scoped.+ expect(getPublicCreation).toHaveBeenCalledWith({ id: UUID, voterKey: null });+ });++ it('resolves the caller voted-state when a forge id is sent', async () => {+ const res = mkRes();+ await creationHandler(mkReq({ url: `/api/forge-creation?id=${UUID}`, headers: { 'x-forge-client': 'cid-1' } }), res);+ expect(getPublicCreation).toHaveBeenCalledWith({ id: UUID, voterKey: 'hashed:cid-1' });+ });++ it('400s on a non-uuid id without touching the store', async () => {+ const res = mkRes();+ await creationHandler(mkReq({ url: '/api/forge-creation?id=not-a-uuid' }), res);+ expect(res.statusCode).toBe(400);+ expect(parsed(res).error).toBe('invalid id');+ expect(getPublicCreation).not.toHaveBeenCalled();+ });++ it('404s an unknown id', async () => {+ getPublicCreation.mockResolvedValueOnce(null);+ const res = mkRes();+ await creationHandler(mkReq({ url: `/api/forge-creation?id=${UUID}` }), res);+ expect(res.statusCode).toBe(404);+ expect(parsed(res).creation).toBeNull();+ });++ it('attaches related models and counts a view only when asked', async () => {+ const res = mkRes();+ await creationHandler(mkReq({ url: `/api/forge-creation?id=${UUID}&related=3&view=1` }), res);+ expect(parsed(res).related).toEqual([{ id: 'c2' }]);+ expect(listRelated).toHaveBeenCalledWith({ id: UUID, category: 'item', limit: 3 });+ expect(recordCreationView).toHaveBeenCalledWith({ id: UUID });++ const plain = mkRes();+ await creationHandler(mkReq({ url: `/api/forge-creation?id=${UUID}` }), plain);+ expect(parsed(plain).related).toBeUndefined();+ expect(recordCreationView).toHaveBeenCalledTimes(1);+ });++ it('degrades to enabled:false when the deployment has no durable store', async () => {+ storeEnabled.mockReturnValue(false);+ const res = mkRes();+ await creationHandler(mkReq({ url: `/api/forge-creation?id=${UUID}` }), res);+ expect(res.statusCode).toBe(200);+ expect(parsed(res)).toEqual({ enabled: false, creation: null });+ });+});++describe('DELETE /api/forge-creation', () => {+ it('refuses a delete with no client header rather than guessing an owner', async () => {+ const res = mkRes();+ await creationHandler(mkReq({ method: 'DELETE', url: `/api/forge-creation?id=${UUID}` }), res);+ expect(res.statusCode).toBe(401);+ expect(parsed(res).error).toBe('missing_client');+ expect(deleteCreation).not.toHaveBeenCalled();+ });++ it('deletes a row owned by the calling browser', async () => {+ const res = mkRes();+ await creationHandler(+ mkReq({ method: 'DELETE', url: `/api/forge-creation?id=${UUID}`, headers: { 'x-forge-client': 'cid-1' } }),+ res,+ );+ expect(res.statusCode).toBe(200);+ expect(parsed(res)).toEqual({ deleted: true });+ expect(deleteCreation).toHaveBeenCalledWith({ id: UUID, clientKey: 'hashed:cid-1' });+ });++ it("answers 404 for another client's row so ids cannot be probed for existence", async () => {+ deleteCreation.mockResolvedValueOnce('not_found');+ const res = mkRes();+ await creationHandler(+ mkReq({ method: 'DELETE', url: `/api/forge-creation?id=${UUID}`, headers: { 'x-forge-client': 'cid-2' } }),+ res,+ );+ expect(res.statusCode).toBe(404);+ expect(parsed(res)).toEqual({ deleted: false, error: 'not_found' });+ });++ it('reports a failed delete as 503 and states nothing was removed', async () => {+ deleteCreation.mockResolvedValueOnce('error');+ const res = mkRes();+ await creationHandler(+ mkReq({ method: 'DELETE', url: `/api/forge-creation?id=${UUID}`, headers: { 'x-forge-client': 'cid-1' } }),+ res,+ );+ expect(res.statusCode).toBe(503);+ expect(parsed(res).error).toBe('delete_failed');+ });+});++describe('POST /api/forge-categorize', () => {+ it('stores a valid category against the calling browser', async () => {+ const res = mkRes();+ await categorizeHandler(+ mkReq({+ method: 'POST',+ url: '/api/forge-categorize',+ headers: { 'x-forge-client': 'cid-1' },+ body: { creation_id: UUID, model_category: 'vehicle' },+ }),+ res,+ );+ expect(res.statusCode).toBe(200);+ expect(parsed(res)).toEqual({ ok: true, stored: true });+ expect(setForgeCategory).toHaveBeenCalledWith({ id: UUID, clientKey: 'hashed:cid-1', modelCategory: 'vehicle' });+ });++ it('rejects a category outside the allowed set and names the valid ones', async () => {+ const res = mkRes();+ await categorizeHandler(+ mkReq({ method: 'POST', url: '/api/forge-categorize', body: { creation_id: UUID, model_category: 'banana' } }),+ res,+ );+ expect(res.statusCode).toBe(400);+ expect(parsed(res).error).toBe('invalid_category');+ expect(parsed(res).message).toContain('avatar');+ expect(setForgeCategory).not.toHaveBeenCalled();+ });++ it('rejects a non-uuid creation_id', async () => {+ const res = mkRes();+ await categorizeHandler(+ mkReq({ method: 'POST', url: '/api/forge-categorize', body: { creation_id: 'x', model_category: 'item' } }),+ res,+ );+ expect(res.statusCode).toBe(400);+ expect(parsed(res).error).toBe('invalid_creation');+ });++ it('answers stored:false instead of failing when no store is configured', async () => {+ storeEnabled.mockReturnValue(false);+ const res = mkRes();+ await categorizeHandler(+ mkReq({ method: 'POST', url: '/api/forge-categorize', body: { creation_id: UUID, model_category: 'item' } }),+ res,+ );+ expect(res.statusCode).toBe(200);+ expect(parsed(res)).toEqual({ ok: false, stored: false, reason: 'persistence_unconfigured' });+ });+});++describe('POST /api/forge-feedback', () => {+ it('records the human verdict against the calling browser', async () => {+ const res = mkRes();+ await feedbackHandler(+ mkReq({+ method: 'POST',+ url: '/api/forge-feedback',+ headers: { 'x-forge-client': 'cid-1' },+ body: { creation_id: UUID, outcome: 'kept', downloaded: true, rating: 5, note: 'clean mesh' },+ }),+ res,+ );+ expect(res.statusCode).toBe(200);+ expect(parsed(res)).toEqual({ ok: true, stored: true });+ expect(recordFeedback).toHaveBeenCalledWith({+ id: UUID,+ clientKey: 'hashed:cid-1',+ outcome: 'kept',+ downloaded: true,+ rating: 5,+ note: 'clean mesh',+ });+ });++ it('drops a non-integer rating rather than writing garbage into the label set', async () => {+ const res = mkRes();+ await feedbackHandler(+ mkReq({ method: 'POST', url: '/api/forge-feedback', body: { creation_id: UUID, rating: 'five' } }),+ res,+ );+ expect(res.statusCode).toBe(200);+ expect(recordFeedback.mock.calls[0][0].rating).toBeUndefined();+ });++ it('rejects a non-uuid creation_id', async () => {+ const res = mkRes();+ await feedbackHandler(mkReq({ method: 'POST', url: '/api/forge-feedback', body: { creation_id: 'nope' } }), res);+ expect(res.statusCode).toBe(400);+ expect(parsed(res).error).toBe('invalid_creation');+ expect(recordFeedback).not.toHaveBeenCalled();+ });+});++describe('/api/forge-comments dispatch', () => {+ it('advertises the methods it accepts on a 405 so a client can correct itself', async () => {+ const res = mkRes();+ await commentsHandler(mkReq({ method: 'PATCH', url: '/api/forge-comments' }), res);+ expect(res.statusCode).toBe(405);+ expect(String(res.getHeader('allow'))).toContain('DELETE');+ expect(String(res.getHeader('allow'))).toContain('HEAD');+ });++ it('requires a session before it will accept a comment', async () => {+ const res = mkRes();+ await commentsHandler(+ mkReq({ method: 'POST', url: '/api/forge-comments', body: { creation_id: UUID, body: 'hi' } }),+ res,+ );+ expect(res.statusCode).toBe(401);+ expect(parsed(res).error).toBe('unauthorized');+ });++ it('requires a session before it will delete a comment', async () => {+ const res = mkRes();+ await commentsHandler(+ mkReq({ method: 'DELETE', url: '/api/forge-comments', body: { comment_id: UUID } }),+ res,+ );+ expect(res.statusCode).toBe(401);+ });++ it('rejects a list read with no creation_id', async () => {+ const res = mkRes();+ await commentsHandler(mkReq({ method: 'GET', url: '/api/forge-comments' }), res);+ expect(res.statusCode).toBe(400);+ expect(parsed(res).error_description).toBe('creation_id required');+ });+});diff --git a/tests/api/forge-enhance-clean.test.js b/tests/api/forge-enhance-clean.test.jsnew file mode 100644index 000000000..a10ec95e4--- /dev/null+++ b/tests/api/forge-enhance-clean.test.js@@ -0,0 +1,119 @@+// Tests for POST /api/forge-enhance, the art-director rewrite that turns a+// terse idea into the prompt the reference-image + reconstruction pipeline can+// actually render.+//+// The load-bearing detail here is the cleanup pass. The system prompt forbids+// quotation marks, but every LLM in the chain wraps its answer in them anyway,+// and whatever survives cleanup is fed verbatim to the diffusion model that+// paints the reference image, where a stray quote is just more text to draw.+// A regression had left only the CURLY-quote branch working, so the far more+// common straight-quoted reply ("a knight in armor") kept its quotes all the way+// into the image prompt. These pin both quote styles, plus the label strip and+// the fall-back-to-the-user's-own-words behavior.++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { Readable } from 'node:stream';++const llmComplete = vi.fn(async () => ({ text: 'a plain reply', provider: 'test', model: 'test-model' }));++vi.mock('../../api/_lib/llm.js', () => ({+ llmComplete: (...a) => llmComplete(...a),+ LlmUnavailableError: class LlmUnavailableError extends Error {},+}));++// The Vertex director lane is optional and fail-soft; keep it out of the way so+// these assert the cleanup pass rather than a GCP token exchange.+vi.mock('../../api/_lib/gcp-auth.js', () => ({ getGcpAccessToken: vi.fn(async () => 'token') }));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { forgeEnhance: vi.fn(async () => ({ success: true })) },+ clientIp: vi.fn(() => '203.0.113.7'),+}));++const handler = (await import('../../api/forge-enhance.js')).default;++function mkReq(body) {+ const payload = JSON.stringify(body);+ const stream = Readable.from([Buffer.from(payload, 'utf8')]);+ stream.method = 'POST';+ stream.url = '/api/forge-enhance';+ stream.headers = { 'content-type': 'application/json' };+ return stream;+}++function mkRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ setHeader(k, v) {+ this.headers[String(k).toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[String(k).toLowerCase()];+ },+ end(chunk) {+ if (chunk !== undefined) this.body += String(chunk);+ this.writableEnded = true;+ },+ };+}++const parsed = (res) => JSON.parse(res.body || '{}');++async function enhance(replyText, prompt = 'a knight') {+ llmComplete.mockResolvedValueOnce({ text: replyText, provider: 'test', model: 'test-model' });+ const res = mkRes();+ await handler(mkReq({ prompt }), res);+ return parsed(res);+}++beforeEach(() => {+ vi.clearAllMocks();+ // GOOGLE_CLOUD_PROJECT would divert the rewrite to the Vertex lane; the free+ // chain is the one under test here.+ delete process.env.GOOGLE_CLOUD_PROJECT;+});++describe('POST /api/forge-enhance, prompt cleanup', () => {+ it('strips straight double quotes the model wrapped around its answer', async () => {+ const body = await enhance('"a knight in weathered steel plate armor"');+ expect(body.prompt).toBe('a knight in weathered steel plate armor');+ });++ it('strips curly quotes too', async () => {+ const body = await enhance('“a knight in weathered steel plate armor”');+ expect(body.prompt).toBe('a knight in weathered steel plate armor');+ });++ it('keeps a quote that is part of the prompt rather than wrapping it', async () => {+ const body = await enhance('a sign reading "open" in painted enamel');+ expect(body.prompt).toBe('a sign reading "open" in painted enamel');+ });++ it('strips a Prompt: label, collapses whitespace, and drops the trailing period', async () => {+ const body = await enhance('Enhanced prompt: a matte\n ceramic teapot.');+ expect(body.prompt).toBe('a matte ceramic teapot');+ });++ it("falls back to the user's own words when the rewrite comes back degenerate", async () => {+ const body = await enhance('.', 'a small brass compass');+ expect(body.prompt).toBe('a small brass compass');+ });++ it('returns the subject class and its negative prompt alongside the rewrite', async () => {+ const body = await enhance('"a golden retriever"', 'a golden retriever');+ expect(body.subject).toBe('animal');+ expect(body.negative_prompt).toContain('extra legs');+ // Realistic by default, so the photoreal failure modes are layered on too.+ expect(body.negative_prompt).toContain('plastic doll skin');+ });++ it('rejects a prompt too short to rewrite before calling any provider', async () => {+ const res = mkRes();+ await handler(mkReq({ prompt: 'ab' }), res);+ expect(res.statusCode).toBe(400);+ expect(parsed(res).error).toBe('prompt_too_short');+ expect(llmComplete).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/forge-nim.test.js b/tests/api/forge-nim.test.jsindex 56e17ea8a..c20834418 100644--- a/tests/api/forge-nim.test.js+++ b/tests/api/forge-nim.test.js@@ -133,6 +133,21 @@ describe('GET /api/forge-nim?action=health', () => {expect(fetchMock.mock.calls[0][0]).toBe('https://nim.example.run.app/v1/health/ready');});+ it('blames the caller, not the deployment, for a bad baseUrl override', async () => {+ // A rejected override says nothing about whether the operator wired a NIM.+ // Reporting configured:false made the page's status pill claim nothing was+ // set up on a deployment that was wired correctly.+ process.env.NIM_TRELLIS_URL = 'https://nim.example.run.app';+ const { res, body } = await dispatch(+ makeReq({ method: 'GET', url: '/api/forge-nim?action=health&baseUrl=http://10.0.0.1' }),+ makeRes(),+ );+ expect(res.statusCode).toBe(200);+ expect(body.configured).toBe(true);+ expect(body.reachable).toBe(false);+ expect(body.reason).toMatch(/https/i);+ });+it('reports down when the ready check is unreachable', async () => {process.env.NIM_TRELLIS_URL = 'https://nim.example.run.app';globalThis.fetch = vi.fn(async () => {@@ -227,6 +242,22 @@ describe('POST /api/forge-nim — configuration & SSRF', () => {expect(body.error).toBe('nim_unconfigured');});+ it('names the missing input on an unconfigured deployment instead of hiding it behind the 503', async () => {+ // Cheap, network-free input checks run before the NIM is resolved, so a+ // caller who sent no prompt is told THAT, rather than being handed the+ // unconfigured 503 every malformed request used to collect first.+ const { res: noPrompt, body: promptBody } = await dispatch(+ makeReq({ body: { mode: 'text', prompt: '' } }),+ makeRes(),+ );+ expect(noPrompt.statusCode).toBe(400);+ expect(promptBody.error).toBe('no_prompt');++ const { res: noImage, body: imageBody } = await dispatch(makeReq({ body: { mode: 'image' } }), makeRes());+ expect(noImage.statusCode).toBe(400);+ expect(imageBody.error).toBe('no_image');+ });+it('blocks a private-network baseUrl override (SSRF guard)', async () => {const calls = [];globalThis.fetch = vi.fn(async (u) => {diff --git a/tests/forge-iterate.test.js b/tests/forge-iterate.test.jsindex e781baaba..cc006a304 100644--- a/tests/forge-iterate.test.js+++ b/tests/forge-iterate.test.js@@ -233,6 +233,29 @@ describe('api/forge-iterate — handler', () => {expect(out.retry_after).toBe(5);});+ it('reports a submit that times out as busy with a back-off, not a bare gateway timeout', async () => {+ // /api/forge holds the connection open while a saturated generator queues the+ // job (a live three.ws submit held for 157s before answering its own busy+ // 429), so the submit timeout fires on exactly the busy condition. Answering+ // 504 sent both iterate UIs down the generic "rephrase your instruction"+ // branch, blaming a wording the user had got right.+ fetchMock.mockRejectedValueOnce(Object.assign(new Error('The operation was aborted'), { name: 'TimeoutError' }));+ const res = mockRes();+ await handler(mockReq({ body: { glb_url: 'https://three.ws/cdn/a.glb', instruction: 'bigger' } }), res);+ expect(res.statusCode).toBe(429);+ const out = parsed(res);+ expect(out.error).toBe('busy');+ expect(out.retry_after).toBeGreaterThan(0);+ });++ it('surfaces an unreachable generator as a 502 rather than a busy signal', async () => {+ fetchMock.mockRejectedValueOnce(new Error('ECONNREFUSED'));+ const res = mockRes();+ await handler(mockReq({ body: { glb_url: 'https://three.ws/cdn/a.glb', instruction: 'bigger' } }), res);+ expect(res.statusCode).toBe(502);+ expect(parsed(res).error).toBe('provider_error');+ });+it('is rate-limited per forgeIterate', async () => {limits.forgeIterate.mockResolvedValueOnce({ success: false, limit: 60, remaining: 0, reset: Date.now() + 1000 });const res = mockRes();diff --git a/tests/github-token-connect.test.js b/tests/github-token-connect.test.jsnew file mode 100644index 000000000..a32cdb0e4--- /dev/null+++ b/tests/github-token-connect.test.js@@ -0,0 +1,406 @@+// Tests for the personal-access-token route into GitHub memory seeding.+//+// The token path exists because OAuth is not always available: it needs an+// operator to register a GitHub OAuth app, and until that happens /connect can+// only answer 501. What is covered here is the part that makes the token path+// safe to offer: the scope policy that refuses a token carrying more access than+// seeding can use, and the disconnect that must not claim a GitHub-side+// revocation it never performed.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import {+ classifyTokenScopes,+ looksLikeGithubToken,+ encryptGithubToken,+ ALLOWED_TOKEN_SCOPES,+} from '../api/_lib/github-token.js';++// ── Pure scope policy ─────────────────────────────────────────────────────────++describe('classifyTokenScopes', () => {+ it('treats a missing header as a fine-grained token and accepts it', () => {+ // Fine-grained tokens and GitHub App user tokens omit x-oauth-scopes+ // entirely; their permissions were already narrowed at creation.+ expect(classifyTokenScopes(null)).toEqual({+ kind: 'fine_grained',+ scopes: [],+ allowed: true,+ refused: [],+ });+ expect(classifyTokenScopes(undefined).kind).toBe('fine_grained');+ });++ it('accepts a no-scope classic token', () => {+ // A scopeless classic PAT still reads public data, which is all the+ // catalog is ever built from.+ const out = classifyTokenScopes('');+ expect(out).toEqual({ kind: 'classic', scopes: [], allowed: true, refused: [] });+ });++ it('accepts the scopes seeding actually uses', () => {+ const out = classifyTokenScopes('read:user, public_repo');+ expect(out.allowed).toBe(true);+ expect(out.scopes).toEqual(['read:user', 'public_repo']);+ expect(out.refused).toEqual([]);+ });++ it('refuses full repo access, which reaches private repositories', () => {+ // The catalog is public-only by construction, so `repo` is strictly more+ // access than the feature can ever use.+ const out = classifyTokenScopes('read:user, repo');+ expect(out.allowed).toBe(false);+ expect(out.refused).toEqual(['repo']);+ });++ it('refuses destructive and admin scopes and names every one of them', () => {+ const out = classifyTokenScopes('delete_repo, admin:org, workflow, read:user');+ expect(out.allowed).toBe(false);+ expect(out.refused).toEqual(['delete_repo', 'admin:org', 'workflow']);+ });++ it('is an allowlist, so a scope GitHub invents later is refused by default', () => {+ const out = classifyTokenScopes('some:future_scope');+ expect(out.allowed).toBe(false);+ expect(out.refused).toEqual(['some:future_scope']);+ expect(ALLOWED_TOKEN_SCOPES).not.toContain('some:future_scope');+ });++ it('never contains a scope that grants private repository access', () => {+ expect(ALLOWED_TOKEN_SCOPES).not.toContain('repo');+ expect(ALLOWED_TOKEN_SCOPES).not.toContain('delete_repo');+ expect(ALLOWED_TOKEN_SCOPES.some((s) => s.startsWith('admin:'))).toBe(false);+ expect(ALLOWED_TOKEN_SCOPES.some((s) => s.startsWith('write:'))).toBe(false);+ });+});++describe('looksLikeGithubToken', () => {+ it('accepts realistic token shapes', () => {+ expect(looksLikeGithubToken('ghp_' + 'a'.repeat(36))).toBe(true);+ expect(looksLikeGithubToken('github_pat_' + 'b'.repeat(60))).toBe(true);+ expect(looksLikeGithubToken(' ghu_' + 'c'.repeat(36) + ' ')).toBe(true);+ });++ it('rejects input that cannot be a token at all', () => {+ expect(looksLikeGithubToken('')).toBe(false);+ expect(looksLikeGithubToken('short')).toBe(false);+ expect(looksLikeGithubToken('ghp_with a space in it padding padding')).toBe(false);+ expect(looksLikeGithubToken('x'.repeat(256))).toBe(false);+ expect(looksLikeGithubToken(null)).toBe(false);+ expect(looksLikeGithubToken(12345)).toBe(false);+ });+});++// ── Route ─────────────────────────────────────────────────────────────────────++const sqlMock = vi.fn();+sqlMock.transaction = vi.fn(async () => []);+vi.mock('../api/_lib/db.js', () => ({+ sql: sqlMock,+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const getSessionUserMock = vi.fn();+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: (...a) => getSessionUserMock(...a),+}));++const requireCsrfMock = vi.fn();+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: (...a) => requireCsrfMock(...a) }));++// Hoisted so the module mock below can close over it: this file statically+// imports github-token.js, which pulls env.js in before a plain const would be+// initialised.+const envMock = vi.hoisted(() => ({+ APP_ORIGIN: 'http://localhost:3000',+ ISSUER: 'http://t',+ MCP_RESOURCE: 'http://t',+ JWT_SECRET: 'test-secret-value-for-hkdf-derivation',+ GITHUB_OAUTH_CLIENT_ID: '',+ GITHUB_OAUTH_CLIENT_SECRET: '',+}));+vi.mock('../api/_lib/env.js', () => ({ env: envMock }));++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { authIp: async () => ({ success: true, limit: 30, remaining: 29, reset: Date.now() + 60_000 }) },+ clientIp: () => '127.0.0.1',+}));++const verifyTokenMock = vi.fn();+const revokeGrantMock = vi.fn();+vi.mock('../api/_lib/github-api.js', () => ({+ verifyToken: (...a) => verifyTokenMock(...a),+ revokeGrant: (...a) => revokeGrantMock(...a),+}));++const { default: handler } = await import('../api/auth/github/[action].js');++const USER = '55555555-5555-4555-8555-555555555555';++function mkReq({ method = 'POST', action = 'token', body = null, headers = {} } = {}) {+ return {+ method,+ url: `/api/auth/github/${action}?action=${action}`,+ headers: { 'content-type': 'application/json', ...headers },+ on(event, cb) {+ if (event === 'data' && body != null) {+ const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));+ queueMicrotask(() => {+ cb(buf);+ this._endCb?.();+ });+ } else if (event === 'end') {+ this._endCb = cb;+ if (body == null) queueMicrotask(() => cb());+ }+ },+ destroy() {},+ };+}++function mkRes() {+ return {+ statusCode: 200,+ headers: {},+ body: undefined,+ writableEnded: false,+ headersSent: false,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ end(b) {+ this.body = b;+ this.writableEnded = true;+ },+ };+}++const parseBody = (res) => (res.body ? JSON.parse(res.body) : undefined);+const GOOD_TOKEN = 'ghp_' + 'a'.repeat(36);++beforeEach(() => {+ sqlMock.mockReset().mockImplementation(() => Promise.resolve([]));+ sqlMock.transaction.mockReset().mockResolvedValue([[]]);+ getSessionUserMock.mockReset().mockResolvedValue({ id: USER });+ requireCsrfMock.mockReset().mockResolvedValue(true);+ verifyTokenMock.mockReset();+ revokeGrantMock.mockReset().mockResolvedValue(true);+ envMock.GITHUB_OAUTH_CLIENT_ID = '';+ envMock.GITHUB_OAUTH_CLIENT_SECRET = '';+});++describe('POST /api/auth/github/token', () => {+ it('stores a token GitHub accepts and reports the connect method', async () => {+ verifyTokenMock.mockResolvedValue({+ valid: true,+ status: 200,+ profile: { id: 42, login: 'octocat' },+ scopeHeader: 'read:user',+ });+ sqlMock.mockImplementation(() =>+ Promise.resolve([{ username: 'octocat', connected_at: '2026-08-16T00:00:00Z' }]),+ );++ const res = mkRes();+ await handler(mkReq({ body: { token: GOOD_TOKEN } }), res);++ expect(res.statusCode).toBe(200);+ const out = parseBody(res);+ expect(out.connected).toBe(true);+ expect(out.connect_method).toBe('token');+ expect(out.username).toBe('octocat');+ expect(out.scopes).toEqual(['read:user']);+ });++ it('never writes the token in the clear', async () => {+ verifyTokenMock.mockResolvedValue({+ valid: true,+ status: 200,+ profile: { id: 42, login: 'octocat' },+ scopeHeader: 'read:user',+ });+ sqlMock.mockImplementation(() =>+ Promise.resolve([{ username: 'octocat', connected_at: '2026-08-16T00:00:00Z' }]),+ );++ await handler(mkReq({ body: { token: GOOD_TOKEN } }), mkRes());++ // Every interpolated value across every query this call made.+ const written = sqlMock.mock.calls.flatMap((call) => call.slice(1)).map(String);+ expect(written.some((v) => v.includes(GOOD_TOKEN))).toBe(false);+ // The encrypted blob did get stored, so the check above is meaningful.+ expect(written.some((v) => v.length > 40)).toBe(true);+ });++ it('refuses a token that carries more access than seeding needs', async () => {+ verifyTokenMock.mockResolvedValue({+ valid: true,+ status: 200,+ profile: { id: 42, login: 'octocat' },+ scopeHeader: 'repo, delete_repo',+ });++ const res = mkRes();+ await handler(mkReq({ body: { token: GOOD_TOKEN } }), res);++ expect(res.statusCode).toBe(400);+ const out = parseBody(res);+ expect(out.error).toBe('token_scope_refused');+ expect(out.refused_scopes).toEqual(['repo', 'delete_repo']);+ expect(out.create_url).toContain('github.com/settings/tokens/new');+ // Nothing was stored.+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('reports a token GitHub rejects as a user error, not an outage', async () => {+ verifyTokenMock.mockResolvedValue({ valid: false, status: 401 });++ const res = mkRes();+ await handler(mkReq({ body: { token: GOOD_TOKEN } }), res);++ expect(res.statusCode).toBe(400);+ expect(parseBody(res).error).toBe('invalid_token');+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('rejects input that cannot be a token without calling GitHub', async () => {+ const res = mkRes();+ await handler(mkReq({ body: { token: 'nope' } }), res);++ expect(res.statusCode).toBe(400);+ expect(parseBody(res).error).toBe('validation_error');+ expect(verifyTokenMock).not.toHaveBeenCalled();+ });++ it('requires a session', async () => {+ getSessionUserMock.mockResolvedValue(null);++ const res = mkRes();+ await handler(mkReq({ body: { token: GOOD_TOKEN } }), res);++ expect(res.statusCode).toBe(401);+ expect(verifyTokenMock).not.toHaveBeenCalled();+ });++ it('requires CSRF, so another site cannot connect a token to your account', async () => {+ requireCsrfMock.mockResolvedValue(false);++ const res = mkRes();+ await handler(mkReq({ body: { token: GOOD_TOKEN } }), res);++ expect(verifyTokenMock).not.toHaveBeenCalled();+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('refuses a GET, because connecting is a mutation', async () => {+ const res = mkRes();+ await handler(mkReq({ method: 'GET', body: null }), res);++ expect(res.statusCode).toBe(405);+ });+});++describe('GET /api/auth/github/status', () => {+ it('offers the token path even with no OAuth app configured', async () => {+ sqlMock.mockImplementation(() => Promise.resolve([]));++ const res = mkRes();+ await handler(mkReq({ method: 'GET', action: 'status', body: null }), res);++ const out = parseBody(res);+ expect(out.connected).toBe(false);+ expect(out.configured).toBe(false);+ // The card reads this to decide that an unconfigured deployment is not a+ // dead end. Before the token path it rendered an "Unavailable" tag.+ expect(out.token_connect.available).toBe(true);+ expect(out.token_connect.recommended_scopes).toContain('read:user');+ });++ it('reports how a live connection was made', async () => {+ let call = 0;+ sqlMock.mockImplementation(() => {+ call += 1;+ if (call === 1)+ return Promise.resolve([+ {+ username: 'octocat',+ connected_at: '2026-08-16T00:00:00Z',+ raw_data: { connect_method: 'token' },+ },+ ]);+ return Promise.resolve([{ n: 7 }]);+ });++ const res = mkRes();+ await handler(mkReq({ method: 'GET', action: 'status', body: null }), res);++ const out = parseBody(res);+ expect(out.connected).toBe(true);+ expect(out.connect_method).toBe('token');+ expect(out.seeded_fact_count).toBe(7);+ });++ it('reads a row written before the token path existed as an OAuth connection', async () => {+ let call = 0;+ sqlMock.mockImplementation(() => {+ call += 1;+ if (call === 1)+ return Promise.resolve([+ { username: 'octocat', connected_at: '2026-08-16T00:00:00Z', raw_data: {} },+ ]);+ return Promise.resolve([{ n: 0 }]);+ });++ const res = mkRes();+ await handler(mkReq({ method: 'GET', action: 'status', body: null }), res);++ expect(parseBody(res).connect_method).toBe('oauth');+ });+});++describe('POST /api/auth/github/disconnect', () => {+ it('deletes seeded memories and does not claim a revocation it cannot perform', async () => {+ envMock.GITHUB_OAUTH_CLIENT_ID = 'client-id';+ envMock.GITHUB_OAUTH_CLIENT_SECRET = 'client-secret';+ sqlMock.mockImplementation(() =>+ Promise.resolve([{ id: 'conn-1', access_token: 'enc', raw_data: { connect_method: 'token' } }]),+ );+ sqlMock.transaction.mockResolvedValue([[{ id: 'm1' }, { id: 'm2' }], []]);++ const res = mkRes();+ await handler(mkReq({ method: 'POST', action: 'disconnect', body: null }), res);++ const out = parseBody(res);+ expect(out.disconnected).toBe(true);+ expect(out.memories_deleted).toBe(2);+ expect(out.connect_method).toBe('token');+ expect(out.grant_revoked).toBe(false);+ expect(out.revoke_url).toBe('https://github.com/settings/tokens');+ // GitHub exposes no way to delete a PAT using that same PAT, so the OAuth+ // grant revoke must not run against one.+ expect(revokeGrantMock).not.toHaveBeenCalled();+ });++ it('still revokes the grant for an OAuth connection', async () => {+ envMock.GITHUB_OAUTH_CLIENT_ID = 'client-id';+ envMock.GITHUB_OAUTH_CLIENT_SECRET = 'client-secret';+ // A real ciphertext: the revoke only runs if the stored token decrypts,+ // which is the same gate production hits.+ const stored = await encryptGithubToken('gho_' + 'd'.repeat(36));+ sqlMock.mockImplementation(() =>+ Promise.resolve([{ id: 'conn-1', access_token: stored, raw_data: { connect_method: 'oauth' } }]),+ );+ sqlMock.transaction.mockResolvedValue([[{ id: 'm1' }], []]);++ const res = mkRes();+ await handler(mkReq({ method: 'POST', action: 'disconnect', body: null }), res);++ const out = parseBody(res);+ expect(out.connect_method).toBe('oauth');+ expect(out.revoke_url).toBeNull();+ expect(revokeGrantMock).toHaveBeenCalledTimes(1);+ });+});