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.
Files changed (98) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/LICENSE +21 -0
  3. package/README.md +436 -2
  4. package/dist/cjs/access-token.d.ts +56 -0
  5. package/dist/cjs/access-token.js +196 -0
  6. package/dist/cjs/config.d.ts +128 -0
  7. package/dist/cjs/config.js +233 -0
  8. package/dist/cjs/cookies.d.ts +23 -0
  9. package/dist/cjs/cookies.js +118 -0
  10. package/dist/cjs/discovery.d.ts +24 -0
  11. package/dist/cjs/discovery.js +91 -0
  12. package/dist/cjs/errors.d.ts +63 -0
  13. package/dist/cjs/errors.js +69 -0
  14. package/dist/cjs/express.d.ts +71 -0
  15. package/dist/cjs/express.js +114 -0
  16. package/dist/cjs/http.d.ts +10 -0
  17. package/dist/cjs/http.js +68 -0
  18. package/dist/cjs/id-token.d.ts +19 -0
  19. package/dist/cjs/id-token.js +77 -0
  20. package/dist/cjs/idp.d.ts +81 -0
  21. package/dist/cjs/idp.js +482 -0
  22. package/dist/cjs/index.d.ts +9 -0
  23. package/dist/cjs/index.js +53 -0
  24. package/dist/cjs/logout-token.d.ts +13 -0
  25. package/dist/cjs/logout-token.js +63 -0
  26. package/dist/cjs/nestjs.d.ts +53 -0
  27. package/dist/cjs/nestjs.js +142 -0
  28. package/dist/cjs/next.d.ts +61 -0
  29. package/dist/cjs/next.js +118 -0
  30. package/dist/cjs/node-adapter.d.ts +16 -0
  31. package/dist/cjs/node-adapter.js +76 -0
  32. package/dist/cjs/node-http.d.ts +22 -0
  33. package/dist/cjs/node-http.js +127 -0
  34. package/dist/cjs/node.d.ts +50 -0
  35. package/dist/cjs/node.js +57 -0
  36. package/dist/cjs/package.json +1 -0
  37. package/dist/cjs/pkce.d.ts +6 -0
  38. package/dist/cjs/pkce.js +49 -0
  39. package/dist/cjs/return-path.d.ts +6 -0
  40. package/dist/cjs/return-path.js +41 -0
  41. package/dist/cjs/sealed.d.ts +12 -0
  42. package/dist/cjs/sealed.js +78 -0
  43. package/dist/cjs/service.d.ts +61 -0
  44. package/dist/cjs/service.js +173 -0
  45. package/dist/cjs/session.d.ts +51 -0
  46. package/dist/cjs/session.js +97 -0
  47. package/dist/cjs/store.d.ts +58 -0
  48. package/dist/cjs/store.js +145 -0
  49. package/dist/cjs/tokens.d.ts +38 -0
  50. package/dist/cjs/tokens.js +138 -0
  51. package/dist/esm/access-token.d.ts +56 -0
  52. package/dist/esm/access-token.js +156 -0
  53. package/dist/esm/config.d.ts +128 -0
  54. package/dist/esm/config.js +206 -0
  55. package/dist/esm/cookies.d.ts +23 -0
  56. package/dist/esm/cookies.js +89 -0
  57. package/dist/esm/discovery.d.ts +24 -0
  58. package/dist/esm/discovery.js +56 -0
  59. package/dist/esm/errors.d.ts +63 -0
  60. package/dist/esm/errors.js +41 -0
  61. package/dist/esm/express.d.ts +71 -0
  62. package/dist/esm/express.js +90 -0
  63. package/dist/esm/http.d.ts +10 -0
  64. package/dist/esm/http.js +44 -0
  65. package/dist/esm/id-token.d.ts +19 -0
  66. package/dist/esm/id-token.js +51 -0
  67. package/dist/esm/idp.d.ts +81 -0
  68. package/dist/esm/idp.js +488 -0
  69. package/dist/esm/index.d.ts +9 -0
  70. package/dist/esm/index.js +30 -0
  71. package/dist/esm/logout-token.d.ts +13 -0
  72. package/dist/esm/logout-token.js +39 -0
  73. package/dist/esm/nestjs.d.ts +53 -0
  74. package/dist/esm/nestjs.js +118 -0
  75. package/dist/esm/next.d.ts +61 -0
  76. package/dist/esm/next.js +94 -0
  77. package/dist/esm/node-adapter.d.ts +16 -0
  78. package/dist/esm/node-adapter.js +60 -0
  79. package/dist/esm/node-http.d.ts +22 -0
  80. package/dist/esm/node-http.js +96 -0
  81. package/dist/esm/node.d.ts +50 -0
  82. package/dist/esm/node.js +33 -0
  83. package/dist/esm/package.json +1 -0
  84. package/dist/esm/pkce.d.ts +6 -0
  85. package/dist/esm/pkce.js +23 -0
  86. package/dist/esm/return-path.d.ts +6 -0
  87. package/dist/esm/return-path.js +17 -0
  88. package/dist/esm/sealed.d.ts +12 -0
  89. package/dist/esm/sealed.js +54 -0
  90. package/dist/esm/service.d.ts +61 -0
  91. package/dist/esm/service.js +148 -0
  92. package/dist/esm/session.d.ts +51 -0
  93. package/dist/esm/session.js +58 -0
  94. package/dist/esm/store.d.ts +58 -0
  95. package/dist/esm/store.js +119 -0
  96. package/dist/esm/tokens.d.ts +38 -0
  97. package/dist/esm/tokens.js +100 -0
  98. package/package.json +147 -3
@@ -0,0 +1,118 @@
1
+ import {
2
+ createParamDecorator,
3
+ ForbiddenException,
4
+ Inject,
5
+ Injectable,
6
+ Module,
7
+ ServiceUnavailableException,
8
+ SetMetadata,
9
+ UnauthorizedException
10
+ } from "@nestjs/common";
11
+ import { APP_GUARD, Reflector } from "@nestjs/core";
12
+ import { bearerChallenge } from "./access-token.js";
13
+ import { isIdpError, isTokenError } from "./errors.js";
14
+ import { createIdp } from "./idp.js";
15
+ const IDP = "nextidp:idp";
16
+ const SCOPES_KEY = "nextidp:scopes";
17
+ const PUBLIC_KEY = "nextidp:public";
18
+ const Scopes = (...scopes) => SetMetadata(SCOPES_KEY, scopes);
19
+ const Public = () => SetMetadata(PUBLIC_KEY, true);
20
+ const CurrentToken = createParamDecorator(
21
+ (_data, context) => context.switchToHttp().getRequest().idp?.token
22
+ );
23
+ class IdpGuard {
24
+ constructor(auth, reflector) {
25
+ this.auth = auth;
26
+ this.reflector = reflector;
27
+ }
28
+ auth;
29
+ reflector;
30
+ async canActivate(context) {
31
+ const targets = [context.getHandler(), context.getClass()];
32
+ if (this.reflector.getAllAndOverride(PUBLIC_KEY, targets)) return true;
33
+ if (context.getType() !== "http") {
34
+ throw new UnauthorizedException("nextidp's IdpGuard checks HTTP requests only.");
35
+ }
36
+ const http = context.switchToHttp();
37
+ const request = http.getRequest();
38
+ const scopes = this.reflector.getAllAndMerge(SCOPES_KEY, [
39
+ context.getClass(),
40
+ context.getHandler()
41
+ ]) ?? [];
42
+ const authorization = request.headers?.authorization;
43
+ try {
44
+ const token = await this.auth.verifyBearer(
45
+ Array.isArray(authorization) ? void 0 : authorization,
46
+ { scopes }
47
+ );
48
+ request.idp = { token };
49
+ return true;
50
+ } catch (error) {
51
+ if (!isTokenError(error)) {
52
+ throw new ServiceUnavailableException(
53
+ `The access token can't be checked now (${isIdpError(error) ? error.code : "unexpected error"}).`
54
+ );
55
+ }
56
+ const response = http.getResponse();
57
+ const challenge = bearerChallenge(error);
58
+ if (typeof response.setHeader === "function")
59
+ response.setHeader("WWW-Authenticate", challenge);
60
+ else if (typeof response.header === "function")
61
+ response.header("WWW-Authenticate", challenge);
62
+ throw error.code === "insufficient_scope" ? new ForbiddenException(error.message) : new UnauthorizedException(error.message);
63
+ }
64
+ }
65
+ }
66
+ Injectable()(IdpGuard);
67
+ Inject(IDP)(IdpGuard, void 0, 0);
68
+ Inject(Reflector)(IdpGuard, void 0, 1);
69
+ function isIdp(value) {
70
+ return typeof value.verifyBearer === "function";
71
+ }
72
+ function guards(protectAll) {
73
+ return [IdpGuard, ...protectAll === false ? [] : [{ provide: APP_GUARD, useClass: IdpGuard }]];
74
+ }
75
+ class IdpModule {
76
+ static forRoot(auth = {}, options = {}) {
77
+ return {
78
+ module: IdpModule,
79
+ global: true,
80
+ providers: [
81
+ { provide: IDP, useValue: isIdp(auth) ? auth : createIdp(auth) },
82
+ ...guards(options.protectAll)
83
+ ],
84
+ exports: [IDP, IdpGuard]
85
+ };
86
+ }
87
+ static forRootAsync(options) {
88
+ return {
89
+ module: IdpModule,
90
+ global: true,
91
+ imports: options.imports ?? [],
92
+ providers: [
93
+ {
94
+ provide: IDP,
95
+ inject: options.inject ?? [],
96
+ useFactory: async (...args) => createIdp(await options.useFactory(...args))
97
+ },
98
+ ...guards(options.protectAll)
99
+ ],
100
+ exports: [IDP, IdpGuard]
101
+ };
102
+ }
103
+ }
104
+ Module({})(IdpModule);
105
+ import { IdpError, isIdpError as isIdpError2, isTokenError as isTokenError2 } from "./errors.js";
106
+ import { createIdp as createIdp2 } from "./idp.js";
107
+ export {
108
+ CurrentToken,
109
+ IDP,
110
+ IdpError,
111
+ IdpGuard,
112
+ IdpModule,
113
+ Public,
114
+ Scopes,
115
+ createIdp2 as idp,
116
+ isIdpError2 as isIdpError,
117
+ isTokenError2 as isTokenError
118
+ };
@@ -0,0 +1,61 @@
1
+ import { NextRequest } from "next/server";
2
+ import type { AccessToken, TokenRequirements } from "./access-token.js";
3
+ import type { IdpOptions } from "./config.js";
4
+ import { type Idp } from "./idp.js";
5
+ import type { Session } from "./session.js";
6
+ export type ProxyOptions = {
7
+ /**
8
+ * Pages that need a session: a signed-out visitor goes to sign in, and comes back after.
9
+ * Path prefixes (`/dashboard` covers `/dashboard/…`), or a function of the pathname.
10
+ */
11
+ protect?: readonly string[] | ((pathname: string) => boolean);
12
+ /** Refresh the access token before it expires (default true). */
13
+ refresh?: boolean;
14
+ /**
15
+ * The rest of your proxy. It gets the request with the refreshed cookies; to hand them to
16
+ * the page, pass its headers on: `NextResponse.next({ request: { headers: request.headers } })`.
17
+ */
18
+ next?: (request: NextRequest) => Response | Promise<Response>;
19
+ };
20
+ export type NextIdp = Idp & {
21
+ /** For `app/<basePath>/[...nextidp]/route.ts`: `export const { GET, POST } = auth.routes();` */
22
+ routes(): {
23
+ GET: (request: Request) => Promise<Response>;
24
+ POST: (request: Request) => Promise<Response>;
25
+ };
26
+ /** The session in a server component, server action or route handler; null if signed out. */
27
+ session(): Promise<Session | null>;
28
+ /** The session, or a redirect to sign in that comes back to `returnTo` (a path). */
29
+ requireSession(returnTo?: string): Promise<Session>;
30
+ /** For `proxy.ts`: `export const proxy = auth.proxy({ protect: ["/dashboard"] });` */
31
+ proxy(options?: ProxyOptions): (request: NextRequest) => Promise<Response>;
32
+ /**
33
+ * A route handler of an API: the bearer token is checked (and its scopes) before `handler`
34
+ * runs, which gets it as `context.token`. A refused token gets 401 or 403.
35
+ *
36
+ * ```ts
37
+ * export const GET = auth.withToken({ scopes: ["orders:read"] }, async (request, { token }) =>
38
+ * Response.json(await ordersOf(token.subject)),
39
+ * );
40
+ * ```
41
+ */
42
+ withToken<Context extends object = object>(requirements: TokenRequirements, handler: (request: NextRequest, context: Context & {
43
+ token: AccessToken;
44
+ }) => Response | Promise<Response>): (request: NextRequest, context: Context) => Promise<Response>;
45
+ };
46
+ /**
47
+ * The client for a Next.js app. Call it once, in a module of its own, and import the result:
48
+ *
49
+ * ```ts
50
+ * import { idp } from "nextidp/next";
51
+ * export const auth = idp(); // the IDP_* environment variables, read on first use
52
+ * ```
53
+ */
54
+ export declare function idp(options?: IdpOptions | (() => IdpOptions)): NextIdp;
55
+ export type { AccessToken, TokenRequirements } from "./access-token.js";
56
+ export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
57
+ export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
58
+ export type { Idp, Refreshed } from "./idp.js";
59
+ export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
60
+ export type { IdpUser, Session } from "./session.js";
61
+ export { memoryStore, type SessionStore } from "./store.js";
@@ -0,0 +1,94 @@
1
+ import { cookies } from "next/headers";
2
+ import { redirect } from "next/navigation";
3
+ import { connection, NextRequest, NextResponse } from "next/server";
4
+ import { isIdpError, isTokenError } from "./errors.js";
5
+ import { createIdp } from "./idp.js";
6
+ function isProtected(protect, pathname) {
7
+ if (!protect) return false;
8
+ if (typeof protect === "function") return protect(pathname);
9
+ return protect.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
10
+ }
11
+ function idp(options) {
12
+ const core = createIdp(options);
13
+ const handle = async (request) => {
14
+ await connection();
15
+ return core.handler(request);
16
+ };
17
+ const session = async () => {
18
+ await connection();
19
+ return core.getSession((await cookies()).toString());
20
+ };
21
+ return {
22
+ ...core,
23
+ routes: () => ({ GET: handle, POST: handle }),
24
+ session,
25
+ async requireSession(returnTo) {
26
+ const current = await session();
27
+ if (!current) redirect(core.signInPath(returnTo));
28
+ return current;
29
+ },
30
+ withToken(requirements, handler) {
31
+ return async (request, context) => {
32
+ let token;
33
+ try {
34
+ token = await core.verifyBearer(request.headers.get("authorization"), requirements);
35
+ } catch (error) {
36
+ if (isTokenError(error)) return core.tokenErrorResponse(error);
37
+ console.error(
38
+ `nextidp: a token couldn't be checked: ${isIdpError(error) ? error.code : "unexpected error"}`
39
+ );
40
+ return Response.json(
41
+ {
42
+ error: "temporarily_unavailable",
43
+ error_description: "The token can't be checked now."
44
+ },
45
+ { status: 503, headers: { "retry-after": "5", "cache-control": "no-store" } }
46
+ );
47
+ }
48
+ return handler(request, { ...context, token });
49
+ };
50
+ },
51
+ proxy(options2 = {}) {
52
+ return async (request) => {
53
+ const config = core.config();
54
+ const { pathname, search } = request.nextUrl;
55
+ const pass = (forward) => options2.next ? options2.next(forward) : NextResponse.next({ request: { headers: forward.headers } });
56
+ if (pathname === config.basePath || pathname.startsWith(`${config.basePath}/`)) {
57
+ return pass(request);
58
+ }
59
+ const { session: session2, setCookies, cookieHeader } = options2.refresh === false ? { session: await core.getSession(request), setCookies: [], cookieHeader: void 0 } : await core.refreshIfNeeded(request);
60
+ let response;
61
+ if (!session2 && isProtected(options2.protect, pathname)) {
62
+ response = NextResponse.redirect(
63
+ new URL(core.signInPath(`${pathname}${search}`), config.appUrl)
64
+ );
65
+ } else if (cookieHeader === void 0) {
66
+ response = await pass(request);
67
+ } else {
68
+ const headers = new Headers(request.headers);
69
+ headers.set("cookie", cookieHeader);
70
+ response = await pass(new NextRequest(request, { headers }));
71
+ }
72
+ for (const cookie of setCookies) response.headers.append("set-cookie", cookie);
73
+ return response;
74
+ };
75
+ }
76
+ };
77
+ }
78
+ import {
79
+ IdpError,
80
+ isIdpError as isIdpError2,
81
+ isSignInErrorCode,
82
+ isTokenError as isTokenError2,
83
+ SIGN_IN_ERROR_CODES
84
+ } from "./errors.js";
85
+ import { memoryStore } from "./store.js";
86
+ export {
87
+ IdpError,
88
+ SIGN_IN_ERROR_CODES,
89
+ idp,
90
+ isIdpError2 as isIdpError,
91
+ isSignInErrorCode,
92
+ isTokenError2 as isTokenError,
93
+ memoryStore
94
+ };
@@ -0,0 +1,16 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import type { Idp } from "./idp.js";
3
+ import type { Session } from "./session.js";
4
+ export type SessionOptions = {
5
+ /**
6
+ * Refresh the access token when it expires within a minute (default true). Needs the
7
+ * response's headers unsent, to set the new cookie: once they're sent, it only reads.
8
+ */
9
+ refresh?: boolean;
10
+ };
11
+ export type NodeAdapter = {
12
+ handle(req: IncomingMessage, res: ServerResponse): Promise<boolean>;
13
+ session(req: IncomingMessage, res: ServerResponse, options?: SessionOptions): Promise<Session | null>;
14
+ turnAway(req: IncomingMessage, res: ServerResponse, returnTo?: string): void;
15
+ };
16
+ export declare function nodeAdapter(core: Idp): NodeAdapter;
@@ -0,0 +1,60 @@
1
+ import {
2
+ appendSetCookies,
3
+ BodyTooLarge,
4
+ pathOf,
5
+ sendText,
6
+ sendWebResponse,
7
+ toWebRequest,
8
+ urlOf
9
+ } from "./node-http.js";
10
+ function nodeAdapter(core) {
11
+ const sessions = /* @__PURE__ */ new WeakMap();
12
+ return {
13
+ async handle(req, res) {
14
+ const { appUrl, basePath } = core.config();
15
+ const { pathname } = urlOf(req, appUrl);
16
+ if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return false;
17
+ let request;
18
+ try {
19
+ request = await toWebRequest(req, appUrl);
20
+ } catch (error) {
21
+ if (!(error instanceof BodyTooLarge)) throw error;
22
+ res.setHeader("connection", "close");
23
+ sendText(res, 413, "Payload too large");
24
+ return true;
25
+ }
26
+ await sendWebResponse(res, await core.handler(request));
27
+ return true;
28
+ },
29
+ session(req, res, { refresh = true } = {}) {
30
+ const known = sessions.get(req);
31
+ if (known) return known;
32
+ const read = (async () => {
33
+ if (!refresh || res.headersSent) return core.getSession(req.headers.cookie);
34
+ const { session, setCookies, cookieHeader } = await core.refreshIfNeeded(
35
+ req.headers.cookie
36
+ );
37
+ appendSetCookies(res, setCookies);
38
+ if (cookieHeader !== void 0) req.headers.cookie = cookieHeader;
39
+ return session;
40
+ })();
41
+ sessions.set(req, read);
42
+ return read;
43
+ },
44
+ turnAway(req, res, returnTo = pathOf(req)) {
45
+ const method = (req.method ?? "GET").toUpperCase();
46
+ if (method !== "GET" && method !== "HEAD") {
47
+ sendText(res, 401, "Sign in first.");
48
+ return;
49
+ }
50
+ const { appUrl } = core.config();
51
+ res.statusCode = 302;
52
+ res.setHeader("location", new URL(core.signInPath(returnTo), appUrl).toString());
53
+ res.setHeader("cache-control", "no-store");
54
+ res.end();
55
+ }
56
+ };
57
+ }
58
+ export {
59
+ nodeAdapter
60
+ };
@@ -0,0 +1,22 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ /** nextidp's routes take small forms only: a bigger body is refused before it's read whole. */
3
+ export declare const MAX_FORM_BYTES: number;
4
+ /** The body was bigger than MAX_FORM_BYTES: answered 413. */
5
+ export declare class BodyTooLarge extends Error {
6
+ constructor();
7
+ }
8
+ /** The path and query asked for: Express's `originalUrl` when it's mounted under a path. */
9
+ export declare function pathOf(req: IncomingMessage): string;
10
+ /**
11
+ * The URL asked for, on this app's own origin. The Host header never decides it (anyone can
12
+ * send one), and a path like `//elsewhere` stays a path.
13
+ */
14
+ export declare function urlOf(req: IncomingMessage, appUrl: string): URL;
15
+ /** The Web Request for a Node request, its body read (or taken from a parser that read it). */
16
+ export declare function toWebRequest(req: IncomingMessage, appUrl: string): Promise<Request>;
17
+ /** Adds Set-Cookie headers to those the response already has. */
18
+ export declare function appendSetCookies(res: ServerResponse, cookies: readonly string[]): void;
19
+ /** Writes a Web Response to Node's response, and ends it. */
20
+ export declare function sendWebResponse(res: ServerResponse, response: Response): Promise<void>;
21
+ /** A plain-text answer. */
22
+ export declare function sendText(res: ServerResponse, status: number, text: string): void;
@@ -0,0 +1,96 @@
1
+ const MAX_FORM_BYTES = 64 * 1024;
2
+ class BodyTooLarge extends Error {
3
+ constructor() {
4
+ super("The request body is too large.");
5
+ this.name = "BodyTooLarge";
6
+ }
7
+ }
8
+ function pathOf(req) {
9
+ const original = req.originalUrl;
10
+ const path = typeof original === "string" ? original : req.url ?? "/";
11
+ return path.startsWith("/") ? path : `/${path}`;
12
+ }
13
+ function urlOf(req, appUrl) {
14
+ return new URL(`${appUrl}${pathOf(req)}`);
15
+ }
16
+ function headersOf(req) {
17
+ const headers = new Headers();
18
+ for (const [name, value] of Object.entries(req.headers)) {
19
+ if (value === void 0 || name.startsWith(":")) continue;
20
+ if (Array.isArray(value)) for (const item of value) headers.append(name, item);
21
+ else headers.set(name, value);
22
+ }
23
+ return headers;
24
+ }
25
+ function parsedBody(body) {
26
+ if (typeof body === "string") return body;
27
+ if (body instanceof Uint8Array) return new Uint8Array(body);
28
+ if (!body || typeof body !== "object") return void 0;
29
+ const form = new URLSearchParams();
30
+ for (const [name, value] of Object.entries(body)) {
31
+ if (typeof value === "string") form.append(name, value);
32
+ else if (Array.isArray(value)) {
33
+ for (const item of value) if (typeof item === "string") form.append(name, item);
34
+ }
35
+ }
36
+ return form.toString();
37
+ }
38
+ async function readBody(req) {
39
+ const declared = Number(req.headers["content-length"]);
40
+ if (declared > MAX_FORM_BYTES) throw new BodyTooLarge();
41
+ const chunks = [];
42
+ let size = 0;
43
+ for await (const chunk of req) {
44
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
45
+ size += bytes.length;
46
+ if (size > MAX_FORM_BYTES) throw new BodyTooLarge();
47
+ chunks.push(bytes);
48
+ }
49
+ return new Uint8Array(Buffer.concat(chunks));
50
+ }
51
+ async function toWebRequest(req, appUrl) {
52
+ const url = urlOf(req, appUrl);
53
+ const headers = headersOf(req);
54
+ const method = (req.method ?? "GET").toUpperCase();
55
+ if (method === "GET" || method === "HEAD") return new Request(url, { method, headers });
56
+ let body;
57
+ if (req.readableEnded) {
58
+ body = parsedBody(req.body);
59
+ if (typeof body === "string") headers.set("content-type", "application/x-www-form-urlencoded");
60
+ } else {
61
+ body = await readBody(req);
62
+ }
63
+ headers.delete("content-length");
64
+ headers.delete("transfer-encoding");
65
+ return new Request(url, { method, headers, ...body === void 0 ? {} : { body } });
66
+ }
67
+ function appendSetCookies(res, cookies) {
68
+ if (cookies.length === 0) return;
69
+ const existing = res.getHeader("set-cookie");
70
+ const list = existing === void 0 ? [] : Array.isArray(existing) ? existing : [String(existing)];
71
+ res.setHeader("set-cookie", [...list, ...cookies]);
72
+ }
73
+ async function sendWebResponse(res, response) {
74
+ res.statusCode = response.status;
75
+ response.headers.forEach((value, name) => {
76
+ if (name !== "set-cookie") res.setHeader(name, value);
77
+ });
78
+ appendSetCookies(res, response.headers.getSetCookie());
79
+ res.end(response.body ? Buffer.from(await response.arrayBuffer()) : void 0);
80
+ }
81
+ function sendText(res, status, text) {
82
+ res.statusCode = status;
83
+ res.setHeader("content-type", "text/plain; charset=utf-8");
84
+ res.setHeader("cache-control", "no-store");
85
+ res.end(text);
86
+ }
87
+ export {
88
+ BodyTooLarge,
89
+ MAX_FORM_BYTES,
90
+ appendSetCookies,
91
+ pathOf,
92
+ sendText,
93
+ sendWebResponse,
94
+ toWebRequest,
95
+ urlOf
96
+ };
@@ -0,0 +1,50 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import type { IdpOptions } from "./config.js";
3
+ import { type Idp } from "./idp.js";
4
+ import { type SessionOptions } from "./node-adapter.js";
5
+ import type { Session } from "./session.js";
6
+ export type NodeIdp = Idp & {
7
+ /**
8
+ * Answers nextidp's routes (`<basePath>/login`, `/callback`, `/logout`, `/refresh`) and
9
+ * returns true; any other path is left to you, and it returns false.
10
+ */
11
+ handle(req: IncomingMessage, res: ServerResponse): Promise<boolean>;
12
+ /**
13
+ * The signed-in session, or null. Refreshes the access token first when it's about to
14
+ * expire, setting the new cookie on `res`, so call it before you start the response. Read
15
+ * twice in one request, it answers the same.
16
+ */
17
+ session(req: IncomingMessage, res: ServerResponse, options?: SessionOptions): Promise<Session | null>;
18
+ /**
19
+ * The session; or, signed out, a redirect to sign in that comes back to `returnTo` (default:
20
+ * this request's path) for GET and HEAD, or 401 for anything else. Then it's null and the
21
+ * response is sent.
22
+ */
23
+ requireSession(req: IncomingMessage, res: ServerResponse, returnTo?: string): Promise<Session | null>;
24
+ };
25
+ /**
26
+ * The client for an app on Node's own HTTP server:
27
+ *
28
+ * ```ts
29
+ * import { createServer } from "node:http";
30
+ * import { idp } from "nextidp/node";
31
+ *
32
+ * const auth = idp(); // the IDP_* environment variables, read on first use
33
+ *
34
+ * createServer(async (req, res) => {
35
+ * if (await auth.handle(req, res)) return;
36
+ * const session = await auth.requireSession(req, res);
37
+ * if (!session) return;
38
+ * res.end(`Hello, ${session.user.name}`);
39
+ * }).listen(3000);
40
+ * ```
41
+ */
42
+ export declare function idp(options?: IdpOptions | (() => IdpOptions)): NodeIdp;
43
+ export type { AccessToken, TokenRequirements } from "./access-token.js";
44
+ export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
45
+ export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
46
+ export type { Idp, Refreshed } from "./idp.js";
47
+ export type { SessionOptions } from "./node-adapter.js";
48
+ export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
49
+ export type { IdpUser, Session } from "./session.js";
50
+ export { memoryStore, type SessionStore } from "./store.js";
@@ -0,0 +1,33 @@
1
+ import { createIdp } from "./idp.js";
2
+ import { nodeAdapter } from "./node-adapter.js";
3
+ function idp(options) {
4
+ const core = createIdp(options);
5
+ const node = nodeAdapter(core);
6
+ return {
7
+ ...core,
8
+ handle: node.handle,
9
+ session: node.session,
10
+ async requireSession(req, res, returnTo) {
11
+ const session = await node.session(req, res);
12
+ if (!session) node.turnAway(req, res, returnTo);
13
+ return session;
14
+ }
15
+ };
16
+ }
17
+ import {
18
+ IdpError,
19
+ isIdpError,
20
+ isSignInErrorCode,
21
+ isTokenError,
22
+ SIGN_IN_ERROR_CODES
23
+ } from "./errors.js";
24
+ import { memoryStore } from "./store.js";
25
+ export {
26
+ IdpError,
27
+ SIGN_IN_ERROR_CODES,
28
+ idp,
29
+ isIdpError,
30
+ isSignInErrorCode,
31
+ isTokenError,
32
+ memoryStore
33
+ };
@@ -0,0 +1 @@
1
+ {"type":"module"}
@@ -0,0 +1,6 @@
1
+ /** 256 random bits, base64url: a PKCE verifier (RFC 7636 4.1), a state or a nonce. */
2
+ export declare function randomToken(): string;
3
+ /** The S256 code challenge for a verifier: base64url(SHA-256(verifier)). */
4
+ export declare function challengeFor(verifier: string): Promise<string>;
5
+ /** Compares two strings without leaking where they differ through timing. */
6
+ export declare function sameString(a: string, b: string): boolean;
@@ -0,0 +1,23 @@
1
+ import { base64url } from "jose";
2
+ function randomToken() {
3
+ return base64url.encode(crypto.getRandomValues(new Uint8Array(32)));
4
+ }
5
+ async function challengeFor(verifier) {
6
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
7
+ return base64url.encode(new Uint8Array(digest));
8
+ }
9
+ function sameString(a, b) {
10
+ const left = new TextEncoder().encode(a);
11
+ const right = new TextEncoder().encode(b);
12
+ if (left.length !== right.length) return false;
13
+ let difference = 0;
14
+ for (let index = 0; index < left.length; index += 1) {
15
+ difference |= (left[index] ?? 0) ^ (right[index] ?? 0);
16
+ }
17
+ return difference === 0;
18
+ }
19
+ export {
20
+ challengeFor,
21
+ randomToken,
22
+ sameString
23
+ };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * A path of this app, or undefined. Where a sign-in returns to comes from the browser
3
+ * (`?returnTo=`, a form field), so anything that could lead to another site is refused:
4
+ * `//evil.example`, `/\evil.example`, `https://…`, `javascript:…`, and control characters.
5
+ */
6
+ export declare function safePath(value: unknown): string | undefined;
@@ -0,0 +1,17 @@
1
+ const PLACEHOLDER = "http://nextidp.invalid";
2
+ function safePath(value) {
3
+ if (typeof value !== "string" || !value.startsWith("/")) return void 0;
4
+ if (value.startsWith("//") || value.includes("\\") || /[\u0000-\u001f\u007f]/.test(value)) {
5
+ return void 0;
6
+ }
7
+ try {
8
+ const url = new URL(value, PLACEHOLDER);
9
+ if (url.origin !== PLACEHOLDER) return void 0;
10
+ return `${url.pathname}${url.search}${url.hash}`;
11
+ } catch {
12
+ return void 0;
13
+ }
14
+ }
15
+ export {
16
+ safePath
17
+ };
@@ -0,0 +1,12 @@
1
+ /** Seals and opens values for one `idp()` instance; derived keys are kept, not recomputed. */
2
+ export declare class Sealer {
3
+ #private;
4
+ constructor(secrets: readonly string[]);
5
+ /** Encrypts with the first secret. */
6
+ seal(payload: Record<string, unknown>, purpose: string, maxAgeSeconds: number): Promise<string>;
7
+ /**
8
+ * The payload, or undefined if the value is missing, altered, sealed for another purpose,
9
+ * expired, or sealed with a secret no longer in the list. Tries every secret, in order.
10
+ */
11
+ unseal(value: string | undefined, purpose: string): Promise<Record<string, unknown> | undefined>;
12
+ }