fix(db): transactional useMagicToken, O(2) getSession, ?? for displayName

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-30 01:00:20 +00:00
parent d8de79ce7d
commit b229e6871f
2 changed files with 8 additions and 11 deletions
+6 -5
View File
@@ -61,7 +61,7 @@ function initDb(dbPath) {
const stmt = instance.prepare(
'INSERT INTO profiles (email, display_name, created_at, last_seen) VALUES (?,?,?,?) RETURNING *'
)
return stmt.get(email, displayName || null, now, now)
return stmt.get(email, displayName ?? null, now, now)
}
function findProfileByEmail(email) {
@@ -83,14 +83,14 @@ function initDb(dbPath) {
)
}
function useMagicToken(token) {
const useMagicToken = instance.transaction((token) => {
const row = instance
.prepare('SELECT * FROM magic_tokens WHERE token = ? AND used = 0 AND expires_at > ?')
.get(token, Date.now())
if (!row) return null
instance.prepare('UPDATE magic_tokens SET used = 1 WHERE token = ?').run(token)
return row.profile_id
}
})
function createSession(token, profileId) {
const now = Date.now()
@@ -102,8 +102,9 @@ function initDb(dbPath) {
function getSession(token) {
const row = instance.prepare('SELECT * FROM sessions WHERE token = ?').get(token)
if (!row) return null
instance.prepare('UPDATE sessions SET last_seen = ? WHERE token = ?').run(Date.now(), token)
return instance.prepare('SELECT * FROM sessions WHERE token = ?').get(token)
const now = Date.now()
instance.prepare('UPDATE sessions SET last_seen = ? WHERE token = ?').run(now, token)
return { ...row, last_seen: now }
}
function deleteSession(token) {
+2 -6
View File
@@ -43,14 +43,10 @@ describe('profiles', () => {
test('updateProfileSeen updates last_seen timestamp', () => {
const created = db.createProfile('seen@example.com', 'Seen')
const before = created.last_seen
// Ensure time advances by at least 1ms
const laterTime = before + 1
// Use a small delay approach: manipulate via direct SQL isn't needed,
// just call updateProfileSeen and verify last_seen >= original
const callTime = Date.now()
db.updateProfileSeen(created.id)
const updated = db.findProfileById(created.id)
assert.ok(updated.last_seen >= before)
assert.ok(updated.last_seen >= callTime)
})
})