| 1 | import { createHash } from "node:crypto"; |
| 2 | import { describe, expect, it } from "vitest"; |
| 3 | import { authorizeUrl, clientId, editorRedirect, normalizeServer, pkce, readCallback } from "../src/util"; |
| 4 | |
| 5 | const S = "https://diffinery.com"; |
| 6 | |
| 7 | describe("server and OAuth", () => { |
| 8 | it("normalizes the server setting", () => { |
| 9 | expect(normalizeServer(undefined)).toBe(S); |
| 10 | expect(normalizeServer(" https://diffinery.com/ ")).toBe(S); |
| 11 | expect(normalizeServer("diffinery.example.org")).toBe("https://diffinery.example.org"); |
| 12 | expect(normalizeServer("http://localhost:8787")).toBe("http://localhost:8787"); |
| 13 | expect(() => normalizeServer("http://diffinery.com")).toThrow(/https/); |
| 14 | expect(() => normalizeServer("https://")).toThrow(/valid URL/); |
| 15 | }); |
| 16 | |
| 17 | it("returns to the editor by its own scheme when the server knows it", () => { |
| 18 | expect(editorRedirect("vscode")).toBe("vscode://codician.diffinery/oauth"); |
| 19 | expect(editorRedirect("cursor")).toBe("cursor://codician.diffinery/oauth"); |
| 20 | expect(editorRedirect("some-fork")).toBeNull(); |
| 21 | expect(clientId(S)).toBe("https://diffinery.com/oauth/clients/editor.json"); |
| 22 | }); |
| 23 | |
| 24 | it("makes a PKCE pair and an authorization URL", () => { |
| 25 | const p = pkce(); |
| 26 | expect(p.challenge).toBe(createHash("sha256").update(p.verifier).digest("base64url")); |
| 27 | const u = new URL(authorizeUrl(S, "cursor://codician.diffinery/oauth", p.challenge, p.state)); |
| 28 | expect(u.origin + u.pathname).toBe(`${S}/oauth/authorize`); |
| 29 | expect(Object.fromEntries(u.searchParams)).toEqual({ response_type: "code", client_id: clientId(S), redirect_uri: "cursor://codician.diffinery/oauth", code_challenge: p.challenge, code_challenge_method: "S256", state: p.state, scope: "write" }); |
| 30 | }); |
| 31 | |
| 32 | it("accepts only the callback of this sign-in, from this server", () => { |
| 33 | const expect_ = { state: "st", server: S }; |
| 34 | expect(readCallback(`code=dfa_1&state=st&iss=${encodeURIComponent(S)}`, expect_)).toEqual({ code: "dfa_1" }); |
| 35 | expect(readCallback("code=dfa_1&state=other", expect_)).toHaveProperty("error"); |
| 36 | expect(readCallback("code=dfa_1&state=st&iss=https%3A%2F%2Fevil.example", expect_)).toEqual({ error: expect.stringMatching(/evil\.example/) }); |
| 37 | expect(readCallback("error=access_denied&state=st", expect_)).toEqual({ error: "Sign-in was cancelled in the browser." }); |
| 38 | expect(readCallback("state=st", expect_)).toHaveProperty("error"); |
| 39 | }); |
| 40 | }); |