Add device access token authentication
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AssetsModule } from './modules/assets/assets.module';
|
||||
import { AuthModule } from './modules/auth/auth.module';
|
||||
import { ArtworkModule } from './modules/artwork/artwork.module';
|
||||
import { AppConfigModule } from './modules/config/config.module';
|
||||
import { DevicesModule } from './modules/devices/devices.module';
|
||||
@@ -12,6 +13,7 @@ import { UsersModule } from './modules/users/users.module';
|
||||
@Module({
|
||||
imports: [
|
||||
AppConfigModule,
|
||||
AuthModule,
|
||||
UsersModule,
|
||||
AssetsModule,
|
||||
ArtworkModule,
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Injectable, NestMiddleware } from '@nestjs/common';
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { RequestContextService } from './request-context.service';
|
||||
|
||||
@Injectable()
|
||||
export class RequestContextMiddleware implements NestMiddleware {
|
||||
constructor(private readonly requestContext: RequestContextService) {}
|
||||
|
||||
use(_request: Request, _response: Response, next: NextFunction): void {
|
||||
this.requestContext.run(() => next());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { RequestContextMiddleware } from './request-context.middleware';
|
||||
import { RequestContextService } from './request-context.service';
|
||||
|
||||
@Module({
|
||||
providers: [RequestContextService, RequestContextMiddleware],
|
||||
exports: [RequestContextService, RequestContextMiddleware],
|
||||
})
|
||||
export class RequestContextModule {}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
|
||||
export interface AuthenticatedDeviceContextValue {
|
||||
deviceId: string;
|
||||
userId: string;
|
||||
}
|
||||
|
||||
interface RequestContextState {
|
||||
authenticatedDevice: AuthenticatedDeviceContextValue | null;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class RequestContextService {
|
||||
private readonly storage = new AsyncLocalStorage<RequestContextState>();
|
||||
|
||||
run<T>(callback: () => T): T {
|
||||
return this.storage.run(
|
||||
{
|
||||
authenticatedDevice: null,
|
||||
},
|
||||
callback,
|
||||
);
|
||||
}
|
||||
|
||||
getAuthenticatedDevice(): AuthenticatedDeviceContextValue | null {
|
||||
return this.storage.getStore()?.authenticatedDevice ?? null;
|
||||
}
|
||||
|
||||
setAuthenticatedDevice(device: AuthenticatedDeviceContextValue): void {
|
||||
const store = this.storage.getStore();
|
||||
|
||||
if (!store) {
|
||||
return;
|
||||
}
|
||||
|
||||
store.authenticatedDevice = device;
|
||||
}
|
||||
}
|
||||
@@ -5,14 +5,23 @@ import {
|
||||
Query,
|
||||
Res,
|
||||
StreamableFile,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
import { ApiOkResponse, ApiProduces, ApiTags } from '@nestjs/swagger';
|
||||
import {
|
||||
ApiBearerAuth,
|
||||
ApiOkResponse,
|
||||
ApiProduces,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { AssetDownloadQueryDto } from '../assets/assets.dto';
|
||||
import { DeviceAuthGuard } from '../auth/device-auth.guard';
|
||||
import { ArtworkService } from './artwork.service';
|
||||
|
||||
@ApiTags('artwork')
|
||||
@UseGuards(DeviceAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Controller({
|
||||
path: 'artwork',
|
||||
version: '1',
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../../infrastructure/database/prisma.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { StorageModule } from '../storage/storage.module';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { ArtworkController } from './artwork.controller';
|
||||
import { ArtworkService } from './artwork.service';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, StorageModule, UsersModule],
|
||||
imports: [PrismaModule, StorageModule, UsersModule, AuthModule],
|
||||
controllers: [ArtworkController],
|
||||
providers: [ArtworkService],
|
||||
})
|
||||
|
||||
@@ -5,23 +5,17 @@ import { join } from 'node:path';
|
||||
import { ForbiddenException, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '../../infrastructure/database/prisma.service';
|
||||
import { AppConfigService } from '../config/config.service';
|
||||
import { DeviceAuthService } from '../auth/device-auth.service';
|
||||
import { LocalFilesystemStorageService } from '../storage/storage.service';
|
||||
import { OwnerContext } from '../users/owner-context.service';
|
||||
import { ArtworkService } from './artwork.service';
|
||||
|
||||
type MockState = ReturnType<typeof createPrismaMock>['state'];
|
||||
|
||||
function createPrismaMock() {
|
||||
const devices = new Map<string, any>();
|
||||
const artworkAssets = new Map<string, any>();
|
||||
|
||||
return {
|
||||
prismaMock: {
|
||||
device: {
|
||||
findUnique: jest.fn().mockImplementation(async ({ where }) => {
|
||||
return devices.get(where.id) ?? null;
|
||||
}),
|
||||
},
|
||||
artworkAsset: {
|
||||
findUnique: jest.fn().mockImplementation(async ({ where }) => {
|
||||
return artworkAssets.get(where.id) ?? null;
|
||||
@@ -29,7 +23,6 @@ function createPrismaMock() {
|
||||
},
|
||||
} as unknown as PrismaService,
|
||||
state: {
|
||||
devices,
|
||||
artworkAssets,
|
||||
},
|
||||
};
|
||||
@@ -48,6 +41,9 @@ describe('ArtworkService', () => {
|
||||
let storageRoot: string;
|
||||
let storageService: LocalFilesystemStorageService;
|
||||
let ownerUserId: string;
|
||||
let deviceAuthService: {
|
||||
resolveCurrentDevice: jest.Mock;
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const mock = createPrismaMock();
|
||||
@@ -55,14 +51,16 @@ describe('ArtworkService', () => {
|
||||
storageRoot = await mkdtemp(join(tmpdir(), 'velody-artwork-spec-'));
|
||||
storageService = new LocalFilesystemStorageService(createAppConfig(storageRoot));
|
||||
ownerUserId = randomUUID();
|
||||
deviceAuthService = {
|
||||
resolveCurrentDevice: jest.fn().mockResolvedValue({
|
||||
deviceId: randomUUID(),
|
||||
userId: ownerUserId,
|
||||
}),
|
||||
};
|
||||
service = new ArtworkService(
|
||||
mock.prismaMock,
|
||||
storageService,
|
||||
{
|
||||
resolve: jest.fn().mockResolvedValue({
|
||||
userId: ownerUserId,
|
||||
}),
|
||||
} as OwnerContext,
|
||||
deviceAuthService as unknown as DeviceAuthService,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -72,7 +70,6 @@ describe('ArtworkService', () => {
|
||||
|
||||
it('returns a local file path, content length, and mime type for the owning device user', async () => {
|
||||
const userId = ownerUserId;
|
||||
const deviceId = randomUUID();
|
||||
const artworkId = randomUUID();
|
||||
const storageKey = join('users', userId, 'artwork', `${artworkId}.png`);
|
||||
const bytes = Buffer.from(
|
||||
@@ -80,7 +77,6 @@ describe('ArtworkService', () => {
|
||||
'base64',
|
||||
);
|
||||
|
||||
state.devices.set(deviceId, { id: deviceId, userId });
|
||||
state.artworkAssets.set(artworkId, {
|
||||
userId,
|
||||
storageKey,
|
||||
@@ -91,7 +87,7 @@ describe('ArtworkService', () => {
|
||||
await storageService.ensureParentDirectory(filePath);
|
||||
await writeFile(filePath, bytes);
|
||||
|
||||
const download = await service.getOwnedArtworkDownload(artworkId, deviceId);
|
||||
const download = await service.getOwnedArtworkDownload(artworkId, randomUUID());
|
||||
|
||||
expect(download.filePath).toBe(filePath);
|
||||
expect(download.contentLength).toBe(bytes.length);
|
||||
@@ -100,10 +96,8 @@ describe('ArtworkService', () => {
|
||||
|
||||
it('rejects cross-owner artwork downloads', async () => {
|
||||
const otherUserId = randomUUID();
|
||||
const ownerDeviceId = randomUUID();
|
||||
const artworkId = randomUUID();
|
||||
|
||||
state.devices.set(ownerDeviceId, { id: ownerDeviceId, userId: ownerUserId });
|
||||
state.artworkAssets.set(artworkId, {
|
||||
userId: otherUserId,
|
||||
storageKey: join('users', otherUserId, 'artwork', `${artworkId}.jpg`),
|
||||
@@ -111,29 +105,24 @@ describe('ArtworkService', () => {
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.getOwnedArtworkDownload(artworkId, ownerDeviceId),
|
||||
service.getOwnedArtworkDownload(artworkId, randomUUID()),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
});
|
||||
|
||||
it('rejects foreign-owner devices before reading artwork', async () => {
|
||||
const foreignDeviceId = randomUUID();
|
||||
|
||||
state.devices.set(foreignDeviceId, {
|
||||
id: foreignDeviceId,
|
||||
userId: randomUUID(),
|
||||
});
|
||||
deviceAuthService.resolveCurrentDevice.mockRejectedValueOnce(
|
||||
new NotFoundException('Device not found'),
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.getOwnedArtworkDownload(randomUUID(), foreignDeviceId),
|
||||
service.getOwnedArtworkDownload(randomUUID(), randomUUID()),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
|
||||
it('returns not found when the artwork file is missing from storage', async () => {
|
||||
const userId = ownerUserId;
|
||||
const deviceId = randomUUID();
|
||||
const artworkId = randomUUID();
|
||||
|
||||
state.devices.set(deviceId, { id: deviceId, userId });
|
||||
state.artworkAssets.set(artworkId, {
|
||||
userId,
|
||||
storageKey: join('users', userId, 'artwork', `${artworkId}.png`),
|
||||
@@ -141,18 +130,13 @@ describe('ArtworkService', () => {
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.getOwnedArtworkDownload(artworkId, deviceId),
|
||||
service.getOwnedArtworkDownload(artworkId, randomUUID()),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
|
||||
it('returns not found when the artwork asset does not exist', async () => {
|
||||
const userId = randomUUID();
|
||||
const deviceId = randomUUID();
|
||||
|
||||
state.devices.set(deviceId, { id: deviceId, userId });
|
||||
|
||||
await expect(
|
||||
service.getOwnedArtworkDownload(randomUUID(), deviceId),
|
||||
service.getOwnedArtworkDownload(randomUUID(), randomUUID()),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,8 +5,8 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { stat } from 'node:fs/promises';
|
||||
import { PrismaService } from '../../infrastructure/database/prisma.service';
|
||||
import { DeviceAuthService } from '../auth/device-auth.service';
|
||||
import { LocalFilesystemStorageService } from '../storage/storage.service';
|
||||
import { OwnerContext } from '../users/owner-context.service';
|
||||
|
||||
export interface ArtworkDownload {
|
||||
filePath: string;
|
||||
@@ -19,24 +19,15 @@ export class ArtworkService {
|
||||
constructor(
|
||||
private readonly prismaService: PrismaService,
|
||||
private readonly storageService: LocalFilesystemStorageService,
|
||||
private readonly ownerContext: OwnerContext,
|
||||
private readonly deviceAuthService: DeviceAuthService,
|
||||
) {}
|
||||
|
||||
async getOwnedArtworkDownload(
|
||||
artworkId: string,
|
||||
deviceId: string,
|
||||
legacyDeviceId?: string,
|
||||
): Promise<ArtworkDownload> {
|
||||
const ownerUserId = await this.resolveCurrentOwnerUserId();
|
||||
const device = await this.prismaService.device.findUnique({
|
||||
where: { id: deviceId },
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!device || device.userId !== ownerUserId) {
|
||||
throw new NotFoundException('Device not found');
|
||||
}
|
||||
const { userId: ownerUserId } =
|
||||
await this.deviceAuthService.resolveCurrentDevice(legacyDeviceId);
|
||||
|
||||
const artwork = await this.prismaService.artworkAsset.findUnique({
|
||||
where: { id: artworkId },
|
||||
@@ -77,9 +68,4 @@ export class ArtworkService {
|
||||
throw new NotFoundException('Artwork file not found');
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveCurrentOwnerUserId(): Promise<string> {
|
||||
const owner = await this.ownerContext.resolve();
|
||||
return owner.userId;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,27 @@
|
||||
import { Controller, Get, Param, Query, Res, StreamableFile } from '@nestjs/common';
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
Query,
|
||||
Res,
|
||||
StreamableFile,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
import { ApiOkResponse, ApiProduces, ApiTags } from '@nestjs/swagger';
|
||||
import {
|
||||
ApiBearerAuth,
|
||||
ApiOkResponse,
|
||||
ApiProduces,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { DeviceAuthGuard } from '../auth/device-auth.guard';
|
||||
import { AssetDownloadQueryDto } from './assets.dto';
|
||||
import { AssetsService } from './assets.service';
|
||||
|
||||
@ApiTags('assets')
|
||||
@UseGuards(DeviceAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Controller({
|
||||
path: 'assets',
|
||||
version: '1',
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsUUID } from 'class-validator';
|
||||
import { IsOptional, IsUUID } from 'class-validator';
|
||||
|
||||
export class AssetDownloadQueryDto {
|
||||
@ApiProperty({ format: 'uuid' })
|
||||
@ApiProperty({
|
||||
format: 'uuid',
|
||||
required: false,
|
||||
description:
|
||||
'Legacy migration fallback. Omit when Authorization: Bearer <deviceAccessToken> is provided.',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
deviceId!: string;
|
||||
deviceId?: string;
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../../infrastructure/database/prisma.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { StorageModule } from '../storage/storage.module';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { AssetsController } from './assets.controller';
|
||||
import { AssetsService } from './assets.service';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, StorageModule, UsersModule],
|
||||
imports: [PrismaModule, StorageModule, UsersModule, AuthModule],
|
||||
controllers: [AssetsController],
|
||||
providers: [AssetsService],
|
||||
})
|
||||
|
||||
@@ -5,23 +5,17 @@ import { join } from 'node:path';
|
||||
import { ForbiddenException, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '../../infrastructure/database/prisma.service';
|
||||
import { AppConfigService } from '../config/config.service';
|
||||
import { DeviceAuthService } from '../auth/device-auth.service';
|
||||
import { LocalFilesystemStorageService } from '../storage/storage.service';
|
||||
import { OwnerContext } from '../users/owner-context.service';
|
||||
import { AssetsService } from './assets.service';
|
||||
|
||||
type MockState = ReturnType<typeof createPrismaMock>['state'];
|
||||
|
||||
function createPrismaMock() {
|
||||
const devices = new Map<string, any>();
|
||||
const audioAssets = new Map<string, any>();
|
||||
|
||||
return {
|
||||
prismaMock: {
|
||||
device: {
|
||||
findUnique: jest.fn().mockImplementation(async ({ where }) => {
|
||||
return devices.get(where.id) ?? null;
|
||||
}),
|
||||
},
|
||||
audioAsset: {
|
||||
findUnique: jest.fn().mockImplementation(async ({ where }) => {
|
||||
return audioAssets.get(where.id) ?? null;
|
||||
@@ -29,7 +23,6 @@ function createPrismaMock() {
|
||||
},
|
||||
} as unknown as PrismaService,
|
||||
state: {
|
||||
devices,
|
||||
audioAssets,
|
||||
},
|
||||
};
|
||||
@@ -48,6 +41,9 @@ describe('AssetsService', () => {
|
||||
let storageRoot: string;
|
||||
let storageService: LocalFilesystemStorageService;
|
||||
let ownerUserId: string;
|
||||
let deviceAuthService: {
|
||||
resolveCurrentDevice: jest.Mock;
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const mock = createPrismaMock();
|
||||
@@ -55,14 +51,16 @@ describe('AssetsService', () => {
|
||||
storageRoot = await mkdtemp(join(tmpdir(), 'velody-assets-spec-'));
|
||||
storageService = new LocalFilesystemStorageService(createAppConfig(storageRoot));
|
||||
ownerUserId = randomUUID();
|
||||
deviceAuthService = {
|
||||
resolveCurrentDevice: jest.fn().mockResolvedValue({
|
||||
deviceId: randomUUID(),
|
||||
userId: ownerUserId,
|
||||
}),
|
||||
};
|
||||
service = new AssetsService(
|
||||
mock.prismaMock,
|
||||
storageService,
|
||||
{
|
||||
resolve: jest.fn().mockResolvedValue({
|
||||
userId: ownerUserId,
|
||||
}),
|
||||
} as OwnerContext,
|
||||
deviceAuthService as unknown as DeviceAuthService,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -72,12 +70,10 @@ describe('AssetsService', () => {
|
||||
|
||||
it('returns a local file path and content length for the owning device user', async () => {
|
||||
const userId = ownerUserId;
|
||||
const deviceId = randomUUID();
|
||||
const assetId = randomUUID();
|
||||
const storageKey = join('users', userId, 'audio', 'owner.mp3');
|
||||
const assetBytes = Buffer.from('ID3-owner-track', 'utf8');
|
||||
|
||||
state.devices.set(deviceId, { id: deviceId, userId });
|
||||
state.audioAssets.set(assetId, {
|
||||
id: assetId,
|
||||
userId,
|
||||
@@ -88,7 +84,7 @@ describe('AssetsService', () => {
|
||||
await storageService.ensureParentDirectory(filePath);
|
||||
await writeFile(filePath, assetBytes);
|
||||
|
||||
const download = await service.getOwnedAudioAssetDownload(assetId, deviceId);
|
||||
const download = await service.getOwnedAudioAssetDownload(assetId, randomUUID());
|
||||
|
||||
expect(download.filePath).toBe(filePath);
|
||||
expect(download.contentLength).toBe(assetBytes.length);
|
||||
@@ -96,10 +92,8 @@ describe('AssetsService', () => {
|
||||
|
||||
it('rejects cross-owner audio asset downloads', async () => {
|
||||
const otherUserId = randomUUID();
|
||||
const ownerDeviceId = randomUUID();
|
||||
const assetId = randomUUID();
|
||||
|
||||
state.devices.set(ownerDeviceId, { id: ownerDeviceId, userId: ownerUserId });
|
||||
state.audioAssets.set(assetId, {
|
||||
id: assetId,
|
||||
userId: otherUserId,
|
||||
@@ -107,30 +101,24 @@ describe('AssetsService', () => {
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.getOwnedAudioAssetDownload(assetId, ownerDeviceId),
|
||||
service.getOwnedAudioAssetDownload(assetId, randomUUID()),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
});
|
||||
|
||||
it('rejects foreign-owner devices before reading audio assets', async () => {
|
||||
const foreignOwnerId = randomUUID();
|
||||
const foreignDeviceId = randomUUID();
|
||||
|
||||
state.devices.set(foreignDeviceId, {
|
||||
id: foreignDeviceId,
|
||||
userId: foreignOwnerId,
|
||||
});
|
||||
deviceAuthService.resolveCurrentDevice.mockRejectedValueOnce(
|
||||
new NotFoundException('Device not found'),
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.getOwnedAudioAssetDownload(randomUUID(), foreignDeviceId),
|
||||
service.getOwnedAudioAssetDownload(randomUUID(), randomUUID()),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
|
||||
it('returns not found when the asset file is missing from storage', async () => {
|
||||
const userId = ownerUserId;
|
||||
const deviceId = randomUUID();
|
||||
const assetId = randomUUID();
|
||||
|
||||
state.devices.set(deviceId, { id: deviceId, userId });
|
||||
state.audioAssets.set(assetId, {
|
||||
id: assetId,
|
||||
userId,
|
||||
@@ -138,11 +126,15 @@ describe('AssetsService', () => {
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.getOwnedAudioAssetDownload(assetId, deviceId),
|
||||
service.getOwnedAudioAssetDownload(assetId, randomUUID()),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
|
||||
it('returns not found when the device does not exist', async () => {
|
||||
deviceAuthService.resolveCurrentDevice.mockRejectedValueOnce(
|
||||
new NotFoundException('Device not found'),
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.getOwnedAudioAssetDownload(randomUUID(), randomUUID()),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
|
||||
@@ -5,8 +5,8 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { stat } from 'node:fs/promises';
|
||||
import { PrismaService } from '../../infrastructure/database/prisma.service';
|
||||
import { DeviceAuthService } from '../auth/device-auth.service';
|
||||
import { LocalFilesystemStorageService } from '../storage/storage.service';
|
||||
import { OwnerContext } from '../users/owner-context.service';
|
||||
|
||||
export interface AudioAssetDownload {
|
||||
filePath: string;
|
||||
@@ -18,24 +18,15 @@ export class AssetsService {
|
||||
constructor(
|
||||
private readonly prismaService: PrismaService,
|
||||
private readonly storageService: LocalFilesystemStorageService,
|
||||
private readonly ownerContext: OwnerContext,
|
||||
private readonly deviceAuthService: DeviceAuthService,
|
||||
) {}
|
||||
|
||||
async getOwnedAudioAssetDownload(
|
||||
assetId: string,
|
||||
deviceId: string,
|
||||
legacyDeviceId?: string,
|
||||
): Promise<AudioAssetDownload> {
|
||||
const ownerUserId = await this.resolveCurrentOwnerUserId();
|
||||
const device = await this.prismaService.device.findUnique({
|
||||
where: { id: deviceId },
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!device || device.userId !== ownerUserId) {
|
||||
throw new NotFoundException('Device not found');
|
||||
}
|
||||
const { userId: ownerUserId } =
|
||||
await this.deviceAuthService.resolveCurrentDevice(legacyDeviceId);
|
||||
|
||||
const asset = await this.prismaService.audioAsset.findUnique({
|
||||
where: { id: assetId },
|
||||
@@ -74,9 +65,4 @@ export class AssetsService {
|
||||
throw new NotFoundException('Audio asset file not found');
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveCurrentOwnerUserId(): Promise<string> {
|
||||
const owner = await this.ownerContext.resolve();
|
||||
return owner.userId;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
|
||||
import { PrismaModule } from '../../infrastructure/database/prisma.module';
|
||||
import { RequestContextMiddleware } from '../../infrastructure/request-context/request-context.middleware';
|
||||
import { RequestContextModule } from '../../infrastructure/request-context/request-context.module';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { DeviceAuthGuard } from './device-auth.guard';
|
||||
import { DeviceAuthService } from './device-auth.service';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, RequestContextModule, UsersModule],
|
||||
providers: [DeviceAuthService, DeviceAuthGuard],
|
||||
exports: [DeviceAuthService, DeviceAuthGuard],
|
||||
})
|
||||
export class AuthModule implements NestModule {
|
||||
configure(consumer: MiddlewareConsumer): void {
|
||||
consumer.apply(RequestContextMiddleware).forRoutes('*');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { DeviceAuthService } from './device-auth.service';
|
||||
|
||||
@Injectable()
|
||||
export class DeviceAuthGuard implements CanActivate {
|
||||
constructor(private readonly deviceAuthService: DeviceAuthService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
const authorization = request.headers.authorization;
|
||||
|
||||
if (!authorization) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const authenticatedDevice =
|
||||
await this.deviceAuthService.authenticateAuthorizationHeader(
|
||||
authorization,
|
||||
);
|
||||
|
||||
(request as Request & { authenticatedDevice?: unknown }).authenticatedDevice =
|
||||
authenticatedDevice;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import {
|
||||
BadRequestException,
|
||||
NotFoundException,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { RequestContextService } from '../../infrastructure/request-context/request-context.service';
|
||||
import { OwnerContext } from '../users/owner-context.service';
|
||||
import { DeviceAuthService } from './device-auth.service';
|
||||
|
||||
describe('DeviceAuthService', () => {
|
||||
it('authenticates a valid bearer token and records it in request context', async () => {
|
||||
const userId = randomUUID();
|
||||
const deviceId = randomUUID();
|
||||
const requestContext = new RequestContextService();
|
||||
const ownerContext = {
|
||||
resolve: jest.fn().mockResolvedValue({ userId }),
|
||||
} as OwnerContext;
|
||||
const service = new DeviceAuthService(
|
||||
{
|
||||
device: {
|
||||
findUnique: jest.fn().mockResolvedValue({
|
||||
id: deviceId,
|
||||
userId,
|
||||
tokenRevokedAt: null,
|
||||
}),
|
||||
update: jest.fn().mockResolvedValue({}),
|
||||
},
|
||||
} as any,
|
||||
requestContext,
|
||||
ownerContext,
|
||||
);
|
||||
const token = service.generateDeviceAccessToken();
|
||||
|
||||
await requestContext.run(async () => {
|
||||
await expect(
|
||||
service.authenticateAuthorizationHeader(`Bearer ${token}`),
|
||||
).resolves.toEqual({
|
||||
deviceId,
|
||||
userId,
|
||||
});
|
||||
await expect(service.resolveCurrentDevice(randomUUID())).resolves.toEqual({
|
||||
deviceId,
|
||||
userId,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects invalid or revoked tokens', async () => {
|
||||
const requestContext = new RequestContextService();
|
||||
const service = new DeviceAuthService(
|
||||
{
|
||||
device: {
|
||||
findUnique: jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockResolvedValueOnce({
|
||||
id: randomUUID(),
|
||||
userId: randomUUID(),
|
||||
tokenRevokedAt: new Date(),
|
||||
}),
|
||||
update: jest.fn(),
|
||||
},
|
||||
} as any,
|
||||
requestContext,
|
||||
{
|
||||
resolve: jest.fn(),
|
||||
} as any,
|
||||
);
|
||||
|
||||
await expect(
|
||||
requestContext.run(() =>
|
||||
service.authenticateAuthorizationHeader('Bearer invalid-token'),
|
||||
),
|
||||
).rejects.toBeInstanceOf(UnauthorizedException);
|
||||
await expect(
|
||||
requestContext.run(() =>
|
||||
service.authenticateAuthorizationHeader('Bearer revoked-token'),
|
||||
),
|
||||
).rejects.toBeInstanceOf(UnauthorizedException);
|
||||
});
|
||||
|
||||
it('falls back to legacy device ids only when no authenticated device is present', async () => {
|
||||
const userId = randomUUID();
|
||||
const deviceId = randomUUID();
|
||||
const otherDeviceId = randomUUID();
|
||||
const requestContext = new RequestContextService();
|
||||
const ownerContext = {
|
||||
resolve: jest.fn().mockResolvedValue({ userId }),
|
||||
} as any;
|
||||
const service = new DeviceAuthService(
|
||||
{
|
||||
device: {
|
||||
findUnique: jest.fn().mockImplementation(async ({ where }) => {
|
||||
if (where.id === deviceId) {
|
||||
return {
|
||||
id: deviceId,
|
||||
userId,
|
||||
};
|
||||
}
|
||||
|
||||
if (where.id === otherDeviceId) {
|
||||
return {
|
||||
id: otherDeviceId,
|
||||
userId: randomUUID(),
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}),
|
||||
update: jest.fn(),
|
||||
},
|
||||
} as any,
|
||||
requestContext,
|
||||
ownerContext as OwnerContext,
|
||||
);
|
||||
|
||||
await expect(
|
||||
requestContext.run(() => service.resolveCurrentDevice()),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
await expect(
|
||||
requestContext.run(() => service.resolveCurrentDevice(otherDeviceId)),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
await expect(
|
||||
requestContext.run(() => service.resolveCurrentDevice(deviceId)),
|
||||
).resolves.toEqual({
|
||||
deviceId,
|
||||
userId,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { PrismaService } from '../../infrastructure/database/prisma.service';
|
||||
import {
|
||||
AuthenticatedDeviceContextValue,
|
||||
RequestContextService,
|
||||
} from '../../infrastructure/request-context/request-context.service';
|
||||
import { OwnerContext } from '../users/owner-context.service';
|
||||
|
||||
@Injectable()
|
||||
export class DeviceAuthService {
|
||||
constructor(
|
||||
private readonly prismaService: PrismaService,
|
||||
private readonly requestContext: RequestContextService,
|
||||
private readonly ownerContext: OwnerContext,
|
||||
) {}
|
||||
|
||||
generateDeviceAccessToken(): string {
|
||||
return randomBytes(32).toString('base64url');
|
||||
}
|
||||
|
||||
hashDeviceAccessToken(token: string): string {
|
||||
return createHash('sha256').update(token).digest('hex');
|
||||
}
|
||||
|
||||
async authenticateAuthorizationHeader(
|
||||
authorizationHeader: string | string[],
|
||||
): Promise<AuthenticatedDeviceContextValue> {
|
||||
const token = this.extractBearerToken(authorizationHeader);
|
||||
const tokenHash = this.hashDeviceAccessToken(token);
|
||||
const device = await this.prismaService.device.findUnique({
|
||||
where: {
|
||||
tokenHash,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
tokenRevokedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!device || device.tokenRevokedAt) {
|
||||
throw new UnauthorizedException('Invalid device access token');
|
||||
}
|
||||
|
||||
await this.prismaService.device.update({
|
||||
where: {
|
||||
id: device.id,
|
||||
},
|
||||
data: {
|
||||
tokenLastUsedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
const authenticatedDevice = {
|
||||
deviceId: device.id,
|
||||
userId: device.userId,
|
||||
};
|
||||
|
||||
this.requestContext.setAuthenticatedDevice(authenticatedDevice);
|
||||
|
||||
return authenticatedDevice;
|
||||
}
|
||||
|
||||
async resolveCurrentDevice(
|
||||
legacyDeviceId?: string,
|
||||
): Promise<AuthenticatedDeviceContextValue> {
|
||||
const authenticatedDevice = this.requestContext.getAuthenticatedDevice();
|
||||
|
||||
if (authenticatedDevice) {
|
||||
return authenticatedDevice;
|
||||
}
|
||||
|
||||
if (!legacyDeviceId) {
|
||||
throw new BadRequestException(
|
||||
'deviceId is required when Authorization is missing.',
|
||||
);
|
||||
}
|
||||
|
||||
const owner = await this.ownerContext.resolve();
|
||||
const device = await this.prismaService.device.findUnique({
|
||||
where: {
|
||||
id: legacyDeviceId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!device || device.userId !== owner.userId) {
|
||||
throw new NotFoundException('Device not found');
|
||||
}
|
||||
|
||||
return {
|
||||
deviceId: device.id,
|
||||
userId: device.userId,
|
||||
};
|
||||
}
|
||||
|
||||
private extractBearerToken(authorizationHeader: string | string[]): string {
|
||||
const normalizedHeader = Array.isArray(authorizationHeader)
|
||||
? authorizationHeader[0]
|
||||
: authorizationHeader;
|
||||
|
||||
if (!normalizedHeader) {
|
||||
throw new UnauthorizedException('Invalid device access token');
|
||||
}
|
||||
|
||||
const match = normalizedHeader.match(/^Bearer\s+(.+)$/i);
|
||||
|
||||
if (!match || !match[1]?.trim()) {
|
||||
throw new UnauthorizedException('Invalid device access token');
|
||||
}
|
||||
|
||||
return match[1].trim();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,11 @@
|
||||
import { Body, Controller, Post } from '@nestjs/common';
|
||||
import { ApiCreatedResponse, ApiOkResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { Body, Controller, Post, UseGuards } from '@nestjs/common';
|
||||
import {
|
||||
ApiBearerAuth,
|
||||
ApiCreatedResponse,
|
||||
ApiOkResponse,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { DeviceAuthGuard } from '../auth/device-auth.guard';
|
||||
import {
|
||||
DeviceHeartbeatRequestDto,
|
||||
DeviceHeartbeatResponseDto,
|
||||
@@ -25,6 +31,8 @@ export class DevicesController {
|
||||
}
|
||||
|
||||
@Post('heartbeat')
|
||||
@UseGuards(DeviceAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@ApiOkResponse({ type: DeviceHeartbeatResponseDto })
|
||||
async heartbeat(
|
||||
@Body() body: DeviceHeartbeatRequestDto,
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { DevicePlatform } from '@prisma/client';
|
||||
import { IsEnum, IsString, IsUUID, MinLength } from 'class-validator';
|
||||
import {
|
||||
IsEnum,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
MinLength,
|
||||
} from 'class-validator';
|
||||
|
||||
export class RegisterDeviceRequestDto {
|
||||
@ApiProperty({ enum: DevicePlatform, example: DevicePlatform.MACOS })
|
||||
@@ -22,6 +28,12 @@ export class RegisterDeviceResponseDto {
|
||||
@ApiProperty({ format: 'uuid' })
|
||||
deviceId!: string;
|
||||
|
||||
@ApiProperty({
|
||||
description:
|
||||
'Raw device access token returned only during registration. Store it securely.',
|
||||
})
|
||||
deviceAccessToken!: string;
|
||||
|
||||
@ApiProperty()
|
||||
bootstrapToken!: string;
|
||||
|
||||
@@ -30,9 +42,15 @@ export class RegisterDeviceResponseDto {
|
||||
}
|
||||
|
||||
export class DeviceHeartbeatRequestDto {
|
||||
@ApiProperty({ format: 'uuid' })
|
||||
@ApiProperty({
|
||||
format: 'uuid',
|
||||
required: false,
|
||||
description:
|
||||
'Legacy migration fallback. Omit when Authorization: Bearer <deviceAccessToken> is provided.',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
deviceId!: string;
|
||||
deviceId?: string;
|
||||
|
||||
@ApiProperty({ example: '0.1.0' })
|
||||
@IsString()
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../../infrastructure/database/prisma.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { DevicesController } from './devices.controller';
|
||||
import { DevicesService } from './devices.service';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, UsersModule],
|
||||
imports: [PrismaModule, UsersModule, AuthModule],
|
||||
controllers: [DevicesController],
|
||||
providers: [DevicesService],
|
||||
exports: [DevicesService],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { DeviceAuthService } from '../auth/device-auth.service';
|
||||
import { OwnerContext } from '../users/owner-context.service';
|
||||
import { DevicesService } from './devices.service';
|
||||
|
||||
@@ -21,12 +22,18 @@ describe('DevicesService', () => {
|
||||
userId: ownerId,
|
||||
}),
|
||||
} as any;
|
||||
const deviceAuthService = {
|
||||
generateDeviceAccessToken: jest.fn().mockReturnValue('device-access-token'),
|
||||
hashDeviceAccessToken: jest.fn().mockReturnValue('device-token-hash'),
|
||||
resolveCurrentDevice: jest.fn(),
|
||||
} as any;
|
||||
const service = new DevicesService(
|
||||
prismaService,
|
||||
ownerContext as OwnerContext,
|
||||
deviceAuthService as DeviceAuthService,
|
||||
);
|
||||
|
||||
await service.register({
|
||||
const response = await service.register({
|
||||
platform: 'MACOS',
|
||||
deviceName: 'Velody Mac',
|
||||
appVersion: '0.1.0',
|
||||
@@ -39,30 +46,33 @@ describe('DevicesService', () => {
|
||||
platform: 'MACOS',
|
||||
deviceName: 'Velody Mac',
|
||||
appVersion: '0.1.0',
|
||||
tokenHash: 'device-token-hash',
|
||||
}),
|
||||
});
|
||||
expect(response.deviceAccessToken).toBe('device-access-token');
|
||||
});
|
||||
|
||||
it('rejects heartbeat updates for a foreign-owner device', async () => {
|
||||
const ownerId = randomUUID();
|
||||
const foreignOwnerId = randomUUID();
|
||||
const deviceId = randomUUID();
|
||||
const prismaService = {
|
||||
device: {
|
||||
findUnique: jest.fn().mockResolvedValue({
|
||||
userId: foreignOwnerId,
|
||||
}),
|
||||
update: jest.fn(),
|
||||
},
|
||||
} as any;
|
||||
const ownerContext = {
|
||||
resolve: jest.fn().mockResolvedValue({
|
||||
userId: ownerId,
|
||||
}),
|
||||
resolve: jest.fn(),
|
||||
} as any;
|
||||
const deviceAuthService = {
|
||||
generateDeviceAccessToken: jest.fn(),
|
||||
hashDeviceAccessToken: jest.fn(),
|
||||
resolveCurrentDevice: jest
|
||||
.fn()
|
||||
.mockRejectedValue(new NotFoundException('Device not found')),
|
||||
} as any;
|
||||
const service = new DevicesService(
|
||||
prismaService,
|
||||
ownerContext as OwnerContext,
|
||||
deviceAuthService as DeviceAuthService,
|
||||
);
|
||||
|
||||
await expect(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { PrismaService } from '../../infrastructure/database/prisma.service';
|
||||
import { DeviceAuthService } from '../auth/device-auth.service';
|
||||
import { OwnerContext } from '../users/owner-context.service';
|
||||
import {
|
||||
DeviceHeartbeatRequestDto,
|
||||
@@ -14,15 +15,19 @@ export class DevicesService {
|
||||
constructor(
|
||||
private readonly prismaService: PrismaService,
|
||||
private readonly ownerContext: OwnerContext,
|
||||
private readonly deviceAuthService: DeviceAuthService,
|
||||
) {}
|
||||
|
||||
async register(
|
||||
body: RegisterDeviceRequestDto,
|
||||
): Promise<RegisterDeviceResponseDto> {
|
||||
const bootstrapToken = randomBytes(24).toString('hex');
|
||||
const deviceAccessToken = this.deviceAuthService.generateDeviceAccessToken();
|
||||
const installTokenHash = createHash('sha256')
|
||||
.update(bootstrapToken)
|
||||
.digest('hex');
|
||||
const tokenHash =
|
||||
this.deviceAuthService.hashDeviceAccessToken(deviceAccessToken);
|
||||
const owner = await this.ownerContext.resolve();
|
||||
|
||||
const device = await this.prismaService.device.create({
|
||||
@@ -32,12 +37,15 @@ export class DevicesService {
|
||||
deviceName: body.deviceName,
|
||||
appVersion: body.appVersion,
|
||||
installTokenHash,
|
||||
tokenHash,
|
||||
tokenCreatedAt: new Date(),
|
||||
lastSeenAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
deviceId: device.id,
|
||||
deviceAccessToken,
|
||||
bootstrapToken,
|
||||
serverTime: new Date().toISOString(),
|
||||
};
|
||||
@@ -46,20 +54,10 @@ export class DevicesService {
|
||||
async heartbeat(
|
||||
body: DeviceHeartbeatRequestDto,
|
||||
): Promise<DeviceHeartbeatResponseDto> {
|
||||
const ownerUserId = await this.resolveCurrentOwnerUserId();
|
||||
const existing = await this.prismaService.device.findUnique({
|
||||
where: { id: body.deviceId },
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!existing || existing.userId !== ownerUserId) {
|
||||
throw new NotFoundException('Device not found');
|
||||
}
|
||||
const device = await this.deviceAuthService.resolveCurrentDevice(body.deviceId);
|
||||
|
||||
await this.prismaService.device.update({
|
||||
where: { id: body.deviceId },
|
||||
where: { id: device.deviceId },
|
||||
data: {
|
||||
appVersion: body.appVersion,
|
||||
lastSeenAt: new Date(),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Controller, Get, Query } from '@nestjs/common';
|
||||
import { ApiOkResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOkResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { DeviceAuthGuard } from '../auth/device-auth.guard';
|
||||
import {
|
||||
LibraryTracksQueryDto,
|
||||
LibraryTracksResponseDto,
|
||||
@@ -7,6 +8,8 @@ import {
|
||||
import { LibraryService } from './library.service';
|
||||
|
||||
@ApiTags('library')
|
||||
@UseGuards(DeviceAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Controller({
|
||||
path: 'library',
|
||||
version: '1',
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsUUID } from 'class-validator';
|
||||
import { IsOptional, IsUUID } from 'class-validator';
|
||||
|
||||
export class LibraryTracksQueryDto {
|
||||
@ApiProperty({ format: 'uuid' })
|
||||
@ApiProperty({
|
||||
format: 'uuid',
|
||||
required: false,
|
||||
description:
|
||||
'Legacy migration fallback. Omit when Authorization: Bearer <deviceAccessToken> is provided.',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
deviceId!: string;
|
||||
deviceId?: string;
|
||||
}
|
||||
|
||||
export class RemoteArtworkDto {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../../infrastructure/database/prisma.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { LibraryController } from './library.controller';
|
||||
import { LibraryService } from './library.service';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, UsersModule],
|
||||
imports: [PrismaModule, UsersModule, AuthModule],
|
||||
controllers: [LibraryController],
|
||||
providers: [LibraryService],
|
||||
exports: [LibraryService],
|
||||
|
||||
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { PrismaService } from '../../infrastructure/database/prisma.service';
|
||||
import { DeviceAuthService } from '../auth/device-auth.service';
|
||||
import { OwnerContext } from '../users/owner-context.service';
|
||||
import { LibraryService } from './library.service';
|
||||
|
||||
@@ -58,6 +59,9 @@ describe('LibraryService', () => {
|
||||
let ownerContextMock: {
|
||||
resolve: jest.Mock;
|
||||
};
|
||||
let deviceAuthServiceMock: {
|
||||
resolveCurrentDevice: jest.Mock;
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const { prismaMock, state: nextState } = createPrismaMock();
|
||||
@@ -65,6 +69,9 @@ describe('LibraryService', () => {
|
||||
ownerContextMock = {
|
||||
resolve: jest.fn(),
|
||||
};
|
||||
deviceAuthServiceMock = {
|
||||
resolveCurrentDevice: jest.fn(),
|
||||
};
|
||||
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
providers: [
|
||||
@@ -77,6 +84,10 @@ describe('LibraryService', () => {
|
||||
provide: OwnerContext,
|
||||
useValue: ownerContextMock,
|
||||
},
|
||||
{
|
||||
provide: DeviceAuthService,
|
||||
useValue: deviceAuthServiceMock,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
@@ -151,6 +162,10 @@ describe('LibraryService', () => {
|
||||
userId: ownerId,
|
||||
});
|
||||
state.devices.set(ownerDeviceId, { id: ownerDeviceId, userId: ownerId });
|
||||
deviceAuthServiceMock.resolveCurrentDevice.mockResolvedValue({
|
||||
deviceId: ownerDeviceId,
|
||||
userId: ownerId,
|
||||
});
|
||||
|
||||
state.audioAssets.set(ownerAssetId, {
|
||||
id: ownerAssetId,
|
||||
@@ -251,6 +266,10 @@ describe('LibraryService', () => {
|
||||
userId: ownerId,
|
||||
});
|
||||
state.devices.set(ownerDeviceId, { id: ownerDeviceId, userId: ownerId });
|
||||
deviceAuthServiceMock.resolveCurrentDevice.mockResolvedValue({
|
||||
deviceId: ownerDeviceId,
|
||||
userId: ownerId,
|
||||
});
|
||||
|
||||
await expect(
|
||||
libraryService.getRemoteLibraryTracks(ownerDeviceId),
|
||||
@@ -268,6 +287,10 @@ describe('LibraryService', () => {
|
||||
userId: ownerId,
|
||||
});
|
||||
state.devices.set(ownerDeviceId, { id: ownerDeviceId, userId: ownerId });
|
||||
deviceAuthServiceMock.resolveCurrentDevice.mockResolvedValue({
|
||||
deviceId: ownerDeviceId,
|
||||
userId: ownerId,
|
||||
});
|
||||
state.audioAssets.set(otherAssetId, {
|
||||
id: otherAssetId,
|
||||
sha256: 'sha-other-owner',
|
||||
@@ -291,9 +314,10 @@ describe('LibraryService', () => {
|
||||
});
|
||||
|
||||
it('throws for an unknown device', async () => {
|
||||
ownerContextMock.resolve.mockResolvedValue({
|
||||
userId: randomUUID(),
|
||||
});
|
||||
deviceAuthServiceMock.resolveCurrentDevice.mockRejectedValueOnce(
|
||||
new NotFoundException('Device not found'),
|
||||
);
|
||||
|
||||
await expect(
|
||||
libraryService.getRemoteLibraryTracks(randomUUID()),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
@@ -304,13 +328,14 @@ describe('LibraryService', () => {
|
||||
const otherUserId = randomUUID();
|
||||
const foreignDeviceId = randomUUID();
|
||||
|
||||
ownerContextMock.resolve.mockResolvedValue({
|
||||
userId: ownerId,
|
||||
});
|
||||
ownerContextMock.resolve.mockResolvedValue({ userId: ownerId });
|
||||
state.devices.set(foreignDeviceId, {
|
||||
id: foreignDeviceId,
|
||||
userId: otherUserId,
|
||||
});
|
||||
deviceAuthServiceMock.resolveCurrentDevice.mockRejectedValueOnce(
|
||||
new NotFoundException('Device not found'),
|
||||
);
|
||||
|
||||
await expect(
|
||||
libraryService.getRemoteLibraryTracks(foreignDeviceId),
|
||||
@@ -324,6 +349,10 @@ describe('LibraryService', () => {
|
||||
userId: ownerId,
|
||||
});
|
||||
state.devices.set(ownerDeviceId, { id: ownerDeviceId, userId: ownerId });
|
||||
deviceAuthServiceMock.resolveCurrentDevice.mockResolvedValue({
|
||||
deviceId: ownerDeviceId,
|
||||
userId: ownerId,
|
||||
});
|
||||
|
||||
state.tracks.set(randomUUID(), {
|
||||
id: randomUUID(),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '../../infrastructure/database/prisma.service';
|
||||
import { DeviceAuthService } from '../auth/device-auth.service';
|
||||
import { LibraryTrackDto } from '../sync/sync.dto';
|
||||
import { OwnerContext } from '../users/owner-context.service';
|
||||
import { RemoteLibraryTrackDto } from './library.dto';
|
||||
@@ -9,6 +10,7 @@ export class LibraryService {
|
||||
constructor(
|
||||
private readonly prismaService: PrismaService,
|
||||
private readonly ownerContext: OwnerContext,
|
||||
private readonly deviceAuthService: DeviceAuthService,
|
||||
) {}
|
||||
|
||||
async getBootstrapTracks(): Promise<LibraryTrackDto[]> {
|
||||
@@ -36,19 +38,10 @@ export class LibraryService {
|
||||
}
|
||||
|
||||
async getRemoteLibraryTracks(
|
||||
deviceId: string,
|
||||
legacyDeviceId?: string,
|
||||
): Promise<RemoteLibraryTrackDto[]> {
|
||||
const ownerUserId = await this.resolveCurrentOwnerUserId();
|
||||
const device = await this.prismaService.device.findUnique({
|
||||
where: { id: deviceId },
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!device || device.userId !== ownerUserId) {
|
||||
throw new NotFoundException('Device not found');
|
||||
}
|
||||
const { userId: ownerUserId } =
|
||||
await this.deviceAuthService.resolveCurrentDevice(legacyDeviceId);
|
||||
|
||||
const tracks = await this.prismaService.track.findMany({
|
||||
where: {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Controller, Get, Query } from '@nestjs/common';
|
||||
import { ApiOkResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOkResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { DeviceAuthGuard } from '../auth/device-auth.guard';
|
||||
import {
|
||||
SyncBootstrapResponseDto,
|
||||
SyncChangesQueryDto,
|
||||
@@ -8,6 +9,8 @@ import {
|
||||
import { SyncService } from './sync.service';
|
||||
|
||||
@ApiTags('sync')
|
||||
@UseGuards(DeviceAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Controller({
|
||||
path: 'sync',
|
||||
version: '1',
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../../infrastructure/database/prisma.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { LibraryModule } from '../library/library.module';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { SyncController } from './sync.controller';
|
||||
import { SyncService } from './sync.service';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, LibraryModule, UsersModule],
|
||||
imports: [PrismaModule, LibraryModule, UsersModule, AuthModule],
|
||||
controllers: [SyncController],
|
||||
providers: [SyncService],
|
||||
})
|
||||
|
||||
@@ -6,15 +6,18 @@ import {
|
||||
Post,
|
||||
Put,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import {
|
||||
ApiBearerAuth,
|
||||
ApiBody,
|
||||
ApiCreatedResponse,
|
||||
ApiConsumes,
|
||||
ApiOkResponse,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { DeviceAuthGuard } from '../auth/device-auth.guard';
|
||||
import {
|
||||
UploadFinalizeRequestDto,
|
||||
UploadFinalizeResponseDto,
|
||||
@@ -25,6 +28,8 @@ import {
|
||||
import { UploadsService } from './uploads.service';
|
||||
|
||||
@ApiTags('uploads')
|
||||
@UseGuards(DeviceAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Controller({
|
||||
path: 'uploads',
|
||||
version: '1',
|
||||
|
||||
@@ -14,9 +14,15 @@ import {
|
||||
} from 'class-validator';
|
||||
|
||||
export class UploadPrepareRequestDto {
|
||||
@ApiProperty({ format: 'uuid' })
|
||||
@ApiProperty({
|
||||
format: 'uuid',
|
||||
required: false,
|
||||
description:
|
||||
'Legacy migration fallback. Omit when Authorization: Bearer <deviceAccessToken> is provided.',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
deviceId!: string;
|
||||
deviceId?: string;
|
||||
|
||||
@ApiProperty({
|
||||
example:
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../../infrastructure/database/prisma.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { StorageModule } from '../storage/storage.module';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { UploadsController } from './uploads.controller';
|
||||
import { UploadsService } from './uploads.service';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, StorageModule, UsersModule],
|
||||
imports: [PrismaModule, StorageModule, UsersModule, AuthModule],
|
||||
controllers: [UploadsController],
|
||||
providers: [UploadsService],
|
||||
})
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Readable } from 'node:stream';
|
||||
import { NotFoundException, UnprocessableEntityException } from '@nestjs/common';
|
||||
import { UploadSessionStatus } from '@prisma/client';
|
||||
import { AppConfigService } from '../config/config.service';
|
||||
import { DeviceAuthService } from '../auth/device-auth.service';
|
||||
import { LocalFilesystemStorageService } from '../storage/storage.service';
|
||||
import { OwnerContext } from '../users/owner-context.service';
|
||||
import { UploadsService } from './uploads.service';
|
||||
@@ -284,6 +285,9 @@ describe('UploadsService', () => {
|
||||
let storageService: LocalFilesystemStorageService;
|
||||
let service: UploadsService;
|
||||
let ownerContext: OwnerContext;
|
||||
let deviceAuthService: {
|
||||
resolveCurrentDevice: jest.Mock;
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const mock = createPrismaMock();
|
||||
@@ -296,11 +300,30 @@ describe('UploadsService', () => {
|
||||
userId: state.defaultUser.id,
|
||||
}),
|
||||
} as OwnerContext;
|
||||
deviceAuthService = {
|
||||
resolveCurrentDevice: jest.fn().mockImplementation(async (deviceId?: string) => {
|
||||
if (!deviceId) {
|
||||
throw new NotFoundException('Device not found');
|
||||
}
|
||||
|
||||
const device = state.devices.get(deviceId);
|
||||
|
||||
if (!device || device.userId !== state.defaultUser.id) {
|
||||
throw new NotFoundException('Device not found');
|
||||
}
|
||||
|
||||
return {
|
||||
deviceId: device.id,
|
||||
userId: device.userId,
|
||||
};
|
||||
}),
|
||||
};
|
||||
service = new UploadsService(
|
||||
prismaMock,
|
||||
createAppConfig(storageRoot),
|
||||
storageService,
|
||||
ownerContext,
|
||||
deviceAuthService as unknown as DeviceAuthService,
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import { access, open, rename, unlink, writeFile } from 'node:fs/promises';
|
||||
import { extname } from 'node:path';
|
||||
import { PrismaService } from '../../infrastructure/database/prisma.service';
|
||||
import { AppConfigService } from '../config/config.service';
|
||||
import { DeviceAuthService } from '../auth/device-auth.service';
|
||||
import { LocalFilesystemStorageService } from '../storage/storage.service';
|
||||
import { OwnerContext } from '../users/owner-context.service';
|
||||
import {
|
||||
@@ -44,6 +45,7 @@ export class UploadsService {
|
||||
private readonly configService: AppConfigService,
|
||||
private readonly storageService: LocalFilesystemStorageService,
|
||||
private readonly ownerContext: OwnerContext,
|
||||
private readonly deviceAuthService: DeviceAuthService,
|
||||
) {}
|
||||
|
||||
async prepare(
|
||||
@@ -52,8 +54,8 @@ export class UploadsService {
|
||||
this.assertFileSizeWithinLimit(body.sizeBytes);
|
||||
this.assertMp3Filename(body.originalFilename);
|
||||
|
||||
const ownerUserId = await this.resolveCurrentOwnerUserId();
|
||||
await this.getOwnedDeviceOrThrow(body.deviceId, ownerUserId);
|
||||
const device = await this.deviceAuthService.resolveCurrentDevice(body.deviceId);
|
||||
const ownerUserId = device.userId;
|
||||
|
||||
const existingAsset = await this.prismaService.audioAsset.findUnique({
|
||||
where: {
|
||||
@@ -70,7 +72,7 @@ export class UploadsService {
|
||||
data: {
|
||||
id: uploadId,
|
||||
userId: ownerUserId,
|
||||
deviceId: body.deviceId,
|
||||
deviceId: device.deviceId,
|
||||
trackId: existingAsset.trackId,
|
||||
audioAssetId: existingAsset.id,
|
||||
expectedSha256: body.sha256,
|
||||
@@ -97,7 +99,7 @@ export class UploadsService {
|
||||
data: {
|
||||
id: uploadId,
|
||||
userId: ownerUserId,
|
||||
deviceId: body.deviceId,
|
||||
deviceId: device.deviceId,
|
||||
expectedSha256: body.sha256,
|
||||
originalFilename: body.originalFilename,
|
||||
expectedSizeBytes: BigInt(body.sizeBytes),
|
||||
@@ -479,22 +481,6 @@ export class UploadsService {
|
||||
return owner.userId;
|
||||
}
|
||||
|
||||
private async getOwnedDeviceOrThrow(deviceId: string, ownerUserId: string) {
|
||||
const device = await this.prismaService.device.findUnique({
|
||||
where: { id: deviceId },
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!device || device.userId !== ownerUserId) {
|
||||
throw new NotFoundException('Device not found');
|
||||
}
|
||||
|
||||
return device;
|
||||
}
|
||||
|
||||
private async getOwnedUploadSessionOrThrow(
|
||||
uploadId: string,
|
||||
ownerUserId: string,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { RequestContextService } from '../../infrastructure/request-context/request-context.service';
|
||||
import { BootstrapOwnerContextService } from './owner-context.service';
|
||||
|
||||
describe('BootstrapOwnerContextService', () => {
|
||||
@@ -12,11 +13,39 @@ describe('BootstrapOwnerContextService', () => {
|
||||
const defaultUserService = {
|
||||
getOrCreateDefaultUser: jest.fn().mockResolvedValue(defaultUser),
|
||||
} as any;
|
||||
const service = new BootstrapOwnerContextService(defaultUserService);
|
||||
const service = new BootstrapOwnerContextService(
|
||||
defaultUserService,
|
||||
new RequestContextService(),
|
||||
);
|
||||
|
||||
await expect(service.resolve()).resolves.toEqual({
|
||||
userId: defaultUser.id,
|
||||
});
|
||||
expect(defaultUserService.getOrCreateDefaultUser).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('prefers the authenticated device owner when present', async () => {
|
||||
const requestContext = new RequestContextService();
|
||||
const defaultUserService = {
|
||||
getOrCreateDefaultUser: jest.fn(),
|
||||
} as any;
|
||||
const service = new BootstrapOwnerContextService(
|
||||
defaultUserService,
|
||||
requestContext,
|
||||
);
|
||||
const authenticatedOwnerId = randomUUID();
|
||||
|
||||
await requestContext.run(async () => {
|
||||
requestContext.setAuthenticatedDevice({
|
||||
deviceId: randomUUID(),
|
||||
userId: authenticatedOwnerId,
|
||||
});
|
||||
|
||||
await expect(service.resolve()).resolves.toEqual({
|
||||
userId: authenticatedOwnerId,
|
||||
});
|
||||
});
|
||||
|
||||
expect(defaultUserService.getOrCreateDefaultUser).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { RequestContextService } from '../../infrastructure/request-context/request-context.service';
|
||||
import { DefaultUserService } from './default-user.service';
|
||||
|
||||
export interface ResolvedOwnerContext {
|
||||
@@ -11,11 +12,22 @@ export abstract class OwnerContext {
|
||||
|
||||
@Injectable()
|
||||
export class BootstrapOwnerContextService extends OwnerContext {
|
||||
constructor(private readonly defaultUserService: DefaultUserService) {
|
||||
constructor(
|
||||
private readonly defaultUserService: DefaultUserService,
|
||||
private readonly requestContext: RequestContextService,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async resolve(): Promise<ResolvedOwnerContext> {
|
||||
const authenticatedDevice = this.requestContext.getAuthenticatedDevice();
|
||||
|
||||
if (authenticatedDevice) {
|
||||
return {
|
||||
userId: authenticatedDevice.userId,
|
||||
};
|
||||
}
|
||||
|
||||
const defaultUser = await this.defaultUserService.getOrCreateDefaultUser();
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../../infrastructure/database/prisma.module';
|
||||
import { RequestContextModule } from '../../infrastructure/request-context/request-context.module';
|
||||
import { DefaultUserService } from './default-user.service';
|
||||
import {
|
||||
BootstrapOwnerContextService,
|
||||
@@ -7,7 +8,7 @@ import {
|
||||
} from './owner-context.service';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
imports: [PrismaModule, RequestContextModule],
|
||||
providers: [
|
||||
DefaultUserService,
|
||||
BootstrapOwnerContextService,
|
||||
|
||||
Reference in New Issue
Block a user