@jgb-solutions/kit 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  All notable changes to `@jgb-solutions/kit`. Versions follow semver.
4
4
 
5
+ ## 0.2.3
6
+
7
+ - `createMobileAuth({ randomId })` (`kit/auth/expo`): signing up without an email no longer needs a global `crypto`. React Native's Hermes has none, so `signUp` crashed there ("Property 'crypto' doesn't exist", found in the jgb-starter app template). Pass expo-crypto's `randomUUID`; it defaults to the runtime's `crypto.randomUUID` when present, and without either, `signUp` answers `NO_RANDOM_ID` instead of throwing. `placeholderEmail(randomId?)` takes the same function.
8
+
9
+ ## 0.2.2
10
+
11
+ - 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`.
12
+
5
13
  ## 0.2.1
6
14
 
7
15
  - `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).
package/README.md CHANGED
@@ -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 `/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). 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
 
@@ -119,11 +119,19 @@ const { withUser, requireUser, requireAdmin } = authMiddleware({
119
119
  #### `kit/auth/expo`: the mobile app
120
120
 
121
121
  ```ts
122
+ import { randomUUID } from 'expo-crypto'
122
123
  import * as SecureStore from 'expo-secure-store'
123
124
  import * as Passkeys from 'react-native-passkeys'
124
125
  import { createMobileAuth } from '@jgb-solutions/kit/auth/expo'
125
126
 
126
- export const auth = createMobileAuth({ origin: 'https://app.example.com', storage: SecureStore, tokenKey: 'example.session', fetchMe })
127
+ // randomId: Hermes has no global crypto; sign-up without an email needs one for its placeholder address.
128
+ export const auth = createMobileAuth({
129
+ origin: 'https://app.example.com',
130
+ storage: SecureStore,
131
+ tokenKey: 'example.session',
132
+ fetchMe,
133
+ randomId: randomUUID,
134
+ })
127
135
 
128
136
  const session = useSyncExternalStore(auth.subscribe, auth.getSession)
129
137
  await auth.signIn('maria', password) // or an email address
@@ -33,6 +33,12 @@ export type MobileAuthConfig<U> = {
33
33
  fetchMe: () => Promise<U>;
34
34
  /** Runs after each sign-in (`firstTime`) and each launch with a saved session: syncing what the phone holds. */
35
35
  onSignedIn?: (firstTime: boolean) => Promise<void>;
36
+ /**
37
+ * A random UUID, for the placeholder address of an account made without an email. Defaults to the
38
+ * runtime's `crypto.randomUUID`, which React Native's Hermes doesn't have: pass expo-crypto's
39
+ * `randomUUID` there. Without either, signUp without an email answers `NO_RANDOM_ID`.
40
+ */
41
+ randomId?: () => string;
36
42
  /** For tests. */
37
43
  fetch?: typeof fetch;
38
44
  };
@@ -62,7 +68,7 @@ export declare function createMobileAuth<U>(config: MobileAuthConfig<U>): {
62
68
  /**
63
69
  * Connects Google to the signed-in account (its account page), with an ID token from the app's
64
70
  * 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.
71
+ * may differ from the account's. Every session of the account stays.
66
72
  */
67
73
  linkGoogle(idToken: string, options?: {
68
74
  nonce?: string;
package/dist/auth/expo.js CHANGED
@@ -14,8 +14,8 @@ var PLACEHOLDER_EMAIL_DOMAIN = "users.invalid";
14
14
  function isPlaceholderEmail(email) {
15
15
  return email.toLowerCase().endsWith(`@${PLACEHOLDER_EMAIL_DOMAIN}`);
16
16
  }
17
- function placeholderEmail() {
18
- return `${crypto.randomUUID().replaceAll("-", "")}@${PLACEHOLDER_EMAIL_DOMAIN}`;
17
+ function placeholderEmail(randomId = () => globalThis.crypto.randomUUID()) {
18
+ return `${randomId().replaceAll("-", "")}@${PLACEHOLDER_EMAIL_DOMAIN}`;
19
19
  }
20
20
  function usernameFromName(name, email, fallback) {
21
21
  const clean = (text) => (typeof text.normalize === "function" ? text.normalize("NFKD") : text).replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[\s-]+/g, ".").replace(/[^a-z0-9_.]/g, "").replace(/\.{2,}/g, ".").replace(/^[._]+|[._]+$/g, "").slice(0, USERNAME.max - 5).replace(/[._]+$/g, "");
@@ -172,12 +172,11 @@ function createMobileAuth(config) {
172
172
  },
173
173
  signUp(input) {
174
174
  const username = input.username.trim().toLowerCase();
175
- return signInWith("/sign-up/email", {
176
- name: input.name?.trim() || username,
177
- username,
178
- email: input.email?.trim() || placeholderEmail(),
179
- password: input.password
180
- });
175
+ const randomId = config.randomId ?? (typeof globalThis.crypto?.randomUUID === "function" ? () => globalThis.crypto.randomUUID() : null);
176
+ const email = input.email?.trim() || (randomId ? placeholderEmail(randomId) : null);
177
+ if (!email)
178
+ return Promise.resolve({ ok: false, code: "NO_RANDOM_ID" });
179
+ return signInWith("/sign-up/email", { name: input.name?.trim() || username, username, email, password: input.password });
181
180
  },
182
181
  signInWithGoogle(idToken, options = {}) {
183
182
  return signInWith("/sign-in/social", {
@@ -24,8 +24,12 @@ export declare function usernameProblem(username: string): 'too-short' | 'too-lo
24
24
  */
25
25
  export declare const PLACEHOLDER_EMAIL_DOMAIN = "users.invalid";
26
26
  export declare function isPlaceholderEmail(email: string): boolean;
27
- /** A new placeholder address, random enough never to collide. */
28
- export declare function placeholderEmail(): string;
27
+ /**
28
+ * A new placeholder address, random enough never to collide. `randomId` defaults to the runtime's
29
+ * `crypto.randomUUID`; React Native's Hermes has no global `crypto`, so an app there passes its own
30
+ * (expo-crypto's `randomUUID`).
31
+ */
32
+ export declare function placeholderEmail(randomId?: () => string): string;
29
33
  /**
30
34
  * A username made from a person's name, for accounts made with Google: "Marie-Ève Dupont" →
31
35
  * "marie.eve.dupont". Accents dropped, spaces and dashes to dots, anything else out, short enough to
@@ -14,8 +14,8 @@ var PLACEHOLDER_EMAIL_DOMAIN = "users.invalid";
14
14
  function isPlaceholderEmail(email) {
15
15
  return email.toLowerCase().endsWith(`@${PLACEHOLDER_EMAIL_DOMAIN}`);
16
16
  }
17
- function placeholderEmail() {
18
- return `${crypto.randomUUID().replaceAll("-", "")}@${PLACEHOLDER_EMAIL_DOMAIN}`;
17
+ function placeholderEmail(randomId = () => globalThis.crypto.randomUUID()) {
18
+ return `${randomId().replaceAll("-", "")}@${PLACEHOLDER_EMAIL_DOMAIN}`;
19
19
  }
20
20
  function usernameFromName(name, email, fallback) {
21
21
  const clean = (text) => (typeof text.normalize === "function" ? text.normalize("NFKD") : text).replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[\s-]+/g, ".").replace(/[^a-z0-9_.]/g, "").replace(/\.{2,}/g, ".").replace(/^[._]+|[._]+$/g, "").slice(0, USERNAME.max - 5).replace(/[._]+$/g, "");
package/dist/auth.d.ts CHANGED
@@ -157,16 +157,17 @@ export declare function googleProvider(google: GoogleSettings, options: {
157
157
  export declare function freeUsername(name: string | null | undefined, email: string | null | undefined, taken: (candidates: string[]) => Promise<ReadonlySet<string>>, fallback: string): Promise<string>;
158
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. */
159
159
  export declare function pictureFromIdToken(idToken: string | null | undefined): string | null;
160
- /** The part of Better Auth's internal adapter `afterAccountSaved` uses. */
160
+ /** The part of Better Auth's internal adapter `afterAccountSaved` and its hook use. */
161
161
  export type AccountAdapter = {
162
162
  findAccounts(userId: string): Promise<{
163
163
  providerId: string;
164
164
  }[]>;
165
165
  deleteUserSessions(userId: string): Promise<unknown>;
166
- listSessions(userId: string): Promise<{
167
- token: string;
168
- }[]>;
169
- deleteSessions(tokens: string[]): Promise<unknown>;
166
+ findSession(token: string): Promise<{
167
+ user: {
168
+ id: string;
169
+ };
170
+ } | null>;
170
171
  findUserById(userId: string): Promise<{
171
172
  image?: string | null | undefined;
172
173
  } | null>;
@@ -175,24 +176,30 @@ export type AccountAdapter = {
175
176
  }): Promise<unknown>;
176
177
  };
177
178
  /**
178
- * After an account row is saved: when it is Google joining an account that already had another way
179
- * in, the account's other sessions end (a session someone else held doesn't carry on), and the account
180
- * takes Google's picture if it had none. `keepSessionToken` is the session of the person connecting
181
- * Google from their account page, which stays; a Google sign-in that joins an account ends them all
182
- * 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.
183
190
  */
184
191
  export declare function afterAccountSaved(account: {
185
192
  providerId: string;
186
193
  userId: string;
187
194
  idToken?: string | null | undefined;
188
- }, adapter: AccountAdapter, keepSessionToken?: string | null): Promise<boolean>;
195
+ }, adapter: AccountAdapter, signedInUserId?: string | null): Promise<boolean>;
189
196
  /** The part of Better Auth's endpoint context the account hook reads. */
190
197
  type AccountHookContext = {
191
198
  context: {
192
199
  internalAdapter: AccountAdapter;
193
200
  session?: {
194
- session: {
195
- token: string;
201
+ user: {
202
+ id: string;
196
203
  };
197
204
  } | null;
198
205
  authCookies: {
package/dist/auth.js CHANGED
@@ -21,8 +21,8 @@ var PLACEHOLDER_EMAIL_DOMAIN = "users.invalid";
21
21
  function isPlaceholderEmail(email) {
22
22
  return email.toLowerCase().endsWith(`@${PLACEHOLDER_EMAIL_DOMAIN}`);
23
23
  }
24
- function placeholderEmail() {
25
- return `${crypto.randomUUID().replaceAll("-", "")}@${PLACEHOLDER_EMAIL_DOMAIN}`;
24
+ function placeholderEmail(randomId = () => globalThis.crypto.randomUUID()) {
25
+ return `${randomId().replaceAll("-", "")}@${PLACEHOLDER_EMAIL_DOMAIN}`;
26
26
  }
27
27
  function usernameFromName(name, email, fallback) {
28
28
  const clean = (text) => (typeof text.normalize === "function" ? text.normalize("NFKD") : text).replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[\s-]+/g, ".").replace(/[^a-z0-9_.]/g, "").replace(/\.{2,}/g, ".").replace(/^[._]+|[._]+$/g, "").slice(0, USERNAME.max - 5).replace(/[._]+$/g, "");
@@ -199,19 +199,14 @@ function pictureFromIdToken(idToken) {
199
199
  return null;
200
200
  }
201
201
  }
202
- async function afterAccountSaved(account, adapter, keepSessionToken) {
202
+ async function afterAccountSaved(account, adapter, signedInUserId) {
203
203
  if (account.providerId !== "google")
204
204
  return false;
205
205
  const accounts = await adapter.findAccounts(account.userId);
206
206
  if (!accounts.some((other) => other.providerId !== "google"))
207
207
  return false;
208
- if (keepSessionToken) {
209
- const others = (await adapter.listSessions(account.userId)).map((session) => session.token).filter((token) => token !== keepSessionToken);
210
- if (others.length)
211
- await adapter.deleteSessions(others);
212
- } else {
208
+ if (signedInUserId !== account.userId)
213
209
  await adapter.deleteUserSessions(account.userId);
214
- }
215
210
  const picture = pictureFromIdToken(account.idToken);
216
211
  if (picture) {
217
212
  const user = await adapter.findUserById(account.userId);
@@ -220,9 +215,14 @@ async function afterAccountSaved(account, adapter, keepSessionToken) {
220
215
  }
221
216
  return true;
222
217
  }
223
- async function currentSessionToken(ctx) {
224
- const token = ctx.context.session?.session.token ?? await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret).catch(() => null);
225
- 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;
226
226
  }
227
227
  function signedInFlagHook(name, maxAgeSeconds = 365 * 24 * 60 * 60) {
228
228
  return createAuthMiddleware(async (ctx) => {
@@ -304,7 +304,7 @@ function standardAuthOptions(input) {
304
304
  create: {
305
305
  after: async (account, ctx) => {
306
306
  if (ctx)
307
- await afterAccountSaved(account, ctx.context.internalAdapter, await currentSessionToken(ctx));
307
+ await afterAccountSaved(account, ctx.context.internalAdapter, await signedInUserId(ctx));
308
308
  }
309
309
  }
310
310
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jgb-solutions/kit",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
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",