@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,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where sessions and sign-in attempts are kept: ports an application or an adapter provides (clavia's
|
|
3
|
+
* `docs/design/sdks.md` §4, *Ports*). A store sees sealed records and handle digests only: a leaked store opens
|
|
4
|
+
* no session and names nobody but by `sub` and `sid`.
|
|
5
|
+
*/
|
|
6
|
+
/** A sealed record: opaque to the store, opened by the core alone. */
|
|
7
|
+
export type Sealed = string;
|
|
8
|
+
/**
|
|
9
|
+
* What a session is kept under: the SHA-256 digest of the handle the browser holds (base64url). The store never
|
|
10
|
+
* sees the handle itself.
|
|
11
|
+
*/
|
|
12
|
+
export type HandleDigest = string;
|
|
13
|
+
/**
|
|
14
|
+
* Sessions, by the digest of their handle, with an index by `sid` and by `sub` for back-channel logout, and a
|
|
15
|
+
* lock per session that serialises refreshes across processes.
|
|
16
|
+
*
|
|
17
|
+
* Every TTL is in seconds; a record past its TTL is gone. `SessionStoreContract`
|
|
18
|
+
* (`@clavia-auth/core/testing`) is what an implementation must pass.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```ts
|
|
22
|
+
* import { memorySessionStore } from "@clavia-auth/core";
|
|
23
|
+
*
|
|
24
|
+
* const sessions: SessionStore = memorySessionStore({ production: process.env.NODE_ENV === "production" });
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export interface SessionStore {
|
|
28
|
+
/** Keeps a new session under `key`, indexed by its `sid` (when it has one) and its `sub`. */
|
|
29
|
+
create(key: HandleDigest, record: Sealed, ttl: number, index: SessionIndex): Promise<void>;
|
|
30
|
+
/** The session under `key`, or `null` when there is none (never kept, ended, or past its TTL). */
|
|
31
|
+
read(key: HandleDigest): Promise<Sealed | null>;
|
|
32
|
+
/**
|
|
33
|
+
* Replaces the session under `key` and its TTL, keeping its index. A session that no longer exists stays
|
|
34
|
+
* gone: a refresh that finishes after a sign-out or a back-channel logout does not bring it back.
|
|
35
|
+
*/
|
|
36
|
+
save(key: HandleDigest, record: Sealed, ttl: number): Promise<void>;
|
|
37
|
+
/** Ends the session under `key`; returns it, or `null` when there was none. */
|
|
38
|
+
destroy(key: HandleDigest): Promise<Sealed | null>;
|
|
39
|
+
/** Ends every session of an issuer's session `sid`; returns how many. */
|
|
40
|
+
destroyBySid(sid: string): Promise<number>;
|
|
41
|
+
/** Ends every session of a person; returns how many. */
|
|
42
|
+
destroyBySubject(sub: string): Promise<number>;
|
|
43
|
+
/**
|
|
44
|
+
* Runs `work` while no other caller, in any process, holds the lock of `key`, and returns what it returns.
|
|
45
|
+
* The lock is released when `work` settles, whether it resolves or throws.
|
|
46
|
+
*/
|
|
47
|
+
exclusively<T>(key: HandleDigest, work: () => Promise<T>): Promise<T>;
|
|
48
|
+
}
|
|
49
|
+
/** What a session is indexed by. */
|
|
50
|
+
export interface SessionIndex {
|
|
51
|
+
readonly sid: string | null;
|
|
52
|
+
readonly sub: string;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Sign-in attempts, by their `state`, each taken once. `AttemptStoreContract` (`@clavia-auth/core/testing`) is
|
|
56
|
+
* what an implementation must pass.
|
|
57
|
+
*/
|
|
58
|
+
export interface AttemptStore {
|
|
59
|
+
/** Keeps an attempt under its `state` for `ttl` seconds. */
|
|
60
|
+
put(record: Sealed, state: string, ttl: number): Promise<void>;
|
|
61
|
+
/** The attempt under `state`, removed as it is read: of callers racing for it, one alone gets it. */
|
|
62
|
+
take(state: string): Promise<Sealed | null>;
|
|
63
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where sessions and sign-in attempts are kept: ports an application or an adapter provides (clavia's
|
|
3
|
+
* `docs/design/sdks.md` §4, *Ports*). A store sees sealed records and handle digests only: a leaked store opens
|
|
4
|
+
* no session and names nobody but by `sub` and `sid`.
|
|
5
|
+
*/
|
|
6
|
+
export {};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { HandleDigest, Sealed } from "./ports.js";
|
|
2
|
+
import { type Session, type SignInAttempt } from "./values.js";
|
|
3
|
+
/**
|
|
4
|
+
* The keys records are sealed with: 32 bytes each, base64url. The first seals; every one opens, so a key is
|
|
5
|
+
* rotated by putting the new one first and dropping the old one once its sessions have ended.
|
|
6
|
+
*/
|
|
7
|
+
export declare class SessionKeys {
|
|
8
|
+
#private;
|
|
9
|
+
private constructor();
|
|
10
|
+
static from(keys: string | readonly string[]): Promise<SessionKeys>;
|
|
11
|
+
/** Seals `value` for `context`. */
|
|
12
|
+
seal(value: unknown, context: string): Promise<Sealed>;
|
|
13
|
+
/** What `sealed` holds, or `null` when it does not open: another context, a key not held, tampered, truncated. */
|
|
14
|
+
open(sealed: Sealed, context: string): Promise<unknown>;
|
|
15
|
+
}
|
|
16
|
+
/** A session, sealed under its handle's digest. Refuses `data` heavier than {@link MAX_SESSION_DATA_BYTES}. */
|
|
17
|
+
export declare function sealSession(keys: SessionKeys, key: HandleDigest, session: Session): Promise<Sealed>;
|
|
18
|
+
/** The session sealed under `key`, or `null`: a record that does not open, or opens to something else, is none. */
|
|
19
|
+
export declare function openSession(keys: SessionKeys, key: HandleDigest, sealed: Sealed): Promise<Session | null>;
|
|
20
|
+
/** A sign-in attempt, sealed under its state. */
|
|
21
|
+
export declare function sealAttempt(keys: SessionKeys, attempt: SignInAttempt): Promise<Sealed>;
|
|
22
|
+
/** The attempt sealed under `state`, or `null`. */
|
|
23
|
+
export declare function openAttempt(keys: SessionKeys, state: string, sealed: Sealed): Promise<SignInAttempt | null>;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// Records sealed with AES-256-GCM on Web Crypto (clavia's docs/design/sdks.md §2 *Where the session lives*, §7
|
|
2
|
+
// *A leaked store opens nothing*): `v1.` and base64url(iv ‖ ciphertext ‖ tag). What the record is kept under is
|
|
3
|
+
// bound in as associated data (the handle's digest for a session, the state for an attempt), so a record moved
|
|
4
|
+
// under another key does not open.
|
|
5
|
+
import { fromBase64Url, toBase64Url, utf8 } from "../encoding.js";
|
|
6
|
+
import { MAX_SESSION_DATA_BYTES } from "./values.js";
|
|
7
|
+
const VERSION = "v1.";
|
|
8
|
+
const IV_BYTES = 12;
|
|
9
|
+
const TAG_BYTES = 16;
|
|
10
|
+
/**
|
|
11
|
+
* The keys records are sealed with: 32 bytes each, base64url. The first seals; every one opens, so a key is
|
|
12
|
+
* rotated by putting the new one first and dropping the old one once its sessions have ended.
|
|
13
|
+
*/
|
|
14
|
+
export class SessionKeys {
|
|
15
|
+
#keys;
|
|
16
|
+
constructor(keys) {
|
|
17
|
+
this.#keys = keys;
|
|
18
|
+
}
|
|
19
|
+
static async from(keys) {
|
|
20
|
+
const list = typeof keys === "string" ? [keys] : keys;
|
|
21
|
+
if (list.length === 0) {
|
|
22
|
+
throw new TypeError("sessionKey is required: 32 bytes, base64url.");
|
|
23
|
+
}
|
|
24
|
+
const imported = await Promise.all(list.map((key, position) => {
|
|
25
|
+
const bytes = typeof key === "string" ? fromBase64Url(key) : null;
|
|
26
|
+
if (bytes?.length !== 32) {
|
|
27
|
+
// Which one, never what it is.
|
|
28
|
+
throw new TypeError(`sessionKey ${String(position + 1)} is not 32 bytes of base64url.`);
|
|
29
|
+
}
|
|
30
|
+
return crypto.subtle.importKey("raw", bytes, "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
31
|
+
}));
|
|
32
|
+
return new SessionKeys(imported);
|
|
33
|
+
}
|
|
34
|
+
/** Seals `value` for `context`. */
|
|
35
|
+
async seal(value, context) {
|
|
36
|
+
const key = this.#keys[0];
|
|
37
|
+
if (key === undefined) {
|
|
38
|
+
throw new TypeError("No session key.");
|
|
39
|
+
}
|
|
40
|
+
const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
|
|
41
|
+
const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: utf8.encode(context) }, key, utf8.encode(JSON.stringify(value))));
|
|
42
|
+
const bytes = new Uint8Array(IV_BYTES + sealed.length);
|
|
43
|
+
bytes.set(iv);
|
|
44
|
+
bytes.set(sealed, IV_BYTES);
|
|
45
|
+
return VERSION + toBase64Url(bytes);
|
|
46
|
+
}
|
|
47
|
+
/** What `sealed` holds, or `null` when it does not open: another context, a key not held, tampered, truncated. */
|
|
48
|
+
async open(sealed, context) {
|
|
49
|
+
const bytes = sealed.startsWith(VERSION) ? fromBase64Url(sealed.slice(VERSION.length)) : null;
|
|
50
|
+
if (bytes === null || bytes.length < IV_BYTES + TAG_BYTES) {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
const iv = bytes.subarray(0, IV_BYTES);
|
|
54
|
+
const data = bytes.subarray(IV_BYTES);
|
|
55
|
+
for (const key of this.#keys) {
|
|
56
|
+
try {
|
|
57
|
+
const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv, additionalData: utf8.encode(context) }, key, data);
|
|
58
|
+
return JSON.parse(new TextDecoder().decode(plain));
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
// Not this key: the next one, or no record at all.
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** A session, sealed under its handle's digest. Refuses `data` heavier than {@link MAX_SESSION_DATA_BYTES}. */
|
|
68
|
+
export async function sealSession(keys, key, session) {
|
|
69
|
+
const data = utf8.encode(JSON.stringify(session.data)).length;
|
|
70
|
+
if (data > MAX_SESSION_DATA_BYTES) {
|
|
71
|
+
throw new RangeError(`The session's data is ${String(data)} bytes of JSON; at most ${String(MAX_SESSION_DATA_BYTES)}.`);
|
|
72
|
+
}
|
|
73
|
+
return keys.seal(session, `clavia:session:${key}`);
|
|
74
|
+
}
|
|
75
|
+
/** The session sealed under `key`, or `null`: a record that does not open, or opens to something else, is none. */
|
|
76
|
+
export async function openSession(keys, key, sealed) {
|
|
77
|
+
const value = await keys.open(sealed, `clavia:session:${key}`);
|
|
78
|
+
return isSession(value) ? value : null;
|
|
79
|
+
}
|
|
80
|
+
/** A sign-in attempt, sealed under its state. */
|
|
81
|
+
export function sealAttempt(keys, attempt) {
|
|
82
|
+
return keys.seal(attempt, `clavia:attempt:${attempt.state}`);
|
|
83
|
+
}
|
|
84
|
+
/** The attempt sealed under `state`, or `null`. */
|
|
85
|
+
export async function openAttempt(keys, state, sealed) {
|
|
86
|
+
const value = await keys.open(sealed, `clavia:attempt:${state}`);
|
|
87
|
+
return isAttempt(value) && value.state === state ? value : null;
|
|
88
|
+
}
|
|
89
|
+
function isSession(value) {
|
|
90
|
+
if (!isRecord(value) || !isRecord(value.person) || !isRecord(value.tokens)) {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
const { person, tokens } = value;
|
|
94
|
+
return (typeof person.sub === "string" &&
|
|
95
|
+
isNullable(person.name, "string") &&
|
|
96
|
+
isNullable(person.email, "string") &&
|
|
97
|
+
isNullable(person.email_verified, "boolean") &&
|
|
98
|
+
isNullable(person.picture, "string") &&
|
|
99
|
+
isNullable(value.sid, "string") &&
|
|
100
|
+
typeof tokens.accessToken === "string" &&
|
|
101
|
+
typeof tokens.accessTokenExpiresAt === "number" &&
|
|
102
|
+
isNullable(tokens.refreshToken, "string") &&
|
|
103
|
+
typeof tokens.idToken === "string" &&
|
|
104
|
+
Array.isArray(tokens.scopes) &&
|
|
105
|
+
tokens.scopes.every((scope) => typeof scope === "string") &&
|
|
106
|
+
(tokens.dpopKey === null || isRecord(tokens.dpopKey)) &&
|
|
107
|
+
typeof value.createdAt === "number" &&
|
|
108
|
+
typeof value.expiresAt === "number" &&
|
|
109
|
+
typeof value.lastSeenAt === "number" &&
|
|
110
|
+
"data" in value &&
|
|
111
|
+
isJson(value.data));
|
|
112
|
+
}
|
|
113
|
+
function isAttempt(value) {
|
|
114
|
+
return (isRecord(value) &&
|
|
115
|
+
typeof value.state === "string" &&
|
|
116
|
+
typeof value.nonce === "string" &&
|
|
117
|
+
typeof value.codeVerifier === "string" &&
|
|
118
|
+
typeof value.returnTo === "string" &&
|
|
119
|
+
isNullable(value.acrValues, "string") &&
|
|
120
|
+
(value.dpopKey === null || isRecord(value.dpopKey)));
|
|
121
|
+
}
|
|
122
|
+
function isNullable(value, type) {
|
|
123
|
+
return value === null || typeof value === type;
|
|
124
|
+
}
|
|
125
|
+
function isJson(value) {
|
|
126
|
+
return value !== undefined;
|
|
127
|
+
}
|
|
128
|
+
function isRecord(value) {
|
|
129
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
130
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a signed-in session holds, kept on the server and sealed in the store (clavia's `docs/design/sdks.md` §4,
|
|
3
|
+
* *Values*). Every time is in milliseconds since the Unix epoch.
|
|
4
|
+
*/
|
|
5
|
+
/** A JSON value, as the application's own session `data` must be. */
|
|
6
|
+
export type JsonValue = null | boolean | number | string | readonly JsonValue[] | {
|
|
7
|
+
readonly [key: string]: JsonValue;
|
|
8
|
+
};
|
|
9
|
+
/** What the issuer gave for a session. Never sent to the browser. */
|
|
10
|
+
export interface TokenSet {
|
|
11
|
+
readonly accessToken: string;
|
|
12
|
+
/** When the access token expires. */
|
|
13
|
+
readonly accessTokenExpiresAt: number;
|
|
14
|
+
/** `null` when the issuer gave none: the session then ends with its access token. */
|
|
15
|
+
readonly refreshToken: string | null;
|
|
16
|
+
/** Kept for RP-initiated logout's `id_token_hint`. */
|
|
17
|
+
readonly idToken: string;
|
|
18
|
+
/** The scopes the access token carries. */
|
|
19
|
+
readonly scopes: readonly string[];
|
|
20
|
+
/** The session's DPoP key (RFC 9449), as a private JWK, when DPoP is on; otherwise `null`. */
|
|
21
|
+
readonly dpopKey: JsonWebKey | null;
|
|
22
|
+
}
|
|
23
|
+
/** Who signed in, as userinfo describes them (OpenID Connect Core §5.1). */
|
|
24
|
+
export interface Person {
|
|
25
|
+
readonly sub: string;
|
|
26
|
+
readonly name: string | null;
|
|
27
|
+
readonly email: string | null;
|
|
28
|
+
readonly email_verified: boolean | null;
|
|
29
|
+
readonly picture: string | null;
|
|
30
|
+
}
|
|
31
|
+
/** A session: the person, their tokens, and the application's own `data`. */
|
|
32
|
+
export interface Session {
|
|
33
|
+
readonly person: Person;
|
|
34
|
+
/** The `sid` of the person's session at the issuer, which back-channel logout names. */
|
|
35
|
+
readonly sid: string | null;
|
|
36
|
+
readonly tokens: TokenSet;
|
|
37
|
+
readonly createdAt: number;
|
|
38
|
+
/** The absolute end: after it the person signs in again, however active. */
|
|
39
|
+
readonly expiresAt: number;
|
|
40
|
+
/** When the session was last used, for the idle lifetime. */
|
|
41
|
+
readonly lastSeenAt: number;
|
|
42
|
+
/** The application's own data, at most {@link MAX_SESSION_DATA_BYTES} of JSON. */
|
|
43
|
+
readonly data: JsonValue;
|
|
44
|
+
}
|
|
45
|
+
/** What a sign-in in progress remembers between the redirect and the callback. */
|
|
46
|
+
export interface SignInAttempt {
|
|
47
|
+
/** OAuth 2.0 `state`: the callback belongs to this attempt. */
|
|
48
|
+
readonly state: string;
|
|
49
|
+
readonly nonce: string;
|
|
50
|
+
/** PKCE's `code_verifier` (RFC 7636). */
|
|
51
|
+
readonly codeVerifier: string;
|
|
52
|
+
/** Where to land once signed in: a local path, checked when the sign-in started. */
|
|
53
|
+
readonly returnTo: string;
|
|
54
|
+
/** The `acr_values` asked for (RFC 9470), or `null`. */
|
|
55
|
+
readonly acrValues: string | null;
|
|
56
|
+
/** The DPoP key made for this sign-in, when DPoP is on; otherwise `null`. */
|
|
57
|
+
readonly dpopKey: JsonWebKey | null;
|
|
58
|
+
}
|
|
59
|
+
/** The most the application's session `data` may weigh, as UTF-8 JSON. */
|
|
60
|
+
export declare const MAX_SESSION_DATA_BYTES = 4096;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a signed-in session holds, kept on the server and sealed in the store (clavia's `docs/design/sdks.md` §4,
|
|
3
|
+
* *Values*). Every time is in milliseconds since the Unix epoch.
|
|
4
|
+
*/
|
|
5
|
+
/** The most the application's session `data` may weigh, as UTF-8 JSON. */
|
|
6
|
+
export const MAX_SESSION_DATA_BYTES = 4096;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { type ClaviaOptions } from "./options.js";
|
|
2
|
+
import { type CurrentSession } from "./session.js";
|
|
3
|
+
/** How long a sign-in may take between the redirect and the callback, in seconds. */
|
|
4
|
+
export declare const SIGN_IN_ATTEMPT_LIFETIME = 600;
|
|
5
|
+
/** Clavia for an application signing people in, as a backend for frontend. */
|
|
6
|
+
export interface Clavia {
|
|
7
|
+
/**
|
|
8
|
+
* Serves the routes under `routes.base` (`/auth` by default), Fetch API `Request` to `Response`:
|
|
9
|
+
*
|
|
10
|
+
* - `GET {base}/sign-in?return_to=/path` sends the browser to the issuer. A `return_to` that is not a local
|
|
11
|
+
* path is refused (`400`); without one, the person lands on `/`.
|
|
12
|
+
* - `GET {base}/callback` completes the sign-in and sends the browser to its `return_to`, or answers the
|
|
13
|
+
* `signInFailed` page.
|
|
14
|
+
* - `POST {base}/sign-out`, from a form of the application's own pages, ends the session, gives its refresh
|
|
15
|
+
* token back and sends the browser to the issuer to end its session there, then to `signedOutPath`. A request
|
|
16
|
+
* whose `Origin` is not `appUrl`'s is refused (`403`), and changes nothing; browsers send `Origin` on every
|
|
17
|
+
* `POST`. There is no `GET` sign-out: an image tag on any site could fire one.
|
|
18
|
+
*
|
|
19
|
+
* Any other request answers `404` (`405` for another method on a route), so an application can mount
|
|
20
|
+
* `handle` on `{base}/*` alone and leave everything else to its own routes.
|
|
21
|
+
*/
|
|
22
|
+
handle(request: Request): Promise<Response>;
|
|
23
|
+
/**
|
|
24
|
+
* The person signed in on `request`, from its session cookie, or `null`: no cookie, a session ended, past its
|
|
25
|
+
* absolute lifetime, or unused for longer than its idle lifetime. Never a token.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```ts
|
|
29
|
+
* const session = await clavia.session(request);
|
|
30
|
+
* if (session === null) {
|
|
31
|
+
* return Response.redirect(new URL("/auth/sign-in?return_to=/reports", request.url), 303);
|
|
32
|
+
* }
|
|
33
|
+
* return new Response(`Hello, ${session.person.name ?? session.person.sub}`);
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
session(request: Request): Promise<CurrentSession | null>;
|
|
37
|
+
/**
|
|
38
|
+
* The session's access token, to call the API it is for, refreshed first when it expires within a minute.
|
|
39
|
+
* Server-side only: never send it to the browser.
|
|
40
|
+
*
|
|
41
|
+
* A refresh happens under the session's lock, across processes, after reading the session again, so
|
|
42
|
+
* requests in parallel make one refresh and take its tokens: Clavia spends a refresh token on every use.
|
|
43
|
+
* `null` when there is no session, or when the issuer refuses the refresh token (the session then ends, and
|
|
44
|
+
* the person signs in again). Throws a `SignInRefused` (`provider_error`, `unreachable`) when the refresh
|
|
45
|
+
* fails otherwise; the session is kept, since its refresh token was not spent.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```ts
|
|
49
|
+
* const token = await clavia.accessToken(request);
|
|
50
|
+
* if (token === null) {
|
|
51
|
+
* return Response.redirect(new URL("/auth/sign-in", request.url), 303);
|
|
52
|
+
* }
|
|
53
|
+
* const reports = await fetch("https://reports.example.com/api", { headers: { Authorization: `Bearer ${token}` } });
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
accessToken(request: Request): Promise<string | null>;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Clavia for an application that signs people in with an OpenID Connect issuer, as a backend for frontend
|
|
60
|
+
* (clavia's `docs/design/sdks.md` §5.1): the code flow with PKCE, pushed authorization requests whenever the
|
|
61
|
+
* issuer offers them, the ID token checked, the person read from userinfo, and a session kept on the server
|
|
62
|
+
* behind a 256-bit handle in one cookie. The tokens never reach the browser.
|
|
63
|
+
*
|
|
64
|
+
* Every option is checked here: a mistake throws now, not at the first sign-in. Server-side only: it refuses to
|
|
65
|
+
* be made in a browser.
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* ```ts
|
|
69
|
+
* import { createClavia, memoryAttemptStore, memorySessionStore } from "@clavia-auth/core";
|
|
70
|
+
*
|
|
71
|
+
* const production = process.env.NODE_ENV === "production";
|
|
72
|
+
* const clavia = createClavia({
|
|
73
|
+
* issuer: "https://auth.example.com",
|
|
74
|
+
* clientId: process.env.CLAVIA_CLIENT_ID!,
|
|
75
|
+
* clientSecret: process.env.CLAVIA_CLIENT_SECRET!,
|
|
76
|
+
* appUrl: "https://reports.example.com",
|
|
77
|
+
* sessionKey: process.env.CLAVIA_SESSION_KEY!,
|
|
78
|
+
* sessions: memorySessionStore({ production }),
|
|
79
|
+
* attempts: memoryAttemptStore({ production }),
|
|
80
|
+
* });
|
|
81
|
+
*
|
|
82
|
+
* // any server speaking the Fetch API: Bun, Deno, Hono, a Next.js route handler
|
|
83
|
+
* export default { fetch: (request: Request) => clavia.handle(request) };
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
export declare function createClavia(options: ClaviaOptions): Clavia;
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import * as oauth from "oauth4webapi";
|
|
2
|
+
import { handleDigest, newHandle } from "../session/handle.js";
|
|
3
|
+
import { openAttempt, sealAttempt, sealSession, SessionKeys } from "../session/sealing.js";
|
|
4
|
+
import { refuseInBrowser } from "../urls.js";
|
|
5
|
+
import { cookieNames, equalInConstantTime, readCookie, setCookie } from "./cookies.js";
|
|
6
|
+
import { settings } from "./options.js";
|
|
7
|
+
import { Provider } from "./provider.js";
|
|
8
|
+
import { SignInRefused } from "./refused.js";
|
|
9
|
+
import { isLocalPath } from "./return-to.js";
|
|
10
|
+
import { Sessions } from "./session.js";
|
|
11
|
+
import { signOut } from "./sign-out.js";
|
|
12
|
+
/** How long a sign-in may take between the redirect and the callback, in seconds. */
|
|
13
|
+
export const SIGN_IN_ATTEMPT_LIFETIME = 600;
|
|
14
|
+
/** The routes under `routes.base`, and the one method each answers. */
|
|
15
|
+
const ROUTES = {
|
|
16
|
+
"sign-in": "GET",
|
|
17
|
+
callback: "GET",
|
|
18
|
+
"sign-out": "POST",
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Clavia for an application that signs people in with an OpenID Connect issuer, as a backend for frontend
|
|
22
|
+
* (clavia's `docs/design/sdks.md` §5.1): the code flow with PKCE, pushed authorization requests whenever the
|
|
23
|
+
* issuer offers them, the ID token checked, the person read from userinfo, and a session kept on the server
|
|
24
|
+
* behind a 256-bit handle in one cookie. The tokens never reach the browser.
|
|
25
|
+
*
|
|
26
|
+
* Every option is checked here: a mistake throws now, not at the first sign-in. Server-side only: it refuses to
|
|
27
|
+
* be made in a browser.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```ts
|
|
31
|
+
* import { createClavia, memoryAttemptStore, memorySessionStore } from "@clavia-auth/core";
|
|
32
|
+
*
|
|
33
|
+
* const production = process.env.NODE_ENV === "production";
|
|
34
|
+
* const clavia = createClavia({
|
|
35
|
+
* issuer: "https://auth.example.com",
|
|
36
|
+
* clientId: process.env.CLAVIA_CLIENT_ID!,
|
|
37
|
+
* clientSecret: process.env.CLAVIA_CLIENT_SECRET!,
|
|
38
|
+
* appUrl: "https://reports.example.com",
|
|
39
|
+
* sessionKey: process.env.CLAVIA_SESSION_KEY!,
|
|
40
|
+
* sessions: memorySessionStore({ production }),
|
|
41
|
+
* attempts: memoryAttemptStore({ production }),
|
|
42
|
+
* });
|
|
43
|
+
*
|
|
44
|
+
* // any server speaking the Fetch API: Bun, Deno, Hono, a Next.js route handler
|
|
45
|
+
* export default { fetch: (request: Request) => clavia.handle(request) };
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
export function createClavia(options) {
|
|
49
|
+
refuseInBrowser("createClavia");
|
|
50
|
+
const config = settings(options);
|
|
51
|
+
const provider = new Provider(config);
|
|
52
|
+
const cookies = cookieNames(config.secureCookies);
|
|
53
|
+
let keys = null;
|
|
54
|
+
const sessionKeys = () => (keys ??= SessionKeys.from(config.sessionKeys));
|
|
55
|
+
const sessions = new Sessions(config, provider, sessionKeys, cookies.session);
|
|
56
|
+
const failed = async (error, request, headers) => {
|
|
57
|
+
const page = (await config.signInFailed?.(error, request)) ??
|
|
58
|
+
new Response("Sign-in failed.", {
|
|
59
|
+
status: error.status,
|
|
60
|
+
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
|
61
|
+
});
|
|
62
|
+
const response = new Response(page.body, page);
|
|
63
|
+
for (const [name, value] of headers) {
|
|
64
|
+
response.headers.append(name, value);
|
|
65
|
+
}
|
|
66
|
+
response.headers.set("Cache-Control", "no-store");
|
|
67
|
+
return response;
|
|
68
|
+
};
|
|
69
|
+
const signIn = async (request, url) => {
|
|
70
|
+
const returnTo = url.searchParams.get("return_to") ?? "/";
|
|
71
|
+
if (!isLocalPath(returnTo)) {
|
|
72
|
+
return new Response("return_to is not a local path.", {
|
|
73
|
+
status: 400,
|
|
74
|
+
headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" },
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
const attempt = {
|
|
78
|
+
state: oauth.generateRandomState(),
|
|
79
|
+
nonce: oauth.generateRandomNonce(),
|
|
80
|
+
codeVerifier: oauth.generateRandomCodeVerifier(),
|
|
81
|
+
returnTo,
|
|
82
|
+
acrValues: null,
|
|
83
|
+
dpopKey: null,
|
|
84
|
+
};
|
|
85
|
+
let location;
|
|
86
|
+
try {
|
|
87
|
+
location = await provider.authorizationUrl(attempt);
|
|
88
|
+
await config.attempts.put(await sealAttempt(await sessionKeys(), attempt), attempt.state, SIGN_IN_ATTEMPT_LIFETIME);
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
if (error instanceof SignInRefused) {
|
|
92
|
+
return failed(error, request, new Headers());
|
|
93
|
+
}
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
return redirect(location, [
|
|
97
|
+
setCookie(cookies.attempt, attempt.state, SIGN_IN_ATTEMPT_LIFETIME, config.secureCookies),
|
|
98
|
+
]);
|
|
99
|
+
};
|
|
100
|
+
const callback = async (request, url) => {
|
|
101
|
+
// The attempt cookie goes, whatever happens.
|
|
102
|
+
const clear = new Headers({ "Set-Cookie": setCookie(cookies.attempt, "", 0, config.secureCookies) });
|
|
103
|
+
try {
|
|
104
|
+
const attempt = await claim(request, url);
|
|
105
|
+
const redeemed = await provider.redeem(url, attempt);
|
|
106
|
+
const decision = await config.onSignedIn?.(redeemed.person, redeemed.claims);
|
|
107
|
+
if (decision === false) {
|
|
108
|
+
throw new SignInRefused("access_denied");
|
|
109
|
+
}
|
|
110
|
+
const data = decision === undefined ? null : decision.data;
|
|
111
|
+
const now = config.clock.now();
|
|
112
|
+
const session = {
|
|
113
|
+
person: redeemed.person,
|
|
114
|
+
sid: typeof redeemed.claims.sid === "string" ? redeemed.claims.sid : null,
|
|
115
|
+
tokens: {
|
|
116
|
+
accessToken: redeemed.accessToken,
|
|
117
|
+
accessTokenExpiresAt: now + (redeemed.expiresIn ?? 0) * 1000,
|
|
118
|
+
refreshToken: redeemed.refreshToken,
|
|
119
|
+
idToken: redeemed.idToken,
|
|
120
|
+
scopes: (redeemed.scope ?? config.scopes.join(" ")).split(" ").filter((scope) => scope !== ""),
|
|
121
|
+
dpopKey: null,
|
|
122
|
+
},
|
|
123
|
+
createdAt: now,
|
|
124
|
+
expiresAt: now + config.absoluteLifetime * 1000,
|
|
125
|
+
lastSeenAt: now,
|
|
126
|
+
data,
|
|
127
|
+
};
|
|
128
|
+
// A new handle at every sign-in, never one the browser brought (§7, *A session is fixed by nobody*).
|
|
129
|
+
const handle = newHandle();
|
|
130
|
+
const key = await handleDigest(handle);
|
|
131
|
+
await config.sessions.create(key, await sealSession(await sessionKeys(), key, session), config.idleLifetime, {
|
|
132
|
+
sid: session.sid,
|
|
133
|
+
sub: session.person.sub,
|
|
134
|
+
});
|
|
135
|
+
return redirect(new URL(attempt.returnTo, config.appUrl), [
|
|
136
|
+
clear.get("Set-Cookie") ?? "",
|
|
137
|
+
setCookie(cookies.session, handle, config.absoluteLifetime, config.secureCookies),
|
|
138
|
+
]);
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
if (error instanceof SignInRefused) {
|
|
142
|
+
return failed(error, request, clear);
|
|
143
|
+
}
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
/** The attempt this callback belongs to, taken once: the state must be the browser's own (RFC 9700 §4.7). */
|
|
148
|
+
const claim = async (request, url) => {
|
|
149
|
+
const state = url.searchParams.get("state");
|
|
150
|
+
const expected = readCookie(request, cookies.attempt);
|
|
151
|
+
if (state === null || expected === null || state === "" || !equalInConstantTime(state, expected)) {
|
|
152
|
+
throw new SignInRefused("unknown_attempt");
|
|
153
|
+
}
|
|
154
|
+
const sealed = await config.attempts.take(state);
|
|
155
|
+
const attempt = sealed === null ? null : await openAttempt(await sessionKeys(), state, sealed);
|
|
156
|
+
if (attempt === null) {
|
|
157
|
+
throw new SignInRefused("unknown_attempt");
|
|
158
|
+
}
|
|
159
|
+
return attempt;
|
|
160
|
+
};
|
|
161
|
+
return {
|
|
162
|
+
async handle(request) {
|
|
163
|
+
const url = new URL(request.url);
|
|
164
|
+
const route = url.pathname.startsWith(`${config.base}/`) ? url.pathname.slice(config.base.length + 1) : null;
|
|
165
|
+
// Own keys only: `/auth/constructor` is no route.
|
|
166
|
+
const method = route !== null && Object.hasOwn(ROUTES, route) ? ROUTES[route] : undefined;
|
|
167
|
+
if (route === null || method === undefined) {
|
|
168
|
+
return new Response("Not found.", { status: 404 });
|
|
169
|
+
}
|
|
170
|
+
if (request.method !== method) {
|
|
171
|
+
return new Response("Method not allowed.", { status: 405, headers: { Allow: method } });
|
|
172
|
+
}
|
|
173
|
+
if (route === "sign-out") {
|
|
174
|
+
return signOut(request, { config, provider, cookies, sessionKeys });
|
|
175
|
+
}
|
|
176
|
+
return route === "sign-in" ? signIn(request, url) : callback(request, url);
|
|
177
|
+
},
|
|
178
|
+
session: (request) => sessions.session(request),
|
|
179
|
+
accessToken: (request) => sessions.accessToken(request),
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
function redirect(location, cookies) {
|
|
183
|
+
const headers = new Headers({ Location: location.href, "Cache-Control": "no-store" });
|
|
184
|
+
for (const cookie of cookies) {
|
|
185
|
+
if (cookie !== "") {
|
|
186
|
+
headers.append("Set-Cookie", cookie);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return new Response(null, { status: 303, headers });
|
|
190
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface CookieNames {
|
|
2
|
+
readonly attempt: string;
|
|
3
|
+
readonly session: string;
|
|
4
|
+
}
|
|
5
|
+
export declare function cookieNames(secure: boolean): CookieNames;
|
|
6
|
+
/** A `Set-Cookie` value; `maxAge` 0 deletes the cookie. */
|
|
7
|
+
export declare function setCookie(name: string, value: string, maxAge: number, secure: boolean): string;
|
|
8
|
+
/** The value of cookie `name` in a request, or `null`. */
|
|
9
|
+
export declare function readCookie(request: Request, name: string): string | null;
|
|
10
|
+
/** Whether two strings are equal, in a time that does not depend on where they differ. */
|
|
11
|
+
export declare function equalInConstantTime(a: string, b: string): boolean;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// The two cookies (clavia's docs/design/sdks.md §2, *Cookies*): `__Host-` (Secure, Path=/, no Domain), HttpOnly,
|
|
2
|
+
// SameSite=Lax. Over http://localhost in development, the same without the prefix and Secure.
|
|
3
|
+
export function cookieNames(secure) {
|
|
4
|
+
return secure
|
|
5
|
+
? { attempt: "__Host-clavia_tx", session: "__Host-clavia_session" }
|
|
6
|
+
: { attempt: "clavia_tx", session: "clavia_session" };
|
|
7
|
+
}
|
|
8
|
+
/** A `Set-Cookie` value; `maxAge` 0 deletes the cookie. */
|
|
9
|
+
export function setCookie(name, value, maxAge, secure) {
|
|
10
|
+
return [
|
|
11
|
+
`${name}=${value}`,
|
|
12
|
+
"Path=/",
|
|
13
|
+
`Max-Age=${String(Math.max(0, Math.floor(maxAge)))}`,
|
|
14
|
+
"HttpOnly",
|
|
15
|
+
"SameSite=Lax",
|
|
16
|
+
...(secure ? ["Secure"] : []),
|
|
17
|
+
].join("; ");
|
|
18
|
+
}
|
|
19
|
+
/** The value of cookie `name` in a request, or `null`. */
|
|
20
|
+
export function readCookie(request, name) {
|
|
21
|
+
const header = request.headers.get("Cookie");
|
|
22
|
+
if (header === null) {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
for (const part of header.split(";")) {
|
|
26
|
+
const at = part.indexOf("=");
|
|
27
|
+
if (at !== -1 && part.slice(0, at).trim() === name) {
|
|
28
|
+
return part.slice(at + 1).trim();
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
/** Whether two strings are equal, in a time that does not depend on where they differ. */
|
|
34
|
+
export function equalInConstantTime(a, b) {
|
|
35
|
+
const left = new TextEncoder().encode(a);
|
|
36
|
+
const right = new TextEncoder().encode(b);
|
|
37
|
+
let difference = left.length ^ right.length;
|
|
38
|
+
for (let i = 0; i < left.length; i += 1) {
|
|
39
|
+
difference |= (left[i] ?? 0) ^ (right[i % Math.max(1, right.length)] ?? 0);
|
|
40
|
+
}
|
|
41
|
+
return difference === 0;
|
|
42
|
+
}
|