chore(services): rename services/provisioning -> services/platform-api

O.0 prep from OPERATOR-PLAN.md. Mechanical refactor before adding partner
management and operator-specific endpoints. The service now owns more than
just provisioning orchestration (it'll soon own partners, tenant lifecycle
actions, multi-audience JWT validation), so the name 'platform-api' reflects
its scope better.

What changed:
- Directory: services/provisioning/ -> services/platform-api/
- Package: @dezky/provisioning -> @dezky/platform-api
- Docker: container_name dezky-provisioning -> dezky-platform-api;
  compose service key 'provisioning' -> 'platform-api'; volume
  provisioning_node_modules -> platform_api_node_modules
- Portal: PROVISIONING_INTERNAL_URL env var -> PLATFORM_API_INTERNAL_URL,
  default URL http://provisioning:3001 -> http://platform-api:3001 in all
  three proxy routes (me.get.ts, tenants/index.post.ts, tenants/[slug]/
  reconcile.post.ts), plus NUXT_API_BASE updated
- Health endpoint service identifier and main.ts log lines updated to
  'dezky-platform-api'
- Docs swept: README, CLAUDE.md, SERVICES.md, AUTHENTIK-SETUP.md,
  NEXT-STEPS.md, TROUBLESHOOTING.md, OPERATOR-PLAN.md, traefik/dynamic.yml

What deliberately stays:
- Internal module names ProvisioningService / ProvisioningModule (those
  describe an orchestration sub-concern, not the service's purpose)
- Tenant.provisioningStatus / provisioningErrors field names (state
  per integration, not service name)
- File services/platform-api/src/tenants/provisioning.service.ts
- 'Hetzner provisioning' references in production-prep docs (infrastructure
  provisioning, unrelated)

Verified end-to-end after rename: /api/me returns 200 with profile + 2
tenants + subscription, /api/tenants/dezky/reconcile returns 200 with
Authentik integration still ok.

OPERATOR-PLAN.md O.0 checkboxes ticked.
This commit is contained in:
Ronni Baslund
2026-05-24 00:35:01 +02:00
parent fb3d7aa716
commit 22b2583f0b
49 changed files with 66 additions and 60 deletions
@@ -0,0 +1,18 @@
import { IsArray, IsEmail, IsEnum, IsOptional, IsString, MaxLength, MinLength } from 'class-validator'
export class CreateUserDto {
@IsString() @MinLength(1)
authentikSubjectId!: string
@IsEmail()
email!: string
@IsString() @MinLength(1) @MaxLength(200)
name!: string
@IsOptional() @IsArray() @IsString({ each: true })
tenantSlugs?: string[]
@IsOptional() @IsEnum(['owner', 'admin', 'member'])
role?: 'owner' | 'admin' | 'member'
}
@@ -0,0 +1,15 @@
import { IsArray, IsBoolean, IsEnum, IsOptional, IsString, MaxLength, MinLength } from 'class-validator'
export class UpdateUserDto {
@IsOptional() @IsString() @MinLength(1) @MaxLength(200)
name?: string
@IsOptional() @IsArray() @IsString({ each: true })
tenantSlugs?: string[]
@IsOptional() @IsEnum(['owner', 'admin', 'member'])
role?: 'owner' | 'admin' | 'member'
@IsOptional() @IsBoolean()
active?: boolean
}
@@ -0,0 +1,102 @@
import {
Body,
Controller,
Delete,
ForbiddenException,
Get,
HttpCode,
Param,
Patch,
Post,
UseGuards,
} from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { ActorService } from '../auth/actor.service.js'
import { CurrentUser } from '../auth/current-user.decorator.js'
import { JwtAuthGuard } from '../auth/jwt-auth.guard.js'
import type { AuthentikJwtPayload } from '../auth/jwt-payload.interface.js'
import { CreateUserDto } from './dto/create-user.dto.js'
import { UpdateUserDto } from './dto/update-user.dto.js'
import { UsersService } from './users.service.js'
// Authentik group name that grants platform-wide admin in Dezky. This is the ONLY
// place we look at the JWT's groups claim outside of /users/me — and even here it's
// just for the bootstrap: the resulting platformAdmin boolean on the User doc is
// what every other endpoint reads.
const ADMIN_BOOTSTRAP_GROUP_DEFAULT = 'dezky-platform-admins'
@Controller('users')
@UseGuards(JwtAuthGuard)
export class UsersController {
private readonly adminBootstrapGroup: string
constructor(
private readonly users: UsersService,
private readonly actor: ActorService,
config: ConfigService,
) {
this.adminBootstrapGroup =
config.get<string>('PLATFORM_ADMIN_BOOTSTRAP_GROUP') ?? ADMIN_BOOTSTRAP_GROUP_DEFAULT
}
// The signed-in user's own profile — bootstraps the user record on first call,
// and syncs name/email/tenants/platformAdmin from the JWT on every subsequent call.
@Get('me')
async me(@CurrentUser() jwt: AuthentikJwtPayload) {
return this.users.upsertFromAuthentik({
subject: jwt.sub,
email: jwt.email ?? jwt.preferred_username ?? jwt.sub,
name: jwt.name ?? jwt.preferred_username ?? jwt.email ?? jwt.sub,
tenantSlugs: jwt.groups ?? [],
platformAdmin: jwt.groups?.includes(this.adminBootstrapGroup) ?? false,
})
}
@Post()
async create(@Body() dto: CreateUserDto, @CurrentUser() jwt: AuthentikJwtPayload) {
const actor = await this.actor.resolve(jwt)
if (!actor.platformAdmin) {
throw new ForbiddenException('Only platform admins can create users directly')
}
return this.users.create(dto)
}
@Get()
async findAll(@CurrentUser() jwt: AuthentikJwtPayload) {
const actor = await this.actor.resolve(jwt)
if (actor.platformAdmin) return this.users.findAll()
return this.users.findAllForTenants(actor.tenantIds)
}
@Get(':subject')
async findOne(@Param('subject') subject: string, @CurrentUser() jwt: AuthentikJwtPayload) {
const actor = await this.actor.resolve(jwt)
if (subject !== jwt.sub && !actor.platformAdmin) {
throw new ForbiddenException('Cannot read other users')
}
return this.users.findOneBySubject(subject)
}
@Patch(':subject')
async update(
@Param('subject') subject: string,
@Body() dto: UpdateUserDto,
@CurrentUser() jwt: AuthentikJwtPayload,
) {
const actor = await this.actor.resolve(jwt)
if (!actor.platformAdmin) {
throw new ForbiddenException('Only platform admins can update users')
}
return this.users.update(subject, dto)
}
@Delete(':subject')
@HttpCode(204)
async deactivate(@Param('subject') subject: string, @CurrentUser() jwt: AuthentikJwtPayload) {
const actor = await this.actor.resolve(jwt)
if (!actor.platformAdmin) {
throw new ForbiddenException('Only platform admins can deactivate users')
}
await this.users.deactivate(subject)
}
}
@@ -0,0 +1,23 @@
import { Module } from '@nestjs/common'
import { MongooseModule } from '@nestjs/mongoose'
import { AuthModule } from '../auth/auth.module.js'
import { Tenant, TenantSchema } from '../schemas/tenant.schema.js'
import { User, UserSchema } from '../schemas/user.schema.js'
import { TenantsModule } from '../tenants/tenants.module.js'
import { UsersController } from './users.controller.js'
import { UsersService } from './users.service.js'
@Module({
imports: [
MongooseModule.forFeature([
{ name: User.name, schema: UserSchema },
{ name: Tenant.name, schema: TenantSchema },
]),
AuthModule,
TenantsModule,
],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}
@@ -0,0 +1,98 @@
import { ConflictException, Injectable, NotFoundException } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model, Types } from 'mongoose'
import { Tenant, TenantDocument } from '../schemas/tenant.schema.js'
import { User, UserDocument } from '../schemas/user.schema.js'
import type { CreateUserDto } from './dto/create-user.dto.js'
import type { UpdateUserDto } from './dto/update-user.dto.js'
@Injectable()
export class UsersService {
constructor(
@InjectModel(User.name) private readonly userModel: Model<UserDocument>,
@InjectModel(Tenant.name) private readonly tenantModel: Model<TenantDocument>,
) {}
async create(dto: CreateUserDto): Promise<UserDocument> {
const exists = await this.userModel.exists({ authentikSubjectId: dto.authentikSubjectId })
if (exists) throw new ConflictException(`User ${dto.authentikSubjectId} already exists`)
const tenantIds = await this.resolveTenantIds(dto.tenantSlugs ?? [])
return this.userModel.create({
authentikSubjectId: dto.authentikSubjectId,
email: dto.email,
name: dto.name,
role: dto.role ?? 'member',
tenantIds,
})
}
async findAllForTenants(tenantIds: Types.ObjectId[]): Promise<UserDocument[]> {
return this.userModel.find({ tenantIds: { $in: tenantIds } }).sort({ createdAt: -1 }).exec()
}
async findAll(): Promise<UserDocument[]> {
return this.userModel.find().sort({ createdAt: -1 }).exec()
}
async findOneBySubject(subject: string): Promise<UserDocument> {
const user = await this.userModel.findOne({ authentikSubjectId: subject }).exec()
if (!user) throw new NotFoundException(`User ${subject} not found`)
return user
}
async update(subject: string, dto: UpdateUserDto): Promise<UserDocument> {
const patch: Record<string, unknown> = { ...dto }
if (dto.tenantSlugs !== undefined) {
patch.tenantIds = await this.resolveTenantIds(dto.tenantSlugs)
delete patch.tenantSlugs
}
const user = await this.userModel
.findOneAndUpdate({ authentikSubjectId: subject }, patch, { new: true, runValidators: true })
.exec()
if (!user) throw new NotFoundException(`User ${subject} not found`)
return user
}
async deactivate(subject: string): Promise<void> {
const result = await this.userModel
.updateOne({ authentikSubjectId: subject }, { active: false })
.exec()
if (result.matchedCount === 0) throw new NotFoundException(`User ${subject} not found`)
}
// Called on every authenticated request from /users/me. The JWT's groups claim
// is treated as a hint for first-time membership sync — the DB is the source of
// truth for all subsequent authorization decisions.
async upsertFromAuthentik(payload: {
subject: string
email: string
name: string
tenantSlugs: string[]
platformAdmin: boolean
}): Promise<UserDocument> {
const tenantIds = await this.resolveTenantIds(payload.tenantSlugs)
return this.userModel
.findOneAndUpdate(
{ authentikSubjectId: payload.subject },
{
$set: {
email: payload.email,
name: payload.name,
tenantIds,
platformAdmin: payload.platformAdmin,
lastLoginAt: new Date(),
},
$setOnInsert: { role: 'member', active: true },
},
{ new: true, upsert: true, runValidators: true },
)
.exec()
}
private async resolveTenantIds(slugs: string[]): Promise<Types.ObjectId[]> {
if (slugs.length === 0) return []
const tenants = await this.tenantModel.find({ slug: { $in: slugs } }, { _id: 1 }).exec()
return tenants.map((t) => t._id)
}
}