@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.
@@ -0,0 +1,318 @@
1
+ import { APIError, getAuthoritativeSessionFromCtx } from "better-auth/api";
2
+ import { expireCookie, setSessionCookie } from "better-auth/cookies";
3
+ import { constantTimeEqual, generateRandomString, symmetricDecrypt, symmetricEncrypt, } from "better-auth/crypto";
4
+ import { parseUserOutput } from "better-auth/db";
5
+ import { AUTHMOJI_ERROR_CODES } from "./error-codes.js";
6
+ export const AUTHMOJI_COOKIE_NAME = "authmoji_two_factor";
7
+ export const AUTHMOJI_TRUST_DEVICE_COOKIE_NAME = "authmoji_trust_device";
8
+ export const DEFAULT_TRUST_DEVICE_MAX_AGE = 60 * 60 * 24 * 30; // 30 days
9
+ export const DEFAULT_AUTHMOJI_COOKIE_MAX_AGE = 600; // 10 minutes
10
+ const TEXT_ENCODER = new TextEncoder();
11
+ export function getEncryptionKey(ctx) {
12
+ return ctx.context.secretConfig ?? ctx.context.secret;
13
+ }
14
+ function bytesToBase64Url(bytes) {
15
+ let binary = "";
16
+ for (const byte of bytes) {
17
+ binary += String.fromCharCode(byte);
18
+ }
19
+ return btoa(binary)
20
+ .replaceAll("+", "-")
21
+ .replaceAll("/", "_")
22
+ .replaceAll("=", "");
23
+ }
24
+ export async function signHmacBase64Url(secret, payload) {
25
+ const key = await globalThis.crypto.subtle.importKey("raw", TEXT_ENCODER.encode(secret), { name: "HMAC", hash: { name: "SHA-256" } }, false, ["sign"]);
26
+ const signature = await globalThis.crypto.subtle.sign("HMAC", key, TEXT_ENCODER.encode(payload));
27
+ return bytesToBase64Url(new Uint8Array(signature));
28
+ }
29
+ export async function verifyHmacBase64Url(secret, payload, expectedToken) {
30
+ const computed = await signHmacBase64Url(secret, payload);
31
+ return constantTimeEqual(TEXT_ENCODER.encode(computed), TEXT_ENCODER.encode(expectedToken));
32
+ }
33
+ export async function encodeStoredOTP(ctx, canonicalAnswer, storeOTP) {
34
+ if (storeOTP === "hashed") {
35
+ return signHmacBase64Url(ctx.context.secret, `authmoji:otp:${canonicalAnswer}`);
36
+ }
37
+ if (storeOTP === "encrypted") {
38
+ return symmetricEncrypt({
39
+ key: getEncryptionKey(ctx),
40
+ data: canonicalAnswer,
41
+ });
42
+ }
43
+ if (typeof storeOTP === "object" && "hash" in storeOTP) {
44
+ return storeOTP.hash(canonicalAnswer);
45
+ }
46
+ if (typeof storeOTP === "object" && "encrypt" in storeOTP) {
47
+ return storeOTP.encrypt(canonicalAnswer);
48
+ }
49
+ return canonicalAnswer;
50
+ }
51
+ export async function compareStoredOTP(ctx, storedValue, submittedCanonical, storeOTP) {
52
+ let left;
53
+ let right;
54
+ if (storeOTP === "hashed") {
55
+ left = storedValue;
56
+ right = await signHmacBase64Url(ctx.context.secret, `authmoji:otp:${submittedCanonical}`);
57
+ }
58
+ else if (storeOTP === "encrypted") {
59
+ left = await symmetricDecrypt({
60
+ key: getEncryptionKey(ctx),
61
+ data: storedValue,
62
+ });
63
+ right = submittedCanonical;
64
+ }
65
+ else if (typeof storeOTP === "object" && "hash" in storeOTP) {
66
+ left = storedValue;
67
+ right = await storeOTP.hash(submittedCanonical);
68
+ }
69
+ else if (typeof storeOTP === "object" && "encrypt" in storeOTP) {
70
+ left = await storeOTP.decrypt(storedValue);
71
+ right = submittedCanonical;
72
+ }
73
+ else {
74
+ left = storedValue;
75
+ right = submittedCanonical;
76
+ }
77
+ return constantTimeEqual(TEXT_ENCODER.encode(left), TEXT_ENCODER.encode(right));
78
+ }
79
+ export async function shouldRequirePassword(ctx, userId, allowPasswordless) {
80
+ if (!allowPasswordless) {
81
+ return true;
82
+ }
83
+ const credentialAccount = await ctx.context.internalAdapter.findCredentialAccount(userId);
84
+ return Boolean(credentialAccount?.password);
85
+ }
86
+ export async function assertValidPasswordIfRequired(ctx, userId, password, allowPasswordless) {
87
+ if (!(await shouldRequirePassword(ctx, userId, allowPasswordless))) {
88
+ return;
89
+ }
90
+ if (!password) {
91
+ throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.INVALID_PASSWORD);
92
+ }
93
+ if (password.length > ctx.context.password.config.maxPasswordLength) {
94
+ throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.INVALID_PASSWORD);
95
+ }
96
+ const credentialAccount = await ctx.context.internalAdapter.findCredentialAccount(userId);
97
+ if (!credentialAccount?.password) {
98
+ await ctx.context.password.hash(password);
99
+ throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.INVALID_PASSWORD);
100
+ }
101
+ const valid = await ctx.context.password.verify({
102
+ hash: credentialAccount.password,
103
+ password,
104
+ });
105
+ if (!valid) {
106
+ throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.INVALID_PASSWORD);
107
+ }
108
+ }
109
+ export async function rotateSessionWithUser(ctx, currentSession, updatedUser) {
110
+ const newSession = await ctx.context.internalAdapter.createSession(updatedUser.id, false, currentSession);
111
+ await setSessionCookie(ctx, {
112
+ session: newSession,
113
+ user: updatedUser,
114
+ });
115
+ await ctx.context.internalAdapter.deleteSession(currentSession.token);
116
+ return newSession;
117
+ }
118
+ export async function issueTrustDeviceCookie(ctx, userId, trustDeviceMaxAge) {
119
+ const trustDeviceCookie = ctx.context.createAuthCookie(AUTHMOJI_TRUST_DEVICE_COOKIE_NAME, { maxAge: trustDeviceMaxAge });
120
+ const trustIdentifier = `authmoji-trust-${generateRandomString(32)}`;
121
+ const token = await signHmacBase64Url(ctx.context.secret, `${userId}!${trustIdentifier}`);
122
+ await ctx.context.internalAdapter.createVerificationValue({
123
+ value: userId,
124
+ identifier: trustIdentifier,
125
+ expiresAt: new Date(Date.now() + trustDeviceMaxAge * 1000),
126
+ });
127
+ await ctx.setSignedCookie(trustDeviceCookie.name, `${token}!${trustIdentifier}`, ctx.context.secret, trustDeviceCookie.attributes);
128
+ }
129
+ export async function clearTrustDeviceCookie(ctx, trustDeviceMaxAge) {
130
+ const trustCookie = ctx.context.createAuthCookie(AUTHMOJI_TRUST_DEVICE_COOKIE_NAME, { maxAge: trustDeviceMaxAge });
131
+ const value = await ctx.getSignedCookie(trustCookie.name, ctx.context.secret);
132
+ if (value) {
133
+ const [, trustId] = value.split("!");
134
+ if (trustId) {
135
+ await ctx.context.internalAdapter.deleteVerificationByIdentifier(trustId);
136
+ }
137
+ expireCookie(ctx, trustCookie);
138
+ }
139
+ }
140
+ export async function resolveAuthmojiContext(ctx, trustDeviceMaxAge) {
141
+ const authoritativeSession = await getAuthoritativeSessionFromCtx(ctx);
142
+ const activeSession = authoritativeSession ?? ctx.context.session;
143
+ if (!activeSession) {
144
+ const challengeCookie = ctx.context.createAuthCookie(AUTHMOJI_COOKIE_NAME);
145
+ const signedCookieValue = await ctx.getSignedCookie(challengeCookie.name, ctx.context.secret);
146
+ if (!signedCookieValue) {
147
+ throw APIError.from("UNAUTHORIZED", AUTHMOJI_ERROR_CODES.INVALID_AUTHMOJI_COOKIE);
148
+ }
149
+ const verificationToken = await ctx.context.internalAdapter.findVerificationValue(signedCookieValue);
150
+ if (!verificationToken ||
151
+ new Date(verificationToken.expiresAt).getTime() <= Date.now()) {
152
+ throw APIError.from("UNAUTHORIZED", AUTHMOJI_ERROR_CODES.INVALID_AUTHMOJI_COOKIE);
153
+ }
154
+ const user = await ctx.context.internalAdapter.findUserById(verificationToken.value);
155
+ if (!user) {
156
+ throw APIError.from("UNAUTHORIZED", AUTHMOJI_ERROR_CODES.INVALID_AUTHMOJI_COOKIE);
157
+ }
158
+ const dontRememberMe = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret);
159
+ return {
160
+ session: { session: null, user },
161
+ isSignIn: true,
162
+ key: signedCookieValue,
163
+ complete: async (options) => {
164
+ const consumed = await ctx.context.internalAdapter.consumeVerificationValue(signedCookieValue);
165
+ if (!consumed || consumed.value !== user.id) {
166
+ expireCookie(ctx, challengeCookie);
167
+ throw APIError.from("UNAUTHORIZED", AUTHMOJI_ERROR_CODES.INVALID_AUTHMOJI_COOKIE);
168
+ }
169
+ // Clean up attempt tracker for this challenge.
170
+ await ctx.context.internalAdapter
171
+ .deleteVerificationByIdentifier(`authmoji-attempts-${signedCookieValue}`)
172
+ .catch(() => { });
173
+ if (options?.disableSession) {
174
+ expireCookie(ctx, challengeCookie);
175
+ return {
176
+ token: undefined,
177
+ user: parseUserOutput(ctx.context.options, user),
178
+ };
179
+ }
180
+ const newSession = await ctx.context.internalAdapter.createSession(consumed.value, Boolean(dontRememberMe));
181
+ if (!newSession) {
182
+ throw APIError.from("INTERNAL_SERVER_ERROR", {
183
+ code: "FAILED_TO_CREATE_SESSION",
184
+ message: "Failed to create session",
185
+ });
186
+ }
187
+ await setSessionCookie(ctx, { session: newSession, user });
188
+ expireCookie(ctx, challengeCookie);
189
+ if (options?.trustDevice) {
190
+ await issueTrustDeviceCookie(ctx, user.id, trustDeviceMaxAge);
191
+ expireCookie(ctx, ctx.context.authCookies.dontRememberToken);
192
+ }
193
+ return {
194
+ token: newSession.token,
195
+ user: parseUserOutput(ctx.context.options, user),
196
+ };
197
+ },
198
+ beginAttempt: async (allowedAttempts) => {
199
+ const attemptIdentifier = `authmoji-attempts-${signedCookieValue}`;
200
+ const consumed = await ctx.context.internalAdapter
201
+ .consumeVerificationValue(attemptIdentifier)
202
+ .catch(() => null);
203
+ if (!consumed) {
204
+ throw APIError.from("UNAUTHORIZED", AUTHMOJI_ERROR_CODES.INVALID_AUTHMOJI_COOKIE);
205
+ }
206
+ const parsed = Number(consumed.value);
207
+ const attempts = Number.isInteger(parsed) && parsed >= 0 ? parsed : allowedAttempts;
208
+ if (attempts >= allowedAttempts) {
209
+ await ctx.context.internalAdapter
210
+ .consumeVerificationValue(signedCookieValue)
211
+ .catch(() => null);
212
+ expireCookie(ctx, challengeCookie);
213
+ throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE);
214
+ }
215
+ const rearm = async (count) => {
216
+ await ctx.context.internalAdapter
217
+ .createVerificationValue({
218
+ value: String(count),
219
+ identifier: attemptIdentifier,
220
+ expiresAt: verificationToken.expiresAt,
221
+ })
222
+ .catch(() => { });
223
+ };
224
+ return {
225
+ recordFailure: () => rearm(attempts + 1),
226
+ restore: () => rearm(attempts),
227
+ };
228
+ },
229
+ };
230
+ }
231
+ const user = activeSession.user;
232
+ return {
233
+ session: {
234
+ session: activeSession.session,
235
+ user,
236
+ },
237
+ isSignIn: false,
238
+ key: `${user.id}!${activeSession.session.id}`,
239
+ complete: () => Promise.resolve({
240
+ token: activeSession.session.token,
241
+ user: parseUserOutput(ctx.context.options, user),
242
+ }),
243
+ beginAttempt: () => Promise.resolve({
244
+ recordFailure: () => Promise.resolve(),
245
+ restore: () => Promise.resolve(),
246
+ }),
247
+ };
248
+ }
249
+ function resolveLockoutConfig(options) {
250
+ return {
251
+ enabled: options?.enabled ?? true,
252
+ maxFailedAttempts: options?.maxFailedAttempts ?? 10,
253
+ durationMs: (options?.durationSeconds ?? 900) * 1000,
254
+ };
255
+ }
256
+ export async function assertAuthmojiNotLocked(ctx, tableName, record, lockoutOptions) {
257
+ const { enabled } = resolveLockoutConfig(lockoutOptions);
258
+ if (!enabled || !record.lockedUntil) {
259
+ return;
260
+ }
261
+ if (new Date(record.lockedUntil).getTime() > Date.now()) {
262
+ throw APIError.from("TOO_MANY_REQUESTS", AUTHMOJI_ERROR_CODES.ACCOUNT_TEMPORARILY_LOCKED);
263
+ }
264
+ await ctx.context.adapter.update({
265
+ model: tableName,
266
+ where: [{ field: "id", value: record.id }],
267
+ update: {
268
+ failedVerificationCount: 0,
269
+ lockedUntil: null,
270
+ },
271
+ });
272
+ }
273
+ export async function recordAuthmojiFailure(ctx, tableName, record, lockoutOptions) {
274
+ const { enabled, maxFailedAttempts, durationMs } = resolveLockoutConfig(lockoutOptions);
275
+ if (!enabled) {
276
+ return;
277
+ }
278
+ let nextCount;
279
+ if (typeof ctx.context.adapter.incrementOne === "function") {
280
+ const updated = await ctx.context.adapter.incrementOne({
281
+ model: tableName,
282
+ where: [{ field: "id", value: record.id }],
283
+ increment: { failedVerificationCount: 1 },
284
+ });
285
+ nextCount =
286
+ updated?.failedVerificationCount ??
287
+ (record.failedVerificationCount ?? 0) + 1;
288
+ }
289
+ else {
290
+ nextCount = (record.failedVerificationCount ?? 0) + 1;
291
+ await ctx.context.adapter.update({
292
+ model: tableName,
293
+ where: [{ field: "id", value: record.id }],
294
+ update: { failedVerificationCount: nextCount },
295
+ });
296
+ }
297
+ if (nextCount >= maxFailedAttempts) {
298
+ await ctx.context.adapter.update({
299
+ model: tableName,
300
+ where: [{ field: "id", value: record.id }],
301
+ update: { lockedUntil: new Date(Date.now() + durationMs) },
302
+ });
303
+ }
304
+ }
305
+ export async function resetAuthmojiFailures(ctx, tableName, record, lockoutOptions) {
306
+ const { enabled } = resolveLockoutConfig(lockoutOptions);
307
+ if (!enabled) {
308
+ return;
309
+ }
310
+ await ctx.context.adapter.update({
311
+ model: tableName,
312
+ where: [{ field: "id", value: record.id }],
313
+ update: {
314
+ failedVerificationCount: 0,
315
+ lockedUntil: null,
316
+ },
317
+ });
318
+ }
@@ -0,0 +1,59 @@
1
+ import type { authmoji } from "./server.js";
2
+ import type { AuthmojiClientOptions } from "./types.js";
3
+ /**
4
+ * Better Auth client plugin for Authmoji.
5
+ *
6
+ * Adds typed `authClient.authmoji.*` methods, session reactivity, and automatic
7
+ * handling of Authmoji 2FA sign-in redirects.
8
+ */
9
+ export declare const authmojiClient: (options?: AuthmojiClientOptions) => {
10
+ id: "authmoji";
11
+ $InferServerPlugin: ReturnType<typeof authmoji>;
12
+ atomListeners: {
13
+ matcher: (path: string) => boolean;
14
+ signal: "$sessionSignal";
15
+ }[];
16
+ pathMethods: {
17
+ "/authmoji/enable": "POST";
18
+ "/authmoji/disable": "POST";
19
+ "/authmoji/status": "GET";
20
+ "/authmoji/send-otp": "POST";
21
+ "/authmoji/verify-otp": "POST";
22
+ "/authmoji/get-totp-uri": "POST";
23
+ "/authmoji/get-totp-challenge": "POST";
24
+ "/authmoji/verify-totp": "POST";
25
+ "/authmoji/generate-backup-codes": "POST";
26
+ "/authmoji/verify-backup-code": "POST";
27
+ };
28
+ fetchPlugins: {
29
+ id: string;
30
+ name: string;
31
+ hooks: {
32
+ onSuccess(context: import("better-auth/client").SuccessContext<any>): Promise<void>;
33
+ };
34
+ }[];
35
+ $ERROR_CODES: {
36
+ ACCOUNT_TEMPORARILY_LOCKED: import("./error-codes.js").AuthmojiErrorEntry<"ACCOUNT_TEMPORARILY_LOCKED">;
37
+ AUTHMOJI_NOT_ENABLED: import("./error-codes.js").AuthmojiErrorEntry<"AUTHMOJI_NOT_ENABLED">;
38
+ BACKUP_CODES_NOT_ENABLED: import("./error-codes.js").AuthmojiErrorEntry<"BACKUP_CODES_NOT_ENABLED">;
39
+ INVALID_AUTHMOJI_COOKIE: import("./error-codes.js").AuthmojiErrorEntry<"INVALID_AUTHMOJI_COOKIE">;
40
+ INVALID_BACKUP_CODE: import("./error-codes.js").AuthmojiErrorEntry<"INVALID_BACKUP_CODE">;
41
+ INVALID_CODE: import("./error-codes.js").AuthmojiErrorEntry<"INVALID_CODE">;
42
+ INVALID_PASSWORD: import("./error-codes.js").AuthmojiErrorEntry<"INVALID_PASSWORD">;
43
+ OTP_HAS_EXPIRED: import("./error-codes.js").AuthmojiErrorEntry<"OTP_HAS_EXPIRED">;
44
+ OTP_NOT_CONFIGURED: import("./error-codes.js").AuthmojiErrorEntry<"OTP_NOT_CONFIGURED">;
45
+ TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE: import("./error-codes.js").AuthmojiErrorEntry<"TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE">;
46
+ TOTP_ALREADY_ENABLED: import("./error-codes.js").AuthmojiErrorEntry<"TOTP_ALREADY_ENABLED">;
47
+ TOTP_CHOICES_DISABLED: import("./error-codes.js").AuthmojiErrorEntry<"TOTP_CHOICES_DISABLED">;
48
+ TOTP_NOT_CONFIGURED: import("./error-codes.js").AuthmojiErrorEntry<"TOTP_NOT_CONFIGURED">;
49
+ TOTP_NOT_ENABLED: import("./error-codes.js").AuthmojiErrorEntry<"TOTP_NOT_ENABLED">;
50
+ UNAUTHORIZED: import("./error-codes.js").AuthmojiErrorEntry<"UNAUTHORIZED">;
51
+ };
52
+ };
53
+ export { extractEmojisFromText, formatEmojiSequence, getDefaultEmojis, getEmojisFromDataset, normalizeEmoji, parseEmojiSequence, resolveEmojiPool, } from "./emojis.js";
54
+ export type { EmojiDatasetEntry, EmojiPoolInput, GetEmojisOptions, } from "./emojis.js";
55
+ export { AUTHMOJI_ERROR_CODES } from "./error-codes.js";
56
+ export type { AuthmojiErrorCode, AuthmojiErrorEntry } from "./error-codes.js";
57
+ export { createAuthmojiTOTPURI, generateEmojiTOTP, generateEmojiTOTPChoices, parseAuthmojiTOTPURI, verifyEmojiTOTP, } from "./totp.js";
58
+ export type { AuthmojiTOTPURIParams, EmojiTOTPChoicesOptions, EmojiTOTPChoicesResult, EmojiTOTPOptions, EmojiTOTPResult, ParsedAuthmojiTOTPURI, TOTPAlgorithm, VerifyEmojiTOTPOptions, VerifyEmojiTOTPResult, } from "./totp.js";
59
+ export type { AuthmojiClientOptions, AuthmojiMethod, AuthmojiRedirectContext, } from "./types.js";
package/dist/client.js ADDED
@@ -0,0 +1,74 @@
1
+ import { AUTHMOJI_ERROR_CODES } from "./error-codes.js";
2
+ function isSafeRedirectUrl(url) {
3
+ if (url.startsWith("/") && !url.startsWith("//")) {
4
+ return true;
5
+ }
6
+ try {
7
+ const parsed = new URL(url);
8
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
9
+ }
10
+ catch {
11
+ return false;
12
+ }
13
+ }
14
+ /**
15
+ * Better Auth client plugin for Authmoji.
16
+ *
17
+ * Adds typed `authClient.authmoji.*` methods, session reactivity, and automatic
18
+ * handling of Authmoji 2FA sign-in redirects.
19
+ */
20
+ export const authmojiClient = (options) => {
21
+ return {
22
+ id: "authmoji",
23
+ $InferServerPlugin: {},
24
+ atomListeners: [
25
+ {
26
+ matcher: (path) => path.startsWith("/authmoji/"),
27
+ signal: "$sessionSignal",
28
+ },
29
+ ],
30
+ pathMethods: {
31
+ "/authmoji/enable": "POST",
32
+ "/authmoji/disable": "POST",
33
+ "/authmoji/status": "GET",
34
+ "/authmoji/send-otp": "POST",
35
+ "/authmoji/verify-otp": "POST",
36
+ "/authmoji/get-totp-uri": "POST",
37
+ "/authmoji/get-totp-challenge": "POST",
38
+ "/authmoji/verify-totp": "POST",
39
+ "/authmoji/generate-backup-codes": "POST",
40
+ "/authmoji/verify-backup-code": "POST",
41
+ },
42
+ fetchPlugins: [
43
+ {
44
+ id: "authmoji",
45
+ name: "authmoji",
46
+ hooks: {
47
+ async onSuccess(context) {
48
+ const data = context.data;
49
+ if (!data?.authmojiRedirect && !data?.twoFactorRedirect) {
50
+ return;
51
+ }
52
+ const methods = data.methods ?? data.twoFactorMethods ?? [];
53
+ if (options?.onTwoFactorRedirect) {
54
+ await options.onTwoFactorRedirect({
55
+ methods,
56
+ twoFactorMethods: methods,
57
+ });
58
+ return;
59
+ }
60
+ if (options?.twoFactorPage &&
61
+ typeof window !== "undefined" &&
62
+ isSafeRedirectUrl(options.twoFactorPage)) {
63
+ window.location.href = options.twoFactorPage;
64
+ }
65
+ },
66
+ },
67
+ },
68
+ ],
69
+ $ERROR_CODES: AUTHMOJI_ERROR_CODES,
70
+ };
71
+ };
72
+ export { extractEmojisFromText, formatEmojiSequence, getDefaultEmojis, getEmojisFromDataset, normalizeEmoji, parseEmojiSequence, resolveEmojiPool, } from "./emojis.js";
73
+ export { AUTHMOJI_ERROR_CODES } from "./error-codes.js";
74
+ export { createAuthmojiTOTPURI, generateEmojiTOTP, generateEmojiTOTPChoices, parseAuthmojiTOTPURI, verifyEmojiTOTP, } from "./totp.js";
@@ -0,0 +1,97 @@
1
+ import type { CompactEmoji, Emoji, GroupKey } from "emojibase";
2
+ export type EmojiDatasetEntry = CompactEmoji | Emoji;
3
+ /**
4
+ * Accepted emoji alphabet input: plain emoji strings or an Emojibase dataset
5
+ * (`CompactEmoji[]` from `compact.json` or `Emoji[]` from `data.json`).
6
+ */
7
+ export type EmojiPoolInput = readonly string[] | readonly CompactEmoji[] | readonly Emoji[];
8
+ export interface GetEmojisOptions {
9
+ /**
10
+ * Filter the Emojibase dataset to specific groups (e.g. `["smileys-emotion", "animals-nature"]`).
11
+ * Defaults to all standalone emoji groups (excluding `"component"` and uncategorized regional indicators).
12
+ */
13
+ groups?: readonly GroupKey[];
14
+ /**
15
+ * Include Unicode component entries (skin tones, hair styles).
16
+ * @default false
17
+ */
18
+ includeComponents?: boolean;
19
+ }
20
+ export interface EmojiChallenge {
21
+ /** Ordered emoji array the user must match. */
22
+ emojis: string[];
23
+ /** Concatenated emoji string (e.g. `"😍🤩🍣"`). */
24
+ code: string;
25
+ /** Shuffled tap-grid options containing the answer plus distractors. Empty when `choiceCount` is `0`. */
26
+ choices: string[];
27
+ }
28
+ export interface GenerateEmojiChallengeOptions {
29
+ /** Custom emoji alphabet or Emojibase dataset. Defaults to `getDefaultEmojis()`. */
30
+ emojis?: EmojiPoolInput;
31
+ /** Filter default Emojibase dataset by group keys when `emojis` is omitted. */
32
+ groups?: readonly GroupKey[];
33
+ /** Number of emojis in the secret answer sequence. @default 3 */
34
+ length?: number;
35
+ /**
36
+ * Number of shuffled emojis returned as tap-grid choices.
37
+ * Set to `0` to omit choices.
38
+ * @default 8
39
+ */
40
+ choiceCount?: number;
41
+ }
42
+ /**
43
+ * Extracts standalone emoji characters from an Emojibase dataset (`compact.json` or `data.json`),
44
+ * excluding uncategorized regional indicators and (by default) non-standalone components.
45
+ */
46
+ export declare function getEmojisFromDataset(dataset?: readonly EmojiDatasetEntry[], options?: GetEmojisOptions): readonly string[];
47
+ /**
48
+ * Returns the default emoji alphabet derived from `emojibase-data/en/compact.json`.
49
+ */
50
+ export declare function getDefaultEmojis(options?: GetEmojisOptions): readonly string[];
51
+ /**
52
+ * Resolves either a string array, an Emojibase dataset (`CompactEmoji[]` / `Emoji[]`),
53
+ * or optional Emojibase group filter into a string array of emoji characters.
54
+ */
55
+ export declare function resolveEmojiPool(emojis?: EmojiPoolInput, groups?: readonly GroupKey[]): readonly string[];
56
+ /**
57
+ * Normalizes an emoji for comparison by applying NFC normalization and
58
+ * stripping optional emoji variation selectors (U+FE0F).
59
+ */
60
+ export declare function normalizeEmoji(emoji: string): string;
61
+ /**
62
+ * Validates that an emoji pool contains at least `minSize` unique emojis
63
+ * (after variation-selector normalization).
64
+ */
65
+ export declare function assertValidEmojiPool(emojis: readonly string[], minSize: number): readonly string[];
66
+ /**
67
+ * Cryptographically secure unbiased integer in `[0, maxExclusive)`.
68
+ */
69
+ export declare function cryptoRandomInt(maxExclusive: number): number;
70
+ /**
71
+ * Cryptographically secure Fisher-Yates shuffle returning a new array.
72
+ */
73
+ export declare function cryptoShuffle<T>(items: readonly T[]): T[];
74
+ /**
75
+ * Generates a cryptographically random Authmoji challenge with an ordered
76
+ * answer sequence and an optional shuffled choice grid.
77
+ */
78
+ export declare function generateEmojiChallenge(options?: GenerateEmojiChallengeOptions): EmojiChallenge;
79
+ /**
80
+ * Strictly parses an emoji sequence from either an array of emojis or a
81
+ * string (concatenated or separated by commas/spaces/hyphens).
82
+ * Returns `null` if the input contains unrecognized characters or non-pool emojis.
83
+ */
84
+ export declare function parseEmojiSequence(input: string | readonly string[], pool?: EmojiPoolInput): string[] | null;
85
+ /**
86
+ * Leniently extracts recognized emojis from arbitrary text such as SMS
87
+ * messages or WebOTP autofill payloads.
88
+ */
89
+ export declare function extractEmojisFromText(text: string, pool?: EmojiPoolInput): string[];
90
+ /**
91
+ * Formats an emoji array as a string (default concatenated with no separator).
92
+ */
93
+ export declare function formatEmojiSequence(emojis: readonly string[], separator?: string): string;
94
+ /**
95
+ * Canonical normalized representation used for hashing and constant-time comparison.
96
+ */
97
+ export declare function canonicalizeEmojiSequence(emojis: readonly string[]): string;