@jgb-solutions/kit 0.5.0 → 0.7.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/CHANGELOG.md +41 -0
- package/README.md +37 -6
- package/dist/auth/browser.d.ts +77 -0
- package/dist/auth/browser.js +83 -0
- package/dist/auth/bun.d.ts +3 -2
- package/dist/auth/bun.js +4 -2
- package/dist/auth/expo.d.ts +65 -1
- package/dist/auth/expo.js +42 -2
- package/dist/auth/orpc.d.ts +6 -0
- package/dist/auth/orpc.js +11 -3
- package/dist/auth/server.d.ts +43 -7
- package/dist/auth/server.js +178 -16
- package/dist/auth/versions.d.ts +17 -0
- package/dist/auth/versions.js +19 -0
- package/dist/auth.d.ts +111 -3
- package/dist/auth.js +110 -4
- package/dist/i18n.js +2 -2
- package/package.json +11 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,47 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `@jgb-solutions/kit`. Versions follow semver.
|
|
4
4
|
|
|
5
|
+
## 0.7.0
|
|
6
|
+
|
|
7
|
+
Security fixes from the 2026-12-04 audit. Breaking changes are marked; see "Upgrading" at the end of this section.
|
|
8
|
+
|
|
9
|
+
- **Breaking:** `authServer` takes a required `rateLimit: { storage }`, or `'off'` for E2E (it throws on a production server unless E2E=1). Better Auth limits only requests to its own routes, so direct `auth.api` calls from server functions were unthrottled. Each sign-in, sign-up, password change, first password, Google start or link and account deletion now counts per address under Better Auth's own keys (`<ip>|<path>`). Over the limit: `TOO_MANY_REQUESTS`.
|
|
10
|
+
- Password sign-in also counts per login, through /api/auth and direct calls alike: `accountSignInLimit(storage)`, a Better Auth hook that `standardAuthOptions` adds when rate limits are on (`ACCOUNT_SIGN_IN_RULE`, 30 in 15 minutes, keyed by a hash), so a new address per attempt doesn't reset it.
|
|
11
|
+
- **Breaking:** `AuthResult`'s failure has an optional `retryAfter`; code that rebuilds the type or matches it exactly must allow it.
|
|
12
|
+
- **Breaking:** `AuthInstance` (and so `authServer`'s `auth`) needs `options` as well as `api` (the Better Auth instance has both; a hand-made stub needs `options: {}`), and `AuthApi.getSession` must answer `session.createdAt`.
|
|
13
|
+
- **Breaking:** `deleteOwnAccount` for an account without a password no longer takes `confirmUsername` (a public username proved nothing). It needs a sign-in from the last `REAUTH_MINUTES` (5), else `REAUTH_REQUIRED`. `AUTH_SERVER_CODES.confirmUsername` becomes `reauthRequired`.
|
|
14
|
+
- **Breaking:** `MobileSession` has a new `{ status: 'unverified' }`. When the server can't be reached at launch, `restore()` sets it instead of `out` with the token still sent. New `handleUnauthorized(error)` forgets the token on any UNAUTHORIZED answer.
|
|
15
|
+
- **Breaking (trust):** the client's address comes from `ipAddressHeaders` (`cf-connecting-ip` by default), which only Cloudflare sets reliably. A server reachable without Cloudflare must list its own proxy's header, or every per-address limit can be dodged.
|
|
16
|
+
- `googleIdTokenNonce({ mode })` (new Better Auth plugin, added by `standardAuthOptions` when Google is on; `googleNonce: 'optional'` by default). POST /google/nonce issues a single-use nonce (5 minutes, never cached; expired ones are swept), and a Google ID-token sign-in or link spends it, so a stolen token can't be replayed. **Plan:** `'required'` becomes the default in 0.9.0 (planned for January 2027), once every app's mobile build sends a nonce; until then a token sent without one still skips the check. Apps can set `googleNonce: 'required'` sooner.
|
|
17
|
+
- Expo: `auth.googleNonce()` answers `{ ok: true, nonce }` or `{ ok: false, code }` (NONCE_UNAVAILABLE, NETWORK, TOO_MANY_REQUESTS…) for the app's error tracker. **Breaking:** `googleIdToken(module, webClientId, nonce)` passes the nonce to the native module's `signIn(serverClientId, nonce)`, so the module must accept and use it (Credential Manager's `setNonce`).
|
|
18
|
+
- `kit/auth/versions` (new, no imports): `AUTH_VERSIONS`, the better-auth, passkey and jose versions this release is tested with, and `authVersionProblems(dependencies)` for an app's CI check, so the auth set moves in every app together.
|
|
19
|
+
- `counterRateLimit` counts in memory while its store is down, instead of letting every attempt through. New `memoryRateLimit()`.
|
|
20
|
+
- `kit/auth/orpc`: `authMiddleware({ freshViewer })` makes `requireAdmin` re-read the session fresh, so a ban or a lost role counts at once. `withUser` marks any answer for a signed-in person `private, no-store`.
|
|
21
|
+
- `concurrencyLimit(limit, maxQueue)` refuses new tasks past `maxQueue` waiting; `argon2idHasher({ concurrency })` caps its queue at 100 per running hash.
|
|
22
|
+
- `createTranslator` reads own properties only, so `{constructor}` in a message or key never prints a built-in.
|
|
23
|
+
|
|
24
|
+
### Upgrading
|
|
25
|
+
|
|
26
|
+
From 0.4.x:
|
|
27
|
+
|
|
28
|
+
1. Pin `better-auth` and `@better-auth/passkey` to `AUTH_VERSIONS` (1.7.29).
|
|
29
|
+
2. Pass `rateLimit: { storage }` to `authServer`, the same store as `standardAuthOptions`' `rateLimitStorage` (`counterRateLimit(…)`, or `memoryRateLimit()` on one server); `'off'` only on the E2E server.
|
|
30
|
+
3. Check `ipAddressHeaders` names a header your proxy sets.
|
|
31
|
+
4. Deleting an account without a password: drop the username field; offer "sign in with Google again" on `REAUTH_REQUIRED`, then delete.
|
|
32
|
+
5. Mobile: handle `unverified` wherever the session status is switched on, call `handleUnauthorized` from the RPC client's error interceptor, fetch `googleNonce()` before Google's sheet, and update the native module's `signIn` to take the nonce.
|
|
33
|
+
6. Word the new codes: `TOO_MANY_REQUESTS`, `REAUTH_REQUIRED`, `INVALID_NONCE`, `NONCE_REQUIRED`.
|
|
34
|
+
|
|
35
|
+
From 0.3.x, also take 0.4.x's and 0.5.0's changes: move the app's own account code onto `kit/auth/server` (0.5.0) and `kit/auth/browser` (0.6.0), and its caching headers onto `kit/auth/cache`, then follow the steps above.
|
|
36
|
+
|
|
37
|
+
## 0.6.0
|
|
38
|
+
|
|
39
|
+
- `kit/auth/browser` (new, no dependencies):
|
|
40
|
+
- `passkeyClient({ webauthn })`: passkey sign-in and adding a passkey against Better Auth's endpoints, with the app's `@simplewebauthn/browser` passed in. Answers are codes (`CANCELLED`, `NETWORK`, `INVALID_OPTIONS`, or Better Auth's own).
|
|
41
|
+
- `createPendingAction<Kind>()`: what a signed-out visitor tapped, kept in this tab until sign-in.
|
|
42
|
+
- `afterSignIn(next, done)` adds the `#done=` flash.
|
|
43
|
+
- `readSignedInFlag(name)` reads the signed-in flag cookie.
|
|
44
|
+
- `kit/auth/expo`: `googleIdToken(module, webClientId)`, the ID token from the phone's Google account sheet (the app's native Credential Manager module). Errors are mapped to `CANCELLED`, `NO_GOOGLE_ACCOUNT`, `GOOGLE_UNAVAILABLE` or `GOOGLE_FAILED` (with a detail for the error tracker).
|
|
45
|
+
|
|
5
46
|
## 0.5.0
|
|
6
47
|
|
|
7
48
|
The account logic every app copied, now in the kit. Nothing existing changes.
|
package/README.md
CHANGED
|
@@ -83,7 +83,7 @@ What the preset sets:
|
|
|
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.
|
|
86
|
-
- **Limits:** 60 requests a minute, tighter on sign-in, sign-up, passkeys and password changes (`RATE_LIMIT_RULES`). Counts go in the database, or in a counter store with `rateLimitStorage: counterRateLimit(() => redis)`, which
|
|
86
|
+
- **Limits:** 60 requests a minute, tighter on sign-in, sign-up, passkeys and password changes (`RATE_LIMIT_RULES`). Counts go in the database, or in a counter store with `rateLimitStorage: counterRateLimit(() => redis)`, which counts in the server's memory while the store is down (`memoryRateLimit()` on its own suits a single server).
|
|
87
87
|
- **Sessions:** 30 days, renewed daily, with a 5-minute cookie cache. The base URL is the request's host only for the site or a local host; anything else falls back to the site.
|
|
88
88
|
|
|
89
89
|
#### Google and existing accounts: merge only confirmed
|
|
@@ -123,7 +123,13 @@ Sign-in, sign-up, passwords, passkeys, Google, deleting one's own account and th
|
|
|
123
123
|
```ts
|
|
124
124
|
import { authServer } from '@jgb-solutions/kit/auth/server'
|
|
125
125
|
|
|
126
|
-
const accounts = authServer({
|
|
126
|
+
const accounts = authServer({
|
|
127
|
+
auth: getAuth,
|
|
128
|
+
headers: getRequestHeaders,
|
|
129
|
+
roleOf,
|
|
130
|
+
canOpenAdmin,
|
|
131
|
+
rateLimit: { storage: rateLimitStorage }, // required: the store given to standardAuthOptions; 'off' only for E2E
|
|
132
|
+
})
|
|
127
133
|
|
|
128
134
|
await accounts.viewer() // the signed-in person, or null (also when suspended); { fresh: true } skips the cookie cache
|
|
129
135
|
await accounts.signIn({ login, password }) // username or email; a placeholder address never signs in
|
|
@@ -131,11 +137,13 @@ await accounts.signUp({ username, password, email }) // no email: a placeholder
|
|
|
131
137
|
await accounts.changePassword({ currentPassword, newPassword }) // signs out the other devices
|
|
132
138
|
await accounts.passkeys() // newest first
|
|
133
139
|
await accounts.googleStartUrl({ redirect, home: '/account', signInPath: '/sign-in' }) // redirect checked with safeRedirect
|
|
134
|
-
await accounts.deleteOwnAccount({ password }) //
|
|
140
|
+
await accounts.deleteOwnAccount({ password }) // without a password (Google): a sign-in from the last 5 minutes, else REAUTH_REQUIRED
|
|
135
141
|
await accounts.admin.listUsers({ page, pageSize: 25, search })
|
|
136
142
|
await accounts.admin.ban({ userId }) // also setRole, unban, resetPassword: never on the admin's own account
|
|
137
143
|
```
|
|
138
144
|
|
|
145
|
+
**Rate limits.** The client's address comes from `ipAddressHeaders` (`cf-connecting-ip` by default): that header is trustworthy only when every request comes through Cloudflare. A server reachable directly must list the header its own proxy sets, or anyone can pick a new address per request. Better Auth limits only requests to its own routes (/api/auth/…), never a direct `auth.api` call, so a server function calling it is unthrottled. `authServer` counts each attempt itself, in the same store and under Better Auth's own keys (`<ip>|<path>`, the address read the way the instance reads it), so the two add up. Password sign-in also counts per login, through either door: `standardAuthOptions` adds `accountSignInLimit` (`ACCOUNT_SIGN_IN_RULE`, 30 in 15 minutes per login, its username and its address each, keyed by a hash), a Better Auth hook that runs for /api/auth requests and direct calls alike, so a new address per attempt doesn't reset it. It uses `rateLimitStorage` (in memory with the database store). `rateLimit: 'off'` throws on a production server unless E2E=1. Over the limit: `TOO_MANY_REQUESTS` with `retryAfter` in seconds.
|
|
146
|
+
|
|
139
147
|
Admin calls read the session fresh and go through `toAuthUser`, so a suspended admin is out at once. `authResult(fn)` turns any other Better Auth call into the same `{ ok, code }`.
|
|
140
148
|
|
|
141
149
|
#### `kit/auth/cache`: per-person pages stay out of shared caches
|
|
@@ -146,6 +154,24 @@ CDN cache keys ignore cookies, so a signed-in page stored once reaches the next
|
|
|
146
154
|
|
|
147
155
|
`redisCounterStore(redis, 'app:')` is a counter store for `counterRateLimit`, with any client that has `incr` and `expire` (Bun's `RedisClient`, ioredis). For oRPC's Redis limiter, `evalWithFallback(() => redis.send('EVAL', …))` answers `RATE_LIMIT_SCRIPT_FALLBACK` (`[1, 0, 0]`: allowed, nothing counted) while the store is away. From oRPC 2.0.0-beta.53 the old `[0, 0]` reads as refused, and every call failed.
|
|
148
156
|
|
|
157
|
+
#### `kit/auth/browser`: passkeys and pending actions in the website
|
|
158
|
+
|
|
159
|
+
No dependencies: the app passes `@simplewebauthn/browser` in, loaded only when a passkey button is pressed.
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
import { afterSignIn, createPendingAction, passkeyClient, readSignedInFlag } from '@jgb-solutions/kit/auth/browser'
|
|
163
|
+
|
|
164
|
+
const passkeys = passkeyClient({ webauthn: () => import('@simplewebauthn/browser') }) // Better Auth's /api/auth/passkey
|
|
165
|
+
await passkeys.signIn() // { ok: true } or { ok: false, code } (CANCELLED, NETWORK, Better Auth's codes)
|
|
166
|
+
await passkeys.add('My laptop')
|
|
167
|
+
|
|
168
|
+
export const pending = createPendingAction<'favorite' | 'follow'>() // what a signed-out visitor tapped, in this tab only
|
|
169
|
+
pending.set({ kind: 'favorite', name: song.title, run: () => addFavorite(song.id) })
|
|
170
|
+
const done = await pending.finish('signed-in') // after sign-in: runs it, answers its kind
|
|
171
|
+
location.assign(afterSignIn(redirect, done)) // …#done=favorite for the confirmation
|
|
172
|
+
readSignedInFlag('example_in') // the readable flag cookie standardAuthOptions sets (a hint; the server checks)
|
|
173
|
+
```
|
|
174
|
+
|
|
149
175
|
#### `kit/auth/expo`: the mobile app
|
|
150
176
|
|
|
151
177
|
```ts
|
|
@@ -165,12 +191,17 @@ export const auth = createMobileAuth({
|
|
|
165
191
|
|
|
166
192
|
const session = useSyncExternalStore(auth.subscribe, auth.getSession)
|
|
167
193
|
await auth.signIn('maria', password) // or an email address
|
|
168
|
-
await auth.
|
|
194
|
+
const nonce = await auth.googleNonce() // { ok: true, nonce } (single use) or { ok: false, code }: report the code
|
|
195
|
+
await auth.signInWithGoogle(idToken, nonce.ok ? { nonce: nonce.nonce } : {}) // from the app's Google Sign-In SDK, asked with the nonce
|
|
169
196
|
await auth.linkGoogle(idToken) // signed in: connect Google from the account screen
|
|
170
197
|
await auth.signInWithPasskey(Passkeys)
|
|
171
|
-
new RPCLink({ url, headers: auth.authHeaders }) // Bearer on every RPC call
|
|
198
|
+
new RPCLink({ url, headers: auth.authHeaders }) // Bearer on every RPC call; in its error interceptor: auth.handleUnauthorized(error)
|
|
172
199
|
```
|
|
173
200
|
|
|
201
|
+
`restore()` at launch checks the saved token with the server. Offline, the session is `unverified`: never signed in (show signed-out or cached screens) and `restore()` again when back online. Any UNAUTHORIZED answer passed to `handleUnauthorized` forgets the token.
|
|
202
|
+
|
|
203
|
+
On Android, `googleIdToken(nativeModule, webClientId, nonce)` gets the ID token from the phone's Google account sheet (the app's own Credential Manager module: `signIn(serverClientId)` answering `{ idToken }`, rejecting with `ERR_CANCELLED` or `ERR_NO_ACCOUNT`). It answers `{ ok: true, idToken }`, or `CANCELLED`, `NO_GOOGLE_ACCOUNT`, `GOOGLE_UNAVAILABLE` (no module or client ID), or `GOOGLE_FAILED` with a `detail` for the error tracker.
|
|
204
|
+
|
|
174
205
|
Failures come back as codes (`INVALID_USERNAME_OR_PASSWORD`, `ACCOUNT_NOT_LINKED`, `GOOGLE_ALREADY_LINKED`, `TOO_MANY_REQUESTS`, `NETWORK`, `CANCELLED`…), and the app words them. The module has no dependencies: the app passes in its secure storage and passkey modules.
|
|
175
206
|
|
|
176
207
|
### `@jgb-solutions/kit/i18n`: four languages, one set of rules
|
|
@@ -349,7 +380,7 @@ Type: Bricolage Grotesque (700/800) for titles and numbers (`tabular-nums`), Fig
|
|
|
349
380
|
- **Infrastructure details:** hosts, IP addresses, server names, internal URLs, deploy setup.
|
|
350
381
|
- **Personal data, or real addresses outside `example.com`.**
|
|
351
382
|
|
|
352
|
-
`bun run check:package` scans every file that would be published, before each publish and in CI. It fails on an Access team domain other than the examples, on a 32- or 64-character hex ID, on an address outside `example.com`, on any file besides `dist/`, the README, the changelog, the license and `package.json`, and on a module importing more than it may (`kit/access` jose alone; `kit/auth/rules`, `kit/auth/cache`, `kit/auth/redis`, `kit/auth/expo` and `kit/auth/bun` nothing). `bun run check:install` installs the packed package without the optional peers and checks that `kit/access`, `kit/auth/rules` and `kit/auth/expo` load and type-check there.
|
|
383
|
+
`bun run check:package` scans every file that would be published, before each publish and in CI. It fails on an Access team domain other than the examples, on a 32- or 64-character hex ID, on an address outside `example.com`, on any file besides `dist/`, the README, the changelog, the license and `package.json`, and on a module importing more than it may (`kit/access` jose alone; `kit/auth/rules`, `kit/auth/browser`, `kit/auth/cache`, `kit/auth/redis`, `kit/auth/expo` and `kit/auth/bun` nothing). `bun run check:install` installs the packed package without the optional peers and checks that `kit/access`, `kit/auth/rules` and `kit/auth/expo` load and type-check there.
|
|
353
384
|
|
|
354
385
|
## Developing
|
|
355
386
|
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sign-in pieces that run in the website's browser, the same in every app: passkeys against Better
|
|
3
|
+
* Auth's own endpoints, the action a visitor tried before signing in, and the signed-in flag. No
|
|
4
|
+
* dependencies: the app passes `@simplewebauthn/browser` in (loaded only when a passkey button is
|
|
5
|
+
* pressed), so no auth library ships to every visitor.
|
|
6
|
+
*
|
|
7
|
+
* import { passkeyClient } from '@jgb-solutions/kit/auth/browser'
|
|
8
|
+
* const passkeys = passkeyClient({ webauthn: () => import('@simplewebauthn/browser') })
|
|
9
|
+
* const result = await passkeys.signIn() // { ok: true } or { ok: false, code }
|
|
10
|
+
*/
|
|
11
|
+
/** What a passkey call answers: done, or a code (Better Auth's, or CANCELLED / NETWORK / INVALID_OPTIONS). */
|
|
12
|
+
export type PasskeyResult = {
|
|
13
|
+
ok: true;
|
|
14
|
+
} | {
|
|
15
|
+
ok: false;
|
|
16
|
+
code: string;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* The two calls of `@simplewebauthn/browser` this module makes. The options come from Better Auth's
|
|
20
|
+
* passkey endpoints, which build them for these very functions.
|
|
21
|
+
*/
|
|
22
|
+
export type WebAuthnBrowser = {
|
|
23
|
+
startAuthentication(input: {
|
|
24
|
+
optionsJSON: never;
|
|
25
|
+
}): Promise<unknown>;
|
|
26
|
+
startRegistration(input: {
|
|
27
|
+
optionsJSON: never;
|
|
28
|
+
}): Promise<unknown>;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Passkeys in the browser: the WebAuthn ceremony with the app's `@simplewebauthn/browser`, against
|
|
32
|
+
* Better Auth's endpoints under `base` (same origin, so its session and challenge cookies ride along).
|
|
33
|
+
*/
|
|
34
|
+
export declare function passkeyClient(config: {
|
|
35
|
+
webauthn: () => Promise<WebAuthnBrowser>;
|
|
36
|
+
base?: string;
|
|
37
|
+
fetch?: typeof globalThis.fetch;
|
|
38
|
+
}): {
|
|
39
|
+
/** Signs in with a passkey on this device. On success the session cookie is set: reload or refetch. */
|
|
40
|
+
signIn: () => Promise<PasskeyResult>;
|
|
41
|
+
/** Adds a passkey, named `name`, to the signed-in account. */
|
|
42
|
+
add: (name: string) => Promise<PasskeyResult>;
|
|
43
|
+
};
|
|
44
|
+
/** Something a signed-out visitor tapped (a heart, Follow), to do once they're signed in. */
|
|
45
|
+
export type PendingAction<Kind extends string> = {
|
|
46
|
+
kind: Kind;
|
|
47
|
+
name?: string;
|
|
48
|
+
run: () => Promise<unknown>;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* The action a visitor tried before signing in, kept in this tab's memory only: no storage, nothing in
|
|
52
|
+
* the URL. The button sets it and opens sign-in; sign-in finishes it once the person is in. A full
|
|
53
|
+
* reload on the way (a Google round trip) drops it: the visitor is signed in all the same and can tap again.
|
|
54
|
+
*/
|
|
55
|
+
export declare function createPendingAction<Kind extends string>(): {
|
|
56
|
+
set(action: PendingAction<Kind>): void;
|
|
57
|
+
/** The name of what the visitor tapped, for the sign-in notice. */
|
|
58
|
+
name(): string | undefined;
|
|
59
|
+
clear(): void;
|
|
60
|
+
/**
|
|
61
|
+
* Runs the pending action once signed in and answers its kind, for the confirmation. With nothing
|
|
62
|
+
* pending it answers `otherwise` (for example 'signed-in' for a visitor sent from a page that needs
|
|
63
|
+
* an account). A failed action answers undefined: they're signed in and can tap again.
|
|
64
|
+
*/
|
|
65
|
+
finish<Otherwise extends string | undefined = undefined>(otherwise?: Otherwise): Promise<Kind | Otherwise | undefined>;
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Where to go after signing in: `next`, with `#done=<kind>` when something was done. `next` must
|
|
69
|
+
* already be a path checked with `safeRedirect` (kit/auth/rules): this adds the flash, it checks nothing.
|
|
70
|
+
*/
|
|
71
|
+
export declare function afterSignIn(next: string, done: string | undefined): string;
|
|
72
|
+
/**
|
|
73
|
+
* True when the signed-in flag cookie (`signedInFlag` in `standardAuthOptions`, readable by scripts,
|
|
74
|
+
* unlike the session) says this browser is signed in: a cached page can then fetch the person's own
|
|
75
|
+
* bits without a request for every visitor. A hint only; the server always checks the session.
|
|
76
|
+
*/
|
|
77
|
+
export declare function readSignedInFlag(name: string, cookie?: string): boolean;
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// src/auth/browser.ts
|
|
2
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3
|
+
var codeOf = (body, fallback) => isRecord(body) && typeof body.code === "string" && body.code ? body.code : fallback;
|
|
4
|
+
var looksLikeOptions = (body) => isRecord(body) && typeof body.challenge === "string";
|
|
5
|
+
function passkeyClient(config) {
|
|
6
|
+
const base = (config.base ?? "/api/auth/passkey").replace(/\/+$/, "");
|
|
7
|
+
const fetcher = config.fetch ?? globalThis.fetch.bind(globalThis);
|
|
8
|
+
async function call(path, body) {
|
|
9
|
+
try {
|
|
10
|
+
const response = await fetcher(`${base}/${path}`, {
|
|
11
|
+
credentials: "same-origin",
|
|
12
|
+
...body === undefined ? {} : { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }
|
|
13
|
+
});
|
|
14
|
+
return { ok: response.ok, body: await response.json().catch(() => null) };
|
|
15
|
+
} catch {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
async function ceremony(optionsPath, run, verifyPath, extra) {
|
|
20
|
+
const options = await call(optionsPath);
|
|
21
|
+
if (!options)
|
|
22
|
+
return { ok: false, code: "NETWORK" };
|
|
23
|
+
if (!options.ok)
|
|
24
|
+
return { ok: false, code: codeOf(options.body, "FAILED") };
|
|
25
|
+
if (!looksLikeOptions(options.body))
|
|
26
|
+
return { ok: false, code: "INVALID_OPTIONS" };
|
|
27
|
+
let response;
|
|
28
|
+
try {
|
|
29
|
+
response = await run(await config.webauthn(), options.body);
|
|
30
|
+
} catch {
|
|
31
|
+
return { ok: false, code: "CANCELLED" };
|
|
32
|
+
}
|
|
33
|
+
const verified = await call(verifyPath, { response, ...extra });
|
|
34
|
+
if (!verified)
|
|
35
|
+
return { ok: false, code: "NETWORK" };
|
|
36
|
+
return verified.ok ? { ok: true } : { ok: false, code: codeOf(verified.body, "FAILED") };
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
signIn: () => ceremony("generate-authenticate-options", (webauthn, optionsJSON) => webauthn.startAuthentication({ optionsJSON }), "verify-authentication", {}),
|
|
40
|
+
add: (name) => ceremony(`generate-register-options?name=${encodeURIComponent(name)}`, (webauthn, optionsJSON) => webauthn.startRegistration({ optionsJSON }), "verify-registration", { name })
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function createPendingAction() {
|
|
44
|
+
let pending;
|
|
45
|
+
return {
|
|
46
|
+
set(action) {
|
|
47
|
+
pending = action;
|
|
48
|
+
},
|
|
49
|
+
name() {
|
|
50
|
+
return pending?.name;
|
|
51
|
+
},
|
|
52
|
+
clear() {
|
|
53
|
+
pending = undefined;
|
|
54
|
+
},
|
|
55
|
+
async finish(otherwise) {
|
|
56
|
+
const action = pending;
|
|
57
|
+
pending = undefined;
|
|
58
|
+
if (!action)
|
|
59
|
+
return otherwise;
|
|
60
|
+
try {
|
|
61
|
+
await action.run();
|
|
62
|
+
return action.kind;
|
|
63
|
+
} catch {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function afterSignIn(next, done) {
|
|
70
|
+
return done ? `${next.split("#")[0]}#done=${encodeURIComponent(done)}` : next;
|
|
71
|
+
}
|
|
72
|
+
function readSignedInFlag(name, cookie = typeof document === "undefined" ? "" : document.cookie) {
|
|
73
|
+
return cookie.split(";").some((part) => {
|
|
74
|
+
const [key, value] = part.split("=");
|
|
75
|
+
return key?.trim() === name && value?.trim() === "1";
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
export {
|
|
79
|
+
afterSignIn,
|
|
80
|
+
createPendingAction,
|
|
81
|
+
passkeyClient,
|
|
82
|
+
readSignedInFlag
|
|
83
|
+
};
|
package/dist/auth/bun.d.ts
CHANGED
|
@@ -30,6 +30,7 @@ export declare function argon2idHasher(options?: {
|
|
|
30
30
|
}): PasswordHasher;
|
|
31
31
|
/**
|
|
32
32
|
* Runs at most `limit` tasks at once; the rest wait in order. A finished task hands its place
|
|
33
|
-
* straight to the next one waiting, so a newcomer can never slip past the limit in between.
|
|
33
|
+
* straight to the next one waiting, so a newcomer can never slip past the limit in between. Past
|
|
34
|
+
* `maxQueue` waiting tasks, a new one is refused at once (it throws) instead of piling up in memory.
|
|
34
35
|
*/
|
|
35
|
-
export declare function concurrencyLimit(limit: number): <T>(task: () => Promise<T>) => Promise<T>;
|
|
36
|
+
export declare function concurrencyLimit(limit: number, maxQueue?: number): <T>(task: () => Promise<T>) => Promise<T>;
|
package/dist/auth/bun.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
function argon2idHasher(options = {}) {
|
|
3
3
|
const { fallbackVerify, concurrency, ...cost } = options;
|
|
4
4
|
const algorithm = { algorithm: "argon2id", ...cost };
|
|
5
|
-
const run = concurrency === undefined ? (task) => task() : concurrencyLimit(concurrency);
|
|
5
|
+
const run = concurrency === undefined ? (task) => task() : concurrencyLimit(concurrency, concurrency * 100);
|
|
6
6
|
return {
|
|
7
7
|
hash: (password) => run(() => Bun.password.hash(password, algorithm)),
|
|
8
8
|
verify: ({ hash, password }) => run(() => {
|
|
@@ -12,7 +12,7 @@ function argon2idHasher(options = {}) {
|
|
|
12
12
|
})
|
|
13
13
|
};
|
|
14
14
|
}
|
|
15
|
-
function concurrencyLimit(limit) {
|
|
15
|
+
function concurrencyLimit(limit, maxQueue = Infinity) {
|
|
16
16
|
if (!Number.isInteger(limit) || limit < 1)
|
|
17
17
|
throw new RangeError("concurrency must be a whole number of at least 1");
|
|
18
18
|
let running = 0;
|
|
@@ -20,6 +20,8 @@ function concurrencyLimit(limit) {
|
|
|
20
20
|
return async (task) => {
|
|
21
21
|
if (running < limit)
|
|
22
22
|
running++;
|
|
23
|
+
else if (waiting.length >= maxQueue)
|
|
24
|
+
throw new Error("concurrency limit: the queue is full");
|
|
23
25
|
else
|
|
24
26
|
await new Promise((resolve) => waiting.push(resolve));
|
|
25
27
|
try {
|
package/dist/auth/expo.d.ts
CHANGED
|
@@ -9,10 +9,17 @@ export type PasskeysModule = {
|
|
|
9
9
|
get(request: unknown): Promise<unknown>;
|
|
10
10
|
create(request: unknown): Promise<unknown>;
|
|
11
11
|
};
|
|
12
|
+
/**
|
|
13
|
+
* The app's session. `unverified`: a saved token the server couldn't check (offline at launch). It
|
|
14
|
+
* is never signed in: show signed-out or cached screens and call `restore()` again when back online.
|
|
15
|
+
* The token is kept for that retry, and dropped as soon as the server says it is dead.
|
|
16
|
+
*/
|
|
12
17
|
export type MobileSession<U> = {
|
|
13
18
|
status: 'loading';
|
|
14
19
|
} | {
|
|
15
20
|
status: 'out';
|
|
21
|
+
} | {
|
|
22
|
+
status: 'unverified';
|
|
16
23
|
} | {
|
|
17
24
|
status: 'in';
|
|
18
25
|
user: U;
|
|
@@ -46,8 +53,16 @@ export declare function createMobileAuth<U>(config: MobileAuthConfig<U>): {
|
|
|
46
53
|
subscribe(listener: () => void): () => void;
|
|
47
54
|
getSession: () => MobileSession<U>;
|
|
48
55
|
authHeaders: () => Record<string, string>;
|
|
49
|
-
/**
|
|
56
|
+
/**
|
|
57
|
+
* At launch, and again when back online: the saved token, checked with the server. A dead token
|
|
58
|
+
* is dropped; when the server can't be reached the session is `unverified`, never signed in.
|
|
59
|
+
*/
|
|
50
60
|
restore(): Promise<void>;
|
|
61
|
+
/**
|
|
62
|
+
* For the app's RPC client's error interceptor: an UNAUTHORIZED answer to any call means the
|
|
63
|
+
* token is dead (expired, revoked, account deleted), so it is forgotten at once. True when it was.
|
|
64
|
+
*/
|
|
65
|
+
handleUnauthorized(error: unknown): Promise<boolean>;
|
|
51
66
|
/** A username or an email address, and the password. */
|
|
52
67
|
signIn(login: string, password: string): Promise<AuthResult>;
|
|
53
68
|
/** A new account. Without an email address, the placeholder the website uses (never shown or mailed). */
|
|
@@ -62,6 +77,20 @@ export declare function createMobileAuth<U>(config: MobileAuthConfig<U>): {
|
|
|
62
77
|
* with Google (its audience must be one of GOOGLE_CLIENT_ID or GOOGLE_MOBILE_CLIENT_IDS) and signs
|
|
63
78
|
* in, links or creates the account by the server's rules.
|
|
64
79
|
*/
|
|
80
|
+
/**
|
|
81
|
+
* A single-use nonce from the server (kit's googleIdTokenNonce), for Google's sheet and then
|
|
82
|
+
* `signInWithGoogle` / `linkGoogle`: a stolen ID token can't be replayed. Without one the answer
|
|
83
|
+
* says why, for the app's error tracker: NONCE_UNAVAILABLE (a server without the plugin), NETWORK,
|
|
84
|
+
* TOO_MANY_REQUESTS or the server's code. While the server's mode is 'optional' the app may go on
|
|
85
|
+
* without a nonce; once it is 'required' that sign-in will be refused.
|
|
86
|
+
*/
|
|
87
|
+
googleNonce(): Promise<{
|
|
88
|
+
ok: true;
|
|
89
|
+
nonce: string;
|
|
90
|
+
} | {
|
|
91
|
+
ok: false;
|
|
92
|
+
code: string;
|
|
93
|
+
}>;
|
|
65
94
|
signInWithGoogle(idToken: string, options?: {
|
|
66
95
|
nonce?: string;
|
|
67
96
|
}): Promise<AuthResult>;
|
|
@@ -83,3 +112,38 @@ export declare function createMobileAuth<U>(config: MobileAuthConfig<U>): {
|
|
|
83
112
|
forget: () => Promise<void>;
|
|
84
113
|
};
|
|
85
114
|
export type MobileAuth<U> = ReturnType<typeof createMobileAuth<U>>;
|
|
115
|
+
/**
|
|
116
|
+
* The native Google account sheet: a module with `signIn(serverClientId)` answering Google's ID token
|
|
117
|
+
* (Android's Credential Manager), rejecting with `error.code` ERR_CANCELLED, ERR_NO_ACCOUNT or another.
|
|
118
|
+
*/
|
|
119
|
+
export type GoogleCredentialModule = {
|
|
120
|
+
signIn(serverClientId: string, nonce?: string): Promise<{
|
|
121
|
+
idToken: string;
|
|
122
|
+
}>;
|
|
123
|
+
};
|
|
124
|
+
export type GoogleTokenResult = {
|
|
125
|
+
ok: true;
|
|
126
|
+
idToken: string;
|
|
127
|
+
} | {
|
|
128
|
+
ok: false;
|
|
129
|
+
code: 'CANCELLED' | 'NO_GOOGLE_ACCOUNT' | 'GOOGLE_UNAVAILABLE';
|
|
130
|
+
}
|
|
131
|
+
/** `detail` (the native code and message) is for the error tracker, never for the screen. */
|
|
132
|
+
| {
|
|
133
|
+
ok: false;
|
|
134
|
+
code: 'GOOGLE_FAILED';
|
|
135
|
+
detail: string;
|
|
136
|
+
};
|
|
137
|
+
/**
|
|
138
|
+
* Google's ID token from the phone's account sheet, for `signInWithGoogle` or `linkGoogle`, with the
|
|
139
|
+
* nonce from `auth.googleNonce()` when there is one:
|
|
140
|
+
*
|
|
141
|
+
* const nonce = await auth.googleNonce() // report a failure's code to the error tracker
|
|
142
|
+
* const google = await googleIdToken(GoogleModule, webClientId, nonce.ok ? nonce.nonce : null)
|
|
143
|
+
* if (google.ok) await auth.signInWithGoogle(google.idToken, nonce.ok ? { nonce: nonce.nonce } : {})
|
|
144
|
+
* `module`
|
|
145
|
+
* is the app's native module, or null where the installed app lacks it (iOS, older builds):
|
|
146
|
+
* GOOGLE_UNAVAILABLE then, as without `webClientId` (the website's OAuth client, whose tokens Better
|
|
147
|
+
* Auth accepts). CANCELLED means the person closed the sheet: nothing to say.
|
|
148
|
+
*/
|
|
149
|
+
export declare function googleIdToken(module: GoogleCredentialModule | null | undefined, webClientId: string | null | undefined, nonce?: string | null): Promise<GoogleTokenResult>;
|
package/dist/auth/expo.js
CHANGED
|
@@ -205,9 +205,15 @@ function createMobileAuth(config) {
|
|
|
205
205
|
} catch (error) {
|
|
206
206
|
if (isUnauthorized(error))
|
|
207
207
|
return forget();
|
|
208
|
-
set({ status: "
|
|
208
|
+
set({ status: "unverified" });
|
|
209
209
|
}
|
|
210
210
|
},
|
|
211
|
+
async handleUnauthorized(error) {
|
|
212
|
+
if (!isUnauthorized(error) || !token)
|
|
213
|
+
return false;
|
|
214
|
+
await forget();
|
|
215
|
+
return true;
|
|
216
|
+
},
|
|
211
217
|
signIn(login, password) {
|
|
212
218
|
const value = login.trim().toLowerCase();
|
|
213
219
|
if (!value || !password)
|
|
@@ -224,6 +230,21 @@ function createMobileAuth(config) {
|
|
|
224
230
|
return Promise.resolve({ ok: false, code: "NO_RANDOM_ID" });
|
|
225
231
|
return signInWith("/sign-up/email", { name: input.name?.trim() || username, username, email, password: input.password });
|
|
226
232
|
},
|
|
233
|
+
async googleNonce() {
|
|
234
|
+
try {
|
|
235
|
+
const { response, body } = await call("/google/nonce", { method: "POST", body: {} });
|
|
236
|
+
if (response.status === 404)
|
|
237
|
+
return { ok: false, code: "NONCE_UNAVAILABLE" };
|
|
238
|
+
if (response.status === 429)
|
|
239
|
+
return { ok: false, code: "TOO_MANY_REQUESTS" };
|
|
240
|
+
const nonce = response.ok && typeof body === "object" && body !== null && "nonce" in body ? body.nonce : null;
|
|
241
|
+
if (typeof nonce === "string" && nonce)
|
|
242
|
+
return { ok: true, nonce };
|
|
243
|
+
return { ok: false, code: codeOf(body, response.ok ? "NO_NONCE" : String(response.status)) };
|
|
244
|
+
} catch {
|
|
245
|
+
return { ok: false, code: "NETWORK" };
|
|
246
|
+
}
|
|
247
|
+
},
|
|
227
248
|
signInWithGoogle(idToken, options = {}) {
|
|
228
249
|
return signInWith("/sign-in/social", {
|
|
229
250
|
provider: "google",
|
|
@@ -285,6 +306,25 @@ function createMobileAuth(config) {
|
|
|
285
306
|
forget
|
|
286
307
|
};
|
|
287
308
|
}
|
|
309
|
+
async function googleIdToken(module, webClientId, nonce) {
|
|
310
|
+
if (!module || !webClientId)
|
|
311
|
+
return { ok: false, code: "GOOGLE_UNAVAILABLE" };
|
|
312
|
+
try {
|
|
313
|
+
const { idToken } = await (nonce ? module.signIn(webClientId, nonce) : module.signIn(webClientId));
|
|
314
|
+
if (typeof idToken !== "string" || !idToken)
|
|
315
|
+
return { ok: false, code: "GOOGLE_FAILED", detail: "NO_TOKEN" };
|
|
316
|
+
return { ok: true, idToken };
|
|
317
|
+
} catch (error) {
|
|
318
|
+
const code = typeof error === "object" && error !== null && "code" in error ? String(error.code) : "";
|
|
319
|
+
if (code === "ERR_CANCELLED")
|
|
320
|
+
return { ok: false, code: "CANCELLED" };
|
|
321
|
+
if (code === "ERR_NO_ACCOUNT")
|
|
322
|
+
return { ok: false, code: "NO_GOOGLE_ACCOUNT" };
|
|
323
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
324
|
+
return { ok: false, code: "GOOGLE_FAILED", detail: `${code || "UNKNOWN"}: ${message}` };
|
|
325
|
+
}
|
|
326
|
+
}
|
|
288
327
|
export {
|
|
289
|
-
createMobileAuth
|
|
328
|
+
createMobileAuth,
|
|
329
|
+
googleIdToken
|
|
290
330
|
};
|
package/dist/auth/orpc.d.ts
CHANGED
|
@@ -11,6 +11,12 @@ export declare function authMiddleware<U extends {
|
|
|
11
11
|
canOpenAdmin: (role: string) => boolean;
|
|
12
12
|
/** An extra check for admin procedures, such as Cloudflare Access's token. False means FORBIDDEN. */
|
|
13
13
|
adminCheck?: () => Promise<boolean>;
|
|
14
|
+
/**
|
|
15
|
+
* The signed-in person read fresh from the database, skipping the session cookie cache (authServer's
|
|
16
|
+
* `viewer({ fresh: true })`). `requireAdmin` re-checks with it, so a ban or a role taken away counts
|
|
17
|
+
* at once instead of up to 5 minutes later. Recommended.
|
|
18
|
+
*/
|
|
19
|
+
freshViewer?: () => Promise<U | null>;
|
|
14
20
|
}): {
|
|
15
21
|
withUser: import("@orpc/server").DecoratedMiddleware<HeadersContext & object, {
|
|
16
22
|
user: U | null;
|
package/dist/auth/orpc.js
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
// src/auth/orpc.ts
|
|
2
2
|
import { ORPCError, os } from "@orpc/server";
|
|
3
3
|
function authMiddleware(options) {
|
|
4
|
-
const withUser = os.$context().middleware(async ({ next }) =>
|
|
4
|
+
const withUser = os.$context().middleware(async ({ context, next }) => {
|
|
5
|
+
const user = await options.viewer();
|
|
6
|
+
if (user)
|
|
7
|
+
context.resHeaders?.set("cache-control", "private, no-store");
|
|
8
|
+
return next({ context: { user } });
|
|
9
|
+
});
|
|
5
10
|
const requireUser = os.$context().middleware(async ({ context, next }) => {
|
|
6
11
|
if (!context.user)
|
|
7
12
|
throw new ORPCError("UNAUTHORIZED");
|
|
@@ -11,12 +16,15 @@ function authMiddleware(options) {
|
|
|
11
16
|
const requireAdmin = os.$context().middleware(async ({ context, next }) => {
|
|
12
17
|
if (!context.user)
|
|
13
18
|
throw new ORPCError("UNAUTHORIZED");
|
|
14
|
-
|
|
19
|
+
const user = options.freshViewer ? await options.freshViewer() : context.user;
|
|
20
|
+
if (!user)
|
|
21
|
+
throw new ORPCError("UNAUTHORIZED");
|
|
22
|
+
if (!options.canOpenAdmin(user.role))
|
|
15
23
|
throw new ORPCError("FORBIDDEN");
|
|
16
24
|
if (options.adminCheck && !await options.adminCheck())
|
|
17
25
|
throw new ORPCError("FORBIDDEN");
|
|
18
26
|
context.resHeaders?.set("cache-control", "private, no-store");
|
|
19
|
-
return next({ context: { user
|
|
27
|
+
return next({ context: { user } });
|
|
20
28
|
});
|
|
21
29
|
return { withUser, requireUser, requireAdmin };
|
|
22
30
|
}
|