@pithy-sh/auth 0.10.0 → 0.12.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 +30 -2
- package/dist/admin/users.js +1 -1
- package/dist/audit/actions.d.ts +58 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +59 -1
- package/dist/audit/emit.d.ts +36 -0
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +48 -2
- package/dist/audit/evidence.d.ts +8 -2
- package/dist/audit/evidence.d.ts.map +1 -1
- package/dist/capability.d.ts +47 -8
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +56 -6
- package/dist/client/api.d.ts +55 -12
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/api.js +57 -18
- package/dist/client/bearer.d.ts +110 -0
- package/dist/client/bearer.d.ts.map +1 -0
- package/dist/client/bearer.js +265 -0
- package/dist/client/handoff.d.ts +77 -0
- package/dist/client/handoff.d.ts.map +1 -0
- package/dist/client/handoff.js +119 -0
- package/dist/client/mcp.d.ts +70 -0
- package/dist/client/mcp.d.ts.map +1 -0
- package/dist/client/mcp.js +65 -0
- package/dist/data/betterAuth.d.ts +3 -2
- package/dist/data/betterAuth.d.ts.map +1 -1
- package/dist/data/betterAuth.js +5 -3
- package/dist/data/kitFields.d.ts +5 -0
- package/dist/data/kitFields.d.ts.map +1 -1
- package/dist/data/kitFields.js +5 -0
- package/dist/data/tables.d.ts +26 -4
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +10 -0
- package/dist/data/userLifecycle.d.ts.map +1 -1
- package/dist/data/userLifecycle.js +8 -3
- package/dist/data/verificationOutcome.d.ts +53 -0
- package/dist/data/verificationOutcome.d.ts.map +1 -0
- package/dist/data/verificationOutcome.js +50 -0
- package/dist/email/send.js +6 -2
- package/dist/http/adminRoutes.d.ts.map +1 -1
- package/dist/http/adminRoutes.js +319 -8
- package/dist/http/csrf.d.ts.map +1 -1
- package/dist/http/csrf.js +2 -1
- package/dist/http/guards.d.ts +15 -10
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +76 -10
- package/dist/http/handoff.d.ts +76 -0
- package/dist/http/handoff.d.ts.map +1 -0
- package/dist/http/handoff.js +316 -0
- package/dist/http/middleware.d.ts +37 -1
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +68 -6
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +9 -3
- package/dist/http/responses.d.ts +322 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +202 -5
- package/dist/http/routes.d.ts +3 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +78 -5
- package/dist/http/schemas.d.ts +114 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +94 -1
- package/dist/http/views.d.ts +60 -3
- package/dist/http/views.d.ts.map +1 -1
- package/dist/http/views.js +143 -3
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/instance/auth.d.ts +148 -10
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +87 -42
- package/dist/instance/plugins.d.ts +6 -0
- package/dist/instance/plugins.d.ts.map +1 -1
- package/dist/instance/plugins.js +14 -1
- package/dist/ledger/read.d.ts +53 -0
- package/dist/ledger/read.d.ts.map +1 -0
- package/dist/ledger/read.js +85 -0
- package/dist/ledger/record.d.ts +35 -0
- package/dist/ledger/record.d.ts.map +1 -0
- package/dist/ledger/record.js +98 -0
- package/dist/lifecycle/audited.d.ts +48 -0
- package/dist/lifecycle/audited.d.ts.map +1 -0
- package/dist/lifecycle/audited.js +65 -0
- package/dist/lifecycle/enforce.d.ts +37 -2
- package/dist/lifecycle/enforce.d.ts.map +1 -1
- package/dist/lifecycle/enforce.js +46 -5
- package/dist/lifecycle/erasure.d.ts +9 -0
- package/dist/lifecycle/erasure.d.ts.map +1 -0
- package/dist/lifecycle/erasure.js +96 -0
- package/dist/lifecycle/inactivity.d.ts +19 -0
- package/dist/lifecycle/inactivity.d.ts.map +1 -0
- package/dist/lifecycle/inactivity.js +28 -0
- package/dist/lifecycle/reason.d.ts +11 -0
- package/dist/lifecycle/reason.d.ts.map +1 -0
- package/dist/lifecycle/reason.js +13 -0
- package/dist/lifecycle/request.d.ts +5 -2
- package/dist/lifecycle/request.d.ts.map +1 -1
- package/dist/lifecycle/request.js +6 -2
- package/dist/lifecycle/transitions.d.ts +179 -18
- package/dist/lifecycle/transitions.d.ts.map +1 -1
- package/dist/lifecycle/transitions.js +391 -70
- package/dist/mcp/argumentClass.d.ts +51 -0
- package/dist/mcp/argumentClass.d.ts.map +1 -0
- package/dist/mcp/argumentClass.js +69 -0
- package/dist/mcp/capability.d.ts +50 -0
- package/dist/mcp/capability.d.ts.map +1 -0
- package/dist/mcp/capability.js +140 -0
- package/dist/mcp/clientMetadata.d.ts +40 -0
- package/dist/mcp/clientMetadata.d.ts.map +1 -0
- package/dist/mcp/clientMetadata.js +68 -0
- package/dist/mcp/consent.d.ts +49 -0
- package/dist/mcp/consent.d.ts.map +1 -0
- package/dist/mcp/consent.js +69 -0
- package/dist/mcp/dispatch.d.ts +35 -0
- package/dist/mcp/dispatch.d.ts.map +1 -0
- package/dist/mcp/dispatch.js +135 -0
- package/dist/mcp/floor.d.ts +37 -0
- package/dist/mcp/floor.d.ts.map +1 -0
- package/dist/mcp/floor.js +41 -0
- package/dist/mcp/host.d.ts +34 -0
- package/dist/mcp/host.d.ts.map +1 -0
- package/dist/mcp/host.js +2 -0
- package/dist/mcp/http/redirectList.d.ts +9 -0
- package/dist/mcp/http/redirectList.d.ts.map +1 -0
- package/dist/mcp/http/redirectList.js +24 -0
- package/dist/mcp/http/responses.d.ts +143 -0
- package/dist/mcp/http/responses.d.ts.map +1 -0
- package/dist/mcp/http/responses.js +83 -0
- package/dist/mcp/http/routes.d.ts +28 -0
- package/dist/mcp/http/routes.d.ts.map +1 -0
- package/dist/mcp/http/routes.js +517 -0
- package/dist/mcp/http/schemas.d.ts +24 -0
- package/dist/mcp/http/schemas.d.ts.map +1 -0
- package/dist/mcp/http/schemas.js +18 -0
- package/dist/mcp/marker.d.ts +15 -0
- package/dist/mcp/marker.d.ts.map +1 -0
- package/dist/mcp/marker.js +15 -0
- package/dist/mcp/provider.d.ts +78 -0
- package/dist/mcp/provider.d.ts.map +1 -0
- package/dist/mcp/provider.js +108 -0
- package/dist/mcp/purge.d.ts +15 -0
- package/dist/mcp/purge.d.ts.map +1 -0
- package/dist/mcp/purge.js +31 -0
- package/dist/mcp/rpc.d.ts +79 -0
- package/dist/mcp/rpc.d.ts.map +1 -0
- package/dist/mcp/rpc.js +103 -0
- package/dist/mcp/toolAudit.d.ts +76 -0
- package/dist/mcp/toolAudit.d.ts.map +1 -0
- package/dist/mcp/toolAudit.js +86 -0
- package/dist/migrations/0005_purge_once.d.ts +22 -0
- package/dist/migrations/0005_purge_once.d.ts.map +1 -0
- package/dist/migrations/0005_purge_once.js +35 -0
- package/dist/migrations/0006_verification_outcomes.d.ts +15 -0
- package/dist/migrations/0006_verification_outcomes.d.ts.map +1 -0
- package/dist/migrations/0006_verification_outcomes.js +35 -0
- package/dist/migrations/0007_erasure_record.d.ts +17 -0
- package/dist/migrations/0007_erasure_record.d.ts.map +1 -0
- package/dist/migrations/0007_erasure_record.js +36 -0
- package/dist/migrations/0008_last_active.d.ts +15 -0
- package/dist/migrations/0008_last_active.d.ts.map +1 -0
- package/dist/migrations/0008_last_active.js +29 -0
- package/dist/migrations/pluginTables.d.ts +8 -0
- package/dist/migrations/pluginTables.d.ts.map +1 -1
- package/dist/migrations/pluginTables.js +8 -1
- package/dist/migrations/set.d.ts +5 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +10 -2
- package/dist/peer.d.ts +3 -2
- package/dist/peer.d.ts.map +1 -1
- package/dist/processing/activities.d.ts +6 -0
- package/dist/processing/activities.d.ts.map +1 -0
- package/dist/processing/activities.js +12 -0
- package/dist/purge/contribution.d.ts +62 -0
- package/dist/purge/contribution.d.ts.map +1 -0
- package/dist/purge/contribution.js +155 -0
- package/dist/purge/retryPolicy.d.ts +22 -0
- package/dist/purge/retryPolicy.d.ts.map +1 -0
- package/dist/purge/retryPolicy.js +26 -0
- package/dist/purge/run.d.ts +158 -0
- package/dist/purge/run.d.ts.map +1 -0
- package/dist/purge/run.js +205 -0
- package/dist/purge/specs.d.ts +71 -0
- package/dist/purge/specs.d.ts.map +1 -0
- package/dist/purge/specs.js +72 -0
- package/dist/purge/start.d.ts +42 -0
- package/dist/purge/start.d.ts.map +1 -0
- package/dist/purge/start.js +37 -0
- package/dist/purge/workflow.d.ts +71 -0
- package/dist/purge/workflow.d.ts.map +1 -0
- package/dist/purge/workflow.js +140 -0
- package/dist/test-utils/accountFootprint.d.ts +13 -0
- package/dist/test-utils/accountFootprint.d.ts.map +1 -0
- package/dist/test-utils/accountFootprint.js +49 -0
- package/dist/test-utils/liveApp.d.ts +6 -0
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +7 -2
- package/dist/token/handoff.d.ts +80 -0
- package/dist/token/handoff.d.ts.map +1 -0
- package/dist/token/handoff.js +136 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/account-lifecycle.md +176 -12
- package/docs/apple-signin.md +32 -4
- package/docs/facebook-oauth.md +2 -2
- package/docs/github-oauth.md +2 -2
- package/docs/google-oauth.md +9 -7
- package/docs/microsoft-oauth.md +2 -2
- package/package.json +11 -5
- package/pithy.manifest.json +2 -2
- package/pithy.mcp.manifest.json +36 -0
- package/src/audit/actions.ts +58 -0
- package/src/audit/emit.ts +66 -1
- package/src/audit/evidence.ts +8 -4
- package/src/capability.ts +122 -18
- package/src/client/api.ts +69 -19
- package/src/client/bearer.ts +388 -0
- package/src/client/handoff.ts +172 -0
- package/src/client/mcp.ts +140 -0
- package/src/data/betterAuth.ts +8 -4
- package/src/data/kitFields.ts +2 -0
- package/src/data/tables.ts +4 -2
- package/src/data/userLifecycle.ts +19 -4
- package/src/data/verificationOutcome.ts +86 -0
- package/src/email/send.ts +2 -2
- package/src/http/adminRoutes.ts +465 -4
- package/src/http/csrf.ts +4 -1
- package/src/http/guards.ts +79 -10
- package/src/http/handoff.ts +350 -0
- package/src/http/middleware.ts +74 -5
- package/src/http/resolve.ts +25 -25
- package/src/http/responses.ts +374 -3
- package/src/http/routes.ts +116 -5
- package/src/http/schemas.ts +195 -0
- package/src/http/views.ts +192 -3
- package/src/index.ts +2 -0
- package/src/instance/auth.ts +58 -3
- package/src/instance/plugins.ts +20 -2
- package/src/ledger/read.ts +133 -0
- package/src/ledger/record.ts +198 -0
- package/src/lifecycle/audited.ts +104 -0
- package/src/lifecycle/enforce.ts +55 -5
- package/src/lifecycle/erasure.ts +118 -0
- package/src/lifecycle/inactivity.ts +56 -0
- package/src/lifecycle/reason.ts +11 -0
- package/src/lifecycle/request.ts +10 -2
- package/src/lifecycle/transitions.ts +552 -93
- package/src/mcp/argumentClass.ts +112 -0
- package/src/mcp/capability.ts +194 -0
- package/src/mcp/clientMetadata.ts +81 -0
- package/src/mcp/consent.ts +95 -0
- package/src/mcp/dispatch.ts +154 -0
- package/src/mcp/floor.ts +62 -0
- package/src/mcp/host.ts +36 -0
- package/src/mcp/http/redirectList.ts +26 -0
- package/src/mcp/http/responses.ts +157 -0
- package/src/mcp/http/routes.ts +635 -0
- package/src/mcp/http/schemas.ts +37 -0
- package/src/mcp/marker.ts +18 -0
- package/src/mcp/provider.ts +151 -0
- package/src/mcp/purge.ts +39 -0
- package/src/mcp/rpc.ts +135 -0
- package/src/mcp/toolAudit.ts +132 -0
- package/src/migrations/0005_purge_once.ts +42 -0
- package/src/migrations/0006_verification_outcomes.ts +51 -0
- package/src/migrations/0007_erasure_record.ts +43 -0
- package/src/migrations/0008_last_active.ts +30 -0
- package/src/migrations/pluginTables.ts +19 -1
- package/src/migrations/set.ts +9 -1
- package/src/processing/activities.ts +14 -0
- package/src/purge/contribution.ts +218 -0
- package/src/purge/retryPolicy.ts +26 -0
- package/src/purge/run.ts +348 -0
- package/src/purge/specs.ts +95 -0
- package/src/purge/start.ts +79 -0
- package/src/purge/workflow.ts +202 -0
- package/src/seeds/example.ts +2 -2
- package/src/test-utils/accountFootprint.ts +104 -0
- package/src/test-utils/liveApp.ts +10 -1
- package/src/token/handoff.ts +180 -0
- package/src/version.generated.ts +1 -1
package/src/http/guards.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
|
-
import type {
|
|
4
|
+
import type { AdminRouteDeclaration } from "@pithy-sh/core/src/controlPlane/discovery/adminRoute";
|
|
5
5
|
import type { ControlPlaneScope } from "@pithy-sh/core/src/controlPlane/scope/scope";
|
|
6
6
|
|
|
7
7
|
/**
|
|
@@ -29,7 +29,7 @@ import type { ControlPlaneScope } from "@pithy-sh/core/src/controlPlane/scope/sc
|
|
|
29
29
|
* every legitimate management call, permanently, and **no credential could fix it** — there is no user
|
|
30
30
|
* to sign in as. `controlPlaneIsolation.workers.test.ts` pins both directions of that separation.
|
|
31
31
|
*
|
|
32
|
-
* ##
|
|
32
|
+
* ## Nine scopes, because these are nine different blast radii
|
|
33
33
|
*
|
|
34
34
|
* The temptation is one `auth:admin` flag, and on this capability it is the most dangerous version of
|
|
35
35
|
* that mistake. **Reading a user is a privacy operation; revoking their sessions is an availability
|
|
@@ -93,33 +93,39 @@ export const AUTH_USERS_LOGOUT_SCOPE: ControlPlaneScope = "auth:users:logout";
|
|
|
93
93
|
export const AUTH_DEVICES_REVOKE_SCOPE: ControlPlaneScope = "auth:devices:revoke";
|
|
94
94
|
|
|
95
95
|
/**
|
|
96
|
-
* Suspend an account and reinstate it
|
|
96
|
+
* Suspend an account and reinstate it: `POST {base}/admin/users/:userId/suspend` and `/reinstate`. Ending somebody's access is an availability
|
|
97
97
|
* operation on one person, and reversible — which is what separates it from deleting them, and why it is
|
|
98
98
|
* granted apart from both reading them and erasing them.
|
|
99
99
|
*/
|
|
100
100
|
export const AUTH_USERS_SUSPEND_SCOPE: ControlPlaneScope = "auth:users:suspend";
|
|
101
101
|
|
|
102
102
|
/**
|
|
103
|
-
* Delete an account, restore one inside its purge window, and start a purge
|
|
103
|
+
* Delete an account, restore one inside its purge window, and start a purge:
|
|
104
|
+
* `DELETE {base}/admin/users/:userId` and `POST …/restore`. The
|
|
104
105
|
* one scope on this surface whose worst case cannot be undone: once the window closes, the person's rows are
|
|
105
106
|
* gone from every capability that held them.
|
|
106
107
|
*/
|
|
107
108
|
export const AUTH_USERS_DELETE_SCOPE: ControlPlaneScope = "auth:users:delete";
|
|
108
109
|
|
|
109
110
|
/**
|
|
110
|
-
* Export everything the kit holds about one account — the answer to an access request
|
|
111
|
-
*
|
|
111
|
+
* Export everything the kit holds about one account — the answer to an access request:
|
|
112
|
+
* `GET {base}/admin/users/:userId/export`. A disclosure, and a far larger one than reading the user: it carries every capability's rows about
|
|
112
113
|
* them, so it is granted on its own and audited as one.
|
|
113
114
|
*/
|
|
114
115
|
export const AUTH_USERS_EXPORT_SCOPE: ControlPlaneScope = "auth:users:export";
|
|
115
116
|
|
|
117
|
+
/**
|
|
118
|
+
* Read the verification ledger: every sign-in link and code issued over a window, whether it was used,
|
|
119
|
+
* expired or is still waiting, and the mail that carried it. A read, and apart from `auth:users:read` because the question is the fleet's deliverability rather than
|
|
120
|
+
* who one person is — the rows name accounts by id and never by address.
|
|
121
|
+
*/
|
|
122
|
+
export const AUTH_VERIFICATIONS_READ_SCOPE: ControlPlaneScope = "auth:verifications:read";
|
|
123
|
+
|
|
116
124
|
/**
|
|
117
125
|
* Every control-plane scope auth defines — what `pithy dashboard connect` offers for this capability,
|
|
118
126
|
* and the list a manifest or a doc quotes rather than re-typing.
|
|
119
127
|
*
|
|
120
|
-
*
|
|
121
|
-
* export routes land in #621 and #622; declaring the vocabulary here, once, is what lets those issues build on
|
|
122
|
-
* one name each rather than three issues each choosing their own.
|
|
128
|
+
* Declaring the vocabulary here, once, gives every route that requires one of these the same name.
|
|
123
129
|
*/
|
|
124
130
|
export const AUTH_CONTROL_PLANE_SCOPES: readonly ControlPlaneScope[] = [
|
|
125
131
|
AUTH_USERS_READ_SCOPE,
|
|
@@ -130,6 +136,7 @@ export const AUTH_CONTROL_PLANE_SCOPES: readonly ControlPlaneScope[] = [
|
|
|
130
136
|
AUTH_USERS_SUSPEND_SCOPE,
|
|
131
137
|
AUTH_USERS_DELETE_SCOPE,
|
|
132
138
|
AUTH_USERS_EXPORT_SCOPE,
|
|
139
|
+
AUTH_VERIFICATIONS_READ_SCOPE,
|
|
133
140
|
];
|
|
134
141
|
|
|
135
142
|
/**
|
|
@@ -144,43 +151,105 @@ export const AUTH_CONTROL_PLANE_SCOPES: readonly ControlPlaneScope[] = [
|
|
|
144
151
|
* The summaries say what the operation is *for*. A client renders these next to a button somebody is
|
|
145
152
|
* about to press on a real person's account.
|
|
146
153
|
*/
|
|
147
|
-
export function authAdminRoutes(basePath: string):
|
|
154
|
+
export function authAdminRoutes(basePath: string): AdminRouteDeclaration[] {
|
|
148
155
|
return [
|
|
149
156
|
{
|
|
150
157
|
method: "GET",
|
|
158
|
+
operation: "users.list",
|
|
151
159
|
path: `${basePath}/admin/users`,
|
|
152
160
|
scope: AUTH_USERS_READ_SCOPE,
|
|
161
|
+
kind: "reads",
|
|
153
162
|
summary: "Find a user. Lists everyone newest first, or searches email and display name.",
|
|
154
163
|
},
|
|
155
164
|
{
|
|
156
165
|
method: "GET",
|
|
166
|
+
operation: "users.read",
|
|
157
167
|
path: `${basePath}/admin/users/:userId`,
|
|
158
168
|
scope: AUTH_USERS_READ_SCOPE,
|
|
169
|
+
kind: "reads",
|
|
159
170
|
summary: "One user, with where they are signed in and what they sign in with.",
|
|
160
171
|
},
|
|
161
172
|
{
|
|
162
173
|
method: "GET",
|
|
174
|
+
operation: "devices.list",
|
|
163
175
|
path: `${basePath}/admin/devices`,
|
|
164
176
|
scope: AUTH_DEVICES_READ_SCOPE,
|
|
177
|
+
kind: "reads",
|
|
165
178
|
summary: "The device registry across users, most-recently-seen first.",
|
|
166
179
|
},
|
|
167
180
|
{
|
|
168
181
|
method: "POST",
|
|
182
|
+
operation: "sessions.revoke",
|
|
169
183
|
path: `${basePath}/admin/sessions/revoke`,
|
|
170
184
|
scope: AUTH_SESSIONS_REVOKE_SCOPE,
|
|
185
|
+
kind: "credentials",
|
|
171
186
|
summary: "Kill one session. The rest of that person's sign-ins keep working.",
|
|
172
187
|
},
|
|
173
188
|
{
|
|
174
189
|
method: "POST",
|
|
190
|
+
operation: "users.sessions.revoke",
|
|
175
191
|
path: `${basePath}/admin/users/:userId/sessions/revoke`,
|
|
176
192
|
scope: AUTH_USERS_LOGOUT_SCOPE,
|
|
193
|
+
kind: "credentials",
|
|
177
194
|
summary: "Sign a user out everywhere, on every device, immediately.",
|
|
178
195
|
},
|
|
179
196
|
{
|
|
180
197
|
method: "POST",
|
|
198
|
+
operation: "users.devices.revoke",
|
|
181
199
|
path: `${basePath}/admin/users/:userId/devices/revoke`,
|
|
182
200
|
scope: AUTH_DEVICES_REVOKE_SCOPE,
|
|
201
|
+
kind: "credentials",
|
|
183
202
|
summary: "Sign one device out and forget it — for a phone reported lost.",
|
|
184
203
|
},
|
|
204
|
+
{
|
|
205
|
+
method: "POST",
|
|
206
|
+
operation: "users.suspend",
|
|
207
|
+
path: `${basePath}/admin/users/:userId/suspend`,
|
|
208
|
+
scope: AUTH_USERS_SUSPEND_SCOPE,
|
|
209
|
+
kind: "writes",
|
|
210
|
+
summary: "Suspend a user, with a reason. Their sessions end and every sign-in is refused.",
|
|
211
|
+
},
|
|
212
|
+
{
|
|
213
|
+
method: "POST",
|
|
214
|
+
operation: "users.reinstate",
|
|
215
|
+
path: `${basePath}/admin/users/:userId/reinstate`,
|
|
216
|
+
scope: AUTH_USERS_SUSPEND_SCOPE,
|
|
217
|
+
kind: "writes",
|
|
218
|
+
summary: "Lift a suspension, with a reason. They sign in again; no session comes back.",
|
|
219
|
+
},
|
|
220
|
+
{
|
|
221
|
+
method: "DELETE",
|
|
222
|
+
operation: "users.delete",
|
|
223
|
+
path: `${basePath}/admin/users/:userId`,
|
|
224
|
+
scope: AUTH_USERS_DELETE_SCOPE,
|
|
225
|
+
kind: "deletes",
|
|
226
|
+
summary:
|
|
227
|
+
"Delete a user, with a reason. Soft by default: restorable until the purge window closes. Hard, when named: erased now.",
|
|
228
|
+
},
|
|
229
|
+
{
|
|
230
|
+
method: "POST",
|
|
231
|
+
operation: "users.restore",
|
|
232
|
+
path: `${basePath}/admin/users/:userId/restore`,
|
|
233
|
+
scope: AUTH_USERS_DELETE_SCOPE,
|
|
234
|
+
kind: "deletes",
|
|
235
|
+
summary: "Restore a deleted user inside the purge window, with a reason. They sign in again.",
|
|
236
|
+
},
|
|
237
|
+
{
|
|
238
|
+
method: "GET",
|
|
239
|
+
operation: "verifications.list",
|
|
240
|
+
path: `${basePath}/admin/verifications`,
|
|
241
|
+
scope: AUTH_VERIFICATIONS_READ_SCOPE,
|
|
242
|
+
kind: "reads",
|
|
243
|
+
summary:
|
|
244
|
+
"Every sign-in link and code sent over a window: used, expired or still waiting, and the mail that carried it.",
|
|
245
|
+
},
|
|
246
|
+
{
|
|
247
|
+
method: "GET",
|
|
248
|
+
operation: "users.export",
|
|
249
|
+
path: `${basePath}/admin/users/:userId/export`,
|
|
250
|
+
scope: AUTH_USERS_EXPORT_SCOPE,
|
|
251
|
+
kind: "reads",
|
|
252
|
+
summary: "Everything the kit holds about one user, from every capability — the answer to an access request.",
|
|
253
|
+
},
|
|
185
254
|
];
|
|
186
255
|
}
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
|
|
5
|
+
import {
|
|
6
|
+
ForbiddenError,
|
|
7
|
+
InternalError,
|
|
8
|
+
NotFoundError,
|
|
9
|
+
PithyError,
|
|
10
|
+
ValidationError,
|
|
11
|
+
} from "@pithy-sh/core/src/error/pithyError";
|
|
12
|
+
import type { Context } from "hono";
|
|
13
|
+
import { correlation, emitHandoffExchanged, emitHandoffIssued } from "../audit/emit";
|
|
14
|
+
import type { AuthWiring } from "../capability";
|
|
15
|
+
import { Session } from "../data/betterAuth";
|
|
16
|
+
import { authDatabase } from "../data/tables";
|
|
17
|
+
import { parseDeviceMeta, registerDevice } from "../device/registry";
|
|
18
|
+
import type { AuthInstance } from "../instance/auth";
|
|
19
|
+
import { isHandoffChallenge, issueHandoff, redeemHandoff } from "../token/handoff";
|
|
20
|
+
import { guardErrorCallbackURL } from "./errorCallbackUrl";
|
|
21
|
+
import { apiErrorToPithy } from "./errors";
|
|
22
|
+
import { getAuthInstance, resolveDb } from "./resolve";
|
|
23
|
+
import type { HandoffExchangeResponse } from "./responses";
|
|
24
|
+
import type { HandoffExchangeBody, SocialSignInStartQuery } from "./schemas";
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The redirect half of a native sign-in, and the trade that ends it.
|
|
28
|
+
*
|
|
29
|
+
* A native app starts a social sign-in with its own deep link as `callbackURL` (a scheme in `trustedOrigins`,
|
|
30
|
+
* such as `myapp://auth/callback`). Better Auth checks that URL when the sign-in starts and, at the provider's
|
|
31
|
+
* callback, answers with a redirect to it carrying the session as a cookie. A cookie set on a redirect to an app
|
|
32
|
+
* scheme lands in the system browser, which the app never reads. {@link handOffToApp} replaces that answer: the
|
|
33
|
+
* session cookies are dropped and the deep link carries a one-time code instead (`../token/handoff.ts`). The app
|
|
34
|
+
* posts the code to `POST {base}/handoff`, {@link exchangeHandoff}, and gets the raw session token back.
|
|
35
|
+
*
|
|
36
|
+
* The code is bound to the app that asked for it. The app puts the S256 challenge of a verifier only it holds on
|
|
37
|
+
* its `callbackURL` as `handoff_challenge`, Better Auth keeps that URL with the sign-in's state, and the challenge
|
|
38
|
+
* comes back here on the redirect. It is moved off the link and stored with the code, and the trade must present
|
|
39
|
+
* the verifier. A deep link with no challenge gets no code at all.
|
|
40
|
+
*
|
|
41
|
+
* Which redirects are handed off: any whose link carries `handoff_challenge`, whatever its scheme, and any to a
|
|
42
|
+
* non-http(s) scheme. So an app's https universal link (iOS) or app link (Android), which the operating system
|
|
43
|
+
* routes only to the app that proves it owns the domain, gets a code when the app asks for one with a challenge.
|
|
44
|
+
* An http(s) callback with no challenge is a web page, and a web page gets its cookie.
|
|
45
|
+
*
|
|
46
|
+
* A magic link is handed off only to an https link. Whoever asks for the link chooses the challenge, and the
|
|
47
|
+
* person who opens it is somebody else, so the code must reach only the app that owns the link's domain. Any app
|
|
48
|
+
* can claim a custom scheme; a magic link to one is refused, and a native app without a universal link signs in
|
|
49
|
+
* by email with a one-time code instead.
|
|
50
|
+
*
|
|
51
|
+
* A native app starts a redirect sign-in with {@link startNativeSignIn}, a GET the system browser's sign-in sheet
|
|
52
|
+
* opens, rather than by posting `/sign-in/social` itself. Better Auth binds the sign-in to a signed `state`
|
|
53
|
+
* cookie and checks it at the provider's callback; set on the app's own request, that cookie would never reach
|
|
54
|
+
* the sheet that completes the callback.
|
|
55
|
+
*/
|
|
56
|
+
|
|
57
|
+
/** The deep-link query parameter the one-time code travels in. */
|
|
58
|
+
export const HANDOFF_CODE_PARAM = "code";
|
|
59
|
+
|
|
60
|
+
/** The `callbackURL` query parameter the app's S256 challenge travels in. */
|
|
61
|
+
export const HANDOFF_CHALLENGE_PARAM = "handoff_challenge";
|
|
62
|
+
|
|
63
|
+
/** The `error` a deep link gets back when it carried no challenge to bind a code to. */
|
|
64
|
+
export const HANDOFF_UNBOUND_ERROR = "handoff_challenge_required";
|
|
65
|
+
|
|
66
|
+
/** The `error` a magic link to a custom scheme gets back: only an https universal link or app link is handed one. */
|
|
67
|
+
export const HANDOFF_SCHEME_REFUSED_ERROR = "handoff_scheme_refused";
|
|
68
|
+
|
|
69
|
+
/** Better Auth's magic-link verification, under `basePath`: the one redirect that ends an emailed sign-in. */
|
|
70
|
+
const MAGIC_LINK_VERIFY_PATH = "/magic-link/verify";
|
|
71
|
+
|
|
72
|
+
type Ctx = Context<PithyHonoEnv>;
|
|
73
|
+
|
|
74
|
+
/** The cookie lines a response sets, as name and value. */
|
|
75
|
+
function setCookies(response: Response): { line: string; name: string; value: string }[] {
|
|
76
|
+
return response.headers.getSetCookie().map((line) => {
|
|
77
|
+
const pair = line.slice(0, line.indexOf(";") === -1 ? line.length : line.indexOf(";"));
|
|
78
|
+
const equals = pair.indexOf("=");
|
|
79
|
+
return { line, name: pair.slice(0, equals).trim(), value: pair.slice(equals + 1).trim() };
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The raw session token inside a signed session cookie: everything before the signature. */
|
|
84
|
+
function rawToken(cookieValue: string): string | null {
|
|
85
|
+
let decoded: string;
|
|
86
|
+
try {
|
|
87
|
+
decoded = decodeURIComponent(cookieValue);
|
|
88
|
+
} catch {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
const token = decoded.split(".")[0];
|
|
92
|
+
return token ? token : null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The app link a redirect points at, or null when it points anywhere a browser should go: a custom-scheme deep link,
|
|
97
|
+
* or an http(s) link that asked for a handoff by carrying a challenge.
|
|
98
|
+
*/
|
|
99
|
+
function appLink(response: Response): URL | null {
|
|
100
|
+
if (response.status < 300 || response.status >= 400) return null;
|
|
101
|
+
const location = response.headers.get("location");
|
|
102
|
+
if (!location) return null;
|
|
103
|
+
let target: URL;
|
|
104
|
+
try {
|
|
105
|
+
target = new URL(location);
|
|
106
|
+
} catch {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
const web = target.protocol === "http:" || target.protocol === "https:";
|
|
110
|
+
return web && !target.searchParams.has(HANDOFF_CHALLENGE_PARAM) ? null : target;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The `trustedOrigins` entry that would admit a link: its origin for http(s), its scheme otherwise. */
|
|
114
|
+
function trustedEntry(target: URL): string {
|
|
115
|
+
return target.protocol === "http:" || target.protocol === "https:" ? target.origin : `${target.protocol}//`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Rewrite a sign-in that ends on an app link into a handoff, or answer null and leave the response as Better Auth
|
|
120
|
+
* wrote it: any answer that is not a redirect to an app link, and a redirect that sets no session (a refused
|
|
121
|
+
* sign-in returning its error to the app).
|
|
122
|
+
*
|
|
123
|
+
* An app link outside `trustedOrigins` is refused rather than followed. Better Auth checked the callback when the
|
|
124
|
+
* sign-in started, so reaching that branch means something else wrote the redirect, and a session must never be
|
|
125
|
+
* handed to a scheme this Worker does not trust.
|
|
126
|
+
*/
|
|
127
|
+
export async function handOffToApp(
|
|
128
|
+
c: Ctx,
|
|
129
|
+
wiring: AuthWiring,
|
|
130
|
+
instance: AuthInstance,
|
|
131
|
+
response: Response,
|
|
132
|
+
): Promise<Response | null> {
|
|
133
|
+
const target = appLink(response);
|
|
134
|
+
if (!target) return null;
|
|
135
|
+
const context = await instance.$context;
|
|
136
|
+
// Every cookie that carries the session or what was read alongside it. Better Auth splits a cookie cache too
|
|
137
|
+
// large for one cookie into `<name>.0`, `<name>.1`, …, so each chunk goes with its name.
|
|
138
|
+
const sessionCookieNames = [
|
|
139
|
+
context.authCookies.sessionToken.name,
|
|
140
|
+
context.authCookies.sessionData.name,
|
|
141
|
+
context.authCookies.dontRememberToken.name,
|
|
142
|
+
context.authCookies.accountData.name,
|
|
143
|
+
];
|
|
144
|
+
const isSessionCookie = (name: string) =>
|
|
145
|
+
sessionCookieNames.some((cookie) => name === cookie || name.startsWith(`${cookie}.`));
|
|
146
|
+
const cookies = setCookies(response);
|
|
147
|
+
const session = cookies.find((cookie) => cookie.name === context.authCookies.sessionToken.name && cookie.value);
|
|
148
|
+
if (!session) return null;
|
|
149
|
+
if (!context.isTrustedOrigin(target.href, { allowRelativePaths: false })) {
|
|
150
|
+
// The session the redirect made is reachable by nothing once its cookie is dropped, so it goes too.
|
|
151
|
+
const token = rawToken(session.value);
|
|
152
|
+
if (token) {
|
|
153
|
+
await authDatabase(resolveDb(c.env, wiring.config.database))
|
|
154
|
+
.deleteFrom("pithyAuthSessions")
|
|
155
|
+
.where("token", "=", token)
|
|
156
|
+
.execute();
|
|
157
|
+
}
|
|
158
|
+
throw new ForbiddenError({
|
|
159
|
+
message: "That app link is not one this service trusts.",
|
|
160
|
+
action: `Add the app's link to auth's \`trustedOrigins\`, for example "${trustedEntry(target)}".`,
|
|
161
|
+
detail: `sign-in redirect to untrusted app link ${trustedEntry(target)}`,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
const token = rawToken(session.value);
|
|
165
|
+
if (!token) return null;
|
|
166
|
+
const db = authDatabase(resolveDb(c.env, wiring.config.database));
|
|
167
|
+
const row = await db
|
|
168
|
+
.selectFrom("pithyAuthSessions")
|
|
169
|
+
.select(["id", "userId"])
|
|
170
|
+
.where("token", "=", token)
|
|
171
|
+
.executeTakeFirst();
|
|
172
|
+
if (!row) return null;
|
|
173
|
+
|
|
174
|
+
const challenge = target.searchParams.get(HANDOFF_CHALLENGE_PARAM);
|
|
175
|
+
target.searchParams.delete(HANDOFF_CHALLENGE_PARAM);
|
|
176
|
+
const emailed = new URL(c.req.raw.url).pathname === `${wiring.config.basePath}${MAGIC_LINK_VERIFY_PATH}`;
|
|
177
|
+
const refusal =
|
|
178
|
+
emailed && target.protocol !== "https:"
|
|
179
|
+
? HANDOFF_SCHEME_REFUSED_ERROR
|
|
180
|
+
: challenge !== null && isHandoffChallenge(challenge)
|
|
181
|
+
? null
|
|
182
|
+
: HANDOFF_UNBOUND_ERROR;
|
|
183
|
+
if (refusal === null && challenge !== null) {
|
|
184
|
+
const { code } = await issueHandoff(db, { sessionId: row.id, challenge, now: new Date() });
|
|
185
|
+
target.searchParams.set(HANDOFF_CODE_PARAM, code);
|
|
186
|
+
} else {
|
|
187
|
+
// No code. The session the callback made is reachable by nothing once its cookie is dropped, so it goes too,
|
|
188
|
+
// and the app hears why on its own link.
|
|
189
|
+
await db.deleteFrom("pithyAuthSessions").where("id", "=", row.id).execute();
|
|
190
|
+
target.searchParams.set("error", refusal ?? HANDOFF_UNBOUND_ERROR);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const headers = new Headers(response.headers);
|
|
194
|
+
headers.delete("set-cookie");
|
|
195
|
+
headers.delete("set-auth-token");
|
|
196
|
+
headers.set("location", target.href);
|
|
197
|
+
headers.set("cache-control", "no-store");
|
|
198
|
+
headers.set("referrer-policy", "no-referrer");
|
|
199
|
+
for (const cookie of cookies) {
|
|
200
|
+
if (!isSessionCookie(cookie.name)) headers.append("set-cookie", cookie.line);
|
|
201
|
+
}
|
|
202
|
+
await emitHandoffIssued(c.var.emit, {
|
|
203
|
+
...(refusal === null
|
|
204
|
+
? { outcome: "success" as const }
|
|
205
|
+
: { outcome: "denied" as const, reason: refusal === HANDOFF_SCHEME_REFUSED_ERROR ? "scheme" : "unbound" }),
|
|
206
|
+
userId: row.userId,
|
|
207
|
+
sessionId: row.id,
|
|
208
|
+
...correlation(c.req.raw.headers),
|
|
209
|
+
});
|
|
210
|
+
return new Response(null, { status: response.status, headers });
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Start a native redirect sign-in inside the system browser's sign-in sheet: run the social sign-in here and
|
|
215
|
+
* answer a redirect to the provider that carries Better Auth's `Set-Cookie`, so the signed `state` cookie lands in
|
|
216
|
+
* the jar of the browser that will come back through the provider's callback.
|
|
217
|
+
*
|
|
218
|
+
* Only for the handoff: the callback must be a link `trustedOrigins` admits, carrying a well-formed
|
|
219
|
+
* `handoff_challenge`, and a navigation another page started (`Sec-Fetch-Site` other than `none`) is refused. A web page starts its sign-in with the JSON `POST /sign-in/social`, as it always has.
|
|
220
|
+
* The sign-in runs on a request of its own with the sheet's cookies, origin and fetch metadata left behind:
|
|
221
|
+
* nothing the sheet already holds takes part in it.
|
|
222
|
+
*/
|
|
223
|
+
export async function startNativeSignIn(c: Ctx, wiring: AuthWiring, query: SocialSignInStartQuery): Promise<Response> {
|
|
224
|
+
// The sheet opens this address itself, so its navigation is `none`. A page that sent the browser here chose the
|
|
225
|
+
// challenge, and the code would go to whichever app claims the link.
|
|
226
|
+
const site = c.req.raw.headers.get("sec-fetch-site");
|
|
227
|
+
if (site !== null && site !== "none") {
|
|
228
|
+
throw new ForbiddenError({
|
|
229
|
+
message: "Start a sign-in from the app.",
|
|
230
|
+
action: "Open the start address in the system browser's sign-in sheet, not from a link on a page.",
|
|
231
|
+
detail: `native sign-in start reached from ${site}`,
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
if (!wiring.config[query.provider].enabled) {
|
|
235
|
+
throw new NotFoundError({
|
|
236
|
+
message: "That sign-in provider is not available here.",
|
|
237
|
+
action: `Enable \`${query.provider}\` in auth's config, or stop offering it.`,
|
|
238
|
+
detail: `native sign-in start for disabled provider ${query.provider}`,
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
const instance = await getAuthInstance(c, wiring);
|
|
242
|
+
const context = await instance.$context;
|
|
243
|
+
for (const [field, value] of [
|
|
244
|
+
["callbackURL", query.callbackURL],
|
|
245
|
+
["errorCallbackURL", query.errorCallbackURL],
|
|
246
|
+
] as const) {
|
|
247
|
+
if (value !== undefined && !context.isTrustedOrigin(value, { allowRelativePaths: false })) {
|
|
248
|
+
throw new ForbiddenError({
|
|
249
|
+
message: "That app link is not one this service trusts.",
|
|
250
|
+
action: "Add the app's link to auth's `trustedOrigins`.",
|
|
251
|
+
detail: `native sign-in start with untrusted ${field}`,
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
let challenge: string | null;
|
|
256
|
+
try {
|
|
257
|
+
challenge = new URL(query.callbackURL).searchParams.get(HANDOFF_CHALLENGE_PARAM);
|
|
258
|
+
} catch {
|
|
259
|
+
challenge = null;
|
|
260
|
+
}
|
|
261
|
+
if (challenge === null || !isHandoffChallenge(challenge)) {
|
|
262
|
+
throw new ValidationError({
|
|
263
|
+
message: "That sign-in link has no handoff challenge.",
|
|
264
|
+
action: "Start a native sign-in with `handoffCallbackURL` from `@pithy-sh/auth/src/client/handoff`.",
|
|
265
|
+
detail: "native sign-in start without a well-formed handoff challenge",
|
|
266
|
+
issues: [{ path: ["callbackURL"], message: `carries no well-formed ${HANDOFF_CHALLENGE_PARAM}`, code: "custom" }],
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const headers = new Headers(c.req.raw.headers);
|
|
271
|
+
for (const name of [...headers.keys()]) {
|
|
272
|
+
if (name === "cookie" || name === "origin" || name === "referer" || name.startsWith("sec-fetch-")) {
|
|
273
|
+
headers.delete(name);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
headers.delete("content-length");
|
|
277
|
+
headers.set("content-type", "application/json");
|
|
278
|
+
const signIn = new Request(new URL(`${wiring.config.basePath}/sign-in/social`, c.req.raw.url), {
|
|
279
|
+
method: "POST",
|
|
280
|
+
headers,
|
|
281
|
+
body: JSON.stringify({
|
|
282
|
+
provider: query.provider,
|
|
283
|
+
callbackURL: query.callbackURL,
|
|
284
|
+
...(query.errorCallbackURL === undefined ? {} : { errorCallbackURL: query.errorCallbackURL }),
|
|
285
|
+
}),
|
|
286
|
+
});
|
|
287
|
+
let answer: Response;
|
|
288
|
+
try {
|
|
289
|
+
answer = await instance.handler(await guardErrorCallbackURL(signIn, signIn.url));
|
|
290
|
+
} catch (error) {
|
|
291
|
+
throw apiErrorToPithy(error);
|
|
292
|
+
}
|
|
293
|
+
// Better Auth's own refusal is its own answer, as it is on the catch-all.
|
|
294
|
+
if (!answer.ok) return answer;
|
|
295
|
+
const body: unknown = await answer.json();
|
|
296
|
+
const url = typeof body === "object" && body !== null ? (body as { url?: unknown }).url : undefined;
|
|
297
|
+
if (typeof url !== "string") {
|
|
298
|
+
throw new InternalError({ detail: "the social sign-in answered without an authorization URL" });
|
|
299
|
+
}
|
|
300
|
+
const redirect = new Headers({ location: url, "cache-control": "no-store", "referrer-policy": "no-referrer" });
|
|
301
|
+
for (const line of answer.headers.getSetCookie()) redirect.append("set-cookie", line);
|
|
302
|
+
return new Response(null, { status: 302, headers: redirect });
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** The refusal every failed trade gets. One answer for spent, expired, unknown and a wrong verifier. */
|
|
306
|
+
function handoffInvalid(reason: string): PithyError {
|
|
307
|
+
return new PithyError({
|
|
308
|
+
code: "auth/handoff_invalid",
|
|
309
|
+
status: 400,
|
|
310
|
+
message: "That sign-in link has expired or was already used. Sign in again.",
|
|
311
|
+
detail: `handoff refused: ${reason}`,
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Trade a one-time code and its verifier for the session the code stands for. The code is spent by the attempt
|
|
317
|
+
* whatever the answer, so a wrong verifier gets one guess.
|
|
318
|
+
* Device headers sent with the trade register the device and bind it to the session, as they would on any other
|
|
319
|
+
* native sign-in; the browser that completed the redirect had none to send.
|
|
320
|
+
*/
|
|
321
|
+
export async function exchangeHandoff(c: Ctx, wiring: AuthWiring, body: HandoffExchangeBody): Promise<Response> {
|
|
322
|
+
const db = authDatabase(resolveDb(c.env, wiring.config.database));
|
|
323
|
+
const corr = correlation(c.req.raw.headers);
|
|
324
|
+
const now = new Date();
|
|
325
|
+
const redemption = await redeemHandoff(db, { code: body.code, verifier: body.verifier }, now);
|
|
326
|
+
if (!redemption.ok) {
|
|
327
|
+
await emitHandoffExchanged(c.var.emit, { outcome: "denied", reason: redemption.reason, ...corr });
|
|
328
|
+
throw handoffInvalid(redemption.reason);
|
|
329
|
+
}
|
|
330
|
+
const row = await db
|
|
331
|
+
.selectFrom("pithyAuthSessions")
|
|
332
|
+
.select(["id", "token", "userId", "expiresAt", "deviceId"])
|
|
333
|
+
.where("id", "=", redemption.sessionId)
|
|
334
|
+
.executeTakeFirst();
|
|
335
|
+
const expiresAt = row ? Session.shape.expiresAt.parse(row.expiresAt) : null;
|
|
336
|
+
if (!row || !expiresAt || expiresAt.getTime() <= now.getTime()) {
|
|
337
|
+
await emitHandoffExchanged(c.var.emit, { outcome: "denied", reason: "unknown", ...corr });
|
|
338
|
+
throw handoffInvalid("the session the code stood for has ended");
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const device = parseDeviceMeta(c.req.raw.headers);
|
|
342
|
+
if (device && !row.deviceId) {
|
|
343
|
+
await registerDevice(db, device, { userId: row.userId, lastIp: corr.ip ?? null, now });
|
|
344
|
+
await db.updateTable("pithyAuthSessions").set({ deviceId: device.id }).where("id", "=", row.id).execute();
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
await emitHandoffExchanged(c.var.emit, { outcome: "success", userId: row.userId, sessionId: row.id, ...corr });
|
|
348
|
+
c.header("cache-control", "no-store");
|
|
349
|
+
return c.json({ token: row.token, expiresAt: expiresAt.toISOString() } satisfies HandoffExchangeResponse);
|
|
350
|
+
}
|
package/src/http/middleware.ts
CHANGED
|
@@ -9,16 +9,18 @@ import type { Context, MiddlewareHandler } from "hono";
|
|
|
9
9
|
import type { AuthWiring, ScopeResolver, ScopeResolverSession } from "../capability";
|
|
10
10
|
import { authDatabase } from "../data/tables";
|
|
11
11
|
import type { AuthInstance } from "../instance/auth";
|
|
12
|
-
import { lifecycleRefusalFor, noteRefusal, noticedRefusal } from "../lifecycle/enforce";
|
|
12
|
+
import { lifecycleRefusalFor, noteRefusal, noticedRefusal, suspendedHolder } from "../lifecycle/enforce";
|
|
13
13
|
import { LifecycleColumns } from "../lifecycle/state";
|
|
14
|
+
import { dispatchedAuth } from "../mcp/dispatch";
|
|
14
15
|
import { withResignedCredentials } from "./credentialResign";
|
|
15
16
|
import { getAuthInstance, resolveDb } from "./resolve";
|
|
16
17
|
|
|
17
18
|
/**
|
|
18
19
|
* The session-resolution middleware: it fills core's `AuthContext` seam (`c.var.auth`) for every
|
|
19
|
-
* request that carries a credential — a bearer token
|
|
20
|
+
* request that carries a credential — a bearer token, a session cookie, or an API key in `x-api-key` when
|
|
21
|
+
* the adopter composes `apiKey({ enableSessionForAPIKeys: true })`. Better Auth resolves all three
|
|
20
22
|
* transparently (the bearer plugin rewrites the header into the session cookie), so one `getSession`
|
|
21
|
-
* call covers mobile and
|
|
23
|
+
* call covers mobile, web and a machine. A credential-less request stays anonymous (no instance build, no D1 hit).
|
|
22
24
|
* Resolution never throws — an invalid credential simply leaves `auth` null for `requireAuth` to reject.
|
|
23
25
|
*/
|
|
24
26
|
/** The session's authentication instant when it is a real `Date`, else `null`. Never anything else. */
|
|
@@ -67,10 +69,34 @@ async function resolvedScopes(
|
|
|
67
69
|
return parsed.data;
|
|
68
70
|
}
|
|
69
71
|
|
|
72
|
+
/**
|
|
73
|
+
* The header Better Auth's `apiKey()` plugin reads a key from by default. With `enableSessionForAPIKeys` on, the plugin
|
|
74
|
+
* answers `getSession` for a request carrying one, so a key stands for its owner's session. It is the default
|
|
75
|
+
* rather than whatever an adopter configured, because the plugin does not expose its options: an adopter who renames
|
|
76
|
+
* the header keeps `x-api-key` for keys meant to reach this middleware.
|
|
77
|
+
*/
|
|
78
|
+
export const API_KEY_HEADER = "x-api-key";
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Whether a request carries anything `getSession` could resolve: a bearer token, a session cookie, or an API key. A
|
|
82
|
+
* request with none stays anonymous without building the instance or reading D1.
|
|
83
|
+
*/
|
|
84
|
+
export function carriesCredential(headers: Headers): boolean {
|
|
85
|
+
return headers.has("authorization") || headers.has("cookie") || headers.has(API_KEY_HEADER);
|
|
86
|
+
}
|
|
87
|
+
|
|
70
88
|
export function createSessionMiddleware(wiring: AuthWiring): PithyMiddleware {
|
|
71
89
|
return (app) => {
|
|
72
90
|
app.use("*", async (c, next) => {
|
|
73
|
-
|
|
91
|
+
// A tool call the MCP endpoint dispatched to a route. Its caller was verified there, against the
|
|
92
|
+
// token, the consent, the session and the account's standing, and it arrives with no credential of its own:
|
|
93
|
+
// the identity rides beside the request in process, where nothing on the network can put one.
|
|
94
|
+
const dispatched = dispatchedAuth(c.req.raw);
|
|
95
|
+
if (dispatched !== undefined) {
|
|
96
|
+
c.set("auth", dispatched);
|
|
97
|
+
return await next();
|
|
98
|
+
}
|
|
99
|
+
if (!carriesCredential(c.req.raw.headers)) return await next();
|
|
74
100
|
// A credential signed under a session secret this deployment has since rotated is re-signed under the
|
|
75
101
|
// current one before anything reads it (#602), and the re-signed one rides back on the response. A
|
|
76
102
|
// failure building the instance is not this middleware's to raise, so it is left to the routes.
|
|
@@ -103,7 +129,7 @@ async function resolveSession(c: Context<PithyHonoEnv>, wiring: AuthWiring, inst
|
|
|
103
129
|
// capability's own guard raises the refusal itself, with its code; see `requireAuth` below.
|
|
104
130
|
const refusal = await standingRefusal(c, wiring, session.user);
|
|
105
131
|
if (refusal) {
|
|
106
|
-
noteRefusal(c, refusal);
|
|
132
|
+
noteRefusal(c, refusal, { userId: session.user.id, sessionId: session.session.id });
|
|
107
133
|
return;
|
|
108
134
|
}
|
|
109
135
|
// Before the context is built, so a resolver sees the request exactly as it arrived and the
|
|
@@ -202,3 +228,46 @@ export function requireAuth(): MiddlewareHandler<PithyHonoEnv> {
|
|
|
202
228
|
await next();
|
|
203
229
|
};
|
|
204
230
|
}
|
|
231
|
+
|
|
232
|
+
/** Whose account a request may act on as its own holder: the signed-in account, or a suspended one's. */
|
|
233
|
+
export interface AccountHolder {
|
|
234
|
+
/** The account. */
|
|
235
|
+
readonly userId: string;
|
|
236
|
+
/** The session the request presented. */
|
|
237
|
+
readonly sessionId: string;
|
|
238
|
+
/** Whether the account is suspended — every other route refuses it. */
|
|
239
|
+
readonly suspended: boolean;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* The account this request's credential opens, for a route a **suspended** account may still use — and there is
|
|
244
|
+
* exactly one, deleting it (#622). The App Store and Google Play require that a person can delete their account
|
|
245
|
+
* from inside the app, and a suspension is no reason to keep somebody who wants to leave.
|
|
246
|
+
*
|
|
247
|
+
* A deleted account is not admitted: there is nothing left to delete. Neither is a request whose standing could
|
|
248
|
+
* not be checked.
|
|
249
|
+
*/
|
|
250
|
+
export function accountHolder(c: Context<PithyHonoEnv>): AccountHolder | null {
|
|
251
|
+
if (c.var.auth) return { userId: c.var.auth.userId, sessionId: c.var.auth.sessionId, suspended: false };
|
|
252
|
+
const held = suspendedHolder(c);
|
|
253
|
+
return held ? { ...held, suspended: true } : null;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* The gate for that route: `requireAuth()`, with a suspended account's genuine credential admitted. Everything
|
|
258
|
+
* `requireAuth()` refuses otherwise, it refuses the same way — a deleted account with its code, anything else
|
|
259
|
+
* with `auth/invalid_token`.
|
|
260
|
+
*/
|
|
261
|
+
export function requireAccountHolder(): MiddlewareHandler<PithyHonoEnv> {
|
|
262
|
+
return async (c, next) => {
|
|
263
|
+
if (!accountHolder(c)) {
|
|
264
|
+
const refusal = noticedRefusal(c);
|
|
265
|
+
if (refusal) throw refusal;
|
|
266
|
+
throw new UnauthorizedError({
|
|
267
|
+
message: "Authentication required.",
|
|
268
|
+
action: "Sign in and retry with a valid session or bearer token.",
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
await next();
|
|
272
|
+
};
|
|
273
|
+
}
|