@clavia-auth/core 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +45 -1
- package/dist/encoding.d.ts +4 -0
- package/dist/encoding.js +21 -0
- package/dist/errors.d.ts +5 -3
- package/dist/errors.js +2 -1
- package/dist/index.d.ts +12 -3
- package/dist/index.js +9 -3
- package/dist/management/client.js +2 -21
- package/dist/redis/index.d.ts +18 -0
- package/dist/redis/index.js +18 -0
- package/dist/redis/stores.d.ts +51 -0
- package/dist/redis/stores.js +183 -0
- package/dist/session/handle.d.ts +7 -0
- package/dist/session/handle.js +15 -0
- package/dist/session/memory.d.ts +32 -0
- package/dist/session/memory.js +106 -0
- package/dist/session/ports.d.ts +63 -0
- package/dist/session/ports.js +6 -0
- package/dist/session/sealing.d.ts +23 -0
- package/dist/session/sealing.js +130 -0
- package/dist/session/values.d.ts +60 -0
- package/dist/session/values.js +6 -0
- package/dist/sign-in/clavia.d.ts +86 -0
- package/dist/sign-in/clavia.js +190 -0
- package/dist/sign-in/cookies.d.ts +11 -0
- package/dist/sign-in/cookies.js +42 -0
- package/dist/sign-in/options.d.ts +95 -0
- package/dist/sign-in/options.js +79 -0
- package/dist/sign-in/provider.d.ts +57 -0
- package/dist/sign-in/provider.js +279 -0
- package/dist/sign-in/refused.d.ts +42 -0
- package/dist/sign-in/refused.js +49 -0
- package/dist/sign-in/return-to.d.ts +6 -0
- package/dist/sign-in/return-to.js +13 -0
- package/dist/sign-in/session.d.ts +23 -0
- package/dist/sign-in/session.js +136 -0
- package/dist/sign-in/sign-out.d.ts +18 -0
- package/dist/sign-in/sign-out.js +47 -0
- package/dist/testing/contracts.d.ts +43 -0
- package/dist/testing/contracts.js +198 -0
- package/dist/testing/fake-provider.d.ts +102 -0
- package/dist/testing/fake-provider.js +295 -0
- package/dist/testing/index.d.ts +20 -0
- package/dist/testing/index.js +20 -0
- package/dist/urls.d.ts +6 -0
- package/dist/urls.js +29 -0
- package/package.json +19 -1
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { type Clock } from "../clock.js";
|
|
2
|
+
import type { AttemptStore, SessionStore } from "../session/ports.js";
|
|
3
|
+
import type { JsonValue, Person } from "../session/values.js";
|
|
4
|
+
import type { SignInRefused } from "./refused.js";
|
|
5
|
+
/**
|
|
6
|
+
* Everything `createClavia` is configured with (clavia's `docs/design/sdks.md` §3). The core reads no
|
|
7
|
+
* environment: an adapter, or the application, passes each option, with the `CLAVIA_*` defaults of §2 read
|
|
8
|
+
* there. Every lifetime is in seconds.
|
|
9
|
+
*/
|
|
10
|
+
export interface ClaviaOptions {
|
|
11
|
+
/** The issuer, the single source of every endpoint: `https://auth.example.com`. */
|
|
12
|
+
readonly issuer: string | URL;
|
|
13
|
+
readonly clientId: string;
|
|
14
|
+
readonly clientSecret: string;
|
|
15
|
+
/** As the client is registered: `client_secret_basic` (the default) or `client_secret_post`. */
|
|
16
|
+
readonly clientAuthentication?: "client_secret_basic" | "client_secret_post";
|
|
17
|
+
/** The application's public origin: `https://reports.example.com`. https, but `http://localhost` in development. */
|
|
18
|
+
readonly appUrl: string | URL;
|
|
19
|
+
/**
|
|
20
|
+
* The keys sessions are sealed with: 32 bytes, base64url. A list rotates them: the first seals, every one
|
|
21
|
+
* opens.
|
|
22
|
+
*/
|
|
23
|
+
readonly sessionKey: string | readonly string[];
|
|
24
|
+
/** What to ask for; `openid profile email` by default, and `openid` always. */
|
|
25
|
+
readonly scopes?: readonly string[];
|
|
26
|
+
/** The one API the session's access token is for (its identifier), if any. */
|
|
27
|
+
readonly audience?: string;
|
|
28
|
+
readonly session?: {
|
|
29
|
+
/** How long a session lasts at most: 7 days by default, 5 minutes to 90 days. */
|
|
30
|
+
readonly absoluteLifetime?: number;
|
|
31
|
+
/** How long it lasts unused: 1 day by default, 1 minute to `absoluteLifetime`. */
|
|
32
|
+
readonly idleLifetime?: number;
|
|
33
|
+
};
|
|
34
|
+
readonly routes?: {
|
|
35
|
+
/**
|
|
36
|
+
* Where the routes are served: `/auth` by default (`/auth/sign-in`, `/auth/callback`, `/auth/sign-out`).
|
|
37
|
+
* A local path.
|
|
38
|
+
*/
|
|
39
|
+
readonly base?: string;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Where the browser lands once signed out: `/` by default, a local path. The issuer sends it back to
|
|
43
|
+
* `appUrl` + this path, which must be registered as one of the client's post-logout redirect URIs.
|
|
44
|
+
*/
|
|
45
|
+
readonly signedOutPath?: string;
|
|
46
|
+
/** Where sessions are kept (`memorySessionStore` in development, a Redis store in production). */
|
|
47
|
+
readonly sessions: SessionStore;
|
|
48
|
+
/** Where sign-in attempts are kept, for ten minutes each. */
|
|
49
|
+
readonly attempts: AttemptStore;
|
|
50
|
+
/**
|
|
51
|
+
* Called once a person has signed in, before the session is made: returns the session's `data`, or `false`
|
|
52
|
+
* to refuse the sign-in (`access_denied`). Returning nothing keeps `data` at `null`.
|
|
53
|
+
*/
|
|
54
|
+
readonly onSignedIn?: (person: Person, claims: Readonly<Record<string, unknown>>) => SignInDecision | void | Promise<SignInDecision | void>;
|
|
55
|
+
/**
|
|
56
|
+
* The page a refused sign-in answers with. By default, "Sign-in failed." and the refusal's status, nothing
|
|
57
|
+
* more: the issuer's words never reach a page.
|
|
58
|
+
*/
|
|
59
|
+
readonly signInFailed?: (error: SignInRefused, request: Request) => Response | Promise<Response>;
|
|
60
|
+
/** The Fetch API to call the issuer with; the global `fetch` by default. */
|
|
61
|
+
readonly fetch?: typeof fetch;
|
|
62
|
+
/** The time; the system clock by default. */
|
|
63
|
+
readonly clock?: Clock;
|
|
64
|
+
}
|
|
65
|
+
/** What `onSignedIn` decides: the session's `data`, nothing (`data` stays `null`), or `false` to refuse. */
|
|
66
|
+
export type SignInDecision = {
|
|
67
|
+
readonly data: JsonValue;
|
|
68
|
+
} | false | undefined;
|
|
69
|
+
/** The options, checked and completed. */
|
|
70
|
+
export interface Settings {
|
|
71
|
+
readonly issuer: URL;
|
|
72
|
+
readonly clientId: string;
|
|
73
|
+
readonly clientSecret: string;
|
|
74
|
+
readonly clientAuthentication: "client_secret_basic" | "client_secret_post";
|
|
75
|
+
readonly appUrl: URL;
|
|
76
|
+
/** Whether the cookies are `Secure` with the `__Host-` prefix: always, but over `http://localhost`. */
|
|
77
|
+
readonly secureCookies: boolean;
|
|
78
|
+
readonly sessionKeys: readonly string[];
|
|
79
|
+
readonly scopes: readonly string[];
|
|
80
|
+
readonly audience: string | null;
|
|
81
|
+
readonly absoluteLifetime: number;
|
|
82
|
+
readonly idleLifetime: number;
|
|
83
|
+
readonly base: string;
|
|
84
|
+
readonly redirectUri: string;
|
|
85
|
+
/** Where the browser lands once signed out, absolute: `appUrl` + `signedOutPath`. */
|
|
86
|
+
readonly signedOutUrl: URL;
|
|
87
|
+
readonly sessions: SessionStore;
|
|
88
|
+
readonly attempts: AttemptStore;
|
|
89
|
+
readonly onSignedIn: ClaviaOptions["onSignedIn"];
|
|
90
|
+
readonly signInFailed: ClaviaOptions["signInFailed"];
|
|
91
|
+
readonly fetch: typeof fetch;
|
|
92
|
+
readonly clock: Clock;
|
|
93
|
+
}
|
|
94
|
+
/** Checks every option at start: a mistake is a `TypeError` or a `RangeError` now, not a failed sign-in later. */
|
|
95
|
+
export declare function settings(options: ClaviaOptions): Settings;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { systemClock } from "../clock.js";
|
|
2
|
+
import { fromBase64Url } from "../encoding.js";
|
|
3
|
+
import { isLoopback, secureUrl } from "../urls.js";
|
|
4
|
+
import { isLocalPath } from "./return-to.js";
|
|
5
|
+
const MINUTE = 60;
|
|
6
|
+
const DAY = 24 * 60 * MINUTE;
|
|
7
|
+
/** Checks every option at start: a mistake is a `TypeError` or a `RangeError` now, not a failed sign-in later. */
|
|
8
|
+
export function settings(options) {
|
|
9
|
+
const issuer = secureUrl(options.issuer, "issuer");
|
|
10
|
+
const appUrl = secureUrl(options.appUrl, "appUrl");
|
|
11
|
+
if (appUrl.pathname !== "/" || appUrl.search !== "") {
|
|
12
|
+
throw new TypeError(`appUrl is the application's origin, with no path or query: ${appUrl.href} is not.`);
|
|
13
|
+
}
|
|
14
|
+
for (const [name, value] of [
|
|
15
|
+
["clientId", options.clientId],
|
|
16
|
+
["clientSecret", options.clientSecret],
|
|
17
|
+
]) {
|
|
18
|
+
if (typeof value !== "string" || value === "") {
|
|
19
|
+
throw new TypeError(`${name} is required.`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
if (options.audience !== undefined && (typeof options.audience !== "string" || options.audience === "")) {
|
|
23
|
+
throw new TypeError("audience, when given, is the API's identifier.");
|
|
24
|
+
}
|
|
25
|
+
const sessionKeys = typeof options.sessionKey === "string" ? [options.sessionKey] : [...options.sessionKey];
|
|
26
|
+
if (sessionKeys.length === 0) {
|
|
27
|
+
throw new TypeError("sessionKey is required: 32 bytes, base64url.");
|
|
28
|
+
}
|
|
29
|
+
sessionKeys.forEach((key, position) => {
|
|
30
|
+
if (typeof key !== "string" || fromBase64Url(key)?.length !== 32) {
|
|
31
|
+
throw new TypeError(`sessionKey ${String(position + 1)} is not 32 bytes of base64url.`);
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
if (typeof options.sessions !== "object" || typeof options.attempts !== "object") {
|
|
35
|
+
throw new TypeError("sessions and attempts are required: the stores sessions and sign-in attempts are kept in.");
|
|
36
|
+
}
|
|
37
|
+
const absoluteLifetime = within(options.session?.absoluteLifetime ?? 7 * DAY, 5 * MINUTE, 90 * DAY, "session.absoluteLifetime");
|
|
38
|
+
const idleLifetime = within(options.session?.idleLifetime ?? DAY, MINUTE, absoluteLifetime, "session.idleLifetime");
|
|
39
|
+
const base = (options.routes?.base ?? "/auth").replace(/\/+$/, "");
|
|
40
|
+
if (base === "" || !isLocalPath(base) || base.includes("?") || base.includes("#")) {
|
|
41
|
+
throw new TypeError(`routes.base is a local path, such as /auth: ${options.routes?.base ?? ""} is not.`);
|
|
42
|
+
}
|
|
43
|
+
const signedOutPath = options.signedOutPath ?? "/";
|
|
44
|
+
if (typeof signedOutPath !== "string" || !isLocalPath(signedOutPath)) {
|
|
45
|
+
throw new TypeError(`signedOutPath is a local path, such as /: ${String(options.signedOutPath)} is not.`);
|
|
46
|
+
}
|
|
47
|
+
const scopes = [...new Set(["openid", ...(options.scopes ?? ["openid", "profile", "email"])])];
|
|
48
|
+
if (scopes.some((scope) => !/^[\x21\x23-\x5b\x5d-\x7e]+$/.test(scope))) {
|
|
49
|
+
throw new TypeError("scopes are OAuth 2.0 scope tokens (RFC 6749 §3.3), with no space or quote.");
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
issuer,
|
|
53
|
+
clientId: options.clientId,
|
|
54
|
+
clientSecret: options.clientSecret,
|
|
55
|
+
clientAuthentication: options.clientAuthentication ?? "client_secret_basic",
|
|
56
|
+
appUrl,
|
|
57
|
+
secureCookies: appUrl.protocol === "https:" || !isLoopback(appUrl),
|
|
58
|
+
sessionKeys,
|
|
59
|
+
scopes,
|
|
60
|
+
audience: options.audience ?? null,
|
|
61
|
+
absoluteLifetime,
|
|
62
|
+
idleLifetime,
|
|
63
|
+
base,
|
|
64
|
+
redirectUri: new URL(`${base}/callback`, appUrl).href,
|
|
65
|
+
signedOutUrl: new URL(signedOutPath, appUrl),
|
|
66
|
+
sessions: options.sessions,
|
|
67
|
+
attempts: options.attempts,
|
|
68
|
+
onSignedIn: options.onSignedIn,
|
|
69
|
+
signInFailed: options.signInFailed,
|
|
70
|
+
fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
|
|
71
|
+
clock: options.clock ?? systemClock,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function within(value, least, most, name) {
|
|
75
|
+
if (!Number.isInteger(value) || value < least || value > most) {
|
|
76
|
+
throw new RangeError(`${name} is ${String(value)} seconds; it is from ${String(least)} to ${String(most)}.`);
|
|
77
|
+
}
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import * as oauth from "oauth4webapi";
|
|
2
|
+
import type { Person, Session, SignInAttempt } from "../session/values.js";
|
|
3
|
+
import type { Settings } from "./options.js";
|
|
4
|
+
/** What a redeemed code gives. */
|
|
5
|
+
export interface Redeemed {
|
|
6
|
+
readonly accessToken: string;
|
|
7
|
+
readonly expiresIn: number | null;
|
|
8
|
+
readonly refreshToken: string | null;
|
|
9
|
+
readonly idToken: string;
|
|
10
|
+
readonly scope: string | null;
|
|
11
|
+
readonly claims: Readonly<Record<string, unknown>>;
|
|
12
|
+
readonly person: Person;
|
|
13
|
+
}
|
|
14
|
+
/** What a refresh gives: what the issuer did not send again is `null`, and the session keeps what it had. */
|
|
15
|
+
export interface Refreshed {
|
|
16
|
+
readonly accessToken: string;
|
|
17
|
+
readonly expiresIn: number | null;
|
|
18
|
+
readonly refreshToken: string | null;
|
|
19
|
+
readonly idToken: string | null;
|
|
20
|
+
readonly scope: string | null;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The issuer, as an OpenID Connect provider for a confidential client, on `oauth4webapi`: discovery, the
|
|
24
|
+
* authorization request (pushed when the issuer offers it), the code redeemed and the ID token checked, userinfo.
|
|
25
|
+
* Every failure is a {@link SignInRefused}.
|
|
26
|
+
*/
|
|
27
|
+
export declare class Provider {
|
|
28
|
+
#private;
|
|
29
|
+
constructor(settings: Settings);
|
|
30
|
+
/** The discovery document, cached (OpenID Connect Discovery §4). */
|
|
31
|
+
server(): Promise<oauth.AuthorizationServer>;
|
|
32
|
+
/** Where to send the browser for `attempt`: the authorization endpoint, with a pushed request when offered. */
|
|
33
|
+
authorizationUrl(attempt: SignInAttempt): Promise<URL>;
|
|
34
|
+
/**
|
|
35
|
+
* The callback checked against `attempt` and its code redeemed: `state`, RFC 9207's `iss` when the issuer
|
|
36
|
+
* advertises it, the ID token (OpenID Connect Core §3.1.3.7: its signature by the issuer's keys, `iss`, `aud`,
|
|
37
|
+
* `azp`, `exp`, `iat`, `nonce`), then userinfo, whose `sub` must be the ID token's (§5.3.2).
|
|
38
|
+
*/
|
|
39
|
+
redeem(callback: URL, attempt: SignInAttempt): Promise<Redeemed>;
|
|
40
|
+
/**
|
|
41
|
+
* Gives a refresh token back (RFC 7009), best effort: whatever the issuer answers, or if it does not answer
|
|
42
|
+
* within five seconds, the sign-out goes on. Nothing is logged, and the token never leaves this call.
|
|
43
|
+
*/
|
|
44
|
+
revoke(refreshToken: string): Promise<void>;
|
|
45
|
+
/**
|
|
46
|
+
* Where to send the browser to end its session at the issuer too (OpenID Connect RP-Initiated Logout 1.0 §2),
|
|
47
|
+
* or `null` when the issuer names no end-session endpoint or cannot be read.
|
|
48
|
+
*/
|
|
49
|
+
endSessionUrl(idToken: string, postLogoutRedirectUri: string, state: string): Promise<URL | null>;
|
|
50
|
+
/**
|
|
51
|
+
* New tokens for `session`, by its refresh token (RFC 6749 §6), or `null` when the issuer refuses it
|
|
52
|
+
* (`invalid_grant`: spent, revoked, or expired), and the session must end. A new ID token is checked as at
|
|
53
|
+
* sign-in, and must name the same person (OpenID Connect Core §12.2). Any other failure is a
|
|
54
|
+
* {@link SignInRefused}, and the refresh token was not spent.
|
|
55
|
+
*/
|
|
56
|
+
refresh(session: Session): Promise<Refreshed | null>;
|
|
57
|
+
}
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import * as oauth from "oauth4webapi";
|
|
2
|
+
import { SignInRefused } from "./refused.js";
|
|
3
|
+
/** Discovery is kept for its `max-age`, at most a day; an hour when the issuer gives none. */
|
|
4
|
+
const MOST_DISCOVERY_MS = 24 * 60 * 60 * 1000;
|
|
5
|
+
const DEFAULT_DISCOVERY_MS = 60 * 60 * 1000;
|
|
6
|
+
/** How long a sign-out waits for the issuer to take a refresh token back. */
|
|
7
|
+
const REVOCATION_TIMEOUT_MS = 5000;
|
|
8
|
+
/**
|
|
9
|
+
* The issuer, as an OpenID Connect provider for a confidential client, on `oauth4webapi`: discovery, the
|
|
10
|
+
* authorization request (pushed when the issuer offers it), the code redeemed and the ID token checked, userinfo.
|
|
11
|
+
* Every failure is a {@link SignInRefused}.
|
|
12
|
+
*/
|
|
13
|
+
export class Provider {
|
|
14
|
+
#settings;
|
|
15
|
+
#server = null;
|
|
16
|
+
#pending = null;
|
|
17
|
+
/** The issuer's keys: fetched again on an unknown `kid` at most once a minute, and every five minutes. */
|
|
18
|
+
#jwks = {};
|
|
19
|
+
constructor(settings) {
|
|
20
|
+
this.#settings = settings;
|
|
21
|
+
}
|
|
22
|
+
/** The discovery document, cached (OpenID Connect Discovery §4). */
|
|
23
|
+
server() {
|
|
24
|
+
const now = this.#settings.clock.now();
|
|
25
|
+
if (this.#server !== null && now < this.#server.until) {
|
|
26
|
+
return Promise.resolve(this.#server.metadata);
|
|
27
|
+
}
|
|
28
|
+
this.#pending ??= this.#discover().finally(() => {
|
|
29
|
+
this.#pending = null;
|
|
30
|
+
});
|
|
31
|
+
return this.#pending;
|
|
32
|
+
}
|
|
33
|
+
/** Where to send the browser for `attempt`: the authorization endpoint, with a pushed request when offered. */
|
|
34
|
+
async authorizationUrl(attempt) {
|
|
35
|
+
const server = await this.server();
|
|
36
|
+
const authorizationEndpoint = server.authorization_endpoint;
|
|
37
|
+
if (authorizationEndpoint === undefined) {
|
|
38
|
+
throw new SignInRefused("provider_error");
|
|
39
|
+
}
|
|
40
|
+
const parameters = new URLSearchParams({
|
|
41
|
+
client_id: this.#settings.clientId,
|
|
42
|
+
response_type: "code",
|
|
43
|
+
redirect_uri: this.#settings.redirectUri,
|
|
44
|
+
scope: this.#settings.scopes.join(" "),
|
|
45
|
+
state: attempt.state,
|
|
46
|
+
nonce: attempt.nonce,
|
|
47
|
+
code_challenge: await oauth.calculatePKCECodeChallenge(attempt.codeVerifier),
|
|
48
|
+
code_challenge_method: "S256",
|
|
49
|
+
});
|
|
50
|
+
if (this.#settings.audience !== null) {
|
|
51
|
+
parameters.set("audience", this.#settings.audience);
|
|
52
|
+
}
|
|
53
|
+
const url = new URL(authorizationEndpoint);
|
|
54
|
+
if (server.pushed_authorization_request_endpoint !== undefined) {
|
|
55
|
+
// RFC 9126: the parameters never reach the address bar.
|
|
56
|
+
const pushed = await this.#call(async () => {
|
|
57
|
+
const response = await oauth.pushedAuthorizationRequest(server, this.#client(), this.#authentication(), parameters, this.#http());
|
|
58
|
+
return oauth.processPushedAuthorizationResponse(server, this.#client(), response);
|
|
59
|
+
});
|
|
60
|
+
url.searchParams.set("client_id", this.#settings.clientId);
|
|
61
|
+
url.searchParams.set("request_uri", pushed.request_uri);
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
for (const [name, value] of parameters) {
|
|
65
|
+
url.searchParams.set(name, value);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return url;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The callback checked against `attempt` and its code redeemed: `state`, RFC 9207's `iss` when the issuer
|
|
72
|
+
* advertises it, the ID token (OpenID Connect Core §3.1.3.7: its signature by the issuer's keys, `iss`, `aud`,
|
|
73
|
+
* `azp`, `exp`, `iat`, `nonce`), then userinfo, whose `sub` must be the ID token's (§5.3.2).
|
|
74
|
+
*/
|
|
75
|
+
async redeem(callback, attempt) {
|
|
76
|
+
const server = await this.server();
|
|
77
|
+
const client = this.#client();
|
|
78
|
+
const parameters = this.#check(() => oauth.validateAuthResponse(server, client, callback, attempt.state));
|
|
79
|
+
return this.#call(async () => {
|
|
80
|
+
const response = await oauth.authorizationCodeGrantRequest(server, client, this.#authentication(), parameters, this.#settings.redirectUri, attempt.codeVerifier, this.#http());
|
|
81
|
+
const tokens = await oauth.processAuthorizationCodeResponse(server, client, response, {
|
|
82
|
+
expectedNonce: attempt.nonce,
|
|
83
|
+
requireIdToken: true,
|
|
84
|
+
});
|
|
85
|
+
await oauth.validateApplicationLevelSignature(server, response, {
|
|
86
|
+
...this.#http(),
|
|
87
|
+
[oauth.jwksCache]: this.#jwks,
|
|
88
|
+
});
|
|
89
|
+
const claims = oauth.getValidatedIdTokenClaims(tokens);
|
|
90
|
+
if (claims === undefined || tokens.id_token === undefined) {
|
|
91
|
+
throw new SignInRefused("provider_error");
|
|
92
|
+
}
|
|
93
|
+
const userinfo = await oauth.processUserInfoResponse(server, client, claims.sub, await oauth.userInfoRequest(server, client, tokens.access_token, this.#http()));
|
|
94
|
+
return {
|
|
95
|
+
accessToken: tokens.access_token,
|
|
96
|
+
expiresIn: typeof tokens.expires_in === "number" ? tokens.expires_in : null,
|
|
97
|
+
refreshToken: tokens.refresh_token ?? null,
|
|
98
|
+
idToken: tokens.id_token,
|
|
99
|
+
scope: typeof tokens.scope === "string" ? tokens.scope : null,
|
|
100
|
+
claims: { ...claims },
|
|
101
|
+
person: {
|
|
102
|
+
sub: userinfo.sub,
|
|
103
|
+
name: typeof userinfo.name === "string" ? userinfo.name : null,
|
|
104
|
+
email: typeof userinfo.email === "string" ? userinfo.email : null,
|
|
105
|
+
email_verified: typeof userinfo.email_verified === "boolean" ? userinfo.email_verified : null,
|
|
106
|
+
picture: typeof userinfo.picture === "string" ? userinfo.picture : null,
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Gives a refresh token back (RFC 7009), best effort: whatever the issuer answers, or if it does not answer
|
|
113
|
+
* within five seconds, the sign-out goes on. Nothing is logged, and the token never leaves this call.
|
|
114
|
+
*/
|
|
115
|
+
async revoke(refreshToken) {
|
|
116
|
+
try {
|
|
117
|
+
const server = await this.server();
|
|
118
|
+
if (server.revocation_endpoint === undefined) {
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
const response = await oauth.revocationRequest(server, this.#client(), this.#authentication(), refreshToken, {
|
|
122
|
+
...this.#http(),
|
|
123
|
+
additionalParameters: { token_type_hint: "refresh_token" },
|
|
124
|
+
signal: AbortSignal.timeout(REVOCATION_TIMEOUT_MS),
|
|
125
|
+
});
|
|
126
|
+
await oauth.processRevocationResponse(response);
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
// Best effort: the session is already gone here, and the token dies with its family's lifetime.
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Where to send the browser to end its session at the issuer too (OpenID Connect RP-Initiated Logout 1.0 §2),
|
|
134
|
+
* or `null` when the issuer names no end-session endpoint or cannot be read.
|
|
135
|
+
*/
|
|
136
|
+
async endSessionUrl(idToken, postLogoutRedirectUri, state) {
|
|
137
|
+
let server;
|
|
138
|
+
try {
|
|
139
|
+
server = await this.server();
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
if (server.end_session_endpoint === undefined) {
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
const url = new URL(server.end_session_endpoint);
|
|
148
|
+
url.searchParams.set("id_token_hint", idToken);
|
|
149
|
+
url.searchParams.set("client_id", this.#settings.clientId);
|
|
150
|
+
url.searchParams.set("post_logout_redirect_uri", postLogoutRedirectUri);
|
|
151
|
+
url.searchParams.set("state", state);
|
|
152
|
+
return url;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* New tokens for `session`, by its refresh token (RFC 6749 §6), or `null` when the issuer refuses it
|
|
156
|
+
* (`invalid_grant`: spent, revoked, or expired), and the session must end. A new ID token is checked as at
|
|
157
|
+
* sign-in, and must name the same person (OpenID Connect Core §12.2). Any other failure is a
|
|
158
|
+
* {@link SignInRefused}, and the refresh token was not spent.
|
|
159
|
+
*/
|
|
160
|
+
async refresh(session) {
|
|
161
|
+
const refreshToken = session.tokens.refreshToken;
|
|
162
|
+
if (refreshToken === null) {
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
const server = await this.server();
|
|
166
|
+
const client = this.#client();
|
|
167
|
+
try {
|
|
168
|
+
return await this.#call(async () => {
|
|
169
|
+
const response = await oauth.refreshTokenGrantRequest(server, client, this.#authentication(), refreshToken, this.#http());
|
|
170
|
+
const tokens = await oauth.processRefreshTokenResponse(server, client, response);
|
|
171
|
+
const claims = oauth.getValidatedIdTokenClaims(tokens);
|
|
172
|
+
if (tokens.id_token !== undefined) {
|
|
173
|
+
await oauth.validateApplicationLevelSignature(server, response, {
|
|
174
|
+
...this.#http(),
|
|
175
|
+
[oauth.jwksCache]: this.#jwks,
|
|
176
|
+
});
|
|
177
|
+
if (claims?.sub !== session.person.sub) {
|
|
178
|
+
throw new SignInRefused("provider_error");
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return {
|
|
182
|
+
accessToken: tokens.access_token,
|
|
183
|
+
expiresIn: typeof tokens.expires_in === "number" ? tokens.expires_in : null,
|
|
184
|
+
refreshToken: tokens.refresh_token ?? null,
|
|
185
|
+
idToken: tokens.id_token ?? null,
|
|
186
|
+
scope: typeof tokens.scope === "string" ? tokens.scope : null,
|
|
187
|
+
};
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
if (error instanceof SignInRefused && error.code === "invalid_grant") {
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
async #discover() {
|
|
198
|
+
const { issuer, clock } = this.#settings;
|
|
199
|
+
const { metadata, maxAge } = await this.#call(async () => {
|
|
200
|
+
const response = await oauth.discoveryRequest(issuer, { algorithm: "oidc", ...this.#http() });
|
|
201
|
+
const maxAge = /(?:^|,)\s*max-age=(\d+)/i.exec(response.headers.get("Cache-Control") ?? "")?.[1];
|
|
202
|
+
// The document must name this issuer, exactly (Discovery §4.3).
|
|
203
|
+
return { metadata: await oauth.processDiscoveryResponse(issuer, response), maxAge };
|
|
204
|
+
});
|
|
205
|
+
// Every endpoint over https, as the issuer is; plain http only from a loopback issuer, in development.
|
|
206
|
+
for (const [name, value] of Object.entries(metadata)) {
|
|
207
|
+
if ((name.endsWith("_endpoint") || name === "jwks_uri") && typeof value === "string") {
|
|
208
|
+
const url = URL.canParse(value) ? new URL(value) : null;
|
|
209
|
+
if (url === null || (url.protocol !== "https:" && !(url.protocol === "http:" && issuer.protocol === "http:"))) {
|
|
210
|
+
throw new SignInRefused("provider_error");
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const keep = maxAge === undefined ? DEFAULT_DISCOVERY_MS : Math.min(Number(maxAge) * 1000, MOST_DISCOVERY_MS);
|
|
215
|
+
this.#server = { metadata, until: clock.now() + keep };
|
|
216
|
+
return metadata;
|
|
217
|
+
}
|
|
218
|
+
#client() {
|
|
219
|
+
// oauth4webapi reads the system clock: the skew makes it read this one, so `exp` and `iat` follow it.
|
|
220
|
+
const skew = Math.floor(this.#settings.clock.now() / 1000) - Math.floor(Date.now() / 1000);
|
|
221
|
+
return { client_id: this.#settings.clientId, [oauth.clockSkew]: skew };
|
|
222
|
+
}
|
|
223
|
+
#authentication() {
|
|
224
|
+
return this.#settings.clientAuthentication === "client_secret_post"
|
|
225
|
+
? oauth.ClientSecretPost(this.#settings.clientSecret)
|
|
226
|
+
: oauth.ClientSecretBasic(this.#settings.clientSecret);
|
|
227
|
+
}
|
|
228
|
+
#http() {
|
|
229
|
+
return {
|
|
230
|
+
[oauth.customFetch]: this.#settings.fetch,
|
|
231
|
+
// Plain http only to a loopback issuer, which createClavia has already checked: development.
|
|
232
|
+
// eslint-disable-next-line @typescript-eslint/no-deprecated -- deprecated to stand out, as it does here
|
|
233
|
+
...(this.#settings.issuer.protocol === "http:" ? { [oauth.allowInsecureRequests]: true } : {}),
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
#check(work) {
|
|
237
|
+
try {
|
|
238
|
+
return work();
|
|
239
|
+
}
|
|
240
|
+
catch (cause) {
|
|
241
|
+
throw refusal(cause);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
async #call(work) {
|
|
245
|
+
try {
|
|
246
|
+
return await work();
|
|
247
|
+
}
|
|
248
|
+
catch (cause) {
|
|
249
|
+
throw refusal(cause);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/** What went wrong, as a refusal: the issuer's `error` code kept, its description never. */
|
|
254
|
+
function refusal(cause) {
|
|
255
|
+
if (cause instanceof SignInRefused) {
|
|
256
|
+
return cause;
|
|
257
|
+
}
|
|
258
|
+
if (cause instanceof oauth.AuthorizationResponseError) {
|
|
259
|
+
return new SignInRefused(cause.error === "access_denied" ? "access_denied" : "provider_error", {
|
|
260
|
+
code: cause.error,
|
|
261
|
+
cause,
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
if (cause instanceof oauth.ResponseBodyError) {
|
|
265
|
+
return new SignInRefused("provider_error", { code: cause.error, cause });
|
|
266
|
+
}
|
|
267
|
+
if (cause instanceof oauth.OperationProcessingError ||
|
|
268
|
+
cause instanceof oauth.WWWAuthenticateChallengeError ||
|
|
269
|
+
cause instanceof oauth.UnsupportedOperationError) {
|
|
270
|
+
return new SignInRefused("provider_error", { cause });
|
|
271
|
+
}
|
|
272
|
+
// fetch rejects with a TypeError when nothing answers; oauth4webapi with one for an argument it refuses.
|
|
273
|
+
return new SignInRefused(isNetworkFailure(cause) ? "unreachable" : "provider_error", { cause });
|
|
274
|
+
}
|
|
275
|
+
function isNetworkFailure(cause) {
|
|
276
|
+
return ((cause instanceof TypeError &&
|
|
277
|
+
!("code" in cause && typeof cause.code === "string" && cause.code.startsWith("ERR_"))) ||
|
|
278
|
+
(cause instanceof DOMException && (cause.name === "AbortError" || cause.name === "TimeoutError")));
|
|
279
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** Why a sign-in did not complete (clavia's `docs/design/sdks.md` §2, *Errors*). */
|
|
2
|
+
export type SignInRefusal =
|
|
3
|
+
/** The callback reached a browser that did not start the attempt, or the attempt is unknown or spent. */
|
|
4
|
+
"unknown_attempt"
|
|
5
|
+
/** The person, or the issuer on their behalf, or the application's `onSignedIn`, refused. */
|
|
6
|
+
| "access_denied"
|
|
7
|
+
/** Anything else the issuer answered: an error, or an answer that did not check out. */
|
|
8
|
+
| "provider_error"
|
|
9
|
+
/** The issuer could not be reached: a refused connection, a certificate, a name, a timeout. */
|
|
10
|
+
| "unreachable";
|
|
11
|
+
/**
|
|
12
|
+
* A sign-in that did not complete. It never carries the issuer's `error_description`: a provider's words never
|
|
13
|
+
* reach a page, and the default page says nothing more than "Sign-in failed". The `error` code the issuer sent,
|
|
14
|
+
* when it sent one, is in `code`, for the logs.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```ts
|
|
18
|
+
* const clavia = createClavia({
|
|
19
|
+
* // …
|
|
20
|
+
* signInFailed: (error) =>
|
|
21
|
+
* new Response(error.reason === "access_denied" ? "You declined to sign in." : "Sign-in failed.", {
|
|
22
|
+
* status: error.status,
|
|
23
|
+
* }),
|
|
24
|
+
* });
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare class SignInRefused extends Error {
|
|
28
|
+
readonly reason: SignInRefusal;
|
|
29
|
+
/** The tag of the error, for a `switch` over `ClaviaError`. */
|
|
30
|
+
readonly _tag: "SignInRefused";
|
|
31
|
+
readonly name = "SignInRefused";
|
|
32
|
+
/** The OAuth 2.0 `error` code the issuer sent, when it sent one (`invalid_grant`); never its description. */
|
|
33
|
+
readonly code: string | null;
|
|
34
|
+
constructor(reason: SignInRefusal, options?: {
|
|
35
|
+
code?: string | null;
|
|
36
|
+
cause?: unknown;
|
|
37
|
+
});
|
|
38
|
+
/** The status a page about this refusal answers with. */
|
|
39
|
+
get status(): number;
|
|
40
|
+
}
|
|
41
|
+
/** Whether `value` is a {@link SignInRefused}. */
|
|
42
|
+
export declare function isSignInRefused(value: unknown): value is SignInRefused;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A sign-in that did not complete. It never carries the issuer's `error_description`: a provider's words never
|
|
3
|
+
* reach a page, and the default page says nothing more than "Sign-in failed". The `error` code the issuer sent,
|
|
4
|
+
* when it sent one, is in `code`, for the logs.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```ts
|
|
8
|
+
* const clavia = createClavia({
|
|
9
|
+
* // …
|
|
10
|
+
* signInFailed: (error) =>
|
|
11
|
+
* new Response(error.reason === "access_denied" ? "You declined to sign in." : "Sign-in failed.", {
|
|
12
|
+
* status: error.status,
|
|
13
|
+
* }),
|
|
14
|
+
* });
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
export class SignInRefused extends Error {
|
|
18
|
+
reason;
|
|
19
|
+
/** The tag of the error, for a `switch` over `ClaviaError`. */
|
|
20
|
+
_tag = "SignInRefused";
|
|
21
|
+
name = "SignInRefused";
|
|
22
|
+
/** The OAuth 2.0 `error` code the issuer sent, when it sent one (`invalid_grant`); never its description. */
|
|
23
|
+
code;
|
|
24
|
+
constructor(reason, options = {}) {
|
|
25
|
+
super(MESSAGES[reason], { cause: options.cause });
|
|
26
|
+
this.reason = reason;
|
|
27
|
+
this.code = options.code ?? null;
|
|
28
|
+
}
|
|
29
|
+
/** The status a page about this refusal answers with. */
|
|
30
|
+
get status() {
|
|
31
|
+
return STATUSES[this.reason];
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Whether `value` is a {@link SignInRefused}. */
|
|
35
|
+
export function isSignInRefused(value) {
|
|
36
|
+
return value instanceof SignInRefused;
|
|
37
|
+
}
|
|
38
|
+
const MESSAGES = {
|
|
39
|
+
unknown_attempt: "The sign-in attempt is unknown, spent, or belongs to another browser.",
|
|
40
|
+
access_denied: "The sign-in was refused.",
|
|
41
|
+
provider_error: "The issuer answered with an error, or with something that did not check out.",
|
|
42
|
+
unreachable: "The issuer could not be reached.",
|
|
43
|
+
};
|
|
44
|
+
const STATUSES = {
|
|
45
|
+
unknown_attempt: 400,
|
|
46
|
+
access_denied: 403,
|
|
47
|
+
provider_error: 502,
|
|
48
|
+
unreachable: 503,
|
|
49
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether `value` is a local path, where a browser may go once signed in: `/` followed by anything but `/` or
|
|
3
|
+
* `\`, and no control character (clavia's `docs/design/sdks.md` §2, *Return path*). A value that is not is
|
|
4
|
+
* refused, never repaired: an open redirect after sign-in is the classic phishing aid.
|
|
5
|
+
*/
|
|
6
|
+
export declare function isLocalPath(value: string): boolean;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether `value` is a local path, where a browser may go once signed in: `/` followed by anything but `/` or
|
|
3
|
+
* `\`, and no control character (clavia's `docs/design/sdks.md` §2, *Return path*). A value that is not is
|
|
4
|
+
* refused, never repaired: an open redirect after sign-in is the classic phishing aid.
|
|
5
|
+
*/
|
|
6
|
+
export function isLocalPath(value) {
|
|
7
|
+
return (value.startsWith("/") &&
|
|
8
|
+
!value.startsWith("//") &&
|
|
9
|
+
!value.startsWith("/\\") &&
|
|
10
|
+
// eslint-disable-next-line no-control-regex -- control characters are what is refused
|
|
11
|
+
!/[\u0000-\u001f\u007f]/.test(value) &&
|
|
12
|
+
!value.includes("\\"));
|
|
13
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type SessionKeys } from "../session/sealing.js";
|
|
2
|
+
import type { JsonValue, Person } from "../session/values.js";
|
|
3
|
+
import type { Settings } from "./options.js";
|
|
4
|
+
import type { Provider } from "./provider.js";
|
|
5
|
+
/** An access token this close to expiring is refreshed before it is handed out, in milliseconds. */
|
|
6
|
+
export declare const REFRESH_AHEAD_MS = 60000;
|
|
7
|
+
/** `lastSeenAt` is written back at most this often, in milliseconds. */
|
|
8
|
+
export declare const TOUCH_INTERVAL_MS = 60000;
|
|
9
|
+
/** What `session()` tells about the person signed in: never a token. */
|
|
10
|
+
export interface CurrentSession {
|
|
11
|
+
readonly person: Person;
|
|
12
|
+
/** The scopes the session's access token carries. */
|
|
13
|
+
readonly scopes: readonly string[];
|
|
14
|
+
/** The application's own data, as `onSignedIn` gave it. */
|
|
15
|
+
readonly data: JsonValue;
|
|
16
|
+
}
|
|
17
|
+
/** The sessions of one `createClavia`. */
|
|
18
|
+
export declare class Sessions {
|
|
19
|
+
#private;
|
|
20
|
+
constructor(config: Settings, provider: Provider, keys: () => Promise<SessionKeys>, cookie: string);
|
|
21
|
+
session(request: Request): Promise<CurrentSession | null>;
|
|
22
|
+
accessToken(request: Request): Promise<string | null>;
|
|
23
|
+
}
|