@pithy-sh/auth 0.1.2 → 0.1.3
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/dist/admin/users.d.ts +155 -0
- package/dist/admin/users.d.ts.map +1 -0
- package/dist/admin/users.js +205 -0
- package/dist/audit/actions.d.ts +66 -0
- package/dist/audit/actions.d.ts.map +1 -0
- package/dist/audit/actions.js +66 -0
- package/dist/audit/emit.d.ts +101 -0
- package/dist/audit/emit.d.ts.map +1 -0
- package/dist/audit/emit.js +170 -0
- package/dist/capability.d.ts +60 -0
- package/dist/capability.d.ts.map +1 -0
- package/dist/capability.js +169 -0
- package/dist/client/api.d.ts +299 -0
- package/dist/client/api.d.ts.map +1 -0
- package/dist/client/api.js +385 -0
- package/dist/client/projection.d.ts +51 -0
- package/dist/client/projection.d.ts.map +1 -0
- package/dist/client/projection.js +0 -0
- package/dist/data/betterAuth.d.ts +75 -0
- package/dist/data/betterAuth.d.ts.map +1 -0
- package/dist/data/betterAuth.js +92 -0
- package/dist/data/device.d.ts +36 -0
- package/dist/data/device.d.ts.map +1 -0
- package/dist/data/device.js +33 -0
- package/dist/data/kitFields.d.ts +78 -0
- package/dist/data/kitFields.d.ts.map +1 -0
- package/dist/data/kitFields.js +77 -0
- package/dist/data/rotatedToken.d.ts +20 -0
- package/dist/data/rotatedToken.d.ts.map +1 -0
- package/dist/data/rotatedToken.js +22 -0
- package/dist/data/tables.d.ts +104 -0
- package/dist/data/tables.d.ts.map +1 -0
- package/dist/data/tables.js +30 -0
- package/dist/device/registry.d.ts +54 -0
- package/dist/device/registry.d.ts.map +1 -0
- package/dist/device/registry.js +85 -0
- package/dist/email/send.d.ts +38 -0
- package/dist/email/send.d.ts.map +1 -0
- package/dist/email/send.js +48 -0
- package/dist/http/adminRoutes.d.ts +9 -0
- package/dist/http/adminRoutes.d.ts.map +1 -0
- package/dist/http/adminRoutes.js +274 -0
- package/dist/http/baseUrl.d.ts +41 -0
- package/dist/http/baseUrl.d.ts.map +1 -0
- package/dist/http/baseUrl.js +96 -0
- package/dist/http/csrf.d.ts +18 -0
- package/dist/http/csrf.d.ts.map +1 -0
- package/dist/http/csrf.js +81 -0
- package/dist/http/devLoginRoute.d.ts +42 -0
- package/dist/http/devLoginRoute.d.ts.map +1 -0
- package/dist/http/devLoginRoute.js +112 -0
- package/dist/http/errors.d.ts +24 -0
- package/dist/http/errors.d.ts.map +1 -0
- package/dist/http/errors.js +67 -0
- package/dist/http/guards.d.ts +103 -0
- package/dist/http/guards.d.ts.map +1 -0
- package/dist/http/guards.js +148 -0
- package/dist/http/middleware.d.ts +17 -0
- package/dist/http/middleware.d.ts.map +1 -0
- package/dist/http/middleware.js +47 -0
- package/dist/http/rateLimit.d.ts +17 -0
- package/dist/http/rateLimit.d.ts.map +1 -0
- package/dist/http/rateLimit.js +31 -0
- package/dist/http/resolve.d.ts +9 -0
- package/dist/http/resolve.d.ts.map +1 -0
- package/dist/http/resolve.js +92 -0
- package/dist/http/responses.d.ts +152 -0
- package/dist/http/responses.d.ts.map +1 -0
- package/dist/http/responses.js +121 -0
- package/dist/http/routes.d.ts +34 -0
- package/dist/http/routes.d.ts.map +1 -0
- package/dist/http/routes.js +268 -0
- package/dist/http/schemas.d.ts +66 -0
- package/dist/http/schemas.d.ts.map +1 -0
- package/dist/http/schemas.js +59 -0
- package/dist/http/views.d.ts +53 -0
- package/dist/http/views.d.ts.map +1 -0
- package/dist/http/views.js +86 -0
- package/dist/i18n/errorCopy.d.ts +24 -0
- package/dist/i18n/errorCopy.d.ts.map +1 -0
- package/dist/i18n/errorCopy.es.d.ts +31 -0
- package/dist/i18n/errorCopy.es.d.ts.map +1 -0
- package/dist/i18n/errorCopy.es.js +33 -0
- package/dist/i18n/errorCopy.js +91 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/instance/auth.d.ts +1122 -0
- package/dist/instance/auth.d.ts.map +1 -0
- package/dist/instance/auth.js +176 -0
- package/dist/instance/plugins.d.ts +87 -0
- package/dist/instance/plugins.d.ts.map +1 -0
- package/dist/instance/plugins.js +116 -0
- package/dist/instance/providers.d.ts +117 -0
- package/dist/instance/providers.d.ts.map +1 -0
- package/dist/instance/providers.js +111 -0
- package/dist/instance/secrets.d.ts +163 -0
- package/dist/instance/secrets.d.ts.map +1 -0
- package/dist/instance/secrets.js +169 -0
- package/dist/migrations/0001_init.d.ts +33 -0
- package/dist/migrations/0001_init.d.ts.map +1 -0
- package/dist/migrations/0001_init.js +77 -0
- package/dist/migrations/pluginTables.d.ts +126 -0
- package/dist/migrations/pluginTables.d.ts.map +1 -0
- package/dist/migrations/pluginTables.js +233 -0
- package/dist/seeds/devSession.d.ts +124 -0
- package/dist/seeds/devSession.d.ts.map +1 -0
- package/dist/seeds/devSession.js +211 -0
- package/dist/seeds/example.d.ts +12 -0
- package/dist/seeds/example.d.ts.map +1 -0
- package/dist/seeds/example.js +30 -0
- package/dist/test-utils/liveApp.d.ts +227 -0
- package/dist/test-utils/liveApp.d.ts.map +1 -0
- package/dist/test-utils/liveApp.js +240 -0
- package/dist/token/rotation.d.ts +56 -0
- package/dist/token/rotation.d.ts.map +1 -0
- package/dist/token/rotation.js +68 -0
- package/dist/version.generated.d.ts +5 -0
- package/dist/version.generated.d.ts.map +1 -0
- package/dist/version.generated.js +7 -0
- package/package.json +24 -13
- package/src/version.generated.ts +1 -1
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { AuthAuditActions } from "./actions.js";
|
|
2
|
+
//#region src/audit/emit.ts
|
|
3
|
+
/**
|
|
4
|
+
* Audit emission helpers, kept out of the instance so the hook wiring stays legible. Every helper goes
|
|
5
|
+
* through core's `emit` seam (a no-op when audit is absent) and swallows its own failure — an audit
|
|
6
|
+
* write must never break the auth action it records.
|
|
7
|
+
*
|
|
8
|
+
* Sign-in is emitted from the endpoint `after` hook (where `newSession` is set), not the DB hook — so
|
|
9
|
+
* the internal `createSession` a token rotation performs never looks like a fresh sign-in.
|
|
10
|
+
*/
|
|
11
|
+
/** Pull request correlation from hook headers (no PII beyond ip/user-agent). */
|
|
12
|
+
function correlation(headers) {
|
|
13
|
+
return {
|
|
14
|
+
ip: headers?.get("cf-connecting-ip") ?? void 0,
|
|
15
|
+
userAgent: headers?.get("user-agent") ?? void 0
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
async function safeEmit(emit, event) {
|
|
19
|
+
try {
|
|
20
|
+
await emit(event);
|
|
21
|
+
} catch {}
|
|
22
|
+
}
|
|
23
|
+
function pathAction(path) {
|
|
24
|
+
if (path === "/sign-in/magic-link") return AuthAuditActions.magicLinkSent;
|
|
25
|
+
if (path === "/email-otp/send-verification-otp") return AuthAuditActions.otpSent;
|
|
26
|
+
if (path === "/sign-out") return AuthAuditActions.signout;
|
|
27
|
+
if (path === "/token") return AuthAuditActions.tokenRefresh;
|
|
28
|
+
if (path === "/link-social") return AuthAuditActions.oauthLinked;
|
|
29
|
+
}
|
|
30
|
+
/** Emit the audit events for a completed auth request: sign-in (+device) from a new session, then any path event. */
|
|
31
|
+
async function emitAfterRequest(emit, req) {
|
|
32
|
+
const corr = correlation(req.headers);
|
|
33
|
+
if (req.newSession) {
|
|
34
|
+
await safeEmit(emit, {
|
|
35
|
+
action: AuthAuditActions.signin,
|
|
36
|
+
outcome: "success",
|
|
37
|
+
actorType: "user",
|
|
38
|
+
actorId: req.newSession.userId,
|
|
39
|
+
sessionId: req.newSession.sessionId,
|
|
40
|
+
...corr
|
|
41
|
+
});
|
|
42
|
+
if (req.newSession.deviceId) await safeEmit(emit, {
|
|
43
|
+
action: AuthAuditActions.deviceRegistered,
|
|
44
|
+
outcome: "success",
|
|
45
|
+
actorType: "user",
|
|
46
|
+
actorId: req.newSession.userId,
|
|
47
|
+
sessionId: req.newSession.sessionId,
|
|
48
|
+
...corr
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
const action = pathAction(req.path);
|
|
52
|
+
if (action) {
|
|
53
|
+
const actorId = req.newSession?.userId ?? req.currentUserId ?? void 0;
|
|
54
|
+
await safeEmit(emit, {
|
|
55
|
+
action,
|
|
56
|
+
outcome: "success",
|
|
57
|
+
actorType: actorId ? "user" : "anonymous",
|
|
58
|
+
actorId,
|
|
59
|
+
...corr
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** Emit a `token_refresh` event for a session rotation (the custom rotate route). */
|
|
64
|
+
async function emitTokenRefresh(emit, context) {
|
|
65
|
+
await safeEmit(emit, {
|
|
66
|
+
action: AuthAuditActions.tokenRefresh,
|
|
67
|
+
outcome: "success",
|
|
68
|
+
actorType: "user",
|
|
69
|
+
actorId: context.userId,
|
|
70
|
+
sessionId: context.sessionId,
|
|
71
|
+
ip: context.ip,
|
|
72
|
+
userAgent: context.userAgent
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Emit a `token_reuse_detected` event — a replayed refresh token was caught and its family revoked.
|
|
77
|
+
* Recorded as `denied` and attributed to the compromised account (the family's owner), so the security
|
|
78
|
+
* trail names whose family was revoked, not the anonymous replayer.
|
|
79
|
+
*/
|
|
80
|
+
async function emitTokenReuseDetected(emit, context) {
|
|
81
|
+
await safeEmit(emit, {
|
|
82
|
+
action: AuthAuditActions.tokenReuseDetected,
|
|
83
|
+
outcome: "denied",
|
|
84
|
+
severity: "critical",
|
|
85
|
+
actorType: "user",
|
|
86
|
+
actorId: context.userId,
|
|
87
|
+
ip: context.ip,
|
|
88
|
+
userAgent: context.userAgent,
|
|
89
|
+
metadata: { familyId: context.familyId }
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
/** Emit a `device_revoked` event. */
|
|
93
|
+
async function emitDeviceRevoked(emit, context) {
|
|
94
|
+
await safeEmit(emit, {
|
|
95
|
+
action: AuthAuditActions.deviceRevoked,
|
|
96
|
+
outcome: "success",
|
|
97
|
+
actorType: "user",
|
|
98
|
+
actorId: context.userId,
|
|
99
|
+
ip: context.ip,
|
|
100
|
+
userAgent: context.userAgent
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Emit one control-plane admin action.
|
|
105
|
+
*
|
|
106
|
+
* `actorType` is `control-plane` and never `user`: the caller holds no session and owns no user row, so
|
|
107
|
+
* recording it as a user would make "what did the management client do" unanswerable from the trail —
|
|
108
|
+
* and would put a dashboard operator's id in the same column as the adopter's own customers.
|
|
109
|
+
*
|
|
110
|
+
* `actorId` is the token's verified `sub` — *which person at the dashboard*, not merely which
|
|
111
|
+
* dashboard. `resourceId` is the user or session acted on, so the trail reads from both ends: every
|
|
112
|
+
* action one operator took, and everything ever done to one customer.
|
|
113
|
+
*
|
|
114
|
+
* No email address, no session token, no device push token reaches `metadata`. The trail is queryable
|
|
115
|
+
* and long-lived, and a management client that already saw the address does not need it copied into a
|
|
116
|
+
* second store with a different retention policy.
|
|
117
|
+
*/
|
|
118
|
+
async function emitControlPlaneAction(emit, event) {
|
|
119
|
+
await safeEmit(emit, {
|
|
120
|
+
action: event.action,
|
|
121
|
+
outcome: "success",
|
|
122
|
+
actorType: "control-plane",
|
|
123
|
+
actorId: event.subject,
|
|
124
|
+
resourceType: event.resourceType,
|
|
125
|
+
resourceId: event.resourceId ?? null,
|
|
126
|
+
ip: event.ip,
|
|
127
|
+
userAgent: event.userAgent,
|
|
128
|
+
requestId: event.requestId,
|
|
129
|
+
metadata: {
|
|
130
|
+
connectionId: event.connectionId,
|
|
131
|
+
...event.metadata
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Emit a `provider_unavailable` event — somebody asked for a sign-in method this deployment enables and
|
|
137
|
+
* could not serve.
|
|
138
|
+
*
|
|
139
|
+
* `anonymous`, because the caller has no session yet by definition. `denied` rather than `failure`: the
|
|
140
|
+
* request was refused deliberately by a rule this Worker holds, not lost to a fault. `warning` rather
|
|
141
|
+
* than `critical` — the other sign-in methods are working, which is the entire point of #381, so this is
|
|
142
|
+
* notable rather than alert-worthy.
|
|
143
|
+
*
|
|
144
|
+
* `metadata.provider` is the provider id and nothing else. The secret name is derivable from it and is
|
|
145
|
+
* still not written: an audit row is long-lived and queryable, and naming a store entry in one is a map
|
|
146
|
+
* for whoever reads the trail later.
|
|
147
|
+
*/
|
|
148
|
+
async function emitProviderUnavailable(emit, context) {
|
|
149
|
+
await safeEmit(emit, {
|
|
150
|
+
action: AuthAuditActions.providerUnavailable,
|
|
151
|
+
outcome: "denied",
|
|
152
|
+
severity: "warning",
|
|
153
|
+
actorType: "anonymous",
|
|
154
|
+
metadata: { provider: context.provider },
|
|
155
|
+
...correlation(context.headers)
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
/** A blocked/failed auth attempt — recorded as `denied` (first-class). */
|
|
159
|
+
async function emitDenied(emit, context) {
|
|
160
|
+
await safeEmit(emit, {
|
|
161
|
+
action: AuthAuditActions.signin,
|
|
162
|
+
outcome: "denied",
|
|
163
|
+
actorType: "anonymous",
|
|
164
|
+
ip: context.ip,
|
|
165
|
+
userAgent: context.userAgent,
|
|
166
|
+
metadata: context.detail ? { reason: context.detail } : void 0
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
//#endregion
|
|
170
|
+
export { correlation, emitAfterRequest, emitControlPlaneAction, emitDenied, emitDeviceRevoked, emitProviderUnavailable, emitTokenRefresh, emitTokenReuseDetected };
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { Capability } from "@pithy-sh/core/src/capability/capability";
|
|
2
|
+
import type { EmailCapability } from "@pithy-sh/email/src/capability";
|
|
3
|
+
import { type TurnstileMode } from "@pithy-sh/turnstile/src/config/config";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
/** The auth capability's configuration — the thin surface an adopter owns in `pithy.config.ts`. */
|
|
6
|
+
export declare const AuthConfig: z.ZodObject<{
|
|
7
|
+
basePath: z.ZodDefault<z.ZodString>;
|
|
8
|
+
baseURL: z.ZodString;
|
|
9
|
+
trustedOrigins: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
10
|
+
database: z.ZodDefault<z.ZodString>;
|
|
11
|
+
rateLimiterBinding: z.ZodDefault<z.ZodString>;
|
|
12
|
+
google: z.ZodDefault<z.ZodObject<{
|
|
13
|
+
enabled: z.ZodDefault<z.ZodBoolean>;
|
|
14
|
+
}, z.core.$strip>>;
|
|
15
|
+
apple: z.ZodDefault<z.ZodObject<{
|
|
16
|
+
enabled: z.ZodDefault<z.ZodBoolean>;
|
|
17
|
+
}, z.core.$strip>>;
|
|
18
|
+
facebook: z.ZodDefault<z.ZodObject<{
|
|
19
|
+
enabled: z.ZodDefault<z.ZodBoolean>;
|
|
20
|
+
}, z.core.$strip>>;
|
|
21
|
+
github: z.ZodDefault<z.ZodObject<{
|
|
22
|
+
enabled: z.ZodDefault<z.ZodBoolean>;
|
|
23
|
+
}, z.core.$strip>>;
|
|
24
|
+
sessionExpiresIn: z.ZodDefault<z.ZodNumber>;
|
|
25
|
+
sessionUpdateAge: z.ZodDefault<z.ZodNumber>;
|
|
26
|
+
verificationExpiresIn: z.ZodDefault<z.ZodNumber>;
|
|
27
|
+
otpLength: z.ZodDefault<z.ZodNumber>;
|
|
28
|
+
disableSignUp: z.ZodDefault<z.ZodBoolean>;
|
|
29
|
+
plugins: z.ZodDefault<z.ZodArray<z.ZodCustom<import("better-auth").BetterAuthPlugin, import("better-auth").BetterAuthPlugin>>>;
|
|
30
|
+
}, z.core.$strip>;
|
|
31
|
+
export type AuthConfig = z.output<typeof AuthConfig>;
|
|
32
|
+
export type AuthConfigInput = z.input<typeof AuthConfig>;
|
|
33
|
+
/**
|
|
34
|
+
* The runtime wiring the middleware and routes close over. `config` is known at `auth()` call time;
|
|
35
|
+
* `emailConfig` and `turnstile` are filled by `compose` from the composed peer capabilities, before
|
|
36
|
+
* any request runs.
|
|
37
|
+
*/
|
|
38
|
+
export interface AuthWiring {
|
|
39
|
+
config: AuthConfig;
|
|
40
|
+
/** The email capability's bound enqueue seam — how magic-link/OTP are delivered. Set by `compose`. */
|
|
41
|
+
enqueueEmail: EmailCapability["enqueue"] | undefined;
|
|
42
|
+
/** The turnstile login gate, when the turnstile capability is composed. Set by `compose`. */
|
|
43
|
+
turnstile: {
|
|
44
|
+
mode: TurnstileMode;
|
|
45
|
+
} | undefined;
|
|
46
|
+
}
|
|
47
|
+
/** The auth capability, with its resolved config attached for inspection. */
|
|
48
|
+
export interface AuthCapability extends Capability {
|
|
49
|
+
authConfig: AuthConfig;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The auth capability. Passwordless sign-in (magic link, OTP, Google, Apple), the hybrid bearer +
|
|
53
|
+
* cookie token model, the per-device session registry, and the `bearer`/`session` fills for core's
|
|
54
|
+
* `AuthContext` seam. Depends on `secrets` and `email`; auto-gates its send routes with `turnstile`
|
|
55
|
+
* and emits `auth/*` through `audit` when those are composed.
|
|
56
|
+
*/
|
|
57
|
+
export declare function auth(config: AuthConfigInput): AuthCapability;
|
|
58
|
+
/** Type guard: is this capability the auth capability? */
|
|
59
|
+
export declare function isAuthCapability(capability: Capability): capability is AuthCapability;
|
|
60
|
+
//# sourceMappingURL=capability.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"capability.d.ts","sourceRoot":"","sources":["../src/capability.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAmB,MAAM,0CAA0C,CAAC;AAG5F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAGtE,OAAO,EAA0B,KAAK,aAAa,EAAE,MAAM,uCAAuC,CAAC;AACnG,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AA2BxB,mGAAmG;AACnG,eAAO,MAAM,UAAU;;;;;;;;;;;;;;;;;;;;;;;;iBAsE8B,CAAC;AACtD,MAAM,MAAM,UAAU,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AACrD,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,UAAU,CAAC,CAAC;AAEzD;;;;GAIG;AACH,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,UAAU,CAAC;IACnB,sGAAsG;IACtG,YAAY,EAAE,eAAe,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;IACrD,6FAA6F;IAC7F,SAAS,EAAE;QAAE,IAAI,EAAE,aAAa,CAAA;KAAE,GAAG,SAAS,CAAC;CAChD;AAED,6EAA6E;AAC7E,MAAM,WAAW,cAAe,SAAQ,UAAU;IAChD,UAAU,EAAE,UAAU,CAAC;CACxB;AAiCD;;;;;GAKG;AACH,wBAAgB,IAAI,CAAC,MAAM,EAAE,eAAe,GAAG,cAAc,CA+H5D;AAED,0DAA0D;AAC1D,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,UAAU,GAAG,UAAU,IAAI,cAAc,CAErF"}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { authTables } from "./data/tables.js";
|
|
2
|
+
import { publishSameOrigin } from "./http/csrf.js";
|
|
3
|
+
import { authSecretsRegistry } from "./instance/secrets.js";
|
|
4
|
+
import { authDevSessionSeed } from "./seeds/devSession.js";
|
|
5
|
+
import { AuthPlugin, assertAdditivePlugins } from "./instance/plugins.js";
|
|
6
|
+
import { registerDevLoginRoute } from "./http/devLoginRoute.js";
|
|
7
|
+
import { authAdminRoutes } from "./http/guards.js";
|
|
8
|
+
import { createSessionMiddleware } from "./http/middleware.js";
|
|
9
|
+
import { createRateLimitMiddleware } from "./http/rateLimit.js";
|
|
10
|
+
import { createAuthRoutes } from "./http/routes.js";
|
|
11
|
+
import { auth_0001_init } from "./migrations/0001_init.js";
|
|
12
|
+
import { authPluginPlan } from "./migrations/pluginTables.js";
|
|
13
|
+
import { authExampleSeed } from "./seeds/example.js";
|
|
14
|
+
import { PACKAGE_VERSION } from "./version.generated.js";
|
|
15
|
+
import { defineCapability } from "@pithy-sh/core/src/capability/capability";
|
|
16
|
+
import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
17
|
+
import { isEmailCapability } from "@pithy-sh/email/src/capability";
|
|
18
|
+
import { isTurnstileCapability } from "@pithy-sh/turnstile/src/capability";
|
|
19
|
+
import { TURNSTILE_LOGIN_ACTION } from "@pithy-sh/turnstile/src/config/config";
|
|
20
|
+
import { z } from "zod";
|
|
21
|
+
//#region src/capability.ts
|
|
22
|
+
/** A social provider toggle. Credentials live in the secrets store, never config. */
|
|
23
|
+
const ProviderToggle = z.object({ enabled: z.boolean().default(false).describe("Whether this social provider is enabled. Credentials are read from the secrets store, never config.") }).describe("A social provider's on/off toggle.");
|
|
24
|
+
/** The auth capability's configuration — the thin surface an adopter owns in `pithy.config.ts`. */
|
|
25
|
+
const AuthConfig = z.object({
|
|
26
|
+
basePath: z.string().default("/auth").describe("The path the auth handler mounts under. Must match the OAuth redirect URIs you register. Defaults to `/auth`."),
|
|
27
|
+
baseURL: z.string().describe("The public origin of this worker where it is deployed (no trailing slash). OAuth callbacks, JWKS and magic-link URLs are built from it. A `dev` composition ignores it and serves on `http://<the host the request arrived at>` instead — local dev has no TLS and its port is assigned per run, so it is the one address nobody can write down."),
|
|
28
|
+
trustedOrigins: z.array(z.string()).default([]).describe("Web origins and mobile deep-link schemes allowed as redirect targets and for cookie CSRF origin checks (e.g. `https://app.example.com`, `myapp://`)."),
|
|
29
|
+
database: z.string().default("DB").describe("The D1 binding the auth tables and migrations target. Defaults to `DB`, the shared app database."),
|
|
30
|
+
rateLimiterBinding: z.string().default("AUTH_RATE_LIMITER").describe("The Workers Rate Limiting binding for the coarse per-IP edge guard on the auth routes (tier 1). Its limit and window are set on the binding in wrangler.jsonc. Complements Better Auth's per-action limiter (tier 2)."),
|
|
31
|
+
google: ProviderToggle.default({ enabled: false }).describe("Google OAuth. Enable it, then store credentials as the `auth-google-credentials` secret. See docs/google-oauth.md."),
|
|
32
|
+
apple: ProviderToggle.default({ enabled: false }).describe("Apple Sign-In. Enable it, then store credentials as the `auth-apple-credentials` secret. See docs/apple-signin.md."),
|
|
33
|
+
facebook: ProviderToggle.default({ enabled: false }).describe("Facebook Login. Enable it, then store credentials as the `auth-facebook-credentials` secret. See docs/facebook-oauth.md."),
|
|
34
|
+
github: ProviderToggle.default({ enabled: false }).describe("GitHub OAuth. Enable it, then store credentials as the `auth-github-credentials` secret. See docs/github-oauth.md."),
|
|
35
|
+
sessionExpiresIn: z.number().int().default(604800).describe("Session (refresh credential) lifetime in seconds. Defaults to 7 days. Expiry slides forward on use."),
|
|
36
|
+
sessionUpdateAge: z.number().int().default(86400).describe("How often (seconds) an active session's expiry slides forward. Defaults to 1 day."),
|
|
37
|
+
verificationExpiresIn: z.number().int().default(300).describe("Magic-link and OTP lifetime in seconds. Defaults to 5 minutes. Single-use regardless."),
|
|
38
|
+
otpLength: z.number().int().default(6).describe("The number of digits in an email OTP. Defaults to 6."),
|
|
39
|
+
disableSignUp: z.boolean().default(false).describe("When true, sign-in never provisions a new user — existing accounts only. Unknown emails get no email (anti-enumeration)."),
|
|
40
|
+
plugins: z.array(AuthPlugin).default([]).describe("Additional Better Auth plugins to compose — `organization()`, `passkey()`, `twoFactor()`, `apiKey()`, a generic OAuth provider. Additive: they join the set the kit composes (i18n, bearer, jwt, magic-link, email-otp) and cannot replace one. Tables a plugin declares are created by `pithy migrate`; add the matching client plugin to `createAuthClient` for its typed client surface.")
|
|
41
|
+
}).describe("Configuration for the auth capability.");
|
|
42
|
+
/**
|
|
43
|
+
* Refuse a composition where a Better Auth plugin's table is one another capability already declares in
|
|
44
|
+
* the same database. `capabilities` is every capability composed into this backend, so this is the first
|
|
45
|
+
* moment the question can be asked at all — `auth()` sees only itself.
|
|
46
|
+
*/
|
|
47
|
+
function assertPluginTablesUnclaimed(capabilities, binding, extensions) {
|
|
48
|
+
const claimed = /* @__PURE__ */ new Map();
|
|
49
|
+
for (const capability of capabilities) {
|
|
50
|
+
if (capability.name === "auth") continue;
|
|
51
|
+
for (const spec of Object.values(capability.databases ?? {})) {
|
|
52
|
+
if (spec.binding !== binding) continue;
|
|
53
|
+
for (const table of Object.keys(spec.tables)) claimed.set(table, capability.name);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
for (const extension of extensions) for (const table of extension.tables) {
|
|
57
|
+
const owner = claimed.get(table);
|
|
58
|
+
if (!owner) continue;
|
|
59
|
+
throw new ValidationError({
|
|
60
|
+
message: `The Better Auth "${extension.id}" plugin and the ${owner} capability both use a ${table} table.`,
|
|
61
|
+
action: `Rename the plugin's through its own \`schema: { ${table}: { modelName: "…" } }\` option, or point auth at another database.`,
|
|
62
|
+
detail: `plugin "${extension.id}" table "${table}" is already declared by capability "${owner}" on binding ${binding}`
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The auth capability. Passwordless sign-in (magic link, OTP, Google, Apple), the hybrid bearer +
|
|
68
|
+
* cookie token model, the per-device session registry, and the `bearer`/`session` fills for core's
|
|
69
|
+
* `AuthContext` seam. Depends on `secrets` and `email`; auto-gates its send routes with `turnstile`
|
|
70
|
+
* and emits `auth/*` through `audit` when those are composed.
|
|
71
|
+
*/
|
|
72
|
+
function auth(config) {
|
|
73
|
+
const resolved = AuthConfig.parse(config);
|
|
74
|
+
assertAdditivePlugins(resolved.plugins);
|
|
75
|
+
const pluginPlan = authPluginPlan(resolved.plugins);
|
|
76
|
+
const wiring = {
|
|
77
|
+
config: resolved,
|
|
78
|
+
enqueueEmail: void 0,
|
|
79
|
+
turnstile: void 0
|
|
80
|
+
};
|
|
81
|
+
const rateLimitMiddleware = (app) => {
|
|
82
|
+
app.use(`${resolved.basePath}/*`, createRateLimitMiddleware(resolved.rateLimiterBinding));
|
|
83
|
+
};
|
|
84
|
+
const capability = defineCapability({
|
|
85
|
+
name: "auth",
|
|
86
|
+
version: PACKAGE_VERSION,
|
|
87
|
+
config: AuthConfig,
|
|
88
|
+
dependsOn: ["secrets", "email"],
|
|
89
|
+
secretRegistry: authSecretsRegistry,
|
|
90
|
+
requiredBindings: [{
|
|
91
|
+
type: "d1",
|
|
92
|
+
name: resolved.database
|
|
93
|
+
}, {
|
|
94
|
+
type: "ratelimit",
|
|
95
|
+
name: resolved.rateLimiterBinding
|
|
96
|
+
}],
|
|
97
|
+
extensions: pluginPlan.extensions.map((extension) => ({
|
|
98
|
+
kind: "better-auth-plugin",
|
|
99
|
+
id: extension.id,
|
|
100
|
+
tables: extension.tables
|
|
101
|
+
})),
|
|
102
|
+
databases: { app: {
|
|
103
|
+
binding: resolved.database,
|
|
104
|
+
tables: authTables,
|
|
105
|
+
migrationOrder: 300,
|
|
106
|
+
migrations: {
|
|
107
|
+
"0001_init": auth_0001_init,
|
|
108
|
+
...pluginPlan.migrations
|
|
109
|
+
}
|
|
110
|
+
} },
|
|
111
|
+
compose: ({ capabilities }) => {
|
|
112
|
+
const email = capabilities.find(isEmailCapability);
|
|
113
|
+
if (!email) throw new ValidationError({
|
|
114
|
+
message: "The auth capability requires the email capability.",
|
|
115
|
+
action: "Add `email(...)` to your capabilities — magic-link and OTP delivery enqueue email jobs."
|
|
116
|
+
});
|
|
117
|
+
wiring.enqueueEmail = email.enqueue;
|
|
118
|
+
const loginMode = capabilities.find(isTurnstileCapability)?.turnstileConfig.protect[TURNSTILE_LOGIN_ACTION];
|
|
119
|
+
wiring.turnstile = loginMode ? { mode: loginMode } : void 0;
|
|
120
|
+
assertPluginTablesUnclaimed(capabilities, resolved.database, pluginPlan.extensions);
|
|
121
|
+
},
|
|
122
|
+
/**
|
|
123
|
+
* The client-safe projection — what a sign-in screen needs and nothing more: where to call
|
|
124
|
+
* (`basePath`), which buttons to render (the four provider toggles), how many OTP boxes to draw
|
|
125
|
+
* (`otpLength`), and whether to offer sign-up (`signUpEnabled`).
|
|
126
|
+
*
|
|
127
|
+
* Deliberately absent: `baseURL`, `trustedOrigins`, `database`, `rateLimiterBinding`, and every
|
|
128
|
+
* session/verification lifetime — a browser has no use for them and they describe the deployment.
|
|
129
|
+
* OAuth credentials cannot leak here because they are not in this config at all: they live in the
|
|
130
|
+
* secrets store (`authSecretsRegistry`), read only inside the Worker. That is what makes this
|
|
131
|
+
* projection provably safe — the sensitive values are not in reach of the function.
|
|
132
|
+
*
|
|
133
|
+
* The return type is {@link AuthClientProjection} — **declared, not inferred**. `Capability.client`
|
|
134
|
+
* types this as `{ enabled: boolean }` plus a JSON catchall, which accepts anything this literal
|
|
135
|
+
* could say. The declared type is what makes a dropped field — and a grown one, `baseURL` projected
|
|
136
|
+
* "just for a redirect" — a compile error here rather than a browser's problem.
|
|
137
|
+
*/
|
|
138
|
+
client: () => ({
|
|
139
|
+
enabled: true,
|
|
140
|
+
basePath: resolved.basePath,
|
|
141
|
+
providers: {
|
|
142
|
+
google: resolved.google.enabled,
|
|
143
|
+
apple: resolved.apple.enabled,
|
|
144
|
+
facebook: resolved.facebook.enabled,
|
|
145
|
+
github: resolved.github.enabled
|
|
146
|
+
},
|
|
147
|
+
otpLength: resolved.otpLength,
|
|
148
|
+
signUpEnabled: !resolved.disableSignUp
|
|
149
|
+
}),
|
|
150
|
+
middleware: [
|
|
151
|
+
publishSameOrigin(wiring),
|
|
152
|
+
rateLimitMiddleware,
|
|
153
|
+
createSessionMiddleware(wiring)
|
|
154
|
+
],
|
|
155
|
+
routes: (app) => {
|
|
156
|
+
registerDevLoginRoute(wiring)(app);
|
|
157
|
+
createAuthRoutes(wiring)(app);
|
|
158
|
+
},
|
|
159
|
+
adminRoutes: authAdminRoutes(resolved.basePath),
|
|
160
|
+
seeds: [authExampleSeed, authDevSessionSeed]
|
|
161
|
+
});
|
|
162
|
+
return Object.assign(capability, { authConfig: resolved });
|
|
163
|
+
}
|
|
164
|
+
/** Type guard: is this capability the auth capability? */
|
|
165
|
+
function isAuthCapability(capability) {
|
|
166
|
+
return capability.name === "auth" && "authConfig" in capability;
|
|
167
|
+
}
|
|
168
|
+
//#endregion
|
|
169
|
+
export { AuthConfig, auth, isAuthCapability };
|