@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/LICENSE +21 -0
- package/README.md +194 -2
- package/dist/backup-codes.d.ts +18 -0
- package/dist/backup-codes.js +108 -0
- package/dist/challenge.d.ts +45 -0
- package/dist/challenge.js +318 -0
- package/dist/client.d.ts +59 -0
- package/dist/client.js +74 -0
- package/dist/emojis.d.ts +97 -0
- package/dist/emojis.js +285 -0
- package/dist/error-codes.d.ts +23 -0
- package/dist/error-codes.js +28 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +5 -0
- package/dist/schema.d.ts +62 -0
- package/dist/schema.js +62 -0
- package/dist/server.d.ts +494 -0
- package/dist/server.js +934 -0
- package/dist/totp.d.ts +122 -0
- package/dist/totp.js +383 -0
- package/dist/types.d.ts +250 -0
- package/dist/types.js +1 -0
- package/package.json +81 -4
package/dist/server.js
ADDED
|
@@ -0,0 +1,934 @@
|
|
|
1
|
+
import { APIError, createAuthEndpoint, createAuthMiddleware, getAuthoritativeSessionFromCtx, sensitiveSessionMiddleware, sessionMiddleware, } from "better-auth/api";
|
|
2
|
+
import { deleteSessionCookie, expireCookie } from "better-auth/cookies";
|
|
3
|
+
import { generateRandomString, symmetricDecrypt, symmetricEncrypt, } from "better-auth/crypto";
|
|
4
|
+
import { mergeSchema, parseUserOutput } from "better-auth/db";
|
|
5
|
+
import * as z from "zod";
|
|
6
|
+
import { decodeBackupCodes, encodeBackupCodes, generateBackupCodes, verifyAndConsumeBackupCode, } from "./backup-codes.js";
|
|
7
|
+
import { assertAuthmojiNotLocked, assertValidPasswordIfRequired, AUTHMOJI_COOKIE_NAME, AUTHMOJI_TRUST_DEVICE_COOKIE_NAME, clearTrustDeviceCookie, compareStoredOTP, DEFAULT_AUTHMOJI_COOKIE_MAX_AGE, DEFAULT_TRUST_DEVICE_MAX_AGE, encodeStoredOTP, getEncryptionKey, issueTrustDeviceCookie, recordAuthmojiFailure, resetAuthmojiFailures, resolveAuthmojiContext, rotateSessionWithUser, verifyHmacBase64Url, } from "./challenge.js";
|
|
8
|
+
import { assertValidEmojiPool, canonicalizeEmojiSequence, generateEmojiChallenge, parseEmojiSequence, resolveEmojiPool, } from "./emojis.js";
|
|
9
|
+
import { AUTHMOJI_ERROR_CODES } from "./error-codes.js";
|
|
10
|
+
import { authmojiSchema } from "./schema.js";
|
|
11
|
+
import { createAuthmojiTOTPURI, generateEmojiTOTP, generateEmojiTOTPChoices, generateTOTPSecret, verifyEmojiTOTP, } from "./totp.js";
|
|
12
|
+
const DEFAULT_SIGN_IN_PATHS = [
|
|
13
|
+
"/sign-in/email",
|
|
14
|
+
"/sign-in/username",
|
|
15
|
+
"/sign-in/phone-number",
|
|
16
|
+
];
|
|
17
|
+
const signInAuthmojiStates = new WeakMap();
|
|
18
|
+
async function readSignInAuthmojiState(ctx, trustDeviceMaxAge) {
|
|
19
|
+
const data = ctx.context.newSession;
|
|
20
|
+
const user = data?.user;
|
|
21
|
+
if (!user?.authmojiEnabled) {
|
|
22
|
+
return { requiresAuthmoji: false, trustDeviceCookie: null };
|
|
23
|
+
}
|
|
24
|
+
const cookie = ctx.context.createAuthCookie(AUTHMOJI_TRUST_DEVICE_COOKIE_NAME, { maxAge: trustDeviceMaxAge });
|
|
25
|
+
const trustDeviceCookie = await ctx.getSignedCookie(cookie.name, ctx.context.secret);
|
|
26
|
+
if (!trustDeviceCookie) {
|
|
27
|
+
return { requiresAuthmoji: true, trustDeviceCookie: null };
|
|
28
|
+
}
|
|
29
|
+
const [token, trustIdentifier] = trustDeviceCookie.split("!");
|
|
30
|
+
if (!token || !trustIdentifier) {
|
|
31
|
+
return { requiresAuthmoji: true, trustDeviceCookie };
|
|
32
|
+
}
|
|
33
|
+
const isValidSignature = await verifyHmacBase64Url(ctx.context.secret, `${user.id}!${trustIdentifier}`, token);
|
|
34
|
+
if (!isValidSignature) {
|
|
35
|
+
return { requiresAuthmoji: true, trustDeviceCookie };
|
|
36
|
+
}
|
|
37
|
+
const verificationRecord = await ctx.context.internalAdapter.findVerificationValue(trustIdentifier);
|
|
38
|
+
const isStillTrusted = Boolean(verificationRecord) &&
|
|
39
|
+
verificationRecord.value === user.id &&
|
|
40
|
+
new Date(verificationRecord.expiresAt).getTime() > Date.now();
|
|
41
|
+
return {
|
|
42
|
+
requiresAuthmoji: !isStillTrusted,
|
|
43
|
+
trustDeviceCookie,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function serializeOTPPayload(payload) {
|
|
47
|
+
return JSON.stringify(payload);
|
|
48
|
+
}
|
|
49
|
+
function parseOTPPayload(raw) {
|
|
50
|
+
try {
|
|
51
|
+
const parsed = JSON.parse(raw);
|
|
52
|
+
if (typeof parsed === "object" &&
|
|
53
|
+
parsed !== null &&
|
|
54
|
+
"answer" in parsed &&
|
|
55
|
+
"attempts" in parsed &&
|
|
56
|
+
typeof parsed.answer === "string" &&
|
|
57
|
+
typeof parsed.attempts === "number" &&
|
|
58
|
+
Number.isInteger(parsed.attempts) &&
|
|
59
|
+
parsed.attempts >= 0) {
|
|
60
|
+
return { answer: parsed.answer, attempts: parsed.attempts };
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const emojiVerificationBodySchema = z
|
|
69
|
+
.object({
|
|
70
|
+
code: z.string().optional().meta({
|
|
71
|
+
description: 'Emoji sequence as a string (concatenated or comma-separated), e.g. "😍🤩🍣" or "😍,🤩,🍣".',
|
|
72
|
+
}),
|
|
73
|
+
emojis: z.array(z.string()).optional().meta({
|
|
74
|
+
description: 'Ordered emoji array, e.g. ["😍", "🤩", "🍣"].',
|
|
75
|
+
}),
|
|
76
|
+
trustDevice: z.boolean().optional().meta({
|
|
77
|
+
description: "If true, sets a trusted-device cookie so subsequent sign-ins skip Authmoji verification until it expires.",
|
|
78
|
+
}),
|
|
79
|
+
})
|
|
80
|
+
.refine((data) => (typeof data.code === "string" && data.code.trim().length > 0) ||
|
|
81
|
+
(Array.isArray(data.emojis) && data.emojis.length > 0), { message: "Either 'code' or 'emojis' must be provided." });
|
|
82
|
+
/**
|
|
83
|
+
* Authmoji plugin for Better Auth.
|
|
84
|
+
*
|
|
85
|
+
* Adds self-hosted emoji-based OTP and TOTP two-factor authentication,
|
|
86
|
+
* tap-grid challenges, recovery backup codes, trusted devices, and account
|
|
87
|
+
* lockout on top of Better Auth's adapter, session, and verification primitives.
|
|
88
|
+
*/
|
|
89
|
+
export const authmoji = (options) => {
|
|
90
|
+
const tableName = options?.authmojiTable ?? "authmoji";
|
|
91
|
+
const emojiPool = resolveEmojiPool(options?.emojis, options?.emojiGroups);
|
|
92
|
+
const allowPasswordless = options?.allowPasswordless ?? false;
|
|
93
|
+
const skipVerificationOnEnable = options?.skipVerificationOnEnable ?? false;
|
|
94
|
+
const trustDeviceMaxAge = options?.trustDeviceMaxAge ?? DEFAULT_TRUST_DEVICE_MAX_AGE;
|
|
95
|
+
const authmojiCookieMaxAge = options?.authmojiCookieMaxAge ?? DEFAULT_AUTHMOJI_COOKIE_MAX_AGE;
|
|
96
|
+
const otpLength = options?.otpOptions?.length ?? 3;
|
|
97
|
+
const otpChoiceCount = options?.otpOptions?.choiceCount ?? 8;
|
|
98
|
+
const otpPeriodMs = (options?.otpOptions?.period ?? 5) * 60 * 1000;
|
|
99
|
+
const otpAllowedAttempts = options?.otpOptions?.allowedAttempts ?? 3;
|
|
100
|
+
const otpStoreMode = options?.otpOptions?.storeOTP ?? "hashed";
|
|
101
|
+
const totpDisabled = options?.totpOptions?.disable ?? false;
|
|
102
|
+
const totpLength = options?.totpOptions?.length ?? 3;
|
|
103
|
+
const totpChoiceCount = options?.totpOptions?.choiceCount ?? 8;
|
|
104
|
+
const totpPeriod = options?.totpOptions?.period ?? 30;
|
|
105
|
+
const totpWindow = options?.totpOptions?.window ?? 1;
|
|
106
|
+
const totpAlgorithm = options?.totpOptions?.algorithm ?? "SHA-256";
|
|
107
|
+
const totpPreventReplay = options?.totpOptions?.preventReplay ?? true;
|
|
108
|
+
const totpAllowedAttempts = options?.totpOptions?.allowedAttempts ?? 5;
|
|
109
|
+
const totpSecretByteLength = options?.totpOptions?.secretByteLength ?? 20;
|
|
110
|
+
const backupCodeOptions = {
|
|
111
|
+
storeBackupCodes: "encrypted",
|
|
112
|
+
...options?.backupCodeOptions,
|
|
113
|
+
};
|
|
114
|
+
// Eagerly validate emoji pool and lengths at startup.
|
|
115
|
+
if (otpChoiceCount > 0 && otpChoiceCount < otpLength) {
|
|
116
|
+
throw new RangeError(`Authmoji otpOptions.choiceCount (${otpChoiceCount}) must be 0 or >= otpOptions.length (${otpLength}).`);
|
|
117
|
+
}
|
|
118
|
+
if (!totpDisabled && totpChoiceCount > 0 && totpChoiceCount < totpLength) {
|
|
119
|
+
throw new RangeError(`Authmoji totpOptions.choiceCount (${totpChoiceCount}) must be 0 or >= totpOptions.length (${totpLength}).`);
|
|
120
|
+
}
|
|
121
|
+
const requiredPoolSize = Math.max(otpLength, otpChoiceCount, totpDisabled ? 0 : totpLength, totpDisabled ? 0 : totpChoiceCount, backupCodeOptions.format === "emoji" ? (backupCodeOptions.length ?? 6) : 0);
|
|
122
|
+
assertValidEmojiPool(emojiPool, Math.max(1, requiredPoolSize));
|
|
123
|
+
const signInPaths = new Set([
|
|
124
|
+
...DEFAULT_SIGN_IN_PATHS,
|
|
125
|
+
...(options?.signInPaths ?? []),
|
|
126
|
+
]);
|
|
127
|
+
const passwordSchema = z.string().meta({ description: "User password" });
|
|
128
|
+
const methodField = z.enum(["otp", "totp"]).default("totp").meta({
|
|
129
|
+
description: "Authmoji 2FA method to enable. 'totp' generates an emoji TOTP secret and backup codes; 'otp' enables out-of-band emoji OTP codes immediately.",
|
|
130
|
+
});
|
|
131
|
+
const issuerField = z
|
|
132
|
+
.string()
|
|
133
|
+
.optional()
|
|
134
|
+
.meta({ description: "Custom issuer for the Authmoji TOTP URI" });
|
|
135
|
+
const enableBodySchema = allowPasswordless
|
|
136
|
+
? z.object({
|
|
137
|
+
password: passwordSchema.optional(),
|
|
138
|
+
method: methodField,
|
|
139
|
+
issuer: issuerField,
|
|
140
|
+
})
|
|
141
|
+
: z.object({
|
|
142
|
+
password: passwordSchema,
|
|
143
|
+
method: methodField,
|
|
144
|
+
issuer: issuerField,
|
|
145
|
+
});
|
|
146
|
+
const passwordOnlyBodySchema = allowPasswordless
|
|
147
|
+
? z.object({ password: passwordSchema.optional() })
|
|
148
|
+
: z.object({ password: passwordSchema });
|
|
149
|
+
async function findAuthmojiRecord(ctx, userId) {
|
|
150
|
+
return ctx.context.adapter.findOne({
|
|
151
|
+
model: tableName,
|
|
152
|
+
where: [{ field: "userId", value: userId }],
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
function getSignInAuthmojiState(ctx) {
|
|
156
|
+
const existing = signInAuthmojiStates.get(ctx.context);
|
|
157
|
+
if (existing) {
|
|
158
|
+
return existing;
|
|
159
|
+
}
|
|
160
|
+
const pending = readSignInAuthmojiState(ctx, trustDeviceMaxAge);
|
|
161
|
+
signInAuthmojiStates.set(ctx.context, pending);
|
|
162
|
+
return pending;
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
id: "authmoji",
|
|
166
|
+
endpoints: {
|
|
167
|
+
/**
|
|
168
|
+
* POST `/authmoji/enable`
|
|
169
|
+
*
|
|
170
|
+
* Enables Authmoji 2FA for the authenticated user using either `"totp"`
|
|
171
|
+
* (returns a Base32 secret, `authmoji://totp/...` URI, and backup codes)
|
|
172
|
+
* or `"otp"` (enables out-of-band emoji OTP delivery immediately).
|
|
173
|
+
*/
|
|
174
|
+
enableAuthmoji: createAuthEndpoint("/authmoji/enable", {
|
|
175
|
+
method: "POST",
|
|
176
|
+
body: enableBodySchema,
|
|
177
|
+
use: [sessionMiddleware],
|
|
178
|
+
metadata: {
|
|
179
|
+
openapi: {
|
|
180
|
+
summary: "Enable Authmoji two-factor authentication",
|
|
181
|
+
description: "Enable Authmoji 2FA via emoji TOTP or emoji OTP for the signed-in user.",
|
|
182
|
+
},
|
|
183
|
+
},
|
|
184
|
+
}, async (ctx) => {
|
|
185
|
+
const session = (await getAuthoritativeSessionFromCtx(ctx)) ?? ctx.context.session;
|
|
186
|
+
if (!session) {
|
|
187
|
+
throw APIError.from("UNAUTHORIZED", AUTHMOJI_ERROR_CODES.UNAUTHORIZED);
|
|
188
|
+
}
|
|
189
|
+
const user = session.user;
|
|
190
|
+
const { password, method, issuer } = ctx.body;
|
|
191
|
+
await assertValidPasswordIfRequired(ctx, user.id, password, allowPasswordless);
|
|
192
|
+
if (method === "otp" && !options?.otpOptions?.sendOTP) {
|
|
193
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.OTP_NOT_CONFIGURED);
|
|
194
|
+
}
|
|
195
|
+
if (method === "totp" && totpDisabled) {
|
|
196
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.TOTP_NOT_CONFIGURED);
|
|
197
|
+
}
|
|
198
|
+
if (method === "otp") {
|
|
199
|
+
const updatedUser = await ctx.context.internalAdapter.updateUser(user.id, { authmojiEnabled: true });
|
|
200
|
+
await rotateSessionWithUser(ctx, session.session, updatedUser);
|
|
201
|
+
return ctx.json({ method: "otp" });
|
|
202
|
+
}
|
|
203
|
+
const existing = await findAuthmojiRecord(ctx, user.id);
|
|
204
|
+
if (existing && existing.verified) {
|
|
205
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.TOTP_ALREADY_ENABLED);
|
|
206
|
+
}
|
|
207
|
+
const encryptionKey = getEncryptionKey(ctx);
|
|
208
|
+
const secret = generateTOTPSecret(totpSecretByteLength);
|
|
209
|
+
const encryptedSecret = await symmetricEncrypt({
|
|
210
|
+
key: encryptionKey,
|
|
211
|
+
data: secret,
|
|
212
|
+
});
|
|
213
|
+
const backupCodes = await generateBackupCodes(encryptionKey, backupCodeOptions, emojiPool);
|
|
214
|
+
if (skipVerificationOnEnable) {
|
|
215
|
+
const updatedUser = await ctx.context.internalAdapter.updateUser(user.id, { authmojiEnabled: true });
|
|
216
|
+
await rotateSessionWithUser(ctx, session.session, updatedUser);
|
|
217
|
+
}
|
|
218
|
+
const recordData = {
|
|
219
|
+
secret: encryptedSecret,
|
|
220
|
+
backupCodes: backupCodes.encryptedBackupCodes,
|
|
221
|
+
verified: skipVerificationOnEnable,
|
|
222
|
+
lastTotpCounter: null,
|
|
223
|
+
failedVerificationCount: 0,
|
|
224
|
+
lockedUntil: null,
|
|
225
|
+
};
|
|
226
|
+
if (existing) {
|
|
227
|
+
await ctx.context.adapter.update({
|
|
228
|
+
model: tableName,
|
|
229
|
+
where: [{ field: "id", value: existing.id }],
|
|
230
|
+
update: recordData,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
else {
|
|
234
|
+
await ctx.context.adapter.create({
|
|
235
|
+
model: tableName,
|
|
236
|
+
data: {
|
|
237
|
+
...recordData,
|
|
238
|
+
userId: user.id,
|
|
239
|
+
},
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
const totpURI = createAuthmojiTOTPURI({
|
|
243
|
+
secret,
|
|
244
|
+
issuer: issuer || options?.issuer || ctx.context.appName,
|
|
245
|
+
accountName: user.email,
|
|
246
|
+
period: totpPeriod,
|
|
247
|
+
length: totpLength,
|
|
248
|
+
algorithm: totpAlgorithm,
|
|
249
|
+
});
|
|
250
|
+
return ctx.json({
|
|
251
|
+
method: "totp",
|
|
252
|
+
secret,
|
|
253
|
+
totpURI,
|
|
254
|
+
backupCodes: backupCodes.backupCodes,
|
|
255
|
+
period: totpPeriod,
|
|
256
|
+
length: totpLength,
|
|
257
|
+
});
|
|
258
|
+
}),
|
|
259
|
+
/**
|
|
260
|
+
* POST `/authmoji/disable`
|
|
261
|
+
*
|
|
262
|
+
* Disables Authmoji 2FA, removes stored TOTP/backup secrets, and revokes
|
|
263
|
+
* any trusted-device cookie for the user.
|
|
264
|
+
*/
|
|
265
|
+
disableAuthmoji: createAuthEndpoint("/authmoji/disable", {
|
|
266
|
+
method: "POST",
|
|
267
|
+
body: passwordOnlyBodySchema,
|
|
268
|
+
use: [sensitiveSessionMiddleware],
|
|
269
|
+
metadata: {
|
|
270
|
+
openapi: {
|
|
271
|
+
summary: "Disable Authmoji two-factor authentication",
|
|
272
|
+
description: "Disable Authmoji 2FA and delete stored TOTP secrets and backup codes.",
|
|
273
|
+
},
|
|
274
|
+
},
|
|
275
|
+
}, async (ctx) => {
|
|
276
|
+
const user = ctx.context.session.user;
|
|
277
|
+
await assertValidPasswordIfRequired(ctx, user.id, ctx.body.password, allowPasswordless);
|
|
278
|
+
const updatedUser = await ctx.context.internalAdapter.updateUser(user.id, { authmojiEnabled: false });
|
|
279
|
+
await ctx.context.adapter.delete({
|
|
280
|
+
model: tableName,
|
|
281
|
+
where: [{ field: "userId", value: updatedUser.id }],
|
|
282
|
+
});
|
|
283
|
+
await rotateSessionWithUser(ctx, ctx.context.session.session, updatedUser);
|
|
284
|
+
await clearTrustDeviceCookie(ctx, trustDeviceMaxAge);
|
|
285
|
+
return ctx.json({ status: true });
|
|
286
|
+
}),
|
|
287
|
+
/**
|
|
288
|
+
* GET `/authmoji/status`
|
|
289
|
+
*
|
|
290
|
+
* Returns the current user's Authmoji 2FA enrollment state and available methods.
|
|
291
|
+
*/
|
|
292
|
+
getAuthmojiStatus: createAuthEndpoint("/authmoji/status", {
|
|
293
|
+
method: "GET",
|
|
294
|
+
use: [sessionMiddleware],
|
|
295
|
+
metadata: {
|
|
296
|
+
openapi: {
|
|
297
|
+
summary: "Get Authmoji status",
|
|
298
|
+
description: "Returns whether Authmoji 2FA is enabled and which methods (OTP/TOTP) are active.",
|
|
299
|
+
},
|
|
300
|
+
},
|
|
301
|
+
}, async (ctx) => {
|
|
302
|
+
const user = ctx.context.session.user;
|
|
303
|
+
const record = await findAuthmojiRecord(ctx, user.id);
|
|
304
|
+
const totpVerified = Boolean(!totpDisabled && record?.verified);
|
|
305
|
+
const methods = [];
|
|
306
|
+
if (totpVerified) {
|
|
307
|
+
methods.push("totp");
|
|
308
|
+
}
|
|
309
|
+
if (options?.otpOptions?.sendOTP && user.authmojiEnabled) {
|
|
310
|
+
methods.push("otp");
|
|
311
|
+
}
|
|
312
|
+
return ctx.json({
|
|
313
|
+
enabled: Boolean(user.authmojiEnabled),
|
|
314
|
+
methods,
|
|
315
|
+
totpVerified,
|
|
316
|
+
hasBackupCodes: Boolean(record?.backupCodes),
|
|
317
|
+
});
|
|
318
|
+
}),
|
|
319
|
+
/**
|
|
320
|
+
* POST `/authmoji/send-otp`
|
|
321
|
+
*
|
|
322
|
+
* Generates a random emoji OTP sequence, delivers the answer via the
|
|
323
|
+
* developer's `otpOptions.sendOTP` callback, and returns the shuffled
|
|
324
|
+
* tap-grid `choices` (never the answer) to the client.
|
|
325
|
+
*/
|
|
326
|
+
sendAuthmojiOTP: createAuthEndpoint("/authmoji/send-otp", {
|
|
327
|
+
method: "POST",
|
|
328
|
+
body: z
|
|
329
|
+
.object({
|
|
330
|
+
trustDevice: z.boolean().optional(),
|
|
331
|
+
})
|
|
332
|
+
.optional(),
|
|
333
|
+
metadata: {
|
|
334
|
+
openapi: {
|
|
335
|
+
summary: "Send Authmoji OTP",
|
|
336
|
+
description: "Generate an emoji OTP challenge, send the secret sequence via sendOTP, and return shuffled tap-grid choices.",
|
|
337
|
+
},
|
|
338
|
+
},
|
|
339
|
+
}, async (ctx) => {
|
|
340
|
+
const sendOTP = options?.otpOptions?.sendOTP;
|
|
341
|
+
if (!sendOTP) {
|
|
342
|
+
ctx.context.logger.error("Authmoji sendOTP is not configured. Provide otpOptions.sendOTP when creating the authmoji plugin.");
|
|
343
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.OTP_NOT_CONFIGURED);
|
|
344
|
+
}
|
|
345
|
+
const { session, key } = await resolveAuthmojiContext(ctx, trustDeviceMaxAge);
|
|
346
|
+
const challenge = generateEmojiChallenge({
|
|
347
|
+
emojis: emojiPool,
|
|
348
|
+
length: otpLength,
|
|
349
|
+
choiceCount: otpChoiceCount,
|
|
350
|
+
});
|
|
351
|
+
const canonicalAnswer = canonicalizeEmojiSequence(challenge.emojis);
|
|
352
|
+
const storedAnswer = await encodeStoredOTP(ctx, canonicalAnswer, otpStoreMode);
|
|
353
|
+
const expiresAt = new Date(Date.now() + otpPeriodMs);
|
|
354
|
+
// Invalidate any previous OTP for this challenge scope.
|
|
355
|
+
await ctx.context.internalAdapter
|
|
356
|
+
.deleteVerificationByIdentifier(`authmoji-otp-${key}`)
|
|
357
|
+
.catch(() => { });
|
|
358
|
+
await ctx.context.internalAdapter.createVerificationValue({
|
|
359
|
+
identifier: `authmoji-otp-${key}`,
|
|
360
|
+
value: serializeOTPPayload({
|
|
361
|
+
answer: storedAnswer,
|
|
362
|
+
attempts: 0,
|
|
363
|
+
}),
|
|
364
|
+
expiresAt,
|
|
365
|
+
});
|
|
366
|
+
const delivery = sendOTP({
|
|
367
|
+
user: session.user,
|
|
368
|
+
emojis: challenge.emojis,
|
|
369
|
+
code: challenge.code,
|
|
370
|
+
choices: challenge.choices,
|
|
371
|
+
expiresAt,
|
|
372
|
+
}, ctx);
|
|
373
|
+
if (delivery instanceof Promise) {
|
|
374
|
+
await ctx.context.runInBackgroundOrAwait(delivery.catch((error) => {
|
|
375
|
+
ctx.context.logger.error("Failed to send Authmoji OTP", error);
|
|
376
|
+
}));
|
|
377
|
+
}
|
|
378
|
+
return ctx.json({
|
|
379
|
+
status: true,
|
|
380
|
+
choices: challenge.choices,
|
|
381
|
+
length: otpLength,
|
|
382
|
+
expiresAt: expiresAt.toISOString(),
|
|
383
|
+
});
|
|
384
|
+
}),
|
|
385
|
+
/**
|
|
386
|
+
* POST `/authmoji/verify-otp`
|
|
387
|
+
*
|
|
388
|
+
* Verifies a submitted emoji OTP sequence (as `code` string or `emojis`
|
|
389
|
+
* array) against the active challenge.
|
|
390
|
+
*/
|
|
391
|
+
verifyAuthmojiOTP: createAuthEndpoint("/authmoji/verify-otp", {
|
|
392
|
+
method: "POST",
|
|
393
|
+
body: emojiVerificationBodySchema,
|
|
394
|
+
metadata: {
|
|
395
|
+
openapi: {
|
|
396
|
+
summary: "Verify Authmoji OTP",
|
|
397
|
+
description: "Verify a submitted emoji OTP sequence.",
|
|
398
|
+
},
|
|
399
|
+
},
|
|
400
|
+
}, async (ctx) => {
|
|
401
|
+
const { session, isSignIn, key, complete, beginAttempt } = await resolveAuthmojiContext(ctx, trustDeviceMaxAge);
|
|
402
|
+
const record = isSignIn
|
|
403
|
+
? await findAuthmojiRecord(ctx, session.user.id)
|
|
404
|
+
: null;
|
|
405
|
+
if (record) {
|
|
406
|
+
await assertAuthmojiNotLocked(ctx, tableName, record, options?.accountLockout);
|
|
407
|
+
}
|
|
408
|
+
const otpIdentifier = `authmoji-otp-${key}`;
|
|
409
|
+
const consumed = await ctx.context.internalAdapter.consumeVerificationValue(otpIdentifier);
|
|
410
|
+
if (!consumed) {
|
|
411
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.OTP_HAS_EXPIRED);
|
|
412
|
+
}
|
|
413
|
+
const payload = parseOTPPayload(consumed.value);
|
|
414
|
+
if (!payload) {
|
|
415
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.OTP_HAS_EXPIRED);
|
|
416
|
+
}
|
|
417
|
+
if (payload.attempts >= otpAllowedAttempts) {
|
|
418
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE);
|
|
419
|
+
}
|
|
420
|
+
const maxChallengeAttempts = Math.max(otpAllowedAttempts * 2, 5);
|
|
421
|
+
const attempt = isSignIn
|
|
422
|
+
? await beginAttempt(maxChallengeAttempts)
|
|
423
|
+
: null;
|
|
424
|
+
let isMatch;
|
|
425
|
+
try {
|
|
426
|
+
const submittedInput = ctx.body.emojis ?? ctx.body.code ?? "";
|
|
427
|
+
const parsed = parseEmojiSequence(submittedInput, emojiPool);
|
|
428
|
+
isMatch =
|
|
429
|
+
parsed !== null &&
|
|
430
|
+
parsed.length === otpLength &&
|
|
431
|
+
(await compareStoredOTP(ctx, payload.answer, canonicalizeEmojiSequence(parsed), otpStoreMode));
|
|
432
|
+
}
|
|
433
|
+
catch (error) {
|
|
434
|
+
await attempt?.restore();
|
|
435
|
+
throw error;
|
|
436
|
+
}
|
|
437
|
+
if (!isMatch) {
|
|
438
|
+
await attempt?.recordFailure();
|
|
439
|
+
const nextAttempts = payload.attempts + 1;
|
|
440
|
+
if (record) {
|
|
441
|
+
await recordAuthmojiFailure(ctx, tableName, record, options?.accountLockout);
|
|
442
|
+
}
|
|
443
|
+
if (nextAttempts >= otpAllowedAttempts) {
|
|
444
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE);
|
|
445
|
+
}
|
|
446
|
+
await ctx.context.internalAdapter.createVerificationValue({
|
|
447
|
+
identifier: otpIdentifier,
|
|
448
|
+
value: serializeOTPPayload({
|
|
449
|
+
answer: payload.answer,
|
|
450
|
+
attempts: nextAttempts,
|
|
451
|
+
}),
|
|
452
|
+
expiresAt: consumed.expiresAt,
|
|
453
|
+
});
|
|
454
|
+
throw APIError.from("UNAUTHORIZED", AUTHMOJI_ERROR_CODES.INVALID_CODE);
|
|
455
|
+
}
|
|
456
|
+
if (record) {
|
|
457
|
+
await resetAuthmojiFailures(ctx, tableName, record, options?.accountLockout);
|
|
458
|
+
}
|
|
459
|
+
if (!session.user.authmojiEnabled) {
|
|
460
|
+
if (!session.session) {
|
|
461
|
+
throw APIError.from("BAD_REQUEST", {
|
|
462
|
+
code: "FAILED_TO_CREATE_SESSION",
|
|
463
|
+
message: "Failed to create session",
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
const updatedUser = await ctx.context.internalAdapter.updateUser(session.user.id, { authmojiEnabled: true });
|
|
467
|
+
const newSession = await rotateSessionWithUser(ctx, session.session, updatedUser);
|
|
468
|
+
return ctx.json({
|
|
469
|
+
token: newSession.token,
|
|
470
|
+
user: parseUserOutput(ctx.context.options, updatedUser),
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
const completed = await complete({
|
|
474
|
+
trustDevice: ctx.body.trustDevice,
|
|
475
|
+
});
|
|
476
|
+
return ctx.json(completed);
|
|
477
|
+
}),
|
|
478
|
+
/**
|
|
479
|
+
* Server-only helper `auth.api.generateAuthmojiTOTP`
|
|
480
|
+
*
|
|
481
|
+
* Computes the current emoji TOTP sequence for a Base32 secret.
|
|
482
|
+
* Not exposed over HTTP.
|
|
483
|
+
*/
|
|
484
|
+
generateAuthmojiTOTP: createAuthEndpoint.serverOnly({
|
|
485
|
+
method: "POST",
|
|
486
|
+
body: z.object({
|
|
487
|
+
secret: z.string().meta({
|
|
488
|
+
description: "Base32 TOTP secret to generate a code for",
|
|
489
|
+
}),
|
|
490
|
+
timestamp: z
|
|
491
|
+
.number()
|
|
492
|
+
.optional()
|
|
493
|
+
.meta({ description: "Optional Unix timestamp in milliseconds" }),
|
|
494
|
+
}),
|
|
495
|
+
}, async (ctx) => {
|
|
496
|
+
if (totpDisabled) {
|
|
497
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.TOTP_NOT_CONFIGURED);
|
|
498
|
+
}
|
|
499
|
+
return generateEmojiTOTP(ctx.body.secret, {
|
|
500
|
+
emojis: emojiPool,
|
|
501
|
+
length: totpLength,
|
|
502
|
+
period: totpPeriod,
|
|
503
|
+
algorithm: totpAlgorithm,
|
|
504
|
+
timestamp: ctx.body.timestamp,
|
|
505
|
+
});
|
|
506
|
+
}),
|
|
507
|
+
/**
|
|
508
|
+
* POST `/authmoji/get-totp-uri`
|
|
509
|
+
*
|
|
510
|
+
* Re-fetches the user's `authmoji://totp/...` setup URI and Base32 secret
|
|
511
|
+
* after verifying their password.
|
|
512
|
+
*/
|
|
513
|
+
getAuthmojiTOTPURI: createAuthEndpoint("/authmoji/get-totp-uri", {
|
|
514
|
+
method: "POST",
|
|
515
|
+
use: [sessionMiddleware],
|
|
516
|
+
body: passwordOnlyBodySchema,
|
|
517
|
+
metadata: {
|
|
518
|
+
openapi: {
|
|
519
|
+
summary: "Get Authmoji TOTP URI",
|
|
520
|
+
description: "Retrieve the authenticated user's Authmoji TOTP setup URI and Base32 secret.",
|
|
521
|
+
},
|
|
522
|
+
},
|
|
523
|
+
}, async (ctx) => {
|
|
524
|
+
if (totpDisabled) {
|
|
525
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.TOTP_NOT_CONFIGURED);
|
|
526
|
+
}
|
|
527
|
+
const user = ctx.context.session.user;
|
|
528
|
+
await assertValidPasswordIfRequired(ctx, user.id, ctx.body.password, allowPasswordless);
|
|
529
|
+
const record = await findAuthmojiRecord(ctx, user.id);
|
|
530
|
+
if (!record) {
|
|
531
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.TOTP_NOT_ENABLED);
|
|
532
|
+
}
|
|
533
|
+
const secret = await symmetricDecrypt({
|
|
534
|
+
key: getEncryptionKey(ctx),
|
|
535
|
+
data: record.secret,
|
|
536
|
+
});
|
|
537
|
+
const totpURI = createAuthmojiTOTPURI({
|
|
538
|
+
secret,
|
|
539
|
+
issuer: options?.issuer || ctx.context.appName,
|
|
540
|
+
accountName: user.email,
|
|
541
|
+
period: totpPeriod,
|
|
542
|
+
length: totpLength,
|
|
543
|
+
algorithm: totpAlgorithm,
|
|
544
|
+
});
|
|
545
|
+
return ctx.json({
|
|
546
|
+
totpURI,
|
|
547
|
+
secret,
|
|
548
|
+
period: totpPeriod,
|
|
549
|
+
length: totpLength,
|
|
550
|
+
});
|
|
551
|
+
}),
|
|
552
|
+
/**
|
|
553
|
+
* POST `/authmoji/get-totp-challenge`
|
|
554
|
+
*
|
|
555
|
+
* Returns a deterministically shuffled emoji tap-grid (`choices`) for the
|
|
556
|
+
* current TOTP time step. Repeated calls within the same step yield the
|
|
557
|
+
* exact same grid to prevent set-intersection leakage.
|
|
558
|
+
*/
|
|
559
|
+
getAuthmojiTOTPChallenge: createAuthEndpoint("/authmoji/get-totp-challenge", {
|
|
560
|
+
method: "POST",
|
|
561
|
+
metadata: {
|
|
562
|
+
openapi: {
|
|
563
|
+
summary: "Get Authmoji TOTP tap-grid challenge",
|
|
564
|
+
description: "Returns the deterministic shuffled emoji choices for the current TOTP time step.",
|
|
565
|
+
},
|
|
566
|
+
},
|
|
567
|
+
}, async (ctx) => {
|
|
568
|
+
if (totpDisabled) {
|
|
569
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.TOTP_NOT_CONFIGURED);
|
|
570
|
+
}
|
|
571
|
+
if (totpChoiceCount === 0) {
|
|
572
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.TOTP_CHOICES_DISABLED);
|
|
573
|
+
}
|
|
574
|
+
const { session, isSignIn } = await resolveAuthmojiContext(ctx, trustDeviceMaxAge);
|
|
575
|
+
const record = await findAuthmojiRecord(ctx, session.user.id);
|
|
576
|
+
if (!record || (isSignIn && !record.verified)) {
|
|
577
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.TOTP_NOT_ENABLED);
|
|
578
|
+
}
|
|
579
|
+
const secret = await symmetricDecrypt({
|
|
580
|
+
key: getEncryptionKey(ctx),
|
|
581
|
+
data: record.secret,
|
|
582
|
+
});
|
|
583
|
+
const challenge = await generateEmojiTOTPChoices(secret, {
|
|
584
|
+
emojis: emojiPool,
|
|
585
|
+
length: totpLength,
|
|
586
|
+
choiceCount: totpChoiceCount,
|
|
587
|
+
period: totpPeriod,
|
|
588
|
+
algorithm: totpAlgorithm,
|
|
589
|
+
});
|
|
590
|
+
return ctx.json({
|
|
591
|
+
choices: challenge.choices,
|
|
592
|
+
length: challenge.length,
|
|
593
|
+
period: challenge.period,
|
|
594
|
+
expiresAt: new Date(challenge.expiresAt).toISOString(),
|
|
595
|
+
});
|
|
596
|
+
}),
|
|
597
|
+
/**
|
|
598
|
+
* POST `/authmoji/verify-totp`
|
|
599
|
+
*
|
|
600
|
+
* Verifies an emoji TOTP code (for initial enrollment confirmation,
|
|
601
|
+
* sign-in 2FA completion, or step-up verification).
|
|
602
|
+
*/
|
|
603
|
+
verifyAuthmojiTOTP: createAuthEndpoint("/authmoji/verify-totp", {
|
|
604
|
+
method: "POST",
|
|
605
|
+
body: emojiVerificationBodySchema,
|
|
606
|
+
metadata: {
|
|
607
|
+
openapi: {
|
|
608
|
+
summary: "Verify Authmoji TOTP",
|
|
609
|
+
description: "Verify a time-based emoji TOTP sequence.",
|
|
610
|
+
},
|
|
611
|
+
},
|
|
612
|
+
}, async (ctx) => {
|
|
613
|
+
if (totpDisabled) {
|
|
614
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.TOTP_NOT_CONFIGURED);
|
|
615
|
+
}
|
|
616
|
+
const { session, isSignIn, complete, beginAttempt } = await resolveAuthmojiContext(ctx, trustDeviceMaxAge);
|
|
617
|
+
const user = session.user;
|
|
618
|
+
const record = await findAuthmojiRecord(ctx, user.id);
|
|
619
|
+
if (!record || (isSignIn && !record.verified)) {
|
|
620
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.TOTP_NOT_ENABLED);
|
|
621
|
+
}
|
|
622
|
+
if (isSignIn) {
|
|
623
|
+
await assertAuthmojiNotLocked(ctx, tableName, record, options?.accountLockout);
|
|
624
|
+
}
|
|
625
|
+
const attempt = isSignIn
|
|
626
|
+
? await beginAttempt(totpAllowedAttempts)
|
|
627
|
+
: null;
|
|
628
|
+
let verification;
|
|
629
|
+
try {
|
|
630
|
+
const secret = await symmetricDecrypt({
|
|
631
|
+
key: getEncryptionKey(ctx),
|
|
632
|
+
data: record.secret,
|
|
633
|
+
});
|
|
634
|
+
const submittedInput = ctx.body.emojis ?? ctx.body.code ?? "";
|
|
635
|
+
verification = await verifyEmojiTOTP(secret, submittedInput, {
|
|
636
|
+
emojis: emojiPool,
|
|
637
|
+
length: totpLength,
|
|
638
|
+
period: totpPeriod,
|
|
639
|
+
window: totpWindow,
|
|
640
|
+
algorithm: totpAlgorithm,
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
catch (error) {
|
|
644
|
+
await attempt?.restore();
|
|
645
|
+
throw error;
|
|
646
|
+
}
|
|
647
|
+
const isReplayed = totpPreventReplay &&
|
|
648
|
+
verification.valid &&
|
|
649
|
+
verification.counter !== null &&
|
|
650
|
+
typeof record.lastTotpCounter === "number" &&
|
|
651
|
+
verification.counter <= record.lastTotpCounter;
|
|
652
|
+
if (!verification.valid || isReplayed) {
|
|
653
|
+
await attempt?.recordFailure();
|
|
654
|
+
if (isSignIn) {
|
|
655
|
+
await recordAuthmojiFailure(ctx, tableName, record, options?.accountLockout);
|
|
656
|
+
}
|
|
657
|
+
throw APIError.from("UNAUTHORIZED", AUTHMOJI_ERROR_CODES.INVALID_CODE);
|
|
658
|
+
}
|
|
659
|
+
if (isSignIn) {
|
|
660
|
+
await resetAuthmojiFailures(ctx, tableName, record, options?.accountLockout);
|
|
661
|
+
}
|
|
662
|
+
const recordUpdates = {};
|
|
663
|
+
if (verification.counter !== null) {
|
|
664
|
+
recordUpdates.lastTotpCounter = verification.counter;
|
|
665
|
+
}
|
|
666
|
+
if (!record.verified) {
|
|
667
|
+
recordUpdates.verified = true;
|
|
668
|
+
}
|
|
669
|
+
if (Object.keys(recordUpdates).length > 0) {
|
|
670
|
+
await ctx.context.adapter.update({
|
|
671
|
+
model: tableName,
|
|
672
|
+
where: [{ field: "id", value: record.id }],
|
|
673
|
+
update: recordUpdates,
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
if (!record.verified && !user.authmojiEnabled && session.session) {
|
|
677
|
+
const updatedUser = await ctx.context.internalAdapter.updateUser(user.id, { authmojiEnabled: true });
|
|
678
|
+
const newSession = await rotateSessionWithUser(ctx, session.session, updatedUser);
|
|
679
|
+
return ctx.json({
|
|
680
|
+
token: newSession.token,
|
|
681
|
+
user: parseUserOutput(ctx.context.options, updatedUser),
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
const completed = await complete({
|
|
685
|
+
trustDevice: ctx.body.trustDevice,
|
|
686
|
+
});
|
|
687
|
+
return ctx.json(completed);
|
|
688
|
+
}),
|
|
689
|
+
/**
|
|
690
|
+
* POST `/authmoji/generate-backup-codes`
|
|
691
|
+
*
|
|
692
|
+
* Replaces the user's recovery backup codes and returns the plaintext codes once.
|
|
693
|
+
*/
|
|
694
|
+
generateAuthmojiBackupCodes: createAuthEndpoint("/authmoji/generate-backup-codes", {
|
|
695
|
+
method: "POST",
|
|
696
|
+
body: passwordOnlyBodySchema,
|
|
697
|
+
use: [sessionMiddleware],
|
|
698
|
+
metadata: {
|
|
699
|
+
openapi: {
|
|
700
|
+
summary: "Generate Authmoji backup codes",
|
|
701
|
+
description: "Generate a fresh set of recovery backup codes for Authmoji 2FA.",
|
|
702
|
+
},
|
|
703
|
+
},
|
|
704
|
+
}, async (ctx) => {
|
|
705
|
+
const session = (await getAuthoritativeSessionFromCtx(ctx)) ?? ctx.context.session;
|
|
706
|
+
if (!session) {
|
|
707
|
+
throw APIError.from("UNAUTHORIZED", AUTHMOJI_ERROR_CODES.UNAUTHORIZED);
|
|
708
|
+
}
|
|
709
|
+
const user = session.user;
|
|
710
|
+
if (!user.authmojiEnabled) {
|
|
711
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.AUTHMOJI_NOT_ENABLED);
|
|
712
|
+
}
|
|
713
|
+
await assertValidPasswordIfRequired(ctx, user.id, ctx.body.password, allowPasswordless);
|
|
714
|
+
const record = await findAuthmojiRecord(ctx, user.id);
|
|
715
|
+
if (!record) {
|
|
716
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.BACKUP_CODES_NOT_ENABLED);
|
|
717
|
+
}
|
|
718
|
+
const generated = await generateBackupCodes(getEncryptionKey(ctx), backupCodeOptions, emojiPool);
|
|
719
|
+
await ctx.context.adapter.update({
|
|
720
|
+
model: tableName,
|
|
721
|
+
where: [{ field: "id", value: record.id }],
|
|
722
|
+
update: { backupCodes: generated.encryptedBackupCodes },
|
|
723
|
+
});
|
|
724
|
+
return ctx.json({
|
|
725
|
+
status: true,
|
|
726
|
+
backupCodes: generated.backupCodes,
|
|
727
|
+
});
|
|
728
|
+
}),
|
|
729
|
+
/**
|
|
730
|
+
* POST `/authmoji/verify-backup-code`
|
|
731
|
+
*
|
|
732
|
+
* Verifies and consumes a single-use recovery backup code.
|
|
733
|
+
*/
|
|
734
|
+
verifyAuthmojiBackupCode: createAuthEndpoint("/authmoji/verify-backup-code", {
|
|
735
|
+
method: "POST",
|
|
736
|
+
body: z.object({
|
|
737
|
+
code: z
|
|
738
|
+
.string()
|
|
739
|
+
.min(1)
|
|
740
|
+
.meta({ description: "Single-use recovery backup code" }),
|
|
741
|
+
disableSession: z.boolean().optional().meta({
|
|
742
|
+
description: "If true, verifies the backup code without creating a session cookie.",
|
|
743
|
+
}),
|
|
744
|
+
trustDevice: z.boolean().optional().meta({
|
|
745
|
+
description: "If true, sets a trusted-device cookie.",
|
|
746
|
+
}),
|
|
747
|
+
}),
|
|
748
|
+
metadata: {
|
|
749
|
+
openapi: {
|
|
750
|
+
summary: "Verify Authmoji backup code",
|
|
751
|
+
description: "Verify and consume a single-use backup code to complete Authmoji 2FA.",
|
|
752
|
+
},
|
|
753
|
+
},
|
|
754
|
+
}, async (ctx) => {
|
|
755
|
+
const { session, isSignIn, complete, beginAttempt } = await resolveAuthmojiContext(ctx, trustDeviceMaxAge);
|
|
756
|
+
const record = await findAuthmojiRecord(ctx, session.user.id);
|
|
757
|
+
if (!record) {
|
|
758
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.BACKUP_CODES_NOT_ENABLED);
|
|
759
|
+
}
|
|
760
|
+
if (isSignIn) {
|
|
761
|
+
await assertAuthmojiNotLocked(ctx, tableName, record, options?.accountLockout);
|
|
762
|
+
}
|
|
763
|
+
const attempt = isSignIn
|
|
764
|
+
? await beginAttempt(totpAllowedAttempts)
|
|
765
|
+
: null;
|
|
766
|
+
let verification;
|
|
767
|
+
try {
|
|
768
|
+
verification = await verifyAndConsumeBackupCode({
|
|
769
|
+
storedBackupCodes: record.backupCodes,
|
|
770
|
+
submittedCode: ctx.body.code,
|
|
771
|
+
key: getEncryptionKey(ctx),
|
|
772
|
+
options: backupCodeOptions,
|
|
773
|
+
emojiPool,
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
catch (error) {
|
|
777
|
+
await attempt?.restore();
|
|
778
|
+
throw error;
|
|
779
|
+
}
|
|
780
|
+
if (!verification.valid || !verification.remaining) {
|
|
781
|
+
await attempt?.recordFailure();
|
|
782
|
+
if (isSignIn) {
|
|
783
|
+
await recordAuthmojiFailure(ctx, tableName, record, options?.accountLockout);
|
|
784
|
+
}
|
|
785
|
+
throw APIError.from("UNAUTHORIZED", AUTHMOJI_ERROR_CODES.INVALID_BACKUP_CODE);
|
|
786
|
+
}
|
|
787
|
+
const updatedEncrypted = await encodeBackupCodes(verification.remaining, getEncryptionKey(ctx), backupCodeOptions);
|
|
788
|
+
// Use optimistic concurrency check when adapter supports incrementOne.
|
|
789
|
+
if (typeof ctx.context.adapter.incrementOne === "function") {
|
|
790
|
+
const swapped = await ctx.context.adapter.incrementOne({
|
|
791
|
+
model: tableName,
|
|
792
|
+
where: [
|
|
793
|
+
{ field: "id", value: record.id },
|
|
794
|
+
{ field: "backupCodes", value: record.backupCodes },
|
|
795
|
+
],
|
|
796
|
+
increment: {},
|
|
797
|
+
set: { backupCodes: updatedEncrypted },
|
|
798
|
+
});
|
|
799
|
+
if (!swapped) {
|
|
800
|
+
throw APIError.fromStatus("CONFLICT", {
|
|
801
|
+
message: "Failed to verify backup code. Please try again.",
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
else {
|
|
806
|
+
await ctx.context.adapter.update({
|
|
807
|
+
model: tableName,
|
|
808
|
+
where: [{ field: "id", value: record.id }],
|
|
809
|
+
update: { backupCodes: updatedEncrypted },
|
|
810
|
+
});
|
|
811
|
+
}
|
|
812
|
+
if (isSignIn) {
|
|
813
|
+
await resetAuthmojiFailures(ctx, tableName, record, options?.accountLockout);
|
|
814
|
+
}
|
|
815
|
+
const completed = await complete({
|
|
816
|
+
trustDevice: ctx.body.trustDevice,
|
|
817
|
+
disableSession: ctx.body.disableSession,
|
|
818
|
+
});
|
|
819
|
+
return ctx.json(completed);
|
|
820
|
+
}),
|
|
821
|
+
/**
|
|
822
|
+
* Server-only helper `auth.api.viewAuthmojiBackupCodes`
|
|
823
|
+
*
|
|
824
|
+
* Returns decrypted backup codes for a user from trusted server code.
|
|
825
|
+
* Not exposed over HTTP.
|
|
826
|
+
*/
|
|
827
|
+
viewAuthmojiBackupCodes: createAuthEndpoint.serverOnly({
|
|
828
|
+
method: "POST",
|
|
829
|
+
body: z.object({
|
|
830
|
+
userId: z.coerce
|
|
831
|
+
.string()
|
|
832
|
+
.meta({ description: "User ID to view backup codes for" }),
|
|
833
|
+
}),
|
|
834
|
+
}, async (ctx) => {
|
|
835
|
+
const record = await findAuthmojiRecord(ctx, ctx.body.userId);
|
|
836
|
+
if (!record) {
|
|
837
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.BACKUP_CODES_NOT_ENABLED);
|
|
838
|
+
}
|
|
839
|
+
const decrypted = await decodeBackupCodes(record.backupCodes, getEncryptionKey(ctx), backupCodeOptions);
|
|
840
|
+
if (!decrypted) {
|
|
841
|
+
throw APIError.from("BAD_REQUEST", AUTHMOJI_ERROR_CODES.INVALID_BACKUP_CODE);
|
|
842
|
+
}
|
|
843
|
+
return ctx.json({
|
|
844
|
+
status: true,
|
|
845
|
+
backupCodes: decrypted,
|
|
846
|
+
});
|
|
847
|
+
}),
|
|
848
|
+
},
|
|
849
|
+
options,
|
|
850
|
+
hooks: {
|
|
851
|
+
after: [
|
|
852
|
+
{
|
|
853
|
+
matcher(context) {
|
|
854
|
+
return signInPaths.has(context.path ?? "");
|
|
855
|
+
},
|
|
856
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
857
|
+
const data = ctx.context.newSession;
|
|
858
|
+
const user = data?.user;
|
|
859
|
+
if (!data || !user?.authmojiEnabled) {
|
|
860
|
+
return;
|
|
861
|
+
}
|
|
862
|
+
const { requiresAuthmoji, trustDeviceCookie } = await getSignInAuthmojiState(ctx);
|
|
863
|
+
const trustCookieAttrs = ctx.context.createAuthCookie(AUTHMOJI_TRUST_DEVICE_COOKIE_NAME, { maxAge: trustDeviceMaxAge });
|
|
864
|
+
// Trusted device hit: rotate the trust token and allow sign-in through.
|
|
865
|
+
if (!requiresAuthmoji && trustDeviceCookie) {
|
|
866
|
+
const trustIdentifier = trustDeviceCookie.split("!")[1];
|
|
867
|
+
if (trustIdentifier) {
|
|
868
|
+
await ctx.context.internalAdapter
|
|
869
|
+
.deleteVerificationByIdentifier(trustIdentifier)
|
|
870
|
+
.catch(() => { });
|
|
871
|
+
}
|
|
872
|
+
await issueTrustDeviceCookie(ctx, user.id, trustDeviceMaxAge);
|
|
873
|
+
return;
|
|
874
|
+
}
|
|
875
|
+
if (trustDeviceCookie) {
|
|
876
|
+
expireCookie(ctx, trustCookieAttrs);
|
|
877
|
+
}
|
|
878
|
+
// Revoke the temporary session created by primary sign-in until Authmoji is verified.
|
|
879
|
+
deleteSessionCookie(ctx, true);
|
|
880
|
+
await ctx.context.internalAdapter.deleteSession(data.session.token);
|
|
881
|
+
ctx.context.setNewSession(null);
|
|
882
|
+
const challengeCookie = ctx.context.createAuthCookie(AUTHMOJI_COOKIE_NAME, { maxAge: authmojiCookieMaxAge });
|
|
883
|
+
const identifier = `authmoji-${generateRandomString(20)}`;
|
|
884
|
+
const expiresAt = new Date(Date.now() + authmojiCookieMaxAge * 1000);
|
|
885
|
+
await ctx.context.internalAdapter.createVerificationValue({
|
|
886
|
+
value: user.id,
|
|
887
|
+
identifier,
|
|
888
|
+
expiresAt,
|
|
889
|
+
});
|
|
890
|
+
await ctx.context.internalAdapter.createVerificationValue({
|
|
891
|
+
value: "0",
|
|
892
|
+
identifier: `authmoji-attempts-${identifier}`,
|
|
893
|
+
expiresAt,
|
|
894
|
+
});
|
|
895
|
+
await ctx.setSignedCookie(challengeCookie.name, identifier, ctx.context.secret, challengeCookie.attributes);
|
|
896
|
+
const methods = [];
|
|
897
|
+
if (!totpDisabled) {
|
|
898
|
+
const record = await findAuthmojiRecord(ctx, user.id);
|
|
899
|
+
if (record?.verified) {
|
|
900
|
+
methods.push("totp");
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
if (options?.otpOptions?.sendOTP) {
|
|
904
|
+
methods.push("otp");
|
|
905
|
+
}
|
|
906
|
+
return ctx.json({
|
|
907
|
+
twoFactorRedirect: true,
|
|
908
|
+
authmojiRedirect: true,
|
|
909
|
+
twoFactorMethods: methods,
|
|
910
|
+
methods,
|
|
911
|
+
});
|
|
912
|
+
}),
|
|
913
|
+
},
|
|
914
|
+
],
|
|
915
|
+
},
|
|
916
|
+
schema: mergeSchema(authmojiSchema, {
|
|
917
|
+
...options?.schema,
|
|
918
|
+
authmoji: {
|
|
919
|
+
...options?.schema?.authmoji,
|
|
920
|
+
...(options?.authmojiTable ? { modelName: options.authmojiTable } : {}),
|
|
921
|
+
},
|
|
922
|
+
}),
|
|
923
|
+
rateLimit: [
|
|
924
|
+
{
|
|
925
|
+
pathMatcher(path) {
|
|
926
|
+
return path.startsWith("/authmoji/");
|
|
927
|
+
},
|
|
928
|
+
window: 10,
|
|
929
|
+
max: 5,
|
|
930
|
+
},
|
|
931
|
+
],
|
|
932
|
+
$ERROR_CODES: AUTHMOJI_ERROR_CODES,
|
|
933
|
+
};
|
|
934
|
+
};
|