@prunellejs/auth 0.7.3 → 0.7.4
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/package.json +2 -2
- package/src/index.ts +36 -20
- package/src/routes.ts +9 -1
- package/src/sqlite.ts +33 -5
- package/src/store-ext.ts +2 -0
- package/src/store.ts +7 -0
- package/src/webauthn-crypto.ts +12 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/auth",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.4",
|
|
4
4
|
"description": "Zero-dependency Bun-native auth plugin for Prunelle (Argon2id, hashed sessions, SQLite, magic links, OAuth2 PKCE, TOTP 2FA, Passkeys, Organizations)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -24,6 +24,6 @@
|
|
|
24
24
|
"directory": "packages/plugin-auth"
|
|
25
25
|
},
|
|
26
26
|
"peerDependencies": {
|
|
27
|
-
"prunelle": "^0.7.
|
|
27
|
+
"prunelle": "^0.7.4"
|
|
28
28
|
}
|
|
29
29
|
}
|
package/src/index.ts
CHANGED
|
@@ -350,6 +350,40 @@ function lazySecret(optionSecret: string | undefined): () => string {
|
|
|
350
350
|
}
|
|
351
351
|
}
|
|
352
352
|
|
|
353
|
+
async function registerUser<TUser extends AuthUser>(
|
|
354
|
+
store: AuthStore<TUser>,
|
|
355
|
+
observeAsync: <T>(value: T | Promise<T>) => T | Promise<T>,
|
|
356
|
+
insertUser: (fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>) => Promise<TUser>,
|
|
357
|
+
input: CreateUserInput<TUser>,
|
|
358
|
+
): Promise<PublicUser<TUser>> {
|
|
359
|
+
const { email: rawEmail, password, name, avatarUrl, role, emailVerified, ...extra } = input
|
|
360
|
+
const email = normalizeEmail(rawEmail)
|
|
361
|
+
if (!isValidEmail(email))
|
|
362
|
+
throw new Error('Invalid email address')
|
|
363
|
+
if (await observeAsync(store.getUserByEmail(email)))
|
|
364
|
+
throw new Error('Email is already registered')
|
|
365
|
+
|
|
366
|
+
const passwordHash = password !== undefined ? await hashPassword(password) : undefined
|
|
367
|
+
let created: TUser
|
|
368
|
+
try {
|
|
369
|
+
created = await insertUser({
|
|
370
|
+
...extra,
|
|
371
|
+
email,
|
|
372
|
+
...(name !== undefined ? { name } : {}),
|
|
373
|
+
...(avatarUrl !== undefined ? { avatarUrl } : {}),
|
|
374
|
+
...(role !== undefined ? { role } : {}),
|
|
375
|
+
emailVerified: emailVerified ?? false,
|
|
376
|
+
...(passwordHash !== undefined ? { passwordHash } : {}),
|
|
377
|
+
} as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
|
|
378
|
+
}
|
|
379
|
+
catch (err) {
|
|
380
|
+
if (await observeAsync(store.getUserByEmail(email)))
|
|
381
|
+
throw new Error('Email is already registered', { cause: err })
|
|
382
|
+
throw err
|
|
383
|
+
}
|
|
384
|
+
return toPublicUser(created)
|
|
385
|
+
}
|
|
386
|
+
|
|
353
387
|
export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptions<TUser> = {}): Auth<TUser> {
|
|
354
388
|
const secret = lazySecret(options.secret)
|
|
355
389
|
const store = options.store ?? memoryAuthStore<TUser>()
|
|
@@ -449,26 +483,8 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
449
483
|
} as TUser))
|
|
450
484
|
}
|
|
451
485
|
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
const email = normalizeEmail(rawEmail)
|
|
455
|
-
if (!isValidEmail(email))
|
|
456
|
-
throw new Error('Invalid email address')
|
|
457
|
-
if (await sessions.observeAsync(store.getUserByEmail(email)))
|
|
458
|
-
throw new Error('Email is already registered')
|
|
459
|
-
|
|
460
|
-
const passwordHash = password !== undefined ? await hashPassword(password) : undefined
|
|
461
|
-
const created = await insertUser({
|
|
462
|
-
...extra,
|
|
463
|
-
email,
|
|
464
|
-
...(name !== undefined ? { name } : {}),
|
|
465
|
-
...(avatarUrl !== undefined ? { avatarUrl } : {}),
|
|
466
|
-
...(role !== undefined ? { role } : {}),
|
|
467
|
-
emailVerified: emailVerified ?? false,
|
|
468
|
-
...(passwordHash !== undefined ? { passwordHash } : {}),
|
|
469
|
-
} as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
|
|
470
|
-
return toPublicUser(created)
|
|
471
|
-
}
|
|
486
|
+
const createUser = (input: CreateUserInput<TUser>): Promise<PublicUser<TUser>> =>
|
|
487
|
+
registerUser(store, sessions.observeAsync, insertUser, input)
|
|
472
488
|
|
|
473
489
|
const mailedLinkOrigin = (url: URL): string | undefined => linkOrigin(site, url)
|
|
474
490
|
|
package/src/routes.ts
CHANGED
|
@@ -240,7 +240,15 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
|
|
|
240
240
|
if (await sessions.observeAsync(store.getUserByEmail(email)))
|
|
241
241
|
return respondAuthError(ctx, 409, messages['signup.email-taken'])
|
|
242
242
|
|
|
243
|
-
|
|
243
|
+
let user: PublicUser<TUser>
|
|
244
|
+
try {
|
|
245
|
+
user = await createUser({ email, password, name } as CreateUserInput<TUser>)
|
|
246
|
+
}
|
|
247
|
+
catch (err) {
|
|
248
|
+
if (await sessions.observeAsync(store.getUserByEmail(email)))
|
|
249
|
+
return respondAuthError(ctx, 409, messages['signup.email-taken'])
|
|
250
|
+
throw err
|
|
251
|
+
}
|
|
244
252
|
await sessions.createSessionForUser(user.id, ctx, user)
|
|
245
253
|
|
|
246
254
|
if (wantsJson(ctx.request))
|
package/src/sqlite.ts
CHANGED
|
@@ -226,16 +226,44 @@ function exportSqliteUser(
|
|
|
226
226
|
|
|
227
227
|
type SqliteAuthStore = AuthStore & { readonly db: Database }
|
|
228
228
|
|
|
229
|
+
function isInMemorySqlitePath(path: string): boolean {
|
|
230
|
+
if (path === '' || path === ':memory:')
|
|
231
|
+
return true
|
|
232
|
+
if (!path.startsWith('file:'))
|
|
233
|
+
return false
|
|
234
|
+
const rest = path.slice('file:'.length)
|
|
235
|
+
const qIdx = rest.indexOf('?')
|
|
236
|
+
const target = (qIdx === -1 ? rest : rest.slice(0, qIdx)).split('#', 1)[0]!
|
|
237
|
+
if (target === '' || target === ':memory:')
|
|
238
|
+
return true
|
|
239
|
+
if (qIdx === -1)
|
|
240
|
+
return false
|
|
241
|
+
const query = rest.slice(qIdx + 1).split('#', 1)[0]!
|
|
242
|
+
return new URLSearchParams(query).get('mode') === 'memory'
|
|
243
|
+
}
|
|
244
|
+
|
|
229
245
|
export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): SqliteAuthStore {
|
|
230
|
-
if (typeof dbOrPath !== 'string' || dbOrPath
|
|
246
|
+
if (typeof dbOrPath !== 'string' || isInMemorySqlitePath(dbOrPath))
|
|
231
247
|
return openSqliteAuthStore(dbOrPath)
|
|
232
248
|
// A file opens at first use, so a build importing prunelle.config.ts creates no database.
|
|
233
249
|
let opened: SqliteAuthStore | undefined
|
|
234
250
|
const open = (): SqliteAuthStore => (opened ??= openSqliteAuthStore(appPath(dbOrPath)))
|
|
235
251
|
const target = Object.create(null) as SqliteAuthStore
|
|
236
252
|
return markSyncStore(new Proxy(target, {
|
|
237
|
-
get: (_, key) =>
|
|
238
|
-
|
|
253
|
+
get: (_, key) => {
|
|
254
|
+
if (opened === undefined) {
|
|
255
|
+
if (key === 'close')
|
|
256
|
+
return () => {}
|
|
257
|
+
if (key === 'then' || typeof key === 'symbol')
|
|
258
|
+
return undefined
|
|
259
|
+
}
|
|
260
|
+
return Reflect.get(open(), key)
|
|
261
|
+
},
|
|
262
|
+
has: (_, key) => {
|
|
263
|
+
if (opened === undefined && (key === 'then' || typeof key === 'symbol'))
|
|
264
|
+
return false
|
|
265
|
+
return Reflect.has(open(), key)
|
|
266
|
+
},
|
|
239
267
|
}))
|
|
240
268
|
}
|
|
241
269
|
|
|
@@ -260,7 +288,7 @@ function ensurePrivateDbFile(dbPath: string): void {
|
|
|
260
288
|
|
|
261
289
|
function openSqliteAuthStore(dbOrPath: string | Database): SqliteAuthStore {
|
|
262
290
|
const ownsDb = typeof dbOrPath === 'string'
|
|
263
|
-
if (ownsDb && dbOrPath
|
|
291
|
+
if (ownsDb && !isInMemorySqlitePath(dbOrPath) && !dbOrPath.startsWith('file:'))
|
|
264
292
|
ensurePrivateDbFile(dbOrPath)
|
|
265
293
|
const db = ownsDb ? new Database(dbOrPath, { create: true }) : dbOrPath
|
|
266
294
|
let closed = false
|
|
@@ -282,7 +310,7 @@ function openSqliteAuthStore(dbOrPath: string | Database): SqliteAuthStore {
|
|
|
282
310
|
return qListUserSessions.all(userId, Date.now()).map(row => rowToSession(row)!)
|
|
283
311
|
}
|
|
284
312
|
|
|
285
|
-
return markSyncStore(keptInMemory(db.filename
|
|
313
|
+
return markSyncStore(keptInMemory(isInMemorySqlitePath(db.filename), {
|
|
286
314
|
...ext.methods,
|
|
287
315
|
db,
|
|
288
316
|
close() {
|
package/src/store-ext.ts
CHANGED
|
@@ -241,6 +241,8 @@ function buildMemoryTotpPasskeyMethods(state: MemoryExtState) {
|
|
|
241
241
|
return out
|
|
242
242
|
},
|
|
243
243
|
createPasskey(record: PasskeyRecord): void {
|
|
244
|
+
if (state.passkeys.has(record.id))
|
|
245
|
+
throw new Error('prunelle: Passkey is already registered')
|
|
244
246
|
state.passkeys.set(record.id, clonePasskey(record))
|
|
245
247
|
},
|
|
246
248
|
updatePasskeyUsage(credentialId: string, signCount: number, lastUsedAt: number): void {
|
package/src/store.ts
CHANGED
|
@@ -228,6 +228,10 @@ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<
|
|
|
228
228
|
},
|
|
229
229
|
createUser(user) {
|
|
230
230
|
const norm: TUser = { ...user, email: normalizeEmail(user.email) }
|
|
231
|
+
if (state.users.has(norm.id))
|
|
232
|
+
throw new Error(`prunelle: user id "${norm.id}" already exists`)
|
|
233
|
+
if (state.usersByEmail.has(norm.email))
|
|
234
|
+
throw new Error('prunelle: Email is already registered')
|
|
231
235
|
state.users.set(norm.id, norm)
|
|
232
236
|
state.usersByEmail.set(norm.email, norm.id)
|
|
233
237
|
return norm
|
|
@@ -238,6 +242,9 @@ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<
|
|
|
238
242
|
return undefined
|
|
239
243
|
const nextEmail = patch.email !== undefined ? normalizeEmail(patch.email) : cur.email
|
|
240
244
|
if (nextEmail !== cur.email) {
|
|
245
|
+
const owner = state.usersByEmail.get(nextEmail)
|
|
246
|
+
if (owner !== undefined && owner !== userId)
|
|
247
|
+
throw new Error('prunelle: Email is already registered')
|
|
241
248
|
state.usersByEmail.delete(cur.email)
|
|
242
249
|
state.usersByEmail.set(nextEmail, userId)
|
|
243
250
|
}
|
package/src/webauthn-crypto.ts
CHANGED
|
@@ -216,9 +216,13 @@ function readDerLength(der: Uint8Array, offset: number): { length: number, nextO
|
|
|
216
216
|
const count = first & 0x7F
|
|
217
217
|
if (count === 0 || count > 2 || offset + 1 + count > der.length)
|
|
218
218
|
throw new Error('prunelle: unsupported DER length')
|
|
219
|
+
if (der[offset + 1] === 0x00)
|
|
220
|
+
throw new Error('prunelle: non-minimal DER length')
|
|
219
221
|
let length = 0
|
|
220
222
|
for (let i = 0; i < count; i++)
|
|
221
223
|
length = (length << 8) | der[offset + 1 + i]!
|
|
224
|
+
if (length < 0x80)
|
|
225
|
+
throw new Error('prunelle: non-minimal DER length')
|
|
222
226
|
return { length, nextOffset: offset + 1 + count }
|
|
223
227
|
}
|
|
224
228
|
|
|
@@ -229,8 +233,15 @@ function readDerInteger(der: Uint8Array, offset: number, coordSize: number): { v
|
|
|
229
233
|
if (length === 0 || nextOffset + length > der.length)
|
|
230
234
|
throw new Error('prunelle: truncated DER integer')
|
|
231
235
|
let slice = der.subarray(nextOffset, nextOffset + length)
|
|
232
|
-
if (slice[0]
|
|
236
|
+
if ((slice[0]! & 0x80) !== 0)
|
|
237
|
+
throw new Error('prunelle: DER integer must not be negative')
|
|
238
|
+
if (slice[0] === 0x00) {
|
|
239
|
+
if (slice.length === 1)
|
|
240
|
+
throw new Error('prunelle: DER integer must be positive')
|
|
241
|
+
if ((slice[1]! & 0x80) === 0)
|
|
242
|
+
throw new Error('prunelle: non-minimal DER integer')
|
|
233
243
|
slice = slice.subarray(1)
|
|
244
|
+
}
|
|
234
245
|
if (slice.length > coordSize)
|
|
235
246
|
throw new Error('prunelle: DER integer exceeds coordinate size')
|
|
236
247
|
const out = new Uint8Array(coordSize)
|