@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.
Files changed (47) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/dist/encoding.d.ts +4 -0
  3. package/dist/encoding.js +21 -0
  4. package/dist/errors.d.ts +5 -3
  5. package/dist/errors.js +2 -1
  6. package/dist/index.d.ts +12 -3
  7. package/dist/index.js +9 -3
  8. package/dist/management/client.js +2 -21
  9. package/dist/redis/index.d.ts +18 -0
  10. package/dist/redis/index.js +18 -0
  11. package/dist/redis/stores.d.ts +51 -0
  12. package/dist/redis/stores.js +183 -0
  13. package/dist/session/handle.d.ts +7 -0
  14. package/dist/session/handle.js +15 -0
  15. package/dist/session/memory.d.ts +32 -0
  16. package/dist/session/memory.js +106 -0
  17. package/dist/session/ports.d.ts +63 -0
  18. package/dist/session/ports.js +6 -0
  19. package/dist/session/sealing.d.ts +23 -0
  20. package/dist/session/sealing.js +130 -0
  21. package/dist/session/values.d.ts +60 -0
  22. package/dist/session/values.js +6 -0
  23. package/dist/sign-in/clavia.d.ts +86 -0
  24. package/dist/sign-in/clavia.js +190 -0
  25. package/dist/sign-in/cookies.d.ts +11 -0
  26. package/dist/sign-in/cookies.js +42 -0
  27. package/dist/sign-in/options.d.ts +95 -0
  28. package/dist/sign-in/options.js +79 -0
  29. package/dist/sign-in/provider.d.ts +57 -0
  30. package/dist/sign-in/provider.js +279 -0
  31. package/dist/sign-in/refused.d.ts +42 -0
  32. package/dist/sign-in/refused.js +49 -0
  33. package/dist/sign-in/return-to.d.ts +6 -0
  34. package/dist/sign-in/return-to.js +13 -0
  35. package/dist/sign-in/session.d.ts +23 -0
  36. package/dist/sign-in/session.js +136 -0
  37. package/dist/sign-in/sign-out.d.ts +18 -0
  38. package/dist/sign-in/sign-out.js +47 -0
  39. package/dist/testing/contracts.d.ts +43 -0
  40. package/dist/testing/contracts.js +198 -0
  41. package/dist/testing/fake-provider.d.ts +102 -0
  42. package/dist/testing/fake-provider.js +295 -0
  43. package/dist/testing/index.d.ts +20 -0
  44. package/dist/testing/index.js +20 -0
  45. package/dist/urls.d.ts +6 -0
  46. package/dist/urls.js +29 -0
  47. package/package.json +19 -1
@@ -0,0 +1,136 @@
1
+ // Using a session (clavia's docs/design/sdks.md §5.2): reading it, ending it when its time is up, and refreshing
2
+ // its access token under the session's lock (§2 *Refresh*, §7 *A refresh token is presented at most once*).
3
+ import { handleDigest, isHandle } from "../session/handle.js";
4
+ import { openSession, sealSession } from "../session/sealing.js";
5
+ import { readCookie } from "./cookies.js";
6
+ /** An access token this close to expiring is refreshed before it is handed out, in milliseconds. */
7
+ export const REFRESH_AHEAD_MS = 60_000;
8
+ /** `lastSeenAt` is written back at most this often, in milliseconds. */
9
+ export const TOUCH_INTERVAL_MS = 60_000;
10
+ /** The sessions of one `createClavia`. */
11
+ export class Sessions {
12
+ #config;
13
+ #provider;
14
+ #keys;
15
+ #cookie;
16
+ constructor(config, provider, keys, cookie) {
17
+ this.#config = config;
18
+ this.#provider = provider;
19
+ this.#keys = keys;
20
+ this.#cookie = cookie;
21
+ }
22
+ async session(request) {
23
+ const found = await this.#find(request);
24
+ if (found === null) {
25
+ return null;
26
+ }
27
+ const { person, tokens, data } = found.session;
28
+ return { person, scopes: tokens.scopes, data };
29
+ }
30
+ async accessToken(request) {
31
+ const found = await this.#find(request);
32
+ if (found === null) {
33
+ return null;
34
+ }
35
+ if (!this.#due(found.session)) {
36
+ return found.session.tokens.accessToken;
37
+ }
38
+ // Under the session's lock, across processes: read again, and refresh only if it is still due, so the
39
+ // requests that waited take the new tokens instead of spending the old refresh token.
40
+ return this.#config.sessions.exclusively(found.key, async () => {
41
+ const current = await this.#open(found.key);
42
+ if (current === null) {
43
+ return null;
44
+ }
45
+ if (!this.#due(current)) {
46
+ return current.tokens.accessToken;
47
+ }
48
+ if (current.tokens.refreshToken === null) {
49
+ await this.#config.sessions.destroy(found.key);
50
+ return null;
51
+ }
52
+ // Throws on anything but a refused refresh token: the token was not spent, so the session stays.
53
+ const refreshed = await this.#provider.refresh(current);
54
+ if (refreshed === null) {
55
+ await this.#config.sessions.destroy(found.key);
56
+ return null;
57
+ }
58
+ const now = this.#config.clock.now();
59
+ const session = {
60
+ ...current,
61
+ tokens: {
62
+ accessToken: refreshed.accessToken,
63
+ accessTokenExpiresAt: now + (refreshed.expiresIn ?? 0) * 1000,
64
+ // A server that does not rotate keeps the one it has (RFC 6749 §6).
65
+ refreshToken: refreshed.refreshToken ?? current.tokens.refreshToken,
66
+ idToken: refreshed.idToken ?? current.tokens.idToken,
67
+ scopes: refreshed.scope === null
68
+ ? current.tokens.scopes
69
+ : refreshed.scope.split(" ").filter((scope) => scope !== ""),
70
+ dpopKey: current.tokens.dpopKey,
71
+ },
72
+ lastSeenAt: now,
73
+ };
74
+ await this.#save(found.key, session);
75
+ return session.tokens.accessToken;
76
+ });
77
+ }
78
+ /**
79
+ * The session the request's cookie names, if it is still on: a cookie that is not a handle is no session
80
+ * (and the store is not asked), a record that does not open is none, and one past its end or idle too long is
81
+ * ended. `lastSeenAt` is written back at most once a minute.
82
+ */
83
+ async #find(request) {
84
+ const handle = readCookie(request, this.#cookie);
85
+ if (!isHandle(handle)) {
86
+ return null;
87
+ }
88
+ const key = await handleDigest(handle);
89
+ const session = await this.#open(key);
90
+ if (session === null) {
91
+ return null;
92
+ }
93
+ if (this.#config.clock.now() - session.lastSeenAt < TOUCH_INTERVAL_MS) {
94
+ return { key, session };
95
+ }
96
+ // Written under the lock, from a record read again: a write from a stale read could put back a refresh
97
+ // token another request has just spent.
98
+ const touched = await this.#config.sessions.exclusively(key, async () => {
99
+ const current = await this.#open(key);
100
+ if (current === null) {
101
+ return null;
102
+ }
103
+ const now = this.#config.clock.now();
104
+ if (now - current.lastSeenAt < TOUCH_INTERVAL_MS) {
105
+ return current;
106
+ }
107
+ const seen = { ...current, lastSeenAt: now };
108
+ await this.#save(key, seen);
109
+ return seen;
110
+ });
111
+ return touched === null ? null : { key, session: touched };
112
+ }
113
+ /** The session under `key`, opened, or `null`: one past its end or idle too long is ended here. */
114
+ async #open(key) {
115
+ const sealed = await this.#config.sessions.read(key);
116
+ const session = sealed === null ? null : await openSession(await this.#keys(), key, sealed);
117
+ if (session === null) {
118
+ return null;
119
+ }
120
+ const now = this.#config.clock.now();
121
+ if (now >= session.expiresAt || now - session.lastSeenAt >= this.#config.idleLifetime * 1000) {
122
+ await this.#config.sessions.destroy(key);
123
+ return null;
124
+ }
125
+ return session;
126
+ }
127
+ /** Kept for its idle lifetime, never past its absolute end. */
128
+ async #save(key, session) {
129
+ const remaining = Math.ceil((session.expiresAt - this.#config.clock.now()) / 1000);
130
+ const ttl = Math.max(1, Math.min(this.#config.idleLifetime, remaining));
131
+ await this.#config.sessions.save(key, await sealSession(await this.#keys(), key, session), ttl);
132
+ }
133
+ #due(session) {
134
+ return this.#config.clock.now() >= session.tokens.accessTokenExpiresAt - REFRESH_AHEAD_MS;
135
+ }
136
+ }
@@ -0,0 +1,18 @@
1
+ import { type SessionKeys } from "../session/sealing.js";
2
+ import { type CookieNames } from "./cookies.js";
3
+ import type { Settings } from "./options.js";
4
+ import type { Provider } from "./provider.js";
5
+ export interface SignOutContext {
6
+ readonly config: Settings;
7
+ readonly provider: Provider;
8
+ readonly cookies: CookieNames;
9
+ readonly sessionKeys: () => Promise<SessionKeys>;
10
+ }
11
+ /**
12
+ * `POST {base}/sign-out`. A request whose `Origin` is not the application's is refused (`403`) and changes
13
+ * nothing: a sign-out another site could fire would let it sign anyone out. Otherwise the session is ended first,
14
+ * then its refresh token is revoked, best effort, and the browser goes to the issuer's end-session endpoint, or
15
+ * to `signedOutPath` when there was no session or the issuer has no such endpoint. The session cookie is cleared
16
+ * on every sign-out.
17
+ */
18
+ export declare function signOut(request: Request, context: SignOutContext): Promise<Response>;
@@ -0,0 +1,47 @@
1
+ // Signing out (clavia's docs/design/sdks.md §5.3, §7 *A session is fixed by nobody*): `POST` only, from the
2
+ // application's own pages, then the session ended here, its refresh token given back, and the session ended at
3
+ // the issuer too (OpenID Connect RP-Initiated Logout 1.0).
4
+ import * as oauth from "oauth4webapi";
5
+ import { handleDigest, isHandle } from "../session/handle.js";
6
+ import { openSession } from "../session/sealing.js";
7
+ import { readCookie, setCookie } from "./cookies.js";
8
+ /**
9
+ * `POST {base}/sign-out`. A request whose `Origin` is not the application's is refused (`403`) and changes
10
+ * nothing: a sign-out another site could fire would let it sign anyone out. Otherwise the session is ended first,
11
+ * then its refresh token is revoked, best effort, and the browser goes to the issuer's end-session endpoint, or
12
+ * to `signedOutPath` when there was no session or the issuer has no such endpoint. The session cookie is cleared
13
+ * on every sign-out.
14
+ */
15
+ export async function signOut(request, context) {
16
+ const { config, provider, cookies } = context;
17
+ // Browsers send `Origin` on every POST; a request without one, or with `null`, is not the application's form.
18
+ if (request.headers.get("Origin") !== config.appUrl.origin) {
19
+ return new Response("Forbidden.", {
20
+ status: 403,
21
+ headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" },
22
+ });
23
+ }
24
+ const clear = setCookie(cookies.session, "", 0, config.secureCookies);
25
+ const handle = readCookie(request, cookies.session);
26
+ if (!isHandle(handle)) {
27
+ return redirect(config.signedOutUrl, clear);
28
+ }
29
+ const key = await handleDigest(handle);
30
+ // Ended first: whatever happens next, the session is gone here.
31
+ const sealed = await config.sessions.destroy(key);
32
+ const session = sealed === null ? null : await openSession(await context.sessionKeys(), key, sealed);
33
+ if (session === null) {
34
+ return redirect(config.signedOutUrl, clear);
35
+ }
36
+ if (session.tokens.refreshToken !== null) {
37
+ await provider.revoke(session.tokens.refreshToken);
38
+ }
39
+ const endSession = await provider.endSessionUrl(session.tokens.idToken, config.signedOutUrl.href, oauth.generateRandomState());
40
+ return redirect(endSession ?? config.signedOutUrl, clear);
41
+ }
42
+ function redirect(location, cookie) {
43
+ return new Response(null, {
44
+ status: 303,
45
+ headers: { Location: location.href, "Set-Cookie": cookie, "Cache-Control": "no-store" },
46
+ });
47
+ }
@@ -0,0 +1,43 @@
1
+ import type { AttemptStore, SessionStore } from "../session/ports.js";
2
+ /**
3
+ * A store under test, with a way to let time pass: an in-memory store moves its clock, a real one (Redis) waits.
4
+ * Each case gets a store of its own.
5
+ */
6
+ export interface StoreSubject<Store> {
7
+ readonly store: Store;
8
+ /** Lets `seconds` pass, as the store sees time. */
9
+ readonly elapse: (seconds: number) => Promise<void>;
10
+ }
11
+ /** One case of a contract: a name, and a check that rejects when the store breaks it. */
12
+ export interface ContractCase<Store> {
13
+ readonly name: string;
14
+ run(subject: StoreSubject<Store>): Promise<void>;
15
+ }
16
+ /**
17
+ * What every {@link SessionStore} must do, as cases any test runner can run: an application's own store (a
18
+ * database, Memcached) passes the same as the SDK's. The TTL cases let 2 seconds pass at most.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import { SessionStoreContract } from "@clavia-auth/core/testing";
23
+ * import { describe, it } from "vitest";
24
+ *
25
+ * describe("my session store", () => {
26
+ * for (const contract of SessionStoreContract) {
27
+ * it(contract.name, () => contract.run({ store: new MySessionStore(), elapse: (s) => sleep(s * 1000) }));
28
+ * }
29
+ * });
30
+ * ```
31
+ */
32
+ export declare const SessionStoreContract: readonly ContractCase<SessionStore>[];
33
+ /**
34
+ * What every {@link AttemptStore} must do, as cases any test runner can run. The TTL case lets 2 seconds pass.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * for (const contract of AttemptStoreContract) {
39
+ * it(contract.name, () => contract.run({ store: new MyAttemptStore(), elapse: (s) => sleep(s * 1000) }));
40
+ * }
41
+ * ```
42
+ */
43
+ export declare const AttemptStoreContract: readonly ContractCase<AttemptStore>[];
@@ -0,0 +1,198 @@
1
+ /**
2
+ * What every {@link SessionStore} must do, as cases any test runner can run: an application's own store (a
3
+ * database, Memcached) passes the same as the SDK's. The TTL cases let 2 seconds pass at most.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import { SessionStoreContract } from "@clavia-auth/core/testing";
8
+ * import { describe, it } from "vitest";
9
+ *
10
+ * describe("my session store", () => {
11
+ * for (const contract of SessionStoreContract) {
12
+ * it(contract.name, () => contract.run({ store: new MySessionStore(), elapse: (s) => sleep(s * 1000) }));
13
+ * }
14
+ * });
15
+ * ```
16
+ */
17
+ export const SessionStoreContract = [
18
+ {
19
+ name: "reads what it was given, and nothing for a key it never had",
20
+ async run({ store }) {
21
+ const key = unique("key");
22
+ await store.create(key, "record-1", 60, { sid: null, sub: unique("sub") });
23
+ equal(await store.read(key), "record-1", "read() of a created session");
24
+ equal(await store.read(unique("key")), null, "read() of an unknown key");
25
+ },
26
+ },
27
+ {
28
+ name: "replaces a session on save",
29
+ async run({ store }) {
30
+ const key = unique("key");
31
+ await store.create(key, "record-1", 60, { sid: null, sub: unique("sub") });
32
+ await store.save(key, "record-2", 60);
33
+ equal(await store.read(key), "record-2", "read() after save()");
34
+ },
35
+ },
36
+ {
37
+ name: "brings no ended session back on save",
38
+ async run({ store }) {
39
+ const key = unique("key");
40
+ await store.create(key, "record-1", 60, { sid: null, sub: unique("sub") });
41
+ await store.destroy(key);
42
+ await store.save(key, "record-2", 60);
43
+ equal(await store.read(key), null, "read() after save() of an ended session");
44
+ },
45
+ },
46
+ {
47
+ name: "ends a session, returning it once",
48
+ async run({ store }) {
49
+ const key = unique("key");
50
+ await store.create(key, "record-1", 60, { sid: null, sub: unique("sub") });
51
+ equal(await store.destroy(key), "record-1", "the first destroy()");
52
+ equal(await store.read(key), null, "read() after destroy()");
53
+ equal(await store.destroy(key), null, "a second destroy()");
54
+ },
55
+ },
56
+ {
57
+ name: "ends every session of a sid, and only those",
58
+ async run({ store }) {
59
+ const sid = unique("sid");
60
+ const sub = unique("sub");
61
+ const [first, second, other, none] = [unique("key"), unique("key"), unique("key"), unique("key")];
62
+ await store.create(first, "a", 60, { sid, sub });
63
+ await store.create(second, "b", 60, { sid, sub: unique("sub") });
64
+ await store.create(other, "c", 60, { sid: unique("sid"), sub });
65
+ await store.create(none, "d", 60, { sid: null, sub });
66
+ equal(await store.destroyBySid(sid), 2, "destroyBySid() counts what it ended");
67
+ equal(await store.read(first), null, "a session of the sid");
68
+ equal(await store.read(second), null, "another session of the sid");
69
+ equal(await store.read(other), "c", "a session of another sid");
70
+ equal(await store.read(none), "d", "a session with no sid");
71
+ equal(await store.destroyBySid(sid), 0, "destroyBySid() again");
72
+ },
73
+ },
74
+ {
75
+ name: "ends every session of a person, and only theirs",
76
+ async run({ store }) {
77
+ const sub = unique("sub");
78
+ const [first, second, other] = [unique("key"), unique("key"), unique("key")];
79
+ await store.create(first, "a", 60, { sid: unique("sid"), sub });
80
+ await store.create(second, "b", 60, { sid: null, sub });
81
+ await store.create(other, "c", 60, { sid: null, sub: unique("sub") });
82
+ equal(await store.destroyBySubject(sub), 2, "destroyBySubject() counts what it ended");
83
+ equal(await store.read(first), null, "a session of the person");
84
+ equal(await store.read(second), null, "another session of the person");
85
+ equal(await store.read(other), "c", "someone else's session");
86
+ },
87
+ },
88
+ {
89
+ name: "counts no session already ended by its index",
90
+ async run({ store }) {
91
+ const sid = unique("sid");
92
+ const sub = unique("sub");
93
+ const key = unique("key");
94
+ await store.create(key, "a", 60, { sid, sub });
95
+ await store.destroy(key);
96
+ equal(await store.destroyBySid(sid), 0, "destroyBySid() after destroy()");
97
+ equal(await store.destroyBySubject(sub), 0, "destroyBySubject() after destroy()");
98
+ },
99
+ },
100
+ {
101
+ name: "forgets a session past its TTL, and save() sets a new one",
102
+ async run({ store, elapse }) {
103
+ const [kept, gone] = [unique("key"), unique("key")];
104
+ await store.create(kept, "a", 1, { sid: null, sub: unique("sub") });
105
+ await store.create(gone, "b", 1, { sid: null, sub: unique("sub") });
106
+ await store.save(kept, "a2", 60);
107
+ await elapse(2);
108
+ equal(await store.read(gone), null, "read() past the TTL");
109
+ equal(await store.read(kept), "a2", "read() of a session saved with a longer TTL");
110
+ },
111
+ },
112
+ {
113
+ name: "runs work under one key one at a time, and returns what it returns",
114
+ async run({ store }) {
115
+ const key = unique("key");
116
+ let inside = 0;
117
+ let most = 0;
118
+ const work = async (value) => {
119
+ inside += 1;
120
+ most = Math.max(most, inside);
121
+ await pause(20);
122
+ inside -= 1;
123
+ return value;
124
+ };
125
+ const results = await Promise.all([1, 2, 3, 4, 5].map((value) => store.exclusively(key, () => work(value))));
126
+ equal(most, 1, "callers inside exclusively() at once");
127
+ equal(results.join(","), "1,2,3,4,5", "what exclusively() returned");
128
+ },
129
+ },
130
+ {
131
+ name: "releases the lock when work throws",
132
+ async run({ store }) {
133
+ const key = unique("key");
134
+ const failure = new Error("work failed");
135
+ const thrown = await store
136
+ .exclusively(key, () => Promise.reject(failure))
137
+ .then(() => null, (reason) => reason);
138
+ equal(thrown, failure, "what exclusively() rejected with");
139
+ equal(await store.exclusively(key, () => Promise.resolve("after")), "after", "exclusively() after a failure");
140
+ },
141
+ },
142
+ ];
143
+ /**
144
+ * What every {@link AttemptStore} must do, as cases any test runner can run. The TTL case lets 2 seconds pass.
145
+ *
146
+ * @example
147
+ * ```ts
148
+ * for (const contract of AttemptStoreContract) {
149
+ * it(contract.name, () => contract.run({ store: new MyAttemptStore(), elapse: (s) => sleep(s * 1000) }));
150
+ * }
151
+ * ```
152
+ */
153
+ export const AttemptStoreContract = [
154
+ {
155
+ name: "gives an attempt back once",
156
+ async run({ store }) {
157
+ const state = unique("state");
158
+ await store.put("attempt", state, 60);
159
+ equal(await store.take(state), "attempt", "the first take()");
160
+ equal(await store.take(state), null, "a second take()");
161
+ },
162
+ },
163
+ {
164
+ name: "gives nothing for a state it never had",
165
+ async run({ store }) {
166
+ equal(await store.take(unique("state")), null, "take() of an unknown state");
167
+ },
168
+ },
169
+ {
170
+ name: "gives an attempt to one of the callers racing for it",
171
+ async run({ store }) {
172
+ const state = unique("state");
173
+ await store.put("attempt", state, 60);
174
+ const taken = await Promise.all(Array.from({ length: 5 }, () => store.take(state)));
175
+ equal(taken.filter((record) => record !== null).length, 1, "callers that got the attempt");
176
+ },
177
+ },
178
+ {
179
+ name: "forgets an attempt past its TTL",
180
+ async run({ store, elapse }) {
181
+ const state = unique("state");
182
+ await store.put("attempt", state, 1);
183
+ await elapse(2);
184
+ equal(await store.take(state), null, "take() past the TTL");
185
+ },
186
+ },
187
+ ];
188
+ function unique(prefix) {
189
+ return `${prefix}-${crypto.randomUUID()}`;
190
+ }
191
+ function pause(ms) {
192
+ return new Promise((resolve) => setTimeout(resolve, ms));
193
+ }
194
+ function equal(actual, expected, what) {
195
+ if (!Object.is(actual, expected)) {
196
+ throw new Error(`${what}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}.`);
197
+ }
198
+ }
@@ -0,0 +1,102 @@
1
+ import { type Clock } from "../clock.js";
2
+ /** How the fake provider is set up. */
3
+ export interface FakeProviderOptions {
4
+ /** `https://auth.example.test` by default. */
5
+ readonly issuer?: string;
6
+ readonly clientId?: string;
7
+ readonly clientSecret?: string;
8
+ /** Whether discovery names a pushed authorization request endpoint (RFC 9126); `true` by default. */
9
+ readonly par?: boolean;
10
+ /** Whether the authorization response carries `iss` (RFC 9207), and discovery says so; `true` by default. */
11
+ readonly issParameter?: boolean;
12
+ /** Who signs in: `sub` and what userinfo says of them. */
13
+ readonly person?: Readonly<Record<string, unknown>> & {
14
+ readonly sub?: string;
15
+ };
16
+ /** The `sid` of the ID token, or `null` for none; a fixed one by default. */
17
+ readonly sid?: string | null;
18
+ /** Seconds an access token lives (`expires_in`); 300 by default. */
19
+ readonly accessTokenLifetime?: number;
20
+ /**
21
+ * Whether a refresh gives a new refresh token and spends the one used (rotation, as Clavia does); `true` by
22
+ * default. A spent refresh token presented again is `invalid_grant`.
23
+ */
24
+ readonly rotateRefreshTokens?: boolean;
25
+ /** The time it issues tokens at; the system clock by default. Give the core's clock. */
26
+ readonly clock?: Clock;
27
+ }
28
+ /** One answer to tamper with: the next ID token, as issued. */
29
+ export interface IdTokenTampering {
30
+ /** Claims replacing or adding to the ones issued (`nonce`, `aud`, `exp`…); `undefined` removes one. */
31
+ readonly claims?: Readonly<Record<string, unknown>>;
32
+ /** Header members replacing or adding to the ones issued (`alg`, `kid`…). */
33
+ readonly header?: Readonly<Record<string, unknown>>;
34
+ /** Signed by the provider's key (by default), by a key it never published, or not at all (`alg: none`). */
35
+ readonly signedWith?: "issuer" | "foreign" | "none";
36
+ }
37
+ /** A request the fake provider was sent. */
38
+ export interface FakeProviderRequest {
39
+ readonly method: string;
40
+ readonly url: URL;
41
+ readonly headers: Headers;
42
+ readonly form: URLSearchParams;
43
+ }
44
+ /** A fake provider: give its `fetch` to the code under test, and drive the browser's part with `authorize()`. */
45
+ export interface FakeProvider {
46
+ readonly issuer: string;
47
+ readonly clientId: string;
48
+ readonly clientSecret: string;
49
+ /** Answers discovery, PAR, the token endpoint, userinfo and the JWKS. */
50
+ readonly fetch: typeof fetch;
51
+ /** Every request sent to `fetch`, in order. */
52
+ readonly requests: readonly FakeProviderRequest[];
53
+ /** The tokens given back at the revocation endpoint (RFC 7009), in order. */
54
+ readonly revoked: readonly string[];
55
+ /** How many refreshes it granted. */
56
+ readonly refreshes: number;
57
+ /**
58
+ * The browser at the authorization endpoint: given where the sign-in sent it, the callback URL the provider
59
+ * sends it back to, with a code, the `state` and (by default) `iss`. `error` answers with that error instead;
60
+ * `iss` and `state` replace what is sent back.
61
+ */
62
+ authorize(location: string | URL, options?: {
63
+ error?: string;
64
+ iss?: string;
65
+ state?: string;
66
+ }): Promise<URL>;
67
+ /** One-shot tampering with the next answers; each is cleared once used. */
68
+ readonly next: {
69
+ idToken?: IdTokenTampering;
70
+ /** Members replacing or adding to the next userinfo answer (`sub`…). */
71
+ userinfo?: Readonly<Record<string, unknown>>;
72
+ /** Members replacing or adding to the next discovery document (`issuer`, an `http` endpoint…). */
73
+ discovery?: Readonly<Record<string, unknown>>;
74
+ /** The next revocation answers with this status (a `503`…) and keeps the token. */
75
+ revocation?: {
76
+ readonly status: number;
77
+ };
78
+ /** The next token endpoint answer, as an OAuth 2.0 error (`invalid_grant`, `server_error`…), 400 by default. */
79
+ token?: {
80
+ readonly error: string;
81
+ readonly status?: number;
82
+ };
83
+ };
84
+ }
85
+ /**
86
+ * A fake OpenID Connect provider for tests: it holds an ES256 key, issues real signed tokens, and checks what a
87
+ * real one would (client authentication, PKCE S256, the redirect URI, codes used once).
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * import { fakeProvider } from "@clavia-auth/core/testing";
92
+ *
93
+ * const provider = await fakeProvider({ person: { sub: "usr_1", name: "Ada" } });
94
+ * const clavia = createClavia({ issuer: provider.issuer, clientId: provider.clientId,
95
+ * clientSecret: provider.clientSecret, fetch: provider.fetch, … });
96
+ *
97
+ * const started = await clavia.handle(new Request("https://app.example.test/auth/sign-in"));
98
+ * const callback = await provider.authorize(started.headers.get("Location")!);
99
+ * provider.next.idToken = { claims: { nonce: "another" } }; // the next ID token is refused
100
+ * ```
101
+ */
102
+ export declare function fakeProvider(options?: FakeProviderOptions): Promise<FakeProvider>;