Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4fb1c502c8 | ||
|
|
d895812235 | ||
|
|
f680764373 | ||
|
|
acc17bf291 | ||
|
|
1b57dcc850 | ||
|
|
77d750992d |
@@ -5,6 +5,8 @@ import { AuthorizationModule } from '../authorization/authorization.module';
|
|||||||
import { PhaseADataModule } from '../core-data/phase-a-data.module';
|
import { PhaseADataModule } from '../core-data/phase-a-data.module';
|
||||||
import { AuthController } from './auth.controller';
|
import { AuthController } from './auth.controller';
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
|
import { MobileAuthController } from './mobile-auth.controller';
|
||||||
|
import { MobileAuthService } from './mobile-auth.service';
|
||||||
import { AccessTokenGuard } from './guards/access-token.guard';
|
import { AccessTokenGuard } from './guards/access-token.guard';
|
||||||
import { CsrfGuard } from './guards/csrf.guard';
|
import { CsrfGuard } from './guards/csrf.guard';
|
||||||
import { AuthConfigService } from '../common/config/auth-config.service';
|
import { AuthConfigService } from '../common/config/auth-config.service';
|
||||||
@@ -18,6 +20,7 @@ const providers = [
|
|||||||
PasswordService,
|
PasswordService,
|
||||||
TokenService,
|
TokenService,
|
||||||
AuthService,
|
AuthService,
|
||||||
|
MobileAuthService,
|
||||||
AccessTokenGuard,
|
AccessTokenGuard,
|
||||||
CsrfGuard,
|
CsrfGuard,
|
||||||
];
|
];
|
||||||
@@ -29,7 +32,7 @@ const providers = [
|
|||||||
AuditModule,
|
AuditModule,
|
||||||
AuthorizationModule,
|
AuthorizationModule,
|
||||||
],
|
],
|
||||||
controllers: [AuthController],
|
controllers: [AuthController, MobileAuthController],
|
||||||
providers,
|
providers,
|
||||||
exports: [
|
exports: [
|
||||||
AuthConfigService,
|
AuthConfigService,
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { IsString, MaxLength, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class MobileRefreshDto {
|
||||||
|
@IsString()
|
||||||
|
@MinLength(32)
|
||||||
|
@MaxLength(256)
|
||||||
|
refreshToken!: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
HttpCode,
|
||||||
|
Post,
|
||||||
|
Req,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Throttle } from '@nestjs/throttler';
|
||||||
|
import type {
|
||||||
|
AuthPrincipal,
|
||||||
|
RequestWithContext,
|
||||||
|
} from '../common/http/request-context';
|
||||||
|
import { CurrentAuth } from './decorators/current-auth.decorator';
|
||||||
|
import { Public } from './decorators/public.decorator';
|
||||||
|
import { SkipCsrf } from './decorators/skip-csrf.decorator';
|
||||||
|
import { LoginDto } from './dto/login.dto';
|
||||||
|
import { MobileRefreshDto } from './dto/mobile-refresh.dto';
|
||||||
|
import { MobileAuthService } from './mobile-auth.service';
|
||||||
|
|
||||||
|
@Controller('auth/mobile')
|
||||||
|
export class MobileAuthController {
|
||||||
|
constructor(private readonly mobileAuth: MobileAuthService) {}
|
||||||
|
|
||||||
|
@Post('login')
|
||||||
|
@HttpCode(200)
|
||||||
|
@Public()
|
||||||
|
@SkipCsrf()
|
||||||
|
@Throttle({ default: { limit: 5, ttl: 60_000, blockDuration: 60_000 } })
|
||||||
|
login(
|
||||||
|
@Body() dto: LoginDto,
|
||||||
|
@Req() request: RequestWithContext,
|
||||||
|
) {
|
||||||
|
return this.mobileAuth.login(dto, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('refresh')
|
||||||
|
@HttpCode(200)
|
||||||
|
@Public()
|
||||||
|
@SkipCsrf()
|
||||||
|
@Throttle({ default: { limit: 20, ttl: 60_000 } })
|
||||||
|
refresh(
|
||||||
|
@Body() dto: MobileRefreshDto,
|
||||||
|
@Req() request: RequestWithContext,
|
||||||
|
) {
|
||||||
|
return this.mobileAuth.refresh(dto.refreshToken, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('logout')
|
||||||
|
@HttpCode(200)
|
||||||
|
logout(
|
||||||
|
@CurrentAuth() principal: AuthPrincipal,
|
||||||
|
@Req() request: RequestWithContext,
|
||||||
|
) {
|
||||||
|
return this.mobileAuth.logout(principal, request);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,386 @@
|
|||||||
|
import { isIP } from 'node:net';
|
||||||
|
import {
|
||||||
|
ForbiddenException,
|
||||||
|
Injectable,
|
||||||
|
UnauthorizedException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { DataSource } from 'typeorm';
|
||||||
|
import { AuditService } from '../audit/audit.service';
|
||||||
|
import type {
|
||||||
|
AuthPrincipal,
|
||||||
|
RequestWithContext,
|
||||||
|
} from '../common/http/request-context';
|
||||||
|
import { AuthSessionsRepository } from '../core-data/repositories/auth-sessions.repository';
|
||||||
|
import { RolesRepository } from '../core-data/repositories/roles.repository';
|
||||||
|
import { UsersRepository } from '../core-data/repositories/users.repository';
|
||||||
|
import {
|
||||||
|
AuditAction,
|
||||||
|
AuditSource,
|
||||||
|
AuthSession,
|
||||||
|
User,
|
||||||
|
UserStatus,
|
||||||
|
} from '../database/entities';
|
||||||
|
import type { LoginDto } from './dto/login.dto';
|
||||||
|
import { PasswordService } from './services/password.service';
|
||||||
|
import {
|
||||||
|
IssuedRefreshToken,
|
||||||
|
TokenService,
|
||||||
|
} from './services/token.service';
|
||||||
|
|
||||||
|
interface RequestMetadata {
|
||||||
|
ip: string | null;
|
||||||
|
userAgent: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SuccessfulAuthentication {
|
||||||
|
user: User;
|
||||||
|
accessToken: string;
|
||||||
|
refreshToken: IssuedRefreshToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
type LoginOutcome = SuccessfulAuthentication | null;
|
||||||
|
type RefreshOutcome =
|
||||||
|
| ({ kind: 'ok' } & SuccessfulAuthentication)
|
||||||
|
| { kind: 'reuse' }
|
||||||
|
| { kind: 'invalid' };
|
||||||
|
|
||||||
|
function invalidCredentials(): UnauthorizedException {
|
||||||
|
return new UnauthorizedException({
|
||||||
|
code: 'INVALID_CREDENTIALS',
|
||||||
|
message: 'Credenciales inválidas',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function invalidSession(): UnauthorizedException {
|
||||||
|
return new UnauthorizedException({
|
||||||
|
code: 'INVALID_SESSION',
|
||||||
|
message: 'Sesión móvil inválida o vencida',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function inspectorRequired(): ForbiddenException {
|
||||||
|
return new ForbiddenException({
|
||||||
|
code: 'INSPECTION_INSPECTOR_ROLE_REQUIRED',
|
||||||
|
message: 'Sólo un usuario con rol inspector puede ingresar a la aplicación móvil',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestMetadata(request: RequestWithContext): RequestMetadata {
|
||||||
|
const candidateIp = request.ip || request.socket.remoteAddress || '';
|
||||||
|
const ip = isIP(candidateIp) ? candidateIp : null;
|
||||||
|
const rawUserAgent = request.header('user-agent')?.trim();
|
||||||
|
return {
|
||||||
|
ip,
|
||||||
|
userAgent: rawUserAgent ? rawUserAgent.slice(0, 2048) : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MobileAuthService {
|
||||||
|
constructor(
|
||||||
|
private readonly dataSource: DataSource,
|
||||||
|
private readonly users: UsersRepository,
|
||||||
|
private readonly sessions: AuthSessionsRepository,
|
||||||
|
private readonly roles: RolesRepository,
|
||||||
|
private readonly passwords: PasswordService,
|
||||||
|
private readonly tokens: TokenService,
|
||||||
|
private readonly audit: AuditService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async login(dto: LoginDto, request: RequestWithContext) {
|
||||||
|
const identifier = dto.identifier.trim().toLowerCase();
|
||||||
|
const candidate = await this.users.findForAuthentication(identifier);
|
||||||
|
const metadata = requestMetadata(request);
|
||||||
|
|
||||||
|
if (!candidate) {
|
||||||
|
await this.passwords.verifyUnknown(dto.password);
|
||||||
|
await this.audit.record({
|
||||||
|
action: AuditAction.AUTH_LOGIN_FAILED,
|
||||||
|
requestId: request.requestId,
|
||||||
|
source: AuditSource.ANDROID,
|
||||||
|
...metadata,
|
||||||
|
metadata: { identifier, reason: 'UNKNOWN_IDENTIFIER' },
|
||||||
|
});
|
||||||
|
throw invalidCredentials();
|
||||||
|
}
|
||||||
|
|
||||||
|
const outcome = await this.dataSource.transaction<LoginOutcome>(
|
||||||
|
async (manager) => {
|
||||||
|
const user = await manager
|
||||||
|
.getRepository(User)
|
||||||
|
.createQueryBuilder('user')
|
||||||
|
.addSelect('user.passwordHash')
|
||||||
|
.where('user.id = :id', { id: candidate.id })
|
||||||
|
.setLock('pessimistic_write')
|
||||||
|
.getOne();
|
||||||
|
if (!user) return null;
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const passwordMatches = await this.passwords.verify(
|
||||||
|
user.passwordHash,
|
||||||
|
dto.password,
|
||||||
|
);
|
||||||
|
const locked = Boolean(user.lockedUntil && user.lockedUntil > now);
|
||||||
|
const active = user.status === UserStatus.ACTIVE;
|
||||||
|
|
||||||
|
if (!passwordMatches || locked || !active) {
|
||||||
|
if (!passwordMatches && active && !locked) {
|
||||||
|
await manager.query(
|
||||||
|
`
|
||||||
|
UPDATE users
|
||||||
|
SET
|
||||||
|
failed_login_attempts = failed_login_attempts + 1,
|
||||||
|
locked_until = CASE
|
||||||
|
WHEN failed_login_attempts + 1 >= $2
|
||||||
|
THEN CURRENT_TIMESTAMP + ($3 * INTERVAL '1 second')
|
||||||
|
ELSE locked_until
|
||||||
|
END,
|
||||||
|
updated_at = CURRENT_TIMESTAMP
|
||||||
|
WHERE id = $1
|
||||||
|
`,
|
||||||
|
[
|
||||||
|
user.id,
|
||||||
|
this.tokens.maxLoginAttempts,
|
||||||
|
this.tokens.lockoutSeconds,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.audit.record(
|
||||||
|
{
|
||||||
|
actorUserId: user.id,
|
||||||
|
actorUsername: user.username,
|
||||||
|
action: AuditAction.AUTH_LOGIN_FAILED,
|
||||||
|
entityType: 'user',
|
||||||
|
entityId: user.id,
|
||||||
|
requestId: request.requestId,
|
||||||
|
source: AuditSource.ANDROID,
|
||||||
|
...metadata,
|
||||||
|
metadata: {
|
||||||
|
reason: !active
|
||||||
|
? 'INACTIVE_USER'
|
||||||
|
: locked
|
||||||
|
? 'LOCKED_USER'
|
||||||
|
: 'INVALID_PASSWORD',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
manager,
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.passwords.needsRehash(user.passwordHash)) {
|
||||||
|
user.passwordHash = await this.passwords.hash(dto.password);
|
||||||
|
}
|
||||||
|
user.failedLoginAttempts = 0;
|
||||||
|
user.lockedUntil = null;
|
||||||
|
user.lastLoginAt = now;
|
||||||
|
await manager.getRepository(User).save(user);
|
||||||
|
|
||||||
|
const refreshToken = this.tokens.issueRefreshToken();
|
||||||
|
const session = manager.getRepository(AuthSession).create({
|
||||||
|
id: refreshToken.sessionId,
|
||||||
|
userId: user.id,
|
||||||
|
refreshTokenHash: refreshToken.tokenHash,
|
||||||
|
expiresAt: this.tokens.refreshExpiresAt(now),
|
||||||
|
lastUsedAt: now,
|
||||||
|
revokedAt: null,
|
||||||
|
replacedBySessionId: null,
|
||||||
|
ip: metadata.ip,
|
||||||
|
userAgent: metadata.userAgent,
|
||||||
|
deviceLabel: dto.deviceLabel?.trim() || 'DH Android',
|
||||||
|
});
|
||||||
|
await manager.getRepository(AuthSession).save(session);
|
||||||
|
|
||||||
|
const accessToken = await this.tokens.issueAccessToken({
|
||||||
|
userId: user.id,
|
||||||
|
sessionId: session.id,
|
||||||
|
username: user.username,
|
||||||
|
});
|
||||||
|
|
||||||
|
await this.audit.record(
|
||||||
|
{
|
||||||
|
actorUserId: user.id,
|
||||||
|
actorUsername: user.username,
|
||||||
|
action: AuditAction.AUTH_LOGIN_SUCCESS,
|
||||||
|
entityType: 'auth_session',
|
||||||
|
entityId: session.id,
|
||||||
|
requestId: request.requestId,
|
||||||
|
source: AuditSource.ANDROID,
|
||||||
|
...metadata,
|
||||||
|
metadata: { deviceLabel: session.deviceLabel },
|
||||||
|
},
|
||||||
|
manager,
|
||||||
|
);
|
||||||
|
|
||||||
|
return { user, accessToken, refreshToken };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!outcome) throw invalidCredentials();
|
||||||
|
return this.complete(outcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
async refresh(rawToken: string, request: RequestWithContext) {
|
||||||
|
const parsed = this.tokens.parseRefreshToken(rawToken);
|
||||||
|
if (!parsed) throw invalidSession();
|
||||||
|
|
||||||
|
const metadata = requestMetadata(request);
|
||||||
|
const outcome = await this.dataSource.transaction<RefreshOutcome>(
|
||||||
|
async (manager) => {
|
||||||
|
const session = await manager
|
||||||
|
.getRepository(AuthSession)
|
||||||
|
.createQueryBuilder('session')
|
||||||
|
.addSelect('session.refreshTokenHash')
|
||||||
|
.where('session.id = :id', { id: parsed.sessionId })
|
||||||
|
.setLock('pessimistic_write')
|
||||||
|
.getOne();
|
||||||
|
|
||||||
|
if (
|
||||||
|
!session ||
|
||||||
|
!this.tokens.verifyRefreshToken(rawToken, session.refreshTokenHash)
|
||||||
|
) {
|
||||||
|
return { kind: 'invalid' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await manager.getRepository(User).findOne({
|
||||||
|
where: { id: session.userId },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (session.revokedAt) {
|
||||||
|
await this.sessions.revokeSessionFamily(session.id, manager);
|
||||||
|
await this.audit.record(
|
||||||
|
{
|
||||||
|
actorUserId: user?.id ?? null,
|
||||||
|
actorUsername: user?.username ?? null,
|
||||||
|
action: AuditAction.AUTH_REFRESH_REUSE_DETECTED,
|
||||||
|
entityType: 'auth_session',
|
||||||
|
entityId: session.id,
|
||||||
|
requestId: request.requestId,
|
||||||
|
source: AuditSource.ANDROID,
|
||||||
|
...metadata,
|
||||||
|
},
|
||||||
|
manager,
|
||||||
|
);
|
||||||
|
return { kind: 'reuse' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
if (!user || user.status !== UserStatus.ACTIVE || session.expiresAt <= now) {
|
||||||
|
session.revokedAt = now;
|
||||||
|
session.lastUsedAt = now;
|
||||||
|
await manager.getRepository(AuthSession).save(session);
|
||||||
|
if (user?.status === UserStatus.INACTIVE) {
|
||||||
|
await this.sessions.revokeUserSessions(user.id, undefined, manager);
|
||||||
|
}
|
||||||
|
return { kind: 'invalid' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const refreshToken = this.tokens.issueRefreshToken();
|
||||||
|
const replacement = manager.getRepository(AuthSession).create({
|
||||||
|
id: refreshToken.sessionId,
|
||||||
|
userId: user.id,
|
||||||
|
refreshTokenHash: refreshToken.tokenHash,
|
||||||
|
expiresAt: this.tokens.refreshExpiresAt(now),
|
||||||
|
lastUsedAt: now,
|
||||||
|
revokedAt: null,
|
||||||
|
replacedBySessionId: null,
|
||||||
|
ip: metadata.ip,
|
||||||
|
userAgent: metadata.userAgent,
|
||||||
|
deviceLabel: session.deviceLabel,
|
||||||
|
});
|
||||||
|
await manager.getRepository(AuthSession).save(replacement);
|
||||||
|
|
||||||
|
session.revokedAt = now;
|
||||||
|
session.lastUsedAt = now;
|
||||||
|
session.replacedBySessionId = replacement.id;
|
||||||
|
await manager.getRepository(AuthSession).save(session);
|
||||||
|
|
||||||
|
const accessToken = await this.tokens.issueAccessToken({
|
||||||
|
userId: user.id,
|
||||||
|
sessionId: replacement.id,
|
||||||
|
username: user.username,
|
||||||
|
});
|
||||||
|
|
||||||
|
await this.audit.record(
|
||||||
|
{
|
||||||
|
actorUserId: user.id,
|
||||||
|
actorUsername: user.username,
|
||||||
|
action: AuditAction.AUTH_REFRESH,
|
||||||
|
entityType: 'auth_session',
|
||||||
|
entityId: replacement.id,
|
||||||
|
requestId: request.requestId,
|
||||||
|
source: AuditSource.ANDROID,
|
||||||
|
...metadata,
|
||||||
|
metadata: { replacedSessionId: session.id },
|
||||||
|
},
|
||||||
|
manager,
|
||||||
|
);
|
||||||
|
|
||||||
|
return { kind: 'ok', user, accessToken, refreshToken };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (outcome.kind !== 'ok') throw invalidSession();
|
||||||
|
return this.complete(outcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
async logout(
|
||||||
|
principal: AuthPrincipal,
|
||||||
|
request: RequestWithContext,
|
||||||
|
) {
|
||||||
|
const metadata = requestMetadata(request);
|
||||||
|
await this.dataSource.transaction(async (manager) => {
|
||||||
|
await this.sessions.revokeSession(
|
||||||
|
principal.sessionId,
|
||||||
|
principal.userId,
|
||||||
|
manager,
|
||||||
|
);
|
||||||
|
await this.audit.record(
|
||||||
|
{
|
||||||
|
actorUserId: principal.userId,
|
||||||
|
actorUsername: principal.username,
|
||||||
|
action: AuditAction.AUTH_LOGOUT,
|
||||||
|
entityType: 'auth_session',
|
||||||
|
entityId: principal.sessionId,
|
||||||
|
requestId: request.requestId,
|
||||||
|
source: AuditSource.ANDROID,
|
||||||
|
...metadata,
|
||||||
|
},
|
||||||
|
manager,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
return { status: 'ok' };
|
||||||
|
}
|
||||||
|
|
||||||
|
private async complete(authentication: SuccessfulAuthentication) {
|
||||||
|
const [roleCodes, permissionCodes] = await Promise.all([
|
||||||
|
this.roles.findRoleCodesForUser(authentication.user.id),
|
||||||
|
this.roles.findPermissionCodesForUser(authentication.user.id),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!roleCodes.includes('inspector')) {
|
||||||
|
await this.sessions.revokeSession(
|
||||||
|
authentication.refreshToken.sessionId,
|
||||||
|
authentication.user.id,
|
||||||
|
);
|
||||||
|
throw inspectorRequired();
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
user: {
|
||||||
|
id: authentication.user.id,
|
||||||
|
username: authentication.user.username,
|
||||||
|
firstName: authentication.user.firstName,
|
||||||
|
lastName: authentication.user.lastName,
|
||||||
|
email: authentication.user.email,
|
||||||
|
mustChangePassword: authentication.user.mustChangePassword,
|
||||||
|
roles: roleCodes,
|
||||||
|
permissions: permissionCodes,
|
||||||
|
},
|
||||||
|
accessToken: authentication.accessToken,
|
||||||
|
refreshToken: authentication.refreshToken.token,
|
||||||
|
accessExpiresInSeconds: this.tokens.accessTokenTtlSeconds,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+256
-67
@@ -3,112 +3,301 @@ set -Eeuo pipefail
|
|||||||
|
|
||||||
APP="/var/www/dhv2.korexlabs.com"
|
APP="/var/www/dhv2.korexlabs.com"
|
||||||
KEY="/root/.ssh/dhv2_github"
|
KEY="/root/.ssh/dhv2_github"
|
||||||
|
BACKUP_ROOT="/root/DH_V2_BACKUPS"
|
||||||
DEPLOY_REF="${DHV2_DEPLOY_REF:-deploy}"
|
DEPLOY_REF="${DHV2_DEPLOY_REF:-deploy}"
|
||||||
LOG="$(mktemp /tmp/dhv2-android-discovery.XXXXXX.log)"
|
STAMP="$(date +%Y%m%d_%H%M%S)"
|
||||||
STATUS="$(mktemp /tmp/dhv2-android-discovery-status.XXXXXX)"
|
BACKUP="$BACKUP_ROOT/GITHUB_DEPLOY_${STAMP}"
|
||||||
|
STAGE="/root/dhv2-github-stage-${STAMP}"
|
||||||
|
LOG="/tmp/dhv2-github-deploy-${STAMP}.log"
|
||||||
|
API_TEST_IMAGE="dhv2-api:github-${STAMP}"
|
||||||
|
WEB_TEST_IMAGE="dhv2-web:github-${STAMP}"
|
||||||
|
PHASE="bootstrap"
|
||||||
|
PREV_SHA=""
|
||||||
|
TARGET_SHA=""
|
||||||
|
EXPECTED_API_VERSION=""
|
||||||
|
EXPECTED_WEB_VERSION=""
|
||||||
|
APP_TOUCHED=0
|
||||||
|
|
||||||
cd "$APP"
|
cd "$APP"
|
||||||
export GIT_SSH_COMMAND="ssh -i $KEY -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new"
|
export GIT_SSH_COMMAND="ssh -i $KEY -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new"
|
||||||
exec > >(tee -a "$LOG") 2>&1
|
exec > >(tee -a "$LOG") 2>&1
|
||||||
|
|
||||||
|
cleanup() {
|
||||||
|
set +e
|
||||||
|
git worktree remove --force "$STAGE" >/dev/null 2>&1 || true
|
||||||
|
rm -rf "$STAGE"
|
||||||
|
docker image rm "$API_TEST_IMAGE" "$WEB_TEST_IMAGE" >/dev/null 2>&1 || true
|
||||||
|
}
|
||||||
|
|
||||||
publish_status() {
|
publish_status() {
|
||||||
local rc="${1:-1}"
|
local rc="${1:-1}"
|
||||||
set +e
|
set +e
|
||||||
|
|
||||||
local outcome="failure"
|
local outcome="failure"
|
||||||
[ "$rc" -eq 0 ] && outcome="success"
|
[ "$rc" -eq 0 ] && outcome="success"
|
||||||
local current target status_blob log_blob tree commit
|
local current="unknown"
|
||||||
current="$(git rev-parse HEAD 2>/dev/null || echo unknown)"
|
current="$(git rev-parse HEAD 2>/dev/null || echo unknown)"
|
||||||
target="$(git rev-parse origin/$DEPLOY_REF 2>/dev/null || echo unknown)"
|
local status_file log_file status_blob log_blob tree commit
|
||||||
|
|
||||||
|
status_file="$(mktemp /tmp/dhv2-status.XXXXXX)"
|
||||||
|
log_file="$(mktemp /tmp/dhv2-log.XXXXXX)"
|
||||||
|
|
||||||
{
|
{
|
||||||
echo "status=$outcome"
|
echo "status=$outcome"
|
||||||
echo "exit_code=$rc"
|
echo "exit_code=$rc"
|
||||||
echo "phase=android-source-discovery"
|
echo "phase=$PHASE"
|
||||||
echo "timestamp=$(date --iso-8601=seconds)"
|
echo "timestamp=$(date --iso-8601=seconds)"
|
||||||
echo "deploy_ref=$DEPLOY_REF"
|
echo "deploy_ref=$DEPLOY_REF"
|
||||||
echo "target_sha=$target"
|
echo "previous_sha=${PREV_SHA:-unknown}"
|
||||||
|
echo "target_sha=${TARGET_SHA:-unknown}"
|
||||||
echo "current_sha=$current"
|
echo "current_sha=$current"
|
||||||
echo "app_touched=0"
|
echo "api_version=${EXPECTED_API_VERSION:-unknown}"
|
||||||
echo "backup=not-required-read-only"
|
echo "web_version=${EXPECTED_WEB_VERSION:-unknown}"
|
||||||
} > "$STATUS"
|
echo "app_touched=$APP_TOUCHED"
|
||||||
status_blob="$(git hash-object -w "$STATUS" 2>/dev/null || true)"
|
echo "backup=${BACKUP:-unknown}"
|
||||||
log_blob="$(git hash-object -w "$LOG" 2>/dev/null || true)"
|
} > "$status_file"
|
||||||
|
|
||||||
|
tail -n 500 "$LOG" > "$log_file" 2>/dev/null || true
|
||||||
|
status_blob="$(git hash-object -w "$status_file" 2>/dev/null || true)"
|
||||||
|
log_blob="$(git hash-object -w "$log_file" 2>/dev/null || true)"
|
||||||
|
|
||||||
if [ -n "$status_blob" ] && [ -n "$log_blob" ]; then
|
if [ -n "$status_blob" ] && [ -n "$log_blob" ]; then
|
||||||
tree="$(printf '100644 blob %s\tdeploy.log\n100644 blob %s\tstatus.txt\n' "$log_blob" "$status_blob" | git mktree 2>/dev/null || true)"
|
tree="$(printf '100644 blob %s\tdeploy.log\n100644 blob %s\tstatus.txt\n' "$log_blob" "$status_blob" | git mktree 2>/dev/null || true)"
|
||||||
if [ -n "$tree" ]; then
|
if [ -n "$tree" ]; then
|
||||||
commit="$(printf 'deploy-status: %s · android-source-discovery\n' "$outcome" | git -c user.name='DH V2 Deploy Bot' -c user.email='deploy@dhv2.local' commit-tree "$tree" 2>/dev/null || true)"
|
commit="$(printf 'deploy-status: %s · phase %s\n' "$outcome" "$PHASE" | git -c user.name='DH V2 Deploy Bot' -c user.email='deploy@dhv2.local' commit-tree "$tree" 2>/dev/null || true)"
|
||||||
[ -z "$commit" ] || git push --force origin "$commit:refs/heads/deploy-status" >/dev/null 2>&1 || true
|
[ -z "$commit" ] || git push --force origin "$commit:refs/heads/deploy-status" >/dev/null 2>&1 || true
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
rm -f "$STATUS" "$LOG"
|
|
||||||
|
rm -f "$status_file" "$log_file"
|
||||||
}
|
}
|
||||||
trap 'rc=$?; trap - EXIT; publish_status "$rc"; exit "$rc"' EXIT
|
|
||||||
|
|
||||||
|
on_exit() {
|
||||||
|
local rc=$?
|
||||||
|
trap - EXIT ERR
|
||||||
|
cleanup
|
||||||
|
publish_status "$rc"
|
||||||
|
exit "$rc"
|
||||||
|
}
|
||||||
|
trap on_exit EXIT
|
||||||
|
|
||||||
|
rollback() {
|
||||||
|
local rc=$?
|
||||||
|
trap - ERR
|
||||||
|
PHASE="rollback"
|
||||||
|
|
||||||
|
echo
|
||||||
echo "============================================================"
|
echo "============================================================"
|
||||||
echo " DH V2 · ANDROID SOURCE DISCOVERY · SOLO LECTURA"
|
echo " DH V2 · DEPLOY FALLÓ · ROLLBACK"
|
||||||
echo "============================================================"
|
echo "============================================================"
|
||||||
|
|
||||||
|
cd "$APP"
|
||||||
|
if [ "$APP_TOUCHED" -eq 1 ] && [ -n "${PREV_SHA:-}" ]; then
|
||||||
|
echo "Restaurando aplicación al commit previo: $PREV_SHA"
|
||||||
|
git reset --hard "$PREV_SHA" || true
|
||||||
|
docker compose build api web </dev/null || true
|
||||||
|
docker compose up -d --no-deps --force-recreate api web </dev/null || true
|
||||||
|
else
|
||||||
|
echo "El candidato falló antes de modificar producción; no se reconstruye ni reinicia la aplicación activa."
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "Estado actual:"
|
||||||
|
docker compose ps -a </dev/null || true
|
||||||
|
|
||||||
|
if [ "$APP_TOUCHED" -eq 1 ]; then
|
||||||
|
echo
|
||||||
|
echo "Últimos logs:"
|
||||||
|
docker compose logs --tail=160 api web </dev/null || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo
|
||||||
|
if [ -d "$BACKUP" ]; then
|
||||||
|
echo "Backup PRE disponible en: $BACKUP"
|
||||||
|
echo "Las migraciones son forward-only; database-before.dump queda disponible para restauración manual si hiciera falta."
|
||||||
|
else
|
||||||
|
echo "No fue necesario crear backup PRE: el fallo ocurrió durante el preflight del candidato, antes de tocar producción."
|
||||||
|
fi
|
||||||
|
exit "$rc"
|
||||||
|
}
|
||||||
|
trap rollback ERR
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "============================================================"
|
||||||
|
echo " DH V2 · DEPLOY DESDE GITHUB · $DEPLOY_REF"
|
||||||
|
echo "============================================================"
|
||||||
|
|
||||||
|
for cmd in git docker curl tar node; do
|
||||||
|
command -v "$cmd" >/dev/null || { echo "ERROR: falta $cmd"; false; }
|
||||||
|
done
|
||||||
|
[ -f "$KEY" ] || { echo "ERROR: falta deploy key $KEY"; false; }
|
||||||
|
[ -d .git ] || { echo "ERROR: $APP no es repositorio Git"; false; }
|
||||||
|
[ -f .env ] || { echo "ERROR: falta $APP/.env"; false; }
|
||||||
|
|
||||||
|
git config --global --get-all safe.directory 2>/dev/null | grep -Fxq "$APP" || git config --global --add safe.directory "$APP"
|
||||||
|
|
||||||
|
if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
|
||||||
|
echo "ERROR: hay cambios locales versionados en producción."
|
||||||
|
git status --short
|
||||||
|
false
|
||||||
|
fi
|
||||||
|
|
||||||
|
PREV_SHA="$(git rev-parse HEAD)"
|
||||||
|
PHASE="fetch"
|
||||||
git fetch origin "$DEPLOY_REF"
|
git fetch origin "$DEPLOY_REF"
|
||||||
TARGET="$(git rev-parse "origin/$DEPLOY_REF")"
|
TARGET_SHA="$(git rev-parse "origin/$DEPLOY_REF")"
|
||||||
CURRENT="$(git rev-parse HEAD)"
|
|
||||||
echo "Current: $CURRENT"
|
|
||||||
echo "Target: $TARGET"
|
|
||||||
git merge-base --is-ancestor "$CURRENT" "$TARGET"
|
|
||||||
|
|
||||||
echo
|
echo "Actual: $PREV_SHA"
|
||||||
echo "========== PROYECTOS GRADLE / ANDROID =========="
|
echo "Objetivo: $TARGET_SHA"
|
||||||
for root in /root /var/www /home /tmp; do
|
|
||||||
[ -d "$root" ] || continue
|
|
||||||
find "$root" -maxdepth 9 -type f \
|
|
||||||
\( -name gradlew -o -name settings.gradle -o -name settings.gradle.kts -o -name build.gradle -o -name build.gradle.kts \) \
|
|
||||||
-printf '%TY-%Tm-%Td %TH:%TM %10s %p\n' 2>/dev/null || true
|
|
||||||
done | sort -r | head -300
|
|
||||||
|
|
||||||
echo
|
if [ "$TARGET_SHA" = "$PREV_SHA" ]; then
|
||||||
echo "========== ZIP / APK / AAB RELACIONADOS =========="
|
echo "Producción ya está en el commit autorizado."
|
||||||
for root in /root /var/www /home /tmp; do
|
PHASE="complete"
|
||||||
[ -d "$root" ] || continue
|
exit 0
|
||||||
find "$root" -maxdepth 10 -type f \
|
|
||||||
\( -iname '*android*.zip' -o -iname '*inspeccion*.zip' -o -iname '*dh*.apk' -o -iname '*inspeccion*.apk' -o -iname '*.aab' -o -iname '*E1.1*' -o -iname '*E1_1*' -o -iname '*E1.2*' -o -iname '*E1_2*' -o -iname '*F2.2*' -o -iname '*F2_2*' \) \
|
|
||||||
-printf '%TY-%Tm-%Td %TH:%TM %10s %p\n' 2>/dev/null || true
|
|
||||||
done | sort -r | head -300
|
|
||||||
|
|
||||||
echo
|
|
||||||
echo "========== VERSIONES ANDROID =========="
|
|
||||||
for root in /root /var/www /home /tmp; do
|
|
||||||
[ -d "$root" ] || continue
|
|
||||||
find "$root" -maxdepth 10 -type f \( -name build.gradle -o -name build.gradle.kts \) -print0 2>/dev/null || true
|
|
||||||
done | while IFS= read -r -d '' f; do
|
|
||||||
if grep -Eq 'applicationId|versionCode|versionName|namespace' "$f" 2>/dev/null; then
|
|
||||||
echo "----- $f -----"
|
|
||||||
grep -nE 'applicationId|namespace|versionCode|versionName' "$f" 2>/dev/null | head -30 || true
|
|
||||||
fi
|
fi
|
||||||
done
|
|
||||||
|
|
||||||
echo
|
if ! git merge-base --is-ancestor "$PREV_SHA" "$TARGET_SHA"; then
|
||||||
echo "========== GIT REPOS CON GRADLE =========="
|
echo "ERROR: origin/$DEPLOY_REF no es fast-forward desde producción."
|
||||||
for root in /root /var/www /home /tmp; do
|
false
|
||||||
[ -d "$root" ] || continue
|
|
||||||
find "$root" -maxdepth 9 -type d -name .git -print 2>/dev/null || true
|
|
||||||
done | while read -r gitdir; do
|
|
||||||
dir="${gitdir%/.git}"
|
|
||||||
if find "$dir" -maxdepth 3 \( -name gradlew -o -name settings.gradle -o -name settings.gradle.kts \) -print -quit 2>/dev/null | grep -q .; then
|
|
||||||
echo "----- $dir -----"
|
|
||||||
git -C "$dir" status --short --branch 2>/dev/null || true
|
|
||||||
git -C "$dir" log -8 --oneline 2>/dev/null || true
|
|
||||||
fi
|
fi
|
||||||
done
|
|
||||||
|
PHASE="candidate-preflight"
|
||||||
|
rm -rf "$STAGE"
|
||||||
|
git worktree add --detach "$STAGE" "$TARGET_SHA" >/dev/null
|
||||||
|
|
||||||
|
EXPECTED_API_VERSION="$(node -p "require('$STAGE/api-v3/package.json').version")"
|
||||||
|
EXPECTED_WEB_VERSION="$(node -p "require('$STAGE/web-v2/package.json').version")"
|
||||||
|
|
||||||
|
echo "API candidata: $EXPECTED_API_VERSION"
|
||||||
|
echo "WEB candidata: $EXPECTED_WEB_VERSION"
|
||||||
|
|
||||||
|
docker compose --env-file "$APP/.env" -f "$STAGE/docker-compose.yml" config >/dev/null
|
||||||
|
|
||||||
|
while IFS= read -r -d '' script; do
|
||||||
|
bash -n "$script"
|
||||||
|
done < <(find "$STAGE/scripts" -type f -name '*.sh' -print0)
|
||||||
|
|
||||||
echo
|
echo
|
||||||
echo "========== HUELLA KOTLIN / COMPOSE =========="
|
echo "========== TEST API CANDIDATA =========="
|
||||||
for root in /root /var/www /home /tmp; do
|
docker build --target builder -t "$API_TEST_IMAGE" "$STAGE/api-v3" </dev/null
|
||||||
[ -d "$root" ] || continue
|
docker run --rm \
|
||||||
find "$root" -maxdepth 10 -type f -name '*.kt' -printf '%h\n' 2>/dev/null || true
|
-v "$STAGE/api-v3/test:/app/test:ro" \
|
||||||
done | grep -Ei 'dh|inspe|android|mobile|app' | sort -u | head -300
|
-v "$STAGE/api-v3/tsconfig.test.json:/app/tsconfig.test.json:ro" \
|
||||||
|
"$API_TEST_IMAGE" npm test </dev/null
|
||||||
|
|
||||||
echo
|
echo
|
||||||
echo "DISCOVERY_OK"
|
echo "========== BUILD WEB CANDIDATA =========="
|
||||||
|
docker build -t "$WEB_TEST_IMAGE" "$STAGE/web-v2" </dev/null
|
||||||
|
|
||||||
|
PHASE="backup"
|
||||||
echo
|
echo
|
||||||
echo "========== REGISTRAR COMMIT DIAGNÓSTICO =========="
|
echo "========== BACKUP PRE =========="
|
||||||
|
install -d -m 700 "$BACKUP"
|
||||||
|
docker compose exec -T db sh -lc 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc' </dev/null > "$BACKUP/database-before.dump"
|
||||||
|
tar \
|
||||||
|
--exclude='./.git' \
|
||||||
|
--exclude='./.env' \
|
||||||
|
--exclude='*/node_modules' \
|
||||||
|
--exclude='*/dist' \
|
||||||
|
--exclude='*.zip' \
|
||||||
|
--exclude='*.tar.gz' \
|
||||||
|
--exclude='*.tgz' \
|
||||||
|
-czf "$BACKUP/source-before.tar.gz" .
|
||||||
|
install -m 600 .env "$BACKUP/.env"
|
||||||
|
git rev-parse HEAD > "$BACKUP/previous.sha"
|
||||||
|
printf '%s\n' "$TARGET_SHA" > "$BACKUP/target.sha"
|
||||||
|
docker compose ps -a > "$BACKUP/docker-before.txt"
|
||||||
|
(
|
||||||
|
cd "$BACKUP"
|
||||||
|
sha256sum database-before.dump source-before.tar.gz .env previous.sha target.sha docker-before.txt > SHA256SUMS.txt
|
||||||
|
sha256sum -c SHA256SUMS.txt
|
||||||
|
)
|
||||||
|
chmod 600 "$BACKUP"/* "$BACKUP/.env" 2>/dev/null || true
|
||||||
|
|
||||||
|
PHASE="fast-forward"
|
||||||
|
echo
|
||||||
|
echo "========== FAST-FORWARD =========="
|
||||||
|
git log --oneline --no-decorate "$PREV_SHA..$TARGET_SHA"
|
||||||
|
APP_TOUCHED=1
|
||||||
git merge --ff-only "origin/$DEPLOY_REF"
|
git merge --ff-only "origin/$DEPLOY_REF"
|
||||||
echo "Diagnostic commit registrado localmente: $(git rev-parse HEAD)"
|
|
||||||
|
PHASE="build"
|
||||||
|
echo
|
||||||
|
echo "========== BUILD PRODUCCIÓN =========="
|
||||||
|
docker compose build api migrate web </dev/null
|
||||||
|
|
||||||
|
PHASE="migrations"
|
||||||
|
echo
|
||||||
|
echo "========== MIGRACIONES =========="
|
||||||
|
docker compose --profile tools run --rm migrate </dev/null
|
||||||
|
docker compose --profile tools run --rm migrate npm run migration:show </dev/null | tee "$BACKUP/migrations.txt"
|
||||||
|
grep -Fq 'Pending migrations: no' "$BACKUP/migrations.txt"
|
||||||
|
|
||||||
|
PHASE="recreate"
|
||||||
|
echo
|
||||||
|
echo "========== RECREATE API + WEB =========="
|
||||||
|
docker compose up -d --no-deps --force-recreate api web </dev/null
|
||||||
|
|
||||||
|
PHASE="health"
|
||||||
|
echo
|
||||||
|
echo "========== HEALTH =========="
|
||||||
|
HEALTH_OK=0
|
||||||
|
for _ in $(seq 1 60); do
|
||||||
|
if curl -fsS --max-time 5 http://127.0.0.1:3101/api/v3/health > "$BACKUP/health.json" 2>/dev/null; then
|
||||||
|
if grep -F '"status":"ok"' "$BACKUP/health.json" >/dev/null; then
|
||||||
|
HEALTH_OK=1
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ "$HEALTH_OK" -ne 1 ]; then
|
||||||
|
echo "ERROR: API no pasó healthcheck."
|
||||||
|
docker compose logs --tail=180 api
|
||||||
|
false
|
||||||
|
fi
|
||||||
|
|
||||||
|
cat "$BACKUP/health.json"
|
||||||
|
echo
|
||||||
|
|
||||||
|
grep -Fq "\"version\":\"$EXPECTED_API_VERSION\"" "$BACKUP/health.json"
|
||||||
|
grep -Fq '"database":"ok"' "$BACKUP/health.json"
|
||||||
|
|
||||||
|
WEB_CODE="$(curl -sS -o /dev/null -w '%{http_code}' --max-time 10 http://127.0.0.1:8182/)"
|
||||||
|
[ "$WEB_CODE" = "200" ] || { echo "ERROR: WEB HTTP $WEB_CODE"; false; }
|
||||||
|
|
||||||
|
PHASE="verify"
|
||||||
|
echo
|
||||||
|
echo "========== VERIFICACIÓN FINAL =========="
|
||||||
|
docker compose ps -a | tee "$BACKUP/docker-after.txt"
|
||||||
|
if docker compose ps --status running --services | grep -Fxq api && docker compose ps --status running --services | grep -Fxq web && docker compose ps --status running --services | grep -Fxq db; then
|
||||||
|
echo "Servicios críticos: OK"
|
||||||
|
else
|
||||||
|
echo "ERROR: falta un servicio crítico en ejecución."
|
||||||
|
false
|
||||||
|
fi
|
||||||
|
|
||||||
|
PHASE="post-backup"
|
||||||
|
docker compose exec -T db sh -lc 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc' </dev/null > "$BACKUP/database-after.dump"
|
||||||
|
git rev-parse HEAD > "$BACKUP/deployed.sha"
|
||||||
|
printf 'API=%s\nWEB=%s\n' "$EXPECTED_API_VERSION" "$EXPECTED_WEB_VERSION" > "$BACKUP/deployed-versions.txt"
|
||||||
|
(
|
||||||
|
cd "$BACKUP"
|
||||||
|
sha256sum database-after.dump deployed.sha deployed-versions.txt health.json migrations.txt docker-after.txt >> SHA256SUMS.txt
|
||||||
|
sha256sum -c SHA256SUMS.txt
|
||||||
|
)
|
||||||
|
chmod 600 "$BACKUP"/* "$BACKUP/.env" 2>/dev/null || true
|
||||||
|
|
||||||
|
PHASE="complete"
|
||||||
|
trap - ERR
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "============================================================"
|
||||||
|
echo " DH V2 · DEPLOY OK"
|
||||||
|
echo "============================================================"
|
||||||
|
echo "Commit: $TARGET_SHA"
|
||||||
|
echo "API: $EXPECTED_API_VERSION"
|
||||||
|
echo "WEB: $EXPECTED_WEB_VERSION"
|
||||||
|
echo "Backup: $BACKUP"
|
||||||
|
echo "============================================================"
|
||||||
|
|||||||
Reference in New Issue
Block a user