@pithy-sh/auth 0.4.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/audit/emit.d.ts +7 -3
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +6 -4
- package/dist/http/{linkFreshness.d.ts → providerFreshness.d.ts} +27 -15
- package/dist/http/providerFreshness.d.ts.map +1 -0
- package/dist/http/{linkFreshness.js → providerFreshness.js} +19 -12
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +3 -2
- package/dist/instance/auth.d.ts +14 -0
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +15 -0
- package/docs/github-oauth.md +1 -1
- package/package.json +5 -5
- package/src/audit/emit.ts +10 -4
- package/src/capability.ts +36 -1
- package/src/data/betterAuth.ts +6 -1
- package/src/http/devLoginRoute.ts +84 -59
- package/src/http/{linkFreshness.ts → providerFreshness.ts} +36 -20
- package/src/http/resolve.ts +7 -1
- package/src/http/routes.ts +61 -8
- package/src/instance/auth.ts +82 -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
- package/dist/http/linkFreshness.d.ts.map +0 -1
|
@@ -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
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"linkFreshness.d.ts","sourceRoot":"","sources":["../../src/http/linkFreshness.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,EAAE,UAAU,EAAqB,MAAM,qCAAqC,CAAC;AACpF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAG9C;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,sBAAsB,QAAU,CAAC;AAE9C;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,eAAe,EAAE,IAAI,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,GAAG,EAAE,IAAI,GAAG,OAAO,CAQ3G;AAED;;;;;;;;;;;;;;;;GAgBG;AACH;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,IAAI,UAAU,CAS5C;AAED,wBAAgB,gCAAgC,CAAC,GAAG,GAAE,MAAM,IAAuB,GAAG,iBAAiB,CAAC,YAAY,CAAC,CAmBpH"}
|