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,25 @@
import { Injectable, UnauthorizedException } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { User, UserDocument } from '../schemas/user.schema.js'
import type { AuthentikJwtPayload } from './jwt-payload.interface.js'
// Resolves the JWT-authenticated identity into a Mongo User document. The JWT is
// just identity (sub); all authorization state — tenant memberships, platformAdmin —
// reads from the DB. Keeps the token small regardless of how many tenants a user
// belongs to.
@Injectable()
export class ActorService {
constructor(@InjectModel(User.name) private readonly userModel: Model<UserDocument>) {}
async resolve(jwt: AuthentikJwtPayload): Promise<UserDocument> {
const user = await this.userModel.findOne({ authentikSubjectId: jwt.sub }).exec()
if (!user) {
// First login should always hit /users/me first, which upserts. If we get here
// some other endpoint was called before any /users/me — surface as 401 so the
// caller bootstraps the session.
throw new UnauthorizedException('User record not yet provisioned — call /users/me first')
}
return user
}
}
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common'
import { MongooseModule } from '@nestjs/mongoose'
import { User, UserSchema } from '../schemas/user.schema.js'
import { ActorService } from './actor.service.js'
import { JwtAuthGuard } from './jwt-auth.guard.js'
@Module({
imports: [MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])],
providers: [JwtAuthGuard, ActorService],
exports: [JwtAuthGuard, ActorService],
})
export class AuthModule {}
@@ -0,0 +1,13 @@
import { ExecutionContext, createParamDecorator } from '@nestjs/common'
import type { AuthentikJwtPayload } from './jwt-payload.interface.js'
// Extract the verified JWT payload that JwtAuthGuard attached to the request.
export const CurrentUser = createParamDecorator(
(_data: unknown, ctx: ExecutionContext): AuthentikJwtPayload => {
const req = ctx.switchToHttp().getRequest<{ user?: AuthentikJwtPayload }>()
if (!req.user) {
throw new Error('CurrentUser used without JwtAuthGuard — guard not applied to this route')
}
return req.user
},
)
@@ -0,0 +1,64 @@
import {
CanActivate,
ExecutionContext,
Injectable,
Logger,
UnauthorizedException,
} from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { createRemoteJWKSet, jwtVerify } from 'jose'
import type { AuthentikJwtPayload } from './jwt-payload.interface.js'
@Injectable()
export class JwtAuthGuard implements CanActivate {
private readonly logger = new Logger(JwtAuthGuard.name)
private jwks: ReturnType<typeof createRemoteJWKSet> | null = null
private readonly issuer: string
private readonly audience: string
private readonly jwksUri: string
constructor(config: ConfigService) {
this.issuer = config.getOrThrow<string>('AUTHENTIK_ISSUER')
this.audience = config.getOrThrow<string>('AUTHENTIK_AUDIENCE')
this.jwksUri = config.getOrThrow<string>('AUTHENTIK_JWKS_URI')
}
// Lazy init so misconfigured env doesn't crash the module bootstrap; the first
// request will surface a useful 401 instead of a startup failure.
private getJwks() {
if (!this.jwks) {
this.jwks = createRemoteJWKSet(new URL(this.jwksUri), {
cacheMaxAge: 10 * 60 * 1000,
cooldownDuration: 30 * 1000,
})
}
return this.jwks
}
async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest<{
headers: Record<string, string | string[]>
user?: AuthentikJwtPayload
}>()
const authHeader = req.headers['authorization']
const headerValue = Array.isArray(authHeader) ? authHeader[0] : authHeader
if (!headerValue?.startsWith('Bearer ')) {
throw new UnauthorizedException('Missing or malformed Authorization header')
}
const token = headerValue.slice('Bearer '.length).trim()
try {
const { payload } = await jwtVerify(token, this.getJwks(), {
issuer: this.issuer,
audience: this.audience,
})
req.user = payload as unknown as AuthentikJwtPayload
return true
} catch (err) {
this.logger.warn(`JWT verification failed: ${(err as Error).message}`)
throw new UnauthorizedException('Invalid access token')
}
}
}
@@ -0,0 +1,20 @@
// Authentik OIDC access token claims we care about.
// Full set of claims is larger — only typing what we read.
export interface AuthentikJwtPayload {
iss: string
sub: string
aud: string | string[]
exp: number
iat: number
jti?: string
// User info (populated when 'profile' + 'email' scopes are requested)
email?: string
email_verified?: boolean
name?: string
given_name?: string
preferred_username?: string
// Authentik groups the user belongs to — we model tenants as groups.
groups?: string[]
}