nextidp 0.4.0 → 0.6.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 CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0
4
+
5
+ - `GET <basePath>/login?login_hint=…` passes the hint on to the auth server (OIDC Core
6
+ 3.1.2.1), and pushes it with PAR. Next-Identity Server sends someone whose company signs them
7
+ in straight to the company's sign-in page. It's trimmed; one past 254 characters or with a
8
+ control character is left out.
9
+ - `signInPath(returnTo, { loginHint })` adds it to a sign-in link.
10
+
11
+ ## 0.5.0
12
+
13
+ ### Managing accounts
14
+
15
+ - `nextidp/management`: a service's side of Next-Identity Server's management API (on with
16
+ `MANAGEMENT_API=true` there). `management()` takes the service's settings (IDP_ISSUER,
17
+ IDP_CLIENT_ID, IDP_CLIENT_SECRET) and gives `findUser` (at once), `signOut`, `disable` and
18
+ `enable`, which file a request that waits for an admin, and `request(id)` and
19
+ `requests({ status, userId, since, page })` to check on them.
20
+ - Its token is the service's own (client credentials), asked for per scope
21
+ (`management:users.read`, `management:users.manage`) for the API's resource, kept, and renewed
22
+ once when the API refuses it.
23
+ - A refusal is a `ManagementError` (`isManagementError`): an `IdpError` with the new code
24
+ `management_refused` and the API's code in `refusal`. No answer is `management_unavailable`.
25
+ - NestJS: `IdpModule.forRoot(settings, { management: true })` and `forRootAsync` provide one
26
+ under the new `MANAGEMENT` token.
27
+
3
28
  ## 0.4.0
4
29
 
5
30
  - Access, ID and logout tokens signed with `Ed25519` are accepted: RFC 9864's fully specified
package/README.md CHANGED
@@ -27,6 +27,10 @@ ES module and CommonJS builds, with types. Node 24 or later, or an edge runtime
27
27
  Router), Express (tested with 5) or anything else that takes Node middleware, Fastify 5,
28
28
  Node's own HTTP server, Hono 4, and NestJS 11 or 12 for APIs.
29
29
 
30
+ For Python, [`nextidp` on PyPI](https://pypi.org/project/nextidp/) is the same package for
31
+ FastAPI, Flask and the MCP Python SDK, with the same settings, routes and cookie and store
32
+ format, so a Python app and a Node app with the same client ID share sessions.
33
+
30
34
  ## 1. Register your app on the auth server
31
35
 
32
36
  In the auth server's **Admin → OIDC clients**, create a client (or declare it in
@@ -263,7 +267,7 @@ All under `basePath` (default `/auth`):
263
267
 
264
268
  | Route | What it does |
265
269
  |---|---|
266
- | `GET /auth/login?returnTo=/path` | Starts a sign-in, and comes back to `returnTo` (paths of this app only). Takes `prompt` and `reauthenticate=false` too ([below](#asking-for-the-password-again)). |
270
+ | `GET /auth/login?returnTo=/path` | Starts a sign-in, and comes back to `returnTo` (paths of this app only). Takes `prompt`, `reauthenticate=false` ([below](#asking-for-the-password-again)) and `login_hint` ([below](#who-is-signing-in)) too. |
267
271
  | `GET /auth/callback` | Finishes it: the redirect URI you registered. |
268
272
  | `POST /auth/logout` | Revokes the refresh token and ends this app's session. With `signOutOfIdp=true`, the auth server's too. |
269
273
  | `POST /auth/refresh` | New tokens now, then back to the form's `returnTo`. |
@@ -275,7 +279,8 @@ The POST routes accept forms from this app's own pages only (they check `Origin`
275
279
  `GET /auth/login?prompt=login` makes the auth server ask for the password even while its own
276
280
  session is still live; `consent` shows the consent screen again; `select_account` asks which
277
281
  account. Several go together, separated by spaces (`prompt=login consent`). Any other value
278
- (`none` included) is left out, and nothing else in the query reaches the auth server.
282
+ (`none` included) is left out, and nothing else in the query reaches the auth server but
283
+ `login_hint`.
279
284
 
280
285
  Signing out of the app alone leaves the auth server's session live, so by default the next
281
286
  sign-in goes straight through: on a shared computer, as the person before. With
@@ -293,7 +298,20 @@ cookie.
293
298
  <a href={auth.signInPath("/settings", { prompt: "consent" })}>Review permissions</a>
294
299
  ```
295
300
 
296
- `auth.signInPath(returnTo, { prompt, reauthenticate })` builds these links.
301
+ `auth.signInPath(returnTo, { prompt, reauthenticate, loginHint })` builds these links.
302
+
303
+ ### Who is signing in
304
+
305
+ `GET /auth/login?login_hint=ada@acme.com` tells the auth server who is signing in, when the app
306
+ already knows (OIDC Core 3.1.2.1): an app that asks for the email first, or a link in an email.
307
+ Next-Identity Server sends someone whose company signs them in (single sign-on) straight to the
308
+ company's sign-in page, without its own. The hint is trimmed, and one longer than an email
309
+ address (254 characters) or with a control character is left out. With PAR it's pushed with the
310
+ rest.
311
+
312
+ ```tsx
313
+ <a href={auth.signInPath("/", { loginHint: email })}>Continue</a>
314
+ ```
297
315
 
298
316
  ### Pushing the sign-in first (PAR)
299
317
 
@@ -627,6 +645,70 @@ A refusal throws `IdpError` with the code `service_token_failed` and the auth se
627
645
  status (`invalid_scope` for a scope the client may not have, `invalid_target` for an API it
628
646
  isn't linked to).
629
647
 
648
+ ## Managing accounts (Next-Identity Server)
649
+
650
+ `nextidp/management` is a service's side of Next-Identity Server's management API, for a product
651
+ whose operators manage accounts from its own screens. It's that server's own API, not OpenID
652
+ Connect, and it's on only with `MANAGEMENT_API=true` there. A lookup answers at once; a sign-out,
653
+ a disable or an enable **waits for an admin's approval**, so what comes back is a request to
654
+ check on, not something done.
655
+
656
+ The service needs a confidential client with the management API and its scopes
657
+ (`management:users.read` to look up, `management:users.manage` to ask and check), and runs on the
658
+ server: the client secret is in its settings.
659
+
660
+ ```ts
661
+ import { isManagementError, management } from "nextidp/management";
662
+
663
+ const accounts = management(); // IDP_ISSUER, IDP_CLIENT_ID, IDP_CLIENT_SECRET
664
+
665
+ const user = await accounts.findUser({ email: "ada@example.com" }); // or { id }; undefined if none
666
+ const request = await accounts.disable(user.id, { until: "2027-01-31T00:00:00Z", reason: "Chargeback" });
667
+ // request.status === "pending": store request.id
668
+
669
+ const later = await accounts.request(request.id);
670
+ // later.status: "pending" (still waiting), "approved" (done), "denied" (later.note says why),
671
+ // "expired" (nobody decided within 7 days) or "failed" (approved, but something had changed:
672
+ // later.problem)
673
+
674
+ // Everything decided since the last check, for a job that syncs them:
675
+ const { requests, pageCount } = await accounts.requests({ since: lastCheck, page: 1 });
676
+ ```
677
+
678
+ | Call | Scope | Answers |
679
+ |---|---|---|
680
+ | `findUser({ email })`, `findUser({ id })` | read | The account, or undefined |
681
+ | `signOut(userId)` | manage | A request: sign out everywhere |
682
+ | `disable(userId, { until?, reason? })` | manage | A request: disable, until a date within a year or until enabled |
683
+ | `enable(userId)` | manage | A request: enable again |
684
+ | `request(id)` | manage | The request as it stands now, or undefined |
685
+ | `requests({ status?, userId?, since?, page? })` | manage | `{ requests, page, pageCount, total }`, newest first, 50 a page |
686
+
687
+ A refusal throws a `ManagementError` (an `IdpError` with the code `management_refused`): check it
688
+ with `isManagementError`, and read `refusal` for the API's code: `admin_account` (only another
689
+ admin manages an admin), `not_disabled`, `disabled_by_admin` (an enable for an account an admin
690
+ disabled on the admin pages), `too_many_pending` (100 waiting), `insufficient_scope`,
691
+ `invalid_token`, `invalid_request`. No answer at all is `management_unavailable`. Tokens are
692
+ asked for per scope and kept; one the API refuses is renewed once. `url` overrides the API's
693
+ address (`<issuer>/api/auth/management` by default).
694
+
695
+ With NestJS, `IdpModule.forRoot(settings, { management: true })` (or `forRootAsync`) provides one
696
+ under the `MANAGEMENT` token, with the module's settings:
697
+
698
+ ```ts
699
+ import { Inject, Injectable } from "@nestjs/common";
700
+ import { MANAGEMENT, type Management } from "nextidp/nestjs";
701
+
702
+ @Injectable()
703
+ export class AccountsService {
704
+ constructor(@Inject(MANAGEMENT) private readonly accounts: Management) {}
705
+
706
+ suspend(userId: string) {
707
+ return this.accounts.disable(userId, { reason: "Suspended by an operator" });
708
+ }
709
+ }
710
+ ```
711
+
630
712
  ## Sessions in a store, and back-channel logout
631
713
 
632
714
  By default a session lives in its encrypted cookie, which only the browser holds: the auth
@@ -40,7 +40,11 @@ export type IdpErrorCode = SignInErrorCode
40
40
  */
41
41
  | "pushed_authorization_failed"
42
42
  /** A back-channel logout request's token didn't verify, or isn't a logout token. */
43
- | "invalid_logout_token";
43
+ | "invalid_logout_token"
44
+ /** The management API refused a call (`nextidp/management`): see ManagementError's refusal. */
45
+ | "management_refused"
46
+ /** The management API didn't answer (a network error or a timeout). */
47
+ | "management_unavailable";
44
48
  /** The three codes an API answers a caller with; see `tokenErrorResponse`. */
45
49
  export type TokenErrorCode = "missing_token" | "invalid_token" | "insufficient_scope";
46
50
  export declare function isTokenError(error: unknown): error is IdpError & {
@@ -6,5 +6,7 @@ export type Answer = {
6
6
  export type Http = {
7
7
  get(url: string, headers?: Record<string, string>): Promise<Answer>;
8
8
  postForm(url: string, form: URLSearchParams, headers?: Record<string, string>): Promise<Answer>;
9
+ /** A JSON body, never retried, like the form posts. */
10
+ postJson(url: string, body: unknown, headers?: Record<string, string>): Promise<Answer>;
9
11
  };
10
12
  export declare function createIdpHttp(): Http;
package/dist/cjs/http.js CHANGED
@@ -47,6 +47,19 @@ function createIdpHttp() {
47
47
  throw bare(error);
48
48
  }
49
49
  },
50
+ async postJson(url, body, headers) {
51
+ try {
52
+ const response = await client.post(url, JSON.stringify(body), {
53
+ retry: false,
54
+ headers: { "content-type": "application/json", ...headers }
55
+ });
56
+ return { ok: true, status: response.status, data: response.data };
57
+ } catch (error) {
58
+ const answer = refusal(error);
59
+ if (answer) return answer;
60
+ throw bare(error);
61
+ }
62
+ },
50
63
  async postForm(url, form, headers) {
51
64
  try {
52
65
  const response = await client.post(url, form, {
package/dist/cjs/idp.d.ts CHANGED
@@ -110,6 +110,11 @@ export type SignInPathOptions = {
110
110
  prompt?: string | undefined;
111
111
  /** false: no `prompt=login` from an earlier sign-out (see `reauthenticateAfterSignOut`). */
112
112
  reauthenticate?: boolean | undefined;
113
+ /**
114
+ * Who is signing in, usually their email (`login_hint`). Next-Identity Server sends someone
115
+ * whose company signs them in straight to the company's sign-in.
116
+ */
117
+ loginHint?: string | undefined;
113
118
  };
114
119
  /**
115
120
  * The client for one app. Settings are checked on first use, not here, so a module that
package/dist/cjs/idp.js CHANGED
@@ -45,6 +45,11 @@ function promptFrom(value) {
45
45
  if (values.length === 0 || !values.every((each) => PROMPTS.has(each))) return void 0;
46
46
  return [...new Set(values)].join(" ");
47
47
  }
48
+ function loginHintFrom(value) {
49
+ const hint = value?.trim();
50
+ if (!hint || hint.length > 254 || new RegExp("\\p{Cc}", "u").test(hint)) return void 0;
51
+ return hint;
52
+ }
48
53
  const SIGNED_OUT_MAX_AGE = 30 * 24 * 60 * 60;
49
54
  const INTROSPECTION_CACHE_MS = 6e4;
50
55
  const INTROSPECTION_CACHE_SIZE = 1e3;
@@ -299,6 +304,7 @@ function createIdp(options = {}) {
299
304
  async function login(s, request, url) {
300
305
  const returnTo = (0, import_return_path.safePath)(url.searchParams.get("returnTo")) ?? s.config.afterSignIn;
301
306
  const { prompt, setCookies } = promptOf(s, request, url);
307
+ const loginHint = loginHintFrom(url.searchParams.get("login_hint"));
302
308
  let discovery;
303
309
  try {
304
310
  discovery = await s.discovery();
@@ -317,7 +323,8 @@ function createIdp(options = {}) {
317
323
  code_challenge: await (0, import_pkce.challengeFor)(flow.verifier),
318
324
  code_challenge_method: "S256",
319
325
  ...s.config.resource ? { resource: s.config.resource } : {},
320
- ...prompt ? { prompt } : {}
326
+ ...prompt ? { prompt } : {},
327
+ ...loginHint ? { login_hint: loginHint } : {}
321
328
  });
322
329
  const authorize = new URL(discovery.authorization_endpoint);
323
330
  const push = pushEndpoint(s, discovery);
@@ -595,8 +602,10 @@ function createIdp(options = {}) {
595
602
  const query = new URLSearchParams();
596
603
  const safe = (0, import_return_path.safePath)(returnTo);
597
604
  const prompt = promptFrom(options2.prompt);
605
+ const loginHint = loginHintFrom(options2.loginHint);
598
606
  if (safe) query.set("returnTo", safe);
599
607
  if (prompt) query.set("prompt", prompt);
608
+ if (loginHint) query.set("login_hint", loginHint);
600
609
  if (options2.reauthenticate === false) query.set("reauthenticate", "false");
601
610
  const login2 = `${s.config.basePath}/login`;
602
611
  return query.size > 0 ? `${login2}?${query}` : login2;
@@ -0,0 +1,137 @@
1
+ import { type IdpOptions } from "./config.js";
2
+ import { IdpError } from "./errors.js";
3
+ /** The scopes the management API checks: looking up, and asking for changes. */
4
+ export declare const MANAGEMENT_SCOPES: {
5
+ readonly read: "management:users.read";
6
+ readonly manage: "management:users.manage";
7
+ };
8
+ export type ManagedUserStatus = "active" | "disabled" | "unconfirmed";
9
+ /** An account as the management API shows it: no secrets, no reason an admin wrote. */
10
+ export type ManagedUser = {
11
+ id: string;
12
+ email: string;
13
+ name: string;
14
+ emailVerified: boolean;
15
+ status: ManagedUserStatus;
16
+ /** When a disabled account opens again; null when it's until enabled, or not disabled. */
17
+ disabledUntil: string | null;
18
+ twoFactorEnabled: boolean;
19
+ createdAt: string;
20
+ /** When one of its sessions was last used; null when none is left. */
21
+ lastActiveAt: string | null;
22
+ };
23
+ export type ManagedRequestAction = "user.sign_out" | "user.disable" | "user.enable";
24
+ /**
25
+ * Where a request stands. `pending` until an admin decides; `approved` is done; `denied`
26
+ * comes with the admin's `note`, if any; `expired` after 7 days without a decision; `failed`
27
+ * when it was approved but something had changed (`problem` says what).
28
+ */
29
+ export type ManagedRequestStatus = "pending" | "approved" | "denied" | "expired" | "failed";
30
+ /** A request this service filed, as the API shows it. Dates are ISO 8601. */
31
+ export type ManagedRequest = {
32
+ id: string;
33
+ action: ManagedRequestAction;
34
+ userId: string;
35
+ status: ManagedRequestStatus;
36
+ /** For a disable: when the account opens again; null is until enabled. */
37
+ until: string | null;
38
+ /** What the deciding admin wrote, if anything. */
39
+ note: string | null;
40
+ /** Why an approved request couldn't be done, when it failed. */
41
+ problem: string | null;
42
+ createdAt: string;
43
+ expiresAt: string;
44
+ decidedAt: string | null;
45
+ };
46
+ /** One page of this service's requests, newest first. */
47
+ export type ManagedRequestPage = {
48
+ requests: ManagedRequest[];
49
+ page: number;
50
+ pageCount: number;
51
+ total: number;
52
+ };
53
+ export type RequestFilter = {
54
+ status?: ManagedRequestStatus | undefined;
55
+ /** Only requests about this account. */
56
+ userId?: string | undefined;
57
+ /** Only requests decided or expired since then: what changed since the last check. */
58
+ since?: Date | string | undefined;
59
+ /** From 1; 50 requests a page. */
60
+ page?: number | undefined;
61
+ };
62
+ export type DisableOptions = {
63
+ /** When the account opens again by itself (within a year); none: until it's enabled. */
64
+ until?: Date | string | undefined;
65
+ /** Why, for the admins who decide. The person never sees it. */
66
+ reason?: string | undefined;
67
+ };
68
+ /**
69
+ * What the management API refused, by the code it answered with. `request()` and
70
+ * `findUser()` answer undefined for a not_found rather than throwing.
71
+ */
72
+ export type ManagementRefusal =
73
+ /** The token was refused (401): a client that's disabled, or not linked to the API. */
74
+ "invalid_token"
75
+ /** The client lacks the scope the call needs (403). */
76
+ | "insufficient_scope"
77
+ /** An admin's account: only another admin manages it, on the admin pages (403). */
78
+ | "admin_account"
79
+ /** There's no such account (404). */
80
+ | "not_found"
81
+ /** An enable for an account that isn't disabled (409). */
82
+ | "not_disabled"
83
+ /** An enable for an account an admin disabled on the admin pages (409). */
84
+ | "disabled_by_admin"
85
+ /** This service already has 100 requests waiting (429). */
86
+ | "too_many_pending"
87
+ /** Something in the call was wrong (400): `message` says what. */
88
+ | "invalid_request";
89
+ /** A refusal from the management API. Check it with `isManagementError`. */
90
+ export declare class ManagementError extends IdpError {
91
+ /** The code the API answered with: a ManagementRefusal, or another the server sent. */
92
+ readonly refusal: ManagementRefusal | (string & {});
93
+ constructor(refusal: string, message: string, status: number);
94
+ }
95
+ export declare function isManagementError(error: unknown): error is ManagementError;
96
+ export type Management = {
97
+ /** An account by email or id, at once; undefined when there's none. Needs the read scope. */
98
+ findUser(by: {
99
+ email: string;
100
+ } | {
101
+ id: string;
102
+ }): Promise<ManagedUser | undefined>;
103
+ /** Asks for the account to be signed out everywhere. Waits for an admin: not done yet. */
104
+ signOut(userId: string): Promise<ManagedRequest>;
105
+ /** Asks for the account to be disabled, until a date or until enabled. Waits for an admin. */
106
+ disable(userId: string, options?: DisableOptions): Promise<ManagedRequest>;
107
+ /**
108
+ * Asks for a disabled account to be enabled. Waits for an admin. Refused for an account an
109
+ * admin disabled on the admin pages (`disabled_by_admin`), and one that isn't disabled.
110
+ */
111
+ enable(userId: string): Promise<ManagedRequest>;
112
+ /** One of this service's requests, as it stands now; undefined when there's none. */
113
+ request(id: string): Promise<ManagedRequest | undefined>;
114
+ /** This service's requests, newest first, 50 a page. */
115
+ requests(filter?: RequestFilter): Promise<ManagedRequestPage>;
116
+ };
117
+ export type ManagementOptions = IdpOptions & {
118
+ /**
119
+ * The management API's address. Default: `<issuer>/api/auth/management`, where
120
+ * Next-Identity Server serves it with MANAGEMENT_API=true.
121
+ */
122
+ url?: string | undefined;
123
+ };
124
+ /**
125
+ * A client for Next-Identity Server's management API, for a service with its own client:
126
+ * `clientId` and `clientSecret` (IDP_CLIENT_ID, IDP_CLIENT_SECRET) and the issuer
127
+ * (IDP_ISSUER), given the API and its scopes on the auth server's admin screen. Server code
128
+ * only: it holds the client secret.
129
+ *
130
+ * ```ts
131
+ * const accounts = management();
132
+ * const user = await accounts.findUser({ email: "ada@example.com" });
133
+ * const { id } = await accounts.disable(user.id, { reason: "Chargeback" }); // pending
134
+ * const later = await accounts.request(id); // approved, denied, expired, failed or pending
135
+ * ```
136
+ */
137
+ export declare function management(options?: ManagementOptions | (() => ManagementOptions)): Management;
@@ -0,0 +1,155 @@
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 management_exports = {};
20
+ __export(management_exports, {
21
+ MANAGEMENT_SCOPES: () => MANAGEMENT_SCOPES,
22
+ ManagementError: () => ManagementError,
23
+ isManagementError: () => isManagementError,
24
+ management: () => management
25
+ });
26
+ module.exports = __toCommonJS(management_exports);
27
+ var import_config = require("./config.js");
28
+ var import_errors = require("./errors.js");
29
+ var import_http = require("./http.js");
30
+ var import_idp = require("./idp.js");
31
+ const MANAGEMENT_SCOPES = {
32
+ read: "management:users.read",
33
+ manage: "management:users.manage"
34
+ };
35
+ const MANAGEMENT_PATH = "/api/auth/management";
36
+ class ManagementError extends import_errors.IdpError {
37
+ /** The code the API answered with: a ManagementRefusal, or another the server sent. */
38
+ refusal;
39
+ constructor(refusal, message, status) {
40
+ super("management_refused", message, { status });
41
+ this.refusal = refusal;
42
+ }
43
+ }
44
+ function isManagementError(error) {
45
+ return (0, import_errors.isIdpError)(error) && error.code === "management_refused" && typeof error.refusal === "string";
46
+ }
47
+ function iso(value) {
48
+ if (value === void 0) return void 0;
49
+ const date = value instanceof Date ? value : new Date(value);
50
+ if (Number.isNaN(date.getTime())) {
51
+ throw new import_errors.IdpError("misconfigured", "nextidp: a management date must be a valid date.");
52
+ }
53
+ return date.toISOString();
54
+ }
55
+ function refusalOf(answer) {
56
+ const data = answer.data ?? {};
57
+ const code = typeof data.error === "string" ? data.error : `http_${answer.status}`;
58
+ const description = typeof data.error_description === "string" ? data.error_description : "No description.";
59
+ return new ManagementError(
60
+ code,
61
+ `The management API refused the call (${code}): ${description}`,
62
+ answer.status
63
+ );
64
+ }
65
+ function management(options = {}) {
66
+ let resolved;
67
+ const ready = () => {
68
+ if (resolved) return resolved;
69
+ const settings = typeof options === "function" ? options() : options;
70
+ const config = (0, import_config.resolveServiceConfig)(settings);
71
+ const url = (settings.url ?? `${config.issuer}${MANAGEMENT_PATH}`).replace(/\/+$/, "");
72
+ if (!URL.canParse(url) || !/^https?:/i.test(url)) {
73
+ throw new import_errors.IdpError("misconfigured", "nextidp is misconfigured: url must be an http(s) URL.");
74
+ }
75
+ resolved = { url, idp: (0, import_idp.createIdp)(settings), http: (0, import_http.createIdpHttp)() };
76
+ return resolved;
77
+ };
78
+ async function call(scope, send) {
79
+ const { url, idp, http } = ready();
80
+ const tokenFor = (fresh) => idp.serviceToken({ scopes: [MANAGEMENT_SCOPES[scope]], resource: url, fresh });
81
+ const sent = async (token2) => {
82
+ try {
83
+ return await send(http, url, { authorization: `Bearer ${token2}` });
84
+ } catch {
85
+ throw new import_errors.IdpError("management_unavailable", "The management API didn't answer.");
86
+ }
87
+ };
88
+ const token = await tokenFor(false);
89
+ const answer = await sent(token);
90
+ if (answer.status !== 401) return answer;
91
+ idp.dropServiceToken(token);
92
+ return sent(await tokenFor(true));
93
+ }
94
+ async function ask(path, body) {
95
+ const answer = await call(
96
+ "manage",
97
+ (http, url, auth) => http.postJson(`${url}${path}`, body, auth)
98
+ );
99
+ if (!answer.ok) throw refusalOf(answer);
100
+ return answer.data.request;
101
+ }
102
+ return {
103
+ async findUser(by) {
104
+ const query = new URLSearchParams("email" in by ? { email: by.email } : { id: by.id });
105
+ const answer = await call(
106
+ "read",
107
+ (http, url, auth) => http.get(`${url}/users?${query}`, auth)
108
+ );
109
+ if (answer.status === 404) return void 0;
110
+ if (!answer.ok) throw refusalOf(answer);
111
+ return answer.data.user;
112
+ },
113
+ signOut: (userId) => ask("/users/sign-out", { userId }),
114
+ async disable(userId, options2 = {}) {
115
+ const until = iso(options2.until);
116
+ return ask("/users/disable", {
117
+ userId,
118
+ ...until ? { until } : {},
119
+ ...options2.reason ? { reason: options2.reason } : {}
120
+ });
121
+ },
122
+ enable: (userId) => ask("/users/enable", { userId }),
123
+ async request(id) {
124
+ const answer = await call(
125
+ "manage",
126
+ (http, url, auth) => http.get(`${url}/requests/${encodeURIComponent(id)}`, auth)
127
+ );
128
+ if (answer.status === 404) return void 0;
129
+ if (!answer.ok) throw refusalOf(answer);
130
+ return answer.data.request;
131
+ },
132
+ async requests(filter = {}) {
133
+ const query = new URLSearchParams();
134
+ if (filter.status) query.set("status", filter.status);
135
+ if (filter.userId) query.set("userId", filter.userId);
136
+ const since = iso(filter.since);
137
+ if (since) query.set("since", since);
138
+ if (filter.page !== void 0) query.set("page", String(filter.page));
139
+ const text = query.toString();
140
+ const answer = await call(
141
+ "manage",
142
+ (http, url, auth) => http.get(`${url}/requests${text ? `?${text}` : ""}`, auth)
143
+ );
144
+ if (!answer.ok) throw refusalOf(answer);
145
+ return answer.data;
146
+ }
147
+ };
148
+ }
149
+ // Annotate the CommonJS export names for ESM import in node:
150
+ 0 && (module.exports = {
151
+ MANAGEMENT_SCOPES,
152
+ ManagementError,
153
+ isManagementError,
154
+ management
155
+ });
@@ -2,8 +2,11 @@ import { type CanActivate, type DynamicModule, type ExecutionContext } from "@ne
2
2
  import { Reflector } from "@nestjs/core";
3
3
  import type { IdpOptions } from "./config.js";
4
4
  import { type Idp } from "./idp.js";
5
+ import { type ManagementOptions } from "./management.js";
5
6
  /** The injection token of the `Idp` instance the module was given. */
6
7
  export declare const IDP = "nextidp:idp";
8
+ /** The injection token of the management client, with `management` on (nextidp/management). */
9
+ export declare const MANAGEMENT = "nextidp:management";
7
10
  /** Every one of these scopes is needed. On a controller, they add to its routes' own. */
8
11
  export declare const Scopes: (...scopes: string[]) => import("@nestjs/common").CustomDecorator<string>;
9
12
  /** No token needed for this route (or every route of this controller). */
@@ -27,6 +30,12 @@ export type IdpModuleOptions = {
27
30
  * it's @Public(). With false, guard routes yourself: @UseGuards(IdpGuard).
28
31
  */
29
32
  protectAll?: boolean;
33
+ /**
34
+ * Provide a management client (`nextidp/management`) under the MANAGEMENT token: `true`
35
+ * for one with the module's own settings (or IDP_* when given an Idp), or its own settings.
36
+ * It needs the client's secret, and the management API's scopes for that client.
37
+ */
38
+ management?: true | ManagementOptions | undefined;
30
39
  };
31
40
  export type IdpModuleAsyncOptions = IdpModuleOptions & {
32
41
  imports?: DynamicModule["imports"];
@@ -51,4 +60,5 @@ export type { ApiConfig, IdpOptions } from "./config.js";
51
60
  export { IdpError, isIdpError, isTokenError, type TokenErrorCode } from "./errors.js";
52
61
  export type { ExchangeTokenOptions } from "./exchange.js";
53
62
  export { createIdp as idp, type Idp } from "./idp.js";
63
+ export type { Management, ManagementOptions } from "./management.js";
54
64
  export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
@@ -23,6 +23,7 @@ __export(nestjs_exports, {
23
23
  IdpError: () => import_errors2.IdpError,
24
24
  IdpGuard: () => IdpGuard,
25
25
  IdpModule: () => IdpModule,
26
+ MANAGEMENT: () => MANAGEMENT,
26
27
  Public: () => Public,
27
28
  Scopes: () => Scopes,
28
29
  idp: () => import_idp2.createIdp,
@@ -35,9 +36,11 @@ var import_core = require("@nestjs/core");
35
36
  var import_access_token = require("./access-token.js");
36
37
  var import_errors = require("./errors.js");
37
38
  var import_idp = require("./idp.js");
39
+ var import_management = require("./management.js");
38
40
  var import_errors2 = require("./errors.js");
39
41
  var import_idp2 = require("./idp.js");
40
42
  const IDP = "nextidp:idp";
43
+ const MANAGEMENT = "nextidp:management";
41
44
  const SCOPES_KEY = "nextidp:scopes";
42
45
  const PUBLIC_KEY = "nextidp:public";
43
46
  const Scopes = (...scopes) => (0, import_common.SetMetadata)(SCOPES_KEY, scopes);
@@ -94,6 +97,10 @@ class IdpGuard {
94
97
  function isIdp(value) {
95
98
  return typeof value.verifyBearer === "function";
96
99
  }
100
+ function managementProvider(wanted, settings) {
101
+ if (!wanted) return [];
102
+ return [{ provide: MANAGEMENT, useValue: (0, import_management.management)(wanted === true ? settings : wanted) }];
103
+ }
97
104
  function guards(protectAll) {
98
105
  return [IdpGuard, ...protectAll === false ? [] : [{ provide: import_core.APP_GUARD, useClass: IdpGuard }]];
99
106
  }
@@ -104,12 +111,15 @@ class IdpModule {
104
111
  global: true,
105
112
  providers: [
106
113
  { provide: IDP, useValue: isIdp(auth) ? auth : (0, import_idp.createIdp)(auth) },
107
- ...guards(options.protectAll)
114
+ ...guards(options.protectAll),
115
+ ...managementProvider(options.management, () => isIdp(auth) ? {} : auth)
108
116
  ],
109
- exports: [IDP, IdpGuard]
117
+ exports: [IDP, IdpGuard, ...options.management ? [MANAGEMENT] : []]
110
118
  };
111
119
  }
112
120
  static forRootAsync(options) {
121
+ const settingsOf = options.useFactory;
122
+ const wanted = options.management;
113
123
  return {
114
124
  module: IdpModule,
115
125
  global: true,
@@ -120,9 +130,16 @@ class IdpModule {
120
130
  inject: options.inject ?? [],
121
131
  useFactory: async (...args) => (0, import_idp.createIdp)(await options.useFactory(...args))
122
132
  },
123
- ...guards(options.protectAll)
133
+ ...guards(options.protectAll),
134
+ ...options.management ? [
135
+ {
136
+ provide: MANAGEMENT,
137
+ inject: options.inject ?? [],
138
+ useFactory: async (...args) => (0, import_management.management)(wanted === true ? await settingsOf(...args) : wanted ?? {})
139
+ }
140
+ ] : []
124
141
  ],
125
- exports: [IDP, IdpGuard]
142
+ exports: [IDP, IdpGuard, ...options.management ? [MANAGEMENT] : []]
126
143
  };
127
144
  }
128
145
  }
@@ -134,6 +151,7 @@ class IdpModule {
134
151
  IdpError,
135
152
  IdpGuard,
136
153
  IdpModule,
154
+ MANAGEMENT,
137
155
  Public,
138
156
  Scopes,
139
157
  idp,
@@ -40,7 +40,11 @@ export type IdpErrorCode = SignInErrorCode
40
40
  */
41
41
  | "pushed_authorization_failed"
42
42
  /** A back-channel logout request's token didn't verify, or isn't a logout token. */
43
- | "invalid_logout_token";
43
+ | "invalid_logout_token"
44
+ /** The management API refused a call (`nextidp/management`): see ManagementError's refusal. */
45
+ | "management_refused"
46
+ /** The management API didn't answer (a network error or a timeout). */
47
+ | "management_unavailable";
44
48
  /** The three codes an API answers a caller with; see `tokenErrorResponse`. */
45
49
  export type TokenErrorCode = "missing_token" | "invalid_token" | "insufficient_scope";
46
50
  export declare function isTokenError(error: unknown): error is IdpError & {
@@ -6,5 +6,7 @@ export type Answer = {
6
6
  export type Http = {
7
7
  get(url: string, headers?: Record<string, string>): Promise<Answer>;
8
8
  postForm(url: string, form: URLSearchParams, headers?: Record<string, string>): Promise<Answer>;
9
+ /** A JSON body, never retried, like the form posts. */
10
+ postJson(url: string, body: unknown, headers?: Record<string, string>): Promise<Answer>;
9
11
  };
10
12
  export declare function createIdpHttp(): Http;
package/dist/esm/http.js CHANGED
@@ -24,6 +24,19 @@ function createIdpHttp() {
24
24
  throw bare(error);
25
25
  }
26
26
  },
27
+ async postJson(url, body, headers) {
28
+ try {
29
+ const response = await client.post(url, JSON.stringify(body), {
30
+ retry: false,
31
+ headers: { "content-type": "application/json", ...headers }
32
+ });
33
+ return { ok: true, status: response.status, data: response.data };
34
+ } catch (error) {
35
+ const answer = refusal(error);
36
+ if (answer) return answer;
37
+ throw bare(error);
38
+ }
39
+ },
27
40
  async postForm(url, form, headers) {
28
41
  try {
29
42
  const response = await client.post(url, form, {
package/dist/esm/idp.d.ts CHANGED
@@ -110,6 +110,11 @@ export type SignInPathOptions = {
110
110
  prompt?: string | undefined;
111
111
  /** false: no `prompt=login` from an earlier sign-out (see `reauthenticateAfterSignOut`). */
112
112
  reauthenticate?: boolean | undefined;
113
+ /**
114
+ * Who is signing in, usually their email (`login_hint`). Next-Identity Server sends someone
115
+ * whose company signs them in straight to the company's sign-in.
116
+ */
117
+ loginHint?: string | undefined;
113
118
  };
114
119
  /**
115
120
  * The client for one app. Settings are checked on first use, not here, so a module that
package/dist/esm/idp.js CHANGED
@@ -55,6 +55,11 @@ function promptFrom(value) {
55
55
  if (values.length === 0 || !values.every((each) => PROMPTS.has(each))) return void 0;
56
56
  return [...new Set(values)].join(" ");
57
57
  }
58
+ function loginHintFrom(value) {
59
+ const hint = value?.trim();
60
+ if (!hint || hint.length > 254 || new RegExp("\\p{Cc}", "u").test(hint)) return void 0;
61
+ return hint;
62
+ }
58
63
  const SIGNED_OUT_MAX_AGE = 30 * 24 * 60 * 60;
59
64
  const INTROSPECTION_CACHE_MS = 6e4;
60
65
  const INTROSPECTION_CACHE_SIZE = 1e3;
@@ -309,6 +314,7 @@ function createIdp(options = {}) {
309
314
  async function login(s, request, url) {
310
315
  const returnTo = safePath(url.searchParams.get("returnTo")) ?? s.config.afterSignIn;
311
316
  const { prompt, setCookies } = promptOf(s, request, url);
317
+ const loginHint = loginHintFrom(url.searchParams.get("login_hint"));
312
318
  let discovery;
313
319
  try {
314
320
  discovery = await s.discovery();
@@ -327,7 +333,8 @@ function createIdp(options = {}) {
327
333
  code_challenge: await challengeFor(flow.verifier),
328
334
  code_challenge_method: "S256",
329
335
  ...s.config.resource ? { resource: s.config.resource } : {},
330
- ...prompt ? { prompt } : {}
336
+ ...prompt ? { prompt } : {},
337
+ ...loginHint ? { login_hint: loginHint } : {}
331
338
  });
332
339
  const authorize = new URL(discovery.authorization_endpoint);
333
340
  const push = pushEndpoint(s, discovery);
@@ -605,8 +612,10 @@ function createIdp(options = {}) {
605
612
  const query = new URLSearchParams();
606
613
  const safe = safePath(returnTo);
607
614
  const prompt = promptFrom(options2.prompt);
615
+ const loginHint = loginHintFrom(options2.loginHint);
608
616
  if (safe) query.set("returnTo", safe);
609
617
  if (prompt) query.set("prompt", prompt);
618
+ if (loginHint) query.set("login_hint", loginHint);
610
619
  if (options2.reauthenticate === false) query.set("reauthenticate", "false");
611
620
  const login2 = `${s.config.basePath}/login`;
612
621
  return query.size > 0 ? `${login2}?${query}` : login2;
@@ -0,0 +1,137 @@
1
+ import { type IdpOptions } from "./config.js";
2
+ import { IdpError } from "./errors.js";
3
+ /** The scopes the management API checks: looking up, and asking for changes. */
4
+ export declare const MANAGEMENT_SCOPES: {
5
+ readonly read: "management:users.read";
6
+ readonly manage: "management:users.manage";
7
+ };
8
+ export type ManagedUserStatus = "active" | "disabled" | "unconfirmed";
9
+ /** An account as the management API shows it: no secrets, no reason an admin wrote. */
10
+ export type ManagedUser = {
11
+ id: string;
12
+ email: string;
13
+ name: string;
14
+ emailVerified: boolean;
15
+ status: ManagedUserStatus;
16
+ /** When a disabled account opens again; null when it's until enabled, or not disabled. */
17
+ disabledUntil: string | null;
18
+ twoFactorEnabled: boolean;
19
+ createdAt: string;
20
+ /** When one of its sessions was last used; null when none is left. */
21
+ lastActiveAt: string | null;
22
+ };
23
+ export type ManagedRequestAction = "user.sign_out" | "user.disable" | "user.enable";
24
+ /**
25
+ * Where a request stands. `pending` until an admin decides; `approved` is done; `denied`
26
+ * comes with the admin's `note`, if any; `expired` after 7 days without a decision; `failed`
27
+ * when it was approved but something had changed (`problem` says what).
28
+ */
29
+ export type ManagedRequestStatus = "pending" | "approved" | "denied" | "expired" | "failed";
30
+ /** A request this service filed, as the API shows it. Dates are ISO 8601. */
31
+ export type ManagedRequest = {
32
+ id: string;
33
+ action: ManagedRequestAction;
34
+ userId: string;
35
+ status: ManagedRequestStatus;
36
+ /** For a disable: when the account opens again; null is until enabled. */
37
+ until: string | null;
38
+ /** What the deciding admin wrote, if anything. */
39
+ note: string | null;
40
+ /** Why an approved request couldn't be done, when it failed. */
41
+ problem: string | null;
42
+ createdAt: string;
43
+ expiresAt: string;
44
+ decidedAt: string | null;
45
+ };
46
+ /** One page of this service's requests, newest first. */
47
+ export type ManagedRequestPage = {
48
+ requests: ManagedRequest[];
49
+ page: number;
50
+ pageCount: number;
51
+ total: number;
52
+ };
53
+ export type RequestFilter = {
54
+ status?: ManagedRequestStatus | undefined;
55
+ /** Only requests about this account. */
56
+ userId?: string | undefined;
57
+ /** Only requests decided or expired since then: what changed since the last check. */
58
+ since?: Date | string | undefined;
59
+ /** From 1; 50 requests a page. */
60
+ page?: number | undefined;
61
+ };
62
+ export type DisableOptions = {
63
+ /** When the account opens again by itself (within a year); none: until it's enabled. */
64
+ until?: Date | string | undefined;
65
+ /** Why, for the admins who decide. The person never sees it. */
66
+ reason?: string | undefined;
67
+ };
68
+ /**
69
+ * What the management API refused, by the code it answered with. `request()` and
70
+ * `findUser()` answer undefined for a not_found rather than throwing.
71
+ */
72
+ export type ManagementRefusal =
73
+ /** The token was refused (401): a client that's disabled, or not linked to the API. */
74
+ "invalid_token"
75
+ /** The client lacks the scope the call needs (403). */
76
+ | "insufficient_scope"
77
+ /** An admin's account: only another admin manages it, on the admin pages (403). */
78
+ | "admin_account"
79
+ /** There's no such account (404). */
80
+ | "not_found"
81
+ /** An enable for an account that isn't disabled (409). */
82
+ | "not_disabled"
83
+ /** An enable for an account an admin disabled on the admin pages (409). */
84
+ | "disabled_by_admin"
85
+ /** This service already has 100 requests waiting (429). */
86
+ | "too_many_pending"
87
+ /** Something in the call was wrong (400): `message` says what. */
88
+ | "invalid_request";
89
+ /** A refusal from the management API. Check it with `isManagementError`. */
90
+ export declare class ManagementError extends IdpError {
91
+ /** The code the API answered with: a ManagementRefusal, or another the server sent. */
92
+ readonly refusal: ManagementRefusal | (string & {});
93
+ constructor(refusal: string, message: string, status: number);
94
+ }
95
+ export declare function isManagementError(error: unknown): error is ManagementError;
96
+ export type Management = {
97
+ /** An account by email or id, at once; undefined when there's none. Needs the read scope. */
98
+ findUser(by: {
99
+ email: string;
100
+ } | {
101
+ id: string;
102
+ }): Promise<ManagedUser | undefined>;
103
+ /** Asks for the account to be signed out everywhere. Waits for an admin: not done yet. */
104
+ signOut(userId: string): Promise<ManagedRequest>;
105
+ /** Asks for the account to be disabled, until a date or until enabled. Waits for an admin. */
106
+ disable(userId: string, options?: DisableOptions): Promise<ManagedRequest>;
107
+ /**
108
+ * Asks for a disabled account to be enabled. Waits for an admin. Refused for an account an
109
+ * admin disabled on the admin pages (`disabled_by_admin`), and one that isn't disabled.
110
+ */
111
+ enable(userId: string): Promise<ManagedRequest>;
112
+ /** One of this service's requests, as it stands now; undefined when there's none. */
113
+ request(id: string): Promise<ManagedRequest | undefined>;
114
+ /** This service's requests, newest first, 50 a page. */
115
+ requests(filter?: RequestFilter): Promise<ManagedRequestPage>;
116
+ };
117
+ export type ManagementOptions = IdpOptions & {
118
+ /**
119
+ * The management API's address. Default: `<issuer>/api/auth/management`, where
120
+ * Next-Identity Server serves it with MANAGEMENT_API=true.
121
+ */
122
+ url?: string | undefined;
123
+ };
124
+ /**
125
+ * A client for Next-Identity Server's management API, for a service with its own client:
126
+ * `clientId` and `clientSecret` (IDP_CLIENT_ID, IDP_CLIENT_SECRET) and the issuer
127
+ * (IDP_ISSUER), given the API and its scopes on the auth server's admin screen. Server code
128
+ * only: it holds the client secret.
129
+ *
130
+ * ```ts
131
+ * const accounts = management();
132
+ * const user = await accounts.findUser({ email: "ada@example.com" });
133
+ * const { id } = await accounts.disable(user.id, { reason: "Chargeback" }); // pending
134
+ * const later = await accounts.request(id); // approved, denied, expired, failed or pending
135
+ * ```
136
+ */
137
+ export declare function management(options?: ManagementOptions | (() => ManagementOptions)): Management;
@@ -0,0 +1,128 @@
1
+ import { resolveServiceConfig } from "./config.js";
2
+ import { IdpError, isIdpError } from "./errors.js";
3
+ import { createIdpHttp } from "./http.js";
4
+ import { createIdp } from "./idp.js";
5
+ const MANAGEMENT_SCOPES = {
6
+ read: "management:users.read",
7
+ manage: "management:users.manage"
8
+ };
9
+ const MANAGEMENT_PATH = "/api/auth/management";
10
+ class ManagementError extends IdpError {
11
+ /** The code the API answered with: a ManagementRefusal, or another the server sent. */
12
+ refusal;
13
+ constructor(refusal, message, status) {
14
+ super("management_refused", message, { status });
15
+ this.refusal = refusal;
16
+ }
17
+ }
18
+ function isManagementError(error) {
19
+ return isIdpError(error) && error.code === "management_refused" && typeof error.refusal === "string";
20
+ }
21
+ function iso(value) {
22
+ if (value === void 0) return void 0;
23
+ const date = value instanceof Date ? value : new Date(value);
24
+ if (Number.isNaN(date.getTime())) {
25
+ throw new IdpError("misconfigured", "nextidp: a management date must be a valid date.");
26
+ }
27
+ return date.toISOString();
28
+ }
29
+ function refusalOf(answer) {
30
+ const data = answer.data ?? {};
31
+ const code = typeof data.error === "string" ? data.error : `http_${answer.status}`;
32
+ const description = typeof data.error_description === "string" ? data.error_description : "No description.";
33
+ return new ManagementError(
34
+ code,
35
+ `The management API refused the call (${code}): ${description}`,
36
+ answer.status
37
+ );
38
+ }
39
+ function management(options = {}) {
40
+ let resolved;
41
+ const ready = () => {
42
+ if (resolved) return resolved;
43
+ const settings = typeof options === "function" ? options() : options;
44
+ const config = resolveServiceConfig(settings);
45
+ const url = (settings.url ?? `${config.issuer}${MANAGEMENT_PATH}`).replace(/\/+$/, "");
46
+ if (!URL.canParse(url) || !/^https?:/i.test(url)) {
47
+ throw new IdpError("misconfigured", "nextidp is misconfigured: url must be an http(s) URL.");
48
+ }
49
+ resolved = { url, idp: createIdp(settings), http: createIdpHttp() };
50
+ return resolved;
51
+ };
52
+ async function call(scope, send) {
53
+ const { url, idp, http } = ready();
54
+ const tokenFor = (fresh) => idp.serviceToken({ scopes: [MANAGEMENT_SCOPES[scope]], resource: url, fresh });
55
+ const sent = async (token2) => {
56
+ try {
57
+ return await send(http, url, { authorization: `Bearer ${token2}` });
58
+ } catch {
59
+ throw new IdpError("management_unavailable", "The management API didn't answer.");
60
+ }
61
+ };
62
+ const token = await tokenFor(false);
63
+ const answer = await sent(token);
64
+ if (answer.status !== 401) return answer;
65
+ idp.dropServiceToken(token);
66
+ return sent(await tokenFor(true));
67
+ }
68
+ async function ask(path, body) {
69
+ const answer = await call(
70
+ "manage",
71
+ (http, url, auth) => http.postJson(`${url}${path}`, body, auth)
72
+ );
73
+ if (!answer.ok) throw refusalOf(answer);
74
+ return answer.data.request;
75
+ }
76
+ return {
77
+ async findUser(by) {
78
+ const query = new URLSearchParams("email" in by ? { email: by.email } : { id: by.id });
79
+ const answer = await call(
80
+ "read",
81
+ (http, url, auth) => http.get(`${url}/users?${query}`, auth)
82
+ );
83
+ if (answer.status === 404) return void 0;
84
+ if (!answer.ok) throw refusalOf(answer);
85
+ return answer.data.user;
86
+ },
87
+ signOut: (userId) => ask("/users/sign-out", { userId }),
88
+ async disable(userId, options2 = {}) {
89
+ const until = iso(options2.until);
90
+ return ask("/users/disable", {
91
+ userId,
92
+ ...until ? { until } : {},
93
+ ...options2.reason ? { reason: options2.reason } : {}
94
+ });
95
+ },
96
+ enable: (userId) => ask("/users/enable", { userId }),
97
+ async request(id) {
98
+ const answer = await call(
99
+ "manage",
100
+ (http, url, auth) => http.get(`${url}/requests/${encodeURIComponent(id)}`, auth)
101
+ );
102
+ if (answer.status === 404) return void 0;
103
+ if (!answer.ok) throw refusalOf(answer);
104
+ return answer.data.request;
105
+ },
106
+ async requests(filter = {}) {
107
+ const query = new URLSearchParams();
108
+ if (filter.status) query.set("status", filter.status);
109
+ if (filter.userId) query.set("userId", filter.userId);
110
+ const since = iso(filter.since);
111
+ if (since) query.set("since", since);
112
+ if (filter.page !== void 0) query.set("page", String(filter.page));
113
+ const text = query.toString();
114
+ const answer = await call(
115
+ "manage",
116
+ (http, url, auth) => http.get(`${url}/requests${text ? `?${text}` : ""}`, auth)
117
+ );
118
+ if (!answer.ok) throw refusalOf(answer);
119
+ return answer.data;
120
+ }
121
+ };
122
+ }
123
+ export {
124
+ MANAGEMENT_SCOPES,
125
+ ManagementError,
126
+ isManagementError,
127
+ management
128
+ };
@@ -2,8 +2,11 @@ import { type CanActivate, type DynamicModule, type ExecutionContext } from "@ne
2
2
  import { Reflector } from "@nestjs/core";
3
3
  import type { IdpOptions } from "./config.js";
4
4
  import { type Idp } from "./idp.js";
5
+ import { type ManagementOptions } from "./management.js";
5
6
  /** The injection token of the `Idp` instance the module was given. */
6
7
  export declare const IDP = "nextidp:idp";
8
+ /** The injection token of the management client, with `management` on (nextidp/management). */
9
+ export declare const MANAGEMENT = "nextidp:management";
7
10
  /** Every one of these scopes is needed. On a controller, they add to its routes' own. */
8
11
  export declare const Scopes: (...scopes: string[]) => import("@nestjs/common").CustomDecorator<string>;
9
12
  /** No token needed for this route (or every route of this controller). */
@@ -27,6 +30,12 @@ export type IdpModuleOptions = {
27
30
  * it's @Public(). With false, guard routes yourself: @UseGuards(IdpGuard).
28
31
  */
29
32
  protectAll?: boolean;
33
+ /**
34
+ * Provide a management client (`nextidp/management`) under the MANAGEMENT token: `true`
35
+ * for one with the module's own settings (or IDP_* when given an Idp), or its own settings.
36
+ * It needs the client's secret, and the management API's scopes for that client.
37
+ */
38
+ management?: true | ManagementOptions | undefined;
30
39
  };
31
40
  export type IdpModuleAsyncOptions = IdpModuleOptions & {
32
41
  imports?: DynamicModule["imports"];
@@ -51,4 +60,5 @@ export type { ApiConfig, IdpOptions } from "./config.js";
51
60
  export { IdpError, isIdpError, isTokenError, type TokenErrorCode } from "./errors.js";
52
61
  export type { ExchangeTokenOptions } from "./exchange.js";
53
62
  export { createIdp as idp, type Idp } from "./idp.js";
63
+ export type { Management, ManagementOptions } from "./management.js";
54
64
  export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
@@ -12,7 +12,9 @@ import { APP_GUARD, Reflector } from "@nestjs/core";
12
12
  import { bearerChallenge } from "./access-token.js";
13
13
  import { isIdpError, isTokenError } from "./errors.js";
14
14
  import { createIdp } from "./idp.js";
15
+ import { management } from "./management.js";
15
16
  const IDP = "nextidp:idp";
17
+ const MANAGEMENT = "nextidp:management";
16
18
  const SCOPES_KEY = "nextidp:scopes";
17
19
  const PUBLIC_KEY = "nextidp:public";
18
20
  const Scopes = (...scopes) => SetMetadata(SCOPES_KEY, scopes);
@@ -69,6 +71,10 @@ Inject(Reflector)(IdpGuard, void 0, 1);
69
71
  function isIdp(value) {
70
72
  return typeof value.verifyBearer === "function";
71
73
  }
74
+ function managementProvider(wanted, settings) {
75
+ if (!wanted) return [];
76
+ return [{ provide: MANAGEMENT, useValue: management(wanted === true ? settings : wanted) }];
77
+ }
72
78
  function guards(protectAll) {
73
79
  return [IdpGuard, ...protectAll === false ? [] : [{ provide: APP_GUARD, useClass: IdpGuard }]];
74
80
  }
@@ -79,12 +85,15 @@ class IdpModule {
79
85
  global: true,
80
86
  providers: [
81
87
  { provide: IDP, useValue: isIdp(auth) ? auth : createIdp(auth) },
82
- ...guards(options.protectAll)
88
+ ...guards(options.protectAll),
89
+ ...managementProvider(options.management, () => isIdp(auth) ? {} : auth)
83
90
  ],
84
- exports: [IDP, IdpGuard]
91
+ exports: [IDP, IdpGuard, ...options.management ? [MANAGEMENT] : []]
85
92
  };
86
93
  }
87
94
  static forRootAsync(options) {
95
+ const settingsOf = options.useFactory;
96
+ const wanted = options.management;
88
97
  return {
89
98
  module: IdpModule,
90
99
  global: true,
@@ -95,9 +104,16 @@ class IdpModule {
95
104
  inject: options.inject ?? [],
96
105
  useFactory: async (...args) => createIdp(await options.useFactory(...args))
97
106
  },
98
- ...guards(options.protectAll)
107
+ ...guards(options.protectAll),
108
+ ...options.management ? [
109
+ {
110
+ provide: MANAGEMENT,
111
+ inject: options.inject ?? [],
112
+ useFactory: async (...args) => management(wanted === true ? await settingsOf(...args) : wanted ?? {})
113
+ }
114
+ ] : []
99
115
  ],
100
- exports: [IDP, IdpGuard]
116
+ exports: [IDP, IdpGuard, ...options.management ? [MANAGEMENT] : []]
101
117
  };
102
118
  }
103
119
  }
@@ -110,6 +126,7 @@ export {
110
126
  IdpError,
111
127
  IdpGuard,
112
128
  IdpModule,
129
+ MANAGEMENT,
113
130
  Public,
114
131
  Scopes,
115
132
  createIdp2 as idp,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nextidp",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Sign people in to Next.js, Express, Fastify, Hono and Node apps, and protect NestJS, Express, Fastify, Hono and Next.js APIs, with Next-Identity Server, in one call. Runs on Node and edge runtimes.",
5
5
  "keywords": [
6
6
  "oidc",
@@ -47,6 +47,9 @@
47
47
  ],
48
48
  "nestjs": [
49
49
  "./dist/cjs/nestjs.d.ts"
50
+ ],
51
+ "management": [
52
+ "./dist/cjs/management.d.ts"
50
53
  ]
51
54
  }
52
55
  },
@@ -126,6 +129,16 @@
126
129
  "default": "./dist/cjs/nestjs.js"
127
130
  }
128
131
  },
132
+ "./management": {
133
+ "import": {
134
+ "types": "./dist/esm/management.d.ts",
135
+ "default": "./dist/esm/management.js"
136
+ },
137
+ "require": {
138
+ "types": "./dist/cjs/management.d.ts",
139
+ "default": "./dist/cjs/management.js"
140
+ }
141
+ },
129
142
  "./package.json": "./package.json"
130
143
  },
131
144
  "files": [
@@ -174,7 +187,7 @@
174
187
  "fastify": "5.12.8",
175
188
  "hono": "4.13.22",
176
189
  "miniflare": "4.20260730.0",
177
- "next": "16.4.6",
190
+ "next": "16.5.0",
178
191
  "publint": "0.3.25",
179
192
  "react": "19.3.1",
180
193
  "react-dom": "19.3.1",