feat(api-token): store API tokens as SHA-256 hashes (#492)

New tokens are 32 random bytes with a shumai_ prefix and are returned
only once at creation. The list endpoint returns a 4-character hint
instead of the plaintext. A migration hashes existing tokens in place so
they keep authenticating.
This commit is contained in:
Yiling-J
2026-10-26 11:08:46 +08:00
committed by GitHub
parent c2af7494ec
commit 22486b893b
19 changed files with 413 additions and 113 deletions
+82 -17
View File
@@ -1,39 +1,104 @@
import { describe, expect, it } from 'vitest'
import { setupTestDbHooks } from '@shumai/db/test'
import { prisma } from '@shumai/db'
import { apiTokenService } from './api-token'
import { apiTokenService, hashToken } from './api-token'
async function createUser(email = 'dev@shumai.com') {
return prisma.user.create({
data: {
name: 'Test Dev',
email,
password: 'password',
},
})
}
describe('ApiTokenService', () => {
setupTestDbHooks()
it('can create, list, validate, and delete api tokens', async () => {
const user = await prisma.user.create({
data: {
name: 'Test Dev',
email: 'dev@shumai.com',
password: 'password',
},
})
const user = await createUser()
const token = await apiTokenService.createToken(user.id, 'My CLI Key')
expect(token.id).toBeDefined()
expect(token.token).toBeDefined()
expect(token.name).toBe('My CLI Key')
expect(token.userId).toBe(user.id)
const { record, token } = await apiTokenService.createToken(user.id, 'My CLI Key')
expect(record.id).toBeDefined()
expect(record.name).toBe('My CLI Key')
expect(record.userId).toBe(user.id)
const tokens = await apiTokenService.listTokens(user.id)
expect(tokens.length).toBe(1)
expect(tokens[0].id).toBe(token.id)
expect(tokens[0].id).toBe(record.id)
const validatedUser = await apiTokenService.validateToken(token.token)
const validatedUser = await apiTokenService.validateToken(token)
expect(validatedUser).toBeDefined()
expect(validatedUser?.id).toBe(user.id)
await apiTokenService.deleteToken(user.id, token.id)
await apiTokenService.deleteToken(user.id, record.id)
const tokensAfterDelete = await apiTokenService.listTokens(user.id)
expect(tokensAfterDelete.length).toBe(0)
const validatedAfterDelete = await apiTokenService.validateToken(token.token)
const validatedAfterDelete = await apiTokenService.validateToken(token)
expect(validatedAfterDelete).toBeNull()
})
it('generates a prefixed, high-entropy token and returns it only at creation', async () => {
const user = await createUser()
const first = await apiTokenService.createToken(user.id, 'first')
const second = await apiTokenService.createToken(user.id, 'second')
// shumai_ + base64url(32 bytes) = 7 + 43 characters
expect(first.token).toMatch(/^shumai_[A-Za-z0-9_-]{43}$/)
expect(second.token).not.toBe(first.token)
expect(first.record.tokenHint).toBe(first.token.slice(-4))
expect(first.record).not.toHaveProperty('token')
expect(first.record).not.toHaveProperty('tokenHash')
})
it('stores only the hash and hint, never the plaintext', async () => {
const user = await createUser()
const { record, token } = await apiTokenService.createToken(user.id, 'cli')
const row = await prisma.apiToken.findUniqueOrThrow({ where: { id: record.id } })
expect(row.tokenHash).toBe(hashToken(token))
expect(row.tokenHash).not.toBe(token)
expect(JSON.stringify(row)).not.toContain(token)
})
it('rejects unknown tokens and the stored hash itself', async () => {
const user = await createUser()
const { record } = await apiTokenService.createToken(user.id, 'cli')
const row = await prisma.apiToken.findUniqueOrThrow({ where: { id: record.id } })
expect(await apiTokenService.validateToken('shumai_not-a-real-token')).toBeNull()
// Presenting the digest must not authenticate (it would be hashed again)
expect(await apiTokenService.validateToken(row.tokenHash)).toBeNull()
})
it('validates legacy tokens hashed by the SQL migration', async () => {
const user = await createUser()
const legacyPlaintext = '01KV5VHB6MR3HCW66C1YRY0A9F'
// Same expression as the hash_api_tokens migration backfill
await prisma.$executeRaw`
INSERT INTO "api_tokens" ("id", "token_hash", "token_hint", "name", "user_id", "updated_at")
VALUES (
'legacy-token-id',
encode(sha256(convert_to(${legacyPlaintext}, 'UTF8')), 'hex'),
right(${legacyPlaintext}, 4),
'legacy',
${user.id},
now()
)
`
expect(hashToken(legacyPlaintext)).toBe(
'd190d6daae5269c015a7e99a23cffa21193f1a56bb785579b337c9ca7708f12c',
)
const validatedUser = await apiTokenService.validateToken(legacyPlaintext)
expect(validatedUser?.id).toBe(user.id)
const [legacy] = await apiTokenService.listTokens(user.id)
expect(legacy.tokenHint).toBe('0A9F')
})
})
+43 -2
View File
@@ -1,20 +1,60 @@
import { createHash, randomBytes } from 'node:crypto'
import { prisma } from '@shumai/db'
const TOKEN_PREFIX = 'shumai_'
const TOKEN_BYTES = 32
const TOKEN_HINT_LENGTH = 4
/**
* Hex-encoded SHA-256 digest of a plaintext API token.
*
* Must stay in sync with the backfill expression in the `hash_api_tokens`
* migration (`encode(sha256(convert_to(token, 'UTF8')), 'hex')`). A fast,
* unsalted hash is sufficient because tokens are long random secrets, not
* user-chosen passwords.
*/
export function hashToken(token: string): string {
return createHash('sha256').update(token, 'utf8').digest('hex')
}
function generateToken(): string {
return `${TOKEN_PREFIX}${randomBytes(TOKEN_BYTES).toString('base64url')}`
}
const tokenSelect = {
id: true,
name: true,
tokenHint: true,
userId: true,
createdAt: true,
updatedAt: true,
} as const
export class ApiTokenService {
async listTokens(userId: string) {
return prisma.apiToken.findMany({
where: { userId },
select: tokenSelect,
orderBy: { id: 'desc' },
})
}
/**
* Create a token for the user. The plaintext is returned only here; it is
* never stored and cannot be retrieved later.
*/
async createToken(userId: string, name: string) {
return prisma.apiToken.create({
const token = generateToken()
const record = await prisma.apiToken.create({
data: {
userId,
name,
tokenHash: hashToken(token),
tokenHint: token.slice(-TOKEN_HINT_LENGTH),
},
select: tokenSelect,
})
return { record, token }
}
async deleteToken(userId: string, tokenId: string) {
@@ -23,12 +63,13 @@ export class ApiTokenService {
id: tokenId,
userId,
},
select: tokenSelect,
})
}
async validateToken(tokenString: string) {
const apiToken = await prisma.apiToken.findUnique({
where: { token: tokenString },
where: { tokenHash: hashToken(tokenString) },
include: { user: true },
})
return apiToken ? apiToken.user : null