nextidp 0.0.0-stage → 0.1.2
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 +85 -0
- package/LICENSE +21 -0
- package/README.md +436 -2
- package/dist/cjs/access-token.d.ts +56 -0
- package/dist/cjs/access-token.js +196 -0
- package/dist/cjs/config.d.ts +128 -0
- package/dist/cjs/config.js +233 -0
- package/dist/cjs/cookies.d.ts +23 -0
- package/dist/cjs/cookies.js +118 -0
- package/dist/cjs/discovery.d.ts +24 -0
- package/dist/cjs/discovery.js +91 -0
- package/dist/cjs/errors.d.ts +63 -0
- package/dist/cjs/errors.js +69 -0
- package/dist/cjs/express.d.ts +71 -0
- package/dist/cjs/express.js +114 -0
- package/dist/cjs/http.d.ts +10 -0
- package/dist/cjs/http.js +68 -0
- package/dist/cjs/id-token.d.ts +19 -0
- package/dist/cjs/id-token.js +77 -0
- package/dist/cjs/idp.d.ts +81 -0
- package/dist/cjs/idp.js +482 -0
- package/dist/cjs/index.d.ts +9 -0
- package/dist/cjs/index.js +53 -0
- package/dist/cjs/logout-token.d.ts +13 -0
- package/dist/cjs/logout-token.js +63 -0
- package/dist/cjs/nestjs.d.ts +53 -0
- package/dist/cjs/nestjs.js +142 -0
- package/dist/cjs/next.d.ts +61 -0
- package/dist/cjs/next.js +118 -0
- package/dist/cjs/node-adapter.d.ts +16 -0
- package/dist/cjs/node-adapter.js +76 -0
- package/dist/cjs/node-http.d.ts +22 -0
- package/dist/cjs/node-http.js +127 -0
- package/dist/cjs/node.d.ts +50 -0
- package/dist/cjs/node.js +57 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pkce.d.ts +6 -0
- package/dist/cjs/pkce.js +49 -0
- package/dist/cjs/return-path.d.ts +6 -0
- package/dist/cjs/return-path.js +41 -0
- package/dist/cjs/sealed.d.ts +12 -0
- package/dist/cjs/sealed.js +78 -0
- package/dist/cjs/service.d.ts +61 -0
- package/dist/cjs/service.js +173 -0
- package/dist/cjs/session.d.ts +51 -0
- package/dist/cjs/session.js +97 -0
- package/dist/cjs/store.d.ts +58 -0
- package/dist/cjs/store.js +145 -0
- package/dist/cjs/tokens.d.ts +38 -0
- package/dist/cjs/tokens.js +138 -0
- package/dist/esm/access-token.d.ts +56 -0
- package/dist/esm/access-token.js +156 -0
- package/dist/esm/config.d.ts +128 -0
- package/dist/esm/config.js +206 -0
- package/dist/esm/cookies.d.ts +23 -0
- package/dist/esm/cookies.js +89 -0
- package/dist/esm/discovery.d.ts +24 -0
- package/dist/esm/discovery.js +56 -0
- package/dist/esm/errors.d.ts +63 -0
- package/dist/esm/errors.js +41 -0
- package/dist/esm/express.d.ts +71 -0
- package/dist/esm/express.js +90 -0
- package/dist/esm/http.d.ts +10 -0
- package/dist/esm/http.js +44 -0
- package/dist/esm/id-token.d.ts +19 -0
- package/dist/esm/id-token.js +51 -0
- package/dist/esm/idp.d.ts +81 -0
- package/dist/esm/idp.js +488 -0
- package/dist/esm/index.d.ts +9 -0
- package/dist/esm/index.js +30 -0
- package/dist/esm/logout-token.d.ts +13 -0
- package/dist/esm/logout-token.js +39 -0
- package/dist/esm/nestjs.d.ts +53 -0
- package/dist/esm/nestjs.js +118 -0
- package/dist/esm/next.d.ts +61 -0
- package/dist/esm/next.js +94 -0
- package/dist/esm/node-adapter.d.ts +16 -0
- package/dist/esm/node-adapter.js +60 -0
- package/dist/esm/node-http.d.ts +22 -0
- package/dist/esm/node-http.js +96 -0
- package/dist/esm/node.d.ts +50 -0
- package/dist/esm/node.js +33 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/pkce.d.ts +6 -0
- package/dist/esm/pkce.js +23 -0
- package/dist/esm/return-path.d.ts +6 -0
- package/dist/esm/return-path.js +17 -0
- package/dist/esm/sealed.d.ts +12 -0
- package/dist/esm/sealed.js +54 -0
- package/dist/esm/service.d.ts +61 -0
- package/dist/esm/service.js +148 -0
- package/dist/esm/session.d.ts +51 -0
- package/dist/esm/session.js +58 -0
- package/dist/esm/store.d.ts +58 -0
- package/dist/esm/store.js +119 -0
- package/dist/esm/tokens.d.ts +38 -0
- package/dist/esm/tokens.js +100 -0
- package/package.json +147 -3
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { EncryptJWT, jwtDecrypt } from "jose";
|
|
2
|
+
const encoder = new TextEncoder();
|
|
3
|
+
const SALT = encoder.encode("nextidp sealed cookie");
|
|
4
|
+
async function deriveKey(secret, purpose) {
|
|
5
|
+
const material = await crypto.subtle.importKey("raw", encoder.encode(secret), "HKDF", false, [
|
|
6
|
+
"deriveBits"
|
|
7
|
+
]);
|
|
8
|
+
const bits = await crypto.subtle.deriveBits(
|
|
9
|
+
{ name: "HKDF", hash: "SHA-256", salt: SALT, info: encoder.encode(purpose) },
|
|
10
|
+
material,
|
|
11
|
+
256
|
|
12
|
+
);
|
|
13
|
+
return new Uint8Array(bits);
|
|
14
|
+
}
|
|
15
|
+
class Sealer {
|
|
16
|
+
#secrets;
|
|
17
|
+
#keys = /* @__PURE__ */ new Map();
|
|
18
|
+
constructor(secrets) {
|
|
19
|
+
this.#secrets = secrets;
|
|
20
|
+
}
|
|
21
|
+
#key(secret, purpose) {
|
|
22
|
+
const id = `${purpose}\0${secret}`;
|
|
23
|
+
let key = this.#keys.get(id);
|
|
24
|
+
if (!key) {
|
|
25
|
+
key = deriveKey(secret, purpose);
|
|
26
|
+
this.#keys.set(id, key);
|
|
27
|
+
}
|
|
28
|
+
return key;
|
|
29
|
+
}
|
|
30
|
+
/** Encrypts with the first secret. */
|
|
31
|
+
async seal(payload, purpose, maxAgeSeconds) {
|
|
32
|
+
const [secret] = this.#secrets;
|
|
33
|
+
if (secret === void 0) throw new Error("No secret to seal with.");
|
|
34
|
+
return new EncryptJWT(payload).setProtectedHeader({ alg: "dir", enc: "A256GCM" }).setIssuedAt().setExpirationTime(`${maxAgeSeconds}s`).encrypt(await this.#key(secret, purpose));
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The payload, or undefined if the value is missing, altered, sealed for another purpose,
|
|
38
|
+
* expired, or sealed with a secret no longer in the list. Tries every secret, in order.
|
|
39
|
+
*/
|
|
40
|
+
async unseal(value, purpose) {
|
|
41
|
+
if (!value) return void 0;
|
|
42
|
+
for (const secret of this.#secrets) {
|
|
43
|
+
try {
|
|
44
|
+
const { payload } = await jwtDecrypt(value, await this.#key(secret, purpose));
|
|
45
|
+
return payload;
|
|
46
|
+
} catch {
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return void 0;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export {
|
|
53
|
+
Sealer
|
|
54
|
+
};
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { ServiceConfig } from "./config.js";
|
|
2
|
+
import type { Discovery } from "./discovery.js";
|
|
3
|
+
import type { Http } from "./http.js";
|
|
4
|
+
export type ServiceTokenOptions = {
|
|
5
|
+
/** The scopes to ask for (default: none, so the auth server decides). */
|
|
6
|
+
scopes?: readonly string[] | undefined;
|
|
7
|
+
/** The API the token is for (RFC 8707). Default `resource` (IDP_RESOURCE), if set. */
|
|
8
|
+
resource?: string | undefined;
|
|
9
|
+
/** Ask for a new token even if one is kept. */
|
|
10
|
+
fresh?: boolean | undefined;
|
|
11
|
+
};
|
|
12
|
+
export type UseServiceTokenOptions = Omit<ServiceTokenOptions, "fresh"> & {
|
|
13
|
+
/**
|
|
14
|
+
* The origins the token may be sent to, like `https://orders.example.com`. Default: the
|
|
15
|
+
* origin of `resource` (or IDP_RESOURCE). A request anywhere else goes out untouched, with
|
|
16
|
+
* no token: a URL from elsewhere must never carry this service's token away.
|
|
17
|
+
*/
|
|
18
|
+
origins?: readonly string[] | undefined;
|
|
19
|
+
};
|
|
20
|
+
type RequestConfigLike = {
|
|
21
|
+
url: string;
|
|
22
|
+
baseUrl?: string;
|
|
23
|
+
headers?: Record<string, string>;
|
|
24
|
+
retried?: boolean;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* What `useServiceToken` needs of an HTTP client: fast-http-client's `createHttp()` has it.
|
|
28
|
+
* Written out rather than imported, so a client from another version of it fits too.
|
|
29
|
+
*/
|
|
30
|
+
export type InterceptableClient = {
|
|
31
|
+
request(config: RequestConfigLike): Promise<unknown>;
|
|
32
|
+
interceptors: {
|
|
33
|
+
request: {
|
|
34
|
+
use(fn: (config: RequestConfigLike) => Promise<RequestConfigLike>): () => void;
|
|
35
|
+
};
|
|
36
|
+
response: {
|
|
37
|
+
use(handlers: {
|
|
38
|
+
onRejected?: (error: unknown) => unknown;
|
|
39
|
+
}): () => void;
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
export type ServiceTokens = {
|
|
44
|
+
get(options?: ServiceTokenOptions): Promise<string>;
|
|
45
|
+
drop(token: string): void;
|
|
46
|
+
/** The API a token is for when a call names none (IDP_RESOURCE). */
|
|
47
|
+
defaultResource: string | undefined;
|
|
48
|
+
};
|
|
49
|
+
export declare function createServiceTokens(deps: {
|
|
50
|
+
http: Http;
|
|
51
|
+
discovery: () => Promise<Discovery>;
|
|
52
|
+
config: ServiceConfig;
|
|
53
|
+
}): ServiceTokens;
|
|
54
|
+
/**
|
|
55
|
+
* Puts a service token on every request of `client` to the allowed origins, and nowhere else.
|
|
56
|
+
* When the API answers 401, the token is dropped and the request sent once more with a new
|
|
57
|
+
* one (a token revoked early); a second 401 is the caller's. Returns a function that takes
|
|
58
|
+
* both hooks off.
|
|
59
|
+
*/
|
|
60
|
+
export declare function useServiceToken(tokens: ServiceTokens, client: InterceptableClient, options?: UseServiceTokenOptions): () => void;
|
|
61
|
+
export {};
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { bearerToken } from "./access-token.js";
|
|
2
|
+
import { IdpError } from "./errors.js";
|
|
3
|
+
import { clientCredentials } from "./tokens.js";
|
|
4
|
+
const RENEW_BEFORE_S = 60;
|
|
5
|
+
const MAX_KEPT = 100;
|
|
6
|
+
function misconfigured(problem) {
|
|
7
|
+
return new IdpError("misconfigured", `nextidp is misconfigured: ${problem}.`);
|
|
8
|
+
}
|
|
9
|
+
function scopeOf(scopes) {
|
|
10
|
+
const list = [...new Set((scopes ?? []).map((scope) => scope.trim()).filter(Boolean))];
|
|
11
|
+
if (list.some((scope) => /\s/.test(scope))) throw misconfigured("a scope can't hold spaces");
|
|
12
|
+
return list.length > 0 ? list.sort().join(" ") : void 0;
|
|
13
|
+
}
|
|
14
|
+
function resourceOf(resource) {
|
|
15
|
+
if (resource === void 0) return void 0;
|
|
16
|
+
if (!URL.canParse(resource) || /\s/.test(resource)) {
|
|
17
|
+
throw misconfigured("resource must be an absolute URI");
|
|
18
|
+
}
|
|
19
|
+
return resource;
|
|
20
|
+
}
|
|
21
|
+
function createServiceTokens(deps) {
|
|
22
|
+
const kept = /* @__PURE__ */ new Map();
|
|
23
|
+
const client = { clientId: deps.config.clientId, clientSecret: deps.config.clientSecret };
|
|
24
|
+
const issue = async (scope, resource) => {
|
|
25
|
+
const tokens = await clientCredentials(deps.http, await deps.discovery(), client, {
|
|
26
|
+
scope,
|
|
27
|
+
resource
|
|
28
|
+
});
|
|
29
|
+
const lifetime = tokens.expires_in ?? 0;
|
|
30
|
+
const renewIn = lifetime - Math.min(RENEW_BEFORE_S, lifetime / 2);
|
|
31
|
+
return { token: tokens.access_token, until: Date.now() + Math.max(0, renewIn) * 1e3 };
|
|
32
|
+
};
|
|
33
|
+
const prune = (now) => {
|
|
34
|
+
for (const [key, entry] of kept) {
|
|
35
|
+
if (entry.issued && entry.issued.until <= now) kept.delete(key);
|
|
36
|
+
}
|
|
37
|
+
const oldest = kept.keys().next();
|
|
38
|
+
if (kept.size >= MAX_KEPT && !oldest.done) kept.delete(oldest.value);
|
|
39
|
+
};
|
|
40
|
+
return {
|
|
41
|
+
async get(options = {}) {
|
|
42
|
+
const scope = scopeOf(options.scopes);
|
|
43
|
+
const resource = resourceOf(options.resource ?? deps.config.resource);
|
|
44
|
+
const key = JSON.stringify([resource ?? null, scope ?? null]);
|
|
45
|
+
const now = Date.now();
|
|
46
|
+
const known = kept.get(key);
|
|
47
|
+
if (known && !options.fresh) {
|
|
48
|
+
if (!known.issued) return (await known.pending).token;
|
|
49
|
+
if (known.issued.until > now) return known.issued.token;
|
|
50
|
+
}
|
|
51
|
+
if (kept.size >= MAX_KEPT) prune(now);
|
|
52
|
+
const entry = { pending: issue(scope, resource) };
|
|
53
|
+
entry.pending.then(
|
|
54
|
+
(issued) => {
|
|
55
|
+
entry.issued = issued;
|
|
56
|
+
},
|
|
57
|
+
() => void 0
|
|
58
|
+
);
|
|
59
|
+
kept.set(key, entry);
|
|
60
|
+
try {
|
|
61
|
+
return (await entry.pending).token;
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (kept.get(key) === entry) kept.delete(key);
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
drop(token) {
|
|
68
|
+
for (const [key, entry] of kept) if (entry.issued?.token === token) kept.delete(key);
|
|
69
|
+
},
|
|
70
|
+
defaultResource: deps.config.resource
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function statusOf(error) {
|
|
74
|
+
const status = error?.status;
|
|
75
|
+
return typeof status === "number" ? status : void 0;
|
|
76
|
+
}
|
|
77
|
+
function configOf(error) {
|
|
78
|
+
const config = error?.config;
|
|
79
|
+
return config && typeof config === "object" && typeof config.url === "string" ? config : void 0;
|
|
80
|
+
}
|
|
81
|
+
function originOf(config) {
|
|
82
|
+
try {
|
|
83
|
+
return new URL(config.url, config.baseUrl).origin;
|
|
84
|
+
} catch {
|
|
85
|
+
return void 0;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function allowedOrigins(tokens, options) {
|
|
89
|
+
const resource = options.resource ?? tokens.defaultResource;
|
|
90
|
+
const listed = options.origins ?? (resource && /^https?:\/\//i.test(resource) ? [resource] : []);
|
|
91
|
+
const origins = /* @__PURE__ */ new Set();
|
|
92
|
+
for (const value of listed) {
|
|
93
|
+
const url = URL.canParse(value) ? new URL(value) : void 0;
|
|
94
|
+
if (!url || url.protocol !== "https:" && url.protocol !== "http:") {
|
|
95
|
+
throw misconfigured("useServiceToken's origins must be http(s) URLs");
|
|
96
|
+
}
|
|
97
|
+
origins.add(url.origin);
|
|
98
|
+
}
|
|
99
|
+
if (origins.size === 0) {
|
|
100
|
+
throw misconfigured(
|
|
101
|
+
"useServiceToken needs origins, or an http(s) resource, to know where the token may go"
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
return origins;
|
|
105
|
+
}
|
|
106
|
+
function withoutAuthorization(headers) {
|
|
107
|
+
return Object.fromEntries(
|
|
108
|
+
Object.entries(headers ?? {}).filter(([name]) => name.toLowerCase() !== "authorization")
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
function useServiceToken(tokens, client, options = {}) {
|
|
112
|
+
const origins = allowedOrigins(tokens, options);
|
|
113
|
+
const { origins: _listed, ...tokenOptions } = options;
|
|
114
|
+
const allowed = (config) => {
|
|
115
|
+
const origin = originOf(config);
|
|
116
|
+
return origin !== void 0 && origins.has(origin);
|
|
117
|
+
};
|
|
118
|
+
const stopRequest = client.interceptors.request.use(
|
|
119
|
+
async (config) => allowed(config) ? {
|
|
120
|
+
...config,
|
|
121
|
+
headers: {
|
|
122
|
+
...withoutAuthorization(config.headers),
|
|
123
|
+
authorization: `Bearer ${await tokens.get(tokenOptions)}`
|
|
124
|
+
}
|
|
125
|
+
} : config
|
|
126
|
+
);
|
|
127
|
+
const stopResponse = client.interceptors.response.use({
|
|
128
|
+
async onRejected(error) {
|
|
129
|
+
const config = configOf(error);
|
|
130
|
+
if (statusOf(error) !== 401 || !config || config.retried || !allowed(config)) throw error;
|
|
131
|
+
const refused = bearerToken(
|
|
132
|
+
Object.entries(config.headers ?? {}).find(
|
|
133
|
+
([name]) => name.toLowerCase() === "authorization"
|
|
134
|
+
)?.[1]
|
|
135
|
+
);
|
|
136
|
+
if (refused) tokens.drop(refused);
|
|
137
|
+
return client.request({ ...config, retried: true });
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
return () => {
|
|
141
|
+
stopRequest();
|
|
142
|
+
stopResponse();
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
export {
|
|
146
|
+
createServiceTokens,
|
|
147
|
+
useServiceToken
|
|
148
|
+
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { JWTPayload } from "jose";
|
|
2
|
+
import * as v from "valibot";
|
|
3
|
+
export declare const FLOW_PURPOSE = "nextidp:flow";
|
|
4
|
+
export declare const SESSION_PURPOSE = "nextidp:session";
|
|
5
|
+
/** A sign-in in progress lasts as long as the auth server's signed request: 10 minutes. */
|
|
6
|
+
export declare const FLOW_MAX_AGE = 600;
|
|
7
|
+
declare const FlowSchema: v.ObjectSchema<{
|
|
8
|
+
readonly verifier: v.StringSchema<undefined>;
|
|
9
|
+
readonly state: v.StringSchema<undefined>;
|
|
10
|
+
readonly nonce: v.StringSchema<undefined>;
|
|
11
|
+
readonly returnTo: v.StringSchema<undefined>;
|
|
12
|
+
}, undefined>;
|
|
13
|
+
export type Flow = v.InferOutput<typeof FlowSchema>;
|
|
14
|
+
export declare function parseFlow(payload: unknown): Flow | undefined;
|
|
15
|
+
declare const StoredSessionSchema: v.ObjectSchema<{
|
|
16
|
+
readonly claims: v.RecordSchema<v.StringSchema<undefined>, v.UnknownSchema, undefined>;
|
|
17
|
+
readonly accessToken: v.StringSchema<undefined>;
|
|
18
|
+
/** Seconds since the epoch. */
|
|
19
|
+
readonly accessTokenExpiresAt: v.NumberSchema<undefined>;
|
|
20
|
+
readonly refreshToken: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
21
|
+
/** As received: the hint when signing out of the auth server too. */
|
|
22
|
+
readonly idToken: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
23
|
+
readonly scope: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
24
|
+
}, undefined>;
|
|
25
|
+
export type StoredSession = v.InferOutput<typeof StoredSessionSchema>;
|
|
26
|
+
export declare function parseStoredSession(payload: unknown): StoredSession | undefined;
|
|
27
|
+
/** The person signed in, from the ID token's standard claims. */
|
|
28
|
+
export type IdpUser = {
|
|
29
|
+
/** The `sub` claim: stable for this person at this auth server. */
|
|
30
|
+
id: string;
|
|
31
|
+
email?: string;
|
|
32
|
+
emailVerified?: boolean;
|
|
33
|
+
name?: string;
|
|
34
|
+
picture?: string;
|
|
35
|
+
};
|
|
36
|
+
/** A signed-in session, as the app reads it. The refresh token stays inside nextidp. */
|
|
37
|
+
export type Session = {
|
|
38
|
+
user: IdpUser;
|
|
39
|
+
/** Every claim of the ID token, checked. */
|
|
40
|
+
claims: JWTPayload;
|
|
41
|
+
/** For calling APIs as this person: `Authorization: Bearer <accessToken>`. */
|
|
42
|
+
accessToken: string;
|
|
43
|
+
/** When the access token expires, in seconds since the epoch. */
|
|
44
|
+
accessTokenExpiresAt: number;
|
|
45
|
+
/** The scopes the auth server granted, when it said. */
|
|
46
|
+
scope: string | undefined;
|
|
47
|
+
/** Whether there's a refresh token: `offline_access` was granted. */
|
|
48
|
+
canRefresh: boolean;
|
|
49
|
+
};
|
|
50
|
+
export declare function toSession(stored: StoredSession): Session;
|
|
51
|
+
export {};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import * as v from "valibot";
|
|
2
|
+
const FLOW_PURPOSE = "nextidp:flow";
|
|
3
|
+
const SESSION_PURPOSE = "nextidp:session";
|
|
4
|
+
const FLOW_MAX_AGE = 600;
|
|
5
|
+
const FlowSchema = v.object({
|
|
6
|
+
verifier: v.string(),
|
|
7
|
+
state: v.string(),
|
|
8
|
+
nonce: v.string(),
|
|
9
|
+
returnTo: v.string()
|
|
10
|
+
});
|
|
11
|
+
function parseFlow(payload) {
|
|
12
|
+
const parsed = v.safeParse(FlowSchema, payload);
|
|
13
|
+
return parsed.success ? parsed.output : void 0;
|
|
14
|
+
}
|
|
15
|
+
const StoredSessionSchema = v.object({
|
|
16
|
+
claims: v.record(v.string(), v.unknown()),
|
|
17
|
+
accessToken: v.string(),
|
|
18
|
+
/** Seconds since the epoch. */
|
|
19
|
+
accessTokenExpiresAt: v.number(),
|
|
20
|
+
refreshToken: v.optional(v.string()),
|
|
21
|
+
/** As received: the hint when signing out of the auth server too. */
|
|
22
|
+
idToken: v.optional(v.string()),
|
|
23
|
+
scope: v.optional(v.string())
|
|
24
|
+
});
|
|
25
|
+
function parseStoredSession(payload) {
|
|
26
|
+
const parsed = v.safeParse(StoredSessionSchema, payload);
|
|
27
|
+
return parsed.success ? parsed.output : void 0;
|
|
28
|
+
}
|
|
29
|
+
function text(value) {
|
|
30
|
+
return typeof value === "string" && value ? value : void 0;
|
|
31
|
+
}
|
|
32
|
+
function toSession(stored) {
|
|
33
|
+
const claims = stored.claims;
|
|
34
|
+
const user = { id: String(claims.sub ?? "") };
|
|
35
|
+
const email = text(claims.email);
|
|
36
|
+
const name = text(claims.name);
|
|
37
|
+
const picture = text(claims.picture);
|
|
38
|
+
if (email) user.email = email;
|
|
39
|
+
if (typeof claims.email_verified === "boolean") user.emailVerified = claims.email_verified;
|
|
40
|
+
if (name) user.name = name;
|
|
41
|
+
if (picture) user.picture = picture;
|
|
42
|
+
return {
|
|
43
|
+
user,
|
|
44
|
+
claims,
|
|
45
|
+
accessToken: stored.accessToken,
|
|
46
|
+
accessTokenExpiresAt: stored.accessTokenExpiresAt,
|
|
47
|
+
scope: stored.scope,
|
|
48
|
+
canRefresh: Boolean(stored.refreshToken)
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
export {
|
|
52
|
+
FLOW_MAX_AGE,
|
|
53
|
+
FLOW_PURPOSE,
|
|
54
|
+
SESSION_PURPOSE,
|
|
55
|
+
parseFlow,
|
|
56
|
+
parseStoredSession,
|
|
57
|
+
toSession
|
|
58
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { type CookieJar } from "./cookies.js";
|
|
2
|
+
import type { Sealer } from "./sealed.js";
|
|
3
|
+
import { type StoredSession } from "./session.js";
|
|
4
|
+
/**
|
|
5
|
+
* Somewhere to keep sessions: Redis, a database table, or `memoryStore()` for one process.
|
|
6
|
+
* Values are strings nextidp has already encrypted. `set` must expire the key after
|
|
7
|
+
* `ttlSeconds`; `get` answers undefined (or null) for a key that's missing or expired.
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* const store: SessionStore = {
|
|
11
|
+
* get: (key) => redis.get(key),
|
|
12
|
+
* set: async (key, value, ttlSeconds) => { await redis.set(key, value, "EX", ttlSeconds); },
|
|
13
|
+
* delete: async (key) => { await redis.del(key); },
|
|
14
|
+
* };
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
export type SessionStore = {
|
|
18
|
+
get(key: string): Promise<string | null | undefined>;
|
|
19
|
+
set(key: string, value: string, ttlSeconds: number): Promise<void>;
|
|
20
|
+
delete(key: string): Promise<void>;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* A store in this process's memory: for development, tests and single-instance apps. Every
|
|
24
|
+
* session is lost on a restart, and instances don't share it.
|
|
25
|
+
*/
|
|
26
|
+
export declare function memoryStore(): SessionStore;
|
|
27
|
+
/** A session as read: the store's id and when it began, when it lives in a store. */
|
|
28
|
+
export type Loaded = {
|
|
29
|
+
stored: StoredSession;
|
|
30
|
+
id?: string;
|
|
31
|
+
createdAt?: number;
|
|
32
|
+
};
|
|
33
|
+
/** What ends sessions from the auth server's side: its session, or every one of a person. */
|
|
34
|
+
export type IdpLogout = {
|
|
35
|
+
sid?: string | undefined;
|
|
36
|
+
sub?: string | undefined;
|
|
37
|
+
};
|
|
38
|
+
export type SessionBackend = {
|
|
39
|
+
load(jar: CookieJar): Promise<Loaded | undefined>;
|
|
40
|
+
/** A new session, after a sign-in: in a store, any session the cookie named is removed. */
|
|
41
|
+
create(jar: CookieJar, stored: StoredSession): Promise<string[]>;
|
|
42
|
+
/** The same session with new tokens, after a refresh. */
|
|
43
|
+
update(jar: CookieJar, loaded: Loaded, stored: StoredSession): Promise<string[]>;
|
|
44
|
+
remove(jar: CookieJar): Promise<string[]>;
|
|
45
|
+
/** Back-channel logout; only with a store. */
|
|
46
|
+
endIdpSession?: (logout: IdpLogout) => Promise<void>;
|
|
47
|
+
};
|
|
48
|
+
type Settings = {
|
|
49
|
+
sealer: Sealer;
|
|
50
|
+
cookie: string;
|
|
51
|
+
secure: boolean;
|
|
52
|
+
maxAge: number;
|
|
53
|
+
clientId: string;
|
|
54
|
+
};
|
|
55
|
+
/** The session in its cookie, as before any store. */
|
|
56
|
+
export declare function cookieBackend(settings: Settings): SessionBackend;
|
|
57
|
+
export declare function storeBackend(store: SessionStore, settings: Settings): SessionBackend;
|
|
58
|
+
export {};
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { clearCookie, readCookie, writeCookie } from "./cookies.js";
|
|
2
|
+
import { randomToken } from "./pkce.js";
|
|
3
|
+
import { parseStoredSession, SESSION_PURPOSE } from "./session.js";
|
|
4
|
+
function memoryStore() {
|
|
5
|
+
const values = /* @__PURE__ */ new Map();
|
|
6
|
+
const sweep = (now) => {
|
|
7
|
+
for (const [key, entry] of values) if (entry.until <= now) values.delete(key);
|
|
8
|
+
};
|
|
9
|
+
return {
|
|
10
|
+
async get(key) {
|
|
11
|
+
const entry = values.get(key);
|
|
12
|
+
if (!entry) return void 0;
|
|
13
|
+
if (entry.until > Date.now()) return entry.value;
|
|
14
|
+
values.delete(key);
|
|
15
|
+
return void 0;
|
|
16
|
+
},
|
|
17
|
+
async set(key, value, ttlSeconds) {
|
|
18
|
+
const now = Date.now();
|
|
19
|
+
if (values.size >= 1e4) sweep(now);
|
|
20
|
+
values.set(key, { value, until: now + ttlSeconds * 1e3 });
|
|
21
|
+
},
|
|
22
|
+
async delete(key) {
|
|
23
|
+
values.delete(key);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function cookieBackend(settings) {
|
|
28
|
+
const { sealer, cookie, secure, maxAge } = settings;
|
|
29
|
+
const write = async (jar, stored) => writeCookie(jar, cookie, await sealer.seal(stored, SESSION_PURPOSE, maxAge), {
|
|
30
|
+
secure,
|
|
31
|
+
maxAge
|
|
32
|
+
});
|
|
33
|
+
return {
|
|
34
|
+
async load(jar) {
|
|
35
|
+
const stored = parseStoredSession(
|
|
36
|
+
await sealer.unseal(readCookie(jar, cookie), SESSION_PURPOSE)
|
|
37
|
+
);
|
|
38
|
+
return stored ? { stored } : void 0;
|
|
39
|
+
},
|
|
40
|
+
create: write,
|
|
41
|
+
update: (jar, _loaded, stored) => write(jar, stored),
|
|
42
|
+
async remove(jar) {
|
|
43
|
+
return clearCookie(jar, cookie, secure);
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
const REFERENCE_PURPOSE = "nextidp:session-reference";
|
|
48
|
+
const RECORD_PURPOSE = "nextidp:stored-session";
|
|
49
|
+
function nowSeconds() {
|
|
50
|
+
return Math.floor(Date.now() / 1e3);
|
|
51
|
+
}
|
|
52
|
+
function storeBackend(store, settings) {
|
|
53
|
+
const { sealer, cookie, secure, maxAge } = settings;
|
|
54
|
+
const prefix = `nextidp:${encodeURIComponent(settings.clientId)}`;
|
|
55
|
+
const sessionKey = (id) => `${prefix}:session:${id}`;
|
|
56
|
+
const sidKey = (sid) => `${prefix}:ended-sid:${encodeURIComponent(sid)}`;
|
|
57
|
+
const subKey = (sub) => `${prefix}:ended-sub:${encodeURIComponent(sub)}`;
|
|
58
|
+
const referenced = async (jar) => {
|
|
59
|
+
const reference = await sealer.unseal(readCookie(jar, cookie), REFERENCE_PURPOSE);
|
|
60
|
+
return typeof reference?.id === "string" ? reference.id : void 0;
|
|
61
|
+
};
|
|
62
|
+
const save = async (jar, id, stored, createdAt) => {
|
|
63
|
+
await store.set(
|
|
64
|
+
sessionKey(id),
|
|
65
|
+
await sealer.seal({ ...stored, createdAt }, RECORD_PURPOSE, maxAge),
|
|
66
|
+
maxAge
|
|
67
|
+
);
|
|
68
|
+
return writeCookie(jar, cookie, await sealer.seal({ id }, REFERENCE_PURPOSE, maxAge), {
|
|
69
|
+
secure,
|
|
70
|
+
maxAge
|
|
71
|
+
});
|
|
72
|
+
};
|
|
73
|
+
const ended = async (stored, createdAt) => {
|
|
74
|
+
const { sid, sub } = stored.claims;
|
|
75
|
+
if (typeof sid === "string" && sid && await store.get(sidKey(sid))) return true;
|
|
76
|
+
if (typeof sub !== "string" || !sub) return false;
|
|
77
|
+
const since = Number(await store.get(subKey(sub)));
|
|
78
|
+
return Number.isFinite(since) && since >= createdAt;
|
|
79
|
+
};
|
|
80
|
+
return {
|
|
81
|
+
async load(jar) {
|
|
82
|
+
const id = await referenced(jar);
|
|
83
|
+
if (!id) return void 0;
|
|
84
|
+
const sealed = await store.get(sessionKey(id));
|
|
85
|
+
if (!sealed) return void 0;
|
|
86
|
+
const payload = await sealer.unseal(sealed, RECORD_PURPOSE);
|
|
87
|
+
const stored = parseStoredSession(payload);
|
|
88
|
+
const createdAt = typeof payload?.createdAt === "number" ? payload.createdAt : 0;
|
|
89
|
+
if (!stored) return void 0;
|
|
90
|
+
if (await ended(stored, createdAt)) {
|
|
91
|
+
await store.delete(sessionKey(id));
|
|
92
|
+
return void 0;
|
|
93
|
+
}
|
|
94
|
+
return { stored, id, createdAt };
|
|
95
|
+
},
|
|
96
|
+
async create(jar, stored) {
|
|
97
|
+
const previous = await referenced(jar);
|
|
98
|
+
if (previous) await store.delete(sessionKey(previous));
|
|
99
|
+
return save(jar, randomToken(), stored, nowSeconds());
|
|
100
|
+
},
|
|
101
|
+
update(jar, loaded, stored) {
|
|
102
|
+
return save(jar, loaded.id ?? randomToken(), stored, loaded.createdAt ?? nowSeconds());
|
|
103
|
+
},
|
|
104
|
+
async remove(jar) {
|
|
105
|
+
const id = await referenced(jar);
|
|
106
|
+
if (id) await store.delete(sessionKey(id));
|
|
107
|
+
return clearCookie(jar, cookie, secure);
|
|
108
|
+
},
|
|
109
|
+
async endIdpSession({ sid, sub }) {
|
|
110
|
+
if (sid) await store.set(sidKey(sid), "1", maxAge);
|
|
111
|
+
else if (sub) await store.set(subKey(sub), String(nowSeconds()), maxAge);
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
export {
|
|
116
|
+
cookieBackend,
|
|
117
|
+
memoryStore,
|
|
118
|
+
storeBackend
|
|
119
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import * as v from "valibot";
|
|
2
|
+
import type { Discovery } from "./discovery.js";
|
|
3
|
+
import type { Http } from "./http.js";
|
|
4
|
+
declare const TokenResponseSchema: v.ObjectSchema<{
|
|
5
|
+
readonly access_token: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.NonEmptyAction<string, undefined>]>;
|
|
6
|
+
readonly token_type: v.StringSchema<undefined>;
|
|
7
|
+
readonly expires_in: v.OptionalSchema<v.NumberSchema<undefined>, undefined>;
|
|
8
|
+
readonly id_token: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
9
|
+
readonly refresh_token: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
10
|
+
readonly scope: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
11
|
+
}, undefined>;
|
|
12
|
+
export type TokenResponse = v.InferOutput<typeof TokenResponseSchema>;
|
|
13
|
+
export type Client = {
|
|
14
|
+
clientId: string;
|
|
15
|
+
clientSecret: string | undefined;
|
|
16
|
+
};
|
|
17
|
+
/** Redeems an authorization code, proving with the PKCE verifier that this app asked for it. */
|
|
18
|
+
export declare function exchangeCode(http: Http, discovery: Discovery, client: Client, input: {
|
|
19
|
+
code: string;
|
|
20
|
+
verifier: string;
|
|
21
|
+
redirectUri: string;
|
|
22
|
+
resource: string | undefined;
|
|
23
|
+
}): Promise<TokenResponse>;
|
|
24
|
+
/** New tokens for a refresh token. The server rotates it: the old one stops working. */
|
|
25
|
+
export declare function refreshTokens(http: Http, discovery: Discovery, client: Client, input: {
|
|
26
|
+
refreshToken: string;
|
|
27
|
+
resource: string | undefined;
|
|
28
|
+
}): Promise<TokenResponse>;
|
|
29
|
+
/** A service's own access token (RFC 6749 4.4): no person, the client's own credentials. */
|
|
30
|
+
export declare function clientCredentials(http: Http, discovery: Discovery, client: Client, input: {
|
|
31
|
+
scope: string | undefined;
|
|
32
|
+
resource: string | undefined;
|
|
33
|
+
}): Promise<TokenResponse>;
|
|
34
|
+
/** Revokes a refresh token at sign-out, when the server offers revocation. Never throws. */
|
|
35
|
+
export declare function revokeRefreshToken(http: Http, discovery: Discovery, client: Client, refreshToken: string): Promise<void>;
|
|
36
|
+
/** The userinfo endpoint's claims for an access token. */
|
|
37
|
+
export declare function fetchUserInfo(http: Http, discovery: Discovery, accessToken: string): Promise<Record<string, unknown>>;
|
|
38
|
+
export {};
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import * as v from "valibot";
|
|
2
|
+
import { IdpError } from "./errors.js";
|
|
3
|
+
const TokenResponseSchema = v.object({
|
|
4
|
+
access_token: v.pipe(v.string(), v.nonEmpty()),
|
|
5
|
+
token_type: v.string(),
|
|
6
|
+
expires_in: v.optional(v.number()),
|
|
7
|
+
id_token: v.optional(v.string()),
|
|
8
|
+
refresh_token: v.optional(v.string()),
|
|
9
|
+
scope: v.optional(v.string())
|
|
10
|
+
});
|
|
11
|
+
function authenticate(client, form) {
|
|
12
|
+
if (!client.clientSecret) {
|
|
13
|
+
form.set("client_id", client.clientId);
|
|
14
|
+
return {};
|
|
15
|
+
}
|
|
16
|
+
const pair = `${encodeURIComponent(client.clientId)}:${encodeURIComponent(client.clientSecret)}`;
|
|
17
|
+
return { authorization: `Basic ${btoa(pair)}` };
|
|
18
|
+
}
|
|
19
|
+
function oauthError(data) {
|
|
20
|
+
const error = data?.error;
|
|
21
|
+
return typeof error === "string" && /^[A-Za-z0-9_.-]{1,64}$/.test(error) ? error : void 0;
|
|
22
|
+
}
|
|
23
|
+
async function tokenRequest(http, discovery, client, form, code) {
|
|
24
|
+
const headers = authenticate(client, form);
|
|
25
|
+
let answer;
|
|
26
|
+
try {
|
|
27
|
+
answer = await http.postForm(discovery.token_endpoint, form, headers);
|
|
28
|
+
} catch (cause) {
|
|
29
|
+
throw new IdpError(code, "The token endpoint didn't answer.", { cause });
|
|
30
|
+
}
|
|
31
|
+
if (!answer.ok) {
|
|
32
|
+
throw new IdpError(
|
|
33
|
+
code,
|
|
34
|
+
`The token endpoint refused: ${oauthError(answer.data) ?? answer.status}.`,
|
|
35
|
+
{ status: answer.status }
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
const parsed = v.safeParse(TokenResponseSchema, answer.data);
|
|
39
|
+
if (!parsed.success) throw new IdpError(code, "The token endpoint's answer isn't valid.");
|
|
40
|
+
return parsed.output;
|
|
41
|
+
}
|
|
42
|
+
function exchangeCode(http, discovery, client, input) {
|
|
43
|
+
const form = new URLSearchParams({
|
|
44
|
+
grant_type: "authorization_code",
|
|
45
|
+
code: input.code,
|
|
46
|
+
code_verifier: input.verifier,
|
|
47
|
+
redirect_uri: input.redirectUri
|
|
48
|
+
});
|
|
49
|
+
if (input.resource) form.set("resource", input.resource);
|
|
50
|
+
return tokenRequest(http, discovery, client, form, "token_failed");
|
|
51
|
+
}
|
|
52
|
+
function refreshTokens(http, discovery, client, input) {
|
|
53
|
+
const form = new URLSearchParams({
|
|
54
|
+
grant_type: "refresh_token",
|
|
55
|
+
refresh_token: input.refreshToken
|
|
56
|
+
});
|
|
57
|
+
if (input.resource) form.set("resource", input.resource);
|
|
58
|
+
return tokenRequest(http, discovery, client, form, "refresh_failed");
|
|
59
|
+
}
|
|
60
|
+
function clientCredentials(http, discovery, client, input) {
|
|
61
|
+
const form = new URLSearchParams({ grant_type: "client_credentials" });
|
|
62
|
+
if (input.scope) form.set("scope", input.scope);
|
|
63
|
+
if (input.resource) form.set("resource", input.resource);
|
|
64
|
+
return tokenRequest(http, discovery, client, form, "service_token_failed");
|
|
65
|
+
}
|
|
66
|
+
async function revokeRefreshToken(http, discovery, client, refreshToken) {
|
|
67
|
+
if (!discovery.revocation_endpoint) return;
|
|
68
|
+
const form = new URLSearchParams({ token: refreshToken, token_type_hint: "refresh_token" });
|
|
69
|
+
const headers = authenticate(client, form);
|
|
70
|
+
await http.postForm(discovery.revocation_endpoint, form, headers).catch(() => void 0);
|
|
71
|
+
}
|
|
72
|
+
async function fetchUserInfo(http, discovery, accessToken) {
|
|
73
|
+
if (!discovery.userinfo_endpoint) {
|
|
74
|
+
throw new IdpError("userinfo_failed", "The auth server has no userinfo endpoint.");
|
|
75
|
+
}
|
|
76
|
+
let answer;
|
|
77
|
+
try {
|
|
78
|
+
answer = await http.get(discovery.userinfo_endpoint, {
|
|
79
|
+
authorization: `Bearer ${accessToken}`
|
|
80
|
+
});
|
|
81
|
+
} catch (cause) {
|
|
82
|
+
throw new IdpError("userinfo_failed", "The userinfo endpoint didn't answer.", { cause });
|
|
83
|
+
}
|
|
84
|
+
if (!answer.ok) {
|
|
85
|
+
throw new IdpError("userinfo_failed", `The userinfo endpoint answered ${answer.status}.`, {
|
|
86
|
+
status: answer.status
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
if (!answer.data || typeof answer.data !== "object" || Array.isArray(answer.data)) {
|
|
90
|
+
throw new IdpError("userinfo_failed", "The userinfo answer isn't an object.");
|
|
91
|
+
}
|
|
92
|
+
return answer.data;
|
|
93
|
+
}
|
|
94
|
+
export {
|
|
95
|
+
clientCredentials,
|
|
96
|
+
exchangeCode,
|
|
97
|
+
fetchUserInfo,
|
|
98
|
+
refreshTokens,
|
|
99
|
+
revokeRefreshToken
|
|
100
|
+
};
|