@pithy-sh/auth 0.12.2 → 0.14.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/README.md +1 -1
- package/dist/admin/users.d.ts +19 -1
- package/dist/admin/users.d.ts.map +1 -1
- package/dist/admin/users.js +18 -1
- package/dist/http/adminRoutes.d.ts.map +1 -1
- package/dist/http/adminRoutes.js +40 -22
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +12 -2
- package/dist/http/responses.d.ts +10 -10
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +12 -12
- package/dist/http/schemas.d.ts +45 -11
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +50 -13
- package/dist/mcp/http/schemas.d.ts.map +1 -1
- package/dist/mcp/http/schemas.js +2 -1
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/account-lifecycle.md +3 -3
- package/package.json +5 -5
- package/src/admin/users.ts +40 -2
- package/src/http/adminRoutes.ts +67 -40
- package/src/http/guards.ts +12 -2
- package/src/http/responses.ts +13 -13
- package/src/http/schemas.ts +98 -26
- package/src/mcp/http/schemas.ts +4 -5
- package/src/version.generated.ts +1 -1
package/dist/http/schemas.js
CHANGED
|
@@ -6,6 +6,7 @@ import "../lifecycle/reason.js";
|
|
|
6
6
|
import { z } from "zod";
|
|
7
7
|
import { JsonDate } from "@pithy-sh/core/src/data/codecs";
|
|
8
8
|
import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
|
|
9
|
+
import { freeText } from "@pithy-sh/core/src/http/freeText";
|
|
9
10
|
//#region src/http/schemas.ts
|
|
10
11
|
/**
|
|
11
12
|
* The request schemas for the auth routes Pithy owns. Validation happens at the HTTP boundary
|
|
@@ -65,12 +66,47 @@ const UserIdParam = z.object({ userId: z.string().min(1).max(255).describe("The
|
|
|
65
66
|
const PageLimit = z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).optional().describe("How many rows to return. Bounded, because a verified client can still have a bug.");
|
|
66
67
|
/** Where a paged admin listing resumes. */
|
|
67
68
|
const PageCursorParam = z.string().max(512).optional().describe("Where to resume, from the previous page's `nextCursor`. Opaque; a malformed one is a first page.");
|
|
68
|
-
/**
|
|
69
|
+
/** A signup-window bound, as ISO-8601, decoded to a `Date` by the schema so the handler takes a typed value. */
|
|
70
|
+
const SignupBound = z.iso.datetime({ offset: true }).transform((value) => new Date(value));
|
|
71
|
+
/** The narrowing a listing and a search share, beside `verified`, which a query and a body spell differently. */
|
|
72
|
+
const userFilterFields = {
|
|
73
|
+
state: z.enum([
|
|
74
|
+
"active",
|
|
75
|
+
"suspended",
|
|
76
|
+
"deleted"
|
|
77
|
+
]).describe("Narrow to where the account stands now: `active`, `suspended` or `deleted`. A suspension whose end has passed reads `active`, as enforcement reads it.").optional().describe("Narrow to where the account stands now: `active`, `suspended` or `deleted`. A suspension whose end has passed reads `active`, as enforcement reads it."),
|
|
78
|
+
since: SignupBound.optional().describe("Created at or after this instant, ISO-8601. Inclusive."),
|
|
79
|
+
until: SignupBound.optional().describe("Created before this instant, ISO-8601. Exclusive."),
|
|
80
|
+
cursor: PageCursorParam
|
|
81
|
+
};
|
|
82
|
+
/** A signup window that ends before it starts holds nothing. */
|
|
83
|
+
const SIGNUP_WINDOW_ORDER = { message: "`since` must be before `until`. A window that ends before it starts holds nothing." };
|
|
84
|
+
/** Whether a signup window is in order: either bound may be absent. */
|
|
85
|
+
function windowInOrder(query) {
|
|
86
|
+
return query.since === void 0 || query.until === void 0 || query.since < query.until;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The user listing query. Strict, and there is no `search`: a search term is usually somebody's address, and
|
|
90
|
+
* a query string is written to every request log, so a search is {@link SearchUsersBody}, in a body. A
|
|
91
|
+
* client still sending `?search=` is refused as `validation/invalid_input` rather than handed every user as
|
|
92
|
+
* though they were the match.
|
|
93
|
+
*/
|
|
69
94
|
const ListUsersQuery = z.object({
|
|
70
|
-
|
|
71
|
-
|
|
95
|
+
...userFilterFields,
|
|
96
|
+
verified: z.enum(["true", "false"]).describe("`true` or `false`.").transform((value) => value === "true").optional().describe("`true` for the users whose address is verified, `false` for those whose is not. Both when absent."),
|
|
72
97
|
limit: PageLimit
|
|
73
|
-
}).describe("The user listing query:
|
|
98
|
+
}).strict().refine(windowInOrder, SIGNUP_WINDOW_ORDER).describe("The user listing query: which standing, verification and signup window to narrow to, how many to return, and where to resume. To search by address or name, POST to `/admin/users/search`.");
|
|
99
|
+
/**
|
|
100
|
+
* The body of `POST {base}/admin/users/search`: the term, the listing's filters, and the cursor, all in a body
|
|
101
|
+
* so the term never reaches a request log. Pages exactly as the listing does.
|
|
102
|
+
*/
|
|
103
|
+
const SearchUsersBody = z.object({
|
|
104
|
+
search: freeText(z.string().trim().min(1).max(200)).describe("Free text matched against email and display name. `%` and `_` are escaped rather than treated as wildcards, so an address containing an underscore matches itself and nothing else."),
|
|
105
|
+
...userFilterFields,
|
|
106
|
+
cursor: z.string().max(512).nullish().transform((value) => value ?? void 0).describe("Where to resume, from the previous page's `nextCursor`, passed back as it came: `null` or absent is a first page. Opaque; a malformed one is a first page."),
|
|
107
|
+
verified: z.boolean().optional().describe("`true` for the users whose address is verified, `false` for those whose is not. Both when absent."),
|
|
108
|
+
limit: z.number().int().min(1).max(MAX_PAGE_SIZE).optional().describe("How many rows to return. Bounded, because a verified client can still have a bug.")
|
|
109
|
+
}).strict().refine(windowInOrder, SIGNUP_WINDOW_ORDER).describe("A user search: the term, which standing, verification and signup window to narrow to, how many to return, and where to resume.");
|
|
74
110
|
/** The device-registry listing query. */
|
|
75
111
|
const ListDevicesQuery = z.object({
|
|
76
112
|
userId: z.string().min(1).max(255).optional().describe("Narrow to one user's devices. Absent walks the whole fleet, most-recently-seen first."),
|
|
@@ -81,7 +117,7 @@ const ListDevicesQuery = z.object({
|
|
|
81
117
|
/** A window bound on the verification read: ISO-8601 with an offset, decoded to a `Date` here so no handler parses it. */
|
|
82
118
|
const WindowBound = z.iso.datetime({ offset: true }).transform((value) => new Date(value));
|
|
83
119
|
/**
|
|
84
|
-
* The verification ledger read's query
|
|
120
|
+
* The verification ledger read's query: a window of issue times, what to narrow it to, and where to resume.
|
|
85
121
|
* Both bounds are optional — the last 30 days, ending now — and a window that ends before it starts is refused by
|
|
86
122
|
* the handler, which is where the default is known.
|
|
87
123
|
*/
|
|
@@ -103,13 +139,13 @@ const ListVerificationsQuery = z.object({
|
|
|
103
139
|
*/
|
|
104
140
|
const RevokeSessionBody = z.object({ sessionId: z.string().min(1).max(255).describe("The session's id, as the admin read routes report it. Not the session token.") }).describe("The body identifying which single session to revoke.");
|
|
105
141
|
/**
|
|
106
|
-
* Why an account's access is changing — required on both lifecycle routes
|
|
142
|
+
* Why an account's access is changing — required on both lifecycle routes.
|
|
107
143
|
*
|
|
108
144
|
* Trimmed, then bounded by the same constant the transition enforces, so a reason the transition would refuse
|
|
109
145
|
* is a 400 here rather than a conflict later. Required rather than defaulted: a suspension nobody explained is
|
|
110
146
|
* a lockout the person cannot answer, and the trail would record nothing about why.
|
|
111
147
|
*/
|
|
112
|
-
const LifecycleReason = z.string().trim().min(1).max(500).describe("Why, in a sentence written for the person. A suspension's reason is what every refused sign-in shows them.");
|
|
148
|
+
const LifecycleReason = freeText(z.string().trim().min(1).max(500)).describe("Why, in a sentence written for the person. A suspension's reason is what every refused sign-in shows them.");
|
|
113
149
|
/** Whether the person is mailed. */
|
|
114
150
|
const Notify = z.boolean().optional().describe("Whether to mail the person. Absent is true. The config can turn a lifecycle mail off for every call; this turns it off for one.");
|
|
115
151
|
/** The body of `POST /admin/users/:userId/suspend`. */
|
|
@@ -124,7 +160,7 @@ const ReinstateUserBody = z.object({
|
|
|
124
160
|
notify: Notify
|
|
125
161
|
}).describe("A reinstatement: why, and whether to tell the person. It restores no session.");
|
|
126
162
|
/**
|
|
127
|
-
* How a deletion runs
|
|
163
|
+
* How a deletion runs. `soft` is the default and the only thing an omission reaches: the account is shut
|
|
128
164
|
* now and erased once the window closes, restorable until then. `hard` starts the purge at once, with no
|
|
129
165
|
* window, and is reached only by naming it — a typo is a 400, never either mode.
|
|
130
166
|
*/
|
|
@@ -138,12 +174,13 @@ const DeleteUserBody = z.object({
|
|
|
138
174
|
/** The body of `POST /admin/users/:userId/restore`. */
|
|
139
175
|
const RestoreUserBody = z.object({ reason: LifecycleReason }).describe("A restoration inside the purge window: why. It restores no session; the person signs in again.");
|
|
140
176
|
/**
|
|
141
|
-
* The
|
|
142
|
-
* says why, like every lifecycle call: the reason goes on the trail beside who asked
|
|
177
|
+
* The body of `POST /admin/users/:userId/export`. A disclosure of everything the kit holds about one person
|
|
178
|
+
* says why, like every lifecycle call: the reason goes on the trail beside who asked, and in a body, never a
|
|
179
|
+
* URL, because a reason names the request it answers and often the person who made it.
|
|
143
180
|
*/
|
|
144
|
-
const
|
|
181
|
+
const ExportUserBody = z.object({ reason: LifecycleReason.describe("Why this person's data is being exported — the access request it answers. Recorded on the audit trail.") }).strict().describe("An export: why it is being made.");
|
|
145
182
|
/**
|
|
146
|
-
* The body of `DELETE /account`, the signed-in person deleting their own account
|
|
183
|
+
* The body of `DELETE /account`, the signed-in person deleting their own account.
|
|
147
184
|
*
|
|
148
185
|
* The confirmation is the literal `true`, so a client must say it on purpose: a stray `DELETE` with an empty
|
|
149
186
|
* body, or a form posting `"false"`, deletes nothing. There is no field naming an account — the subject is the
|
|
@@ -151,4 +188,4 @@ const ExportUserQuery = z.object({ reason: LifecycleReason.describe("Why this pe
|
|
|
151
188
|
*/
|
|
152
189
|
const DeleteAccountBody = z.object({ confirm: z.literal(true).describe("Must be `true`. The person confirmed, in your app, that they want their account deleted.") }).describe("A self-service deletion: the person's own confirmation. Always soft, on the configured window.");
|
|
153
190
|
//#endregion
|
|
154
|
-
export { DeleteAccountBody, DeleteUserBody, DeletionMode,
|
|
191
|
+
export { DeleteAccountBody, DeleteUserBody, DeletionMode, ExportUserBody, HandoffExchangeBody, ListDevicesQuery, ListUsersQuery, ListVerificationsQuery, RedirectProvider, ReinstateUserBody, RestoreUserBody, RevokeDeviceBody, RevokeSessionBody, SearchUsersBody, SocialSignInStartQuery, SuspendUserBody, UserIdParam };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../../src/mcp/http/schemas.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../../src/mcp/http/schemas.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,qDAAqD;AACrD,eAAO,MAAM,cAAc;;;;;iBAAa,CAAC;AAEzC,qGAAqG;AACrG,eAAO,MAAM,YAAY;;iBAM8C,CAAC;AAExE,wDAAwD;AACxD,eAAO,MAAM,WAAW;;;kBAUqE,CAAC;AAE9F,mCAAmC;AACnC,eAAO,MAAM,eAAe;;iBAEa,CAAC"}
|
package/dist/mcp/http/schemas.js
CHANGED
|
@@ -2,11 +2,12 @@
|
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
import { RpcMessage } from "../rpc.js";
|
|
4
4
|
import { z } from "zod";
|
|
5
|
+
import { notFreeText } from "@pithy-sh/core/src/http/freeText";
|
|
5
6
|
//#region src/mcp/http/schemas.ts
|
|
6
7
|
/** The MCP endpoint's body: one JSON-RPC message. */
|
|
7
8
|
const McpRequestBody = RpcMessage;
|
|
8
9
|
/** The consent screen's question: the signed authorization query the provider redirected it with. */
|
|
9
|
-
const ConsentQuery = z.object({ oauth_query: z.string().min(1).max(8192).describe("The query string the authorization server redirected the screen with, signed by it.") }).describe("Which authorization request the consent screen is about.");
|
|
10
|
+
const ConsentQuery = z.object({ oauth_query: notFreeText(z.string().min(1).max(8192)).describe("The query string the authorization server redirected the screen with, signed by it. Machine-made: no person types it.") }).describe("Which authorization request the consent screen is about.");
|
|
10
11
|
/** The consent decision: one, for the whole request. */
|
|
11
12
|
const ConsentBody = z.object({
|
|
12
13
|
oauth_query: z.string().min(1).max(8192).describe("The query string the authorization server redirected the screen with, signed by it."),
|
|
@@ -3,5 +3,5 @@
|
|
|
3
3
|
/** This package's npm name — the join key against a release feed. */
|
|
4
4
|
export declare const PACKAGE_NAME = "@pithy-sh/auth";
|
|
5
5
|
/** This package's version, stamped from its own package.json at generation time. */
|
|
6
|
-
export declare const PACKAGE_VERSION = "0.
|
|
6
|
+
export declare const PACKAGE_VERSION = "0.14.0";
|
|
7
7
|
//# sourceMappingURL=version.generated.d.ts.map
|
|
@@ -4,6 +4,6 @@
|
|
|
4
4
|
/** This package's npm name — the join key against a release feed. */
|
|
5
5
|
const PACKAGE_NAME = "@pithy-sh/auth";
|
|
6
6
|
/** This package's version, stamped from its own package.json at generation time. */
|
|
7
|
-
const PACKAGE_VERSION = "0.
|
|
7
|
+
const PACKAGE_VERSION = "0.14.0";
|
|
8
8
|
//#endregion
|
|
9
9
|
export { PACKAGE_NAME, PACKAGE_VERSION };
|
|
@@ -13,7 +13,7 @@ Both live on `pithy_auth_users`, so a session read already carries them. An acco
|
|
|
13
13
|
|
|
14
14
|
No client can write its own state. The four columns are `input: false`, and only the kit's transitions set them.
|
|
15
15
|
|
|
16
|
-
**The admin reads say where each account stands.** `GET /auth/admin/users` and `GET /auth/admin/users/:userId` return each user with `state` — `active`, `suspended` or `deleted` — `suspendedUntil`, the end of a suspension in force or null for one with none and in every other state, and `purgeAfter`, the last day a deleted account can be restored or null otherwise. They are read the way enforcement reads them, so a suspension past its end is `active`. The listing does not leave a suspended or deleted account out, and these are what let a pane offer suspend or reinstate without sending a write to find out. Neither the reason nor who acted is there: the reason is on the trail, and the trail is audit's. Each field is optional in `AdminUserView`, so a client reading a Worker older than them still parses its answer.
|
|
16
|
+
**The admin reads say where each account stands.** `GET /auth/admin/users` and `GET /auth/admin/users/:userId` return each user with `state` — `active`, `suspended` or `deleted` — `suspendedUntil`, the end of a suspension in force or null for one with none and in every other state, and `purgeAfter`, the last day a deleted account can be restored or null otherwise. They are read the way enforcement reads them, so a suspension past its end is `active`. The listing does not leave a suspended or deleted account out, and these are what let a pane offer suspend or reinstate without sending a write to find out. Neither the reason nor who acted is there: the reason is on the trail, and the trail is audit's. Each field is optional in `AdminUserView`, so a client reading a Worker older than them still parses its answer. The listing narrows on it too: `GET /auth/admin/users?state=suspended` pages the suspended accounts on the server, judged as enforcement judges them, so a suspension past its end is `active`.
|
|
17
17
|
|
|
18
18
|
## Enforcement
|
|
19
19
|
|
|
@@ -82,10 +82,10 @@ Three routes. Deleting and restoring are gated by `auth:users:delete`, exporting
|
|
|
82
82
|
```
|
|
83
83
|
DELETE /auth/admin/users/:userId { mode?, reason, notify? }
|
|
84
84
|
POST /auth/admin/users/:userId/restore { reason }
|
|
85
|
-
|
|
85
|
+
POST /auth/admin/users/:userId/export { reason }
|
|
86
86
|
```
|
|
87
87
|
|
|
88
|
-
`reason` is required on all three, on the same terms as a suspension's. A request without one is `validation/invalid_input`.
|
|
88
|
+
`reason` is required on all three, on the same terms as a suspension's, and travels in the body on all three: a reason often names the request it answers, and a URL is written to every request log. A request without one is `validation/invalid_input`.
|
|
89
89
|
|
|
90
90
|
**Two modes, and soft is the default.** `mode: "soft"`, or no mode at all, stamps `deleted_at` and `purge_after` — now plus the purge window — and revokes every session the account holds. Signing in again answers `auth/account_deleted`. The deletion-scheduled mail goes out with the purge date and, when you configure one, the restore path. `onUserDeleted` fires. The account can be restored until `purge_after`. `mode: "hard"` closes the window now: `purge_after` is the moment of the deletion, nothing can restore it, and the purge starts in the same call. You name it on purpose. A typo — `"Hard"`, `"hrad"` — is a 400, never either mode. A hard deletion of an account already deleted softly brings its purge forward to now.
|
|
91
91
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pithy-sh/auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -46,10 +46,10 @@
|
|
|
46
46
|
"better-auth": "^1.7.11"
|
|
47
47
|
},
|
|
48
48
|
"peerDependencies": {
|
|
49
|
-
"@pithy-sh/core": "^0.
|
|
50
|
-
"@pithy-sh/email": "^0.
|
|
51
|
-
"@pithy-sh/secrets": "^0.6.
|
|
52
|
-
"@pithy-sh/turnstile": "^0.8.
|
|
49
|
+
"@pithy-sh/core": "^0.18.0",
|
|
50
|
+
"@pithy-sh/email": "^0.10.0",
|
|
51
|
+
"@pithy-sh/secrets": "^0.6.6",
|
|
52
|
+
"@pithy-sh/turnstile": "^0.8.2",
|
|
53
53
|
"hono": "^4.13.2",
|
|
54
54
|
"kysely": "^0.29.0",
|
|
55
55
|
"zod": "^4.4.0"
|
package/src/admin/users.ts
CHANGED
|
@@ -2,12 +2,15 @@
|
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
4
|
import { boundParameterBudget, MAX_BOUND_PARAMETERS } from "@pithy-sh/core/src/data/boundParameters";
|
|
5
|
+
import { SQLiteBoolean, SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
5
6
|
import { decodeCursor, pageLimit, toPage } from "@pithy-sh/core/src/data/cursor";
|
|
7
|
+
import type { DatabaseSchema } from "@pithy-sh/core/src/data/db";
|
|
6
8
|
import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
7
|
-
import { type SqlBool, sql } from "kysely";
|
|
9
|
+
import { type Expression, type ExpressionBuilder, type SqlBool, sql } from "kysely";
|
|
8
10
|
import { Session, User } from "../data/betterAuth";
|
|
9
11
|
import { Device, type DevicePlatform } from "../data/device";
|
|
10
|
-
import type { AuthDatabase } from "../data/tables";
|
|
12
|
+
import type { AuthDatabase, AuthTables } from "../data/tables";
|
|
13
|
+
import type { AccountStanding } from "../lifecycle/state";
|
|
11
14
|
|
|
12
15
|
/**
|
|
13
16
|
* The reads a management dashboard's user panes resolve to, and the lookups its revocations need.
|
|
@@ -89,12 +92,41 @@ function likePattern(term: string): string {
|
|
|
89
92
|
export interface ListUsersOptions {
|
|
90
93
|
/** Free text matched against email and display name. Absent lists everyone, newest first. */
|
|
91
94
|
search?: string;
|
|
95
|
+
/** Where the account stands, judged at `now` exactly as `accountStanding` judges it. */
|
|
96
|
+
state?: AccountStanding["state"];
|
|
97
|
+
/** Whether the address is verified. */
|
|
98
|
+
verified?: boolean;
|
|
99
|
+
/** Created at or after this instant. Inclusive. */
|
|
100
|
+
since?: Date;
|
|
101
|
+
/** Created before this instant. Exclusive. */
|
|
102
|
+
until?: Date;
|
|
103
|
+
/** The instant `state` is judged at. Defaults to the moment of the read. */
|
|
104
|
+
now?: Date;
|
|
92
105
|
/** The previous page's `nextCursor`. A malformed one is a first page, never an error. */
|
|
93
106
|
cursor?: string;
|
|
94
107
|
/** How many rows to return, clamped into `[1, MAX_PAGE_SIZE]` by `pageLimit`. */
|
|
95
108
|
limit?: number;
|
|
96
109
|
}
|
|
97
110
|
|
|
111
|
+
/**
|
|
112
|
+
* The rows `accountStanding` reads as `state` at `now`, as one predicate: deleted outranks suspended, and a
|
|
113
|
+
* suspension ends at the instant its `suspendedUntil` names.
|
|
114
|
+
*/
|
|
115
|
+
export function standingPredicate(
|
|
116
|
+
state: AccountStanding["state"],
|
|
117
|
+
now: Date,
|
|
118
|
+
): (eb: ExpressionBuilder<DatabaseSchema<AuthTables>, "pithyAuthUsers">) => Expression<SqlBool> {
|
|
119
|
+
const at = SQLiteDate.encode(now);
|
|
120
|
+
return (eb) => {
|
|
121
|
+
if (state === "deleted") return eb("deletedAt", "is not", null);
|
|
122
|
+
const inForce = eb.and([
|
|
123
|
+
eb("suspendedAt", "is not", null),
|
|
124
|
+
eb.or([eb("suspendedUntil", "is", null), eb("suspendedUntil", ">", at)]),
|
|
125
|
+
]);
|
|
126
|
+
return eb.and([eb("deletedAt", "is", null), state === "suspended" ? inForce : eb.not(inForce)]);
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
98
130
|
/**
|
|
99
131
|
* Users, newest first, optionally filtered by a free-text term over email and display name.
|
|
100
132
|
*
|
|
@@ -123,6 +155,12 @@ export async function listUsers(db: AuthDatabase, options: ListUsersOptions = {}
|
|
|
123
155
|
query = query.where(sql<SqlBool>`(email like ${pattern} escape '\\' or name like ${pattern} escape '\\')`);
|
|
124
156
|
}
|
|
125
157
|
|
|
158
|
+
if (options.state !== undefined) query = query.where(standingPredicate(options.state, options.now ?? new Date()));
|
|
159
|
+
if (options.verified !== undefined) query = query.where("emailVerified", "=", SQLiteBoolean.encode(options.verified));
|
|
160
|
+
// ISO-8601 text on both sides, as the cursor below compares it.
|
|
161
|
+
if (options.since !== undefined) query = query.where("createdAt", ">=", options.since.toISOString());
|
|
162
|
+
if (options.until !== undefined) query = query.where("createdAt", "<", options.until.toISOString());
|
|
163
|
+
|
|
126
164
|
const cursor = decodeCursor(options.cursor);
|
|
127
165
|
if (cursor) {
|
|
128
166
|
// ISO-8601 text, because that is what the Better-Auth adapter wrote. Descending lexicographic order
|
package/src/http/adminRoutes.ts
CHANGED
|
@@ -71,7 +71,7 @@ import {
|
|
|
71
71
|
} from "./responses";
|
|
72
72
|
import {
|
|
73
73
|
DeleteUserBody,
|
|
74
|
-
|
|
74
|
+
ExportUserBody,
|
|
75
75
|
ListDevicesQuery,
|
|
76
76
|
ListUsersQuery,
|
|
77
77
|
ListVerificationsQuery,
|
|
@@ -79,6 +79,7 @@ import {
|
|
|
79
79
|
RestoreUserBody,
|
|
80
80
|
RevokeDeviceBody,
|
|
81
81
|
RevokeSessionBody,
|
|
82
|
+
SearchUsersBody,
|
|
82
83
|
SuspendUserBody,
|
|
83
84
|
UserIdParam,
|
|
84
85
|
} from "./schemas";
|
|
@@ -102,6 +103,7 @@ type Ctx = Context<PithyHonoEnv>;
|
|
|
102
103
|
* revocations an incident costs.
|
|
103
104
|
*
|
|
104
105
|
* GET {base}/admin/users auth:users:read query: ListUsersQuery
|
|
106
|
+
* POST {base}/admin/users/search auth:users:read json: SearchUsersBody
|
|
105
107
|
* GET {base}/admin/users/:userId auth:users:read param: UserIdParam
|
|
106
108
|
* GET {base}/admin/devices auth:devices:read query: ListDevicesQuery
|
|
107
109
|
* GET {base}/admin/verifications auth:verifications:read query: ListVerificationsQuery
|
|
@@ -112,7 +114,7 @@ type Ctx = Context<PithyHonoEnv>;
|
|
|
112
114
|
* POST {base}/admin/users/:userId/reinstate auth:users:suspend param + json: ReinstateUserBody
|
|
113
115
|
* DELETE {base}/admin/users/:userId auth:users:delete param + json: DeleteUserBody
|
|
114
116
|
* POST {base}/admin/users/:userId/restore auth:users:delete param + json: RestoreUserBody
|
|
115
|
-
*
|
|
117
|
+
* POST {base}/admin/users/:userId/export auth:users:export param + json: ExportUserBody
|
|
116
118
|
*
|
|
117
119
|
* ## Registered before the catch-all, or dead
|
|
118
120
|
*
|
|
@@ -155,11 +157,11 @@ function db(c: Ctx, wiring: AuthWiring) {
|
|
|
155
157
|
}
|
|
156
158
|
|
|
157
159
|
/**
|
|
158
|
-
* One of the user pane's sub-reads, guarded and projected in one step
|
|
160
|
+
* One of the user pane's sub-reads, guarded and projected in one step.
|
|
159
161
|
*
|
|
160
162
|
* **`try`/`catch` inside an `async` function, never `.catch()`.** The read is *called* inside the `try`,
|
|
161
163
|
* so a seam that throws before it returns a promise is caught too — a rejected promise is not the only
|
|
162
|
-
* way a D1 read fails, and a `.catch()` guard
|
|
164
|
+
* way a D1 read fails, and a `.catch()` guard is escaped by exactly that.
|
|
163
165
|
*
|
|
164
166
|
* **The guard takes no binding.** The state is the whole of what travels; what the read threw names a
|
|
165
167
|
* query and a table, and this response goes to a management client across a trust boundary.
|
|
@@ -246,7 +248,7 @@ function lifecycleCall(c: Ctx, wiring: AuthWiring, caller: ControlPlaneContext,
|
|
|
246
248
|
}
|
|
247
249
|
|
|
248
250
|
/**
|
|
249
|
-
* A lifecycle route's body validator, which audits the bodies it refuses
|
|
251
|
+
* A lifecycle route's body validator, which audits the bodies it refuses. Every call is on the trail,
|
|
250
252
|
* a refusal included, and a body the validator turns away never reaches `auditedLifecycleCall`. So it is
|
|
251
253
|
* recorded here, as `denied` under the route's own action, with whatever reason the body carried — cut to the
|
|
252
254
|
* reason's own limit, so a refused essay is not stored whole — and the 400 is thrown as before.
|
|
@@ -301,7 +303,7 @@ async function endSessions(
|
|
|
301
303
|
}
|
|
302
304
|
|
|
303
305
|
/**
|
|
304
|
-
* Start the purge of one account now
|
|
306
|
+
* Start the purge of one account now: `started` when this Worker binds the purge Workflow and it took the
|
|
305
307
|
* instance — or already held it — and `pending` when it binds none or the start failed; the account is due
|
|
306
308
|
* either way, and the daily pass starts it. A failed start is not this call's failure: the deletion is already
|
|
307
309
|
* written, and a 500 over it would invite a retry that finds the account deleted and says nothing new.
|
|
@@ -351,40 +353,66 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
|
|
|
351
353
|
return (app) => {
|
|
352
354
|
const base = wiring.config.basePath;
|
|
353
355
|
|
|
356
|
+
/** One page of users, audited as a listing: whether it was a search and how much came back, never the term. */
|
|
357
|
+
const pageOfUsers = async (c: Ctx, query: ListUsersQuery | SearchUsersBody) => {
|
|
358
|
+
const caller = controlPlaneCaller(c);
|
|
359
|
+
// One instant for the page, so the filter and every user on it are judged at the same moment.
|
|
360
|
+
const now = new Date();
|
|
361
|
+
const page = await listUsers(db(c, wiring), { ...query, now });
|
|
362
|
+
await emitControlPlaneAction(c.var.emit, {
|
|
363
|
+
action: AuthAuditActions.adminUsersListed,
|
|
364
|
+
subject: caller.subject,
|
|
365
|
+
connectionId: caller.connectionId,
|
|
366
|
+
resourceType: "user",
|
|
367
|
+
...context(c),
|
|
368
|
+
// `searched`, not the term. A search term is usually somebody's email address, and the audit trail
|
|
369
|
+
// is queryable and kept far longer than the pane that displayed it, so the term would copy the
|
|
370
|
+
// personal data the caller already saw into a second store. That it was a search, and how much came
|
|
371
|
+
// back, is what makes an exfiltration pattern visible.
|
|
372
|
+
metadata: {
|
|
373
|
+
searched: "search" in query,
|
|
374
|
+
returned: page.items.length,
|
|
375
|
+
filters: {
|
|
376
|
+
state: query.state ?? null,
|
|
377
|
+
verified: query.verified ?? null,
|
|
378
|
+
since: query.since?.toISOString() ?? null,
|
|
379
|
+
until: query.until?.toISOString() ?? null,
|
|
380
|
+
},
|
|
381
|
+
},
|
|
382
|
+
});
|
|
383
|
+
return c.json({
|
|
384
|
+
users: page.items.map((user) => userView(user, now)),
|
|
385
|
+
nextCursor: page.nextCursor,
|
|
386
|
+
} satisfies AdminUsersResponse);
|
|
387
|
+
};
|
|
388
|
+
|
|
354
389
|
app.get(
|
|
355
390
|
`${base}/admin/users`,
|
|
356
391
|
describeRoute({
|
|
357
|
-
summary:
|
|
392
|
+
summary:
|
|
393
|
+
"Page through the users, newest first, narrowing by standing, verification or signup window. A search by address or name is `POST /admin/users/search`.",
|
|
358
394
|
verification: "control-plane",
|
|
359
395
|
scopes: [AUTH_USERS_READ_SCOPE],
|
|
360
396
|
responses: { 200: AdminUsersResponse },
|
|
361
397
|
}),
|
|
362
398
|
requireControlPlane(AUTH_USERS_READ_SCOPE),
|
|
363
399
|
validate("query", ListUsersQuery),
|
|
364
|
-
async (c) =>
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
});
|
|
381
|
-
// One instant for the page, so every user on it is judged at the same moment.
|
|
382
|
-
const now = new Date();
|
|
383
|
-
return c.json({
|
|
384
|
-
users: page.items.map((user) => userView(user, now)),
|
|
385
|
-
nextCursor: page.nextCursor,
|
|
386
|
-
} satisfies AdminUsersResponse);
|
|
387
|
-
},
|
|
400
|
+
async (c) => pageOfUsers(c, c.req.valid("query")),
|
|
401
|
+
);
|
|
402
|
+
|
|
403
|
+
app.post(
|
|
404
|
+
`${base}/admin/users/search`,
|
|
405
|
+
describeRoute({
|
|
406
|
+
summary: "Search the users by email or name, newest first, with the listing's filters, paged on its cursor.",
|
|
407
|
+
description:
|
|
408
|
+
"The term travels in the body, because a query string is written to every request log between the client and the Worker and a search term is usually somebody's address. Answers the listing's envelope. Audited as a listing that searched, never with the term. Read-only.",
|
|
409
|
+
verification: "control-plane",
|
|
410
|
+
scopes: [AUTH_USERS_READ_SCOPE],
|
|
411
|
+
responses: { 200: AdminUsersResponse },
|
|
412
|
+
}),
|
|
413
|
+
requireControlPlane(AUTH_USERS_READ_SCOPE),
|
|
414
|
+
validate("json", SearchUsersBody),
|
|
415
|
+
async (c) => pageOfUsers(c, c.req.valid("json")),
|
|
388
416
|
);
|
|
389
417
|
|
|
390
418
|
app.get(
|
|
@@ -409,10 +437,9 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
|
|
|
409
437
|
// Bounded, because a device id is client-generated: a user can mint as many device rows as they
|
|
410
438
|
// like, so an unbounded sub-list would let any end user decide how much work this pane does.
|
|
411
439
|
//
|
|
412
|
-
// Each read is guarded on its own
|
|
413
|
-
//
|
|
414
|
-
//
|
|
415
|
-
// when an account is already in trouble. Still concurrent: the guard is inside each arm.
|
|
440
|
+
// Each read is guarded on its own: they are three independent tables, and one that will not read
|
|
441
|
+
// must not take the user and the other two lists with it, on the pane a support agent opens when an
|
|
442
|
+
// account is already in trouble. Still concurrent: the guard is inside each arm.
|
|
416
443
|
const [sessions, devices, providers] = await Promise.all([
|
|
417
444
|
readBounded(() => listUserSessions(database, userId, MAX_PAGE_SIZE), sessionView),
|
|
418
445
|
readBounded(() => listUserDevices(database, userId, MAX_PAGE_SIZE), deviceView),
|
|
@@ -805,22 +832,22 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
|
|
|
805
832
|
},
|
|
806
833
|
);
|
|
807
834
|
|
|
808
|
-
app.
|
|
835
|
+
app.post(
|
|
809
836
|
`${base}/admin/users/:userId/export`,
|
|
810
837
|
describeRoute({
|
|
811
838
|
summary: "Export everything the kit holds about one user, from every composed capability, as one document.",
|
|
812
839
|
description:
|
|
813
|
-
"The answer to an access request. One entry per composed capability that declares a purge contribution, in the order the purge erases them. Audited as a disclosure, with the reason.",
|
|
840
|
+
"The answer to an access request. One entry per composed capability that declares a purge contribution, in the order the purge erases them. Audited as a disclosure, with the reason, which travels in the body because a reason often names the person who asked and a URL is written to every request log. Changes nothing.",
|
|
814
841
|
verification: "control-plane",
|
|
815
842
|
scopes: [AUTH_USERS_EXPORT_SCOPE],
|
|
816
843
|
responses: { 200: AdminUserExportResponse },
|
|
817
844
|
}),
|
|
818
845
|
requireControlPlane(AUTH_USERS_EXPORT_SCOPE),
|
|
819
846
|
validate("param", UserIdParam),
|
|
820
|
-
validate("
|
|
847
|
+
validate("json", ExportUserBody),
|
|
821
848
|
async (c) => {
|
|
822
849
|
const { userId } = c.req.valid("param");
|
|
823
|
-
const { reason } = c.req.valid("
|
|
850
|
+
const { reason } = c.req.valid("json");
|
|
824
851
|
const caller = controlPlaneCaller(c);
|
|
825
852
|
const call = lifecycleCall(c, wiring, caller, userId, reason);
|
|
826
853
|
const exportedAt = new Date();
|
|
@@ -836,7 +863,7 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
|
|
|
836
863
|
return purgeExports(wiring.purgeSteps ?? [], {
|
|
837
864
|
subject: { type: "user", id: userId },
|
|
838
865
|
env: c.env as Record<string, unknown>,
|
|
839
|
-
// A capability holding rows by address — a suppression, a tester's membership — reads it here
|
|
866
|
+
// A capability holding rows by address — a suppression, a tester's membership — reads it here.
|
|
840
867
|
address: () => purgeAddress(database, userId),
|
|
841
868
|
});
|
|
842
869
|
},
|
package/src/http/guards.ts
CHANGED
|
@@ -159,7 +159,16 @@ export function authAdminRoutes(basePath: string): AdminRouteDeclaration[] {
|
|
|
159
159
|
path: `${basePath}/admin/users`,
|
|
160
160
|
scope: AUTH_USERS_READ_SCOPE,
|
|
161
161
|
kind: "reads",
|
|
162
|
-
summary: "
|
|
162
|
+
summary: "List the users newest first, narrowed by standing, verification or signup window.",
|
|
163
|
+
},
|
|
164
|
+
{
|
|
165
|
+
method: "POST",
|
|
166
|
+
operation: "users.search",
|
|
167
|
+
path: `${basePath}/admin/users/search`,
|
|
168
|
+
scope: AUTH_USERS_READ_SCOPE,
|
|
169
|
+
kind: "reads",
|
|
170
|
+
readInBody: true,
|
|
171
|
+
summary: "Find a user by email or display name, the term in the body so it never reaches a request log.",
|
|
163
172
|
},
|
|
164
173
|
{
|
|
165
174
|
method: "GET",
|
|
@@ -244,11 +253,12 @@ export function authAdminRoutes(basePath: string): AdminRouteDeclaration[] {
|
|
|
244
253
|
"Every sign-in link and code sent over a window: used, expired or still waiting, and the mail that carried it.",
|
|
245
254
|
},
|
|
246
255
|
{
|
|
247
|
-
method: "
|
|
256
|
+
method: "POST",
|
|
248
257
|
operation: "users.export",
|
|
249
258
|
path: `${basePath}/admin/users/:userId/export`,
|
|
250
259
|
scope: AUTH_USERS_EXPORT_SCOPE,
|
|
251
260
|
kind: "reads",
|
|
261
|
+
readInBody: true,
|
|
252
262
|
summary: "Everything the kit holds about one user, from every capability — the answer to an access request.",
|
|
253
263
|
},
|
|
254
264
|
];
|
package/src/http/responses.ts
CHANGED
|
@@ -26,7 +26,7 @@ import { VerificationState, VerificationType } from "../data/verificationOutcome
|
|
|
26
26
|
* **A field added here later is `.optional()`, not merely `.nullable()`.** This module is read across a
|
|
27
27
|
* version boundary — a management client validates a response with this schema against a customer's
|
|
28
28
|
* Worker at whatever kit version it is on — so an additive required key fails `safeParse` for everyone
|
|
29
|
-
* below that release and takes the whole pane with it
|
|
29
|
+
* below that release and takes the whole pane with it. Absent then means *this Worker cannot
|
|
30
30
|
* say*, which is a different fact from `null`.
|
|
31
31
|
*/
|
|
32
32
|
|
|
@@ -60,7 +60,7 @@ export const AdminUserView = z
|
|
|
60
60
|
),
|
|
61
61
|
createdAt: z.iso.datetime().describe("When the user was created, ISO-8601."),
|
|
62
62
|
updatedAt: z.iso.datetime().describe("When the row was last written, ISO-8601."),
|
|
63
|
-
// Where the account stands
|
|
63
|
+
// Where the account stands, on the organization view's shape. Each optional: absent from a Worker
|
|
64
64
|
// older than the field. No reason and no actor — the reason is on the trail, and the trail is audit's.
|
|
65
65
|
state: z
|
|
66
66
|
.enum(["active", "suspended", "deleted"])
|
|
@@ -117,7 +117,7 @@ export const AdminDeviceView = z
|
|
|
117
117
|
.describe("One registered device as a management client sees it — without the push token, which is a credential.");
|
|
118
118
|
export type AdminDeviceView = z.output<typeof AdminDeviceView>;
|
|
119
119
|
|
|
120
|
-
/** `GET {base}/admin/users`. */
|
|
120
|
+
/** `GET {base}/admin/users` and `POST {base}/admin/users/search`. */
|
|
121
121
|
export const AdminUsersResponse = z
|
|
122
122
|
.object({
|
|
123
123
|
users: z.array(AdminUserView).describe("The page, newest first."),
|
|
@@ -128,7 +128,7 @@ export type AdminUsersResponse = z.output<typeof AdminUsersResponse>;
|
|
|
128
128
|
|
|
129
129
|
/** `GET {base}/admin/users/:userId`. */
|
|
130
130
|
/**
|
|
131
|
-
* A sub-read of the user pane that could not be made
|
|
131
|
+
* A sub-read of the user pane that could not be made.
|
|
132
132
|
*
|
|
133
133
|
* The pane fans out over three independent tables and this route used to `Promise.all` them: one D1 read
|
|
134
134
|
* failing took the whole page down, so a support agent looking at a locked-out account saw a 500 instead
|
|
@@ -201,7 +201,7 @@ export const AdminDevicesResponse = z
|
|
|
201
201
|
export type AdminDevicesResponse = z.output<typeof AdminDevicesResponse>;
|
|
202
202
|
|
|
203
203
|
/**
|
|
204
|
-
* One sign-in link or code from the verification ledger
|
|
204
|
+
* One sign-in link or code from the verification ledger, as a management client sees it.
|
|
205
205
|
*
|
|
206
206
|
* Never the token and never the address: the ledger holds neither. The mail is named by its job id, which is how
|
|
207
207
|
* a reader holding `email:jobs:read` joins this to a bounce, a deferral or a suppression.
|
|
@@ -243,7 +243,7 @@ export const VerificationTypeCounts = z
|
|
|
243
243
|
export type VerificationTypeCounts = z.output<typeof VerificationTypeCounts>;
|
|
244
244
|
|
|
245
245
|
/**
|
|
246
|
-
* `GET {base}/admin/verifications
|
|
246
|
+
* `GET {base}/admin/verifications`: the window it covered, the counts by type and state over all of it,
|
|
247
247
|
* and a page of its rows, newest issue first.
|
|
248
248
|
*
|
|
249
249
|
* The counts cover every row in the window whatever the page or the filters say, and every type, with zeros —
|
|
@@ -286,7 +286,7 @@ export const AdminDeviceRevokeResponse = z
|
|
|
286
286
|
export type AdminDeviceRevokeResponse = z.output<typeof AdminDeviceRevokeResponse>;
|
|
287
287
|
|
|
288
288
|
/**
|
|
289
|
-
* `POST {base}/admin/users/:userId/suspend
|
|
289
|
+
* `POST {base}/admin/users/:userId/suspend`.
|
|
290
290
|
*
|
|
291
291
|
* The suspension the account is now under, how many sessions ended with it, and whether the person was told.
|
|
292
292
|
* Not the reason: the caller wrote it, the trail keeps it, and echoing it back would put it in one more place
|
|
@@ -319,7 +319,7 @@ export const AdminUserSuspendResponse = z
|
|
|
319
319
|
export type AdminUserSuspendResponse = z.output<typeof AdminUserSuspendResponse>;
|
|
320
320
|
|
|
321
321
|
/**
|
|
322
|
-
* `POST {base}/admin/users/:userId/reinstate
|
|
322
|
+
* `POST {base}/admin/users/:userId/reinstate`.
|
|
323
323
|
*
|
|
324
324
|
* No session count: a reinstatement restores none. The person signs in again.
|
|
325
325
|
*/
|
|
@@ -349,7 +349,7 @@ const PurgeAfter = z.iso
|
|
|
349
349
|
);
|
|
350
350
|
|
|
351
351
|
/**
|
|
352
|
-
* `DELETE {base}/admin/users/:userId
|
|
352
|
+
* `DELETE {base}/admin/users/:userId`.
|
|
353
353
|
*
|
|
354
354
|
* What the deletion left in force, how many sessions ended with it, whether the person was told, and what
|
|
355
355
|
* became of the purge. Not the reason: the caller wrote it and the trail keeps it.
|
|
@@ -382,7 +382,7 @@ export const AdminUserDeleteResponse = z
|
|
|
382
382
|
export type AdminUserDeleteResponse = z.output<typeof AdminUserDeleteResponse>;
|
|
383
383
|
|
|
384
384
|
/**
|
|
385
|
-
* `POST {base}/admin/users/:userId/restore
|
|
385
|
+
* `POST {base}/admin/users/:userId/restore`. No session count: a restoration restores none.
|
|
386
386
|
*/
|
|
387
387
|
export const AdminUserRestoreResponse = z
|
|
388
388
|
.object({
|
|
@@ -425,7 +425,7 @@ const AuthExportTransition = z
|
|
|
425
425
|
);
|
|
426
426
|
|
|
427
427
|
/**
|
|
428
|
-
* What `@pithy-sh/auth` holds about one account, as its purge contribution exports it
|
|
428
|
+
* What `@pithy-sh/auth` holds about one account, as its purge contribution exports it — the `data` of
|
|
429
429
|
* the `auth` entry in an export.
|
|
430
430
|
*
|
|
431
431
|
* The person's own data and none of their credentials: no session token, no provider token, no push token.
|
|
@@ -513,7 +513,7 @@ const AdminUserExportEntry = z
|
|
|
513
513
|
.describe("One capability's part of an export, behind a state, so an unread part cannot be taken for an empty one.");
|
|
514
514
|
|
|
515
515
|
/**
|
|
516
|
-
* `
|
|
516
|
+
* `POST {base}/admin/users/:userId/export`.
|
|
517
517
|
*
|
|
518
518
|
* Everything the kit holds about one account — the answer to an access request. One entry per composed
|
|
519
519
|
* capability that declares a purge contribution, in the order the purge runs them, each read on its own so
|
|
@@ -607,7 +607,7 @@ export const MyDeviceRevokeResponse = z
|
|
|
607
607
|
export type MyDeviceRevokeResponse = z.output<typeof MyDeviceRevokeResponse>;
|
|
608
608
|
|
|
609
609
|
/**
|
|
610
|
-
* `DELETE {base}/account`
|
|
610
|
+
* `DELETE {base}/account` — the signed-in person deleted their own account. Always soft, on the
|
|
611
611
|
* configured window. Their sessions end with it, this one included.
|
|
612
612
|
*/
|
|
613
613
|
export const AccountDeleteResponse = z
|