nextidp 0.3.0 → 0.5.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 +23 -0
- package/README.md +68 -0
- package/dist/cjs/access-token.js +1 -1
- package/dist/cjs/errors.d.ts +5 -1
- package/dist/cjs/http.d.ts +2 -0
- package/dist/cjs/http.js +13 -0
- package/dist/cjs/id-token.js +1 -1
- package/dist/cjs/management.d.ts +137 -0
- package/dist/cjs/management.js +155 -0
- package/dist/cjs/nestjs.d.ts +10 -0
- package/dist/cjs/nestjs.js +22 -4
- package/dist/esm/access-token.js +1 -1
- package/dist/esm/errors.d.ts +5 -1
- package/dist/esm/http.d.ts +2 -0
- package/dist/esm/http.js +13 -0
- package/dist/esm/id-token.js +1 -1
- package/dist/esm/management.d.ts +137 -0
- package/dist/esm/management.js +128 -0
- package/dist/esm/nestjs.d.ts +10 -0
- package/dist/esm/nestjs.js +21 -4
- package/package.json +15 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.0
|
|
4
|
+
|
|
5
|
+
### Managing accounts
|
|
6
|
+
|
|
7
|
+
- `nextidp/management`: a service's side of Next-Identity Server's management API (on with
|
|
8
|
+
`MANAGEMENT_API=true` there). `management()` takes the service's settings (IDP_ISSUER,
|
|
9
|
+
IDP_CLIENT_ID, IDP_CLIENT_SECRET) and gives `findUser` (at once), `signOut`, `disable` and
|
|
10
|
+
`enable`, which file a request that waits for an admin, and `request(id)` and
|
|
11
|
+
`requests({ status, userId, since, page })` to check on them.
|
|
12
|
+
- Its token is the service's own (client credentials), asked for per scope
|
|
13
|
+
(`management:users.read`, `management:users.manage`) for the API's resource, kept, and renewed
|
|
14
|
+
once when the API refuses it.
|
|
15
|
+
- A refusal is a `ManagementError` (`isManagementError`): an `IdpError` with the new code
|
|
16
|
+
`management_refused` and the API's code in `refusal`. No answer is `management_unavailable`.
|
|
17
|
+
- NestJS: `IdpModule.forRoot(settings, { management: true })` and `forRootAsync` provide one
|
|
18
|
+
under the new `MANAGEMENT` token.
|
|
19
|
+
|
|
20
|
+
## 0.4.0
|
|
21
|
+
|
|
22
|
+
- Access, ID and logout tokens signed with `Ed25519` are accepted: RFC 9864's fully specified
|
|
23
|
+
name for an Edwards-curve signature. The name it deprecates, `EdDSA`, still works for now and
|
|
24
|
+
will be dropped in a later release, as nextidp for Python already has.
|
|
25
|
+
|
|
3
26
|
## 0.3.0
|
|
4
27
|
|
|
5
28
|
### Pushed authorization requests
|
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
|
|
@@ -627,6 +631,70 @@ A refusal throws `IdpError` with the code `service_token_failed` and the auth se
|
|
|
627
631
|
status (`invalid_scope` for a scope the client may not have, `invalid_target` for an API it
|
|
628
632
|
isn't linked to).
|
|
629
633
|
|
|
634
|
+
## Managing accounts (Next-Identity Server)
|
|
635
|
+
|
|
636
|
+
`nextidp/management` is a service's side of Next-Identity Server's management API, for a product
|
|
637
|
+
whose operators manage accounts from its own screens. It's that server's own API, not OpenID
|
|
638
|
+
Connect, and it's on only with `MANAGEMENT_API=true` there. A lookup answers at once; a sign-out,
|
|
639
|
+
a disable or an enable **waits for an admin's approval**, so what comes back is a request to
|
|
640
|
+
check on, not something done.
|
|
641
|
+
|
|
642
|
+
The service needs a confidential client with the management API and its scopes
|
|
643
|
+
(`management:users.read` to look up, `management:users.manage` to ask and check), and runs on the
|
|
644
|
+
server: the client secret is in its settings.
|
|
645
|
+
|
|
646
|
+
```ts
|
|
647
|
+
import { isManagementError, management } from "nextidp/management";
|
|
648
|
+
|
|
649
|
+
const accounts = management(); // IDP_ISSUER, IDP_CLIENT_ID, IDP_CLIENT_SECRET
|
|
650
|
+
|
|
651
|
+
const user = await accounts.findUser({ email: "ada@example.com" }); // or { id }; undefined if none
|
|
652
|
+
const request = await accounts.disable(user.id, { until: "2027-01-31T00:00:00Z", reason: "Chargeback" });
|
|
653
|
+
// request.status === "pending": store request.id
|
|
654
|
+
|
|
655
|
+
const later = await accounts.request(request.id);
|
|
656
|
+
// later.status: "pending" (still waiting), "approved" (done), "denied" (later.note says why),
|
|
657
|
+
// "expired" (nobody decided within 7 days) or "failed" (approved, but something had changed:
|
|
658
|
+
// later.problem)
|
|
659
|
+
|
|
660
|
+
// Everything decided since the last check, for a job that syncs them:
|
|
661
|
+
const { requests, pageCount } = await accounts.requests({ since: lastCheck, page: 1 });
|
|
662
|
+
```
|
|
663
|
+
|
|
664
|
+
| Call | Scope | Answers |
|
|
665
|
+
|---|---|---|
|
|
666
|
+
| `findUser({ email })`, `findUser({ id })` | read | The account, or undefined |
|
|
667
|
+
| `signOut(userId)` | manage | A request: sign out everywhere |
|
|
668
|
+
| `disable(userId, { until?, reason? })` | manage | A request: disable, until a date within a year or until enabled |
|
|
669
|
+
| `enable(userId)` | manage | A request: enable again |
|
|
670
|
+
| `request(id)` | manage | The request as it stands now, or undefined |
|
|
671
|
+
| `requests({ status?, userId?, since?, page? })` | manage | `{ requests, page, pageCount, total }`, newest first, 50 a page |
|
|
672
|
+
|
|
673
|
+
A refusal throws a `ManagementError` (an `IdpError` with the code `management_refused`): check it
|
|
674
|
+
with `isManagementError`, and read `refusal` for the API's code: `admin_account` (only another
|
|
675
|
+
admin manages an admin), `not_disabled`, `disabled_by_admin` (an enable for an account an admin
|
|
676
|
+
disabled on the admin pages), `too_many_pending` (100 waiting), `insufficient_scope`,
|
|
677
|
+
`invalid_token`, `invalid_request`. No answer at all is `management_unavailable`. Tokens are
|
|
678
|
+
asked for per scope and kept; one the API refuses is renewed once. `url` overrides the API's
|
|
679
|
+
address (`<issuer>/api/auth/management` by default).
|
|
680
|
+
|
|
681
|
+
With NestJS, `IdpModule.forRoot(settings, { management: true })` (or `forRootAsync`) provides one
|
|
682
|
+
under the `MANAGEMENT` token, with the module's settings:
|
|
683
|
+
|
|
684
|
+
```ts
|
|
685
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
686
|
+
import { MANAGEMENT, type Management } from "nextidp/nestjs";
|
|
687
|
+
|
|
688
|
+
@Injectable()
|
|
689
|
+
export class AccountsService {
|
|
690
|
+
constructor(@Inject(MANAGEMENT) private readonly accounts: Management) {}
|
|
691
|
+
|
|
692
|
+
suspend(userId: string) {
|
|
693
|
+
return this.accounts.disable(userId, { reason: "Suspended by an operator" });
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
```
|
|
697
|
+
|
|
630
698
|
## Sessions in a store, and back-channel logout
|
|
631
699
|
|
|
632
700
|
By default a session lives in its encrypted cookie, which only the browser holds: the auth
|
package/dist/cjs/access-token.js
CHANGED
|
@@ -43,7 +43,7 @@ var import_jose = require("jose");
|
|
|
43
43
|
var v = __toESM(require("valibot"), 1);
|
|
44
44
|
var import_errors = require("./errors.js");
|
|
45
45
|
const ACCESS_TOKEN_TYPES = /* @__PURE__ */ new Set(["at+jwt", "application/at+jwt"]);
|
|
46
|
-
const ALGORITHMS = ["RS256", "PS256", "ES256", "EdDSA"];
|
|
46
|
+
const ALGORITHMS = ["RS256", "PS256", "ES256", "Ed25519", "EdDSA"];
|
|
47
47
|
const BEARER = /^Bearer +([A-Za-z0-9\-._~+/]+=*)\s*$/i;
|
|
48
48
|
const invalid = (message, cause) => new import_errors.IdpError("invalid_token", message, { status: 401, cause });
|
|
49
49
|
function bearerToken(authorization) {
|
package/dist/cjs/errors.d.ts
CHANGED
|
@@ -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 & {
|
package/dist/cjs/http.d.ts
CHANGED
|
@@ -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/id-token.js
CHANGED
|
@@ -26,7 +26,7 @@ module.exports = __toCommonJS(id_token_exports);
|
|
|
26
26
|
var import_jose = require("jose");
|
|
27
27
|
var import_errors = require("./errors.js");
|
|
28
28
|
var import_pkce = require("./pkce.js");
|
|
29
|
-
const ALLOWED_ALGORITHMS = ["RS256", "PS256", "ES256", "EdDSA"];
|
|
29
|
+
const ALLOWED_ALGORITHMS = ["RS256", "PS256", "ES256", "Ed25519", "EdDSA"];
|
|
30
30
|
function signingAlgorithms(listed) {
|
|
31
31
|
const algorithms = listed ? listed.filter((alg) => ALLOWED_ALGORITHMS.includes(alg)) : [];
|
|
32
32
|
return algorithms.length > 0 ? algorithms : ["RS256"];
|
|
@@ -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
|
+
});
|
package/dist/cjs/nestjs.d.ts
CHANGED
|
@@ -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";
|
package/dist/cjs/nestjs.js
CHANGED
|
@@ -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,
|
package/dist/esm/access-token.js
CHANGED
|
@@ -2,7 +2,7 @@ import { decodeProtectedHeader, jwtVerify } from "jose";
|
|
|
2
2
|
import * as v from "valibot";
|
|
3
3
|
import { IdpError } from "./errors.js";
|
|
4
4
|
const ACCESS_TOKEN_TYPES = /* @__PURE__ */ new Set(["at+jwt", "application/at+jwt"]);
|
|
5
|
-
const ALGORITHMS = ["RS256", "PS256", "ES256", "EdDSA"];
|
|
5
|
+
const ALGORITHMS = ["RS256", "PS256", "ES256", "Ed25519", "EdDSA"];
|
|
6
6
|
const BEARER = /^Bearer +([A-Za-z0-9\-._~+/]+=*)\s*$/i;
|
|
7
7
|
const invalid = (message, cause) => new IdpError("invalid_token", message, { status: 401, cause });
|
|
8
8
|
function bearerToken(authorization) {
|
package/dist/esm/errors.d.ts
CHANGED
|
@@ -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 & {
|
package/dist/esm/http.d.ts
CHANGED
|
@@ -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/id-token.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
2
2
|
import { IdpError } from "./errors.js";
|
|
3
3
|
import { sameString } from "./pkce.js";
|
|
4
|
-
const ALLOWED_ALGORITHMS = ["RS256", "PS256", "ES256", "EdDSA"];
|
|
4
|
+
const ALLOWED_ALGORITHMS = ["RS256", "PS256", "ES256", "Ed25519", "EdDSA"];
|
|
5
5
|
function signingAlgorithms(listed) {
|
|
6
6
|
const algorithms = listed ? listed.filter((alg) => ALLOWED_ALGORITHMS.includes(alg)) : [];
|
|
7
7
|
return algorithms.length > 0 ? algorithms : ["RS256"];
|
|
@@ -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
|
+
};
|
package/dist/esm/nestjs.d.ts
CHANGED
|
@@ -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";
|
package/dist/esm/nestjs.js
CHANGED
|
@@ -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.
|
|
3
|
+
"version": "0.5.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.
|
|
190
|
+
"next": "16.5.0",
|
|
178
191
|
"publint": "0.3.25",
|
|
179
192
|
"react": "19.3.1",
|
|
180
193
|
"react-dom": "19.3.1",
|