@pithy-sh/auth 0.11.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/audit/actions.d.ts +39 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +40 -1
- package/dist/audit/emit.d.ts +34 -0
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +47 -1
- package/dist/audit/evidence.d.ts +8 -2
- package/dist/audit/evidence.d.ts.map +1 -1
- package/dist/capability.d.ts +31 -11
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +38 -5
- 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 +25 -4
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +9 -0
- package/dist/data/userLifecycle.d.ts.map +1 -1
- package/dist/data/userLifecycle.js +6 -2
- 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 +56 -10
- package/dist/http/csrf.d.ts.map +1 -1
- package/dist/http/csrf.js +2 -1
- package/dist/http/guards.d.ts +15 -11
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +46 -11
- 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 +12 -0
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +25 -4
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +9 -3
- package/dist/http/responses.d.ts +142 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +66 -10
- package/dist/http/routes.d.ts +2 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +35 -4
- package/dist/http/schemas.d.ts +57 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +44 -1
- package/dist/http/views.d.ts +22 -2
- package/dist/http/views.d.ts.map +1 -1
- package/dist/http/views.js +40 -4
- 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 +86 -41
- 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/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/transitions.d.ts +22 -1
- package/dist/lifecycle/transitions.d.ts.map +1 -1
- package/dist/lifecycle/transitions.js +51 -4
- 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/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/set.d.ts +4 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +8 -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 +20 -5
- package/dist/purge/contribution.d.ts.map +1 -1
- package/dist/purge/contribution.js +20 -6
- package/dist/purge/run.d.ts +75 -5
- package/dist/purge/run.d.ts.map +1 -1
- package/dist/purge/run.js +117 -14
- package/dist/purge/workflow.d.ts +15 -2
- package/dist/purge/workflow.d.ts.map +1 -1
- package/dist/purge/workflow.js +51 -7
- package/dist/test-utils/accountFootprint.d.ts +5 -2
- package/dist/test-utils/accountFootprint.d.ts.map +1 -1
- package/dist/test-utils/accountFootprint.js +7 -2
- 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 +59 -7
- 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 +39 -0
- package/src/audit/emit.ts +63 -0
- package/src/audit/evidence.ts +8 -4
- package/src/capability.ts +80 -23
- 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 +15 -3
- package/src/data/verificationOutcome.ts +86 -0
- package/src/email/send.ts +2 -2
- package/src/http/adminRoutes.ts +68 -3
- package/src/http/csrf.ts +4 -1
- package/src/http/guards.ts +48 -11
- package/src/http/handoff.ts +350 -0
- package/src/http/middleware.ts +29 -3
- package/src/http/resolve.ts +25 -25
- package/src/http/responses.ts +134 -8
- package/src/http/routes.ts +63 -4
- package/src/http/schemas.ts +85 -0
- package/src/http/views.ts +46 -2
- package/src/index.ts +2 -0
- package/src/instance/auth.ts +51 -1
- package/src/instance/plugins.ts +20 -2
- package/src/ledger/read.ts +133 -0
- package/src/ledger/record.ts +198 -0
- package/src/lifecycle/erasure.ts +118 -0
- package/src/lifecycle/inactivity.ts +56 -0
- package/src/lifecycle/transitions.ts +75 -5
- 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/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/set.ts +7 -1
- package/src/processing/activities.ts +14 -0
- package/src/purge/contribution.ts +37 -10
- package/src/purge/run.ts +179 -16
- package/src/purge/workflow.ts +65 -7
- package/src/seeds/example.ts +2 -2
- package/src/test-utils/accountFootprint.ts +10 -1
- 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. */
|
|
@@ -183,6 +198,17 @@ export const AuthAuditActions = {
|
|
|
183
198
|
adminUserRestored: "auth/admin_user_restored",
|
|
184
199
|
/** A deleted account's data was erased. Recorded once, when the last purge step has run. */
|
|
185
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",
|
|
186
212
|
/** The account's own holder deleted their account. Always a soft deletion, on the configured window. */
|
|
187
213
|
userSelfDeleted: "auth/user_self_deleted",
|
|
188
214
|
/**
|
|
@@ -192,6 +218,19 @@ export const AuthAuditActions = {
|
|
|
192
218
|
* answered; never with any of the data.
|
|
193
219
|
*/
|
|
194
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",
|
|
195
234
|
} as const;
|
|
196
235
|
|
|
197
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
|
|
|
@@ -554,6 +555,68 @@ export async function emitProviderChangeNotFresh(
|
|
|
554
555
|
});
|
|
555
556
|
}
|
|
556
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
|
+
|
|
557
620
|
/** A blocked/failed auth attempt — recorded as `denied` (first-class). */
|
|
558
621
|
export async function emitDenied(
|
|
559
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
|
@@ -10,27 +10,38 @@ import { type PurgeStep, purgeSteps } from "@pithy-sh/core/src/capability/purge"
|
|
|
10
10
|
import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
11
11
|
import type { EmailCapability } from "@pithy-sh/email/src/capability";
|
|
12
12
|
import { isEmailCapability } from "@pithy-sh/email/src/capability";
|
|
13
|
-
import { isTurnstileCapability } from "@pithy-sh/turnstile/src/capability";
|
|
14
|
-
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";
|
|
15
19
|
import type { Context } from "hono";
|
|
16
20
|
import { z } from "zod";
|
|
21
|
+
import { AuthAuditActions } from "./audit/actions";
|
|
17
22
|
import type { AuthClientProjection } from "./client/projection";
|
|
18
23
|
import { authTables } from "./data/tables";
|
|
24
|
+
import { baseURLResolver } from "./http/baseUrl";
|
|
19
25
|
import { publishSameOrigin } from "./http/csrf";
|
|
20
26
|
import { registerDevLoginRoute } from "./http/devLoginRoute";
|
|
21
27
|
import { authAdminRoutes } from "./http/guards";
|
|
22
28
|
import { createSessionMiddleware } from "./http/middleware";
|
|
23
29
|
import { createRateLimitMiddleware } from "./http/rateLimit";
|
|
30
|
+
import { getAuthInstance } from "./http/resolve";
|
|
24
31
|
import { createAuthRoutes } from "./http/routes";
|
|
25
32
|
import type { GithubUserInfoResolver } from "./instance/githubUserInfo";
|
|
26
33
|
import { AuthPlugin, assertAdditivePlugins } from "./instance/plugins";
|
|
27
34
|
import { authSecretsRegistryFor, inapplicableProviderSecrets } from "./instance/secrets";
|
|
35
|
+
import { authErasureRecords } from "./lifecycle/erasure";
|
|
28
36
|
import type { UserLifecycleHooks } from "./lifecycle/hooks";
|
|
37
|
+
import type { McpHost, McpWiring } from "./mcp/host";
|
|
38
|
+
import { isMcpCapability } from "./mcp/marker";
|
|
29
39
|
import { AUTH_MIGRATION_ORDER } from "./migrations/0001_init";
|
|
30
40
|
import { authPluginPlan } from "./migrations/pluginTables";
|
|
31
41
|
import { AUTH_MIGRATIONS } from "./migrations/set";
|
|
32
42
|
import { type AuthPeer, authPeer } from "./peer";
|
|
33
|
-
import {
|
|
43
|
+
import { AUTH_PROCESSING } from "./processing/activities";
|
|
44
|
+
import { authAddressOf, authPurgeContribution } from "./purge/contribution";
|
|
34
45
|
import { authWorkflows } from "./purge/specs";
|
|
35
46
|
import { authDevSessionSeed } from "./seeds/devSession";
|
|
36
47
|
import { authExampleSeed } from "./seeds/example";
|
|
@@ -188,6 +199,19 @@ export const AuthConfig = z
|
|
|
188
199
|
export type AuthConfig = z.output<typeof AuthConfig>;
|
|
189
200
|
export type AuthConfigInput = z.input<typeof AuthConfig>;
|
|
190
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
|
+
|
|
191
215
|
/**
|
|
192
216
|
* The runtime wiring the middleware and routes close over. `config` is known at `auth()` call time;
|
|
193
217
|
* `emailConfig` and `turnstile` are filled by `compose` from the composed peer capabilities, before
|
|
@@ -200,7 +224,7 @@ export interface AuthWiring {
|
|
|
200
224
|
/** The email capability's bound enqueue seam — how magic-link/OTP are delivered. Set by `compose`. */
|
|
201
225
|
enqueueEmail: EmailCapability["enqueue"] | undefined;
|
|
202
226
|
/** The turnstile login gate, when the turnstile capability is composed. Set by `compose`. */
|
|
203
|
-
turnstile:
|
|
227
|
+
turnstile: TurnstileLoginGate | undefined;
|
|
204
228
|
/**
|
|
205
229
|
* The adopter's session-revoked listener, or absent. See {@link AuthOptions.onSessionRevoked}.
|
|
206
230
|
*
|
|
@@ -221,11 +245,21 @@ export interface AuthWiring {
|
|
|
221
245
|
*/
|
|
222
246
|
lifecycleHooks?: UserLifecycleHooks | undefined;
|
|
223
247
|
/**
|
|
224
|
-
* Every composed capability's purge step for a user, auth's own among them, in composition order
|
|
248
|
+
* Every composed capability's purge step for a user, auth's own among them, in composition order. Filled
|
|
225
249
|
* by `compose`; the export route reads every capability's contribution from it, and the purge runs it.
|
|
226
250
|
* Optional on the wiring for the reason `onSessionRevoked` is: a harness that builds this by hand composes none.
|
|
227
251
|
*/
|
|
228
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;
|
|
229
263
|
}
|
|
230
264
|
|
|
231
265
|
/** The session a {@link ScopeResolver} is asked about — the one Better Auth just resolved for this request. */
|
|
@@ -237,7 +271,7 @@ export interface ScopeResolverSession {
|
|
|
237
271
|
}
|
|
238
272
|
|
|
239
273
|
/**
|
|
240
|
-
* 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.
|
|
241
275
|
*
|
|
242
276
|
* Called by the session middleware on every authenticated request, after Better Auth has resolved the
|
|
243
277
|
* session and before any route runs. What it returns becomes `AuthContext.scopes`. It reads the **request**,
|
|
@@ -301,7 +335,7 @@ export type AuthOptions = AuthConfigInput &
|
|
|
301
335
|
*/
|
|
302
336
|
onSessionRevoked?: SessionRevokedListener;
|
|
303
337
|
/**
|
|
304
|
-
* 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.
|
|
305
339
|
*
|
|
306
340
|
* `leaderboard:submit`, `rating:record`, `leaderboard:admin` and `ledger:admin` are **attestations about
|
|
307
341
|
* the caller, not permissions granted to the user**: each says *this write came from the adopter's own
|
|
@@ -326,25 +360,27 @@ export interface AuthCapability extends Capability {
|
|
|
326
360
|
authConfig: AuthConfig;
|
|
327
361
|
/**
|
|
328
362
|
* The adopter's account-lifecycle hooks, as `auth()` was handed them. Read by whatever runs a transition
|
|
329
|
-
* outside a request this capability serves — the purge Workflow
|
|
363
|
+
* outside a request this capability serves — the purge Workflow fires `onUserPurged` through it.
|
|
330
364
|
*/
|
|
331
365
|
lifecycleHooks: UserLifecycleHooks;
|
|
332
366
|
/**
|
|
333
|
-
* Every composed capability's purge step for a user, auth's own among them, in composition order
|
|
367
|
+
* Every composed capability's purge step for a user, auth's own among them, in composition order. Empty
|
|
334
368
|
* until `compose` has run. Read by the purge Workflow, which runs in the Worker that composed it.
|
|
335
369
|
*/
|
|
336
370
|
purgeSteps: readonly PurgeStep[];
|
|
337
371
|
/**
|
|
338
372
|
* The audit recorder for code with no request, over one run's env — the composed audit capability's, or the
|
|
339
|
-
* no-op
|
|
373
|
+
* no-op. Read by the purge Workflow, which owes the trail its `auth/admin_user_purged`.
|
|
340
374
|
*/
|
|
341
375
|
auditFor: (env: Record<string, unknown>) => AuditEmit;
|
|
342
376
|
/**
|
|
343
377
|
* What a capability composed beside this one reads an account through — `matchmaking`, `support`,
|
|
344
378
|
* `testers`. Found in their `compose` hooks, so none of them imports this package and a project without
|
|
345
|
-
* auth bundles them
|
|
379
|
+
* auth bundles them. See `peer.ts`.
|
|
346
380
|
*/
|
|
347
381
|
authPeer: AuthPeer;
|
|
382
|
+
/** What the MCP capability composed beside this one reads. See `mcp/host.ts`. */
|
|
383
|
+
mcpHost: McpHost;
|
|
348
384
|
}
|
|
349
385
|
|
|
350
386
|
/**
|
|
@@ -412,7 +448,7 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
412
448
|
// sign-in this product promises and what the control-plane seam verifies against, so a list naming one
|
|
413
449
|
// of them is refused here by name rather than silently redefining a route at request time — and so is a
|
|
414
450
|
// plugin that answers a refused social sign-in somewhere `http/providerRefusal` cannot collapse it,
|
|
415
|
-
// 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.
|
|
416
452
|
assertAdditivePlugins(resolved.plugins);
|
|
417
453
|
// And the tables those plugins imply, derived now so a collision is a config error at `auth()` rather
|
|
418
454
|
// than a half-applied migration against a database with no transactional DDL.
|
|
@@ -443,18 +479,18 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
443
479
|
// The package this capability ships in and the version it ships at, both stamped by
|
|
444
480
|
// `scripts/stampVersions.ts` — a Worker cannot read its own package.json. Reported per capability by
|
|
445
481
|
// the control-plane manifest, and reported together: a release feed is keyed by package name, so the
|
|
446
|
-
// version alone leaves a client guessing the key
|
|
482
|
+
// version alone leaves a client guessing the key.
|
|
447
483
|
version: PACKAGE_VERSION,
|
|
448
484
|
package: PACKAGE_NAME,
|
|
449
485
|
config: AuthConfig,
|
|
450
486
|
dependsOn: ["secrets", "email"],
|
|
451
487
|
// Whether anything will ever put a string in `AuthContext.scopes` — only when the adopter supplied a
|
|
452
|
-
// resolver. `pithy doctor` reads it against every composed capability's `scopeGates
|
|
488
|
+
// resolver. `pithy doctor` reads it against every composed capability's `scopeGates`.
|
|
453
489
|
providesScopes: resolveScopes !== undefined,
|
|
454
490
|
// Built from the config, so the session secret's overlap is this composition's session lifetime and its
|
|
455
|
-
// period is the one the adopter asked for, if any
|
|
491
|
+
// period is the one the adopter asked for, if any.
|
|
456
492
|
secretRegistry: authSecretsRegistryFor(resolved),
|
|
457
|
-
// 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
|
|
458
494
|
// has no code path that reads its pair, so `pithy doctor` listing it as outstanding re-raised a
|
|
459
495
|
// settled question on every run. Declared rather than inferred: the config key and the secret name
|
|
460
496
|
// are spelled alike by coincidence, and this is the only place that holds both.
|
|
@@ -486,12 +522,26 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
486
522
|
// one. A project that composes no plugins contributes exactly what it did before.
|
|
487
523
|
// Every kit migration, from one definition — see `migrations/set.ts` for why it is not written
|
|
488
524
|
// out here. Appended, never folded into `0001`: this capability has shipped, so that migration is
|
|
489
|
-
// 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.
|
|
490
526
|
migrations: { ...AUTH_MIGRATIONS, ...pluginPlan.migrations },
|
|
491
527
|
},
|
|
492
528
|
},
|
|
493
|
-
// What erasing a person means for the `pithy_auth_*` tables, and what exporting them hands back
|
|
529
|
+
// What erasing a person means for the `pithy_auth_*` tables, and what exporting them hands back.
|
|
494
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),
|
|
495
545
|
// The purge of one account, and the daily pass that starts every due one. Both hosted by the adopter's own
|
|
496
546
|
// Worker, because a purge runs every composed capability's contribution — see `purge/specs.ts`.
|
|
497
547
|
workflows: authWorkflows,
|
|
@@ -505,9 +555,7 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
505
555
|
}
|
|
506
556
|
wiring.enqueueEmail = email.enqueue;
|
|
507
557
|
// Auto-wire turnstile onto the login routes when it is composed (Jim's requirement: zero config).
|
|
508
|
-
|
|
509
|
-
const loginMode = turnstileCap?.turnstileConfig.protect[TURNSTILE_LOGIN_ACTION];
|
|
510
|
-
wiring.turnstile = loginMode ? { mode: loginMode } : undefined;
|
|
558
|
+
wiring.turnstile = turnstileLoginGate(capabilities.find(isTurnstileCapability));
|
|
511
559
|
// And the one collision `auth()` could not see. A plugin's tables carry the plugin's own names —
|
|
512
560
|
// `organization`, `member`, `invitation` — with no `pithy_auth_` prefix to keep them out of an
|
|
513
561
|
// adopter's way, because they are the adopter's tables now. `composeDatabases` catches two
|
|
@@ -516,9 +564,12 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
516
564
|
// Refused at boot, naming both sides: the alternative is a `create table` that fails halfway
|
|
517
565
|
// through `pithy migrate`, or two capabilities quietly reading and writing one table.
|
|
518
566
|
assertPluginTablesUnclaimed(capabilities, resolved.database, pluginPlan.extensions);
|
|
519
|
-
// Every composed capability's purge step, auth's own among them, for the export route and the purge
|
|
567
|
+
// Every composed capability's purge step, auth's own among them, for the export route and the purge.
|
|
520
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;
|
|
521
571
|
composition = capabilities;
|
|
572
|
+
wiring.composed = capabilities;
|
|
522
573
|
},
|
|
523
574
|
/**
|
|
524
575
|
* The client-safe projection — what a sign-in screen needs and nothing more: where to call
|
|
@@ -549,7 +600,7 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
549
600
|
microsoft: resolved.microsoft.enabled,
|
|
550
601
|
},
|
|
551
602
|
// Per provider, beside the global one. A project may let email create accounts while a provider
|
|
552
|
-
// 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.
|
|
553
604
|
providerSignUp: {
|
|
554
605
|
google: resolved.google.allowSignUp,
|
|
555
606
|
apple: resolved.apple.allowSignUp,
|
|
@@ -588,6 +639,12 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
588
639
|
lifecycleHooks,
|
|
589
640
|
purgeSteps: steps,
|
|
590
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,
|
|
591
648
|
});
|
|
592
649
|
}
|
|
593
650
|
|
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
|
}
|