nextidp 0.0.1 → 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 (97) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +434 -4
  3. package/dist/cjs/access-token.d.ts +56 -0
  4. package/dist/cjs/access-token.js +196 -0
  5. package/dist/cjs/config.d.ts +128 -0
  6. package/dist/cjs/config.js +233 -0
  7. package/dist/cjs/cookies.d.ts +23 -0
  8. package/dist/cjs/cookies.js +118 -0
  9. package/dist/cjs/discovery.d.ts +24 -0
  10. package/dist/cjs/discovery.js +91 -0
  11. package/dist/cjs/errors.d.ts +63 -0
  12. package/dist/cjs/errors.js +69 -0
  13. package/dist/cjs/express.d.ts +71 -0
  14. package/dist/cjs/express.js +114 -0
  15. package/dist/cjs/http.d.ts +10 -0
  16. package/dist/cjs/http.js +68 -0
  17. package/dist/cjs/id-token.d.ts +19 -0
  18. package/dist/cjs/id-token.js +77 -0
  19. package/dist/cjs/idp.d.ts +81 -0
  20. package/dist/cjs/idp.js +482 -0
  21. package/dist/cjs/index.d.ts +9 -0
  22. package/dist/cjs/index.js +53 -0
  23. package/dist/cjs/logout-token.d.ts +13 -0
  24. package/dist/cjs/logout-token.js +63 -0
  25. package/dist/cjs/nestjs.d.ts +53 -0
  26. package/dist/cjs/nestjs.js +142 -0
  27. package/dist/cjs/next.d.ts +61 -0
  28. package/dist/cjs/next.js +118 -0
  29. package/dist/cjs/node-adapter.d.ts +16 -0
  30. package/dist/cjs/node-adapter.js +76 -0
  31. package/dist/cjs/node-http.d.ts +22 -0
  32. package/dist/cjs/node-http.js +127 -0
  33. package/dist/cjs/node.d.ts +50 -0
  34. package/dist/cjs/node.js +57 -0
  35. package/dist/cjs/package.json +1 -0
  36. package/dist/cjs/pkce.d.ts +6 -0
  37. package/dist/cjs/pkce.js +49 -0
  38. package/dist/cjs/return-path.d.ts +6 -0
  39. package/dist/cjs/return-path.js +41 -0
  40. package/dist/cjs/sealed.d.ts +12 -0
  41. package/dist/cjs/sealed.js +78 -0
  42. package/dist/cjs/service.d.ts +61 -0
  43. package/dist/cjs/service.js +173 -0
  44. package/dist/cjs/session.d.ts +51 -0
  45. package/dist/cjs/session.js +97 -0
  46. package/dist/cjs/store.d.ts +58 -0
  47. package/dist/cjs/store.js +145 -0
  48. package/dist/cjs/tokens.d.ts +38 -0
  49. package/dist/cjs/tokens.js +138 -0
  50. package/dist/esm/access-token.d.ts +56 -0
  51. package/dist/esm/access-token.js +156 -0
  52. package/dist/esm/config.d.ts +128 -0
  53. package/dist/esm/config.js +206 -0
  54. package/dist/esm/cookies.d.ts +23 -0
  55. package/dist/esm/cookies.js +89 -0
  56. package/dist/esm/discovery.d.ts +24 -0
  57. package/dist/esm/discovery.js +56 -0
  58. package/dist/esm/errors.d.ts +63 -0
  59. package/dist/esm/errors.js +41 -0
  60. package/dist/esm/express.d.ts +71 -0
  61. package/dist/esm/express.js +90 -0
  62. package/dist/esm/http.d.ts +10 -0
  63. package/dist/esm/http.js +44 -0
  64. package/dist/esm/id-token.d.ts +19 -0
  65. package/dist/esm/id-token.js +51 -0
  66. package/dist/esm/idp.d.ts +81 -0
  67. package/dist/esm/idp.js +488 -0
  68. package/dist/esm/index.d.ts +9 -0
  69. package/dist/esm/index.js +30 -0
  70. package/dist/esm/logout-token.d.ts +13 -0
  71. package/dist/esm/logout-token.js +39 -0
  72. package/dist/esm/nestjs.d.ts +53 -0
  73. package/dist/esm/nestjs.js +118 -0
  74. package/dist/esm/next.d.ts +61 -0
  75. package/dist/esm/next.js +94 -0
  76. package/dist/esm/node-adapter.d.ts +16 -0
  77. package/dist/esm/node-adapter.js +60 -0
  78. package/dist/esm/node-http.d.ts +22 -0
  79. package/dist/esm/node-http.js +96 -0
  80. package/dist/esm/node.d.ts +50 -0
  81. package/dist/esm/node.js +33 -0
  82. package/dist/esm/package.json +1 -0
  83. package/dist/esm/pkce.d.ts +6 -0
  84. package/dist/esm/pkce.js +23 -0
  85. package/dist/esm/return-path.d.ts +6 -0
  86. package/dist/esm/return-path.js +17 -0
  87. package/dist/esm/sealed.d.ts +12 -0
  88. package/dist/esm/sealed.js +54 -0
  89. package/dist/esm/service.d.ts +61 -0
  90. package/dist/esm/service.js +148 -0
  91. package/dist/esm/session.d.ts +51 -0
  92. package/dist/esm/session.js +58 -0
  93. package/dist/esm/store.d.ts +58 -0
  94. package/dist/esm/store.js +119 -0
  95. package/dist/esm/tokens.d.ts +38 -0
  96. package/dist/esm/tokens.js +100 -0
  97. package/package.json +130 -5
@@ -0,0 +1,53 @@
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 index_exports = {};
20
+ __export(index_exports, {
21
+ DEFAULT_SCOPES: () => import_config.DEFAULT_SCOPES,
22
+ IdpError: () => import_errors.IdpError,
23
+ SIGN_IN_ERROR_CODES: () => import_errors.SIGN_IN_ERROR_CODES,
24
+ bearerChallenge: () => import_access_token.bearerChallenge,
25
+ bearerToken: () => import_access_token.bearerToken,
26
+ idp: () => import_idp.createIdp,
27
+ isIdpError: () => import_errors.isIdpError,
28
+ isSignInErrorCode: () => import_errors.isSignInErrorCode,
29
+ isTokenError: () => import_errors.isTokenError,
30
+ memoryStore: () => import_store.memoryStore,
31
+ safePath: () => import_return_path.safePath
32
+ });
33
+ module.exports = __toCommonJS(index_exports);
34
+ var import_access_token = require("./access-token.js");
35
+ var import_config = require("./config.js");
36
+ var import_errors = require("./errors.js");
37
+ var import_idp = require("./idp.js");
38
+ var import_return_path = require("./return-path.js");
39
+ var import_store = require("./store.js");
40
+ // Annotate the CommonJS export names for ESM import in node:
41
+ 0 && (module.exports = {
42
+ DEFAULT_SCOPES,
43
+ IdpError,
44
+ SIGN_IN_ERROR_CODES,
45
+ bearerChallenge,
46
+ bearerToken,
47
+ idp,
48
+ isIdpError,
49
+ isSignInErrorCode,
50
+ isTokenError,
51
+ memoryStore,
52
+ safePath
53
+ });
@@ -0,0 +1,13 @@
1
+ import { type JWTVerifyGetKey } from "jose";
2
+ import type { IdpLogout } from "./store.js";
3
+ /**
4
+ * Checks a logout token (OIDC Back-Channel Logout 1.0, 2.6): signed by one of the issuer's
5
+ * keys, `iss` the issuer, `aud` this client, `iat` and `exp` (not expired), the
6
+ * back-channel logout event, a `sid` or a `sub`, and no `nonce`, so an ID token can't pass
7
+ * for one. Its `typ`, when there is one, must be logout+jwt.
8
+ */
9
+ export declare function verifyLogoutToken(token: string, keys: JWTVerifyGetKey, check: {
10
+ issuer: string;
11
+ clientId: string;
12
+ algorithms?: readonly string[] | undefined;
13
+ }): Promise<IdpLogout>;
@@ -0,0 +1,63 @@
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 logout_token_exports = {};
20
+ __export(logout_token_exports, {
21
+ verifyLogoutToken: () => verifyLogoutToken
22
+ });
23
+ module.exports = __toCommonJS(logout_token_exports);
24
+ var import_jose = require("jose");
25
+ var import_errors = require("./errors.js");
26
+ var import_id_token = require("./id-token.js");
27
+ const BACKCHANNEL_LOGOUT_EVENT = "http://schemas.openid.net/event/backchannel-logout";
28
+ function invalid(message, cause) {
29
+ return new import_errors.IdpError("invalid_logout_token", message, cause === void 0 ? {} : { cause });
30
+ }
31
+ async function verifyLogoutToken(token, keys, check) {
32
+ let verified;
33
+ try {
34
+ verified = await (0, import_jose.jwtVerify)(token, keys, {
35
+ algorithms: (0, import_id_token.signingAlgorithms)(check.algorithms),
36
+ issuer: check.issuer,
37
+ audience: check.clientId,
38
+ requiredClaims: ["iat", "exp"],
39
+ clockTolerance: 60
40
+ });
41
+ } catch (cause) {
42
+ throw invalid("The logout token didn't verify.", cause);
43
+ }
44
+ const { payload, protectedHeader } = verified;
45
+ const typ = protectedHeader.typ?.toLowerCase();
46
+ if (typ !== void 0 && typ !== "logout+jwt" && typ !== "application/logout+jwt") {
47
+ throw invalid("The token isn't a logout token (typ).");
48
+ }
49
+ const events = payload.events;
50
+ const event = events && typeof events === "object" ? events[BACKCHANNEL_LOGOUT_EVENT] : void 0;
51
+ if (!event || typeof event !== "object") {
52
+ throw invalid("The logout token has no back-channel logout event.");
53
+ }
54
+ if ("nonce" in payload) throw invalid("A logout token can't have a nonce.");
55
+ const sid = typeof payload.sid === "string" && payload.sid ? payload.sid : void 0;
56
+ const sub = typeof payload.sub === "string" && payload.sub ? payload.sub : void 0;
57
+ if (!sid && !sub) throw invalid("The logout token names no session (sid) and no one (sub).");
58
+ return { sid, sub };
59
+ }
60
+ // Annotate the CommonJS export names for ESM import in node:
61
+ 0 && (module.exports = {
62
+ verifyLogoutToken
63
+ });
@@ -0,0 +1,53 @@
1
+ import { type CanActivate, type DynamicModule, type ExecutionContext } from "@nestjs/common";
2
+ import { Reflector } from "@nestjs/core";
3
+ import type { IdpOptions } from "./config.js";
4
+ import { type Idp } from "./idp.js";
5
+ /** The injection token of the `Idp` instance the module was given. */
6
+ export declare const IDP = "nextidp:idp";
7
+ /** Every one of these scopes is needed. On a controller, they add to its routes' own. */
8
+ export declare const Scopes: (...scopes: string[]) => import("@nestjs/common").CustomDecorator<string>;
9
+ /** No token needed for this route (or every route of this controller). */
10
+ export declare const Public: () => import("@nestjs/common").CustomDecorator<string>;
11
+ /** The checked access token of this request: `list(@CurrentToken() token: AccessToken)`. */
12
+ export declare const CurrentToken: (...dataOrPipes: unknown[]) => ParameterDecorator;
13
+ /**
14
+ * Checks the bearer token of every HTTP request it guards: a missing or bad token is 401, a
15
+ * missing scope 403 (each with WWW-Authenticate, RFC 6750), and a token that can't be checked
16
+ * now 503. Only HTTP: on any other kind of context it refuses, rather than let a call through.
17
+ */
18
+ export declare class IdpGuard implements CanActivate {
19
+ private readonly auth;
20
+ private readonly reflector;
21
+ constructor(auth: Idp, reflector: Reflector);
22
+ canActivate(context: ExecutionContext): Promise<boolean>;
23
+ }
24
+ export type IdpModuleOptions = {
25
+ /**
26
+ * Guard every route of the app (default true): a route without a token is refused unless
27
+ * it's @Public(). With false, guard routes yourself: @UseGuards(IdpGuard).
28
+ */
29
+ protectAll?: boolean;
30
+ };
31
+ export type IdpModuleAsyncOptions = IdpModuleOptions & {
32
+ imports?: DynamicModule["imports"];
33
+ inject?: Array<string | symbol | (abstract new (...args: never[]) => unknown)>;
34
+ /** The settings, from your configuration: `(config: ConfigService) => ({ issuer: … })`. */
35
+ useFactory: (...args: never[]) => IdpOptions | Promise<IdpOptions>;
36
+ };
37
+ /**
38
+ * The module, once, in the app's root module. Global: IdpGuard and the IDP token can be used
39
+ * in every module.
40
+ *
41
+ * ```ts
42
+ * @Module({ imports: [IdpModule.forRoot({ issuer: "https://auth.example.com", audience: "https://api.example.com" })] })
43
+ * ```
44
+ */
45
+ export declare class IdpModule {
46
+ static forRoot(auth?: Idp | IdpOptions, options?: IdpModuleOptions): DynamicModule;
47
+ static forRootAsync(options: IdpModuleAsyncOptions): DynamicModule;
48
+ }
49
+ export type { AccessToken, TokenRequirements } from "./access-token.js";
50
+ export type { ApiConfig, IdpOptions } from "./config.js";
51
+ export { IdpError, isIdpError, isTokenError, type TokenErrorCode } from "./errors.js";
52
+ export { createIdp as idp, type Idp } from "./idp.js";
53
+ export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
@@ -0,0 +1,142 @@
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 nestjs_exports = {};
20
+ __export(nestjs_exports, {
21
+ CurrentToken: () => CurrentToken,
22
+ IDP: () => IDP,
23
+ IdpError: () => import_errors2.IdpError,
24
+ IdpGuard: () => IdpGuard,
25
+ IdpModule: () => IdpModule,
26
+ Public: () => Public,
27
+ Scopes: () => Scopes,
28
+ idp: () => import_idp2.createIdp,
29
+ isIdpError: () => import_errors2.isIdpError,
30
+ isTokenError: () => import_errors2.isTokenError
31
+ });
32
+ module.exports = __toCommonJS(nestjs_exports);
33
+ var import_common = require("@nestjs/common");
34
+ var import_core = require("@nestjs/core");
35
+ var import_access_token = require("./access-token.js");
36
+ var import_errors = require("./errors.js");
37
+ var import_idp = require("./idp.js");
38
+ var import_errors2 = require("./errors.js");
39
+ var import_idp2 = require("./idp.js");
40
+ const IDP = "nextidp:idp";
41
+ const SCOPES_KEY = "nextidp:scopes";
42
+ const PUBLIC_KEY = "nextidp:public";
43
+ const Scopes = (...scopes) => (0, import_common.SetMetadata)(SCOPES_KEY, scopes);
44
+ const Public = () => (0, import_common.SetMetadata)(PUBLIC_KEY, true);
45
+ const CurrentToken = (0, import_common.createParamDecorator)(
46
+ (_data, context) => context.switchToHttp().getRequest().idp?.token
47
+ );
48
+ class IdpGuard {
49
+ constructor(auth, reflector) {
50
+ this.auth = auth;
51
+ this.reflector = reflector;
52
+ }
53
+ auth;
54
+ reflector;
55
+ async canActivate(context) {
56
+ const targets = [context.getHandler(), context.getClass()];
57
+ if (this.reflector.getAllAndOverride(PUBLIC_KEY, targets)) return true;
58
+ if (context.getType() !== "http") {
59
+ throw new import_common.UnauthorizedException("nextidp's IdpGuard checks HTTP requests only.");
60
+ }
61
+ const http = context.switchToHttp();
62
+ const request = http.getRequest();
63
+ const scopes = this.reflector.getAllAndMerge(SCOPES_KEY, [
64
+ context.getClass(),
65
+ context.getHandler()
66
+ ]) ?? [];
67
+ const authorization = request.headers?.authorization;
68
+ try {
69
+ const token = await this.auth.verifyBearer(
70
+ Array.isArray(authorization) ? void 0 : authorization,
71
+ { scopes }
72
+ );
73
+ request.idp = { token };
74
+ return true;
75
+ } catch (error) {
76
+ if (!(0, import_errors.isTokenError)(error)) {
77
+ throw new import_common.ServiceUnavailableException(
78
+ `The access token can't be checked now (${(0, import_errors.isIdpError)(error) ? error.code : "unexpected error"}).`
79
+ );
80
+ }
81
+ const response = http.getResponse();
82
+ const challenge = (0, import_access_token.bearerChallenge)(error);
83
+ if (typeof response.setHeader === "function")
84
+ response.setHeader("WWW-Authenticate", challenge);
85
+ else if (typeof response.header === "function")
86
+ response.header("WWW-Authenticate", challenge);
87
+ throw error.code === "insufficient_scope" ? new import_common.ForbiddenException(error.message) : new import_common.UnauthorizedException(error.message);
88
+ }
89
+ }
90
+ }
91
+ (0, import_common.Injectable)()(IdpGuard);
92
+ (0, import_common.Inject)(IDP)(IdpGuard, void 0, 0);
93
+ (0, import_common.Inject)(import_core.Reflector)(IdpGuard, void 0, 1);
94
+ function isIdp(value) {
95
+ return typeof value.verifyBearer === "function";
96
+ }
97
+ function guards(protectAll) {
98
+ return [IdpGuard, ...protectAll === false ? [] : [{ provide: import_core.APP_GUARD, useClass: IdpGuard }]];
99
+ }
100
+ class IdpModule {
101
+ static forRoot(auth = {}, options = {}) {
102
+ return {
103
+ module: IdpModule,
104
+ global: true,
105
+ providers: [
106
+ { provide: IDP, useValue: isIdp(auth) ? auth : (0, import_idp.createIdp)(auth) },
107
+ ...guards(options.protectAll)
108
+ ],
109
+ exports: [IDP, IdpGuard]
110
+ };
111
+ }
112
+ static forRootAsync(options) {
113
+ return {
114
+ module: IdpModule,
115
+ global: true,
116
+ imports: options.imports ?? [],
117
+ providers: [
118
+ {
119
+ provide: IDP,
120
+ inject: options.inject ?? [],
121
+ useFactory: async (...args) => (0, import_idp.createIdp)(await options.useFactory(...args))
122
+ },
123
+ ...guards(options.protectAll)
124
+ ],
125
+ exports: [IDP, IdpGuard]
126
+ };
127
+ }
128
+ }
129
+ (0, import_common.Module)({})(IdpModule);
130
+ // Annotate the CommonJS export names for ESM import in node:
131
+ 0 && (module.exports = {
132
+ CurrentToken,
133
+ IDP,
134
+ IdpError,
135
+ IdpGuard,
136
+ IdpModule,
137
+ Public,
138
+ Scopes,
139
+ idp,
140
+ isIdpError,
141
+ isTokenError
142
+ });
@@ -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,118 @@
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 next_exports = {};
20
+ __export(next_exports, {
21
+ IdpError: () => import_errors2.IdpError,
22
+ SIGN_IN_ERROR_CODES: () => import_errors2.SIGN_IN_ERROR_CODES,
23
+ idp: () => idp,
24
+ isIdpError: () => import_errors2.isIdpError,
25
+ isSignInErrorCode: () => import_errors2.isSignInErrorCode,
26
+ isTokenError: () => import_errors2.isTokenError,
27
+ memoryStore: () => import_store.memoryStore
28
+ });
29
+ module.exports = __toCommonJS(next_exports);
30
+ var import_headers = require("next/headers");
31
+ var import_navigation = require("next/navigation");
32
+ var import_server = require("next/server");
33
+ var import_errors = require("./errors.js");
34
+ var import_idp = require("./idp.js");
35
+ var import_errors2 = require("./errors.js");
36
+ var import_store = require("./store.js");
37
+ function isProtected(protect, pathname) {
38
+ if (!protect) return false;
39
+ if (typeof protect === "function") return protect(pathname);
40
+ return protect.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
41
+ }
42
+ function idp(options) {
43
+ const core = (0, import_idp.createIdp)(options);
44
+ const handle = async (request) => {
45
+ await (0, import_server.connection)();
46
+ return core.handler(request);
47
+ };
48
+ const session = async () => {
49
+ await (0, import_server.connection)();
50
+ return core.getSession((await (0, import_headers.cookies)()).toString());
51
+ };
52
+ return {
53
+ ...core,
54
+ routes: () => ({ GET: handle, POST: handle }),
55
+ session,
56
+ async requireSession(returnTo) {
57
+ const current = await session();
58
+ if (!current) (0, import_navigation.redirect)(core.signInPath(returnTo));
59
+ return current;
60
+ },
61
+ withToken(requirements, handler) {
62
+ return async (request, context) => {
63
+ let token;
64
+ try {
65
+ token = await core.verifyBearer(request.headers.get("authorization"), requirements);
66
+ } catch (error) {
67
+ if ((0, import_errors.isTokenError)(error)) return core.tokenErrorResponse(error);
68
+ console.error(
69
+ `nextidp: a token couldn't be checked: ${(0, import_errors.isIdpError)(error) ? error.code : "unexpected error"}`
70
+ );
71
+ return Response.json(
72
+ {
73
+ error: "temporarily_unavailable",
74
+ error_description: "The token can't be checked now."
75
+ },
76
+ { status: 503, headers: { "retry-after": "5", "cache-control": "no-store" } }
77
+ );
78
+ }
79
+ return handler(request, { ...context, token });
80
+ };
81
+ },
82
+ proxy(options2 = {}) {
83
+ return async (request) => {
84
+ const config = core.config();
85
+ const { pathname, search } = request.nextUrl;
86
+ const pass = (forward) => options2.next ? options2.next(forward) : import_server.NextResponse.next({ request: { headers: forward.headers } });
87
+ if (pathname === config.basePath || pathname.startsWith(`${config.basePath}/`)) {
88
+ return pass(request);
89
+ }
90
+ const { session: session2, setCookies, cookieHeader } = options2.refresh === false ? { session: await core.getSession(request), setCookies: [], cookieHeader: void 0 } : await core.refreshIfNeeded(request);
91
+ let response;
92
+ if (!session2 && isProtected(options2.protect, pathname)) {
93
+ response = import_server.NextResponse.redirect(
94
+ new URL(core.signInPath(`${pathname}${search}`), config.appUrl)
95
+ );
96
+ } else if (cookieHeader === void 0) {
97
+ response = await pass(request);
98
+ } else {
99
+ const headers = new Headers(request.headers);
100
+ headers.set("cookie", cookieHeader);
101
+ response = await pass(new import_server.NextRequest(request, { headers }));
102
+ }
103
+ for (const cookie of setCookies) response.headers.append("set-cookie", cookie);
104
+ return response;
105
+ };
106
+ }
107
+ };
108
+ }
109
+ // Annotate the CommonJS export names for ESM import in node:
110
+ 0 && (module.exports = {
111
+ IdpError,
112
+ SIGN_IN_ERROR_CODES,
113
+ idp,
114
+ isIdpError,
115
+ isSignInErrorCode,
116
+ isTokenError,
117
+ memoryStore
118
+ });
@@ -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,76 @@
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 node_adapter_exports = {};
20
+ __export(node_adapter_exports, {
21
+ nodeAdapter: () => nodeAdapter
22
+ });
23
+ module.exports = __toCommonJS(node_adapter_exports);
24
+ var import_node_http = require("./node-http.js");
25
+ function nodeAdapter(core) {
26
+ const sessions = /* @__PURE__ */ new WeakMap();
27
+ return {
28
+ async handle(req, res) {
29
+ const { appUrl, basePath } = core.config();
30
+ const { pathname } = (0, import_node_http.urlOf)(req, appUrl);
31
+ if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return false;
32
+ let request;
33
+ try {
34
+ request = await (0, import_node_http.toWebRequest)(req, appUrl);
35
+ } catch (error) {
36
+ if (!(error instanceof import_node_http.BodyTooLarge)) throw error;
37
+ res.setHeader("connection", "close");
38
+ (0, import_node_http.sendText)(res, 413, "Payload too large");
39
+ return true;
40
+ }
41
+ await (0, import_node_http.sendWebResponse)(res, await core.handler(request));
42
+ return true;
43
+ },
44
+ session(req, res, { refresh = true } = {}) {
45
+ const known = sessions.get(req);
46
+ if (known) return known;
47
+ const read = (async () => {
48
+ if (!refresh || res.headersSent) return core.getSession(req.headers.cookie);
49
+ const { session, setCookies, cookieHeader } = await core.refreshIfNeeded(
50
+ req.headers.cookie
51
+ );
52
+ (0, import_node_http.appendSetCookies)(res, setCookies);
53
+ if (cookieHeader !== void 0) req.headers.cookie = cookieHeader;
54
+ return session;
55
+ })();
56
+ sessions.set(req, read);
57
+ return read;
58
+ },
59
+ turnAway(req, res, returnTo = (0, import_node_http.pathOf)(req)) {
60
+ const method = (req.method ?? "GET").toUpperCase();
61
+ if (method !== "GET" && method !== "HEAD") {
62
+ (0, import_node_http.sendText)(res, 401, "Sign in first.");
63
+ return;
64
+ }
65
+ const { appUrl } = core.config();
66
+ res.statusCode = 302;
67
+ res.setHeader("location", new URL(core.signInPath(returnTo), appUrl).toString());
68
+ res.setHeader("cache-control", "no-store");
69
+ res.end();
70
+ }
71
+ };
72
+ }
73
+ // Annotate the CommonJS export names for ESM import in node:
74
+ 0 && (module.exports = {
75
+ nodeAdapter
76
+ });
@@ -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;