Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ id, or product name.
- `src/session.ts` — `createTokenSession`, the refresh-ahead-of-expiry logic.
- `src/browser.ts` — best-effort browser launch.
- `src/login.ts` — `startOAuthLogin`, wiring the above into one flow.
- `src/provider.ts` — `OAuthLoginProvider` and `loginWithProvider`, which
builds the login deps from a provider and saves the result.
- `src/index.ts` — the only module consumers import from.
- `src/*.test.ts` — tests next to the module they cover.

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,9 @@ import {
type BaseTokens,
type CallbackServer,
type OAuthLoginDeps,
type OAuthLoginProvider,
type TokenSessionDeps,
} from "@corbits/oauth-core";
import type { OAuthLoginProvider } from "@corbits/oauth-core/hub";

// The host's own callback page, served on the provider's fixed redirect_uri.
function startBrandedCallbackServer(
Expand Down
6 changes: 1 addition & 5 deletions src/hub/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
// Server-only entry point: the hub-hosted login mount. The root export
// stays free of `hono` and `@intx/*` so browser bundles never reach them.
export { mountOAuthLogin, type MountOAuthLoginOpts } from "./mount.js";
export {
callbackTargetFor,
type OAuthLoginProvider,
type OAuthLoginProviders,
} from "./registry.js";
export type { OAuthLoginProviders } from "../provider.js";
export {
persistOAuthCredential,
OAUTH_PROVIDER_METADATA_KEY,
Expand Down
17 changes: 8 additions & 9 deletions src/hub/mount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@ import {
} from "../index.js";
import { persistOAuthCredential } from "./credentials.js";
import { createLoginStore, type LoginState } from "./login-store.js";
import { callbackTargetFor, type OAuthLoginProviders } from "./registry.js";
import {
callbackTargetFor,
signedInHtml,
signInFailedHtml,
type OAuthLoginProviders,
} from "../provider.js";

/** An abandoned login holds a fixed loopback port, so it is not held long. */
const DEFAULT_LOGIN_TTL_MS = 5 * 60 * 1000;
Expand All @@ -23,12 +28,6 @@ const StartLogin = type({
credentialName: "string",
});

const DONE_HTML =
"<!doctype html><meta charset=utf-8><title>Signed in</title><p>Signed in — you can close this tab and return to your workbench.";

const failedHtml = (reason: string): string =>
`<!doctype html><meta charset=utf-8><title>Sign-in failed</title><p>Sign-in failed: ${reason.replace(/[<&]/g, "")}`;

export type MountOAuthLoginOpts = {
readonly db: DB["db"];
readonly cipher: CredentialCipher;
Expand Down Expand Up @@ -90,8 +89,8 @@ export function mountOAuthLogin(
port: target.port,
host: target.host,
path: target.path,
doneHtml: DONE_HTML,
failedHtml,
doneHtml: signedInHtml,
failedHtml: signInFailedHtml,
}),
buildAuthorizeUrl: (pkce, state) =>
buildAuthorizeUrl(provider.oauthConfig, pkce, state),
Expand Down
2 changes: 1 addition & 1 deletion src/hub/refresh.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
refreshCredential,
type OAuthRefreshStore,
} from "./refresh.js";
import type { OAuthLoginProviders } from "./registry.js";
import type { OAuthLoginProviders } from "../provider.js";

const MINUTE = 60_000;

Expand Down
2 changes: 1 addition & 1 deletion src/hub/refresh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
OAUTH_PROVIDER_METADATA_KEY,
writeOAuthTokens,
} from "./credentials.js";
import type { OAuthLoginProviders } from "./registry.js";
import type { OAuthLoginProviders } from "../provider.js";

const DEFAULT_INTERVAL_MS = 60_000;
const DEFAULT_MARGIN_MS = 10 * 60 * 1000;
Expand Down
33 changes: 0 additions & 33 deletions src/hub/registry.test.ts

This file was deleted.

55 changes: 0 additions & 55 deletions src/hub/registry.ts

This file was deleted.

7 changes: 7 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ export {
type StartOAuthLoginOptions,
} from "./login.js";

export {
callbackTargetFor,
loginWithProvider,
type LoginWithProviderOptions,
type OAuthLoginProvider,
} from "./provider.js";

export {
createTokenSession,
isTokenExpired,
Expand Down
97 changes: 97 additions & 0 deletions src/provider.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { createServer } from "node:net";

import { describe, expect, it, test } from "bun:test";

import {
callbackTargetFor,
loginWithProvider,
type BaseTokens,
type OAuthClientConfig,
type OAuthLoginProvider,
} from "./index.js";

async function freePort(): Promise<number> {
const server = createServer();
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
await new Promise((resolve) => server.close(resolve));
if (address === null || typeof address === "string") {
throw new Error("no TCP address");
}
return address.port;
}

describe("loginWithProvider", () => {
test("binds the provider's redirect_uri, exchanges the code, and saves before returning", async () => {
const port = await freePort();
// Load-bearing: the helper derives every login dependency from the
// provider. A wrong callback target or a skipped save only shows up as a
// login that hangs or a profile that is gone on the next run.
const tokens: BaseTokens = {
access: "access-1",
refresh: "refresh-1",
expiresAt: 10_000,
};
const exchanged: string[] = [];
const provider: OAuthLoginProvider = {
oauthConfig: {
clientId: "client",
authorizeUrl: "https://auth.example/authorize",
tokenUrl: "https://auth.example/token",
redirectUri: `http://127.0.0.1:${String(port)}/cb`,
scopes: ["openid"],
tokenTimeoutMs: 1_000,
},
exchange: async (code) => {
exchanged.push(code);
return tokens;
},
};
const saved: string[] = [];
let callback: Promise<Response> | undefined;

const done = loginWithProvider(provider, {
profile: "work",
signal: AbortSignal.timeout(5_000),
save: async (profile) => {
saved.push(profile.name);
},
openInBrowser: (url) => {
const state = new URL(url).searchParams.get("state") ?? "";
callback = fetch(
`http://127.0.0.1:${String(port)}/cb?code=the-code&state=${state}`,
);
},
});
const profile = await done;
expect((await callback)?.status).toBe(200);
expect(profile.tokens).toEqual(tokens);
expect(exchanged).toEqual(["the-code"]);
expect(saved).toEqual(["work"]);
});
});

const configFor = (redirectUri: string): OAuthClientConfig => ({
clientId: "client",
authorizeUrl: "https://auth.example.com/authorize",
tokenUrl: "https://auth.example.com/token",
redirectUri,
scopes: ["openid"],
tokenTimeoutMs: 1_000,
});

describe("callbackTargetFor", () => {
it("binds the host the provider registered, not a normalized loopback", () => {
// A provider that registered `localhost` is not interchangeable with
// `127.0.0.1`: the authorization server matches redirect_uri literally.
expect(
callbackTargetFor(configFor("http://localhost:1455/auth/callback")),
).toEqual({ host: "localhost", port: 1455, path: "/auth/callback" });
});

it("refuses a redirect_uri with no explicit port", () => {
expect(() =>
callbackTargetFor(configFor("http://127.0.0.1/callback")),
).toThrow(/explicit loopback port/);
});
});
Loading
Loading