diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 74a6c536..e7f9d266 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,15 +1,12 @@ name: CI on: - push: - branches: - - develop pull_request: branches: - - develop + - main jobs: - quality: + lint: runs-on: ubuntu-latest steps: @@ -27,8 +24,20 @@ jobs: - name: Run lint run: bun run lint - - name: Run type check - run: bun run check + unit-tests: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Setup Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version: latest + + - name: Install dependencies + run: bun install - - name: Run formatting check - run: bun run format:check + - name: Run unit tests + run: bun test diff --git a/bun.lock b/bun.lock index 1ee6f4c0..48793425 100644 --- a/bun.lock +++ b/bun.lock @@ -21,6 +21,7 @@ "@types/node": "^22.10.1", "@typescript-eslint/eslint-plugin": "^8.17.0", "@typescript-eslint/parser": "^8.17.0", + "@vitest/coverage-v8": "^4.1.11", "autoprefixer": "^10.5.3", "eslint": "^9.14.0", "eslint-config-prettier": "^9.0.0", @@ -81,6 +82,16 @@ "@aws/lambda-invoke-store": ["@aws/lambda-invoke-store@0.3.0", "", {}, "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ=="], + "@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="], + + "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], + + "@babel/parser": ["@babel/parser@7.29.8", "", { "dependencies": { "@babel/types": "^7.29.8" }, "bin": "./bin/babel-parser.js" }, "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA=="], + + "@babel/types": ["@babel/types@7.29.8", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg=="], + + "@bcoe/v8-coverage": ["@bcoe/v8-coverage@1.0.2", "", {}, "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA=="], + "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.21.5", "", { "os": "aix", "cpu": "ppc64" }, "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ=="], "@esbuild/android-arm": ["@esbuild/android-arm@0.21.5", "", { "os": "android", "cpu": "arm" }, "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg=="], @@ -359,6 +370,8 @@ "@typescript-eslint/visitor-keys": ["@typescript-eslint/visitor-keys@8.64.0", "", { "dependencies": { "@typescript-eslint/types": "8.64.0", "eslint-visitor-keys": "^5.0.0" } }, "sha512-mrtuL8Nsn6gi2H4mo5KMTp823M+3Q19Ew/i+Zlikq20tIMm99C3Ez0dCmkWWnxut20esQvTg8aUSEhMcAOXhEw=="], + "@vitest/coverage-v8": ["@vitest/coverage-v8@4.1.11", "", { "dependencies": { "@bcoe/v8-coverage": "^1.0.2", "@vitest/utils": "4.1.11", "ast-v8-to-istanbul": "^1.0.0", "istanbul-lib-coverage": "^3.2.2", "istanbul-lib-report": "^3.0.1", "istanbul-reports": "^3.2.0", "magicast": "^0.5.2", "obug": "^2.1.1", "std-env": "^4.0.0-rc.1", "tinyrainbow": "^3.1.0" }, "peerDependencies": { "@vitest/browser": "4.1.11", "vitest": "4.1.11" }, "optionalPeers": ["@vitest/browser"] }, "sha512-8MVGEFnJIcdGjcbfKmeq8z0pZHH0JlVtoVZH9Q/qwUp6wyFnEJUBMrw9DCaj+ra3vShGmhavjalMIhPNxZAUcw=="], + "@vitest/expect": ["@vitest/expect@4.1.11", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.1.11", "@vitest/utils": "4.1.11", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" } }, "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw=="], "@vitest/mocker": ["@vitest/mocker@4.1.11", "", { "dependencies": { "@vitest/spy": "4.1.11", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ=="], @@ -395,6 +408,8 @@ "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], + "ast-v8-to-istanbul": ["ast-v8-to-istanbul@1.0.5", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.31", "estree-walker": "^3.0.3", "js-tokens": "^10.0.0" } }, "sha512-UPAgKJFSEGMWSDr3LX4tqnAb4f7KGT8O40Tyx8wbYmmZ/yn58lNCm8h3svs3eXgiGd5AXxz8NDOvXWvicq+rJA=="], + "async-retry": ["async-retry@1.3.3", "", { "dependencies": { "retry": "0.13.1" } }, "sha512-wfr/jstw9xNi/0teMHrRW7dsz3Lt5ARhYNZ2ewpadnhaIp5mbALhOAP+EAdsC7t4Z6wqsDVv9+W6gm1Dk9mEyw=="], "asynckit": ["asynckit@0.4.0", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="], @@ -605,6 +620,8 @@ "html-entities": ["html-entities@2.6.0", "", {}, "sha512-kig+rMn/QOVRvr7c86gQ8lWXq+Hkv6CbAH1hLu+RG338StTpE8Z0b44SDVaqVu7HGKf27frdmUYEs9hTUX/cLQ=="], + "html-escaper": ["html-escaper@2.0.2", "", {}, "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg=="], + "http-proxy-agent": ["http-proxy-agent@5.0.0", "", { "dependencies": { "@tootallnate/once": "2", "agent-base": "6", "debug": "4" } }, "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w=="], "https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="], @@ -637,8 +654,16 @@ "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], + "istanbul-lib-coverage": ["istanbul-lib-coverage@3.2.2", "", {}, "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg=="], + + "istanbul-lib-report": ["istanbul-lib-report@3.0.1", "", { "dependencies": { "istanbul-lib-coverage": "^3.0.0", "make-dir": "^4.0.0", "supports-color": "^7.1.0" } }, "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw=="], + + "istanbul-reports": ["istanbul-reports@3.2.0", "", { "dependencies": { "html-escaper": "^2.0.0", "istanbul-lib-report": "^3.0.0" } }, "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA=="], + "jiti": ["jiti@2.7.0", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="], + "js-tokens": ["js-tokens@10.0.0", "", {}, "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q=="], + "js-yaml": ["js-yaml@4.3.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q=="], "json-bigint": ["json-bigint@1.0.0", "", { "dependencies": { "bignumber.js": "^9.0.0" } }, "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ=="], @@ -697,6 +722,10 @@ "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], + "magicast": ["magicast@0.5.4", "", { "dependencies": { "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7", "source-map-js": "^1.2.1" } }, "sha512-llBEhWm1SacoRwgHUoQJYtwp4PBLF4faQi5TCpIGyGs9n4y5+juI0tDgyKIfpqxckRHaHzouUEph3THklWh03w=="], + + "make-dir": ["make-dir@4.0.0", "", { "dependencies": { "semver": "^7.5.3" } }, "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw=="], + "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="], "mdn-data": ["mdn-data@2.0.30", "", {}, "sha512-GaqWWShW4kv/G9IEucWScBx9G1/vsFZZJUO+tD26M8J8z3Kw5RDQjaoZe03YAClgeS/SWPOcb4nkFBTEi5DUEA=="], diff --git a/package.json b/package.json index 5b941757..062bc152 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,8 @@ "preview": "vite preview", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "lint": "eslint . --ext .js,.ts,.svelte", + "test": "vitest run", + "test:watch": "vitest", "format": "prettier --write .", "format:check": "prettier --check .", "test": "vitest run", @@ -25,6 +27,7 @@ "@types/node": "^22.10.1", "@typescript-eslint/eslint-plugin": "^8.17.0", "@typescript-eslint/parser": "^8.17.0", + "@vitest/coverage-v8": "^4.1.11", "autoprefixer": "^10.5.3", "eslint": "^9.14.0", "eslint-config-prettier": "^9.0.0", diff --git a/src/lib/database/schemas.ts b/src/lib/database/schemas.ts index 8a2ba5f7..697122b2 100644 --- a/src/lib/database/schemas.ts +++ b/src/lib/database/schemas.ts @@ -29,6 +29,7 @@ export const ApiKeyEntity = entity('api_keys', { name: text().notNull(), keyPrefix: text().notNull(), keyHash: text().notNull(), + expiresAt: timestamp(), lastUsedAt: timestamp(), revokedAt: timestamp(), createdAt: timestamp().notNull().$defaultFn(() => new Date().toISOString()), diff --git a/src/modules/auth/application/apikeys.service.test.ts b/src/modules/auth/application/apikeys.service.test.ts new file mode 100644 index 00000000..1ddb7a97 --- /dev/null +++ b/src/modules/auth/application/apikeys.service.test.ts @@ -0,0 +1,182 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { ApiKeysService } from './apikeys.service'; +import type { ApiKeyView } from '../domain/entities'; + +function createRepositoryMock(): any { + return { + listByUser: vi.fn(), + findValidByHash: vi.fn(), + create: vi.fn(), + findById: vi.fn(), + revoke: vi.fn(), + updateKeyMaterial: vi.fn(), + }; +} + +describe('ApiKeysService', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('lists keys through the repository', async () => { + const repository = createRepositoryMock(); + const keys: ApiKeyView[] = [ + { + id: 'key-1', + name: 'Deploy', + keyPrefix: 'gvs_12', + expiresAt: null, + lastUsedAt: null, + revokedAt: null, + createdAt: '2026-08-18T00:00:00.000Z', + }, + ]; + + repository.listByUser.mockImplementation(async () => keys); + + const service = new ApiKeysService(repository); + + await expect(service.listActiveApiKeys('user-1')).resolves.toEqual(keys); + expect(repository.listByUser).toHaveBeenCalledWith('user-1'); + }); + + it('validates an active api key token', async () => { + const repository = createRepositoryMock(); + repository.findValidByHash.mockImplementation(async () => ({ + id: 'key-1', + name: 'Deploy', + keyPrefix: 'gvs_12', + expiresAt: null, + lastUsedAt: null, + revokedAt: null, + createdAt: '2026-08-18T00:00:00.000Z', + })); + + const service = new ApiKeysService(repository); + + await expect(service.validateApiKey('gvs_121212')).resolves.toBe(true); + expect(repository.findValidByHash).toHaveBeenCalledWith(expect.any(String)); + }); + + it('rejects empty api key tokens', async () => { + const repository = createRepositoryMock(); + const service = new ApiKeysService(repository); + + await expect(service.validateApiKey(' ')).resolves.toBe(false); + expect(repository.findValidByHash).not.toHaveBeenCalled(); + }); + + it('returns false when the token does not map to an active key', async () => { + const repository = createRepositoryMock(); + repository.findValidByHash.mockImplementation(async () => null); + + const service = new ApiKeysService(repository); + + await expect(service.validateApiKey('gvs_missing')).resolves.toBe(false); + expect(repository.findValidByHash).toHaveBeenCalledWith(expect.any(String)); + }); + + it('creates a key with a capped prefix and hashed token', async () => { + const repository = createRepositoryMock(); + const service = new ApiKeysService(repository); + + const result = await service.createApiKey('user-1', 'Deploy', '2026-12-31T00:00:00.000Z'); + + expect(result.token.startsWith('gvs_')).toBe(true); + expect(result.key).toMatchObject({ + id: expect.any(String), + name: 'Deploy', + keyPrefix: result.token.slice(0, 6), + expiresAt: '2026-12-31T00:00:00.000Z', + lastUsedAt: null, + revokedAt: null, + }); + + expect(repository.create).toHaveBeenCalledWith({ + id: expect.any(String), + userId: 'user-1', + name: 'Deploy', + keyPrefix: result.token.slice(0, 6), + keyHash: expect.any(String), + expiresAt: '2026-12-31T00:00:00.000Z', + }); + }); + + it('revokes an active key and rejects already revoked keys', async () => { + const repository = createRepositoryMock(); + repository.findById + .mockImplementationOnce(async () => ({ + id: 'key-1', + name: 'Deploy', + keyPrefix: 'gvs_12', + expiresAt: null, + lastUsedAt: null, + revokedAt: null, + createdAt: '2026-08-18T00:00:00.000Z', + })) + .mockImplementationOnce(async () => ({ + id: 'key-1', + name: 'Deploy', + keyPrefix: 'gvs_12', + expiresAt: null, + lastUsedAt: null, + revokedAt: '2026-08-18T00:10:00.000Z', + createdAt: '2026-08-18T00:00:00.000Z', + })); + + const service = new ApiKeysService(repository); + + await service.revokeApiKey('user-1', 'key-1'); + await expect(service.revokeApiKey('user-1', 'key-1')).rejects.toThrow('API key is already revoked'); + expect(repository.revoke).toHaveBeenCalledTimes(1); + }); + + it('regenerates the same record instead of creating a new one', async () => { + const repository = createRepositoryMock(); + repository.findById.mockImplementation(async () => ({ + id: 'key-1', + name: 'Deploy', + keyPrefix: 'gvs_old', + expiresAt: '2026-12-31T00:00:00.000Z', + lastUsedAt: null, + revokedAt: null, + createdAt: '2026-08-18T00:00:00.000Z', + })); + + const service = new ApiKeysService(repository); + const result = await service.regenerateApiKey('user-1', 'key-1'); + + expect(repository.updateKeyMaterial).toHaveBeenCalledWith('user-1', 'key-1', { + keyPrefix: result.token.slice(0, 6), + keyHash: expect.any(String), + expiresAt: '2026-12-31T00:00:00.000Z', + }); + expect(repository.create).not.toHaveBeenCalled(); + expect(result.key).toMatchObject({ + id: 'key-1', + name: 'Deploy', + keyPrefix: result.token.slice(0, 6), + expiresAt: '2026-12-31T00:00:00.000Z', + lastUsedAt: null, + revokedAt: null, + }); + }); + + it('does not regenerate revoked keys', async () => { + const repository = createRepositoryMock(); + repository.findById.mockImplementation(async () => ({ + id: 'key-1', + name: 'Deploy', + keyPrefix: 'gvs_old', + expiresAt: null, + lastUsedAt: null, + revokedAt: '2026-08-18T00:10:00.000Z', + createdAt: '2026-08-18T00:00:00.000Z', + })); + + const service = new ApiKeysService(repository); + + await expect(service.regenerateApiKey('user-1', 'key-1')).rejects.toThrow('API key is revoked'); + expect(repository.updateKeyMaterial).not.toHaveBeenCalled(); + }); +}); \ No newline at end of file diff --git a/src/modules/auth/application/apikeys.service.ts b/src/modules/auth/application/apikeys.service.ts index 75910007..dd990ca3 100644 --- a/src/modules/auth/application/apikeys.service.ts +++ b/src/modules/auth/application/apikeys.service.ts @@ -1,10 +1,105 @@ -import type { AuthUserRepository } from '../domain/repositories'; +import crypto from 'crypto'; +import type { ApiKeyView } from '../domain/entities'; +import { ApiKeyRepository } from '../infrastructure/repositories/apikey.repository'; + +function hashApiKey(token: string): string { + return crypto.createHash('sha256').update(token).digest('hex'); +} export class ApiKeysService { constructor( - private readonly userRepository: AuthUserRepository, + private readonly apiKeyRepository: ApiKeyRepository, ) {} + async listActiveApiKeys(userId: string): Promise { + return this.apiKeyRepository.listByUser(userId); + } + + async validateApiKey(token: string): Promise { + if (!token.trim()) { + return false; + } + + const key = await this.apiKeyRepository.findValidByHash(hashApiKey(token)); + return key !== null; + } + + async createApiKey(userId: string, name: string, expiresAt: string | null): Promise<{ token: string; key: ApiKeyView }> { + const token = `gvs_${crypto.randomBytes(24).toString('hex')}`; + const id = crypto.randomUUID(); + const keyPrefix = token.slice(0, 6); + + await this.apiKeyRepository.create({ + id, + userId, + name, + keyPrefix, + keyHash: hashApiKey(token), + expiresAt, + }); + + return { + token, + key: { + id, + name, + keyPrefix, + expiresAt, + lastUsedAt: null, + revokedAt: null, + createdAt: new Date().toISOString(), + }, + }; + } + + async revokeApiKey(userId: string, keyId: string): Promise { + const existing = await this.apiKeyRepository.findById(userId, keyId); + + if (!existing) { + throw new Error('API key not found'); + } + + if (existing.revokedAt) { + throw new Error('API key is already revoked'); + } + + await this.apiKeyRepository.revoke(userId, keyId); + } + + async regenerateApiKey(userId: string, keyId: string): Promise<{ token: string; key: ApiKeyView }> { + const existing = await this.apiKeyRepository.findById(userId, keyId); + + if (!existing) { + throw new Error('API key not found'); + } + + if (existing.revokedAt) { + throw new Error('API key is revoked'); + } + + const token = `gvs_${crypto.randomBytes(24).toString('hex')}`; + const keyPrefix = token.slice(0, 6); + + await this.apiKeyRepository.updateKeyMaterial(userId, keyId, { + keyPrefix, + keyHash: hashApiKey(token), + expiresAt: existing.expiresAt, + }); + + return { + token, + key: { + id: keyId, + name: existing.name, + keyPrefix, + expiresAt: existing.expiresAt, + lastUsedAt: null, + revokedAt: null, + createdAt: new Date().toISOString(), + }, + }; + } + } \ No newline at end of file diff --git a/src/modules/auth/application/profile.service.test.ts b/src/modules/auth/application/profile.service.test.ts new file mode 100644 index 00000000..f044c102 --- /dev/null +++ b/src/modules/auth/application/profile.service.test.ts @@ -0,0 +1,129 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { ProfileService } from './profile.service'; +import type { PasswordService } from './password.service'; +import type { UserRepository } from '../infrastructure/repositories/user.repository'; + +function createUserRepositoryMock() { + return { + findById: vi.fn(), + findByUsername: vi.fn(), + listUsers: vi.fn(), + createUser: vi.fn(), + updateEmail: vi.fn(), + updatePassword: vi.fn(), + updateRole: vi.fn(), + deleteById: vi.fn(), + countAdmins: vi.fn(), + listActiveApiKeys: vi.fn(), + createApiKey: vi.fn(), + revokeApiKey: vi.fn(), + } as unknown as UserRepository; +} + +function createPasswordServiceMock() { + return { + ensureEncryptionKey: vi.fn(), + hashPassword: vi.fn(), + verifyPassword: vi.fn(), + } as unknown as PasswordService; +} + +describe('ProfileService', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('returns the authenticated user profile as JSON', async () => { + const userRepository = createUserRepositoryMock(); + const passwordService = createPasswordServiceMock(); + const service = new ProfileService(userRepository, passwordService); + + const user = { + toJson: vi.fn().mockReturnValue({ + id: 'user-1', + username: 'alice', + email: 'alice@example.com', + role: { id: 'role-1', name: 'Developer' }, + createdAt: '2026-08-18T00:00:00.000Z', + }), + }; + + userRepository.findById.mockResolvedValue(user); + + await expect(service.getAuthenticatedUserProfile('user-1')).resolves.toEqual({ + id: 'user-1', + username: 'alice', + email: 'alice@example.com', + role: { id: 'role-1', name: 'Developer' }, + createdAt: '2026-08-18T00:00:00.000Z', + }); + + expect(userRepository.findById).toHaveBeenCalledWith('user-1'); + expect(user.toJson).toHaveBeenCalledTimes(1); + }); + + it('returns null when the user profile does not exist', async () => { + const userRepository = createUserRepositoryMock(); + const passwordService = createPasswordServiceMock(); + const service = new ProfileService(userRepository, passwordService); + + userRepository.findById.mockResolvedValue(null); + + await expect(service.getAuthenticatedUserProfile('missing-user')).resolves.toBeNull(); + expect(userRepository.findById).toHaveBeenCalledWith('missing-user'); + }); + + it('updates the email address', async () => { + const userRepository = createUserRepositoryMock(); + const passwordService = createPasswordServiceMock(); + const service = new ProfileService(userRepository, passwordService); + + await service.updateEmail('user-1', 'new@example.com'); + + expect(userRepository.updateEmail).toHaveBeenCalledWith('user-1', 'new@example.com'); + }); + + it('changes the password when the current password is valid', async () => { + const userRepository = createUserRepositoryMock(); + const passwordService = createPasswordServiceMock(); + const service = new ProfileService(userRepository, passwordService); + + userRepository.findById.mockResolvedValue({ + password: 'hashed-current', + }); + passwordService.verifyPassword.mockReturnValue(true); + passwordService.hashPassword.mockReturnValue('hashed-new'); + + await expect(service.changePassword('user-1', 'current-pass', 'new-pass')).resolves.toBe(true); + expect(passwordService.verifyPassword).toHaveBeenCalledWith('current-pass', 'hashed-current'); + expect(passwordService.hashPassword).toHaveBeenCalledWith('new-pass'); + expect(userRepository.updatePassword).toHaveBeenCalledWith('user-1', 'hashed-new'); + }); + + it('returns false when the current password is invalid', async () => { + const userRepository = createUserRepositoryMock(); + const passwordService = createPasswordServiceMock(); + const service = new ProfileService(userRepository, passwordService); + + userRepository.findById.mockResolvedValue({ + password: 'hashed-current', + }); + passwordService.verifyPassword.mockReturnValue(false); + + await expect(service.changePassword('user-1', 'wrong-pass', 'new-pass')).resolves.toBe(false); + expect(userRepository.updatePassword).not.toHaveBeenCalled(); + expect(passwordService.hashPassword).not.toHaveBeenCalled(); + }); + + it('returns false when the user does not exist', async () => { + const userRepository = createUserRepositoryMock(); + const passwordService = createPasswordServiceMock(); + const service = new ProfileService(userRepository, passwordService); + + userRepository.findById.mockResolvedValue(null); + + await expect(service.changePassword('missing-user', 'current-pass', 'new-pass')).resolves.toBe(false); + expect(passwordService.verifyPassword).not.toHaveBeenCalled(); + expect(userRepository.updatePassword).not.toHaveBeenCalled(); + }); +}); \ No newline at end of file diff --git a/src/modules/auth/application/profile.service.ts b/src/modules/auth/application/profile.service.ts index dcadf999..9922b503 100644 --- a/src/modules/auth/application/profile.service.ts +++ b/src/modules/auth/application/profile.service.ts @@ -1,12 +1,6 @@ -import crypto from 'crypto'; -import type { ApiKeyView, AuthenticatedUser } from '../domain/entities'; import { UserRepository } from '../infrastructure/repositories/user.repository'; import { PasswordService } from './password.service'; -function hashApiKey(token: string): string { - return crypto.createHash('sha256').update(token).digest('hex'); -} - export class ProfileService { constructor( private readonly userRepository: UserRepository, @@ -32,50 +26,11 @@ export class ProfileService { return false; } - if (!this.passwordService.verifyPassword(currentPassword, user.passwordHash)) { + if (!this.passwordService.verifyPassword(currentPassword, user.password)) { return false; } await this.userRepository.updatePassword(userId, this.passwordService.hashPassword(newPassword)); return true; } - - async listActiveApiKeys(userId: string): Promise { - const keys = await this.userRepository.listActiveApiKeys(userId); - return keys.map((key) => ({ - id: key.id, - name: key.name, - keyPrefix: key.keyPrefix, - lastUsedAt: key.lastUsedAt, - createdAt: key.createdAt, - })); - } - - async createApiKey(userId: string, name: string): Promise<{ token: string; key: ApiKeyView }> { - const token = `gvs_${crypto.randomBytes(24).toString('hex')}`; - const id = crypto.randomUUID(); - - await this.userRepository.createApiKey({ - id, - userId, - name, - keyPrefix: token.slice(0, 10), - keyHash: hashApiKey(token), - }); - - return { - token, - key: { - id, - name, - keyPrefix: token.slice(0, 10), - lastUsedAt: null, - createdAt: new Date().toISOString(), - }, - }; - } - - async revokeApiKey(userId: string, keyId: string): Promise { - await this.userRepository.revokeApiKey(userId, keyId); - } } diff --git a/src/modules/auth/domain/entities.ts b/src/modules/auth/domain/entities.ts index 82dfa776..a972ceef 100644 --- a/src/modules/auth/domain/entities.ts +++ b/src/modules/auth/domain/entities.ts @@ -60,6 +60,8 @@ export type ApiKeyView = { id: string; name: string; keyPrefix: string; + expiresAt: string | null; lastUsedAt: string | null; + revokedAt: string | null; createdAt: string; }; diff --git a/src/modules/auth/index.ts b/src/modules/auth/index.ts index 070a6e96..5cbb6053 100644 --- a/src/modules/auth/index.ts +++ b/src/modules/auth/index.ts @@ -1,5 +1,6 @@ import { canAccessAdminArea, isAdmin, can, hasPermission } from './domain/rbac'; import { AuthService } from './application/auth.service'; +import { ApiKeysService } from './application/apikeys.service'; import { PasswordService } from './application/password.service'; import { ProfileService } from './application/profile.service'; import { SessionService } from './application/session.service'; @@ -7,12 +8,15 @@ import { UserService } from './application/user.service'; import { RoleService } from './application/role.service'; import { UserRepository } from './infrastructure/repositories/user.repository'; import { RoleRepository } from './infrastructure/repositories/role.repository'; +import { ApiKeyRepository } from './infrastructure/repositories/apikey.repository'; const userRepository = new UserRepository(); const roleRepository = new RoleRepository(); +const apiKeyRepository = new ApiKeyRepository(); export const passwordService = new PasswordService(); const sessionService = new SessionService(passwordService); +export const apiKeysService = new ApiKeysService(apiKeyRepository); export const authService = new AuthService(userRepository, passwordService, sessionService); export const userService = new UserService(userRepository, roleRepository, passwordService); diff --git a/src/modules/auth/infrastructure/repositories/apikey.repository.ts b/src/modules/auth/infrastructure/repositories/apikey.repository.ts index 23e331b3..160a575b 100644 --- a/src/modules/auth/infrastructure/repositories/apikey.repository.ts +++ b/src/modules/auth/infrastructure/repositories/apikey.repository.ts @@ -1,6 +1,104 @@ import { Repository } from './repository'; +import { ApiKeyEntity } from '$lib/database/schemas'; +import type { ApiKeyView } from '../../domain/entities'; + +type ApiKeyRow = { + id: string; + userId: string; + name: string; + keyPrefix: string; + keyHash: string; + expiresAt: string | null; + lastUsedAt: string | null; + revokedAt: string | null; + createdAt: string; +}; export class ApiKeyRepository extends Repository { - + async listByUser(userId: string): Promise { + const result = await this.db.select().from(ApiKeyEntity).where({ userId }).orderBy('createdAt', 'desc'); + + return (result.rows as ApiKeyRow[]).map((row) => this.toJSON(row)); + } + + async findById(userId: string, keyId: string): Promise { + const result = await this.db.select().from(ApiKeyEntity).where({ id: keyId, userId }).limit(1); + const row = result.rows[0] as ApiKeyRow | undefined; + + if (!row) { + return null; + } + + return this.toJSON(row); + } + + async findValidByHash(keyHash: string): Promise { + const result = await this.db.select().from(ApiKeyEntity).where({ keyHash }).limit(1); + const row = result.rows[0] as ApiKeyRow | undefined; + + if (!row || row.revokedAt) { + return null; + } + + if (row.expiresAt && row.expiresAt <= new Date().toISOString()) { + return null; + } + + return this.toJSON(row); + } + + async create(input: { + id: string; + userId: string; + name: string; + keyPrefix: string; + keyHash: string; + expiresAt: string | null; + }): Promise { + await this.db.insert(ApiKeyEntity).values({ + id: input.id, + userId: input.userId, + name: input.name, + keyPrefix: input.keyPrefix, + keyHash: input.keyHash, + expiresAt: input.expiresAt, + lastUsedAt: null, + revokedAt: null, + createdAt: new Date().toISOString(), + }); + } + + async revoke(userId: string, keyId: string): Promise { + await this.db.update(ApiKeyEntity).set({ revokedAt: new Date().toISOString() }).where({ id: keyId, userId }); + } + + async updateKeyMaterial(userId: string, keyId: string, input: { + keyPrefix: string; + keyHash: string; + expiresAt: string | null; + }): Promise { + await this.db + .update(ApiKeyEntity) + .set({ + keyPrefix: input.keyPrefix, + keyHash: input.keyHash, + expiresAt: input.expiresAt, + revokedAt: null, + lastUsedAt: null, + }) + .where({ id: keyId, userId }); + } + + override protected toJSON(row: ApiKeyRow): ApiKeyView { + return { + id: row.id, + name: row.name, + keyPrefix: row.keyPrefix.slice(0, 6), + expiresAt: row.expiresAt, + lastUsedAt: row.lastUsedAt, + revokedAt: row.revokedAt, + createdAt: row.createdAt, + }; + } } \ No newline at end of file diff --git a/src/routes/profile/+page.server.ts b/src/routes/profile/+page.server.ts index 9432e765..d26db62a 100644 --- a/src/routes/profile/+page.server.ts +++ b/src/routes/profile/+page.server.ts @@ -1,7 +1,22 @@ import { fail, redirect } from '@sveltejs/kit'; -import { profileService } from '../../modules/auth'; +import { apiKeysService, profileService } from '../../modules/auth'; import { storageBackendService } from '../../modules/config'; +function expiresAtFromDays(expiresInDays: string | null): string | null { + if (!expiresInDays) { + return null; + } + + const days = Number(expiresInDays); + if (!Number.isFinite(days) || days <= 0) { + return null; + } + + const date = new Date(); + date.setDate(date.getDate() + days); + return date.toISOString(); +} + export async function load({ locals, cookies }) { if (!locals.user) { throw redirect(302, '/login'); @@ -18,8 +33,7 @@ export async function load({ locals, cookies }) { const activeBackend = backends.find((backend) => backend.id === activeBackendId) || null; const gcpConnected = activeBackend?.provider === 'gcs'; - // const apiKeys = await profileService.listActiveApiKeys(user.id); - const apiKeys = [] + const apiKeys = await apiKeysService.listActiveApiKeys(user.id); return { user: { @@ -29,13 +43,7 @@ export async function load({ locals, cookies }) { role: user.role, }, gcpConnected, - apiKeys: apiKeys.map((key) => ({ - id: key.id, - name: key.name, - keyPrefix: key.keyPrefix, - lastUsedAt: key.lastUsedAt, - createdAt: key.createdAt, - })), + apiKeys, }; } @@ -83,23 +91,41 @@ export const actions = { const formData = await request.formData(); const name = String(formData.get('name') || '').trim(); + const expiresInDays = String(formData.get('expiresInDays') || '').trim(); if (!name) { return fail(400, { section: 'apiKeys', message: 'Key name is required.' }); } - const { token } = await profileService.createApiKey(locals.user.id, name); + const expiresAt = expiresAtFromDays(expiresInDays || null); + + const { token } = await apiKeysService.createApiKey(locals.user.id, name, expiresAt); return { section: 'apiKeys', message: 'API key created.', createdKey: token }; }, + regenerateApiKey: async ({ request, locals }) => { + if (!locals.user) throw redirect(302, '/login'); + + const formData = await request.formData(); + const keyId = String(formData.get('keyId') || ''); + + if (!keyId) { + return fail(400, { section: 'apiKeys', message: 'Key id is required.' }); + } + + const { token } = await apiKeysService.regenerateApiKey(locals.user.id, keyId); + + return { section: 'apiKeys', message: 'API key regenerated.', createdKey: token }; + }, + revokeApiKey: async ({ request, locals }) => { if (!locals.user) throw redirect(302, '/login'); const formData = await request.formData(); const keyId = String(formData.get('keyId') || ''); - await profileService.revokeApiKey(locals.user.id, keyId); + await apiKeysService.revokeApiKey(locals.user.id, keyId); return { section: 'apiKeys', message: 'API key revoked.' }; }, diff --git a/src/routes/profile/+page.svelte b/src/routes/profile/+page.svelte index 83582f46..80ebec3c 100644 --- a/src/routes/profile/+page.svelte +++ b/src/routes/profile/+page.svelte @@ -1,14 +1,73 @@ @@ -17,7 +76,7 @@
-
+

Account

Profile

@@ -161,27 +220,40 @@

-
- - -
+
{#if form?.createdKey}
-

Copy this token now. It will not be shown again.

- {form.createdKey} +
+
+

Copy this token now. It will not be shown again.

+ {form.createdKey} +
+ + +
{/if} @@ -196,23 +268,123 @@

{key.name}

- Prefix: {key.keyPrefix} · Created {key.createdAt} + Prefix: {key.keyPrefix} · Created {key.createdAt} · Expires {formatDateTime(key.expiresAt)} +

+

+ Status: {getKeyState(key)} + {#if key.revokedAt} + · Revoked {formatDateTime(key.revokedAt)} + {/if}

-
- - -
+
+ {#if !key.revokedAt} +
+ + +
+ +
+ + +
+ {:else} +
+ Actions unavailable for revoked keys. +
+ {/if} +
{/each} {/if} - \ No newline at end of file + + +{#if createApiKeyModalOpen} + +
+ +
+{/if} \ No newline at end of file diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 00000000..30c7f9d3 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + environment: 'node', + include: ['src/**/*.test.ts', 'src/**/*.spec.ts'], + globals: true, + }, +}); \ No newline at end of file