Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions env.example
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES=false
# ===========================================
# LICENΓ‡A β€” ATIVAÇÃO AUTOMÁTICA POR E-MAIL
# ===========================================
# Defina este valor com o e-mail usado no seu primeiro registro manual.
# Na inicializaΓ§Γ£o, o serviΓ§o chama silenciosamente /v1/register/auto e pula
# a etapa do navegador. Cai para o fluxo manual se o e-mail ainda nΓ£o estiver
# registrado no servidor de licenciamento.
# Na inicializaΓ§Γ£o sem licenΓ§a salva, se AUTHENTICATION_API_KEY for recusada
# como chave de licenΓ§a, o serviΓ§o chama /v1/register/auto com este e-mail e
# pula a etapa do navegador. O servidor de licenciamento decide se o e-mail
# basta; se ele recusar, cai para o fluxo manual.
# Deixe vazio (ou nΓ£o defina) para manter o comportamento padrΓ£o (registro manual).
# EVOLUTION_OPERATOR_EMAIL=operator@example.com

Expand Down
44 changes: 27 additions & 17 deletions src/licensing/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { NextFunction, Request, Response } from 'express';
import { activateIntegrity } from './integrity';
import { RegisterExchangeResponse, RuntimeContextSnapshot } from './model';
import { loadOrCreateInstanceID, loadRuntimeData, saveRuntimeData } from './store';
import { postSigned, postUnsigned, readErrorMessage } from './transport';
import { isRejectedCredential, postSigned, postUnsigned, readErrorMessage } from './transport';

const logger = new Logger('Licensing');

Expand Down Expand Up @@ -119,7 +119,8 @@ export function trackMessageRecv(): void {
* 1. Load or create instance ID (hardware-based, persistent)
* 2. If license exists in DB β†’ activate locally (works even if licensing server is down)
* 3. If no license but globalApiKey is set β†’ try to use it as api_key
* 4. Otherwise β†’ inactive; gate middleware will return 503 until activation
* 4. Otherwise β†’ try EVOLUTION_OPERATOR_EMAIL auto-activation
* 5. Otherwise β†’ inactive; gate middleware will return 503 until activation
*/
export async function initializeRuntime(opts: InitializeOptions = {}): Promise<RuntimeContext> {
const tier = opts.tier || 'evolution-api';
Expand Down Expand Up @@ -176,33 +177,42 @@ export async function initializeRuntime(opts: InitializeOptions = {}): Promise<R
activateIntegrity(rc);
logger.info('Global API key accepted β€” license saved and activated');
} catch (err) {
// Not a valid api_key β€” fall through to registration flow.
rc.apiKey = '';
printRegistrationBanner();
rc.setActive(false);
logger.debug(`Global API key not accepted by licensing server: ${readErrorMessage(err)}`);
// Only a key the server refused may be replaced by an e-mail issued one;
// outages and save errors keep the operator's key for the next boot.
if (isRejectedCredential(err)) {
await autoRegisterOrWait(rc);
} else {
printRegistrationBanner(rc);
rc.setActive(false);
}
}
} else {
// No license in DB and no globalApiKey β€” try silent auto-activation via email.
// EVOLUTION_OPERATOR_EMAIL in .env signals: "this email already registered
// manually once before, please skip the browser flow".
const autoOk = await tryAutoRegisterFromEnv(rc);
if (autoOk) {
logger.info('License activated automatically via EVOLUTION_OPERATOR_EMAIL');
} else {
printRegistrationBanner(rc);
rc.setActive(false);
}
await autoRegisterOrWait(rc);
}

globalRC = rc;
return rc;
}

/**
* Last boot step when no stored license applies: try silent activation via
* EVOLUTION_OPERATOR_EMAIL, otherwise stay inactive until the browser flow runs.
*/
async function autoRegisterOrWait(rc: RuntimeContext): Promise<void> {
if (await tryAutoRegisterFromEnv(rc)) {
logger.info('License activated automatically via EVOLUTION_OPERATOR_EMAIL');
return;
}
printRegistrationBanner(rc);
rc.setActive(false);
}

/**
* tryAutoRegisterFromEnv attempts a silent license activation using only the
* operator email from EVOLUTION_OPERATOR_EMAIL. The customer must have completed
* at least one manual registration in the past.
* operator email from EVOLUTION_OPERATOR_EMAIL. Whether the email alone is enough
* to get a key is decided by the licensing server.
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
*
* Returns true on success. Returns false on any failure β€” the caller is expected
* to fall back to the manual flow. Non-fatal best-effort path.
Expand Down
6 changes: 6 additions & 0 deletions src/licensing/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ export async function getUnsigned<T = unknown>(path: string): Promise<AxiosRespo
return httpClient.get<T>(resolveEndpoint() + path);
}

/** True when the licensing server answered and refused the credential (401/403). */
export function isRejectedCredential(err: unknown): boolean {
const status = axios.isAxiosError(err) ? err.response?.status : undefined;
return status === 401 || status === 403;
}

export function readErrorMessage(err: unknown): string {
if (axios.isAxiosError(err)) {
const data = err.response?.data as { message?: string; error?: string } | undefined;
Expand Down
Loading