@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/totp.d.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import type { GroupKey } from "emojibase";
|
|
2
|
+
import { type EmojiPoolInput } from "./emojis.js";
|
|
3
|
+
export type TOTPAlgorithm = "SHA-1" | "SHA-256" | "SHA-512";
|
|
4
|
+
export interface EmojiTOTPOptions {
|
|
5
|
+
/** Emoji alphabet or Emojibase dataset used to derive codes. Defaults to `getDefaultEmojis()`. */
|
|
6
|
+
emojis?: EmojiPoolInput;
|
|
7
|
+
/** Filter default Emojibase dataset by group keys when `emojis` is omitted. */
|
|
8
|
+
groups?: readonly GroupKey[];
|
|
9
|
+
/** Number of emojis per TOTP code. @default 3 */
|
|
10
|
+
length?: number;
|
|
11
|
+
/** Time step duration in seconds. @default 30 */
|
|
12
|
+
period?: number;
|
|
13
|
+
/** HMAC hash algorithm. @default "SHA-256" */
|
|
14
|
+
algorithm?: TOTPAlgorithm;
|
|
15
|
+
/** Unix timestamp in milliseconds. Defaults to `Date.now()`. */
|
|
16
|
+
timestamp?: number;
|
|
17
|
+
}
|
|
18
|
+
export interface EmojiTOTPChoicesOptions extends EmojiTOTPOptions {
|
|
19
|
+
/** Number of emojis in the shuffled tap grid. @default 8 */
|
|
20
|
+
choiceCount?: number;
|
|
21
|
+
}
|
|
22
|
+
export interface VerifyEmojiTOTPOptions extends EmojiTOTPOptions {
|
|
23
|
+
/**
|
|
24
|
+
* Number of time steps to allow before and after the current step
|
|
25
|
+
* to tolerate clock drift.
|
|
26
|
+
* @default 1
|
|
27
|
+
*/
|
|
28
|
+
window?: number;
|
|
29
|
+
}
|
|
30
|
+
export interface EmojiTOTPResult {
|
|
31
|
+
/** Ordered emoji sequence for the current time step. */
|
|
32
|
+
emojis: string[];
|
|
33
|
+
/** Concatenated emoji code string (e.g. `"😍🤩🍣"`). */
|
|
34
|
+
code: string;
|
|
35
|
+
/** Current TOTP time counter (`Math.floor(timestamp / (period * 1000))`). */
|
|
36
|
+
counter: number;
|
|
37
|
+
/** Time step period in seconds. */
|
|
38
|
+
period: number;
|
|
39
|
+
/** Unix timestamp (ms) when this TOTP step expires. */
|
|
40
|
+
expiresAt: number;
|
|
41
|
+
}
|
|
42
|
+
export interface EmojiTOTPChoicesResult {
|
|
43
|
+
/**
|
|
44
|
+
* Deterministically shuffled emoji grid for the current time step.
|
|
45
|
+
* Repeated calls within the same step return the exact same order.
|
|
46
|
+
*/
|
|
47
|
+
choices: string[];
|
|
48
|
+
/** Expected number of emojis the user must select. */
|
|
49
|
+
length: number;
|
|
50
|
+
/** Current TOTP time counter. */
|
|
51
|
+
counter: number;
|
|
52
|
+
/** Time step period in seconds. */
|
|
53
|
+
period: number;
|
|
54
|
+
/** Unix timestamp (ms) when this TOTP step expires. */
|
|
55
|
+
expiresAt: number;
|
|
56
|
+
}
|
|
57
|
+
export interface VerifyEmojiTOTPResult {
|
|
58
|
+
/** Whether the submitted emoji sequence matched within the allowed window. */
|
|
59
|
+
valid: boolean;
|
|
60
|
+
/** Matched step delta relative to the current counter (e.g. `-1`, `0`, `1`), or `null`. */
|
|
61
|
+
delta: number | null;
|
|
62
|
+
/** Matched absolute counter value (useful for replay protection), or `null`. */
|
|
63
|
+
counter: number | null;
|
|
64
|
+
}
|
|
65
|
+
export interface AuthmojiTOTPURIParams {
|
|
66
|
+
/** Base32-encoded TOTP secret. */
|
|
67
|
+
secret: string;
|
|
68
|
+
/** Issuer / application name. */
|
|
69
|
+
issuer: string;
|
|
70
|
+
/** User account identifier (typically email or username). */
|
|
71
|
+
accountName: string;
|
|
72
|
+
/** Time step in seconds. @default 30 */
|
|
73
|
+
period?: number;
|
|
74
|
+
/** Number of emojis per code. @default 3 */
|
|
75
|
+
length?: number;
|
|
76
|
+
/** HMAC algorithm. @default "SHA-256" */
|
|
77
|
+
algorithm?: TOTPAlgorithm;
|
|
78
|
+
}
|
|
79
|
+
export interface ParsedAuthmojiTOTPURI {
|
|
80
|
+
scheme: "authmoji" | "otpauth";
|
|
81
|
+
secret: string;
|
|
82
|
+
issuer: string;
|
|
83
|
+
accountName: string;
|
|
84
|
+
period: number;
|
|
85
|
+
length: number;
|
|
86
|
+
algorithm: TOTPAlgorithm;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Encodes raw bytes to RFC 4648 Base32 (without padding).
|
|
90
|
+
*/
|
|
91
|
+
export declare function encodeBase32(bytes: Uint8Array): string;
|
|
92
|
+
/**
|
|
93
|
+
* Decodes an RFC 4648 Base32 string (case-insensitive, ignores spaces/hyphens/padding).
|
|
94
|
+
*/
|
|
95
|
+
export declare function decodeBase32(input: string): Uint8Array<ArrayBuffer>;
|
|
96
|
+
/**
|
|
97
|
+
* Generates a cryptographically random Base32-encoded TOTP secret.
|
|
98
|
+
* @param byteLength Secret size in bytes (default `20` = 160 bits).
|
|
99
|
+
*/
|
|
100
|
+
export declare function generateTOTPSecret(byteLength?: number): string;
|
|
101
|
+
/**
|
|
102
|
+
* Generates the current Time-based One-Time Emoji Password for a shared secret.
|
|
103
|
+
*/
|
|
104
|
+
export declare function generateEmojiTOTP(secret: string | Uint8Array, options?: EmojiTOTPOptions): Promise<EmojiTOTPResult>;
|
|
105
|
+
/**
|
|
106
|
+
* Deterministically derives a shuffled emoji tap grid for the current TOTP time
|
|
107
|
+
* step. Repeated calls within the same step yield the exact same choice list so
|
|
108
|
+
* callers cannot extract the answer via set intersection.
|
|
109
|
+
*/
|
|
110
|
+
export declare function generateEmojiTOTPChoices(secret: string | Uint8Array, options?: EmojiTOTPChoicesOptions): Promise<EmojiTOTPChoicesResult>;
|
|
111
|
+
/**
|
|
112
|
+
* Verifies an emoji TOTP code against a shared secret across `[-window, +window]`.
|
|
113
|
+
*/
|
|
114
|
+
export declare function verifyEmojiTOTP(secret: string | Uint8Array, input: string | readonly string[], options?: VerifyEmojiTOTPOptions): Promise<VerifyEmojiTOTPResult>;
|
|
115
|
+
/**
|
|
116
|
+
* Formats an `authmoji://totp/...` Key URI for QR codes and authenticator import.
|
|
117
|
+
*/
|
|
118
|
+
export declare function createAuthmojiTOTPURI(params: AuthmojiTOTPURIParams): string;
|
|
119
|
+
/**
|
|
120
|
+
* Parses an `authmoji://totp/...` (or `otpauth://totp/...`) URI.
|
|
121
|
+
*/
|
|
122
|
+
export declare function parseAuthmojiTOTPURI(uri: string): ParsedAuthmojiTOTPURI;
|
package/dist/totp.js
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
import { assertValidEmojiPool, canonicalizeEmojiSequence, parseEmojiSequence, resolveEmojiPool, } from "./emojis.js";
|
|
2
|
+
const BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
3
|
+
const BASE32_LOOKUP = Object.fromEntries([...BASE32_ALPHABET].map((char, index) => [char, index]));
|
|
4
|
+
const TOTP_CODE_DOMAIN = new TextEncoder().encode("authmoji:totp:code:v1:");
|
|
5
|
+
const TOTP_CHOICES_DOMAIN = new TextEncoder().encode("authmoji:totp:choices:v1:");
|
|
6
|
+
/**
|
|
7
|
+
* Encodes raw bytes to RFC 4648 Base32 (without padding).
|
|
8
|
+
*/
|
|
9
|
+
export function encodeBase32(bytes) {
|
|
10
|
+
let bits = 0;
|
|
11
|
+
let value = 0;
|
|
12
|
+
let output = "";
|
|
13
|
+
for (const byte of bytes) {
|
|
14
|
+
value = (value << 8) | byte;
|
|
15
|
+
bits += 8;
|
|
16
|
+
while (bits >= 5) {
|
|
17
|
+
output += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];
|
|
18
|
+
bits -= 5;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
if (bits > 0) {
|
|
22
|
+
output += BASE32_ALPHABET[(value << (5 - bits)) & 31];
|
|
23
|
+
}
|
|
24
|
+
return output;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Decodes an RFC 4648 Base32 string (case-insensitive, ignores spaces/hyphens/padding).
|
|
28
|
+
*/
|
|
29
|
+
export function decodeBase32(input) {
|
|
30
|
+
const cleaned = input.replace(/[\s=-]+/g, "").toUpperCase();
|
|
31
|
+
if (!cleaned) {
|
|
32
|
+
throw new Error("Base32 secret must not be empty.");
|
|
33
|
+
}
|
|
34
|
+
const output = new Uint8Array(new ArrayBuffer(Math.floor((cleaned.length * 5) / 8)));
|
|
35
|
+
let bits = 0;
|
|
36
|
+
let value = 0;
|
|
37
|
+
let index = 0;
|
|
38
|
+
for (const char of cleaned) {
|
|
39
|
+
const digit = BASE32_LOOKUP[char];
|
|
40
|
+
if (digit === undefined) {
|
|
41
|
+
throw new Error(`Invalid Base32 character "${char}".`);
|
|
42
|
+
}
|
|
43
|
+
value = (value << 5) | digit;
|
|
44
|
+
bits += 5;
|
|
45
|
+
if (bits >= 8) {
|
|
46
|
+
output[index] = (value >>> (bits - 8)) & 0xff;
|
|
47
|
+
index += 1;
|
|
48
|
+
bits -= 8;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return output.subarray(0, index);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Generates a cryptographically random Base32-encoded TOTP secret.
|
|
55
|
+
* @param byteLength Secret size in bytes (default `20` = 160 bits).
|
|
56
|
+
*/
|
|
57
|
+
export function generateTOTPSecret(byteLength = 20) {
|
|
58
|
+
if (!Number.isInteger(byteLength) || byteLength < 16) {
|
|
59
|
+
throw new RangeError(`TOTP secret byteLength must be an integer >= 16 (received ${byteLength}).`);
|
|
60
|
+
}
|
|
61
|
+
const bytes = new Uint8Array(byteLength);
|
|
62
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
63
|
+
return encodeBase32(bytes);
|
|
64
|
+
}
|
|
65
|
+
function secretToBytes(secret) {
|
|
66
|
+
if (secret instanceof Uint8Array) {
|
|
67
|
+
const copy = new Uint8Array(new ArrayBuffer(secret.byteLength));
|
|
68
|
+
copy.set(secret);
|
|
69
|
+
return copy;
|
|
70
|
+
}
|
|
71
|
+
return decodeBase32(secret);
|
|
72
|
+
}
|
|
73
|
+
function uint64BigEndian(value) {
|
|
74
|
+
const bytes = new Uint8Array(8);
|
|
75
|
+
const view = new DataView(bytes.buffer);
|
|
76
|
+
const big = BigInt(value);
|
|
77
|
+
view.setBigUint64(0, big, false);
|
|
78
|
+
return bytes;
|
|
79
|
+
}
|
|
80
|
+
function uint32BigEndian(value) {
|
|
81
|
+
const bytes = new Uint8Array(4);
|
|
82
|
+
const view = new DataView(bytes.buffer);
|
|
83
|
+
view.setUint32(0, value >>> 0, false);
|
|
84
|
+
return bytes;
|
|
85
|
+
}
|
|
86
|
+
function concatBytes(...chunks) {
|
|
87
|
+
let total = 0;
|
|
88
|
+
for (const chunk of chunks) {
|
|
89
|
+
total += chunk.byteLength;
|
|
90
|
+
}
|
|
91
|
+
const result = new Uint8Array(new ArrayBuffer(total));
|
|
92
|
+
let offset = 0;
|
|
93
|
+
for (const chunk of chunks) {
|
|
94
|
+
result.set(chunk, offset);
|
|
95
|
+
offset += chunk.byteLength;
|
|
96
|
+
}
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
async function importHmacKey(secretBytes, algorithm) {
|
|
100
|
+
return globalThis.crypto.subtle.importKey("raw", secretBytes, { name: "HMAC", hash: { name: algorithm } }, false, ["sign"]);
|
|
101
|
+
}
|
|
102
|
+
class DeterministicHmacStream {
|
|
103
|
+
key;
|
|
104
|
+
prefix;
|
|
105
|
+
blockIndex = 0;
|
|
106
|
+
buffer = new Uint8Array(0);
|
|
107
|
+
offset = 0;
|
|
108
|
+
constructor(key, domain, counter) {
|
|
109
|
+
this.key = key;
|
|
110
|
+
this.prefix = concatBytes(domain, uint64BigEndian(counter));
|
|
111
|
+
}
|
|
112
|
+
async nextUint32() {
|
|
113
|
+
if (this.offset + 4 > this.buffer.byteLength) {
|
|
114
|
+
const payload = concatBytes(this.prefix, uint32BigEndian(this.blockIndex));
|
|
115
|
+
this.blockIndex += 1;
|
|
116
|
+
const sig = await globalThis.crypto.subtle.sign("HMAC", this.key, payload);
|
|
117
|
+
this.buffer = new Uint8Array(sig);
|
|
118
|
+
this.offset = 0;
|
|
119
|
+
}
|
|
120
|
+
const view = new DataView(this.buffer.buffer, this.buffer.byteOffset + this.offset, 4);
|
|
121
|
+
this.offset += 4;
|
|
122
|
+
return view.getUint32(0, false);
|
|
123
|
+
}
|
|
124
|
+
async nextInt(maxExclusive) {
|
|
125
|
+
if (maxExclusive <= 1) {
|
|
126
|
+
return 0;
|
|
127
|
+
}
|
|
128
|
+
const maxUint32 = 0x1_00_00_00_00;
|
|
129
|
+
const limit = Math.floor(maxUint32 / maxExclusive) * maxExclusive;
|
|
130
|
+
while (true) {
|
|
131
|
+
const value = await this.nextUint32();
|
|
132
|
+
if (value < limit) {
|
|
133
|
+
return value % maxExclusive;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function getTimeStep(timestampMs, periodSeconds) {
|
|
139
|
+
if (!Number.isFinite(periodSeconds) || periodSeconds <= 0) {
|
|
140
|
+
throw new RangeError(`TOTP period must be a positive number of seconds (received ${periodSeconds}).`);
|
|
141
|
+
}
|
|
142
|
+
const periodMs = periodSeconds * 1000;
|
|
143
|
+
const counter = Math.floor(timestampMs / periodMs);
|
|
144
|
+
const expiresAt = (counter + 1) * periodMs;
|
|
145
|
+
return { counter, expiresAt };
|
|
146
|
+
}
|
|
147
|
+
async function deriveCodeForCounter(key, counter, pool, length) {
|
|
148
|
+
const working = [...pool];
|
|
149
|
+
const stream = new DeterministicHmacStream(key, TOTP_CODE_DOMAIN, counter);
|
|
150
|
+
for (let i = 0; i < length; i += 1) {
|
|
151
|
+
const remaining = working.length - i;
|
|
152
|
+
const j = i + (await stream.nextInt(remaining));
|
|
153
|
+
const temp = working[i];
|
|
154
|
+
working[i] = working[j];
|
|
155
|
+
working[j] = temp;
|
|
156
|
+
}
|
|
157
|
+
return working.slice(0, length);
|
|
158
|
+
}
|
|
159
|
+
function constantTimeStringEqual(a, b) {
|
|
160
|
+
const encoder = new TextEncoder();
|
|
161
|
+
const aBytes = encoder.encode(a);
|
|
162
|
+
const bBytes = encoder.encode(b);
|
|
163
|
+
const maxLen = Math.max(aBytes.length, bBytes.length);
|
|
164
|
+
let diff = aBytes.length ^ bBytes.length;
|
|
165
|
+
for (let i = 0; i < maxLen; i += 1) {
|
|
166
|
+
diff |= (aBytes[i] ?? 0) ^ (bBytes[i] ?? 0);
|
|
167
|
+
}
|
|
168
|
+
return diff === 0;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Generates the current Time-based One-Time Emoji Password for a shared secret.
|
|
172
|
+
*/
|
|
173
|
+
export async function generateEmojiTOTP(secret, options) {
|
|
174
|
+
const pool = resolveEmojiPool(options?.emojis, options?.groups);
|
|
175
|
+
const length = options?.length ?? 3;
|
|
176
|
+
const period = options?.period ?? 30;
|
|
177
|
+
const algorithm = options?.algorithm ?? "SHA-256";
|
|
178
|
+
const timestamp = options?.timestamp ?? Date.now();
|
|
179
|
+
if (!Number.isInteger(length) || length < 1) {
|
|
180
|
+
throw new RangeError(`TOTP length must be an integer >= 1 (received ${length}).`);
|
|
181
|
+
}
|
|
182
|
+
assertValidEmojiPool(pool, length);
|
|
183
|
+
const { counter, expiresAt } = getTimeStep(timestamp, period);
|
|
184
|
+
const key = await importHmacKey(secretToBytes(secret), algorithm);
|
|
185
|
+
const emojis = await deriveCodeForCounter(key, counter, pool, length);
|
|
186
|
+
return {
|
|
187
|
+
emojis,
|
|
188
|
+
code: emojis.join(""),
|
|
189
|
+
counter,
|
|
190
|
+
period,
|
|
191
|
+
expiresAt,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Deterministically derives a shuffled emoji tap grid for the current TOTP time
|
|
196
|
+
* step. Repeated calls within the same step yield the exact same choice list so
|
|
197
|
+
* callers cannot extract the answer via set intersection.
|
|
198
|
+
*/
|
|
199
|
+
export async function generateEmojiTOTPChoices(secret, options) {
|
|
200
|
+
const pool = resolveEmojiPool(options?.emojis, options?.groups);
|
|
201
|
+
const length = options?.length ?? 3;
|
|
202
|
+
const choiceCount = options?.choiceCount ?? 8;
|
|
203
|
+
const period = options?.period ?? 30;
|
|
204
|
+
const algorithm = options?.algorithm ?? "SHA-256";
|
|
205
|
+
const timestamp = options?.timestamp ?? Date.now();
|
|
206
|
+
if (!Number.isInteger(length) || length < 1) {
|
|
207
|
+
throw new RangeError(`TOTP length must be an integer >= 1 (received ${length}).`);
|
|
208
|
+
}
|
|
209
|
+
if (!Number.isInteger(choiceCount) || choiceCount < length) {
|
|
210
|
+
throw new RangeError(`TOTP choiceCount (${choiceCount}) must be an integer >= length (${length}).`);
|
|
211
|
+
}
|
|
212
|
+
assertValidEmojiPool(pool, choiceCount);
|
|
213
|
+
const { counter, expiresAt } = getTimeStep(timestamp, period);
|
|
214
|
+
const key = await importHmacKey(secretToBytes(secret), algorithm);
|
|
215
|
+
const answer = await deriveCodeForCounter(key, counter, pool, length);
|
|
216
|
+
const answerSet = new Set(answer);
|
|
217
|
+
const distractorsPool = pool.filter((emoji) => !answerSet.has(emoji));
|
|
218
|
+
const distractorsNeeded = choiceCount - length;
|
|
219
|
+
const stream = new DeterministicHmacStream(key, TOTP_CHOICES_DOMAIN, counter);
|
|
220
|
+
for (let i = 0; i < distractorsNeeded; i += 1) {
|
|
221
|
+
const remaining = distractorsPool.length - i;
|
|
222
|
+
const j = i + (await stream.nextInt(remaining));
|
|
223
|
+
const temp = distractorsPool[i];
|
|
224
|
+
distractorsPool[i] = distractorsPool[j];
|
|
225
|
+
distractorsPool[j] = temp;
|
|
226
|
+
}
|
|
227
|
+
const choices = [...answer, ...distractorsPool.slice(0, distractorsNeeded)];
|
|
228
|
+
// Deterministically shuffle choices so answer emojis are randomly positioned.
|
|
229
|
+
for (let i = choices.length - 1; i > 0; i -= 1) {
|
|
230
|
+
const j = await stream.nextInt(i + 1);
|
|
231
|
+
const temp = choices[i];
|
|
232
|
+
choices[i] = choices[j];
|
|
233
|
+
choices[j] = temp;
|
|
234
|
+
}
|
|
235
|
+
return {
|
|
236
|
+
choices,
|
|
237
|
+
length,
|
|
238
|
+
counter,
|
|
239
|
+
period,
|
|
240
|
+
expiresAt,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Verifies an emoji TOTP code against a shared secret across `[-window, +window]`.
|
|
245
|
+
*/
|
|
246
|
+
export async function verifyEmojiTOTP(secret, input, options) {
|
|
247
|
+
const pool = resolveEmojiPool(options?.emojis, options?.groups);
|
|
248
|
+
const length = options?.length ?? 3;
|
|
249
|
+
const period = options?.period ?? 30;
|
|
250
|
+
const algorithm = options?.algorithm ?? "SHA-256";
|
|
251
|
+
const window = options?.window ?? 1;
|
|
252
|
+
const timestamp = options?.timestamp ?? Date.now();
|
|
253
|
+
if (!Number.isInteger(length) || length < 1) {
|
|
254
|
+
throw new RangeError(`TOTP length must be an integer >= 1 (received ${length}).`);
|
|
255
|
+
}
|
|
256
|
+
if (!Number.isInteger(window) || window < 0) {
|
|
257
|
+
throw new RangeError(`TOTP window must be an integer >= 0 (received ${window}).`);
|
|
258
|
+
}
|
|
259
|
+
assertValidEmojiPool(pool, length);
|
|
260
|
+
const parsed = parseEmojiSequence(input, pool);
|
|
261
|
+
if (!parsed || parsed.length !== length) {
|
|
262
|
+
return { valid: false, delta: null, counter: null };
|
|
263
|
+
}
|
|
264
|
+
const submittedCanonical = canonicalizeEmojiSequence(parsed);
|
|
265
|
+
const { counter: currentCounter } = getTimeStep(timestamp, period);
|
|
266
|
+
const key = await importHmacKey(secretToBytes(secret), algorithm);
|
|
267
|
+
let matchedDelta = null;
|
|
268
|
+
let matchedCounter = null;
|
|
269
|
+
for (let delta = -window; delta <= window; delta += 1) {
|
|
270
|
+
const stepCounter = currentCounter + delta;
|
|
271
|
+
if (stepCounter < 0) {
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
const candidate = await deriveCodeForCounter(key, stepCounter, pool, length);
|
|
275
|
+
const candidateCanonical = canonicalizeEmojiSequence(candidate);
|
|
276
|
+
if (constantTimeStringEqual(candidateCanonical, submittedCanonical) &&
|
|
277
|
+
matchedDelta === null) {
|
|
278
|
+
matchedDelta = delta;
|
|
279
|
+
matchedCounter = stepCounter;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return {
|
|
283
|
+
valid: matchedDelta !== null,
|
|
284
|
+
delta: matchedDelta,
|
|
285
|
+
counter: matchedCounter,
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
function formatAlgorithmParam(algorithm) {
|
|
289
|
+
switch (algorithm) {
|
|
290
|
+
case "SHA-1":
|
|
291
|
+
return "SHA1";
|
|
292
|
+
case "SHA-256":
|
|
293
|
+
return "SHA256";
|
|
294
|
+
case "SHA-512":
|
|
295
|
+
return "SHA512";
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
function parseAlgorithmParam(value) {
|
|
299
|
+
switch (value?.toUpperCase()) {
|
|
300
|
+
case "SHA1":
|
|
301
|
+
case "SHA-1":
|
|
302
|
+
return "SHA-1";
|
|
303
|
+
case "SHA512":
|
|
304
|
+
case "SHA-512":
|
|
305
|
+
return "SHA-512";
|
|
306
|
+
case "SHA256":
|
|
307
|
+
case "SHA-256":
|
|
308
|
+
case undefined:
|
|
309
|
+
case "":
|
|
310
|
+
return "SHA-256";
|
|
311
|
+
default:
|
|
312
|
+
throw new Error(`Unsupported Authmoji TOTP algorithm "${value}".`);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Formats an `authmoji://totp/...` Key URI for QR codes and authenticator import.
|
|
317
|
+
*/
|
|
318
|
+
export function createAuthmojiTOTPURI(params) {
|
|
319
|
+
const period = params.period ?? 30;
|
|
320
|
+
const length = params.length ?? 3;
|
|
321
|
+
const algorithm = params.algorithm ?? "SHA-256";
|
|
322
|
+
const issuer = params.issuer.trim() || "Authmoji";
|
|
323
|
+
const accountName = params.accountName.trim();
|
|
324
|
+
const label = `${encodeURIComponent(issuer)}:${encodeURIComponent(accountName)}`;
|
|
325
|
+
const search = new URLSearchParams({
|
|
326
|
+
secret: params.secret,
|
|
327
|
+
issuer,
|
|
328
|
+
period: String(period),
|
|
329
|
+
length: String(length),
|
|
330
|
+
algorithm: formatAlgorithmParam(algorithm),
|
|
331
|
+
});
|
|
332
|
+
return `authmoji://totp/${label}?${search.toString()}`;
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Parses an `authmoji://totp/...` (or `otpauth://totp/...`) URI.
|
|
336
|
+
*/
|
|
337
|
+
export function parseAuthmojiTOTPURI(uri) {
|
|
338
|
+
let parsedUrl;
|
|
339
|
+
try {
|
|
340
|
+
parsedUrl = new URL(uri);
|
|
341
|
+
}
|
|
342
|
+
catch {
|
|
343
|
+
throw new Error("Invalid Authmoji TOTP URI.");
|
|
344
|
+
}
|
|
345
|
+
const scheme = parsedUrl.protocol.replace(/:$/, "");
|
|
346
|
+
if (scheme !== "authmoji" && scheme !== "otpauth") {
|
|
347
|
+
throw new Error(`Unsupported TOTP URI scheme "${scheme}".`);
|
|
348
|
+
}
|
|
349
|
+
if (parsedUrl.host !== "totp") {
|
|
350
|
+
throw new Error(`Unsupported TOTP URI type "${parsedUrl.host}".`);
|
|
351
|
+
}
|
|
352
|
+
const secret = parsedUrl.searchParams.get("secret");
|
|
353
|
+
if (!secret) {
|
|
354
|
+
throw new Error("Authmoji TOTP URI is missing required secret parameter.");
|
|
355
|
+
}
|
|
356
|
+
// Validate Base32 secret format.
|
|
357
|
+
decodeBase32(secret);
|
|
358
|
+
const rawLabel = decodeURIComponent(parsedUrl.pathname.replace(/^\/+/, ""));
|
|
359
|
+
const colonIndex = rawLabel.indexOf(":");
|
|
360
|
+
const labelIssuer = colonIndex >= 0 ? rawLabel.slice(0, colonIndex) : "";
|
|
361
|
+
const accountName = colonIndex >= 0 ? rawLabel.slice(colonIndex + 1).trim() : rawLabel.trim();
|
|
362
|
+
const issuer = parsedUrl.searchParams.get("issuer") || labelIssuer;
|
|
363
|
+
const periodRaw = parsedUrl.searchParams.get("period");
|
|
364
|
+
const period = periodRaw ? Number(periodRaw) : 30;
|
|
365
|
+
if (!Number.isInteger(period) || period <= 0) {
|
|
366
|
+
throw new Error(`Invalid period "${periodRaw}" in Authmoji TOTP URI.`);
|
|
367
|
+
}
|
|
368
|
+
const lengthRaw = parsedUrl.searchParams.get("length");
|
|
369
|
+
const length = lengthRaw ? Number(lengthRaw) : 3;
|
|
370
|
+
if (!Number.isInteger(length) || length < 1) {
|
|
371
|
+
throw new Error(`Invalid length "${lengthRaw}" in Authmoji TOTP URI.`);
|
|
372
|
+
}
|
|
373
|
+
const algorithm = parseAlgorithmParam(parsedUrl.searchParams.get("algorithm"));
|
|
374
|
+
return {
|
|
375
|
+
scheme,
|
|
376
|
+
secret,
|
|
377
|
+
issuer,
|
|
378
|
+
accountName,
|
|
379
|
+
period,
|
|
380
|
+
length,
|
|
381
|
+
algorithm,
|
|
382
|
+
};
|
|
383
|
+
}
|