@authmoji/better-auth 0.0.0 → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ShipWorthyAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,195 @@
1
+ # `@authmoji/better-auth`
2
+
3
+ Self-hosted emoji two-factor authentication (**OTP** and **TOTP**) plugin for [Better Auth](https://better-auth.com).
4
+
5
+ Instead of typing 6-digit numeric codes, users verify sign-ins by tapping or entering short, memorable emoji sequences — running completely inside your own infrastructure with Better Auth's database, sessions, and security primitives.
6
+
7
+ ## Features
8
+
9
+ - **Emoji OTP**: Generates cryptographically random emoji sequences, delivers the answer via your own SMS/email/push callback (`sendOTP`), and returns a shuffled emoji tap-grid (`choices`) without exposing the answer.
10
+ - **Emoji TOTP**: Web Crypto RFC 6238-style time-based emoji codes (`authmoji://totp/...` URIs), clock-skew window verification, deterministic tap-grid choices (resistant to set-intersection leaks), and counter-based replay protection.
11
+ - **Recovery Backup Codes**: Single-use alphanumeric or emoji recovery codes stored encrypted at rest.
12
+ - **Trusted Devices & Account Lockout**: Rotating HMAC-signed trusted-device cookies, per-challenge attempt limits, account-level lockout, and rate limiting.
13
+ - **Universal Runtime**: Zero Node-only dependencies — works in Node.js, Bun, Deno, Cloudflare Workers, Vercel Functions, and browsers.
14
+
15
+ ## Installation
16
+
17
+ ```sh
18
+ npm install @authmoji/better-auth better-auth
19
+ # or
20
+ bun add @authmoji/better-auth better-auth
21
+ ```
22
+
23
+ ## Quick Start
24
+
25
+ ### 1. Server Setup (`auth.ts`)
26
+
27
+ ```ts
28
+ import { authmoji } from "@authmoji/better-auth";
29
+ import { betterAuth } from "better-auth";
30
+
31
+ export const auth = betterAuth({
32
+ appName: "My App",
33
+ database: /* your database adapter */,
34
+ emailAndPassword: { enabled: true },
35
+ plugins: [
36
+ authmoji({
37
+ issuer: "My App",
38
+ otpOptions: {
39
+ // Deliver emoji OTP codes via SMS, email, push, Slack, etc.
40
+ sendOTP: async ({ user, code, emojis }) => {
41
+ await sendSMS(
42
+ user.phone,
43
+ `${code} is your Authmoji.\n\n@myapp.com #${code}`
44
+ );
45
+ },
46
+ },
47
+ totpOptions: {
48
+ length: 3, // 3 emojis from Emojibase (~32.7 bits of entropy, > 6-digit numeric TOTP)
49
+ choiceCount: 8, // 8-tile deterministic tap grid (set 0 to disable)
50
+ period: 30,
51
+ },
52
+ // Optional: restrict to specific Emojibase groups or pass a custom dataset
53
+ // emojiGroups: ["smileys-emotion", "animals-nature", "food-drink"],
54
+ }),
55
+ ],
56
+ });
57
+ ```
58
+
59
+ ### 2. Migrate Schema
60
+
61
+ Run the Better Auth CLI to add `user.authmojiEnabled` and the `authmoji` table to your database:
62
+
63
+ ```sh
64
+ npx auth@latest migrate
65
+ # or with Drizzle / Prisma:
66
+ npx auth@latest generate
67
+ ```
68
+
69
+ ### 3. Client Setup (`auth-client.ts`)
70
+
71
+ ```ts
72
+ import { authmojiClient } from "@authmoji/better-auth/client";
73
+ import { createAuthClient } from "better-auth/react";
74
+
75
+ export const authClient = createAuthClient({
76
+ plugins: [
77
+ authmojiClient({
78
+ onTwoFactorRedirect({ methods }) {
79
+ // Redirect to your Authmoji verification screen
80
+ window.location.href = `/verify-authmoji?methods=${methods.join(",")}`;
81
+ },
82
+ }),
83
+ ],
84
+ });
85
+ ```
86
+
87
+ ## Usage
88
+
89
+ ### OTP Flow
90
+
91
+ ```ts
92
+ // 1. Enable OTP for the signed-in user
93
+ await authClient.authmoji.enable({
94
+ password: userPassword,
95
+ method: "otp",
96
+ });
97
+
98
+ // 2. On sign-in, Better Auth intercepts the session and triggers onTwoFactorRedirect.
99
+ // Request an emoji OTP challenge to render the tap grid:
100
+ const { data } = await authClient.authmoji.sendOtp();
101
+ // data => { status: true, choices: ["🦊", "🚀", "🍕", ...], length: 3, expiresAt: "..." }
102
+
103
+ // 3. Submit the emojis the user tapped (or autofilled as a string):
104
+ await authClient.authmoji.verifyOtp({
105
+ emojis: ["😍", "🤩", "🍣"], // or code: "😍🤩🍣"
106
+ trustDevice: true,
107
+ });
108
+ ```
109
+
110
+ ### TOTP Flow
111
+
112
+ ```ts
113
+ // 1. Enroll TOTP — returns Base32 secret, authmoji://totp/... URI, and backup codes
114
+ const { data } = await authClient.authmoji.enable({
115
+ password: userPassword,
116
+ method: "totp",
117
+ });
118
+ // data => { method: "totp", secret, totpURI, backupCodes, period: 30, length: 3 }
119
+
120
+ // 2. Confirm setup by verifying the current TOTP emoji sequence
121
+ await authClient.authmoji.verifyTotp({
122
+ emojis: selectedEmojis, // or code: "😍🤩🍣"
123
+ });
124
+
125
+ // 3. During sign-in, optionally fetch the deterministic tap grid for the current time step:
126
+ const challenge = await authClient.authmoji.getTotpChallenge();
127
+ // challenge.data => { choices: [...], length: 3, period: 30, expiresAt: "..." }
128
+
129
+ // 4. Verify the TOTP sequence to complete sign-in
130
+ await authClient.authmoji.verifyTotp({
131
+ emojis: selectedEmojis,
132
+ trustDevice: true,
133
+ });
134
+ ```
135
+
136
+ ### Backup Codes & Management
137
+
138
+ ```ts
139
+ // Inspect enrollment status
140
+ const { data: status } = await authClient.authmoji.status();
141
+
142
+ // Verify a recovery backup code during sign-in
143
+ await authClient.authmoji.verifyBackupCode({ code: "abcde-12345" });
144
+
145
+ // Rotate backup codes
146
+ await authClient.authmoji.generateBackupCodes({ password: userPassword });
147
+
148
+ // Re-fetch TOTP URI
149
+ await authClient.authmoji.getTotpUri({ password: userPassword });
150
+
151
+ // Disable Authmoji 2FA
152
+ await authClient.authmoji.disable({ password: userPassword });
153
+ ```
154
+
155
+ ## Standalone Utilities
156
+
157
+ `@authmoji/better-auth` exports zero-dependency subpaths for authenticators, CLIs, and UI components:
158
+
159
+ - `@authmoji/better-auth/totp`: `generateTOTPSecret`, `generateEmojiTOTP`, `generateEmojiTOTPChoices`, `verifyEmojiTOTP`, `createAuthmojiTOTPURI`, `parseAuthmojiTOTPURI`, `encodeBase32`, `decodeBase32`
160
+ - `@authmoji/better-auth/emojis`: `getDefaultEmojis`, `getEmojisFromDataset`, `resolveEmojiPool`, `generateEmojiChallenge`, `parseEmojiSequence`, `extractEmojisFromText`, `formatEmojiSequence`, `normalizeEmoji` (backed by [Emojibase](https://emojibase.dev/))
161
+
162
+ ```ts
163
+ import {
164
+ generateEmojiTOTP,
165
+ parseAuthmojiTOTPURI,
166
+ } from "@authmoji/better-auth/totp";
167
+
168
+ const parsed = parseAuthmojiTOTPURI(totpURI);
169
+ const { emojis, code, expiresAt } = await generateEmojiTOTP(parsed.secret, {
170
+ period: parsed.period,
171
+ length: parsed.length,
172
+ algorithm: parsed.algorithm,
173
+ });
174
+ ```
175
+
176
+ ## Endpoints Reference
177
+
178
+ | Endpoint | Method | Client Method | Server Method |
179
+ | --------------------------------- | ------ | ------------------------------------------- | ---------------------------------------- |
180
+ | `/authmoji/enable` | `POST` | `authClient.authmoji.enable()` | `auth.api.enableAuthmoji()` |
181
+ | `/authmoji/disable` | `POST` | `authClient.authmoji.disable()` | `auth.api.disableAuthmoji()` |
182
+ | `/authmoji/status` | `GET` | `authClient.authmoji.status()` | `auth.api.getAuthmojiStatus()` |
183
+ | `/authmoji/send-otp` | `POST` | `authClient.authmoji.sendOtp()` | `auth.api.sendAuthmojiOTP()` |
184
+ | `/authmoji/verify-otp` | `POST` | `authClient.authmoji.verifyOtp()` | `auth.api.verifyAuthmojiOTP()` |
185
+ | `/authmoji/get-totp-uri` | `POST` | `authClient.authmoji.getTotpUri()` | `auth.api.getAuthmojiTOTPURI()` |
186
+ | `/authmoji/get-totp-challenge` | `POST` | `authClient.authmoji.getTotpChallenge()` | `auth.api.getAuthmojiTOTPChallenge()` |
187
+ | `/authmoji/verify-totp` | `POST` | `authClient.authmoji.verifyTotp()` | `auth.api.verifyAuthmojiTOTP()` |
188
+ | `/authmoji/generate-backup-codes` | `POST` | `authClient.authmoji.generateBackupCodes()` | `auth.api.generateAuthmojiBackupCodes()` |
189
+ | `/authmoji/verify-backup-code` | `POST` | `authClient.authmoji.verifyBackupCode()` | `auth.api.verifyAuthmojiBackupCode()` |
190
+ | _(server-only)_ | — | — | `auth.api.generateAuthmojiTOTP()` |
191
+ | _(server-only)_ | — | — | `auth.api.viewAuthmojiBackupCodes()` |
192
+
193
+ ## License
194
+
195
+ MIT
@@ -0,0 +1,18 @@
1
+ import type { SecretConfig } from "better-auth/crypto";
2
+ import type { AuthmojiBackupCodeOptions } from "./types.js";
3
+ export declare function encodeBackupCodes(codes: string[], key: string | SecretConfig, options?: AuthmojiBackupCodeOptions): Promise<string>;
4
+ export declare function generateBackupCodes(key: string | SecretConfig, options: AuthmojiBackupCodeOptions | undefined, emojiPool?: readonly string[]): Promise<{
5
+ backupCodes: string[];
6
+ encryptedBackupCodes: string;
7
+ }>;
8
+ export declare function decodeBackupCodes(stored: string, key: string | SecretConfig, options?: AuthmojiBackupCodeOptions): Promise<string[] | null>;
9
+ export declare function verifyAndConsumeBackupCode(params: {
10
+ storedBackupCodes: string;
11
+ submittedCode: string;
12
+ key: string | SecretConfig;
13
+ options?: AuthmojiBackupCodeOptions;
14
+ emojiPool?: readonly string[];
15
+ }): Promise<{
16
+ valid: boolean;
17
+ remaining: string[] | null;
18
+ }>;
@@ -0,0 +1,108 @@
1
+ import { constantTimeEqual, generateRandomString, symmetricDecrypt, symmetricEncrypt, } from "better-auth/crypto";
2
+ import { canonicalizeEmojiSequence, generateEmojiChallenge, getDefaultEmojis, parseEmojiSequence, } from "./emojis.js";
3
+ const TEXT_ENCODER = new TextEncoder();
4
+ function generateDefaultBackupCodes(options, emojiPool) {
5
+ const amount = options?.amount ?? 10;
6
+ const format = options?.format ?? "alphanumeric";
7
+ if (format === "emoji") {
8
+ const length = options?.length ?? 6;
9
+ return Array.from({ length: amount }, () => {
10
+ const challenge = generateEmojiChallenge({
11
+ emojis: emojiPool,
12
+ length,
13
+ choiceCount: 0,
14
+ });
15
+ return challenge.code;
16
+ });
17
+ }
18
+ const length = options?.length ?? 10;
19
+ const splitAt = Math.floor(length / 2);
20
+ return Array.from({ length: amount }, () => {
21
+ const raw = generateRandomString(length, "a-z", "0-9", "A-Z");
22
+ return splitAt > 0 ? `${raw.slice(0, splitAt)}-${raw.slice(splitAt)}` : raw;
23
+ });
24
+ }
25
+ export async function encodeBackupCodes(codes, key, options) {
26
+ const json = JSON.stringify(codes);
27
+ const store = options?.storeBackupCodes ?? "encrypted";
28
+ if (store === "encrypted") {
29
+ return symmetricEncrypt({ data: json, key });
30
+ }
31
+ if (typeof store === "object" && "encrypt" in store) {
32
+ return store.encrypt(json);
33
+ }
34
+ return json;
35
+ }
36
+ export async function generateBackupCodes(key, options, emojiPool = getDefaultEmojis()) {
37
+ const backupCodes = options?.customBackupCodesGenerate
38
+ ? options.customBackupCodesGenerate()
39
+ : generateDefaultBackupCodes(options, emojiPool);
40
+ return {
41
+ backupCodes,
42
+ encryptedBackupCodes: await encodeBackupCodes(backupCodes, key, options),
43
+ };
44
+ }
45
+ export async function decodeBackupCodes(stored, key, options) {
46
+ const store = options?.storeBackupCodes ?? "encrypted";
47
+ let raw;
48
+ try {
49
+ if (store === "encrypted") {
50
+ raw = await symmetricDecrypt({ key, data: stored });
51
+ }
52
+ else if (typeof store === "object" && "decrypt" in store) {
53
+ raw = await store.decrypt(stored);
54
+ }
55
+ else {
56
+ raw = stored;
57
+ }
58
+ const parsed = JSON.parse(raw);
59
+ if (!Array.isArray(parsed)) {
60
+ return null;
61
+ }
62
+ return parsed.filter((item) => typeof item === "string");
63
+ }
64
+ catch {
65
+ return null;
66
+ }
67
+ }
68
+ function normalizeCodeForFormat(code, format, emojiPool) {
69
+ const trimmed = code.trim();
70
+ if (!trimmed) {
71
+ return null;
72
+ }
73
+ if (format === "emoji") {
74
+ const parsed = parseEmojiSequence(trimmed, emojiPool);
75
+ return parsed ? canonicalizeEmojiSequence(parsed) : null;
76
+ }
77
+ return trimmed;
78
+ }
79
+ export async function verifyAndConsumeBackupCode(params) {
80
+ const { storedBackupCodes, submittedCode, key, options, emojiPool = getDefaultEmojis(), } = params;
81
+ const codes = await decodeBackupCodes(storedBackupCodes, key, options);
82
+ if (!codes || codes.length === 0) {
83
+ return { valid: false, remaining: null };
84
+ }
85
+ const format = options?.format ?? "alphanumeric";
86
+ const normalizedSubmitted = normalizeCodeForFormat(submittedCode, format, emojiPool);
87
+ if (!normalizedSubmitted) {
88
+ return { valid: false, remaining: null };
89
+ }
90
+ const submittedBytes = TEXT_ENCODER.encode(normalizedSubmitted);
91
+ let matchedIndex = -1;
92
+ for (let i = 0; i < codes.length; i += 1) {
93
+ const normalizedCandidate = normalizeCodeForFormat(codes[i], format, emojiPool);
94
+ if (!normalizedCandidate) {
95
+ continue;
96
+ }
97
+ const candidateBytes = TEXT_ENCODER.encode(normalizedCandidate);
98
+ if (constantTimeEqual(candidateBytes, submittedBytes) &&
99
+ matchedIndex === -1) {
100
+ matchedIndex = i;
101
+ }
102
+ }
103
+ if (matchedIndex === -1) {
104
+ return { valid: false, remaining: null };
105
+ }
106
+ const remaining = codes.filter((_, index) => index !== matchedIndex);
107
+ return { valid: true, remaining };
108
+ }
@@ -0,0 +1,45 @@
1
+ import type { GenericEndpointContext, Session } from "better-auth";
2
+ import type { SecretConfig } from "better-auth/crypto";
3
+ import type { AuthmojiAccountLockoutOptions, AuthmojiRecord, StoreOTPOption, UserWithAuthmoji } from "./types.js";
4
+ export declare const AUTHMOJI_COOKIE_NAME = "authmoji_two_factor";
5
+ export declare const AUTHMOJI_TRUST_DEVICE_COOKIE_NAME = "authmoji_trust_device";
6
+ export declare const DEFAULT_TRUST_DEVICE_MAX_AGE: number;
7
+ export declare const DEFAULT_AUTHMOJI_COOKIE_MAX_AGE = 600;
8
+ export declare function getEncryptionKey(ctx: GenericEndpointContext): string | SecretConfig;
9
+ export declare function signHmacBase64Url(secret: string, payload: string): Promise<string>;
10
+ export declare function verifyHmacBase64Url(secret: string, payload: string, expectedToken: string): Promise<boolean>;
11
+ export declare function encodeStoredOTP(ctx: GenericEndpointContext, canonicalAnswer: string, storeOTP: StoreOTPOption): Promise<string>;
12
+ export declare function compareStoredOTP(ctx: GenericEndpointContext, storedValue: string, submittedCanonical: string, storeOTP: StoreOTPOption): Promise<boolean>;
13
+ export declare function shouldRequirePassword(ctx: GenericEndpointContext, userId: string, allowPasswordless: boolean): Promise<boolean>;
14
+ export declare function assertValidPasswordIfRequired(ctx: GenericEndpointContext, userId: string, password: string | undefined, allowPasswordless: boolean): Promise<void>;
15
+ export declare function rotateSessionWithUser(ctx: GenericEndpointContext, currentSession: Session & Record<string, unknown>, updatedUser: UserWithAuthmoji): Promise<Session>;
16
+ export declare function issueTrustDeviceCookie(ctx: GenericEndpointContext, userId: string, trustDeviceMaxAge: number): Promise<void>;
17
+ export declare function clearTrustDeviceCookie(ctx: GenericEndpointContext, trustDeviceMaxAge: number): Promise<void>;
18
+ export interface AttemptLease {
19
+ recordFailure: () => Promise<void>;
20
+ restore: () => Promise<void>;
21
+ }
22
+ export interface ResolvedAuthmojiContext {
23
+ session: {
24
+ session: (Session & Record<string, unknown>) | null;
25
+ user: UserWithAuthmoji;
26
+ };
27
+ /** True when completing a pending sign-in 2FA challenge (no active session yet). */
28
+ isSignIn: boolean;
29
+ /** Unique challenge scope key for verification storage. */
30
+ key: string;
31
+ /** Completes the pending sign-in (creating session + optional trust cookie) or returns the active session. */
32
+ complete: (options?: {
33
+ trustDevice?: boolean;
34
+ disableSession?: boolean;
35
+ }) => Promise<{
36
+ token: string | undefined;
37
+ user: UserWithAuthmoji;
38
+ }>;
39
+ /** Atomically reserves an attempt against the pending 2FA sign-in cookie. */
40
+ beginAttempt: (allowedAttempts: number) => Promise<AttemptLease>;
41
+ }
42
+ export declare function resolveAuthmojiContext(ctx: GenericEndpointContext, trustDeviceMaxAge: number): Promise<ResolvedAuthmojiContext>;
43
+ export declare function assertAuthmojiNotLocked(ctx: GenericEndpointContext, tableName: string, record: AuthmojiRecord, lockoutOptions?: AuthmojiAccountLockoutOptions): Promise<void>;
44
+ export declare function recordAuthmojiFailure(ctx: GenericEndpointContext, tableName: string, record: AuthmojiRecord, lockoutOptions?: AuthmojiAccountLockoutOptions): Promise<void>;
45
+ export declare function resetAuthmojiFailures(ctx: GenericEndpointContext, tableName: string, record: AuthmojiRecord, lockoutOptions?: AuthmojiAccountLockoutOptions): Promise<void>;