@pithy-sh/auth 0.5.0 → 0.6.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/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/package.json +5 -5
- package/src/capability.ts +36 -1
- package/src/data/betterAuth.ts +6 -1
- package/src/http/devLoginRoute.ts +84 -59
- package/src/http/resolve.ts +7 -1
- package/src/http/routes.ts +53 -1
- package/src/instance/auth.ts +67 -0
- package/src/migrations/0001_init.ts +10 -2
- package/src/profile/profile.ts +230 -0
- package/src/seeds/devSession.ts +129 -70
- package/src/version.generated.ts +1 -1
|
@@ -3,5 +3,5 @@
|
|
|
3
3
|
/** This package's npm name — the join key against a release feed. */
|
|
4
4
|
export declare const PACKAGE_NAME = "@pithy-sh/auth";
|
|
5
5
|
/** This package's version, stamped from its own package.json at generation time. */
|
|
6
|
-
export declare const PACKAGE_VERSION = "0.
|
|
6
|
+
export declare const PACKAGE_VERSION = "0.4.0";
|
|
7
7
|
//# sourceMappingURL=version.generated.d.ts.map
|
|
@@ -4,6 +4,6 @@
|
|
|
4
4
|
/** This package's npm name — the join key against a release feed. */
|
|
5
5
|
const PACKAGE_NAME = "@pithy-sh/auth";
|
|
6
6
|
/** This package's version, stamped from its own package.json at generation time. */
|
|
7
|
-
const PACKAGE_VERSION = "0.
|
|
7
|
+
const PACKAGE_VERSION = "0.4.0";
|
|
8
8
|
//#endregion
|
|
9
9
|
export { PACKAGE_NAME, PACKAGE_VERSION };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pithy-sh/auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -42,10 +42,10 @@
|
|
|
42
42
|
"better-auth": "^1.7.1"
|
|
43
43
|
},
|
|
44
44
|
"peerDependencies": {
|
|
45
|
-
"@pithy-sh/core": "^0.
|
|
46
|
-
"@pithy-sh/email": "^0.3.
|
|
47
|
-
"@pithy-sh/secrets": "^0.2.
|
|
48
|
-
"@pithy-sh/turnstile": "^0.2.
|
|
45
|
+
"@pithy-sh/core": "^0.6.0",
|
|
46
|
+
"@pithy-sh/email": "^0.3.2",
|
|
47
|
+
"@pithy-sh/secrets": "^0.2.2",
|
|
48
|
+
"@pithy-sh/turnstile": "^0.2.2",
|
|
49
49
|
"hono": "^4.13.2",
|
|
50
50
|
"kysely": "^0.29.0",
|
|
51
51
|
"zod": "^4.4.0"
|
package/src/capability.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
|
+
import type { D1Database } from "@cloudflare/workers-types";
|
|
4
5
|
import type { Capability, PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
|
|
5
6
|
import { defineCapability } from "@pithy-sh/core/src/capability/capability";
|
|
6
7
|
import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
@@ -140,8 +141,25 @@ export interface AuthWiring {
|
|
|
140
141
|
enqueueEmail: EmailCapability["enqueue"] | undefined;
|
|
141
142
|
/** The turnstile login gate, when the turnstile capability is composed. Set by `compose`. */
|
|
142
143
|
turnstile: { mode: TurnstileMode } | undefined;
|
|
144
|
+
/**
|
|
145
|
+
* The adopter's session-revoked listener, or absent. See {@link AuthOptions.onSessionRevoked}.
|
|
146
|
+
*
|
|
147
|
+
* Optional on the wiring rather than required-and-undefined, because a composition without a listener
|
|
148
|
+
* is the ordinary case and every harness that builds this shape by hand would otherwise have to say so.
|
|
149
|
+
*/
|
|
150
|
+
onSessionRevoked?: SessionRevokedListener | undefined;
|
|
143
151
|
}
|
|
144
152
|
|
|
153
|
+
/**
|
|
154
|
+
* Called when a session row is deleted — a sign-out, a revoke, an admin ending somebody's devices.
|
|
155
|
+
*
|
|
156
|
+
* **Handed this request's D1 binding**, because the auth instance is built per request and the listener
|
|
157
|
+
* almost certainly wants to write to the same database under a different capability's view of it. Taking
|
|
158
|
+
* the binding rather than a typed database keeps this seam out of the business of knowing whose tables
|
|
159
|
+
* the listener is about to touch.
|
|
160
|
+
*/
|
|
161
|
+
export type SessionRevokedListener = (session: { id: string; userId: string }, d1: D1Database) => Promise<void>;
|
|
162
|
+
|
|
145
163
|
/**
|
|
146
164
|
* What `auth()` takes: the config, plus the seams that are **behavior rather than data**.
|
|
147
165
|
*
|
|
@@ -166,6 +184,22 @@ export type AuthOptions = AuthConfigInput & {
|
|
|
166
184
|
* real per-address flag, always.
|
|
167
185
|
*/
|
|
168
186
|
resolveGithubUserInfo?: GithubUserInfoResolver;
|
|
187
|
+
/**
|
|
188
|
+
* Told when a session is revoked, so state another capability keyed on it can go with it.
|
|
189
|
+
*
|
|
190
|
+
* **On the row, not on the sign-out route.** A sign-out, a revoke and an admin ending somebody's
|
|
191
|
+
* devices all delete the same row, so a listener hung off one endpoint would miss the others.
|
|
192
|
+
*
|
|
193
|
+
* The case this exists for is `@pithy-sh/organization`: its acting selection is keyed by session id
|
|
194
|
+
* and its schema says signing out must take it with it. Tenancy depends on auth and not the reverse,
|
|
195
|
+
* so the composition holding both is what joins them, and this is the join.
|
|
196
|
+
*
|
|
197
|
+
* **Non-fatal by contract.** The session is already gone when this runs; a failure here must not turn
|
|
198
|
+
* a completed sign-out into an error the caller retries, so the instance swallows what it throws.
|
|
199
|
+
*
|
|
200
|
+
* A function, so it is destructured off before `AuthConfig.parse` for the reason above.
|
|
201
|
+
*/
|
|
202
|
+
onSessionRevoked?: SessionRevokedListener;
|
|
169
203
|
};
|
|
170
204
|
|
|
171
205
|
/** The auth capability, with its resolved config attached for inspection. */
|
|
@@ -215,7 +249,7 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
215
249
|
// Zod 4 objects strip unknown keys silently, so a `resolveGithubUserInfo` handed to `AuthConfig.parse`
|
|
216
250
|
// would vanish with no error and the adopter's override would simply never run. `payments()` splits
|
|
217
251
|
// its `resolveSubject` out for the same reason.
|
|
218
|
-
const { resolveGithubUserInfo, ...config } = options;
|
|
252
|
+
const { resolveGithubUserInfo, onSessionRevoked, ...config } = options;
|
|
219
253
|
const resolved = AuthConfig.parse(config);
|
|
220
254
|
// Additivity, before anything is built from the list. The four the kit composes are the sign-in this
|
|
221
255
|
// product promises and what the control-plane seam verifies against, so a list naming one of them is
|
|
@@ -229,6 +263,7 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
229
263
|
resolveGithubUserInfo,
|
|
230
264
|
enqueueEmail: undefined,
|
|
231
265
|
turnstile: undefined,
|
|
266
|
+
onSessionRevoked,
|
|
232
267
|
};
|
|
233
268
|
|
|
234
269
|
// Tier-1 edge rate limiter, contributed as middleware so it runs before session resolution.
|
package/src/data/betterAuth.ts
CHANGED
|
@@ -37,7 +37,12 @@ export const User = z
|
|
|
37
37
|
emailVerified: SQLiteBoolean.describe(
|
|
38
38
|
"Whether the email has been verified. Stored as `0|1`; magic-link/OTP sign-in sets it true.",
|
|
39
39
|
),
|
|
40
|
-
image: z
|
|
40
|
+
image: z
|
|
41
|
+
.string()
|
|
42
|
+
.nullable()
|
|
43
|
+
.describe(
|
|
44
|
+
"The user's picture: a URL on the provider that signed them in, or bytes this application stores as a bounded `data:` URL — see `../profile/profile.ts` for why the column takes two shapes. Null when nobody has set one, and then a caller draws initials, which is a real answer and not a placeholder.\n\n**Permissive here and strict on the write, exactly as `name` is, and the asymmetry is the point.** `UserImage` runs at the database hook, so nothing this kit writes can put an unacceptable value in the column. What this schema decodes is what is *already there* — a row a provider wrote before the rule existed, a repair script, a restored backup. A strict column turns one such row into a `ZodError` on every read that touches it, and `getUsers` parses a page of rows at once: one poisoned row would take down the whole roster for every operator rather than drawing one gap. That is the failure mode `./kitFields.ts` records for `locale`, and it is worse here, because a roster is read by people who did not write the row.\n\nThe value is made safe on the way **out** instead. `userImageSource` answers null for anything the rule does not recognize, so an unrecognized value renders as initials; and the serving route refuses to hand out bytes it cannot type.",
|
|
45
|
+
),
|
|
41
46
|
locale: Locale.nullable().describe(
|
|
42
47
|
"The reader's chosen language as a BCP-47 tag, or null when they have never chosen. Null is not the default locale: it means negotiate from `Accept-Language`, so an unchosen reader follows their device. A stored tag outranks the header.",
|
|
43
48
|
),
|
|
@@ -1,24 +1,21 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
|
+
import { zValidator } from "@hono/zod-validator";
|
|
4
5
|
import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
|
|
5
|
-
import { JsonDate } from "@pithy-sh/core/src/data/codecs";
|
|
6
6
|
import { type AmbientEnv, ambientEnv, compositionEnvironment } from "@pithy-sh/core/src/env/ambient";
|
|
7
7
|
import { isContinuousIntegration } from "@pithy-sh/core/src/env/ci";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
8
|
+
import { NotFoundError } from "@pithy-sh/core/src/error/pithyError";
|
|
9
|
+
import { validationHook } from "@pithy-sh/core/src/http/validation";
|
|
10
|
+
import { DEV_LOGIN_CLAIM_PARAM, DEV_LOGIN_ROUTE } from "@pithy-sh/core/src/seed/devLogin";
|
|
10
11
|
import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
|
|
11
12
|
import type { Context, Hono } from "hono";
|
|
12
13
|
import { z } from "zod";
|
|
13
14
|
import type { AuthWiring } from "../capability";
|
|
15
|
+
import { Session } from "../data/betterAuth";
|
|
14
16
|
import { authDatabase } from "../data/tables";
|
|
15
17
|
import { resolveSessionSecret } from "../instance/secrets";
|
|
16
|
-
import {
|
|
17
|
-
DEV_SESSION_COOKIE_NAME,
|
|
18
|
-
DEV_SESSION_TOKEN_PREFIX,
|
|
19
|
-
secretFingerprint,
|
|
20
|
-
signCookieValue,
|
|
21
|
-
} from "../seeds/devSession";
|
|
18
|
+
import { DEV_SESSION_COOKIE_NAME, signCookieValue, verifyDevLoginClaim } from "../seeds/devSession";
|
|
22
19
|
import { resolveDb } from "./resolve";
|
|
23
20
|
|
|
24
21
|
/**
|
|
@@ -66,30 +63,14 @@ export function registerDevLoginRoute(
|
|
|
66
63
|
if (compositionEnvironment(env) !== "dev") return;
|
|
67
64
|
// Gate two: continuous integration, independently. A `dev` composition in CI gets no route either.
|
|
68
65
|
if (isContinuousIntegration(env)) return;
|
|
69
|
-
|
|
66
|
+
// The claim is read here rather than inside the handler: `c.req.valid` is typed off the chain it was
|
|
67
|
+
// declared on, and a handler taking a bare `Context` has no validator to read from.
|
|
68
|
+
app.get(DEV_LOGIN_ROUTE, zValidator("query", DevLoginQuery, validationHook), (c) =>
|
|
69
|
+
serveDevLogin(c, wiring, c.req.valid("query")[DEV_LOGIN_CLAIM_PARAM]),
|
|
70
|
+
);
|
|
70
71
|
};
|
|
71
72
|
}
|
|
72
73
|
|
|
73
|
-
/**
|
|
74
|
-
* The seeded session row, narrowed to what handing it to a browser needs — and validated, because a D1
|
|
75
|
-
* row is a boundary like any other. `z.input` is the stored row (ISO-8601 text); `z.output` the app shape.
|
|
76
|
-
*/
|
|
77
|
-
const DevSessionRow = z
|
|
78
|
-
.object({
|
|
79
|
-
token: z
|
|
80
|
-
.string()
|
|
81
|
-
.min(1)
|
|
82
|
-
.describe("The seeded session's opaque token — signed with this environment's secret to make the cookie."),
|
|
83
|
-
expiresAt: JsonDate.describe("When the seeded session expires. ISO-8601 text in SQLite; a `Date` here."),
|
|
84
|
-
})
|
|
85
|
-
.describe("A seeded dev session, narrowed to the two columns the dev-login redirect needs.");
|
|
86
|
-
type DevSessionRow = z.output<typeof DevSessionRow>;
|
|
87
|
-
|
|
88
|
-
/** How long the browser is told to keep the cookie: whatever is left of the seeded session, never longer. */
|
|
89
|
-
function maxAgeSeconds(expiresAt: Date, now: Date): number {
|
|
90
|
-
return Math.floor((expiresAt.getTime() - now.getTime()) / 1000);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
74
|
/**
|
|
94
75
|
* The refusal when there is nothing to sign in as. A 404, because the honest answer is that this
|
|
95
76
|
* composition has no seeded session — not that the caller got something wrong.
|
|
@@ -110,48 +91,92 @@ function noSeededSession(): NotFoundError {
|
|
|
110
91
|
}
|
|
111
92
|
|
|
112
93
|
/**
|
|
113
|
-
*
|
|
94
|
+
* What the route takes: the claim, in the query.
|
|
95
|
+
*
|
|
96
|
+
* **Optional, and that is deliberate.** A required field would make a missing claim a 400 and a wrong one
|
|
97
|
+
* a 404, and the difference between those two answers is exactly what this route must not tell anybody.
|
|
98
|
+
* Declaring it optional puts every refusal in the handler, where there is one of them.
|
|
114
99
|
*
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
-
|
|
100
|
+
* Bounded because an unbounded query parameter is an unbounded read. The ceiling is far above any claim
|
|
101
|
+
* this seed mints; a value past it is refused for its length, which tells the sender only about the
|
|
102
|
+
* request they just made.
|
|
103
|
+
*/
|
|
104
|
+
const DevLoginQuery = z
|
|
105
|
+
.object({
|
|
106
|
+
[DEV_LOGIN_CLAIM_PARAM]: z
|
|
107
|
+
.string()
|
|
108
|
+
.max(4096)
|
|
109
|
+
.optional()
|
|
110
|
+
.describe("The signed claim naming the user to sign in as, as `pithy seed` wrote it into the URL."),
|
|
111
|
+
})
|
|
112
|
+
.describe("The dev-login route's query: a claim, or nothing and the same refusal as a wrong one.");
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Exchange a claim for a session, as a `Set-Cookie` and a redirect to `/`.
|
|
119
116
|
*
|
|
120
117
|
* Nothing about the cookie is logged, and nothing is written to a response body: the value exists in
|
|
121
|
-
* this handler and in the browser, and in no third place.
|
|
118
|
+
* this handler and in the browser, and in no third place. The claim that bought it is in the URL, which
|
|
119
|
+
* is the one place it has to be — `dev/devLogin.ts` in the CLI carries why, and keeps it out of every
|
|
120
|
+
* printed line it can.
|
|
122
121
|
*/
|
|
123
|
-
async function serveDevLogin(
|
|
122
|
+
async function serveDevLogin(
|
|
123
|
+
c: Context<PithyHonoEnv>,
|
|
124
|
+
wiring: AuthWiring,
|
|
125
|
+
presented: string | undefined,
|
|
126
|
+
): Promise<Response> {
|
|
127
|
+
if (!presented) throw noSeededSession();
|
|
128
|
+
|
|
124
129
|
const secret = await resolveSessionSecret(c.env as unknown as SecretsStoreEnv);
|
|
125
|
-
const
|
|
130
|
+
const now = new Date();
|
|
131
|
+
// One answer for malformed, for signed-by-another-secret, and for expired. Telling them apart would
|
|
132
|
+
// make this route a probe against the running secret.
|
|
133
|
+
const claim = await verifyDevLoginClaim(presented, secret, now);
|
|
134
|
+
if (!claim) throw noSeededSession();
|
|
126
135
|
|
|
127
136
|
const db = authDatabase(resolveDb(c.env, wiring.config.database));
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
137
|
+
// The user is proved to exist rather than assumed from the claim. A claim outliving the seed that
|
|
138
|
+
// named it — a reseed with a different `dev.json`, a user removed — must not mint a session pointing
|
|
139
|
+
// at nobody, which `get-session` would answer `null` for while the cookie looked like a way in.
|
|
140
|
+
const user = await db.selectFrom("pithyAuthUsers").select("id").where("id", "=", claim.userId).executeTakeFirst();
|
|
141
|
+
if (!user) throw noSeededSession();
|
|
142
|
+
|
|
143
|
+
/*
|
|
144
|
+
A real session, minted now — `#572`.
|
|
136
145
|
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
const
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
146
|
+
**Random, not derived.** The token this replaced was `dev-session-<userId>-<fingerprint>`, which made
|
|
147
|
+
it reproducible across reseeds and made every dev sign-in the same row. This one is a session like any
|
|
148
|
+
other: its own id, its own token, revoked on its own when somebody signs out, and leaving the claim
|
|
149
|
+
that produced it untouched. Nothing about it says "seeded", because nothing about it is — a person
|
|
150
|
+
opened a link and a session was created, which is what sign-in means.
|
|
151
|
+
*/
|
|
152
|
+
const token = crypto.randomUUID();
|
|
153
|
+
const expiresAt = new Date(now.getTime() + wiring.config.sessionExpiresIn * 1000);
|
|
154
|
+
await db
|
|
155
|
+
.insertInto("pithyAuthSessions")
|
|
156
|
+
.values(
|
|
157
|
+
Session.encode({
|
|
158
|
+
id: crypto.randomUUID(),
|
|
159
|
+
token,
|
|
160
|
+
userId: claim.userId,
|
|
161
|
+
expiresAt,
|
|
162
|
+
createdAt: now,
|
|
163
|
+
updatedAt: now,
|
|
164
|
+
ipAddress: "127.0.0.1",
|
|
165
|
+
userAgent: "pithy dev login",
|
|
166
|
+
deviceId: null,
|
|
167
|
+
familyId: null,
|
|
168
|
+
// A dev login is a real sign-in, so it is authenticated now — what the live hook stamps.
|
|
169
|
+
authenticatedAt: now,
|
|
170
|
+
}),
|
|
171
|
+
)
|
|
172
|
+
.execute();
|
|
149
173
|
|
|
150
|
-
const value = await signCookieValue(
|
|
174
|
+
const value = await signCookieValue(token, secret);
|
|
151
175
|
// The attributes Better Auth's own session cookie carries in a `dev` composition: `HttpOnly` (a
|
|
152
176
|
// session token has no business in `document.cookie`, which is also the habit this route retires),
|
|
153
177
|
// `SameSite=Lax`, root path. No `Secure` — a `dev` base URL is `http://localhost`, and a `Secure`
|
|
154
178
|
// cookie there is one the browser accepts and never sends back.
|
|
179
|
+
const maxAge = Math.floor((expiresAt.getTime() - now.getTime()) / 1000);
|
|
155
180
|
const cookie = `${DEV_SESSION_COOKIE_NAME}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}`;
|
|
156
181
|
// 302 to the app root rather than 200 with a page: the developer asked to be signed in, not to read a
|
|
157
182
|
// confirmation, and a redirect leaves the address bar on the app instead of on this route.
|
package/src/http/resolve.ts
CHANGED
|
@@ -111,8 +111,14 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
|
|
|
111
111
|
resolveProvider(cfg.github.enabled, () => resolveGithubCredentials(env)),
|
|
112
112
|
]);
|
|
113
113
|
const expiresMinutes = Math.max(1, Math.round(cfg.verificationExpiresIn / 60));
|
|
114
|
+
const d1 = resolveDb(c.env, cfg.database);
|
|
115
|
+
const listener = wiring.onSessionRevoked;
|
|
114
116
|
return makeAuth({
|
|
115
|
-
db: authDatabase(
|
|
117
|
+
db: authDatabase(d1),
|
|
118
|
+
// The adopter's listener, bound to *this* request's binding. The instance is built per request, so
|
|
119
|
+
// there is a real binding to hand over here and nowhere earlier — `auth()` runs at compose time and
|
|
120
|
+
// has none.
|
|
121
|
+
...(listener ? { onSessionRevoked: (session: { id: string; userId: string }) => listener(session, d1) } : {}),
|
|
116
122
|
secret,
|
|
117
123
|
// Never `cfg.baseURL` directly. The instance derives the session cookie's name, the OAuth callback
|
|
118
124
|
// URLs, and the magic-link URL from whatever base URL it is handed, so in a `dev` composition every
|
package/src/http/routes.ts
CHANGED
|
@@ -3,9 +3,10 @@
|
|
|
3
3
|
|
|
4
4
|
import { zValidator } from "@hono/zod-validator";
|
|
5
5
|
import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
|
|
6
|
-
import { UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
|
|
6
|
+
import { NotFoundError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
|
|
7
7
|
import { requireSameOrigin } from "@pithy-sh/core/src/http/sameOrigin";
|
|
8
8
|
import { validationHook } from "@pithy-sh/core/src/http/validation";
|
|
9
|
+
import { STORED_IMAGE_HEADERS, storedImageBytes } from "@pithy-sh/core/src/image/storedImage";
|
|
9
10
|
import { TURNSTILE_LOGIN_ACTION } from "@pithy-sh/turnstile/src/config/config";
|
|
10
11
|
import { turnstile } from "@pithy-sh/turnstile/src/http/middleware";
|
|
11
12
|
import type { Context, Hono } from "hono";
|
|
@@ -13,6 +14,7 @@ import { correlation, emitDenied, emitDeviceRevoked, emitTokenRefresh, emitToken
|
|
|
13
14
|
import type { AuthWiring } from "../capability";
|
|
14
15
|
import { authDatabase } from "../data/tables";
|
|
15
16
|
import { deleteDevice, deviceSessionTokens, listDevices } from "../device/registry";
|
|
17
|
+
import { PROFILE_IMAGE_PATH } from "../profile/profile";
|
|
16
18
|
import {
|
|
17
19
|
consumeSession,
|
|
18
20
|
findConsumedToken,
|
|
@@ -96,6 +98,10 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
|
|
|
96
98
|
app.post(`${base}/link-social`, requireFreshAuthentication("link"), (c) => handleBetterAuth(c, wiring));
|
|
97
99
|
app.post(`${base}/unlink-account`, requireFreshAuthentication("unlink"), (c) => handleBetterAuth(c, wiring));
|
|
98
100
|
|
|
101
|
+
// The caller's own stored picture, as bytes a browser can cache. No id in the path — see
|
|
102
|
+
// `serveMyImage`, which is where the reason lives.
|
|
103
|
+
app.get(`${base}${PROFILE_IMAGE_PATH}`, requireAuth(), (c) => serveMyImage(c, wiring));
|
|
104
|
+
|
|
99
105
|
// The control-plane management surface. Registered here, before the catch-all below, or it is dead.
|
|
100
106
|
registerAuthAdminRoutes(wiring)(app);
|
|
101
107
|
|
|
@@ -351,3 +357,49 @@ async function revokeMyDevice(c: Ctx, wiring: AuthWiring, body: RevokeDeviceBody
|
|
|
351
357
|
await emitDeviceRevoked(c.var.emit, { userId, ...correlation(c.req.raw.headers) });
|
|
352
358
|
return c.json({ revoked: tokens.length });
|
|
353
359
|
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Serve the signed-in caller's own stored picture.
|
|
363
|
+
*
|
|
364
|
+
* **There is no id in the path, and that is the security design rather than a simplification.** A
|
|
365
|
+
* serving route addressed by user id has to answer *is this caller entitled to see this person*, and
|
|
366
|
+
* this capability has no such notion — everyone signed in is a peer, so any answer it invented would be
|
|
367
|
+
* either an enumeration oracle or a guess. The subject here is the session, so there is nothing to
|
|
368
|
+
* enumerate. A roster of *other* people's faces is a tenancy question, and `@pithy-sh/organization`
|
|
369
|
+
* answers it with membership, through the same core helpers.
|
|
370
|
+
*
|
|
371
|
+
* **A vector is refused rather than served with headers.** `storedImageBytes` answers null for one and
|
|
372
|
+
* this 404s on null — so there is no arrangement of parameters that makes this origin return an SVG by
|
|
373
|
+
* navigation, which would run script in it. `@pithy-sh/core/src/image/storedImage` carries the full
|
|
374
|
+
* argument.
|
|
375
|
+
*
|
|
376
|
+
* A provider link 404s too, for the same reason it is not this origin's to serve: it is already a URL
|
|
377
|
+
* somewhere else, and `userImageSource` hands the client that URL directly rather than this path.
|
|
378
|
+
*
|
|
379
|
+
* The response is `immutable` because `userImageSource` puts the row's `updatedAt` in the query, and
|
|
380
|
+
* `private` because it was authorized against a session.
|
|
381
|
+
*/
|
|
382
|
+
async function serveMyImage(c: Ctx, wiring: AuthWiring): Promise<Response> {
|
|
383
|
+
const auth = c.var.auth;
|
|
384
|
+
if (!auth) throw new UnauthorizedError({ message: "Sign in to see this." });
|
|
385
|
+
// Named columns, never `select *`: this table sits beside `pithy_auth_accounts`, and a habit of
|
|
386
|
+
// widening a select on the auth schema is how a provider token reaches a log.
|
|
387
|
+
const row = await db(c, wiring)
|
|
388
|
+
.selectFrom("pithyAuthUsers")
|
|
389
|
+
.select(["image"])
|
|
390
|
+
.where("id", "=", auth.userId)
|
|
391
|
+
.executeTakeFirst();
|
|
392
|
+
const bytes = storedImageBytes(row?.image ?? null);
|
|
393
|
+
if (!bytes) {
|
|
394
|
+
// One answer for four different facts — no row, no picture, a linked one, a vector. The caller is
|
|
395
|
+
// asking about themselves, so none of them is a secret; they are one answer because the route has
|
|
396
|
+
// exactly one thing to say, which is *nothing to serve here*.
|
|
397
|
+
throw new NotFoundError({
|
|
398
|
+
message: "No picture to show.",
|
|
399
|
+
detail: `user ${auth.userId}: ${row === undefined || row.image === null ? "no stored picture" : "picture is linked or a vector, neither served by URL"}`,
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
return new Response(bytes.body as unknown as BodyInit, {
|
|
403
|
+
headers: { "content-type": bytes.type, ...STORED_IMAGE_HEADERS },
|
|
404
|
+
});
|
|
405
|
+
}
|
package/src/instance/auth.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { KIT_SESSION_FIELDS, KIT_USER_FIELDS } from "../data/kitFields";
|
|
|
9
9
|
import type { AuthDatabase } from "../data/tables";
|
|
10
10
|
import { parseDeviceMeta, registerDevice } from "../device/registry";
|
|
11
11
|
import { PROVIDER_CHANGE_FRESH_AGE_SECONDS } from "../http/providerFreshness";
|
|
12
|
+
import { refuseUnsafeProfile, sanitizeProfile } from "../profile/profile";
|
|
12
13
|
import { defaultGithubUserInfo, type GithubUserInfoResolver } from "./githubUserInfo";
|
|
13
14
|
import { kitPlugins } from "./plugins";
|
|
14
15
|
import {
|
|
@@ -113,6 +114,21 @@ export function isUnverifiedSignup(user: { emailVerified?: boolean | null }): bo
|
|
|
113
114
|
return user.emailVerified !== true;
|
|
114
115
|
}
|
|
115
116
|
|
|
117
|
+
/**
|
|
118
|
+
* Refuse a write whose `name` or `image` is not a shape this kit will render, with a 400 naming the
|
|
119
|
+
* field.
|
|
120
|
+
*
|
|
121
|
+
* The decision is `../profile/profile.ts`'s and is pure; this is the half that needs `APIError`, which
|
|
122
|
+
* is what turns a refusal into a 400 instead of a row that throws on every later read. That failure
|
|
123
|
+
* mode is the one `../data/kitFields.ts` already documents for `locale`: a bad value written once makes
|
|
124
|
+
* the *listing* fail for every operator rather than only for its author.
|
|
125
|
+
*/
|
|
126
|
+
function refuseUnsafeProfileFields(user: { name?: unknown; image?: unknown }): void {
|
|
127
|
+
const refusal = refuseUnsafeProfile(user);
|
|
128
|
+
if (!refusal) return;
|
|
129
|
+
throw new APIError("BAD_REQUEST", { code: "INVALID_PROFILE_FIELD", message: refusal.message });
|
|
130
|
+
}
|
|
131
|
+
|
|
116
132
|
/**
|
|
117
133
|
* What the instance hands to Pithy's email seam to deliver. The route never sends inline — the hook
|
|
118
134
|
* enqueues an `@pithy-sh/email` job (`magicLink`/`otp` template) which a Workflow delivers.
|
|
@@ -184,6 +200,21 @@ export interface AuthInstanceDeps<Plugins extends readonly BetterAuthPlugin[] =
|
|
|
184
200
|
resolveGithubUserInfo?: GithubUserInfoResolver;
|
|
185
201
|
/** Audit seam — emits `auth/*` events. A no-op when the audit capability is absent. */
|
|
186
202
|
emit: AuditEmit;
|
|
203
|
+
/**
|
|
204
|
+
* Called when a session row is deleted — a sign-out, a revoke, an admin ending somebody's devices.
|
|
205
|
+
*
|
|
206
|
+
* **The seam exists because a session id is a key other capabilities hang state on**, and nothing
|
|
207
|
+
* else tells them it has gone. `@pithy-sh/organization` keys its acting selection by session id and
|
|
208
|
+
* states that signing out must take it with it; without this there was no moment at which it could,
|
|
209
|
+
* so every sign-in/sign-out cycle left an orphan row in a table with no TTL and no sweep.
|
|
210
|
+
*
|
|
211
|
+
* Wired by the project that composes both — a capability does not reach into another, and the
|
|
212
|
+
* direction is wrong anyway: tenancy depends on auth, not the reverse.
|
|
213
|
+
*
|
|
214
|
+
* **Non-fatal by contract.** By the time this runs the session is already gone; a failure here must
|
|
215
|
+
* not turn a completed sign-out into an error the caller retries. Implementations swallow their own.
|
|
216
|
+
*/
|
|
217
|
+
onSessionRevoked?: (session: { id: string; userId: string }) => Promise<void>;
|
|
187
218
|
/**
|
|
188
219
|
* The adopter's additional Better Auth plugins, from `auth({ plugins: [...] })`. Composed **after**
|
|
189
220
|
* the kit's own, never in place of one — `assertAdditivePlugins` has already refused a list that
|
|
@@ -252,6 +283,21 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
|
|
|
252
283
|
"This email isn't verified by the provider. Sign in with a magic link to verify it, then connect the provider.",
|
|
253
284
|
});
|
|
254
285
|
}
|
|
286
|
+
// **Sanitized, not refused.** This is a provider's profile arriving mid-sign-in, and the
|
|
287
|
+
// person signing in did not choose it — see `../profile/profile.ts`. A long name is
|
|
288
|
+
// truncated, an avatar this kit will not hold becomes initials, and they get in.
|
|
289
|
+
const safe = sanitizeProfile(user);
|
|
290
|
+
if (Object.keys(safe).length > 0) return { data: { ...user, ...safe } };
|
|
291
|
+
},
|
|
292
|
+
},
|
|
293
|
+
update: {
|
|
294
|
+
// The profile gate. **Every** write to `name` or `image` passes through here — Better Auth's
|
|
295
|
+
// own `/update-user`, an adopter's route, an admin tool — because the hook is at the adapter
|
|
296
|
+
// rather than at any one door. `../profile/profile.ts` records why a validator declared
|
|
297
|
+
// beside the column would not have run: `parseUserInput` reaches the additional fields only,
|
|
298
|
+
// and these two are Better Auth's own.
|
|
299
|
+
before: async (user) => {
|
|
300
|
+
refuseUnsafeProfileFields(user);
|
|
255
301
|
},
|
|
256
302
|
},
|
|
257
303
|
},
|
|
@@ -296,6 +342,27 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
|
|
|
296
342
|
return { data: { ...session, deviceId: meta.id, authenticatedAt } };
|
|
297
343
|
},
|
|
298
344
|
},
|
|
345
|
+
delete: {
|
|
346
|
+
/**
|
|
347
|
+
* Tell whoever keyed state on this session that it has gone.
|
|
348
|
+
*
|
|
349
|
+
* A sign-out, a revoke, an admin ending somebody's devices — all of them land here, which is
|
|
350
|
+
* why the seam is on the row rather than on the sign-out endpoint. A handler wired to one
|
|
351
|
+
* endpoint would miss the other three, and the row is what the state was keyed by.
|
|
352
|
+
*
|
|
353
|
+
* **After, not before.** The session is already gone when this runs, so a slow or failing
|
|
354
|
+
* listener cannot hold up or refuse a sign-out — and it swallows its own failure for the same
|
|
355
|
+
* reason the audit emit does: the thing it reports has already happened.
|
|
356
|
+
*/
|
|
357
|
+
after: async (session) => {
|
|
358
|
+
if (!deps.onSessionRevoked) return;
|
|
359
|
+
try {
|
|
360
|
+
await deps.onSessionRevoked({ id: String(session.id), userId: String(session.userId) });
|
|
361
|
+
} catch {
|
|
362
|
+
// Swallowed by contract. The sign-out succeeded; a listener's failure is not the caller's.
|
|
363
|
+
}
|
|
364
|
+
},
|
|
365
|
+
},
|
|
299
366
|
},
|
|
300
367
|
},
|
|
301
368
|
hooks: {
|
|
@@ -14,8 +14,16 @@ import type { Migration } from "kysely/migration";
|
|
|
14
14
|
* every identifier in the emitted DDL (CLAUDE.md §Data layer) — and the same plugin lets Better
|
|
15
15
|
* Auth's camelCase queries land on these snake_case columns. Better-Auth `date` columns are **text**
|
|
16
16
|
* (it stores ISO-8601 strings on SQLite; ISO sorts chronologically); Pithy's own device timestamps
|
|
17
|
-
* are **integer** ms-epoch.
|
|
18
|
-
*
|
|
17
|
+
* are **integer** ms-epoch. Linkage is by indexed id columns.
|
|
18
|
+
*
|
|
19
|
+
* **No foreign keys across a capability boundary — a choice, not a limitation.** D1 *does* enforce
|
|
20
|
+
* them: `PRAGMA foreign_keys` is on, a cascade fires, and an orphan insert is refused with
|
|
21
|
+
* `FOREIGN KEY constraint failed`. `packages/core/src/data/foreignKeys.workers.test.ts` measures both
|
|
22
|
+
* directions, because this is the kind of claim that rots quietly. What is traded away is real, and the
|
|
23
|
+
* reason is the boundary rather than the platform: a constraint from one capability's table to another's
|
|
24
|
+
* binds two release cadences together and breaks the day either moves to its own database. Within a
|
|
25
|
+
* single capability's own tables a foreign key is available and is simply not used here — worth
|
|
26
|
+
* revisiting per table rather than as a rule.
|
|
19
27
|
*
|
|
20
28
|
* `down` is the tested inverse — indexes then tables, in reverse creation order (D1 has no
|
|
21
29
|
* transactional DDL, so order matters).
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
INLINE_IMAGE_TYPES,
|
|
6
|
+
StoredImage,
|
|
7
|
+
storedImageSource,
|
|
8
|
+
typeOfStoredImage,
|
|
9
|
+
} from "@pithy-sh/core/src/image/storedImage";
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A person's own display name and face — the two things about themselves they may change.
|
|
14
|
+
*
|
|
15
|
+
* ## Why the column takes two shapes
|
|
16
|
+
*
|
|
17
|
+
* `pithy_auth_users.image` has always held **a link**: a URL on whichever provider signed somebody in,
|
|
18
|
+
* written once and never again. Two things follow, and both are things every adopter hits.
|
|
19
|
+
*
|
|
20
|
+
* **A linked avatar is a third-party fetch per face.** A roster of twenty people is twenty requests to
|
|
21
|
+
* hosts the viewer did not choose, leaking their IP and referrer before they had done anything, and it
|
|
22
|
+
* needs a CSP hole to render at all.
|
|
23
|
+
*
|
|
24
|
+
* **And nothing in the kit could change it.** Somebody who signed in with GitHub was called whatever
|
|
25
|
+
* GitHub calls them, forever.
|
|
26
|
+
*
|
|
27
|
+
* So the column keeps accepting the provider URL it already holds — an existing row is untouched — and
|
|
28
|
+
* gains a second accepted shape: bytes, stored as a bounded `data:` URL under the kit's one image rule
|
|
29
|
+
* (`@pithy-sh/core/src/image/storedImage`). Where the column is settable by its subject, the host is
|
|
30
|
+
* chosen by them.
|
|
31
|
+
*
|
|
32
|
+
* ## Why the rule is core's and not this package's
|
|
33
|
+
*
|
|
34
|
+
* `@pithy-sh/organization` holds an account's mark under the identical rule. It is the same object at a
|
|
35
|
+
* different scale, and two answers to *what may be stored as an image* is one of them being wrong.
|
|
36
|
+
*
|
|
37
|
+
* ## Why this is `auth` and not `organization`
|
|
38
|
+
*
|
|
39
|
+
* Somebody in two accounts is the same person in both, and being asked to upload the same photograph
|
|
40
|
+
* twice would be a product mistaking a membership for an identity. A single-tenant app — a consumer app
|
|
41
|
+
* with no organizations at all — wants a display name and a face just as much, and should not have to
|
|
42
|
+
* compose a tenancy capability to get one.
|
|
43
|
+
*
|
|
44
|
+
* ## What this package does *not* decide: who may see whose face
|
|
45
|
+
*
|
|
46
|
+
* Serving a raster by URL needs an answer to *is this caller entitled to see this person*, and this
|
|
47
|
+
* capability has no such notion — everyone signed in is a peer. So the route here serves exactly one
|
|
48
|
+
* image: **the caller's own**, at a path carrying no id at all, which cannot be an enumeration oracle
|
|
49
|
+
* because there is nothing in it to enumerate. A roster of other people's faces is a tenancy question,
|
|
50
|
+
* and `@pithy-sh/organization` answers it with membership, through the same core helpers.
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The ceiling on a display name, in characters — applied on the **write** and not on the read.
|
|
55
|
+
*
|
|
56
|
+
* Deliberately asymmetric, and the reason is the one `data/kitFields.ts` already records: a bound on
|
|
57
|
+
* the *column* schema turns a row a provider wrote before the bound existed into a row that throws on
|
|
58
|
+
* every later read, and an admin listing reading a page of rows would then fail for every operator
|
|
59
|
+
* rather than only for the author. A bound on the write is a 400 to the one caller who exceeded it.
|
|
60
|
+
*
|
|
61
|
+
* 256, which is longer than any name and short enough that a roster cannot be made expensive with it.
|
|
62
|
+
*/
|
|
63
|
+
export const MAX_DISPLAY_NAME_CHARS = 256;
|
|
64
|
+
|
|
65
|
+
/** A display name somebody may set for themselves. Trimmed by the caller; bounded here. */
|
|
66
|
+
export const DisplayName = z
|
|
67
|
+
.string()
|
|
68
|
+
.min(1)
|
|
69
|
+
.max(MAX_DISPLAY_NAME_CHARS)
|
|
70
|
+
.describe(
|
|
71
|
+
"What this application calls somebody, as they typed it. Bounded on the write rather than on the column, so a longer name a provider wrote before the bound existed still reads.",
|
|
72
|
+
);
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* A picture linked on a provider's host — the shape the column has always held.
|
|
76
|
+
*
|
|
77
|
+
* Accepted rather than blessed: it is what Google, GitHub and Apple write at sign-in, and refusing it
|
|
78
|
+
* would break every existing row. **Bounded and scheme-pinned**, because the only two things that can
|
|
79
|
+
* be checked about somebody else's URL are how long it is and that it is not a `javascript:` or `data:`
|
|
80
|
+
* payload wearing a URL's clothes.
|
|
81
|
+
*/
|
|
82
|
+
export const ProviderImageUrl = z
|
|
83
|
+
.url({ protocol: /^https?$/ })
|
|
84
|
+
.max(2048)
|
|
85
|
+
.describe(
|
|
86
|
+
"An avatar on the provider's own host, written at sign-in. A third-party fetch per face — see the module note for why a stored image is preferred.",
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* What `pithy_auth_users.image` may hold: a provider's link, or bytes this application stores.
|
|
91
|
+
*
|
|
92
|
+
* The union is ordered link-first only for readability; the two shapes cannot both match, because a
|
|
93
|
+
* `data:` URL is not `http(s):` and a stored image is pinned to an allowlisted media type inline in the
|
|
94
|
+
* string. `data:text/html` matches neither, which is the whole of what makes this column safe to render.
|
|
95
|
+
*/
|
|
96
|
+
export const UserImage = z
|
|
97
|
+
.union([ProviderImageUrl, StoredImage])
|
|
98
|
+
.describe(
|
|
99
|
+
"A person's picture: either a provider URL, as the column has always held, or bytes stored under the kit's image rule. Rendered only through `<img>`.",
|
|
100
|
+
);
|
|
101
|
+
export type UserImage = z.output<typeof UserImage>;
|
|
102
|
+
|
|
103
|
+
/** The path a signed-in caller's own stored raster is served from, relative to the auth base path. */
|
|
104
|
+
export const PROFILE_IMAGE_PATH = "/profile/image";
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* What a screen should draw this person's face from.
|
|
108
|
+
*
|
|
109
|
+
* Three answers, and a caller renders every one of them through the same `<img src>`:
|
|
110
|
+
*
|
|
111
|
+
* - **A provider link passes through.** It is already a URL and already cached by somebody else; there
|
|
112
|
+
* is nothing this origin can add to it.
|
|
113
|
+
* - **A stored raster becomes a versioned URL on this origin**, so a browser caches it and a roster
|
|
114
|
+
* costs one request per face once rather than its bytes on every read.
|
|
115
|
+
* - **A stored vector stays inline**, and the serving route refuses to serve one. An `<img src>` is
|
|
116
|
+
* inert by specification; a URL is navigable, and a navigated SVG runs script in the origin that
|
|
117
|
+
* served it. The class of attack is removed rather than managed with headers.
|
|
118
|
+
*
|
|
119
|
+
* `path` is where the owning capability serves bytes from — `basePath + PROFILE_IMAGE_PATH` here, and a
|
|
120
|
+
* membership-scoped path in `@pithy-sh/organization`.
|
|
121
|
+
*/
|
|
122
|
+
export function userImageSource(image: string | null, path: string, version: Date | number): string | null {
|
|
123
|
+
if (image === null) return null;
|
|
124
|
+
// A provider link is not a stored image, and `storedImageSource` would answer null for it — which is
|
|
125
|
+
// right for a column value nobody recognizes and wrong for the one shape this column was born
|
|
126
|
+
// holding. Checked here rather than there, because core's rule is about stored bytes and this is the
|
|
127
|
+
// package that also accepts a link.
|
|
128
|
+
if (typeOfStoredImage(image) === null) return ProviderImageUrl.safeParse(image).success ? image : null;
|
|
129
|
+
return storedImageSource(image, path, version);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Whether this value is drawn inline rather than fetched.
|
|
134
|
+
*
|
|
135
|
+
* Exported for the projection tests and for a caller deciding whether a listing response is carrying
|
|
136
|
+
* bytes — which is what `@pithy-sh/organization`'s roster budget counts.
|
|
137
|
+
*/
|
|
138
|
+
export function isInlineImage(image: string | null): boolean {
|
|
139
|
+
if (image === null) return false;
|
|
140
|
+
const type = typeOfStoredImage(image);
|
|
141
|
+
return type !== null && INLINE_IMAGE_TYPES.includes(type);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** A profile field a write supplied, and why it was refused. */
|
|
145
|
+
export interface ProfileRefusal {
|
|
146
|
+
/** Which field failed — `name` or `image`. Named so a caller's message can say which. */
|
|
147
|
+
readonly field: "name" | "image";
|
|
148
|
+
/** Client-safe text. Says what is wrong without echoing the value back. */
|
|
149
|
+
readonly message: string;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Check the profile fields of a write, or say which one is refused and why.
|
|
154
|
+
*
|
|
155
|
+
* **This is the gate, and it sits at the database hook rather than at a route, deliberately.** Better
|
|
156
|
+
* Auth's own `/update-user` endpoint pulls `name` and `image` out of the body and passes them straight
|
|
157
|
+
* to the adapter — `parseUserInput` runs `validator.input` over the *additional* fields only, so the
|
|
158
|
+
* mechanism `KIT_USER_FIELDS` relies on for `locale` does not reach these two at all. A validator
|
|
159
|
+
* declared next to the column would therefore have been a validator nothing ran.
|
|
160
|
+
*
|
|
161
|
+
* A `databaseHooks.user` hook does reach it, and reaches every other producer with it: `/update-user`,
|
|
162
|
+
* a social sign-in writing a provider's avatar, an admin route, and whatever the adopter composes next.
|
|
163
|
+
* One rule, at the thing being called rather than at each call site.
|
|
164
|
+
*
|
|
165
|
+
* Absent fields pass: a write that does not mention a field is not a write to it.
|
|
166
|
+
*/
|
|
167
|
+
export function refuseUnsafeProfile(fields: { name?: unknown; image?: unknown }): ProfileRefusal | null {
|
|
168
|
+
if (fields.name !== undefined && fields.name !== null && !DisplayName.safeParse(fields.name).success) {
|
|
169
|
+
return {
|
|
170
|
+
field: "name",
|
|
171
|
+
message: `A name is between 1 and ${MAX_DISPLAY_NAME_CHARS} characters.`,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
if (fields.image !== undefined && fields.image !== null && !UserImage.safeParse(fields.image).success) {
|
|
175
|
+
return {
|
|
176
|
+
field: "image",
|
|
177
|
+
// Says the shape rather than the reason it matters: a caller learns what to send, and an attacker
|
|
178
|
+
// probing for `data:text/html` learns only that it was refused.
|
|
179
|
+
message: "A picture must be an https URL or an image this application stores, within the size limit.",
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** What a sign-in's profile fields become after the kit has made them safe to store. */
|
|
186
|
+
export interface SanitizedProfile {
|
|
187
|
+
/** The name, truncated to the bound. Absent when the write did not mention one. */
|
|
188
|
+
readonly name?: string;
|
|
189
|
+
/** The picture, or null when the provider offered one this kit will not hold. */
|
|
190
|
+
readonly image?: string | null;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Make a **provider's** profile fields storable, rather than refusing them.
|
|
195
|
+
*
|
|
196
|
+
* The asymmetry with {@link refuseUnsafeProfile} is the point, and it is about whose act it is.
|
|
197
|
+
*
|
|
198
|
+
* A person setting their own name and picture is one caller doing one thing: a 400 tells them what to
|
|
199
|
+
* send, and they send it. A provider's profile arrives in the middle of somebody signing in, and they
|
|
200
|
+
* did not choose it — refusing there would mean **a person cannot sign in because Google gave them a
|
|
201
|
+
* long display name.** So an over-long name is truncated and an avatar this kit will not hold becomes
|
|
202
|
+
* no avatar, which draws initials, which is a real answer.
|
|
203
|
+
*
|
|
204
|
+
* Nothing unsafe reaches the column either way. The two paths differ in what they do about it, not in
|
|
205
|
+
* what they accept.
|
|
206
|
+
*/
|
|
207
|
+
export function sanitizeProfile(fields: { name?: unknown; image?: unknown }): SanitizedProfile {
|
|
208
|
+
const sanitized: { name?: string; image?: string | null } = {};
|
|
209
|
+
if (fields.name !== undefined && !DisplayName.safeParse(fields.name).success) {
|
|
210
|
+
/*
|
|
211
|
+
**Every value that is not a name, not only the long ones.**
|
|
212
|
+
|
|
213
|
+
The guard was `typeof fields.name === "string" && …`, so a `name` that arrived as a number or an
|
|
214
|
+
object failed the first clause and was neither truncated nor replaced — it fell through untouched
|
|
215
|
+
and was spread into the row by the `create.before` hook. The `image` branch below never had that
|
|
216
|
+
gap, because `UserImage.safeParse` fails for any non-string, and `refuseUnsafeProfile` covers the
|
|
217
|
+
update path. This was the one way in that did not.
|
|
218
|
+
|
|
219
|
+
Truncated rather than dropped where there is something to truncate: Better Auth's user model
|
|
220
|
+
requires a name, and an empty one is a row every roster renders as a blank. A slice of a long name
|
|
221
|
+
is still recognisably them; a value that was never a string has nothing to slice, so it becomes the
|
|
222
|
+
same placeholder an empty slice would.
|
|
223
|
+
*/
|
|
224
|
+
sanitized.name = typeof fields.name === "string" ? fields.name.slice(0, MAX_DISPLAY_NAME_CHARS) || "—" : "—";
|
|
225
|
+
}
|
|
226
|
+
if (fields.image !== undefined && fields.image !== null && !UserImage.safeParse(fields.image).success) {
|
|
227
|
+
sanitized.image = null;
|
|
228
|
+
}
|
|
229
|
+
return sanitized;
|
|
230
|
+
}
|
package/src/seeds/devSession.ts
CHANGED
|
@@ -5,15 +5,8 @@ import { normalizeAddress } from "@pithy-sh/core/src/address/address";
|
|
|
5
5
|
import { fromZodError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
6
6
|
import { MAX_SEED_ORDER } from "@pithy-sh/core/src/seed/compose";
|
|
7
7
|
import { DEV_LOGIN_FILE, DEV_LOGIN_PATH, DevLogin } from "@pithy-sh/core/src/seed/devLogin";
|
|
8
|
-
import {
|
|
9
|
-
d1SeedGroup,
|
|
10
|
-
defineSeed,
|
|
11
|
-
type SeedPreparation,
|
|
12
|
-
type SeedPrepareContext,
|
|
13
|
-
type SeedSet,
|
|
14
|
-
} from "@pithy-sh/core/src/seed/seed";
|
|
8
|
+
import { defineSeed, type SeedPreparation, type SeedPrepareContext, type SeedSet } from "@pithy-sh/core/src/seed/seed";
|
|
15
9
|
import { z } from "zod";
|
|
16
|
-
import { Session } from "../data/betterAuth";
|
|
17
10
|
import { DEV_PROTOCOL, sessionCookieName } from "../http/baseUrl";
|
|
18
11
|
import { AUTH_SESSION_SECRET } from "../instance/secrets";
|
|
19
12
|
|
|
@@ -71,20 +64,12 @@ const USERS_TABLE = "pithyAuthUsers";
|
|
|
71
64
|
export const DEV_SESSION_COOKIE_NAME = sessionCookieName(DEV_PROTOCOL);
|
|
72
65
|
|
|
73
66
|
/**
|
|
74
|
-
*
|
|
67
|
+
* How long a dev login stays usable. Long, because reseeding to restore one is the friction this removes.
|
|
75
68
|
*
|
|
76
|
-
* It
|
|
77
|
-
*
|
|
78
|
-
* filesystem). And it is what makes one identifiable at all — a `pithy_auth_sessions` row minted by a
|
|
79
|
-
* seed is otherwise indistinguishable from one a real sign-in created.
|
|
69
|
+
* It bounds the *claim*, not a session — `#572`. The session the route mints from it lives by the auth
|
|
70
|
+
* config's own `sessionExpiresIn`, exactly as a real sign-in does, because it *is* one.
|
|
80
71
|
*/
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
/** How long a seeded session lives. Long, because reseeding to restore a dev login is the friction this removes. */
|
|
84
|
-
const DEV_SESSION_LIFETIME_MS = 365 * 24 * 60 * 60 * 1000;
|
|
85
|
-
|
|
86
|
-
/** Bytes of the secret digest kept as the token's fingerprint — enough to separate secrets, short enough to read. */
|
|
87
|
-
const FINGERPRINT_BYTES = 4;
|
|
72
|
+
const DEV_LOGIN_LIFETIME_MS = 365 * 24 * 60 * 60 * 1000;
|
|
88
73
|
|
|
89
74
|
/** The developer's machine-local preferences for this project, read from `~/.config/pithy/<project>/dev.json`. */
|
|
90
75
|
export const DevPreferences = z
|
|
@@ -115,11 +100,9 @@ export const SeededUser = z
|
|
|
115
100
|
.describe("A seeded `pithy_auth_users` row, narrowed to what minting a dev session for it requires.");
|
|
116
101
|
export type SeededUser = z.output<typeof SeededUser>;
|
|
117
102
|
|
|
118
|
-
/** What {@link
|
|
119
|
-
export interface
|
|
120
|
-
/** The
|
|
121
|
-
session: Session;
|
|
122
|
-
/** The dev-login artifact, written to `logs/dev-login.json` once the row lands. */
|
|
103
|
+
/** What {@link mintDevLogin} produces. One field, because a dev login is no longer a row — `#572`. */
|
|
104
|
+
export interface MintedDevLogin {
|
|
105
|
+
/** The dev-login artifact, written to `logs/dev-login.json`. */
|
|
123
106
|
login: DevLogin;
|
|
124
107
|
}
|
|
125
108
|
|
|
@@ -145,65 +128,139 @@ export async function signCookieValue(value: string, secret: string): Promise<st
|
|
|
145
128
|
return encodeURIComponent(`${value}.${base64}`);
|
|
146
129
|
}
|
|
147
130
|
|
|
148
|
-
/**
|
|
149
|
-
|
|
150
|
-
*
|
|
151
|
-
* Putting it in the session token makes the token deterministic across reseeds — the same cookie keeps
|
|
152
|
-
* working in every worktree once each is seeded, which is the whole point — while rotating the secret
|
|
153
|
-
* changes the token *and* invalidates every cookie signed with the old one, for free. A truncated digest,
|
|
154
|
-
* never the secret: the token is written to a file and read back by tooling.
|
|
155
|
-
*/
|
|
156
|
-
export async function secretFingerprint(secret: string): Promise<string> {
|
|
157
|
-
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret));
|
|
158
|
-
return Array.from(new Uint8Array(digest).slice(0, FINGERPRINT_BYTES))
|
|
159
|
-
.map((byte) => byte.toString(16).padStart(2, "0"))
|
|
160
|
-
.join("");
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
/** Inputs to {@link mintDevSession}. `now` is a seam so the determinism tests do not depend on the clock. */
|
|
164
|
-
export interface MintDevSessionInput {
|
|
131
|
+
/** Inputs to {@link mintDevLogin}. `now` is a seam so the tests do not depend on the clock. */
|
|
132
|
+
export interface MintDevLoginInput {
|
|
165
133
|
/** The seeded user to sign in as. */
|
|
166
134
|
user: SeededUser;
|
|
167
135
|
/** The Better Auth signing secret for this environment — never logged, never stored, never in an error. */
|
|
168
136
|
secret: string;
|
|
169
|
-
/** The moment the
|
|
137
|
+
/** The moment the claim is minted. Defaults to now. */
|
|
170
138
|
now?: Date;
|
|
171
139
|
}
|
|
172
140
|
|
|
173
141
|
/**
|
|
174
|
-
*
|
|
142
|
+
* Sign a claim naming the user a dev login signs in as — `#572`.
|
|
143
|
+
*
|
|
144
|
+
* **The payload is base64 of JSON, not a delimited string.** A user id is an adopter's to choose and may
|
|
145
|
+
* hold any character at all, including whichever one a hand-rolled format picked as its separator. JSON
|
|
146
|
+
* inside base64 has no separator to collide with, and the whole of it is what the signature covers.
|
|
175
147
|
*
|
|
176
|
-
* The
|
|
177
|
-
*
|
|
148
|
+
* The same HMAC-SHA-256 construction {@link signCookieValue} uses, deliberately not the same function:
|
|
149
|
+
* that one mirrors better-call's cookie format because Better Auth has to accept its output, and this is
|
|
150
|
+
* ours. Two consumers, two formats, no shared spelling to break one by fixing the other.
|
|
178
151
|
*/
|
|
179
|
-
export async function
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
152
|
+
export async function signDevLoginClaim(input: MintDevLoginInput & { expiresAt: Date }): Promise<string> {
|
|
153
|
+
// **`TextEncoder`, not `btoa` on the string.** `btoa` throws `InvalidCharacterError` for any code
|
|
154
|
+
// point above U+00FF, and a user id is the adopter's to choose — this module already reasons about
|
|
155
|
+
// ids holding a separator, and a non-ASCII one is no stranger. Encoding to UTF-8 bytes first makes
|
|
156
|
+
// the payload total in the id, which is what a seed that must not die on somebody's name requires.
|
|
157
|
+
const body = base64Of(new TextEncoder().encode(JSON.stringify({ u: input.user.id, e: input.expiresAt.getTime() })));
|
|
158
|
+
const key = await claimKey(input.secret, ["sign"]);
|
|
159
|
+
const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(body));
|
|
160
|
+
return encodeURIComponent(`${body}.${base64Of(signature)}`);
|
|
161
|
+
}
|
|
184
162
|
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
163
|
+
/**
|
|
164
|
+
* What a claim says, once it has been proved to say it.
|
|
165
|
+
*
|
|
166
|
+
* `null` for every failure and never a reason: a malformed claim, one signed by another secret, and one
|
|
167
|
+
* naming a user who has since gone are the same answer to whoever presented it, because distinguishing
|
|
168
|
+
* them is a probe. The route turns all three into the one 404 it already had.
|
|
169
|
+
*/
|
|
170
|
+
export async function verifyDevLoginClaim(
|
|
171
|
+
claim: string,
|
|
172
|
+
secret: string,
|
|
173
|
+
now: Date = new Date(),
|
|
174
|
+
): Promise<{ userId: string; expiresAt: Date } | null> {
|
|
175
|
+
const raw = safeDecode(claim);
|
|
176
|
+
if (raw === null) return null;
|
|
177
|
+
// The last dot, because base64 never contains one and a payload might have been anything.
|
|
178
|
+
const cut = raw.lastIndexOf(".");
|
|
179
|
+
if (cut <= 0) return null;
|
|
180
|
+
const body = raw.slice(0, cut);
|
|
181
|
+
const signature = safeBytes(raw.slice(cut + 1));
|
|
182
|
+
if (signature === null) return null;
|
|
183
|
+
|
|
184
|
+
// `crypto.subtle.verify` rather than comparing strings: the comparison is the part that has to be
|
|
185
|
+
// constant-time, and this is the primitive that already is.
|
|
186
|
+
const key = await claimKey(secret, ["verify"]);
|
|
187
|
+
if (!(await crypto.subtle.verify("HMAC", key, signature, new TextEncoder().encode(body)))) return null;
|
|
188
|
+
|
|
189
|
+
const decoded = safeJson(body);
|
|
190
|
+
const parsed = DevLoginClaim.safeParse(decoded);
|
|
191
|
+
if (!parsed.success) return null;
|
|
192
|
+
const expiresAt = new Date(parsed.data.e);
|
|
193
|
+
if (expiresAt.getTime() <= now.getTime()) return null;
|
|
194
|
+
return { userId: parsed.data.u, expiresAt };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** The claim's payload, as it is signed. Two letters, because it is written into a URL a person may see. */
|
|
198
|
+
const DevLoginClaim = z
|
|
199
|
+
.object({
|
|
200
|
+
u: z.string().min(1).describe("The user id the route mints a session for."),
|
|
201
|
+
e: z.number().int().positive().describe("When the claim stops being accepted, in ms since the epoch."),
|
|
202
|
+
})
|
|
203
|
+
.describe("What a dev-login claim asserts: which seeded user, and until when.");
|
|
204
|
+
|
|
205
|
+
/** The HMAC key for a claim. Imported per call — a key object is not something to cache across requests. */
|
|
206
|
+
function claimKey(secret: string, usages: readonly ("sign" | "verify")[]): Promise<CryptoKey> {
|
|
207
|
+
return crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [
|
|
208
|
+
...usages,
|
|
209
|
+
]);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Base64 of bytes — a signature, or a UTF-8 payload. */
|
|
213
|
+
function base64Of(bytes: ArrayBuffer | Uint8Array): string {
|
|
214
|
+
return btoa(String.fromCharCode(...new Uint8Array(bytes)));
|
|
215
|
+
}
|
|
199
216
|
|
|
217
|
+
/** `decodeURIComponent`, or null. A malformed escape throws, and a throw here is just "not a claim". */
|
|
218
|
+
function safeDecode(value: string): string | null {
|
|
219
|
+
try {
|
|
220
|
+
return decodeURIComponent(value);
|
|
221
|
+
} catch {
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Base64 to bytes, or null. Same reason: unparseable input is not an error, it is a refusal. */
|
|
227
|
+
function safeBytes(value: string): Uint8Array | null {
|
|
228
|
+
try {
|
|
229
|
+
return Uint8Array.from(atob(value), (character) => character.charCodeAt(0));
|
|
230
|
+
} catch {
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Base64 UTF-8 JSON to a value, or null. Decoded as bytes, to match how {@link base64Of} wrote it. */
|
|
236
|
+
function safeJson(body: string): unknown {
|
|
237
|
+
try {
|
|
238
|
+
const bytes = Uint8Array.from(atob(body), (character) => character.charCodeAt(0));
|
|
239
|
+
return JSON.parse(new TextDecoder().decode(bytes));
|
|
240
|
+
} catch {
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Mint one dev login: the signed claim, and the artifact that carries it.
|
|
247
|
+
*
|
|
248
|
+
* **No `pithy_auth_sessions` row — `#572`.** This used to write one and hand it over on every open, which
|
|
249
|
+
* meant the product's own sign-out revoked the dev login along with the session, and the only way back was
|
|
250
|
+
* a reseed. It also meant a row in that table which was, by this module's own admission, indistinguishable
|
|
251
|
+
* from a real sign-in — so it showed up in every surface built over sessions as a device nobody used.
|
|
252
|
+
*
|
|
253
|
+
* What is minted here is a claim about *who*. The route exchanges it for a session at the moment somebody
|
|
254
|
+
* opens the link, so the session is real, is theirs, and is the only thing a sign-out takes away.
|
|
255
|
+
*/
|
|
256
|
+
export async function mintDevLogin(input: MintDevLoginInput): Promise<MintedDevLogin> {
|
|
257
|
+
const now = input.now ?? new Date();
|
|
258
|
+
const expiresAt = new Date(now.getTime() + DEV_LOGIN_LIFETIME_MS);
|
|
200
259
|
return {
|
|
201
|
-
session,
|
|
202
260
|
login: {
|
|
203
261
|
email: input.user.email,
|
|
204
262
|
userId: input.user.id,
|
|
205
|
-
|
|
206
|
-
cookieValue: await signCookieValue(token, input.secret),
|
|
263
|
+
claim: await signDevLoginClaim({ ...input, expiresAt }),
|
|
207
264
|
expiresAt,
|
|
208
265
|
},
|
|
209
266
|
};
|
|
@@ -279,9 +336,11 @@ export const authDevSessionSeed: SeedSet = defineSeed({
|
|
|
279
336
|
});
|
|
280
337
|
}
|
|
281
338
|
|
|
282
|
-
const minted = await
|
|
339
|
+
const minted = await mintDevLogin({ user, secret });
|
|
340
|
+
// **No `d1` — `#572`.** This set writes a file and nothing else now. Nothing reaches
|
|
341
|
+
// `pithy_auth_sessions` until somebody opens the link and the route mints a session for them, which
|
|
342
|
+
// is what makes signing out of the app harmless to the way back in.
|
|
283
343
|
return {
|
|
284
|
-
d1: [d1SeedGroup("app", "pithyAuthSessions", Session, [minted.session])],
|
|
285
344
|
artifacts: [{ file: DEV_LOGIN_FILE, contents: `${JSON.stringify(DevLogin.encode(minted.login), null, 2)}\n` }],
|
|
286
345
|
};
|
|
287
346
|
},
|
package/src/version.generated.ts
CHANGED