@jgb-solutions/kit 0.2.0 → 0.2.2

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/CHANGELOG.md CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  All notable changes to `@jgb-solutions/kit`. Versions follow semver.
4
4
 
5
+ ## 0.2.2
6
+
7
+ - Connecting Google while signed in (`/link-social`, `linkGoogle`) keeps every session of the account: the owner proved both sides, and signing their other devices out would be a bad surprise. A Google sign-in that joins a confirmed account still ends every session of that account. The hook tells them apart by who is signed in: a browser holding another account's session counts as a join. `afterAccountSaved(account, adapter, signedInUserId)` replaces 0.2.0's `keepSessionToken`, and `AccountAdapter` uses `findSession` instead of `listSessions` and `deleteSessions`.
8
+
9
+ ## 0.2.1
10
+
11
+ - `standardAuthOptions({ passkeyOrigin: 'request' })`: passkeys checked against the request's own origin, which `trustedBaseUrl` limits to the site and local hosts, so the site, previews and any local port each work (the jgb-starter template's setup). The default, `'listed'`, keeps the fixed list (the site, `localOrigins`, the Android app).
12
+ - README: the server call is `auth.api.linkSocialAccount` (the endpoint is `/link-social`).
13
+ - `authSettings`: `E2E=1` is refused only on a production server that listens beyond this machine (`NODE_ENV=production` and `HOST` not a loopback address). 0.2.0 refused it whenever `NODE_ENV` was production, which also stopped E2E servers that run the production build on `127.0.0.1` (the jgb-starter Bun stack).
14
+
5
15
  ## 0.2.0
6
16
 
7
17
  - `@jgb-solutions/kit/auth`: Better Auth set up the same way in every app. Pieces (`authSettings`, `trustedBaseUrl`, `passkeyOrigins`, `androidOrigin`, `assetLinks`, `RATE_LIMIT_RULES`, `counterRateLimit`, `googleProvider`, `CONFIRMED_ACCOUNT_LINKING`, `freeUsername`, `afterAccountSaved`, `pictureFromIdToken`, `signedInFlagHook`, `asPublicRequest`, `toAuthUser`) and the preset `standardAuthOptions`: username or email with a password, passkeys, Google that joins only confirmed accounts (connect Google from the account page otherwise), roles and the first admins (`ADMIN_EMAILS`, confirmed addresses only), Bearer sessions for the mobile app, rate limits, no email ever sent.
package/README.md CHANGED
@@ -79,7 +79,7 @@ What the preset sets:
79
79
 
80
80
  - **Passwords:** 12 to 128 characters, with no email verification and no reset link (no email is ever sent). `SIGN_UP=off` closes sign-up; existing accounts still sign in.
81
81
  - **Usernames** (Better Auth's username plugin): 3 to 30 characters, lower-case letters, digits, dots and underscores. An account made without one (Google) gets one from its name, with a number when it's taken.
82
- - **Passkeys** for the site, the `localOrigins` and the Android app (`androidCertSha256`).
82
+ - **Passkeys** for the site, the `localOrigins` and the Android app (`androidCertSha256`). With `passkeyOrigin: 'request'`, the request's own origin instead (the site, previews and any local port; one of `trustedBaseUrl`'s hosts), for apps without an Android app.
83
83
  - **Google**, when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set. `GOOGLE_MOBILE_CLIENT_IDS` adds the apps' clients, for ID-token sign-in. A new Google address makes a new account with a confirmed address. Joining existing accounts is "merge only confirmed" (see below).
84
84
  - **Roles:** Better Auth's admin plugin, with the app's access control. A new account whose address is in `ADMIN_EMAILS` starts as admin when it's created with Google (a confirmed address); a sign-up with that address by email and password starts as an ordinary user, so nobody can claim an admin's address first. Other first admins are promoted from the server (the app's admin script).
85
85
  - **The mobile app:** the bearer plugin.
@@ -91,10 +91,10 @@ What the preset sets:
91
91
  The app never sends email, so an address typed at sign-up is never confirmed. Someone could sign up first with another person's address and a password they know. So **"Continue with Google" joins an existing account with the same address only when that account's address is confirmed**: it was made with Google, or by an admin. Otherwise Better Auth refuses, and the app shows the way in:
92
92
 
93
93
  1. **On the sign-in page**, the refusal arrives as `?error=account_not_linked` after Google's redirect, or as an error body from an ID-token sign-in. `authErrorCode(answer)` (`kit/auth/rules`) turns either into `ACCOUNT_NOT_LINKED`. The page says: _An account with this address already exists. Sign in with your password, then connect Google from your account page._
94
- 2. **On the account page**, "Connect Google" calls Better Auth's `linkSocial` for the signed-in person: `auth.api.linkSocial({ body: { provider: 'google', callbackURL: '/account', errorCallbackURL: '/account' }, headers })` on the website (go to the `url` it returns), or `auth.linkGoogle(idToken)` in the app. The Google address may differ from the account's (username accounts have a placeholder address). The account's other sessions end, this one stays, and the account takes Google's picture if it had none. From then on, "Continue with Google" signs into it.
94
+ 2. **On the account page**, "Connect Google" calls Better Auth's `/link-social` for the signed-in person: `auth.api.linkSocialAccount({ body: { provider: 'google', callbackURL: '/account', errorCallbackURL: '/account' }, headers })` on the website (go to the `url` it returns), or `auth.linkGoogle(idToken)` in the app. The Google address may differ from the account's (username accounts have a placeholder address). Every session of the account stays (the owner proved both sides), and the account takes Google's picture if it had none. From then on, "Continue with Google" signs into it.
95
95
  3. A Google account that already belongs to another account gives `GOOGLE_ALREADY_LINKED`. A Google address Google didn't verify gives `GOOGLE_EMAIL_NOT_CONFIRMED`.
96
96
 
97
- When Google joins a confirmed account that also has a password, that account's other sessions end too.
97
+ When a Google sign-in joins a confirmed account that also has a password, every session of that account ends: one someone else held doesn't carry on. A browser signed into another account counts as such a sign-in, not as the owner connecting.
98
98
 
99
99
  Everything the preset uses is exported on its own, for an app that needs a different mix (`authSettings`, `trustedBaseUrl`, `passkeyOrigins`, `androidOrigin`, `assetLinks`, `googleProvider`, `CONFIRMED_ACCOUNT_LINKING`, `freeUsername`, `afterAccountSaved`, `pictureFromIdToken`, `signedInFlagHook`, `asPublicRequest`, `toAuthUser`). What stays in the app is its own: its name and address, database and schema (`bunx auth@latest generate`), roles and permissions, texts, pages, and its Google, Android and Access identifiers.
100
100
 
@@ -62,7 +62,7 @@ export declare function createMobileAuth<U>(config: MobileAuthConfig<U>): {
62
62
  /**
63
63
  * Connects Google to the signed-in account (its account page), with an ID token from the app's
64
64
  * Google Sign-In SDK: afterwards "Continue with Google" signs into this account. The Google address
65
- * may differ from the account's. Other sessions of the account end; this one stays.
65
+ * may differ from the account's. Every session of the account stays.
66
66
  */
67
67
  linkGoogle(idToken: string, options?: {
68
68
  nonce?: string;
package/dist/auth.d.ts CHANGED
@@ -22,8 +22,9 @@ export type AuthSettings = {
22
22
  * Sign-in settings from the environment, the same on every host: BETTER_AUTH_SECRET, SIGN_UP,
23
23
  * ADMIN_EMAILS, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET and GOOGLE_MOBILE_CLIENT_IDS (comma-separated:
24
24
  * the Android and iOS clients). E2E=1 marks the E2E test server: its stand-in secret and its rate
25
- * limits off are refused when NODE_ENV is production, so a stray E2E=1 can't start production with a
26
- * public secret. Throws without a secret.
25
+ * limits off are refused on a production server that listens beyond this machine (NODE_ENV=production
26
+ * with HOST unset or not a loopback address), so a stray E2E=1 can't start production with a public
27
+ * secret. E2E servers run a production build on 127.0.0.1. Throws without a secret.
27
28
  */
28
29
  export declare function authSettings(env: Env): AuthSettings;
29
30
  /**
@@ -156,16 +157,17 @@ export declare function googleProvider(google: GoogleSettings, options: {
156
157
  export declare function freeUsername(name: string | null | undefined, email: string | null | undefined, taken: (candidates: string[]) => Promise<ReadonlySet<string>>, fallback: string): Promise<string>;
157
158
  /** The picture in a Google ID token (already verified by Better Auth), when it is an https address of at most 2,000 characters. */
158
159
  export declare function pictureFromIdToken(idToken: string | null | undefined): string | null;
159
- /** The part of Better Auth's internal adapter `afterAccountSaved` uses. */
160
+ /** The part of Better Auth's internal adapter `afterAccountSaved` and its hook use. */
160
161
  export type AccountAdapter = {
161
162
  findAccounts(userId: string): Promise<{
162
163
  providerId: string;
163
164
  }[]>;
164
165
  deleteUserSessions(userId: string): Promise<unknown>;
165
- listSessions(userId: string): Promise<{
166
- token: string;
167
- }[]>;
168
- deleteSessions(tokens: string[]): Promise<unknown>;
166
+ findSession(token: string): Promise<{
167
+ user: {
168
+ id: string;
169
+ };
170
+ } | null>;
169
171
  findUserById(userId: string): Promise<{
170
172
  image?: string | null | undefined;
171
173
  } | null>;
@@ -174,24 +176,30 @@ export type AccountAdapter = {
174
176
  }): Promise<unknown>;
175
177
  };
176
178
  /**
177
- * After an account row is saved: when it is Google joining an account that already had another way
178
- * in, the account's other sessions end (a session someone else held doesn't carry on), and the account
179
- * takes Google's picture if it had none. `keepSessionToken` is the session of the person connecting
180
- * Google from their account page, which stays; a Google sign-in that joins an account ends them all
181
- * and gets its own right after. Returns whether it was such a join.
179
+ * After an account row is saved, when it is Google joining an account that already had another way in:
180
+ *
181
+ * - **Connected by the signed-in owner** (`signedInUserId` is the account's own, through Better
182
+ * Auth's `/link-social`): every session stays. The owner proved both sides, and signing their phone
183
+ * out because they connected Google on the web would be a bad surprise (Control Center, 2026-11-24).
184
+ * - **Joined by a Google sign-in** (into a confirmed account, "merge only confirmed"): every session
185
+ * of the account ends, so one someone else held doesn't carry on. The Google sign-in gets its own
186
+ * session right after. Rare, and defensive.
187
+ *
188
+ * Either way, the account takes Google's picture if it had none. Returns whether it was such a join or
189
+ * connection.
182
190
  */
183
191
  export declare function afterAccountSaved(account: {
184
192
  providerId: string;
185
193
  userId: string;
186
194
  idToken?: string | null | undefined;
187
- }, adapter: AccountAdapter, keepSessionToken?: string | null): Promise<boolean>;
195
+ }, adapter: AccountAdapter, signedInUserId?: string | null): Promise<boolean>;
188
196
  /** The part of Better Auth's endpoint context the account hook reads. */
189
197
  type AccountHookContext = {
190
198
  context: {
191
199
  internalAdapter: AccountAdapter;
192
200
  session?: {
193
- session: {
194
- token: string;
201
+ user: {
202
+ id: string;
195
203
  };
196
204
  } | null;
197
205
  authCookies: {
@@ -254,7 +262,14 @@ export type StandardAuthInput<A extends AdminOptions> = {
254
262
  takenUsernames: (candidates: string[]) => Promise<ReadonlySet<string>>;
255
263
  /** The username base when a name gives too little ("listener", "member"…). */
256
264
  usernameFallback: string;
257
- /** Local origins allowed to use passkeys (development and E2E): `['http://localhost:5173']`. */
265
+ /**
266
+ * Which origins may use passkeys. `'listed'` (the default): the site, `localOrigins` and the Android
267
+ * app (`androidCertSha256`). `'request'`: the request's own origin, which `trustedBaseUrl` limits to
268
+ * the site and local hosts, so the site, previews and any local port work, each with its own
269
+ * passkeys. `'request'` can't serve the Android app.
270
+ */
271
+ passkeyOrigin?: 'listed' | 'request';
272
+ /** Local origins allowed to use passkeys (development and E2E) with `passkeyOrigin: 'listed'`: `['http://localhost:5173']`. */
258
273
  localOrigins?: readonly string[];
259
274
  /** The Android app's signing certificates (SHA-256, `AB:CD:…`), for passkeys in the app. */
260
275
  androidCertSha256?: readonly string[];
@@ -339,17 +354,7 @@ export declare function standardAuthOptions<A extends AdminOptions>(input: Stand
339
354
  email: string;
340
355
  emailVerified: boolean;
341
356
  name: string;
342
- image
343
- /**
344
- * Better Auth's `baseURL`: the request's own host, but only the site's or a local one; anything else
345
- * falls back to the site. A forged Host header can't choose the passkeys' relying party or the
346
- * address in a callback.
347
- */
348
- ? /**
349
- * Better Auth's `baseURL`: the request's own host, but only the site's or a local one; anything else
350
- * falls back to the site. A forged Host header can't choose the passkeys' relying party or the
351
- * address in a callback.
352
- */: string | null | undefined;
357
+ image?: string | null | undefined;
353
358
  }> & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null): Promise<{
354
359
  data: {
355
360
  displayUsername?: string | undefined;
@@ -1617,7 +1622,7 @@ export declare function standardAuthOptions<A extends AdminOptions>(input: Stand
1617
1622
  userId: string;
1618
1623
  expiresAt: Date;
1619
1624
  token: string;
1620
- ipAddress? /** Local origins allowed to use passkeys (development and E2E): `['http://localhost:5173']`. */: string | null | undefined;
1625
+ ipAddress?: string | null | undefined;
1621
1626
  userAgent?: string | null | undefined;
1622
1627
  };
1623
1628
  };
package/dist/auth.js CHANGED
@@ -94,8 +94,9 @@ function authErrorCode(answer) {
94
94
  var E2E_SECRET = "e2e-only-secret-never-used-in-production-0000";
95
95
  function authSettings(env) {
96
96
  const e2e = env.E2E === "1";
97
- if (e2e && env.NODE_ENV === "production")
98
- throw new Error("E2E=1 is set in production: remove it.");
97
+ const loopback = ["127.0.0.1", "::1", "localhost"].includes((env.HOST ?? "").trim().toLowerCase());
98
+ if (e2e && env.NODE_ENV === "production" && !loopback)
99
+ throw new Error("E2E=1 is set on a production server that listens beyond this machine: remove it.");
99
100
  const secret = env.BETTER_AUTH_SECRET || (e2e ? E2E_SECRET : "");
100
101
  if (!secret)
101
102
  throw new Error("BETTER_AUTH_SECRET is not set.");
@@ -198,19 +199,14 @@ function pictureFromIdToken(idToken) {
198
199
  return null;
199
200
  }
200
201
  }
201
- async function afterAccountSaved(account, adapter, keepSessionToken) {
202
+ async function afterAccountSaved(account, adapter, signedInUserId) {
202
203
  if (account.providerId !== "google")
203
204
  return false;
204
205
  const accounts = await adapter.findAccounts(account.userId);
205
206
  if (!accounts.some((other) => other.providerId !== "google"))
206
207
  return false;
207
- if (keepSessionToken) {
208
- const others = (await adapter.listSessions(account.userId)).map((session) => session.token).filter((token) => token !== keepSessionToken);
209
- if (others.length)
210
- await adapter.deleteSessions(others);
211
- } else {
208
+ if (signedInUserId !== account.userId)
212
209
  await adapter.deleteUserSessions(account.userId);
213
- }
214
210
  const picture = pictureFromIdToken(account.idToken);
215
211
  if (picture) {
216
212
  const user = await adapter.findUserById(account.userId);
@@ -219,9 +215,14 @@ async function afterAccountSaved(account, adapter, keepSessionToken) {
219
215
  }
220
216
  return true;
221
217
  }
222
- async function currentSessionToken(ctx) {
223
- const token = ctx.context.session?.session.token ?? await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret).catch(() => null);
224
- return typeof token === "string" && token ? token : null;
218
+ async function signedInUserId(ctx) {
219
+ if (ctx.context.session)
220
+ return ctx.context.session.user.id;
221
+ const token = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret).catch(() => null);
222
+ if (typeof token !== "string" || !token)
223
+ return null;
224
+ const found = await ctx.context.internalAdapter.findSession(token).catch(() => null);
225
+ return found?.user.id ?? null;
225
226
  }
226
227
  function signedInFlagHook(name, maxAgeSeconds = 365 * 24 * 60 * 60) {
227
228
  return createAuthMiddleware(async (ctx) => {
@@ -254,6 +255,9 @@ function toAuthUser(user, roleOf) {
254
255
  }
255
256
  function standardAuthOptions(input) {
256
257
  const { settings } = input;
258
+ const fromRequest = input.passkeyOrigin === "request";
259
+ if (fromRequest && (input.androidCertSha256?.length || input.localOrigins?.length))
260
+ throw new Error("passkeyOrigin 'request' can't take androidCertSha256 or localOrigins: use 'listed'.");
257
261
  const days = input.sessionDays ?? 30;
258
262
  return {
259
263
  appName: input.appName,
@@ -300,7 +304,7 @@ function standardAuthOptions(input) {
300
304
  create: {
301
305
  after: async (account, ctx) => {
302
306
  if (ctx)
303
- await afterAccountSaved(account, ctx.context.internalAdapter, await currentSessionToken(ctx));
307
+ await afterAccountSaved(account, ctx.context.internalAdapter, await signedInUserId(ctx));
304
308
  }
305
309
  }
306
310
  }
@@ -311,10 +315,12 @@ function standardAuthOptions(input) {
311
315
  username({ minUsernameLength: USERNAME.min, maxUsernameLength: USERNAME.max }),
312
316
  passkey({
313
317
  rpName: input.appName,
314
- origin: passkeyOrigins(input.siteUrl, {
315
- ...input.localOrigins ? { local: input.localOrigins } : {},
316
- ...input.androidCertSha256 ? { androidCertSha256: input.androidCertSha256 } : {}
317
- })
318
+ ...fromRequest ? {} : {
319
+ origin: passkeyOrigins(input.siteUrl, {
320
+ ...input.localOrigins ? { local: input.localOrigins } : {},
321
+ ...input.androidCertSha256 ? { androidCertSha256: input.androidCertSha256 } : {}
322
+ })
323
+ }
318
324
  }),
319
325
  admin(input.admin),
320
326
  bearer(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jgb-solutions/kit",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Generic plumbing for web apps on Bun and Cloudflare Workers: small, typed, tree-shakable modules (Cloudflare Access, Better Auth).",
5
5
  "license": "MIT",
6
6
  "author": "JGB Solutions",