@jgb-solutions/kit 0.1.1 → 0.2.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 +9 -0
- package/README.md +97 -4
- package/dist/auth/bun.d.ts +24 -0
- package/dist/auth/bun.js +16 -0
- package/dist/auth/expo.d.ts +79 -0
- package/dist/auth/expo.js +245 -0
- package/dist/auth/orpc.d.ts +29 -0
- package/dist/auth/orpc.js +25 -0
- package/dist/auth/rules.d.ts +100 -0
- package/dist/auth/rules.js +101 -0
- package/dist/auth.d.ts +2211 -0
- package/dist/auth.js +344 -0
- package/package.json +48 -4
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `@jgb-solutions/kit`. Versions follow semver.
|
|
4
4
|
|
|
5
|
+
## 0.2.0
|
|
6
|
+
|
|
7
|
+
- `@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.
|
|
8
|
+
- `@jgb-solutions/kit/auth/bun`: `argon2idHasher()`, Bun's argon2id for passwords; `fallbackVerify` keeps older hashes (Better Auth's scrypt) working for an app moving over.
|
|
9
|
+
- `@jgb-solutions/kit/auth/orpc`: `authMiddleware` → `withUser`, `requireUser`, `requireAdmin` (with an optional extra check, such as Cloudflare Access).
|
|
10
|
+
- `@jgb-solutions/kit/auth/rules`: browser-safe rules (usernames, passwords, placeholder emails, `defineRoles`, `avatarSrc`, `avatarInitials`), and `authErrorCode` with `ACCOUNT_NOT_LINKED`, `GOOGLE_ALREADY_LINKED` and `GOOGLE_EMAIL_NOT_CONFIRMED`.
|
|
11
|
+
- `@jgb-solutions/kit/auth/expo`: `createMobileAuth`, the mobile app's session (secure storage, Bearer header), sign-in and sign-up, Google with an ID token (`signInWithGoogle`, `linkGoogle`), passkeys. No dependencies: the app passes in `expo-secure-store` and `react-native-passkeys`.
|
|
12
|
+
- `better-auth`, `@better-auth/passkey` and `@orpc/server` are optional peer dependencies: an app that only uses `kit/access` installs jose alone. `check:package` checks each module's imports, and `check:install` installs the package without the peers and checks `access`, `auth/rules` and `auth/expo` there.
|
|
13
|
+
|
|
5
14
|
## 0.1.1
|
|
6
15
|
|
|
7
16
|
- Published from GitHub Actions with npm trusted publishing and provenance: the first release built and published by CI. No code changes.
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @jgb-solutions/kit
|
|
2
2
|
|
|
3
|
-
Small, typed, tree-shakable modules for the generic plumbing web apps need: the kind of code every app would otherwise copy by hand. ESM with TypeScript types, one subpath per module, MIT licensed. The modules run anywhere with Web Crypto and `fetch`: Bun, Node and Cloudflare Workers.
|
|
3
|
+
Small, typed, tree-shakable modules for the generic plumbing web apps need: the kind of code every app would otherwise copy by hand. ESM with TypeScript types, one subpath per module, MIT licensed. The modules run anywhere with Web Crypto and `fetch`: Bun, Node and Cloudflare Workers (`kit/auth/bun` on Bun only, `kit/auth/expo` in React Native).
|
|
4
4
|
|
|
5
5
|
```bash
|
|
6
6
|
bun add @jgb-solutions/kit
|
|
@@ -42,6 +42,99 @@ result.email // the signed-in person (null for a service token)
|
|
|
42
42
|
|
|
43
43
|
Keep the app's own role check after this one: Access decides who may reach the app, and the app decides what they may do.
|
|
44
44
|
|
|
45
|
+
### `@jgb-solutions/kit/auth`: Better Auth, the same in every app
|
|
46
|
+
|
|
47
|
+
Sign-in set up once for every app: a username or email with a password, passkeys (also the way back into an account whose password is forgotten, since no email is ever sent), "Continue with Google" when its keys are set, roles with an admin panel, and the same session for the website (cookie) and the mobile app (`Authorization: Bearer`).
|
|
48
|
+
|
|
49
|
+
It needs `better-auth` and `@better-auth/passkey` (and `@orpc/server` for `kit/auth/orpc`). They are **optional peer dependencies**: install them in the apps that use auth, and an app that only uses `kit/access` never gets them.
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
bun add @jgb-solutions/kit better-auth @better-auth/passkey
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
import { betterAuth } from 'better-auth'
|
|
57
|
+
import { tanstackStartCookies } from 'better-auth/tanstack-start'
|
|
58
|
+
import { authSettings, standardAuthOptions } from '@jgb-solutions/kit/auth'
|
|
59
|
+
import { argon2idHasher } from '@jgb-solutions/kit/auth/bun' // on Bun (Workers keep Better Auth's scrypt); fallbackVerify for older hashes
|
|
60
|
+
|
|
61
|
+
export const auth = betterAuth(
|
|
62
|
+
standardAuthOptions({
|
|
63
|
+
appName: 'Example',
|
|
64
|
+
siteUrl: 'https://app.example.com',
|
|
65
|
+
settings: authSettings(process.env), // BETTER_AUTH_SECRET, SIGN_UP, ADMIN_EMAILS, GOOGLE_*
|
|
66
|
+
database: drizzleAdapter(db, { provider: 'sqlite', schema }),
|
|
67
|
+
admin: { ac, roles, defaultRole: 'user', adminRoles: ['admin'] }, // the app's permissions
|
|
68
|
+
takenUsernames: (candidates) => findUsedUsernames(candidates), // one query
|
|
69
|
+
usernameFallback: 'member',
|
|
70
|
+
localOrigins: ['http://localhost:5173'],
|
|
71
|
+
password: argon2idHasher(),
|
|
72
|
+
beforeDeleteUser: (user) => deleteEverythingOf(user.id),
|
|
73
|
+
lastPlugin: tanstackStartCookies(),
|
|
74
|
+
}),
|
|
75
|
+
)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
What the preset sets:
|
|
79
|
+
|
|
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
|
+
- **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`).
|
|
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
|
+
- **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
|
+
- **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 lets attempts through when the store is down.
|
|
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
|
+
|
|
89
|
+
#### Google and existing accounts: merge only confirmed
|
|
90
|
+
|
|
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
|
+
|
|
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.
|
|
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
|
+
|
|
97
|
+
When Google joins a confirmed account that also has a password, that account's other sessions end too.
|
|
98
|
+
|
|
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
|
+
|
|
101
|
+
#### `kit/auth/orpc`: the person in `context.user`
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
import { authMiddleware } from '@jgb-solutions/kit/auth/orpc'
|
|
105
|
+
|
|
106
|
+
const { withUser, requireUser, requireAdmin } = authMiddleware({
|
|
107
|
+
viewer: async () => toAuthUser((await auth.api.getSession({ headers }))?.user, roleOf), // cookie or Bearer
|
|
108
|
+
canOpenAdmin,
|
|
109
|
+
adminCheck: async () => (await verifyAccess(headers, access)).ok, // optional: Cloudflare Access too
|
|
110
|
+
})
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`requireUser` answers `UNAUTHORIZED`, and `requireAdmin` answers `FORBIDDEN` for a role that can't open the admin panel or a failed `adminCheck`. Both mark the answer `private, no-store`.
|
|
114
|
+
|
|
115
|
+
#### `kit/auth/rules`: the same rules in the browser
|
|
116
|
+
|
|
117
|
+
`USERNAME`, `PASSWORD`, `usernameProblem`, `isPlaceholderEmail`, `placeholderEmail`, `defineRoles({ roles, defaultRole, adminPanel })` (`roleOf`, `canOpenAdmin`, `isRole`), the `AuthUser` type, `authErrorCode` with `ACCOUNT_NOT_LINKED`, `GOOGLE_ALREADY_LINKED` and `GOOGLE_EMAIL_NOT_CONFIRMED`, `avatarSrc` (https pictures only, sized) and `avatarInitials`. No dependencies.
|
|
118
|
+
|
|
119
|
+
#### `kit/auth/expo`: the mobile app
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
import * as SecureStore from 'expo-secure-store'
|
|
123
|
+
import * as Passkeys from 'react-native-passkeys'
|
|
124
|
+
import { createMobileAuth } from '@jgb-solutions/kit/auth/expo'
|
|
125
|
+
|
|
126
|
+
export const auth = createMobileAuth({ origin: 'https://app.example.com', storage: SecureStore, tokenKey: 'example.session', fetchMe })
|
|
127
|
+
|
|
128
|
+
const session = useSyncExternalStore(auth.subscribe, auth.getSession)
|
|
129
|
+
await auth.signIn('maria', password) // or an email address
|
|
130
|
+
await auth.signInWithGoogle(idToken) // from the app's Google Sign-In SDK
|
|
131
|
+
await auth.linkGoogle(idToken) // signed in: connect Google from the account screen
|
|
132
|
+
await auth.signInWithPasskey(Passkeys)
|
|
133
|
+
new RPCLink({ url, headers: auth.authHeaders }) // Bearer on every RPC call
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
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.
|
|
137
|
+
|
|
45
138
|
## What goes in, and what never goes in
|
|
46
139
|
|
|
47
140
|
**In:** generic plumbing that several apps need in the same shape, written once and tested: checking a signed token, parsing a header, a retry or rate-limit helper, a typed client for a public protocol. Every module:
|
|
@@ -58,13 +151,13 @@ Keep the app's own role check after this one: Access decides who may reach the a
|
|
|
58
151
|
- **Infrastructure details:** hosts, IP addresses, server names, internal URLs, deploy setup.
|
|
59
152
|
- **Personal data, or real addresses outside `example.com`.**
|
|
60
153
|
|
|
61
|
-
`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`,
|
|
154
|
+
`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/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.
|
|
62
155
|
|
|
63
156
|
## Developing
|
|
64
157
|
|
|
65
|
-
Bun only: `bun install`, `bun test`, `bun run typecheck` (`bun check`), `bun run format` (`bun fmt`), `bun run build` (one ESM file per export, plus `.d.ts` types), `bun run check:package`.
|
|
158
|
+
Bun only: `bun install`, `bun test`, `bun run typecheck` (`bun check`), `bun run format` (`bun fmt`), `bun run build` (one ESM file per export, plus `.d.ts` types), `bun run check:package`, `bun run check:install`.
|
|
66
159
|
|
|
67
|
-
A new module goes in `src/<name>.ts`
|
|
160
|
+
A new module goes in `src/<name>.ts` (or `src/<group>/<name>.ts`) with its test next to it. It gets its own subpath in `package.json`'s `exports` (`./<name>` pointing at `./dist/<name>.js` and `./dist/<name>.d.ts`), and its allowed imports in `IMPORTS` in `scripts/check-package.ts`. A library it needs is an optional peer dependency, unless every module needs it.
|
|
68
161
|
|
|
69
162
|
## Publishing
|
|
70
163
|
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Passwords hashed with Bun's built-in argon2id, for apps that run on Bun (not on Cloudflare Workers,
|
|
3
|
+
* which keep Better Auth's scrypt). A hash is only ever checked by the host that made it.
|
|
4
|
+
*
|
|
5
|
+
* import { argon2idHasher } from '@jgb-solutions/kit/auth/bun'
|
|
6
|
+
* standardAuthOptions({ …, password: argon2idHasher() })
|
|
7
|
+
*/
|
|
8
|
+
import type { PasswordHasher } from '../auth';
|
|
9
|
+
/**
|
|
10
|
+
* Bun.password with argon2id, Bun's default cost unless one is given. The settings are stored in each
|
|
11
|
+
* hash, so changing them never breaks existing passwords.
|
|
12
|
+
*
|
|
13
|
+
* An app moving to argon2id keeps its older hashes working with `fallbackVerify`: hashes that aren't
|
|
14
|
+
* argon2 are checked by it (Better Auth's scrypt: `verifyPassword` from `better-auth/crypto`), new
|
|
15
|
+
* passwords are argon2id.
|
|
16
|
+
*/
|
|
17
|
+
export declare function argon2idHasher(options?: {
|
|
18
|
+
memoryCost?: number;
|
|
19
|
+
timeCost?: number;
|
|
20
|
+
fallbackVerify?: (input: {
|
|
21
|
+
hash: string;
|
|
22
|
+
password: string;
|
|
23
|
+
}) => Promise<boolean>;
|
|
24
|
+
}): PasswordHasher;
|
package/dist/auth/bun.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// src/auth/bun.ts
|
|
2
|
+
function argon2idHasher(options = {}) {
|
|
3
|
+
const { fallbackVerify, ...cost } = options;
|
|
4
|
+
const algorithm = { algorithm: "argon2id", ...cost };
|
|
5
|
+
return {
|
|
6
|
+
hash: (password) => Bun.password.hash(password, algorithm),
|
|
7
|
+
verify: ({ hash, password }) => {
|
|
8
|
+
if (fallbackVerify && !hash.startsWith("$argon2"))
|
|
9
|
+
return fallbackVerify({ hash, password }).catch(() => false);
|
|
10
|
+
return Bun.password.verify(password, hash).catch(() => false);
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export {
|
|
15
|
+
argon2idHasher
|
|
16
|
+
};
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/** What the app passes as `storage`: `expo-secure-store` has exactly this shape. */
|
|
2
|
+
export type SecureStorage = {
|
|
3
|
+
getItemAsync(key: string): Promise<string | null>;
|
|
4
|
+
setItemAsync(key: string, value: string): Promise<void>;
|
|
5
|
+
deleteItemAsync(key: string): Promise<void>;
|
|
6
|
+
};
|
|
7
|
+
/** What the passkey calls need: `react-native-passkeys` has this shape (its methods take the options Better Auth sends). */
|
|
8
|
+
export type PasskeysModule = {
|
|
9
|
+
get(request: unknown): Promise<unknown>;
|
|
10
|
+
create(request: unknown): Promise<unknown>;
|
|
11
|
+
};
|
|
12
|
+
export type MobileSession<U> = {
|
|
13
|
+
status: 'loading';
|
|
14
|
+
} | {
|
|
15
|
+
status: 'out';
|
|
16
|
+
} | {
|
|
17
|
+
status: 'in';
|
|
18
|
+
user: U;
|
|
19
|
+
};
|
|
20
|
+
export type AuthResult = {
|
|
21
|
+
ok: true;
|
|
22
|
+
} | {
|
|
23
|
+
ok: false;
|
|
24
|
+
code: string;
|
|
25
|
+
};
|
|
26
|
+
export type MobileAuthConfig<U> = {
|
|
27
|
+
/** The website's origin, `https://…`: Better Auth checks sign-ins come from it. */
|
|
28
|
+
origin: string;
|
|
29
|
+
storage: SecureStorage;
|
|
30
|
+
/** Where the token is kept in secure storage. */
|
|
31
|
+
tokenKey: string;
|
|
32
|
+
/** The signed-in person, from the app's own RPC call; it throws `{ code: 'UNAUTHORIZED' }` for a dead token. */
|
|
33
|
+
fetchMe: () => Promise<U>;
|
|
34
|
+
/** Runs after each sign-in (`firstTime`) and each launch with a saved session: syncing what the phone holds. */
|
|
35
|
+
onSignedIn?: (firstTime: boolean) => Promise<void>;
|
|
36
|
+
/** For tests. */
|
|
37
|
+
fetch?: typeof fetch;
|
|
38
|
+
};
|
|
39
|
+
export declare function createMobileAuth<U>(config: MobileAuthConfig<U>): {
|
|
40
|
+
subscribe(listener: () => void): () => void;
|
|
41
|
+
getSession: () => MobileSession<U>;
|
|
42
|
+
authHeaders: () => Record<string, string>;
|
|
43
|
+
/** At launch: the saved token, checked with the server. A dead token is dropped; offline, the app shows signed out. */
|
|
44
|
+
restore(): Promise<void>;
|
|
45
|
+
/** A username or an email address, and the password. */
|
|
46
|
+
signIn(login: string, password: string): Promise<AuthResult>;
|
|
47
|
+
/** A new account. Without an email address, the placeholder the website uses (never shown or mailed). */
|
|
48
|
+
signUp(input: {
|
|
49
|
+
username: string;
|
|
50
|
+
password: string;
|
|
51
|
+
email?: string;
|
|
52
|
+
name?: string;
|
|
53
|
+
}): Promise<AuthResult>;
|
|
54
|
+
/**
|
|
55
|
+
* "Continue with Google" with the ID token from the app's Google Sign-In SDK. Better Auth checks it
|
|
56
|
+
* with Google (its audience must be one of GOOGLE_CLIENT_ID or GOOGLE_MOBILE_CLIENT_IDS) and signs
|
|
57
|
+
* in, links or creates the account by the server's rules.
|
|
58
|
+
*/
|
|
59
|
+
signInWithGoogle(idToken: string, options?: {
|
|
60
|
+
nonce?: string;
|
|
61
|
+
}): Promise<AuthResult>;
|
|
62
|
+
/**
|
|
63
|
+
* Connects Google to the signed-in account (its account page), with an ID token from the app's
|
|
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.
|
|
66
|
+
*/
|
|
67
|
+
linkGoogle(idToken: string, options?: {
|
|
68
|
+
nonce?: string;
|
|
69
|
+
}): Promise<AuthResult>;
|
|
70
|
+
/** Signs in with a passkey saved on the phone (or in the person's Google or Apple account). */
|
|
71
|
+
signInWithPasskey(passkeys: PasskeysModule): Promise<AuthResult>;
|
|
72
|
+
/** Adds a passkey to the signed-in account: the way back in if the password is forgotten. */
|
|
73
|
+
addPasskey(passkeys: PasskeysModule, name: string): Promise<AuthResult>;
|
|
74
|
+
/** Ends the session on the server too, then forgets it. */
|
|
75
|
+
signOut(): Promise<void>;
|
|
76
|
+
/** Forgets the session without calling the server: after the account was deleted. */
|
|
77
|
+
forget: () => Promise<void>;
|
|
78
|
+
};
|
|
79
|
+
export type MobileAuth<U> = ReturnType<typeof createMobileAuth<U>>;
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
// src/auth/rules.ts
|
|
2
|
+
var USERNAME = { min: 3, max: 30, pattern: /^[a-z0-9_.]+$/ };
|
|
3
|
+
var PASSWORD = { min: 12, max: 128 };
|
|
4
|
+
function usernameProblem(username) {
|
|
5
|
+
if (username.length < USERNAME.min)
|
|
6
|
+
return "too-short";
|
|
7
|
+
if (username.length > USERNAME.max)
|
|
8
|
+
return "too-long";
|
|
9
|
+
if (!USERNAME.pattern.test(username))
|
|
10
|
+
return "characters";
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
var PLACEHOLDER_EMAIL_DOMAIN = "users.invalid";
|
|
14
|
+
function isPlaceholderEmail(email) {
|
|
15
|
+
return email.toLowerCase().endsWith(`@${PLACEHOLDER_EMAIL_DOMAIN}`);
|
|
16
|
+
}
|
|
17
|
+
function placeholderEmail() {
|
|
18
|
+
return `${crypto.randomUUID().replaceAll("-", "")}@${PLACEHOLDER_EMAIL_DOMAIN}`;
|
|
19
|
+
}
|
|
20
|
+
function usernameFromName(name, email, fallback) {
|
|
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, "");
|
|
22
|
+
for (const source of [name ?? "", (email ?? "").split("@")[0] ?? ""]) {
|
|
23
|
+
const base = clean(source);
|
|
24
|
+
if (base.length >= USERNAME.min)
|
|
25
|
+
return base;
|
|
26
|
+
}
|
|
27
|
+
return clean(fallback) || "member";
|
|
28
|
+
}
|
|
29
|
+
function usernameCandidates(base, random = Math.random) {
|
|
30
|
+
const numbered = Array.from({ length: 8 }, () => `${base}${Math.floor(1000 + random() * 9000)}`);
|
|
31
|
+
return [base, ...numbered];
|
|
32
|
+
}
|
|
33
|
+
function defineRoles(config) {
|
|
34
|
+
const known = config.roles;
|
|
35
|
+
const panel = config.adminPanel;
|
|
36
|
+
const isRole = (value) => typeof value === "string" && known.includes(value);
|
|
37
|
+
const split = (stored) => (stored ?? "").split(",").map((role) => role.trim());
|
|
38
|
+
return {
|
|
39
|
+
ROLES: config.roles,
|
|
40
|
+
DEFAULT_ROLE: config.defaultRole,
|
|
41
|
+
ADMIN_PANEL_ROLES: config.adminPanel,
|
|
42
|
+
isRole,
|
|
43
|
+
roleOf(stored) {
|
|
44
|
+
const roles = split(stored).filter(isRole);
|
|
45
|
+
return roles.find((role) => panel.includes(role)) ?? roles[0] ?? config.defaultRole;
|
|
46
|
+
},
|
|
47
|
+
canOpenAdmin(stored) {
|
|
48
|
+
return split(stored).some((role) => panel.includes(role));
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function avatarSrc(image, px) {
|
|
53
|
+
if (!image)
|
|
54
|
+
return "";
|
|
55
|
+
try {
|
|
56
|
+
const url = new URL(image);
|
|
57
|
+
if (url.protocol !== "https:")
|
|
58
|
+
return "";
|
|
59
|
+
if (url.hostname.endsWith(".googleusercontent.com"))
|
|
60
|
+
return `${url.origin}${url.pathname.replace(/=[^/]*$/, "")}=s${px * 2}-c`;
|
|
61
|
+
return url.href;
|
|
62
|
+
} catch {
|
|
63
|
+
return "";
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function avatarInitials(user) {
|
|
67
|
+
const words = (user.name.trim() || user.username).replace(/[_.-]+/g, " ").split(/\s+/).filter(Boolean);
|
|
68
|
+
const letters = words.length > 1 ? [words[0], words[words.length - 1]] : [words[0]];
|
|
69
|
+
return letters.map((word) => [...word ?? ""][0] ?? "").join("").toUpperCase();
|
|
70
|
+
}
|
|
71
|
+
var ACCOUNT_NOT_LINKED = "ACCOUNT_NOT_LINKED";
|
|
72
|
+
var GOOGLE_ALREADY_LINKED = "GOOGLE_ALREADY_LINKED";
|
|
73
|
+
var GOOGLE_EMAIL_NOT_CONFIRMED = "GOOGLE_EMAIL_NOT_CONFIRMED";
|
|
74
|
+
function authErrorCode(answer) {
|
|
75
|
+
const code = typeof answer === "string" ? answer : answer && typeof answer === "object" && ("code" in answer) ? String(answer.code) : "";
|
|
76
|
+
const message = answer && typeof answer === "object" && "message" in answer ? String(answer.message) : "";
|
|
77
|
+
if (code === "account_not_linked" || code === "OAUTH_LINK_ERROR" && message === "account not linked")
|
|
78
|
+
return ACCOUNT_NOT_LINKED;
|
|
79
|
+
if (code === "SOCIAL_ACCOUNT_ALREADY_LINKED" || code === "account_already_linked_to_different_user")
|
|
80
|
+
return GOOGLE_ALREADY_LINKED;
|
|
81
|
+
if (code === "LINKING_NOT_ALLOWED" || code === "email_not_verified" || code === "EMAIL_NOT_VERIFIED")
|
|
82
|
+
return GOOGLE_EMAIL_NOT_CONFIRMED;
|
|
83
|
+
return code;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// src/auth/expo.ts
|
|
87
|
+
function codeOf(body, fallback) {
|
|
88
|
+
return authErrorCode(body) || fallback;
|
|
89
|
+
}
|
|
90
|
+
function isUnauthorized(error) {
|
|
91
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === "UNAUTHORIZED";
|
|
92
|
+
}
|
|
93
|
+
function createMobileAuth(config) {
|
|
94
|
+
const doFetch = config.fetch ?? fetch;
|
|
95
|
+
let token = null;
|
|
96
|
+
let session = { status: "loading" };
|
|
97
|
+
const listeners = new Set;
|
|
98
|
+
function set(next) {
|
|
99
|
+
session = next;
|
|
100
|
+
for (const listener of listeners)
|
|
101
|
+
listener();
|
|
102
|
+
}
|
|
103
|
+
async function forget() {
|
|
104
|
+
token = null;
|
|
105
|
+
await config.storage.deleteItemAsync(config.tokenKey).catch(() => {});
|
|
106
|
+
set({ status: "out" });
|
|
107
|
+
}
|
|
108
|
+
function authHeaders() {
|
|
109
|
+
return token ? { authorization: `Bearer ${token}` } : {};
|
|
110
|
+
}
|
|
111
|
+
async function call(path, init = {}) {
|
|
112
|
+
const response = await doFetch(`${config.origin}/api/auth${path}`, {
|
|
113
|
+
method: init.method ?? "GET",
|
|
114
|
+
credentials: "include",
|
|
115
|
+
headers: { "content-type": "application/json", origin: config.origin, ...authHeaders() },
|
|
116
|
+
...init.body === undefined ? {} : { body: JSON.stringify(init.body) }
|
|
117
|
+
});
|
|
118
|
+
return { response, body: await response.json().catch(() => null) };
|
|
119
|
+
}
|
|
120
|
+
async function start(newToken, firstTime) {
|
|
121
|
+
token = newToken;
|
|
122
|
+
await config.storage.setItemAsync(config.tokenKey, newToken);
|
|
123
|
+
try {
|
|
124
|
+
set({ status: "in", user: await config.fetchMe() });
|
|
125
|
+
} catch {
|
|
126
|
+
await forget();
|
|
127
|
+
return { ok: false, code: "NO_SESSION" };
|
|
128
|
+
}
|
|
129
|
+
await config.onSignedIn?.(firstTime).catch(() => {});
|
|
130
|
+
return { ok: true };
|
|
131
|
+
}
|
|
132
|
+
async function signInWith(path, body) {
|
|
133
|
+
try {
|
|
134
|
+
const { response, body: answer } = await call(path, { method: "POST", body });
|
|
135
|
+
if (response.status === 429)
|
|
136
|
+
return { ok: false, code: "TOO_MANY_REQUESTS" };
|
|
137
|
+
const newToken = response.headers.get("set-auth-token");
|
|
138
|
+
if (response.ok && newToken)
|
|
139
|
+
return start(newToken, true);
|
|
140
|
+
return { ok: false, code: codeOf(answer, response.ok ? "NO_TOKEN" : String(response.status)) };
|
|
141
|
+
} catch {
|
|
142
|
+
return { ok: false, code: "NETWORK" };
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
subscribe(listener) {
|
|
147
|
+
listeners.add(listener);
|
|
148
|
+
return () => listeners.delete(listener);
|
|
149
|
+
},
|
|
150
|
+
getSession: () => session,
|
|
151
|
+
authHeaders,
|
|
152
|
+
async restore() {
|
|
153
|
+
token = await config.storage.getItemAsync(config.tokenKey).catch(() => null);
|
|
154
|
+
if (!token)
|
|
155
|
+
return set({ status: "out" });
|
|
156
|
+
try {
|
|
157
|
+
set({ status: "in", user: await config.fetchMe() });
|
|
158
|
+
config.onSignedIn?.(false).catch(() => {});
|
|
159
|
+
} catch (error) {
|
|
160
|
+
if (isUnauthorized(error))
|
|
161
|
+
return forget();
|
|
162
|
+
set({ status: "out" });
|
|
163
|
+
}
|
|
164
|
+
},
|
|
165
|
+
signIn(login, password) {
|
|
166
|
+
const value = login.trim().toLowerCase();
|
|
167
|
+
if (!value || !password)
|
|
168
|
+
return Promise.resolve({ ok: false, code: "MISSING_FIELDS" });
|
|
169
|
+
if (value.includes("@") && isPlaceholderEmail(value))
|
|
170
|
+
return Promise.resolve({ ok: false, code: "INVALID_EMAIL_OR_PASSWORD" });
|
|
171
|
+
return value.includes("@") ? signInWith("/sign-in/email", { email: value, password }) : signInWith("/sign-in/username", { username: value, password });
|
|
172
|
+
},
|
|
173
|
+
signUp(input) {
|
|
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
|
+
});
|
|
181
|
+
},
|
|
182
|
+
signInWithGoogle(idToken, options = {}) {
|
|
183
|
+
return signInWith("/sign-in/social", {
|
|
184
|
+
provider: "google",
|
|
185
|
+
disableRedirect: true,
|
|
186
|
+
idToken: { token: idToken, ...options.nonce ? { nonce: options.nonce } : {} }
|
|
187
|
+
});
|
|
188
|
+
},
|
|
189
|
+
async linkGoogle(idToken, options = {}) {
|
|
190
|
+
if (!token)
|
|
191
|
+
return { ok: false, code: "NO_SESSION" };
|
|
192
|
+
try {
|
|
193
|
+
const { response, body } = await call("/link-social", {
|
|
194
|
+
method: "POST",
|
|
195
|
+
body: {
|
|
196
|
+
provider: "google",
|
|
197
|
+
disableRedirect: true,
|
|
198
|
+
idToken: { token: idToken, ...options.nonce ? { nonce: options.nonce } : {} }
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
if (response.status === 429)
|
|
202
|
+
return { ok: false, code: "TOO_MANY_REQUESTS" };
|
|
203
|
+
return response.ok ? { ok: true } : { ok: false, code: codeOf(body, String(response.status)) };
|
|
204
|
+
} catch {
|
|
205
|
+
return { ok: false, code: "NETWORK" };
|
|
206
|
+
}
|
|
207
|
+
},
|
|
208
|
+
async signInWithPasskey(passkeys) {
|
|
209
|
+
try {
|
|
210
|
+
const options = await call("/passkey/generate-authenticate-options");
|
|
211
|
+
if (!options.response.ok)
|
|
212
|
+
return { ok: false, code: codeOf(options.body, String(options.response.status)) };
|
|
213
|
+
const assertion = await passkeys.get(options.body);
|
|
214
|
+
if (!assertion)
|
|
215
|
+
return { ok: false, code: "CANCELLED" };
|
|
216
|
+
return signInWith("/passkey/verify-authentication", { response: assertion });
|
|
217
|
+
} catch {
|
|
218
|
+
return { ok: false, code: "CANCELLED" };
|
|
219
|
+
}
|
|
220
|
+
},
|
|
221
|
+
async addPasskey(passkeys, name) {
|
|
222
|
+
try {
|
|
223
|
+
const options = await call("/passkey/generate-register-options");
|
|
224
|
+
if (!options.response.ok)
|
|
225
|
+
return { ok: false, code: codeOf(options.body, String(options.response.status)) };
|
|
226
|
+
const credential = await passkeys.create(options.body);
|
|
227
|
+
if (!credential)
|
|
228
|
+
return { ok: false, code: "CANCELLED" };
|
|
229
|
+
const verified = await call("/passkey/verify-registration", { method: "POST", body: { response: credential, name } });
|
|
230
|
+
return verified.response.ok ? { ok: true } : { ok: false, code: codeOf(verified.body, String(verified.response.status)) };
|
|
231
|
+
} catch {
|
|
232
|
+
return { ok: false, code: "CANCELLED" };
|
|
233
|
+
}
|
|
234
|
+
},
|
|
235
|
+
async signOut() {
|
|
236
|
+
if (token)
|
|
237
|
+
await call("/sign-out", { method: "POST" }).catch(() => {});
|
|
238
|
+
await forget();
|
|
239
|
+
},
|
|
240
|
+
forget
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
export {
|
|
244
|
+
createMobileAuth
|
|
245
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** oRPC's ResponseHeadersHandlerPlugin context, when the app uses it. */
|
|
2
|
+
type HeadersContext = {
|
|
3
|
+
resHeaders?: Headers;
|
|
4
|
+
};
|
|
5
|
+
export declare function authMiddleware<U extends {
|
|
6
|
+
role: string;
|
|
7
|
+
}>(options: {
|
|
8
|
+
/** The signed-in person, or null: the app's own session read (cookie or Bearer token). */
|
|
9
|
+
viewer: () => Promise<U | null>;
|
|
10
|
+
/** Whether a role may open the admin panel. */
|
|
11
|
+
canOpenAdmin: (role: string) => boolean;
|
|
12
|
+
/** An extra check for admin procedures, such as Cloudflare Access's token. False means FORBIDDEN. */
|
|
13
|
+
adminCheck?: () => Promise<boolean>;
|
|
14
|
+
}): {
|
|
15
|
+
withUser: import("@orpc/server").DecoratedMiddleware<HeadersContext & object, {
|
|
16
|
+
user: U | null;
|
|
17
|
+
}, unknown, any, {}>;
|
|
18
|
+
requireUser: import("@orpc/server").DecoratedMiddleware<HeadersContext & {
|
|
19
|
+
user: U | null;
|
|
20
|
+
} & object, {
|
|
21
|
+
user: U;
|
|
22
|
+
}, unknown, any, {}>;
|
|
23
|
+
requireAdmin: import("@orpc/server").DecoratedMiddleware<HeadersContext & {
|
|
24
|
+
user: U | null;
|
|
25
|
+
} & object, {
|
|
26
|
+
user: U;
|
|
27
|
+
}, unknown, any, {}>;
|
|
28
|
+
};
|
|
29
|
+
export {};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// src/auth/orpc.ts
|
|
2
|
+
import { ORPCError, os } from "@orpc/server";
|
|
3
|
+
function authMiddleware(options) {
|
|
4
|
+
const withUser = os.$context().middleware(async ({ next }) => next({ context: { user: await options.viewer() } }));
|
|
5
|
+
const requireUser = os.$context().middleware(async ({ context, next }) => {
|
|
6
|
+
if (!context.user)
|
|
7
|
+
throw new ORPCError("UNAUTHORIZED");
|
|
8
|
+
context.resHeaders?.set("cache-control", "private, no-store");
|
|
9
|
+
return next({ context: { user: context.user } });
|
|
10
|
+
});
|
|
11
|
+
const requireAdmin = os.$context().middleware(async ({ context, next }) => {
|
|
12
|
+
if (!context.user)
|
|
13
|
+
throw new ORPCError("UNAUTHORIZED");
|
|
14
|
+
if (!options.canOpenAdmin(context.user.role))
|
|
15
|
+
throw new ORPCError("FORBIDDEN");
|
|
16
|
+
if (options.adminCheck && !await options.adminCheck())
|
|
17
|
+
throw new ORPCError("FORBIDDEN");
|
|
18
|
+
context.resHeaders?.set("cache-control", "private, no-store");
|
|
19
|
+
return next({ context: { user: context.user } });
|
|
20
|
+
});
|
|
21
|
+
return { withUser, requireUser, requireAdmin };
|
|
22
|
+
}
|
|
23
|
+
export {
|
|
24
|
+
authMiddleware
|
|
25
|
+
};
|