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
+2
View File
@@ -12,6 +12,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Changed
* **api-token**: API tokens are now stored securely, so they can no longer be read back from the database. A new token is shown only once when you create it, so copy it right away; the token list now shows just the last few characters. Existing tokens keep working without any changes.
## [0.6.1] - 2026-10-24
### Added
+2 -1
View File
@@ -18,7 +18,8 @@ Before using the CLI, you must set the following environment variables to authen
# The endpoint of your Shumai API server (e.g. http://localhost:3000)
export SHUMAI_API_SERVER="http://localhost:3000"
# Your personal API Token (Generate this in the WebUI via Settings -> Developer tab)
# Your personal API Token (Generate this in the WebUI via Settings -> API Tokens tab).
# The token is shown only once when it is created, so copy it right away.
export SHUMAI_API_KEY="your-developer-api-token"
# Optional: Enable asset deletion capability (disabled by default for safety)
+1 -1
View File
@@ -12,7 +12,7 @@ export function getClient() {
if (!apiKey) {
console.error(
'Error: SHUMAI_API_KEY environment variable is not set. Please generate a token in the Settings -> Developer tab.',
'Error: SHUMAI_API_KEY environment variable is not set. Please generate a token in the Settings -> API Tokens tab.',
)
process.exit(1)
}
+1
View File
@@ -66,6 +66,7 @@ apps/web/e2e/
| Owner removes a member via the members dialog; the membership is deleted from the DB | `tests/team/remove-member.spec.ts` |
| Owner changes a team member role in the members dialog and permissions update | `tests/team/change-member-role.spec.ts` |
| Owner manages resource quotas in settings and resets usage from the dashboard | `tests/team/quotas-settings.spec.ts` |
| Owner creates an API token that is shown once, listed by hint, and authenticates API calls | `tests/team/api-tokens.spec.ts` |
### project
| Test | File |
@@ -0,0 +1,61 @@
import { createHash } from 'node:crypto'
import { expect, test } from '../../fixtures'
import { E2E_APP_URL } from '../../helpers/auth'
test('owner creates an API token that is shown once, listed by hint, and authenticates API calls', async ({
owner,
prisma,
playwright,
}) => {
const { page, teamId } = owner
// 1. Open the API Tokens settings tab
await page.goto(`/teams/${teamId}/settings`)
await page.getByRole('button', { name: /^(API Tokens|API 令牌)$/i }).click()
await expect(page.getByText(/No API tokens found|未找到 API 令牌/i)).toBeVisible()
// 2. Generate a token
await page.fill('#tokenName', 'e2e-cli')
await page.getByRole('button', { name: /^(Generate|生成)$/i }).click()
// 3. The plaintext is shown once in a dialog
const dialog = page.getByRole('dialog')
await expect(dialog.getByText(/Save your API token|保存您的 API 令牌/i)).toBeVisible()
const tokenInput = dialog.getByRole('textbox')
await expect(tokenInput).toHaveValue(/^shumai_[A-Za-z0-9_-]{43}$/)
const token = await tokenInput.inputValue()
await dialog.getByRole('button', { name: /^(Done|完成)$/i }).click()
await expect(dialog).toBeHidden()
// 4. The list identifies the token by name and hint only
const hint = token.slice(-4)
const row = page.getByRole('row', { name: /e2e-cli/ })
await expect(row).toBeVisible()
await expect(row.getByText(`…${hint}`)).toBeVisible()
await expect(page.getByText(token)).toHaveCount(0)
// 5. Only the hash is stored
const stored = await prisma.apiToken.findFirstOrThrow({ where: { name: 'e2e-cli' } })
expect(stored.tokenHash).toBe(createHash('sha256').update(token, 'utf8').digest('hex'))
expect(stored.tokenHint).toBe(hint)
// 6. The token authenticates a request that carries no session cookie
const tokenClient = await playwright.request.newContext({
// eslint-disable-next-line @typescript-eslint/naming-convention
baseURL: E2E_APP_URL,
})
try {
const ok = await tokenClient.get('/api/projects', {
headers: { Authorization: `Bearer ${token}` },
})
expect(ok.status()).toBe(200)
const rejected = await tokenClient.get('/api/projects', {
headers: { Authorization: `Bearer ${stored.tokenHash}` },
})
expect(rejected.status()).toBe(401)
} finally {
await tokenClient.dispose()
}
})
+18 -15
View File
@@ -493,27 +493,27 @@ describe('team api', () => {
vi.mocked(apiTokenService.listTokens).mockResolvedValue([
{
id: 'token1',
token: 'ulid1',
tokenHint: 'a1b2',
name: 'cli-key',
userId: 'user1',
createdAt: mockDate,
updatedAt: mockDate,
},
// Mocking return value of listTokens is simpler with any casting
// eslint-disable-next-line @typescript-eslint/no-explicit-any
] as any)
])
const res = await app.request('/teams/t1/api-tokens')
expect(res.status).toBe(200)
const data = await res.json()
expect(data).toHaveLength(1)
// The plaintext token is never returned when listing
expect(data[0]).toEqual({
id: 'token1',
token: 'ulid1',
tokenHint: 'a1b2',
name: 'cli-key',
createdAt: '2026-06-21T00:00:00.000Z',
})
expect(data[0]).not.toHaveProperty('token')
expect(apiTokenService.listTokens).toHaveBeenCalledWith('user1')
})
@@ -521,15 +521,16 @@ describe('team api', () => {
const { apiTokenService } = await import('@shumai/core/src/user/api-token')
const mockDate = new Date('2026-06-21T00:00:00.000Z')
vi.mocked(apiTokenService.createToken).mockResolvedValue({
id: 'token1',
token: 'ulid1',
name: 'cli-key',
userId: 'user1',
createdAt: mockDate,
updatedAt: mockDate,
// Mocking return value of createToken is simpler with any casting
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
record: {
id: 'token1',
tokenHint: 'a1b2',
name: 'cli-key',
userId: 'user1',
createdAt: mockDate,
updatedAt: mockDate,
},
token: 'shumai_plaintext-a1b2',
})
const res = await app.request('/teams/t1/api-tokens', {
method: 'POST',
@@ -539,9 +540,11 @@ describe('team api', () => {
expect(res.status).toBe(200)
const data = await res.json()
// The plaintext is returned exactly once, at creation
expect(data).toEqual({
id: 'token1',
token: 'ulid1',
token: 'shumai_plaintext-a1b2',
tokenHint: 'a1b2',
name: 'cli-key',
createdAt: '2026-06-21T00:00:00.000Z',
})
+12 -9
View File
@@ -24,6 +24,7 @@ import {
getTeamAiUsageQuerySchema,
AuditAction,
} from '@shumai/dtos'
import type { ApiTokenResponse, CreateApiTokenResponse } from '@shumai/dtos'
import { apiTokenService } from '@shumai/core/src/user/api-token'
import { aiUsageService } from '@shumai/core/src/ai-usage/ai-usage'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
@@ -433,10 +434,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const tokens = await apiTokenService.listTokens(user.id)
return c.json(
tokens.map((t) => ({
tokens.map((t): ApiTokenResponse => ({
id: t.id,
token: t.token,
name: t.name,
tokenHint: t.tokenHint,
createdAt: t.createdAt.toISOString(),
})),
)
@@ -453,13 +454,15 @@ const route = new Hono<{ Variables: { user: User } }>()
id: teamId,
})
const token = await apiTokenService.createToken(user.id, req.name)
return c.json({
id: token.id,
token: token.token,
name: token.name,
createdAt: token.createdAt.toISOString(),
})
const { record, token } = await apiTokenService.createToken(user.id, req.name)
const response: CreateApiTokenResponse = {
id: record.id,
name: record.name,
tokenHint: record.tokenHint,
createdAt: record.createdAt.toISOString(),
token,
}
return c.json(response)
})
.delete('/teams/:teamId/api-tokens/:tokenId', async (c) => {
const user = c.get('user')
+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
@@ -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");
+4 -1
View File
@@ -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)
File diff suppressed because one or more lines are too long
@@ -4940,7 +4940,8 @@ export type CollectionScalarFieldEnum = (typeof CollectionScalarFieldEnum)[keyof
export const ApiTokenScalarFieldEnum = {
id: 'id',
token: 'token',
tokenHash: 'tokenHash',
tokenHint: 'tokenHint',
name: 'name',
userId: 'userId',
createdAt: 'createdAt',
@@ -706,7 +706,8 @@ export type CollectionScalarFieldEnum = (typeof CollectionScalarFieldEnum)[keyof
export const ApiTokenScalarFieldEnum = {
id: 'id',
token: 'token',
tokenHash: 'tokenHash',
tokenHint: 'tokenHint',
name: 'name',
userId: 'userId',
createdAt: 'createdAt',
+78 -37
View File
@@ -28,7 +28,8 @@ export type AggregateApiToken = {
export type ApiTokenMinAggregateOutputType = {
id: string | null
token: string | null
tokenHash: string | null
tokenHint: string | null
name: string | null
userId: string | null
createdAt: Date | null
@@ -37,7 +38,8 @@ export type ApiTokenMinAggregateOutputType = {
export type ApiTokenMaxAggregateOutputType = {
id: string | null
token: string | null
tokenHash: string | null
tokenHint: string | null
name: string | null
userId: string | null
createdAt: Date | null
@@ -46,7 +48,8 @@ export type ApiTokenMaxAggregateOutputType = {
export type ApiTokenCountAggregateOutputType = {
id: number
token: number
tokenHash: number
tokenHint: number
name: number
userId: number
createdAt: number
@@ -57,7 +60,8 @@ export type ApiTokenCountAggregateOutputType = {
export type ApiTokenMinAggregateInputType = {
id?: true
token?: true
tokenHash?: true
tokenHint?: true
name?: true
userId?: true
createdAt?: true
@@ -66,7 +70,8 @@ export type ApiTokenMinAggregateInputType = {
export type ApiTokenMaxAggregateInputType = {
id?: true
token?: true
tokenHash?: true
tokenHint?: true
name?: true
userId?: true
createdAt?: true
@@ -75,7 +80,8 @@ export type ApiTokenMaxAggregateInputType = {
export type ApiTokenCountAggregateInputType = {
id?: true
token?: true
tokenHash?: true
tokenHint?: true
name?: true
userId?: true
createdAt?: true
@@ -157,7 +163,8 @@ export type ApiTokenGroupByArgs<ExtArgs extends runtime.Types.Extensions.Interna
export type ApiTokenGroupByOutputType = {
id: string
token: string
tokenHash: string
tokenHint: string
name: string
userId: string
createdAt: Date
@@ -187,7 +194,8 @@ export type ApiTokenWhereInput = {
OR?: Prisma.ApiTokenWhereInput[]
NOT?: Prisma.ApiTokenWhereInput | Prisma.ApiTokenWhereInput[]
id?: Prisma.StringFilter<"ApiToken"> | string
token?: Prisma.StringFilter<"ApiToken"> | string
tokenHash?: Prisma.StringFilter<"ApiToken"> | string
tokenHint?: Prisma.StringFilter<"ApiToken"> | string
name?: Prisma.StringFilter<"ApiToken"> | string
userId?: Prisma.StringFilter<"ApiToken"> | string
createdAt?: Prisma.DateTimeFilter<"ApiToken"> | Date | string
@@ -197,7 +205,8 @@ export type ApiTokenWhereInput = {
export type ApiTokenOrderByWithRelationInput = {
id?: Prisma.SortOrder
token?: Prisma.SortOrder
tokenHash?: Prisma.SortOrder
tokenHint?: Prisma.SortOrder
name?: Prisma.SortOrder
userId?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
@@ -207,20 +216,22 @@ export type ApiTokenOrderByWithRelationInput = {
export type ApiTokenWhereUniqueInput = Prisma.AtLeast<{
id?: string
token?: string
tokenHash?: string
AND?: Prisma.ApiTokenWhereInput | Prisma.ApiTokenWhereInput[]
OR?: Prisma.ApiTokenWhereInput[]
NOT?: Prisma.ApiTokenWhereInput | Prisma.ApiTokenWhereInput[]
tokenHint?: Prisma.StringFilter<"ApiToken"> | string
name?: Prisma.StringFilter<"ApiToken"> | string
userId?: Prisma.StringFilter<"ApiToken"> | string
createdAt?: Prisma.DateTimeFilter<"ApiToken"> | Date | string
updatedAt?: Prisma.DateTimeFilter<"ApiToken"> | Date | string
user?: Prisma.XOR<Prisma.UserScalarRelationFilter, Prisma.UserWhereInput>
}, "id" | "token">
}, "id" | "tokenHash">
export type ApiTokenOrderByWithAggregationInput = {
id?: Prisma.SortOrder
token?: Prisma.SortOrder
tokenHash?: Prisma.SortOrder
tokenHint?: Prisma.SortOrder
name?: Prisma.SortOrder
userId?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
@@ -235,7 +246,8 @@ export type ApiTokenScalarWhereWithAggregatesInput = {
OR?: Prisma.ApiTokenScalarWhereWithAggregatesInput[]
NOT?: Prisma.ApiTokenScalarWhereWithAggregatesInput | Prisma.ApiTokenScalarWhereWithAggregatesInput[]
id?: Prisma.StringWithAggregatesFilter<"ApiToken"> | string
token?: Prisma.StringWithAggregatesFilter<"ApiToken"> | string
tokenHash?: Prisma.StringWithAggregatesFilter<"ApiToken"> | string
tokenHint?: Prisma.StringWithAggregatesFilter<"ApiToken"> | string
name?: Prisma.StringWithAggregatesFilter<"ApiToken"> | string
userId?: Prisma.StringWithAggregatesFilter<"ApiToken"> | string
createdAt?: Prisma.DateTimeWithAggregatesFilter<"ApiToken"> | Date | string
@@ -244,7 +256,8 @@ export type ApiTokenScalarWhereWithAggregatesInput = {
export type ApiTokenCreateInput = {
id?: string
token?: string
tokenHash: string
tokenHint: string
name: string
createdAt?: Date | string
updatedAt?: Date | string
@@ -253,7 +266,8 @@ export type ApiTokenCreateInput = {
export type ApiTokenUncheckedCreateInput = {
id?: string
token?: string
tokenHash: string
tokenHint: string
name: string
userId: string
createdAt?: Date | string
@@ -262,7 +276,8 @@ export type ApiTokenUncheckedCreateInput = {
export type ApiTokenUpdateInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
token?: Prisma.StringFieldUpdateOperationsInput | string
tokenHash?: Prisma.StringFieldUpdateOperationsInput | string
tokenHint?: Prisma.StringFieldUpdateOperationsInput | string
name?: Prisma.StringFieldUpdateOperationsInput | string
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -271,7 +286,8 @@ export type ApiTokenUpdateInput = {
export type ApiTokenUncheckedUpdateInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
token?: Prisma.StringFieldUpdateOperationsInput | string
tokenHash?: Prisma.StringFieldUpdateOperationsInput | string
tokenHint?: Prisma.StringFieldUpdateOperationsInput | string
name?: Prisma.StringFieldUpdateOperationsInput | string
userId?: Prisma.StringFieldUpdateOperationsInput | string
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -280,7 +296,8 @@ export type ApiTokenUncheckedUpdateInput = {
export type ApiTokenCreateManyInput = {
id?: string
token?: string
tokenHash: string
tokenHint: string
name: string
userId: string
createdAt?: Date | string
@@ -289,7 +306,8 @@ export type ApiTokenCreateManyInput = {
export type ApiTokenUpdateManyMutationInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
token?: Prisma.StringFieldUpdateOperationsInput | string
tokenHash?: Prisma.StringFieldUpdateOperationsInput | string
tokenHint?: Prisma.StringFieldUpdateOperationsInput | string
name?: Prisma.StringFieldUpdateOperationsInput | string
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -297,7 +315,8 @@ export type ApiTokenUpdateManyMutationInput = {
export type ApiTokenUncheckedUpdateManyInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
token?: Prisma.StringFieldUpdateOperationsInput | string
tokenHash?: Prisma.StringFieldUpdateOperationsInput | string
tokenHint?: Prisma.StringFieldUpdateOperationsInput | string
name?: Prisma.StringFieldUpdateOperationsInput | string
userId?: Prisma.StringFieldUpdateOperationsInput | string
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -316,7 +335,8 @@ export type ApiTokenOrderByRelationAggregateInput = {
export type ApiTokenCountOrderByAggregateInput = {
id?: Prisma.SortOrder
token?: Prisma.SortOrder
tokenHash?: Prisma.SortOrder
tokenHint?: Prisma.SortOrder
name?: Prisma.SortOrder
userId?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
@@ -325,7 +345,8 @@ export type ApiTokenCountOrderByAggregateInput = {
export type ApiTokenMaxOrderByAggregateInput = {
id?: Prisma.SortOrder
token?: Prisma.SortOrder
tokenHash?: Prisma.SortOrder
tokenHint?: Prisma.SortOrder
name?: Prisma.SortOrder
userId?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
@@ -334,7 +355,8 @@ export type ApiTokenMaxOrderByAggregateInput = {
export type ApiTokenMinOrderByAggregateInput = {
id?: Prisma.SortOrder
token?: Prisma.SortOrder
tokenHash?: Prisma.SortOrder
tokenHint?: Prisma.SortOrder
name?: Prisma.SortOrder
userId?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
@@ -385,7 +407,8 @@ export type ApiTokenUncheckedUpdateManyWithoutUserNestedInput = {
export type ApiTokenCreateWithoutUserInput = {
id?: string
token?: string
tokenHash: string
tokenHint: string
name: string
createdAt?: Date | string
updatedAt?: Date | string
@@ -393,7 +416,8 @@ export type ApiTokenCreateWithoutUserInput = {
export type ApiTokenUncheckedCreateWithoutUserInput = {
id?: string
token?: string
tokenHash: string
tokenHint: string
name: string
createdAt?: Date | string
updatedAt?: Date | string
@@ -430,7 +454,8 @@ export type ApiTokenScalarWhereInput = {
OR?: Prisma.ApiTokenScalarWhereInput[]
NOT?: Prisma.ApiTokenScalarWhereInput | Prisma.ApiTokenScalarWhereInput[]
id?: Prisma.StringFilter<"ApiToken"> | string
token?: Prisma.StringFilter<"ApiToken"> | string
tokenHash?: Prisma.StringFilter<"ApiToken"> | string
tokenHint?: Prisma.StringFilter<"ApiToken"> | string
name?: Prisma.StringFilter<"ApiToken"> | string
userId?: Prisma.StringFilter<"ApiToken"> | string
createdAt?: Prisma.DateTimeFilter<"ApiToken"> | Date | string
@@ -439,7 +464,8 @@ export type ApiTokenScalarWhereInput = {
export type ApiTokenCreateManyUserInput = {
id?: string
token?: string
tokenHash: string
tokenHint: string
name: string
createdAt?: Date | string
updatedAt?: Date | string
@@ -447,7 +473,8 @@ export type ApiTokenCreateManyUserInput = {
export type ApiTokenUpdateWithoutUserInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
token?: Prisma.StringFieldUpdateOperationsInput | string
tokenHash?: Prisma.StringFieldUpdateOperationsInput | string
tokenHint?: Prisma.StringFieldUpdateOperationsInput | string
name?: Prisma.StringFieldUpdateOperationsInput | string
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -455,7 +482,8 @@ export type ApiTokenUpdateWithoutUserInput = {
export type ApiTokenUncheckedUpdateWithoutUserInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
token?: Prisma.StringFieldUpdateOperationsInput | string
tokenHash?: Prisma.StringFieldUpdateOperationsInput | string
tokenHint?: Prisma.StringFieldUpdateOperationsInput | string
name?: Prisma.StringFieldUpdateOperationsInput | string
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -463,7 +491,8 @@ export type ApiTokenUncheckedUpdateWithoutUserInput = {
export type ApiTokenUncheckedUpdateManyWithoutUserInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
token?: Prisma.StringFieldUpdateOperationsInput | string
tokenHash?: Prisma.StringFieldUpdateOperationsInput | string
tokenHint?: Prisma.StringFieldUpdateOperationsInput | string
name?: Prisma.StringFieldUpdateOperationsInput | string
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -473,7 +502,8 @@ export type ApiTokenUncheckedUpdateManyWithoutUserInput = {
export type ApiTokenSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
id?: boolean
token?: boolean
tokenHash?: boolean
tokenHint?: boolean
name?: boolean
userId?: boolean
createdAt?: boolean
@@ -483,7 +513,8 @@ export type ApiTokenSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs
export type ApiTokenSelectCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
id?: boolean
token?: boolean
tokenHash?: boolean
tokenHint?: boolean
name?: boolean
userId?: boolean
createdAt?: boolean
@@ -493,7 +524,8 @@ export type ApiTokenSelectCreateManyAndReturn<ExtArgs extends runtime.Types.Exte
export type ApiTokenSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
id?: boolean
token?: boolean
tokenHash?: boolean
tokenHint?: boolean
name?: boolean
userId?: boolean
createdAt?: boolean
@@ -503,14 +535,15 @@ export type ApiTokenSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.Exte
export type ApiTokenSelectScalar = {
id?: boolean
token?: boolean
tokenHash?: boolean
tokenHint?: boolean
name?: boolean
userId?: boolean
createdAt?: boolean
updatedAt?: boolean
}
export type ApiTokenOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "token" | "name" | "userId" | "createdAt" | "updatedAt", ExtArgs["result"]["apiToken"]>
export type ApiTokenOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "tokenHash" | "tokenHint" | "name" | "userId" | "createdAt" | "updatedAt", ExtArgs["result"]["apiToken"]>
export type ApiTokenInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
user?: boolean | Prisma.UserDefaultArgs<ExtArgs>
}
@@ -528,7 +561,14 @@ export type $ApiTokenPayload<ExtArgs extends runtime.Types.Extensions.InternalAr
}
scalars: runtime.Types.Extensions.GetPayloadResult<{
id: string
token: string
/**
* SHA-256 hex digest of the plaintext token. The plaintext is never stored.
*/
tokenHash: string
/**
* Last characters of the plaintext token, shown in the UI to identify it.
*/
tokenHint: string
name: string
userId: string
createdAt: Date
@@ -958,7 +998,8 @@ export interface Prisma__ApiTokenClient<T, Null = never, ExtArgs extends runtime
*/
export interface ApiTokenFieldRefs {
readonly id: Prisma.FieldRef<"ApiToken", 'String'>
readonly token: Prisma.FieldRef<"ApiToken", 'String'>
readonly tokenHash: Prisma.FieldRef<"ApiToken", 'String'>
readonly tokenHint: Prisma.FieldRef<"ApiToken", 'String'>
readonly name: Prisma.FieldRef<"ApiToken", 'String'>
readonly userId: Prisma.FieldRef<"ApiToken", 'String'>
readonly createdAt: Prisma.FieldRef<"ApiToken", 'DateTime'>
+9 -1
View File
@@ -11,10 +11,18 @@ export const createApiTokenRequestSchema = z.object({
})
export type CreateApiTokenRequest = z.infer<typeof createApiTokenRequestSchema>
/** An API token as listed in settings. The plaintext is never returned after creation. */
export const apiTokenResponseSchema = z.object({
id: z.string(),
token: z.string(),
name: z.string(),
/** Last characters of the token, used to identify it in the UI. */
tokenHint: z.string(),
createdAt: z.string(),
})
export type ApiTokenResponse = z.infer<typeof apiTokenResponseSchema>
/** Returned once when a token is created; `token` is the only time the plaintext is exposed. */
export const createApiTokenResponseSchema = apiTokenResponseSchema.extend({
token: z.string(),
})
export type CreateApiTokenResponse = z.infer<typeof createApiTokenResponseSchema>
@@ -15,13 +15,23 @@ import {
import { Loader2, Plus, Trash2, Copy, Check } from 'lucide-react'
import { toast } from 'sonner'
import { copyToClipboard } from '@/ui/lib/clipboard'
import type { ApiTokenResponse } from '@shumai/dtos'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
import type { ApiTokenResponse, CreateApiTokenResponse } from '@shumai/dtos'
import { m } from '@/ui/paraglide/messages.js'
export function DeveloperSettings({ teamId }: { teamId: string }) {
const queryClient = useQueryClient()
const [tokenName, setTokenName] = useState('')
const [copiedId, setCopiedId] = useState<string | null>(null)
// Plaintext of a just-created token. It is only available in the create response.
const [createdToken, setCreatedToken] = useState<CreateApiTokenResponse | null>(null)
const [copied, setCopied] = useState(false)
const { data: tokens, isLoading } = useQuery<ApiTokenResponse[]>({
queryKey: ['teams', teamId, 'api-tokens'],
@@ -41,11 +51,13 @@ export function DeveloperSettings({ teamId }: { teamId: string }) {
json: { name },
})
if (!res.ok) throw new Error('Failed to create API token')
return (await res.json()) as ApiTokenResponse
return (await res.json()) as CreateApiTokenResponse
},
onSuccess: () => {
onSuccess: (created) => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'api-tokens'] })
setTokenName('')
setCopied(false)
setCreatedToken(created)
toast.success(m.api_token_generated_successfully())
},
onError: (err) => {
@@ -76,11 +88,11 @@ export function DeveloperSettings({ teamId }: { teamId: string }) {
createToken(tokenName.trim())
}
const handleCopy = async (id: string, token: string) => {
const handleCopy = async (token: string) => {
await copyToClipboard(token)
setCopiedId(id)
setCopied(true)
toast.success(m.copied_api_token_to_clipboard())
setTimeout(() => setCopiedId(null), 2000)
setTimeout(() => setCopied(false), 2000)
}
if (isLoading) {
@@ -146,22 +158,8 @@ export function DeveloperSettings({ teamId }: { teamId: string }) {
tokens.map((token) => (
<TableRow key={token.id}>
<TableCell className="font-medium">{token.name}</TableCell>
<TableCell className="font-mono text-sm max-w-[200px] truncate">
<div className="flex items-center gap-2">
<span>{token.token.substring(0, 8)}...</span>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => handleCopy(token.id, token.token)}
>
{copiedId === token.id ? (
<Check className="h-3.5 w-3.5 text-green-500" />
) : (
<Copy className="h-3.5 w-3.5" />
)}
</Button>
</div>
<TableCell className="font-mono text-sm text-muted-foreground">
…{token.tokenHint}
</TableCell>
<TableCell className="text-muted-foreground">
{new Date(token.createdAt).toLocaleDateString()}
@@ -182,8 +180,45 @@ export function DeveloperSettings({ teamId }: { teamId: string }) {
</TableBody>
</Table>
</div>
<p className="text-xs text-muted-foreground">{m.api_token_hidden_hint()}</p>
</CardContent>
</Card>
<Dialog
open={createdToken !== null}
onOpenChange={(open) => {
if (!open) setCreatedToken(null)
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>{m.api_token_created_title()}</DialogTitle>
<DialogDescription>{m.api_token_created_description()}</DialogDescription>
</DialogHeader>
{createdToken && (
<div className="flex items-center gap-2">
<Input
readOnly
value={createdToken.token}
aria-label={m.token()}
className="font-mono text-sm"
onFocus={(e) => e.currentTarget.select()}
/>
<Button
variant="outline"
size="icon"
aria-label={m.copy()}
onClick={() => handleCopy(createdToken.token)}
>
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
</Button>
</div>
)}
<DialogFooter>
<Button onClick={() => setCreatedToken(null)}>{m.done()}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}
+3
View File
@@ -388,6 +388,9 @@
"failed_to_revoke_token": "Failed to revoke token",
"copied_to_clipboard": "Copied to clipboard",
"copied_api_token_to_clipboard": "Copied API token to clipboard",
"api_token_created_title": "Save your API token",
"api_token_created_description": "Copy this token now and store it somewhere safe. For your security, it won't be shown again.",
"api_token_hidden_hint": "Tokens can only be viewed when they are created.",
"copy_name_and_download_link": "Copy name and download link",
"copied_name_and_download_link_to_clipboard": "Copied name and download link to clipboard",
+3
View File
@@ -388,6 +388,9 @@
"failed_to_revoke_token": "撤销令牌失败",
"copied_to_clipboard": "已复制到剪贴板",
"copied_api_token_to_clipboard": "已将 API 令牌复制到剪贴板",
"api_token_created_title": "保存您的 API 令牌",
"api_token_created_description": "请立即复制此令牌并妥善保存。出于安全考虑,它将不会再次显示。",
"api_token_hidden_hint": "令牌仅在创建时可见。",
"copy_name_and_download_link": "复制名称和下载链接",
"copied_name_and_download_link_to_clipboard": "已复制名称和下载链接到剪贴板",