@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
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,49 @@ the Clavia release it is generated from and tested against.
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.2.0] - 2026-11-29
|
|
11
|
+
|
|
12
|
+
Sign-in for a backend, on the core alone: an application signs people in with Clavia, keeps their session on
|
|
13
|
+
the server, and refreshes its access token without ever presenting a refresh token twice, across every process
|
|
14
|
+
it runs. Tested against Clavia 0.6.1 and `edge`, with a real browser, by an example application running as two
|
|
15
|
+
processes. The Management API client is unchanged, still generated from Clavia 0.6.1.
|
|
16
|
+
|
|
17
|
+
### Added
|
|
18
|
+
|
|
19
|
+
- **Sign-in** (`createClavia`, and `handle(request)` on the Fetch API's `Request` and `Response`):
|
|
20
|
+
- `GET /auth/sign-in` sends the browser to the issuer, with PKCE (S256), `state` and `nonce`, through a pushed
|
|
21
|
+
authorization request (RFC 9126) whenever the issuer offers one. Only a local `return_to` is accepted.
|
|
22
|
+
- `GET /auth/callback` completes it: honoured once, and only for the browser that started it. It checks RFC
|
|
23
|
+
9207's `iss` when advertised, the ID token by the issuer's keys (OpenID Connect Core §3.1.3.7), and that
|
|
24
|
+
userinfo names the same person.
|
|
25
|
+
- `POST /auth/sign-out` ends the session, gives its refresh token back (RFC 7009, best effort), and sends the
|
|
26
|
+
browser to the issuer to sign out there too, then to `signedOutPath` (a new option, `/` by default, to
|
|
27
|
+
register at Clavia as a post-logout redirect URI).
|
|
28
|
+
- **The session** (`clavia.session(request)`): the person, their scopes and the application's own data, never a
|
|
29
|
+
token. A session ends past its absolute lifetime, or after its idle lifetime unused.
|
|
30
|
+
- **The access token** (`clavia.accessToken(request)`), refreshed within a minute of its expiry, under the
|
|
31
|
+
session's lock: requests in parallel make one refresh between them. A refresh token the issuer refuses ends
|
|
32
|
+
the session (`null`); any other failure throws and keeps it.
|
|
33
|
+
- **Stores** for sessions and sign-in attempts, behind two ports (`SessionStore`, `AttemptStore`) an application
|
|
34
|
+
can implement for its own database:
|
|
35
|
+
- `@clavia-auth/core/redis`: `redisSessionStore` and `redisAttemptStore`, for production, on `ioredis` (an
|
|
36
|
+
optional peer dependency), with a standalone Redis or Sentinel 7.0 or later;
|
|
37
|
+
- `memorySessionStore` and `memoryAttemptStore`, for tests and a single development process.
|
|
38
|
+
- **Errors**: `SignInRefused` (`unknown_attempt`, `access_denied`, `provider_error`, `unreachable`) joins the
|
|
39
|
+
`ClaviaError` union. `signInFailed` replaces the default failure page.
|
|
40
|
+
- **`@clavia-auth/core/testing`**, for applications and the framework packages:
|
|
41
|
+
- `SessionStoreContract` and `AttemptStoreContract`, the cases an application's own store must pass, for any
|
|
42
|
+
test runner;
|
|
43
|
+
- `fakeProvider`, an OpenID Connect provider for tests: it issues real signed tokens, grants and counts
|
|
44
|
+
refreshes, serves revocation, and can be told to answer wrongly.
|
|
45
|
+
|
|
46
|
+
### Security
|
|
47
|
+
|
|
48
|
+
- Sessions live on the server, sealed with AES-256-GCM. The browser holds only a 256-bit handle, in a `__Host-`
|
|
49
|
+
cookie; the store keeps the handle's SHA-256, never the handle, so a leaked store opens no session.
|
|
50
|
+
- The issuer's error descriptions never reach a page. A sign-out from another origin is refused and changes
|
|
51
|
+
nothing.
|
|
52
|
+
|
|
10
53
|
## [0.1.0] - 2026-11-28
|
|
11
54
|
|
|
12
55
|
The first release: the package, and a client for Clavia's Management API. Generated from the Management API
|
|
@@ -28,5 +71,6 @@ of Clavia 0.6.1, and tested against Clavia 0.6.1 and `edge`. Node.js 22.12 or la
|
|
|
28
71
|
- A path parameter that is empty or a dot-segment (`.`, `..`) is refused before anything is sent, so it
|
|
29
72
|
cannot reach another resource than the one the method names.
|
|
30
73
|
|
|
31
|
-
[Unreleased]: https://github.com/clavia-auth/clavia-js-core/compare/v0.
|
|
74
|
+
[Unreleased]: https://github.com/clavia-auth/clavia-js-core/compare/v0.2.0...HEAD
|
|
75
|
+
[0.2.0]: https://github.com/clavia-auth/clavia-js-core/compare/v0.1.0...v0.2.0
|
|
32
76
|
[0.1.0]: https://github.com/clavia-auth/clavia-js-core/releases/tag/v0.1.0
|
package/dist/encoding.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// base64url (RFC 4648 §5, no padding) on Web standards: no Buffer, so it runs wherever fetch does.
|
|
2
|
+
export function toBase64Url(bytes) {
|
|
3
|
+
let binary = "";
|
|
4
|
+
for (const byte of bytes) {
|
|
5
|
+
binary += String.fromCharCode(byte);
|
|
6
|
+
}
|
|
7
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
8
|
+
}
|
|
9
|
+
/** The bytes, or `null` when `value` is not base64url. */
|
|
10
|
+
export function fromBase64Url(value) {
|
|
11
|
+
if (!/^[A-Za-z0-9_-]*$/.test(value) || value.length % 4 === 1) {
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
const binary = atob(value.replace(/-/g, "+").replace(/_/g, "/"));
|
|
15
|
+
const bytes = new Uint8Array(binary.length);
|
|
16
|
+
for (let i = 0; i < binary.length; i += 1) {
|
|
17
|
+
bytes[i] = binary.charCodeAt(i);
|
|
18
|
+
}
|
|
19
|
+
return bytes;
|
|
20
|
+
}
|
|
21
|
+
export const utf8 = new TextEncoder();
|
package/dist/errors.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { ManagementError } from "./management/error.js";
|
|
2
|
+
import { SignInRefused } from "./sign-in/refused.js";
|
|
2
3
|
/**
|
|
3
4
|
* Every error the SDK raises on purpose: a closed set, each member with a `_tag`, so an adapter maps them one
|
|
4
|
-
* to one and a `switch` over `_tag` is exhaustive. It grows with the SDK (
|
|
5
|
-
* the Management API's refusal alone.
|
|
5
|
+
* to one and a `switch` over `_tag` is exhaustive. It grows with the SDK (token checks, step-up).
|
|
6
6
|
*
|
|
7
7
|
* @example
|
|
8
8
|
* ```ts
|
|
@@ -10,10 +10,12 @@ import { ManagementError } from "./management/error.js";
|
|
|
10
10
|
* switch (error._tag) {
|
|
11
11
|
* case "ManagementError":
|
|
12
12
|
* return `The Management API answered ${error.status ?? "nothing"}`;
|
|
13
|
+
* case "SignInRefused":
|
|
14
|
+
* return `The sign-in was refused: ${error.reason}`;
|
|
13
15
|
* }
|
|
14
16
|
* }
|
|
15
17
|
* ```
|
|
16
18
|
*/
|
|
17
|
-
export type ClaviaError = ManagementError;
|
|
19
|
+
export type ClaviaError = ManagementError | SignInRefused;
|
|
18
20
|
/** Whether `value` is one of the SDK's own errors ({@link ClaviaError}). */
|
|
19
21
|
export declare function isClaviaError(value: unknown): value is ClaviaError;
|
package/dist/errors.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ManagementError } from "./management/error.js";
|
|
2
|
+
import { SignInRefused } from "./sign-in/refused.js";
|
|
2
3
|
/** Whether `value` is one of the SDK's own errors ({@link ClaviaError}). */
|
|
3
4
|
export function isClaviaError(value) {
|
|
4
|
-
return value instanceof ManagementError;
|
|
5
|
+
return value instanceof ManagementError || value instanceof SignInRefused;
|
|
5
6
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `@clavia-auth/core`: the framework-free core of the Clavia SDKs, on the Fetch API, Web Crypto and Promises.
|
|
3
3
|
*
|
|
4
|
-
* The Management API client is `@clavia-auth/core/management
|
|
5
|
-
* (
|
|
4
|
+
* The Management API client is `@clavia-auth/core/management`. Here: sign-in as a backend for frontend
|
|
5
|
+
* (`createClavia`), the errors, the clock, and the ports sessions and sign-in attempts are kept through, with
|
|
6
|
+
* in-memory stores for tests and development; their contracts and a fake provider are
|
|
7
|
+
* `@clavia-auth/core/testing`. Sessions in use, refresh and sign-out follow (clavia's `docs/design/sdks.md`).
|
|
6
8
|
*
|
|
7
9
|
* @example
|
|
8
10
|
* ```ts
|
|
9
11
|
* import { isClaviaError } from "@clavia-auth/core";
|
|
10
12
|
*
|
|
11
|
-
* if (isClaviaError(error) && error._tag === "
|
|
13
|
+
* if (isClaviaError(error) && error._tag === "SignInRefused") {
|
|
12
14
|
* // …
|
|
13
15
|
* }
|
|
14
16
|
* ```
|
|
@@ -18,3 +20,10 @@
|
|
|
18
20
|
export { type ClaviaError, isClaviaError } from "./errors.js";
|
|
19
21
|
export { type Clock, systemClock } from "./clock.js";
|
|
20
22
|
export { ManagementError } from "./management/error.js";
|
|
23
|
+
export type { AttemptStore, HandleDigest, Sealed, SessionIndex, SessionStore } from "./session/ports.js";
|
|
24
|
+
export { type JsonValue, MAX_SESSION_DATA_BYTES, type Person, type Session, type SignInAttempt, type TokenSet, } from "./session/values.js";
|
|
25
|
+
export { memoryAttemptStore, memorySessionStore, type MemoryStoreOptions } from "./session/memory.js";
|
|
26
|
+
export { type Clavia, createClavia, SIGN_IN_ATTEMPT_LIFETIME } from "./sign-in/clavia.js";
|
|
27
|
+
export type { ClaviaOptions, SignInDecision } from "./sign-in/options.js";
|
|
28
|
+
export type { CurrentSession } from "./sign-in/session.js";
|
|
29
|
+
export { isSignInRefused, SignInRefused, type SignInRefusal } from "./sign-in/refused.js";
|
package/dist/index.js
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `@clavia-auth/core`: the framework-free core of the Clavia SDKs, on the Fetch API, Web Crypto and Promises.
|
|
3
3
|
*
|
|
4
|
-
* The Management API client is `@clavia-auth/core/management
|
|
5
|
-
* (
|
|
4
|
+
* The Management API client is `@clavia-auth/core/management`. Here: sign-in as a backend for frontend
|
|
5
|
+
* (`createClavia`), the errors, the clock, and the ports sessions and sign-in attempts are kept through, with
|
|
6
|
+
* in-memory stores for tests and development; their contracts and a fake provider are
|
|
7
|
+
* `@clavia-auth/core/testing`. Sessions in use, refresh and sign-out follow (clavia's `docs/design/sdks.md`).
|
|
6
8
|
*
|
|
7
9
|
* @example
|
|
8
10
|
* ```ts
|
|
9
11
|
* import { isClaviaError } from "@clavia-auth/core";
|
|
10
12
|
*
|
|
11
|
-
* if (isClaviaError(error) && error._tag === "
|
|
13
|
+
* if (isClaviaError(error) && error._tag === "SignInRefused") {
|
|
12
14
|
* // …
|
|
13
15
|
* }
|
|
14
16
|
* ```
|
|
@@ -18,3 +20,7 @@
|
|
|
18
20
|
export { isClaviaError } from "./errors.js";
|
|
19
21
|
export { systemClock } from "./clock.js";
|
|
20
22
|
export { ManagementError } from "./management/error.js";
|
|
23
|
+
export { MAX_SESSION_DATA_BYTES, } from "./session/values.js";
|
|
24
|
+
export { memoryAttemptStore, memorySessionStore } from "./session/memory.js";
|
|
25
|
+
export { createClavia, SIGN_IN_ATTEMPT_LIFETIME } from "./sign-in/clavia.js";
|
|
26
|
+
export { isSignInRefused, SignInRefused } from "./sign-in/refused.js";
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import createClient from "openapi-fetch";
|
|
2
2
|
import { systemClock } from "../clock.js";
|
|
3
|
+
import { refuseInBrowser, secureUrl } from "../urls.js";
|
|
3
4
|
import { refusal, unreachable } from "./error.js";
|
|
4
5
|
import { managementOperations } from "./generated/operations.js";
|
|
5
6
|
import { ClientCredentials } from "./token.js";
|
|
@@ -33,9 +34,7 @@ const API_PATH = "/api/v1";
|
|
|
33
34
|
* ```
|
|
34
35
|
*/
|
|
35
36
|
export function createManagementClient(options) {
|
|
36
|
-
|
|
37
|
-
throw new TypeError("createManagementClient holds a client secret and runs on a server only, not in a browser.");
|
|
38
|
-
}
|
|
37
|
+
refuseInBrowser("createManagementClient");
|
|
39
38
|
const issuer = secureUrl(options.issuer, "issuer");
|
|
40
39
|
const baseUrl = secureUrl(options.baseUrl, "baseUrl");
|
|
41
40
|
const path = baseUrl.pathname.replace(/\/+$/, "");
|
|
@@ -112,21 +111,3 @@ async function body(response) {
|
|
|
112
111
|
return null;
|
|
113
112
|
}
|
|
114
113
|
}
|
|
115
|
-
/** https, or http to a loopback address in development; never credentials or a fragment in it. */
|
|
116
|
-
function secureUrl(value, name) {
|
|
117
|
-
let url;
|
|
118
|
-
try {
|
|
119
|
-
url = new URL(value);
|
|
120
|
-
}
|
|
121
|
-
catch {
|
|
122
|
-
throw new TypeError(`${name} is not a URL.`);
|
|
123
|
-
}
|
|
124
|
-
const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
125
|
-
if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
|
|
126
|
-
throw new TypeError(`${name} must be https (plain http only to localhost): ${url.origin}.`);
|
|
127
|
-
}
|
|
128
|
-
if (url.username !== "" || url.password !== "" || url.hash !== "") {
|
|
129
|
-
throw new TypeError(`${name} must carry no credentials and no fragment.`);
|
|
130
|
-
}
|
|
131
|
-
return url;
|
|
132
|
-
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@clavia-auth/core/redis`: sessions and sign-in attempts in Redis, shared by every process of an application,
|
|
3
|
+
* with the lock that serialises refreshes across them. On any client with `ioredis`'s `call()`; `ioredis` is an
|
|
4
|
+
* optional peer dependency, needed only by an application that imports this entry point.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```ts
|
|
8
|
+
* import { Redis } from "ioredis";
|
|
9
|
+
* import { redisAttemptStore, redisSessionStore } from "@clavia-auth/core/redis";
|
|
10
|
+
*
|
|
11
|
+
* const redis = new Redis(process.env.REDIS_URL!);
|
|
12
|
+
* const sessions = redisSessionStore(redis);
|
|
13
|
+
* const attempts = redisAttemptStore(redis);
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* @module
|
|
17
|
+
*/
|
|
18
|
+
export { type RedisClient, redisAttemptStore, redisSessionStore, type RedisStoreOptions } from "./stores.js";
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@clavia-auth/core/redis`: sessions and sign-in attempts in Redis, shared by every process of an application,
|
|
3
|
+
* with the lock that serialises refreshes across them. On any client with `ioredis`'s `call()`; `ioredis` is an
|
|
4
|
+
* optional peer dependency, needed only by an application that imports this entry point.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```ts
|
|
8
|
+
* import { Redis } from "ioredis";
|
|
9
|
+
* import { redisAttemptStore, redisSessionStore } from "@clavia-auth/core/redis";
|
|
10
|
+
*
|
|
11
|
+
* const redis = new Redis(process.env.REDIS_URL!);
|
|
12
|
+
* const sessions = redisSessionStore(redis);
|
|
13
|
+
* const attempts = redisAttemptStore(redis);
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* @module
|
|
17
|
+
*/
|
|
18
|
+
export { redisAttemptStore, redisSessionStore } from "./stores.js";
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { AttemptStore, SessionStore } from "../session/ports.js";
|
|
2
|
+
/**
|
|
3
|
+
* The one method of a Redis client the stores use, as `ioredis` has it: a command and its arguments. Typed here
|
|
4
|
+
* rather than imported, so the package carries no Node.js types; an `ioredis` client fits as it is.
|
|
5
|
+
*/
|
|
6
|
+
export interface RedisClient {
|
|
7
|
+
call(command: string, ...args: (string | number)[]): Promise<unknown>;
|
|
8
|
+
}
|
|
9
|
+
/** What the Redis stores take. */
|
|
10
|
+
export interface RedisStoreOptions {
|
|
11
|
+
/** Prepended to every key, to share a Redis with other data: `clavia:` by default. */
|
|
12
|
+
readonly prefix?: string;
|
|
13
|
+
/** How long a session's lock is held at most, in milliseconds: 10 seconds by default, far longer than a refresh. */
|
|
14
|
+
readonly lockLease?: number;
|
|
15
|
+
/**
|
|
16
|
+
* How long a caller waits for another's lock before giving up, in milliseconds: 15 seconds by default, longer
|
|
17
|
+
* than a lease, so a lock left by a process that died is waited out rather than reported.
|
|
18
|
+
*/
|
|
19
|
+
readonly lockWait?: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Sessions in Redis, shared by every process of the application: the store to run in production.
|
|
23
|
+
*
|
|
24
|
+
* A session is kept under `{prefix}session:{digest of its handle}`, sealed, with two indexes (by `sid` and by
|
|
25
|
+
* `sub`, each by its SHA-256) for back-channel logout. `exclusively()` takes `{prefix}lock:{digest}` with
|
|
26
|
+
* `SET NX PX` and a random token, waits while another process holds it, and releases it with a script that
|
|
27
|
+
* checks the token; a process that dies holding it frees it when the lease ends.
|
|
28
|
+
*
|
|
29
|
+
* Needs a standalone Redis (or Sentinel) 7.0 or later; not a Cluster.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```ts
|
|
33
|
+
* import { Redis } from "ioredis";
|
|
34
|
+
* import { redisSessionStore } from "@clavia-auth/core/redis";
|
|
35
|
+
*
|
|
36
|
+
* const sessions = redisSessionStore(new Redis(process.env.REDIS_URL!));
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
export declare function redisSessionStore(redis: RedisClient, options?: RedisStoreOptions): SessionStore;
|
|
40
|
+
/**
|
|
41
|
+
* Sign-in attempts in Redis, under `{prefix}attempt:{state}`, each taken once (`GETDEL`, Redis 6.2 or later).
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```ts
|
|
45
|
+
* import { Redis } from "ioredis";
|
|
46
|
+
* import { redisAttemptStore } from "@clavia-auth/core/redis";
|
|
47
|
+
*
|
|
48
|
+
* const attempts = redisAttemptStore(new Redis(process.env.REDIS_URL!));
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
export declare function redisAttemptStore(redis: RedisClient, options?: Pick<RedisStoreOptions, "prefix">): AttemptStore;
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// Sessions and sign-in attempts in Redis (clavia's docs/design/sdks.md §2 *Refresh*, §4): the lock that
|
|
2
|
+
// serialises refreshes across processes, and the indexes back-channel logout ends sessions by. Taken from the
|
|
3
|
+
// dashboard's src/adapters/session/redis-session-store.ts. Every write that touches more than one key is a Lua
|
|
4
|
+
// script, so it is atomic; that needs a standalone Redis (or Sentinel) 7.0 or later, not a Cluster.
|
|
5
|
+
import { toBase64Url, utf8 } from "../encoding.js";
|
|
6
|
+
const DEFAULT_PREFIX = "clavia:";
|
|
7
|
+
const DEFAULT_LEASE = 10_000;
|
|
8
|
+
const DEFAULT_WAIT = 15_000;
|
|
9
|
+
// KEYS: the session, the set of its index keys, then each index. ARGV: the record, the TTL, the session's key.
|
|
10
|
+
// An index lives as long as its longest session: EXPIRE NX sets a first TTL, GT only ever extends it.
|
|
11
|
+
const CREATE = `
|
|
12
|
+
redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[2])
|
|
13
|
+
redis.call('DEL', KEYS[2])
|
|
14
|
+
for i = 3, #KEYS do
|
|
15
|
+
redis.call('SADD', KEYS[i], ARGV[3])
|
|
16
|
+
redis.call('EXPIRE', KEYS[i], ARGV[2], 'NX')
|
|
17
|
+
redis.call('EXPIRE', KEYS[i], ARGV[2], 'GT')
|
|
18
|
+
redis.call('SADD', KEYS[2], KEYS[i])
|
|
19
|
+
end
|
|
20
|
+
redis.call('EXPIRE', KEYS[2], ARGV[2])
|
|
21
|
+
return 1`;
|
|
22
|
+
// KEYS: the session, the set of its index keys. ARGV: the record, the TTL. Nothing when the session is gone (XX):
|
|
23
|
+
// a refresh that ends after a sign-out does not bring the session back.
|
|
24
|
+
const SAVE = `
|
|
25
|
+
if not redis.call('SET', KEYS[1], ARGV[1], 'XX', 'EX', ARGV[2]) then
|
|
26
|
+
return 0
|
|
27
|
+
end
|
|
28
|
+
redis.call('EXPIRE', KEYS[2], ARGV[2])
|
|
29
|
+
for _, index in ipairs(redis.call('SMEMBERS', KEYS[2])) do
|
|
30
|
+
redis.call('EXPIRE', index, ARGV[2], 'NX')
|
|
31
|
+
redis.call('EXPIRE', index, ARGV[2], 'GT')
|
|
32
|
+
end
|
|
33
|
+
return 1`;
|
|
34
|
+
// KEYS: the session, the set of its index keys. ARGV: the session's key. Returns the record, or nil.
|
|
35
|
+
const DESTROY = `
|
|
36
|
+
local record = redis.call('GET', KEYS[1])
|
|
37
|
+
redis.call('DEL', KEYS[1])
|
|
38
|
+
for _, index in ipairs(redis.call('SMEMBERS', KEYS[2])) do
|
|
39
|
+
redis.call('SREM', index, ARGV[1])
|
|
40
|
+
end
|
|
41
|
+
redis.call('DEL', KEYS[2])
|
|
42
|
+
return record`;
|
|
43
|
+
// KEYS: an index. ARGV: the prefix. Ends every session the index names, counting only those still there.
|
|
44
|
+
const DESTROY_INDEXED = `
|
|
45
|
+
local count = 0
|
|
46
|
+
for _, key in ipairs(redis.call('SMEMBERS', KEYS[1])) do
|
|
47
|
+
local indexes = ARGV[1] .. 'indexes:' .. key
|
|
48
|
+
count = count + redis.call('DEL', ARGV[1] .. 'session:' .. key)
|
|
49
|
+
for _, index in ipairs(redis.call('SMEMBERS', indexes)) do
|
|
50
|
+
redis.call('SREM', index, key)
|
|
51
|
+
end
|
|
52
|
+
redis.call('DEL', indexes)
|
|
53
|
+
end
|
|
54
|
+
redis.call('DEL', KEYS[1])
|
|
55
|
+
return count`;
|
|
56
|
+
// KEYS: the lock. ARGV: the holder's token. Releases the lock only for its holder: a lease that ran out may now
|
|
57
|
+
// be somebody else's.
|
|
58
|
+
const RELEASE = `
|
|
59
|
+
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
|
60
|
+
return redis.call('DEL', KEYS[1])
|
|
61
|
+
end
|
|
62
|
+
return 0`;
|
|
63
|
+
/**
|
|
64
|
+
* Sessions in Redis, shared by every process of the application: the store to run in production.
|
|
65
|
+
*
|
|
66
|
+
* A session is kept under `{prefix}session:{digest of its handle}`, sealed, with two indexes (by `sid` and by
|
|
67
|
+
* `sub`, each by its SHA-256) for back-channel logout. `exclusively()` takes `{prefix}lock:{digest}` with
|
|
68
|
+
* `SET NX PX` and a random token, waits while another process holds it, and releases it with a script that
|
|
69
|
+
* checks the token; a process that dies holding it frees it when the lease ends.
|
|
70
|
+
*
|
|
71
|
+
* Needs a standalone Redis (or Sentinel) 7.0 or later; not a Cluster.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```ts
|
|
75
|
+
* import { Redis } from "ioredis";
|
|
76
|
+
* import { redisSessionStore } from "@clavia-auth/core/redis";
|
|
77
|
+
*
|
|
78
|
+
* const sessions = redisSessionStore(new Redis(process.env.REDIS_URL!));
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
81
|
+
export function redisSessionStore(redis, options = {}) {
|
|
82
|
+
const prefix = options.prefix ?? DEFAULT_PREFIX;
|
|
83
|
+
const lease = positive(options.lockLease ?? DEFAULT_LEASE, "lockLease");
|
|
84
|
+
const wait = positive(options.lockWait ?? DEFAULT_WAIT, "lockWait");
|
|
85
|
+
const session = (key) => `${prefix}session:${key}`;
|
|
86
|
+
const indexes = (key) => `${prefix}indexes:${key}`;
|
|
87
|
+
const index = async (kind, value) => `${prefix}${kind}:${await sha256(value)}`;
|
|
88
|
+
return {
|
|
89
|
+
async create(key, record, ttl, { sid, sub }) {
|
|
90
|
+
const keys = [session(key), indexes(key), await index("sub", sub)];
|
|
91
|
+
if (sid !== null) {
|
|
92
|
+
keys.push(await index("sid", sid));
|
|
93
|
+
}
|
|
94
|
+
await redis.call("EVAL", CREATE, keys.length, ...keys, record, seconds(ttl), key);
|
|
95
|
+
},
|
|
96
|
+
async read(key) {
|
|
97
|
+
return text(await redis.call("GET", session(key)));
|
|
98
|
+
},
|
|
99
|
+
async save(key, record, ttl) {
|
|
100
|
+
await redis.call("EVAL", SAVE, 2, session(key), indexes(key), record, seconds(ttl));
|
|
101
|
+
},
|
|
102
|
+
async destroy(key) {
|
|
103
|
+
return text(await redis.call("EVAL", DESTROY, 2, session(key), indexes(key), key));
|
|
104
|
+
},
|
|
105
|
+
async destroyBySid(sid) {
|
|
106
|
+
return Number(await redis.call("EVAL", DESTROY_INDEXED, 1, await index("sid", sid), prefix));
|
|
107
|
+
},
|
|
108
|
+
async destroyBySubject(sub) {
|
|
109
|
+
return Number(await redis.call("EVAL", DESTROY_INDEXED, 1, await index("sub", sub), prefix));
|
|
110
|
+
},
|
|
111
|
+
async exclusively(key, work) {
|
|
112
|
+
const lock = `${prefix}lock:${key}`;
|
|
113
|
+
const token = toBase64Url(crypto.getRandomValues(new Uint8Array(16)));
|
|
114
|
+
const deadline = Date.now() + wait;
|
|
115
|
+
let pause = 10;
|
|
116
|
+
while ((await redis.call("SET", lock, token, "NX", "PX", lease)) !== "OK") {
|
|
117
|
+
if (Date.now() >= deadline) {
|
|
118
|
+
throw new Error(`The lock of a session was held by another caller for ${String(wait)} ms; nothing was done.`);
|
|
119
|
+
}
|
|
120
|
+
await sleep(pause);
|
|
121
|
+
pause = Math.min(pause * 2, 200);
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
return await work();
|
|
125
|
+
}
|
|
126
|
+
finally {
|
|
127
|
+
await redis.call("EVAL", RELEASE, 1, lock, token);
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Sign-in attempts in Redis, under `{prefix}attempt:{state}`, each taken once (`GETDEL`, Redis 6.2 or later).
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* ```ts
|
|
137
|
+
* import { Redis } from "ioredis";
|
|
138
|
+
* import { redisAttemptStore } from "@clavia-auth/core/redis";
|
|
139
|
+
*
|
|
140
|
+
* const attempts = redisAttemptStore(new Redis(process.env.REDIS_URL!));
|
|
141
|
+
* ```
|
|
142
|
+
*/
|
|
143
|
+
export function redisAttemptStore(redis, options = {}) {
|
|
144
|
+
const prefix = options.prefix ?? DEFAULT_PREFIX;
|
|
145
|
+
const attempt = (state) => `${prefix}attempt:${state}`;
|
|
146
|
+
return {
|
|
147
|
+
async put(record, state, ttl) {
|
|
148
|
+
await redis.call("SET", attempt(state), record, "EX", seconds(ttl));
|
|
149
|
+
},
|
|
150
|
+
async take(state) {
|
|
151
|
+
return text(await redis.call("GETDEL", attempt(state)));
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
async function sha256(value) {
|
|
156
|
+
return toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", utf8.encode(value))));
|
|
157
|
+
}
|
|
158
|
+
/** A TTL Redis takes: whole seconds, at least one. */
|
|
159
|
+
function seconds(ttl) {
|
|
160
|
+
return Math.max(1, Math.ceil(ttl));
|
|
161
|
+
}
|
|
162
|
+
function positive(value, name) {
|
|
163
|
+
if (!Number.isFinite(value) || value <= 0) {
|
|
164
|
+
throw new TypeError(`${name} must be a positive number of milliseconds.`);
|
|
165
|
+
}
|
|
166
|
+
return value;
|
|
167
|
+
}
|
|
168
|
+
/** A string reply, or `null`; a Buffer (a client set to return them) as its UTF-8 text. */
|
|
169
|
+
function text(reply) {
|
|
170
|
+
if (reply === null || reply === undefined) {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
if (typeof reply === "string") {
|
|
174
|
+
return reply;
|
|
175
|
+
}
|
|
176
|
+
if (reply instanceof Uint8Array) {
|
|
177
|
+
return new TextDecoder().decode(reply);
|
|
178
|
+
}
|
|
179
|
+
throw new TypeError("Redis answered with something that is not a string.");
|
|
180
|
+
}
|
|
181
|
+
function sleep(ms) {
|
|
182
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
183
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { HandleDigest } from "./ports.js";
|
|
2
|
+
/** A new handle for a browser to hold: 256 random bits, never one the browser brought. */
|
|
3
|
+
export declare function newHandle(): string;
|
|
4
|
+
/** Whether `value` is shaped as a handle: what a cookie brings is checked before anything is looked up. */
|
|
5
|
+
export declare function isHandle(value: string | null | undefined): value is string;
|
|
6
|
+
/** What a handle is kept under: its SHA-256, so the store never holds what opens a session. */
|
|
7
|
+
export declare function handleDigest(handle: string): Promise<HandleDigest>;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { fromBase64Url, toBase64Url, utf8 } from "../encoding.js";
|
|
2
|
+
/** A handle is 256 random bits, base64url: 43 characters. */
|
|
3
|
+
const HANDLE = /^[A-Za-z0-9_-]{43}$/;
|
|
4
|
+
/** A new handle for a browser to hold: 256 random bits, never one the browser brought. */
|
|
5
|
+
export function newHandle() {
|
|
6
|
+
return toBase64Url(crypto.getRandomValues(new Uint8Array(32)));
|
|
7
|
+
}
|
|
8
|
+
/** Whether `value` is shaped as a handle: what a cookie brings is checked before anything is looked up. */
|
|
9
|
+
export function isHandle(value) {
|
|
10
|
+
return typeof value === "string" && HANDLE.test(value) && fromBase64Url(value)?.length === 32;
|
|
11
|
+
}
|
|
12
|
+
/** What a handle is kept under: its SHA-256, so the store never holds what opens a session. */
|
|
13
|
+
export async function handleDigest(handle) {
|
|
14
|
+
return toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", utf8.encode(handle))));
|
|
15
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type Clock } from "../clock.js";
|
|
2
|
+
import type { AttemptStore, SessionStore } from "./ports.js";
|
|
3
|
+
/** What the in-memory stores take. */
|
|
4
|
+
export interface MemoryStoreOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Whether the application runs in production, where an in-memory store is refused: its sessions die with
|
|
7
|
+
* the process, and its lock serialises nothing across processes. The core reads no environment, so the
|
|
8
|
+
* adapter or the application says so (`process.env.NODE_ENV === "production"`).
|
|
9
|
+
*/
|
|
10
|
+
readonly production: boolean;
|
|
11
|
+
/** The time, for the TTLs; the system clock by default. */
|
|
12
|
+
readonly clock?: Clock;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Sessions kept in this process's memory, for tests and a single development process. Refused in production.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* const sessions = memorySessionStore({ production: process.env.NODE_ENV === "production" });
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export declare function memorySessionStore(options: MemoryStoreOptions): SessionStore;
|
|
23
|
+
/**
|
|
24
|
+
* Sign-in attempts kept in this process's memory, for tests and a single development process. Refused in
|
|
25
|
+
* production.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```ts
|
|
29
|
+
* const attempts = memoryAttemptStore({ production: process.env.NODE_ENV === "production" });
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export declare function memoryAttemptStore(options: MemoryStoreOptions): AttemptStore;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { systemClock } from "../clock.js";
|
|
2
|
+
/**
|
|
3
|
+
* Sessions kept in this process's memory, for tests and a single development process. Refused in production.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```ts
|
|
7
|
+
* const sessions = memorySessionStore({ production: process.env.NODE_ENV === "production" });
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
export function memorySessionStore(options) {
|
|
11
|
+
refuseInProduction(options, "memorySessionStore");
|
|
12
|
+
const clock = options.clock ?? systemClock;
|
|
13
|
+
const sessions = new Map();
|
|
14
|
+
const locks = new Map();
|
|
15
|
+
const live = (key) => {
|
|
16
|
+
const entry = sessions.get(key);
|
|
17
|
+
if (entry !== undefined && entry.until <= clock.now()) {
|
|
18
|
+
sessions.delete(key);
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
return entry;
|
|
22
|
+
};
|
|
23
|
+
const destroyWhere = (matches) => {
|
|
24
|
+
let count = 0;
|
|
25
|
+
for (const key of [...sessions.keys()]) {
|
|
26
|
+
const entry = live(key);
|
|
27
|
+
if (entry !== undefined && matches(entry.index)) {
|
|
28
|
+
sessions.delete(key);
|
|
29
|
+
count += 1;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return count;
|
|
33
|
+
};
|
|
34
|
+
return {
|
|
35
|
+
create(key, record, ttl, index) {
|
|
36
|
+
sessions.set(key, { record, until: clock.now() + ttl * 1000, index: { sid: index.sid, sub: index.sub } });
|
|
37
|
+
return Promise.resolve();
|
|
38
|
+
},
|
|
39
|
+
read(key) {
|
|
40
|
+
return Promise.resolve(live(key)?.record ?? null);
|
|
41
|
+
},
|
|
42
|
+
save(key, record, ttl) {
|
|
43
|
+
const entry = live(key);
|
|
44
|
+
if (entry !== undefined) {
|
|
45
|
+
sessions.set(key, { record, until: clock.now() + ttl * 1000, index: entry.index });
|
|
46
|
+
}
|
|
47
|
+
return Promise.resolve();
|
|
48
|
+
},
|
|
49
|
+
destroy(key) {
|
|
50
|
+
const entry = live(key);
|
|
51
|
+
sessions.delete(key);
|
|
52
|
+
return Promise.resolve(entry?.record ?? null);
|
|
53
|
+
},
|
|
54
|
+
destroyBySid(sid) {
|
|
55
|
+
return Promise.resolve(destroyWhere((index) => index.sid === sid));
|
|
56
|
+
},
|
|
57
|
+
destroyBySubject(sub) {
|
|
58
|
+
return Promise.resolve(destroyWhere((index) => index.sub === sub));
|
|
59
|
+
},
|
|
60
|
+
async exclusively(key, work) {
|
|
61
|
+
const before = locks.get(key) ?? Promise.resolve();
|
|
62
|
+
// `before` never rejects: it is the previous holder's settled run.
|
|
63
|
+
const run = before.then(() => work());
|
|
64
|
+
const settled = run.then(() => undefined, () => undefined);
|
|
65
|
+
locks.set(key, settled);
|
|
66
|
+
try {
|
|
67
|
+
return await run;
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
if (locks.get(key) === settled) {
|
|
71
|
+
locks.delete(key);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Sign-in attempts kept in this process's memory, for tests and a single development process. Refused in
|
|
79
|
+
* production.
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* ```ts
|
|
83
|
+
* const attempts = memoryAttemptStore({ production: process.env.NODE_ENV === "production" });
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
export function memoryAttemptStore(options) {
|
|
87
|
+
refuseInProduction(options, "memoryAttemptStore");
|
|
88
|
+
const clock = options.clock ?? systemClock;
|
|
89
|
+
const attempts = new Map();
|
|
90
|
+
return {
|
|
91
|
+
put(record, state, ttl) {
|
|
92
|
+
attempts.set(state, { record, until: clock.now() + ttl * 1000 });
|
|
93
|
+
return Promise.resolve();
|
|
94
|
+
},
|
|
95
|
+
take(state) {
|
|
96
|
+
const entry = attempts.get(state);
|
|
97
|
+
attempts.delete(state);
|
|
98
|
+
return Promise.resolve(entry !== undefined && entry.until > clock.now() ? entry.record : null);
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function refuseInProduction(options, name) {
|
|
103
|
+
if (options.production) {
|
|
104
|
+
throw new Error(`${name} keeps sessions in one process's memory, and is refused in production: use a shared store, such as Redis.`);
|
|
105
|
+
}
|
|
106
|
+
}
|