@authmoji/better-auth 0.0.0-stage → 0.1.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/dist/emojis.js ADDED
@@ -0,0 +1,285 @@
1
+ import compactEmojis from "emojibase-data/en/compact.json" with { type: "json" };
2
+ import groupMeta from "emojibase-data/meta/groups.json" with { type: "json" };
3
+ const VARIATION_SELECTOR_16 = "\uFE0F";
4
+ const SEPARATOR_CHARS = new Set([" ", "\t", "\n", "\r", ",", "-", "|"]);
5
+ const GROUP_KEY_TO_ID = new Map(Object.entries(groupMeta.groups).map(([id, key]) => [
6
+ key,
7
+ Number(id),
8
+ ]));
9
+ const COMPONENT_GROUP_ID = GROUP_KEY_TO_ID.get("component") ?? 2;
10
+ function getUnicodeFromEntry(entry) {
11
+ return "unicode" in entry ? entry.unicode : entry.emoji;
12
+ }
13
+ /**
14
+ * Extracts standalone emoji characters from an Emojibase dataset (`compact.json` or `data.json`),
15
+ * excluding uncategorized regional indicators and (by default) non-standalone components.
16
+ */
17
+ export function getEmojisFromDataset(dataset = compactEmojis, options) {
18
+ const allowedGroupIds = options?.groups
19
+ ? new Set(options.groups.map((key) => {
20
+ const id = GROUP_KEY_TO_ID.get(key);
21
+ if (id === undefined) {
22
+ throw new Error(`Unknown Emojibase group key "${key}".`);
23
+ }
24
+ return id;
25
+ }))
26
+ : null;
27
+ const includeComponents = options?.includeComponents ?? false;
28
+ const result = [];
29
+ for (const entry of dataset) {
30
+ if (entry.group === undefined) {
31
+ continue;
32
+ }
33
+ if (!includeComponents && entry.group === COMPONENT_GROUP_ID) {
34
+ continue;
35
+ }
36
+ if (allowedGroupIds && !allowedGroupIds.has(entry.group)) {
37
+ continue;
38
+ }
39
+ result.push(getUnicodeFromEntry(entry));
40
+ }
41
+ return result;
42
+ }
43
+ let cachedDefaultEmojis = null;
44
+ /**
45
+ * Returns the default emoji alphabet derived from `emojibase-data/en/compact.json`.
46
+ */
47
+ export function getDefaultEmojis(options) {
48
+ if (!options?.groups && !options?.includeComponents) {
49
+ cachedDefaultEmojis ??= getEmojisFromDataset(compactEmojis);
50
+ return cachedDefaultEmojis;
51
+ }
52
+ return getEmojisFromDataset(compactEmojis, options);
53
+ }
54
+ /**
55
+ * Resolves either a string array, an Emojibase dataset (`CompactEmoji[]` / `Emoji[]`),
56
+ * or optional Emojibase group filter into a string array of emoji characters.
57
+ */
58
+ export function resolveEmojiPool(emojis, groups) {
59
+ if (!emojis) {
60
+ return getDefaultEmojis(groups ? { groups } : undefined);
61
+ }
62
+ if (emojis.length === 0) {
63
+ return [];
64
+ }
65
+ if (typeof emojis[0] === "string") {
66
+ return emojis;
67
+ }
68
+ return getEmojisFromDataset(emojis, groups ? { groups } : undefined);
69
+ }
70
+ /**
71
+ * Normalizes an emoji for comparison by applying NFC normalization and
72
+ * stripping optional emoji variation selectors (U+FE0F).
73
+ */
74
+ export function normalizeEmoji(emoji) {
75
+ return emoji.trim().normalize("NFC").replaceAll(VARIATION_SELECTOR_16, "");
76
+ }
77
+ /**
78
+ * Validates that an emoji pool contains at least `minSize` unique emojis
79
+ * (after variation-selector normalization).
80
+ */
81
+ export function assertValidEmojiPool(emojis, minSize) {
82
+ if (emojis.length < minSize) {
83
+ throw new Error(`Authmoji emoji pool must contain at least ${minSize} emojis (received ${emojis.length}).`);
84
+ }
85
+ const seen = new Set();
86
+ for (const emoji of emojis) {
87
+ const normalized = normalizeEmoji(emoji);
88
+ if (!normalized) {
89
+ throw new Error("Authmoji emoji pool must not contain empty entries.");
90
+ }
91
+ if (seen.has(normalized)) {
92
+ throw new Error(`Authmoji emoji pool contains duplicate emoji "${emoji}" after normalization.`);
93
+ }
94
+ seen.add(normalized);
95
+ }
96
+ return emojis;
97
+ }
98
+ const poolLookupCache = new WeakMap();
99
+ function getPoolLookup(pool) {
100
+ const cached = poolLookupCache.get(pool);
101
+ if (cached) {
102
+ return cached;
103
+ }
104
+ const byNormalized = new Map();
105
+ const byFirstCodePoint = new Map();
106
+ for (const emoji of pool) {
107
+ const normalized = normalizeEmoji(emoji);
108
+ if (!normalized || byNormalized.has(normalized)) {
109
+ continue;
110
+ }
111
+ byNormalized.set(normalized, emoji);
112
+ const firstCodePoint = normalized.codePointAt(0);
113
+ if (firstCodePoint === undefined) {
114
+ continue;
115
+ }
116
+ const bucket = byFirstCodePoint.get(firstCodePoint);
117
+ const entry = { normalized, canonical: emoji };
118
+ if (bucket) {
119
+ bucket.push(entry);
120
+ }
121
+ else {
122
+ byFirstCodePoint.set(firstCodePoint, [entry]);
123
+ }
124
+ }
125
+ // Match longest sequences first within each codepoint bucket (e.g. ZWJ before base).
126
+ for (const bucket of byFirstCodePoint.values()) {
127
+ if (bucket.length > 1) {
128
+ bucket.sort((a, b) => b.normalized.length - a.normalized.length);
129
+ }
130
+ }
131
+ const lookup = { byNormalized, byFirstCodePoint };
132
+ poolLookupCache.set(pool, lookup);
133
+ return lookup;
134
+ }
135
+ /**
136
+ * Cryptographically secure unbiased integer in `[0, maxExclusive)`.
137
+ */
138
+ export function cryptoRandomInt(maxExclusive) {
139
+ if (!Number.isInteger(maxExclusive) || maxExclusive <= 0) {
140
+ throw new RangeError(`maxExclusive must be a positive integer, received ${maxExclusive}`);
141
+ }
142
+ if (maxExclusive === 1) {
143
+ return 0;
144
+ }
145
+ const maxUint32 = 0x1_00_00_00_00;
146
+ const limit = Math.floor(maxUint32 / maxExclusive) * maxExclusive;
147
+ const buffer = new Uint32Array(1);
148
+ while (true) {
149
+ globalThis.crypto.getRandomValues(buffer);
150
+ const value = buffer[0];
151
+ if (value < limit) {
152
+ return value % maxExclusive;
153
+ }
154
+ }
155
+ }
156
+ /**
157
+ * Cryptographically secure Fisher-Yates shuffle returning a new array.
158
+ */
159
+ export function cryptoShuffle(items) {
160
+ const array = [...items];
161
+ for (let i = array.length - 1; i > 0; i -= 1) {
162
+ const j = cryptoRandomInt(i + 1);
163
+ const temp = array[i];
164
+ array[i] = array[j];
165
+ array[j] = temp;
166
+ }
167
+ return array;
168
+ }
169
+ /**
170
+ * Generates a cryptographically random Authmoji challenge with an ordered
171
+ * answer sequence and an optional shuffled choice grid.
172
+ */
173
+ export function generateEmojiChallenge(options) {
174
+ const pool = resolveEmojiPool(options?.emojis, options?.groups);
175
+ const length = options?.length ?? 3;
176
+ const choiceCount = options?.choiceCount ?? 8;
177
+ if (!Number.isInteger(length) || length < 1) {
178
+ throw new RangeError(`Authmoji length must be an integer >= 1 (received ${length}).`);
179
+ }
180
+ if (!Number.isInteger(choiceCount) || choiceCount < 0) {
181
+ throw new RangeError(`Authmoji choiceCount must be an integer >= 0 (received ${choiceCount}).`);
182
+ }
183
+ if (choiceCount > 0 && choiceCount < length) {
184
+ throw new RangeError(`Authmoji choiceCount (${choiceCount}) must be 0 or >= length (${length}).`);
185
+ }
186
+ const minPoolSize = Math.max(length, choiceCount);
187
+ assertValidEmojiPool(pool, minPoolSize);
188
+ const selected = cryptoShuffle(pool).slice(0, minPoolSize);
189
+ const answer = selected.slice(0, length);
190
+ const choices = choiceCount > 0 ? cryptoShuffle(selected) : [];
191
+ return {
192
+ emojis: answer,
193
+ code: answer.join(""),
194
+ choices,
195
+ };
196
+ }
197
+ /**
198
+ * Strictly parses an emoji sequence from either an array of emojis or a
199
+ * string (concatenated or separated by commas/spaces/hyphens).
200
+ * Returns `null` if the input contains unrecognized characters or non-pool emojis.
201
+ */
202
+ export function parseEmojiSequence(input, pool) {
203
+ const resolvedPool = resolveEmojiPool(pool);
204
+ const { byNormalized, byFirstCodePoint } = getPoolLookup(resolvedPool);
205
+ if (Array.isArray(input)) {
206
+ const result = [];
207
+ for (const item of input) {
208
+ if (typeof item !== "string") {
209
+ return null;
210
+ }
211
+ const canonical = byNormalized.get(normalizeEmoji(item));
212
+ if (!canonical) {
213
+ return null;
214
+ }
215
+ result.push(canonical);
216
+ }
217
+ return result.length > 0 ? result : null;
218
+ }
219
+ if (typeof input !== "string") {
220
+ return null;
221
+ }
222
+ const normalizedInput = input
223
+ .trim()
224
+ .normalize("NFC")
225
+ .replaceAll(VARIATION_SELECTOR_16, "");
226
+ if (!normalizedInput) {
227
+ return null;
228
+ }
229
+ const result = [];
230
+ let index = 0;
231
+ while (index < normalizedInput.length) {
232
+ const char = normalizedInput[index];
233
+ if (SEPARATOR_CHARS.has(char)) {
234
+ index += 1;
235
+ continue;
236
+ }
237
+ const codePoint = normalizedInput.codePointAt(index);
238
+ const bucket = codePoint !== undefined ? byFirstCodePoint.get(codePoint) : undefined;
239
+ const match = bucket?.find((entry) => normalizedInput.startsWith(entry.normalized, index));
240
+ if (!match) {
241
+ return null;
242
+ }
243
+ result.push(match.canonical);
244
+ index += match.normalized.length;
245
+ }
246
+ return result.length > 0 ? result : null;
247
+ }
248
+ /**
249
+ * Leniently extracts recognized emojis from arbitrary text such as SMS
250
+ * messages or WebOTP autofill payloads.
251
+ */
252
+ export function extractEmojisFromText(text, pool) {
253
+ const resolvedPool = resolveEmojiPool(pool);
254
+ const { byFirstCodePoint } = getPoolLookup(resolvedPool);
255
+ const normalizedText = text
256
+ .normalize("NFC")
257
+ .replaceAll(VARIATION_SELECTOR_16, "");
258
+ const matched = [];
259
+ let index = 0;
260
+ while (index < normalizedText.length) {
261
+ const codePoint = normalizedText.codePointAt(index);
262
+ const bucket = codePoint !== undefined ? byFirstCodePoint.get(codePoint) : undefined;
263
+ const found = bucket?.find((entry) => normalizedText.startsWith(entry.normalized, index));
264
+ if (found) {
265
+ matched.push(found.canonical);
266
+ index += found.normalized.length;
267
+ }
268
+ else {
269
+ index += codePoint !== undefined && codePoint > 0xffff ? 2 : 1;
270
+ }
271
+ }
272
+ return matched;
273
+ }
274
+ /**
275
+ * Formats an emoji array as a string (default concatenated with no separator).
276
+ */
277
+ export function formatEmojiSequence(emojis, separator = "") {
278
+ return emojis.join(separator);
279
+ }
280
+ /**
281
+ * Canonical normalized representation used for hashing and constant-time comparison.
282
+ */
283
+ export function canonicalizeEmojiSequence(emojis) {
284
+ return emojis.map(normalizeEmoji).join(",");
285
+ }
@@ -0,0 +1,23 @@
1
+ export interface AuthmojiErrorEntry<K extends string = string> {
2
+ readonly code: K;
3
+ readonly message: string;
4
+ toString: () => K;
5
+ }
6
+ export declare const AUTHMOJI_ERROR_CODES: {
7
+ ACCOUNT_TEMPORARILY_LOCKED: AuthmojiErrorEntry<"ACCOUNT_TEMPORARILY_LOCKED">;
8
+ AUTHMOJI_NOT_ENABLED: AuthmojiErrorEntry<"AUTHMOJI_NOT_ENABLED">;
9
+ BACKUP_CODES_NOT_ENABLED: AuthmojiErrorEntry<"BACKUP_CODES_NOT_ENABLED">;
10
+ INVALID_AUTHMOJI_COOKIE: AuthmojiErrorEntry<"INVALID_AUTHMOJI_COOKIE">;
11
+ INVALID_BACKUP_CODE: AuthmojiErrorEntry<"INVALID_BACKUP_CODE">;
12
+ INVALID_CODE: AuthmojiErrorEntry<"INVALID_CODE">;
13
+ INVALID_PASSWORD: AuthmojiErrorEntry<"INVALID_PASSWORD">;
14
+ OTP_HAS_EXPIRED: AuthmojiErrorEntry<"OTP_HAS_EXPIRED">;
15
+ OTP_NOT_CONFIGURED: AuthmojiErrorEntry<"OTP_NOT_CONFIGURED">;
16
+ TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE: AuthmojiErrorEntry<"TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE">;
17
+ TOTP_ALREADY_ENABLED: AuthmojiErrorEntry<"TOTP_ALREADY_ENABLED">;
18
+ TOTP_CHOICES_DISABLED: AuthmojiErrorEntry<"TOTP_CHOICES_DISABLED">;
19
+ TOTP_NOT_CONFIGURED: AuthmojiErrorEntry<"TOTP_NOT_CONFIGURED">;
20
+ TOTP_NOT_ENABLED: AuthmojiErrorEntry<"TOTP_NOT_ENABLED">;
21
+ UNAUTHORIZED: AuthmojiErrorEntry<"UNAUTHORIZED">;
22
+ };
23
+ export type AuthmojiErrorCode = keyof typeof AUTHMOJI_ERROR_CODES;
@@ -0,0 +1,28 @@
1
+ function defineErrorCodes(codes) {
2
+ const entries = Object.entries(codes).map(([key, message]) => [
3
+ key,
4
+ {
5
+ code: key,
6
+ message,
7
+ toString: () => key,
8
+ },
9
+ ]);
10
+ return Object.fromEntries(entries);
11
+ }
12
+ export const AUTHMOJI_ERROR_CODES = defineErrorCodes({
13
+ OTP_NOT_CONFIGURED: "Authmoji OTP is not configured",
14
+ OTP_HAS_EXPIRED: "Authmoji OTP has expired",
15
+ TOTP_NOT_CONFIGURED: "Authmoji TOTP is not available",
16
+ TOTP_NOT_ENABLED: "Authmoji TOTP is not enabled",
17
+ TOTP_ALREADY_ENABLED: "Authmoji TOTP is already enabled",
18
+ TOTP_CHOICES_DISABLED: "Authmoji TOTP choice grid is disabled",
19
+ AUTHMOJI_NOT_ENABLED: "Authmoji two-factor authentication is not enabled",
20
+ BACKUP_CODES_NOT_ENABLED: "Authmoji backup codes are not enabled",
21
+ INVALID_BACKUP_CODE: "Invalid backup code",
22
+ INVALID_CODE: "Invalid Authmoji sequence",
23
+ TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE: "Too many attempts. Please request a new Authmoji sequence.",
24
+ ACCOUNT_TEMPORARILY_LOCKED: "Too many failed verification attempts. Your account is temporarily locked. Please try again later.",
25
+ INVALID_AUTHMOJI_COOKIE: "Invalid Authmoji verification cookie",
26
+ INVALID_PASSWORD: "Invalid password",
27
+ UNAUTHORIZED: "Unauthorized",
28
+ });
@@ -0,0 +1,9 @@
1
+ export { assertValidEmojiPool, canonicalizeEmojiSequence, cryptoRandomInt, cryptoShuffle, extractEmojisFromText, formatEmojiSequence, generateEmojiChallenge, getDefaultEmojis, getEmojisFromDataset, normalizeEmoji, parseEmojiSequence, resolveEmojiPool, } from "./emojis.js";
2
+ export type { EmojiChallenge, EmojiDatasetEntry, EmojiPoolInput, GenerateEmojiChallengeOptions, GetEmojisOptions, } from "./emojis.js";
3
+ export { AUTHMOJI_ERROR_CODES } from "./error-codes.js";
4
+ export type { AuthmojiErrorCode, AuthmojiErrorEntry } from "./error-codes.js";
5
+ export { authmojiSchema } from "./schema.js";
6
+ export { authmoji } from "./server.js";
7
+ export { createAuthmojiTOTPURI, decodeBase32, encodeBase32, generateEmojiTOTP, generateEmojiTOTPChoices, generateTOTPSecret, parseAuthmojiTOTPURI, verifyEmojiTOTP, } from "./totp.js";
8
+ export type { AuthmojiTOTPURIParams, EmojiTOTPChoicesOptions, EmojiTOTPChoicesResult, EmojiTOTPOptions, EmojiTOTPResult, ParsedAuthmojiTOTPURI, TOTPAlgorithm, VerifyEmojiTOTPOptions, VerifyEmojiTOTPResult, } from "./totp.js";
9
+ export type { AuthmojiAccountLockoutOptions, AuthmojiBackupCodeOptions, AuthmojiClientOptions, AuthmojiMethod, AuthmojiOptions, AuthmojiOTPOptions, AuthmojiRecord, AuthmojiRedirectContext, AuthmojiTOTPOptions, Awaitable, SendAuthmojiOTPData, StoreBackupCodesOption, StoreOTPOption, UserWithAuthmoji, } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { assertValidEmojiPool, canonicalizeEmojiSequence, cryptoRandomInt, cryptoShuffle, extractEmojisFromText, formatEmojiSequence, generateEmojiChallenge, getDefaultEmojis, getEmojisFromDataset, normalizeEmoji, parseEmojiSequence, resolveEmojiPool, } from "./emojis.js";
2
+ export { AUTHMOJI_ERROR_CODES } from "./error-codes.js";
3
+ export { authmojiSchema } from "./schema.js";
4
+ export { authmoji } from "./server.js";
5
+ export { createAuthmojiTOTPURI, decodeBase32, encodeBase32, generateEmojiTOTP, generateEmojiTOTPChoices, generateTOTPSecret, parseAuthmojiTOTPURI, verifyEmojiTOTP, } from "./totp.js";
@@ -0,0 +1,62 @@
1
+ export declare const authmojiSchema: {
2
+ user: {
3
+ fields: {
4
+ authmojiEnabled: {
5
+ type: "boolean";
6
+ required: false;
7
+ defaultValue: false;
8
+ input: false;
9
+ };
10
+ };
11
+ };
12
+ authmoji: {
13
+ fields: {
14
+ secret: {
15
+ type: "string";
16
+ required: true;
17
+ returned: false;
18
+ index: true;
19
+ };
20
+ backupCodes: {
21
+ type: "string";
22
+ required: true;
23
+ returned: false;
24
+ };
25
+ userId: {
26
+ type: "string";
27
+ required: true;
28
+ returned: false;
29
+ references: {
30
+ model: string;
31
+ field: string;
32
+ };
33
+ index: true;
34
+ };
35
+ verified: {
36
+ type: "boolean";
37
+ required: false;
38
+ defaultValue: false;
39
+ input: false;
40
+ };
41
+ lastTotpCounter: {
42
+ type: "number";
43
+ required: false;
44
+ input: false;
45
+ returned: false;
46
+ };
47
+ failedVerificationCount: {
48
+ type: "number";
49
+ required: false;
50
+ defaultValue: number;
51
+ input: false;
52
+ returned: false;
53
+ };
54
+ lockedUntil: {
55
+ type: "date";
56
+ required: false;
57
+ input: false;
58
+ returned: false;
59
+ };
60
+ };
61
+ };
62
+ };
package/dist/schema.js ADDED
@@ -0,0 +1,62 @@
1
+ export const authmojiSchema = {
2
+ user: {
3
+ fields: {
4
+ authmojiEnabled: {
5
+ type: "boolean",
6
+ required: false,
7
+ defaultValue: false,
8
+ input: false,
9
+ },
10
+ },
11
+ },
12
+ authmoji: {
13
+ fields: {
14
+ secret: {
15
+ type: "string",
16
+ required: true,
17
+ returned: false,
18
+ index: true,
19
+ },
20
+ backupCodes: {
21
+ type: "string",
22
+ required: true,
23
+ returned: false,
24
+ },
25
+ userId: {
26
+ type: "string",
27
+ required: true,
28
+ returned: false,
29
+ references: {
30
+ model: "user",
31
+ field: "id",
32
+ },
33
+ index: true,
34
+ },
35
+ verified: {
36
+ type: "boolean",
37
+ required: false,
38
+ defaultValue: false,
39
+ input: false,
40
+ },
41
+ lastTotpCounter: {
42
+ type: "number",
43
+ required: false,
44
+ input: false,
45
+ returned: false,
46
+ },
47
+ failedVerificationCount: {
48
+ type: "number",
49
+ required: false,
50
+ defaultValue: 0,
51
+ input: false,
52
+ returned: false,
53
+ },
54
+ lockedUntil: {
55
+ type: "date",
56
+ required: false,
57
+ input: false,
58
+ returned: false,
59
+ },
60
+ },
61
+ },
62
+ };