mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-04 15:14:10 +00:00
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:
@@ -0,0 +1,28 @@
|
||||
-- Store API tokens as SHA-256 digests instead of plaintext.
|
||||
--
|
||||
-- Existing tokens keep working: their plaintext is hashed in place with the same
|
||||
-- algorithm the application uses (hex-encoded SHA-256 of the UTF-8 token), so
|
||||
-- clients holding the plaintext still authenticate. This migration is one-way:
|
||||
-- after it runs the plaintext values are gone.
|
||||
|
||||
-- AlterTable: add the new columns as nullable so existing rows can be backfilled
|
||||
ALTER TABLE "api_tokens" ADD COLUMN "token_hash" TEXT,
|
||||
ADD COLUMN "token_hint" TEXT;
|
||||
|
||||
-- Backfill: keep the last 4 characters for display, then hash the plaintext
|
||||
UPDATE "api_tokens"
|
||||
SET "token_hint" = right("token", 4),
|
||||
"token_hash" = encode(sha256(convert_to("token", 'UTF8')), 'hex');
|
||||
|
||||
-- AlterTable: enforce the final shape
|
||||
ALTER TABLE "api_tokens" ALTER COLUMN "token_hash" SET NOT NULL,
|
||||
ALTER COLUMN "token_hint" SET NOT NULL;
|
||||
|
||||
-- DropIndex
|
||||
DROP INDEX "api_tokens_token_key";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "api_tokens" DROP COLUMN "token";
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "api_tokens_token_hash_key" ON "api_tokens"("token_hash");
|
||||
@@ -1089,7 +1089,10 @@ model Collection {
|
||||
|
||||
model ApiToken {
|
||||
id String @id @default(ulid())
|
||||
token String @unique @default(ulid())
|
||||
/// SHA-256 hex digest of the plaintext token. The plaintext is never stored.
|
||||
tokenHash String @unique @map("token_hash")
|
||||
/// Last characters of the plaintext token, shown in the UI to identify it.
|
||||
tokenHint String @map("token_hint")
|
||||
name String
|
||||
userId String @map("user_id")
|
||||
user User @relation("UserToApiToken", fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
Reference in New Issue
Block a user