@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.
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Account rules every part of an app shares: the website, its server and the mobile app. Browser-safe
3
+ * and dependency-free (no Better Auth, no validator), so a sign-up form can check a username with the
4
+ * same rule the server uses.
5
+ *
6
+ * import { USERNAME, usernameProblem, defineRoles } from '@jgb-solutions/kit/auth/rules'
7
+ */
8
+ /** Usernames: 3 to 30 characters, lower-case letters, digits, dots and underscores (Better Auth's username plugin rule too). */
9
+ export declare const USERNAME: {
10
+ readonly min: 3;
11
+ readonly max: 30;
12
+ readonly pattern: RegExp;
13
+ };
14
+ /** Passwords: 12 to 128 characters. Long beats complicated; no other rules. */
15
+ export declare const PASSWORD: {
16
+ readonly min: 12;
17
+ readonly max: 128;
18
+ };
19
+ /** Why a username can't be used, or null when it can. The app words the message. */
20
+ export declare function usernameProblem(username: string): 'too-short' | 'too-long' | 'characters' | null;
21
+ /**
22
+ * Better Auth needs an email address per account. An account made without one gets
23
+ * `<random>@users.invalid` (`.invalid` is reserved: it can never receive mail). It is never shown or mailed.
24
+ */
25
+ export declare const PLACEHOLDER_EMAIL_DOMAIN = "users.invalid";
26
+ export declare function isPlaceholderEmail(email: string): boolean;
27
+ /** A new placeholder address, random enough never to collide. */
28
+ export declare function placeholderEmail(): string;
29
+ /**
30
+ * A username made from a person's name, for accounts made with Google: "Marie-Ève Dupont" →
31
+ * "marie.eve.dupont". Accents dropped, spaces and dashes to dots, anything else out, short enough to
32
+ * take a 4-digit number. The email's first part, then `fallback`, stand in when the name gives too little.
33
+ */
34
+ export declare function usernameFromName(name: string | null | undefined, email: string | null | undefined, fallback: string): string;
35
+ /** The name, then the name with a 4-digit number (8 of them), to find one nobody has. */
36
+ export declare function usernameCandidates(base: string, random?: () => number): string[];
37
+ /**
38
+ * An app's roles, from its own list. Better Auth's admin plugin stores roles as text ("user", or
39
+ * "user,admin" for several).
40
+ *
41
+ * export const { ROLES, isRole, roleOf, canOpenAdmin } = defineRoles({
42
+ * roles: ['user', 'editor', 'admin'], defaultRole: 'user', adminPanel: ['admin'],
43
+ * })
44
+ */
45
+ export declare function defineRoles<const R extends readonly [string, ...string[]]>(config: {
46
+ roles: R;
47
+ defaultRole: R[number];
48
+ /** Roles that may open the admin panel. */
49
+ adminPanel: readonly R[number][];
50
+ }): {
51
+ ROLES: R;
52
+ DEFAULT_ROLE: R[number];
53
+ ADMIN_PANEL_ROLES: readonly R[number][];
54
+ isRole: (value: unknown) => value is R[number];
55
+ /** The role to act on: one that may open the admin panel wins, then the first known one, else the default. */
56
+ roleOf(stored: string | null | undefined): R[number];
57
+ /** True when any stored role may open the admin panel. */
58
+ canOpenAdmin(stored: string | null | undefined): boolean;
59
+ };
60
+ /**
61
+ * The signed-in person, as every part of the app sees them. `email` is null for an account made
62
+ * without one (its placeholder is never shown).
63
+ */
64
+ export type AuthUser<Role extends string = string> = {
65
+ id: string;
66
+ username: string;
67
+ name: string;
68
+ email: string | null;
69
+ image: string | null;
70
+ role: Role;
71
+ };
72
+ /**
73
+ * A profile picture's address at the size shown (twice that, for sharp screens), or '' when it can't
74
+ * be shown: only https addresses. Google's addresses end with their size (`=s96-c`), so the size needed
75
+ * is asked for instead of the large default.
76
+ */
77
+ export declare function avatarSrc(image: string | null | undefined, px: number): string;
78
+ /** Up to two letters for an avatar without a picture: "Maria Lopez" or "maria_lopez" → "ML". */
79
+ export declare function avatarInitials(user: {
80
+ name: string;
81
+ username: string;
82
+ }): string;
83
+ /**
84
+ * Google refused to join an existing account: one with that address exists, but its address was
85
+ * never confirmed (an email sign-up). The page says: sign in with your password first, then connect
86
+ * Google from your account page.
87
+ */
88
+ export declare const ACCOUNT_NOT_LINKED = "ACCOUNT_NOT_LINKED";
89
+ /** Connecting Google failed: that Google account already belongs to another account here. */
90
+ export declare const GOOGLE_ALREADY_LINKED = "GOOGLE_ALREADY_LINKED";
91
+ /** Google didn't confirm the address, so the account can't be joined or connected. */
92
+ export declare const GOOGLE_EMAIL_NOT_CONFIRMED = "GOOGLE_EMAIL_NOT_CONFIRMED";
93
+ /**
94
+ * One code for the app to word, from whatever Better Auth answered: an error body
95
+ * (`{ code, message }` from an API call or a server function's APIError), the `?error=` value of an
96
+ * OAuth redirect (`/sign-in?error=account_not_linked`), or a code. Google's linking refusals become
97
+ * ACCOUNT_NOT_LINKED, GOOGLE_ALREADY_LINKED and GOOGLE_EMAIL_NOT_CONFIRMED; anything else keeps its
98
+ * own code ('' when there is none).
99
+ */
100
+ export declare function authErrorCode(answer: unknown): string;
@@ -0,0 +1,101 @@
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
+ export {
86
+ ACCOUNT_NOT_LINKED,
87
+ GOOGLE_ALREADY_LINKED,
88
+ GOOGLE_EMAIL_NOT_CONFIRMED,
89
+ PASSWORD,
90
+ PLACEHOLDER_EMAIL_DOMAIN,
91
+ USERNAME,
92
+ authErrorCode,
93
+ avatarInitials,
94
+ avatarSrc,
95
+ defineRoles,
96
+ isPlaceholderEmail,
97
+ placeholderEmail,
98
+ usernameCandidates,
99
+ usernameFromName,
100
+ usernameProblem
101
+ };