@clavia-auth/core 0.0.0-stage → 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 +76 -0
- package/LICENSE +29 -0
- package/README.md +63 -2
- package/dist/clock.d.ts +16 -0
- package/dist/clock.js +2 -0
- package/dist/encoding.d.ts +4 -0
- package/dist/encoding.js +21 -0
- package/dist/errors.d.ts +21 -0
- package/dist/errors.js +6 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +26 -0
- package/dist/management/call.d.ts +27 -0
- package/dist/management/call.js +48 -0
- package/dist/management/client.d.ts +62 -0
- package/dist/management/client.js +113 -0
- package/dist/management/error.d.ts +75 -0
- package/dist/management/error.js +114 -0
- package/dist/management/generated/operations.d.ts +585 -0
- package/dist/management/generated/operations.js +333 -0
- package/dist/management/generated/paths.d.ts +5348 -0
- package/dist/management/generated/paths.js +3 -0
- package/dist/management/index.d.ts +38 -0
- package/dist/management/index.js +24 -0
- package/dist/management/token.d.ts +30 -0
- package/dist/management/token.js +112 -0
- 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 +94 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@clavia-auth/core` are written here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the package follows
|
|
5
|
+
[Semantic Versioning](https://semver.org/spec/v2.0.0.html) with a version of its own. Each release states
|
|
6
|
+
the Clavia release it is generated from and tested against.
|
|
7
|
+
|
|
8
|
+
## [Unreleased]
|
|
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
|
+
|
|
53
|
+
## [0.1.0] - 2026-11-28
|
|
54
|
+
|
|
55
|
+
The first release: the package, and a client for Clavia's Management API. Generated from the Management API
|
|
56
|
+
of Clavia 0.6.1, and tested against Clavia 0.6.1 and `edge`. Node.js 22.12 or later, or any runtime with
|
|
57
|
+
`fetch` (Bun, Deno, workers); server-side only.
|
|
58
|
+
|
|
59
|
+
### Added
|
|
60
|
+
|
|
61
|
+
- `@clavia-auth/core/management`: a typed client for the Management API of Clavia 0.6.1, one method per
|
|
62
|
+
operation (`users.create`, `clients.rotateSecret`), generated from its OpenAPI document by
|
|
63
|
+
`openapi-typescript` and `openapi-fetch`.
|
|
64
|
+
- The client's own access token, by the client credentials grant: kept until a minute before it expires,
|
|
65
|
+
fetched once at a time, and renewed once when the API answers `401`.
|
|
66
|
+
- `ManagementError`, the API's RFC 9457 problem document (`status`, `type`, `title`, `detail`, `errors[]`),
|
|
67
|
+
with `Retry-After` on a `429`; `ClaviaError`, the union of the SDK's errors.
|
|
68
|
+
|
|
69
|
+
### Security
|
|
70
|
+
|
|
71
|
+
- A path parameter that is empty or a dot-segment (`.`, `..`) is refused before anything is sent, so it
|
|
72
|
+
cannot reach another resource than the one the method names.
|
|
73
|
+
|
|
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
|
|
76
|
+
[0.1.0]: https://github.com/clavia-auth/clavia-js-core/releases/tag/v0.1.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026, Phayne Limited (https://phayne.io)
|
|
4
|
+
All rights reserved.
|
|
5
|
+
|
|
6
|
+
Redistribution and use in source and binary forms, with or without
|
|
7
|
+
modification, are permitted provided that the following conditions are met:
|
|
8
|
+
|
|
9
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
10
|
+
list of conditions and the following disclaimer.
|
|
11
|
+
|
|
12
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
13
|
+
this list of conditions and the following disclaimer in the documentation
|
|
14
|
+
and/or other materials provided with the distribution.
|
|
15
|
+
|
|
16
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
17
|
+
contributors may be used to endorse or promote products derived from
|
|
18
|
+
this software without specific prior written permission.
|
|
19
|
+
|
|
20
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
21
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
22
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
23
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
24
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
25
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
26
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
27
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
28
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
29
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,64 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Clavia JS core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@clavia-auth/core` · [npm](https://www.npmjs.com/package/@clavia-auth/core)
|
|
4
|
+
|
|
5
|
+
The framework-free TypeScript core of the Clavia SDKs, on the Fetch API, Web Crypto and Promises. The SDKs are designed in clavia's `docs/design/sdks.md` ([clavia#224](https://github.com/clavia-auth/clavia/issues/224)); the first entry point is here, the rest follows.
|
|
6
|
+
|
|
7
|
+
## The Management API
|
|
8
|
+
|
|
9
|
+
`@clavia-auth/core/management` is a typed client for Clavia's Management API, generated from the OpenAPI document of a stated Clavia release (0.6.1 today, `CONTRACT_RELEASE`), with its own access token by the client credentials grant.
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @clavia-auth/core
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createManagementClient, ManagementError } from "@clavia-auth/core/management";
|
|
17
|
+
|
|
18
|
+
const clavia = createManagementClient({
|
|
19
|
+
issuer: "https://auth.example.com",
|
|
20
|
+
baseUrl: "https://management.example.com/api/v1",
|
|
21
|
+
audience: "https://management.example.com/api/v1/",
|
|
22
|
+
clientId: process.env.CLAVIA_MANAGEMENT_CLIENT_ID!,
|
|
23
|
+
clientSecret: process.env.CLAVIA_MANAGEMENT_CLIENT_SECRET!,
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const user = await clavia.users.create({ email: "ada@example.com", name: "Ada" });
|
|
27
|
+
const page = await clavia.users.list({ q: "ada", per_page: 20 });
|
|
28
|
+
await clavia.users.update(user.id, { name: "Ada Lovelace" });
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
- **Options.** `baseUrl` and `audience` are taken as given, never worked out from the issuer: an operator can rename the audience (`CLAVIA_MANAGEMENT_API_IDENTIFIER`). The client must be granted on the Management API; `scopes` narrows what it asks for, `clientAuthentication` is `client_secret_basic` (the default) or `client_secret_post`, as registered.
|
|
32
|
+
- **Operations.** One method per `operationId`, under its tag, without the tag's noun: `createUser` is `users.create`, `listUserSessions` is `users.listSessions`, `rotateClientSecret` is `clients.rotateSecret`. The arguments are the path parameters in the order of the path, then the body, then the query, then `{ signal }`. A JSON answer resolves as the contract types it, a `204` as `undefined`, bytes (a logo, an export) as a `Blob`. The contract's schemas are `ManagementSchemas["User"]`.
|
|
33
|
+
- **The token** is kept until a minute before it expires and fetched once at a time per client: make one client per process. A `401` takes a new token and sends the call again, once; nothing else is retried, and no redirect is followed.
|
|
34
|
+
- **Errors.** A refusal rejects with a `ManagementError`: the RFC 9457 problem document (`status`, `type`, `title`, `detail`, `errors[]` naming each field or parameter at fault), `retryAfter` (seconds) on a `429`, the `WWW-Authenticate` `challenge` of a refused token, and `_tag: "ManagementError"`. With no answer at all, `status` is `null`.
|
|
35
|
+
- **Server-side only**: the client holds a secret, and refuses to be made in a browser. It runs wherever `fetch` does: Node.js 22.12 and later, Bun, Deno, workers.
|
|
36
|
+
|
|
37
|
+
## What comes next
|
|
38
|
+
|
|
39
|
+
- **Discovery**: everything configured from the issuer's metadata (OpenID Connect Discovery, RFC 8414).
|
|
40
|
+
- **Sign-in for a backend**: the authorization code flow with PKCE, pushed authorization requests (RFC 9126), the ID token checked.
|
|
41
|
+
- **Sessions and refresh**: refresh tokens rotate with no grace period on Clavia, so refreshes are serialised; the session store and the lock are interfaces an application or an adapter provides.
|
|
42
|
+
- **Token checks for an API**: JWT access tokens (RFC 9068), introspection (RFC 7662), DPoP (RFC 9449).
|
|
43
|
+
- **Back-channel logout** (OpenID Connect Back-Channel Logout 1.0) and step-up (RFC 9470).
|
|
44
|
+
- **Errors** as a closed, typed set (a discriminated union on `_tag`), so adapters map them one to one.
|
|
45
|
+
|
|
46
|
+
Every SDK follows the standards only, configures itself from the issuer, and depends on nothing specific to Clavia, so it can be certified with the OpenID Foundation's relying-party tests.
|
|
47
|
+
|
|
48
|
+
## The Clavia SDKs
|
|
49
|
+
|
|
50
|
+
| Repository | Package | For |
|
|
51
|
+
| ------------------------------------------------------------------- | --------------------- | ------------------------------------------------------------ |
|
|
52
|
+
| [clavia-js-core](https://github.com/clavia-auth/clavia-js-core) | `@clavia-auth/core` | Any JavaScript or TypeScript backend; the base of the others |
|
|
53
|
+
| [clavia-js-next](https://github.com/clavia-auth/clavia-js-next) | `@clavia-auth/next` | Next.js App Router applications |
|
|
54
|
+
| [clavia-js-effect](https://github.com/clavia-auth/clavia-js-effect) | `@clavia-auth/effect` | Effect applications |
|
|
55
|
+
|
|
56
|
+
[Clavia](https://github.com/clavia-auth/clavia) is an open-source OAuth 2.1 / OpenID Connect authorization server.
|
|
57
|
+
|
|
58
|
+
## Contributing
|
|
59
|
+
|
|
60
|
+
Work is planned on the [Clavia board](https://github.com/orgs/clavia-auth/projects/1). [CONTRIBUTING.md](CONTRIBUTING.md) explains how, and [SECURITY.md](SECURITY.md) how to report a vulnerability.
|
|
61
|
+
|
|
62
|
+
## Licence
|
|
63
|
+
|
|
64
|
+
BSD 3-Clause, see [LICENSE](LICENSE).
|
package/dist/clock.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The time, as the SDK reads it: a port, so a test can move it instead of waiting.
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* ```ts
|
|
6
|
+
* let now = Date.parse("2026-11-28T12:00:00Z");
|
|
7
|
+
* const clock: Clock = { now: () => now };
|
|
8
|
+
* now += 60_000; // a minute later
|
|
9
|
+
* ```
|
|
10
|
+
*/
|
|
11
|
+
export interface Clock {
|
|
12
|
+
/** Milliseconds since the Unix epoch, as `Date.now()`. */
|
|
13
|
+
now(): number;
|
|
14
|
+
}
|
|
15
|
+
/** The system clock. */
|
|
16
|
+
export declare const systemClock: Clock;
|
package/dist/clock.js
ADDED
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
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { ManagementError } from "./management/error.js";
|
|
2
|
+
import { SignInRefused } from "./sign-in/refused.js";
|
|
3
|
+
/**
|
|
4
|
+
* Every error the SDK raises on purpose: a closed set, each member with a `_tag`, so an adapter maps them one
|
|
5
|
+
* to one and a `switch` over `_tag` is exhaustive. It grows with the SDK (token checks, step-up).
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* function describe(error: ClaviaError): string {
|
|
10
|
+
* switch (error._tag) {
|
|
11
|
+
* case "ManagementError":
|
|
12
|
+
* return `The Management API answered ${error.status ?? "nothing"}`;
|
|
13
|
+
* case "SignInRefused":
|
|
14
|
+
* return `The sign-in was refused: ${error.reason}`;
|
|
15
|
+
* }
|
|
16
|
+
* }
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export type ClaviaError = ManagementError | SignInRefused;
|
|
20
|
+
/** Whether `value` is one of the SDK's own errors ({@link ClaviaError}). */
|
|
21
|
+
export declare function isClaviaError(value: unknown): value is ClaviaError;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { ManagementError } from "./management/error.js";
|
|
2
|
+
import { SignInRefused } from "./sign-in/refused.js";
|
|
3
|
+
/** Whether `value` is one of the SDK's own errors ({@link ClaviaError}). */
|
|
4
|
+
export function isClaviaError(value) {
|
|
5
|
+
return value instanceof ManagementError || value instanceof SignInRefused;
|
|
6
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@clavia-auth/core`: the framework-free core of the Clavia SDKs, on the Fetch API, Web Crypto and Promises.
|
|
3
|
+
*
|
|
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`).
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* import { isClaviaError } from "@clavia-auth/core";
|
|
12
|
+
*
|
|
13
|
+
* if (isClaviaError(error) && error._tag === "SignInRefused") {
|
|
14
|
+
* // …
|
|
15
|
+
* }
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* @module
|
|
19
|
+
*/
|
|
20
|
+
export { type ClaviaError, isClaviaError } from "./errors.js";
|
|
21
|
+
export { type Clock, systemClock } from "./clock.js";
|
|
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
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@clavia-auth/core`: the framework-free core of the Clavia SDKs, on the Fetch API, Web Crypto and Promises.
|
|
3
|
+
*
|
|
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`).
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* import { isClaviaError } from "@clavia-auth/core";
|
|
12
|
+
*
|
|
13
|
+
* if (isClaviaError(error) && error._tag === "SignInRefused") {
|
|
14
|
+
* // …
|
|
15
|
+
* }
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* @module
|
|
19
|
+
*/
|
|
20
|
+
export { isClaviaError } from "./errors.js";
|
|
21
|
+
export { systemClock } from "./clock.js";
|
|
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";
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** What every operation takes last. */
|
|
2
|
+
export interface CallOptions {
|
|
3
|
+
/** Aborts the call; the promise then rejects with a {@link ManagementError} whose `status` is `null`. */
|
|
4
|
+
readonly signal?: AbortSignal | undefined;
|
|
5
|
+
}
|
|
6
|
+
/** A body the API takes as bytes or text in one content type (an `application/x-ndjson` import). */
|
|
7
|
+
export type BinaryBody = Blob | ArrayBuffer | Uint8Array | string;
|
|
8
|
+
type Answer<T> = () => Promise<{
|
|
9
|
+
data?: T;
|
|
10
|
+
error?: unknown;
|
|
11
|
+
response: Response;
|
|
12
|
+
}>;
|
|
13
|
+
/**
|
|
14
|
+
* A path parameter, refused when it would not name one resource: empty, or a dot-segment (`.`, `..`) that URL
|
|
15
|
+
* parsing removes (RFC 3986 §5.2.4), so `users.endSession(id, "..")` would reach `DELETE …/sessions` and end
|
|
16
|
+
* every session. Everything else is percent-encoded into its one segment.
|
|
17
|
+
*/
|
|
18
|
+
export declare function segment(value: string): string;
|
|
19
|
+
/** A JSON answer. */
|
|
20
|
+
export declare function json<T>(answer: Answer<T>): Promise<T>;
|
|
21
|
+
/** An answer with no body (`204`, or a `202` that says nothing). */
|
|
22
|
+
export declare function empty(answer: Answer<unknown>): Promise<void>;
|
|
23
|
+
/** An answer whose body is bytes (a logo, an export): read it with `.text()`, `.arrayBuffer()` or `.stream()`. */
|
|
24
|
+
export declare function blob(answer: Answer<unknown>): Promise<Blob>;
|
|
25
|
+
/** A body sent as it is: bytes, or text in the operation's content type. */
|
|
26
|
+
export declare function passThrough(body: unknown): BodyInit;
|
|
27
|
+
export {};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// What the generated operations call (generated/operations.ts): the answer of a successful call, read as
|
|
2
|
+
// the contract says. A refusal never reaches here: the transport (client.ts) throws it as a ManagementError.
|
|
3
|
+
import { ManagementError, unreachable } from "./error.js";
|
|
4
|
+
/**
|
|
5
|
+
* A path parameter, refused when it would not name one resource: empty, or a dot-segment (`.`, `..`) that URL
|
|
6
|
+
* parsing removes (RFC 3986 §5.2.4), so `users.endSession(id, "..")` would reach `DELETE …/sessions` and end
|
|
7
|
+
* every session. Everything else is percent-encoded into its one segment.
|
|
8
|
+
*/
|
|
9
|
+
export function segment(value) {
|
|
10
|
+
if (typeof value !== "string" || value === "" || value === "." || value === "..") {
|
|
11
|
+
throw new TypeError(`A path parameter must name one resource: ${JSON.stringify(value)} does not.`);
|
|
12
|
+
}
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
/** A JSON answer. */
|
|
16
|
+
export async function json(answer) {
|
|
17
|
+
const { data } = await settle(answer);
|
|
18
|
+
if (data === undefined) {
|
|
19
|
+
throw new ManagementError({ status: null, title: "The Management API answered with no body" });
|
|
20
|
+
}
|
|
21
|
+
return data;
|
|
22
|
+
}
|
|
23
|
+
/** An answer with no body (`204`, or a `202` that says nothing). */
|
|
24
|
+
export async function empty(answer) {
|
|
25
|
+
await settle(answer);
|
|
26
|
+
}
|
|
27
|
+
/** An answer whose body is bytes (a logo, an export): read it with `.text()`, `.arrayBuffer()` or `.stream()`. */
|
|
28
|
+
export async function blob(answer) {
|
|
29
|
+
const { data } = await settle(answer);
|
|
30
|
+
if (!(data instanceof Blob)) {
|
|
31
|
+
throw new ManagementError({ status: null, title: "The Management API answered with no body" });
|
|
32
|
+
}
|
|
33
|
+
return data;
|
|
34
|
+
}
|
|
35
|
+
/** A body sent as it is: bytes, or text in the operation's content type. */
|
|
36
|
+
export function passThrough(body) {
|
|
37
|
+
return body;
|
|
38
|
+
}
|
|
39
|
+
async function settle(answer) {
|
|
40
|
+
// A refused argument (segment) rejects as the TypeError it is, before anything is sent.
|
|
41
|
+
const pending = answer();
|
|
42
|
+
try {
|
|
43
|
+
return await pending;
|
|
44
|
+
}
|
|
45
|
+
catch (cause) {
|
|
46
|
+
throw unreachable(cause);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { type Clock } from "../clock.js";
|
|
2
|
+
import { type ManagementOperations, type ManagementScope } from "./generated/operations.js";
|
|
3
|
+
/** How to reach the Management API, and as whom. */
|
|
4
|
+
export interface ManagementClientOptions {
|
|
5
|
+
/** The issuer, whose discovery document names the token endpoint: `https://auth.example.com`. */
|
|
6
|
+
readonly issuer: string | URL;
|
|
7
|
+
/**
|
|
8
|
+
* The Management API's URL, as given, never worked out from the issuer: `https://management.example.com/api/v1`.
|
|
9
|
+
* It ends with `/api/v1`.
|
|
10
|
+
*/
|
|
11
|
+
readonly baseUrl: string | URL;
|
|
12
|
+
/**
|
|
13
|
+
* The Management API's identifier, as given: `https://management.example.com/api/v1/` by default, with
|
|
14
|
+
* its slash, and whatever `CLAVIA_MANAGEMENT_API_IDENTIFIER` renames it to.
|
|
15
|
+
*/
|
|
16
|
+
readonly audience: string;
|
|
17
|
+
/** A confidential client granted on the Management API. */
|
|
18
|
+
readonly clientId: string;
|
|
19
|
+
readonly clientSecret: string;
|
|
20
|
+
/** As the client is registered: `client_secret_basic` (the default) or `client_secret_post`. */
|
|
21
|
+
readonly clientAuthentication?: "client_secret_basic" | "client_secret_post";
|
|
22
|
+
/** The scopes to ask for; by default none is named, and the client grant's own apply. */
|
|
23
|
+
readonly scopes?: readonly ManagementScope[];
|
|
24
|
+
/** The Fetch API to call with; the global `fetch` by default. */
|
|
25
|
+
readonly fetch?: typeof fetch;
|
|
26
|
+
/** The time, to tell when the token is due; the system clock by default. */
|
|
27
|
+
readonly clock?: Clock;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The Management API, one method per operation of the contract, grouped by tag: `users.create`,
|
|
31
|
+
* `clients.rotateSecret`. Every method resolves with what the API answered, or rejects with a
|
|
32
|
+
* {@link ManagementError}.
|
|
33
|
+
*/
|
|
34
|
+
export type ManagementClient = ManagementOperations;
|
|
35
|
+
/**
|
|
36
|
+
* A Management API client acting as a machine client, with its own access token by the client credentials
|
|
37
|
+
* grant (docs/design/sdks.md §5.7).
|
|
38
|
+
*
|
|
39
|
+
* The token is kept until a minute before it expires, and fetched once at a time per client: make one client
|
|
40
|
+
* per process and share it. A `401` takes a new token and the call is sent again, once; nothing else is
|
|
41
|
+
* retried. A call never follows a redirect.
|
|
42
|
+
*
|
|
43
|
+
* Server-side only: the client holds a secret, and refuses to be made in a browser.
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```ts
|
|
47
|
+
* import { createManagementClient, ManagementError } from "@clavia-auth/core/management";
|
|
48
|
+
*
|
|
49
|
+
* const clavia = createManagementClient({
|
|
50
|
+
* issuer: "https://auth.example.com",
|
|
51
|
+
* baseUrl: "https://management.example.com/api/v1",
|
|
52
|
+
* audience: "https://management.example.com/api/v1/",
|
|
53
|
+
* clientId: process.env.CLAVIA_MANAGEMENT_CLIENT_ID!,
|
|
54
|
+
* clientSecret: process.env.CLAVIA_MANAGEMENT_CLIENT_SECRET!,
|
|
55
|
+
* });
|
|
56
|
+
*
|
|
57
|
+
* const user = await clavia.users.create({ email: "ada@example.com", name: "Ada" });
|
|
58
|
+
* const page = await clavia.users.list({ q: "ada", per_page: 20 });
|
|
59
|
+
* await clavia.users.update(user.id, { name: "Ada Lovelace" });
|
|
60
|
+
* ```
|
|
61
|
+
*/
|
|
62
|
+
export declare function createManagementClient(options: ManagementClientOptions): ManagementClient;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import createClient from "openapi-fetch";
|
|
2
|
+
import { systemClock } from "../clock.js";
|
|
3
|
+
import { refuseInBrowser, secureUrl } from "../urls.js";
|
|
4
|
+
import { refusal, unreachable } from "./error.js";
|
|
5
|
+
import { managementOperations } from "./generated/operations.js";
|
|
6
|
+
import { ClientCredentials } from "./token.js";
|
|
7
|
+
/** Every path of the contract starts here; the base URL names it, as the Management API's own URL does. */
|
|
8
|
+
const API_PATH = "/api/v1";
|
|
9
|
+
/**
|
|
10
|
+
* A Management API client acting as a machine client, with its own access token by the client credentials
|
|
11
|
+
* grant (docs/design/sdks.md §5.7).
|
|
12
|
+
*
|
|
13
|
+
* The token is kept until a minute before it expires, and fetched once at a time per client: make one client
|
|
14
|
+
* per process and share it. A `401` takes a new token and the call is sent again, once; nothing else is
|
|
15
|
+
* retried. A call never follows a redirect.
|
|
16
|
+
*
|
|
17
|
+
* Server-side only: the client holds a secret, and refuses to be made in a browser.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```ts
|
|
21
|
+
* import { createManagementClient, ManagementError } from "@clavia-auth/core/management";
|
|
22
|
+
*
|
|
23
|
+
* const clavia = createManagementClient({
|
|
24
|
+
* issuer: "https://auth.example.com",
|
|
25
|
+
* baseUrl: "https://management.example.com/api/v1",
|
|
26
|
+
* audience: "https://management.example.com/api/v1/",
|
|
27
|
+
* clientId: process.env.CLAVIA_MANAGEMENT_CLIENT_ID!,
|
|
28
|
+
* clientSecret: process.env.CLAVIA_MANAGEMENT_CLIENT_SECRET!,
|
|
29
|
+
* });
|
|
30
|
+
*
|
|
31
|
+
* const user = await clavia.users.create({ email: "ada@example.com", name: "Ada" });
|
|
32
|
+
* const page = await clavia.users.list({ q: "ada", per_page: 20 });
|
|
33
|
+
* await clavia.users.update(user.id, { name: "Ada Lovelace" });
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
export function createManagementClient(options) {
|
|
37
|
+
refuseInBrowser("createManagementClient");
|
|
38
|
+
const issuer = secureUrl(options.issuer, "issuer");
|
|
39
|
+
const baseUrl = secureUrl(options.baseUrl, "baseUrl");
|
|
40
|
+
const path = baseUrl.pathname.replace(/\/+$/, "");
|
|
41
|
+
if (!path.endsWith(API_PATH) || baseUrl.search !== "" || baseUrl.hash !== "") {
|
|
42
|
+
throw new TypeError(`baseUrl is the Management API's URL, ending with ${API_PATH}: ${baseUrl.href} does not.`);
|
|
43
|
+
}
|
|
44
|
+
for (const [name, value] of [
|
|
45
|
+
["audience", options.audience],
|
|
46
|
+
["clientId", options.clientId],
|
|
47
|
+
["clientSecret", options.clientSecret],
|
|
48
|
+
]) {
|
|
49
|
+
if (typeof value !== "string" || value === "") {
|
|
50
|
+
throw new TypeError(`${name} is required.`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
54
|
+
const clock = options.clock ?? systemClock;
|
|
55
|
+
const credentials = new ClientCredentials({
|
|
56
|
+
issuer,
|
|
57
|
+
audience: options.audience,
|
|
58
|
+
clientId: options.clientId,
|
|
59
|
+
clientSecret: options.clientSecret,
|
|
60
|
+
clientAuthentication: options.clientAuthentication ?? "client_secret_basic",
|
|
61
|
+
scopes: options.scopes ?? [],
|
|
62
|
+
fetch: fetcher,
|
|
63
|
+
clock,
|
|
64
|
+
});
|
|
65
|
+
const send = async (request, token) => {
|
|
66
|
+
const headers = new Headers(request.headers);
|
|
67
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
68
|
+
headers.set("Accept", "application/json");
|
|
69
|
+
try {
|
|
70
|
+
return await fetcher(new Request(request, { headers, redirect: "manual" }));
|
|
71
|
+
}
|
|
72
|
+
catch (cause) {
|
|
73
|
+
throw unreachable(cause);
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
const http = createClient({
|
|
77
|
+
baseUrl: baseUrl.origin + path.slice(0, -API_PATH.length),
|
|
78
|
+
fetch: async (request) => {
|
|
79
|
+
// Kept to send again: a body can be read once.
|
|
80
|
+
const again = request.clone();
|
|
81
|
+
const token = await credentials.token();
|
|
82
|
+
let response = await send(request, token);
|
|
83
|
+
if (response.status === 401 && expired(response)) {
|
|
84
|
+
credentials.forget(token);
|
|
85
|
+
response = await send(again, await credentials.token());
|
|
86
|
+
}
|
|
87
|
+
if (!response.ok) {
|
|
88
|
+
throw refusal(response, await body(response), clock.now());
|
|
89
|
+
}
|
|
90
|
+
return response;
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
return managementOperations(http);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* A `401` a new token may cure: the token was refused (`invalid_token`), or none was taken. One that asks
|
|
97
|
+
* for a stronger sign-in (`insufficient_user_authentication`, RFC 9470 §3) is not: a machine token never
|
|
98
|
+
* gets one.
|
|
99
|
+
*/
|
|
100
|
+
function expired(response) {
|
|
101
|
+
const challenge = response.headers.get("WWW-Authenticate") ?? "";
|
|
102
|
+
const error = /(?:^|[\s,])error="?([\w-]+)"?/.exec(challenge)?.[1];
|
|
103
|
+
return error === undefined || error === "invalid_token";
|
|
104
|
+
}
|
|
105
|
+
async function body(response) {
|
|
106
|
+
try {
|
|
107
|
+
const text = await response.text();
|
|
108
|
+
return text === "" ? null : JSON.parse(text);
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One violation a problem document lists: where (`pointer` into the body, RFC 6901, or the `parameter` at
|
|
3
|
+
* fault) and why.
|
|
4
|
+
*/
|
|
5
|
+
export interface ProblemDetail {
|
|
6
|
+
readonly detail: string;
|
|
7
|
+
readonly pointer?: string;
|
|
8
|
+
readonly parameter?: string;
|
|
9
|
+
}
|
|
10
|
+
/** What a {@link ManagementError} is made from. */
|
|
11
|
+
export interface ManagementErrorInit {
|
|
12
|
+
readonly status: number | null;
|
|
13
|
+
readonly type?: string;
|
|
14
|
+
readonly title: string;
|
|
15
|
+
readonly detail?: string;
|
|
16
|
+
readonly errors?: readonly ProblemDetail[];
|
|
17
|
+
readonly retryAfter?: number | null;
|
|
18
|
+
readonly challenge?: string | null;
|
|
19
|
+
readonly cause?: unknown;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The Management API refused a call, or could not be reached.
|
|
23
|
+
*
|
|
24
|
+
* A refusal carries the RFC 9457 problem document the API answered with (`status`, `type`, `title`, `detail`,
|
|
25
|
+
* and `errors[]` saying which field or parameter is at fault). A refused token (RFC 6750 §3) carries its
|
|
26
|
+
* `error` code as `title` and its `WWW-Authenticate` challenge, so a `401` with
|
|
27
|
+
* `insufficient_user_authentication` can be told apart (RFC 9470 §3). A `429` or a `503` carries its
|
|
28
|
+
* `Retry-After`, in seconds. When no answer came at all (the network, a timeout, an answer that cannot be
|
|
29
|
+
* read), `status` is `null`.
|
|
30
|
+
*
|
|
31
|
+
* The client never retries on its own, but a `401` once with a new token: a `429` is the caller's to wait out.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```ts
|
|
35
|
+
* try {
|
|
36
|
+
* await clavia.users.create({ email });
|
|
37
|
+
* } catch (error) {
|
|
38
|
+
* if (error instanceof ManagementError && error.status === 409) {
|
|
39
|
+
* // the address is taken
|
|
40
|
+
* } else if (error instanceof ManagementError && error.retryAfter !== null) {
|
|
41
|
+
* // wait error.retryAfter seconds
|
|
42
|
+
* } else {
|
|
43
|
+
* throw error;
|
|
44
|
+
* }
|
|
45
|
+
* }
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
export declare class ManagementError extends Error {
|
|
49
|
+
/** The tag of the error, for a `switch` over {@link ClaviaError}. */
|
|
50
|
+
readonly _tag: "ManagementError";
|
|
51
|
+
readonly name = "ManagementError";
|
|
52
|
+
/** The HTTP status, or `null` when no answer came. */
|
|
53
|
+
readonly status: number | null;
|
|
54
|
+
/** The problem type: `about:blank` when the answer named none (RFC 9457 §4.2.1). */
|
|
55
|
+
readonly type: string;
|
|
56
|
+
/** The problem's title, or the bearer error code (`invalid_token`) for a refused token. */
|
|
57
|
+
readonly title: string;
|
|
58
|
+
/** What went wrong, for a person to read, when the API said. */
|
|
59
|
+
readonly detail: string | undefined;
|
|
60
|
+
/** Which fields or parameters were refused, and why. */
|
|
61
|
+
readonly errors: readonly ProblemDetail[];
|
|
62
|
+
/** For a `429` or a `503`: the seconds to wait before trying again, when the API said. */
|
|
63
|
+
readonly retryAfter: number | null;
|
|
64
|
+
/** The `WWW-Authenticate` challenge of a refused token (RFC 6750 §3), if any. */
|
|
65
|
+
readonly challenge: string | null;
|
|
66
|
+
constructor(init: ManagementErrorInit);
|
|
67
|
+
}
|
|
68
|
+
/** Whether `value` is a {@link ManagementError}. */
|
|
69
|
+
export declare function isManagementError(value: unknown): value is ManagementError;
|
|
70
|
+
/** The refusal an answer carries: its problem document, or its bearer error, or only its status. */
|
|
71
|
+
export declare function refusal(response: Response, body: unknown, now: number): ManagementError;
|
|
72
|
+
/** No answer, or none that could be read. */
|
|
73
|
+
export declare function unreachable(cause: unknown): ManagementError;
|
|
74
|
+
/** `Retry-After` in seconds: delay-seconds, or an HTTP-date from `now` (RFC 9110 §10.2.3). */
|
|
75
|
+
export declare function retryAfter(headers: Headers, now: number): number | null;
|