@jgb-solutions/kit 0.4.4 → 0.5.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 +10 -0
- package/README.md +33 -3
- package/dist/auth/bun.d.ts +11 -0
- package/dist/auth/bun.js +27 -4
- package/dist/auth/cache.d.ts +45 -0
- package/dist/auth/cache.js +43 -0
- package/dist/auth/expo.js +46 -0
- package/dist/auth/redis.d.ts +34 -0
- package/dist/auth/redis.js +26 -0
- package/dist/auth/rules.d.ts +30 -0
- package/dist/auth/rules.js +52 -0
- package/dist/auth/server.d.ts +293 -0
- package/dist/auth/server.js +582 -0
- package/dist/auth.js +46 -0
- package/package.json +13 -1
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
// src/auth/server.ts
|
|
2
|
+
import { APIError } from "better-auth/api";
|
|
3
|
+
|
|
4
|
+
// src/auth.ts
|
|
5
|
+
import { passkey } from "@better-auth/passkey";
|
|
6
|
+
import { createAuthMiddleware } from "better-auth/api";
|
|
7
|
+
import { admin } from "better-auth/plugins/admin";
|
|
8
|
+
import { bearer } from "better-auth/plugins/bearer";
|
|
9
|
+
import { username } from "better-auth/plugins/username";
|
|
10
|
+
|
|
11
|
+
// src/auth/rules.ts
|
|
12
|
+
var USERNAME = { min: 3, max: 30, pattern: /^[a-z0-9_.]+$/ };
|
|
13
|
+
var PASSWORD = { min: 12, max: 128 };
|
|
14
|
+
function usernameProblem(username) {
|
|
15
|
+
if (username.length < USERNAME.min)
|
|
16
|
+
return "too-short";
|
|
17
|
+
if (username.length > USERNAME.max)
|
|
18
|
+
return "too-long";
|
|
19
|
+
if (!USERNAME.pattern.test(username))
|
|
20
|
+
return "characters";
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
var PLACEHOLDER_EMAIL_DOMAIN = "users.invalid";
|
|
24
|
+
function isPlaceholderEmail(email) {
|
|
25
|
+
return email.toLowerCase().endsWith(`@${PLACEHOLDER_EMAIL_DOMAIN}`);
|
|
26
|
+
}
|
|
27
|
+
function placeholderEmail(randomId = () => globalThis.crypto.randomUUID()) {
|
|
28
|
+
return `${randomId().replaceAll("-", "")}@${PLACEHOLDER_EMAIL_DOMAIN}`;
|
|
29
|
+
}
|
|
30
|
+
function usernameFromName(name, email, fallback) {
|
|
31
|
+
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, "");
|
|
32
|
+
for (const source of [name ?? "", (email ?? "").split("@")[0] ?? ""]) {
|
|
33
|
+
const base = clean(source);
|
|
34
|
+
if (base.length >= USERNAME.min)
|
|
35
|
+
return base;
|
|
36
|
+
}
|
|
37
|
+
return clean(fallback) || "member";
|
|
38
|
+
}
|
|
39
|
+
function usernameCandidates(base, random = Math.random) {
|
|
40
|
+
const numbered = Array.from({ length: 8 }, () => `${base}${Math.floor(1000 + random() * 9000)}`);
|
|
41
|
+
return [base, ...numbered];
|
|
42
|
+
}
|
|
43
|
+
function defineRoles(config) {
|
|
44
|
+
const known = config.roles;
|
|
45
|
+
const panel = config.adminPanel;
|
|
46
|
+
const isRole = (value) => typeof value === "string" && known.includes(value);
|
|
47
|
+
const split = (stored) => (stored ?? "").split(",").map((role) => role.trim());
|
|
48
|
+
return {
|
|
49
|
+
ROLES: config.roles,
|
|
50
|
+
DEFAULT_ROLE: config.defaultRole,
|
|
51
|
+
ADMIN_PANEL_ROLES: config.adminPanel,
|
|
52
|
+
isRole,
|
|
53
|
+
roleOf(stored) {
|
|
54
|
+
const roles = split(stored).filter(isRole);
|
|
55
|
+
return roles.find((role) => panel.includes(role)) ?? roles[0] ?? config.defaultRole;
|
|
56
|
+
},
|
|
57
|
+
canOpenAdmin(stored) {
|
|
58
|
+
return split(stored).some((role) => panel.includes(role));
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function avatarSrc(image, px) {
|
|
63
|
+
if (!image)
|
|
64
|
+
return "";
|
|
65
|
+
try {
|
|
66
|
+
const url = new URL(image);
|
|
67
|
+
if (url.protocol !== "https:")
|
|
68
|
+
return "";
|
|
69
|
+
if (url.hostname.endsWith(".googleusercontent.com"))
|
|
70
|
+
return `${url.origin}${url.pathname.replace(/=[^/]*$/, "")}=s${px * 2}-c`;
|
|
71
|
+
return url.href;
|
|
72
|
+
} catch {
|
|
73
|
+
return "";
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function avatarInitials(user) {
|
|
77
|
+
const words = (user.name.trim() || user.username).replace(/[_.-]+/g, " ").split(/\s+/).filter(Boolean);
|
|
78
|
+
const letters = words.length > 1 ? [words[0], words[words.length - 1]] : [words[0]];
|
|
79
|
+
return letters.map((word) => [...word ?? ""][0] ?? "").join("").toUpperCase();
|
|
80
|
+
}
|
|
81
|
+
var ACCOUNT_NOT_LINKED = "ACCOUNT_NOT_LINKED";
|
|
82
|
+
var GOOGLE_ALREADY_LINKED = "GOOGLE_ALREADY_LINKED";
|
|
83
|
+
var GOOGLE_EMAIL_NOT_CONFIRMED = "GOOGLE_EMAIL_NOT_CONFIRMED";
|
|
84
|
+
function authErrorCode(answer) {
|
|
85
|
+
const code = typeof answer === "string" ? answer : answer && typeof answer === "object" && ("code" in answer) ? String(answer.code) : "";
|
|
86
|
+
const message = answer && typeof answer === "object" && "message" in answer ? String(answer.message) : "";
|
|
87
|
+
if (code === "account_not_linked" || code === "OAUTH_LINK_ERROR" && message === "account not linked")
|
|
88
|
+
return ACCOUNT_NOT_LINKED;
|
|
89
|
+
if (code === "SOCIAL_ACCOUNT_ALREADY_LINKED" || code === "account_already_linked_to_different_user")
|
|
90
|
+
return GOOGLE_ALREADY_LINKED;
|
|
91
|
+
if (code === "LINKING_NOT_ALLOWED" || code === "email_not_verified" || code === "EMAIL_NOT_VERIFIED")
|
|
92
|
+
return GOOGLE_EMAIL_NOT_CONFIRMED;
|
|
93
|
+
return code;
|
|
94
|
+
}
|
|
95
|
+
var USERNAME_ERROR_CODES = {
|
|
96
|
+
"too-short": "USERNAME_TOO_SHORT",
|
|
97
|
+
"too-long": "USERNAME_TOO_LONG",
|
|
98
|
+
characters: "INVALID_USERNAME"
|
|
99
|
+
};
|
|
100
|
+
function usernameErrorCode(username) {
|
|
101
|
+
const problem = usernameProblem(username);
|
|
102
|
+
return problem ? USERNAME_ERROR_CODES[problem] : null;
|
|
103
|
+
}
|
|
104
|
+
var NAME_UNSAFE = /[\u0000-\u001f\u007f<>]/;
|
|
105
|
+
function displayNameProblem(name, max = 50) {
|
|
106
|
+
const trimmed = name.trim();
|
|
107
|
+
if (!trimmed)
|
|
108
|
+
return "empty";
|
|
109
|
+
if ([...trimmed].length > max)
|
|
110
|
+
return "too-long";
|
|
111
|
+
if (NAME_UNSAFE.test(trimmed))
|
|
112
|
+
return "characters";
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
function defineSignInReasons(reasons) {
|
|
116
|
+
return {
|
|
117
|
+
REASONS: reasons,
|
|
118
|
+
reasonOf(value) {
|
|
119
|
+
return reasons.find((reason) => reason === value);
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
var REDIRECT_UNSAFE = /[\u0000-\u001f\u007f\\]/;
|
|
124
|
+
function isSafeRedirectPath(path) {
|
|
125
|
+
if (path.length > 500 || !path.startsWith("/") || path.startsWith("//") || REDIRECT_UNSAFE.test(path))
|
|
126
|
+
return false;
|
|
127
|
+
let decoded;
|
|
128
|
+
try {
|
|
129
|
+
decoded = decodeURIComponent(path);
|
|
130
|
+
} catch {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
if (REDIRECT_UNSAFE.test(decoded) || decoded.startsWith("//"))
|
|
134
|
+
return false;
|
|
135
|
+
const base = "https://this-site.invalid";
|
|
136
|
+
return new URL(path, base).origin === base;
|
|
137
|
+
}
|
|
138
|
+
function safeRedirect(value) {
|
|
139
|
+
return typeof value === "string" && isSafeRedirectPath(value) ? value : undefined;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// src/auth.ts
|
|
143
|
+
var E2E_SECRET = "e2e-only-secret-never-used-in-production-0000";
|
|
144
|
+
function authSettings(env) {
|
|
145
|
+
const e2e = env.E2E === "1";
|
|
146
|
+
const loopback = ["127.0.0.1", "::1", "localhost"].includes((env.HOST ?? "").trim().toLowerCase());
|
|
147
|
+
if (e2e && env.NODE_ENV === "production" && !loopback)
|
|
148
|
+
throw new Error("E2E=1 is set on a production server that listens beyond this machine: remove it.");
|
|
149
|
+
const secret = env.BETTER_AUTH_SECRET || (e2e ? E2E_SECRET : "");
|
|
150
|
+
if (!secret)
|
|
151
|
+
throw new Error("BETTER_AUTH_SECRET is not set.");
|
|
152
|
+
const list = (value) => (value ?? "").split(",").map((item) => item.trim()).filter(Boolean);
|
|
153
|
+
const web = env.GOOGLE_CLIENT_ID?.trim();
|
|
154
|
+
const clientSecret = env.GOOGLE_CLIENT_SECRET?.trim();
|
|
155
|
+
return {
|
|
156
|
+
secret,
|
|
157
|
+
signUp: env.SIGN_UP !== "off",
|
|
158
|
+
rateLimit: !e2e,
|
|
159
|
+
adminEmails: list(env.ADMIN_EMAILS).map((email) => email.toLowerCase()),
|
|
160
|
+
google: web && clientSecret ? { clientId: [web, ...list(env.GOOGLE_MOBILE_CLIENT_IDS)], clientSecret } : null
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function roleForNewUser(user, adminEmails, defaultRole, adminRole) {
|
|
164
|
+
return user.emailVerified === true && adminEmails.includes(user.email.trim().toLowerCase()) ? adminRole : defaultRole;
|
|
165
|
+
}
|
|
166
|
+
function trustedBaseUrl(siteUrl, localHosts = ["localhost:*", "127.0.0.1:*"]) {
|
|
167
|
+
return { allowedHosts: [new URL(siteUrl).host, ...localHosts], protocol: "auto", fallback: siteUrl };
|
|
168
|
+
}
|
|
169
|
+
function androidOrigin(sha256) {
|
|
170
|
+
const bytes = sha256.split(":").map((pair) => String.fromCharCode(Number.parseInt(pair, 16))).join("");
|
|
171
|
+
return `android:apk-key-hash:${btoa(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`;
|
|
172
|
+
}
|
|
173
|
+
function assetLinks(packageName, sha256Fingerprints) {
|
|
174
|
+
return [
|
|
175
|
+
{
|
|
176
|
+
relation: ["delegate_permission/common.handle_all_urls", "delegate_permission/common.get_login_creds"],
|
|
177
|
+
target: { namespace: "android_app", package_name: packageName, sha256_cert_fingerprints: [...sha256Fingerprints] }
|
|
178
|
+
}
|
|
179
|
+
];
|
|
180
|
+
}
|
|
181
|
+
function passkeyOrigins(siteUrl, options = {}) {
|
|
182
|
+
return [new URL(siteUrl).origin, ...options.local ?? [], ...(options.androidCertSha256 ?? []).map(androidOrigin)];
|
|
183
|
+
}
|
|
184
|
+
var RATE_LIMIT_RULES = {
|
|
185
|
+
"/sign-in/email": { window: 60, max: 10 },
|
|
186
|
+
"/sign-in/username": { window: 60, max: 10 },
|
|
187
|
+
"/sign-up/email": { window: 60 * 60, max: 5 },
|
|
188
|
+
"/sign-in/social": { window: 60, max: 10 },
|
|
189
|
+
"/callback/*": { window: 60, max: 10 },
|
|
190
|
+
"/passkey/*": { window: 60, max: 20 },
|
|
191
|
+
"/change-password": { window: 60, max: 5 },
|
|
192
|
+
"/set-password": { window: 60, max: 5 },
|
|
193
|
+
"/delete-user": { window: 60, max: 5 }
|
|
194
|
+
};
|
|
195
|
+
function counterRateLimit(store, now = Date.now) {
|
|
196
|
+
return {
|
|
197
|
+
async consume(key, rule) {
|
|
198
|
+
const windowMs = rule.window * 1000;
|
|
199
|
+
const slot = Math.floor(now() / windowMs);
|
|
200
|
+
let count;
|
|
201
|
+
try {
|
|
202
|
+
count = await store().incr(`auth-limit:${key}:${slot}`, rule.window);
|
|
203
|
+
} catch (error) {
|
|
204
|
+
console.warn("auth rate limit: store unavailable, letting the attempt through", error);
|
|
205
|
+
return { allowed: true, retryAfter: null };
|
|
206
|
+
}
|
|
207
|
+
if (count <= rule.max)
|
|
208
|
+
return { allowed: true, retryAfter: null };
|
|
209
|
+
return { allowed: false, retryAfter: Math.max(1, Math.ceil(((slot + 1) * windowMs - now()) / 1000)) };
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
var CONFIRMED_ACCOUNT_LINKING = {
|
|
214
|
+
enabled: true,
|
|
215
|
+
trustedProviders: [],
|
|
216
|
+
requireLocalEmailVerified: true,
|
|
217
|
+
allowDifferentEmails: true,
|
|
218
|
+
updateUserInfoOnLink: false
|
|
219
|
+
};
|
|
220
|
+
function googleProvider(google, options) {
|
|
221
|
+
return {
|
|
222
|
+
clientId: google.clientId,
|
|
223
|
+
clientSecret: google.clientSecret,
|
|
224
|
+
disableImplicitSignUp: !options.signUp,
|
|
225
|
+
prompt: "select_account"
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
async function freeUsername(name, email, taken, fallback) {
|
|
229
|
+
const base = usernameFromName(name, email, fallback);
|
|
230
|
+
for (let round = 0;round < 3; round++) {
|
|
231
|
+
const candidates = usernameCandidates(base).slice(round === 0 ? 0 : 1);
|
|
232
|
+
const used = await taken(candidates);
|
|
233
|
+
const free = candidates.find((candidate) => !used.has(candidate));
|
|
234
|
+
if (free)
|
|
235
|
+
return free;
|
|
236
|
+
}
|
|
237
|
+
return `${base.slice(0, USERNAME.max - 13)}${crypto.randomUUID().replaceAll("-", "").slice(0, 12)}`;
|
|
238
|
+
}
|
|
239
|
+
function pictureFromIdToken(idToken) {
|
|
240
|
+
const payload = idToken?.split(".")[1];
|
|
241
|
+
if (!payload)
|
|
242
|
+
return null;
|
|
243
|
+
try {
|
|
244
|
+
const claims = JSON.parse(atob(payload.replaceAll("-", "+").replaceAll("_", "/")));
|
|
245
|
+
const picture = claims && typeof claims === "object" && "picture" in claims ? claims.picture : null;
|
|
246
|
+
return typeof picture === "string" && picture.startsWith("https://") && picture.length <= 2000 ? picture : null;
|
|
247
|
+
} catch {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
async function afterAccountSaved(account, adapter, signedInUserId) {
|
|
252
|
+
if (account.providerId !== "google")
|
|
253
|
+
return false;
|
|
254
|
+
const accounts = await adapter.findAccounts(account.userId);
|
|
255
|
+
if (!accounts.some((other) => other.providerId !== "google"))
|
|
256
|
+
return false;
|
|
257
|
+
if (signedInUserId !== account.userId)
|
|
258
|
+
await adapter.deleteUserSessions(account.userId);
|
|
259
|
+
const picture = pictureFromIdToken(account.idToken);
|
|
260
|
+
if (picture) {
|
|
261
|
+
const user = await adapter.findUserById(account.userId);
|
|
262
|
+
if (user && !user.image)
|
|
263
|
+
await adapter.updateUser(account.userId, { image: picture });
|
|
264
|
+
}
|
|
265
|
+
return true;
|
|
266
|
+
}
|
|
267
|
+
async function signedInUserId(ctx) {
|
|
268
|
+
if (ctx.context.session)
|
|
269
|
+
return ctx.context.session.user.id;
|
|
270
|
+
const token = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret).catch(() => null);
|
|
271
|
+
if (typeof token !== "string" || !token)
|
|
272
|
+
return null;
|
|
273
|
+
const found = await ctx.context.internalAdapter.findSession(token).catch(() => null);
|
|
274
|
+
return found?.user.id ?? null;
|
|
275
|
+
}
|
|
276
|
+
function signedInFlagHook(name, maxAgeSeconds = 365 * 24 * 60 * 60) {
|
|
277
|
+
return createAuthMiddleware(async (ctx) => {
|
|
278
|
+
const options = { path: "/", sameSite: "lax", secure: ctx.context.authCookies.sessionToken.attributes.secure === true };
|
|
279
|
+
if (ctx.context.newSession)
|
|
280
|
+
ctx.setCookie(name, "1", { ...options, maxAge: maxAgeSeconds });
|
|
281
|
+
else if (ctx.path === "/sign-out" || ctx.path === "/delete-user")
|
|
282
|
+
ctx.setCookie(name, "", { ...options, maxAge: 0 });
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
function asPublicRequest(request, siteUrl) {
|
|
286
|
+
const url = new URL(request.url);
|
|
287
|
+
const site = new URL(siteUrl);
|
|
288
|
+
if (url.host !== site.host || url.protocol === site.protocol)
|
|
289
|
+
return request;
|
|
290
|
+
url.protocol = site.protocol;
|
|
291
|
+
return new Request(url, request);
|
|
292
|
+
}
|
|
293
|
+
function createdIso(value) {
|
|
294
|
+
if (value === null || value === undefined)
|
|
295
|
+
return null;
|
|
296
|
+
const date = value instanceof Date ? value : new Date(value);
|
|
297
|
+
return Number.isNaN(date.getTime()) ? null : date.toISOString();
|
|
298
|
+
}
|
|
299
|
+
function toAuthUser(user, roleOf) {
|
|
300
|
+
if (!user || user.banned)
|
|
301
|
+
return null;
|
|
302
|
+
return {
|
|
303
|
+
id: user.id,
|
|
304
|
+
username: user.displayUsername || user.username || user.name,
|
|
305
|
+
name: user.name,
|
|
306
|
+
email: isPlaceholderEmail(user.email) ? null : user.email,
|
|
307
|
+
image: user.image ?? null,
|
|
308
|
+
role: roleOf(user.role),
|
|
309
|
+
...withCreatedAt(createdIso(user.createdAt))
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
var withCreatedAt = (createdAt) => createdAt ? { createdAt } : {};
|
|
313
|
+
function standardAuthOptions(input) {
|
|
314
|
+
const { settings } = input;
|
|
315
|
+
const fromRequest = input.passkeyOrigin === "request";
|
|
316
|
+
if (fromRequest && (input.androidCertSha256?.length || input.localOrigins?.length))
|
|
317
|
+
throw new Error("passkeyOrigin 'request' can't take androidCertSha256 or localOrigins: use 'listed'.");
|
|
318
|
+
const days = input.sessionDays ?? 30;
|
|
319
|
+
return {
|
|
320
|
+
appName: input.appName,
|
|
321
|
+
baseURL: trustedBaseUrl(input.siteUrl),
|
|
322
|
+
secret: settings.secret,
|
|
323
|
+
database: input.database,
|
|
324
|
+
emailAndPassword: {
|
|
325
|
+
enabled: true,
|
|
326
|
+
disableSignUp: !settings.signUp,
|
|
327
|
+
requireEmailVerification: false,
|
|
328
|
+
minPasswordLength: PASSWORD.min,
|
|
329
|
+
maxPasswordLength: PASSWORD.max,
|
|
330
|
+
...input.password ? { password: input.password } : {}
|
|
331
|
+
},
|
|
332
|
+
...settings.google ? { socialProviders: { google: googleProvider(settings.google, { signUp: settings.signUp }) } } : {},
|
|
333
|
+
account: { accountLinking: CONFIRMED_ACCOUNT_LINKING },
|
|
334
|
+
session: { expiresIn: days * 24 * 60 * 60, updateAge: 24 * 60 * 60, cookieCache: { enabled: true, maxAge: 5 * 60 } },
|
|
335
|
+
...input.beforeDeleteUser ? { user: { deleteUser: { enabled: true, beforeDelete: input.beforeDeleteUser } } } : {},
|
|
336
|
+
rateLimit: {
|
|
337
|
+
enabled: settings.rateLimit,
|
|
338
|
+
window: 60,
|
|
339
|
+
max: 60,
|
|
340
|
+
customRules: { ...RATE_LIMIT_RULES },
|
|
341
|
+
...input.rateLimitStorage ? { customStorage: input.rateLimitStorage } : { storage: "database" }
|
|
342
|
+
},
|
|
343
|
+
databaseHooks: {
|
|
344
|
+
user: {
|
|
345
|
+
create: {
|
|
346
|
+
before: async (user) => {
|
|
347
|
+
const data = {
|
|
348
|
+
...user,
|
|
349
|
+
role: roleForNewUser(user, settings.adminEmails, input.admin.defaultRole, input.admin.adminRoles[0] ?? "admin")
|
|
350
|
+
};
|
|
351
|
+
if (typeof data.username !== "string" || !data.username) {
|
|
352
|
+
const name = await freeUsername(user.name, user.email, input.takenUsernames, input.usernameFallback);
|
|
353
|
+
data.username = name;
|
|
354
|
+
data.displayUsername = name;
|
|
355
|
+
}
|
|
356
|
+
return { data };
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
},
|
|
360
|
+
account: {
|
|
361
|
+
create: {
|
|
362
|
+
after: async (account, ctx) => {
|
|
363
|
+
if (ctx)
|
|
364
|
+
await afterAccountSaved(account, ctx.context.internalAdapter, await signedInUserId(ctx));
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
},
|
|
369
|
+
...input.signedInFlag ? { hooks: { after: signedInFlagHook(input.signedInFlag) } } : {},
|
|
370
|
+
advanced: { ipAddress: { ipAddressHeaders: input.ipAddressHeaders ?? ["cf-connecting-ip"] } },
|
|
371
|
+
plugins: [
|
|
372
|
+
username({ minUsernameLength: USERNAME.min, maxUsernameLength: USERNAME.max }),
|
|
373
|
+
passkey({
|
|
374
|
+
rpName: input.appName,
|
|
375
|
+
...fromRequest ? {} : {
|
|
376
|
+
origin: passkeyOrigins(input.siteUrl, {
|
|
377
|
+
...input.localOrigins ? { local: input.localOrigins } : {},
|
|
378
|
+
...input.androidCertSha256 ? { androidCertSha256: input.androidCertSha256 } : {}
|
|
379
|
+
})
|
|
380
|
+
}
|
|
381
|
+
}),
|
|
382
|
+
admin(input.admin),
|
|
383
|
+
bearer(),
|
|
384
|
+
...input.plugins ?? [],
|
|
385
|
+
...input.lastPlugin ? [input.lastPlugin] : []
|
|
386
|
+
]
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// src/auth/server.ts
|
|
391
|
+
async function authResult(action) {
|
|
392
|
+
try {
|
|
393
|
+
await action();
|
|
394
|
+
return { ok: true };
|
|
395
|
+
} catch (error) {
|
|
396
|
+
if (error instanceof APIError)
|
|
397
|
+
return { ok: false, code: String(error.body?.code ?? error.status) };
|
|
398
|
+
throw error;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
var AUTH_SERVER_CODES = {
|
|
402
|
+
unauthorized: "UNAUTHORIZED",
|
|
403
|
+
passwordRequired: "INVALID_PASSWORD",
|
|
404
|
+
confirmUsername: "CONFIRM_USERNAME",
|
|
405
|
+
invalidLogin: "INVALID_EMAIL_OR_PASSWORD",
|
|
406
|
+
noRedirect: "NO_REDIRECT_URL",
|
|
407
|
+
self: "CANNOT_ACT_ON_SELF"
|
|
408
|
+
};
|
|
409
|
+
function temporaryPassword() {
|
|
410
|
+
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(18));
|
|
411
|
+
return btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_");
|
|
412
|
+
}
|
|
413
|
+
var iso = (value) => new Date(value).toISOString();
|
|
414
|
+
function authServer(config) {
|
|
415
|
+
const api = async () => (typeof config.auth === "function" ? await config.auth() : config.auth).api;
|
|
416
|
+
async function viewer(options = {}) {
|
|
417
|
+
const session = await (await api()).getSession({
|
|
418
|
+
headers: config.headers(),
|
|
419
|
+
...options.fresh ? { query: { disableCookieCache: true } } : {}
|
|
420
|
+
});
|
|
421
|
+
return toAuthUser(session?.user, config.roleOf);
|
|
422
|
+
}
|
|
423
|
+
async function signInMethods() {
|
|
424
|
+
const accounts = await (await api()).listUserAccounts({ headers: config.headers() });
|
|
425
|
+
const providers = new Set(accounts.map((account) => account.providerId));
|
|
426
|
+
return { password: providers.has("credential"), google: providers.has("google") };
|
|
427
|
+
}
|
|
428
|
+
async function googleUrl(start) {
|
|
429
|
+
try {
|
|
430
|
+
const answer = await start();
|
|
431
|
+
return answer.url ? { ok: true, url: answer.url } : { ok: false, code: AUTH_SERVER_CODES.noRedirect };
|
|
432
|
+
} catch (error) {
|
|
433
|
+
if (error instanceof APIError)
|
|
434
|
+
return { ok: false, code: String(error.body?.code ?? error.status) };
|
|
435
|
+
throw error;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
async function adminViewer() {
|
|
439
|
+
const session = await (await api()).getSession({ headers: config.headers(), query: { disableCookieCache: true } });
|
|
440
|
+
const user = toAuthUser(session?.user, config.roleOf);
|
|
441
|
+
return user && config.canOpenAdmin(session?.user.role) ? user : null;
|
|
442
|
+
}
|
|
443
|
+
async function onOther(userId, action) {
|
|
444
|
+
const admin = await adminViewer();
|
|
445
|
+
if (!admin)
|
|
446
|
+
return { ok: false, code: AUTH_SERVER_CODES.unauthorized };
|
|
447
|
+
if (admin.id === userId)
|
|
448
|
+
return { ok: false, code: AUTH_SERVER_CODES.self };
|
|
449
|
+
const auth = await api();
|
|
450
|
+
const headers = config.headers();
|
|
451
|
+
return authResult(() => action(auth, headers));
|
|
452
|
+
}
|
|
453
|
+
return {
|
|
454
|
+
viewer,
|
|
455
|
+
signInMethods,
|
|
456
|
+
async signIn(input) {
|
|
457
|
+
const login = input.login.trim();
|
|
458
|
+
if (login.includes("@") && isPlaceholderEmail(login))
|
|
459
|
+
return { ok: false, code: AUTH_SERVER_CODES.invalidLogin };
|
|
460
|
+
const auth = await api();
|
|
461
|
+
const headers = config.headers();
|
|
462
|
+
return authResult(() => login.includes("@") ? auth.signInEmail({ body: { email: login, password: input.password }, headers }) : auth.signInUsername({ body: { username: login, password: input.password }, headers }));
|
|
463
|
+
},
|
|
464
|
+
async signUp(input) {
|
|
465
|
+
if (input.email && isPlaceholderEmail(input.email))
|
|
466
|
+
return { ok: false, code: "INVALID_EMAIL" };
|
|
467
|
+
const auth = await api();
|
|
468
|
+
const email = input.email || placeholderEmail(config.randomId);
|
|
469
|
+
return authResult(() => auth.signUpEmail({
|
|
470
|
+
body: { name: input.name || input.username, username: input.username, email, password: input.password },
|
|
471
|
+
headers: config.headers()
|
|
472
|
+
}));
|
|
473
|
+
},
|
|
474
|
+
async signOut() {
|
|
475
|
+
const auth = await api();
|
|
476
|
+
return authResult(() => auth.signOut({ headers: config.headers() }));
|
|
477
|
+
},
|
|
478
|
+
async changePassword(input) {
|
|
479
|
+
const auth = await api();
|
|
480
|
+
return authResult(() => auth.changePassword({
|
|
481
|
+
body: { currentPassword: input.currentPassword, newPassword: input.newPassword, revokeOtherSessions: true },
|
|
482
|
+
headers: config.headers()
|
|
483
|
+
}));
|
|
484
|
+
},
|
|
485
|
+
async setFirstPassword(input) {
|
|
486
|
+
const auth = await api();
|
|
487
|
+
return authResult(() => auth.setPassword({ body: { newPassword: input.newPassword }, headers: config.headers() }));
|
|
488
|
+
},
|
|
489
|
+
async passkeys() {
|
|
490
|
+
if (!await viewer())
|
|
491
|
+
return [];
|
|
492
|
+
const rows = await (await api()).listPasskeys({ headers: config.headers() });
|
|
493
|
+
return rows.map((row) => ({ id: row.id, name: row.name ?? null, createdAt: iso(row.createdAt) })).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
494
|
+
},
|
|
495
|
+
async removePasskey(id) {
|
|
496
|
+
const auth = await api();
|
|
497
|
+
return authResult(() => auth.deletePasskey({ body: { id }, headers: config.headers() }));
|
|
498
|
+
},
|
|
499
|
+
async googleStartUrl(input) {
|
|
500
|
+
const redirect = safeRedirect(input.redirect);
|
|
501
|
+
const back = redirect ? `?redirect=${encodeURIComponent(redirect)}` : "";
|
|
502
|
+
const auth = await api();
|
|
503
|
+
return googleUrl(() => auth.signInSocial({
|
|
504
|
+
body: { provider: "google", callbackURL: redirect ?? input.home, errorCallbackURL: `${input.signInPath}${back}` },
|
|
505
|
+
headers: config.headers()
|
|
506
|
+
}));
|
|
507
|
+
},
|
|
508
|
+
async googleLinkUrl(input) {
|
|
509
|
+
if (!await viewer())
|
|
510
|
+
return { ok: false, code: AUTH_SERVER_CODES.unauthorized };
|
|
511
|
+
const auth = await api();
|
|
512
|
+
return googleUrl(() => auth.linkSocialAccount({
|
|
513
|
+
body: { provider: "google", callbackURL: `${input.accountPath}?connected=google`, errorCallbackURL: input.accountPath },
|
|
514
|
+
headers: config.headers()
|
|
515
|
+
}));
|
|
516
|
+
},
|
|
517
|
+
async deleteOwnAccount(input) {
|
|
518
|
+
const me = await viewer();
|
|
519
|
+
if (!me)
|
|
520
|
+
return { ok: false, code: AUTH_SERVER_CODES.unauthorized };
|
|
521
|
+
const auth = await api();
|
|
522
|
+
const headers = config.headers();
|
|
523
|
+
if ((await signInMethods()).password) {
|
|
524
|
+
const password = input.password;
|
|
525
|
+
if (!password)
|
|
526
|
+
return { ok: false, code: AUTH_SERVER_CODES.passwordRequired };
|
|
527
|
+
return authResult(() => auth.deleteUser({ body: { password }, headers }));
|
|
528
|
+
}
|
|
529
|
+
if (input.confirmUsername?.trim().toLowerCase() !== me.username.toLowerCase())
|
|
530
|
+
return { ok: false, code: AUTH_SERVER_CODES.confirmUsername };
|
|
531
|
+
return authResult(() => auth.deleteUser({ body: {}, headers }));
|
|
532
|
+
},
|
|
533
|
+
admin: {
|
|
534
|
+
viewer: adminViewer,
|
|
535
|
+
async listUsers(input) {
|
|
536
|
+
if (!await adminViewer())
|
|
537
|
+
return { ok: false, code: AUTH_SERVER_CODES.unauthorized };
|
|
538
|
+
const search = input.search?.trim();
|
|
539
|
+
const result = await (await api()).listUsers({
|
|
540
|
+
headers: config.headers(),
|
|
541
|
+
query: {
|
|
542
|
+
limit: input.pageSize,
|
|
543
|
+
offset: (Math.max(1, input.page) - 1) * input.pageSize,
|
|
544
|
+
sortBy: "createdAt",
|
|
545
|
+
sortDirection: "desc",
|
|
546
|
+
...search ? { searchValue: search, searchField: search.includes("@") ? "email" : "name", searchOperator: "contains" } : {}
|
|
547
|
+
}
|
|
548
|
+
});
|
|
549
|
+
return {
|
|
550
|
+
ok: true,
|
|
551
|
+
total: result.total,
|
|
552
|
+
users: result.users.map((user) => ({
|
|
553
|
+
id: user.id,
|
|
554
|
+
name: user.name,
|
|
555
|
+
username: user.displayUsername || user.username || user.name,
|
|
556
|
+
email: isPlaceholderEmail(user.email) ? null : user.email,
|
|
557
|
+
role: config.roleOf(user.role),
|
|
558
|
+
banned: Boolean(user.banned),
|
|
559
|
+
createdAt: iso(user.createdAt)
|
|
560
|
+
}))
|
|
561
|
+
};
|
|
562
|
+
},
|
|
563
|
+
setRole: (input) => onOther(input.userId, (auth, headers) => auth.setRole({ body: { userId: input.userId, role: input.role }, headers })),
|
|
564
|
+
ban: (input) => onOther(input.userId, (auth, headers) => auth.banUser({ body: { userId: input.userId, ...input.reason ? { banReason: input.reason } : {} }, headers })),
|
|
565
|
+
unban: (input) => onOther(input.userId, (auth, headers) => auth.unbanUser({ body: { userId: input.userId }, headers })),
|
|
566
|
+
async resetPassword(input) {
|
|
567
|
+
const password = temporaryPassword();
|
|
568
|
+
const result = await onOther(input.userId, async (auth, headers) => {
|
|
569
|
+
await auth.setUserPassword({ body: { userId: input.userId, newPassword: password }, headers });
|
|
570
|
+
await auth.revokeUserSessions({ body: { userId: input.userId }, headers });
|
|
571
|
+
});
|
|
572
|
+
return result.ok ? { ok: true, password } : result;
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
export {
|
|
578
|
+
AUTH_SERVER_CODES,
|
|
579
|
+
authResult,
|
|
580
|
+
authServer,
|
|
581
|
+
temporaryPassword
|
|
582
|
+
};
|
package/dist/auth.js
CHANGED
|
@@ -89,6 +89,52 @@ function authErrorCode(answer) {
|
|
|
89
89
|
return GOOGLE_EMAIL_NOT_CONFIRMED;
|
|
90
90
|
return code;
|
|
91
91
|
}
|
|
92
|
+
var USERNAME_ERROR_CODES = {
|
|
93
|
+
"too-short": "USERNAME_TOO_SHORT",
|
|
94
|
+
"too-long": "USERNAME_TOO_LONG",
|
|
95
|
+
characters: "INVALID_USERNAME"
|
|
96
|
+
};
|
|
97
|
+
function usernameErrorCode(username) {
|
|
98
|
+
const problem = usernameProblem(username);
|
|
99
|
+
return problem ? USERNAME_ERROR_CODES[problem] : null;
|
|
100
|
+
}
|
|
101
|
+
var NAME_UNSAFE = /[\u0000-\u001f\u007f<>]/;
|
|
102
|
+
function displayNameProblem(name, max = 50) {
|
|
103
|
+
const trimmed = name.trim();
|
|
104
|
+
if (!trimmed)
|
|
105
|
+
return "empty";
|
|
106
|
+
if ([...trimmed].length > max)
|
|
107
|
+
return "too-long";
|
|
108
|
+
if (NAME_UNSAFE.test(trimmed))
|
|
109
|
+
return "characters";
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
function defineSignInReasons(reasons) {
|
|
113
|
+
return {
|
|
114
|
+
REASONS: reasons,
|
|
115
|
+
reasonOf(value) {
|
|
116
|
+
return reasons.find((reason) => reason === value);
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
var REDIRECT_UNSAFE = /[\u0000-\u001f\u007f\\]/;
|
|
121
|
+
function isSafeRedirectPath(path) {
|
|
122
|
+
if (path.length > 500 || !path.startsWith("/") || path.startsWith("//") || REDIRECT_UNSAFE.test(path))
|
|
123
|
+
return false;
|
|
124
|
+
let decoded;
|
|
125
|
+
try {
|
|
126
|
+
decoded = decodeURIComponent(path);
|
|
127
|
+
} catch {
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
if (REDIRECT_UNSAFE.test(decoded) || decoded.startsWith("//"))
|
|
131
|
+
return false;
|
|
132
|
+
const base = "https://this-site.invalid";
|
|
133
|
+
return new URL(path, base).origin === base;
|
|
134
|
+
}
|
|
135
|
+
function safeRedirect(value) {
|
|
136
|
+
return typeof value === "string" && isSafeRedirectPath(value) ? value : undefined;
|
|
137
|
+
}
|
|
92
138
|
|
|
93
139
|
// src/auth.ts
|
|
94
140
|
var E2E_SECRET = "e2e-only-secret-never-used-in-production-0000";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jgb-solutions/kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "One package for JGB Solutions apps, in tree-shakable namespaces: Cloudflare Access, Better Auth (kit/access, kit/auth\u2026) and the admin panel kit (kit/admin, React 19). An app bundles only the subpaths it imports.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "JGB Solutions",
|
|
@@ -57,6 +57,18 @@
|
|
|
57
57
|
"types": "./dist/auth/rules.d.ts",
|
|
58
58
|
"import": "./dist/auth/rules.js"
|
|
59
59
|
},
|
|
60
|
+
"./auth/server": {
|
|
61
|
+
"types": "./dist/auth/server.d.ts",
|
|
62
|
+
"import": "./dist/auth/server.js"
|
|
63
|
+
},
|
|
64
|
+
"./auth/cache": {
|
|
65
|
+
"types": "./dist/auth/cache.d.ts",
|
|
66
|
+
"import": "./dist/auth/cache.js"
|
|
67
|
+
},
|
|
68
|
+
"./auth/redis": {
|
|
69
|
+
"types": "./dist/auth/redis.d.ts",
|
|
70
|
+
"import": "./dist/auth/redis.js"
|
|
71
|
+
},
|
|
60
72
|
"./auth/expo": {
|
|
61
73
|
"types": "./dist/auth/expo.d.ts",
|
|
62
74
|
"import": "./dist/auth/expo.js"
|