@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/audit/actions.ts
CHANGED
|
@@ -97,6 +97,19 @@ export const AuthAuditActions = {
|
|
|
97
97
|
* behind it at all, not the row a cascade wrote.
|
|
98
98
|
*/
|
|
99
99
|
oauthUnlinked: "auth/oauth_unlinked",
|
|
100
|
+
/**
|
|
101
|
+
* A redirect sign-in ended on a native app's deep link, and the session it made was left there as a one-time
|
|
102
|
+
* code instead of a cookie. Attributed to the account; `sessionId` names the session the code stands for. Outcome
|
|
103
|
+
* `denied`, severity `warning`, when the deep link carried no challenge to bind a code to: no code is issued and
|
|
104
|
+
* the session is deleted.
|
|
105
|
+
*/
|
|
106
|
+
handoffIssued: "auth/handoff_issued",
|
|
107
|
+
/**
|
|
108
|
+
* A native app traded a one-time code for its session. Outcome `denied`, severity `warning`, for a code that was
|
|
109
|
+
* spent, expired, never issued or presented with the wrong verifier, with which of those in `metadata.reason` as
|
|
110
|
+
* `expired`, `unknown` or `mismatch`.
|
|
111
|
+
*/
|
|
112
|
+
handoffExchanged: "auth/handoff_exchanged",
|
|
100
113
|
/** A device was registered or updated from sign-in metadata. */
|
|
101
114
|
deviceRegistered: "auth/device_registered",
|
|
102
115
|
/** A device was revoked (its session(s) signed out). */
|
|
@@ -144,6 +157,8 @@ export const AuthAuditActions = {
|
|
|
144
157
|
adminUserRead: "auth/admin_user_read",
|
|
145
158
|
/** The device registry was walked from the management surface. */
|
|
146
159
|
adminDevicesListed: "auth/admin_devices_listed",
|
|
160
|
+
/** The verification ledger was read from the management surface (#829): counts and rows over a window. */
|
|
161
|
+
adminVerificationsListed: "auth/admin_verifications_listed",
|
|
147
162
|
/** One named session was revoked from the management surface. */
|
|
148
163
|
adminSessionRevoked: "auth/admin_session_revoked",
|
|
149
164
|
/** Every session a user held was revoked from the management surface — signed out everywhere. */
|
|
@@ -159,6 +174,12 @@ export const AuthAuditActions = {
|
|
|
159
174
|
*
|
|
160
175
|
* The dashboard's own `customer/user_suspended` and `customer/user_restored` are the client side of the
|
|
161
176
|
* same events, recorded where the operator pressed the button.
|
|
177
|
+
*
|
|
178
|
+
* **The suspend and reinstate routes record every call under the same action (#621)**, the ones the
|
|
179
|
+
* transition did not write included: a refusal as `denied` with its code in `metadata.code`, and a
|
|
180
|
+
* reinstatement that found nothing to lift as a `success` with `metadata.changed: false`. A restated
|
|
181
|
+
* suspension is the transition's own event, with `metadata.updated: true`. So one filter on the action
|
|
182
|
+
* finds every attempt on one account. `../lifecycle/audited.ts` writes the route's half.
|
|
162
183
|
*/
|
|
163
184
|
|
|
164
185
|
/** An account was suspended from the management surface. Carries the reason and any end date. */
|
|
@@ -167,12 +188,49 @@ export const AuthAuditActions = {
|
|
|
167
188
|
adminUserReinstated: "auth/admin_user_reinstated",
|
|
168
189
|
/** An account was deleted from the management surface, with its purge window starting now. */
|
|
169
190
|
adminUserSoftDeleted: "auth/admin_user_soft_deleted",
|
|
191
|
+
/**
|
|
192
|
+
* An account was deleted from the management surface with no window — its purge starts now (#622). Also
|
|
193
|
+
* written when a hard deletion brings an already-deleted account's purge forward, with
|
|
194
|
+
* `metadata.broughtForward: true`. Never written by omission: the route reaches it only for `mode: "hard"`.
|
|
195
|
+
*/
|
|
196
|
+
adminUserHardDeleted: "auth/admin_user_hard_deleted",
|
|
170
197
|
/** A deleted account was restored inside its purge window, from the management surface. */
|
|
171
198
|
adminUserRestored: "auth/admin_user_restored",
|
|
172
199
|
/** A deleted account's data was erased. Recorded once, when the last purge step has run. */
|
|
173
200
|
adminUserPurged: "auth/admin_user_purged",
|
|
201
|
+
/**
|
|
202
|
+
* One purge step answered for a capability's rows: erased them, or kept them under a stated basis (#814).
|
|
203
|
+
* `metadata.step` names the capability and `metadata.disposition` says which. The erasure attestation cites it
|
|
204
|
+
* by event id and chain position (#823).
|
|
205
|
+
*/
|
|
206
|
+
adminUserPurgeStep: "auth/admin_user_purge_step",
|
|
207
|
+
/**
|
|
208
|
+
* A purge gave up at the step `metadata.step` names, until the next daily pass starts it again (#823). The
|
|
209
|
+
* erasure attestation cites it, and names every failed purge in a period.
|
|
210
|
+
*/
|
|
211
|
+
adminUserPurgeFailed: "auth/admin_user_purge_failed",
|
|
174
212
|
/** The account's own holder deleted their account. Always a soft deletion, on the configured window. */
|
|
175
213
|
userSelfDeleted: "auth/user_self_deleted",
|
|
214
|
+
/**
|
|
215
|
+
* Everything the kit holds about one account was exported from the management surface — an access request
|
|
216
|
+
* answered (#622). A **disclosure**, and the largest one on this surface: it carries every composed
|
|
217
|
+
* capability's rows about the person. Recorded with the caller, the reason they gave, and which capabilities
|
|
218
|
+
* answered; never with any of the data.
|
|
219
|
+
*/
|
|
220
|
+
adminUserExported: "auth/admin_user_exported",
|
|
221
|
+
/**
|
|
222
|
+
* A user let an MCP client act as them in this application. The one decision the consent screen asks,
|
|
223
|
+
* recorded with the client's id and the redirect it will send tokens to — the thing that identifies it, since
|
|
224
|
+
* its name is whatever it said. Asking again is a new consent and a new row.
|
|
225
|
+
*/
|
|
226
|
+
mcpGrantApproved: "auth/mcp_grant_approved",
|
|
227
|
+
/** A user refused an MCP client on the consent screen. */
|
|
228
|
+
mcpGrantDenied: "auth/mcp_grant_denied",
|
|
229
|
+
/**
|
|
230
|
+
* A user revoked an MCP client from their connected applications. Its consent and refresh tokens are gone
|
|
231
|
+
* and its next call is refused. Revocation is the only narrowing the user has, so it is recorded like a grant.
|
|
232
|
+
*/
|
|
233
|
+
mcpGrantRevoked: "auth/mcp_grant_revoked",
|
|
176
234
|
} as const;
|
|
177
235
|
|
|
178
236
|
/** One of the auth audit action codes. */
|
package/src/audit/emit.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
|
|
5
5
|
import { APIError } from "better-auth/api";
|
|
6
6
|
import { z } from "zod";
|
|
7
|
+
import type { HandoffRefusal } from "../token/handoff";
|
|
7
8
|
import { type AuthAuditAction, AuthAuditActions } from "./actions";
|
|
8
9
|
import type { AuthEmailDelivery, EndedSession } from "./evidence";
|
|
9
10
|
|
|
@@ -371,11 +372,13 @@ export async function emitControlPlaneAction(
|
|
|
371
372
|
userAgent?: string;
|
|
372
373
|
requestId?: string;
|
|
373
374
|
metadata?: Record<string, unknown>;
|
|
375
|
+
/** `success` unless the call was refused (`denied`) or broke (`failure`) — #621 records both. */
|
|
376
|
+
outcome?: "success" | "denied" | "failure";
|
|
374
377
|
},
|
|
375
378
|
): Promise<void> {
|
|
376
379
|
await safeEmit(emit, {
|
|
377
380
|
action: event.action,
|
|
378
|
-
outcome: "success",
|
|
381
|
+
outcome: event.outcome ?? "success",
|
|
379
382
|
actorType: "control-plane",
|
|
380
383
|
actorId: event.subject,
|
|
381
384
|
resourceType: event.resourceType,
|
|
@@ -552,6 +555,68 @@ export async function emitProviderChangeNotFresh(
|
|
|
552
555
|
});
|
|
553
556
|
}
|
|
554
557
|
|
|
558
|
+
/**
|
|
559
|
+
* Emit a `handoff_issued` event: a redirect sign-in's session left on a deep link as a one-time code, or, denied,
|
|
560
|
+
* a sign-in whose deep link carried no challenge, or a magic link to a custom scheme, so no code was issued.
|
|
561
|
+
*/
|
|
562
|
+
export async function emitHandoffIssued(
|
|
563
|
+
emit: AuditEmit,
|
|
564
|
+
context: (
|
|
565
|
+
| { outcome: "success" }
|
|
566
|
+
/** `unbound`: the link carried no challenge to bind a code to. `scheme`: a magic link to a custom scheme. */
|
|
567
|
+
| { outcome: "denied"; reason: "unbound" | "scheme" }
|
|
568
|
+
) & {
|
|
569
|
+
userId: string;
|
|
570
|
+
sessionId: string;
|
|
571
|
+
ip?: string;
|
|
572
|
+
userAgent?: string;
|
|
573
|
+
},
|
|
574
|
+
): Promise<void> {
|
|
575
|
+
await safeEmit(emit, {
|
|
576
|
+
action: AuthAuditActions.handoffIssued,
|
|
577
|
+
outcome: context.outcome,
|
|
578
|
+
...(context.outcome === "denied" ? { severity: "warning" as const, metadata: { reason: context.reason } } : {}),
|
|
579
|
+
actorType: "user",
|
|
580
|
+
actorId: context.userId,
|
|
581
|
+
sessionId: context.sessionId,
|
|
582
|
+
ip: context.ip,
|
|
583
|
+
userAgent: context.userAgent,
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* Emit a `handoff_exchanged` event. A traded code is attributed to the account it signed in; a refused one is
|
|
589
|
+
* anonymous, because the code named nobody anybody can trust.
|
|
590
|
+
*/
|
|
591
|
+
export async function emitHandoffExchanged(
|
|
592
|
+
emit: AuditEmit,
|
|
593
|
+
context:
|
|
594
|
+
| { outcome: "success"; userId: string; sessionId: string; ip?: string; userAgent?: string }
|
|
595
|
+
| { outcome: "denied"; reason: HandoffRefusal; ip?: string; userAgent?: string },
|
|
596
|
+
): Promise<void> {
|
|
597
|
+
if (context.outcome === "success") {
|
|
598
|
+
await safeEmit(emit, {
|
|
599
|
+
action: AuthAuditActions.handoffExchanged,
|
|
600
|
+
outcome: "success",
|
|
601
|
+
actorType: "user",
|
|
602
|
+
actorId: context.userId,
|
|
603
|
+
sessionId: context.sessionId,
|
|
604
|
+
ip: context.ip,
|
|
605
|
+
userAgent: context.userAgent,
|
|
606
|
+
});
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
await safeEmit(emit, {
|
|
610
|
+
action: AuthAuditActions.handoffExchanged,
|
|
611
|
+
outcome: "denied",
|
|
612
|
+
severity: "warning",
|
|
613
|
+
actorType: "anonymous",
|
|
614
|
+
ip: context.ip,
|
|
615
|
+
userAgent: context.userAgent,
|
|
616
|
+
metadata: { reason: context.reason },
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
|
|
555
620
|
/** A blocked/failed auth attempt — recorded as `denied` (first-class). */
|
|
556
621
|
export async function emitDenied(
|
|
557
622
|
emit: AuditEmit,
|
package/src/audit/evidence.ts
CHANGED
|
@@ -73,10 +73,14 @@ export function sessionEndedDuring(requestContext: unknown): EndedSession | null
|
|
|
73
73
|
* error's text is the one thing in reach that nobody has vetted for what it might carry.
|
|
74
74
|
*/
|
|
75
75
|
export type AuthEmailDelivery =
|
|
76
|
-
/**
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
76
|
+
/**
|
|
77
|
+
* Handed to the email seam, which wrote a job row for it. A send is what the trail may claim. `jobId` is that
|
|
78
|
+
* row's, for the verification ledger to join on (#829); optional, because a seam a test stands in for may not
|
|
79
|
+
* say.
|
|
80
|
+
*/
|
|
81
|
+
| { readonly delivery: "queued"; readonly jobId?: string }
|
|
82
|
+
/** The capability withheld it, correctly, and named why. Not a fault, and not a send. Its row is `jobId`. */
|
|
83
|
+
| { readonly delivery: "withheld"; readonly reason: string; readonly jobId?: string }
|
|
80
84
|
/** The seam itself failed. Nothing was queued and something is wrong with this deployment. */
|
|
81
85
|
| { readonly delivery: "failed"; readonly reason: string };
|
|
82
86
|
|
package/src/capability.ts
CHANGED
|
@@ -2,31 +2,47 @@
|
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
4
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
5
|
+
import { composedAuditEmit } from "@pithy-sh/core/src/audit/composed";
|
|
6
|
+
import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
|
|
5
7
|
import type { Capability, PithyHonoEnv, PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
|
|
6
8
|
import { defineCapability } from "@pithy-sh/core/src/capability/capability";
|
|
9
|
+
import { type PurgeStep, purgeSteps } from "@pithy-sh/core/src/capability/purge";
|
|
7
10
|
import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
8
11
|
import type { EmailCapability } from "@pithy-sh/email/src/capability";
|
|
9
12
|
import { isEmailCapability } from "@pithy-sh/email/src/capability";
|
|
10
|
-
import { isTurnstileCapability } from "@pithy-sh/turnstile/src/capability";
|
|
11
|
-
import {
|
|
13
|
+
import { isTurnstileCapability, type TurnstileCapability } from "@pithy-sh/turnstile/src/capability";
|
|
14
|
+
import {
|
|
15
|
+
TURNSTILE_LOGIN_ACTION,
|
|
16
|
+
type TurnstileMode,
|
|
17
|
+
type TurnstileTokenSource,
|
|
18
|
+
} from "@pithy-sh/turnstile/src/config/config";
|
|
12
19
|
import type { Context } from "hono";
|
|
13
20
|
import { z } from "zod";
|
|
21
|
+
import { AuthAuditActions } from "./audit/actions";
|
|
14
22
|
import type { AuthClientProjection } from "./client/projection";
|
|
15
23
|
import { authTables } from "./data/tables";
|
|
24
|
+
import { baseURLResolver } from "./http/baseUrl";
|
|
16
25
|
import { publishSameOrigin } from "./http/csrf";
|
|
17
26
|
import { registerDevLoginRoute } from "./http/devLoginRoute";
|
|
18
27
|
import { authAdminRoutes } from "./http/guards";
|
|
19
28
|
import { createSessionMiddleware } from "./http/middleware";
|
|
20
29
|
import { createRateLimitMiddleware } from "./http/rateLimit";
|
|
30
|
+
import { getAuthInstance } from "./http/resolve";
|
|
21
31
|
import { createAuthRoutes } from "./http/routes";
|
|
22
32
|
import type { GithubUserInfoResolver } from "./instance/githubUserInfo";
|
|
23
33
|
import { AuthPlugin, assertAdditivePlugins } from "./instance/plugins";
|
|
24
34
|
import { authSecretsRegistryFor, inapplicableProviderSecrets } from "./instance/secrets";
|
|
35
|
+
import { authErasureRecords } from "./lifecycle/erasure";
|
|
25
36
|
import type { UserLifecycleHooks } from "./lifecycle/hooks";
|
|
37
|
+
import type { McpHost, McpWiring } from "./mcp/host";
|
|
38
|
+
import { isMcpCapability } from "./mcp/marker";
|
|
26
39
|
import { AUTH_MIGRATION_ORDER } from "./migrations/0001_init";
|
|
27
40
|
import { authPluginPlan } from "./migrations/pluginTables";
|
|
28
41
|
import { AUTH_MIGRATIONS } from "./migrations/set";
|
|
29
42
|
import { type AuthPeer, authPeer } from "./peer";
|
|
43
|
+
import { AUTH_PROCESSING } from "./processing/activities";
|
|
44
|
+
import { authAddressOf, authPurgeContribution } from "./purge/contribution";
|
|
45
|
+
import { authWorkflows } from "./purge/specs";
|
|
30
46
|
import { authDevSessionSeed } from "./seeds/devSession";
|
|
31
47
|
import { authExampleSeed } from "./seeds/example";
|
|
32
48
|
import { PACKAGE_NAME, PACKAGE_VERSION } from "./version.generated";
|
|
@@ -141,6 +157,12 @@ export const AuthConfig = z
|
|
|
141
157
|
.describe(
|
|
142
158
|
"How many days a deleted account waits before its data is erased. Inside the window it cannot sign in and can be restored; after it, the purge erases its rows from every capability that holds them. Defaults to 30.",
|
|
143
159
|
),
|
|
160
|
+
restoreUrl: z
|
|
161
|
+
.url({ protocol: /^https?$/ })
|
|
162
|
+
.optional()
|
|
163
|
+
.describe(
|
|
164
|
+
"Where a person whose account is deleted asks for it back inside the window: an http(s) page of yours. Carried in the deletion-scheduled mail as its restore button, so it must be a web address — a tracked click redirects only to one. Absent, the mail still tells them to reply before the purge date.",
|
|
165
|
+
),
|
|
144
166
|
})
|
|
145
167
|
.prefault({})
|
|
146
168
|
.describe(
|
|
@@ -177,6 +199,19 @@ export const AuthConfig = z
|
|
|
177
199
|
export type AuthConfig = z.output<typeof AuthConfig>;
|
|
178
200
|
export type AuthConfigInput = z.input<typeof AuthConfig>;
|
|
179
201
|
|
|
202
|
+
/** The widget the sign-in routes are gated with, and where the gate reads its token. */
|
|
203
|
+
export interface TurnstileLoginGate {
|
|
204
|
+
mode: TurnstileMode;
|
|
205
|
+
/** The `token` source turnstile's config names, which its client projection hands a screen. */
|
|
206
|
+
token: TurnstileTokenSource;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** The sign-in gate a composed turnstile asks for, or `undefined` when none is composed or sign-in is unprotected. */
|
|
210
|
+
export function turnstileLoginGate(capability: TurnstileCapability | undefined): TurnstileLoginGate | undefined {
|
|
211
|
+
const mode = capability?.turnstileConfig.protect[TURNSTILE_LOGIN_ACTION];
|
|
212
|
+
return mode ? { mode, token: capability.turnstileConfig.token } : undefined;
|
|
213
|
+
}
|
|
214
|
+
|
|
180
215
|
/**
|
|
181
216
|
* The runtime wiring the middleware and routes close over. `config` is known at `auth()` call time;
|
|
182
217
|
* `emailConfig` and `turnstile` are filled by `compose` from the composed peer capabilities, before
|
|
@@ -189,7 +224,7 @@ export interface AuthWiring {
|
|
|
189
224
|
/** The email capability's bound enqueue seam — how magic-link/OTP are delivered. Set by `compose`. */
|
|
190
225
|
enqueueEmail: EmailCapability["enqueue"] | undefined;
|
|
191
226
|
/** The turnstile login gate, when the turnstile capability is composed. Set by `compose`. */
|
|
192
|
-
turnstile:
|
|
227
|
+
turnstile: TurnstileLoginGate | undefined;
|
|
193
228
|
/**
|
|
194
229
|
* The adopter's session-revoked listener, or absent. See {@link AuthOptions.onSessionRevoked}.
|
|
195
230
|
*
|
|
@@ -209,6 +244,22 @@ export interface AuthWiring {
|
|
|
209
244
|
* Optional on the wiring for the reason `onSessionRevoked` is: no hook is the ordinary composition.
|
|
210
245
|
*/
|
|
211
246
|
lifecycleHooks?: UserLifecycleHooks | undefined;
|
|
247
|
+
/**
|
|
248
|
+
* Every composed capability's purge step for a user, auth's own among them, in composition order. Filled
|
|
249
|
+
* by `compose`; the export route reads every capability's contribution from it, and the purge runs it.
|
|
250
|
+
* Optional on the wiring for the reason `onSessionRevoked` is: a harness that builds this by hand composes none.
|
|
251
|
+
*/
|
|
252
|
+
purgeSteps?: readonly PurgeStep[] | undefined;
|
|
253
|
+
/**
|
|
254
|
+
* The MCP capability's endpoint and consent screen, when one is composed beside this one. Set by
|
|
255
|
+
* `compose`; the instance then carries the OAuth provider that mints its tokens.
|
|
256
|
+
*/
|
|
257
|
+
mcp?: McpWiring | undefined;
|
|
258
|
+
/**
|
|
259
|
+
* Every capability composed beside this one, auth among them. Set by `compose`; a rotation announces itself to
|
|
260
|
+
* each one's `sessionRotated` through core. Optional on the wiring for the reason `onSessionRevoked` is.
|
|
261
|
+
*/
|
|
262
|
+
composed?: readonly Capability[] | undefined;
|
|
212
263
|
}
|
|
213
264
|
|
|
214
265
|
/** The session a {@link ScopeResolver} is asked about — the one Better Auth just resolved for this request. */
|
|
@@ -220,7 +271,7 @@ export interface ScopeResolverSession {
|
|
|
220
271
|
}
|
|
221
272
|
|
|
222
273
|
/**
|
|
223
|
-
* Decide what this request's caller is, and answer the scopes that attests to
|
|
274
|
+
* Decide what this request's caller is, and answer the scopes that attests to.
|
|
224
275
|
*
|
|
225
276
|
* Called by the session middleware on every authenticated request, after Better Auth has resolved the
|
|
226
277
|
* session and before any route runs. What it returns becomes `AuthContext.scopes`. It reads the **request**,
|
|
@@ -284,7 +335,7 @@ export type AuthOptions = AuthConfigInput &
|
|
|
284
335
|
*/
|
|
285
336
|
onSessionRevoked?: SessionRevokedListener;
|
|
286
337
|
/**
|
|
287
|
-
* Decide, per request, what this request's caller is — and so which scope gates it opens
|
|
338
|
+
* Decide, per request, what this request's caller is — and so which scope gates it opens.
|
|
288
339
|
*
|
|
289
340
|
* `leaderboard:submit`, `rating:record`, `leaderboard:admin` and `ledger:admin` are **attestations about
|
|
290
341
|
* the caller, not permissions granted to the user**: each says *this write came from the adopter's own
|
|
@@ -309,15 +360,27 @@ export interface AuthCapability extends Capability {
|
|
|
309
360
|
authConfig: AuthConfig;
|
|
310
361
|
/**
|
|
311
362
|
* The adopter's account-lifecycle hooks, as `auth()` was handed them. Read by whatever runs a transition
|
|
312
|
-
* outside a request this capability serves — the purge Workflow
|
|
363
|
+
* outside a request this capability serves — the purge Workflow fires `onUserPurged` through it.
|
|
313
364
|
*/
|
|
314
365
|
lifecycleHooks: UserLifecycleHooks;
|
|
366
|
+
/**
|
|
367
|
+
* Every composed capability's purge step for a user, auth's own among them, in composition order. Empty
|
|
368
|
+
* until `compose` has run. Read by the purge Workflow, which runs in the Worker that composed it.
|
|
369
|
+
*/
|
|
370
|
+
purgeSteps: readonly PurgeStep[];
|
|
371
|
+
/**
|
|
372
|
+
* The audit recorder for code with no request, over one run's env — the composed audit capability's, or the
|
|
373
|
+
* no-op. Read by the purge Workflow, which owes the trail its `auth/admin_user_purged`.
|
|
374
|
+
*/
|
|
375
|
+
auditFor: (env: Record<string, unknown>) => AuditEmit;
|
|
315
376
|
/**
|
|
316
377
|
* What a capability composed beside this one reads an account through — `matchmaking`, `support`,
|
|
317
378
|
* `testers`. Found in their `compose` hooks, so none of them imports this package and a project without
|
|
318
|
-
* auth bundles them
|
|
379
|
+
* auth bundles them. See `peer.ts`.
|
|
319
380
|
*/
|
|
320
381
|
authPeer: AuthPeer;
|
|
382
|
+
/** What the MCP capability composed beside this one reads. See `mcp/host.ts`. */
|
|
383
|
+
mcpHost: McpHost;
|
|
321
384
|
}
|
|
322
385
|
|
|
323
386
|
/**
|
|
@@ -385,7 +448,7 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
385
448
|
// sign-in this product promises and what the control-plane seam verifies against, so a list naming one
|
|
386
449
|
// of them is refused here by name rather than silently redefining a route at request time — and so is a
|
|
387
450
|
// plugin that answers a refused social sign-in somewhere `http/providerRefusal` cannot collapse it,
|
|
388
|
-
// because composing that one would leave the guarantee stated and not held
|
|
451
|
+
// because composing that one would leave the guarantee stated and not held.
|
|
389
452
|
assertAdditivePlugins(resolved.plugins);
|
|
390
453
|
// And the tables those plugins imply, derived now so a collision is a config error at `auth()` rather
|
|
391
454
|
// than a half-applied migration against a database with no transactional DDL.
|
|
@@ -398,7 +461,13 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
398
461
|
onSessionRevoked,
|
|
399
462
|
resolveScopes,
|
|
400
463
|
lifecycleHooks,
|
|
464
|
+
purgeSteps: [],
|
|
401
465
|
};
|
|
466
|
+
// Filled by `compose`, read by the purge Workflow through the capability and by the export route through the
|
|
467
|
+
// wiring. One array, so both read the same steps.
|
|
468
|
+
const steps: PurgeStep[] = [];
|
|
469
|
+
wiring.purgeSteps = steps;
|
|
470
|
+
let composition: readonly Capability[] = [];
|
|
402
471
|
|
|
403
472
|
// Tier-1 edge rate limiter, contributed as middleware so it runs before session resolution.
|
|
404
473
|
const rateLimitMiddleware: PithyMiddleware = (app) => {
|
|
@@ -410,18 +479,18 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
410
479
|
// The package this capability ships in and the version it ships at, both stamped by
|
|
411
480
|
// `scripts/stampVersions.ts` — a Worker cannot read its own package.json. Reported per capability by
|
|
412
481
|
// the control-plane manifest, and reported together: a release feed is keyed by package name, so the
|
|
413
|
-
// version alone leaves a client guessing the key
|
|
482
|
+
// version alone leaves a client guessing the key.
|
|
414
483
|
version: PACKAGE_VERSION,
|
|
415
484
|
package: PACKAGE_NAME,
|
|
416
485
|
config: AuthConfig,
|
|
417
486
|
dependsOn: ["secrets", "email"],
|
|
418
487
|
// Whether anything will ever put a string in `AuthContext.scopes` — only when the adopter supplied a
|
|
419
|
-
// resolver. `pithy doctor` reads it against every composed capability's `scopeGates
|
|
488
|
+
// resolver. `pithy doctor` reads it against every composed capability's `scopeGates`.
|
|
420
489
|
providesScopes: resolveScopes !== undefined,
|
|
421
490
|
// Built from the config, so the session secret's overlap is this composition's session lifetime and its
|
|
422
|
-
// period is the one the adopter asked for, if any
|
|
491
|
+
// period is the one the adopter asked for, if any.
|
|
423
492
|
secretRegistry: authSecretsRegistryFor(resolved),
|
|
424
|
-
// And which of those four credentials this composition cannot reach
|
|
493
|
+
// And which of those four credentials this composition cannot reach. A provider that is off
|
|
425
494
|
// has no code path that reads its pair, so `pithy doctor` listing it as outstanding re-raised a
|
|
426
495
|
// settled question on every run. Declared rather than inferred: the config key and the secret name
|
|
427
496
|
// are spelled alike by coincidence, and this is the only place that holds both.
|
|
@@ -453,10 +522,29 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
453
522
|
// one. A project that composes no plugins contributes exactly what it did before.
|
|
454
523
|
// Every kit migration, from one definition — see `migrations/set.ts` for why it is not written
|
|
455
524
|
// out here. Appended, never folded into `0001`: this capability has shipped, so that migration is
|
|
456
|
-
// history and re-shaping it would re-shape a database somebody is already running
|
|
525
|
+
// history and re-shaping it would re-shape a database somebody is already running.
|
|
457
526
|
migrations: { ...AUTH_MIGRATIONS, ...pluginPlan.migrations },
|
|
458
527
|
},
|
|
459
528
|
},
|
|
529
|
+
// What erasing a person means for the `pithy_auth_*` tables, and what exporting them hands back.
|
|
530
|
+
purge: [authPurgeContribution(resolved.database, pluginPlan.userTables)],
|
|
531
|
+
processing: AUTH_PROCESSING,
|
|
532
|
+
// How a purge's record is read back for the control plane's erasure attestation.
|
|
533
|
+
erasureRecords: authErasureRecords(resolved.database),
|
|
534
|
+
// The soft-delete window this config declares. A Worker's `retention` block may replace it.
|
|
535
|
+
purgeWindow: { subject: "user", days: resolved.retention.purgeAfterDays },
|
|
536
|
+
// The lifecycle transitions the erasure record does not name, so the retention floor keeps them too.
|
|
537
|
+
lifecycleAuditActions: [
|
|
538
|
+
AuthAuditActions.adminUserSuspended,
|
|
539
|
+
AuthAuditActions.adminUserReinstated,
|
|
540
|
+
AuthAuditActions.adminUserRestored,
|
|
541
|
+
],
|
|
542
|
+
// An account's address, for a capability that keeps state by address, such as email suppressing an address when
|
|
543
|
+
// its owner withdraws marketing consent. Read on demand, never carried.
|
|
544
|
+
addressOf: authAddressOf(resolved.database),
|
|
545
|
+
// The purge of one account, and the daily pass that starts every due one. Both hosted by the adopter's own
|
|
546
|
+
// Worker, because a purge runs every composed capability's contribution — see `purge/specs.ts`.
|
|
547
|
+
workflows: authWorkflows,
|
|
460
548
|
compose: ({ capabilities }) => {
|
|
461
549
|
const email = capabilities.find(isEmailCapability);
|
|
462
550
|
if (!email) {
|
|
@@ -467,9 +555,7 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
467
555
|
}
|
|
468
556
|
wiring.enqueueEmail = email.enqueue;
|
|
469
557
|
// Auto-wire turnstile onto the login routes when it is composed (Jim's requirement: zero config).
|
|
470
|
-
|
|
471
|
-
const loginMode = turnstileCap?.turnstileConfig.protect[TURNSTILE_LOGIN_ACTION];
|
|
472
|
-
wiring.turnstile = loginMode ? { mode: loginMode } : undefined;
|
|
558
|
+
wiring.turnstile = turnstileLoginGate(capabilities.find(isTurnstileCapability));
|
|
473
559
|
// And the one collision `auth()` could not see. A plugin's tables carry the plugin's own names —
|
|
474
560
|
// `organization`, `member`, `invitation` — with no `pithy_auth_` prefix to keep them out of an
|
|
475
561
|
// adopter's way, because they are the adopter's tables now. `composeDatabases` catches two
|
|
@@ -478,6 +564,12 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
478
564
|
// Refused at boot, naming both sides: the alternative is a `create table` that fails halfway
|
|
479
565
|
// through `pithy migrate`, or two capabilities quietly reading and writing one table.
|
|
480
566
|
assertPluginTablesUnclaimed(capabilities, resolved.database, pluginPlan.extensions);
|
|
567
|
+
// Every composed capability's purge step, auth's own among them, for the export route and the purge.
|
|
568
|
+
steps.splice(0, steps.length, ...purgeSteps(capabilities, "user"));
|
|
569
|
+
// An agent surface, when one is composed: its authorization server lives in this instance.
|
|
570
|
+
wiring.mcp = capabilities.find(isMcpCapability)?.mcpWiring;
|
|
571
|
+
composition = capabilities;
|
|
572
|
+
wiring.composed = capabilities;
|
|
481
573
|
},
|
|
482
574
|
/**
|
|
483
575
|
* The client-safe projection — what a sign-in screen needs and nothing more: where to call
|
|
@@ -508,7 +600,7 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
508
600
|
microsoft: resolved.microsoft.enabled,
|
|
509
601
|
},
|
|
510
602
|
// Per provider, beside the global one. A project may let email create accounts while a provider
|
|
511
|
-
// may not, and a screen with only `signUpEnabled` promises what that provider will refuse
|
|
603
|
+
// may not, and a screen with only `signUpEnabled` promises what that provider will refuse.
|
|
512
604
|
providerSignUp: {
|
|
513
605
|
google: resolved.google.allowSignUp,
|
|
514
606
|
apple: resolved.apple.allowSignUp,
|
|
@@ -541,7 +633,19 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
541
633
|
seeds: [authExampleSeed, authDevSessionSeed],
|
|
542
634
|
});
|
|
543
635
|
|
|
544
|
-
return Object.assign(capability, {
|
|
636
|
+
return Object.assign(capability, {
|
|
637
|
+
authConfig: resolved,
|
|
638
|
+
authPeer,
|
|
639
|
+
lifecycleHooks,
|
|
640
|
+
purgeSteps: steps,
|
|
641
|
+
auditFor: (env: Record<string, unknown>) => composedAuditEmit(composition, env),
|
|
642
|
+
mcpHost: {
|
|
643
|
+
instance: (c) => getAuthInstance(c, wiring),
|
|
644
|
+
baseURL: (request) => baseURLResolver(resolved.baseURL)(request),
|
|
645
|
+
basePath: resolved.basePath,
|
|
646
|
+
database: resolved.database,
|
|
647
|
+
} satisfies McpHost,
|
|
648
|
+
});
|
|
545
649
|
}
|
|
546
650
|
|
|
547
651
|
/** Type guard: is this capability the auth capability? */
|
package/src/client/api.ts
CHANGED
|
@@ -14,11 +14,12 @@
|
|
|
14
14
|
* `/sign-out`, the two OTP routes, the magic link, and the social handoff — each spelling out the same
|
|
15
15
|
* transport by hand. They call this now, and this upgrades with a minor release (#370).
|
|
16
16
|
*
|
|
17
|
-
* **
|
|
18
|
-
* `credentials: "include"` and nothing else: no token in `localStorage` or
|
|
19
|
-
* `Authorization` header, no refresh rotation. The SPA and its Worker share an
|
|
20
|
-
* rides an httpOnly cookie JavaScript cannot read.
|
|
21
|
-
*
|
|
17
|
+
* **Two transports, chosen by one option.** With no `origin`, every request is a rooted path on the
|
|
18
|
+
* page's own origin carrying `credentials: "include"` and nothing else: no token in `localStorage` or
|
|
19
|
+
* `sessionStorage`, no `Authorization` header, no refresh rotation. The SPA and its Worker share an
|
|
20
|
+
* origin, so the session rides an httpOnly cookie JavaScript cannot read. With an `origin` — a native
|
|
21
|
+
* app, which no Worker serves — the request goes to that origin with `credentials: "omit"`, and the
|
|
22
|
+
* credential is the `Authorization` header the handed-in `fetch` adds. `./bearer` builds that fetch.
|
|
22
23
|
*
|
|
23
24
|
* **CSRF travels with the cookie mode, and half of it is on this side of the wire.** The server's
|
|
24
25
|
* `requireSameOrigin()` refuses a cookie-authenticated mutating request whose `Origin` does not match;
|
|
@@ -35,7 +36,7 @@
|
|
|
35
36
|
* on this side of the wire protects anything, it only decides what a screen shows.
|
|
36
37
|
*
|
|
37
38
|
* **No absolute URL literals, and no schema library.** Paths are relative, so the calls follow whatever
|
|
38
|
-
* origin the bundle is served from. Answers are narrowed by hand-written `is…(value: unknown): value is
|
|
39
|
+
* origin the bundle is served from, or the one `origin` names. Answers are narrowed by hand-written `is…(value: unknown): value is
|
|
39
40
|
* T` guards rather than Zod: this file compiles into an adopter's browser bundle, and it must not drag
|
|
40
41
|
* the Worker's schema graph in behind it. `sameOrigin.test.ts` holds the import list to empty, so the
|
|
41
42
|
* property is structural rather than a habit.
|
|
@@ -58,7 +59,10 @@ export interface AuthRequestInit {
|
|
|
58
59
|
headers?: Record<string, string>;
|
|
59
60
|
/** The JSON body, already serialized. */
|
|
60
61
|
body?: string;
|
|
61
|
-
/**
|
|
62
|
+
/**
|
|
63
|
+
* Cookie policy. `include` on the page's own origin, where the session is an httpOnly cookie; `omit`
|
|
64
|
+
* once an {@link AuthClientOptions.origin} is set, where the credential is a bearer the fetch adds.
|
|
65
|
+
*/
|
|
62
66
|
credentials?: "include" | "same-origin" | "omit";
|
|
63
67
|
}
|
|
64
68
|
|
|
@@ -102,6 +106,13 @@ export type AuthGate = (body: Record<string, unknown>) => {
|
|
|
102
106
|
|
|
103
107
|
/** What every call takes: where the routes are, and the seams a test replaces. */
|
|
104
108
|
export interface AuthClientOptions {
|
|
109
|
+
/**
|
|
110
|
+
* The Worker's absolute origin, for a program it does not serve: a native app. `scheme://host[:port]`
|
|
111
|
+
* over http or https and nothing else — no path, no trailing slash. Absent, every request is a rooted
|
|
112
|
+
* path on the page's own origin carrying its cookie. Present, the request goes to this origin with no
|
|
113
|
+
* cookie, and the credential is whatever the `fetch` handed in adds.
|
|
114
|
+
*/
|
|
115
|
+
origin?: string;
|
|
105
116
|
/** Where the auth routes mount. Defaults to {@link AUTH_BASE_PATH}. */
|
|
106
117
|
basePath?: string;
|
|
107
118
|
/** The fetch to use. Defaults to the one on {@link AuthClientOptions.global}. */
|
|
@@ -142,15 +153,15 @@ export const AUTH_UNREADABLE: AuthFailure = {
|
|
|
142
153
|
/**
|
|
143
154
|
* The request would have left this origin, so it was never sent.
|
|
144
155
|
*
|
|
145
|
-
*
|
|
146
|
-
*
|
|
147
|
-
* would attach
|
|
148
|
-
* the cookie mode exists to keep from happening.
|
|
156
|
+
* Reached through a `basePath` that is not a rooted path — an absolute URL, a protocol-relative
|
|
157
|
+
* `//host`, a backslash form a URL parser reads as one — or an `origin` that is not a bare http(s)
|
|
158
|
+
* origin. Sending it would attach a session to a request this program is not entitled to make.
|
|
149
159
|
*/
|
|
150
160
|
export const AUTH_CROSS_ORIGIN: AuthFailure = {
|
|
151
161
|
code: "client/cross_origin",
|
|
152
162
|
message: "That request would have left this site, so it wasn't sent.",
|
|
153
|
-
action:
|
|
163
|
+
action:
|
|
164
|
+
"Check the auth `basePath` in pithy.config.ts, which is a path on the worker and not a URL, and the client's `origin`, which is a scheme and host with no path.",
|
|
154
165
|
};
|
|
155
166
|
|
|
156
167
|
/** Whether a value is a plain record — the first step of every guard below. */
|
|
@@ -165,12 +176,45 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
|
|
165
176
|
* parser reads as an authority rather than as a path, and a browser follows both — which is why the
|
|
166
177
|
* check is on the second character rather than on a scheme it would never find after a leading `/`.
|
|
167
178
|
*/
|
|
168
|
-
function isSameOriginPath(path: string): boolean {
|
|
179
|
+
export function isSameOriginPath(path: string): boolean {
|
|
169
180
|
if (!path.startsWith("/")) return false;
|
|
170
181
|
const second = path.charAt(1);
|
|
171
182
|
return second !== "/" && second !== "\\";
|
|
172
183
|
}
|
|
173
184
|
|
|
185
|
+
/**
|
|
186
|
+
* Whether a configured origin is a bare http(s) origin: a scheme, a host, an optional port, nothing else.
|
|
187
|
+
*
|
|
188
|
+
* A regular expression rather than `new URL`, because React Native's `URL` does not implement the
|
|
189
|
+
* getters a parsed check would read. Userinfo, a path, a query, a fragment, a backslash and whitespace
|
|
190
|
+
* are all refused, so the composed URL can only ever name this host.
|
|
191
|
+
*/
|
|
192
|
+
export function isBareOrigin(origin: string): boolean {
|
|
193
|
+
return /^https?:\/\/[A-Za-z0-9.-]+(?::[0-9]{1,5})?$|^https?:\/\/\[[0-9A-Fa-f:.]+\](?::[0-9]{1,5})?$/.test(origin);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* The fetch a call goes through: the one passed, else the one on the injected global, else none.
|
|
198
|
+
*
|
|
199
|
+
* Exported so `./bearer` reaches the global the same way every call here does, rather than keeping a
|
|
200
|
+
* second copy of where a fetch comes from.
|
|
201
|
+
*/
|
|
202
|
+
export function resolveFetch(options: Pick<AuthClientOptions, "fetch" | "global"> | undefined): AuthFetch | undefined {
|
|
203
|
+
return options?.fetch ?? (options?.global ?? (globalThis as AuthGlobal)).fetch;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* The same request with no cookie on it — the bearer transport's policy.
|
|
208
|
+
*
|
|
209
|
+
* Written here because this module is the one place a cookie mode is written. `./bearer` puts it on
|
|
210
|
+
* every request its session sends, which is what keeps a cookie a native `fetch` stored from a sign-in
|
|
211
|
+
* answer from riding alongside the bearer: Better Auth refuses a cookie-carrying request with no
|
|
212
|
+
* `Origin`.
|
|
213
|
+
*/
|
|
214
|
+
export function withoutCookies(init: AuthRequestInit | undefined): AuthRequestInit {
|
|
215
|
+
return { ...init, credentials: "omit" };
|
|
216
|
+
}
|
|
217
|
+
|
|
174
218
|
/**
|
|
175
219
|
* A failure read off either shape this Worker answers with, or the generic one when the body is neither.
|
|
176
220
|
*
|
|
@@ -212,7 +256,8 @@ function readFailure(body: unknown): AuthFailure {
|
|
|
212
256
|
}
|
|
213
257
|
|
|
214
258
|
/**
|
|
215
|
-
* One call: same-origin
|
|
259
|
+
* One call: same-origin and cookie-carrying, or to an absolute origin with no cookie; never throwing.
|
|
260
|
+
* **The only producer of either request.**
|
|
216
261
|
*
|
|
217
262
|
* The body is read before the status is judged, because a refusal's body is the failure a screen
|
|
218
263
|
* renders. A body that will not parse is the generic failure rather than a crash — a corporate proxy's
|
|
@@ -235,17 +280,22 @@ export async function callAuth<T>(
|
|
|
235
280
|
guard: (value: unknown) => value is T,
|
|
236
281
|
): Promise<AuthResult<T>> {
|
|
237
282
|
const base = options?.basePath ?? AUTH_BASE_PATH;
|
|
238
|
-
const
|
|
283
|
+
const rooted = `${base}${path}`;
|
|
239
284
|
// Before anything else, and before any fetch: the cookie mode below is only safe because this is a
|
|
240
|
-
// request to this Worker. `base`
|
|
241
|
-
if (!isSameOriginPath(
|
|
285
|
+
// request to this Worker. `base` and `origin` are adopter config; `path` is ours.
|
|
286
|
+
if (!isSameOriginPath(rooted)) return { ok: false, failure: AUTH_CROSS_ORIGIN };
|
|
287
|
+
const origin = options?.origin;
|
|
288
|
+
if (origin !== undefined && !isBareOrigin(origin)) return { ok: false, failure: AUTH_CROSS_ORIGIN };
|
|
242
289
|
|
|
243
|
-
const fetcher =
|
|
290
|
+
const fetcher = resolveFetch(options);
|
|
244
291
|
if (!fetcher) return { ok: false, failure: AUTH_UNREACHABLE };
|
|
245
292
|
|
|
246
293
|
let response: AuthResponse;
|
|
247
294
|
try {
|
|
248
|
-
response =
|
|
295
|
+
response =
|
|
296
|
+
origin === undefined
|
|
297
|
+
? await fetcher(rooted, { ...init, credentials: "include" })
|
|
298
|
+
: await fetcher(`${origin}${rooted}`, withoutCookies(init));
|
|
249
299
|
} catch {
|
|
250
300
|
return { ok: false, failure: AUTH_UNREACHABLE };
|
|
251
301
|
}
|