nextidp 0.1.5 → 0.4.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 +43 -0
- package/README.md +86 -0
- package/dist/cjs/access-token.d.ts +29 -4
- package/dist/cjs/access-token.js +53 -10
- package/dist/cjs/config.d.ts +36 -0
- package/dist/cjs/config.js +36 -1
- package/dist/cjs/discovery.d.ts +2 -0
- package/dist/cjs/discovery.js +2 -0
- package/dist/cjs/errors.d.ts +16 -3
- package/dist/cjs/errors.js +7 -1
- package/dist/cjs/exchange.d.ts +21 -0
- package/dist/cjs/exchange.js +76 -0
- package/dist/cjs/express.d.ts +12 -1
- package/dist/cjs/express.js +7 -0
- package/dist/cjs/fastify.d.ts +13 -1
- package/dist/cjs/fastify.js +14 -0
- package/dist/cjs/hono.d.ts +12 -1
- package/dist/cjs/hono.js +8 -0
- package/dist/cjs/id-token.js +1 -1
- package/dist/cjs/idp.d.ts +27 -1
- package/dist/cjs/idp.js +76 -8
- package/dist/cjs/index.d.ts +3 -2
- package/dist/cjs/nestjs.d.ts +2 -1
- package/dist/cjs/next.d.ts +12 -1
- package/dist/cjs/next.js +4 -0
- package/dist/cjs/node-adapter.d.ts +2 -0
- package/dist/cjs/node-adapter.js +8 -0
- package/dist/cjs/node.d.ts +7 -1
- package/dist/cjs/node.js +1 -0
- package/dist/cjs/pushed-authorization.d.ts +9 -0
- package/dist/cjs/pushed-authorization.js +66 -0
- package/dist/cjs/service.d.ts +3 -0
- package/dist/cjs/service.js +13 -41
- package/dist/cjs/token-cache.d.ts +18 -0
- package/dist/cjs/token-cache.js +75 -0
- package/dist/cjs/tokens.d.ts +13 -0
- package/dist/cjs/tokens.js +19 -0
- package/dist/esm/access-token.d.ts +29 -4
- package/dist/esm/access-token.js +50 -9
- package/dist/esm/config.d.ts +36 -0
- package/dist/esm/config.js +35 -1
- package/dist/esm/discovery.d.ts +2 -0
- package/dist/esm/discovery.js +2 -0
- package/dist/esm/errors.d.ts +16 -3
- package/dist/esm/errors.js +7 -1
- package/dist/esm/exchange.d.ts +21 -0
- package/dist/esm/exchange.js +52 -0
- package/dist/esm/express.d.ts +12 -1
- package/dist/esm/express.js +7 -0
- package/dist/esm/fastify.d.ts +13 -1
- package/dist/esm/fastify.js +15 -1
- package/dist/esm/hono.d.ts +12 -1
- package/dist/esm/hono.js +8 -0
- package/dist/esm/id-token.js +1 -1
- package/dist/esm/idp.d.ts +27 -1
- package/dist/esm/idp.js +79 -9
- package/dist/esm/index.d.ts +3 -2
- package/dist/esm/nestjs.d.ts +2 -1
- package/dist/esm/next.d.ts +12 -1
- package/dist/esm/next.js +4 -0
- package/dist/esm/node-adapter.d.ts +2 -0
- package/dist/esm/node-adapter.js +8 -0
- package/dist/esm/node.d.ts +7 -1
- package/dist/esm/node.js +1 -0
- package/dist/esm/pushed-authorization.d.ts +9 -0
- package/dist/esm/pushed-authorization.js +32 -0
- package/dist/esm/service.d.ts +3 -0
- package/dist/esm/service.js +11 -41
- package/dist/esm/token-cache.d.ts +18 -0
- package/dist/esm/token-cache.js +50 -0
- package/dist/esm/tokens.d.ts +13 -0
- package/dist/esm/tokens.js +16 -0
- package/package.json +3 -2
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { TokenResponse } from "./tokens.js";
|
|
2
|
+
export type Issued = {
|
|
3
|
+
token: string;
|
|
4
|
+
until: number;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* What to keep of a token endpoint's answer: the token, and when to stop using it. One that
|
|
8
|
+
* says no lifetime isn't kept at all. `notAfter` (seconds since the epoch) caps it, for a
|
|
9
|
+
* token that must not outlive another.
|
|
10
|
+
*/
|
|
11
|
+
export declare function issued(tokens: TokenResponse, notAfter?: number): Issued;
|
|
12
|
+
export type TokenCache = {
|
|
13
|
+
/** The token kept under `key`, or a new one from `issue`; calls at once share one request. */
|
|
14
|
+
get(key: string, issue: () => Promise<Issued>, fresh?: boolean): Promise<string>;
|
|
15
|
+
/** Forgets a token, wherever it's kept. */
|
|
16
|
+
drop(token: string): void;
|
|
17
|
+
};
|
|
18
|
+
export declare function createTokenCache(maxKept: number): TokenCache;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var token_cache_exports = {};
|
|
20
|
+
__export(token_cache_exports, {
|
|
21
|
+
createTokenCache: () => createTokenCache,
|
|
22
|
+
issued: () => issued
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(token_cache_exports);
|
|
25
|
+
const RENEW_BEFORE_S = 60;
|
|
26
|
+
function issued(tokens, notAfter) {
|
|
27
|
+
const lifetime = tokens.expires_in ?? 0;
|
|
28
|
+
const renewIn = lifetime - Math.min(RENEW_BEFORE_S, lifetime / 2);
|
|
29
|
+
let until = Date.now() + Math.max(0, renewIn) * 1e3;
|
|
30
|
+
if (notAfter !== void 0) until = Math.min(until, (notAfter - RENEW_BEFORE_S) * 1e3);
|
|
31
|
+
return { token: tokens.access_token, until };
|
|
32
|
+
}
|
|
33
|
+
function createTokenCache(maxKept) {
|
|
34
|
+
const kept = /* @__PURE__ */ new Map();
|
|
35
|
+
const prune = (now) => {
|
|
36
|
+
for (const [key, entry] of kept) {
|
|
37
|
+
if (entry.issued && entry.issued.until <= now) kept.delete(key);
|
|
38
|
+
}
|
|
39
|
+
const oldest = kept.keys().next();
|
|
40
|
+
if (kept.size >= maxKept && !oldest.done) kept.delete(oldest.value);
|
|
41
|
+
};
|
|
42
|
+
return {
|
|
43
|
+
async get(key, issue, fresh = false) {
|
|
44
|
+
const now = Date.now();
|
|
45
|
+
const known = kept.get(key);
|
|
46
|
+
if (known && !fresh) {
|
|
47
|
+
if (!known.issued) return (await known.pending).token;
|
|
48
|
+
if (known.issued.until > now) return known.issued.token;
|
|
49
|
+
}
|
|
50
|
+
if (kept.size >= maxKept) prune(now);
|
|
51
|
+
const entry = { pending: issue() };
|
|
52
|
+
entry.pending.then(
|
|
53
|
+
(value) => {
|
|
54
|
+
entry.issued = value;
|
|
55
|
+
},
|
|
56
|
+
() => void 0
|
|
57
|
+
);
|
|
58
|
+
kept.set(key, entry);
|
|
59
|
+
try {
|
|
60
|
+
return (await entry.pending).token;
|
|
61
|
+
} catch (error) {
|
|
62
|
+
if (kept.get(key) === entry) kept.delete(key);
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
drop(token) {
|
|
67
|
+
for (const [key, entry] of kept) if (entry.issued?.token === token) kept.delete(key);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
72
|
+
0 && (module.exports = {
|
|
73
|
+
createTokenCache,
|
|
74
|
+
issued
|
|
75
|
+
});
|
package/dist/cjs/tokens.d.ts
CHANGED
|
@@ -14,6 +14,10 @@ export type Client = {
|
|
|
14
14
|
clientId: string;
|
|
15
15
|
clientSecret: string | undefined;
|
|
16
16
|
};
|
|
17
|
+
/** A public client names itself in the body; a confidential one authenticates with Basic. */
|
|
18
|
+
export declare function authenticate(client: Client, form: URLSearchParams): Record<string, string>;
|
|
19
|
+
/** The OAuth error code in a refusal, if it's a plain word; never its description. */
|
|
20
|
+
export declare function oauthError(data: unknown): string | undefined;
|
|
17
21
|
/** Redeems an authorization code, proving with the PKCE verifier that this app asked for it. */
|
|
18
22
|
export declare function exchangeCode(http: Http, discovery: Discovery, client: Client, input: {
|
|
19
23
|
code: string;
|
|
@@ -31,6 +35,15 @@ export declare function clientCredentials(http: Http, discovery: Discovery, clie
|
|
|
31
35
|
scope: string | undefined;
|
|
32
36
|
resource: string | undefined;
|
|
33
37
|
}): Promise<TokenResponse>;
|
|
38
|
+
/**
|
|
39
|
+
* Token exchange (RFC 8693): the access token this API was called with, traded for one meant
|
|
40
|
+
* for another API, for the same person, with this client's own credentials.
|
|
41
|
+
*/
|
|
42
|
+
export declare function exchangeAccessToken(http: Http, discovery: Discovery, client: Client, input: {
|
|
43
|
+
subjectToken: string;
|
|
44
|
+
resource: string;
|
|
45
|
+
scope: string | undefined;
|
|
46
|
+
}): Promise<TokenResponse>;
|
|
34
47
|
/** Revokes a refresh token at sign-out, when the server offers revocation. Never throws. */
|
|
35
48
|
export declare function revokeRefreshToken(http: Http, discovery: Discovery, client: Client, refreshToken: string): Promise<void>;
|
|
36
49
|
/** The userinfo endpoint's claims for an access token. */
|
package/dist/cjs/tokens.js
CHANGED
|
@@ -28,9 +28,12 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
28
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
29
|
var tokens_exports = {};
|
|
30
30
|
__export(tokens_exports, {
|
|
31
|
+
authenticate: () => authenticate,
|
|
31
32
|
clientCredentials: () => clientCredentials,
|
|
33
|
+
exchangeAccessToken: () => exchangeAccessToken,
|
|
32
34
|
exchangeCode: () => exchangeCode,
|
|
33
35
|
fetchUserInfo: () => fetchUserInfo,
|
|
36
|
+
oauthError: () => oauthError,
|
|
34
37
|
refreshTokens: () => refreshTokens,
|
|
35
38
|
revokeRefreshToken: () => revokeRefreshToken
|
|
36
39
|
});
|
|
@@ -100,6 +103,19 @@ function clientCredentials(http, discovery, client, input) {
|
|
|
100
103
|
if (input.resource) form.set("resource", input.resource);
|
|
101
104
|
return tokenRequest(http, discovery, client, form, "service_token_failed");
|
|
102
105
|
}
|
|
106
|
+
const TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange";
|
|
107
|
+
const ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
|
|
108
|
+
function exchangeAccessToken(http, discovery, client, input) {
|
|
109
|
+
const form = new URLSearchParams({
|
|
110
|
+
grant_type: TOKEN_EXCHANGE_GRANT,
|
|
111
|
+
subject_token: input.subjectToken,
|
|
112
|
+
subject_token_type: ACCESS_TOKEN_TYPE,
|
|
113
|
+
requested_token_type: ACCESS_TOKEN_TYPE,
|
|
114
|
+
resource: input.resource
|
|
115
|
+
});
|
|
116
|
+
if (input.scope) form.set("scope", input.scope);
|
|
117
|
+
return tokenRequest(http, discovery, client, form, "token_exchange_failed");
|
|
118
|
+
}
|
|
103
119
|
async function revokeRefreshToken(http, discovery, client, refreshToken) {
|
|
104
120
|
if (!discovery.revocation_endpoint) return;
|
|
105
121
|
const form = new URLSearchParams({ token: refreshToken, token_type_hint: "refresh_token" });
|
|
@@ -130,9 +146,12 @@ async function fetchUserInfo(http, discovery, accessToken) {
|
|
|
130
146
|
}
|
|
131
147
|
// Annotate the CommonJS export names for ESM import in node:
|
|
132
148
|
0 && (module.exports = {
|
|
149
|
+
authenticate,
|
|
133
150
|
clientCredentials,
|
|
151
|
+
exchangeAccessToken,
|
|
134
152
|
exchangeCode,
|
|
135
153
|
fetchUserInfo,
|
|
154
|
+
oauthError,
|
|
136
155
|
refreshTokens,
|
|
137
156
|
revokeRefreshToken
|
|
138
157
|
});
|
|
@@ -17,6 +17,11 @@ export type AccessToken = {
|
|
|
17
17
|
expiresAt: number | undefined;
|
|
18
18
|
/** Every claim, or every field of the introspection answer. */
|
|
19
19
|
claims: Record<string, unknown>;
|
|
20
|
+
/**
|
|
21
|
+
* The token itself, as the caller sent it: for `exchangeToken`, never to pass on to
|
|
22
|
+
* another API. Don't log it.
|
|
23
|
+
*/
|
|
24
|
+
raw: string;
|
|
20
25
|
};
|
|
21
26
|
export type TokenRequirements = {
|
|
22
27
|
/** Every one of these scopes must be granted. */
|
|
@@ -25,7 +30,7 @@ export type TokenRequirements = {
|
|
|
25
30
|
/** The token in an `Authorization: Bearer …` header, or undefined. */
|
|
26
31
|
export declare function bearerToken(authorization: string | null | undefined): string | undefined;
|
|
27
32
|
/** Throws insufficient_scope (403) unless every required scope was granted. */
|
|
28
|
-
export declare function requireScopes(token:
|
|
33
|
+
export declare function requireScopes<T extends Pick<AccessToken, "scopes">>(token: T, required?: readonly string[]): T;
|
|
29
34
|
/** Whether a token is a JWT (three parts, a header that decodes) rather than opaque. */
|
|
30
35
|
export declare function isJwt(token: string): boolean;
|
|
31
36
|
/**
|
|
@@ -33,18 +38,38 @@ export declare function isJwt(token: string): boolean;
|
|
|
33
38
|
* token) passes for one; a signature by one of the issuer's keys (asymmetric algorithms
|
|
34
39
|
* only); `iss`; `aud` naming this API; and not expired (60 seconds of clock skew).
|
|
35
40
|
*/
|
|
36
|
-
export declare function verifyJwtAccessToken(token: string, keys: JWTVerifyGetKey, config: Pick<ApiConfig, "issuer" | "audience">): Promise<AccessToken
|
|
41
|
+
export declare function verifyJwtAccessToken(token: string, keys: JWTVerifyGetKey, config: Pick<ApiConfig, "issuer" | "audience">): Promise<Omit<AccessToken, "raw">>;
|
|
37
42
|
/**
|
|
38
43
|
* Asks the auth server whether an opaque token is active, with this API's client
|
|
39
44
|
* credentials. The auth server answers only for tokens this client issued, or tokens for an
|
|
40
45
|
* API this client is linked to; to anything else it answers inactive.
|
|
41
46
|
*/
|
|
42
|
-
export declare function introspect(http: Http, discovery: Discovery, config: ApiConfig, token: string): Promise<AccessToken
|
|
47
|
+
export declare function introspect(http: Http, discovery: Discovery, config: ApiConfig, token: string): Promise<Omit<AccessToken, "raw">>;
|
|
43
48
|
/**
|
|
44
49
|
* The WWW-Authenticate challenge for a refused request (RFC 6750 3): no error code when
|
|
45
|
-
* there was no token at all, else invalid_token or insufficient_scope
|
|
50
|
+
* there was no token at all, else invalid_token or insufficient_scope; then the scopes the
|
|
51
|
+
* route needs, every one of them, and the protected resource metadata (RFC 9728 5.1) when
|
|
52
|
+
* the API publishes it, which is how an MCP client finds the auth server.
|
|
46
53
|
*/
|
|
47
54
|
export declare function bearerChallenge(error: IdpError): string;
|
|
55
|
+
/** The protected resource metadata document (RFC 9728 2). */
|
|
56
|
+
export type ResourceMetadata = {
|
|
57
|
+
resource: string;
|
|
58
|
+
authorization_servers: string[];
|
|
59
|
+
bearer_methods_supported: ["header"];
|
|
60
|
+
scopes_supported?: string[];
|
|
61
|
+
resource_name?: string;
|
|
62
|
+
};
|
|
63
|
+
export declare function resourceMetadataDocument(config: Pick<ApiConfig, "issuer" | "audience" | "resourceMetadata">): ResourceMetadata | undefined;
|
|
64
|
+
/**
|
|
65
|
+
* The answer for a request to the protected resource metadata's path, or undefined for any
|
|
66
|
+
* other request (or while it's off). Public and the same for everyone, so any origin may read
|
|
67
|
+
* it: MCP clients in a browser (the MCP Inspector) fetch it too.
|
|
68
|
+
*/
|
|
69
|
+
export declare function resourceMetadataResponse(config: Pick<ApiConfig, "issuer" | "audience" | "resourceMetadata">, request: {
|
|
70
|
+
method: string;
|
|
71
|
+
url: string;
|
|
72
|
+
}): Response | undefined;
|
|
48
73
|
/** The status, challenge and JSON body to answer a refused request with. */
|
|
49
74
|
export declare function tokenRefusal(error: IdpError): {
|
|
50
75
|
status: 401 | 403;
|
package/dist/esm/access-token.js
CHANGED
|
@@ -2,7 +2,7 @@ import { decodeProtectedHeader, jwtVerify } from "jose";
|
|
|
2
2
|
import * as v from "valibot";
|
|
3
3
|
import { IdpError } from "./errors.js";
|
|
4
4
|
const ACCESS_TOKEN_TYPES = /* @__PURE__ */ new Set(["at+jwt", "application/at+jwt"]);
|
|
5
|
-
const ALGORITHMS = ["RS256", "PS256", "ES256", "EdDSA"];
|
|
5
|
+
const ALGORITHMS = ["RS256", "PS256", "ES256", "Ed25519", "EdDSA"];
|
|
6
6
|
const BEARER = /^Bearer +([A-Za-z0-9\-._~+/]+=*)\s*$/i;
|
|
7
7
|
const invalid = (message, cause) => new IdpError("invalid_token", message, { status: 401, cause });
|
|
8
8
|
function bearerToken(authorization) {
|
|
@@ -123,15 +123,54 @@ function quoted(value) {
|
|
|
123
123
|
return `"${value.replace(/[\\"]/g, "\\$&")}"`;
|
|
124
124
|
}
|
|
125
125
|
function bearerChallenge(error) {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
parts.push(`scope=${quoted(error.scopes.join(" "))}`);
|
|
126
|
+
const parts = [];
|
|
127
|
+
if (error.code !== "missing_token") {
|
|
128
|
+
parts.push(
|
|
129
|
+
`error=${quoted(error.code === "insufficient_scope" ? "insufficient_scope" : "invalid_token")}`,
|
|
130
|
+
`error_description=${quoted(error.message)}`
|
|
131
|
+
);
|
|
133
132
|
}
|
|
134
|
-
|
|
133
|
+
if (error.scopes?.length) parts.push(`scope=${quoted(error.scopes.join(" "))}`);
|
|
134
|
+
if (error.resourceMetadata) parts.push(`resource_metadata=${quoted(error.resourceMetadata)}`);
|
|
135
|
+
return parts.length > 0 ? `Bearer ${parts.join(", ")}` : "Bearer";
|
|
136
|
+
}
|
|
137
|
+
function resourceMetadataDocument(config) {
|
|
138
|
+
const metadata = config.resourceMetadata;
|
|
139
|
+
if (!metadata) return void 0;
|
|
140
|
+
return {
|
|
141
|
+
// Exactly as the auth server lists it: clients compare it as a string.
|
|
142
|
+
resource: config.audience,
|
|
143
|
+
authorization_servers: [config.issuer],
|
|
144
|
+
bearer_methods_supported: ["header"],
|
|
145
|
+
...metadata.scopes.length > 0 ? { scopes_supported: metadata.scopes } : {},
|
|
146
|
+
...metadata.name ? { resource_name: metadata.name } : {}
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
const METADATA_CORS = {
|
|
150
|
+
"access-control-allow-origin": "*",
|
|
151
|
+
"access-control-allow-methods": "GET, HEAD, OPTIONS",
|
|
152
|
+
"access-control-allow-headers": "*"
|
|
153
|
+
};
|
|
154
|
+
function resourceMetadataResponse(config, request) {
|
|
155
|
+
const document = resourceMetadataDocument(config);
|
|
156
|
+
if (!document || !config.resourceMetadata) return void 0;
|
|
157
|
+
if (new URL(request.url).pathname.replace(/\/+$/, "") !== config.resourceMetadata.path) {
|
|
158
|
+
return void 0;
|
|
159
|
+
}
|
|
160
|
+
if (request.method === "OPTIONS") {
|
|
161
|
+
return new Response(null, { status: 204, headers: METADATA_CORS });
|
|
162
|
+
}
|
|
163
|
+
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
164
|
+
return new Response(null, { status: 405, headers: { allow: "GET, HEAD, OPTIONS" } });
|
|
165
|
+
}
|
|
166
|
+
return new Response(request.method === "HEAD" ? null : JSON.stringify(document), {
|
|
167
|
+
status: 200,
|
|
168
|
+
headers: {
|
|
169
|
+
"content-type": "application/json",
|
|
170
|
+
"cache-control": "public, max-age=3600",
|
|
171
|
+
...METADATA_CORS
|
|
172
|
+
}
|
|
173
|
+
});
|
|
135
174
|
}
|
|
136
175
|
function tokenRefusal(error) {
|
|
137
176
|
const status = error.code === "insufficient_scope" ? 403 : 401;
|
|
@@ -151,6 +190,8 @@ export {
|
|
|
151
190
|
introspect,
|
|
152
191
|
isJwt,
|
|
153
192
|
requireScopes,
|
|
193
|
+
resourceMetadataDocument,
|
|
194
|
+
resourceMetadataResponse,
|
|
154
195
|
tokenRefusal,
|
|
155
196
|
verifyJwtAccessToken
|
|
156
197
|
};
|
package/dist/esm/config.d.ts
CHANGED
|
@@ -32,6 +32,18 @@ export type IdpOptions = {
|
|
|
32
32
|
* so only tokens for this API pass.
|
|
33
33
|
*/
|
|
34
34
|
acceptOwnTokens?: boolean | undefined;
|
|
35
|
+
/**
|
|
36
|
+
* For an API, an MCP server above all: publish its protected resource metadata (RFC 9728),
|
|
37
|
+
* which tells a client which auth server to sign in with. `audience` must then be an http(s)
|
|
38
|
+
* URL: the document is served at `/.well-known/oauth-protected-resource` followed by its
|
|
39
|
+
* path (each adapter's `resourceMetadata()`), and every 401 and 403 names it in
|
|
40
|
+
* `WWW-Authenticate`. `scopes` are listed as `scopes_supported`, `name` as `resource_name`.
|
|
41
|
+
* Default off (IDP_RESOURCE_METADATA=true turns it on).
|
|
42
|
+
*/
|
|
43
|
+
resourceMetadata?: boolean | {
|
|
44
|
+
scopes?: readonly string[] | undefined;
|
|
45
|
+
name?: string | undefined;
|
|
46
|
+
} | undefined;
|
|
35
47
|
/** Where nextidp's routes live. Default `/auth`: the redirect URI is `<appUrl>/auth/callback`. */
|
|
36
48
|
basePath?: string | undefined;
|
|
37
49
|
/** Where a sign-in lands when it wasn't asked to return somewhere. Default `/`. */
|
|
@@ -57,6 +69,17 @@ export type IdpOptions = {
|
|
|
57
69
|
* `onError` is told. Costs one more request. Default false.
|
|
58
70
|
*/
|
|
59
71
|
userinfo?: boolean | undefined;
|
|
72
|
+
/**
|
|
73
|
+
* Start each sign-in with a pushed authorization request (RFC 9126): `/login` posts the
|
|
74
|
+
* sign-in's parameters to the auth server first, authenticated as at the token endpoint,
|
|
75
|
+
* and sends the browser to authorize with only `client_id` and the `request_uri` it got
|
|
76
|
+
* back, so nothing in the browser, its history or a log can be read or changed. `"auto"`
|
|
77
|
+
* pushes when discovery advertises the endpoint; `true` requires it, and a sign-in fails
|
|
78
|
+
* without it. A push that fails is a 503, never an ordinary authorize request instead.
|
|
79
|
+
* PKCE, `state` and `nonce` already protect the flow; this costs one more request per
|
|
80
|
+
* sign-in. Default false.
|
|
81
|
+
*/
|
|
82
|
+
pushedAuthorization?: boolean | "auto" | undefined;
|
|
60
83
|
/** How long the session cookie lasts, in seconds, renewed at every refresh. Default 7 days. */
|
|
61
84
|
sessionMaxAge?: number | undefined;
|
|
62
85
|
/** The start of this app's cookie names. Default `nextidp`. */
|
|
@@ -87,7 +110,19 @@ export type ApiConfig = {
|
|
|
87
110
|
clientSecret: string | undefined;
|
|
88
111
|
/** See IdpOptions.acceptOwnTokens. */
|
|
89
112
|
acceptOwnTokens: boolean;
|
|
113
|
+
/** See IdpOptions.resourceMetadata: where it's served, and what it says. */
|
|
114
|
+
resourceMetadata: ResourceMetadataConfig | undefined;
|
|
115
|
+
};
|
|
116
|
+
export type ResourceMetadataConfig = {
|
|
117
|
+
/** The document's URL: the audience's origin, the well-known path, then its path. */
|
|
118
|
+
url: string;
|
|
119
|
+
/** Its path alone, for matching a request. */
|
|
120
|
+
path: string;
|
|
121
|
+
scopes: string[];
|
|
122
|
+
name: string | undefined;
|
|
90
123
|
};
|
|
124
|
+
/** RFC 9728 3.1: the well-known path goes between the host and the resource's own path. */
|
|
125
|
+
export declare const RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
|
|
91
126
|
/** What a service needs to get tokens of its own: a confidential client. */
|
|
92
127
|
export type ServiceConfig = {
|
|
93
128
|
issuer: string;
|
|
@@ -116,6 +151,7 @@ export type IdpConfig = {
|
|
|
116
151
|
signOutOfIdp: boolean;
|
|
117
152
|
reauthenticateAfterSignOut: boolean;
|
|
118
153
|
userinfo: boolean;
|
|
154
|
+
pushedAuthorization: boolean | "auto";
|
|
119
155
|
sessionMaxAge: number;
|
|
120
156
|
/** https: cookies are Secure, with `__Host-` names (`__Secure-` for `signedOut`). */
|
|
121
157
|
secure: boolean;
|
package/dist/esm/config.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { IdpError } from "./errors.js";
|
|
2
2
|
import { safePath } from "./return-path.js";
|
|
3
|
+
const RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
|
|
3
4
|
const DEFAULT_SCOPES = ["openid", "profile", "email", "offline_access"];
|
|
4
5
|
const SEVEN_DAYS = 7 * 24 * 60 * 60;
|
|
5
6
|
const MIN_SECRET_LENGTH = 32;
|
|
@@ -88,15 +89,42 @@ function resolveApiConfig(options) {
|
|
|
88
89
|
if (!audience && !problems.some((p) => p.startsWith("audience"))) {
|
|
89
90
|
problems.push("audience (IDP_AUDIENCE) is required to check access tokens: this API's URI");
|
|
90
91
|
}
|
|
92
|
+
const resourceMetadata = audience ? resourceMetadataConfig(options, env, audience, problems) : void 0;
|
|
91
93
|
if (problems.length > 0 || !issuer || !audience) throw misconfigured(problems);
|
|
92
94
|
return {
|
|
93
95
|
issuer: issuer.href.replace(/\/+$/, ""),
|
|
94
96
|
audience,
|
|
95
97
|
clientId: pick(options.clientId, env, "IDP_CLIENT_ID"),
|
|
96
98
|
clientSecret: pick(options.clientSecret, env, "IDP_CLIENT_SECRET"),
|
|
97
|
-
acceptOwnTokens: options.acceptOwnTokens ?? false
|
|
99
|
+
acceptOwnTokens: options.acceptOwnTokens ?? false,
|
|
100
|
+
resourceMetadata
|
|
98
101
|
};
|
|
99
102
|
}
|
|
103
|
+
function resourceMetadataConfig(options, env, audience, problems) {
|
|
104
|
+
const setting = options.resourceMetadata ?? pick(void 0, env, "IDP_RESOURCE_METADATA");
|
|
105
|
+
if (setting === void 0 || setting === false || setting === "false") return void 0;
|
|
106
|
+
if (typeof setting === "string" && setting !== "true") {
|
|
107
|
+
problems.push('resourceMetadata (IDP_RESOURCE_METADATA) must be "true" or "false"');
|
|
108
|
+
return void 0;
|
|
109
|
+
}
|
|
110
|
+
const url = URL.canParse(audience) ? new URL(audience) : void 0;
|
|
111
|
+
if (!url || url.protocol !== "https:" && url.protocol !== "http:" || url.search || url.hash) {
|
|
112
|
+
problems.push(
|
|
113
|
+
"resourceMetadata needs audience (IDP_AUDIENCE) to be an http(s) URL with no query, like https://mcp.example.com/mcp"
|
|
114
|
+
);
|
|
115
|
+
return void 0;
|
|
116
|
+
}
|
|
117
|
+
const own = url.pathname.replace(/\/+$/, "");
|
|
118
|
+
const path2 = `${RESOURCE_METADATA_PATH}${own}`;
|
|
119
|
+
const details = typeof setting === "object" ? setting : {};
|
|
120
|
+
const scopes = [...new Set((details.scopes ?? []).map((scope) => scope.trim()))].filter(
|
|
121
|
+
(scope) => scope !== "" && scope !== "offline_access"
|
|
122
|
+
);
|
|
123
|
+
if (scopes.some((scope) => /\s/.test(scope))) {
|
|
124
|
+
problems.push("resourceMetadata's scopes can't hold spaces");
|
|
125
|
+
}
|
|
126
|
+
return { url: `${url.origin}${path2}`, path: path2, scopes, name: details.name?.trim() || void 0 };
|
|
127
|
+
}
|
|
100
128
|
function resolveServiceConfig(options) {
|
|
101
129
|
const env = envOf(options);
|
|
102
130
|
const problems = [];
|
|
@@ -158,6 +186,10 @@ function resolveConfig(options) {
|
|
|
158
186
|
const afterSignIn = path(options.afterSignIn, "afterSignIn", "/", problems);
|
|
159
187
|
const afterSignOut = path(options.afterSignOut, "afterSignOut", "/", problems);
|
|
160
188
|
const errorPath = path(options.errorPath, "errorPath", "/", problems);
|
|
189
|
+
const pushedAuthorization = options.pushedAuthorization ?? false;
|
|
190
|
+
if (pushedAuthorization !== true && pushedAuthorization !== false && pushedAuthorization !== "auto") {
|
|
191
|
+
problems.push('pushedAuthorization must be true, false or "auto"');
|
|
192
|
+
}
|
|
161
193
|
const sessionMaxAge = options.sessionMaxAge ?? SEVEN_DAYS;
|
|
162
194
|
if (!Number.isInteger(sessionMaxAge) || sessionMaxAge < 60) {
|
|
163
195
|
problems.push("sessionMaxAge must be a whole number of seconds, at least 60");
|
|
@@ -193,6 +225,7 @@ function resolveConfig(options) {
|
|
|
193
225
|
signOutOfIdp: options.signOutOfIdp ?? false,
|
|
194
226
|
reauthenticateAfterSignOut: options.reauthenticateAfterSignOut ?? false,
|
|
195
227
|
userinfo: options.userinfo ?? false,
|
|
228
|
+
pushedAuthorization,
|
|
196
229
|
sessionMaxAge,
|
|
197
230
|
secure,
|
|
198
231
|
cookies: {
|
|
@@ -207,6 +240,7 @@ function resolveConfig(options) {
|
|
|
207
240
|
}
|
|
208
241
|
export {
|
|
209
242
|
DEFAULT_SCOPES,
|
|
243
|
+
RESOURCE_METADATA_PATH,
|
|
210
244
|
resolveApiConfig,
|
|
211
245
|
resolveConfig,
|
|
212
246
|
resolveServiceConfig
|
package/dist/esm/discovery.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ declare const DiscoverySchema: v.ObjectSchema<{
|
|
|
11
11
|
readonly introspection_endpoint: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UrlAction<string, undefined>]>, undefined>;
|
|
12
12
|
/** RP-initiated logout: where to send someone to sign out of the auth server too. */
|
|
13
13
|
readonly end_session_endpoint: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UrlAction<string, undefined>]>, undefined>;
|
|
14
|
+
/** RFC 9126: where a sign-in's parameters can be pushed first (`pushedAuthorization`). */
|
|
15
|
+
readonly pushed_authorization_request_endpoint: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UrlAction<string, undefined>]>, undefined>;
|
|
14
16
|
readonly id_token_signing_alg_values_supported: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
|
|
15
17
|
}, undefined>;
|
|
16
18
|
export type Discovery = v.InferOutput<typeof DiscoverySchema>;
|
package/dist/esm/discovery.js
CHANGED
|
@@ -12,6 +12,8 @@ const DiscoverySchema = v.object({
|
|
|
12
12
|
introspection_endpoint: v.optional(Url),
|
|
13
13
|
/** RP-initiated logout: where to send someone to sign out of the auth server too. */
|
|
14
14
|
end_session_endpoint: v.optional(Url),
|
|
15
|
+
/** RFC 9126: where a sign-in's parameters can be pushed first (`pushedAuthorization`). */
|
|
16
|
+
pushed_authorization_request_endpoint: v.optional(Url),
|
|
15
17
|
id_token_signing_alg_values_supported: v.optional(v.array(v.string()))
|
|
16
18
|
});
|
|
17
19
|
const ONE_HOUR = 60 * 60 * 1e3;
|
package/dist/esm/errors.d.ts
CHANGED
|
@@ -32,6 +32,13 @@ export type IdpErrorCode = SignInErrorCode
|
|
|
32
32
|
| "insufficient_scope"
|
|
33
33
|
/** The token endpoint refused this service's client credentials, or didn't answer. */
|
|
34
34
|
| "service_token_failed"
|
|
35
|
+
/** The token endpoint refused a token exchange (RFC 8693), or didn't answer. */
|
|
36
|
+
| "token_exchange_failed"
|
|
37
|
+
/**
|
|
38
|
+
* A sign-in's pushed authorization request (RFC 9126) was refused or got no answer, or
|
|
39
|
+
* `pushedAuthorization: true` and the auth server doesn't advertise the endpoint.
|
|
40
|
+
*/
|
|
41
|
+
| "pushed_authorization_failed"
|
|
35
42
|
/** A back-channel logout request's token didn't verify, or isn't a logout token. */
|
|
36
43
|
| "invalid_logout_token";
|
|
37
44
|
/** The three codes an API answers a caller with; see `tokenErrorResponse`. */
|
|
@@ -52,12 +59,18 @@ export declare class IdpError extends Error {
|
|
|
52
59
|
* the status to answer the caller with (401 or 403).
|
|
53
60
|
*/
|
|
54
61
|
readonly status: number | undefined;
|
|
55
|
-
/** For
|
|
62
|
+
/** For a token error: the scopes the route needs, for the WWW-Authenticate challenge. */
|
|
56
63
|
readonly scopes: readonly string[] | undefined;
|
|
64
|
+
/**
|
|
65
|
+
* For a token error: this API's protected resource metadata (RFC 9728), named in the
|
|
66
|
+
* challenge so a client (an MCP client) can find the auth server.
|
|
67
|
+
*/
|
|
68
|
+
readonly resourceMetadata: string | undefined;
|
|
57
69
|
constructor(code: IdpErrorCode, message: string, options?: {
|
|
58
|
-
status?: number;
|
|
70
|
+
status?: number | undefined;
|
|
59
71
|
cause?: unknown;
|
|
60
|
-
scopes?: readonly string[];
|
|
72
|
+
scopes?: readonly string[] | undefined;
|
|
73
|
+
resourceMetadata?: string | undefined;
|
|
61
74
|
});
|
|
62
75
|
}
|
|
63
76
|
export declare function isIdpError(error: unknown): error is IdpError;
|
package/dist/esm/errors.js
CHANGED
|
@@ -20,13 +20,19 @@ class IdpError extends Error {
|
|
|
20
20
|
* the status to answer the caller with (401 or 403).
|
|
21
21
|
*/
|
|
22
22
|
status;
|
|
23
|
-
/** For
|
|
23
|
+
/** For a token error: the scopes the route needs, for the WWW-Authenticate challenge. */
|
|
24
24
|
scopes;
|
|
25
|
+
/**
|
|
26
|
+
* For a token error: this API's protected resource metadata (RFC 9728), named in the
|
|
27
|
+
* challenge so a client (an MCP client) can find the auth server.
|
|
28
|
+
*/
|
|
29
|
+
resourceMetadata;
|
|
25
30
|
constructor(code, message, options) {
|
|
26
31
|
super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
|
|
27
32
|
this.code = code;
|
|
28
33
|
this.status = options?.status;
|
|
29
34
|
this.scopes = options?.scopes;
|
|
35
|
+
this.resourceMetadata = options?.resourceMetadata;
|
|
30
36
|
}
|
|
31
37
|
}
|
|
32
38
|
function isIdpError(error) {
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ServiceConfig } from "./config.js";
|
|
2
|
+
import type { Discovery } from "./discovery.js";
|
|
3
|
+
import type { Http } from "./http.js";
|
|
4
|
+
export type ExchangeTokenOptions = {
|
|
5
|
+
/** The access token this API was called with (the person's). */
|
|
6
|
+
subjectToken: string;
|
|
7
|
+
/** The API to get a token for, exactly as the auth server lists it (RFC 8707). */
|
|
8
|
+
resource: string;
|
|
9
|
+
/** The scopes to pass on (default: all the policy allows of the subject's). */
|
|
10
|
+
scopes?: readonly string[] | undefined;
|
|
11
|
+
/** Ask again even if a token is kept. */
|
|
12
|
+
fresh?: boolean | undefined;
|
|
13
|
+
};
|
|
14
|
+
export type TokenExchange = {
|
|
15
|
+
exchange(options: ExchangeTokenOptions): Promise<string>;
|
|
16
|
+
};
|
|
17
|
+
export declare function createTokenExchange(deps: {
|
|
18
|
+
http: Http;
|
|
19
|
+
discovery: () => Promise<Discovery>;
|
|
20
|
+
config: ServiceConfig;
|
|
21
|
+
}): TokenExchange;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { IdpError } from "./errors.js";
|
|
2
|
+
import { resourceOf, scopeOf } from "./service.js";
|
|
3
|
+
import { createTokenCache, issued } from "./token-cache.js";
|
|
4
|
+
import { exchangeAccessToken } from "./tokens.js";
|
|
5
|
+
const MAX_KEPT = 500;
|
|
6
|
+
function expiryOf(token) {
|
|
7
|
+
const [, payload] = token.split(".");
|
|
8
|
+
if (!payload) return void 0;
|
|
9
|
+
try {
|
|
10
|
+
const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
|
|
11
|
+
const exp = JSON.parse(json).exp;
|
|
12
|
+
return typeof exp === "number" ? exp : void 0;
|
|
13
|
+
} catch {
|
|
14
|
+
return void 0;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
async function sha256(value) {
|
|
18
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
|
|
19
|
+
return btoa(String.fromCharCode(...new Uint8Array(digest)));
|
|
20
|
+
}
|
|
21
|
+
function createTokenExchange(deps) {
|
|
22
|
+
const cache = createTokenCache(MAX_KEPT);
|
|
23
|
+
const client = { clientId: deps.config.clientId, clientSecret: deps.config.clientSecret };
|
|
24
|
+
return {
|
|
25
|
+
async exchange(options) {
|
|
26
|
+
const resource = resourceOf(options.resource);
|
|
27
|
+
if (!resource) {
|
|
28
|
+
throw new IdpError(
|
|
29
|
+
"misconfigured",
|
|
30
|
+
"nextidp is misconfigured: exchangeToken needs resource."
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
const scope = scopeOf(options.scopes);
|
|
34
|
+
const key = JSON.stringify([await sha256(options.subjectToken), resource, scope ?? null]);
|
|
35
|
+
return cache.get(
|
|
36
|
+
key,
|
|
37
|
+
async () => issued(
|
|
38
|
+
await exchangeAccessToken(deps.http, await deps.discovery(), client, {
|
|
39
|
+
subjectToken: options.subjectToken,
|
|
40
|
+
resource,
|
|
41
|
+
scope
|
|
42
|
+
}),
|
|
43
|
+
expiryOf(options.subjectToken)
|
|
44
|
+
),
|
|
45
|
+
options.fresh
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
export {
|
|
51
|
+
createTokenExchange
|
|
52
|
+
};
|
package/dist/esm/express.d.ts
CHANGED
|
@@ -47,6 +47,16 @@ export type ExpressIdp = Idp & {
|
|
|
47
47
|
* ```
|
|
48
48
|
*/
|
|
49
49
|
requireToken(requirements?: TokenRequirements): Middleware;
|
|
50
|
+
/**
|
|
51
|
+
* For an API with `resourceMetadata` on: answers its protected resource metadata (RFC 9728)
|
|
52
|
+
* at `/.well-known/oauth-protected-resource` and the audience's path, so MCP clients find the
|
|
53
|
+
* auth server. Mount it on the app, before anything that needs a token:
|
|
54
|
+
*
|
|
55
|
+
* ```ts
|
|
56
|
+
* app.use(auth.resourceMetadata());
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
resourceMetadata(): Middleware;
|
|
50
60
|
/** The access token `requireToken` checked for this request. */
|
|
51
61
|
tokenOf(req: IncomingMessage): AccessToken | undefined;
|
|
52
62
|
};
|
|
@@ -61,9 +71,10 @@ export type ExpressIdp = Idp & {
|
|
|
61
71
|
* ```
|
|
62
72
|
*/
|
|
63
73
|
export declare function idp(options?: IdpOptions | (() => IdpOptions)): ExpressIdp;
|
|
64
|
-
export type { AccessToken, TokenRequirements } from "./access-token.js";
|
|
74
|
+
export type { AccessToken, ResourceMetadata, TokenRequirements } from "./access-token.js";
|
|
65
75
|
export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
|
|
66
76
|
export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
|
|
77
|
+
export type { ExchangeTokenOptions } from "./exchange.js";
|
|
67
78
|
export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
|
|
68
79
|
export type { SessionOptions } from "./node-adapter.js";
|
|
69
80
|
export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
|
package/dist/esm/express.js
CHANGED
|
@@ -68,6 +68,13 @@ function idp(options) {
|
|
|
68
68
|
);
|
|
69
69
|
};
|
|
70
70
|
},
|
|
71
|
+
resourceMetadata() {
|
|
72
|
+
return (req, res, next) => {
|
|
73
|
+
node.resourceMetadata(req, res).then((handled) => {
|
|
74
|
+
if (!handled) next();
|
|
75
|
+
}, next);
|
|
76
|
+
};
|
|
77
|
+
},
|
|
71
78
|
tokenOf: (req) => req.idp?.token
|
|
72
79
|
};
|
|
73
80
|
}
|